repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
aliabd/cos-cvae | [
"d6f94dd0f1de6727e43da55d36a6433fbfd0c44b"
] | [
"GoogleConceptualCaptioning/eval_ensemble.py"
] | [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport numpy as np\n\nimport time\nimport os\nfrom six.moves import cPickle\n\nimport opts\nimport models\nfrom dataloader import *\nfrom dataloaderraw import *\nimport eval_utils\nimport argparse\nimport misc.utils as utils\nimport torch\n\n# Input arguments and options\nparser = argparse.ArgumentParser()\n# Input paths\nparser.add_argument('--ids', nargs='+', required=True, help='id of the models to ensemble')\nparser.add_argument('--weights', nargs='+', required=False, default=None, help='id of the models to ensemble')\n# parser.add_argument('--models', nargs='+', required=True\n# help='path to model to evaluate')\n# parser.add_argument('--infos_paths', nargs='+', required=True, help='path to infos to evaluate')\nopts.add_eval_options(parser)\nopts.add_diversity_opts(parser)\n\nopt = parser.parse_args()\n\nmodel_infos = []\nmodel_paths = []\nfor id in opt.ids:\n if '-' in id:\n id, app = id.split('-')\n app = '-'+app\n else:\n app = ''\n model_infos.append(utils.pickle_load(open('log_%s/infos_%s%s.pkl' %(id, id, app))))\n model_paths.append('log_%s/model%s.pth' %(id,app))\n\n# Load one infos\ninfos = model_infos[0]\n\n# override and collect parameters\nreplace = ['input_fc_dir', 'input_att_dir', 'input_box_dir', 'input_label_h5', 'input_json', 'batch_size', 'id']\nfor k in replace:\n setattr(opt, k, getattr(opt, k) or getattr(infos['opt'], k, ''))\n\nvars(opt).update({k: vars(infos['opt'])[k] for k in vars(infos['opt']).keys() if k not in vars(opt)}) # copy over options from model\n\n\nopt.use_box = max([getattr(infos['opt'], 'use_box', 0) for infos in model_infos])\nassert max([getattr(infos['opt'], 'norm_att_feat', 0) for infos in model_infos]) == max([getattr(infos['opt'], 'norm_att_feat', 0) for infos in model_infos]), 'Not support different norm_att_feat'\nassert max([getattr(infos['opt'], 'norm_box_feat', 0) for infos in model_infos]) == max([getattr(infos['opt'], 'norm_box_feat', 0) for infos in model_infos]), 'Not support different norm_box_feat'\n\nvocab = infos['vocab'] # ix -> word mapping\n\n# Setup the model\nfrom models.AttEnsemble import AttEnsemble\n\n_models = []\nfor i in range(len(model_infos)):\n model_infos[i]['opt'].start_from = None\n model_infos[i]['opt'].vocab = vocab\n tmp = models.setup(model_infos[i]['opt'])\n tmp.load_state_dict(torch.load(model_paths[i]))\n _models.append(tmp)\n\nif opt.weights is not None:\n opt.weights = [float(_) for _ in opt.weights]\nmodel = AttEnsemble(_models, weights=opt.weights)\nmodel.seq_length = opt.max_length\nmodel.cuda()\nmodel.eval()\ncrit = utils.LanguageModelCriterion()\n\n# Create the Data Loader instance\nif len(opt.image_folder) == 0:\n loader = DataLoader(opt)\nelse:\n loader = DataLoaderRaw({'folder_path': opt.image_folder, \n 'coco_json': opt.coco_json,\n 'batch_size': opt.batch_size,\n 'cnn_model': opt.cnn_model})\n# When eval using provided pretrained model, the vocab may be different from what you have in your cocotalk.json\n# So make sure to use the vocab in infos file.\nloader.ix_to_word = infos['vocab']\n\nopt.id = '+'.join([_+str(__) for _,__ in zip(opt.ids, opt.weights)])\n# Set sample options\nloss, split_predictions, lang_stats = eval_utils.eval_split(model, crit, loader, \n vars(opt))\n\nprint('loss: ', loss)\nif lang_stats:\n print(lang_stats)\n\nif opt.post_processing == 1:\n for i in range(len(split_predictions)):\n split_predictions[i]['caption'] = utils.post_processing_for_conceptual(split_predictions[i]['caption'])\n\nif opt.dump_json == 1:\n # dump the json\n json.dump(split_predictions, open('vis/vis.json', 'w'))\n json.dump(split_predictions, open(os.path.join('eval_results/', opt.id + '_' + opt.split + '.json'), 'w'))\n\n"
] | [
[
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
raghu1121/SLM-Lab | [
"58e98b6521f581515d04ebacff5226105237ed9b"
] | [
"slm_lab/env/openai.py"
] | [
"from slm_lab.env.base import BaseEnv, ENV_DATA_NAMES\nfrom slm_lab.env.wrapper import wrap_atari, wrap_deepmind\nfrom slm_lab.env.registration import register_env\nfrom slm_lab.lib import logger, util\nfrom slm_lab.lib.decorator import lab_api\nimport gym\nimport numpy as np\nimport pydash as ps\n\nlogger = logger.get_logger(__name__)\n\n\ndef guard_reward(reward):\n '''Some gym environments have buggy format and reward is in a np array'''\n if np.isscalar(reward):\n return reward\n else: # some gym envs have weird reward format\n assert len(reward) == 1\n return reward[0]\n\n\nclass OpenAIEnv(BaseEnv):\n '''\n Wrapper for OpenAI Gym env to work with the Lab.\n\n e.g. env_spec\n \"env\": [{\n \"name\": \"CartPole-v0\",\n \"max_t\": null,\n \"max_tick\": 150,\n \"max_tick_unit\": \"epi\",\n \"save_frequency\": 50\n }],\n '''\n\n def __init__(self, spec, e=None, env_space=None):\n super(OpenAIEnv, self).__init__(spec, e, env_space)\n register_env(spec) # register any additional environments first\n env = gym.make(self.name)\n if 'NoFrameskip' in env.spec.id: # for Atari\n stack_len = ps.get(spec, 'agent.0.memory.stack_len')\n env = wrap_atari(env)\n if util.get_lab_mode() == 'eval':\n env = wrap_deepmind(env, stack_len=stack_len, clip_rewards=False, episode_life=False)\n else:\n # no reward clipping in training since Atari Memory classes handle it\n env = wrap_deepmind(env, stack_len=stack_len, clip_rewards=False)\n self.u_env = env\n self._set_attr_from_u_env(self.u_env)\n self.max_t = self.max_t or self.u_env.spec.tags.get('wrapper_config.TimeLimit.max_epi_steps')\n if env_space is None: # singleton mode\n pass\n else:\n self.space_init(env_space)\n logger.info(util.self_desc(self))\n\n @lab_api\n def reset(self):\n _reward = np.nan\n state = self.u_env.reset()\n self.done = done = False\n if util.to_render():\n self.u_env.render()\n logger.debug(f'Env {self.e} reset reward: {_reward}, state: {state}, done: {done}')\n return _reward, state, done\n\n @lab_api\n def step(self, action):\n if not self.is_discrete: # guard for continuous\n action = np.array([action])\n state, reward, done, _info = self.u_env.step(action)\n reward = guard_reward(reward)\n reward *= self.reward_scale\n if util.to_render():\n self.u_env.render()\n if self.max_t is not None:\n done = done or self.clock.t > self.max_t\n self.done = done\n logger.debug(f'Env {self.e} step reward: {reward}, state: {state}, done: {done}')\n return reward, state, done\n\n @lab_api\n def close(self):\n self.u_env.close()\n\n # NOTE optional extension for multi-agent-env\n\n @lab_api\n def space_init(self, env_space):\n '''Post init override for space env. Note that aeb is already correct from __init__'''\n self.env_space = env_space\n self.aeb_space = env_space.aeb_space\n self.observation_spaces = [self.observation_space]\n self.action_spaces = [self.action_space]\n\n @lab_api\n def space_reset(self):\n _reward_e, state_e, done_e = self.env_space.aeb_space.init_data_s(ENV_DATA_NAMES, e=self.e)\n for ab, body in util.ndenumerate_nonan(self.body_e):\n state = self.u_env.reset()\n state_e[ab] = state\n done_e[ab] = self.done = False\n if util.to_render():\n self.u_env.render()\n logger.debug(f'Env {self.e} reset reward_e: {_reward_e}, state_e: {state_e}, done_e: {done_e}')\n return _reward_e, state_e, done_e\n\n @lab_api\n def space_step(self, action_e):\n action = action_e[(0, 0)] # single body\n if self.done: # space envs run continually without a central reset signal\n return self.space_reset()\n if not self.is_discrete:\n action = np.array([action])\n state, reward, done, _info = self.u_env.step(action)\n reward = guard_reward(reward)\n reward *= self.reward_scale\n if util.to_render():\n self.u_env.render()\n self.done = done = done or self.clock.t > self.max_t\n reward_e, state_e, done_e = self.env_space.aeb_space.init_data_s(ENV_DATA_NAMES, e=self.e)\n for ab, body in util.ndenumerate_nonan(self.body_e):\n reward_e[ab] = reward\n state_e[ab] = state\n done_e[ab] = done\n logger.debug(f'Env {self.e} step reward_e: {reward_e}, state_e: {state_e}, done_e: {done_e}')\n return reward_e, state_e, done_e\n"
] | [
[
"numpy.array",
"numpy.isscalar"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ErhanYILMAZ/DESC_Model | [
"4735c312b14d470918336519ea23c2214be90a2a"
] | [
"DESC_Simulation.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCopyright (c) 2021 by Erhan YILMAZ (https://orcid.org/0000-0003-4788-9022)\nThis file is licensed under CC BY-SA (Attribution-ShareAlike)\nIt is provided \"as is\", without express or implied warranty, for educational and informational purposes only.\n\nPython file simulate Double Enhanced Self Correcting(DESC) model with 1-RC branch\n\nDouble Enhanced Self Correcting(DESC) model is an Electrical Equivalent Circuit Model \nfor lithium-ion batteries also can be used for other battery types. \nRelated article for DESC can be accessed here <DESC paper link will be here hopefully later>\n\nDESC is an enhanced derivative of Enhanced Self Correcting(ESC) Model from Gregor Plett. \nThus, same documentation for ESC model and DESC model article can be used as referenced to understand \ncode framework. After understanding the code framework and how does model work then one can develop own model.\n\nAll details, documentation and description can be found below \n\nhttp://mocha-java.uccs.edu/BMS1/index.html\nhttp://mocha-java.uccs.edu/ECE5710/index.html\nhttp://mocha-java.uccs.edu/ECE5710/ECE5710-Notes02.pdf\n\"\"\"\n\nimport os\nimport json\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom DESC_1RC import DESC_1RC\nfrom datetime import datetime\n\nnow = datetime.now()\nstart = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n\ntemps=[-5, 5, 15, 25, 35, 45]\nmags= [20, 20, 40, 50, 50, 50]\n\n\n# Read modelocv.json file that contains parameters just for OCV data\n# Such OCV0, OCVrel OCVeta Q etc.\nwith open('model_files/DESC1Model_SLSQP.json') as json_file:\n model = json.load(json_file)\n\n# Define variable for rmse value\nrmse = np.zeros(len(temps))\n\n# Define font size for labels and colors\nxfontsize = 12\nyfontsize = 12\ncolors=['b', # blue\n 'g', #green\n 'r', #red\n 'c', #cyan\n 'm', #magenta\n 'y',# yellow\n 'orange', #orange\n 'purple', #purple\n ]\n\nfor erhan in range(len(temps)):\n\n # Read UDDS dynamic data for specified temperature value\n if(temps[erhan]>0):\n script1 = \"dyn_data/THUN100_DYN_%02d_P%02d_S1.csv\" %(mags[erhan], temps[erhan]) \n data = pd.read_csv(script1)\n else:\n script1 = \"dyn_data/THUN100_DYN_%02d_N%02d_S1.csv\" %(mags[erhan], np.abs(temps[erhan])) \n data= pd.read_csv(script1)\n \n # Get voltage and current values.\n current = np.asarray(data['current'])\n voltage = np.asarray(data['voltage'])\n time = np.asarray(data['time'])/3600\n # Create model instance and initiliaze for the specified temperature.\n cell = DESC_1RC(model=model , temp=temps[erhan], dt=1.0,use_OCVS=True)\n\n # Plot simulated output and cell data output\n plt.figure()\n est_voltage = cell.fun([1.0,0.0,0.0],current)\n rmse[erhan]=np.sqrt(((voltage - est_voltage) ** 2).mean())\n plt.plot(time, est_voltage, color=colors[erhan], label='Simulation')\n plt.plot(time, voltage, label='True')\n plt.legend()\n plt.xlabel('Time(h)', fontsize = xfontsize, fontweight = 'bold')\n plt.ylabel('Voltage', fontsize = xfontsize, fontweight = 'bold')\n plt.title('Estimated Output Voltage for T=%02d, RMSE = %2.2fmV' % (temps[erhan],rmse[erhan]*1000))\n plt.show()\n plt.savefig('figures/simulations/Simulation_T_%02d.png' % temps[erhan], dpi=600, bbox_inches='tight')\n # Print rms error.\n print('RMS=%fmV'%(rmse[erhan]*1000))\n print('------------------------------------------------------------')\n\n# Get stop time\nnow = datetime.now()\nstop = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n# Delete report file if exist\nif os.path.exists(\"reports/simulations/simulation_report.txt\"):\n os.remove(\"reports/simulations/simulation_report.txt\")\n\n# Create a report file and write results.\nf = open(\"reports/simulations/simulation_report.txt\", \"a\")\nf.write('\\r\\n')\nf.write('Simulation Results for DESC Model with 1-RC\\n')\nf.write('\\r\\n')\nfor erhan in range(len(temps)):\n f.write('Simulated Output Voltage RMSE=%2.2fmV at %02d°C Temp\\n' % (rmse[erhan]*1000, temps[erhan])) \nf.write('\\r\\n')\nf.write(\"Start Time =\" + start)\nf.write(\"\\nStop Time =\" + stop)\nf.write('\\n')\nf.close() # Close the file.\n\n"
] | [
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"numpy.abs",
"matplotlib.pyplot.title",
"numpy.asarray",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
jsw7460/mylinear | [
"c1bd90467837ec53a1010e1607d251aa3d2b9766"
] | [
"modules.py"
] | [
"from math import sqrt\n\nimport torch\nimport torch.nn as nn\n\n\n# Linear Embedding\nclass GraphEmbedding(nn.Module):\n def __init__(self, input_size, embedding_size):\n super(GraphEmbedding, self).__init__()\n self.embedding_size = embedding_size\n self.embedding = nn.Linear(input_size, embedding_size).to(\"cuda:0\")\n self.e2 = nn.Linear(embedding_size, embedding_size).to(\"cuda:0\")\n\n def forward(self, inputs):\n return self.e2(torch.tanh(self.embedding(inputs)))\n\n\n# Glimpse using Dot-product attention\nclass Glimpse(nn.Module):\n def __init__(self,\n input_size,\n hidden_size,\n n_head):\n super(Glimpse, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.n_head = n_head\n self.single_dim = hidden_size // n_head\n self.c_div = 1.0 / sqrt(self.single_dim)\n # Why should we take bias?\n\n self.W_q = nn.Linear(self.input_size, self.hidden_size)\n self.W_k = nn.Linear(self.input_size, self.hidden_size)\n self.W_v = nn.Linear(self.input_size, self.hidden_size)\n self.W_out = nn.Linear(self.hidden_size, self.input_size)\n\n # No dropout or No Batch/Layernorm as mentioned at Wouter's paper\n\n def forward(self, query, target, mask=None):\n \"\"\"\n Parameters\n ----------\n query : FloatTensor with shape [batch_size x input_size]\n target : FloatTensor with shape [batch_size x seq_len x input_size]\n mask : BoolTensor with shape [batch_size x input_size]\n if any\n \"\"\"\n batch_size, seq_len, _ = target.shape\n\n q_c = self.W_q(query).reshape(batch_size, self.n_head, self.single_dim)\n k = self.W_k(target).reshape(batch_size, seq_len, self.n_head, self.single_dim).permute(0, 2, 1, 3).contiguous()\n v = self.W_v(target).reshape(batch_size, seq_len, self.n_head, self.single_dim).permute(0, 2, 1, 3).contiguous()\n qk = torch.einsum(\"ijl,ijkl->ijk\", [q_c, k]) * self.c_div\n\n if mask is not None:\n _mask = mask.unsqueeze(1).repeat(1, self.n_head, 1)\n qk[_mask] = -100000.0\n\n alpha = torch.softmax(qk, -1)\n h = torch.einsum(\"ijk,ijkl->ijl\", alpha, v)\n\n if self.n_head == 1:\n ret = h.reshape(batch_size, -1)\n return alpha.squeeze(1), ret\n else:\n ret = self.W_out(h.reshape(batch_size, -1))\n return alpha, ret\n\n\n# Pointer using Dot-product attention\nclass Pointer(nn.Module):\n def __init__(self,\n input_size,\n hidden_size,\n n_head,\n C=10):\n\n super(Pointer, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.C = C\n\n self.W_q = nn.Linear(self.input_size, self.hidden_size)\n self.W_k = nn.Linear(self.input_size, self.hidden_size)\n self.W_v = nn.Linear(self.input_size, self.hidden_size)\n\n def forward(self, query, target, mask=None, ret_score=False):\n \"\"\"\n Parameters\n ----------\n query : FloatTensor [batch_size x input_size]\n target : FloatTensor [batch_size x seq_len x input_size]\n mask : BoolTensor [batch_size x seq_len]\n \"\"\"\n batch_size, seq_len, _ = target.shape\n\n q_c = self.W_q(query) # batch_size x hidden_size\n k = self.W_k(target) # batch_size x seq_len x hidden_size\n v = self.W_v(target) # batch_size x seq_len x hidden_size\n qk = torch.einsum(\"ik,ijk->ij\", [q_c, k]) # batch_size x seq_len\n qk = self.C * torch.tanh(qk)\n\n if mask is not None:\n _mask = mask.clone()\n qk[_mask] = -100000000.0\n if ret_score:\n return qk\n alpha = torch.softmax(qk, dim=-1)\n ret = torch.einsum(\"ij,ijk->ij\", [alpha, v])\n return alpha, ret\n\n\n# Attention/Pointer module using Bahanadu Attention\nclass Attention(nn.Module):\n def __init__(self, hidden_size, C=10):\n super(Attention, self).__init__()\n self.C = C\n self.W_q = nn.Linear(hidden_size, hidden_size)\n self.W_k = nn.Linear(hidden_size, hidden_size)\n self.W_v = nn.Linear(hidden_size, 1)\n\n def forward(self, query, target):\n \"\"\"\n Args:\n query: [batch_size x hidden_size]\n target: [batch_size x seq_len x hidden_size]\n \"\"\"\n\n batch_size, seq_len, _ = target.shape\n query = self.W_q(query).unsqueeze(1).repeat(1, seq_len, 1) # [batch_size x seq_len x hidden_size]\n target = self.W_k(target) # [batch_size x seq_len x hidden_size]\n logits = self.W_v(torch.tanh(query + target)).squeeze(-1)\n logits = self.C * torch.tanh(logits)\n return target, logits\n"
] | [
[
"torch.tanh",
"torch.nn.Linear",
"torch.softmax",
"torch.einsum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jimorsm/vue-element-admin-fastapi | [
"3ffc7dc3d2be988e544f339af466538cb0708d25"
] | [
"backend/app/app/db/init_db.py"
] | [
"import os, logging\nimport pandas as pd\nimport numpy as np\nfrom app.db.session import engine\n\nlogger = logging.getLogger(__name__)\n\ndef init_db() -> None:\n # Tables should be created with Alembic migrations\n init_data_path = os.path.join(os.path.dirname(__file__), \"init_data\")\n files = ['department.csv', 'menu.csv', 'role.csv', 'user.csv', 'dict_type.csv', 'dict_data.csv',\n 'role_menu.csv', 'user_department.csv', 'user_dict.csv', 'user_role.csv', ]\n for file in files:\n file_path = os.path.join(init_data_path, file)\n df = pd.read_csv(file_path, sep=\",\")\n if file == \"menu.csv\":\n df['component'] = df['component'].apply(lambda x: '' if np.isnan(x) else x)\n df['name'] = df['name'].apply(lambda x: '' if np.isnan(x) else x)\n logger.info(f\"{file} load successed\")\n df.to_sql(file.replace(\".csv\", \"\"), engine, if_exists=\"append\", index=False)\n"
] | [
[
"numpy.isnan",
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
OpenSourceBrain/SadehEtAl2017-InhibitionStabilizedNetworks | [
"9d3ec01d545cc0a13b8e8057e83df8b8247d3b79"
] | [
"SpikingSimulationModels/networkTools.py"
] | [
"\n################################################################################\n# -- Tools for simulating networks of spiking neurons using the NEST simulator\n################################################################################\n\nimport numpy as np; import pylab as pl; import time, os, sys\nfrom imp import reload\nimport defaultParams; reload(defaultParams); from defaultParams import *;\nimport nest\n\n# --- NEST initialization\ndef _nest_start_(n_cores=n_cores):\n nest.ResetKernel()\n nest.SetKernelStatus({\"resolution\": dt,\n \"print_time\": True,\n \"overwrite_files\": True,\n 'local_num_threads': n_cores})\n nest.set_verbosity(\"M_WARNING\")\n\n# --- Get simulation time of the network\ndef _simulation_time_():\n return nest.GetStatus([0])[0]['time']\n\n# --- Define nest-compatible \"Connect\"\nbNestUseConvergentConnect = \"ConvergentConnect\" in dir(nest)\n\ndef ConvConnect(arg0, arg1, syn_spec='static_synapse', *args):\n return nest.Connect(arg0, arg1, syn_spec=syn_spec)\n\ndef DivConnect(arg0, arg1, syn_spec='static_synapse', *args):\n return nest.Connect(arg0, arg1, syn_spec=syn_spec)\n\n# --- Making neurons\ndef _make_neurons_(N, neuron_model=\"iaf_cond_alpha\", myparams={}):\n nest.SetDefaults(neuron_model, neuron_params_default)\n neurons = nest.Create(neuron_model, N)\n if myparams != {}:\n for nn in range(N):\n for kk in myparams.keys():\n nest.SetStatus([neurons[nn]], {kk:myparams[kk][nn]})\n return neurons\n\n# --- Generating (poisson) inputs and setting their firing rates\ndef _poisson_inp_(N):\n poisson_inp = nest.Create(\"poisson_generator\", N)\n return poisson_inp\n\ndef _set_rate_(neurons, rates):\n for ii, nn in enumerate(neurons):\n nest.SetStatus([nn], {'rate':rates[ii]})\n\n# --- Setting the rates of background inputs and conencting them\ndef _bkg_inp_(neurons, bkg_rates, bkg_w = Be*1e9):\n N = len(neurons)\n bkg_inp = nest.Create(\"poisson_generator\", N)\n for ii in range(N):\n nest.SetStatus([bkg_inp[ii]], {'rate':bkg_rates[ii]})\n for ii in range(N):\n nest.Connect([bkg_inp[ii]], [neurons[ii]], \\\n syn_spec = {'weight':bkg_w, 'delay':delay_default})\n\n# --- Copy to a parrot neuron (mirroring every spike)\ndef _copy_to_parrots_(pre_pop):\n parrots = nest.Create('parrot_neuron', len(pre_pop))\n nest.Connect(pre_pop, parrots, conn_spec='one_to_one')\n return parrots\n\n# --- Defining synapse types\ndef _define_synapse_(syn_type='static_synapse', name='exc', w=Be*1e9, d=delay_default):\n nest.CopyModel(syn_type, name, {\"weight\":w, \"delay\":d})\n\n# --- Recording and reading spikes and voltages\ndef _recording_spikes_(neurons, start=0., stop=np.inf, to_file=False, to_memory=True):\n spikes = nest.Create(\"spike_detector\", 1)\n nest.SetStatus(spikes, {\"withtime\":True,\n \"label\":'spike-det',\n \"to_file\":to_file,\n \"to_memory\":to_memory,\n \"start\": start,\n \"stop\": stop})\n\n ConvConnect(neurons, spikes)\n return spikes\n\ndef _recording_voltages_(neurons, start=0., stop=np.inf):\n voltages = nest.Create(\"voltmeter\")\n nest.SetStatus(voltages, {\"withtime\":True,\n \"label\":'volt-meter',\n \"to_file\":False,\n \"to_memory\":True,\n \"start\": start,\n \"stop\": stop})\n DivConnect(voltages, neurons)\n return voltages\n\ndef _reading_spikes_(spikes):\n spike_data = nest.GetStatus(spikes)[0]['events']\n return spike_data\n\ndef _reading_voltages_(voltages):\n voltage_data = nest.GetStatus(voltages)[0]['events']\n return voltage_data\n\n# --- Connect population A to population B with weight matrix W\ndef _connect_pops_(pre_pop, post_pop, weight, syn_model='static'):\n print(weight.shape)\n dd = dt + delay_default*np.ones(weight.T.shape)\n nest.Connect(pre_pop, post_pop, syn_spec = {'weight':weight.T, 'delay':dd})\n \n #for ii, nn in enumerate(pre_pop):\n # ww = weight[ii]\n # dd = dt + delay_default*np.ones(len(ww))\n # nest.Connect([nn], post_pop, syn_spec = {'weight':ww.tolist(), 'delay':dd.tolist()})\n print(\" Created %s non zero weight connections from %s to %s, %s\"%(np.count_nonzero(weight),_pop_info_(pre_pop), _pop_info_(post_pop), syn_model))\n \ndef _pop_info_(pop):\n return 'Cells %s->%s (%s total)' %(pop[0],pop[-1],len(pop))\n\n# --- Run the simulation for the duration of T (ms)\ndef _run_simulation_(T):\n nest.Simulate(T)\n\n################################################################################\n################################################################################\n################################################################################\n"
] | [
[
"numpy.count_nonzero",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
siriusdemon/mmaction2 | [
"ba2d97eeaff3ec20dbc51225bdd91bf167861d8e"
] | [
"api.py"
] | [
"import torch\nimport sys\n\nfrom mmaction.apis.inference2 import init_recognizer, inference_recognizer\n\n\nclass Predictor:\n\n def __init__(self):\n self.config_file = 'configs/recognition/slowfast/writing_inference.py'\n self.checkpoint_file = 'checkpoints/writing.pth'\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n self.device = torch.device(device)\n self.model = init_recognizer(self.config_file, self.checkpoint_file, device=device)\n self.labels = 'demo/writing.txt'\n\n def softmax(self, scores):\n exps = [2.7**s for s in scores]\n esum = sum(exps)\n return list(map(lambda x: x / esum, exps))\n\n def predict(self, video):\n results = inference_recognizer(self.model, video, self.labels)\n labels = [r[0] for r in results]\n scores = [r[1] for r in results]\n #scores = self.softmax(scores)\n try:\n idx = labels.index('writing')\n except ValueError:\n return {'prob': 0}\n else:\n return {'prob': scores[idx]}\n\n def predict2(self, video):\n results = inference_recognizer(self.model, video, self.labels)\n return results\n\n\n\nif __name__ == '__main__':\n import os\n if len(sys.argv) == 2:\n video = sys.argv[1]\n else:\n video = '004_4-签字-左前45-远景-会议室-3-衣服1.mp4'\n\n model = Predictor()\n\n import os.path as osp\n if osp.isdir(video):\n vdir = video\n videos = [osp.join(vdir, f) for f in os.listdir(vdir)]\n else:\n videos = [video]\n\n\n for vid in videos:\n print(\"Predict\", osp.basename(vid))\n result = model.predict2(vid)\n print(result)\n print(\"-\"*42)\n"
] | [
[
"torch.device",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
brills/tfx-bsl | [
"089d6673a8d3cccef84ff3d6583808544d2da038"
] | [
"tfx_bsl/coders/sequence_example_coder_test.py"
] | [
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for tfx_bsl.coders.sequence_example_coder.\"\"\"\n\nimport pyarrow as pa\nimport tensorflow as tf\nfrom tfx_bsl.coders import sequence_example_coder\n\nfrom google.protobuf import text_format\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nfrom tensorflow_metadata.proto.v0 import schema_pb2\n\n_TEST_SEQUENCE_COLUMN_NAME = \"##SEQUENCE##\"\n_TYPED_SEQUENCE_EXAMPLE = \"\"\"\n context {\n feature {\n key: 'context_a'\n value {\n int64_list {\n value: [1]\n }\n }\n }\n feature {\n key: \"context_b\"\n value {\n float_list {\n value: [1.0, 2.0]\n }\n }\n }\n feature {\n key: 'context_c'\n value {\n bytes_list {\n value: ['a', 'b', 'c']\n }\n }\n }\n }\n feature_lists {\n feature_list {\n key: 'sequence_x'\n value {\n feature {\n int64_list {\n value: [1, 2]\n }\n }\n feature {\n int64_list {\n value: [3]\n }\n }\n }\n }\n feature_list {\n key: \"sequence_y\"\n value {\n feature {\n float_list {\n value: [3.0, 4.0]\n }\n }\n feature {\n float_list {\n value: [1.0, 2.0]\n }\n }\n }\n }\n feature_list {\n key: 'sequence_z'\n value {\n feature {\n bytes_list {\n value: ['a', 'b']\n }\n }\n feature {\n bytes_list {\n value: ['c']\n }\n }\n }\n }\n }\n \"\"\"\n_UNTYPED_SEQUENCE_EXAMPLE = \"\"\"\n context {\n feature {\n key: 'context_a'\n value {}\n }\n feature {\n key: \"context_b\"\n value {}\n }\n feature {\n key: 'context_c'\n value {}\n }\n feature {\n key: 'context_d'\n value {}\n }\n }\n feature_lists {\n feature_list {\n key: 'sequence_x'\n value {}\n }\n feature_list {\n key: \"sequence_y\"\n value {}\n }\n feature_list {\n key: 'sequence_z'\n value {}\n }\n }\n \"\"\"\n_SOME_FEATURES_TYPED_SEQUENCE_EXAMPLE = \"\"\"\ncontext {\n feature {\n key: 'context_a'\n value {}\n }\n feature {\n key: \"context_b\"\n value {}\n }\n feature {\n key: 'context_c'\n value {}\n }\n feature {\n key: 'context_d'\n value {}\n }\n feature {\n key: 'context_e'\n value {\n float_list {\n value: [1.0]\n }\n }\n }\n }\n feature_lists {\n feature_list {\n key: 'sequence_v'\n value {\n feature {\n float_list {\n value: [1.0]\n }\n }\n }\n }\n feature_list {\n key: 'sequence_x'\n value {\n feature {}\n feature {}\n feature {}\n }\n }\n feature_list {\n key: \"sequence_y\"\n value {\n feature {}\n }\n }\n feature_list {\n key: 'sequence_z'\n value {\n feature {}\n }\n }\n }\n \"\"\"\n_EMPTY_VALUES_LIST_SEQUENCE_EXAMPLE = \"\"\"\ncontext {\n feature {\n key: 'context_a'\n value {\n int64_list {\n value: []\n }\n }\n }\n feature {\n key: \"context_b\"\n value {\n float_list {\n value: []\n }\n }\n }\n feature {\n key: 'context_c'\n value {\n bytes_list {\n value: []\n }\n }\n }\n }\n feature_lists {\n feature_list {\n key: 'sequence_x'\n value {\n feature {\n int64_list {\n value: []\n }\n }\n feature {\n int64_list {\n value: []\n }\n }\n }\n }\n feature_list {\n key: \"sequence_y\"\n value {\n feature {\n float_list {\n value: []\n }\n }\n }\n }\n feature_list {\n key: 'sequence_z'\n value {\n feature {\n bytes_list {\n value: []\n }\n }\n }\n }\n }\n \"\"\"\n_TEST_SEQUENCE_EXAMPLES_NONE_TYPED = [\n \"\"\"\n context {\n feature {\n key: 'context_a'\n value {}\n }\n feature {\n key: \"context_b\"\n value {}\n }\n feature {\n key: 'context_c'\n value {}\n }\n feature {\n key: 'context_d'\n value {}\n }\n }\n feature_lists {\n feature_list {\n key: 'sequence_x'\n value {}\n }\n }\n \"\"\",\n \"\"\"\n context {\n feature {\n key: 'context_a'\n value {}\n }\n feature {\n key: \"context_b\"\n value {}\n }\n feature {\n key: 'context_c'\n value {}\n }\n feature {\n key: 'context_d'\n value {}\n }\n }\n feature_lists {\n feature_list {\n key: 'sequence_w'\n value {\n feature {}\n }\n }\n feature_list {\n key: 'sequence_x'\n value {\n feature {}\n }\n }\n }\n \"\"\",\n]\n\n# pylint: disable=g-long-lambda\n_DECODE_CASES = [\n dict(\n testcase_name=\"without_schema_first_example_typed\",\n schema_text_proto=None,\n sequence_examples_text_proto=[\n _TYPED_SEQUENCE_EXAMPLE, _UNTYPED_SEQUENCE_EXAMPLE,\n _SOME_FEATURES_TYPED_SEQUENCE_EXAMPLE,\n _EMPTY_VALUES_LIST_SEQUENCE_EXAMPLE\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([[1], None, None, []], type=list_factory(pa.int64())),\n pa.array([[1.0, 2.0], None, None, []],\n type=list_factory(pa.float32())),\n pa.array([[b\"a\", b\"b\", b\"c\"], None, None, []],\n type=list_factory(binary_type)),\n pa.array([None, None, None, None], pa.null()),\n pa.array([None, None, [1.0], None], type=list_factory(pa.float32())\n ),\n pa.StructArray.from_arrays([\n pa.array([None, None, [[1.0]], None],\n type=list_factory(list_factory(pa.float32()))),\n pa.array([[[1, 2], [3]], [], [None, None, None], [[], []]],\n type=list_factory(list_factory(pa.int64()))),\n pa.array([[[3.0, 4.0], [1.0, 2.0]], [], [None], [[]]],\n type=list_factory(list_factory(pa.float32()))),\n pa.array([[[b\"a\", b\"b\"], [b\"c\"]], [], [None], [[]]],\n type=list_factory(list_factory(binary_type)))\n ],\n names=[\n \"sequence_v\", \"sequence_x\",\n \"sequence_y\", \"sequence_z\"\n ])\n ], [\n \"context_a\", \"context_b\", \"context_c\", \"context_d\", \"context_e\",\n _TEST_SEQUENCE_COLUMN_NAME\n ])),\n dict(\n testcase_name=\"with_schema_first_example_typed\",\n schema_text_proto=\"\"\"\n feature {\n name: \"context_a\"\n type: INT\n }\n feature {\n name: \"context_b\"\n type: FLOAT\n }\n feature {\n name: \"context_c\"\n type: BYTES\n }\n feature {\n name: \"##SEQUENCE##\"\n type: STRUCT\n struct_domain {\n feature {\n name: \"sequence_x\"\n type: INT\n }\n feature {\n name: \"sequence_y\"\n type: FLOAT\n }\n feature {\n name: \"sequence_z\"\n type: BYTES\n }\n }\n }\"\"\",\n sequence_examples_text_proto=[\n _TYPED_SEQUENCE_EXAMPLE, _UNTYPED_SEQUENCE_EXAMPLE,\n _SOME_FEATURES_TYPED_SEQUENCE_EXAMPLE,\n _EMPTY_VALUES_LIST_SEQUENCE_EXAMPLE\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([[1], None, None, []], type=list_factory(pa.int64())),\n pa.array([[1.0, 2.0], None, None, []],\n type=list_factory(pa.float32())),\n pa.array([[b\"a\", b\"b\", b\"c\"], None, None, []],\n type=list_factory(binary_type)),\n pa.StructArray.from_arrays(\n [\n pa.array([[[1, 2], [3]], [], [None, None, None], [[], []]],\n type=list_factory(list_factory(pa.int64()))),\n pa.array([[[3.0, 4.0], [1.0, 2.0]], [], [None], [[]]],\n type=list_factory(list_factory(pa.float32()))),\n pa.array([[[b\"a\", b\"b\"], [b\"c\"]], [], [None], [[]]],\n type=list_factory(list_factory(binary_type)))\n ],\n names=[\"sequence_x\", \"sequence_y\", \"sequence_z\"])\n ], [\"context_a\", \"context_b\", \"context_c\", _TEST_SEQUENCE_COLUMN_NAME]\n )),\n dict(\n testcase_name=\"without_schema_untyped_then_typed_examples\",\n schema_text_proto=None,\n sequence_examples_text_proto=[\n _UNTYPED_SEQUENCE_EXAMPLE, _SOME_FEATURES_TYPED_SEQUENCE_EXAMPLE,\n _EMPTY_VALUES_LIST_SEQUENCE_EXAMPLE, _TYPED_SEQUENCE_EXAMPLE\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([None, None, [], [1]], type=list_factory(pa.int64())),\n pa.array([None, None, [], [1.0, 2.0]],\n type=list_factory(pa.float32())),\n pa.array([None, None, [], [b\"a\", b\"b\", b\"c\"]],\n type=list_factory(binary_type)),\n pa.array([None, None, None, None], pa.null()),\n pa.array([None, [1.0], None, None], type=list_factory(pa.float32())\n ),\n pa.StructArray.from_arrays([\n pa.array([None, [[1.0]], None, None],\n type=list_factory(list_factory(pa.float32()))),\n pa.array([[], [None, None, None], [[], []], [[1, 2], [3]]],\n type=list_factory(list_factory(pa.int64()))),\n pa.array([[], [None], [[]], [[3.0, 4.0], [1.0, 2.0]]],\n type=list_factory(list_factory(pa.float32()))),\n pa.array([[], [None], [[]], [[b\"a\", b\"b\"], [b\"c\"]]],\n type=list_factory(list_factory(binary_type)))\n ],\n names=[\n \"sequence_v\", \"sequence_x\",\n \"sequence_y\", \"sequence_z\"\n ])\n ], [\n \"context_a\", \"context_b\", \"context_c\", \"context_d\", \"context_e\",\n _TEST_SEQUENCE_COLUMN_NAME\n ])),\n dict(\n testcase_name=\"with_schema_untyped_then_typed_examples\",\n schema_text_proto=\"\"\"\n feature {\n name: \"context_a\"\n type: INT\n }\n feature {\n name: \"context_b\"\n type: FLOAT\n }\n feature {\n name: \"context_c\"\n type: BYTES\n }\n feature {\n name: \"##SEQUENCE##\"\n type: STRUCT\n struct_domain {\n feature {\n name: \"sequence_x\"\n type: INT\n }\n feature {\n name: \"sequence_y\"\n type: FLOAT\n }\n feature {\n name: \"sequence_z\"\n type: BYTES\n }\n }\n }\"\"\",\n sequence_examples_text_proto=[\n _UNTYPED_SEQUENCE_EXAMPLE, _SOME_FEATURES_TYPED_SEQUENCE_EXAMPLE,\n _EMPTY_VALUES_LIST_SEQUENCE_EXAMPLE, _TYPED_SEQUENCE_EXAMPLE\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([None, None, [], [1]], type=list_factory(pa.int64())),\n pa.array([None, None, [], [1.0, 2.0]],\n type=list_factory(pa.float32())),\n pa.array([None, None, [], [b\"a\", b\"b\", b\"c\"]],\n type=list_factory(binary_type)),\n pa.StructArray.from_arrays(\n [\n pa.array([[], [None, None, None], [[], []], [[1, 2], [3]]],\n type=list_factory(list_factory(pa.int64()))),\n pa.array([[], [None], [[]], [[3.0, 4.0], [1.0, 2.0]]],\n type=list_factory(list_factory(pa.float32()))),\n pa.array([[], [None], [[]], [[b\"a\", b\"b\"], [b\"c\"]]],\n type=list_factory(list_factory(binary_type)))\n ],\n names=[\"sequence_x\", \"sequence_y\", \"sequence_z\"])\n ], [\"context_a\", \"context_b\", \"context_c\", _TEST_SEQUENCE_COLUMN_NAME]\n )),\n dict(\n testcase_name=\"without_schema_no_typed_examples\",\n schema_text_proto=None,\n sequence_examples_text_proto=_TEST_SEQUENCE_EXAMPLES_NONE_TYPED,\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([None, None], type=pa.null()),\n pa.array([None, None], type=pa.null()),\n pa.array([None, None], type=pa.null()),\n pa.array([None, None], type=pa.null()),\n pa.StructArray.from_arrays([\n pa.array([None, [None]], type=list_factory(pa.null())),\n pa.array([[], [None]], type=list_factory(pa.null())),\n ],\n names=[\n \"sequence_w\",\n \"sequence_x\",\n ])\n ], [\n \"context_a\", \"context_b\", \"context_c\", \"context_d\",\n _TEST_SEQUENCE_COLUMN_NAME\n ])),\n dict(\n testcase_name=\"with_schema_no_typed_examples\",\n schema_text_proto=\"\"\"\n feature {\n name: \"context_a\"\n type: INT\n }\n feature {\n name: \"context_b\"\n type: FLOAT\n }\n feature {\n name: \"context_c\"\n type: BYTES\n }\n feature {\n name: \"##SEQUENCE##\"\n type: STRUCT\n struct_domain {\n feature {\n name: \"sequence_x\"\n type: INT\n }\n feature {\n name: \"sequence_y\"\n type: FLOAT\n }\n feature {\n name: \"sequence_z\"\n type: BYTES\n }\n }\n }\"\"\",\n sequence_examples_text_proto=_TEST_SEQUENCE_EXAMPLES_NONE_TYPED,\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([None, None], type=list_factory(pa.int64())),\n pa.array([None, None], type=list_factory(pa.float32())),\n pa.array([None, None], type=list_factory(binary_type)),\n pa.StructArray.from_arrays(\n [\n pa.array([[], [None]],\n type=list_factory(list_factory(pa.int64()))),\n pa.array([None, None],\n type=list_factory(list_factory(pa.float32()))),\n pa.array([None, None],\n type=list_factory(list_factory(binary_type)))\n ],\n names=[\"sequence_x\", \"sequence_y\", \"sequence_z\"])\n ], [\"context_a\", \"context_b\", \"context_c\", _TEST_SEQUENCE_COLUMN_NAME]\n )),\n dict(\n testcase_name=\"build_nulls_for_unseen_feature\",\n schema_text_proto=\"\"\"\n feature {\n name: \"context_u\"\n type: BYTES\n }\n feature {\n name: \"##SEQUENCE##\"\n type: STRUCT\n struct_domain {\n feature {\n name: \"sequence_u\"\n type: INT\n }\n }\n }\n \"\"\",\n sequence_examples_text_proto=[\n _TYPED_SEQUENCE_EXAMPLE, _UNTYPED_SEQUENCE_EXAMPLE,\n _SOME_FEATURES_TYPED_SEQUENCE_EXAMPLE,\n _EMPTY_VALUES_LIST_SEQUENCE_EXAMPLE\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([None, None, None, None], type=list_factory(binary_type)),\n pa.StructArray.from_arrays([\n pa.array([None, None, None, None],\n type=list_factory(list_factory(pa.int64())))\n ],\n names=[\"sequence_u\"]),\n ], [\"context_u\", _TEST_SEQUENCE_COLUMN_NAME])),\n dict(\n testcase_name=\"build_null_for_unset_kind\",\n schema_text_proto=\"\"\"\n feature {\n name: \"context_a\"\n type: BYTES\n }\n feature {\n name: \"##SEQUENCE##\"\n type: STRUCT\n struct_domain {\n feature {\n name: \"sequence_a\"\n type: INT\n }\n }\n }\n \"\"\",\n sequence_examples_text_proto=[\n \"\"\"\n context { feature { key: \"context_a\" value { } } }\n feature_lists {\n feature_list { key: 'sequence_a' value { } }\n }\n \"\"\"\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([None], type=list_factory(binary_type)),\n pa.StructArray.from_arrays(\n [pa.array([[]], type=list_factory(list_factory(pa.int64())))],\n names=[\"sequence_a\"]),\n ], [\"context_a\", _TEST_SEQUENCE_COLUMN_NAME])),\n dict(\n testcase_name=\"schema_does_not_contain_sequence_feature\",\n schema_text_proto=\"\"\"\n feature {\n name: \"context_a\"\n type: BYTES\n }\n \"\"\",\n sequence_examples_text_proto=[\n \"\"\"\n context { feature { key: \"context_a\" value { } } }\n feature_lists {\n feature_list { key: 'sequence_a' value { } }\n }\n \"\"\"\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([None], type=list_factory(binary_type)),\n ], [\"context_a\"])),\n dict(\n testcase_name=\"duplicate_context_feature_names_in_schema\",\n schema_text_proto=\"\"\"\n feature {\n name: \"context_a\"\n type: BYTES\n }\n # Note that the second feature \"context_a\" will be ignored.\n feature {\n name: \"context_a\"\n type: INT\n }\n \"\"\",\n sequence_examples_text_proto=[\n \"\"\"\n context { feature { key: \"context_a\" value { } } }\n feature_lists {\n feature_list { key: 'sequence_a' value { } }\n }\n \"\"\"\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([None], type=list_factory(binary_type)),\n ], [\"context_a\"])),\n dict(\n testcase_name=\"duplicate_sequence_feature_names_in_schema\",\n schema_text_proto=\"\"\"\n feature {\n name: \"##SEQUENCE##\"\n type: STRUCT\n struct_domain {\n feature {\n name: \"sequence_a\"\n type: INT\n }\n # Note that the second feature \"sequence_a\" will be ignored.\n feature {\n name: \"sequence_a\"\n type: BYTES\n }\n }\n }\n \"\"\",\n sequence_examples_text_proto=[\n \"\"\"\n feature_lists {\n feature_list { key: 'sequence_a' value { } }\n }\n \"\"\"\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.StructArray.from_arrays(\n [pa.array([[]], type=list_factory(list_factory(pa.int64())))],\n names=[\"sequence_a\"]),\n ], [_TEST_SEQUENCE_COLUMN_NAME])),\n dict(\n testcase_name=\"feature_lists_with_no_sequence_features\",\n schema_text_proto=None,\n sequence_examples_text_proto=[\"\"\"\n feature_lists {}\n \"\"\"],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.StructArray.from_buffers(pa.struct([]), 1, [None]),\n ], [_TEST_SEQUENCE_COLUMN_NAME])),\n dict(\n testcase_name=\"without_schema_only_context_features\",\n schema_text_proto=None,\n sequence_examples_text_proto=[\n \"\"\"\n context {\n feature {\n key: 'context_a'\n value {\n int64_list {\n value: [1, 2]\n }\n }\n }\n }\n \"\"\"\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.array([[1, 2]], type=list_factory(pa.int64())),\n ], [\"context_a\"])),\n dict(\n testcase_name=\"without_schema_only_sequence_features\",\n schema_text_proto=None,\n sequence_examples_text_proto=[\n \"\"\"\n feature_lists {\n feature_list {\n key: 'sequence_x'\n value {\n feature {\n int64_list {\n value: [1, 2]\n }\n }\n }\n }\n }\n \"\"\"\n ],\n create_expected=lambda list_factory, binary_type: pa.RecordBatch.\n from_arrays([\n pa.StructArray.from_arrays([\n pa.array([[[1, 2]]],\n type=list_factory(list_factory(pa.int64()))),\n ],\n names=[\"sequence_x\"])\n ], [_TEST_SEQUENCE_COLUMN_NAME])),\n]\n# pylint: enable=g-long-lambda\n\n_INVALID_INPUT_CASES = [\n dict(\n testcase_name=\"context_feature_actual_type_mismatches_schema_type\",\n schema_text_proto=\"\"\"\n feature {\n name: \"a\"\n type: BYTES\n }\n \"\"\",\n sequence_examples_text_proto=[\n \"\"\"\n context { feature { key: \"a\" value { float_list { value: [] } } } }\n \"\"\"\n ],\n error=RuntimeError,\n error_msg_regex=(\n \"Feature had wrong type, expected bytes_list, found float_list \"\n \"for feature \\\"a\\\"\"),\n ),\n dict(\n testcase_name=\"sequence_feature_actual_type_mismatches_schema_type\",\n schema_text_proto=\"\"\"\n feature {\n name: \"##SEQUENCE##\"\n type: STRUCT\n struct_domain {\n feature {\n name: \"a\"\n type: BYTES\n }\n }\n }\n \"\"\",\n sequence_examples_text_proto=[\n \"\"\"\n feature_lists {\n feature_list {\n key: 'a'\n value {\n feature { float_list { value: [] } }\n }\n }\n }\n \"\"\"\n ],\n error=RuntimeError,\n error_msg_regex=(\n \"Feature had wrong type, expected bytes_list, found float_list \"\n \"for sequence feature \\\"a\\\"\"),\n ),\n dict(\n testcase_name=\"context_feature_no_schema_mixed_type\",\n schema_text_proto=None,\n sequence_examples_text_proto=[\n \"\"\"\n context { feature { key: \"a\" value { float_list { value: [] } } } }\n \"\"\", \"\"\"\n context { feature { key: \"a\" value { int64_list { value: [] } } } }\n \"\"\"\n ],\n error=RuntimeError,\n error_msg_regex=(\n \"Feature had wrong type, expected float_list, found int64_list\"\n \" for feature \\\"a\\\"\"),\n ),\n dict(\n testcase_name=\"sequence_feature_no_schema_mixed_type\",\n schema_text_proto=None,\n sequence_examples_text_proto=[\n \"\"\"\n feature_lists {\n feature_list {\n key: 'a'\n value {\n feature { float_list { value: [] } }\n }\n }\n }\n \"\"\", \"\"\"\n feature_lists {\n feature_list {\n key: 'a'\n value {\n feature { int64_list { value: [] } }\n }\n }\n }\n \"\"\"\n ],\n error=RuntimeError,\n error_msg_regex=(\n \"Feature had wrong type, expected float_list, found int64_list\"\n \" for sequence feature \\\"a\\\"\"),\n ),\n]\n\n\nclass SequenceExamplesToRecordBatchDecoderTest(parameterized.TestCase):\n\n def _test_decode(self, schema_text_proto, sequence_examples_text_proto,\n create_expected, use_large_types):\n serialized_sequence_examples = [\n text_format.Parse(pbtxt,\n tf.train.SequenceExample()).SerializeToString()\n for pbtxt in sequence_examples_text_proto\n ]\n serialized_schema = None\n if schema_text_proto is not None:\n serialized_schema = text_format.Parse(\n schema_text_proto, schema_pb2.Schema()).SerializeToString()\n\n if serialized_schema:\n coder = sequence_example_coder.SequenceExamplesToRecordBatchDecoder(\n _TEST_SEQUENCE_COLUMN_NAME,\n serialized_schema,\n use_large_types=use_large_types)\n else:\n coder = sequence_example_coder.SequenceExamplesToRecordBatchDecoder(\n _TEST_SEQUENCE_COLUMN_NAME, use_large_types=use_large_types)\n\n result = coder.DecodeBatch(serialized_sequence_examples)\n self.assertIsInstance(result, pa.RecordBatch)\n if use_large_types:\n expected = create_expected(pa.large_list, pa.large_binary())\n else:\n expected = create_expected(pa.list_, pa.binary())\n self.assertTrue(\n result.equals(expected),\n \"actual: {}\\n expected:{}\".format(result, expected))\n\n if serialized_schema is not None:\n self.assertTrue(coder.ArrowSchema().equals(result.schema))\n\n @parameterized.named_parameters(*_DECODE_CASES)\n def test_decode(self, schema_text_proto, sequence_examples_text_proto,\n create_expected):\n self._test_decode(schema_text_proto, sequence_examples_text_proto,\n create_expected, use_large_types=False)\n\n @parameterized.named_parameters(*_DECODE_CASES)\n def test_decode_large_types(self, schema_text_proto,\n sequence_examples_text_proto, create_expected):\n self._test_decode(schema_text_proto, sequence_examples_text_proto,\n create_expected, use_large_types=True)\n\n @parameterized.named_parameters(*_INVALID_INPUT_CASES)\n def test_invalid_input(self, schema_text_proto, sequence_examples_text_proto,\n error, error_msg_regex):\n serialized_sequence_examples = [\n text_format.Parse(pbtxt,\n tf.train.SequenceExample()).SerializeToString()\n for pbtxt in sequence_examples_text_proto\n ]\n serialized_schema = None\n if schema_text_proto is not None:\n serialized_schema = text_format.Parse(\n schema_text_proto, schema_pb2.Schema()).SerializeToString()\n\n if serialized_schema:\n coder = sequence_example_coder.SequenceExamplesToRecordBatchDecoder(\n _TEST_SEQUENCE_COLUMN_NAME, serialized_schema)\n else:\n coder = sequence_example_coder.SequenceExamplesToRecordBatchDecoder(\n _TEST_SEQUENCE_COLUMN_NAME)\n\n with self.assertRaisesRegex(error, error_msg_regex):\n coder.DecodeBatch(serialized_sequence_examples)\n\n def test_sequence_feature_column_name_not_struct_in_schema(self):\n schema_text_proto = \"\"\"\n feature {\n name: \"##SEQUENCE##\"\n type: INT\n }\n \"\"\"\n serialized_schema = text_format.Parse(\n schema_text_proto, schema_pb2.Schema()).SerializeToString()\n\n error_msg_regex = (\n \"Found a feature in the schema with the sequence_feature_column_name \"\n r\"\\(i.e., ##SEQUENCE##\\) that is not a struct.*\")\n\n with self.assertRaisesRegex(RuntimeError, error_msg_regex):\n sequence_example_coder.SequenceExamplesToRecordBatchDecoder(\n _TEST_SEQUENCE_COLUMN_NAME, serialized_schema)\n\n\nif __name__ == \"__main__\":\n absltest.main()\n"
] | [
[
"tensorflow.train.SequenceExample"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chepo92/tinyquaternion | [
"cc5a1a576231bb6691dc8a48b4b6f4b81b3ca225"
] | [
"tinyquaternion/test/test_tinyquaternion.py"
] | [
"import numpy as np\r\n\r\nfrom tinyQuaternion import Quaternion\r\n\r\nq = Quaternion(q=np.array([0., 0., 2., 0.]))\r\nprint(q)\r\nprint(repr(q))\r\n\r\nprint(q.vector)\r\nprint(q.scalar)\r\nprint(q.magnitude)\r\nprint(q.is_unit())\r\nprint(q.normalized)\r\nprint(q.is_unit())\r\nprint(q.conjugate)\r\nprint(q.inverse)\r\nprint(q.axisangle())\r\n\r\n\r\nq1 = Quaternion(a=np.pi/3, n=np.array([0.,0.,1.]))\r\nq2 = Quaternion(q=np.array([1.,1.,1.,0.]))\r\n\r\nprint(q1)\r\nprint(q2)\r\nprint(q1.add(q2))\r\nprint(q1.sub(q2))\r\nprint(q1.mul(q2))\r\nprint(q1.div(q2))\r\n\r\n\r\np = np.array([1.,2.,-1.])\r\nprint(q1.rotatePoint(p))\r\n\r\n\r\nq3 = Quaternion(a=np.pi/4, n=np.array([0.,0.,1.]))\r\nprint(q3.log)\r\nprint(q3.exp)\r\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AlexMinhao/NAS_GNN | [
"89183988a96e1d6baed910ab3843c13282f8b077"
] | [
"graphnas/trainer.py"
] | [
"import glob\nimport os\n\nimport numpy as np\nimport scipy.signal\nimport torch\n\nimport graphnas.utils.tensor_utils as utils\nfrom graphnas.gnn_model_manager import CitationGNNManager\nfrom graphnas_variants.macro_graphnas.pyg.pyg_gnn_model_manager import GeoCitationManager\nfrom time import time\n\nlogger = utils.get_logger()\n\n\ndef discount(x, amount):\n return scipy.signal.lfilter([1], [1, -amount], x[::-1], axis=0)[::-1]\n\n\nhistory = []\n\n\ndef scale(value, last_k=10, scale_value=1):\n '''\n scale value into [-scale_value, scale_value], according last_k history\n '''\n max_reward = np.max(history[-last_k:])\n if max_reward == 0:\n return value\n return scale_value / max_reward * value\n\n\ndef _get_optimizer(name):\n if name.lower() == 'sgd':\n optim = torch.optim.SGD\n elif name.lower() == 'adam':\n optim = torch.optim.Adam\n\n return optim\n\n\nclass Trainer(object):\n \"\"\"Manage the training process\"\"\"\n\n def __init__(self, args):\n \"\"\"\n Constructor for training algorithm.\n Build sub-model manager and controller.\n Build optimizer and cross entropy loss for controller.\n\n Args:\n args: From command line, picked up by `argparse`.\n \"\"\"\n self.args = args\n self.controller_step = 0 # counter for controller\n self.cuda = args.cuda\n self.epoch = 0\n self.start_epoch = 0\n\n self.max_length = self.args.shared_rnn_max_length\n\n self.with_retrain = False\n self.submodel_manager = None\n self.controller = None\n self.build_model() # build controller and sub-model -> micro_model_manager.ZengManager && SimpleNASController\n\n controller_optimizer = _get_optimizer(self.args.controller_optim) # adam\n self.controller_optim = controller_optimizer(self.controller.parameters(), lr=self.args.controller_lr) # 0.00035\n\n if self.args.mode == \"derive\": #'train'\n self.load_model()\n\n def build_model(self):\n self.args.share_param = False\n self.with_retrain = True\n self.args.shared_initial_step = 0\n if self.args.search_mode == \"macro\":\n # generate model description in macro way (generate entire network description)\n from graphnas.search_space import MacroSearchSpace\n search_space_cls = MacroSearchSpace()\n self.search_space = search_space_cls.get_search_space()\n self.action_list = search_space_cls.generate_action_list(self.args.layers_of_child_model)\n # build RNN controller\n from graphnas.graphnas_controller import SimpleNASController\n self.controller = SimpleNASController(self.args, action_list=self.action_list,\n search_space=self.search_space,\n cuda=self.args.cuda)\n\n if self.args.dataset in [\"cora\", \"citeseer\", \"pubmed\"]:\n # implements based on dgl\n self.submodel_manager = CitationGNNManager(self.args)\n if self.args.dataset in [\"Cora\", \"Citeseer\", \"Pubmed\"]:\n # implements based on pyg\n self.submodel_manager = GeoCitationManager(self.args)\n\n\n if self.args.search_mode == \"micro\":\n self.args.format = \"micro\"\n self.args.predict_hyper = True\n if not hasattr(self.args, \"num_of_cell\"):\n self.args.num_of_cell = 2\n from graphnas_variants.micro_graphnas.micro_search_space import IncrementSearchSpace\n search_space_cls = IncrementSearchSpace()\n search_space = search_space_cls.get_search_space()\n from graphnas.graphnas_controller import SimpleNASController\n from graphnas_variants.micro_graphnas.micro_model_manager import MicroCitationManager\n self.submodel_manager = MicroCitationManager(self.args)\n self.search_space = search_space\n action_list = search_space_cls.generate_action_list(cell=self.args.num_of_cell)\n if hasattr(self.args, \"predict_hyper\") and self.args.predict_hyper:\n self.action_list = action_list + [\"learning_rate\", \"dropout\", \"weight_decay\", \"hidden_unit\", \"num_layers\"]\n else:\n self.action_list = action_list\n self.controller = SimpleNASController(self.args, action_list=self.action_list,\n search_space=self.search_space,\n cuda=self.args.cuda)\n if self.cuda:\n self.controller.cuda()\n\n if self.args.search_mode == \"Zeng\":\n self.args.format = \"Zeng\"\n self.args.predict_hyper = True\n\n from graphnas_variants.micro_graphnas.micro_search_space import SearchSpaceZeng\n search_space_cls = SearchSpaceZeng(self.args)\n search_space = search_space_cls.get_search_space()\n from graphnas.graphnas_controller import SimpleNASController\n from graphnas_variants.micro_graphnas.micro_model_manager import ZengManager\n self.submodel_manager = ZengManager(self.args)\n self.search_space = search_space\n action_list = search_space_cls.generate_action_list(K=self.args.num_hops)\n\n self.action_list = action_list\n self.controller = SimpleNASController(self.args, action_list=self.action_list,\n search_space=self.search_space,\n cuda=self.args.cuda)\n if self.cuda:\n self.controller.cuda()\n\n if self.cuda:\n self.controller.cuda()\n\n def form_gnn_info(self, gnn): # [0, 'sage', 0, 'gat_6', 'linear', 'product', 0.01, 0.1, 0.0001, 32]\n if self.args.search_mode == \"micro\":\n actual_action = {}\n if self.args.predict_hyper:\n actual_action[\"action\"] = gnn[:-5] # {'action': [0, 'sage', 0, 'gat_6', 'linear', 'product']}\n actual_action[\"hyper_param\"] = gnn[-5:] # [0.01, 0.1, 0.0001, 32]\n else:\n actual_action[\"action\"] = gnn\n actual_action[\"hyper_param\"] = [0.005, 0.8, 5e-5, 128]\n return actual_action\n return gnn\n\n def train(self):\n \"\"\"\n Each epoch consists of two phase:\n - In the first phase, shared parameters are trained to exploration.\n - In the second phase, the controller's parameters are trained.\n \"\"\"\n # best_actions = self.derive()\n\n for self.epoch in range(self.start_epoch, self.args.max_epoch): #0 - 10\n print(\"****** Start - Trainer Current-Epoch {:05d}, start {:05d}, max {:05d} ******\".format(\n self.epoch, self.start_epoch, self.args.max_epoch))\n print(\"#1. Training the shared parameters of the child graphnas\")\n self.train_shared(max_step=self.args.shared_initial_step) #0 no train shared\n print(\"#2. Training the controller parameters theta\")\n self.train_controller() # num_sample = 1\n print(\"#3. Derive architectures\")\n self.derive(sample_num=self.args.derive_num_sample) # default=100 # num_sample = 100\n\n if self.epoch % self.args.save_epoch == 0: # default=2)\n print(\"#4. Save_Model\")\n self.save_model()\n print(\"****** End - Trainer Current-Epoch {:05d}, start {:05d}, max {:05d} ******\".format(\n self.epoch, self.start_epoch, self.args.max_epoch))\n print(\"****** Finish all Epoch ******\")\n if self.args.derive_finally: # default=True\n print(\"****** Start Derive_finally ******\")\n best_actions = self.derive()\n print(\"best structure:\" + str(best_actions))\n print(\"****** Start Derive_finally ******\")\n print(\"****** FINALLY SAVE MODEL ******\")\n self.save_model()\n print(\"****** FINALLY MODEL SAVED******\")\n\n def train_shared(self, max_step=50, gnn_list=None):\n \"\"\"\n Args:\n max_step: Used to run extra training steps as a warm-up.\n gnn: If not None, is used instead of calling sample().\n\n \"\"\"\n if max_step == 0: # no train shared\n return\n\n print(\"*\" * 35, \"training model\", \"*\" * 35)\n gnn_list = gnn_list if gnn_list else self.controller.sample(max_step)\n\n for gnn in gnn_list:\n gnn = self.form_gnn_info(gnn)\n try:\n _, val_score = self.submodel_manager.train(gnn, format=self.args.format)\n logger.info(f\"{gnn}, val_score:{val_score}\")\n except RuntimeError as e:\n if 'CUDA' in str(e): # usually CUDA Out of Memory\n print(e)\n else:\n raise e\n\n print(\"*\" * 35, \"training over\", \"*\" * 35)\n\n def get_reward(self, gnn_list, entropies, hidden):\n \"\"\"\n Computes the reward of a single sampled model on validation data.\n \"\"\"\n if not isinstance(entropies, np.ndarray):\n entropies = entropies.data.cpu().numpy()\n if isinstance(gnn_list, dict):\n gnn_list = [gnn_list]\n if isinstance(gnn_list[0], list) or isinstance(gnn_list[0], dict):\n pass\n else:\n gnn_list = [gnn_list] # when structure_list is one structure\n\n reward_list = []\n for gnn in gnn_list: #[['gat', 'max', 'tanh', 1, 128, 'cos', 'sum', 'tanh', 4, 16]]\n gnn = self.form_gnn_info(gnn)\n reward = self.submodel_manager.test_with_param(gnn, format=self.args.format,\n with_retrain=self.with_retrain)\n\n if reward is None: # cuda error hanppened\n reward = 0\n else:\n reward = reward[1]\n\n reward_list.append(reward)\n\n if self.args.entropy_mode == 'reward':\n rewards = reward_list + self.args.entropy_coeff * entropies\n elif self.args.entropy_mode == 'regularizer':\n rewards = reward_list * np.ones_like(entropies)\n else:\n raise NotImplementedError(f'Unkown entropy mode: {self.args.entropy_mode}')\n\n return rewards, hidden\n\n def train_controller(self):\n \"\"\"\n Train controller to find better structure.\n \"\"\"\n print(\"*\" * 35, \"training controller\", \"*\" * 35)\n model = self.controller\n model.train()\n\n baseline = None\n adv_history = []\n entropy_history = []\n reward_history = []\n\n hidden = self.controller.init_hidden(self.args.batch_size) #2 64 100\n total_loss = 0\n for step in range(self.args.controller_max_step): # 100\n start_time = time()\n # sample graphnas\n structure_list, log_probs, entropies = self.controller.sample(with_details=True) # num_sample = 1\n#[['gat', 'max', 'tanh', 1, 128, 'cos', 'sum', 'tanh', 4, 16]]\n#tensor([-1.9461, -1.3946, -2.0890, -1.7695, -1.9348, -1.9490, -1.3980, -2.0886,-1.7938, -1.9401], device='cuda:0', grad_fn=<CatBackward>)\n#tensor([1.9459, 1.3863, 2.0794, 1.7917, 1.9458, 1.9459, 1.3862, 2.0794, 1.7917,1.9458], device='cuda:0', grad_fn=<CatBackward>)\n # calculate reward\n np_entropies = entropies.data.cpu().numpy()\n results = self.get_reward(structure_list, np_entropies, hidden)\n torch.cuda.empty_cache()\n\n if results: # has reward\n rewards, hidden = results\n else:\n continue # CUDA Error happens, drop structure and step into next iteration\n\n # discount\n if 1 > self.args.discount > 0:\n rewards = discount(rewards, self.args.discount)\n\n reward_history.extend(rewards)\n entropy_history.extend(np_entropies)\n\n # moving average baseline\n if baseline is None:\n baseline = rewards\n else:\n decay = self.args.ema_baseline_decay\n baseline = decay * baseline + (1 - decay) * rewards\n\n adv = rewards - baseline\n history.append(adv)\n adv = scale(adv, scale_value=0.5)\n adv_history.extend(adv)\n\n adv = utils.get_variable(adv, self.cuda, requires_grad=False)\n # policy loss\n loss = -log_probs * adv\n if self.args.entropy_mode == 'regularizer':\n loss -= self.args.entropy_coeff * entropies\n\n loss = loss.sum() # or loss.mean()\n\n # update\n self.controller_optim.zero_grad()\n loss.backward()\n\n if self.args.controller_grad_clip > 0:\n torch.nn.utils.clip_grad_norm(model.parameters(),\n self.args.controller_grad_clip)\n self.controller_optim.step()\n\n total_loss += utils.to_item(loss.data)\n\n self.controller_step += 1\n torch.cuda.empty_cache()\n elapsed = (time() - start_time)\n print('[%d/%d] time %.2f ' % (\n step + 1, self.args.controller_max_step,\n elapsed,\n ))\n print(\"*\" * 35, \"training controller over\", \"*\" * 35)\n\n def evaluate(self, gnn):\n \"\"\"\n Evaluate a structure on the validation set.\n \"\"\"\n self.controller.eval()\n gnn = self.form_gnn_info(gnn)\n results = self.submodel_manager.retrain(gnn, format=self.args.format)\n if results:\n reward, scores = results\n else:\n return\n\n logger.info(f'eval | {gnn} | reward: {reward:8.2f} | scores: {scores:8.2f}')\n\n def derive_from_history(self):\n if self.args.search_mode == 'Zeng':\n with open(self.args.dataset + \"_\" + self.args.search_mode + self.args.submanager_log_file, \"r\") as f:\n lines = f.readlines()\n else:\n with open(self.args.dataset + \"_\" + self.args.search_mode + self.args.submanager_log_file, \"a\") as f:\n lines = f.readlines()\n\n results = []\n best_val_score = \"0\"\n for line in lines:\n actions = line[:line.index(\";\")]\n val_score = line.split(\";\")[-1]\n results.append((actions, val_score))\n results.sort(key=lambda x: x[-1], reverse=True) # sort\n best_structure = \"\"\n best_score = 0\n for actions in results[:5]:\n actions = eval(actions[0])\n np.random.seed(123)\n torch.manual_seed(123)\n torch.cuda.manual_seed_all(123)\n val_scores_list = []\n for i in range(20):\n val_acc, test_acc = self.submodel_manager.evaluate(actions)\n val_scores_list.append(val_acc)\n\n tmp_score = np.mean(val_scores_list)\n if tmp_score > best_score:\n best_score = tmp_score\n best_structure = actions\n\n print(\"best structure:\" + str(best_structure))\n # train from scratch to get the final score\n np.random.seed(123)\n torch.manual_seed(123)\n torch.cuda.manual_seed_all(123)\n test_scores_list = []\n for i in range(100):\n # manager.shuffle_data()\n val_acc, test_acc = self.submodel_manager.evaluate(best_structure)\n test_scores_list.append(test_acc)\n print(f\"best results: {best_structure}: {np.mean(test_scores_list):.8f} +/- {np.std(test_scores_list)}\")\n return best_structure\n\n def derive(self, sample_num=None):\n \"\"\"\n sample a serial of structures, and return the best structure.\n \"\"\"# default=100 # default = True\n if sample_num is None and self.args.derive_from_history:\n print(\"****** Derive_finally -> derive_from_history ******\")\n return self.derive_from_history()\n else:\n if sample_num is None:\n sample_num = self.args.derive_num_sample\n\n gnn_list, _, entropies = self.controller.sample(sample_num, with_details=True)\n\n max_R = 0\n best_actions = None\n filename = self.model_info_filename\n for action in gnn_list: # 100 list action [ , , , , , ]\n gnn = self.form_gnn_info(action)\n reward = self.submodel_manager.test_with_param(gnn, format=self.args.format,\n with_retrain=self.with_retrain)\n\n if reward is None: # cuda error hanppened\n continue\n else:\n results = reward[1]\n\n if results > max_R:\n max_R = results\n best_actions = action\n\n logger.info(f'derive |action:{best_actions} |max_R: {max_R:8.6f}')\n self.evaluate(best_actions)\n return best_actions\n\n @property\n def model_info_filename(self):\n return f\"{self.args.dataset}_hops{self.args.num_hops}_grat{self.args.num_granularity}_{self.args.search_mode}_{self.args.format}_results.txt\"\n\n @property\n def controller_path(self):########################################\n return f'{self.args.dataset}/controller_hops{self.args.num_hops}_grat{self.args.num_granularity}_epoch{self.epoch}_step{self.controller_step}.pth'\n\n # return f'{self.args.dataset}/controller_epoch{self.epoch}_step{self.controller_step}.pth'\n\n @property\n def controller_optimizer_path(self):########################################\n return f'{self.args.dataset}/controller_hops{self.args.num_hops}_grat{self.args.num_granularity}_epoch{self.epoch}_step{self.controller_step}_optimizer.pth'\n\n # return f'{self.args.dataset}/controller_epoch{self.epoch}_step{self.controller_step}_optimizer.pth'\n\n def get_saved_models_info(self):\n paths = glob.glob(os.path.join(self.args.dataset, '*.pth'))\n paths.sort()\n\n def get_numbers(items, delimiter, idx, replace_word, must_contain=''):\n temp = [] # '_' fenge\n for name in items:\n if must_contain in name:\n a1 = name.split(delimiter)[0].replace(replace_word, '')\n a = name.split(delimiter)\n str = a[idx]\n num = str.replace(replace_word, '') #把epoch 替换成‘’\n # temp.append(set(int(a)))\n\n return list(set([int(\n name.split(delimiter)[idx].replace(replace_word, ''))\n for name in items if must_contain in name]))\n\n basenames = [os.path.basename(path.rsplit('.', 1)[0]) for path in paths]\n if self.args.search_mode == 'Zeng':\n hops = get_numbers(basenames, '_', 1, 'hops')\n grat = get_numbers(basenames, '_', 2, 'grat')\n epochs = get_numbers(basenames, '_', 3, 'epoch')\n shared_steps = get_numbers(basenames, '_', 4, 'step', 'shared')\n controller_steps = get_numbers(basenames, '_', 4, 'step', 'controller')\n\n # hops.sort()\n # grat.sort()\n epochs.sort()\n shared_steps.sort()\n controller_steps.sort()\n\n return epochs, shared_steps, controller_steps\n\n else:\n epochs = get_numbers(basenames, '_', 1, 'epoch')\n shared_steps = get_numbers(basenames, '_', 2, 'step', 'shared')\n controller_steps = get_numbers(basenames, '_', 2, 'step', 'controller')\n\n epochs.sort()\n shared_steps.sort()\n controller_steps.sort()\n\n return epochs, shared_steps, controller_steps\n\n\n\n\n def save_model(self):\n\n torch.save(self.controller.state_dict(), self.controller_path)\n torch.save(self.controller_optim.state_dict(), self.controller_optimizer_path)\n\n logger.info(f'[*] SAVED: {self.controller_path}')\n\n epochs, shared_steps, controller_steps = self.get_saved_models_info()\n\n for epoch in epochs[:-self.args.max_save_num]:\n paths = glob.glob(\n os.path.join(self.args.dataset, f'*_hops{self.args.num_hops}_grat{self.args.num_granularity}_epoch{epoch}_*.pth'))\n\n for path in paths:\n utils.remove_file(path)\n\n def load_model(self):\n epochs, shared_steps, controller_steps = self.get_saved_models_info()\n\n if len(epochs) == 0:\n logger.info(f'[!] No checkpoint found in {self.args.dataset}...')\n return\n\n self.epoch = self.start_epoch = max(epochs)\n self.controller_step = max(controller_steps)\n\n self.controller.load_state_dict(\n torch.load(self.controller_path))\n self.controller_optim.load_state_dict(\n torch.load(self.controller_optimizer_path))\n logger.info(f'[*] LOADED: {self.controller_path}')\n"
] | [
[
"numpy.ones_like",
"numpy.random.seed",
"torch.load",
"torch.manual_seed",
"torch.cuda.empty_cache",
"numpy.max",
"numpy.std",
"numpy.mean",
"torch.cuda.manual_seed_all"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DavidSlayback/rlpyt | [
"445adbd3917842caae0cae0d06e4b2866c8f1258"
] | [
"rlpyt/samplers/serial/isaac.py"
] | [
"from rlpyt.utils.logging import logger\nfrom rlpyt.agents.base import AgentInputs\nfrom rlpyt.samplers.buffer import build_samples_buffer_torch_env\nfrom rlpyt.utils.buffer import buffer_to\nfrom rlpyt.utils.logging import logger\nfrom rlpyt.samplers.collections import BatchSpec, TrajInfo\nfrom rlpyt.samplers.prevec.collections import TrajInfoVecGPU\nfrom gym_pomdps.wrappers import AutoresettingBatchPOMDP\nimport numpy as np\nimport torch\n\nclass IsaacSampler:\n \"\"\" Specially made serial sampler variant for isaacgym\"\"\"\n alternating = False # Can't alternate, just one cuda env\n mid_batch_reset = False\n def __init__(self,\n isaac_env, # Instantiated isaac environment\n batch_T, # Number of timesteps per sampled batch\n batch_B=None, # Ignored, comes from env\n max_decorrelation_steps=100 # Number of random actions to take at start,\n ):\n self.batch_spec = BatchSpec(batch_T, isaac_env.num_envs)\n self.env = isaac_env\n self.decorrelation_steps = max_decorrelation_steps\n self.TrajInfoCls = TrajInfoVecGPU\n self.ReturnTrajInfoCls = TrajInfo\n\n def initialize(self,\n agent,\n affinity=None,\n seed=None,\n bootstrap_value=False,\n traj_info_kwargs=None,\n rank=0,\n world_size=1, ):\n \"\"\"Should instantiate all components, including setup of parallel\n process if applicable.\"\"\"\n B = self.batch_spec.B\n global_B = B * world_size\n env_ranks = list(range(rank * B, (rank + 1) * B))\n agent.initialize(self.env.spaces, share_memory=False, global_B=global_B, env_ranks=env_ranks)\n samples_pyt, samples_np, examples = build_samples_buffer_torch_env(agent, self.env,\n self.batch_spec, bootstrap_value, agent_shared=False,\n env_shared=False, subprocess=False)\n self.samples_pyt = buffer_to(samples_pyt, self.env.device) # Pytorch buffer\n if traj_info_kwargs:\n for k, v in traj_info_kwargs.items():\n setattr(self.TrajInfoCls, \"_\" + k, v) # Avoid passing at init.\n setattr(self.ReturnTrajInfoCls, \"_\" + k, v)\n if self.decorrelation_steps != 0:\n self.agent_inputs, self.traj_infos = self._decorrelate_envs()\n # Collector calls start_agent here, but doesn't apply\n self.agent = agent\n logger.log(\"Isaac Sampler initialized.\")\n return examples\n\n def _decorrelate_envs(self):\n \"\"\"Return agent_inputs and traj_info at the end of decorrelation using random actions (collector.start_envs)\"\"\"\n prev_action = torch.tensor(np.tile(self.env.action_space.null_value(), (self.batch_spec.B, 1)), device=self.env.device)\n prev_reward = torch.zeros((self.batch_spec.B,), device=self.env.device)\n observation = torch.zeros((self.batch_spec.B, self.env.observation_space.shape[0]), device=self.env.device)\n traj_infos = self.TrajInfoCls(B=self.batch_spec.B)\n\n self.env.reset() # Reset all environments\n for _ in range(self.decorrelation_steps):\n a = self.env.action_space.sample() # Sample random actions\n o, r, d, info = self.env.step(a) # Take step\n traj_infos.step(o, a, r, d, None, info, reset_dones=True) # Update traj_info\n\n observation[:], prev_action[:], prev_reward[:] = o, a, r\n return AgentInputs(o, a, r), traj_infos\n\n def obtain_samples(self, itr):\n \"\"\"Execute agent-environment interactions and return data batch.\"\"\"\n self.agent_inputs, self.traj_infos, completed_infos = self._collect_batch(itr)\n return self.samples_pyt, completed_infos\n\n def _collect_batch(self, itr):\n \"\"\"Collect batch of experience from environment (collector.collect_batch)\"\"\"\n agent_buf, env_buf = self.samples_pyt.agent, self.samples_pyt.env\n completed_infos = list()\n o, a, r = self.agent_inputs # Previous last inputs. Already torchified\n self.agent.sample_mode(itr)\n for t in range(self.batch_spec.T):\n agent_buf.prev_action[t] = a # Store previous action\n env_buf.prev_reward[t] = r # Store previous reward\n env_buf.observation[t] = o # Store observation\n # Agent inputs and outputs are torch tensors.\n a, agent_info = self.agent.step(o, a, r)\n o, r, d, info = self.env.step(a)\n self.traj_infos.step(o, a, r, d, agent_info, info, reset_dones=False)\n # Get completed infos (non-tensor). Environment auto-resets\n completed_infos += self.traj_infos.terminate(d)\n if torch.sum(d): self.agent.reset_multiple(indexes=d.cpu().bool().numpy())\n env_buf.done[t] = d\n env_buf.reward[t] = r\n agent_buf.action[t] = a\n if info:\n env_buf.env_info[t] = info\n if agent_info:\n agent_buf.agent_info[t] = agent_info\n\n if \"bootstrap_value\" in agent_buf:\n # agent.value() should not advance rnn state.\n agent_buf.bootstrap_value[:] = self.agent.value(o, a, r)\n\n return AgentInputs(o, a, r), self.traj_infos, completed_infos\n\n def evaluate_agent(self, itr):\n \"\"\"Run offline agent evaluation, if applicable.\"\"\"\n raise NotImplementedError\n\n def transfer(self, arg=0.):\n \"\"\"Transfer task in gym training and evaluation environments, if applicable\"\"\"\n self.env.transfer(arg)\n\n def shutdown(self):\n pass\n\n @property\n def batch_size(self):\n return self.batch_spec.size # For logging at least."
] | [
[
"torch.sum",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kifish/ParlAI | [
"93a0f31f3d6b03a97c1a081927427dbe1eb1242e",
"93a0f31f3d6b03a97c1a081927427dbe1eb1242e"
] | [
"parlai/scripts/eval_wordstat.py",
"parlai/core/torch_classifier_agent.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\"\"\"\nThis helper script can be used alone with modelfile and task: the output will contain\nthe word statistics of the model outputs. One can also use the function defined here in\nother places in order to get such statistic for any agent given the agent object (with\ncorr. dict) and a sequence.\n\nAdditionally provides function get_word_stats that can be used in other parts\nof runtime code since it depends only on the agent object. For example:\n\n::\n\n from parlai.scripts.eval_wordstat import get_word_stats\n reqs, cnt = get_word_stats(predictions.tolist(), self.dict)\n\n\nExamples\n--------\n\n.. code-block:: shell\n\n eval_wordstat.py -mf data/model -t convai2:self --freq-bins 10,100,1000\n\"\"\"\n\nfrom parlai.core.params import ParlaiParser\nfrom parlai.core.dict import DictionaryAgent\nfrom parlai.core.agents import create_agent\nfrom parlai.core.worlds import create_task\nfrom parlai.utils.misc import TimeLogger\nfrom parlai.core.metrics import normalize_answer\nfrom parlai.core.logs import TensorboardLogger\nfrom collections import Counter\n\nimport copy\nimport numpy\nimport random\n\n\ndef setup_args(parser=None):\n if parser is None:\n parser = ParlaiParser(True, True, 'compute statistics from model predictions')\n DictionaryAgent.add_cmdline_args(parser)\n # Get command line arguments\n parser.add_argument('-ne', '--num-examples', type=int, default=-1)\n parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2)\n parser.add_argument(\n '-ed',\n '--external-dict',\n type=str,\n default=None,\n help='External dictionary for stat computation',\n )\n parser.add_argument(\n '-fb',\n '--freq-bins',\n type=str,\n default='0,100,1000,10000',\n help='Bins boundaries for rare words stat',\n )\n parser.add_argument(\n '-dup',\n '--dump-predictions-path',\n type=str,\n default=None,\n help='Dump predictions into file',\n )\n parser.add_argument(\n '-cun',\n '--compute-unique',\n type='bool',\n default=True,\n help='Compute %% of unique responses from the model',\n )\n parser.set_defaults(datatype='valid', model='repeat_label')\n TensorboardLogger.add_cmdline_args(parser)\n return parser\n\n\ndef get_word_stats(text, agent_dict, bins=(0, 100, 1000, 100000)):\n \"\"\"\n Function which takes text sequence and dict, returns word freq and length\n statistics.\n\n :param sequence: text sequence\n :param agent_dict: can be external dict or dict from the model\n :param bins: list with range boundaries\n :return: freqs dictionary, num words, avg word length, avg char length\n \"\"\"\n pred_list = agent_dict.tokenize(text)\n pred_freq = [agent_dict.freq[word] for word in pred_list]\n freqs = {i: 0 for i in bins}\n for f in pred_freq:\n for b in bins:\n if f <= b:\n freqs[b] += 1\n break\n\n wlength = len(pred_list)\n clength = len(text) # including spaces\n return freqs, len(pred_freq), wlength, clength\n\n\ndef eval_wordstat(opt, print_parser=None):\n \"\"\"\n Evaluates a model.\n\n :param opt: tells the evaluation function how to run\n :param print_parser: if provided, prints the options that are set within the\n model after loading the model\n \"\"\"\n random.seed(42)\n\n # Create model and assign it to the specified task\n agent = create_agent(opt, requireModelExists=True)\n world = create_task(opt, agent)\n\n if opt.get('external_dict'):\n print('[ Using external dictionary from: {} ]'.format(opt['external_dict']))\n dict_opt = copy.deepcopy(opt)\n dict_opt['dict_file'] = opt['external_dict']\n dictionary = DictionaryAgent(dict_opt)\n else:\n print('[ Using model bundled dictionary ]')\n dictionary = agent.dict\n\n batch_size = opt['batchsize']\n\n if print_parser:\n # Show arguments after loading model\n print_parser.opt = agent.opt\n print_parser.print_args()\n log_every_n_secs = opt.get('log_every_n_secs', -1)\n if log_every_n_secs <= 0:\n log_every_n_secs = float('inf')\n log_time = TimeLogger()\n\n cnt = 0\n word_statistics = {\n 'mean_wlength': [],\n 'mean_clength': [],\n 'freqs_cnt': Counter(),\n 'word_cnt': 0,\n 'pred_list': [],\n 'pure_pred_list': [],\n 'context_list': [],\n 'unique_words': set(),\n }\n bins = [int(i) for i in opt['freq_bins'].split(',')]\n\n def process_prediction(prediction, word_statistics):\n normalized = normalize_answer(prediction)\n word_statistics['pred_list'].append(normalized)\n freqs, _cnt, wlength, clength = get_word_stats(\n prediction, dictionary, bins=bins\n )\n word_statistics['word_cnt'] += _cnt\n word_statistics['mean_wlength'].append(wlength)\n word_statistics['mean_clength'].append(clength)\n word_statistics['freqs_cnt'] += Counter(freqs)\n word_statistics['unique_words'] |= set(normalized.split(\" \"))\n return word_statistics\n\n while not world.epoch_done():\n world.parley()\n if batch_size == 1:\n cnt += 1\n prediction = world.acts[-1]['text']\n word_statistics['context_list'].append(world.acts[0]['text'])\n word_statistics['pure_pred_list'].append(prediction)\n word_statistics = process_prediction(prediction, word_statistics)\n else:\n for w in world.worlds:\n try:\n if 'text' not in w.acts[-1]:\n continue\n prediction = w.acts[-1]['text']\n word_statistics['context_list'].append(w.acts[0]['text'])\n word_statistics['pure_pred_list'].append(prediction)\n except IndexError:\n continue\n cnt += 1\n word_statistics = process_prediction(prediction, word_statistics)\n\n if log_time.time() > log_every_n_secs:\n report = world.report()\n text, report = log_time.log(report['exs'], world.num_examples(), report)\n print(text)\n stat_str = 'total_words: {}, '.format(word_statistics['word_cnt'])\n stat_str += ', '.join(\n [\n '<{}:{} ({:.{prec}f}%)'.format(\n b,\n word_statistics['freqs_cnt'].get(b, 0),\n (\n word_statistics['freqs_cnt'].get(b, 0)\n / word_statistics['word_cnt']\n )\n * 100,\n prec=2,\n )\n for b in bins\n ]\n )\n print(\n \"Word statistics: {}, avg_word_length: {:.{prec}f}, \"\n \"avg_char_length: {:.{prec}f}\".format(\n stat_str,\n numpy.array(word_statistics['mean_wlength']).mean(),\n numpy.array(word_statistics['mean_clength']).mean(),\n prec=2,\n )\n )\n if opt['num_examples'] > 0 and cnt >= opt['num_examples']:\n break\n if world.epoch_done():\n print(\"EPOCH DONE\")\n\n if opt['compute_unique'] is True:\n unique_list = []\n cntr = Counter(word_statistics['pred_list'])\n for k, v in cntr.items():\n if v == 1:\n unique_list.append(k)\n print(\n \"Unique responses: {:.{prec}f}%\".format(\n len(unique_list) / len(word_statistics['pred_list']) * 100, prec=2\n )\n )\n print(\"Total unique tokens:\", len(word_statistics['unique_words']))\n\n if opt['dump_predictions_path'] is not None:\n with open(opt['dump_predictions_path'], 'w') as f:\n f.writelines(\n [\n 'CONTEXT: {}\\nPREDICTION:{}\\n\\n'.format(c, p)\n for c, p in zip(\n word_statistics['context_list'],\n word_statistics['pure_pred_list'],\n )\n ]\n )\n if opt['compute_unique'] is True:\n with open(opt['dump_predictions_path'] + '_unique', 'w') as f:\n f.writelines(['{}\\n'.format(i) for i in unique_list])\n\n stat_str = 'total_words: {}, '.format(word_statistics['word_cnt'])\n stat_str += ', '.join(\n [\n '<{}:{} ({:.{prec}f}%)'.format(\n b,\n word_statistics['freqs_cnt'].get(b, 0),\n (word_statistics['freqs_cnt'].get(b, 0) / word_statistics['word_cnt'])\n * 100,\n prec=2,\n )\n for b in bins\n ]\n )\n print(\n \"Word statistics: {}, avg_word_length: {:.{prec}f}, \"\n \"avg_char_length: {:.{prec}f}\".format(\n stat_str,\n numpy.array(word_statistics['mean_wlength']).mean(),\n numpy.array(word_statistics['mean_clength']).mean(),\n prec=2,\n )\n )\n\n report = world.report()\n print(report)\n return report\n\n\nif __name__ == '__main__':\n parser = setup_args()\n eval_wordstat(parser.parse_args(print_args=False), print_parser=parser)\n",
"#!/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\"\"\"\nTorch Classifier Agents classify text into a fixed set of labels.\n\"\"\"\n\n\nfrom parlai.core.opt import Opt\nfrom parlai.utils.distributed import is_distributed\nfrom parlai.core.torch_agent import TorchAgent, Output\nfrom parlai.utils.misc import round_sigfigs, warn_once\nfrom collections import defaultdict\n\nimport torch\nimport torch.nn.functional as F\n\n\nclass TorchClassifierAgent(TorchAgent):\n \"\"\"\n Abstract Classifier agent. Only meant to be extended.\n\n TorchClassifierAgent aims to handle much of the bookkeeping any classification\n model.\n \"\"\"\n\n @staticmethod\n def add_cmdline_args(parser):\n \"\"\"\n Add CLI args.\n \"\"\"\n TorchAgent.add_cmdline_args(parser)\n parser = parser.add_argument_group('Torch Classifier Arguments')\n # class arguments\n parser.add_argument(\n '--classes',\n type=str,\n nargs='*',\n default=None,\n help='the name of the classes.',\n )\n parser.add_argument(\n '--class-weights',\n type=float,\n nargs='*',\n default=None,\n help='weight of each of the classes for the softmax',\n )\n parser.add_argument(\n '--ref-class',\n type=str,\n default=None,\n hidden=True,\n help='the class that will be used to compute '\n 'precision and recall. By default the first '\n 'class.',\n )\n parser.add_argument(\n '--threshold',\n type=float,\n default=0.5,\n help='during evaluation, threshold for choosing '\n 'ref class; only applies to binary '\n 'classification',\n )\n # interactive mode\n parser.add_argument(\n '--print-scores',\n type='bool',\n default=False,\n help='print probability of chosen class during ' 'interactive mode',\n )\n # miscellaneous arguments\n parser.add_argument(\n '--data-parallel',\n type='bool',\n default=False,\n help='uses nn.DataParallel for multi GPU',\n )\n parser.add_argument(\n '--get-all-metrics',\n type='bool',\n default=True,\n help='give prec/recall metrics for all classes',\n )\n parser.add_argument(\n '--classes-from-file',\n type=str,\n default=None,\n help='loads the list of classes from a file',\n )\n\n def __init__(self, opt: Opt, shared=None):\n init_model, self.is_finetune = self._get_init_model(opt, shared)\n super().__init__(opt, shared)\n\n # set up classes\n if opt.get('classes') is None and opt.get('classes_from_file') is None:\n raise RuntimeError(\n 'Must specify --classes or --classes-from-file argument.'\n )\n if not shared:\n if opt['classes_from_file'] is not None:\n with open(opt['classes_from_file']) as f:\n self.class_list = f.read().splitlines()\n else:\n self.class_list = opt['classes']\n self.class_dict = {val: i for i, val in enumerate(self.class_list)}\n if opt.get('class_weights', None) is not None:\n self.class_weights = opt['class_weights']\n else:\n self.class_weights = [1.0 for c in self.class_list]\n self.reset_metrics()\n else:\n self.class_list = shared['class_list']\n self.class_dict = shared['class_dict']\n self.class_weights = shared['class_weights']\n\n # get reference class; if opt['get_all_metrics'] is False, this is\n # used to compute metrics\n # in binary classfication, opt['threshold'] applies to ref class\n if opt['ref_class'] is None or opt['ref_class'] not in self.class_dict:\n self.ref_class = self.class_list[0]\n else:\n self.ref_class = opt['ref_class']\n ref_class_id = self.class_list.index(self.ref_class)\n if ref_class_id != 0:\n # move to the front of the class list\n self.class_list.insert(0, self.class_list.pop(ref_class_id))\n if not opt['get_all_metrics']:\n warn_once(\n 'Using %s as the class for computing P, R, and F1' % self.ref_class\n )\n\n # set up threshold, only used in binary classification\n if len(self.class_list) == 2 and opt.get('threshold', 0.5) != 0.5:\n self.threshold = opt['threshold']\n else:\n self.threshold = None\n\n # set up model and optimizers\n\n if shared:\n self.model = shared['model']\n else:\n self.model = self.build_model()\n self.criterion = self.build_criterion()\n if self.model is None or self.criterion is None:\n raise AttributeError(\n 'build_model() and build_criterion() need to return the model or criterion'\n )\n if self.use_cuda:\n self.model.cuda()\n self.criterion.cuda()\n if init_model:\n print('Loading existing model parameters from ' + init_model)\n self.load(init_model)\n if self.use_cuda:\n if self.opt['data_parallel']:\n if is_distributed():\n raise ValueError(\n 'Cannot combine --data-parallel and distributed mode'\n )\n self.model = torch.nn.DataParallel(self.model)\n if shared:\n # We don't use get here because hasattr is used on optimizer later.\n if 'optimizer' in shared:\n self.optimizer = shared['optimizer']\n else:\n optim_params = [p for p in self.model.parameters() if p.requires_grad]\n self.init_optim(optim_params)\n self.build_lr_scheduler()\n\n def build_criterion(self):\n weight_tensor = torch.FloatTensor(self.class_weights)\n return torch.nn.CrossEntropyLoss(weight_tensor)\n\n def share(self):\n \"\"\"\n Share model parameters.\n \"\"\"\n shared = super().share()\n shared['class_dict'] = self.class_dict\n shared['class_list'] = self.class_list\n shared['class_weights'] = self.class_weights\n shared['model'] = self.model\n shared['optimizer'] = self.optimizer\n return shared\n\n def _get_labels(self, batch):\n \"\"\"\n Obtain the correct labels.\n\n Raises a ``KeyError`` if one of the labels is not in the class list.\n \"\"\"\n try:\n labels_indices_list = [self.class_dict[label] for label in batch.labels]\n except KeyError as e:\n print('One of your labels is not in the class list.')\n raise e\n labels_tensor = torch.LongTensor(labels_indices_list)\n if self.use_cuda:\n labels_tensor = labels_tensor.cuda()\n return labels_tensor\n\n def _update_confusion_matrix(self, batch, predictions):\n \"\"\"\n Update the confusion matrix given the batch and predictions.\n\n :param batch:\n a Batch object (defined in torch_agent.py)\n :param predictions:\n (list of string of length batchsize) label predicted by the\n classifier\n \"\"\"\n for i, pred in enumerate(predictions):\n label = batch.labels[i]\n self.metrics['confusion_matrix'][(label, pred)] += 1\n\n def _format_interactive_output(self, probs, prediction_id):\n \"\"\"\n Format interactive mode output with scores.\n \"\"\"\n preds = []\n for i, pred_id in enumerate(prediction_id.tolist()):\n prob = round_sigfigs(probs[i][pred_id], 4)\n preds.append(\n 'Predicted class: {}\\nwith probability: {}'.format(\n self.class_list[pred_id], prob\n )\n )\n return preds\n\n def train_step(self, batch):\n \"\"\"\n Train on a single batch of examples.\n \"\"\"\n if batch.text_vec is None:\n return Output()\n self.model.train()\n self.optimizer.zero_grad()\n\n # calculate loss\n labels = self._get_labels(batch)\n scores = self.score(batch)\n loss = self.criterion(scores, labels)\n loss.backward()\n self.update_params()\n\n # update metrics\n self.metrics['loss'] += loss.item()\n self.metrics['examples'] += len(batch.text_vec)\n\n # get predictions\n _, prediction_id = torch.max(scores.cpu(), 1)\n preds = [self.class_list[idx] for idx in prediction_id]\n self._update_confusion_matrix(batch, preds)\n\n return Output(preds)\n\n def eval_step(self, batch):\n \"\"\"\n Train on a single batch of examples.\n \"\"\"\n if batch.text_vec is None:\n return\n\n self.model.eval()\n scores = self.score(batch)\n probs = F.softmax(scores, dim=1)\n if self.threshold is None:\n _, prediction_id = torch.max(probs.cpu(), 1)\n else:\n ref_prob = probs.cpu()[:, 0]\n # choose ref class if Prob(ref class) > threshold\n prediction_id = ref_prob <= self.threshold\n preds = [self.class_list[idx] for idx in prediction_id]\n\n if batch.labels is None:\n # interactive mode\n if self.opt.get('print_scores', False):\n preds = self._format_interactive_output(probs, prediction_id)\n else:\n labels = self._get_labels(batch)\n loss = self.criterion(scores, labels)\n self.metrics['loss'] += loss.item()\n self.metrics['examples'] += len(batch.text_vec)\n self._update_confusion_matrix(batch, preds)\n\n return Output(preds)\n\n def reset_metrics(self):\n \"\"\"\n Reset metrics.\n \"\"\"\n super().reset_metrics()\n self.metrics['confusion_matrix'] = defaultdict(int)\n self.metrics['examples'] = 0\n self.metrics['loss'] = 0.0\n\n def _report_prec_recall_metrics(self, confmat, class_name, metrics):\n \"\"\"\n Use the confusion matrix to compute precision and recall.\n\n :param confmat:\n the confusion matrics\n :param str class_name:\n the class name to compute P/R for\n :param metrics:\n metrics dictionary to modify\n :return:\n the number of examples of each class.\n \"\"\"\n # TODO: document these parameter types.\n eps = 0.00001 # prevent divide by zero errors\n true_positives = confmat[(class_name, class_name)]\n num_actual_positives = (\n sum([confmat[(class_name, c)] for c in self.class_list]) + eps\n )\n num_predicted_positives = (\n sum([confmat[(c, class_name)] for c in self.class_list]) + eps\n )\n\n recall_str = 'class_{}_recall'.format(class_name)\n prec_str = 'class_{}_prec'.format(class_name)\n f1_str = 'class_{}_f1'.format(class_name)\n\n # update metrics dict\n metrics[recall_str] = true_positives / num_actual_positives\n metrics[prec_str] = true_positives / num_predicted_positives\n metrics[f1_str] = 2 * (\n (metrics[recall_str] * metrics[prec_str])\n / (metrics[recall_str] + metrics[prec_str] + eps)\n )\n\n return num_actual_positives\n\n def report(self):\n \"\"\"\n Report loss as well as precision, recall, and F1 metrics.\n \"\"\"\n m = super().report()\n examples = self.metrics['examples']\n if examples > 0:\n m['examples'] = examples\n m['mean_loss'] = self.metrics['loss'] / examples\n\n # get prec/recall metrics\n confmat = self.metrics['confusion_matrix']\n if self.opt.get('get_all_metrics'):\n metrics_list = self.class_list\n else:\n # only give prec/recall metrics for ref class\n metrics_list = [self.ref_class]\n\n examples_per_class = []\n for class_i in metrics_list:\n class_total = self._report_prec_recall_metrics(confmat, class_i, m)\n examples_per_class.append(class_total)\n\n if len(examples_per_class) > 1:\n # get weighted f1\n f1 = 0\n total_exs = sum(examples_per_class)\n for i in range(len(self.class_list)):\n f1 += (examples_per_class[i] / total_exs) * m[\n 'class_{}_f1'.format(self.class_list[i])\n ]\n m['weighted_f1'] = f1\n\n for k, v in m.items():\n m[k] = round_sigfigs(v, 4)\n\n return m\n\n def score(self, batch):\n \"\"\"\n Given a batch and labels, returns the scores.\n\n :param batch:\n a Batch object (defined in torch_agent.py)\n :return:\n a [bsz, num_classes] FloatTensor containing the score of each\n class.\n \"\"\"\n raise NotImplementedError('Abstract class: user must implement score()')\n"
] | [
[
"numpy.array"
],
[
"torch.LongTensor",
"torch.nn.CrossEntropyLoss",
"torch.nn.functional.softmax",
"torch.FloatTensor",
"torch.nn.DataParallel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fabiobaccarin/allstate-loss | [
"4c0fea6ea28847fc67b9e742dc3ac30e1ac4d10a"
] | [
"scripts/08_ranking_raw.py"
] | [
"\"\"\"\nRanking of features with minimum preprocessing (raw features)\n\"\"\"\n\nimport json\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns; sns.set(style='whitegrid')\nfrom matplotlib import pyplot as plt\nfrom sklearn.preprocessing import (\n power_transform, quantile_transform, scale, StandardScaler, FunctionTransformer\n)\nfrom sklearn.pipeline import make_pipeline\nfrom pandas_profiling import ProfileReport\nfrom pathlib import Path\n\np = Path(__file__).parents[1]\n\n# To load project modules\nimport sys; sys.path.append(str(p))\nfrom src.logger import LOGGER\nfrom src import estimators as e\nfrom src.ranker import Ranker\n\n\nA4_DIMS = (11.7, 8.27)\n\nLOGGER.info('Load data')\ndf = pd.read_pickle(p.joinpath('data', 'interim', 'research.pkl'))\nX = df.drop(labels='loss', axis=1)\ny = df['loss'].copy()\n\nLOGGER.info('Process target')\ny = pd.Series(data=power_transform(y.values.reshape(-1, 1)).flatten(), name='loss', index=y.index)\n\nLOGGER.info('Load categorical features to drop')\nnoVarFeatures = json.load(open(file=p.joinpath('src', 'meta', 'NoVariance.json'), mode='r'))\n\nLOGGER.info('Process categorical features')\ncatf = pd.DataFrame(\n data=make_pipeline(\n e.CategoricalGrouper(),\n e.CategoricalEncoder()\n ).fit_transform(X.filter(like='cat').drop(labels=noVarFeatures, axis=1), y),\n columns=X.filter(like='cat').drop(labels=noVarFeatures, axis=1).columns,\n index=X.index\n)\n\nLOGGER.info('Process continuous features')\ncontf = pd.DataFrame(\n data=scale(quantile_transform(\n X=X.filter(like='cont'),\n output_distribution='normal',\n random_state=0\n )),\n columns=X.filter(like='cont').columns,\n index=X.index\n)\n\nLOGGER.info('Make raw X and profile')\nX = catf.join(contf)\ndel catf, contf\nProfileReport(\n df=X.join(y),\n minimal=True,\n title='Data with minimum preprocessing',\n progress_bar=False\n).to_file(p.joinpath('reports', 'profiles', 'raw.html'))\n\nLOGGER.info('Create ranking')\nranking = Ranker().rank(X, y)\n\nLOGGER.info('Figure 4: Volcano plot for features')\nfig, ax = plt.subplots(figsize=A4_DIMS)\nax = sns.scatterplot(\n x=ranking['Statistical Significance'],\n y=ranking['Association Strength'],\n s=100,\n)\nax.set(\n title='Figure 4: Volcano plot for features',\n xlabel='Statistical Significance (-log10(p-value))',\n ylabel='Association Strength (%)'\n)\nax.axvline(x=0, color='black', lw=2)\nax.axhline(y=0, color='black', lw=2)\nplt.tight_layout()\nfig.savefig(\n fname=p.joinpath('reports', 'figures', '04FeatureRanking.png'),\n dpi=800,\n format='png'\n)\nplt.close(fig)\n\nLOGGER.info('Table 5: feature ranking')\nranking['Rank'] = ranking['Association Strength'].abs().rank(ascending=False)\nranking['Group'] = np.ceil(ranking['Rank'].div(5))\nranking.sort_values('Rank').to_html(\n buf=p.joinpath('reports', 'tables', '05FeatureRanking.html'),\n float_format='{:.2f}'.format,\n bold_rows=False\n)"
] | [
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.close"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shashankboosi/Machine-Vision | [
"c37ef9b4c7a309529d0e660fed3eb627fc42804e"
] | [
"src/deep_learning.py"
] | [
"import torch\nimport pandas as pd\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt\n\n# Load data\ndata = pd.read_csv(\"../data/mnist_train.csv\")\ntrain_data = data[:2000]\ntest_data = data[2000:2500]\n\n# ----- Prepare Data ----- #\n# Preparing your data including data normalization\ntrain_X = train_data.iloc[:, 1:]\ntrain_Y = train_data[\"label\"]\ntest_X = test_data.iloc[:, 1:]\ntest_Y = test_data[\"label\"]\n\nmin_max_scaler = preprocessing.MinMaxScaler()\ntrain_X_data_norm = min_max_scaler.fit_transform(train_X)\ntest_X_data_norm = min_max_scaler.fit_transform(test_X)\n\n# Transform np array to pytorch tensor\ntrain_X_tensor = torch.tensor(train_X_data_norm, dtype=torch.float32).reshape(-1, 1, 28, 28)\ntest_X_tensor = torch.tensor(test_X_data_norm, dtype=torch.float32).reshape(-1, 1, 28, 28)\ntrain_Y_tensor = torch.tensor(train_Y)\ntest_Y_tensor = torch.tensor(test_Y.to_numpy())\n\n\n# ----- Build CNN Network ----- #\n# Define your model here\nclass mymodel(torch.nn.Module):\n def __init__(self):\n super(mymodel, self).__init__()\n self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)\n self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)\n self.conv2_drop = torch.nn.Dropout2d()\n self.fc1 = torch.nn.Linear(320, 50)\n self.fc2 = torch.nn.Linear(50, 10)\n\n def forward(self, x):\n x = torch.nn.functional.relu(torch.nn.functional.max_pool2d(self.conv1(x), 2))\n x = torch.nn.functional.relu(torch.nn.functional.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, 320)\n x = torch.nn.functional.relu(self.fc1(x))\n x = torch.nn.functional.dropout(x, training=self.training)\n x = self.fc2(x)\n return torch.nn.functional.log_softmax(x, dim=1)\n\n\n# Define our model\nmodel = mymodel()\nlearning_rate = 0.01\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\ncriterion = torch.nn.NLLLoss()\n\n\n# ----- Complete PlotLearningCurve function ----- #\ndef PlotLearningCurve(epoch, trainingloss, testingloss):\n plt.plot(epoch, trainingloss, color='blue')\n plt.plot(epoch, testingloss, color='red')\n plt.legend(['Train Loss', 'Test Loss'], loc='upper right')\n plt.title('Learning Curve')\n plt.xlabel('Epoch')\n plt.ylabel('Loss')\n plt.savefig('../OutputImages/Deep_Learning/lossvsepochs.png')\n plt.show()\n\n\n# ----- Main Function ----- #\ntrainingloss = []\ntestingloss = []\n# Define number of iterations\nepochs = 100\nfor epoch in range(1, epochs + 1):\n model.train()\n output = model(train_X_tensor)\n loss = criterion(output, train_Y_tensor)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n trainingloss += loss.item(),\n # Evaluation your model by using testing data and get the accuracy\n correct = 0\n with torch.no_grad():\n total = 0\n model.eval()\n output_test = model(test_X_tensor)\n loss = criterion(output_test, test_Y_tensor)\n testingloss += loss.item(),\n if epoch % 10 == 0:\n _, predicted = torch.max(output_test, 1)\n total += test_Y_tensor.size(0)\n correct += (predicted == test_Y_tensor).sum().item()\n acc = 100 * correct / total\n print('Epoch:', epoch, 'Test Accuracy:', acc)\n\nPlotLearningCurve(range(len(trainingloss)), trainingloss, testingloss)\n"
] | [
[
"matplotlib.pyplot.legend",
"torch.nn.NLLLoss",
"pandas.read_csv",
"torch.nn.Dropout2d",
"torch.max",
"matplotlib.pyplot.title",
"torch.nn.functional.dropout",
"torch.nn.functional.log_softmax",
"torch.nn.Conv2d",
"matplotlib.pyplot.savefig",
"torch.tensor",
"matplotlib.pyplot.plot",
"torch.nn.Linear",
"torch.no_grad",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"sklearn.preprocessing.MinMaxScaler",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
gdikov/MNIST_Challenge | [
"56834aeeaeefc440cb1d9882c95b73b84fe20edf"
] | [
"models/logreg/logreg.py"
] | [
"import numpy as np\nimport os\n\nfrom models.model import AbstractModel\nfrom numerics.solver import Adam\nfrom numerics.softmax import softmax_loss, softmax\n\nclass LogisticRegression(AbstractModel):\n\n def __init__(self, batch_size=10000, add_bias=False):\n super(LogisticRegression, self).__init__('LogisticRegression')\n self.data = None\n self.batch_size = batch_size\n self.add_bias = add_bias\n self.num_classes = 10\n solver_config = {'learning_rate': 0.13, 'beta1': 0.9, 'beta2': 0.999, 'epsilon': 1e-8, 't': 0}\n if add_bias:\n solver_config['mov_avg_grad'] = np.zeros(28*28+1)\n solver_config['mov_avg_sq_grad'] = np.zeros(28*28+1)\n else:\n solver_config['mov_avg_grad'] = np.zeros(28*28)\n solver_config['mov_avg_sq_grad'] = np.zeros(28*28)\n self.solver = Adam(config=solver_config)\n self._init_params()\n\n\n def _init_params(self):\n if self.add_bias:\n self.W = 0.01 * np.random.randn(self.num_classes, 28*28)\n self.W = np.hstack((self.W, np.zeros((self.num_classes, 1))))\n else:\n self.W = 0.01 * np.random.randn(self.num_classes, 28 * 28)\n\n\n def save_trainable_params(self):\n path_to_params = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'optimal_W.npy')\n np.save(path_to_params, self.W)\n\n\n def load_trainable_params(self):\n path_to_params = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'optimal_W.npy')\n if not os.path.exists(path_to_params):\n print(\"\\tPath to parameters not found at: {}\".format(path_to_params))\n raise IOError\n self.W = np.load(path_to_params)\n\n\n def fit(self, train_data, **kwargs):\n\n self.data = train_data\n # reshape the images into row vectors of 28*28 elements\n num_samples, dim_x, dim_y = self.data['x_train'].shape\n self.data['x_train'] = self.data['x_train'].reshape(num_samples, dim_x * dim_y)\n if self.add_bias:\n self.data['x_train'] = np.hstack((self.data['x_train'], np.ones((num_samples, 1))))\n # one_hot_labels = OneHot(10).generate_labels(self.data['y_train'])\n\n num_epochs = kwargs.get('num_epochs', 100)\n regularisation = kwargs.get('reg', 0.0)\n reinit = kwargs.get('reinit', True)\n verbose = kwargs.get('verbose', False)\n save_best = kwargs.get('save_best', False)\n if reinit:\n self._init_params()\n\n lowest_loss = np.inf\n for i in xrange(num_epochs):\n losses = []\n for idx in self._batch_idx():\n # scores = np.dot(self.W, self.data['x_train'][idx])\n loss, dW = softmax_loss(self.W,\n self.data['x_train'][idx],\n self.data['y_train'][idx],\n reg=regularisation)\n self.solver.update(self.W, dW)\n losses.append(loss)\n mean_loss = np.mean(losses)\n if verbose:\n print(\"\\t\\tEpoch: {0}, loss: {1}\".format(i, mean_loss))\n if save_best:\n if mean_loss < lowest_loss:\n lowest_loss = mean_loss\n self.save_trainable_params()\n\n\n def _batch_idx(self):\n # maybe this is unneceserray because they are already shuffled\n # but it doesn't harm much to do it again\n num_training = self.data['x_train'].shape[0]\n shuffled_order = np.random.permutation(np.arange(num_training))\n for x in np.array_split(shuffled_order, num_training // self.batch_size):\n yield x\n\n\n def predict(self, new_data, **kwargs):\n # make sure the new_data is shaped like the train data\n if new_data.shape[1] != 28 * 28 + 1 and new_data.shape[1] != 28 * 28:\n new_data = new_data.reshape(new_data.shape[0], 28*28)\n if self.add_bias and new_data.shape[1] != 28*28 + 1:\n new_data = np.hstack((new_data, np.ones((new_data.shape[0], 1))))\n\n scores = np.dot(new_data, self.W.T)\n probs = softmax(scores) # this is unnecessary as the softmax function will not change the order\n return np.argmax(probs, axis=1)\n\n\nif __name__ == \"__main__\":\n from utils.data_utils import load_MNIST\n data_train, data_test = load_MNIST(num_training=50000, num_validation=10000)\n\n model = LogisticRegression(batch_size=50000, add_bias=True)\n\n model.fit(data_train, num_epochs=300, verbose=True)\n\n predictions = model.predict(data_train['x_val'])\n\n test_acc = np.sum(predictions == data_train['y_val']) / float(predictions.shape[0]) * 100.\n print(\"Validation accuracy: {0}\"\n .format(test_acc))\n"
] | [
[
"numpy.dot",
"numpy.arange",
"numpy.save",
"numpy.ones",
"numpy.argmax",
"numpy.mean",
"numpy.random.randn",
"numpy.load",
"numpy.array_split",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
realiti4/td-gammon | [
"5d6ded0536398a6331b0ab2fc63c85aaef755476"
] | [
"td_gammon/utils.py"
] | [
"import os\nimport gym\nimport sys\nfrom agents import TDAgent, HumanAgent, TDAgentGNU, RandomAgent, evaluate_agents, Agent_2ply\nfrom gnubg.gnubg_backgammon import GnubgInterface, GnubgEnv, evaluate_vs_gnubg\nfrom gym_backgammon.envs.backgammon import WHITE, BLACK\nfrom model import TDGammon, TDGammon_stock, TDGammonCNN\nfrom web_gui.gui import GUI\nfrom torch.utils.tensorboard import SummaryWriter\n\n# tensorboard --logdir=runs/ --host localhost --port 8001\n\n\ndef write_file(path, **kwargs):\n with open('{}/parameters.txt'.format(path), 'w+') as file:\n print(\"Parameters:\")\n for key, value in kwargs.items():\n file.write(\"{}={}\\n\".format(key, value))\n print(\"{}={}\".format(key, value))\n print()\n\n\ndef path_exists(path):\n if os.path.exists(path):\n return True\n else:\n print(\"The path {} doesn't exists\".format(path))\n sys.exit()\n\n\n\n# ==================================== TRAINING PARAMETERS ===================================\ndef args_train(args):\n save_step = args.save_step\n save_path = None\n n_episodes = args.episodes\n init_weights = args.init_weights\n lr = args.lr\n hidden_units = args.hidden_units\n lamda = args.lamda\n name = args.name\n model_type = args.type\n seed = args.seed\n\n eligibility = False\n optimizer = None\n\n if model_type == 'nn':\n net = TDGammon(hidden_units=hidden_units, lr=lr, lamda=lamda, init_weights=init_weights, seed=seed)\n eligibility = True\n env = gym.make('gym_backgammon:backgammon-v0')\n\n else:\n net = TDGammonCNN(lr=lr, seed=seed)\n optimizer = True\n env = gym.make('gym_backgammon:backgammon-pixel-v0')\n\n if args.model and path_exists(args.model):\n # assert os.path.exists(args.model), print(\"The path {} doesn't exists\".format(args.model))\n net.load(checkpoint_path=args.model, optimizer=optimizer, eligibility_traces=eligibility)\n\n if args.save_path and path_exists(args.save_path):\n # assert os.path.exists(args.save_path), print(\"The path {} doesn't exists\".format(args.save_path))\n save_path = args.save_path\n\n write_file(\n save_path, save_path=args.save_path, command_line_args=args, type=model_type, hidden_units=hidden_units, init_weights=init_weights, alpha=net.lr, lamda=net.lamda,\n n_episodes=n_episodes, save_step=save_step, start_episode=net.start_episode, name_experiment=name, env=env.spec.id, restored_model=args.model, seed=seed,\n eligibility=eligibility, optimizer=optimizer, modules=[module for module in net.modules()]\n )\n\n net.train_agent(env=env, n_episodes=n_episodes, save_path=save_path, save_step=save_step, eligibility=eligibility, name_experiment=name)\n\n\n# ==================================== WEB GUI PARAMETERS ====================================\ndef args_gui(args):\n if path_exists(args.model):\n # assert os.path.exists(args.model), print(\"The path {} doesn't exists\".format(args.model))\n\n if args.type == 'nn':\n net = TDGammon(hidden_units=args.hidden_units, lr=0.1, lamda=None, init_weights=False)\n env = gym.make('gym_backgammon:backgammon-v0')\n else:\n net = TDGammonCNN(lr=0.0001)\n env = gym.make('gym_backgammon:backgammon-pixel-v0')\n\n net.load(checkpoint_path=args.model, optimizer=None, eligibility_traces=False)\n\n agents = {BLACK: TDAgent(BLACK, net=net), WHITE: HumanAgent(WHITE)}\n # agents = {BLACK: Agent_2ply(BLACK, net=net), WHITE: HumanAgent(WHITE)}\n gui = GUI(env=env, host=args.host, port=args.port, agents=agents)\n gui.run()\n\n\n# =================================== EVALUATE PARAMETERS ====================================\ndef args_evaluate(args):\n model_agent0 = args.model_agent0\n model_agent1 = args.model_agent1\n model_type = args.type\n hidden_units_agent0 = args.hidden_units_agent0\n hidden_units_agent1 = args.hidden_units_agent1\n n_episodes = args.episodes\n\n if path_exists(model_agent0) and path_exists(model_agent1):\n # assert os.path.exists(model_agent0), print(\"The path {} doesn't exists\".format(model_agent0))\n # assert os.path.exists(model_agent1), print(\"The path {} doesn't exists\".format(model_agent1))\n\n if model_type == 'nn':\n net0 = TDGammon(hidden_units=hidden_units_agent0, lr=0.1, lamda=None, init_weights=False)\n net1 = TDGammon_stock(hidden_units=hidden_units_agent1, lr=0.1, lamda=None, init_weights=False)\n # net1 = TDGammon(hidden_units=hidden_units_agent0, lr=0.1, lamda=None, init_weights=False)\n env = gym.make('gym_backgammon:backgammon-v0')\n else:\n net0 = TDGammonCNN(lr=0.0001)\n net1 = TDGammonCNN(lr=0.0001)\n env = gym.make('gym_backgammon:backgammon-pixel-v0')\n\n net0.load(checkpoint_path=model_agent0, optimizer=None, eligibility_traces=False)\n net1.load(checkpoint_path=model_agent1, optimizer=None, eligibility_traces=False)\n\n agents = {WHITE: TDAgent(WHITE, net=net1), BLACK: TDAgent(BLACK, net=net0)}\n # agents = {WHITE: TDAgent(WHITE, net=net1), BLACK: Agent_2ply(BLACK, net=net0)}\n\n evaluate_agents(agents, env, n_episodes)\n\n\n# ===================================== GNUBG PARAMETERS =====================================\ndef args_gnubg(args):\n model_agent0 = args.model_agent0\n model_type = args.type\n hidden_units_agent0 = args.hidden_units_agent0\n n_episodes = args.episodes\n host = args.host\n port = args.port\n difficulty = args.difficulty\n\n if path_exists(model_agent0):\n # assert os.path.exists(model_agent0), print(\"The path {} doesn't exists\".format(model_agent0))\n if model_type == 'nn':\n net0 = TDGammon(hidden_units=hidden_units_agent0, lr=0.1, lamda=None, init_weights=False)\n else:\n net0 = TDGammonCNN(lr=0.0001)\n\n net0.load(checkpoint_path=model_agent0, optimizer=None, eligibility_traces=False)\n\n gnubg_interface = GnubgInterface(host=host, port=port)\n gnubg_env = GnubgEnv(gnubg_interface, difficulty=difficulty, model_type=model_type)\n evaluate_vs_gnubg(agent=TDAgentGNU(WHITE, net=net0, gnubg_interface=gnubg_interface), env=gnubg_env, n_episodes=n_episodes)\n\n\n# ===================================== PLOT PARAMETERS ======================================\ndef args_plot(args, parser):\n '''\n This method is used to plot the number of time an agent wins when it plays against an opponent.\n Instead of evaluating the agent during training (it can require some time and slow down the training), I decided to plot the wins separately, loading the different\n model saved during training.\n For example, suppose I run the training for 100 games and save my model every 10 games.\n Later I will load these 10 models, and for each of them, I will compute how many times the agent would win against an opponent.\n :return: None\n '''\n\n src = args.save_path\n hidden_units = args.hidden_units\n n_episodes = args.episodes\n opponents = args.opponent.split(',')\n host = args.host\n port = args.port\n difficulties = args.difficulty.split(',')\n model_type = args.type\n\n if path_exists(src):\n # assert os.path.exists(src), print(\"The path {} doesn't exists\".format(src))\n\n for d in difficulties:\n if d not in ['beginner', 'intermediate', 'advanced', 'world_class']:\n parser.error(\"--difficulty should be (one or more of) 'beginner','intermediate', 'advanced' ,'world_class'\")\n\n dst = args.dst\n\n if 'gnubg' in opponents and (not host or not port):\n parser.error(\"--host and --port are required when 'gnubg' is specified in --opponent\")\n\n for root, dirs, files in os.walk(src):\n global_step = 0\n files = sorted(files)\n\n writer = SummaryWriter(dst)\n\n for file in files:\n if \".tar\" in file:\n print(\"\\nLoad {}\".format(os.path.join(root, file)))\n\n if model_type == 'nn':\n net = TDGammon(hidden_units=hidden_units, lr=0.1, lamda=None, init_weights=False)\n env = gym.make('gym_backgammon:backgammon-v0')\n else:\n net = TDGammonCNN(lr=0.0001)\n env = gym.make('gym_backgammon:backgammon-pixel-v0')\n\n net.load(checkpoint_path=os.path.join(root, file), optimizer=None, eligibility_traces=False)\n\n if 'gnubg' in opponents:\n tag_scalar_dict = {}\n\n gnubg_interface = GnubgInterface(host=host, port=port)\n\n for difficulty in difficulties:\n gnubg_env = GnubgEnv(gnubg_interface, difficulty=difficulty, model_type=model_type)\n wins = evaluate_vs_gnubg(agent=TDAgentGNU(WHITE, net=net, gnubg_interface=gnubg_interface), env=gnubg_env, n_episodes=n_episodes)\n tag_scalar_dict[difficulty] = wins[WHITE]\n\n writer.add_scalars('wins_vs_gnubg/', tag_scalar_dict, global_step)\n\n with open(root + '/results.txt', 'a') as f:\n print(\"{};\".format(file) + str(tag_scalar_dict), file=f)\n\n if 'random' in opponents:\n tag_scalar_dict = {}\n agents = {WHITE: TDAgent(WHITE, net=net), BLACK: RandomAgent(BLACK)}\n wins = evaluate_agents(agents, env, n_episodes)\n\n tag_scalar_dict['random'] = wins[WHITE]\n\n writer.add_scalars('wins_vs_random/', tag_scalar_dict, global_step)\n\n global_step += 1\n\n writer.close()\n"
] | [
[
"torch.utils.tensorboard.SummaryWriter"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
BlooAM/Day-ahead-prices | [
"e5c51682de4bb2b093fd6412b2131012e7e836ca"
] | [
"src/data_generator/extractors/pscmi_coal_index.py"
] | [
"from datetime import datetime, time\n\nimport pandas as pd\n\nfrom src.data_generator.extractors.base_extractor import BaseExtractor\n\n\nclass PscmiCoalIndexExtractor(BaseExtractor):\n _DATA_PATH = 'resources/PSCMI_1.csv'\n\n def extract(self, date: datetime) -> pd.DataFrame:\n date_truncated_to_month = datetime.combine(date, time()).replace(day=1)\n pscmi = pd.read_csv(self._DATA_PATH, parse_dates=['date'])\n pscmi_truncated_to_month = pscmi[pscmi['date'] == date_truncated_to_month]\n if pscmi_truncated_to_month.empty:\n pscmi_truncated_to_month = pscmi[pscmi['date'] == pscmi['date'].max()]\n pscmi_truncated_to_month['date'] = date\n pscmi_truncated_to_month.reset_index(drop=True, inplace=True)\n return pscmi_truncated_to_month\n"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
zhulf0804/ROPNet | [
"aa12c96f186dadd9a6c5be4524db35fea77cb28c"
] | [
"src/models/CG.py"
] | [
"import numpy as np\nimport open3d as o3d\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport sys\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nROOR_DIR = os.path.dirname(BASE_DIR)\nsys.path.append(ROOR_DIR)\nfrom utils import batch_quat2mat\n\n\nclass PointNet(nn.Module):\n def __init__(self, in_dim, gn, out_dims, cls=False):\n super(PointNet, self).__init__()\n self.cls = cls\n l = len(out_dims)\n self.backbone = nn.Sequential()\n for i, out_dim in enumerate(out_dims):\n self.backbone.add_module(f'pointnet_conv_{i}',\n nn.Conv1d(in_dim, out_dim, 1, 1, 0))\n if gn:\n self.backbone.add_module(f'pointnet_gn_{i}',\n nn.GroupNorm(8, out_dim))\n if self.cls and i != l - 1:\n self.backbone.add_module(f'pointnet_relu_{i}',\n nn.ReLU(inplace=True))\n in_dim = out_dim\n\n def forward(self, x, pooling=True):\n f = self.backbone(x)\n if not pooling:\n return f\n g, _ = torch.max(f, dim=2)\n return f, g\n\n\nclass MLPs(nn.Module):\n def __init__(self, in_dim, mlps):\n super(MLPs, self).__init__()\n self.mlps = nn.Sequential()\n l = len(mlps)\n for i, out_dim in enumerate(mlps):\n self.mlps.add_module(f'fc_{i}', nn.Linear(in_dim, out_dim))\n if i != l - 1:\n self.mlps.add_module(f'relu_{i}', nn.ReLU(inplace=True))\n in_dim = out_dim\n\n def forward(self, x):\n x = self.mlps(x)\n return x\n\n\nclass CGModule(nn.Module):\n def __init__(self, in_dim, gn):\n super(CGModule, self).__init__()\n self.encoder = PointNet(in_dim=in_dim,\n gn=gn,\n out_dims=[64, 64, 64, 128, 512])\n self.decoder_ol = PointNet(in_dim=2048,\n gn=gn,\n out_dims=[512, 512, 256, 2],\n cls=True)\n self.decoder_qt = MLPs(in_dim=1024,\n mlps=[512, 512, 256, 7])\n\n def forward(self, src, tgt):\n '''\n Context-Guided Model for initial alignment and overlap score.\n :param src: (B, N, 3)\n :param tgt: (B, M, 3)\n :return: T0: (B, 3, 4), OX: (B, N, 2), OY: (B, M, 2)\n '''\n x = src.permute(0, 2, 1).contiguous()\n y = tgt.permute(0, 2, 1).contiguous()\n f_x, g_x = self.encoder(x)\n f_y, g_y = self.encoder(y)\n concat = torch.cat((g_x, g_y), dim=1)\n\n # regression initial alignment\n out = self.decoder_qt(concat)\n batch_t, batch_quat = out[:, :3], out[:, 3:] / (\n torch.norm(out[:, 3:], dim=1, keepdim=True) + 1e-8)\n batch_R = batch_quat2mat(batch_quat)\n batch_T = torch.cat([batch_R, batch_t[..., None]], dim=-1)\n\n # overlap prediction\n g_x_expand = torch.unsqueeze(g_x, dim=-1).expand_as(f_x)\n g_y_expand = torch.unsqueeze(g_y, dim=-1).expand_as(f_y)\n f_x_ensemble = torch.cat([f_x, g_x_expand, g_y_expand,\n g_x_expand - g_y_expand], dim=1)\n f_y_ensemble = torch.cat([f_y, g_y_expand, g_x_expand,\n g_y_expand - g_x_expand], dim=1)\n x_ol = self.decoder_ol(f_x_ensemble, pooling=False)\n y_ol = self.decoder_ol(f_y_ensemble, pooling=False)\n\n return batch_T, x_ol, y_ol\n"
] | [
[
"torch.nn.Sequential",
"torch.norm",
"torch.max",
"torch.cat",
"torch.unsqueeze",
"torch.nn.Linear",
"torch.nn.Conv1d",
"torch.nn.GroupNorm",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jacobmas/bezpy | [
"759618d5518a08e456fab748e5d9cf4881a04525"
] | [
"bezpy/mt/io.py"
] | [
"\"\"\"Input/output functions for IRIS magnetotelluric data.\"\"\"\n\n__all__ = [\"read_xml\", \"read_xml_lower\", \"read_1d_usgs_profile\", \"get_1d_site\"]\n\nimport glob\nimport datetime\nimport xml.etree.ElementTree as ET\nimport numpy as np\nimport pandas as pd\nimport pkg_resources\n\nfrom .site import Site1d, Site3d\nfrom .datalogger import DataLogger\n\nDATA_PATH_1D = pkg_resources.resource_filename('bezpy', 'mt/data_1d') + \"/\"\n\n\n####################\n# Helper functions\n####################\ndef convert_float(s):\n \"\"\"Converts values, handling bad strings.\"\"\"\n try:\n return float(s)\n except (ValueError, TypeError):\n return None\n\n\ndef convert_int(s):\n \"\"\"Converts values, handling bad strings.\"\"\"\n try:\n return int(s)\n except (ValueError, TypeError):\n return None\n\n\ndef convert_datetime(s):\n \"\"\"Converts values, handling bad strings.\"\"\"\n try:\n return datetime.datetime.strptime(s, \"%Y-%m-%dT%H:%M:%S\")\n except (ValueError, TypeError):\n return None\n\n\ndef get_text(base, name):\n \"\"\"Gets the text from an xml element.\"\"\"\n try:\n return base.find(name).text\n except AttributeError:\n return None\n\n\ndef parse_data(xml_data):\n \"\"\"Parse data obtained from Anna's xml files.\"\"\"\n # For storing periods in a dictionary\n periods = {}\n # Iterate through the periods\n for period in xml_data:\n period_length = float(period.attrib['value'])\n periods[period_length] = {}\n df_dict = periods[period_length]\n\n for item in period:\n for data in item:\n column_name = item.tag + \"_\"\n if 'name' in data.attrib:\n column_name += data.attrib['name']\n else:\n column_name += data.attrib['output'] + \"_\" + data.attrib['input']\n\n if item.attrib['type'] == 'complex':\n text = data.text.split()\n column_value = float(text[0]) + float(text[1])*1j\n elif item.attrib['type'] == 'real':\n column_value = float(data.text)\n else:\n raise ValueError(\"Error parsing the item type:\",\n item.attrib['type'],\n \"\\nShould be either \\\"real\\\" or \\\"complex\\\"\")\n\n column_name = ''.join(i for i in column_name if not i.isdigit())\n df_dict[column_name.lower()] = column_value\n\n # Create a DataFrame for the data that was stored in the dictionary\n df = pd.DataFrame.from_dict(periods, orient='index')\n df.index.name = \"period\"\n\n return df\n\n\ndef read_xml(fname):\n \"\"\"Read in an IRIS xml file and return a Site3d object\"\"\"\n root = ET.parse(fname).getroot()\n\n xml_site = root.find(\"Site\")\n name = get_text(xml_site, \"Id\")\n # Creating the object\n site = Site3d(name)\n # Store the parsed root xml element\n site.xml = root\n site.product_id = get_text(root, \"ProductId\")\n\n loc = xml_site.find(\"Location\")\n site.latitude = convert_float(get_text(loc, \"Latitude\"))\n site.longitude = convert_float(get_text(loc, \"Longitude\"))\n site.elevation = convert_float(get_text(loc, \"Elevation\"))\n site.declination = convert_float(get_text(loc, \"Declination\"))\n\n site.start_time = convert_datetime(get_text(xml_site, \"Start\"))\n site.end_time = convert_datetime(get_text(xml_site, \"End\"))\n\n quality = xml_site.find(\"DataQualityNotes\")\n site.rating = convert_int(get_text(quality, \"Rating\"))\n site.min_period = convert_float(get_text(quality, \"GoodFromPeriod\"))\n site.max_period = convert_float(get_text(quality, \"GoodToPeriod\"))\n\n site.quality_flag = convert_int(get_text(xml_site, \"DataQualityWarnings/Flag\"))\n\n site.sign_convention = -1 if \"-\" in get_text(root, \"ProcessingInfo/SignConvention\") else 1\n\n # Get all the data in a pandas dataframe\n site.data = parse_data(root.find(\"Data\"))\n # Sort the index so periods are increasing\n site.data = site.data.sort_index()\n\n site.periods = np.array(site.data.index)\n try:\n site.Z = np.vstack([site.data['z_zxx'], site.data['z_zxy'],\n site.data['z_zyx'], site.data['z_zyy']])\n except KeyError:\n site.Z = None\n try:\n\n site.Z_var = np.vstack([site.data['z.var_zxx'], site.data['z.var_zxy'],\n site.data['z.var_zyx'], site.data['z.var_zyy']])\n except KeyError:\n # No variance in the data fields\n site.Z_var = None\n\n site.calc_resisitivity()\n\n site.datalogger = DataLogger()\n try:\n site.datalogger.runlist = get_text(xml_site, \"RunList\").split()\n except AttributeError:\n # No RunList means no data\n return site\n\n try:\n runinfo, nimsid, samplingrate = read_logger_info(site.xml)\n # No info about the nimsid from the logger read, so just return\n # without updating any information about it.\n if nimsid is None:\n return site\n site.datalogger.add_run_info(runinfo, nimsid, samplingrate)\n # Fill out the NIM System Response\n site.datalogger.nim_system_response()\n except ValueError:\n pass\n\n return site\n\ndef read_xml_lower(fname):\n \"\"\"Read in an IRIS xml file and return a Site3d object\n\n hack for lowercase\n \"\"\"\n root = ET.parse(fname).getroot()\n\n xml_site = root.find(\"site\")\n name = get_text(xml_site, \"id\")\n # Creating the object\n site = Site3d(name)\n # Store the parsed root xml element\n site.xml = root\n site.product_id = get_text(root, \"productid\")\n\n loc = xml_site.find(\"location\")\n site.latitude = convert_float(get_text(loc, \"latitude\"))\n site.longitude = convert_float(get_text(loc, \"longitude\"))\n site.elevation = convert_float(get_text(loc, \"elevation\"))\n site.declination = convert_float(get_text(loc, \"declination\"))\n\n site.start_time = convert_datetime(get_text(xml_site, \"start\"))\n site.end_time = convert_datetime(get_text(xml_site, \"end\"))\n\n quality = xml_site.find(\"dataqualitynotes\")\n site.rating = convert_int(get_text(quality, \"rating\"))\n site.min_period = convert_float(get_text(quality, \"goodfromperiod\"))\n site.max_period = convert_float(get_text(quality, \"goodtoperiod\"))\n\n site.quality_flag = convert_int(get_text(xml_site, \"dataqualitywarnings/flag\"))\n\n site.sign_convention = -1 if \"-\" in get_text(root, \"processinginfo/signconvention\") else 1\n\n # Get all the data in a pandas dataframe\n site.data = parse_data(root.find(\"data\"))\n # Sort the index so periods are increasing\n site.data = site.data.sort_index()\n\n site.periods = np.array(site.data.index)\n try:\n site.Z = np.vstack([site.data['z_zxx'], site.data['z_zxy'],\n site.data['z_zyx'], site.data['z_zyy']])\n except KeyError:\n site.Z = None\n try:\n site.Z_var = np.vstack([site.data['z.var_zxx'], site.data['z.var_zxy'],\n site.data['z.var_zyx'], site.data['z.var_zyy']])\n except KeyError:\n # No variance in the data fields\n site.Z_var = None\n\n site.calc_resisitivity()\n\n site.datalogger = DataLogger()\n try:\n site.datalogger.runlist = get_text(xml_site, \"runlist\").split()\n except AttributeError:\n # No RunList means no data\n return site\n\n try:\n runinfo, nimsid, samplingrate = read_logger_info(site.xml)\n # No info about the nimsid from the logger read, so just return\n # without updating any information about it.\n if nimsid is None:\n return site\n site.datalogger.add_run_info(runinfo, nimsid, samplingrate)\n # Fill out the NIM System Response\n site.datalogger.nim_system_response()\n except ValueError:\n pass\n\n return site\n\n\ndef read_1d_usgs_profile(fname):\n \"\"\"Reads in a USGS conductivity profile.\n\n These are downloaded from:\n https://geomag.usgs.gov/conductivity/index.php\n\n Note that they are of a specific format, with thicknesses and conductivity\n listed. This should be adaptable to other 1d profiles from different locations\n with minor modifications to return a new 1d site object.\n \"\"\"\n\n conductivities = []\n thicknesses = []\n # Just keep the last part of the file name\n profile_name = fname.strip(\".txt\").split(\"_\")[-1]\n\n with open(fname, 'r') as f:\n for line in f:\n if line[0] == \"*\":\n continue\n # Moved past all comment lines\n # First line is supposed to be the number of layers\n num_layers = int(line.split()[0])\n f.readline() # Spaces between each set of points\n\n for _ in range(num_layers):\n # Alternates conductivity/depth\n conductivities.append(float(f.readline().split()[0]))\n thicknesses.append(float(f.readline().split()[0]))\n f.readline()\n conductivities.append(float(f.readline().split()[0]))\n\n # Done with the file, so create the site and return it\n site = Site1d(name=profile_name,\n thicknesses=thicknesses,\n resistivities=[1./x for x in conductivities])\n return site\n\n\n_SITES1D = {}\nfor temp_fname in glob.glob(DATA_PATH_1D + \"earth_model_*.txt\"):\n site1d = read_1d_usgs_profile(temp_fname)\n _SITES1D[site1d.name] = site1d\n# Make AK-1 default to AK-1A\n_SITES1D[\"AK1\"] = _SITES1D[\"AK1A\"]\n\n\ndef get_1d_site(name):\n \"\"\"Returns the 1D site for the given name, if present.\"\"\"\n # Test for dropping the \"-\" in the name as well\n newname = \"\".join(name.split(\"-\"))\n if newname in _SITES1D:\n return _SITES1D[newname]\n\n raise ValueError(\"No 1d site profile with the name: \" + name)\n\n\ndef read_logger_info(root):\n \"\"\"Returns the run info, if present.\"\"\"\n runinfo = {}\n nimsid = \"\"\n samplingrate = 1.0\n\n # Run through for each runid\n for field in root.findall(\"FieldNotes\"):\n # runid of fieldnote\n runid = field.attrib['run']\n runinfo[runid] = {}\n\n try:\n nimsid = get_text(field.find('Instrument'), 'Id')\n samplingrate = convert_float(field.find('SamplingRate').text)\n except KeyError:\n pass\n\n # Run through E component\n for ecomp in field.findall(\"Dipole\"):\n # Electric component name\n edir = ecomp.attrib['name'] # Ex or Ey\n # Electric dipole length\n runinfo[runid][edir] = convert_float(get_text(ecomp, \"Length\"))\n\n # set start and end datetime\n runinfo[runid]['Start'] = datetime.datetime.strptime(field.find('Start').text,\n '%Y-%m-%dT%H:%M:%S')\n runinfo[runid]['End'] = datetime.datetime.strptime(field.find('End').text,\n '%Y-%m-%dT%H:%M:%S')\n\n return runinfo, nimsid, samplingrate\n"
] | [
[
"numpy.array",
"numpy.vstack",
"pandas.DataFrame.from_dict"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
cvcoding/STGNN | [
"f85ae92abc598dd23d66a3c959ccc7e42e95a237"
] | [
"rnn_cell_impl_local.py"
] | [
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\"\"\"Module implementing RNN Cells.\r\n\r\nThis module provides a number of basic commonly used RNN cells, such as LSTM\r\n(Long Short Term Memory) or GRU (Gated Recurrent Unit), and a number of\r\noperators that allow adding dropouts, projections, or embeddings for inputs.\r\nConstructing multi-layer cells is supported by the class `MultiRNNCell`, or by\r\ncalling the `rnn` ops several times.\r\n\"\"\"\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport collections\r\nimport hashlib\r\nimport numbers\r\n\r\nfrom tensorflow.python.eager import context\r\nfrom tensorflow.python.framework import constant_op\r\nfrom tensorflow.python.framework import dtypes\r\nfrom tensorflow.python.framework import ops\r\nfrom tensorflow.python.framework import tensor_shape\r\nfrom tensorflow.python.framework import tensor_util\r\nfrom tensorflow.python.keras import activations\r\nfrom tensorflow.python.keras import initializers\r\nfrom tensorflow.python.keras.engine import input_spec\r\nfrom tensorflow.python.keras.utils import tf_utils\r\nfrom tensorflow.python.layers import base as base_layer\r\nfrom tensorflow.python.ops import array_ops\r\nfrom tensorflow.python.ops import clip_ops\r\nfrom tensorflow.python.ops import init_ops\r\nfrom tensorflow.python.ops import math_ops\r\nfrom tensorflow.python.ops import nn_ops\r\nfrom tensorflow.python.ops import partitioned_variables\r\nfrom tensorflow.python.ops import random_ops\r\nfrom tensorflow.python.ops import tensor_array_ops\r\nfrom tensorflow.python.ops import variable_scope as vs\r\nfrom tensorflow.python.ops import variables as tf_variables\r\nfrom tensorflow.python.platform import tf_logging as logging\r\nfrom tensorflow.python.training.checkpointable import base as checkpointable\r\nfrom tensorflow.python.util import nest\r\nfrom tensorflow.python.util.deprecation import deprecated\r\nfrom tensorflow.python.util.tf_export import tf_export\r\n\r\n\r\n_BIAS_VARIABLE_NAME = \"bias\"\r\n_WEIGHTS_VARIABLE_NAME = \"kernel\"\r\n\r\n# This can be used with self.assertRaisesRegexp for assert_like_rnncell.\r\nASSERT_LIKE_RNNCELL_ERROR_REGEXP = \"is not an RNNCell\"\r\n\r\n\r\ndef assert_like_rnncell(cell_name, cell):\r\n \"\"\"Raises a TypeError if cell is not like an RNNCell.\r\n\r\n NOTE: Do not rely on the error message (in particular in tests) which can be\r\n subject to change to increase readability. Use\r\n ASSERT_LIKE_RNNCELL_ERROR_REGEXP.\r\n\r\n Args:\r\n cell_name: A string to give a meaningful error referencing to the name\r\n of the functionargument.\r\n cell: The object which should behave like an RNNCell.\r\n\r\n Raises:\r\n TypeError: A human-friendly exception.\r\n \"\"\"\r\n conditions = [\r\n hasattr(cell, \"output_size\"),\r\n hasattr(cell, \"state_size\"),\r\n hasattr(cell, \"get_initial_state\") or hasattr(cell, \"zero_state\"),\r\n callable(cell),\r\n ]\r\n errors = [\r\n \"'output_size' property is missing\",\r\n \"'state_size' property is missing\",\r\n \"either 'zero_state' or 'get_initial_state' method is required\",\r\n \"is not callable\"\r\n ]\r\n\r\n if not all(conditions):\r\n\r\n errors = [error for error, cond in zip(errors, conditions) if not cond]\r\n raise TypeError(\"The argument {!r} ({}) is not an RNNCell: {}.\".format(\r\n cell_name, cell, \", \".join(errors)))\r\n\r\n\r\ndef _concat(prefix, suffix, static=False):\r\n \"\"\"Concat that enables int, Tensor, or TensorShape values.\r\n\r\n This function takes a size specification, which can be an integer, a\r\n TensorShape, or a Tensor, and converts it into a concatenated Tensor\r\n (if static = False) or a list of integers (if static = True).\r\n\r\n Args:\r\n prefix: The prefix; usually the batch size (and/or time step size).\r\n (TensorShape, int, or Tensor.)\r\n suffix: TensorShape, int, or Tensor.\r\n static: If `True`, return a python list with possibly unknown dimensions.\r\n Otherwise return a `Tensor`.\r\n\r\n Returns:\r\n shape: the concatenation of prefix and suffix.\r\n\r\n Raises:\r\n ValueError: if `suffix` is not a scalar or vector (or TensorShape).\r\n ValueError: if prefix or suffix was `None` and asked for dynamic\r\n Tensors out.\r\n \"\"\"\r\n if isinstance(prefix, ops.Tensor):\r\n p = prefix\r\n p_static = tensor_util.constant_value(prefix)\r\n if p.shape.ndims == 0:\r\n p = array_ops.expand_dims(p, 0)\r\n elif p.shape.ndims != 1:\r\n raise ValueError(\"prefix tensor must be either a scalar or vector, \"\r\n \"but saw tensor: %s\" % p)\r\n else:\r\n p = tensor_shape.as_shape(prefix)\r\n p_static = p.as_list() if p.ndims is not None else None\r\n p = (constant_op.constant(p.as_list(), dtype=dtypes.int32)\r\n if p.is_fully_defined() else None)\r\n if isinstance(suffix, ops.Tensor):\r\n s = suffix\r\n s_static = tensor_util.constant_value(suffix)\r\n if s.shape.ndims == 0:\r\n s = array_ops.expand_dims(s, 0)\r\n elif s.shape.ndims != 1:\r\n raise ValueError(\"suffix tensor must be either a scalar or vector, \"\r\n \"but saw tensor: %s\" % s)\r\n else:\r\n s = tensor_shape.as_shape(suffix)\r\n s_static = s.as_list() if s.ndims is not None else None\r\n s = (constant_op.constant(s.as_list(), dtype=dtypes.int32)\r\n if s.is_fully_defined() else None)\r\n\r\n if static:\r\n shape = tensor_shape.as_shape(p_static).concatenate(s_static)\r\n shape = shape.as_list() if shape.ndims is not None else None\r\n else:\r\n if p is None or s is None:\r\n raise ValueError(\"Provided a prefix or suffix of None: %s and %s\"\r\n % (prefix, suffix))\r\n shape = array_ops.concat((p, s), 0)\r\n return shape\r\n\r\n\r\ndef _zero_state_tensors(state_size, batch_size, dtype):\r\n \"\"\"Create tensors of zeros based on state_size, batch_size, and dtype.\"\"\"\r\n def get_state_shape(s):\r\n \"\"\"Combine s with batch_size to get a proper tensor shape.\"\"\"\r\n c = _concat(batch_size, s)\r\n size = array_ops.zeros(c, dtype=dtype)\r\n if not context.executing_eagerly():\r\n c_static = _concat(batch_size, s, static=True)\r\n size.set_shape(c_static)\r\n return size\r\n return nest.map_structure(get_state_shape, state_size)\r\n\r\n\r\n@tf_export(\"nn.rnn_cell.RNNCell\")\r\nclass RNNCell(base_layer.Layer):\r\n \"\"\"Abstract object representing an RNN cell.\r\n\r\n Every `RNNCell` must have the properties below and implement `call` with\r\n the signature `(output, next_state) = call(input, state)`. The optional\r\n third input argument, `scope`, is allowed for backwards compatibility\r\n purposes; but should be left off for new subclasses.\r\n\r\n This definition of cell differs from the definition used in the literature.\r\n In the literature, 'cell' refers to an object with a single scalar output.\r\n This definition refers to a horizontal array of such units.\r\n\r\n An RNN cell, in the most abstract setting, is anything that has\r\n a state and performs some operation that takes a matrix of inputs.\r\n This operation results in an output matrix with `self.output_size` columns.\r\n If `self.state_size` is an integer, this operation also results in a new\r\n state matrix with `self.state_size` columns. If `self.state_size` is a\r\n (possibly nested tuple of) TensorShape object(s), then it should return a\r\n matching structure of Tensors having shape `[batch_size].concatenate(s)`\r\n for each `s` in `self.batch_size`.\r\n \"\"\"\r\n\r\n def __init__(self, trainable=True, name=None, dtype=None, **kwargs):\r\n super(RNNCell, self).__init__(\r\n trainable=trainable, name=name, dtype=dtype, **kwargs)\r\n # Attribute that indicates whether the cell is a TF RNN cell, due the slight\r\n # difference between TF and Keras RNN cell.\r\n self._is_tf_rnn_cell = True\r\n\r\n def __call__(self, inputs, state, input_nextt_gate, scope=None):\r\n \"\"\"Run this RNN cell on inputs, starting from the given state.\r\n\r\n Args:\r\n inputs: `2-D` tensor with shape `[batch_size, input_size]`.\r\n state: if `self.state_size` is an integer, this should be a `2-D Tensor`\r\n with shape `[batch_size, self.state_size]`. Otherwise, if\r\n `self.state_size` is a tuple of integers, this should be a tuple\r\n with shapes `[batch_size, s] for s in self.state_size`.\r\n scope: VariableScope for the created subgraph; defaults to class name.\r\n\r\n Returns:\r\n A pair containing:\r\n\r\n - Output: A `2-D` tensor with shape `[batch_size, self.output_size]`.\r\n - New state: Either a single `2-D` tensor, or a tuple of tensors matching\r\n the arity and shapes of `state`.\r\n \"\"\"\r\n if scope is not None:\r\n with vs.variable_scope(scope,\r\n custom_getter=self._rnn_get_variable) as scope:\r\n return super(RNNCell, self).__call__(inputs, state, scope=scope)\r\n else:\r\n scope_attrname = \"rnncell_scope\"\r\n scope = getattr(self, scope_attrname, None)\r\n if scope is None:\r\n scope = vs.variable_scope(vs.get_variable_scope(),\r\n custom_getter=self._rnn_get_variable)\r\n setattr(self, scope_attrname, scope)\r\n with scope:\r\n return super(RNNCell, self).__call__(inputs, state)\r\n\r\n def _rnn_get_variable(self, getter, *args, **kwargs):\r\n variable = getter(*args, **kwargs)\r\n if context.executing_eagerly():\r\n trainable = variable._trainable # pylint: disable=protected-access\r\n else:\r\n trainable = (\r\n variable in tf_variables.trainable_variables() or\r\n (isinstance(variable, tf_variables.PartitionedVariable) and\r\n list(variable)[0] in tf_variables.trainable_variables()))\r\n if trainable and variable not in self._trainable_weights:\r\n self._trainable_weights.append(variable)\r\n elif not trainable and variable not in self._non_trainable_weights:\r\n self._non_trainable_weights.append(variable)\r\n return variable\r\n\r\n @property\r\n def state_size(self):\r\n \"\"\"size(s) of state(s) used by this cell.\r\n\r\n It can be represented by an Integer, a TensorShape or a tuple of Integers\r\n or TensorShapes.\r\n \"\"\"\r\n raise NotImplementedError(\"Abstract method\")\r\n\r\n @property\r\n def output_size(self):\r\n \"\"\"Integer or TensorShape: size of outputs produced by this cell.\"\"\"\r\n raise NotImplementedError(\"Abstract method\")\r\n\r\n def build(self, _):\r\n # This tells the parent Layer object that it's OK to call\r\n # self.add_variable() inside the call() method.\r\n pass\r\n\r\n def get_initial_state(self, inputs=None, batch_size=None, dtype=None):\r\n if inputs is not None:\r\n # Validate the given batch_size and dtype against inputs if provided.\r\n inputs = ops.convert_to_tensor(inputs, name=\"inputs\")\r\n if batch_size is not None:\r\n if tensor_util.is_tensor(batch_size):\r\n static_batch_size = tensor_util.constant_value(\r\n batch_size, partial=True)\r\n else:\r\n static_batch_size = batch_size\r\n if inputs.shape.dims[0].value != static_batch_size:\r\n raise ValueError(\r\n \"batch size from input tensor is different from the \"\r\n \"input param. Input tensor batch: {}, batch_size: {}\".format(\r\n inputs.shape.dims[0].value, batch_size))\r\n\r\n if dtype is not None and inputs.dtype != dtype:\r\n raise ValueError(\r\n \"dtype from input tensor is different from the \"\r\n \"input param. Input tensor dtype: {}, dtype: {}\".format(\r\n inputs.dtype, dtype))\r\n\r\n batch_size = inputs.shape.dims[0].value or array_ops.shape(inputs)[0]\r\n dtype = inputs.dtype\r\n if None in [batch_size, dtype]:\r\n raise ValueError(\r\n \"batch_size and dtype cannot be None while constructing initial \"\r\n \"state: batch_size={}, dtype={}\".format(batch_size, dtype))\r\n return self.zero_state(batch_size, dtype)\r\n\r\n def zero_state(self, batch_size, dtype):\r\n \"\"\"Return zero-filled state tensor(s).\r\n\r\n Args:\r\n batch_size: int, float, or unit Tensor representing the batch size.\r\n dtype: the data type to use for the state.\r\n\r\n Returns:\r\n If `state_size` is an int or TensorShape, then the return value is a\r\n `N-D` tensor of shape `[batch_size, state_size]` filled with zeros.\r\n\r\n If `state_size` is a nested list or tuple, then the return value is\r\n a nested list or tuple (of the same structure) of `2-D` tensors with\r\n the shapes `[batch_size, s]` for each s in `state_size`.\r\n \"\"\"\r\n # Try to use the last cached zero_state. This is done to avoid recreating\r\n # zeros, especially when eager execution is enabled.\r\n state_size = self.state_size\r\n is_eager = context.executing_eagerly()\r\n if is_eager and hasattr(self, \"_last_zero_state\"):\r\n (last_state_size, last_batch_size, last_dtype,\r\n last_output) = getattr(self, \"_last_zero_state\")\r\n if (last_batch_size == batch_size and\r\n last_dtype == dtype and\r\n last_state_size == state_size):\r\n return last_output\r\n with ops.name_scope(type(self).__name__ + \"ZeroState\", values=[batch_size]):\r\n output = _zero_state_tensors(state_size, batch_size, dtype)\r\n if is_eager:\r\n self._last_zero_state = (state_size, batch_size, dtype, output)\r\n return output\r\n\r\n\r\nclass LayerRNNCell(RNNCell):\r\n \"\"\"Subclass of RNNCells that act like proper `tf.Layer` objects.\r\n\r\n For backwards compatibility purposes, most `RNNCell` instances allow their\r\n `call` methods to instantiate variables via `tf.get_variable`. The underlying\r\n variable scope thus keeps track of any variables, and returning cached\r\n versions. This is atypical of `tf.layer` objects, which separate this\r\n part of layer building into a `build` method that is only called once.\r\n\r\n Here we provide a subclass for `RNNCell` objects that act exactly as\r\n `Layer` objects do. They must provide a `build` method and their\r\n `call` methods do not access Variables `tf.get_variable`.\r\n \"\"\"\r\n\r\n def __call__(self, inputs, state, scope=None, *args, **kwargs):\r\n \"\"\"Run this RNN cell on inputs, starting from the given state.\r\n\r\n Args:\r\n inputs: `2-D` tensor with shape `[batch_size, input_size]`.\r\n state: if `self.state_size` is an integer, this should be a `2-D Tensor`\r\n with shape `[batch_size, self.state_size]`. Otherwise, if\r\n `self.state_size` is a tuple of integers, this should be a tuple\r\n with shapes `[batch_size, s] for s in self.state_size`.\r\n scope: optional cell scope.\r\n *args: Additional positional arguments.\r\n **kwargs: Additional keyword arguments.\r\n\r\n Returns:\r\n A pair containing:\r\n\r\n - Output: A `2-D` tensor with shape `[batch_size, self.output_size]`.\r\n - New state: Either a single `2-D` tensor, or a tuple of tensors matching\r\n the arity and shapes of `state`.\r\n \"\"\"\r\n # Bypass RNNCell's variable capturing semantics for LayerRNNCell.\r\n # Instead, it is up to subclasses to provide a proper build\r\n # method. See the class docstring for more details.\r\n return base_layer.Layer.__call__(self, inputs, state, scope=scope,\r\n *args, **kwargs)\r\n\r\n\r\n@tf_export(v1=[\"nn.rnn_cell.BasicRNNCell\"])\r\nclass BasicRNNCell(LayerRNNCell):\r\n \"\"\"The most basic RNN cell.\r\n\r\n Note that this cell is not optimized for performance. Please use\r\n `tf.contrib.cudnn_rnn.CudnnRNNTanh` for better performance on GPU.\r\n\r\n Args:\r\n num_units: int, The number of units in the RNN cell.\r\n activation: Nonlinearity to use. Default: `tanh`. It could also be string\r\n that is within Keras activation function names.\r\n reuse: (optional) Python boolean describing whether to reuse variables\r\n in an existing scope. If not `True`, and the existing scope already has\r\n the given variables, an error is raised.\r\n name: String, the name of the layer. Layers with the same name will\r\n share weights, but to avoid mistakes we require reuse=True in such\r\n cases.\r\n dtype: Default dtype of the layer (default of `None` means use the type\r\n of the first input). Required when `build` is called before `call`.\r\n **kwargs: Dict, keyword named properties for common layer attributes, like\r\n `trainable` etc when constructing the cell from configs of get_config().\r\n \"\"\"\r\n\r\n @deprecated(None, \"This class is equivalent as tf.keras.layers.SimpleRNNCell,\"\r\n \" and will be replaced by that in Tensorflow 2.0.\")\r\n def __init__(self,\r\n num_units,\r\n activation=None,\r\n reuse=None,\r\n name=None,\r\n dtype=None,\r\n **kwargs):\r\n super(BasicRNNCell, self).__init__(\r\n _reuse=reuse, name=name, dtype=dtype, **kwargs)\r\n if context.executing_eagerly() and context.num_gpus() > 0:\r\n logging.warn(\"%s: Note that this cell is not optimized for performance. \"\r\n \"Please use tf.contrib.cudnn_rnn.CudnnRNNTanh for better \"\r\n \"performance on GPU.\", self)\r\n\r\n # Inputs must be 2-dimensional.\r\n self.input_spec = input_spec.InputSpec(ndim=2)\r\n\r\n self._num_units = num_units\r\n if activation:\r\n self._activation = activations.get(activation)\r\n else:\r\n self._activation = math_ops.tanh\r\n\r\n @property\r\n def state_size(self):\r\n return self._num_units\r\n\r\n @property\r\n def output_size(self):\r\n return self._num_units\r\n\r\n @tf_utils.shape_type_conversion\r\n def build(self, inputs_shape):\r\n if inputs_shape[-1] is None:\r\n raise ValueError(\"Expected inputs.shape[-1] to be known, saw shape: %s\"\r\n % str(inputs_shape))\r\n\r\n input_depth = inputs_shape[-1]\r\n self._kernel = self.add_variable(\r\n _WEIGHTS_VARIABLE_NAME,\r\n shape=[input_depth + self._num_units, self._num_units])\r\n self._bias = self.add_variable(\r\n _BIAS_VARIABLE_NAME,\r\n shape=[self._num_units],\r\n initializer=init_ops.zeros_initializer(dtype=self.dtype))\r\n\r\n self.built = True\r\n\r\n def call(self, inputs, state):\r\n \"\"\"Most basic RNN: output = new_state = act(W * input + U * state + B).\"\"\"\r\n\r\n gate_inputs = math_ops.matmul(\r\n array_ops.concat([inputs, state], 1), self._kernel)\r\n gate_inputs = nn_ops.bias_add(gate_inputs, self._bias)\r\n output = self._activation(gate_inputs)\r\n return output, output\r\n\r\n def get_config(self):\r\n config = {\r\n \"num_units\": self._num_units,\r\n \"activation\": activations.serialize(self._activation),\r\n \"reuse\": self._reuse,\r\n }\r\n base_config = super(BasicRNNCell, self).get_config()\r\n return dict(list(base_config.items()) + list(config.items()))\r\n\r\n\r\n@tf_export(v1=[\"nn.rnn_cell.GRUCell\"])\r\nclass GRUCell(LayerRNNCell):\r\n \"\"\"Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078).\r\n\r\n Note that this cell is not optimized for performance. Please use\r\n `tf.contrib.cudnn_rnn.CudnnGRU` for better performance on GPU, or\r\n `tf.contrib.rnn.GRUBlockCellV2` for better performance on CPU.\r\n\r\n Args:\r\n num_units: int, The number of units in the GRU cell.\r\n activation: Nonlinearity to use. Default: `tanh`.\r\n reuse: (optional) Python boolean describing whether to reuse variables\r\n in an existing scope. If not `True`, and the existing scope already has\r\n the given variables, an error is raised.\r\n kernel_initializer: (optional) The initializer to use for the weight and\r\n projection matrices.\r\n bias_initializer: (optional) The initializer to use for the bias.\r\n name: String, the name of the layer. Layers with the same name will\r\n share weights, but to avoid mistakes we require reuse=True in such\r\n cases.\r\n dtype: Default dtype of the layer (default of `None` means use the type\r\n of the first input). Required when `build` is called before `call`.\r\n **kwargs: Dict, keyword named properties for common layer attributes, like\r\n `trainable` etc when constructing the cell from configs of get_config().\r\n \"\"\"\r\n\r\n @deprecated(None, \"This class is equivalent as tf.keras.layers.GRUCell,\"\r\n \" and will be replaced by that in Tensorflow 2.0.\")\r\n def __init__(self,\r\n num_units,\r\n activation=None,\r\n reuse=None,\r\n kernel_initializer=None,\r\n bias_initializer=None,\r\n name=None,\r\n dtype=None,\r\n **kwargs):\r\n super(GRUCell, self).__init__(\r\n _reuse=reuse, name=name, dtype=dtype, **kwargs)\r\n\r\n if context.executing_eagerly() and context.num_gpus() > 0:\r\n logging.warn(\"%s: Note that this cell is not optimized for performance. \"\r\n \"Please use tf.contrib.cudnn_rnn.CudnnGRU for better \"\r\n \"performance on GPU.\", self)\r\n # Inputs must be 2-dimensional.\r\n self.input_spec = input_spec.InputSpec(ndim=2)\r\n\r\n self._num_units = num_units\r\n if activation:\r\n self._activation = activations.get(activation)\r\n else:\r\n self._activation = math_ops.tanh\r\n self._kernel_initializer = initializers.get(kernel_initializer)\r\n self._bias_initializer = initializers.get(bias_initializer)\r\n\r\n @property\r\n def state_size(self):\r\n return self._num_units\r\n\r\n @property\r\n def output_size(self):\r\n return self._num_units\r\n\r\n @tf_utils.shape_type_conversion\r\n def build(self, inputs_shape):\r\n if inputs_shape[-1] is None:\r\n raise ValueError(\"Expected inputs.shape[-1] to be known, saw shape: %s\"\r\n % str(inputs_shape))\r\n\r\n input_depth = inputs_shape[-1]\r\n self._gate_kernel = self.add_variable(\r\n \"gates/%s\" % _WEIGHTS_VARIABLE_NAME,\r\n shape=[input_depth + self._num_units, 2 * self._num_units],\r\n initializer=self._kernel_initializer)\r\n self._gate_bias = self.add_variable(\r\n \"gates/%s\" % _BIAS_VARIABLE_NAME,\r\n shape=[2 * self._num_units],\r\n initializer=(\r\n self._bias_initializer\r\n if self._bias_initializer is not None\r\n else init_ops.constant_initializer(1.0, dtype=self.dtype)))\r\n self._candidate_kernel = self.add_variable(\r\n \"candidate/%s\" % _WEIGHTS_VARIABLE_NAME,\r\n shape=[input_depth + self._num_units, self._num_units],\r\n initializer=self._kernel_initializer)\r\n self._candidate_bias = self.add_variable(\r\n \"candidate/%s\" % _BIAS_VARIABLE_NAME,\r\n shape=[self._num_units],\r\n initializer=(\r\n self._bias_initializer\r\n if self._bias_initializer is not None\r\n else init_ops.zeros_initializer(dtype=self.dtype)))\r\n\r\n self.built = True\r\n\r\n def call(self, inputs, state):\r\n \"\"\"Gated recurrent unit (GRU) with nunits cells.\"\"\"\r\n\r\n gate_inputs = math_ops.matmul(\r\n array_ops.concat([inputs, state], 1), self._gate_kernel)\r\n gate_inputs = nn_ops.bias_add(gate_inputs, self._gate_bias)\r\n\r\n value = math_ops.sigmoid(gate_inputs)\r\n r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1)\r\n\r\n r_state = r * state\r\n\r\n candidate = math_ops.matmul(\r\n array_ops.concat([inputs, r_state], 1), self._candidate_kernel)\r\n candidate = nn_ops.bias_add(candidate, self._candidate_bias)\r\n\r\n c = self._activation(candidate)\r\n new_h = u * state + (1 - u) * c\r\n return new_h, new_h\r\n\r\n def get_config(self):\r\n config = {\r\n \"num_units\": self._num_units,\r\n \"kernel_initializer\": initializers.serialize(self._kernel_initializer),\r\n \"bias_initializer\": initializers.serialize(self._bias_initializer),\r\n \"activation\": activations.serialize(self._activation),\r\n \"reuse\": self._reuse,\r\n }\r\n base_config = super(GRUCell, self).get_config()\r\n return dict(list(base_config.items()) + list(config.items()))\r\n\r\n\r\n_LSTMStateTuple = collections.namedtuple(\"LSTMStateTuple\", (\"c\", \"h\"))\r\n\r\n\r\n@tf_export(\"nn.rnn_cell.LSTMStateTuple\")\r\nclass LSTMStateTuple(_LSTMStateTuple):\r\n \"\"\"Tuple used by LSTM Cells for `state_size`, `zero_state`, and output state.\r\n\r\n Stores two elements: `(c, h)`, in that order. Where `c` is the hidden state\r\n and `h` is the output.\r\n\r\n Only used when `state_is_tuple=True`.\r\n \"\"\"\r\n __slots__ = ()\r\n\r\n @property\r\n def dtype(self):\r\n (c, h) = self\r\n if c.dtype != h.dtype:\r\n raise TypeError(\"Inconsistent internal state: %s vs %s\" %\r\n (str(c.dtype), str(h.dtype)))\r\n return c.dtype\r\n\r\n\r\n@tf_export(v1=[\"nn.rnn_cell.BasicLSTMCell\"])\r\nclass BasicLSTMCell(LayerRNNCell):\r\n \"\"\"DEPRECATED: Please use `tf.nn.rnn_cell.LSTMCell` instead.\r\n\r\n Basic LSTM recurrent network cell.\r\n\r\n The implementation is based on: http://arxiv.org/abs/1409.2329.\r\n\r\n We add forget_bias (default: 1) to the biases of the forget gate in order to\r\n reduce the scale of forgetting in the beginning of the training.\r\n\r\n It does not allow cell clipping, a projection layer, and does not\r\n use peep-hole connections: it is the basic baseline.\r\n\r\n For advanced models, please use the full `tf.nn.rnn_cell.LSTMCell`\r\n that follows.\r\n\r\n Note that this cell is not optimized for performance. Please use\r\n `tf.contrib.cudnn_rnn.CudnnLSTM` for better performance on GPU, or\r\n `tf.contrib.rnn.LSTMBlockCell` and `tf.contrib.rnn.LSTMBlockFusedCell` for\r\n better performance on CPU.\r\n \"\"\"\r\n\r\n @deprecated(None, \"This class is equivalent as tf.keras.layers.LSTMCell,\"\r\n \" and will be replaced by that in Tensorflow 2.0.\")\r\n def __init__(self,\r\n num_units,\r\n forget_bias=1.0,\r\n state_is_tuple=True,\r\n activation=None,\r\n reuse=None,\r\n name=None,\r\n dtype=None,\r\n **kwargs):\r\n \"\"\"Initialize the basic LSTM cell.\r\n\r\n Args:\r\n num_units: int, The number of units in the LSTM cell.\r\n forget_bias: float, The bias added to forget gates (see above).\r\n Must set to `0.0` manually when restoring from CudnnLSTM-trained\r\n checkpoints.\r\n state_is_tuple: If True, accepted and returned states are 2-tuples of\r\n the `c_state` and `m_state`. If False, they are concatenated\r\n along the column axis. The latter behavior will soon be deprecated.\r\n activation: Activation function of the inner states. Default: `tanh`. It\r\n could also be string that is within Keras activation function names.\r\n reuse: (optional) Python boolean describing whether to reuse variables\r\n in an existing scope. If not `True`, and the existing scope already has\r\n the given variables, an error is raised.\r\n name: String, the name of the layer. Layers with the same name will\r\n share weights, but to avoid mistakes we require reuse=True in such\r\n cases.\r\n dtype: Default dtype of the layer (default of `None` means use the type\r\n of the first input). Required when `build` is called before `call`.\r\n **kwargs: Dict, keyword named properties for common layer attributes, like\r\n `trainable` etc when constructing the cell from configs of get_config().\r\n\r\n When restoring from CudnnLSTM-trained checkpoints, must use\r\n `CudnnCompatibleLSTMCell` instead.\r\n \"\"\"\r\n super(BasicLSTMCell, self).__init__(\r\n _reuse=reuse, name=name, dtype=dtype, **kwargs)\r\n if not state_is_tuple:\r\n logging.warn(\"%s: Using a concatenated state is slower and will soon be \"\r\n \"deprecated. Use state_is_tuple=True.\", self)\r\n if context.executing_eagerly() and context.num_gpus() > 0:\r\n logging.warn(\"%s: Note that this cell is not optimized for performance. \"\r\n \"Please use tf.contrib.cudnn_rnn.CudnnLSTM for better \"\r\n \"performance on GPU.\", self)\r\n\r\n # Inputs must be 2-dimensional.\r\n self.input_spec = input_spec.InputSpec(ndim=2)\r\n\r\n self._num_units = num_units\r\n self._forget_bias = forget_bias\r\n self._state_is_tuple = state_is_tuple\r\n if activation:\r\n self._activation = activations.get(activation)\r\n else:\r\n self._activation = math_ops.tanh\r\n\r\n @property\r\n def state_size(self):\r\n return (LSTMStateTuple(self._num_units, self._num_units)\r\n if self._state_is_tuple else 2 * self._num_units)\r\n\r\n @property\r\n def output_size(self):\r\n return self._num_units\r\n\r\n @tf_utils.shape_type_conversion\r\n def build(self, inputs_shape):\r\n if inputs_shape[-1] is None:\r\n raise ValueError(\"Expected inputs.shape[-1] to be known, saw shape: %s\"\r\n % str(inputs_shape))\r\n\r\n input_depth = inputs_shape[-1]\r\n h_depth = self._num_units\r\n self._kernel = self.add_variable(\r\n _WEIGHTS_VARIABLE_NAME,\r\n shape=[input_depth + h_depth, 4 * self._num_units])\r\n self._bias = self.add_variable(\r\n _BIAS_VARIABLE_NAME,\r\n shape=[4 * self._num_units],\r\n initializer=init_ops.zeros_initializer(dtype=self.dtype))\r\n\r\n self.built = True\r\n\r\n def call(self, inputs, state):\r\n \"\"\"Long short-term memory cell (LSTM).\r\n\r\n Args:\r\n inputs: `2-D` tensor with shape `[batch_size, input_size]`.\r\n state: An `LSTMStateTuple` of state tensors, each shaped\r\n `[batch_size, num_units]`, if `state_is_tuple` has been set to\r\n `True`. Otherwise, a `Tensor` shaped\r\n `[batch_size, 2 * num_units]`.\r\n\r\n Returns:\r\n A pair containing the new hidden state, and the new state (either a\r\n `LSTMStateTuple` or a concatenated state, depending on\r\n `state_is_tuple`).\r\n \"\"\"\r\n sigmoid = math_ops.sigmoid\r\n one = constant_op.constant(1, dtype=dtypes.int32)\r\n # Parameters of gates are concatenated into one multiply for efficiency.\r\n if self._state_is_tuple:\r\n c, h = state\r\n else:\r\n c, h = array_ops.split(value=state, num_or_size_splits=2, axis=one)\r\n\r\n gate_inputs = math_ops.matmul(\r\n array_ops.concat([inputs, h], 1), self._kernel)\r\n gate_inputs = nn_ops.bias_add(gate_inputs, self._bias)\r\n\r\n # i = input_gate, j = new_input, f = forget_gate, o = output_gate\r\n i, j, f, o = array_ops.split(\r\n value=gate_inputs, num_or_size_splits=4, axis=one)\r\n\r\n forget_bias_tensor = constant_op.constant(self._forget_bias, dtype=f.dtype)\r\n # Note that using `add` and `multiply` instead of `+` and `*` gives a\r\n # performance improvement. So using those at the cost of readability.\r\n add = math_ops.add\r\n multiply = math_ops.multiply\r\n new_c = add(multiply(c, sigmoid(add(f, forget_bias_tensor))),\r\n multiply(sigmoid(i), self._activation(j)))\r\n new_h = multiply(self._activation(new_c), sigmoid(o))\r\n\r\n if self._state_is_tuple:\r\n new_state = LSTMStateTuple(new_c, new_h)\r\n else:\r\n new_state = array_ops.concat([new_c, new_h], 1)\r\n return new_h, new_state\r\n\r\n def get_config(self):\r\n config = {\r\n \"num_units\": self._num_units,\r\n \"forget_bias\": self._forget_bias,\r\n \"state_is_tuple\": self._state_is_tuple,\r\n \"activation\": activations.serialize(self._activation),\r\n \"reuse\": self._reuse,\r\n }\r\n base_config = super(BasicLSTMCell, self).get_config()\r\n return dict(list(base_config.items()) + list(config.items()))\r\n\r\n\r\n@tf_export(v1=[\"nn.rnn_cell.LSTMCell\"])\r\nclass LSTMCell(LayerRNNCell):\r\n \"\"\"Long short-term memory unit (LSTM) recurrent network cell.\r\n\r\n The default non-peephole implementation is based on:\r\n\r\n https://pdfs.semanticscholar.org/1154/0131eae85b2e11d53df7f1360eeb6476e7f4.pdf\r\n\r\n Felix Gers, Jurgen Schmidhuber, and Fred Cummins.\r\n \"Learning to forget: Continual prediction with LSTM.\" IET, 850-855, 1999.\r\n\r\n The peephole implementation is based on:\r\n\r\n https://research.google.com/pubs/archive/43905.pdf\r\n\r\n Hasim Sak, Andrew Senior, and Francoise Beaufays.\r\n \"Long short-term memory recurrent neural network architectures for\r\n large scale acoustic modeling.\" INTERSPEECH, 2014.\r\n\r\n The class uses optional peep-hole connections, optional cell clipping, and\r\n an optional projection layer.\r\n\r\n Note that this cell is not optimized for performance. Please use\r\n `tf.contrib.cudnn_rnn.CudnnLSTM` for better performance on GPU, or\r\n `tf.contrib.rnn.LSTMBlockCell` and `tf.contrib.rnn.LSTMBlockFusedCell` for\r\n better performance on CPU.\r\n \"\"\"\r\n\r\n @deprecated(None, \"This class is equivalent as tf.keras.layers.LSTMCell,\"\r\n \" and will be replaced by that in Tensorflow 2.0.\")\r\n def __init__(self, num_units,\r\n use_peepholes=False, cell_clip=None,\r\n initializer=None, num_proj=None, proj_clip=None,\r\n num_unit_shards=None, num_proj_shards=None,\r\n forget_bias=1.0, state_is_tuple=True,\r\n activation=None, reuse=None, name=None, dtype=None, **kwargs):\r\n \"\"\"Initialize the parameters for an LSTM cell.\r\n\r\n Args:\r\n num_units: int, The number of units in the LSTM cell.\r\n use_peepholes: bool, set True to enable diagonal/peephole connections.\r\n cell_clip: (optional) A float value, if provided the cell state is clipped\r\n by this value prior to the cell output activation.\r\n initializer: (optional) The initializer to use for the weight and\r\n projection matrices.\r\n num_proj: (optional) int, The output dimensionality for the projection\r\n matrices. If None, no projection is performed.\r\n proj_clip: (optional) A float value. If `num_proj > 0` and `proj_clip` is\r\n provided, then the projected values are clipped elementwise to within\r\n `[-proj_clip, proj_clip]`.\r\n num_unit_shards: Deprecated, will be removed by Jan. 2017.\r\n Use a variable_scope partitioner instead.\r\n num_proj_shards: Deprecated, will be removed by Jan. 2017.\r\n Use a variable_scope partitioner instead.\r\n forget_bias: Biases of the forget gate are initialized by default to 1\r\n in order to reduce the scale of forgetting at the beginning of\r\n the training. Must set it manually to `0.0` when restoring from\r\n CudnnLSTM trained checkpoints.\r\n state_is_tuple: If True, accepted and returned states are 2-tuples of\r\n the `c_state` and `m_state`. If False, they are concatenated\r\n along the column axis. This latter behavior will soon be deprecated.\r\n activation: Activation function of the inner states. Default: `tanh`. It\r\n could also be string that is within Keras activation function names.\r\n reuse: (optional) Python boolean describing whether to reuse variables\r\n in an existing scope. If not `True`, and the existing scope already has\r\n the given variables, an error is raised.\r\n name: String, the name of the layer. Layers with the same name will\r\n share weights, but to avoid mistakes we require reuse=True in such\r\n cases.\r\n dtype: Default dtype of the layer (default of `None` means use the type\r\n of the first input). Required when `build` is called before `call`.\r\n **kwargs: Dict, keyword named properties for common layer attributes, like\r\n `trainable` etc when constructing the cell from configs of get_config().\r\n\r\n When restoring from CudnnLSTM-trained checkpoints, use\r\n `CudnnCompatibleLSTMCell` instead.\r\n \"\"\"\r\n super(LSTMCell, self).__init__(\r\n _reuse=reuse, name=name, dtype=dtype, **kwargs)\r\n if not state_is_tuple:\r\n logging.warn(\"%s: Using a concatenated state is slower and will soon be \"\r\n \"deprecated. Use state_is_tuple=True.\", self)\r\n if num_unit_shards is not None or num_proj_shards is not None:\r\n logging.warn(\r\n \"%s: The num_unit_shards and proj_unit_shards parameters are \"\r\n \"deprecated and will be removed in Jan 2017. \"\r\n \"Use a variable scope with a partitioner instead.\", self)\r\n if context.executing_eagerly() and context.num_gpus() > 0:\r\n logging.warn(\"%s: Note that this cell is not optimized for performance. \"\r\n \"Please use tf.contrib.cudnn_rnn.CudnnLSTM for better \"\r\n \"performance on GPU.\", self)\r\n\r\n # Inputs must be 2-dimensional.\r\n self.input_spec = input_spec.InputSpec(ndim=2)\r\n\r\n self._num_units = num_units\r\n self._use_peepholes = use_peepholes\r\n self._cell_clip = cell_clip\r\n self._initializer = initializers.get(initializer)\r\n self._num_proj = num_proj\r\n self._proj_clip = proj_clip\r\n self._num_unit_shards = num_unit_shards\r\n self._num_proj_shards = num_proj_shards\r\n self._forget_bias = forget_bias\r\n self._state_is_tuple = state_is_tuple\r\n if activation:\r\n self._activation = activations.get(activation)\r\n else:\r\n self._activation = math_ops.tanh\r\n\r\n if num_proj:\r\n self._state_size = (\r\n LSTMStateTuple(num_units, num_proj)\r\n if state_is_tuple else num_units + num_proj)\r\n self._output_size = num_proj\r\n else:\r\n self._state_size = (\r\n LSTMStateTuple(num_units, num_units)\r\n if state_is_tuple else 2 * num_units)\r\n self._output_size = num_units\r\n\r\n @property\r\n def state_size(self):\r\n return self._state_size\r\n\r\n @property\r\n def output_size(self):\r\n return self._output_size\r\n\r\n @tf_utils.shape_type_conversion\r\n def build(self, inputs_shape):\r\n if inputs_shape[-1] is None:\r\n raise ValueError(\"Expected inputs.shape[-1] to be known, saw shape: %s\"\r\n % str(inputs_shape))\r\n\r\n input_depth = inputs_shape[-1]\r\n h_depth = self._num_units if self._num_proj is None else self._num_proj\r\n maybe_partitioner = (\r\n partitioned_variables.fixed_size_partitioner(self._num_unit_shards)\r\n if self._num_unit_shards is not None\r\n else None)\r\n self._kernel = self.add_variable(\r\n _WEIGHTS_VARIABLE_NAME,\r\n shape=[input_depth + h_depth, 4 * self._num_units],\r\n initializer=self._initializer,\r\n partitioner=maybe_partitioner)\r\n if self.dtype is None:\r\n initializer = init_ops.zeros_initializer\r\n else:\r\n initializer = init_ops.zeros_initializer(dtype=self.dtype)\r\n self._bias = self.add_variable(\r\n _BIAS_VARIABLE_NAME,\r\n shape=[4 * self._num_units],\r\n initializer=initializer)\r\n if self._use_peepholes:\r\n self._w_f_diag = self.add_variable(\"w_f_diag\", shape=[self._num_units],\r\n initializer=self._initializer)\r\n self._w_i_diag = self.add_variable(\"w_i_diag\", shape=[self._num_units],\r\n initializer=self._initializer)\r\n self._w_o_diag = self.add_variable(\"w_o_diag\", shape=[self._num_units],\r\n initializer=self._initializer)\r\n\r\n if self._num_proj is not None:\r\n maybe_proj_partitioner = (\r\n partitioned_variables.fixed_size_partitioner(self._num_proj_shards)\r\n if self._num_proj_shards is not None\r\n else None)\r\n self._proj_kernel = self.add_variable(\r\n \"projection/%s\" % _WEIGHTS_VARIABLE_NAME,\r\n shape=[self._num_units, self._num_proj],\r\n initializer=self._initializer,\r\n partitioner=maybe_proj_partitioner)\r\n\r\n self.built = True\r\n\r\n def call(self, inputs, state):\r\n \"\"\"Run one step of LSTM.\r\n\r\n Args:\r\n inputs: input Tensor, must be 2-D, `[batch, input_size]`.\r\n state: if `state_is_tuple` is False, this must be a state Tensor,\r\n `2-D, [batch, state_size]`. If `state_is_tuple` is True, this must be a\r\n tuple of state Tensors, both `2-D`, with column sizes `c_state` and\r\n `m_state`.\r\n\r\n Returns:\r\n A tuple containing:\r\n\r\n - A `2-D, [batch, output_dim]`, Tensor representing the output of the\r\n LSTM after reading `inputs` when previous state was `state`.\r\n Here output_dim is:\r\n num_proj if num_proj was set,\r\n num_units otherwise.\r\n - Tensor(s) representing the new state of LSTM after reading `inputs` when\r\n the previous state was `state`. Same type and shape(s) as `state`.\r\n\r\n Raises:\r\n ValueError: If input size cannot be inferred from inputs via\r\n static shape inference.\r\n \"\"\"\r\n num_proj = self._num_units if self._num_proj is None else self._num_proj\r\n sigmoid = math_ops.sigmoid\r\n\r\n if self._state_is_tuple:\r\n (c_prev, m_prev) = state\r\n else:\r\n c_prev = array_ops.slice(state, [0, 0], [-1, self._num_units])\r\n m_prev = array_ops.slice(state, [0, self._num_units], [-1, num_proj])\r\n\r\n input_size = inputs.get_shape().with_rank(2).dims[1].value\r\n if input_size is None:\r\n raise ValueError(\"Could not infer input size from inputs.get_shape()[-1]\")\r\n\r\n # i = input_gate, j = new_input, f = forget_gate, o = output_gate\r\n lstm_matrix = math_ops.matmul(\r\n array_ops.concat([inputs, m_prev], 1), self._kernel)\r\n lstm_matrix = nn_ops.bias_add(lstm_matrix, self._bias)\r\n\r\n i, j, f, o = array_ops.split(\r\n value=lstm_matrix, num_or_size_splits=4, axis=1)\r\n # Diagonal connections\r\n if self._use_peepholes:\r\n c = (sigmoid(f + self._forget_bias + self._w_f_diag * c_prev) * c_prev +\r\n sigmoid(i + self._w_i_diag * c_prev) * self._activation(j))\r\n else:\r\n c = (sigmoid(f + self._forget_bias) * c_prev + sigmoid(i) *\r\n self._activation(j))\r\n\r\n if self._cell_clip is not None:\r\n # pylint: disable=invalid-unary-operand-type\r\n c = clip_ops.clip_by_value(c, -self._cell_clip, self._cell_clip)\r\n # pylint: enable=invalid-unary-operand-type\r\n if self._use_peepholes:\r\n m = sigmoid(o + self._w_o_diag * c) * self._activation(c)\r\n else:\r\n m = sigmoid(o) * self._activation(c)\r\n\r\n if self._num_proj is not None:\r\n m = math_ops.matmul(m, self._proj_kernel)\r\n\r\n if self._proj_clip is not None:\r\n # pylint: disable=invalid-unary-operand-type\r\n m = clip_ops.clip_by_value(m, -self._proj_clip, self._proj_clip)\r\n # pylint: enable=invalid-unary-operand-type\r\n\r\n new_state = (LSTMStateTuple(c, m) if self._state_is_tuple else\r\n array_ops.concat([c, m], 1))\r\n return m, new_state\r\n\r\n def get_config(self):\r\n config = {\r\n \"num_units\": self._num_units,\r\n \"use_peepholes\": self._use_peepholes,\r\n \"cell_clip\": self._cell_clip,\r\n \"initializer\": initializers.serialize(self._initializer),\r\n \"num_proj\": self._num_proj,\r\n \"proj_clip\": self._proj_clip,\r\n \"num_unit_shards\": self._num_unit_shards,\r\n \"num_proj_shards\": self._num_proj_shards,\r\n \"forget_bias\": self._forget_bias,\r\n \"state_is_tuple\": self._state_is_tuple,\r\n \"activation\": activations.serialize(self._activation),\r\n \"reuse\": self._reuse,\r\n }\r\n base_config = super(LSTMCell, self).get_config()\r\n return dict(list(base_config.items()) + list(config.items()))\r\n\r\n\r\ndef _enumerated_map_structure_up_to(shallow_structure, map_fn, *args, **kwargs):\r\n ix = [0]\r\n def enumerated_fn(*inner_args, **inner_kwargs):\r\n r = map_fn(ix[0], *inner_args, **inner_kwargs)\r\n ix[0] += 1\r\n return r\r\n return nest.map_structure_up_to(shallow_structure,\r\n enumerated_fn, *args, **kwargs)\r\n\r\n\r\ndef _default_dropout_state_filter_visitor(substate):\r\n if isinstance(substate, LSTMStateTuple):\r\n # Do not perform dropout on the memory state.\r\n return LSTMStateTuple(c=False, h=True)\r\n elif isinstance(substate, tensor_array_ops.TensorArray):\r\n return False\r\n return True\r\n\r\n\r\n@tf_export(\"nn.rnn_cell.DropoutWrapper\")\r\nclass DropoutWrapper(RNNCell):\r\n \"\"\"Operator adding dropout to inputs and outputs of the given cell.\"\"\"\r\n\r\n def __init__(self, cell, input_keep_prob=1.0, output_keep_prob=1.0,\r\n state_keep_prob=1.0, variational_recurrent=False,\r\n input_size=None, dtype=None, seed=None,\r\n dropout_state_filter_visitor=None):\r\n \"\"\"Create a cell with added input, state, and/or output dropout.\r\n\r\n If `variational_recurrent` is set to `True` (**NOT** the default behavior),\r\n then the same dropout mask is applied at every step, as described in:\r\n\r\n Y. Gal, Z Ghahramani. \"A Theoretically Grounded Application of Dropout in\r\n Recurrent Neural Networks\". https://arxiv.org/abs/1512.05287\r\n\r\n Otherwise a different dropout mask is applied at every time step.\r\n\r\n Note, by default (unless a custom `dropout_state_filter` is provided),\r\n the memory state (`c` component of any `LSTMStateTuple`) passing through\r\n a `DropoutWrapper` is never modified. This behavior is described in the\r\n above article.\r\n\r\n Args:\r\n cell: an RNNCell, a projection to output_size is added to it.\r\n input_keep_prob: unit Tensor or float between 0 and 1, input keep\r\n probability; if it is constant and 1, no input dropout will be added.\r\n output_keep_prob: unit Tensor or float between 0 and 1, output keep\r\n probability; if it is constant and 1, no output dropout will be added.\r\n state_keep_prob: unit Tensor or float between 0 and 1, output keep\r\n probability; if it is constant and 1, no output dropout will be added.\r\n State dropout is performed on the outgoing states of the cell.\r\n **Note** the state components to which dropout is applied when\r\n `state_keep_prob` is in `(0, 1)` are also determined by\r\n the argument `dropout_state_filter_visitor` (e.g. by default dropout\r\n is never applied to the `c` component of an `LSTMStateTuple`).\r\n variational_recurrent: Python bool. If `True`, then the same\r\n dropout pattern is applied across all time steps per run call.\r\n If this parameter is set, `input_size` **must** be provided.\r\n input_size: (optional) (possibly nested tuple of) `TensorShape` objects\r\n containing the depth(s) of the input tensors expected to be passed in to\r\n the `DropoutWrapper`. Required and used **iff**\r\n `variational_recurrent = True` and `input_keep_prob < 1`.\r\n dtype: (optional) The `dtype` of the input, state, and output tensors.\r\n Required and used **iff** `variational_recurrent = True`.\r\n seed: (optional) integer, the randomness seed.\r\n dropout_state_filter_visitor: (optional), default: (see below). Function\r\n that takes any hierarchical level of the state and returns\r\n a scalar or depth=1 structure of Python booleans describing\r\n which terms in the state should be dropped out. In addition, if the\r\n function returns `True`, dropout is applied across this sublevel. If\r\n the function returns `False`, dropout is not applied across this entire\r\n sublevel.\r\n Default behavior: perform dropout on all terms except the memory (`c`)\r\n state of `LSTMCellState` objects, and don't try to apply dropout to\r\n `TensorArray` objects:\r\n ```\r\n def dropout_state_filter_visitor(s):\r\n if isinstance(s, LSTMCellState):\r\n # Never perform dropout on the c state.\r\n return LSTMCellState(c=False, h=True)\r\n elif isinstance(s, TensorArray):\r\n return False\r\n return True\r\n ```\r\n\r\n Raises:\r\n TypeError: if `cell` is not an `RNNCell`, or `keep_state_fn` is provided\r\n but not `callable`.\r\n ValueError: if any of the keep_probs are not between 0 and 1.\r\n \"\"\"\r\n super(DropoutWrapper, self).__init__()\r\n assert_like_rnncell(\"cell\", cell)\r\n\r\n if (dropout_state_filter_visitor is not None\r\n and not callable(dropout_state_filter_visitor)):\r\n raise TypeError(\"dropout_state_filter_visitor must be callable\")\r\n self._dropout_state_filter = (\r\n dropout_state_filter_visitor or _default_dropout_state_filter_visitor)\r\n with ops.name_scope(\"DropoutWrapperInit\"):\r\n def tensor_and_const_value(v):\r\n tensor_value = ops.convert_to_tensor(v)\r\n const_value = tensor_util.constant_value(tensor_value)\r\n return (tensor_value, const_value)\r\n for prob, attr in [(input_keep_prob, \"input_keep_prob\"),\r\n (state_keep_prob, \"state_keep_prob\"),\r\n (output_keep_prob, \"output_keep_prob\")]:\r\n tensor_prob, const_prob = tensor_and_const_value(prob)\r\n if const_prob is not None:\r\n if const_prob < 0 or const_prob > 1:\r\n raise ValueError(\"Parameter %s must be between 0 and 1: %d\"\r\n % (attr, const_prob))\r\n setattr(self, \"_%s\" % attr, float(const_prob))\r\n else:\r\n setattr(self, \"_%s\" % attr, tensor_prob)\r\n\r\n # Set cell, variational_recurrent, seed before running the code below\r\n self._cell = cell\r\n if isinstance(cell, checkpointable.CheckpointableBase):\r\n self._track_checkpointable(self._cell, name=\"cell\")\r\n self._variational_recurrent = variational_recurrent\r\n self._seed = seed\r\n\r\n self._recurrent_input_noise = None\r\n self._recurrent_state_noise = None\r\n self._recurrent_output_noise = None\r\n\r\n if variational_recurrent:\r\n if dtype is None:\r\n raise ValueError(\r\n \"When variational_recurrent=True, dtype must be provided\")\r\n\r\n def convert_to_batch_shape(s):\r\n # Prepend a 1 for the batch dimension; for recurrent\r\n # variational dropout we use the same dropout mask for all\r\n # batch elements.\r\n return array_ops.concat(\r\n ([1], tensor_shape.TensorShape(s).as_list()), 0)\r\n\r\n def batch_noise(s, inner_seed):\r\n shape = convert_to_batch_shape(s)\r\n return random_ops.random_uniform(shape, seed=inner_seed, dtype=dtype)\r\n\r\n if (not isinstance(self._input_keep_prob, numbers.Real) or\r\n self._input_keep_prob < 1.0):\r\n if input_size is None:\r\n raise ValueError(\r\n \"When variational_recurrent=True and input_keep_prob < 1.0 or \"\r\n \"is unknown, input_size must be provided\")\r\n self._recurrent_input_noise = _enumerated_map_structure_up_to(\r\n input_size,\r\n lambda i, s: batch_noise(s, inner_seed=self._gen_seed(\"input\", i)),\r\n input_size)\r\n self._recurrent_state_noise = _enumerated_map_structure_up_to(\r\n cell.state_size,\r\n lambda i, s: batch_noise(s, inner_seed=self._gen_seed(\"state\", i)),\r\n cell.state_size)\r\n self._recurrent_output_noise = _enumerated_map_structure_up_to(\r\n cell.output_size,\r\n lambda i, s: batch_noise(s, inner_seed=self._gen_seed(\"output\", i)),\r\n cell.output_size)\r\n\r\n def _gen_seed(self, salt_prefix, index):\r\n if self._seed is None:\r\n return None\r\n salt = \"%s_%d\" % (salt_prefix, index)\r\n string = (str(self._seed) + salt).encode(\"utf-8\")\r\n return int(hashlib.md5(string).hexdigest()[:8], 16) & 0x7FFFFFFF\r\n\r\n @property\r\n def wrapped_cell(self):\r\n return self._cell\r\n\r\n @property\r\n def state_size(self):\r\n return self._cell.state_size\r\n\r\n @property\r\n def output_size(self):\r\n return self._cell.output_size\r\n\r\n def zero_state(self, batch_size, dtype):\r\n with ops.name_scope(type(self).__name__ + \"ZeroState\", values=[batch_size]):\r\n return self._cell.zero_state(batch_size, dtype)\r\n\r\n def _variational_recurrent_dropout_value(\r\n self, index, value, noise, keep_prob):\r\n \"\"\"Performs dropout given the pre-calculated noise tensor.\"\"\"\r\n # uniform [keep_prob, 1.0 + keep_prob)\r\n random_tensor = keep_prob + noise\r\n\r\n # 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)\r\n binary_tensor = math_ops.floor(random_tensor)\r\n ret = math_ops.div(value, keep_prob) * binary_tensor\r\n ret.set_shape(value.get_shape())\r\n return ret\r\n\r\n def _dropout(self, values, salt_prefix, recurrent_noise, keep_prob,\r\n shallow_filtered_substructure=None):\r\n \"\"\"Decides whether to perform standard dropout or recurrent dropout.\"\"\"\r\n\r\n if shallow_filtered_substructure is None:\r\n # Put something so we traverse the entire structure; inside the\r\n # dropout function we check to see if leafs of this are bool or not.\r\n shallow_filtered_substructure = values\r\n\r\n if not self._variational_recurrent:\r\n def dropout(i, do_dropout, v):\r\n if not isinstance(do_dropout, bool) or do_dropout:\r\n return nn_ops.dropout(\r\n v, keep_prob=keep_prob, seed=self._gen_seed(salt_prefix, i))\r\n else:\r\n return v\r\n return _enumerated_map_structure_up_to(\r\n shallow_filtered_substructure, dropout,\r\n *[shallow_filtered_substructure, values])\r\n else:\r\n def dropout(i, do_dropout, v, n):\r\n if not isinstance(do_dropout, bool) or do_dropout:\r\n return self._variational_recurrent_dropout_value(i, v, n, keep_prob)\r\n else:\r\n return v\r\n return _enumerated_map_structure_up_to(\r\n shallow_filtered_substructure, dropout,\r\n *[shallow_filtered_substructure, values, recurrent_noise])\r\n\r\n def __call__(self, inputs, state, input_nextt_gate, scope=None):\r\n \"\"\"Run the cell with the declared dropouts.\"\"\"\r\n def _should_dropout(p):\r\n return (not isinstance(p, float)) or p < 1\r\n\r\n if _should_dropout(self._input_keep_prob):\r\n inputs = self._dropout(inputs, \"input\",\r\n self._recurrent_input_noise,\r\n self._input_keep_prob)\r\n output, new_state = self._cell(inputs, state, input_nextt_gate, scope=scope)\r\n if _should_dropout(self._state_keep_prob):\r\n # Identify which subsets of the state to perform dropout on and\r\n # which ones to keep.\r\n shallow_filtered_substructure = nest.get_traverse_shallow_structure(\r\n self._dropout_state_filter, new_state)\r\n new_state = self._dropout(new_state, \"state\",\r\n self._recurrent_state_noise,\r\n self._state_keep_prob,\r\n shallow_filtered_substructure)\r\n if _should_dropout(self._output_keep_prob):\r\n output = self._dropout(output, \"output\",\r\n self._recurrent_output_noise,\r\n self._output_keep_prob)\r\n return output, new_state\r\n\r\n\r\n@tf_export(\"nn.rnn_cell.ResidualWrapper\")\r\nclass ResidualWrapper(RNNCell):\r\n \"\"\"RNNCell wrapper that ensures cell inputs are added to the outputs.\"\"\"\r\n\r\n def __init__(self, cell, residual_fn=None):\r\n \"\"\"Constructs a `ResidualWrapper` for `cell`.\r\n\r\n Args:\r\n cell: An instance of `RNNCell`.\r\n residual_fn: (Optional) The function to map raw cell inputs and raw cell\r\n outputs to the actual cell outputs of the residual network.\r\n Defaults to calling nest.map_structure on (lambda i, o: i + o), inputs\r\n and outputs.\r\n \"\"\"\r\n super(ResidualWrapper, self).__init__()\r\n self._cell = cell\r\n if isinstance(cell, checkpointable.CheckpointableBase):\r\n self._track_checkpointable(self._cell, name=\"cell\")\r\n self._residual_fn = residual_fn\r\n\r\n @property\r\n def state_size(self):\r\n return self._cell.state_size\r\n\r\n @property\r\n def output_size(self):\r\n return self._cell.output_size\r\n\r\n def zero_state(self, batch_size, dtype):\r\n with ops.name_scope(type(self).__name__ + \"ZeroState\", values=[batch_size]):\r\n return self._cell.zero_state(batch_size, dtype)\r\n\r\n def __call__(self, inputs, state, scope=None):\r\n \"\"\"Run the cell and then apply the residual_fn on its inputs to its outputs.\r\n\r\n Args:\r\n inputs: cell inputs.\r\n state: cell state.\r\n scope: optional cell scope.\r\n\r\n Returns:\r\n Tuple of cell outputs and new state.\r\n\r\n Raises:\r\n TypeError: If cell inputs and outputs have different structure (type).\r\n ValueError: If cell inputs and outputs have different structure (value).\r\n \"\"\"\r\n outputs, new_state = self._cell(inputs, state, scope=scope)\r\n # Ensure shapes match\r\n def assert_shape_match(inp, out):\r\n inp.get_shape().assert_is_compatible_with(out.get_shape())\r\n def default_residual_fn(inputs, outputs):\r\n nest.assert_same_structure(inputs, outputs)\r\n nest.map_structure(assert_shape_match, inputs, outputs)\r\n return nest.map_structure(lambda inp, out: inp + out, inputs, outputs)\r\n res_outputs = (self._residual_fn or default_residual_fn)(inputs, outputs)\r\n return (res_outputs, new_state)\r\n\r\n\r\n@tf_export(\"nn.rnn_cell.DeviceWrapper\")\r\nclass DeviceWrapper(RNNCell):\r\n \"\"\"Operator that ensures an RNNCell runs on a particular device.\"\"\"\r\n\r\n def __init__(self, cell, device):\r\n \"\"\"Construct a `DeviceWrapper` for `cell` with device `device`.\r\n\r\n Ensures the wrapped `cell` is called with `tf.device(device)`.\r\n\r\n Args:\r\n cell: An instance of `RNNCell`.\r\n device: A device string or function, for passing to `tf.device`.\r\n \"\"\"\r\n super(DeviceWrapper, self).__init__()\r\n self._cell = cell\r\n if isinstance(cell, checkpointable.CheckpointableBase):\r\n self._track_checkpointable(self._cell, name=\"cell\")\r\n self._device = device\r\n\r\n @property\r\n def state_size(self):\r\n return self._cell.state_size\r\n\r\n @property\r\n def output_size(self):\r\n return self._cell.output_size\r\n\r\n def zero_state(self, batch_size, dtype):\r\n with ops.name_scope(type(self).__name__ + \"ZeroState\", values=[batch_size]):\r\n with ops.device(self._device):\r\n return self._cell.zero_state(batch_size, dtype)\r\n\r\n def __call__(self, inputs, state, scope=None):\r\n \"\"\"Run the cell on specified device.\"\"\"\r\n with ops.device(self._device):\r\n return self._cell(inputs, state, scope=scope)\r\n\r\n\r\n@tf_export(v1=[\"nn.rnn_cell.MultiRNNCell\"])\r\nclass MultiRNNCell(RNNCell):\r\n \"\"\"RNN cell composed sequentially of multiple simple cells.\r\n\r\n Example:\r\n\r\n ```python\r\n num_units = [128, 64]\r\n cells = [BasicLSTMCell(num_units=n) for n in num_units]\r\n stacked_rnn_cell = MultiRNNCell(cells)\r\n ```\r\n \"\"\"\r\n\r\n @deprecated(None, \"This class is equivalent as \"\r\n \"tf.keras.layers.StackedRNNCells, and will be replaced by \"\r\n \"that in Tensorflow 2.0.\")\r\n def __init__(self, cells, state_is_tuple=True):\r\n \"\"\"Create a RNN cell composed sequentially of a number of RNNCells.\r\n\r\n Args:\r\n cells: list of RNNCells that will be composed in this order.\r\n state_is_tuple: If True, accepted and returned states are n-tuples, where\r\n `n = len(cells)`. If False, the states are all\r\n concatenated along the column axis. This latter behavior will soon be\r\n deprecated.\r\n\r\n Raises:\r\n ValueError: if cells is empty (not allowed), or at least one of the cells\r\n returns a state tuple but the flag `state_is_tuple` is `False`.\r\n \"\"\"\r\n super(MultiRNNCell, self).__init__()\r\n if not cells:\r\n raise ValueError(\"Must specify at least one cell for MultiRNNCell.\")\r\n if not nest.is_sequence(cells):\r\n raise TypeError(\r\n \"cells must be a list or tuple, but saw: %s.\" % cells)\r\n\r\n if len(set([id(cell) for cell in cells])) < len(cells):\r\n logging.log_first_n(logging.WARN,\r\n \"At least two cells provided to MultiRNNCell \"\r\n \"are the same object and will share weights.\", 1)\r\n\r\n self._cells = cells\r\n for cell_number, cell in enumerate(self._cells):\r\n # Add Checkpointable dependencies on these cells so their variables get\r\n # saved with this object when using object-based saving.\r\n if isinstance(cell, checkpointable.CheckpointableBase):\r\n # TODO(allenl): Track down non-Checkpointable callers.\r\n self._track_checkpointable(cell, name=\"cell-%d\" % (cell_number,))\r\n self._state_is_tuple = state_is_tuple\r\n if not state_is_tuple:\r\n if any(nest.is_sequence(c.state_size) for c in self._cells):\r\n raise ValueError(\"Some cells return tuples of states, but the flag \"\r\n \"state_is_tuple is not set. State sizes are: %s\"\r\n % str([c.state_size for c in self._cells]))\r\n\r\n @property\r\n def state_size(self):\r\n if self._state_is_tuple:\r\n return tuple(cell.state_size for cell in self._cells)\r\n else:\r\n return sum(cell.state_size for cell in self._cells)\r\n\r\n @property\r\n def output_size(self):\r\n return self._cells[-1].output_size\r\n\r\n def zero_state(self, batch_size, dtype):\r\n with ops.name_scope(type(self).__name__ + \"ZeroState\", values=[batch_size]):\r\n if self._state_is_tuple:\r\n return tuple(cell.zero_state(batch_size, dtype) for cell in self._cells)\r\n else:\r\n # We know here that state_size of each cell is not a tuple and\r\n # presumably does not contain TensorArrays or anything else fancy\r\n return super(MultiRNNCell, self).zero_state(batch_size, dtype)\r\n\r\n @property\r\n def trainable_weights(self):\r\n if not self.trainable:\r\n return []\r\n weights = []\r\n for cell in self._cells:\r\n if isinstance(cell, base_layer.Layer):\r\n weights += cell.trainable_weights\r\n return weights\r\n\r\n @property\r\n def non_trainable_weights(self):\r\n weights = []\r\n for cell in self._cells:\r\n if isinstance(cell, base_layer.Layer):\r\n weights += cell.non_trainable_weights\r\n if not self.trainable:\r\n trainable_weights = []\r\n for cell in self._cells:\r\n if isinstance(cell, base_layer.Layer):\r\n trainable_weights += cell.trainable_weights\r\n return trainable_weights + weights\r\n return weights\r\n\r\n def call(self, inputs, state):\r\n \"\"\"Run this multi-layer cell on inputs, starting from state.\"\"\"\r\n cur_state_pos = 0\r\n cur_inp = inputs\r\n new_states = []\r\n for i, cell in enumerate(self._cells):\r\n with vs.variable_scope(\"cell_%d\" % i):\r\n if self._state_is_tuple:\r\n if not nest.is_sequence(state):\r\n raise ValueError(\r\n \"Expected state to be a tuple of length %d, but received: %s\" %\r\n (len(self.state_size), state))\r\n cur_state = state[i]\r\n else:\r\n cur_state = array_ops.slice(state, [0, cur_state_pos],\r\n [-1, cell.state_size])\r\n cur_state_pos += cell.state_size\r\n cur_inp, new_state = cell(cur_inp, cur_state)\r\n new_states.append(new_state)\r\n\r\n new_states = (tuple(new_states) if self._state_is_tuple else\r\n array_ops.concat(new_states, 1))\r\n\r\n return cur_inp, new_states\r\n"
] | [
[
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.python.ops.array_ops.split",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.framework.ops.device",
"tensorflow.python.ops.variables.trainable_variables",
"tensorflow.python.ops.math_ops.floor",
"tensorflow.python.ops.init_ops.constant_initializer",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.ops.partitioned_variables.fixed_size_partitioner",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.platform.tf_logging.log_first_n",
"tensorflow.python.ops.clip_ops.clip_by_value",
"tensorflow.python.framework.tensor_util.constant_value",
"tensorflow.python.ops.nn_ops.bias_add",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.ops.math_ops.matmul",
"tensorflow.python.util.nest.map_structure",
"tensorflow.python.util.deprecation.deprecated",
"tensorflow.python.ops.array_ops.slice",
"tensorflow.python.util.nest.is_sequence",
"tensorflow.python.framework.tensor_util.is_tensor",
"tensorflow.python.layers.base.Layer.__call__",
"tensorflow.python.util.nest.map_structure_up_to",
"tensorflow.python.ops.variable_scope.get_variable_scope",
"tensorflow.python.ops.math_ops.div",
"tensorflow.python.keras.activations.get",
"tensorflow.python.util.nest.get_traverse_shallow_structure",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.eager.context.num_gpus",
"tensorflow.python.ops.math_ops.sigmoid",
"tensorflow.python.keras.activations.serialize",
"tensorflow.python.ops.array_ops.concat",
"tensorflow.python.platform.tf_logging.warn",
"tensorflow.python.util.nest.assert_same_structure",
"tensorflow.python.ops.init_ops.zeros_initializer",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.keras.engine.input_spec.InputSpec",
"tensorflow.python.keras.initializers.get",
"tensorflow.python.framework.tensor_shape.as_shape",
"tensorflow.python.ops.array_ops.expand_dims",
"tensorflow.python.keras.initializers.serialize",
"tensorflow.python.framework.constant_op.constant"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.8",
"2.10"
]
}
] |
mpriessner/CAFI | [
"4dac24cbd65a5cabf741b87d9521f6bbab54b124"
] | [
"ZS4Mic/codes/data_scripts/create_lmdb_mp.py"
] | [
"'''create lmdb files for Vimeo90K-7 frames training dataset (multiprocessing)\nWill read all the images to the memory\n'''\n\nimport os,sys\nimport os.path as osp\nimport glob\nimport pickle\nfrom multiprocessing import Pool\nimport numpy as np\nimport lmdb\nimport cv2\ntry:\n sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))\n import data.util as data_util\n import utils.util as util\nexcept ImportError:\n pass\n\n\ndef reading_image_worker(path, key):\n '''worker for reading images'''\n img = cv2.imread(path, cv2.IMREAD_UNCHANGED)\n return (key, img)\n\ndef vimeo7():\n '''create lmdb for the Vimeo90K-7 frames dataset, each image with fixed size\n GT: [3, 256, 448]\n Only need the 4th frame currently, e.g., 00001_0001_4\n LR: [3, 64, 112]\n With 1st - 7th frames, e.g., 00001_0001_1, ..., 00001_0001_7\n key:\n Use the folder and subfolder names, w/o the frame index, e.g., 00001_0001\n '''\n #### configurations\n mode = 'GT' # GT | LR\n batch = 3000 # TODO: depending on your mem size\n if mode == 'GT':\n img_folder = '/data/datasets/SR/vimeo_septuplet/sequences/train'\n lmdb_save_path = '/data/datasets/SR/vimeo_septuplet/vimeo7_train_GT.lmdb'\n txt_file = '/data/datasets/SR/vimeo_septuplet/sep_trainlist.txt'\n H_dst, W_dst = 256, 448\n elif mode == 'LR':\n img_folder = '/data/datasets/SR/vimeo_septuplet/sequences_LR/LR/x4/train'\n lmdb_save_path = '/data/datasets/SR/vimeo_septuplet/vimeo7_train_LR7.lmdb'\n txt_file = '/data/datasets/SR/vimeo_septuplet/sep_trainlist.txt'\n H_dst, W_dst = 64, 112\n n_thread = 40\n ########################################################\n if not lmdb_save_path.endswith('.lmdb'):\n raise ValueError(\"lmdb_save_path must end with \\'lmdb\\'.\")\n #### whether the lmdb file exist\n if osp.exists(lmdb_save_path):\n print('Folder [{:s}] already exists. Exit...'.format(lmdb_save_path))\n sys.exit(1)\n\n #### read all the image paths to a list\n print('Reading image path list ...')\n with open(txt_file) as f:\n train_l = f.readlines()\n train_l = [v.strip() for v in train_l]\n all_img_list = []\n keys = []\n for line in train_l:\n folder = line.split('/')[0]\n sub_folder = line.split('/')[1]\n file_l = glob.glob(osp.join(img_folder, folder, sub_folder) + '/*')\n all_img_list.extend(file_l)\n for j in range(7):\n keys.append('{}_{}_{}'.format(folder, sub_folder, j + 1))\n all_img_list = sorted(all_img_list)\n keys = sorted(keys)\n if mode == 'GT': \n all_img_list = [v for v in all_img_list if v.endswith('.png')]\n keys = [v for v in keys]\n print('Calculating the total size of images...')\n data_size = sum(os.stat(v).st_size for v in all_img_list)\n\n #### read all images to memory (multiprocessing)\n print('Read images with multiprocessing, #thread: {} ...'.format(n_thread))\n \n #### create lmdb environment\n env = lmdb.open(lmdb_save_path, map_size=data_size * 10)\n txn = env.begin(write=True) # txn is a Transaction object\n\n #### write data to lmdb\n pbar = util.ProgressBar(len(all_img_list))\n\n i = 0\n for path, key in zip(all_img_list, keys):\n pbar.update('Write {}'.format(key))\n img = cv2.imread(path, cv2.IMREAD_UNCHANGED)\n key_byte = key.encode('ascii')\n H, W, C = img.shape # fixed shape\n assert H == H_dst and W == W_dst and C == 3, 'different shape.'\n txn.put(key_byte, img)\n i += 1\n if i % batch == 1:\n txn.commit()\n txn = env.begin(write=True)\n\n txn.commit()\n env.close()\n print('Finish reading and writing {} images.'.format(len(all_img_list)))\n \n print('Finish writing lmdb.')\n\n #### create meta information\n meta_info = {}\n if mode == 'GT':\n meta_info['name'] = 'Vimeo7_train_GT'\n elif mode == 'LR':\n meta_info['name'] = 'Vimeo7_train_LR7'\n meta_info['resolution'] = '{}_{}_{}'.format(3, H_dst, W_dst)\n key_set = set()\n for key in keys:\n a, b, _ = key.split('_')\n key_set.add('{}_{}'.format(a, b))\n meta_info['keys'] = key_set\n pickle.dump(meta_info, open(osp.join(lmdb_save_path, 'Vimeo7_train_keys.pkl'), \"wb\"))\n print('Finish creating lmdb meta info.')\n\ndef test_lmdb(dataroot, dataset='vimeo7'):\n env = lmdb.open(dataroot, readonly=True, lock=False, readahead=False, meminit=False)\n meta_info = pickle.load(open(osp.join(dataroot, 'meta_info.pkl'), \"rb\"))\n print('Name: ', meta_info['name'])\n print('Resolution: ', meta_info['resolution'])\n print('# keys: ', len(meta_info['keys']))\n # read one image\n if dataset == 'vimeo7':\n key = '00001_0001_4'\n else:\n raise NameError('Please check the filename format.')\n print('Reading {} for test.'.format(key))\n with env.begin(write=False) as txn:\n buf = txn.get(key.encode('ascii'))\n img_flat = np.frombuffer(buf, dtype=np.uint8)\n C, H, W = [int(s) for s in meta_info['resolution'].split('_')]\n img = img_flat.reshape(H, W, C)\n cv2.imwrite('test.png', img)\n\n\nif __name__ == \"__main__\":\n vimeo7()\n test_lmdb('/data/datasets/SR/vimeo_septuplet/vimeo7_train_GT.lmdb', 'vimeo7')\n"
] | [
[
"numpy.frombuffer"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Challyfilio/GAIIC2022-itmatch | [
"55eb1f762dec2d9fe859ed9caafd35cfcd125de6"
] | [
"src/training/train.py"
] | [
"import os\nimport time\nimport json\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nfrom torch.cuda.amp import autocast\nimport torch.distributed as dist\n\nfrom zero_shot import zero_shot_eval\nfrom clip.clip import _transform, load, tokenize\n\nimport sys\nimport pdb\nimport wandb\n\nimport logging\n\ndef is_master(args):\n return (not args.distributed) or args.gpu == 0\n\ndef get_loss(model, images, texts, loss_img, loss_txt, args):\n image_features, text_features, logit_scale = model(images, texts)\n logit_scale = logit_scale.mean()\n if args.distributed and args.aggregate:\n world_size = dist.get_world_size()\n rank = dist.get_rank()\n\n # We gather tensors from all gpus to get more negatives to contrast with.\n gathered_image_features = [\n torch.zeros_like(image_features) for _ in range(world_size)\n ]\n gathered_text_features = [\n torch.zeros_like(text_features) for _ in range(world_size)\n ]\n dist.all_gather(gathered_image_features, image_features)\n dist.all_gather(gathered_text_features, text_features)\n\n all_image_features = torch.cat(\n [image_features]\n + gathered_image_features[:rank]\n + gathered_image_features[rank + 1 :]\n )\n all_text_features = torch.cat(\n [text_features]\n + gathered_text_features[:rank]\n + gathered_text_features[rank + 1 :]\n )\n\n # this is needed to send gradients back everywhere.\n logits_per_image = logit_scale * all_image_features @ all_text_features.t()\n logits_per_text = logits_per_image.t()\n\n else:\n logits_per_image = logit_scale * image_features @ text_features.t()\n logits_per_text = logit_scale * text_features @ image_features.t()\n\n ground_truth = torch.arange(len(logits_per_image)).long()\n if args.gpu is not None:\n ground_truth = ground_truth.cuda(args.gpu, non_blocking=True)\n\n total_loss = (\n loss_img(logits_per_image, ground_truth)\n + loss_txt(logits_per_text, ground_truth)\n ) / 2\n return total_loss\n\n\ndef train(model, data, epoch, optimizer, scaler, scheduler, args, tb_writer=None):\n os.environ[\"WDS_EPOCH\"] = str(epoch)\n \n model.train()\n\n dataloader, sampler = data['train'].dataloader, data['train'].sampler\n # print(data['train'])\n\n loss_img = nn.CrossEntropyLoss()\n loss_txt = nn.CrossEntropyLoss()\n if args.gpu is not None:\n loss_img = loss_img.cuda(args.gpu)\n loss_txt = loss_txt.cuda(args.gpu)\n\n if args.distributed and sampler is not None:\n sampler.set_epoch(epoch)\n\n num_batches_per_epoch = dataloader.num_batches\n\n end = time.time()\n for i, batch in enumerate(dataloader):\n step = num_batches_per_epoch * epoch + i\n scheduler(step)\n\n optimizer.zero_grad()\n\n images, texts = batch\n tokens = tokenize(texts)\n if args.gpu is not None:\n images = images.cuda(args.gpu, non_blocking=True)\n tokens = {k: v.cuda(args.gpu, non_blocking=True) for k, v in tokens.items()}\n\n data_time = time.time() - end\n\n m = model.module if args.distributed or args.dp else model\n\n # with automatic mixed precision.\n if args.precision == \"amp\":\n with autocast():\n total_loss = get_loss(model, images, tokens, loss_img, loss_txt, args)\n scaler.scale(total_loss).backward()\n scaler.step(optimizer)\n scaler.update()\n\n else:\n total_loss = get_loss(model, images, tokens, loss_img, loss_txt, args)\n total_loss.backward()\n optimizer.step()\n\n # Note: we clamp to 4.6052 = ln(100), as in the original paper.\n m.logit_scale.data = torch.clamp(m.logit_scale.data, 0, 4.6052)\n\n batch_time = time.time() - end\n end = time.time()\n\n if is_master(args) and (i % 100) == 0:\n samples_per_epoch = dataloader.num_samples\n percent_complete = 100.0 * i / num_batches_per_epoch\n logging.info(\n f\"Train Epoch: {epoch} [{i}/{num_batches_per_epoch} ({percent_complete:.0f}%)]\\t\"\n f\"Loss: {total_loss.item():.6f}\\tData (t) {data_time:.3f}\\tBatch (t) {batch_time:.3f}\"\n f\"\\tLR: {optimizer.param_groups[0]['lr']:5f}\\tlogit_scale {m.logit_scale.data:.3f}\"\n )\n # save train loss / etc.\n\n timestep = epoch * num_batches_per_epoch + i\n log_data = {\n \"loss\": total_loss.item(),\n \"data_time\": data_time,\n \"batch_time\": batch_time,\n \"scale\": m.logit_scale.data.item(),\n \"lr\": optimizer.param_groups[0][\"lr\"]\n }\n\n for name, val in log_data.items():\n name = \"train/\" + name\n if tb_writer is not None:\n tb_writer.add_scalar(name, val, timestep)\n if args.wandb:\n wandb.log({name: val, 'step': timestep})\n\n\ndef evaluate(model, data, epoch, args, tb_writer=None, steps=None):\n if not is_master(args):\n return\n \n model.eval()\n\n zero_shot_metrics = zero_shot_eval(model, data, epoch, args)\n\n dataloader = data['val'].dataloader\n\n loss_img = nn.CrossEntropyLoss()\n loss_txt = nn.CrossEntropyLoss()\n if args.gpu is not None:\n loss_img = loss_img.cuda(args.gpu)\n loss_txt = loss_txt.cuda(args.gpu)\n\n cumulative_loss = 0.0\n num_elements = 0.0\n all_image_features, all_text_features = [], []\n with torch.no_grad():\n for batch in dataloader:\n images, texts = batch\n tokens = tokenize(texts)\n if args.gpu is not None:\n images = images.cuda(args.gpu, non_blocking=True)\n tokens = {k: v.cuda(args.gpu, non_blocking=True) for k, v in tokens.items()}\n\n image_features, text_features, logit_scale = model(images, tokens)\n all_image_features.append(image_features)\n all_text_features.append(text_features)\n logit_scale = logit_scale.mean()\n logits_per_image = logit_scale * image_features @ text_features.t()\n logits_per_text = logits_per_image.t()\n\n ground_truth = torch.arange(len(images)).long()\n if args.gpu is not None:\n ground_truth = ground_truth.cuda(args.gpu, non_blocking=True)\n total_loss = (\n loss_img(logits_per_image, ground_truth)\n + loss_txt(logits_per_text, ground_truth)\n ) / 2\n\n batch_size = len(images)\n cumulative_loss += total_loss * batch_size\n num_elements += batch_size\n\n metrics = get_metrics(\n image_features=torch.cat(all_image_features),\n text_features=torch.cat(all_text_features),\n logit_scale=logit_scale\n )\n loss = cumulative_loss / num_elements\n metrics.update(\n **{\"val_loss\": loss.item(), \"epoch\": epoch, \"num_elements\": num_elements}\n )\n metrics.update(zero_shot_metrics)\n\n logging.info(\n f\"Eval Epoch: {epoch} \"\n + \"\\t\".join([f\"{k}: {v:.4f}\" for k, v in metrics.items()])\n )\n\n if args.save_logs:\n for name, val in metrics.items():\n if tb_writer is not None:\n tb_writer.add_scalar(f\"val/{name}\", val, epoch)\n if args.wandb:\n for name, val in metrics.items():\n wandb.log({f\"val/{name}\": val, 'epoch': epoch})\n\n if args.save_logs:\n with open(os.path.join(args.checkpoint_path, \"results.jsonl\"), \"a+\") as f:\n f.write(json.dumps(metrics))\n f.write(\"\\n\")\n\n return metrics\n\n\ndef get_metrics(image_features, text_features, logit_scale):\n metrics = {}\n logits_per_image = (logit_scale * image_features @ text_features.t()).detach().cpu()\n logits_per_text = logits_per_image.t().detach().cpu()\n\n logits = {\"image_to_text\": logits_per_image, \"text_to_image\": logits_per_text}\n ground_truth = torch.arange(len(text_features)).view(-1, 1)\n\n for name, logit in logits.items():\n ranking = torch.argsort(logit, descending=True)\n preds = torch.where(ranking == ground_truth)[1]\n preds = preds.detach().cpu().numpy()\n metrics[f\"{name}_mean_rank\"] = preds.mean() + 1\n metrics[f\"{name}_median_rank\"] = np.floor(np.median(preds)) + 1\n for k in [1, 5, 10]:\n metrics[f\"{name}_R@{k}\"] = np.mean(preds < k)\n\n return metrics\n"
] | [
[
"torch.nn.CrossEntropyLoss",
"torch.clamp",
"torch.cat",
"torch.argsort",
"numpy.median",
"torch.distributed.all_gather",
"torch.zeros_like",
"torch.cuda.amp.autocast",
"torch.no_grad",
"numpy.mean",
"torch.where",
"torch.distributed.get_rank",
"torch.distributed.get_world_size"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
piyushrpt/fringe | [
"63388b96b98940d84f981899f955cdb4382a2c71"
] | [
"tests/wrapped_phase_velocity/test1.py"
] | [
"#!/usr/bin/env python3\n\nimport numpy as np\nfrom scipy.spatial import Delaunay\nimport matplotlib.pyplot as plt\n\n\nBaseline = np.array([ 0. , 202.23261006 , 247.67336194 , 157.46570522 , -3.03759106,\n 146.51305542, 432.34588205 , 129.9950411 , 304.6576168 , 342.39451334,\n 77.48752496, 35.375345 , 49.16112925 ,-291.19738937 , 525.84622291,\n 131.16981696, -73.74287393 ,-267.98532137 , 126.57065401 , 51.46784891,\n -137.74090081, 204.51096416 , 519.05312568 , 75.56740286 ,-253.08744983,\n 321.84328088, 372.77095751 , 322.70861019 , 239.31234022 , -81.07387604,\n 132.89024919, -71.70800096 , 210.09229394 , -47.12478361 , 312.45312082,\n 152.03018981, 366.71227489 , 310.07070069 ,-216.6017471 , -85.26060589])\n\n\ndef grid_search(cpxPhase, K, DEM_error_range):\n\n gamma = np.zeros_like(DEM_error_range, dtype=np.float64)\n for ii, dz in enumerate(DEM_error_range):\n pred_cpxphase = np.exp(1J*K*dz)\n dif = cpxPhase * np.conjugate(pred_cpxphase)\n tempCoh = np.abs(np.sum(dif)/len(dif))\n gamma[ii] = tempCoh\n #print(ii, tempCoh)\n\n maxIdx = np.argmax(gamma)\n #print(maxIdx, gamma[maxIdx])\n #print(\"##############################\")\n return DEM_error_range[maxIdx]\n\ndef grid_search_2D(cpxPhase, Kb, Kt, DEM_error_range, rate_range):\n\n gamma = np.zeros((len(DEM_error_range), len(rate_range)), dtype=np.float64)\n for ii, dz in enumerate(DEM_error_range):\n for jj,rate in enumerate(rate_range):\n pred_cpxphase = np.exp(1J*(Kb*dz+Kt*rate))\n dif = cpxPhase * np.conjugate(pred_cpxphase)\n tempCoh = np.abs(np.sum(dif)/len(dif))\n gamma[ii,jj] = tempCoh\n \n maxIdx = np.unravel_index(np.argmax(gamma, axis=None), gamma.shape)\n dz = DEM_error_range[maxIdx[0]]\n rate = rate_range[maxIdx[1]]\n #plt.imshow(gamma)\n #plt.show()\n #print(\"##############################\")\n return dz, rate\n\n\n\ndef estimate_dem_error(cpxPhase, wavelength, bperp, rng, theta, dt):\n\n PI = np.pi\n K = 4.0 * PI * bperp / (wavelength * rng * np.sin(theta))\n Kt = 4.0 * PI * dt/wavelength\n\n DEM_error_range = np.arange(-200,200,2)\n rate_range = np.arange(-0.3,0.3,0.01)\n dz, rate = grid_search_2D(cpxPhase, K, Kt, DEM_error_range, rate_range)\n\n #dz = grid_search(cpxPhase, K, DEM_error_range)\n \n DEM_error_range = np.arange(dz-10,dz+10,1) \n rate_range = np.arange(rate-0.01,rate+0.01,0.002)\n dz, rate = grid_search_2D(cpxPhase, K, Kt, DEM_error_range, rate_range)\n\n\n DEM_error_range = np.arange(dz-2,dz+2,0.1)\n rate_range = np.arange(rate-0.005,rate+0.005,0.001)\n dz, rate = grid_search_2D(cpxPhase, K, Kt, DEM_error_range, rate_range)\n\n #DEM_error_range = np.arange(dz-1,dz+1,.1)\n #dz = grid_search(cpxPhase, K, DEM_error_range)\n\n return dz, rate\n\n\nclass stack(object):\n def __init__(self, ySize=100, xSize=100, numDates=40):\n self.numDates= numDates\n self.ySize = ySize\n self.xSize = xSize\n self.wavelength = 0.056 \n self.r = 850000 # avergae range\n self.theta = 34.0 * np.pi/180.0\n\n def configure(self, dt = None, dB= None):\n self.stackSize = (self.ySize, self.xSize, self.numDates)\n if dt is None:\n dt = np.arange(self.numDates)*12.0/365.0\n\n if dB is None:\n dB = np.random.randn(self.numDates)*200\n\n self.dB = dB - dB[0]\n self.dt = dt\n self.signal = np.zeros(self.stackSize)\n self.dz = np.zeros((self.ySize, self.xSize))\n self.rate = np.zeros((self.ySize, self.xSize))\n self.coherence = np.ones((self.ySize, self.xSize))\n self.coherenceThreshold = 1.0\n def add_linear_signal(self, rate = None): #, dz=None):\n \n if rate is None:\n xCenter = int(self.xSize/2)\n yCenter = int(self.ySize/2)\n x,y = np.meshgrid(np.arange(self.xSize),np.arange(self.ySize))\n r = np.sqrt((x-xCenter)**2 + (y-yCenter)**2)\n r = (np.max(r) - r)\n\n radius = np.min((xCenter, yCenter))\n ind = r>radius\n \n\n rate = r.copy()\n \n min_rate = np.min(rate[ind])\n max_rate = np.max(rate[ind])\n rate = (rate-min_rate)/(max_rate-min_rate)\n\n rate[r<radius] = 0\n rate = rate * 0.1\n\n self.rate = rate\n\n for i in range(self.numDates):\n self.signal[:,:,i] = self.signal[:,:,i] + (4*np.pi/self.wavelength)*self.rate*self.dt[i]\n\n def add_dem_error(self, max_demError=50.0, dz=None):\n\n if dz is None:\n x,y = np.meshgrid(np.arange(self.xSize),np.arange(self.ySize))\n dz = 100*(np.sin(2*2*np.pi*x/self.xSize) + np.cos(2*2*np.pi*x/self.xSize))#+ np.sin(2*np.pi*x/2) + np.sin(2*np.pi*x/6) + np.sin(2*np.pi*x/10)\n\n dz = (dz - np.min(dz))/(np.max(dz)-np.min(dz))\n\n self.dz = max_demError*dz\n\n demErrorCoef = 4.0*np.pi/(self.wavelength*self.r*np.sin(self.theta))\n #self.signal = np.zeros(self.stackSize)\n for i in range(self.numDates):\n self.signal[:,:,i] = self.signal[:,:,i] + demErrorCoef*self.dB[i]*self.dz\n\n def add_nonlinear_deformation(self):\n for i in range(self.numDates):\n acceleration = self.rate/4.0\n self.signal[:,:,i] = self.signal[:,:,i] + (4*np.pi/self.wavelength)*acceleration*(self.dt[i]**2)\n\n def add_atmosphere(self, max_atmosphere):\n x,y = np.meshgrid(np.arange(self.xSize),np.arange(self.ySize))\n randomCoef_X = np.random.randn(self.numDates) \n randomCoef_Y = np.random.randn(self.numDates)\n for i in range(1,self.numDates):\n ramp = randomCoef_X[i]*x + randomCoef_Y[i]*y\n ramp = max_atmosphere*(ramp-np.min(ramp))/(np.max(ramp)-np.min(ramp))\n self.signal[:,:,i] = self.signal[:,:,i] + ramp\n\n def simulate_coherence(self):\n coh = np.random.rand(self.ySize, self.xSize)\n coh = (coh-np.min(coh))/(np.max(coh) - np.min(coh))\n\n self.coherence = coh\n\n def wrapped_phase(self, coherenceThreshold = 0.3):\n self.coherenceThreshold = coherenceThreshold\n self.phase = np.zeros(self.stackSize)\n for i in range(self.numDates):\n ph = st.signal[:,:,i]\n ph[st.coherence<coherenceThreshold] = np.nan\n self.phase[:,:,i] = np.angle(np.exp(1j*ph))\n\n\n def DelaunayTriangulation(self):\n ind = self.coherence>self.coherenceThreshold\n x,y = np.meshgrid(np.arange(self.xSize),np.arange(self.ySize))\n # coherent points\n points = np.vstack((x[ind],y[ind])).T\n self.tri = Delaunay(points)\n \n #self.tri = tri\n\n plt.imshow(self.phase[:,:,-1])\n plt.triplot(points[:,0], points[:,1], self.tri.simplices.copy())\n plt.plot(points[:,0], points[:,1], 'o')\n plt.show()\n\n self.tri_coords = points[self.tri.simplices]\n\n tt = self.tri_coords[-1]\n arc01 = self.phase[tt[0][1], tt[0][0],:] - self.phase[tt[1][1], tt[1][0],:]\n arc01_c = np.exp(1J*self.phase[tt[0][1], tt[0][0],:]) * np.exp(-1J*self.phase[tt[1][1], tt[1][0],:])\n\n arc_unw = self.signal[tt[0][1], tt[0][0],:] - self.signal[tt[1][1], tt[1][0],:]\n\n A=np.ones((self.numDates,2))\n A[:,0] = (4*np.pi/self.wavelength)*self.dt\n A[:,1] = 4.0*np.pi*self.dB/(self.wavelength*self.r*np.sin(self.theta))\n X = np.dot(np.linalg.pinv(A), arc01)\n X_c = np.dot(np.linalg.pinv(A), np.angle(arc01_c))\n\n #predicted_L = np.dot(A,X_c)\n #dz_gridSearch = coarse_grid_search(arc01_c, self.wavelength, self.dB, self.r, self.theta) \n dz_gridSearch, rate_gridSearch = estimate_dem_error(arc01_c, self.wavelength, self.dB, self.r, self.theta, self.dt)\n print(\"%%%%%%%%%%%%%%%%%%%%%%%\")\n print(\"simulated values (difference on the arc)\")\n print(\"rate: \" , self.rate[tt[0][1], tt[0][0]] - self.rate[tt[1][1], tt[1][0]])\n print(\"dZ: \" , self.dz[tt[0][1], tt[0][0]] - self.dz[tt[1][1], tt[1][0]])\n print(\"%%%%%%%%%%%%%%%%%%%%%%%\")\n '''print(\"estimated values\")\n print(\"observation = wrapped phase diff\")\n print(\"rate\", X[0])\n print(\"dz\", X[1])\n print(\" *************** \")\n print(\"observation = angle( (exp(1J*Phi) * exp(-1J*Phi) )\")\n print(\"rate\", X_c[0])\n print(\"dz\", X_c[1])\n print(\" *************** \")\n '''\n print(\"grid search\")\n print(\"rate: \", rate_gridSearch)\n print(\"dz: \", dz_gridSearch )\n print()\n print(\"%%%%%%%%%%%%%%%%%%%%%%%\")\n #arc12 = data[tt[1][1], tt[1][0]] - data[tt[2][1], tt[2][0]]\n #arc20 = data[tt[2][1], tt[2][0]] - data[tt[0][1], tt[0][0]]\n #print(tt)\n #print(arc01)\n #plt.plot(arc01)\n #plt.plot(np.angle(arc01_c))\n #plt.plot(arc_unw, '--')\n #plt.plot((arc_unw-predicted_L), '-^')\n #plt.show()\n\n def estimate_arcs(self):\n #coordinates of all triangle vertices\n #tri_coords = points[tri.simplices]\n\n # A design matrix for Least Square estimation\n #A = np.ones((self.numDates,2))\n #A[:,0] = (4*np.pi/self.wavelength)*self.dt\n #A[:,1] = 4.0*np.pi*self.dB/(self.wavelength*self.r*np.sin(self.theta))\n #A1 = np.linalg.pinv(A)\n\n #startVertex = []\n #endVertex = []\n arc = []\n rateDiff = []\n dzDiff = [] \n st = [0,1,2]\n en = [1,2,0]\n\n for ii in range(self.tri.nsimplex):\n print(ii, \" of \", self.tri.nsimplex)\n tt = self.tri_coords[ii]\n for jj in range(3):\n ss = st[jj]\n ee = en[jj]\n #startVertex.append((tt[ss][1], tt[ss][0]))\n #endVertex.append((tt[ee][1], tt[ee][0]))\n arcIdx = (tt[ss][1], tt[ss][0], tt[ee][1], tt[ee][0])\n if arcIdx not in arc:\n arc.append(arcIdx)\n arc_phase = np.exp(1J*self.phase[tt[ss][1], tt[ss][0],:]) * np.exp(-1J*self.phase[tt[ee][1], tt[ee][0],:])\n dz_gridSearch, rate_gridSearch = estimate_dem_error(arc_phase, self.wavelength, self.dB, self.r, self.theta, self.dt)\n rateDiff.append(rate_gridSearch)\n dzDiff.append(dz_gridSearch)\n #startVertex.append((tt[0][1], tt[0][0]))\n #endVertex.append((tt[1][1], tt[1][0]))\n #arc01 = np.exp(1J*self.phase[tt[0][1], tt[0][0],:]) * np.exp(-1J*self.phase[tt[1][1], tt[1][0],:])\n \n #X = np.dot(A1, np.angle(arc01))\n #rateDiff.append(X[0])\n #dzDiff.append(X[1])\n\n return arc, rateDiff, dzDiff\n\n def integrate_arcs_sparse(self, arc, rateDiff, dzDiff):\n rows = np.zeros((1,2*len(arc)))\n cols = np.zeros((1,2*len(arc)))\n data = np.zeros((1,2*len(arc)))\n #A = np.zeros((len(arc), self.xSize*self.ySize))\n for ii,aa in enumerate(arc):\n Yst = aa[0]\n Xst = aa[1]\n Yend = aa[2]\n Xend = aa[3]\n st = Yst*self.xSize + Xst\n end = Yend*self.xSize + Xend\n print(\"*******\")\n print(aa)\n print(st, end)\n A[ii, st] = -1.0\n A[ii, end] = 1.0\n cols[0,2*ii] = ii\n rows[0,2*ii] = st\n\n data[0,2*ii] = -1\n\n cols[0,2*ii+1] = ii\n rows[0,2*ii+1] = end\n data[0,2*ii+1] = 1\n\n A = coo_matrix((data, (row, col)), shape=((len(arc), self.xSize*self.ySize))) \n \n\n def integrate_arcs(self, arc, rateDiff, dzDiff):\n A = np.zeros((len(arc), self.xSize*self.ySize))\n for ii,aa in enumerate(arc):\n Yst = aa[0]\n Xst = aa[1]\n Yend = aa[2]\n Xend = aa[3]\n st = Yst*self.xSize + Xst\n end = Yend*self.xSize + Xend\n print(\"*******\")\n print(aa)\n print(st, end)\n A[ii, st] = -1.0\n A[ii, end] = 1.0\n\n\n\n Yref = 0\n Xref = 0\n refPixel = Yref*self.xSize + Xref\n A = np.hstack((A[:,0:refPixel], A[:,(refPixel+1):]))\n\n rankA = np.linalg.matrix_rank(A)\n print(\"size of design mat: \", A.shape)\n print(\"rank of A: \", rankA)\n rate = np.dot(np.linalg.pinv(A), np.array(rateDiff))\n dz = np.dot(np.linalg.pinv(A), np.array(dzDiff))\n\n dz = np.hstack((0,dz))\n rate = np.hstack((0,rate))\n\n rate = np.reshape(rate, (self.ySize, self.xSize))\n dz = np.reshape(dz, (self.ySize, self.xSize))\n\n return rate , dz\n\n def integrate_arcs_coh(self, arc, rateDiff, dzDiff):\n A = np.zeros((len(arc), self.xSize*self.ySize))\n pixelsIdx = [False] * self.xSize*self.ySize \n for ii,aa in enumerate(arc):\n Yst = aa[0]\n Xst = aa[1]\n Yend = aa[2]\n Xend = aa[3]\n st = Yst*self.xSize + Xst\n end = Yend*self.xSize + Xend\n print(\"*******\")\n print(aa)\n print(st, end)\n A[ii, st] = -1.0\n A[ii, end] = 1.0\n pixelsIdx[st] = True\n pixelsIdx[end] = True\n \n A = A[:, pixelsIdx]\n \n Yref = 0\n Xref = 0\n refPixel = Yref*self.xSize + Xref\n \n #refPixel = end\n #Yref = int(end/self.xSize)\n #Xref = end-Yref*self.xSize\n A = np.hstack((A[:,0:refPixel], A[:,(refPixel+1):]))\n\n rankA = np.linalg.matrix_rank(A) \n print(\"size of design mat: \", A.shape)\n print(\"rank of A: \", rankA)\n rate = np.dot(np.linalg.pinv(A), np.array(rateDiff))\n dz = np.dot(np.linalg.pinv(A), np.array(dzDiff))\n \n dz = np.hstack((0,dz))\n rate = np.hstack((0,rate))\n\n dz_all = np.zeros((self.xSize*self.ySize))\n rate_all = np.zeros((self.xSize*self.ySize))\n\n dz_all[pixelsIdx] = dz\n rate_all[pixelsIdx] = rate\n\n rate_all = np.reshape(rate_all, (self.ySize, self.xSize))\n dz_all = np.reshape(dz_all, (self.ySize, self.xSize))\n\n rate_all[self.coherence<self.coherenceThreshold] = np.nan\n dz_all[self.coherence<self.coherenceThreshold] = np.nan\n\n refPixel = end\n Yref = int(end/self.xSize)\n Xref = end-Yref*self.xSize\n\n rate_all = rate_all - rate_all[Yref, Xref]\n dz_all = dz_all - dz_all[Yref, Xref]\n\n return rate_all , dz_all, Xref, Yref\n#####################################\n\nst = stack()\nst.xSize = 256\nst.ySize = 256\nst.configure(dB=Baseline)\n\nst.add_linear_signal()\nst.add_dem_error(max_demError=50.0)\nst.add_atmosphere(max_atmosphere=10) # maximum atmosphere over the scene in radians\nst.add_nonlinear_deformation()\nst.simulate_coherence()\nst.wrapped_phase(coherenceThreshold = 0.3)\nst.DelaunayTriangulation()\narc, rateDiff, dzDiff = st.estimate_arcs()\n#rate , dz = st.integrate_arcs(arc, rateDiff, dzDiff)\nrate , dz, Xref, Yref = st.integrate_arcs_coh(arc, rateDiff, dzDiff)\n\nfig = plt.figure(figsize=(8,6))\nax1 = fig.add_subplot(2,3,1)\ncax1=ax1.imshow(st.dz-st.dz[Yref, Xref])\nax1.set_title(\"simulated DEM error\")\ncbar = fig.colorbar(cax1)\n\nax2 = fig.add_subplot(2,3,2)\ncax2=ax2.imshow(-1*dz)\nax2.set_title(\"estimated DEM error\")\ncbar = fig.colorbar(cax2)\n\nax3 = fig.add_subplot(2,3,3)\ncax3=ax3.imshow(st.dz -st.dz[Yref,Xref] + dz, vmin = -1, vmax = 1)\nax3.set_title(\"difference\")\ncbar = fig.colorbar(cax3)\n\nax4 = fig.add_subplot(2,3,4)\ncax4=ax4.imshow(st.rate-st.rate[Yref,Xref])\ncbar = fig.colorbar(cax4)\nax4.set_title(\"simulated rate\")\n\nax5 = fig.add_subplot(2,3,5)\ncax5=ax5.imshow(-1*rate)\ncbar = fig.colorbar(cax5)\nax5.set_title(\"estimated rate\")\n\nax6 = fig.add_subplot(2,3,6)\ncax6=ax6.imshow(st.rate -st.rate[Yref,Xref] + rate, vmin = -0.01, vmax = 0.01)\ncbar = fig.colorbar(cax6)\nax6.set_title(\"difference\")\n\n\nplt.savefig(\"simulation.png\")\n\nplt.show()\n\n#print(st.stackSize)\n#print(st.dt)\n#print(st.dB)\n\n#import matplotlib.pyplot as plt\n'''plt.imshow(st.displacement[:,:,-1])\nplt.imshow(np.angle(np.exp(1j*st.phase[:,:,-1])))\nplt.show()\nplt.plot(st.phase[125,125,:])\nplt.show()\n\nplt.imshow(st.coherence, cmap='gray')\nplt.show()\n'''\n\n#ph = st.phase[:,:,-1]\n#ph[st.coherence<0.3] = np.nan\n#ph = np.angle(np.exp(1j*ph))\n#plt.imshow(st.phase[:,:,-1])\n#plt.show()\n\n#plt.plot(st.signal[int(st.ySize/2), int(st.xSize/2),:])\n#plt.show()\n\n# Simulate displacement \n\n# Simulate DEM error\n\n# Simulate wrapped phase\n\n# Simulate average coherence (temporal coherence)\n\n# Delaunay triangulation of coherent pixels\n\n# Compue edge phases\n\n# estimate v and dz for edges\n\n\n"
] | [
[
"matplotlib.pyplot.imshow",
"numpy.linalg.matrix_rank",
"numpy.sqrt",
"matplotlib.pyplot.plot",
"numpy.max",
"numpy.zeros_like",
"numpy.random.randn",
"numpy.exp",
"numpy.conjugate",
"numpy.hstack",
"numpy.reshape",
"numpy.arange",
"numpy.sin",
"numpy.argmax",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.min",
"matplotlib.pyplot.savefig",
"numpy.random.rand",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.sum",
"scipy.spatial.Delaunay",
"numpy.cos",
"numpy.ones",
"numpy.linalg.pinv",
"numpy.angle",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
universea/MoRL | [
"499311cf41f9ef45b6941289ecbfb77cfd9288ec"
] | [
"benchmark/paddle/QuickStart/cartpole_agent.py"
] | [
"import morl\nimport paddle\nimport numpy as np\n\n\nclass CartpoleAgent(morl.Agent):\n \"\"\"Agent of Cartpole env.\n\n Args:\n algorithm(morl.Algorithm): algorithm used to solve the problem.\n\n \"\"\"\n\n def __init__(self, algorithm):\n super(CartpoleAgent, self).__init__(algorithm)\n\n def sample(self, obs):\n \"\"\"Sample an action when given an observation\n\n Args:\n obs(np.float32): shape of (obs_dim,)\n \n Returns:\n act(int): action\n \"\"\"\n obs = paddle.to_tensor(obs.astype(np.float32))\n prob = self.alg.predict(obs)\n prob = prob.numpy()\n act = np.random.choice(len(prob), 1, p=prob)[0]\n return act\n\n def predict(self, obs):\n \"\"\"Predict an action when given an observation\n\n Args:\n obs(np.float32): shape of (obs_dim,)\n \n Returns:\n act(int): action\n \"\"\"\n obs = paddle.to_tensor(obs.astype(np.float32))\n prob = self.alg.predict(obs)\n act = prob.argmax().numpy()[0]\n return act\n\n def learn(self, obs, act, reward):\n \"\"\"Update model with an episode data\n\n Args:\n obs(np.float32): shape of (batch_size, obs_dim)\n act(np.int64): shape of (batch_size)\n reward(np.float32): shape of (batch_size)\n \n Returns:\n loss(float)\n\n \"\"\"\n act = np.expand_dims(act, axis=-1)\n reward = np.expand_dims(reward, axis=-1)\n\n obs = paddle.to_tensor(obs.astype(np.float32))\n act = paddle.to_tensor(act.astype(np.int32))\n reward = paddle.to_tensor(reward.astype(np.float32))\n\n loss = self.alg.learn(obs, act, reward)\n return loss.numpy()[0]\n"
] | [
[
"numpy.expand_dims"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LordArma/cambrac | [
"c781679b59e7d7a39f05680c1892fea18478f883"
] | [
"cambrac/add_two_matrix.py"
] | [
"import cProfile\nimport io\nimport json\nimport pstats\nimport os\nimport matplotlib.pyplot as plt\n\n\ndef add_by(length, is_row=False):\n A = [[1 for i in range(length)] for j in range(length)]\n B = [[2 for i in range(length)] for j in range(length)]\n\n C = [[0 for i in range(length)] for j in range(length)]\n\n if is_row:\n for j in range(length):\n for i in range(length):\n C[i][j] = A[i][j] + B[i][j]\n else:\n for i in range(length):\n for j in range(length):\n C[i][j] = A[i][j] + B[i][j]\n\n\ndef add_by_row(length):\n add_by(length, True)\n\n\ndef add_by_col(length):\n add_by(length, False)\n\n\ndef simulate(Range=100, steps=1):\n rows = []\n cols = []\n\n test_prefix = \"Until\" + str(Range) + \"Step\" + str(steps) + \"/\"\n path = os.path.dirname(__file__) + \"/results/\" + test_prefix\n\n try:\n os.mkdir(path)\n except OSError:\n pass\n else:\n pass\n\n for i in range(1, Range, steps):\n pr = cProfile.Profile()\n pr.enable()\n add_by_row(i)\n pr.disable()\n s = io.StringIO()\n ps = pstats.Stats(pr, stream=s)\n ps.print_stats()\n result = s.getvalue().strip()\n result = result.partition('\\n')[0]\n result = result.split()[4]\n rows.append(float(result))\n\n with open(path + 'rows.txt', 'w+') as f:\n f.write(str(rows))\n\n for i in range(1, Range, steps):\n pr = cProfile.Profile()\n pr.enable()\n add_by_col(i)\n pr.disable()\n s = io.StringIO()\n ps = pstats.Stats(pr, stream=s)\n ps.print_stats()\n result = s.getvalue().strip()\n result = result.partition('\\n')[0]\n result = result.split()[4]\n cols.append(float(result))\n\n with open(path + 'cols.txt', 'w+') as f:\n f.write(str(cols))\n\n\ndef make_plt(Range=100, steps=1, is_fresh=True):\n if is_fresh:\n simulate(Range, steps)\n\n test_prefix = \"Until\" + str(Range) + \"Step\" + str(steps) + \"/\"\n path = os.path.dirname(__file__) + \"/results/\" + test_prefix\n\n myrows = json.load(open(path + 'rows.txt'))\n mycols = json.load(open(path + 'cols.txt'))\n\n fig, ax = plt.subplots()\n\n line1, = ax.plot(myrows, label=\"Rows\", linewidth=1, linestyle='-')\n line2, = ax.plot(mycols, label=\"Cols\", linewidth=1, linestyle='-')\n\n first_legend = ax.legend(handles=[line1], loc='upper right')\n ax.add_artist(first_legend)\n ax.legend(handles=[line2], loc='lower right')\n fig = plt.gcf()\n fig.canvas.set_window_title('Compare Add Two Matrix by Row & Col')\n plt.title(\"Result\")\n plt.savefig(path + 'plot.png', dpi=300, bbox_inches='tight')\n print(\"Image has been saved as \" + path + 'plot.png')\n\n\ndef main():\n Range = 500\n Steps = 1\n make_plt(Range, Steps)\n\n\nif __name__ == \"__main__\":\n main()\n\n"
] | [
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.title",
"matplotlib.pyplot.gcf"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Jbwasse2/snn-rl | [
"29b040655f432bd390bc9d835b86cbfdf1a622e4"
] | [
"furtherFormulas/3dBarChartGenerator.py"
] | [
"# from http://pythonprogramming.net/3d-bar-charts-python-matplotlib/\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport numpy as np\nimport pylab as pylab\n \nfig = plt.figure()\nax1 = fig.add_subplot(111, projection='3d')\n \nxpos = np.ones(60)\nxpos[15:30] *= 2\nxpos[30:45] *= 3\nxpos[45:60] *= 4\nypos = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\n\nnum_elements = len(xpos)\nzpos = np.zeros(60)\ndx = np.ones(60)*.1\ndy = np.ones(60)*.5\ndz = [0.90433194, 0.6139531, 0.50387484, 0.55220372, 0.51213536, 0.85443374, 0.99955922, 0.5039825, 0.73091913, 0.9780236, 0.5241028, 0.71571812, 0.93782861, 0.51210244, 0.73074697,\n\t0., 0., 0.03412608, 0., 0.90455366, 0.78683668, 0., 0.95912629, 0.7282637, 0., 0.78548583, 0.78935491, 0.03193823, 0.00609877, 0.17287094,\n\t0.4474444, 0., 0.98135641, 0., 0.96315942, 0., 0., 0., 0.15930208, 0., 0.77299245, 0., 0., 0.71739497, 0.02804206,\n\t0., 0., 0.99815102, 0., 0.9239562, 0., 0., 0.32862838, 0.29682383, 0., 0.85108903, 0., 0., 0., 0.6687179]\n\ncolors = ['r']*15+['g']*15+['b']*15+['y']*15\n\nxLabel = ax1.set_xlabel('\\nOutput Neuron', linespacing=1.2)\nyLabel = ax1.set_ylabel('\\nInput Neuron', linespacing=1.2)\nzLabel = ax1.set_zlabel('\\nWeight', linespacing=1.2)\n\nneuron1 = plt.Rectangle((0, 0), 0.1, 0.1,fc='r')\nneuron2 = plt.Rectangle((0, 0), 0.1, 0.1,fc='g')\nneuron3 = plt.Rectangle((0, 0), 0.1, 0.1,fc='b')\nneuron4 = plt.Rectangle((0, 0), 0.1, 0.1,fc='y')\n\nax1.legend((neuron1,neuron2,neuron3,neuron4),(\"neuron 1\",\"neuron 2\",\"neuron 3\",\"neuron 4\"),'best')\n\nax1.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors, alpha=0.5)\nax1.view_init(elev=60.0, azim=40)\n\npylab.savefig('Weights3dBar.jpg')\n\nplt.show()\n"
] | [
[
"matplotlib.pyplot.Rectangle",
"numpy.ones",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xhdtc8/mmclassification | [
"606015470be69aaa3ea19b1a1bfed598c2ec5785"
] | [
"mmcls/models/heads/arcface_head.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom ..utils import is_tracing\n\nfrom ..builder import HEADS\nfrom .cls_head import ClsHead\n\n\ndef l2_norm(input, axis = 1):\n norm = torch.norm(input, 2, axis, True)\n output = torch.div(input, norm)\n return output\n\n\[email protected]_module()\nclass ArcFaceHead(ClsHead):\n r\"\"\"Implement of ArcFace (https://arxiv.org/pdf/1801.07698v1.pdf):\n Args:\n in_features: size of each input sample\n out_features: size of each output sample\n device_id: the ID of GPU where the model will be trained by model parallel. \n if device_id=None, it will be trained on CPU without model parallel.\n s: norm of input feature\n m: margin\n cos(theta+m)\n \"\"\"\n def __init__(self,\n num_classes,\n in_channels,\n init_cfg=dict(type='Normal', layer='Linear', std=0.01),\n s = 64.0, \n m = 0.50):\n super(ArcFaceHead, self).__init__(init_cfg=init_cfg)\n self.in_features = in_channels\n self.out_features = num_classes\n\n self.s = s\n self.m = m\n\n self.cos_m = math.cos(m)\n self.sin_m = math.sin(m)\n self.th = math.cos(math.pi - m)\n self.mm = math.sin(math.pi - m) * m\n\n self._init_layers()\n\n def _init_layers(self):\n self.kernel = nn.Parameter(torch.FloatTensor(self.in_features, self.out_features))\n #nn.init.xavier_uniform_(self.kernel)\n nn.init.normal_(self.kernel, std=0.01)\n\n def forward_train(self, embbedings, label):\n embbedings = l2_norm(embbedings, axis = 1)\n kernel_norm = l2_norm(self.kernel, axis = 0)\n cos_theta = torch.mm(embbedings, kernel_norm).clamp(-1, 1) # for numerical stability\n # with torch.no_grad():\n # origin_cos = cos_theta.clone()\n target_logit = cos_theta[torch.arange(0, embbedings.size(0)), label].view(-1, 1)\n\n sin_theta = torch.sqrt(1.0 - torch.pow(target_logit, 2))\n cos_theta_m = target_logit * self.cos_m - sin_theta * self.sin_m #cos(target+margin)\n final_target_logit = torch.where(target_logit > self.th, cos_theta_m, target_logit - self.mm)\n cos_theta.scatter_(1, label.view(-1, 1).long(), final_target_logit)\n output = cos_theta * self.s\n losses = self.loss(output, label)\n return losses\n\n def simple_test(self, embbedings):\n \"\"\"Test without augmentation.\"\"\"\n\n embbedings = l2_norm(embbedings, axis=1)\n kernel_norm = l2_norm(self.kernel, axis=0)\n cos_theta = torch.mm(embbedings, kernel_norm).clamp(-1, 1) # for numerical stability\n cls_score = cos_theta * self.s\n if isinstance(cls_score, list):\n cls_score = sum(cls_score) / float(len(cls_score))\n pred = F.softmax(cls_score, dim=1) if cls_score is not None else None\n\n on_trace = is_tracing()\n if torch.onnx.is_in_onnx_export() or on_trace:\n return pred\n pred = list(pred.detach().cpu().numpy())\n return pred\n\n\n"
] | [
[
"torch.div",
"torch.nn.functional.softmax",
"torch.norm",
"torch.mm",
"torch.FloatTensor",
"torch.nn.init.normal_",
"torch.where",
"torch.onnx.is_in_onnx_export",
"torch.pow"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
claforte/SRGAN-PyTorch | [
"b201d5d20296829d3bb4e852ae989bc3f95165cd"
] | [
"srgan_pytorch/utils/device.py"
] | [
"# Copyright 2020 Dakewe Biotech Corporation. All Rights Reserved.\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\"\"\"Select the specified device for processing\"\"\"\nimport logging\nimport os\n\nimport torch\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(format=\"[ %(levelname)s ] %(message)s\", level=logging.INFO)\n\n\ndef select_device(device: str = \"\", batch_size: int = 1) -> torch.device:\n r\"\"\" Choose the right equipment.\n\n Args:\n device (optional, str): Use CPU or CUDA. (Default: ````)\n batch_size (optional, int): Data batch size, cannot be less than the number of devices. (Default: 1).\n\n Returns:\n torch.device.\n \"\"\"\n # device = \"cpu\" or \"cuda:0,1,2,3\".\n only_cpu = device.lower() == \"cpu\"\n if device and not only_cpu: # if device requested other than \"cpu\".\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = device # set environment variable.\n assert torch.cuda.is_available(), f\"CUDA unavailable, invalid device {device} requested\"\n\n cuda = False if only_cpu else torch.cuda.is_available()\n if cuda:\n c = 1024 ** 2 # bytes to MB.\n gpu_count = torch.cuda.device_count()\n if gpu_count > 1 and batch_size: # check that batch_size is compatible with device_count.\n assert batch_size % gpu_count == 0, f\"batch-size {batch_size} not multiple of GPU count {gpu_count}\"\n x = [torch.cuda.get_device_properties(i) for i in range(gpu_count)]\n s = \"Using CUDA \"\n for i in range(0, gpu_count):\n if i == 1:\n s = \" \" * len(s)\n logger.info(f\"{s}\\n\\t+ device:{i} (name=`{x[i].name}`, total_memory={int(x[i].total_memory / c)}MB)\")\n else:\n logger.info(\"Using CPU.\")\n\n return torch.device(\"cuda:0\" if cuda else \"cpu\")\n"
] | [
[
"torch.device",
"torch.cuda.get_device_properties",
"torch.cuda.device_count",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lukeshingles/artistools | [
"51a6f4f265a976f4a159d284bc257453b26ee426"
] | [
"artistools/estimators/estimators.py"
] | [
"#!/usr/bin/env python3\n\"\"\"Functions for reading and processing estimator files.\n\nExamples are temperatures, populations, and heating/cooling rates.\n\"\"\"\n# import math\nimport math\nimport multiprocessing\nimport sys\nfrom collections import namedtuple\nfrom functools import lru_cache, partial, reduce\n# from itertools import chain\nfrom pathlib import Path\n\nimport pandas as pd\n\nimport artistools as at\nimport artistools.nltepops\n\n\nvariableunits = {\n 'time': 'days',\n 'gamma_NT': '/s',\n 'gamma_R_bfest': '/s',\n 'TR': 'K',\n 'Te': 'K',\n 'TJ': 'K',\n 'nne': 'e-/cm3',\n 'heating': 'erg/s/cm3',\n 'heating_dep/total_dep': 'Ratio',\n 'cooling': 'erg/s/cm3',\n 'velocity': 'km/s',\n 'velocity_outer': 'km/s',\n}\n\nvariablelongunits = {\n 'heating_dep/total_dep': '',\n 'TR': 'Temperature [K]',\n 'Te': 'Temperature [K]',\n 'TJ': 'Temperature [K]',\n}\n\ndictlabelreplacements = {\n 'lognne': 'Log nne',\n 'Te': 'T$_e$',\n 'TR': 'T$_R$',\n 'gamma_NT': r'$\\Gamma_{\\rm non-thermal}$ [s$^{-1}$]',\n 'gamma_R_bfest': r'$\\Gamma_{\\rm phot}$ [s$^{-1}$]',\n 'heating_dep/total_dep': 'Heating fraction',\n}\n\n\ndef apply_filters(xlist, ylist, args):\n filterfunc = at.get_filterfunc(args)\n\n if filterfunc is not None:\n ylist = filterfunc(ylist)\n\n return xlist, ylist\n\n\ndef get_ionrecombrates_fromfile(filename):\n \"\"\"WARNING: copy pasted from artis-atomic! replace with a package import soon ionstage is the lower ion stage.\"\"\"\n print(f'Reading {filename}')\n\n header_row = []\n with open(filename, 'r') as filein:\n while True:\n line = filein.readline()\n if line.strip().startswith('TOTAL RECOMBINATION RATE'):\n line = filein.readline()\n line = filein.readline()\n header_row = filein.readline().strip().replace(' n)', '-n)').split()\n break\n\n if not header_row:\n print(\"ERROR: no header found\")\n sys.exit()\n\n index_logt = header_row.index('log(T)')\n index_low_n = header_row.index('RRC(low-n)')\n index_tot = header_row.index('RRC(total)')\n\n recomb_tuple = namedtuple(\"recomb_tuple\", ['logT', 'RRC_low_n', 'RRC_total'])\n records = []\n for line in filein:\n row = line.split()\n if row:\n if len(row) != len(header_row):\n print('Row contains wrong number of items for header:')\n print(header_row)\n print(row)\n sys.exit()\n records.append(recomb_tuple(\n *[float(row[index]) for index in [index_logt, index_low_n, index_tot]]))\n\n dfrecombrates = pd.DataFrame.from_records(records, columns=recomb_tuple._fields)\n return dfrecombrates\n\n\ndef get_units_string(variable):\n if variable in variableunits:\n return f' [{variableunits[variable]}]'\n elif variable.split('_')[0] in variableunits:\n return f' [{variableunits[variable.split(\"_\")[0]]}]'\n return ''\n\n\ndef parse_estimfile(estfilepath, modelpath, get_ion_values=True, get_heatingcooling=True):\n \"\"\"Generate timestep, modelgridindex, dict from estimator file.\"\"\"\n # itstep = at.get_inputparams(modelpath)['itstep']\n\n with at.zopen(estfilepath, 'rt') as estimfile:\n timestep = -1\n modelgridindex = -1\n estimblock = {}\n for line in estimfile:\n row = line.split()\n if not row:\n continue\n\n if row[0] == 'timestep':\n # yield the previous block before starting a new one\n if timestep >= 0 and modelgridindex >= 0:\n yield timestep, modelgridindex, estimblock\n\n timestep = int(row[1])\n # if timestep > itstep:\n # print(f\"Dropping estimator data from timestep {timestep} and later (> itstep {itstep})\")\n # # itstep in input.txt is updated by ARTIS at every timestep, so the data beyond here\n # # could be half-written to disk and cause parsing errors\n # return\n\n modelgridindex = int(row[3])\n # print(f'Timestep {timestep} cell {modelgridindex}')\n\n estimblock = {}\n emptycell = (row[4] == 'EMPTYCELL')\n estimblock['emptycell'] = emptycell\n if not emptycell:\n # will be TR, Te, W, TJ, nne\n for variablename, value in zip(row[4::2], row[5::2]):\n estimblock[variablename] = float(value)\n estimblock['lognne'] = math.log10(estimblock['nne']) if estimblock['nne'] > 0 else float('-inf')\n\n elif row[1].startswith('Z=') and get_ion_values:\n variablename = row[0]\n if row[1].endswith('='):\n atomic_number = int(row[2])\n startindex = 3\n else:\n atomic_number = int(row[1].split('=')[1])\n startindex = 2\n\n estimblock.setdefault(variablename, {})\n\n for ion_stage_str, value in zip(row[startindex::2], row[startindex + 1::2]):\n if ion_stage_str.strip() in ['SUM:', '(or']:\n continue\n\n try:\n ion_stage = int(ion_stage_str.rstrip(':'))\n except ValueError:\n if variablename == 'populations' and ion_stage_str.startswith(at.elsymbols[atomic_number]):\n estimblock[variablename][ion_stage_str.rstrip(':')] = float(value)\n else:\n print(ion_stage_str, at.elsymbols[atomic_number])\n print(f'Cannot parse row: {row}')\n continue\n\n value_thision = float(value.rstrip(','))\n\n estimblock[variablename][(atomic_number, ion_stage)] = value_thision\n\n if variablename in ['Alpha_R*nne', 'AlphaR*nne']:\n estimblock.setdefault('Alpha_R', {})\n estimblock['Alpha_R'][(atomic_number, ion_stage)] = value_thision / estimblock['nne']\n\n else: # variablename == 'populations':\n\n # contribute the ion population to the element population\n estimblock[variablename].setdefault(atomic_number, 0.)\n estimblock[variablename][atomic_number] += value_thision\n\n if variablename == 'populations':\n # contribute the element population to the total population\n estimblock['populations'].setdefault('total', 0.)\n estimblock['populations']['total'] += estimblock['populations'][atomic_number]\n estimblock['nntot'] = estimblock['populations']['total']\n\n elif row[0] == 'heating:' and get_heatingcooling:\n for heatingtype, value in zip(row[1::2], row[2::2]):\n key = 'heating_' + heatingtype if not heatingtype.startswith('heating_') else heatingtype\n estimblock[key] = float(value)\n\n if 'heating_gamma/gamma_dep' in estimblock and estimblock['heating_gamma/gamma_dep'] > 0:\n estimblock['gamma_dep'] = (\n estimblock['heating_gamma'] /\n estimblock['heating_gamma/gamma_dep'])\n elif 'heating_dep/total_dep' in estimblock and estimblock['heating_dep/total_dep'] > 0:\n estimblock['total_dep'] = (\n estimblock['heating_dep'] /\n estimblock['heating_dep/total_dep'])\n\n elif row[0] == 'cooling:' and get_heatingcooling:\n for coolingtype, value in zip(row[1::2], row[2::2]):\n estimblock['cooling_' + coolingtype] = float(value)\n\n # reached the end of file\n if timestep >= 0 and modelgridindex >= 0:\n yield timestep, modelgridindex, estimblock\n\n\[email protected](ignorekwargs=['printfilename'], quiet=False, funcdepends=parse_estimfile, savegzipped=True)\ndef read_estimators_from_file(modelpath, folderpath, arr_velocity_outer, mpirank, printfilename=False,\n get_ion_values=True, get_heatingcooling=True):\n\n estimators_thisfile = {}\n estimfilename = f'estimators_{mpirank:04d}.out'\n estfilepath = Path(folderpath, estimfilename)\n if not estfilepath.is_file():\n estfilepath = Path(folderpath, estimfilename + '.gz')\n if not estfilepath.is_file():\n print(f'Warning: Could not find {estfilepath.relative_to(modelpath.parent)}')\n return {}\n\n if printfilename:\n filesize = Path(estfilepath).stat().st_size / 1024 / 1024\n print(f'Reading {estfilepath.relative_to(modelpath.parent)} ({filesize:.2f} MiB)')\n\n for fileblock_timestep, fileblock_modelgridindex, file_estimblock in parse_estimfile(\n estfilepath, modelpath, get_ion_values=get_ion_values, get_heatingcooling=get_heatingcooling):\n\n file_estimblock['velocity_outer'] = arr_velocity_outer[fileblock_modelgridindex]\n file_estimblock['velocity'] = file_estimblock['velocity_outer']\n\n estimators_thisfile[(fileblock_timestep, fileblock_modelgridindex)] = file_estimblock\n\n return estimators_thisfile\n\n\n@lru_cache(maxsize=16)\[email protected](savegzipped=True, funcdepends=[read_estimators_from_file, parse_estimfile])\ndef read_estimators(modelpath, modelgridindex=None, timestep=None, get_ion_values=True, get_heatingcooling=True):\n \"\"\"Read estimator files into a nested dictionary structure.\n\n Speed it up by only retrieving estimators for a particular timestep(s) or modelgrid cells.\n \"\"\"\n\n if modelgridindex is None:\n match_modelgridindex = []\n elif hasattr(modelgridindex, '__iter__'):\n match_modelgridindex = tuple(modelgridindex)\n else:\n match_modelgridindex = (modelgridindex,)\n\n if -1 in match_modelgridindex:\n match_modelgridindex = []\n\n if timestep is None:\n match_timestep = []\n else:\n match_timestep = tuple(timestep) if hasattr(timestep, '__iter__') else (timestep,)\n\n if not modelpath.exists() and modelpath.parts[0] == 'codecomparison':\n return artistools.codecomparison.read_reference_estimators(modelpath, timestep=timestep, modelgridindex=modelgridindex)\n\n # print(f\" matching cells {match_modelgridindex} and timesteps {match_timestep}\")\n\n modeldata, _, _ = at.inputmodel.get_modeldata(modelpath)\n arr_velocity_outer = tuple(list([float(v) for v in modeldata['velocity_outer'].values]))\n\n mpiranklist = at.get_mpiranklist(modelpath, modelgridindex=match_modelgridindex)\n\n printfilename = len(mpiranklist) < 10\n\n estimators = {}\n for folderpath in at.get_runfolders(modelpath, timesteps=match_timestep):\n print(f'Reading {len(list(mpiranklist))} estimator files in {folderpath.relative_to(Path(modelpath).parent)}')\n\n processfile = partial(read_estimators_from_file, modelpath, folderpath, arr_velocity_outer,\n get_ion_values=get_ion_values, get_heatingcooling=get_heatingcooling,\n printfilename=printfilename)\n\n if at.num_processes > 1:\n with multiprocessing.Pool(processes=at.num_processes) as pool:\n arr_rankestimators = pool.map(processfile, mpiranklist)\n pool.close()\n pool.join()\n pool.terminate()\n else:\n arr_rankestimators = [processfile(rank) for rank in mpiranklist]\n\n for mpirank, estimators_thisfile in zip(mpiranklist, arr_rankestimators):\n dupekeys = list(sorted([k for k in estimators_thisfile if k in estimators]))\n for k in dupekeys:\n # dropping the lowest timestep is normal for restarts. Only warn about other cases\n if k[0] != dupekeys[0][0]:\n filepath = Path(folderpath, f'estimators_{mpirank:04d}.out')\n print(f'WARNING: Duplicate estimator block for (timestep, mgi) key {k}. '\n f'Dropping block from {filepath}')\n\n del estimators_thisfile[k]\n\n estimators.update(estimators_thisfile)\n\n return estimators\n\n\ndef get_averaged_estimators(modelpath, estimators, timesteps, modelgridindex, keys, avgadjcells=0):\n \"\"\"Get the average of estimators[(timestep, modelgridindex)][keys[0]]...[keys[-1]] across timesteps.\"\"\"\n if isinstance(keys, str):\n keys = [keys]\n\n # reduce(lambda d, k: d[k], keys, dictionary) returns dictionary[keys[0]][keys[1]]...[keys[-1]]\n # applying all keys in the keys list\n\n # if single timestep, no averaging needed\n if not hasattr(timesteps, '__iter__'):\n return reduce(lambda d, k: d[k], [(timesteps, modelgridindex)] + keys, estimators)\n\n firsttimestepvalue = reduce(lambda d, k: d[k], [(timesteps[0], modelgridindex)] + keys, estimators)\n if isinstance(firsttimestepvalue, dict):\n dictout = {k: get_averaged_estimators(modelpath, estimators, timesteps, modelgridindex, keys + [k])\n for k in firsttimestepvalue.keys()}\n\n return dictout\n else:\n tdeltas = at.get_timestep_times_float(modelpath, loc='delta')\n valuesum = 0\n tdeltasum = 0\n for timestep, tdelta in zip(timesteps, tdeltas):\n for mgi in range(modelgridindex - avgadjcells, modelgridindex + avgadjcells + 1):\n try:\n valuesum += reduce(lambda d, k: d[k], [(timestep, mgi)] + keys, estimators) * tdelta\n tdeltasum += tdelta\n except KeyError:\n pass\n return valuesum / tdeltasum\n\n # except KeyError:\n # if (timestep, modelgridindex) in estimators:\n # print(f'Unknown x variable: {xvariable} for timestep {timestep} in cell {modelgridindex}')\n # else:\n # print(f'No data for cell {modelgridindex} at timestep {timestep}')\n # print(estimators[(timestep, modelgridindex)])\n # sys.exit()\n\n\ndef get_averageionisation(populations, atomic_number):\n free_electron_weighted_pop_sum = 0.\n found = False\n popsum = 0\n for key in populations.keys():\n if isinstance(key, tuple) and key[0] == atomic_number:\n found = True\n ion_stage = key[1]\n free_electron_weighted_pop_sum += populations[key] * (ion_stage - 1)\n popsum += populations[key]\n\n if not found:\n return float('NaN')\n\n return free_electron_weighted_pop_sum / populations[atomic_number]\n\n\ndef get_averageexcitation(modelpath, modelgridindex, timestep, atomic_number, ion_stage, T_exc):\n import artistools.nltepops\n dfnltepops = at.nltepops.read_files(modelpath, modelgridindex=modelgridindex, timestep=timestep)\n adata = at.atomic.get_levels(modelpath)\n ionlevels = adata.query('Z == @atomic_number and ion_stage == @ion_stage').iloc[0].levels\n\n energypopsum = 0\n ionpopsum = 0\n if dfnltepops.empty:\n return float('NaN')\n else:\n dfnltepops_ion = dfnltepops.query(\n 'modelgridindex==@modelgridindex and timestep==@timestep and Z==@atomic_number & ion_stage==@ion_stage')\n\n k_b = 8.617333262145179e-05 # eV / K\n\n ionpopsum = dfnltepops_ion.n_NLTE.sum()\n energypopsum = dfnltepops_ion[dfnltepops_ion.level >= 0].eval(\n '@ionlevels.iloc[level].energy_ev.values * n_NLTE').sum()\n\n try:\n superlevelrow = dfnltepops_ion[dfnltepops_ion.level < 0].iloc[0]\n levelnumber_sl = dfnltepops_ion.level.max() + 1\n\n energy_boltzfac_sum = ionlevels.iloc[levelnumber_sl:].eval(\n 'energy_ev * g * exp(- energy_ev / @k_b / @T_exc)').sum()\n\n boltzfac_sum = ionlevels.iloc[levelnumber_sl:].eval('g * exp(- energy_ev / @k_b / @T_exc)').sum()\n # adjust to the actual superlevel population from ARTIS\n energypopsum += energy_boltzfac_sum * superlevelrow.n_NLTE / boltzfac_sum\n except IndexError:\n # no superlevel\n pass\n\n return energypopsum / ionpopsum\n\n\n"
] | [
[
"pandas.DataFrame.from_records"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
amroadel/Learn2steer | [
"e9a3e74c602257b76dbbe777fb7065733c59a801"
] | [
"tools/resnet_50_pre-trained_model.py"
] | [
"import tensorflow as tf\nimport numpy as np\nimport resnet\nfrom config import Config\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.training import moving_averages\n\nactivation = tf.nn.relu\nMOVING_AVERAGE_DECAY = 0.9997\nBN_DECAY = MOVING_AVERAGE_DECAY\nBN_EPSILON = 0.001\nCONV_WEIGHT_DECAY = 0.00004\nCONV_WEIGHT_STDDEV = 0.1\nFC_WEIGHT_DECAY = 0.00004\nFC_WEIGHT_STDDEV = 0.01\nRESNET_VARIABLES = 'resnet_variables'\nUPDATE_OPS_COLLECTION = 'resnet_update_ops' # must be grouped with training op\nIMAGENET_MEAN_BGR = [103.062623801, 115.902882574, 123.151630838, ]\nHEIGHT = 480\nWIDTH = 640\nLEFT_CONTEXT = 0\nSEQ_LEN = 10\nBATCH_SIZE = 4\nCHANNELS = 3\n\ndef stack(x, c):\n for n in range(c['num_blocks']):\n s = c['stack_stride'] if n == 0 else 1\n c['block_stride'] = s\n with tf.variable_scope('block%d' % (n + 1)):\n x = block(x, c)\n return x\n\n\ndef block(x, c):\n filters_in = x.get_shape()[-1]\n\n # Note: filters_out isn't how many filters are outputed.\n # That is the case when bottleneck=False but when bottleneck is\n # True, filters_internal*4 filters are outputted. filters_internal is how many filters\n # the 3x3 convs output internally.\n m = 4 if c['bottleneck'] else 1\n filters_out = m * c['block_filters_internal']\n\n shortcut = x # branch 1\n\n c['conv_filters_out'] = c['block_filters_internal']\n\n if c['bottleneck']:\n with tf.variable_scope('a'):\n c['ksize'] = 1\n c['stride'] = c['block_stride']\n x = conv(x, c)\n x = bn(x, c)\n x = activation(x)\n\n with tf.variable_scope('b'):\n x = conv(x, c)\n x = bn(x, c)\n x = activation(x)\n\n with tf.variable_scope('c'):\n c['conv_filters_out'] = filters_out\n c['ksize'] = 1\n assert c['stride'] == 1\n x = conv(x, c)\n x = bn(x, c)\n else:\n with tf.variable_scope('A'):\n c['stride'] = c['block_stride']\n assert c['ksize'] == 3\n x = conv(x, c)\n x = bn(x, c)\n x = activation(x)\n\n with tf.variable_scope('B'):\n c['conv_filters_out'] = filters_out\n assert c['ksize'] == 3\n assert c['stride'] == 1\n x = conv(x, c)\n x = bn(x, c)\n\n with tf.variable_scope('shortcut'):\n if filters_out != filters_in or c['block_stride'] != 1:\n c['ksize'] = 1\n c['stride'] = c['block_stride']\n c['conv_filters_out'] = filters_out\n shortcut = conv(shortcut, c)\n shortcut = bn(shortcut, c)\n\n return activation(x + shortcut)\n\n\ndef _get_variable(name,\n shape,\n initializer,\n weight_decay=0.0,\n dtype='float',\n trainable=True):\n \"A little wrapper around tf.get_variable to do weight decay and add to\"\n \"resnet collection\"\n if weight_decay > 0:\n regularizer = tf.contrib.layers.l2_regularizer(weight_decay)\n else:\n regularizer = None\n collections = [tf.GraphKeys.VARIABLES, RESNET_VARIABLES]\n return tf.get_variable(name,\n shape=shape,\n initializer=initializer,\n dtype=dtype,\n regularizer=regularizer,\n collections=collections,\n trainable=trainable)\n\n\ndef bn(x, c):\n x_shape = x.get_shape()\n params_shape = x_shape[-1:]\n\n if c['use_bias']:\n bias = _get_variable('bias', params_shape,\n initializer=tf.zeros_initializer)\n return x + bias\n\n\n axis = list(range(len(x_shape) - 1))\n\n beta = resnet._get_variable('beta',\n params_shape,\n initializer=tf.zeros_initializer)\n gamma = resnet._get_variable('gamma',\n params_shape,\n initializer=tf.ones_initializer)\n\n moving_mean = resnet._get_variable('moving_mean',\n params_shape,\n initializer=tf.zeros_initializer,\n trainable=False)\n moving_variance = resnet._get_variable('moving_variance',\n params_shape,\n initializer=tf.ones_initializer,\n trainable=False)\n\n # These ops will only be preformed when training.\n mean, variance = tf.nn.moments(x, axis)\n update_moving_mean = moving_averages.assign_moving_average(moving_mean,\n mean, BN_DECAY)\n update_moving_variance = moving_averages.assign_moving_average(\n moving_variance, variance, BN_DECAY)\n tf.add_to_collection(UPDATE_OPS_COLLECTION, update_moving_mean)\n tf.add_to_collection(UPDATE_OPS_COLLECTION, update_moving_variance)\n\n mean, variance = control_flow_ops.cond(\n c['is_training'], lambda: (mean, variance),\n lambda: (moving_mean, moving_variance))\n\n x = tf.nn.batch_normalization(x, mean, variance, beta, gamma, BN_EPSILON)\n #x.set_shape(inputs.get_shape()) ??\n\n return x\n\ndef conv(x, c):\n ksize = c['ksize']\n stride = c['stride']\n filters_out = c['conv_filters_out']\n\n filters_in = x.get_shape()[-1]\n shape = [ksize, ksize, ksize, filters_in, filters_out]\n initializer = tf.truncated_normal_initializer(stddev=CONV_WEIGHT_STDDEV)\n weights = resnet._get_variable('weights',\n shape=shape,\n dtype='float',\n initializer=initializer,\n weight_decay=CONV_WEIGHT_DECAY)\n return tf.nn.conv3d(x, weights, [1, 1, stride, stride, 1], padding='SAME')\n\n\ndef _max_pool(x, ksize=3, stride=2):\n return tf.nn.max_pool3d(x,\n ksize=[1, ksize, ksize, ksize, 1],\n strides=[1, 1, stride, stride, 1],\n padding='SAME')\n\n\nwith tf.Session() as sess:\n # build 3D ResNet-50\n saver = tf.train.import_meta_graph('/home/cardwing/Downloads/tensorflow-resnet-pretrained-20160509/ResNet-L50.meta')\n saver.restore(sess, '/home/cardwing/Downloads/tensorflow-resnet-pretrained-20160509/ResNet-L50.ckpt')\n var_list = saver._var_list\n value=[]\n for i in range(265):\n tmp = sess.run(var_list[i], feed_dict={})\n if tmp.shape[0] < 10:\n tmp = [tmp / 1.0 / tmp.shape[0] for _ in range(tmp.shape[0])]\n tmp = np.stack(tmp, axis=0)\n value.append(tmp)\n\n\n\ngraph = tf.Graph()\nwith graph.as_default():\n # build 3D ResNet-50\n num_classes = 1000\n num_blocks = [3, 4, 6, 3] # defaults to 50-layer network\n use_bias = False # defaults to using batch norm\n bottleneck = True\n is_training = False\n\n x = tf.placeholder(shape=(BATCH_SIZE, SEQ_LEN, HEIGHT, WIDTH, CHANNELS), dtype=tf.float32)\n\n c = Config()\n c['bottleneck'] = bottleneck\n c['is_training'] = tf.convert_to_tensor(is_training,\n dtype='bool',\n name='is_training')\n c['ksize'] = 3\n c['stride'] = 1\n c['use_bias'] = use_bias\n c['fc_units_out'] = num_classes\n c['num_blocks'] = 1\n c['stack_stride'] = 2\n\n with tf.variable_scope('scale1'):\n c['conv_filters_out'] = 64\n c['ksize'] = 7\n c['stride'] = 2\n x = conv(x, c)\n x = resnet.bn(x, c)\n x = resnet.activation(x)\n\n with tf.variable_scope('scale2'):\n x = _max_pool(x, ksize=3, stride=2)\n c['num_blocks'] = num_blocks[0]\n c['stack_stride'] = 1\n c['block_filters_internal'] = 64\n x = resnet.stack(x, c)\n\n with tf.variable_scope('scale3'):\n c['num_blocks'] = num_blocks[1]\n c['block_filters_internal'] = 128\n assert c['stack_stride'] == 2\n x = resnet.stack(x, c)\n\n with tf.variable_scope('scale4'):\n c['num_blocks'] = num_blocks[2]\n c['block_filters_internal'] = 256\n x = resnet.stack(x, c)\n\n with tf.variable_scope('scale5'):\n c['num_blocks'] = num_blocks[3]\n c['block_filters_internal'] = 512\n x = resnet.stack(x, c)\n\n variable_map = tf.get_collection(key=tf.GraphKeys.TRAINABLE_VARIABLES)\n\n op_list = []\n list_tmp = []\n for i in range(265):\n tmp = tf.placeholder(shape=variable_map[i].shape, dtype=tf.float32, name=str(i))\n op_list.append(tf.assign(ref= variable_map[i], value= tmp))\n list_tmp.append(tmp)\n\nwith graph.as_default():\n with tf.Session() as sess1:\n for i in range(265):\n _ = sess1.run([op_list[i]],feed_dict={list_tmp[i]: value[i]})\n"
] | [
[
"tensorflow.convert_to_tensor",
"tensorflow.get_variable",
"tensorflow.python.ops.control_flow_ops.cond",
"tensorflow.Graph",
"tensorflow.python.training.moving_averages.assign_moving_average",
"tensorflow.get_collection",
"tensorflow.nn.moments",
"tensorflow.truncated_normal_initializer",
"tensorflow.train.import_meta_graph",
"numpy.stack",
"tensorflow.Session",
"tensorflow.nn.batch_normalization",
"tensorflow.placeholder",
"tensorflow.nn.conv3d",
"tensorflow.add_to_collection",
"tensorflow.nn.max_pool3d",
"tensorflow.assign",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.variable_scope"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
Alabenba/EDSR-tensorflow2 | [
"da2edaf18c941e690bee6880c470f7fd944533d8"
] | [
"model.py"
] | [
"from tensorflow.keras.layers import Add, Conv2D, Input, Lambda, Activation\nfrom tensorflow.keras.models import Model\nimport tensorflow as tf\n\n\ndef SubpixelConv2D(scale, **kwargs):\n return Lambda(lambda x: tf.nn.depth_to_space(x, scale), **kwargs)\n\n\ndef edsr(scale, num_filters=64, num_res_blocks=8, res_block_scaling=None):\n x_in = Input(shape=(None, None, 3))\n\n x = b = Conv2D(num_filters, 3, padding=\"same\")(x_in)\n for _ in range(num_res_blocks):\n b = res_block(b, num_filters, res_block_scaling)\n b = Conv2D(num_filters, 3, padding=\"same\")(b)\n x = Add()([x, b])\n\n x = upsample(x, scale, num_filters)\n x = Conv2D(3, 3, padding=\"same\")(x)\n\n return Model(x_in, x, name=\"edsr\")\n\n\ndef res_block(x_in, filters, scaling):\n x = Conv2D(filters, 3, padding=\"same\")(x_in)\n x = Activation(\"relu\")(x)\n x = Conv2D(filters, 3, padding=\"same\")(x)\n x = Add()([x_in, x])\n if scaling:\n x = Lambda(lambda t: t * scaling)(x)\n return x\n\n\ndef upsample(x, scale, num_filters):\n def upsample_1(x, factor, **kwargs):\n x = Conv2D(num_filters * (factor ** 2), 3, padding=\"same\", **kwargs)(x)\n return SubpixelConv2D(factor)(x)\n\n if scale == 2:\n x = upsample_1(x, 2, name=\"conv2d_1_scale_2\")\n elif scale == 3:\n x = upsample_1(x, 3, name=\"conv2d_1_scale_3\")\n elif scale == 4:\n x = upsample_1(x, 2, name=\"conv2d_1_scale_2\")\n x = upsample_1(x, 2, name=\"conv2d_2_scale_2\")\n\n return x\n"
] | [
[
"tensorflow.nn.depth_to_space",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.layers.Lambda",
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.Add",
"tensorflow.keras.layers.Input"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
wmcabee-cs/nbc_analysis | [
"d6c717aea0bd3638f9f6d03e2facb45fdbb062fc"
] | [
"src/nbc_analysis/load_profiles/main.py"
] | [
"from nbc_analysis.utils.debug_utils import retval\nfrom nbc_analysis.utils.config_utils import get_config\nfrom pathlib import Path\nfrom toolz import concatv, first, cons, partial, concat, take\nfrom itertools import starmap\nimport pandas as pd\nimport yaml\nfrom toolz import pluck\nimport re\nimport arrow\nimport numpy as np\nfrom timeit import default_timer as timer\nimport pprint\n\nfrom cortex import Cortex\n\nfrom cortex_common.types import EntityEvent\nfrom cortex_profiles import ProfileBuilder, ProfileClient\n\nSCRIPT_D = Path(__file__).parent.absolute()\n\n\ndef read_files(indir):\n reader = concatv(indir.glob('*.csv'), indir.glob('*.csv.gz'))\n reader = map(lambda x: (x, pd.read_csv(x)), reader)\n reader = list(reader)\n print(f\">> listing input files, dir={indir},file_cnt={len(reader)}\")\n return reader\n\n\ndef load_schema(cortex_schema_version):\n # TODO: Move to data resource so can use from python package\n json_f = SCRIPT_D / 'profile_schema.json'\n with json_f.open() as fh:\n schema = yaml.safe_load(fh)\n if cortex_schema_version != schema['name']:\n raise Exception(\n f\"Schema name doesn't match, cortex_schema_version={cortex_schema_version},name in schema{schema['name']}\")\n return schema\n\n\ndef get_interfaces(schema_version):\n cortex = Cortex.client()\n builder = ProfileBuilder(cortex)\n profile_schema = builder.profiles(schema_version)\n return profile_schema\n\n\ndef get_column_list(schema_version):\n schema = load_schema(schema_version)\n return list(pluck('name', schema['attributes']))\n\n\nregex = re.compile(\"(?P<year>\\d\\d\\d\\d)(?P<month>\\d\\d)(?P<day>\\d\\d)\")\n\n\ndef fix_day(day):\n m = regex.match(day)\n return '/'.join([m.group('month'), m.group('day'), m.group('year')])\n\n\ndef make_sample(df, sample_size):\n if sample_size is None:\n return df\n df = df[df.mpid > 0]\n return df[slice(None, sample_size)].copy()\n\n\ndef clean_data(file, df, column_list, sample_size=None):\n \"\"\" Reformat dates and fix null values \"\"\"\n\n df = make_sample(df, sample_size)\n\n # Add event time and adjust day format\n # TODO: Move to concat script\n df['day'] = df['day'].astype(str).map(fix_day)\n df['event_time'] = df['day'].map(lambda dy: arrow.get(dy).timestamp * 1000)\n df = df[list(cons('event_time', column_list))]\n\n # TOOD: Handle infinity values\n df = df.mask(df.isin([np.inf, -np.inf]))\n # df.replace([np.inf, -np.inf], np.nan)\n\n # TODO: Handle null values. Setting to 0 until get way of handling nulls from Omar\n clean_columns = ['ads_per_video_cnt_avg', 'ad_vs_video_time_avg']\n df[clean_columns] = df[clean_columns].fillna(0.)\n return file, df\n\n\ndef build_file_events(file, df, schema_version):\n record_cnt = len(df)\n file_records = ((idx, [EntityEvent(event=field,\n entityId=str(row.mpid),\n entityType=schema_version,\n eventTime=row.event_time,\n properties={\"value\": value},\n # meta={},\n )\n for field, value in zip(row._fields, row) if field != 'event_time'])\n for idx, row in enumerate(df.itertuples(index=False), start=1))\n return file, record_cnt, file_records\n\n\ndef write_record(file, record_cnt, idx, record, profile_schema, skip_writes, stop_on_fail):\n ret = {''\n 'file': file,\n 'record_cnt': record_cnt,\n 'idx': idx,\n 'start_ts': arrow.utcnow().isoformat(),\n 'end_ts': None,\n 'status': 'error',\n 'exception': 'unknown',\n 'exception_type': 'unknown'}\n try:\n start = timer()\n if not skip_writes:\n profiles = profile_schema.with_events(record)\n profiles.build()\n ret['status'] = 'OK'\n del ret['exception']\n del ret['exception_type']\n return ret\n except Exception as e:\n ret['exception'] = str(e)\n ret['exception_type'] = str(type(e))\n print(f\">> error,{ret}\")\n if stop_on_fail:\n raise\n return ret\n finally:\n end = timer()\n ret['duration'] = end - start\n ret['end_ts'] = arrow.utcnow().isoformat()\n print( f'>>write record,{ret[\"file\"].name},\"'\n f'{ret[\"idx\"]},{ret[\"record_cnt\"]},{ret[\"status\"]},{round(ret[\"duration\"], 5)}')\n\n\ndef main(sample_size=25, skip_writes=False, stop_on_fail=True):\n config = get_config()\n\n concat_d = Path(config['CONCAT_D'])\n schema_version = config['CORTEX_SCHEMA_VERSION']\n profile_schema = get_interfaces(schema_version)\n column_list = get_column_list(schema_version)\n\n # prepare output function\n write_func = partial(write_record,\n profile_schema=profile_schema,\n skip_writes=skip_writes,\n stop_on_fail=stop_on_fail)\n\n # Main processing\n reader = read_files(indir=concat_d)\n reader = starmap(partial(clean_data, column_list=column_list, sample_size=sample_size, ), reader)\n reader = starmap(partial(build_file_events, schema_version=schema_version), reader)\n reader = (write_func(file, record_cnt, idx, record)\n for file, record_cnt, file_records in reader\n for idx, record in file_records)\n outdf = pd.DataFrame.from_records(reader)\n return outdf\n\n return 'OK'\n"
] | [
[
"pandas.DataFrame.from_records",
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
mattkjames7/NNFunction | [
"5a6ecd057678d9b8001488ff7984b134dd534163"
] | [
"NNFunction/LoadANN.py"
] | [
"import numpy as np\nimport PyFileIO as pf\nimport os\nfrom .NNFunction import NNFunction\n\ndef LoadANN(fname,ReturnModel=True,ReadCost=True):\n\t'''\n\tRead an ANN file\n\t\n\t\n\tImports\n\t=======\n\tfname : str\n\t\tName of the file to load from\n\tReturnModel : bool\n\t\tIf True, an ANN will be returned, otherwise only the weights and \n\t\tcosts\n\tReadCost : bool\n\t\tIf True, then the full cost arrays will be loaded with the ANN\n\n\t\t\n\tReturns\n\t=======\n\tif ReturnModel:\n\t\tNNFunction object (ANN)\n\telse:\n\t\ts,scale0,scale1,w,b,Jt,Jc\n\t\t\n\t\ts : number of layers\n\t\tscale0 : output parameter scale \n\t\tscale1 : output parameter scale\n\t\tw : list of weight matrices\n\t\tb : list of bias matrices\n\t\tJt : Training cost\n\t\tJc : Validation cost\n\t\n\t'''\n\t\n\n\tprint('Reading file: '+fname)\n\t#check the file exists\n\tif not os.path.isfile(fname):\n\t\tprint('File not found')\n\t\treturn None,None,None,None,None,np.array([]),np.array([])\n\t\t\n\t#load stuff from file\n\tf = open(fname,'rb')\n\ts = pf.ArrayFromFile('int32',f)\n\tscale0 = pf.ArrayFromFile('float32',f)\n\tscale1 = pf.ArrayFromFile('float32',f)\n\tw = pf.ListArrayFromFile('float32',f)\n\tb = pf.ListArrayFromFile('float32',f)\n\tif ReadCost:\n\t\ttry:\n\t\t\tJt = pf.ArrayFromFile('float32',f)\n\t\t\tJc = pf.ArrayFromFile('float32',f)\n\t\texcept:\n\t\t\tJt = np.array([])\n\t\t\tJc = np.array([])\n\telse:\n\t\tJt = np.array([])\n\t\tJc = np.array([])\n\tf.close()\n\t\n\tif ReturnModel:\n\t\t#create the neural network object\n\t\tmodel = NNFunction(s)\n\n\t\tmodel.k = 1\n\t\tmodel.model = [model._CreateModel()]\n\t\tmodel.Jt = [Jt]\n\t\tmodel.Jc = [Jc]\n\t\tmodel.hist = [[]]\n\n\t\tmodel.SetWeights(w,b)\n\t\tmodel.scale0 = scale0\n\t\tmodel.scale1 = scale1\n\n\n\t\treturn model\n\telse:\n\t\treturn s,scale0,scale1,w,b,Jt,Jc\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ashwinreddy/voting | [
"4a9ef46901ddad23e814d5744944463f6fd9ae83"
] | [
"socialchoice/voting/pairwise.py"
] | [
"from .method import Method\nimport numpy as np\n\nclass PairwiseComparison(Method):\n def __init__(self, preference_schedule):\n super(PairwiseComparison, self).__init__(preference_schedule)\n \n def _compare_candidates(self, i, j):\n \"\"\"Compares candidates i and j as if no other candidates existed\n \"\"\"\n # a table to keep track of who has how many points for this 1-on-1 comparison\n pairwise_votes = {i: 0, j: 0}\n\n def pairswise_comparison(number_of_votes, ballot_order):\n winner = i if np.where(ballot_order == i)[0][0] < np.where(ballot_order == j)[0][0] else j\n pairwise_votes[winner] += number_of_votes\n \n # loop through all preferences, using the voting scheme of all points going to the more liked candidate on each ballot\n self._loop_through_preferences(pairswise_comparison)\n\n # do an argmax on the table and return that candidate's index\n winner = max(pairwise_votes, key=pairwise_votes.get)\n return winner\n\n\n def compute_ranking(self):\n # pit every possible combination of two candidates with each other\n for i in range(self.preference_schedule.number_of_candidates):\n for j in range(i+1, self.preference_schedule.number_of_candidates):\n # compare the candidates\n winner = self._compare_candidates(i, j)\n # give the point to the winner of the comparison\n self._points[winner] += 1\n"
] | [
[
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xdedss/SuccessiveConvexification | [
"8b330b64a31f546ce92c1e34036c212484cbae5e"
] | [
"GFOLD_problem.py"
] | [
"# -*- coding: utf-8 -*-\n# GFOLD_static_p3p4\n\n\nmin_=min\nfrom cvxpy import *\nimport cvxpy_codegen as cpg\nfrom time import time\nimport numpy as np\nimport sys\n\nimport GFOLD_params\n\n''' As defined in the paper...\n\n PROBLEM 3: Minimum Landing Error (tf roughly solved)\n MINIMIZE : norm of landing error vector\n SUBJ TO :\n 0) initial conditions satisfied (position, velocity)\n 1) final conditions satisfied (altitude, velocity)\n 2) dynamics always satisfied\n 3) x stays in cone at all times\n 4) relaxed convexified mass and thrust constraints\n 5) thrust pointing constraint\n 6) sub-surface flight constraint\n\n PROBLEM 4: Minimum Fuel Use\n MAXIMIZE : landing mass, opt variables are dynamical and\n SUBJ TO :\n 0) same constraints as p1, plus:\n 1) landing point must be equal or better than that found by p1\n\n'''\n\n\ndef solve(params, params_super = None, codegen = False, verbose=False):\n #super params\n if (params_super == None):\n params_super = GFOLD_params.SuperParams() # default\n N = params_super.N\n \n #优化变量\n x =Variable(6,N,name='var_x') # state vector (3position,3velocity)\n u =Variable(3,N,name='var_u') # u = Tc/mass because Tc[:,n]/m[n] is not allowed by DCP\n z= Variable(1,N,name='var_z') # z = ln(mass)\n s= Variable(1,N,name='var_s') # thrust slack parameter\n \n # Parameters\n x0 = Parameter(6, 1, name=\"x0\")\n xf = Parameter(6, 1, name=\"xf\")\n z0_term_inv = Parameter(1, N, name=\"z0_term_inv\", sign='positive')\n z0_term_log = Parameter(1, N, name=\"z0_term_log\")\n g = Parameter(3, 1, name=\"g_vec\")\n p_cs_cos = Parameter(1, N, name='p_cs_cos')\n sparse_params = Parameter(7, 1, name=\"sparse_params\", sign='positive')\n m_wet_log = Parameter(2, 1, name='m_wet_log')\n if (not codegen):\n x0.value = params.x0.reshape(6, 1)\n xf.value = params.xf.reshape(6, 1)\n z0_term_inv.value = params.z0_term_inv.reshape(1, N)\n z0_term_log.value = params.z0_term_log.reshape(1, N)\n g.value = params.g.reshape(3, 1)\n p_cs_cos.value = params.p_cs_cos.reshape(1, N)\n m_wet_log.value = [params.m_wet_log, 0]\n sparse_params.value = np.array([\n params.alpha_dt, \n params.G_max, \n params.V_max, \n params.y_gs_cot, \n params.r1, \n params.r2, \n params.tf\n ]).reshape(7, 1)\n alpha_dt, G_max, V_max, y_gs_cot, r1, r2, tf_ = sparse_params\n\n dt = tf_ * (1/N) # Integration dt\n \n # constraints\n con = [] \n \n con += [x[0:3,0] == x0[0:3]] # initial pos\n con += [x[3:6,0] == x0[3:6]] # initial vel\n \n con += [x[0:3,N-1] == xf[0:3]] # final pos\n con += [x[3:6,N-1]== xf[3:6]] # final vel\n\n con += [s[0,N-1] == 0] # thrust at the end must be zero\n con += [u[:,0] == s[0,0]*np.array([1,0,0])] # thrust direction starts straight\n con += [u[:,N-1] == s[0,N-1]*np.array([1,0,0])] # and ends straight\n con += [z[0,0] == m_wet_log[0,0]] # convexified (7)\n\n \n for n in range(0,N-1):\n \n #dynamics\n con += [x[3:6,n+1] == x[3:6,n] + (dt*0.5)*((u[:,n]+g[:,0]) + (u[:,n+1]+g[:,0]))]\n con += [x[0:3,n+1] == x[0:3,n] + (dt*0.5)*(x[3:6,n+1]+x[3:6,n])]\n\n # glideslope cone\n con += [ norm( (x[0:3,n])[1:3] ) - y_gs_cot*(x[0,n]) <= 0 ]\n \n con += [ norm(x[3:6,n]) <= V_max ] # velocity\n #con += [norm(u[:,n+1]-u[:,n]) <= dt*T_max/m_dry * 3]\n con += [z[0,n+1] == z[0,n] - (alpha_dt*0.5)*(s[0,n] + s[0,n+1])] # mass decreases\n con += [norm(u[:,n]) <= s[0,n]] # limit thrust magnitude & also therefore, mass\n\n # Thrust pointing constraint\n con += [ u[0,n] >= p_cs_cos[0,n]*s[0,n] ]\n\n if n > 0:\n \n #z0_term = m_wet - alpha * r2 * (n) * dt # see ref [2], eq 34,35,36\n \n #z0 = log(z0_term)\n \n z0 = z0_term_log[0,n]\n \n mu_1 = r1*(z0_term_inv[0,n])\n mu_2 = r2*(z0_term_inv[0,n])\n \n #更正一处原项目与论文不符之处\n # 示意图:https://www.desmos.com/calculator/wtcfgnepe1\n con += [s[0,n] >= mu_1 * (1 - (z[0,n] - z0) + (z[0,n] - z0)**2 *0.5)] # lower thrust bound\n con += [s[0,n] <= mu_2 * (1 - (z[0,n] - z0))] # upper thrust bound\n\n\n #Objective\n objective = Minimize(-z[0,N-1])\n problem=Problem(objective, con)\n \n if codegen:\n cpg.codegen(problem, codegen_path)\n else:\n obj_opt = problem.solve(solver=ECOS, verbose=verbose)\n return (\n obj_opt,\n np.array(x.value), # r,v\n np.array(u.value), # u (acceleration)\n np.exp(np.array(z.value)) # mass\n ) if type(x.value) != type(None) else (None, None, None, None)\n\nif __name__ == '__main__':\n if (len(sys.argv) > 2 and sys.argv[1] == 'codegen'):\n codegen_path = sys.argv[2]\n solve(None, None, True)\n else:\n print(\"invalid input\")\n print(sys.argv)\n \n \n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
richardyoung00/qiskit-aqua | [
"a72ac30e9f47890968418fb25023898f7450eb9a"
] | [
"qiskit/aqua/components/uncertainty_models/gaussian_conditional_independence_model.py"
] | [
"# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2019, 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"\nThe Gaussian Conditional Independence Model for Credit Risk\nReference: https://arxiv.org/abs/1412.1183\nDependency between individual risk variables and latent variable is approximated linearly.\n\"\"\"\n\nfrom typing import Optional, List, Union\nimport numpy as np\nfrom scipy.stats.distributions import norm\nfrom qiskit.aqua.circuits.linear_rotation import LinearRotation\nfrom .multivariate_distribution import MultivariateDistribution\nfrom .normal_distribution import NormalDistribution\n\n# pylint: disable=invalid-name\n\n\nclass GaussianConditionalIndependenceModel(MultivariateDistribution):\n \"\"\"\n The Gaussian Conditional Independence Model for Credit Risk\n Reference: https://arxiv.org/abs/1412.1183\n Dependency between individual risk variables and latent variable is approximated linearly.\n \"\"\"\n\n def __init__(self,\n n_normal: int,\n normal_max_value: float,\n p_zeros: Union[List[float], np.ndarray],\n rhos: Union[List[float], np.ndarray],\n i_normal: Optional[Union[List[float], np.ndarray]] = None,\n i_ps: Optional[Union[List[float], np.ndarray]] = None) -> None:\n \"\"\"\n Constructor.\n\n The Gaussian Conditional Independence Model for Credit Risk\n Reference: https://arxiv.org/abs/1412.1183\n\n Args:\n n_normal: number of qubits to represent the latent normal random variable Z\n normal_max_value: min/max value to truncate the latent normal random variable Z\n p_zeros: standard default probabilities for each asset\n rhos: sensitivities of default probability of assets\n with respect to latent variable Z\n i_normal: indices of qubits to represent normal variable\n i_ps: indices of qubits to represent asset defaults\n \"\"\"\n self.n_normal = n_normal\n self.normal_max_value = normal_max_value\n self.p_zeros = p_zeros\n self.rhos = rhos\n self.K = len(p_zeros)\n num_qubits = [n_normal] + [1]*self.K\n\n # set and store indices\n if i_normal is not None:\n self.i_normal = i_normal\n else:\n self.i_normal = range(n_normal)\n\n if i_ps is not None:\n self.i_ps = i_ps\n else:\n self.i_ps = range(n_normal, n_normal + self.K)\n\n # get normal (inverse) CDF and pdf\n def F(x):\n return norm.cdf(x)\n\n def F_inv(x):\n return norm.ppf(x)\n\n def f(x):\n return norm.pdf(x)\n\n # set low/high values\n low = [-normal_max_value] + [0]*self.K\n high = [normal_max_value] + [1]*self.K\n\n # call super constructor\n super().__init__(num_qubits, low=low, high=high)\n\n # create normal distribution\n self._normal = NormalDistribution(n_normal, 0, 1, -normal_max_value, normal_max_value)\n\n # create linear rotations for conditional defaults\n self._slopes = np.zeros(self.K)\n self._offsets = np.zeros(self.K)\n self._rotations = []\n for k in range(self.K):\n\n psi = F_inv(p_zeros[k]) / np.sqrt(1 - rhos[k])\n\n # compute slope / offset\n slope = -np.sqrt(rhos[k]) / np.sqrt(1 - rhos[k])\n slope *= f(psi) / np.sqrt(1 - F(psi)) / np.sqrt(F(psi))\n offset = 2*np.arcsin(np.sqrt(F(psi)))\n\n # adjust for integer to normal range mapping\n offset += slope * (-normal_max_value)\n slope *= 2*normal_max_value / (2**n_normal - 1)\n\n self._offsets[k] = offset\n self._slopes[k] = slope\n\n lry = LinearRotation(slope, offset, n_normal,\n i_state=self.i_normal, i_target=self.i_ps[k])\n self._rotations += [lry]\n\n def build(self, qc, q, q_ancillas=None, params=None):\n\n self._normal.build(qc, q, q_ancillas)\n for lry in self._rotations:\n lry.build(qc, q, q_ancillas)\n"
] | [
[
"scipy.stats.distributions.norm.ppf",
"numpy.sqrt",
"scipy.stats.distributions.norm.cdf",
"scipy.stats.distributions.norm.pdf",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shivchander/binary-classifiers | [
"aa8bd0734c2dad484dbe6316e042d283be9e1dd1"
] | [
"neighborhood.py"
] | [
"#!/usr/bin/env python3\n__author__ = \"Shivchander Sudalairaj\"\n__license__ = \"MIT\"\n\n'''\nNeighborhood based Classifier\n'''\nfrom scipy.spatial import distance\nimport random\n\n\nclass NeighborhoodClassifier:\n def __init__(self, X, y):\n self.X = X # data features\n self.y = y # labels\n\n def find_neighborhood(self, x_test, R):\n\n neighborhood = []\n for xi, yi in zip(self.X, self.y):\n dist = distance.euclidean(xi, x_test)\n if dist <= R: # lies inside the circular neighborhood\n if dist != 0.0: # skipping distance from itself\n neighborhood.append((dist, yi))\n\n neighborhood.sort(key=lambda tup: tup[0]) # sorting the distance in ascending order\n return neighborhood\n\n def predict(self, x_test, R):\n neighbors = self.find_neighborhood(x_test, R) # Finds all the neighbors in the circular neighborhood\n # get the most frequent label class from nearest neighbors\n output_labels = list(dict(neighbors).values())\n if len(output_labels) == 0: # there are no neighbors in the neighborhood\n predicted_label = random.randint(0,1) # making a random prediction\n else:\n predicted_label = max(set(output_labels), key=output_labels.count)\n return predicted_label\n"
] | [
[
"scipy.spatial.distance.euclidean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
mgeorgati/PoPNetV2 | [
"2b1b973cec2835a512e2fb1ed436b78dd23a97cd"
] | [
"data_scripts/sumTifsByRegion.py"
] | [
"import os\r\nimport rasterio\r\nimport numpy as np\r\n\r\n#18subregion names and others\r\n# othna is the only dfference between 2011 and 2017\r\ncountry_dict = {\"australia\" : [\"aus\",\"cxr\", \"cck\", \"hmd\", \"nzl\", \"nfk\"],\r\n \"antarctica\" : [\"ata\"],\r\n \"eastern_asia\":[\"chn\", \"hkg\", \"mac\", \"prk\", \"jpn\", \"mng\", \"kor\"],\r\n \"central_asia\":[\"kaz\",\"kgz\",\"tjk\",\"tkm\",\"uzb\"],\r\n \"western_asia\":[\"irq\",\"jor\",\"lbn\", \"syr\"], #\"tur\",\r\n \"southern_asia\":[\"afg\",\"ind\",\"irn\",\"pak\",\"bgd\",\"btn\",\"npl\", \"mdv\",\"lka\"],\r\n \"southern_eastern_asia\":[\"phl\",\"vnm\"\"brn\",\"khm\",\"idn\",\"lao\",\"mys\",\"mmr\",\"sgp\",\"tha\",\"tls\"],\r\n \"micronesia\": [\"gum\",\"kir\",\"mhl\",\"fsm\",\"nru\",\"mnp\",\"plw\",\"umi\"],\r\n \"malanesia\":[\"fji\",\"ncl\",\"png\",\"slb\",\"vut\"],\r\n \"polynesia\": [\"asm\",\"cok\",\"pyf\",\"niu\",\"pcn\",\"wsm\",\"tkl\",\"ton\",\"tuv\",\"wlf\"],\r\n \"latin_america_and_the_caribbean\": [\"aia\",\"atg\",\"abw\",\"bhs\",\"brb\",\"bes\",\"vgb\",\"cym\",\"cub\",\"cuw\",\"dma\",\"dom\",\"grd\",\"glp\",\"hti\",\"jam\",\"mtq\",\"msr\",\"pri\",\"blm\",\"kna\",\"lca\",\r\n \"maf\",\"vct\",\"sxm\",\"tto\",\"tca\",\"vir\",\"blz\",\"cri\",\"slv\",\"gtm\",\"hnd\",\"mex\",\"nic\",\"pan\",\"arg\",\"bol\",\"bvt\",\"bra\",\"chl\",\"col\",\"ecu\",\"flk\",\"guf\",\"guy\",\"pry\",\"per\",\"sgs\",\r\n \"sur\",\"ury\",\"ven\"],\r\n \"northern_america\":[\"bmu\",\"can\",\"grl\",\"spm\",\"usa\"],\r\n \"eastern_europe\":[\"pol\", \"blr\",\"bgr\",\"cze\",\"hun\",\"mda\",\"rou\",\"rus\",\"svk\",\"ukr\"],\r\n \"southern_europe\":[\"bih\",\"mkd\",\"alb\",\"and\",\"hrv\",\"gib\",\"grc\",\"vat\",\"mlt\",\"mne\",\"prt\",\"ita\",\"smr\",\"srb\",\"svn\",\"esp\"],\r\n \"northern_africa\":[\"mar\",\"dza\",\"egy\",\"lby\",\"sdn\",\"tun\",\"esh\"],\r\n \"sub_saharan_africa\":[\"cmr\",\"som\",\"nga\",\"sen\", \"iot\",\"bdi\",\"com\",\"dji\",\"eri\",\"eth\",\"atf\",\"ken\",\"mdg\",\"mwi\",\"mus\",\"myt\",\"moz\",\"reu\",\"rwa\",\"syc\",\"ssd\",\"uga\",\"tza\",\"zmb\",\"zwe\",\r\n \"ago\",\"caf\",\"tcd\",\"cog\",\"cod\",\"gnq\",\"gab\",\"stp\",\"bwa\",\"swz\",\"lso\",\"nam\",\"zaf\",\"ben\",\"bfa\",\"cpv\",\"civ\",\"gmb\",\"gha\",\"gin\",\"gnb\",\"lbr\",\"mli\",\"mrt\",\"ner\",\"shn\",\"sle\",\"tgo\"],\r\n \"western_europe\": [\"deu\",\"nld\",\"aut\",\"bel\",\"fra\",\"lie\",\"lux\",\"mco\",\"che\"],\r\n \"northern_europe\": [\"gbr\",\"nor\",\"irl\",\"swe\",\"lva\",\"est\",\"isl\",\"sjm\",\"fro\",\"fin\",\"jey\",\"imn\",\"ltu\",\"ggy\",\"dnk\",\"ala\"],\r\n \"others\": [\"ocean\",\"twn\",\"unk\",\"othe\",\"urs\",\"otham\",\"yug\",\"othaf\",\"cenam\",\"nstd\",\"othme\",\"othas\",\"scg\",\"tch\",\"othna\",\"sta\"] }\r\n\r\ndef sumUpTif(dictionary, tif_path, out_folder, year):\r\n pop_list=[]\r\n if not os.path.exists(out_folder):\r\n os.makedirs(out_folder)\r\n\r\n for key in dictionary:\r\n for value in dictionary[key]:\r\n for file in os.listdir(tif_path):\r\n #print(value)\r\n if file.endswith('{}.tif'.format(value)) and file.startswith('cph_{}'.format(year)):\r\n print(key, '--',file)\r\n with rasterio.open('{}/{}'.format(tif_path, file)) as src:\r\n pop = src.read(1)\r\n p1 = src.crs\r\n height = src.shape[0],\r\n width= src.shape[1],\r\n bb= src.transform,\r\n pop[pop<0]=0\r\n pop_list.append(pop)\r\n\r\n total_pop=np.add.reduce(pop_list)\r\n print(key, total_pop)\r\n\r\n with rasterio.open('{0}/cph_{1}_pop_origin_new_dnk.tif'.format(tif_path,year)) as dd:\r\n\r\n new_dataset = rasterio.open(\r\n '{0}/totalPop_{1}_{2}.tif'.format(out_folder,key,year),\r\n 'w',\r\n driver='GTiff',\r\n height=total_pop.shape[0],\r\n width=total_pop.shape[1],\r\n count=1,\r\n dtype=total_pop.dtype,\r\n crs=p1,\r\n transform= dd.transform\r\n )\r\n new_dataset.write(total_pop, 1)\r\n new_dataset.close()\r\n\r\nyear= \"2011\"\r\ntif_path =\"C:\\FUME\\DST_Data\\Project_data\\\\temp_tif\\\\{}\".format(year)\r\nout_folder =\"C:\\FUME\\DST_Data\\Project_data\\\\temp_tif\\\\{}\\\\merged\".format(year)\r\nsumUpTif(country_dict, tif_path, out_folder,year)\r\n\r\n#mismatch = [\"atg\",\"kir\",\"kna\",\"stp\",\"tls\",\"vut\",\"othna\"]"
] | [
[
"numpy.add.reduce"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
csmithchicago/n2v | [
"82b73cea6fbc79b6c85002a561d364b250836ee1"
] | [
"n2v/models/care_isotropic.py"
] | [
"from __future__ import print_function, unicode_literals, absolute_import, division\n\nimport numpy as np\nfrom scipy.ndimage.interpolation import zoom\n\nfrom n2v.internals.probability import ProbabilisticPrediction\nfrom .care_standard import CARE\nfrom ..internals.predict import predict_direct\nfrom ..data import PercentileNormalizer, PadAndCropResizer\nfrom ..utils import _raise, axes_check_and_normalize\n\n\nclass IsotropicCARE(CARE):\n \"\"\"CARE network for isotropic image reconstruction.\n\n Extends :class:`n2v.models.CARE` by replacing prediction\n (:func:`predict`, :func:`predict_probabilistic`) to do isotropic reconstruction.\n \"\"\"\n\n def predict(self, img, axes, factor, normalizer=PercentileNormalizer(), resizer=PadAndCropResizer(), batch_size=8):\n \"\"\"Apply neural network to raw image for isotropic reconstruction.\n\n See :func:`CARE.predict` for documentation.\n\n Parameters\n ----------\n factor : float\n Upsampling factor for Z axis. It is important that this is chosen in correspondence\n to the subsampling factor used during training data generation.\n batch_size : int\n Number of image slices that are processed together by the neural network.\n Reduce this value if out of memory errors occur.\n\n \"\"\"\n return self._predict_mean_and_scale(img, axes, factor, normalizer, resizer, batch_size)[0]\n\n\n def predict_probabilistic(self, img, axes, factor, normalizer=PercentileNormalizer(), resizer=PadAndCropResizer(), batch_size=8):\n \"\"\"Apply neural network to raw image to predict probability distribution for isotropic restored image.\n\n See :func:`CARE.predict_probabilistic` for documentation.\n\n Parameters\n ----------\n factor : float\n Upsampling factor for Z axis. It is important that this is chosen in correspondence\n to the subsampling factor used during training data generation.\n batch_size : int\n Number of image slices that are processed together by the neural network.\n Reduce this value if out of memory errors occur.\n\n \"\"\"\n self.config.probabilistic or _raise(ValueError('This is not a probabilistic model.'))\n mean, scale = self._predict_mean_and_scale(img, axes, factor, normalizer, resizer, batch_size)\n return ProbabilisticPrediction(mean, scale)\n\n\n def _predict_mean_and_scale(self, img, axes, factor, normalizer, resizer, batch_size):\n \"\"\"Apply neural network to raw image to restore isotropic resolution.\n\n See :func:`predict` for parameter explanations.\n\n Returns\n -------\n tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray` or None)\n If model is probabilistic, returns a tuple `(mean, scale)` that defines the parameters\n of per-pixel Laplace distributions. Otherwise, returns the restored image via a tuple `(restored,None)`\n\n \"\"\"\n normalizer, resizer = self._check_normalizer_resizer(normalizer, resizer)\n axes = axes_check_and_normalize(axes,img.ndim)\n 'Z' in axes or _raise(ValueError())\n axes_tmp = 'CZ' + axes.replace('Z','').replace('C','')\n _permute_axes = self._make_permute_axes(axes, axes_tmp)\n channel = 0\n\n x = _permute_axes(img)\n\n self.config.n_channel_in == x.shape[channel] or _raise(ValueError())\n np.isscalar(factor) and factor > 0 or _raise(ValueError())\n\n def scale_z(arr,factor):\n return zoom(arr,(1,factor,1,1),order=1)\n\n # normalize\n x = normalizer.before(x,axes_tmp)\n\n # scale z up (second axis)\n x_scaled = scale_z(x,factor)\n\n # resize: make (x,y,z) image dimensions divisible by power of 2 to allow downsampling steps in unet\n div_n = 2 ** self.config.unet_n_depth\n x_scaled = resizer.before(x_scaled,div_n,exclude=channel)\n\n # move channel to the end\n x_scaled = np.moveaxis(x_scaled, channel, -1)\n channel = -1\n\n # u1: first rotation and prediction\n x_rot1 = self._rotate(x_scaled, axis=1, copy=False)\n u_rot1 = predict_direct(self.keras_model, x_rot1, channel_in=channel, channel_out=channel, single_sample=False,\n batch_size=batch_size, verbose=0)\n u1 = self._rotate(u_rot1, -1, axis=1, copy=False)\n\n # u2: second rotation and prediction\n x_rot2 = self._rotate(self._rotate(x_scaled, axis=2, copy=False), axis=0, copy=False)\n u_rot2 = predict_direct(self.keras_model, x_rot2, channel_in=channel, channel_out=channel, single_sample=False,\n batch_size=batch_size, verbose=0)\n u2 = self._rotate(self._rotate(u_rot2, -1, axis=0, copy=False), -1, axis=2, copy=False)\n\n n_channel_predicted = self.config.n_channel_out * (2 if self.config.probabilistic else 1)\n u_rot1.shape[channel] == n_channel_predicted or _raise(ValueError())\n u_rot2.shape[channel] == n_channel_predicted or _raise(ValueError())\n\n # move channel back to the front\n u1 = np.moveaxis(u1, channel, 0)\n u2 = np.moveaxis(u2, channel, 0)\n channel = 0\n\n # resize after prediction\n u1 = resizer.after(u1,exclude=channel)\n u2 = resizer.after(u2,exclude=channel)\n\n # combine u1 & u2\n mean1, scale1 = self._mean_and_scale_from_prediction(u1,axis=channel)\n mean2, scale2 = self._mean_and_scale_from_prediction(u2,axis=channel)\n # avg = lambda u1,u2: (u1+u2)/2 # arithmetic mean\n avg = lambda u1,u2: np.sqrt(np.maximum(u1,0)*np.maximum(u2,0)) # geometric mean\n mean, scale = avg(mean1,mean2), None\n if self.config.probabilistic:\n scale = np.maximum(scale1,scale2)\n\n if normalizer.do_after and self.config.n_channel_in==self.config.n_channel_out:\n mean, scale = normalizer.after(mean, scale)\n\n mean, scale = _permute_axes(mean,undo=True), _permute_axes(scale,undo=True)\n\n return mean, scale\n\n\n @staticmethod\n def _rotate(arr, k=1, axis=1, copy=True):\n \"\"\"Rotate by 90 degrees around the first 2 axes.\"\"\"\n if copy:\n arr = arr.copy()\n\n k = k % 4\n\n arr = np.rollaxis(arr, axis, arr.ndim)\n\n if k == 0:\n res = arr\n elif k == 1:\n res = arr[::-1].swapaxes(0, 1)\n elif k == 2:\n res = arr[::-1, ::-1]\n else:\n res = arr.swapaxes(0, 1)[::-1]\n\n res = np.rollaxis(res, -1, axis)\n return res\n\n"
] | [
[
"numpy.rollaxis",
"numpy.maximum",
"numpy.isscalar",
"numpy.moveaxis",
"scipy.ndimage.interpolation.zoom"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"0.15",
"1.4",
"0.16",
"1.0",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"0.10",
"0.17",
"1.3"
],
"tensorflow": []
}
] |
ArthurTolley/skypy | [
"5621877ada75c667b1af7e665b02a91026f7ef0f"
] | [
"skypy/galaxy/ellipticity.py"
] | [
"\"\"\"Galaxy ellipticity module.\n\nThis module provides facilities to sample the ellipticities of galaxies.\n\"\"\"\n\nimport numpy as np\nfrom scipy import stats\n\n\n__all__ = [\n 'beta_ellipticity',\n 'ryden04',\n]\n\n\ndef beta_ellipticity(e_ratio, e_sum, size=None):\n r'''Galaxy ellipticities sampled from a reparameterized beta distribution.\n\n The ellipticities follow a beta distribution parameterized by\n :math:`e_{\\rm ratio}` and :math:`e_{\\rm sum}` as presented in [1]_ Section\n III.A.\n\n Parameters\n ----------\n e_ratio : array_like\n Mean ellipticity of the distribution, must be between 0 and 1.\n e_sum : array_like\n Parameter controlling the width of the distribution, must be positive.\n\n Notes\n -----\n The probability distribution function :math:`p(e)` for ellipticity\n :math:`e` is given by a beta distribution:\n\n .. math::\n\n p(e) \\sim \\frac{\\Gamma(a+b)}{\\Gamma(a) \\Gamma(b)} x^{a-1} (1-x)^{b-1}\n\n for :math:`0 <= e <= 1`, :math:`a = e_{\\rm sum} e_{\\rm ratio}`,\n :math:`b = e_{\\rm sum} (1 - e_{\\rm ratio})`, :math:`0 < e_{\\rm ratio} < 1`\n and :math:`e_{\\rm sum} > 0`, where :math:`\\Gamma` is the gamma function.\n\n References\n ----------\n .. [1] Kacprzak T., Herbel J., Nicola A. et al., arXiv:1906.01018\n\n Examples\n --------\n Sample 10000 random variates from the Kacprzak model with\n :math:`e_{\\rm ratio} = 0.5` and :math:`e_{\\rm sum} = 1.0`:\n\n >>> from skypy.galaxy.ellipticity import beta_ellipticity\n >>> ellipticity = beta_ellipticity(0.5, 1.0, size=10000)\n\n '''\n\n # convert to beta distribution parameters\n a = e_sum * e_ratio\n b = e_sum * (1.0 - e_ratio)\n\n # sample from the beta distribution\n return np.random.beta(a, b, size)\n\n\ndef ryden04(mu_gamma, sigma_gamma, mu, sigma, size=None):\n r'''Ellipticity distribution of Ryden (2004).\n\n The ellipticity is sampled by randomly projecting a 3D ellipsoid with\n principal axes :math:`A > B > C` [1]_. The distribution of the axis ratio\n :math:`\\gamma = C/A` is a truncated normal with mean :math:`\\mu_\\gamma` and\n standard deviation :math:`\\sigma_\\gamma`. The distribution of\n :math:`\\epsilon = \\log(1 - B/A)` is truncated normal with mean :math:`\\mu`\n and standard deviation :math:`\\sigma`.\n\n Parameters\n ----------\n mu_gamma : array_like\n Mean of the truncated Gaussian for :math:`\\gamma`.\n sigma_gamma : array_like\n Standard deviation for :math:`\\gamma`.\n mu : array_like\n Mean of the truncated Gaussian for :math:`\\epsilon`.\n sigma : array_like\n Standard deviation for :math:`\\epsilon`.\n size : int or tuple of ints or None\n Size of the sample. If `None` the size is inferred from the parameters.\n\n References\n ----------\n .. [1] Ryden B. S., 2004, ApJ, 601, 214\n\n Examples\n --------\n Sample 10000 random variates from the Ryden (2004) model with parameters\n :math:`\\mu_\\gamma = 0.222`, :math:`\\sigma_\\gamma = 0.056`,\n :math:`\\mu = -1.85`, and :math:`\\sigma = 0.89`.\n\n >>> from skypy.galaxy.ellipticity import ryden04\n >>> ellipticity = ryden04(0.222, 0.056, -1.85, 0.89, size=10000)\n\n '''\n\n # get size if not given\n if size is None:\n size = np.broadcast(mu_gamma, sigma_gamma, mu, sigma).shape\n\n # truncation for gamma standard normal\n a_gam = np.divide(np.negative(mu_gamma), sigma_gamma)\n b_gam = np.divide(np.subtract(1, mu_gamma), sigma_gamma)\n\n # truncation for log(epsilon) standard normal\n a_eps = -np.inf\n b_eps = np.divide(np.negative(mu), sigma)\n\n # draw gamma and epsilon from truncated normal -- eq.s (10)-(11)\n gam = stats.truncnorm.rvs(a_gam, b_gam, mu_gamma, sigma_gamma, size=size)\n eps = np.exp(stats.truncnorm.rvs(a_eps, b_eps, mu, sigma, size=size))\n\n # scipy 1.5.x bug: make scalar if size is empty\n if size == () and not np.isscalar(gam): # pragma: no cover\n gam, eps = gam.item(), eps.item()\n\n # draw random viewing angle (theta, phi)\n cos2_theta = np.random.uniform(low=-1., high=1., size=size)**2\n cos2_phi = np.cos(np.random.uniform(low=0., high=2*np.pi, size=size))**2\n sin2_theta = 1 - cos2_theta\n sin2_phi = 1 - cos2_phi\n\n # compute Binney's ABC -- eq.s (13)-(15)\n A = (1 - eps*(2-eps)*sin2_phi)*cos2_theta + gam**2*sin2_theta\n B = (2*eps*(2-eps))**2*cos2_theta*sin2_phi*cos2_phi\n C = 1 - eps*(2-eps)*cos2_phi\n\n # compute axis ratio q -- eq. (12)\n q = np.sqrt((A+C-np.sqrt((A-C)**2+B))/(A+C+np.sqrt((A-C)**2+B)))\n\n # return the ellipticity\n return (1-q)/(1+q)\n"
] | [
[
"numpy.random.beta",
"numpy.sqrt",
"numpy.subtract",
"numpy.random.uniform",
"numpy.broadcast",
"numpy.isscalar",
"numpy.negative",
"scipy.stats.truncnorm.rvs"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
evankozierok/PyPRAM-to-Mesa | [
"a8e47d688b9db9b3e3c7ecd9d5bf77c4a310a521"
] | [
"Samples/Migration/run_abm.py"
] | [
"from Samples.Migration.Migration.MigrationModel import MigrationModel\nfrom mesa.datacollection import DataCollector\nimport matplotlib.pyplot as plt\nimport time\n\n# the original PRAM has 1000000 agents; however, you may want to keep it smaller in the ABM (this sample has 1000)\n# because of memory and time concerns!\npop_size = 1000\n\nmodel = MigrationModel(\n datacollector=DataCollector(\n model_reporters={\n \"Migrating\": lambda m: sum([a.is_migrating for a in m.schedule.agents]),\n \"Settled\": lambda m: sum([hasattr(a, 'has_settled') and a.has_settled for a in m.schedule.agents]),\n \"Dead\": lambda m: pop_size - len(m.schedule.agents)\n }\n )\n)\n\nruns = 48\n\nt0 = time.time()\nfor i in range(runs):\n model.step()\ntime_elapsed = time.time() - t0\nprint(f'Time elapsed in {runs} iterations: {time_elapsed} seconds')\n\nplot = model.datacollector.get_model_vars_dataframe().plot(\n figsize=(8, 6),\n title=f'Migration ABM Model - {runs} iterations',\n)\nplot.set_xlabel('Iteration')\nplot.set_ylabel('Agents')\nplt.tight_layout()\nplt.savefig('Migration_ABM_out.png', dpi=300)\n"
] | [
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.savefig"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pratikpatil92/customer-segmentation | [
"860cb09413ff1218b502f0488f9b37ca5a483908"
] | [
"code.py"
] | [
"# --------------\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# load data\ndf = pd.read_csv(path)\n# check the null values\ndf.isnull().sum()\n# drop null values\ndf.dropna(subset=['Description','CustomerID'],inplace=True)\n# check the null values\ndf.isnull().sum()\n# only take one country\ndf = df[df.Country== 'United Kingdom']\n\n# create new colums returns\ndf['Return']=df.InvoiceNo.str.contains('C')\n# store the result in purchase \ndf['Purchase'] = np.where(df[\"Return\"]==True,0,1)\n\n\n# --------------\n# create new dataframe customer\ncustomers = pd.DataFrame({'CustomerID': df['CustomerID'].unique()},dtype=int)\n\n# calculate the recency\ndf['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])\ndf['Recency'] = pd.to_datetime(\"2011-12-10\") - (df['InvoiceDate'])\n\n# remove the time factor\ndf.Recency = df.Recency.dt.days\n\n# purchase equal to one \ntemp = df[df['Purchase']==1]\n\n# customers latest purchase day\nrecency=temp.groupby(by='CustomerID',as_index=False).min()\ncustomers=customers.merge(recency[['CustomerID','Recency']],on='CustomerID')\n\n\n\n\n# --------------\n# Removing invoice number duplicates\n\ntemp_1=df[['CustomerID','InvoiceNo','Purchase']]\ntemp_1.drop_duplicates(subset=['InvoiceNo'],inplace=True)\n\n# calculte the frequency of the purchases\nannual_invoice=temp_1.groupby(by='CustomerID',as_index=False).sum()\nannual_invoice.rename(columns={'Purchase':'Frequency'},inplace=True)\n\n# merge in the Customer\ncustomers=customers.merge(annual_invoice,on='CustomerID')\nprint(customers.shape)\n\n\n# --------------\n# Create amount and groupby based on customer id\ndf['Amount']=df['Quantity'] * df['UnitPrice']\nannual_sales=df.groupby(by='CustomerID',as_index=False).sum()\nannual_sales.rename(columns={'Amount':'monetary'},inplace=True)\n\n# added in the customer dataframe\ncustomers=customers.merge(annual_sales[['CustomerID','monetary']],on='CustomerID')\n\n\n\n\n# --------------\n# negative monetory removed because they returned the object \ncustomers['monetary']=np.where(customers['monetary']<0,0,customers['monetary']) \n\n# log transform\ncustomers['Recency_log']=np.log(customers['Recency']+0.1) # there values equals to zero to avoid log zero increase by +0.1\ncustomers['Frequency_log']=np.log(customers['Frequency'])\ncustomers['Monetary_log']=np.log(customers['monetary']+0.1)\n\n\n# --------------\n# import packages\nfrom sklearn.cluster import KMeans\n\n# Code starts here\n\n# Empty list for storing WCSS across all values of k\ndist = []\n\n# Iterate from 1-9\nfor i in range(1,10):\n # Initialize KMeans algorithm\n km=KMeans(n_clusters=i,init='k-means++', max_iter=300, n_init=10, random_state=0)\n # Fit on data\n km.fit(customers.iloc[:,1:7])\n # Append WCSS to list storing WCSS\n dist.append(km.inertia_)\n\n# Initialize figure\nplt.figure(figsize=(10,10))\n\n# Line plot # clusters on X-axis and WCSS on Y-axis \nplt.plot(range(1,10),dist)\nplt.title('Elbow Method')\nplt.xlabel('Number of clusters')\nplt.ylabel('wcss')\nplt.show()\n\n# Code ends here\n\n\n# --------------\n\n# Code starts here\n\n# initialize KMeans object\ncluster = KMeans(n_clusters=3, init='k-means++', max_iter=300, n_init=10, random_state=0)\n\n# create 'cluster' column\ncustomers['cluster'] = cluster.fit_predict(customers.iloc[:,1:7])\n\n# plot the cluster\n\ncustomers.plot.scatter(x= 'Frequency_log', y= 'Monetary_log', c='cluster', colormap='viridis')\nplt.show()\n\n# Code ends here\n\n\n"
] | [
[
"numpy.log",
"pandas.to_datetime",
"pandas.read_csv",
"matplotlib.pyplot.title",
"sklearn.cluster.KMeans",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"numpy.where",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
HAL-lucination/segfuse | [
"df19ae53d43ac6ef98b2ed0ddabb14857b2b903a"
] | [
"Utils/Segmentation.py"
] | [
"import sys\r\nsys.path.append(\"Utils/seg/\")\r\n\r\n# System libs\r\nimport os, csv, torch, numpy, scipy.io, PIL.Image, torchvision.transforms\r\n# Our libs\r\nimport mit_semseg as mit_semseg\r\nfrom mit_semseg.models import ModelBuilder, SegmentationModule\r\nfrom mit_semseg.utils import colorEncode\r\n\r\ndef get_seg(input):\r\n colors = scipy.io.loadmat('Utils/seg/data/color150.mat')['colors']\r\n names = {}\r\n with open('Utils/seg/data/object150_info.csv') as f:\r\n reader = csv.reader(f)\r\n next(reader)\r\n for row in reader:\r\n names[int(row[0])] = row[5].split(\";\")[0]\r\n\r\n # Network Builders\r\n net_encoder = ModelBuilder.build_encoder(\r\n arch='resnet50dilated',\r\n fc_dim=2048,\r\n weights='Utils/seg/ckpt/ade20k-resnet50dilated-ppm_deepsup/encoder_epoch_20.pth')\r\n net_decoder = ModelBuilder.build_decoder(\r\n arch='ppm_deepsup',\r\n fc_dim=2048,\r\n num_class=150,\r\n weights='Utils/seg/ckpt/ade20k-resnet50dilated-ppm_deepsup/decoder_epoch_20.pth',\r\n use_softmax=True)\r\n\r\n crit = torch.nn.NLLLoss(ignore_index=-1)\r\n segmentation_module = SegmentationModule(net_encoder, net_decoder, crit)\r\n segmentation_module.eval()\r\n segmentation_module.cuda()\r\n\r\n # Load and normalize one image as a singleton tensor batch\r\n pil_to_tensor = torchvision.transforms.Compose([\r\n torchvision.transforms.ToTensor(),\r\n torchvision.transforms.Normalize(\r\n mean=[0.485, 0.456, 0.406], # These are RGB mean+std values\r\n std=[0.229, 0.224, 0.225]) # across a large photo dataset.\r\n ])\r\n # [income 1 3 256 512]\r\n img_original = torchvision.transforms.ToPILImage()(input[0].cpu()).convert(\"RGB\")\r\n img_data = pil_to_tensor(img_original)\r\n singleton_batch = {'img_data': img_data[None].cuda()}\r\n output_size = img_data.shape[1:]\r\n\r\n # Run the segmentation at the highest resolution.\r\n with torch.no_grad():\r\n scores = segmentation_module(singleton_batch, segSize=output_size)\r\n\r\n # Get the predicted scores for each pixel\r\n _, pred = torch.max(scores, dim=1)\r\n pred = pred.cpu()\r\n\r\n return pred\r\n"
] | [
[
"torch.nn.NLLLoss",
"torch.no_grad",
"torch.max"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AntoniaSophia/deep-reinforcement-learning | [
"1d1c77039eea22fcf6726c35c3dd2563adfcb519"
] | [
"lab-taxi/agent.py"
] | [
"import numpy as np\nfrom collections import defaultdict\n\nclass Agent:\n\n def __init__(self, nA=6):\n \"\"\" Initialize agent.\n\n Params\n ======\n - nA: number of actions available to the agent\n \"\"\"\n self.mode = 1 # 0 = Sarsa , 1 = Sarsamax , 2 = Expected Sarsa\n\n self.nA = nA\n self.Q = defaultdict(lambda: np.zeros(self.nA))\n self.episode = 1\n\n self.epsilon = 1\n self.gamma = 1\n self.alpha = 0.02\n \n if self.mode == 0:\n pass\n elif self.mode == 1:\n pass\n elif self.mode == 2:\n self.epsilon = 0.0006\n else:\n print(\"Error: mode {} is not defined!!!!\" , self.mode) \n\n def get_policy(self, Q_s):\n \"\"\" obtains the action probabilities corresponding to epsilon-greedy policy \"\"\"\n policy_s = np.ones(self.nA) * self.epsilon / self.nA\n best_a = np.argmax(Q_s)\n policy_s[best_a] = 1 - self.epsilon + (self.epsilon / self.nA)\n return policy_s\n\n def select_action(self, state):\n \"\"\" Given the state, select an action.\n\n Params\n ======\n - state: the current state of the environment\n\n Returns\n =======\n - action: an integer, compatible with the task's action space\n \"\"\"\n return np.random.choice(self.nA, p=self.get_policy(self.Q[state]))\n\n def step(self, last_state, last_action, reward, next_state, done):\n \"\"\" Update the agent's knowledge, using the most recently sampled tuple.\n\n Params\n ======\n - state: the previous state of the environment\n - action: the agent's previous choice of action\n - reward: last reward received\n - next_state: the current state of the environment\n - done: whether the episode is complete (True or False)\n \"\"\"\n if done:\n self.episode += 1\n\n if self.mode == 0:\n self.epsilon = 1/self.episode\n self.epsilon = max(self.epsilon,0.0001)\n self.step_sarsa(last_state, last_action, reward, next_state, done)\n elif self.mode == 1:\n self.epsilon = 1/self.episode\n #self.epsilon = 0.005\n self.epsilon = max(self.epsilon,0.0001)\n self.step_sarsamax(last_state, last_action, reward, next_state, done)\n elif self.mode == 2:\n self.step_expectedsarsa(last_state, last_action, reward, next_state, done)\n \n\n def step_sarsa(self, last_state, last_action, reward, next_state, done):\n \"\"\" Update the agent's knowledge, using the most recently sampled tuple.\n\n Params\n ======\n - state: the previous state of the environment\n - action: the agent's previous choice of action\n - reward: last reward received\n - next_state: the current state of the environment\n - done: whether the episode is complete (True or False)\n \"\"\"\n Q_default = 0 # q_default is the default value in case there is no next_state\n next_action = self.select_action(next_state)\n \n if not done:\n self.Q[last_state][last_action] = self.Q[last_state][last_action] + \\\n self.alpha*(reward + self.gamma*self.Q[next_state][next_action] - \\\n self.Q[last_state][last_action])\n else:\n self.Q[last_state][last_action] = self.Q[last_state][last_action] + \\\n self.alpha*(reward + self.gamma*Q_default - \\\n self.Q[last_state][last_action])\n\n\n\n def step_sarsamax(self, last_state, last_action, reward, next_state, done):\n \"\"\" Update the agent's knowledge, using the most recently sampled tuple.\n\n Params\n ======\n - state: the previous state of the environment\n - action: the agent's previous choice of action\n - reward: last reward received\n - next_state: the current state of the environment\n - done: whether the episode is complete (True or False)\n \"\"\"\n\n self.Q[last_state][last_action] = self.Q[last_state][last_action] + \\\n self.alpha*(reward + self.gamma*np.max(self.Q[next_state]) - \\\n self.Q[last_state][last_action])\n\n def step_expectedsarsa(self, last_state, last_action, reward, next_state, done):\n \"\"\" Update the agent's knowledge, using the most recently sampled tuple.\n\n Params\n ======\n - state: the previous state of the environment\n - action: the agent's previous choice of action\n - reward: last reward received\n - next_state: the current state of the environment\n - done: whether the episode is complete (True or False)\n \"\"\"\n Q_default = 0 # q_default is the default value in case there is no next_state\n \n policy_s = np.ones(self.nA) * self.epsilon / self.nA # current policy (for next state S')\n policy_s[np.argmax(self.Q[next_state])] = 1 - self.epsilon + (self.epsilon / self.nA) # greedy action\n # NOTE: np.dot(Q[next_state], policy_s) = scalar product of two vectors Q[next_state] and policy_s which\n # is sum(Q[next_state][1]*policy_s[1] + Q[next_state][2]*policy_s[2] + ...) \n \n if not done:\n self.Q[last_state][last_action] = self.Q[last_state][last_action] + \\\n self.alpha*(reward + self.gamma*np.dot(self.Q[next_state], policy_s) - \\\n self.Q[last_state][last_action])\n else:\n self.Q[last_state][last_action] = self.Q[last_state][last_action] + \\\n self.alpha*(reward + self.gamma*Q_default - \\\n self.Q[last_state][last_action])\n"
] | [
[
"numpy.dot",
"numpy.ones",
"numpy.max",
"numpy.argmax",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AdrianLundell/HelmertTool | [
"1ee5dbed4d2a935b193d4fe83339b5da4d12b36f"
] | [
"HelmertTool/visualise.py"
] | [
"import pandas as pd \nimport numpy as np\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nfrom HelmertTool.io import get_path \n\ndef plot_sites3D(df: pd.DataFrame):\n fig = plt.figure()\n ax = fig.add_subppytholot(projection='3d')\n ax.scatter3D(df.X, df.Y, df.Z)\n plt.show()\n\ndef plot_sites(df: pd.DataFrame, ax: plt.Axes):\n \"\"\"Plots the station sites scattered over a world map to ax\"\"\"\n \n img = mpimg.imread(get_path(\"map.png\"))\n ax.imshow(img, extent = (-180,180, -90, 90))\n \n ax.scatter(df.LAT, df.LONG, s=4)\n #for x,y,s in zip(df.LAT, df.LONG, df.Station_Name):\n # plt.text(x,y,s, fontsize=5)\n ax.grid()\n \ndef plot_residuals(df, ax1, ax2):\n \"\"\"Plots UEN-residuals scattered over a world map to axes\"\"\"\n img = mpimg.imread(get_path(\"map.png\"))\n ax1.imshow(img, extent = (-180,180, -90, 90))\n ax2.imshow(img, extent = (-180,180, -90, 90))\n\n ax1.set_title(\"NE-residual components\")\n ax2.set_title(\"UP-residual component\")\n\n #ax1.quiver(df_from.LAT, df_from.LONG, df_from.dE, df_from.dN, color=\"b\")\n if not df is None:\n q = ax1.quiver(df.LONG, df.LAT, df.dE, df.dN, color=\"k\", scale=2)\n ax1.quiverkey(q, 0.9,1.05, 10**-1, \"0.1m\", color = \"red\")\n\n q = ax2.quiver(df.LONG, df.LAT, np.zeros(len(df.dU)), df.dU, scale=2)\n ax2.quiverkey(q, 0.9,1.05, 10**-1, \"0.1m\", color = \"red\")\n \n ax1.grid()\n ax2.grid()\n\ndef plot_residuals_hist(df_from, df_transformed, ax1, ax2):\n \"\"\"Plots UEN-residuals plotted over value\"\"\"\n ax1.hist([df_from.dU, df_from.dE, df_from.dN], 200, stacked=True)\n ax2.hist([df_transformed.dU, df_transformed.dE, df_transformed.dN], 200, stacked=True)\n\n"
] | [
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bvsk35/Curve-Fitting | [
"549bd3b2f9a0d136f8abd392b52d15a3ef86b1ac"
] | [
"CurveFitting.py"
] | [
"# This file applied Back Propagation Algorithm\r\n# for curve fitting problem\r\n# Neural Network Architecture has\r\n# 3 layers: Input, Hidden and Output\r\n\r\n# Import Required Libraries\r\nimport numpy\r\nimport matplotlib.pyplot as plt\r\n\r\n# Parameters\r\nEpoch = numpy.array([]) # No. of Training Iterations\r\nMSE = numpy.array([]) # Mean Squared Error\r\nM2 = 0 # Momentum Vector for Layer 2\r\nM3 = 0 # Momentum Vector for Layer 3\r\nbeta = 0.9 # Momentum Parameter\r\neta = 4 # Learning Rate\r\ntol = 0.005 # Terminating Condition\r\niterations = 0\r\nmax_iter = 1e6 # Maximum Allowed Iterations\r\n\r\n# Load the Data: Points X, D, Weights for 2nd and 3rd layer\r\nX = numpy.loadtxt('X.txt')\r\nD = numpy.loadtxt('D.txt')\r\nW_Layer_2_Guess = numpy.loadtxt('Layer2WeightsInitialGuess.txt')\r\nW_Layer_3_Guess = numpy.loadtxt('Layer3WeightsInitialGuess.txt')\r\n\r\n# Required Functions\r\ndef ForwardPass(x, W_Layer_2, W_Layer_3):\r\n # V2 and V3 are locally induced fields at Layer 2 and 3\r\n # Y2 and Y3 are locally induced fields at Layer 2 and 3\r\n temp_x = numpy.concatenate(([1], [x]), axis=0)\r\n V2 = numpy.dot(W_Layer_2, temp_x)\r\n Y2 = numpy.tanh(V2)\r\n temp_y = numpy.concatenate(([1], [Y2]), axis=0)\t\r\n V3 = numpy.dot(W_Layer_3, temp_y)\r\n Y3 = V3\r\n return V2, V3, Y2, Y3\r\n\r\ndef BackwardPass(x, d, W_Layer_2, W_Layer_3, V2, V3, Y2, Y3):\r\n feedback_error = (2/300) * (d - Y3)\r\n delta3 = feedback_error * 1\r\n Derivative_Layer2 = numpy.array([1 - numpy.square(numpy.tanh(i)) for i in V2])\r\n delta2 = numpy.multiply(W_Layer_3[1:]*delta3, Derivative_Layer2)\r\n Gradient_Layer_2 = numpy.dot(-delta2[:, numpy.newaxis], numpy.concatenate(([[1]], [[x]]), axis=1))\r\n Gradient_Layer_3 = numpy.dot(-delta3, numpy.concatenate(([1], Y2), axis=0))\r\n return Gradient_Layer_2, Gradient_Layer_3\r\n\r\ndef UpdateWeights(eta, beta, M2, M3, Gradient_Layer_2, Gradient_Layer_3, W_Layer_2, W_Layer_3):\r\n M2 = (beta * M2) - (eta * Gradient_Layer_2) # Momentum\r\n M3 = (beta * M3) - (eta * Gradient_Layer_3) # Momentum\r\n W_Layer_2 = W_Layer_2 + M2\r\n W_Layer_3 = W_Layer_3 + M3\r\n return W_Layer_2, W_Layer_3, M2, M3\r\n\r\ndef CalculateMSE(X, D, W_Layer_2, W_Layer_3):\r\n row = numpy.size(X)\r\n n = 300\r\n sum = 0\r\n for i in range(0, row):\r\n V2, V3, Y2, Y3 = ForwardPass(X[i], W_Layer_2, W_Layer_3)\r\n sum = sum + numpy.square(D[i] - Y3)/n\r\n return sum\r\n\r\ndef CheckLearningrate(eta, MSE):\r\n if MSE[-1] > MSE[-2]:\r\n eta = 0.4 * eta\r\n return eta\r\n\r\n# Main Loop\r\nwhile iterations <= max_iter:\r\n if iterations == 0:\r\n # Back Propagation\r\n row = numpy.size(X)\r\n temp_w2 = numpy.array([W_Layer_2_Guess])\r\n temp_w3 = numpy.array([W_Layer_3_Guess])\r\n for i in range(0, row):\r\n V2, V3, Y2, Y3 = ForwardPass(X[i], temp_w2[-1], temp_w3[-1])\r\n g2, g3 = BackwardPass(X[i], D[i], temp_w2[-1], temp_w3[-1], V2, V3, Y2, Y3)\r\n w2, w3, M2, M3 = UpdateWeights(eta, beta, M2, M3, g2, g3, temp_w2[-1], temp_w3[-1])\r\n temp_w2 = numpy.concatenate((temp_w2, [w2]), axis=0)\r\n temp_w3 = numpy.concatenate((temp_w3, [w3]), axis=0)\r\n # Book Keeping\r\n W2 = numpy.concatenate(([W_Layer_2_Guess], [temp_w2[-1]]), axis=0)\r\n W3 = numpy.concatenate(([W_Layer_3_Guess], [temp_w3[-1]]), axis=0)\r\n Epoch = numpy.concatenate((Epoch, [iterations]), axis=0)\r\n mse = CalculateMSE(X, D, W2[-1], W3[-1])\r\n MSE = numpy.concatenate((MSE, [mse]), axis=0)\r\n # Print\r\n print('Epoch: ', iterations, ' MSE: ', mse, ' Learning Rate: ', eta, '\\n')\r\n # Next...\r\n iterations += 1\r\n else:\r\n # Back Propagation\r\n row = numpy.size(X)\r\n temp_w2 = numpy.array([W2[-1]])\r\n temp_w3 = numpy.array([W3[-1]])\r\n for i in range(0, row):\r\n V2, V3, Y2, Y3 = ForwardPass(X[i], temp_w2[-1], temp_w3[-1])\r\n g2, g3 = BackwardPass(X[i], D[i], temp_w2[-1], temp_w3[-1], V2, V3, Y2, Y3)\r\n w2, w3, M2, M3 = UpdateWeights(eta, beta, M2, M3, g2, g3, temp_w2[-1], temp_w3[-1])\r\n temp_w2 = numpy.concatenate((temp_w2, [w2]), axis=0)\r\n temp_w3 = numpy.concatenate((temp_w3, [w3]), axis=0)\r\n # Book Keeping\r\n W2 = numpy.concatenate((W2, [temp_w2[-1]]), axis=0)\r\n W3 = numpy.concatenate((W3, [temp_w3[-1]]), axis=0)\r\n Epoch = numpy.concatenate((Epoch, [iterations]), axis=0)\r\n mse = CalculateMSE(X, D, W2[-1], W3[-1])\r\n MSE = numpy.concatenate((MSE, [mse]), axis=0)\r\n # Print\r\n print('Epoch: ', iterations, ' MSE: ', mse, ' Learning Rate: ', eta, '\\n')\r\n # Check\r\n # if (MSE[-1] - MSE[-2]).all() < tol:\r\n # print('Optimal Weights Reached')\r\n # break\r\n if MSE[-1] < tol:\r\n print('Optimal Weights Reached')\r\n break\r\n eta = CheckLearningrate(eta, MSE)\r\n # Next...\r\n iterations += 1\r\n\r\n# Save Final Weights\r\nnumpy.savetxt('FinalOptimalWeights2.txt', W2[-1])\r\nnumpy.savetxt('FinalOptimalWeights3.txt', W3[-1])\r\n\r\n# Plot\r\n# Plot 1\r\nfig, ax1 = plt.subplots()\r\nrow = numpy.size(X)\r\nY = numpy.array([])\r\nfor i in range(0, row):\r\n V2, V3, Y2, Y3 = ForwardPass(X[i], W2[-1], W3[-1])\r\n Y = numpy.concatenate((Y, [Y3]), axis=0)\r\nax1.plot(X, D, 'b.', label='Actual Curve')\r\nax1.plot(X, Y, 'r.', label='Curve Fit')\r\nplt.title(r'Curve Fitting for the equation $ y = \\sin{20x} + 3 x + v $ where v is random variable and v $ \\in [-0.1, 0.1] $')\r\nplt.xlabel(r'X $\\rightarrow$')\r\nplt.ylabel(r'Y $\\rightarrow$')\r\nplt.legend()\r\n# Plot 2\r\nfig, ax2 = plt.subplots()\r\nax2.plot(Epoch, MSE, label='Mean Squared Error')\r\nplt.title('No of Training Iterations VS Mean Squared Error (MSE)')\r\nplt.xlabel(r'Epoch $\\rightarrow$')\r\nplt.ylabel(r'MSE $\\rightarrow$')\r\nplt.legend()\r\nplt.show()\r\n"
] | [
[
"numpy.square",
"matplotlib.pyplot.legend",
"numpy.dot",
"matplotlib.pyplot.title",
"numpy.multiply",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"numpy.concatenate",
"numpy.size",
"numpy.savetxt",
"matplotlib.pyplot.xlabel",
"numpy.tanh",
"numpy.array",
"numpy.loadtxt",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
OSU-AIMS/golf-smart | [
"fdc0794dedc21ea832e946013fcb487e9f043f09"
] | [
"scripts/smart_golf_utilities.py"
] | [
"#!/usr/bin/env python3\n#\n# Software License Agreement (Apache 2.0 License)\n# Copyright (c) 2022, The Ohio State University\n#\n# Author: C. Cooper\n#\n# Description:\n# Support class offering tools for robot kinematics and other related calculations.\n\n\nimport numpy as np\n\n\nclass ROBOT_KINEMATICS():\n \"\"\"\n This is the class for the wire frame robot used in all the scripts.\n This is the way the forward kinematics are calculated for the hill climbs.\n It is also useful for looking at the robot. \n \"\"\"\n \n def __init__(self, links, axis = [[0,0,1],[0,1,0],[0,1,0],[0,1,0],[1,0,0]]):\n\n \t# Axis defined as they would be in the defalt zero position of the robot\n self.links = links\n self.axis = axis\n \n def rotateAxis(self, t, vec):\n \n #Rotation matrix just taken straight from wikepedia\n \n C = 1-np.cos(t)\n x,y,z = vec\n\n Rot = [[x**2*C+np.cos(t), x*y*C-z*np.sin(t), z*x*C+y*np.sin(t)],\n [x*y*C+z*np.sin(t), y**2*C+np.cos(t), z*y*C-x*np.sin(t)],\n [x*z*C-y*np. sin(t), y*z*C+x*np.sin(t), z**2*C+np.cos(t)]]\n\n return Rot\n\n def findEnd(self, angles):\n #This function takes an input vector of angles and will output the end position as\n #well as all of the vectors of the robot NOT TRANSLATED FROM THE ORIGIN\n \n v1 = [0,0,0] #Base thing that moves with S\n v2 = [0,0,0] #First link that moves with L\n v3 = [0,0,0] #Second link that moves with U\n v4 = [0,0,0] #Shaft link that moves with B\n v5 = [0,0,0] #Club head that moves with T/R\n \n #Starting Vector\n v1_0 = [self.links[0]/np.sqrt(2), 0, self.links[0]/np.sqrt(2)]\n v5_0 = [0, self.links[4], 0]\n \n #First rotation\n v1 = np.dot(v1_0,self.rotateAxis(angles[0], self.axis[0]))\n axis1 = np.dot(self.axis[1],self.rotateAxis(angles[0], self.axis[0]))\n axis2 = np.dot(self.axis[2],self.rotateAxis(angles[0], self.axis[0]))\n axis3 = np.dot(self.axis[3],self.rotateAxis(angles[0], self.axis[0]))\n axis4 = np.dot(self.axis[4],self.rotateAxis(angles[0], self.axis[0]))\n \n #Second Rotation\n v2 = (self.links[1]/self.links[0])*np.dot(v1,self.rotateAxis(angles[1], axis1))\n axis2 = np.dot(axis2,self.rotateAxis(angles[1], axis1))\n axis3 = np.dot(axis3,self.rotateAxis(angles[1], axis1))\n axis4 = np.dot(axis4,self.rotateAxis(angles[1], axis1))\n \n #Third Rotation\n v3 = (self.links[2]/self.links[1])*np.dot(v2,self.rotateAxis(angles[2], axis2))\n axis3 = np.dot(axis3,self.rotateAxis(angles[2], axis2))\n axis4 = np.dot(axis4,self.rotateAxis(angles[2], axis2))\n\n #Fourth rotation\n axis3 = np.dot(axis3,self.rotateAxis(angles[3], v3/self.links[2])) # Can only rotate around unit vectors\n axis4 = np.dot(axis4,self.rotateAxis(angles[3], v3/self.links[2]))\n \n #Fifth Rotation\n v4 = (self.links[3]/self.links[2])*np.dot(v3,self.rotateAxis(angles[4], axis3))\n axis4 = np.dot(axis4,self.rotateAxis(angles[4], axis3))\n \n #Sixth Rotation\n v5 = np.dot(v5_0,self.rotateAxis(angles[5], axis4))\n \n x_val = v1[0]+v2[0]+v3[0]+v4[0]+v5[0]\n y_val = v1[1]+v2[1]+v3[1]+v4[1]+v5[1]\n z_val = v1[2]+v2[2]+v3[2]+v4[2]+v5[2]\n \n return [x_val, y_val, z_val, v1, v2, v3, v4, v5]\n \n def distanceFromTarget(self,targ,angles):\n \n #Simply finds the distance between a given end from a set of angles and a target end point\n \n end = self.findEnd(angles)\n dist = (end[0]-targ[0])**2+(end[1]-targ[1])**2+(end[2]-targ[2])**2\n \n return dist\n\n\ndef drawRobot2(v1,v2,v3,v4,v5):\n \n \"\"\"\n The purpose of this function is just to convert the five vectors into\n (x,y,z) arrays for plotting. \n \n If you ever see drawRobot, that one is old so delete that\n \"\"\"\n\n x = np.zeros(6,)\n y = np.zeros(6,)\n z = np.zeros(6,)\n \n x[0],y[0],z[0] = [0,0,0]\n x[1],y[1],z[1] = v1\n x[2],y[2],z[2] = v1+v2\n x[3],y[3],z[3] = v1+v2+v3\n x[4],y[4],z[4] = v1+v2+v3+v4\n x[5],y[5],z[5] = v1+v2+v3+v4+v5\n \n # print(x)\n # print(y)\n # print(z)\n \n return x,y,z # The arrays are all just 1x6\n\n\ndef Interp(theta, intervals):\n \"\"\"\n This just turns the 7 points into 90 points linearly spaced in joint space\n \"\"\"\n\n long_theta = [] \n parts = np.zeros((6,intervals-1))\n \n for i in range(int(len(theta)-1)):\n delta = (theta[i+1]-theta[i])/intervals\n parts[i] = np.linspace(theta[i],theta[i+1]-delta,intervals-1)\n for j in range(int(len(parts))):\n long_theta = np.append(long_theta,parts[j])\n \n return long_theta"
] | [
[
"numpy.sqrt",
"numpy.linspace",
"numpy.cos",
"numpy.sin",
"numpy.append",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hemraj4545/Data-Structures-and-Algorithms-in-Python | [
"e13becf63097e86dc073bc2de3b8d5586623743d"
] | [
"Graphs/BFS.py"
] | [
"import numpy\nfrom collections import deque\n\n\nclass Graph:\n def __init__(self, vertices):\n self._vertices = vertices\n self._adjMatrix = numpy.zeros((vertices, vertices))\n self._size = 0\n\n def add_edge(self, u, v, w=1):\n self._adjMatrix[u][v] = w\n\n def delete_edge(self, u, v):\n self._adjMatrix[u][v] = 0\n\n def bfs(self, source):\n i = source\n q = deque()\n q.append(source)\n l = [0] * self._vertices\n l[i] = 1\n print(i, end='->')\n while q:\n i = q.popleft()\n for j in range(self._vertices):\n if self._adjMatrix[i][j] == 1 and l[j] == 0:\n print(j, end='->')\n q.append(j)\n l[j] = 1\n\n\ng = Graph(7)\ng.add_edge(0, 1)\ng.add_edge(0, 5)\ng.add_edge(0, 4)\ng.add_edge(0, 2)\ng.add_edge(2, 5)\ng.add_edge(2, 3)\ng.add_edge(6, 3)\ng.add_edge(1, 3)\ng.add_edge(6, 4)\ng.add_edge(1, 6)\ng.bfs(0)\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ashimgiyanani/ProjectTemplate_python | [
"3135e8976aac751049a6da34a550db0fe045f0bb"
] | [
"fun/FnImportOneDas.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 10 13:33:36 2021\n\n@author: giyash\n\"\"\"\n\ndef FnImportOneDas(tstart, tend, channel_paths, ch_names,sampleRate, target_folder):\n\timport pandas as pd\n\timport numpy as np\n\timport sys, os\n\tsys.path.append(r\"c:\\Users\\giyash\\OneDrive - Fraunhofer\\Python\\Scripts\\userModules\")\n\timport matlab2py as m2p\n\tfrom pythonAssist import now, struct\n\tsys.path.append(\"c:/Users/giyash/OneDrive - Fraunhofer/Python/Scripts/OneDasExplorer/Python Connector\")\n\tfrom odc_exportData import odc_exportData\n\timport datetime as dt\n\tfrom datetime import datetime\n\n ## Initializations\n\ttry:\n\t\ttstart, tend\n\texcept NameError:\n\t\tsys.exit('tstart and tend necessary')\n\n\tbegin = tstart \n\tend = tend #- dt.timedelta(0,0,0,0,10)\n\ttry:\n\t\tsampleRate\n\texcept NameError:\n\t\tsampleRate = 1/600\n\n\tif sampleRate == 1:\n\t\tFs = 's'\n\telif sampleRate == 1/4:\n\t\tFs = '4s'\n\telif sampleRate == 1/600:\n\t\tFs = '10T'\n\telif (sampleRate == 20):\n\t\tFs = '50ms'\n\telse:\n\t\tFs = 'H'\n\n\tfrom pandas.tseries.frequencies import to_offset\n\tt = pd.date_range(start=begin + pd.to_timedelta(to_offset(Fs)), end=end, freq = Fs) \n\n\t# ch_names =['Shead', 'Struehead', 'Swd_scada', 'Syaw'] #\n\ttry:\n\t\ttarget_folder\n\texcept NameError:\n\t\t# target folder points to default folder\n\t\ttarget_folder = r\"c:/Users/giyash/OneDrive - Fraunhofer/Python/Scripts/OneDasExplorer/Python Connector/data\"\n\n\ttry:\n\t\tch_names, channel_paths\n\texcept NameError:\n\t\tprint('[{}]: Channel names and paths are missing'.format(now()))\n\t\tsys.exit('Rerun the script by providing the channel names and path')\n\n\tdata = odc_exportData(begin, end, channel_paths, target_folder)\n\todcData = struct()\n\tsetattr(odcData,'t',np.array(t))\n\tpdData = pd.DataFrame(dtype=np.float64(),index=t)\n\n\t# assign the data values to variable names that are given by ch_names\n\ti = 0\n\tfor keys in data:\n\t\tpdData[ch_names[i]] = np.array(data[keys].values)\n\t\tsetattr(odcData,ch_names[i], np.array(data[keys].values)) \n\t\ti = i+1\n\n\tt = pd.DatetimeIndex(t) # concert to datetime64 format\n\tsetattr(odcData,'t',t)\n\tpdData['t'] = t\n\treturn odcData, pdData, t\n\n\n# Example:\n# must all be of the same sample rate\n# channel_paths = [\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0000_V1/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/P0420_RotorSpdRaw/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0010_V2/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0020_V3/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0030_V4/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0040_V5/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0050_V6/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0060_Precipitation/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0070_D1/600 s_mean_polar',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0100_D4/600 s_mean_polar',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0110_D5/600 s_mean_polar',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0200_B1/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0210_B2/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/GENERAL_DAQ/M0220_T1/600 s_mean',\n# '/AIRPORT/AD8_PROTOTYPE/ISPIN/SaDataValid/600 s',\n# '/AIRPORT/AD8_PROTOTYPE/ISPIN/WS_free_avg/600 s',\n# '/AIRPORT/AD8_PROTOTYPE/ISPIN/DataOK/600 s',\n# '/AIRPORT/AD8_PROTOTYPE/LIDAR_2020/BlackTC_110m_HWS_hub/600 s',\n# '/AIRPORT/AD8_PROTOTYPE/LIDAR_2020/BluePO_110m_HWS_hub/600 s',\n# '/AIRPORT/AD8_PROTOTYPE/LIDAR_2020/GreenPO_110m_HWS_hub/600 s',\n# '/AIRPORT/AD8_PROTOTYPE/LIDAR_2020/BlackTC_110m_HWS_hub_availability/600 s',\n# '/AIRPORT/AD8_PROTOTYPE/LIDAR_2020/BluePO_110m_HWS_hub_availability/600 s',\n# '/AIRPORT/AD8_PROTOTYPE/LIDAR_2020/GreenPO_110m_HWS_hub_availability/600 s',\n# '/AIRPORT/AD8_PROTOTYPE/WIND_CUBE/WC_115m_Wind_Speed/600 s',\n# \t]\n\n# ch_names = [\n# 'v1',\n# 'omega',\n# 'v2',\n# 'v3',\n# 'v4',\n# 'v5',\n# 'v6',\n# 'prec',\n# 'd1',\n# 'd4',\n# 'd5',\n# 'b1',\n# 'b2',\n# 'T1',\n# 's_valid',\n# 's_V', \n# 's_ok',\n# 'btc_v110',\n# 'bpo_v110', \n# 'gpo_v110', \n# 'btc_Av110', \n# 'bpo_Av110', \n# 'gpo_Av110', \n# 'wc_v115',\n# \t]\n\n# import datetime as dt\n# from datetime import datetime\n# tstart = datetime.strptime('2021-01-13_00-00-00', '%Y-%m-%d_%H-%M-%S') # Select start date in the form yyyy-mm-dd_HH-MM-SS\n# # funktioniert\n# tend = datetime.strptime('2021-01-19_00-00-00', '%Y-%m-%d_%H-%M-%S') # Select start date in the form yyyy-mm-dd_HH-MM-SS\n# # funktioniert nicht\n# # tend = datetime.strptime('2021-02-01_00-00-00', '%Y-%m-%d_%H-%M-%S') # Select start date in the form yyyy-mm-dd_HH-MM-SS\n# target_folder = r\"c:/Users/giyash/OneDrive - Fraunhofer/Python/Scripts/OneDasExplorer/Python Connector/data\"\n# sampleRate= 600\n# odc, df, t = FnImportOneDas(tstart, tend, channel_paths, ch_names, sampleRate, target_folder)\n"
] | [
[
"pandas.tseries.frequencies.to_offset",
"numpy.array",
"numpy.float64",
"pandas.DatetimeIndex"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"0.19",
"0.24",
"0.20",
"1.0",
"0.25"
],
"scipy": [],
"tensorflow": []
}
] |
fderyckere/pgmpy | [
"236a74b117a11f7230a3d110bb33fadd18c0acff"
] | [
"pgmpy/tests/test_readwrite/test_BIF.py"
] | [
"import unittest\n\nimport numpy as np\nimport numpy.testing as np_test\nimport networkx as nx\n\nfrom pgmpy.readwrite import BIFReader, BIFWriter\nfrom pgmpy.models import BayesianModel\nfrom pgmpy.factors.discrete import TabularCPD\nfrom pgmpy.extern.six.moves import map, range\n\n\nclass TestBIFReader(unittest.TestCase):\n def setUp(self):\n\n self.reader = BIFReader(\n string=\"\"\"\n // Bayesian Network in the Interchange Format\n // Produced by BayesianNetworks package in JavaBayes\n // Output created Sun Nov 02 17:49:49 GMT+00:00 1997\n // Bayesian network\n network \"Dog-Problem\" { //5 variables and 5 probability distributions\n property \"credal-set constant-density-bounded 1.1\" ;\n }\n variable \"light-on\" { //2 values\n type discrete[2] { \"true\" \"false\" };\n property \"position = (218, 195)\" ;\n }\n variable \"bowel-problem\" { //2 values\n type discrete[2] { \"true\" \"false\" };\n property \"position = (335, 99)\" ;\n }\n variable \"dog-out\" { //2 values\n type discrete[2] { \"true\" \"false\" };\n property \"position = (300, 195)\" ;\n }\n variable \"hear-bark\" { //2 values\n type discrete[2] { \"true\" \"false\" };\n property \"position = (296, 268)\" ;\n }\n variable \"family-out\" { //2 values\n type discrete[2] { \"true\" \"false\" };\n property \"position = (257, 99)\" ;\n }\n probability ( \"light-on\" \"family-out\" ) { //2 variable(s) and 4 values\n (true) 0.6 0.4 ;\n (false) 0.05 0.95 ;\n }\n probability ( \"bowel-problem\" ) { //1 variable(s) and 2 values\n table 0.01 0.99 ;\n }\n probability ( \"dog-out\" \"bowel-problem\" \"family-out\" ) { //3 variable(s) and 8 values\n table 0.99 0.97 0.9 0.3 0.01 0.03 0.1 0.7 ;\n }\n probability ( \"hear-bark\" \"dog-out\" ) { //2 variable(s) and 4 values\n table 0.7 0.01 0.3 0.99 ;\n }\n probability ( \"family-out\" ) { //1 variable(s) and 2 values\n table 0.15 0.85 ;\n }\n \"\"\",\n include_properties=True,\n )\n\n self.water_model = BIFReader(\n \"pgmpy/tests/test_readwrite/testdata/water.bif\", include_properties=True\n )\n\n def test_network_name(self):\n\n name_expected = \"Dog-Problem\"\n self.assertEqual(self.reader.network_name, name_expected)\n\n def test_get_variables(self):\n\n var_expected = [\n \"light-on\",\n \"bowel-problem\",\n \"dog-out\",\n \"hear-bark\",\n \"family-out\",\n ]\n self.assertListEqual(self.reader.get_variables(), var_expected)\n\n def test_states(self):\n\n states_expected = {\n \"bowel-problem\": [\"true\", \"false\"],\n \"dog-out\": [\"true\", \"false\"],\n \"family-out\": [\"true\", \"false\"],\n \"hear-bark\": [\"true\", \"false\"],\n \"light-on\": [\"true\", \"false\"],\n }\n states = self.reader.get_states()\n for variable in states_expected:\n self.assertListEqual(states_expected[variable], states[variable])\n\n def test_get_property(self):\n\n property_expected = {\n \"bowel-problem\": [\"position = (335, 99)\"],\n \"dog-out\": [\"position = (300, 195)\"],\n \"family-out\": [\"position = (257, 99)\"],\n \"hear-bark\": [\"position = (296, 268)\"],\n \"light-on\": [\"position = (218, 195)\"],\n }\n prop = self.reader.get_property()\n for variable in property_expected:\n self.assertListEqual(property_expected[variable], prop[variable])\n\n def test_get_values(self):\n\n cpd_expected = {\n \"bowel-problem\": np.array([[0.01], [0.99]]),\n \"dog-out\": np.array([[0.99, 0.97, 0.9, 0.3], [0.01, 0.03, 0.1, 0.7]]),\n \"family-out\": np.array([[0.15], [0.85]]),\n \"hear-bark\": np.array([[0.7, 0.01], [0.3, 0.99]]),\n \"light-on\": np.array([[0.6, 0.05], [0.4, 0.95]]),\n }\n cpd = self.reader.variable_cpds\n for variable in cpd_expected:\n np_test.assert_array_equal(cpd_expected[variable], cpd[variable])\n\n def test_get_values_reordered(self):\n\n cancer_values1 = BIFReader(\n string=\"\"\"\n network unknown {\n }\n variable Pollution {\n type discrete [ 2 ] { low, high };\n }\n variable Smoker {\n type discrete [ 2 ] { True, False };\n }\n variable Cancer {\n type discrete [ 2 ] { True, False };\n }\n probability ( Cancer | Pollution, Smoker ) {\n (low, True) 0.03, 0.97;\n (low, False) 0.001, 0.999;\n (high, True) 0.05, 0.95;\n (high, False) 0.02, 0.98;\n }\"\"\"\n ).get_values()\n\n cancer_values2 = BIFReader(\n string=\"\"\"\n network unknown {\n }\n variable Pollution {\n type discrete [ 2 ] { low, high };\n }\n variable Smoker {\n type discrete [ 2 ] { True, False };\n }\n variable Cancer {\n type discrete [ 2 ] { True, False };\n }\n probability ( Cancer | Pollution, Smoker ) {\n (low, True) 0.03, 0.97;\n (high, True) 0.05, 0.95;\n (low, False) 0.001, 0.999;\n (high, False) 0.02, 0.98;\n }\"\"\"\n ).get_values()\n\n for var in cancer_values1:\n np_test.assert_array_equal(cancer_values1[var], cancer_values2[var])\n\n def test_get_parents(self):\n\n parents_expected = {\n \"bowel-problem\": [],\n \"dog-out\": [\"bowel-problem\", \"family-out\"],\n \"family-out\": [],\n \"hear-bark\": [\"dog-out\"],\n \"light-on\": [\"family-out\"],\n }\n parents = self.reader.get_parents()\n for variable in parents_expected:\n self.assertListEqual(parents_expected[variable], parents[variable])\n\n def test_get_edges(self):\n\n edges_expected = [\n [\"family-out\", \"dog-out\"],\n [\"bowel-problem\", \"dog-out\"],\n [\"family-out\", \"light-on\"],\n [\"dog-out\", \"hear-bark\"],\n ]\n self.assertListEqual(sorted(self.reader.variable_edges), sorted(edges_expected))\n\n def test_get_model(self):\n edges_expected = [\n (\"family-out\", \"dog-out\"),\n (\"bowel-problem\", \"dog-out\"),\n (\"family-out\", \"light-on\"),\n (\"dog-out\", \"hear-bark\"),\n ]\n nodes_expected = [\n \"bowel-problem\",\n \"hear-bark\",\n \"light-on\",\n \"dog-out\",\n \"family-out\",\n ]\n edge_expected = {\n \"bowel-problem\": {\"dog-out\": {\"weight\": None}},\n \"dog-out\": {\"hear-bark\": {\"weight\": None}},\n \"family-out\": {\"dog-out\": {\"weight\": None}, \"light-on\": {\"weight\": None}},\n \"hear-bark\": {},\n \"light-on\": {},\n }\n node_expected = {\n \"bowel-problem\": {\"weight\": None, \"position\": \"(335, 99)\"},\n \"dog-out\": {\"weight\": None, \"position\": \"(300, 195)\"},\n \"family-out\": {\"weight\": None, \"position\": \"(257, 99)\"},\n \"hear-bark\": {\"weight\": None, \"position\": \"(296, 268)\"},\n \"light-on\": {\"weight\": None, \"position\": \"(218, 195)\"},\n }\n cpds_expected = [\n np.array([[0.01], [0.99]]),\n np.array([[0.99, 0.97, 0.9, 0.3], [0.01, 0.03, 0.1, 0.7]]),\n np.array([[0.15], [0.85]]),\n np.array([[0.7, 0.01], [0.3, 0.99]]),\n np.array([[0.6, 0.05], [0.4, 0.95]]),\n ]\n model = self.reader.get_model()\n for cpd_index in range(0, len(cpds_expected)):\n np_test.assert_array_equal(\n model.get_cpds()[cpd_index].get_values(), cpds_expected[cpd_index]\n )\n self.assertDictEqual(dict(model.nodes), node_expected)\n if nx.__version__.startswith(\"1\"):\n self.assertDictEqual(model.edge, edge_expected)\n else:\n self.assertDictEqual(dict(model.adj), edge_expected)\n\n self.assertListEqual(sorted(model.nodes()), sorted(nodes_expected))\n self.assertListEqual(sorted(model.edges()), sorted(edges_expected))\n\n def test_water_model(self):\n model = self.water_model.get_model()\n self.assertEqual(len(model.nodes()), 32)\n self.assertEqual(len(model.edges()), 66)\n self.assertEqual(len(model.get_cpds()), 32)\n\n def tearDown(self):\n del self.reader\n\n\nclass TestBIFWriter(unittest.TestCase):\n def setUp(self):\n variables = [\n \"kid\",\n \"bowel-problem\",\n \"dog-out\",\n \"family-out\",\n \"hear-bark\",\n \"light-on\",\n ]\n\n edges = [\n [\"family-out\", \"dog-out\"],\n [\"bowel-problem\", \"dog-out\"],\n [\"family-out\", \"light-on\"],\n [\"dog-out\", \"hear-bark\"],\n ]\n\n cpds = {\n \"kid\": np.array([[0.3], [0.7]]),\n \"bowel-problem\": np.array([[0.01], [0.99]]),\n \"dog-out\": np.array([[0.99, 0.01, 0.97, 0.03], [0.9, 0.1, 0.3, 0.7]]),\n \"family-out\": np.array([[0.15], [0.85]]),\n \"hear-bark\": np.array([[0.7, 0.3], [0.01, 0.99]]),\n \"light-on\": np.array([[0.6, 0.4], [0.05, 0.95]]),\n }\n\n states = {\n \"kid\": [\"true\", \"false\"],\n \"bowel-problem\": [\"true\", \"false\"],\n \"dog-out\": [\"true\", \"false\"],\n \"family-out\": [\"true\", \"false\"],\n \"hear-bark\": [\"true\", \"false\"],\n \"light-on\": [\"true\", \"false\"],\n }\n\n parents = {\n \"kid\": [],\n \"bowel-problem\": [],\n \"dog-out\": [\"family-out\", \"bowel-problem\"],\n \"family-out\": [],\n \"hear-bark\": [\"dog-out\"],\n \"light-on\": [\"family-out\"],\n }\n\n properties = {\n \"kid\": [\"position = (100, 165)\"],\n \"bowel-problem\": [\"position = (335, 99)\"],\n \"dog-out\": [\"position = (300, 195)\"],\n \"family-out\": [\"position = (257, 99)\"],\n \"hear-bark\": [\"position = (296, 268)\"],\n \"light-on\": [\"position = (218, 195)\"],\n }\n\n self.model = BayesianModel()\n self.model.add_nodes_from(variables)\n self.model.add_edges_from(edges)\n\n tabular_cpds = []\n for var in sorted(cpds.keys()):\n values = cpds[var]\n cpd = TabularCPD(\n var,\n len(states[var]),\n values,\n evidence=parents[var],\n evidence_card=[\n len(states[evidence_var]) for evidence_var in parents[var]\n ],\n )\n tabular_cpds.append(cpd)\n self.model.add_cpds(*tabular_cpds)\n\n for node, properties in properties.items():\n for prop in properties:\n prop_name, prop_value = map(lambda t: t.strip(), prop.split(\"=\"))\n self.model.nodes[node][prop_name] = prop_value\n\n self.writer = BIFWriter(model=self.model)\n\n def test_str(self):\n self.expected_string = \"\"\"network unknown {\n}\nvariable bowel-problem {\n type discrete [ 2 ] { bowel-problem_0, bowel-problem_1 };\n property position = (335, 99) ;\n property weight = None ;\n}\nvariable dog-out {\n type discrete [ 2 ] { dog-out_0, dog-out_1 };\n property position = (300, 195) ;\n property weight = None ;\n}\nvariable family-out {\n type discrete [ 2 ] { family-out_0, family-out_1 };\n property position = (257, 99) ;\n property weight = None ;\n}\nvariable hear-bark {\n type discrete [ 2 ] { hear-bark_0, hear-bark_1 };\n property position = (296, 268) ;\n property weight = None ;\n}\nvariable kid {\n type discrete [ 2 ] { kid_0, kid_1 };\n property position = (100, 165) ;\n property weight = None ;\n}\nvariable light-on {\n type discrete [ 2 ] { light-on_0, light-on_1 };\n property position = (218, 195) ;\n property weight = None ;\n}\nprobability ( bowel-problem ) {\n table 0.01, 0.99 ;\n}\nprobability ( dog-out | bowel-problem, family-out ) {\n table 0.99, 0.01, 0.97, 0.03, 0.9, 0.1, 0.3, 0.7 ;\n}\nprobability ( family-out ) {\n table 0.15, 0.85 ;\n}\nprobability ( hear-bark | dog-out ) {\n table 0.7, 0.3, 0.01, 0.99 ;\n}\nprobability ( kid ) {\n table 0.3, 0.7 ;\n}\nprobability ( light-on | family-out ) {\n table 0.6, 0.4, 0.05, 0.95 ;\n}\n\"\"\"\n self.maxDiff = None\n self.assertEqual(self.writer.__str__(), self.expected_string)\n"
] | [
[
"numpy.testing.assert_array_equal",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mike-gimelfarb/cascade_correlation_neural_networks | [
"ca9ce7dfb2c145d5c0b67b496c586fc441967518"
] | [
"examples/run_spirals.py"
] | [
"import os\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\nimport string\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport tensorflow.compat.v1 as tf\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\n \nfrom cascor import activations, losses\nfrom cascor.model import CCNN\nfrom cascor.monitor import EarlyStoppingMonitor\nfrom cascor.units.perceptron import TensorflowPerceptron\n\ndef run():\n \n # ==================================================================================\n # DATA\n # ================================================================================== \n # load data\n num = 1000\n \n \n def generate_two_spirals(n_points, noise=.5):\n n = np.sqrt(np.random.rand(n_points, 1)) * 780 * (2 * np.pi) / 360\n d1x = -np.cos(n) * n + np.random.rand(n_points, 1) * noise\n d1y = np.sin(n) * n + np.random.rand(n_points, 1) * noise\n return (np.vstack((np.hstack((d1x, d1y)), np.hstack((-d1x, -d1y)))),\n np.hstack((np.zeros(n_points), np.ones(n_points))))\n \n \n X, y = generate_two_spirals(num)\n plt.title('training set')\n plt.plot(X[y == 0, 0], X[y == 0, 1], '.', label='class 1')\n plt.plot(X[y == 1, 0], X[y == 1, 1], '.', label='class 2')\n plt.legend()\n plt.show()\n y1 = LabelEncoder().fit_transform(y)\n Y = pd.get_dummies(y1).values\n \n # train-test split\n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=0)\n \n # ==================================================================================\n # MODEL\n # ================================================================================== \n # layer for outputs\n output_unit = TensorflowPerceptron(activations=[tf.nn.softmax],\n loss_function=losses.negative_cross_entropy,\n stopping_rule=EarlyStoppingMonitor(1e-3, 400, 5000, normalize=True),\n optimizer=tf.train.AdamOptimizer,\n optimizer_args={'learning_rate' : 0.005},\n batch_size=256)\n \n # layer for candidates\n candidate_unit = TensorflowPerceptron(activations=[tf.nn.tanh] * 5,\n loss_function=losses.S_cascor,\n stopping_rule=EarlyStoppingMonitor(1e-3, 500, 5000, normalize=True),\n optimizer=tf.train.AdamOptimizer,\n optimizer_args={'learning_rate' : 0.05},\n batch_size=999999)\n \n # cascade correlation network\n ccnn = CCNN(2, 2,\n output_unit=output_unit, candidate_unit=candidate_unit,\n metric_function=losses.accuracy,\n lambda_param=0.8)\n \n # ==================================================================================\n # TRAINING\n # ================================================================================== \n result = ccnn.train(X_train, y_train,\n stopping_rule=EarlyStoppingMonitor(1e-10, 10, 10),\n valid_X=X_test, valid_y=y_test)\n \n \n # ==================================================================================\n # PLOTTING\n # ================================================================================== \n def plot_boundary(xx, yy, samples, classes, probs): \n f, ax = plt.subplots(figsize=(5, 5))\n contour = ax.contourf(xx, yy, probs, 100, cmap=\"RdBu\", vmin=0, vmax=1)\n ax_c = f.colorbar(contour)\n ax_c.set_label(\"$P(y = 1)$\")\n ax_c.set_ticks([0, .25, .5, .75, 1])\n K = np.unique(classes).size\n for k in range(K):\n xyk = samples[classes == k]\n ax.scatter(xyk[:, 0], xyk[:, 1], s=6, label='class {}'.format(k))\n plt.legend()\n plt.show()\n \n \n # plot the boundary for classification\n samples, classes = generate_two_spirals(num)\n xmin, xmax = -15., 15.\n ymin, ymax = -15., 15.\n xstp, ystp = 0.05, 0.05\n xx, yy = np.mgrid[xmin:xmax:xstp, ymin:ymax:ystp]\n grid = np.c_[xx.ravel(), yy.ravel()]\n y_pred = ccnn.predict(grid)[0][:, 0].reshape(xx.shape)\n plot_boundary(xx, yy, samples, classes, y_pred)\n"
] | [
[
"matplotlib.pyplot.legend",
"numpy.hstack",
"matplotlib.pyplot.title",
"numpy.unique",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.subplots",
"numpy.sin",
"matplotlib.pyplot.plot",
"sklearn.preprocessing.LabelEncoder",
"numpy.cos",
"numpy.ones",
"numpy.random.rand",
"matplotlib.pyplot.show",
"numpy.zeros",
"pandas.get_dummies"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
LSST/utils | [
"894b03d5c625bfacc91cb7f2a74889d56e580028"
] | [
"python/lsst/utils/tests.py"
] | [
"# This file is part of utils.\n#\n# Developed for the LSST Data Management System.\n# This product includes software developed by the LSST Project\n# (https://www.lsst.org).\n# See the COPYRIGHT file at the top-level directory of this distribution\n# for details of code ownership.\n#\n# Use of this source code is governed by a 3-clause BSD-style\n# license that can be found in the LICENSE file.\n\n\"\"\"Support code for running unit tests\"\"\"\n\n__all__ = [\n \"init\",\n \"MemoryTestCase\",\n \"ExecutablesTestCase\",\n \"getTempFilePath\",\n \"TestCase\",\n \"assertFloatsAlmostEqual\",\n \"assertFloatsNotEqual\",\n \"assertFloatsEqual\",\n \"debugger\",\n \"classParameters\",\n \"methodParameters\",\n \"temporaryDirectory\",\n]\n\nimport contextlib\nimport functools\nimport gc\nimport inspect\nimport itertools\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\nimport warnings\nfrom typing import Any, Callable, Dict, Iterator, List, Mapping, Optional, Sequence, Set, Type, Union\n\nimport numpy\nimport psutil\n\n# Initialize the list of open files to an empty set\nopen_files = set()\n\n\ndef _get_open_files() -> Set[str]:\n \"\"\"Return a set containing the list of files currently open in this\n process.\n\n Returns\n -------\n open_files : `set`\n Set containing the list of open files.\n \"\"\"\n return set(p.path for p in psutil.Process().open_files())\n\n\ndef init() -> None:\n \"\"\"Initialize the memory tester and file descriptor leak tester.\"\"\"\n global open_files\n # Reset the list of open files\n open_files = _get_open_files()\n\n\ndef sort_tests(tests) -> unittest.TestSuite:\n \"\"\"Sort supplied test suites such that MemoryTestCases are at the end.\n\n `lsst.utils.tests.MemoryTestCase` tests should always run after any other\n tests in the module.\n\n Parameters\n ----------\n tests : sequence\n Sequence of test suites.\n\n Returns\n -------\n suite : `unittest.TestSuite`\n A combined `~unittest.TestSuite` with\n `~lsst.utils.tests.MemoryTestCase` at the end.\n \"\"\"\n suite = unittest.TestSuite()\n memtests = []\n for test_suite in tests:\n try:\n # Just test the first test method in the suite for MemoryTestCase\n # Use loop rather than next as it is possible for a test class\n # to not have any test methods and the Python community prefers\n # for loops over catching a StopIteration exception.\n bases = None\n for method in test_suite:\n bases = inspect.getmro(method.__class__)\n break\n if bases is not None and MemoryTestCase in bases:\n memtests.append(test_suite)\n else:\n suite.addTests(test_suite)\n except TypeError:\n if isinstance(test_suite, MemoryTestCase):\n memtests.append(test_suite)\n else:\n suite.addTest(test_suite)\n suite.addTests(memtests)\n return suite\n\n\ndef suiteClassWrapper(tests):\n return unittest.TestSuite(sort_tests(tests))\n\n\n# Replace the suiteClass callable in the defaultTestLoader\n# so that we can reorder the test ordering. This will have\n# no effect if no memory test cases are found.\nunittest.defaultTestLoader.suiteClass = suiteClassWrapper\n\n\nclass MemoryTestCase(unittest.TestCase):\n \"\"\"Check for resource leaks.\"\"\"\n\n @classmethod\n def tearDownClass(cls) -> None:\n \"\"\"Reset the leak counter when the tests have been completed\"\"\"\n init()\n\n def testFileDescriptorLeaks(self) -> None:\n \"\"\"Check if any file descriptors are open since init() called.\"\"\"\n gc.collect()\n global open_files\n now_open = _get_open_files()\n\n # Some files are opened out of the control of the stack.\n now_open = set(\n f\n for f in now_open\n if not f.endswith(\".car\")\n and not f.startswith(\"/proc/\")\n and not f.endswith(\".ttf\")\n and not (f.startswith(\"/var/lib/\") and f.endswith(\"/passwd\"))\n and not f.endswith(\"astropy.log\")\n and not f.endswith(\"mime/mime.cache\")\n )\n\n diff = now_open.difference(open_files)\n if diff:\n for f in diff:\n print(\"File open: %s\" % f)\n self.fail(\"Failed to close %d file%s\" % (len(diff), \"s\" if len(diff) != 1 else \"\"))\n\n\nclass ExecutablesTestCase(unittest.TestCase):\n \"\"\"Test that executables can be run and return good status.\n\n The test methods are dynamically created. Callers\n must subclass this class in their own test file and invoke\n the create_executable_tests() class method to register the tests.\n \"\"\"\n\n TESTS_DISCOVERED = -1\n\n @classmethod\n def setUpClass(cls) -> None:\n \"\"\"Abort testing if automated test creation was enabled and\n no tests were found.\n \"\"\"\n if cls.TESTS_DISCOVERED == 0:\n raise RuntimeError(\"No executables discovered.\")\n\n def testSanity(self) -> None:\n \"\"\"Ensure that there is at least one test to be\n executed. This allows the test runner to trigger the class set up\n machinery to test whether there are some executables to test.\n \"\"\"\n pass\n\n def assertExecutable(\n self,\n executable: str,\n root_dir: Optional[str] = None,\n args: Optional[Sequence[str]] = None,\n msg: Optional[str] = None,\n ) -> None:\n \"\"\"Check an executable runs and returns good status.\n\n Prints output to standard out. On bad exit status the test\n fails. If the executable can not be located the test is skipped.\n\n Parameters\n ----------\n executable : `str`\n Path to an executable. ``root_dir`` is not used if this is an\n absolute path.\n root_dir : `str`, optional\n Directory containing executable. Ignored if `None`.\n args : `list` or `tuple`, optional\n Arguments to be provided to the executable.\n msg : `str`, optional\n Message to use when the test fails. Can be `None` for default\n message.\n\n Raises\n ------\n AssertionError\n The executable did not return 0 exit status.\n \"\"\"\n if root_dir is not None and not os.path.isabs(executable):\n executable = os.path.join(root_dir, executable)\n\n # Form the argument list for subprocess\n sp_args = [executable]\n argstr = \"no arguments\"\n if args is not None:\n sp_args.extend(args)\n argstr = 'arguments \"' + \" \".join(args) + '\"'\n\n print(\"Running executable '{}' with {}...\".format(executable, argstr))\n if not os.path.exists(executable):\n self.skipTest(\"Executable {} is unexpectedly missing\".format(executable))\n failmsg = None\n try:\n output = subprocess.check_output(sp_args)\n except subprocess.CalledProcessError as e:\n output = e.output\n failmsg = \"Bad exit status from '{}': {}\".format(executable, e.returncode)\n print(output.decode(\"utf-8\"))\n if failmsg:\n if msg is None:\n msg = failmsg\n self.fail(msg)\n\n @classmethod\n def _build_test_method(cls, executable: str, root_dir: str) -> None:\n \"\"\"Build a test method and attach to class.\n\n A test method is created for the supplied excutable located\n in the supplied root directory. This method is attached to the class\n so that the test runner will discover the test and run it.\n\n Parameters\n ----------\n cls : `object`\n The class in which to create the tests.\n executable : `str`\n Name of executable. Can be absolute path.\n root_dir : `str`\n Path to executable. Not used if executable path is absolute.\n \"\"\"\n if not os.path.isabs(executable):\n executable = os.path.abspath(os.path.join(root_dir, executable))\n\n # Create the test name from the executable path.\n test_name = \"test_exe_\" + executable.replace(\"/\", \"_\")\n\n # This is the function that will become the test method\n def test_executable_runs(*args: Any) -> None:\n self = args[0]\n self.assertExecutable(executable)\n\n # Give it a name and attach it to the class\n test_executable_runs.__name__ = test_name\n setattr(cls, test_name, test_executable_runs)\n\n @classmethod\n def create_executable_tests(cls, ref_file: str, executables: Optional[Sequence[str]] = None) -> None:\n \"\"\"Discover executables to test and create corresponding test methods.\n\n Scans the directory containing the supplied reference file\n (usually ``__file__`` supplied from the test class) to look for\n executables. If executables are found a test method is created\n for each one. That test method will run the executable and\n check the returned value.\n\n Executable scripts with a ``.py`` extension and shared libraries\n are ignored by the scanner.\n\n This class method must be called before test discovery.\n\n Parameters\n ----------\n ref_file : `str`\n Path to a file within the directory to be searched.\n If the files are in the same location as the test file, then\n ``__file__`` can be used.\n executables : `list` or `tuple`, optional\n Sequence of executables that can override the automated\n detection. If an executable mentioned here is not found, a\n skipped test will be created for it, rather than a failed\n test.\n\n Examples\n --------\n >>> cls.create_executable_tests(__file__)\n \"\"\"\n # Get the search directory from the reference file\n ref_dir = os.path.abspath(os.path.dirname(ref_file))\n\n if executables is None:\n # Look for executables to test by walking the tree\n executables = []\n for root, dirs, files in os.walk(ref_dir):\n for f in files:\n # Skip Python files. Shared libraries are executable.\n if not f.endswith(\".py\") and not f.endswith(\".so\"):\n full_path = os.path.join(root, f)\n if os.access(full_path, os.X_OK):\n executables.append(full_path)\n\n # Store the number of tests found for later assessment.\n # Do not raise an exception if we have no executables as this would\n # cause the testing to abort before the test runner could properly\n # integrate it into the failure report.\n cls.TESTS_DISCOVERED = len(executables)\n\n # Create the test functions and attach them to the class\n for e in executables:\n cls._build_test_method(e, ref_dir)\n\n\[email protected]\ndef getTempFilePath(ext: str, expectOutput: bool = True) -> Iterator[str]:\n \"\"\"Return a path suitable for a temporary file and try to delete the\n file on success\n\n If the with block completes successfully then the file is deleted,\n if possible; failure results in a printed warning.\n If a file is remains when it should not, a RuntimeError exception is\n raised. This exception is also raised if a file is not present on context\n manager exit when one is expected to exist.\n If the block exits with an exception the file if left on disk so it can be\n examined. The file name has a random component such that nested context\n managers can be used with the same file suffix.\n\n Parameters\n ----------\n ext : `str`\n File name extension, e.g. ``.fits``.\n expectOutput : `bool`, optional\n If `True`, a file should be created within the context manager.\n If `False`, a file should not be present when the context manager\n exits.\n\n Returns\n -------\n path : `str`\n Path for a temporary file. The path is a combination of the caller's\n file path and the name of the top-level function\n\n Examples\n --------\n .. code-block:: python\n\n # file tests/testFoo.py\n import unittest\n import lsst.utils.tests\n class FooTestCase(unittest.TestCase):\n def testBasics(self):\n self.runTest()\n\n def runTest(self):\n with lsst.utils.tests.getTempFilePath(\".fits\") as tmpFile:\n # if tests/.tests exists then\n # tmpFile = \"tests/.tests/testFoo_testBasics.fits\"\n # otherwise tmpFile = \"testFoo_testBasics.fits\"\n ...\n # at the end of this \"with\" block the path tmpFile will be\n # deleted, but only if the file exists and the \"with\"\n # block terminated normally (rather than with an exception)\n ...\n \"\"\"\n stack = inspect.stack()\n # get name of first function in the file\n for i in range(2, len(stack)):\n frameInfo = inspect.getframeinfo(stack[i][0])\n if i == 2:\n callerFilePath = frameInfo.filename\n callerFuncName = frameInfo.function\n elif callerFilePath == frameInfo.filename:\n # this function called the previous function\n callerFuncName = frameInfo.function\n else:\n break\n\n callerDir, callerFileNameWithExt = os.path.split(callerFilePath)\n callerFileName = os.path.splitext(callerFileNameWithExt)[0]\n outDir = os.path.join(callerDir, \".tests\")\n if not os.path.isdir(outDir):\n outDir = \"\"\n prefix = \"%s_%s-\" % (callerFileName, callerFuncName)\n outPath = tempfile.mktemp(dir=outDir, suffix=ext, prefix=prefix)\n if os.path.exists(outPath):\n # There should not be a file there given the randomizer. Warn and\n # remove.\n # Use stacklevel 3 so that the warning is reported from the end of the\n # with block\n warnings.warn(\"Unexpectedly found pre-existing tempfile named %r\" % (outPath,), stacklevel=3)\n try:\n os.remove(outPath)\n except OSError:\n pass\n\n yield outPath\n\n fileExists = os.path.exists(outPath)\n if expectOutput:\n if not fileExists:\n raise RuntimeError(\"Temp file expected named {} but none found\".format(outPath))\n else:\n if fileExists:\n raise RuntimeError(\"Unexpectedly discovered temp file named {}\".format(outPath))\n # Try to clean up the file regardless\n if fileExists:\n try:\n os.remove(outPath)\n except OSError as e:\n # Use stacklevel 3 so that the warning is reported from the end of\n # the with block.\n warnings.warn(\"Warning: could not remove file %r: %s\" % (outPath, e), stacklevel=3)\n\n\nclass TestCase(unittest.TestCase):\n \"\"\"Subclass of unittest.TestCase that adds some custom assertions for\n convenience.\n \"\"\"\n\n\ndef inTestCase(func: Callable) -> Callable:\n \"\"\"Add a free function to our custom TestCase class, while\n also making it available as a free function.\n \"\"\"\n setattr(TestCase, func.__name__, func)\n return func\n\n\ndef debugger(*exceptions):\n \"\"\"Enter the debugger when there's an uncaught exception\n\n To use, just slap a ``@debugger()`` on your function.\n\n You may provide specific exception classes to catch as arguments to\n the decorator function, e.g.,\n ``@debugger(RuntimeError, NotImplementedError)``.\n This defaults to just `AssertionError`, for use on `unittest.TestCase`\n methods.\n\n Code provided by \"Rosh Oxymoron\" on StackOverflow:\n http://stackoverflow.com/questions/4398967/python-unit-testing-automatically-running-the-debugger-when-a-test-fails\n\n Notes\n -----\n Consider using ``pytest --pdb`` instead of this decorator.\n \"\"\"\n if not exceptions:\n exceptions = (Exception,)\n\n def decorator(f):\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n try:\n return f(*args, **kwargs)\n except exceptions:\n import pdb\n import sys\n\n pdb.post_mortem(sys.exc_info()[2])\n\n return wrapper\n\n return decorator\n\n\ndef plotImageDiff(\n lhs: numpy.ndarray,\n rhs: numpy.ndarray,\n bad: Optional[numpy.ndarray] = None,\n diff: Optional[numpy.ndarray] = None,\n plotFileName: Optional[str] = None,\n) -> None:\n \"\"\"Plot the comparison of two 2-d NumPy arrays.\n\n Parameters\n ----------\n lhs : `numpy.ndarray`\n LHS values to compare; a 2-d NumPy array\n rhs : `numpy.ndarray`\n RHS values to compare; a 2-d NumPy array\n bad : `numpy.ndarray`\n A 2-d boolean NumPy array of values to emphasize in the plots\n diff : `numpy.ndarray`\n difference array; a 2-d NumPy array, or None to show lhs-rhs\n plotFileName : `str`\n Filename to save the plot to. If None, the plot will be displayed in\n a window.\n\n Notes\n -----\n This method uses `matplotlib` and imports it internally; it should be\n wrapped in a try/except block within packages that do not depend on\n `matplotlib` (including `~lsst.utils`).\n \"\"\"\n from matplotlib import pyplot\n\n if diff is None:\n diff = lhs - rhs\n pyplot.figure()\n if bad is not None:\n # make an rgba image that's red and transparent where not bad\n badImage = numpy.zeros(bad.shape + (4,), dtype=numpy.uint8)\n badImage[:, :, 0] = 255\n badImage[:, :, 1] = 0\n badImage[:, :, 2] = 0\n badImage[:, :, 3] = 255 * bad\n vmin1 = numpy.minimum(numpy.min(lhs), numpy.min(rhs))\n vmax1 = numpy.maximum(numpy.max(lhs), numpy.max(rhs))\n vmin2 = numpy.min(diff)\n vmax2 = numpy.max(diff)\n for n, (image, title) in enumerate([(lhs, \"lhs\"), (rhs, \"rhs\"), (diff, \"diff\")]):\n pyplot.subplot(2, 3, n + 1)\n im1 = pyplot.imshow(\n image, cmap=pyplot.cm.gray, interpolation=\"nearest\", origin=\"lower\", vmin=vmin1, vmax=vmax1\n )\n if bad is not None:\n pyplot.imshow(badImage, alpha=0.2, interpolation=\"nearest\", origin=\"lower\")\n pyplot.axis(\"off\")\n pyplot.title(title)\n pyplot.subplot(2, 3, n + 4)\n im2 = pyplot.imshow(\n image, cmap=pyplot.cm.gray, interpolation=\"nearest\", origin=\"lower\", vmin=vmin2, vmax=vmax2\n )\n if bad is not None:\n pyplot.imshow(badImage, alpha=0.2, interpolation=\"nearest\", origin=\"lower\")\n pyplot.axis(\"off\")\n pyplot.title(title)\n pyplot.subplots_adjust(left=0.05, bottom=0.05, top=0.92, right=0.75, wspace=0.05, hspace=0.05)\n cax1 = pyplot.axes([0.8, 0.55, 0.05, 0.4])\n pyplot.colorbar(im1, cax=cax1)\n cax2 = pyplot.axes([0.8, 0.05, 0.05, 0.4])\n pyplot.colorbar(im2, cax=cax2)\n if plotFileName:\n pyplot.savefig(plotFileName)\n else:\n pyplot.show()\n\n\n@inTestCase\ndef assertFloatsAlmostEqual(\n testCase: unittest.TestCase,\n lhs: Union[float, numpy.ndarray],\n rhs: Union[float, numpy.ndarray],\n rtol: Optional[float] = sys.float_info.epsilon,\n atol: Optional[float] = sys.float_info.epsilon,\n relTo: Optional[float] = None,\n printFailures: bool = True,\n plotOnFailure: bool = False,\n plotFileName: Optional[str] = None,\n invert: bool = False,\n msg: Optional[str] = None,\n ignoreNaNs: bool = False,\n) -> None:\n \"\"\"Highly-configurable floating point comparisons for scalars and arrays.\n\n The test assertion will fail if all elements ``lhs`` and ``rhs`` are not\n equal to within the tolerances specified by ``rtol`` and ``atol``.\n More precisely, the comparison is:\n\n ``abs(lhs - rhs) <= relTo*rtol OR abs(lhs - rhs) <= atol``\n\n If ``rtol`` or ``atol`` is `None`, that term in the comparison is not\n performed at all.\n\n When not specified, ``relTo`` is the elementwise maximum of the absolute\n values of ``lhs`` and ``rhs``. If set manually, it should usually be set\n to either ``lhs`` or ``rhs``, or a scalar value typical of what is\n expected.\n\n Parameters\n ----------\n testCase : `unittest.TestCase`\n Instance the test is part of.\n lhs : scalar or array-like\n LHS value(s) to compare; may be a scalar or array-like of any\n dimension.\n rhs : scalar or array-like\n RHS value(s) to compare; may be a scalar or array-like of any\n dimension.\n rtol : `float`, optional\n Relative tolerance for comparison; defaults to double-precision\n epsilon.\n atol : `float`, optional\n Absolute tolerance for comparison; defaults to double-precision\n epsilon.\n relTo : `float`, optional\n Value to which comparison with rtol is relative.\n printFailures : `bool`, optional\n Upon failure, print all inequal elements as part of the message.\n plotOnFailure : `bool`, optional\n Upon failure, plot the originals and their residual with matplotlib.\n Only 2-d arrays are supported.\n plotFileName : `str`, optional\n Filename to save the plot to. If `None`, the plot will be displayed in\n a window.\n invert : `bool`, optional\n If `True`, invert the comparison and fail only if any elements *are*\n equal. Used to implement `~lsst.utils.tests.assertFloatsNotEqual`,\n which should generally be used instead for clarity.\n will return `True`).\n msg : `str`, optional\n String to append to the error message when assert fails.\n ignoreNaNs : `bool`, optional\n If `True` (`False` is default) mask out any NaNs from operand arrays\n before performing comparisons if they are in the same locations; NaNs\n in different locations are trigger test assertion failures, even when\n ``invert=True``. Scalar NaNs are treated like arrays containing only\n NaNs of the same shape as the other operand, and no comparisons are\n performed if both sides are scalar NaNs.\n\n Raises\n ------\n AssertionError\n The values are not almost equal.\n \"\"\"\n if ignoreNaNs:\n lhsMask = numpy.isnan(lhs)\n rhsMask = numpy.isnan(rhs)\n if not numpy.all(lhsMask == rhsMask):\n testCase.fail(\n f\"lhs has {lhsMask.sum()} NaN values and rhs has {rhsMask.sum()} NaN values, \"\n f\"in different locations.\"\n )\n if numpy.all(lhsMask):\n assert numpy.all(rhsMask), \"Should be guaranteed by previous if.\"\n # All operands are fully NaN (either scalar NaNs or arrays of only\n # NaNs).\n return\n assert not numpy.all(rhsMask), \"Should be guaranteed by prevoius two ifs.\"\n # If either operand is an array select just its not-NaN values. Note\n # that these expressions are never True for scalar operands, because if\n # they are NaN then the numpy.all checks above will catch them.\n if numpy.any(lhsMask):\n lhs = lhs[numpy.logical_not(lhsMask)]\n if numpy.any(rhsMask):\n rhs = rhs[numpy.logical_not(rhsMask)]\n if not numpy.isfinite(lhs).all():\n testCase.fail(\"Non-finite values in lhs\")\n if not numpy.isfinite(rhs).all():\n testCase.fail(\"Non-finite values in rhs\")\n diff = lhs - rhs\n absDiff = numpy.abs(lhs - rhs)\n if rtol is not None:\n if relTo is None:\n relTo = numpy.maximum(numpy.abs(lhs), numpy.abs(rhs))\n else:\n relTo = numpy.abs(relTo)\n bad = absDiff > rtol * relTo\n if atol is not None:\n bad = numpy.logical_and(bad, absDiff > atol)\n else:\n if atol is None:\n raise ValueError(\"rtol and atol cannot both be None\")\n bad = absDiff > atol\n failed = numpy.any(bad)\n if invert:\n failed = not failed\n bad = numpy.logical_not(bad)\n cmpStr = \"==\"\n failStr = \"are the same\"\n else:\n cmpStr = \"!=\"\n failStr = \"differ\"\n errMsg = []\n if failed:\n if numpy.isscalar(bad):\n if rtol is None:\n errMsg = [\"%s %s %s; diff=%s with atol=%s\" % (lhs, cmpStr, rhs, absDiff, atol)]\n elif atol is None:\n errMsg = [\n \"%s %s %s; diff=%s/%s=%s with rtol=%s\"\n % (lhs, cmpStr, rhs, absDiff, relTo, absDiff / relTo, rtol)\n ]\n else:\n errMsg = [\n \"%s %s %s; diff=%s/%s=%s with rtol=%s, atol=%s\"\n % (lhs, cmpStr, rhs, absDiff, relTo, absDiff / relTo, rtol, atol)\n ]\n else:\n errMsg = [\"%d/%d elements %s with rtol=%s, atol=%s\" % (bad.sum(), bad.size, failStr, rtol, atol)]\n if plotOnFailure:\n if len(lhs.shape) != 2 or len(rhs.shape) != 2:\n raise ValueError(\"plotOnFailure is only valid for 2-d arrays\")\n try:\n plotImageDiff(lhs, rhs, bad, diff=diff, plotFileName=plotFileName)\n except ImportError:\n errMsg.append(\"Failure plot requested but matplotlib could not be imported.\")\n if printFailures:\n # Make sure everything is an array if any of them are, so we\n # can treat them the same (diff and absDiff are arrays if\n # either rhs or lhs is), and we don't get here if neither is.\n if numpy.isscalar(relTo):\n relTo = numpy.ones(bad.shape, dtype=float) * relTo\n if numpy.isscalar(lhs):\n lhs = numpy.ones(bad.shape, dtype=float) * lhs\n if numpy.isscalar(rhs):\n rhs = numpy.ones(bad.shape, dtype=float) * rhs\n if rtol is None:\n for a, b, diff in zip(lhs[bad], rhs[bad], absDiff[bad]):\n errMsg.append(\"%s %s %s (diff=%s)\" % (a, cmpStr, b, diff))\n else:\n for a, b, diff, rel in zip(lhs[bad], rhs[bad], absDiff[bad], relTo[bad]):\n errMsg.append(\"%s %s %s (diff=%s/%s=%s)\" % (a, cmpStr, b, diff, rel, diff / rel))\n\n if msg is not None:\n errMsg.append(msg)\n testCase.assertFalse(failed, msg=\"\\n\".join(errMsg))\n\n\n@inTestCase\ndef assertFloatsNotEqual(\n testCase: unittest.TestCase,\n lhs: Union[float, numpy.ndarray],\n rhs: Union[float, numpy.ndarray],\n **kwds: Any,\n) -> None:\n \"\"\"Fail a test if the given floating point values are equal to within the\n given tolerances.\n\n See `~lsst.utils.tests.assertFloatsAlmostEqual` (called with\n ``rtol=atol=0``) for more information.\n\n Parameters\n ----------\n testCase : `unittest.TestCase`\n Instance the test is part of.\n lhs : scalar or array-like\n LHS value(s) to compare; may be a scalar or array-like of any\n dimension.\n rhs : scalar or array-like\n RHS value(s) to compare; may be a scalar or array-like of any\n dimension.\n\n Raises\n ------\n AssertionError\n The values are almost equal.\n \"\"\"\n return assertFloatsAlmostEqual(testCase, lhs, rhs, invert=True, **kwds)\n\n\n@inTestCase\ndef assertFloatsEqual(\n testCase: unittest.TestCase,\n lhs: Union[float, numpy.ndarray],\n rhs: Union[float, numpy.ndarray],\n **kwargs: Any,\n) -> None:\n \"\"\"\n Assert that lhs == rhs (both numeric types, whether scalar or array).\n\n See `~lsst.utils.tests.assertFloatsAlmostEqual` (called with\n ``rtol=atol=0``) for more information.\n\n Parameters\n ----------\n testCase : `unittest.TestCase`\n Instance the test is part of.\n lhs : scalar or array-like\n LHS value(s) to compare; may be a scalar or array-like of any\n dimension.\n rhs : scalar or array-like\n RHS value(s) to compare; may be a scalar or array-like of any\n dimension.\n\n Raises\n ------\n AssertionError\n The values are not equal.\n \"\"\"\n return assertFloatsAlmostEqual(testCase, lhs, rhs, rtol=0, atol=0, **kwargs)\n\n\ndef _settingsIterator(settings: Dict[str, Sequence[Any]]) -> Iterator[Dict[str, Any]]:\n \"\"\"Return an iterator for the provided test settings\n\n Parameters\n ----------\n settings : `dict` (`str`: iterable)\n Lists of test parameters. Each should be an iterable of the same\n length. If a string is provided as an iterable, it will be converted\n to a list of a single string.\n\n Raises\n ------\n AssertionError\n If the ``settings`` are not of the same length.\n\n Yields\n ------\n parameters : `dict` (`str`: anything)\n Set of parameters.\n \"\"\"\n for name, values in settings.items():\n if isinstance(values, str):\n # Probably meant as a single-element string, rather than an\n # iterable of chars.\n settings[name] = [values]\n num = len(next(iter(settings.values()))) # Number of settings\n for name, values in settings.items():\n assert len(values) == num, f\"Length mismatch for setting {name}: {len(values)} vs {num}\"\n for ii in range(num):\n values = [settings[kk][ii] for kk in settings]\n yield dict(zip(settings, values))\n\n\ndef classParameters(**settings: Sequence[Any]) -> Callable:\n \"\"\"Class decorator for generating unit tests\n\n This decorator generates classes with class variables according to the\n supplied ``settings``.\n\n Parameters\n ----------\n **settings : `dict` (`str`: iterable)\n The lists of test parameters to set as class variables in turn. Each\n should be an iterable of the same length.\n\n Examples\n --------\n ::\n\n @classParameters(foo=[1, 2], bar=[3, 4])\n class MyTestCase(unittest.TestCase):\n ...\n\n will generate two classes, as if you wrote::\n\n class MyTestCase_1_3(unittest.TestCase):\n foo = 1\n bar = 3\n ...\n\n class MyTestCase_2_4(unittest.TestCase):\n foo = 2\n bar = 4\n ...\n\n Note that the values are embedded in the class name.\n \"\"\"\n\n def decorator(cls: Type) -> None:\n module = sys.modules[cls.__module__].__dict__\n for params in _settingsIterator(settings):\n name = f\"{cls.__name__}_{'_'.join(str(vv) for vv in params.values())}\"\n bindings = dict(cls.__dict__)\n bindings.update(params)\n module[name] = type(name, (cls,), bindings)\n\n return decorator\n\n\ndef methodParameters(**settings: Sequence[Any]) -> Callable:\n \"\"\"Iterate over supplied settings to create subtests automatically.\n\n This decorator iterates over the supplied settings, using\n ``TestCase.subTest`` to communicate the values in the event of a failure.\n\n Parameters\n ----------\n **settings : `dict` (`str`: iterable)\n The lists of test parameters. Each should be an iterable of the same\n length.\n\n Examples\n --------\n .. code-block:: python\n\n @methodParameters(foo=[1, 2], bar=[3, 4])\n def testSomething(self, foo, bar):\n ...\n\n will run:\n\n .. code-block:: python\n\n testSomething(foo=1, bar=3)\n testSomething(foo=2, bar=4)\n \"\"\"\n\n def decorator(func: Callable) -> Callable:\n @functools.wraps(func)\n def wrapper(self: unittest.TestCase, *args: Any, **kwargs: Any) -> None:\n for params in _settingsIterator(settings):\n kwargs.update(params)\n with self.subTest(**params):\n func(self, *args, **kwargs)\n\n return wrapper\n\n return decorator\n\n\ndef _cartesianProduct(settings: Mapping[str, Sequence[Any]]) -> Mapping[str, Sequence[Any]]:\n \"\"\"Return the cartesian product of the settings\n\n Parameters\n ----------\n settings : `dict` mapping `str` to `iterable`\n Parameter combinations.\n\n Returns\n -------\n product : `dict` mapping `str` to `iterable`\n Parameter combinations covering the cartesian product (all possible\n combinations) of the input parameters.\n\n Examples\n --------\n .. code-block:: python\n\n cartesianProduct({\"foo\": [1, 2], \"bar\": [\"black\", \"white\"]})\n\n will return:\n\n .. code-block:: python\n\n {\"foo\": [1, 1, 2, 2], \"bar\": [\"black\", \"white\", \"black\", \"white\"]}\n \"\"\"\n product: Dict[str, List[Any]] = {kk: [] for kk in settings}\n for values in itertools.product(*settings.values()):\n for kk, vv in zip(settings.keys(), values):\n product[kk].append(vv)\n return product\n\n\ndef classParametersProduct(**settings: Sequence[Any]) -> Callable:\n \"\"\"Class decorator for generating unit tests\n\n This decorator generates classes with class variables according to the\n cartesian product of the supplied ``settings``.\n\n Parameters\n ----------\n **settings : `dict` (`str`: iterable)\n The lists of test parameters to set as class variables in turn. Each\n should be an iterable.\n\n Examples\n --------\n .. code-block:: python\n\n @classParametersProduct(foo=[1, 2], bar=[3, 4])\n class MyTestCase(unittest.TestCase):\n ...\n\n will generate four classes, as if you wrote::\n\n .. code-block:: python\n\n class MyTestCase_1_3(unittest.TestCase):\n foo = 1\n bar = 3\n ...\n\n class MyTestCase_1_4(unittest.TestCase):\n foo = 1\n bar = 4\n ...\n\n class MyTestCase_2_3(unittest.TestCase):\n foo = 2\n bar = 3\n ...\n\n class MyTestCase_2_4(unittest.TestCase):\n foo = 2\n bar = 4\n ...\n\n Note that the values are embedded in the class name.\n \"\"\"\n return classParameters(**_cartesianProduct(settings))\n\n\ndef methodParametersProduct(**settings: Sequence[Any]) -> Callable:\n \"\"\"Iterate over cartesian product creating sub tests.\n\n This decorator iterates over the cartesian product of the supplied\n settings, using `~unittest.TestCase.subTest` to communicate the values in\n the event of a failure.\n\n Parameters\n ----------\n **settings : `dict` (`str`: iterable)\n The parameter combinations to test. Each should be an iterable.\n\n Example\n -------\n\n @methodParametersProduct(foo=[1, 2], bar=[\"black\", \"white\"])\n def testSomething(self, foo, bar):\n ...\n\n will run:\n\n testSomething(foo=1, bar=\"black\")\n testSomething(foo=1, bar=\"white\")\n testSomething(foo=2, bar=\"black\")\n testSomething(foo=2, bar=\"white\")\n \"\"\"\n return methodParameters(**_cartesianProduct(settings))\n\n\[email protected]\ndef temporaryDirectory() -> Iterator[str]:\n \"\"\"Context manager that creates and destroys a temporary directory.\n\n The difference from `tempfile.TemporaryDirectory` is that this ignores\n errors when deleting a directory, which may happen with some filesystems.\n \"\"\"\n tmpdir = tempfile.mkdtemp()\n yield tmpdir\n shutil.rmtree(tmpdir, ignore_errors=True)\n"
] | [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.axes",
"numpy.max",
"numpy.all",
"numpy.any",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.subplots_adjust",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.logical_not",
"matplotlib.pyplot.title",
"numpy.min",
"numpy.isnan",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.show",
"numpy.logical_and",
"numpy.abs",
"numpy.isfinite",
"numpy.ones",
"matplotlib.pyplot.colorbar",
"numpy.isscalar"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JonathanArvidsson/DCE-DSC-MRI_CodeCollection | [
"7ddddbe302a23f51bcec5444e2a3cab31f5a9bb4"
] | [
"src/original/OGJ_OsloU_Norway/Simulations/noise/run.py"
] | [
"import MRImageAnalysis as mri\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom phantoms_py.phantom import phantom\nimport sys\n\ndata_save_path = '../results/noise/'\n\n\ndef plot_phantom_curves(ph, fit=None):\n\tif fit is not None:\n\t\tfitted_img = fit.fittedImage()\n\telse:\n\t\tfitted_img = None\n\n\tfig, axs = plt.subplots(ph.noRows, ph.noCols, figsize=(15,8))\n\tfor i in range(ph.noRows):\n\t\tfor j in range(ph.noCols):\n\t\t\tstarti = i*ph.sectionWidth+i*ph.sectionSpacing\n\t\t\tstopi = (i+1)*ph.sectionWidth+i*ph.sectionSpacing\n\n\t\t\tstartj = j*ph.sectionHeight+j*ph.sectionSpacing\n\t\t\tstopj = (j+1)*ph.sectionHeight+j*ph.sectionSpacing\n\n\t\t\n\t\t\taxs[i,j].plot(ph.time, np.mean(ph[0,:,starti:stopi,startj:stopj], axis=(1,2)), 'k')\n\t\t\tif fit is not None:\n\t\t\t\taxs[i,j].plot(ph.time, np.mean(fitted_img[0,:,starti:stopi,startj:stopj], axis=(1,2)), 'r')\n\t\t\t\t\n\tfor a in axs.flatten():\n\t\ta.tick_params(labelbottom='off',bottom='off',top='off',left='off',right='off',labelleft='off')\n\ndef add_noise(ph, SNR):\t\n\tpbar = mri.io.ProgressBar('Adding noise...', maxval=ph[0,0].shape[0]*ph[0,0].shape[1]*len(ph[0,:,0,0]))\n\tfor i in range(ph[0,0].shape[0]):\n\t\tfor j in range(ph[0,0].shape[1]):\n\t\t\tfor t in range(len(ph[0,:,0,0])):\n\t\t\t\tS = ph[0,t,i,j]\n\t\t\t\tph[0,t,i,j] += np.random.normal(0, S/SNR[j], 1)\n\t\t\t\tpbar.update()\n\n\tpbar.finish()\n\n\treturn ph\n\ndef down_sample(ph, dt):\n\tnew_t, new_C_a = mri.math.misc.downSampleAverage(ph.time, ph.C_a, dt)\n\tnew_voxelArray = np.zeros((1, len(new_t)+1, ph.shape[2], ph.shape[3]))\n\tpbar = mri.io.ProgressBar('Downsampling...', maxval=ph.shape[2]*ph.shape[3])\n\tfor i in range(ph.shape[2]):\n\t\tfor j in range(ph.shape[3]):\n\t\t\tnew_t, new_S = mri.math.misc.downSampleAverage(ph.time, ph[0,:,i,j], dt)\n\t\t\tnew_S = np.append(np.zeros(1), new_S)\n\t\t\tplt.show()\n\t\t\tnew_voxelArray[0,:,i,j] = new_S\n\n\t\t\tpbar.update()\n\tpbar.finish()\n\t\n\tnew_t = np.append(new_t, np.array([new_t[-1] + new_t[1] - new_t[0]]))\n\t\n\tph.voxelArray = new_voxelArray\n\tph.time = new_t\n\tph.noTimepoints = len(new_t)\n\tph.C_a = np.append(np.zeros(1), new_C_a)\n\treturn ph\n\n\nph, data, _ = phantom('sim_with_noise')\n\nnoise = np.linspace(100,10,ph.noCols)\nnoise[0] = np.inf\n\nph = down_sample(ph, 1/60.)\nph = add_noise(ph, noise)\n\n\nheader = 'This file contains voxel by voxel analysis of a phantom.'\nheader += '\\nIn each row, the value of K_trans is held constant, and the noise is changed in each column.'\nheader += '\\nK_trans is varied along the rows. The gaussian noise is changed from SNR={} to SNR={},'.format(noise[0], noise[-1])\nheader += '\\nand K_trans is varied from K_trans={} to K_trans={}'.format(data['K_trans'][0,0], data['K_trans'][-1,-1])\n\nfor model in ['2CXM', 'ETM', 'TM']:\n\tfit = mri.DCE.Analyze.fitToModel(model, ph.voxelArray, ph.time, ph.C_a)\n\n\tnp.savetxt(data_save_path+model+'/K_trans.txt', fit.K_trans.voxelArray[0,0,:,:])\n\tnp.savetxt(data_save_path+model+'/v_e.txt', fit.v_e.voxelArray[0,0,:,:])\n\n\tif model in ['ETM', '2CXM']:\n\t\tnp.savetxt(data_save_path+model+'/v_p.txt', fit.v_p.voxelArray[0,0,:,:])\n\tif model == '2CXM':\n\t\tnp.savetxt(data_save_path+model+'/F_p.txt', fit.F_p.voxelArray[0,0,:,:])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] | [
[
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.random.normal",
"numpy.mean",
"numpy.savetxt",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vdivakar/patchify.py | [
"b3c9b44618f827537e495b619dd370d4391756d3"
] | [
"patchify.py"
] | [
"import numpy as np\nfrom skimage.util import view_as_windows\nfrom itertools import product\nfrom typing import Tuple\n\ndef patchify(patches: np.ndarray, patch_size: Tuple[int, int], step: int = 1):\n return view_as_windows(patches, patch_size, step)\n\ndef unpatchify(patches: np.ndarray, imsize):\n if len(patches.shape) == 4:\n return unpatchify2D(patches, imsize)\n elif len(patches.shape) == 6:\n return unpatchify3D(patches, imsize)\n else:\n print(\"Error in Patches dimension: \", patches.shape)\n return -1\n\ndef unpatchify2D(patches: np.ndarray, imsize: Tuple[int, int]):\n\n assert len(patches.shape) == 4\n\n i_h, i_w = imsize\n image = np.zeros(imsize, dtype=patches.dtype)\n divisor = np.zeros(imsize, dtype=patches.dtype)\n\n n_h, n_w, p_h, p_w = patches.shape\n\n # Calculat the overlap size in each axis\n o_w = (n_w * p_w - i_w) / (n_w - 1)\n o_h = (n_h * p_h - i_h) / (n_h - 1)\n\n # The overlap should be integer, otherwise the patches are unable to reconstruct into a image with given shape\n assert int(o_w) == o_w\n assert int(o_h) == o_h\n\n o_w = int(o_w)\n o_h = int(o_h)\n\n s_w = p_w - o_w\n s_h = p_h - o_h\n\n for i, j in product(range(n_h), range(n_w)):\n patch = patches[i,j]\n image[(i * s_h):(i * s_h) + p_h, (j * s_w):(j * s_w) + p_w] += patch\n divisor[(i * s_h):(i * s_h) + p_h, (j * s_w):(j * s_w) + p_w] += 1\n\n return image / divisor\n\ndef unpatchify3D(patches: np.ndarray, imsize: Tuple[int, int, int]):\n\n assert len(patches.shape) == 6\n\n i_h, i_w, i_c = imsize\n image = np.zeros(imsize, dtype=patches.dtype)\n divisor = np.zeros(imsize, dtype=patches.dtype)\n\n n_h, n_w, n_c, p_h, p_w, p_c = patches.shape\n\n # Calculat the overlap size in each axis\n o_w = (n_w * p_w - i_w) / (n_w - 1)\n o_h = (n_h * p_h - i_h) / (n_h - 1)\n o_c = 1 if n_c==1 else (n_c * p_c - i_c) / (n_c - 1)\n\n # The overlap should be integer, otherwise the patches are unable to reconstruct into a image with given shape\n assert int(o_w) == o_w\n assert int(o_h) == o_h\n assert int(o_c) == o_c\n\n o_w = int(o_w)\n o_h = int(o_h)\n o_c = int(o_c)\n\n s_w = p_w - o_w\n s_h = p_h - o_h\n s_c = p_c - o_c\n\n for i, j, k in product(range(n_h), range(n_w), range(n_c)):\n patch = patches[i,j,k]\n image[(i * s_h):(i * s_h) + p_h, (j * s_w):(j * s_w) + p_w, (k * s_c):(k * s_c) + p_c] += patch\n divisor[(i * s_h):(i * s_h) + p_h, (j * s_w):(j * s_w) + p_w, (k * s_c):(k * s_c) + p_c] += 1\n\n return image / divisor"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Kat-90/improver | [
"a5c31be3430df429ae38e7c16e267fcbc2af1858"
] | [
"improver_tests/cli/test_init.py"
] | [
"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# (C) British Crown Copyright 2017-2020 Met Office.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Unit tests for cli.__init__\"\"\"\n\nimport unittest\nfrom unittest.mock import patch\n\nimport numpy as np\nfrom iris.cube import CubeList\nfrom iris.exceptions import ConstraintMismatchError\n\nimport improver\nfrom improver.cli import (\n clizefy,\n create_constrained_inputcubelist_converter,\n docutilize,\n inputcube,\n inputjson,\n maybe_coerce_with,\n run_main,\n unbracket,\n with_output,\n)\nfrom improver.synthetic_data.set_up_test_cubes import set_up_variable_cube\n\n\ndef dummy_function(first, second=0, third=2):\n \"\"\"A dummy function for testing clize usage.\n\n Args:\n first (str):\n The first argument.\n second (int):\n The second argument.\n third (iris.cube.Cube):\n The third argument\n\n Returns:\n (iris.cube.Cube)\n\n \"\"\"\n first = int(first)\n return first + first\n\n\n@clizefy\n@with_output\ndef wrapped_with_output(first):\n \"\"\"dummy function for testing with_output wrapper\"\"\"\n return dummy_function(first)\n\n\nclass Test_docutilize(unittest.TestCase):\n\n \"\"\"Test the docutilize function.\"\"\"\n\n def setUp(self):\n self.expected = \"\"\"A dummy function for testing clize usage.\n\n:param first: The first argument.\n:type first: str\n:param second: The second argument.\n:type second: int\n:param third: The third argument\n:type third: iris.cube.Cube\n\n:returns: (iris.cube.Cube)\n\"\"\"\n\n def test_obj(self):\n \"\"\"Tests the docutilize function on an object\"\"\"\n doc = docutilize(dummy_function)\n\n self.assertFalse(isinstance(doc, str))\n self.assertEqual(self.expected.strip(), doc.__doc__.strip())\n\n def test_str(self):\n \"\"\"Tests the docutilize function on a string\"\"\"\n doc = docutilize(dummy_function.__doc__)\n self.assertEqual(self.expected.strip(), doc.strip())\n\n\nclass Test_maybe_coerce_with(unittest.TestCase):\n \"\"\"Tests the maybe_coerce_with function.\"\"\"\n\n def test_none_string(self):\n \"\"\"Tests that if a none string is passed in, it will return it.\"\"\"\n result = maybe_coerce_with(dummy_function, 2)\n expected = 2\n self.assertEqual(result, expected)\n\n def test_string(self):\n \"\"\"Tests that if a string is passed in, it will called the function.\"\"\"\n result = maybe_coerce_with(dummy_function, \"2\")\n # Dummy function will be 2 + 2 therefore 4.\n self.assertEqual(result, 4)\n\n\nclass Test_inputcube(unittest.TestCase):\n \"\"\"Tests the input cube function\"\"\"\n\n @patch(\"improver.cli.maybe_coerce_with\", return_value=\"return\")\n def test_basic(self, m):\n \"\"\"Tests that input cube calls load_cube with the string\"\"\"\n result = inputcube(\"foo\")\n m.assert_called_with(improver.utilities.load.load_cube, \"foo\")\n self.assertEqual(result, \"return\")\n\n\nclass Test_inputjson(unittest.TestCase):\n \"\"\"Tests the input cube function\"\"\"\n\n @patch(\"improver.cli.maybe_coerce_with\", return_value={\"mocked\": 1})\n def test_basic(self, m):\n \"\"\"Tests that input json calls load_json_or_none with the string\"\"\"\n result = inputjson(\"foo\")\n m.assert_called_with(improver.utilities.cli_utilities.load_json_or_none, \"foo\")\n self.assertEqual(result, {\"mocked\": 1})\n\n\nclass Test_with_output(unittest.TestCase):\n \"\"\"Tests the with_output wrapper\"\"\"\n\n @patch(\"improver.utilities.save.save_netcdf\")\n def test_without_output(self, m):\n \"\"\"Tests that the result of the wrapped function is returned\"\"\"\n result = wrapped_with_output.cli(\"argv[0]\", \"2\")\n m.assert_not_called()\n self.assertEqual(result, 4)\n\n @patch(\"improver.utilities.save.save_netcdf\")\n def test_with_output(self, m):\n \"\"\"Tests that save_netcdf is called with object and string, default\n compression_level=1 and default least_significant_digit=None\"\"\"\n # pylint disable is needed as it can't see the wrappers output kwarg.\n # pylint: disable=E1123\n result = wrapped_with_output.cli(\"argv[0]\", \"2\", \"--output=foo\")\n m.assert_called_with(4, \"foo\", 1, None)\n self.assertEqual(result, None)\n\n @patch(\"improver.utilities.save.save_netcdf\")\n def test_with_output_compression_level(self, m):\n \"\"\"Tests that save_netcdf is called with object and string, compression-level=9 and default least-significant-digit=None\"\"\"\n # pylint disable is needed as it can't see the wrappers output kwarg.\n # pylint: disable=E1123\n result = wrapped_with_output.cli(\n \"argv[0]\", \"2\", \"--output=foo\", \"--compression-level=9\"\n )\n m.assert_called_with(4, \"foo\", 9, None)\n self.assertEqual(result, None)\n\n @patch(\"improver.utilities.save.save_netcdf\")\n def test_with_output_no_compression(self, m):\n \"\"\"Tests that save_netcdf is called with object and string, compression-level=0 and default least-significant-digit=None\"\"\"\n # pylint disable is needed as it can't see the wrappers output kwarg.\n # pylint: disable=E1123\n result = wrapped_with_output.cli(\n \"argv[0]\", \"2\", \"--output=foo\", \"--compression-level=0\"\n )\n m.assert_called_with(4, \"foo\", 0, None)\n self.assertEqual(result, None)\n\n @patch(\"improver.utilities.save.save_netcdf\")\n def test_with_output_with_least_significant_figure(self, m):\n \"\"\"Tests that save_netcdf is called with object and string, compression-level=0 and least-significant-digit=2 \"\"\"\n # pylint disable is needed as it can't see the wrappers output kwarg.\n # pylint: disable=E1123\n result = wrapped_with_output.cli(\n \"argv[0]\",\n \"2\",\n \"--output=foo\",\n \"--compression-level=0\",\n \"--least-significant-digit=2\",\n )\n m.assert_called_with(4, \"foo\", 0, 2)\n self.assertEqual(result, None)\n\n\ndef setup_for_mock():\n \"\"\"Function that returns a CubeList of wind_speed and wind_from_direction\n\n These cubes should be the same as the setup cubes.\n\n Returns:\n iris.cube.CubeList:\n The CubeList.\n \"\"\"\n return CubeList(\n [\n set_up_variable_cube(\n data=np.zeros((2, 2), dtype=np.float32), name=\"wind_speed\"\n ),\n set_up_variable_cube(\n data=np.zeros((2, 2), dtype=np.float32), name=\"wind_from_direction\"\n ),\n ]\n )\n\n\nclass Test_create_constrained_inputcubelist_converter(unittest.TestCase):\n \"\"\"Tests the create_constrained_inputcubelist_converter\"\"\"\n\n def setUp(self):\n data = np.zeros((2, 2), dtype=np.float32)\n self.wind_speed_cube = set_up_variable_cube(data, name=\"wind_speed\")\n self.wind_dir_cube = set_up_variable_cube(data, name=\"wind_from_direction\")\n self.wind_cubes = CubeList([self.wind_speed_cube, self.wind_dir_cube])\n\n def test_basic(self):\n \"\"\"Tests a basic creation of create_constrained_inputcubelist_converter\"\"\"\n func = create_constrained_inputcubelist_converter(\n lambda cube: cube.name()\n in [\"wind_speed\", \"airspeed_velocity_of_unladen_swallow\"]\n )\n result = func(self.wind_cubes)\n self.assertEqual(self.wind_speed_cube, result[0])\n self.assertEqual(1, len(result))\n\n def test_extracting_two_cubes(self):\n \"\"\"Tests a creation of with two cube names\"\"\"\n func = create_constrained_inputcubelist_converter(\n \"wind_speed\", \"wind_from_direction\"\n )\n result = func(self.wind_cubes)\n self.assertEqual(self.wind_speed_cube, result[0])\n self.assertEqual(self.wind_dir_cube, result[1])\n self.assertEqual(2, len(result))\n\n @patch(\"improver.cli.maybe_coerce_with\", return_value=setup_for_mock())\n def test_basic_given_str(self, mocked_maybe_coerce):\n \"\"\"Tests that a str is given to maybe_coerce_with which would return a CubeList.\"\"\"\n func = create_constrained_inputcubelist_converter(\n \"wind_speed\", \"wind_from_direction\"\n )\n result = func(self.wind_cubes)\n self.assertEqual(self.wind_speed_cube, result[0])\n self.assertEqual(self.wind_dir_cube, result[1])\n self.assertEqual(2, len(result))\n mocked_maybe_coerce.assert_called_once()\n\n def test_list_two_valid(self):\n \"\"\"Tests that one cube is loaded from each list.\"\"\"\n func = create_constrained_inputcubelist_converter(\n lambda cube: cube.name()\n in [\"airspeed_velocity_of_unladen_swallow\", \"wind_speed\"],\n lambda cube: cube.name() in [\"direction_of_swallow\", \"wind_from_direction\"],\n )\n result = func(self.wind_cubes)\n self.assertEqual(self.wind_speed_cube, result[0])\n self.assertEqual(self.wind_dir_cube, result[1])\n self.assertEqual(2, len(result))\n\n def test_list_two_diff_shapes(self):\n \"\"\"Tests that one cube is loaded from each list\n when the two lists are different sizes.\n \"\"\"\n func = create_constrained_inputcubelist_converter(\n \"wind_speed\",\n lambda cube: cube.name() in [\"direction_of_swallow\", \"wind_from_direction\"],\n )\n result = func(self.wind_cubes)\n self.assertEqual(self.wind_speed_cube, result[0])\n self.assertEqual(self.wind_dir_cube, result[1])\n self.assertEqual(2, len(result))\n\n def test_list_no_match(self):\n \"\"\"Tests that providing no valid constraints raises a ConstraintMismatchError.\"\"\"\n func = create_constrained_inputcubelist_converter(\n \"airspeed_velocity_of_unladen_swallow\",\n )\n with self.assertRaisesRegex(ConstraintMismatchError, \"^Got 0 cubes\"):\n func(self.wind_cubes)\n\n def test_two_valid_cubes(self):\n \"\"\"Tests that providing 2 valid constraints raises a ConstraintMismatchError.\"\"\"\n func = create_constrained_inputcubelist_converter(\n lambda cube: cube.name() in [\"wind_speed\", \"wind_from_direction\"],\n )\n with self.assertRaisesRegex(ConstraintMismatchError, \"^Got 2 cubes\"):\n func(self.wind_cubes)\n\n\nclass Test_clizefy(unittest.TestCase):\n \"\"\"Test the clizefy decorator function\"\"\"\n\n @patch(\"improver.cli.docutilize\", return_value=None)\n def test_basic(self, m):\n \"\"\"Tests basic behaviour\"\"\"\n\n def func():\n \"\"\"Dummy\"\"\"\n\n clizefied = clizefy(func)\n self.assertIs(func, clizefied)\n self.assertTrue(hasattr(clizefied, \"cli\"))\n clizefied_cli = clizefied.cli\n clizefied_again = clizefy()(clizefied)\n self.assertIs(clizefied_cli, clizefied_again.cli)\n clizefied_cli(\"argv[0]\", \"--help\")\n m.assert_called_with(func.__doc__)\n\n\nclass Test_unbracket(unittest.TestCase):\n \"\"\"Test the unbracket function\"\"\"\n\n def test_basic(self):\n \"\"\"Tests that a list of strings changes '[' into nested lists\"\"\"\n to_test = [\"foo\", \"[\", \"bar\", \"a\", \"b\", \"]\", \"[\", \"baz\", \"c\", \"]\", \"-o\", \"z\"]\n expected = [\"foo\", [\"bar\", \"a\", \"b\"], [\"baz\", \"c\"], \"-o\", \"z\"]\n result = unbracket(to_test)\n self.assertEqual(result, expected)\n\n def test_mismatched_open_brackets(self):\n \"\"\"Tests if there isn't a corresponding ']' it raises an error\"\"\"\n msg = \"Mismatched bracket at position\"\n with self.assertRaisesRegex(ValueError, msg):\n unbracket([\"foo\", \"[\", \"bar\"])\n\n def test_mismatched_close_brackets(self):\n \"\"\"Tests if there isn't a corresponding '[' it raises an error\"\"\"\n msg = \"Mismatched bracket at position\"\n with self.assertRaisesRegex(ValueError, msg):\n unbracket([\"foo\", \"]\", \"bar\"])\n\n\ndef test_import_cli():\n \"\"\"Test if `import improver.cli` pulls in heavy stuff like numpy.\n\n Large imports cause commands like help or exit due to incorrect arguments\n to be unnecessarily slow, so it's best to test we don't have them.\n \"\"\"\n import subprocess # nosec\n import sys\n\n # Must run in a subprocess to ensure \"fresh\" Python interpreter without\n # modules pulled by other tests\n script = (\n \"import improver.cli, sys; \"\n 'assert \"numpy\" not in sys.modules, '\n '\"rogue numpy import via improver.cli\"'\n )\n subprocess.run([sys.executable, \"-c\", script], check=True) # nosec\n\n\ndef test_help_no_stderr():\n \"\"\"Test if help writes to sys.stderr.\"\"\"\n import contextlib\n import io\n\n stderr = io.StringIO()\n stdout = io.StringIO()\n with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):\n try:\n run_main([\"improver\", \"help\"])\n except SystemExit:\n pass\n result = stderr.getvalue()\n assert not result, \"unexpected output on STDERR:\\n\" + result\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chwj81/pytorch-ssd | [
"1c666d498216b6a569016d010fc6f98b4d14a559"
] | [
"run_ssd_example2.py"
] | [
"from vision.ssd.vgg_ssd import create_vgg_ssd, create_vgg_ssd_predictor\r\nfrom vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd, create_mobilenetv1_ssd_predictor\r\nfrom vision.ssd.mobilenetv1_ssd_lite import create_mobilenetv1_ssd_lite, create_mobilenetv1_ssd_lite_predictor\r\nfrom vision.ssd.squeezenet_ssd_lite import create_squeezenet_ssd_lite, create_squeezenet_ssd_lite_predictor\r\nfrom vision.ssd.mobilenet_v2_ssd_lite import create_mobilenetv2_ssd_lite, create_mobilenetv2_ssd_lite_predictor\r\nfrom vision.ssd.mobilenetv3_ssd_lite import create_mobilenetv3_large_ssd_lite, create_mobilenetv3_small_ssd_lite\r\nfrom vision.utils.misc import Timer\r\nimport cv2\r\nimport sys\r\nfrom vision.datasets.open_images import OpenImagesDataset\r\nfrom vision.utils import box_utils, measurements\r\nimport torch\r\nimport numpy as np\r\nimport argparse\r\nfrom vision.ssd.config import mobilenetv1_ssd_config, mobilenetv3_ssd_config_240, mobilenetv3_ssd_config_200, mobilenetv3_ssd_config_160\r\n\r\n\r\nparser = argparse.ArgumentParser(description=\"SSD Evaluation on VOC Dataset.\")\r\nparser.add_argument('--net', default=\"vgg16-ssd\",\r\n help=\"The network architecture, it should be of mb1-ssd, mb1-ssd-lite, mb2-ssd-lite or vgg16-ssd.\")\r\nparser.add_argument(\"--trained_model\", type=str)\r\n\r\nparser.add_argument(\"--label_file\", type=str, help=\"The label file path.\")\r\nparser.add_argument(\"--iou_threshold\", type=float, default=0.5, help=\"The threshold of Intersection over Union.\")\r\nparser.add_argument('--image_size', default=300, type=int, choices=[300, 240, 200, 160],\r\n help='Input Image size')\r\nargs = parser.parse_args()\r\n\r\n\r\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n\r\nnet_type = args.net\r\nmodel_path = args.trained_model\r\nlabel_path = args.label_file\r\n\r\ndef cal_boxdiff(predictor, dataset, iou_threshold):\r\n totalsum = 0\r\n totalsumtarget = 0\r\n totalsumtext = 0\r\n\r\n try:\r\n for i in range(len(dataset)):\r\n image = dataset.get_image(i)\r\n a, gtbox, gtlabel = dataset.__getitem__(i)\r\n gtboxes = torch.tensor(gtbox)\r\n boxes, labels, probs = predictor.predict(image, -1, iou_threshold)\r\n sum = 0\r\n sumtarget = 0\r\n sumtext = 0\r\n targetcnt = 0\r\n textcnt = 0\r\n\r\n for j in range(gtboxes.size(0)):\r\n iou = box_utils.iou_of(gtboxes[j], boxes)\r\n maxval = torch.max(iou)\r\n xor = 1 - maxval\r\n sum = sum + xor\r\n\r\n if gtlabel[j] == 1:\r\n sumtarget = sumtarget + xor\r\n targetcnt = targetcnt + 1\r\n elif gtlabel[j] == 2:\r\n sumtext = sumtext + xor\r\n textcnt = textcnt + 1\r\n\r\n totalsum = totalsum + sum / gtboxes.size(0)\r\n totalsumtarget = totalsumtarget + sumtarget / targetcnt\r\n totalsumtext = totalsumtext + sumtext / textcnt\r\n\r\n retavr = (totalsum/len(dataset)).item()\r\n retavrtarget = (totalsumtarget/len(dataset)).item()\r\n retavrtext = (totalsumtext/len(dataset)).item()\r\n except:\r\n retavr = 1.0\r\n retavrtarget = 1.0\r\n retavrtext = 1.0\r\n\r\n return retavr, retavrtarget, retavrtext\r\n\r\ndef cal_boxdiff2(args, net_state_dict, DEVICE, iou_threshold, label_file):\r\n class_names = [name.strip() for name in open(label_file).readlines()]\r\n\r\n dataset = OpenImagesDataset(args.datasets, dataset_type=\"test\")\r\n\r\n if args.net == 'vgg16-ssd':\r\n net = create_vgg_ssd(len(class_names), is_test=True)\r\n elif args.net == 'mb1-ssd':\r\n net = create_mobilenetv1_ssd(len(class_names), is_test=True)\r\n elif args.net == 'mb1-ssd-lite':\r\n net = create_mobilenetv1_ssd_lite(len(class_names), is_test=True)\r\n elif args.net == 'sq-ssd-lite':\r\n net = create_squeezenet_ssd_lite(len(class_names), is_test=True)\r\n elif args.net == 'mb2-ssd-lite':\r\n net = create_mobilenetv2_ssd_lite(len(class_names), width_mult=args.mb2_width_mult, is_test=True)\r\n elif args.net == 'mb3-large-ssd-lite':\r\n net = create_mobilenetv3_large_ssd_lite(len(class_names), is_test=True)\r\n elif args.net == 'mb3-small-ssd-lite':\r\n if args.image_size == 240:\r\n config = mobilenetv3_ssd_config_240\r\n elif args.image_size == 200:\r\n config = mobilenetv3_ssd_config_200\r\n elif args.image_size == 160:\r\n config = mobilenetv3_ssd_config_160\r\n else:\r\n config = mobilenetv1_ssd_config\r\n\r\n net = create_mobilenetv3_small_ssd_lite(len(class_names), config=config, is_test=True)\r\n else:\r\n logging.fatal(\"The net type is wrong. It should be one of vgg16-ssd, mb1-ssd and mb1-ssd-lite.\")\r\n parser.print_help(sys.stderr)\r\n sys.exit(1)\r\n\r\n net.load_state_dict(net_state_dict)\r\n net = net.to(DEVICE)\r\n\r\n if args.net == 'vgg16-ssd':\r\n predictor = create_vgg_ssd_predictor(net, nms_method='hard', device=DEVICE, candidate_size=200)\r\n elif args.net == 'mb1-ssd':\r\n predictor = create_mobilenetv1_ssd_predictor(net, nms_method='hard', device=DEVICE, candidate_size=200)\r\n elif args.net == 'mb1-ssd-lite':\r\n predictor = create_mobilenetv1_ssd_lite_predictor(net, nms_method='hard', device=DEVICE, candidate_size=200)\r\n elif args.net == 'sq-ssd-lite':\r\n predictor = create_squeezenet_ssd_lite_predictor(net,nms_method='hard', device=DEVICE, candidate_size=200)\r\n elif args.net == 'mb2-ssd-lite' or args.net == \"mb3-large-ssd-lite\" or args.net == \"mb3-small-ssd-lite\":\r\n #predictor = create_mobilenetv2_ssd_lite_predictor(net, nms_method='hard', device=DEVICE, candidate_size=200)\r\n predictor = create_mobilenetv2_ssd_lite_predictor(net, candidate_size=200, device=DEVICE, config=config)\r\n image = dataset.get_image(0)\r\n boxes, labels, probs = predictor.predict(image, -1, iou_threshold)\r\n print(boxes)\r\n else:\r\n logging.fatal(\"The net type is wrong. It should be one of vgg16-ssd, mb1-ssd and mb1-ssd-lite.\")\r\n parser.print_help(sys.stderr)\r\n sys.exit(1)\r\n\r\n totalsum = 0\r\n totalsumtarget = 0\r\n totalsumtext = 0\r\n\r\n for i in range(len(dataset)):\r\n image = dataset.get_image(i)\r\n a, gtbox, gtlabel = dataset.__getitem__(i)\r\n gtboxes = torch.tensor(gtbox)\r\n boxes, labels, probs = predictor.predict(image, -1, iou_threshold)\r\n print(gtboxes)\r\n print(boxes)\r\n sum = 0\r\n sumtarget = 0\r\n sumtext = 0\r\n targetcnt = 0\r\n textcnt = 0\r\n\r\n for j in range(gtboxes.size(0)):\r\n iou = box_utils.iou_of(gtboxes[j], boxes)\r\n maxval = torch.max(iou)\r\n xor = 1 - maxval\r\n sum = sum + xor\r\n\r\n if gtlabel[j] == 1:\r\n sumtarget = sumtarget + xor\r\n targetcnt = targetcnt + 1\r\n elif gtlabel[j] == 2:\r\n sumtext = sumtext + xor\r\n textcnt = textcnt + 1\r\n\r\n totalsum = totalsum + sum / gtboxes.size(0)\r\n totalsumtarget = totalsumtarget + sumtarget / targetcnt\r\n totalsumtext = totalsumtext + sumtext / textcnt\r\n\r\n retavr = (totalsum/len(dataset)).item()\r\n retavrtarget = (totalsumtarget/len(dataset)).item()\r\n retavrtext = (totalsumtext/len(dataset)).item()\r\n\r\n return retavr, retavrtarget, retavrtext\r\n\r\ndef tfpercent(predictor, dataset, iou_threshold):\r\n totalcnt = 0\r\n totaltargetcnt = 0\r\n totaltextcnt = 0\r\n\r\n matchcnt = 0\r\n matchtargetcnt = 0\r\n matchtextcnt = 0\r\n\r\n facnt = 0\r\n\r\n# try:\r\n for i in range(len(dataset)):\r\n# for i in range(1):\r\n image = dataset.get_image(i)\r\n a, gtbox, gtlabel = dataset.__getitem__(i)\r\n\r\n currcnt = gtbox.shape[0]\r\n currtargetcnt = np.count_nonzero(gtlabel==1)\r\n currtextcnt = np.count_nonzero(gtlabel==2)\r\n totalcnt = totalcnt + gtbox.shape[0]\r\n totaltargetcnt = totaltargetcnt + currtargetcnt\r\n totaltextcnt = totaltextcnt + currtextcnt\r\n\r\n gtboxes = torch.tensor(gtbox)\r\n boxes, labels, probs = predictor.predict(image, -1, iou_threshold)\r\n\r\n predcnt = list(boxes.size())[0]\r\n currmatchcnt = 0\r\n currmatchtargetcnt = 0\r\n currmatchtextcnt = 0\r\n\r\n currfacnt = 0\r\n\r\n for j in range(gtboxes.size(0)):\r\n iou = box_utils.iou_of(gtboxes[j], boxes)\r\n maxval = torch.max(iou)\r\n\r\n if maxval > iou_threshold:\r\n currmatchcnt = currmatchcnt + 1\r\n\r\n if gtlabel[j] == 1:\r\n currmatchtargetcnt = currmatchtargetcnt + 1\r\n elif gtlabel[j] == 2:\r\n currmatchtextcnt = currmatchtextcnt + 1\r\n\r\n matchcnt = matchcnt + currmatchcnt\r\n matchtargetcnt = matchtargetcnt + currmatchtargetcnt\r\n matchtextcnt = matchtextcnt + currmatchtextcnt\r\n\r\n facheck = list(probs > iou_threshold).count(True) - gtboxes.size(0)\r\n\r\n if facheck > 0:\r\n facnt = facnt + facheck\r\n\r\n# except:\r\n# retavr = 1.0\r\n# retavrtarget = 1.0\r\n# retavrtext = 1.0\r\n# print(totalcnt, totaltargetcnt, totaltextcnt, matchcnt, matchtargetcnt, matchtextcnt, facnt)\r\n print(totalcnt, totaltargetcnt, totaltextcnt, matchcnt, matchtargetcnt, matchtextcnt, facnt)\r\n return matchcnt/totalcnt, matchtargetcnt/totaltargetcnt, matchtextcnt/totaltextcnt, facnt\r\n\r\nclass_names = [name.strip() for name in open(label_path).readlines()]\r\n\r\nif args.image_size == 240:\r\n config = mobilenetv3_ssd_config_240\r\nelif args.image_size == 200:\r\n config = mobilenetv3_ssd_config_200\r\nelif args.image_size == 160:\r\n config = mobilenetv3_ssd_config_160\r\nelse:\r\n config = mobilenetv1_ssd_config\r\n\r\nnet = create_mobilenetv3_small_ssd_lite(len(class_names), config=config, is_test=True)\r\nnet.load(model_path)\r\nnet.to(DEVICE)\r\npredictor = create_mobilenetv2_ssd_lite_predictor(net, candidate_size=200, device=DEVICE, config=config)\r\n\r\n#config = mobilenetv1_ssd_config\r\n#test_transform = TestTransform(config.image_size, config.image_mean, config.image_std)\r\n#target_transform = MatchPrior(config.priors, config.center_variance, config.size_variance, 0.5)\r\n\r\n#val_dataset = OpenImagesDataset(args.datasets, transform=test_transform, target_transform=target_transform, dataset_type=\"test\")\r\n#val_loader = DataLoader(val_dataset, args.batch_size, num_workers=args.num_workers, shuffle=False)\r\n#dataset = OpenImagesDataset(args.datasets, dataset_type=\"test\")\r\ndataset = OpenImagesDataset('/content/dataset', dataset_type=\"test\")\r\n\r\nprint(cal_boxdiff(predictor, dataset, args.iou_threshold))\r\nprint(tfpercent(predictor, dataset, args.iou_threshold))\r\n\r\n#from types import SimpleNamespace as sn\r\n\r\n#dictargs = {\r\n# 'net': 'mb3-small-ssd-lite',\r\n# 'datasets': '/content/dataset'\r\n# }\r\n#args = sn(**dictargs)\r\n#print(args.net)\r\n#print(args.datasets)\r\n\r\n#model = torch.load(model_path, map_location=lambda storage, loc: storage)\r\n#model = torch.load(model_path)\r\n#net.load_state_dict(model['model_state_dict'])\r\n#print(cal_boxdiff2(args, model['model_state_dict'], 'cuda:0', 0.5, label_path))\r\n#for i in range(len(dataset)):\r\n# image = dataset.get_image(i)\r\n#totalsum = 0\r\n#totalsumtarget = 0\r\n#totalsumtext = 0\r\n#\r\n#for i in range(len(dataset)):\r\n# image = dataset.get_image(i)\r\n# a, gtbox, gtlabel = dataset.__getitem__(i)\r\n# gtboxes = torch.tensor(gtbox)\r\n# print(gtboxes)\r\n# print(gtboxes.size())\r\n# print(gtboxes[0])\r\n# orig_image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\r\n# boxes, labels, probs = predictor.predict(image, 10, 0.4)\r\n# print(boxes)\r\n# print(gtboxes.size(0))\r\n# sum = 0\r\n# sumtarget = 0\r\n# sumtext = 0\r\n# targetcnt = 0\r\n# textcnt = 0\r\n# print(gtlabel)\r\n#\r\n# for j in range(gtboxes.size(0)):\r\n# iou = box_utils.iou_of(gtboxes[j], boxes)\r\n# maxval = torch.max(iou)\r\n# xor = 1 - maxval\r\n# sum = sum + xor\r\n#\r\n# if gtlabel[j] == 1:\r\n# sumtarget = sumtarget + xor\r\n# targetcnt = targetcnt + 1\r\n# elif gtlabel[j] == 2:\r\n# sumtext = sumtext + xor\r\n# textcnt = textcnt + 1\r\n#\r\n# totalsum = totalsum + sum / gtboxes.size(0)\r\n# totalsumtarget = totalsumtarget + sumtarget / targetcnt\r\n# totalsumtext = totalsumtext + sumtext / textcnt\r\n#\r\n#print((totalsum/len(dataset)).item())\r\n#print((totalsumtarget/len(dataset)).item())\r\n#print((totalsumtext/len(dataset)).item())\r\n#\r\n#orig_image = cv2.imread(image_path)\r\n#image = cv2.cvtColor(orig_image, cv2.COLOR_BGR2RGB)\r\n#boxes, labels, probs = predictor.predict(image, 10, 0.4)\r\n#\r\n#for i in range(boxes.size(0)):\r\n# box = boxes[i, :]\r\n# cv2.rectangle(orig_image, (box[0], box[1]), (box[2], box[3]), (255, 255, 0), 4)\r\n# #label = f\"\"\"{voc_dataset.class_names[labels[i]]}: {probs[i]:.2f}\"\"\"\r\n# label = f\"{class_names[labels[i]]}: {probs[i]:.2f}\"\r\n# cv2.putText(orig_image, label,\r\n# (box[0] + 20, box[1] + 40),\r\n# cv2.FONT_HERSHEY_SIMPLEX,\r\n# 1, # font scale\r\n# (255, 0, 255),\r\n# 2) # line type\r\n#path = \"run_ssd_example_output.jpg\"\r\n#cv2.imwrite(path, orig_image)\r\n#print(f\"Found {len(probs)} objects. The output image is {path}\")\r\n"
] | [
[
"numpy.count_nonzero",
"torch.max",
"torch.cuda.is_available",
"torch.tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
aebrahimian/alpha-zero-hex | [
"466ca3b08713f179390d1595e28f7a473994df54"
] | [
"hex/pytorch/NNet.py"
] | [
"import argparse\nimport os\nimport shutil\nimport time\nimport random\nimport numpy as np\nimport math\nimport sys\nsys.path.append('../../')\nfrom utils import *\nfrom pytorch_classification.utils import Bar, AverageMeter\nfrom NeuralNet import NeuralNet\n\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\nfrom .HexNNet import HexNNet as hnnet\n\nargs = dotdict({\n 'lr': 0.001,\n 'dropout': 0.3,\n 'epochs': 10,\n 'batch_size': 64,\n 'cuda': torch.cuda.is_available(),\n 'num_channels': 512,\n})\n\nclass NNetWrapper(NeuralNet):\n def __init__(self, game):\n self.nnet = hnnet(game, args)\n self.board_x, self.board_y = game.getBoardSize()\n self.action_size = game.getActionSize()\n\n if args.cuda:\n self.nnet.cuda()\n\n def train(self, examples):\n \"\"\"\n examples: list of examples, each example is of form (board, pi, v)\n \"\"\"\n optimizer = optim.Adam(self.nnet.parameters())\n\n for epoch in range(args.epochs):\n print('EPOCH ::: ' + str(epoch+1))\n self.nnet.train()\n data_time = AverageMeter()\n batch_time = AverageMeter()\n pi_losses = AverageMeter()\n v_losses = AverageMeter()\n end = time.time()\n\n bar = Bar('Training Net', max=int(len(examples)/args.batch_size))\n batch_idx = 0\n\n while batch_idx < int(len(examples)/args.batch_size):\n sample_ids = np.random.randint(len(examples), size=args.batch_size)\n boards, pis, vs = list(zip(*[examples[i] for i in sample_ids]))\n boards = torch.FloatTensor(np.array(boards).astype(np.float64))\n target_pis = torch.FloatTensor(np.array(pis))\n target_vs = torch.FloatTensor(np.array(vs).astype(np.float64))\n\n # predict\n if args.cuda:\n boards, target_pis, target_vs = boards.contiguous().cuda(), target_pis.contiguous().cuda(), target_vs.contiguous().cuda()\n\n # measure data loading time\n data_time.update(time.time() - end)\n\n # compute output\n out_pi, out_v = self.nnet(boards)\n l_pi = self.loss_pi(target_pis, out_pi)\n l_v = self.loss_v(target_vs, out_v)\n total_loss = l_pi + l_v\n\n # record loss\n pi_losses.update(l_pi.item(), boards.size(0))\n v_losses.update(l_v.item(), boards.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n total_loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n batch_idx += 1\n\n # plot progress\n bar.suffix = '({batch}/{size}) Data: {data:.3f}s | Batch: {bt:.3f}s | Total: {total:} | ETA: {eta:} | Loss_pi: {lpi:.4f} | Loss_v: {lv:.3f}'.format(\n batch=batch_idx,\n size=int(len(examples)/args.batch_size),\n data=data_time.avg,\n bt=batch_time.avg,\n total=bar.elapsed_td,\n eta=bar.eta_td,\n lpi=pi_losses.avg,\n lv=v_losses.avg,\n )\n bar.next()\n bar.finish()\n\n\n def predict(self, board):\n \"\"\"\n board: np array with board\n \"\"\"\n # timing\n start = time.time()\n\n # preparing input\n board = torch.FloatTensor(board.astype(np.float64))\n if args.cuda: board = board.contiguous().cuda()\n board = board.view(1, self.board_x, self.board_y)\n self.nnet.eval()\n with torch.no_grad(): \n pi, v = self.nnet(board)\n\n #print('PREDICTION TIME TAKEN : {0:03f}'.format(time.time()-start))\n return torch.exp(pi).data.cpu().numpy()[0], v.data.cpu().numpy()[0]\n\n def loss_pi(self, targets, outputs):\n return -torch.sum(targets*outputs)/targets.size()[0]\n\n def loss_v(self, targets, outputs):\n return torch.sum((targets-outputs.view(-1))**2)/targets.size()[0]\n\n def save_checkpoint(self, folder='checkpoint', filename='checkpoint.pth.tar'):\n filepath = os.path.join(folder, filename)\n if not os.path.exists(folder):\n print(\"Checkpoint Directory does not exist! Making directory {}\".format(folder))\n os.mkdir(folder)\n else:\n print(\"Checkpoint Directory exists! \")\n torch.save({\n 'state_dict' : self.nnet.state_dict(),\n }, filepath)\n\n def load_checkpoint(self, folder='checkpoint', filename='checkpoint.pth.tar'):\n # https://github.com/pytorch/examples/blob/master/imagenet/main.py#L98\n filepath = os.path.join(folder, filename)\n if not os.path.exists(filepath):\n raise(\"No model in path {}\".format(filepath))\n map_location = None if args.cuda else 'cpu'\n checkpoint = torch.load(filepath, map_location=map_location)\n self.nnet.load_state_dict(checkpoint['state_dict'])\n"
] | [
[
"torch.load",
"torch.sum",
"torch.exp",
"torch.no_grad",
"torch.cuda.is_available",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
heprom/pymicro | [
"176bf3a829dbf67796a3d4471f18868a3da229a7"
] | [
"pymicro/core/samples.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"DataPlatform module for the management of multimodal mechanical datasets.\n\nThe `samples` module provides a base class `SampleData` implementing a generic\ndata model and data paltform API, allowing to define by inheritance specific\ndata platform classes for specific mechanical applications. It is designed to\ngather and manipulate easily multimodal datasets gathering data from 3D/4D\nimaging experiments and simulations of mechanical material samples. Such data\nconsists in volumic data defined on 3D meshes/images, classical data arrays,\nand associated metadata.\n\n\"\"\"\nimport os\nimport subprocess\nimport shutil\nimport numpy as np\nimport tables\nimport lxml.builder\nfrom lxml import etree\nfrom pathlib import Path\n# BasicTool imports\nfrom BasicTools.Containers.ConstantRectilinearMesh import (\n ConstantRectilinearMesh)\nfrom BasicTools.Containers.UnstructuredMesh import (UnstructuredMesh,\n AllElements)\nimport BasicTools.Containers.UnstructuredMeshCreationTools as UMCT\nfrom BasicTools.Containers.MeshBase import MeshBase\nfrom BasicTools.IO.XdmfTools import XdmfName,XdmfNumber\n# Import variables for XDMF binding\nfrom pymicro.core.global_variables import (XDMF_FIELD_TYPE,\n XDMF_IMAGE_GEOMETRY,\n XDMF_IMAGE_TOPOLOGY)\n# Import variables for SampleData data model\nfrom pymicro.core.global_variables import (SD_GROUP_TYPES, SD_GRID_GROUPS,\n SD_IMAGE_GROUPS, SD_MESH_GROUPS)\n\n\nclass SampleData:\n \"\"\"Base class to store multi-modal datasets for material science.\n\n SampleData is a high level API designed to create and interact with\n complex datasets collecting all the data generated for a material sample\n by material scientists (from experiments, numerical simulation or data\n processing).\n\n Each dataset consist of a pair of files: one HDF5 file containing all\n data and metadata, and one XDMF data gathering metadata for all spatially\n origanized data (grids and fields). The class ensures creation and\n synchronization of both XDMF and HDF5 files.\n\n The HDF5 and XDMF data tree structure and content in both files are\n accessible through the `h5_dataset` and `xdmf_tree` class attributes,\n that are respectively instances of classes imported from the\n `Pytables <https://www.pytables.org/index.html>`_ and\n `lxml <https://lxml.de/>`_ packages.\n\n .. rubric:: SampleData Naming system\n\n An index of the dataset content is stored into a dictionary `content_index`\n as an attribute of the class. Additional names can be defined by users\n for data items, and are stored in an alias dictionary. The `content_index`\n dic is synchronized with the hdf5 Group '/Index'.\n The `aliases` dic is synchronized with the '/Index/Aliases' Group.\n When an existing dataset is opened to create a SampleData instance, these\n attributes are initialized from these Groups in the dataset HDF5 file.\n Each data item can be accessed in the API methods via:\n\n :path: it's path in the HDF5 data tree\n :indexname: it's name in the `content_index` dic (the key associated\n to it's path)\n :alias: an alias of it's indexname\n :name: its name as a HDF5 Node if it is unique\n\n .. rubric:: Data Compression\n\n HDF5 compression algorithm are available through the\n `Pytables <https://www.pytables.org/index.html>`_ package. SampleData\n offers an interface to it with the :func:`set_chunkshape_and_compression`\n method.\n\n .. rubric:: Arguments of the Class constructor\n\n :filename: `str`\n basename of HDF5/XDMF files to create/read. A file pair is created if\n the `filename` do not match any existing file.\n :sample_name: `str`, optional ('')\n name of the sample associated to data (metadata, dataset \"title\"). If\n the class is called to open a pre-existing `filename`, its sample name\n is not overwritten.\n :sample_description: `str`, optional ('')\n short description of the mechanical sample (material, type of\n tests.... -- metadata). If the class is called to open a pre-existing\n `filename`, its sample name is not overwritten.\n :verbose: `bool`, optional (False)\n set verbosity flag\n :overwrite_hdf5: `bool`, optional (False)\n set to `True` to overwrite existing HDF5/XDMF couple of files with the\n same `filename`.\n :autodelete: `bool`, optional (False)\n set to `True` to remove HDF5/XDMF files when deleting SampleData\n instance.\n :autorepack: `bool`, optional (False)\n if `True`, the HDF5 file is automatically repacked when deleting\n the SampleData instance, to recover the memory space freed up by data\n compression operations. See :func:`repack_h5file` for more details.\n\n .. rubric:: Class attributes\n\n :h5_file: basename of HDF5 file containing dataset (`str`)\n :h5_path: full path of the HDF5 dataset file\n :h5_dataset: :py:class:`tables.File` instance associated to the\n `h5_file`\n :xdmf_file: name of XDMF file associated with `h5_file` (`str`)\n :xdmf_path: full path of XDMF file (`str`)\n :xdmf_tree: :py:class:`lxml.etree` XML tree associated with `xdmf_file`\n :autodelete: autodelete flag (`bool`)\n :autorepack: autorepack flag (`bool`)\n :after_file_open_args: command arguments for `after_file_open` (dict)\n :content_index: Dictionnary of data items (nodes/groups)\n names and pathes in HDF5 dataset (`dic`)\n :aliases: Dictionnary of list of aliases for each item in\n content_index (`dic`)\n\"\"\"\n# TODO: Homogenize docstrings style\n\n def __init__(self, filename='sample_data', sample_name='',\n sample_description=' ', verbose=False, overwrite_hdf5=False,\n autodelete=False, autorepack=False,\n after_file_open_args=dict()):\n \"\"\"Sample Data constructor, see class documentation.\"\"\"\n # get file directory and file name\n path_file = Path(filename).absolute()\n filename_tmp = path_file.stem\n file_dir = str(path_file.parent)\n\n self.h5_file = filename_tmp + '.h5'\n self.xdmf_file = filename_tmp + '.xdmf'\n self.file_dir = file_dir\n self.h5_path = os.path.join(self.file_dir,self.h5_file)\n self.xdmf_path = os.path.join(self.file_dir,self.xdmf_file)\n self._verbose = verbose\n self.autodelete = autodelete\n self.autorepack = autorepack\n if os.path.exists(self.h5_path) and overwrite_hdf5:\n self._verbose_print('-- File \"{}\" exists and will be '\n 'overwritten'.format(self.h5_path))\n os.remove(self.h5_path)\n os.remove(self.xdmf_path)\n self._init_file_object(sample_name, sample_description)\n self._after_file_open(**after_file_open_args)\n self.sync()\n return\n\n def _after_file_open(self, **kwargs):\n \"\"\"Initialization code to run after opening a Sample Data file.\n\n Empty method for this class. Use it for SampleData inherited classes,\n to create shortcut class attribute that are linked with hdf5 dataset\n elements (for instance, class attribute pointing towards a dataset\n structured table -- see `add_table` method and Microstructure class\n `grains` attribute)\n \"\"\"\n return\n\n def __del__(self):\n \"\"\"Sample Data destructor.\n\n Deletes SampleData instance and:\n - closes h5_file --> writes data structure into the .h5 file\n - writes the .xdmf file\n \"\"\"\n self._verbose_print('Deleting DataSample object ')\n self.sync()\n if self.autorepack:\n self.repack_h5file()\n self.h5_dataset.close()\n self._verbose_print('Dataset and Datafiles closed')\n if self.autodelete:\n print('{} Autodelete: \\n Removing hdf5 file {} and xdmf file {}'\n ''.format(self.__class__.__name__, self.h5_file,\n self.xdmf_file))\n os.remove(self.h5_path)\n os.remove(self.xdmf_path)\n if os.path.exists(self.h5_path) or os.path.exists(self.xdmf_path):\n raise RuntimeError('HDF5 and XDMF not removed')\n return\n\n def __repr__(self):\n \"\"\"Return a string representation of the dataset content.\"\"\"\n s = ''\n s += self.print_index(as_string=True, max_depth=3)\n s += '\\n'\n s += self.print_dataset_content(as_string=True, max_depth=3,\n short=True)\n return s\n\n def __contains__(self, name):\n \"\"\"Check if name refers to an existing HDF5 node in the dataset.\n\n :param str name: a string for the name / indexname / path\n :return bool: True if the dataset has a node associated with this name,\n False if not.\n \"\"\"\n path = self._name_or_node_to_path(name)\n if path is None:\n return False\n else:\n return self.h5_dataset.__contains__(path)\n\n def __getitem__(self, key):\n \"\"\"Implement dictionnary like access to hdf5 dataset items.\"\"\"\n # Return the object under the appropriate form\n if self._is_field(key):\n return self.get_field(key)\n elif self._is_array(key):\n return self.get_node(key, as_numpy=True)\n elif self._is_group(key):\n return self.get_node(key, as_numpy=False)\n\n def __getattribute__(self, name):\n \"\"\"Implement attribute like access to hdf5 dataset items.\"\"\"\n try:\n return object.__getattribute__(self, name)\n except AttributeError:\n if self._is_field(name):\n return self.get_field(name)\n elif self._is_array(name):\n return self.get_node(name, as_numpy=True)\n elif self._is_group(name):\n return self.get_node(name, as_numpy=False)\n else:\n raise AttributeError(f'{self.__class__} has no attribute'\n f' {name}')\n\n def minimal_data_model(self):\n \"\"\"Specify minimal data model to store in class instance.\n\n This method is designed to construct derived classes from SampleData\n to serve as data platforms for a specific data model, that is specified\n by the two dictionaries returned.\n\n The class constructor searches through these dictionaries to determine\n the name, pathes and types of data items constituting the data model of\n the class, and creates them at each instance creation. If the\n constructor is used to create an instance from an existing file, the\n compatibility with the data model is verified, and the missing data\n items are created if needed. The constructor ensures compatibility of\n previously created datasets with the class if the current data model\n of the class has been enriched. Note that the associated datasets can\n contain additional data items, those defined in this method are the\n minimal required content for this class of datasets.\n\n The return dictionaries keys are the Index names of the data items of\n the data model. Their values are defined hereafter:\n\n :return dic index_dic:\n | Dictionary specifying the indexnames and pathes of data items in\n | the data model. Each entry must be of the form\n | {'indexname':'/data_item/path'}. The data item path is its path\n | in the HDF5 tree structure.\n :return dic type_dic:\n | Dictionary specifying the indexnames and types of data items in\n | the data model. Each entry must be of the form\n | {'indexname':'grouptype'}. 'grouptype' can be:\n\n :'Group': creates a classical HDF5 group (str)\n :'3DImage': creates a HDF5 group containing datasets (fields) defined\n on the same 3D image (str)\n :'Mesh': creates a HDF5 group containing datasets (fields) defined on\n the same mesh (str)\n :'Array': creates a HDF5 node containing a data array (str)\n :Table_description: creates a structured storage array\n (:py:class:`tables.Filters` class) with the given Description.\n `Table_description` must be a subclass of\n :py:class:`tables.IsDescription` class.\n \"\"\"\n index_dic = {}\n type_dic = {}\n return index_dic, type_dic\n\n def print_xdmf(self):\n \"\"\"Print a readable version of xdmf_tree content.\"\"\"\n print(etree.tostring(self.xdmf_tree, pretty_print=True,\n encoding='unicode'))\n return\n\n def write_xdmf(self):\n \"\"\"Write xdmf_tree in .xdmf file with suitable XML declaration.\"\"\"\n self._verbose_print('.... writing xdmf file : {}'\n ''.format(self.xdmf_file),\n line_break=False)\n self.xdmf_tree.write(self.xdmf_path,\n xml_declaration=True,\n pretty_print=True,\n doctype='<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\"[]>')\n\n # correct xml declaration to allow Paraview reader compatibility\n with open(self.xdmf_path, 'r') as f:\n lines = f.readlines()\n\n lines[0] = lines[0].replace(\"encoding='ASCII'\", \"\")\n\n with open(self.xdmf_path, 'w') as f:\n f.writelines(lines)\n return\n\n def print_dataset_content(self, as_string=False, max_depth=3,\n to_file=None, short=False):\n \"\"\"Print information on all nodes in the HDF5 file.\n\n :param bool as_string: If `True` solely returns string representation.\n If `False`, prints the string representation.\n :param int max_depth: Only prints data item whose depth is equal or\n less than this value. The depth is the number of parents a data\n item has. The root Group has thus a depth of 0, its children a\n depth of 1, the children of its children a depth of 2...\n :param str to_file: (optional) If not `None`, writes the dataset\n information to the provided text file name `to_file`. In that case,\n nothing is printed to the standard output.\n :param bool short: If `True`, return a short description of the\n dataset content, reduced to hdf5 tree structure and node memory\n sizes.\n :return str s: string representation of HDF5 nodes information\n \"\"\"\n size, unit = self.get_file_disk_size(print_flag=False)\n s = f'Printing dataset content with max depth {max_depth}\\n'\n if not short:\n s += ('\\n****** DATA SET CONTENT ******\\n -- File: {}\\n '\n '-- Size: {:9.3f} {}\\n -- Data Model Class: {}\\n'\n ''.format(self.h5_file, size, unit, self.__class__.__name__))\n s += self.print_node_info('/', as_string=True)\n s += '\\n************************************************\\n\\n'\n for node in self.h5_dataset.root:\n if node._v_depth > max_depth:\n continue\n if not(node._v_name == 'Index'):\n s += self.print_node_info(node._v_pathname, as_string=True,\n short=short)\n if self._is_group(node._v_pathname):\n s += self.print_group_content(node._v_pathname,\n recursive=True,\n as_string=True,\n max_depth=max_depth,\n short=short)\n if not short:\n s += ('\\n**********************************'\n '**************\\n\\n')\n if to_file:\n with open(to_file,'w') as f:\n f.write(s)\n return\n elif as_string:\n return s\n else:\n print(s)\n return\n\n def print_group_content(self, groupname, recursive=False, as_string=False,\n max_depth=1000, to_file=None, short=False):\n \"\"\"Print information on all nodes in a HDF5 group.\n\n :param str groupname: Name, Path, Index name or Alias of the HDF5 group\n :param bool recursive: If `True`, print content of children groups\n :param bool as_string: If `True` solely returns string representation.\n If `False`, prints the string representation.\n :param int max_depth: Only prints data item whose depth is equal or\n less than this value. The depth is the number of parents a data\n item has. The root Group has thus a depth of 0, its children a\n depth of 1, the children of its children a depth of 2...\n Note that this depth is an absolute depth. Thus, if you want for\n instance to print the content of a group with depth 3, with 2\n levels of depth (its childrens and their childrens), you will need\n to specify a depth of 5 for this method.\n :param str to_file: (optional) If not `None`, writes the group\n contentto the provided text file name `to_file`. In that case,\n nothing is printed to the standard output.\n :param bool short: If `True`, return a short description of the\n dataset content, reduced to hdf5 tree structure and node memory\n sizes.\n :return str s: string representation of HDF5 nodes information\n \"\"\"\n if short:\n s=''\n else:\n s = '\\n****** Group {} CONTENT ******\\n'.format(groupname)\n group = self.get_node(groupname)\n if group._v_depth > max_depth:\n return ''\n if group._v_nchildren == 0:\n return ''\n else:\n if not(as_string):\n print(s)\n for node in group._f_iter_nodes():\n s += self.print_node_info(node._v_pathname, as_string=True,\n short=short)\n if (self._is_group(node._v_pathname) and recursive):\n if ((node._v_name == 'ElementsTags') or\n (node._v_name == 'NodeTags')):\n # skip mesh Element and Node Tags group content\n # that can be very large\n continue\n s += self.print_group_content(node._v_pathname, recursive=True,\n as_string=True,\n max_depth=max_depth-1,\n short=short)\n if to_file:\n with open(to_file,'w') as f:\n f.write(s)\n return\n elif as_string:\n return s+'\\n'\n else:\n print(s)\n return\n\n def print_node_info(self, nodename, as_string=False, short=False):\n \"\"\"Print information on a node in the HDF5 tree.\n\n Prints node name, content, attributes, compression settings, path,\n childrens list if it is a group.\n\n :param str name: Name, Path, Index name or Alias of the HDF5 Node\n :param bool as_string: If `True` solely returns string representation.\n If `False`, prints the string representation.\n :param bool short: If `True`, return a short description of the\n node content, reduced to name, hdf5 type and node memory\n sizs.\n :return str s: string representation of HDF5 Node information\n \"\"\"\n s = ''\n node_path = self._name_or_node_to_path(nodename)\n if self._is_array(node_path):\n s += self._get_array_node_info(nodename, as_string, short)\n else:\n s += self._get_group_info(nodename, as_string, short)\n if as_string:\n return s\n else:\n print(s)\n return\n\n def print_node_attributes(self, nodename, as_string=False):\n \"\"\"Print the hdf5 attributes (metadata) of an array node.\n\n :param str name:Name, Path, Index name or Alias of the HDF5 Node\n :param bool as_string: If `True` solely returns string representation.\n If `False`, prints the string representation.\n :return str s: string representation of HDF5 Node compression settings\n \"\"\"\n s = ''\n Node = self.get_node(nodename)\n if Node is None:\n return f'No group named {nodename}'\n s += str(f' -- {Node._v_name} attributes : \\n')\n for attr in Node._v_attrs._v_attrnamesuser:\n value = Node._v_attrs[attr]\n s += str('\\t * {} : {}\\n'.format(attr, value))\n if as_string:\n return s+'\\n'\n else:\n print(s)\n return\n\n def print_node_compression_info(self, name, as_string=False):\n \"\"\"Print the compression settings of an array node.\n\n :param str name:Name, Path, Index name or Alias of the HDF5 Node\n :param bool as_string: If `True` solely returns string representation.\n If `False`, prints the string representation.\n :return str s: string representation of HDF5 Node compression settings\n \"\"\"\n s = ''\n if not self.__contains__(name):\n raise tables.NodeError('node `{}` not in {} instance'.format(\n name, self.__class__.__name__))\n node_path = self._name_or_node_to_path(name)\n if self._is_array(node_path):\n N = self.get_node(name)\n s += 'Compression options for node `{}`:\\n\\t'.format(name)\n s += repr(N.filters).strip('Filters(').strip(')')\n s += f'\\n --- Chunkshape: {N.chunkshape}'\n else:\n s += '{} is not a data array node'.format(name)\n if not as_string:\n print(s)\n return\n return s+'\\n'\n\n def print_data_arrays_info(self, as_string=False, to_file=None,\n short=False):\n \"\"\"Print information on all data array nodes in hdf5 file.\n\n Mesh node and element sets are excluded from the output due to\n their possibly very high number.\n\n :param bool as_string: If `True` solely returns string representation.\n If `False`, prints the string representation.\n :param str to_file: (optional) If not `None`, writes the dataset\n information to the provided text file name `to_file`. In that case,\n nothing is printed to the standard output.\n :param bool short: If `True`, return a short description of the\n dataset content, reduced to hdf5 tree structure and node memory\n sizes.\n :return str s: string representation of HDF5 nodes information\n \"\"\"\n s = ''\n for node in self.h5_dataset:\n if node._v_name.startswith('ET_'):\n continue\n if self._is_array(node._v_name):\n s += self.print_node_info(node._v_name, as_string=True,\n short=short)\n if to_file:\n with open(to_file,'w') as f:\n f.write(s)\n return\n elif as_string:\n return s\n else:\n print(s)\n return\n\n def print_grids_info(self, as_string=False, to_file=None,\n short=False):\n \"\"\"Print information on all grid groups in hdf5 file.\n\n :param bool as_string: If `True` solely returns string representation.\n If `False`, prints the string representation.\n :param str to_file: (optional) If not `None`, writes the dataset\n information to the provided text file name `to_file`. In that case,\n nothing is printed to the standard output.\n :param bool short: If `True`, return a short description of the\n dataset content, reduced to hdf5 tree structure and node memory\n sizes.\n :return str s: string representation of HDF5 nodes information\n \"\"\"\n s = ''\n for group in self.h5_dataset.walk_groups():\n if self._is_grid(group._v_name):\n s += self.print_node_info(group._v_name, as_string=True,\n short=short)\n if to_file:\n with open(to_file,'w') as f:\n f.write(s)\n return\n elif as_string:\n return s\n else:\n print(s)\n return\n\n def print_index(self, as_string=False, max_depth=3, local_root='/'):\n \"\"\"Print a list of the data items in HDF5 file and their Index names.\n\n :param bool as_string: If `True` solely returns string representation.\n If `False`, prints the string representation.\n :param int max_depth: Only prints data item whose depth is equal or\n less than this value. The depth is the number of parents a data\n item has. The root Group has thus a depth of 0, its children a\n depth of 1, the children of its children a depth of 2...\n :param str local_root: prints only the Index for data items that are\n children of the provided local_root. The Name, Path, Indexname,\n or Alias of the local_root can be passed for this argument.\n :return str s: string representation of HDF5 nodes information if\n `as_string` is True.\n \"\"\"\n s = ''\n s += str('Dataset Content Index :\\n')\n s += str('------------------------:\\n')\n s += str('index printed with max depth `{}` and under local root'\n ' `{}`\\n\\n'.format(max_depth, local_root))\n for key, value in self.content_index.items():\n col = None\n if isinstance(value, list):\n path = value[0]\n col = value[1]\n else:\n path = value\n node = self.get_node(path)\n if node is None:\n # precaution to avoid errors when content index references an\n # empty node\n continue\n if not(self._is_children_of(node, local_root)):\n continue\n if node._v_depth > max_depth:\n continue\n if col is None:\n s += str('\\t Name : {:40} H5_Path : {} \\t\\n'.format(\n key, path))\n else:\n s += str('\\t Name : {:40} H5_Path : {}|col:{} \\t\\n'.format(\n key, path, col))\n if key in self.aliases:\n s += str('\\t {} aliases -->'.format(key))\n for aliasname in self.aliases[key]:\n s += str(' `'+aliasname+'`')\n s += '\\n'\n if not(as_string):\n print(s)\n return\n return s\n\n def sync(self):\n \"\"\"Synchronize and flush .h5 and .xdmf files with dataset content.\n\n After using the `sync` method, the XDMF file can be opened in Paraview\n and 3DImage and/or Mesh data visualized, even if the files are still\n open in the class instance.\n\n .. important::\n Paraview >=5 cannot read data from synchronized files, you must\n close them first. In this case, use method\n :func:`pause_for_visualization`.\n \"\"\"\n message = ('.... Storing content index in {}:/Index attributes'\n ''.format(self.h5_file))\n self._verbose_print(message,\n line_break=False)\n self.add_attributes(dic=self.content_index, nodename='/Index')\n self.add_attributes(dic=self.aliases, nodename='/Index/Aliases')\n self.write_xdmf()\n self._verbose_print('.... flushing data in file {}'.format(\n self.h5_file), line_break=False)\n self.h5_dataset.flush()\n self._verbose_print('File {} synchronized with in memory data tree'\n ''.format(self.h5_file),\n line_break=False)\n return\n\n def pause_for_visualization(self, Vitables=False, Paraview=False,\n **keywords):\n \"\"\"Flushes data, close files and pause interpreter for visualization.\n\n This method pauses the interpreter until you press the <Enter> key.\n During the pause, the HDF5 file object is closed, so that it can be\n read by visualization softwares like Paraview or ViTables. Two\n optional arguments allow to directly open the dataset with Paraview\n and/or Vitables, as a subprocess of Python. In these cases, the Python\n interpreter is paused until you close the visualization software.\n\n Paraview allows to visualize the volumic data that is stored in the\n SampleData dataset, *i.e.* Mesh and Images groups (geometry and\n stored fields). Vitables allows to visualize the content of the HDF5\n dataset in term of data tree, arrays content and nodes attributes. If\n both are requested, Vitables is executed before Paraview.\n\n\n :param bool Vitables: set to `True` to launch Vitables on the HDF5 file\n of the instance HDF5 dataset.\n :param bool Paraview: set to `True` to launch Paraview on the XDMF file\n of the instance.\n \"\"\"\n Pause = True\n self.sync()\n self.h5_dataset.close()\n print('File objects are now closed, you can visualize dataset'\n ' content.')\n if Vitables:\n software_cmd = 'vitables'\n if 'Vitables_path' in keywords:\n software_cmd = keywords['Vitables_path']\n print('--- Lauching Vitables on file {} ---'.format(\n self.h5_file))\n print('Once you will close Vitables, you may resume data'\n ' management with your SampleData instance.')\n subprocess.run(args=[software_cmd,self.h5_path])\n Pause = False\n if Paraview:\n software_cmd = 'paraview'\n if 'Paraview_path' in keywords:\n software_cmd = keywords['Paraview_path']\n print('--- Lauching Paraview on file {} ---'.format(\n self.xdmf_file))\n print('Once you will close Paraview, you may resume data'\n ' management with your SampleData instance.')\n subprocess.run(args=[software_cmd,self.xdmf_path])\n Pause = False\n if Pause:\n input('Paused interpreter, you may open {} and {} files with'\n ' other softwares during this pause.'\n ' Press <Enter> when you want to resume data management'\n ''.format(self.h5_file, self.xdmf_file))\n self.h5_dataset = tables.File(self.h5_path, mode='r+')\n self._file_exist = True\n self._after_file_open()\n print('File objects {} and {} are opened again.\\n You may use this'\n ' SampleData instance normally.'.format(self.h5_file,\n self.xdmf_file))\n return\n\n def switch_verbosity(self):\n \"\"\"Change the verbosity flag to its opposite.\"\"\"\n self._verbose = not (self._verbose)\n return\n\n def add_mesh(self, mesh_object=None, meshname='', indexname='',\n location='/', description=' ', replace=False,\n bin_fields_from_sets=True, file=None,\n compression_options=dict()):\n \"\"\"Create a Mesh group in the dataset from a MeshObject.\n\n A Mesh group is a HDF5 Group that contains arrays describing mesh\n geometry, and fields defined on this mesh. The mesh geometry HDF5 nodes\n are: This methods adds a Mesh group to the dataset from a BasicTools\n :py:class:`UnstructuredMesh` class instance.\n\n :Nodes: array of shape `(Nnodes,Ndim)` with path\n ``'/Mesh_Path/Geometry/Nodes'`` and Index name\n ``'Meshname_Nodes'``\n :Elements: array of shape `(Nelements,Nelement_nodes)` with path\n ``'/Mesh_Path/Geometry/Elements'`` and Index name\n ``'Meshname_Elements'``\n\n Mesh group may also contain data array to describe fields, whose\n pathes, index names and content can be set using the class method\n :func:`add_data_array`. Fields defined on nodes must have a shape equal\n to (Nnodes,Field_dimension). Fields defined on integration points must\n have a shape equal to (Nintegration_points,Field_dimension).\n\n :param mesh_object: mesh to add to dataset. It is an instance from the\n :py:class:`pymicro.core.meshes.MeshObject` class\n :param str meshname: name used to create the Mesh group in dataset\n :param indexname: Index name used to reference the Mesh group\n :location str: Path, Name, Index Name or Alias of the parent group\n where the Mesh group is to be created\n :param str description: Description metadata for this mesh\n :param bool replace: remove Mesh group in the dataset with the same\n name/location if `True` and such group exists\n :param bool bin_fields_from_sets: If `True`, stores all Node and\n Element Sets in mesh_object as binary fields (1 on Set, 0 else)\n :param dict compression_options: Dictionary containing compression\n options items, see `set_chunkshape_and_compression` method for\n more details.\n \"\"\"\n # Check if the input array is in an external file\n if file is not None:\n mesh_object = self._read_mesh_from_file(file)\n ### Create or fetch mesh group\n mesh_group = self.add_group(meshname, location, indexname, replace)\n ### empty meshes creation\n if (mesh_object is None):\n self.add_attributes({'empty': True, 'group_type': 'emptyMesh'},\n mesh_group._v_pathname)\n return\n else:\n self._check_mesh_object_support(mesh_object)\n ### Add Mesh Geometry to HDF5 dataset\n self._add_mesh_geometry(mesh_object,mesh_group, replace,\n bin_fields_from_sets)\n ### Add mesh Grid to xdmf file\n self._add_mesh_to_xdmf(mesh_group)\n # store mesh metadata as HDF5 attributes\n Attribute_dic = {'description': description,\n 'empty': False,\n 'xdmf_gridname': mesh_group._v_name}\n self.add_attributes(Attribute_dic, mesh_group._v_pathname)\n ### Add node and element tags, eventually as fields if extended=True\n self._add_nodes_elements_tags(mesh_object, mesh_group, replace,\n bin_fields_from_sets)\n ### Add fields if some are stored in the mesh object\n for field_name, field in mesh_object.nodeFields.items():\n self.add_field(gridname=mesh_group._v_pathname,\n fieldname=field_name, array=field,\n replace=replace,\n compression_options=compression_options)\n for field_name, field in mesh_object.elemFields.items():\n self.add_field(gridname=mesh_group._v_pathname,\n fieldname=field_name, array=field,\n replace=replace,\n compression_options=compression_options)\n return mesh_object\n\n def add_mesh_from_image(self, imagename, with_fields=True, ofTetras=False,\n meshname='', indexname='', location='/',\n description=' ', replace=False,\n bin_fields_from_sets=True,\n compression_options=dict()):\n \"\"\"Create a Mesh group in the dataset from an Image dataset.\n\n The mesh group created can represent a mesh of tetrahedra or a mesh of\n hexaedra, of the image domain (square/triangles in 2D). The fields in\n the mesh groups are restored, with an adequate shape, and a suffix\n '_msh' in their indexname.\n\n :param str imagename: Name, Path or Indexname of the mesh group to get\n :param bool with_fields: If `True`, load the nodes and elements fields\n from the image group into the mesh object.\n :param bool ofTetras: if `True`, returns a mesh with tetrahedron\n elements. If `False`, return a rectilinera mesh of hexaedron\n elements.\n :param str meshname: name used to create the Mesh group in dataset\n :param indexname: Index name used to reference the Mesh group\n :location str: Path, Name, Index Name or Alias of the parent group\n where the Mesh group is to be created\n :param str description: Description metadata for this mesh\n :param bool replace: remove Mesh group in the dataset with the same\n name/location if `True` and such group exists\n :param bool bin_fields_from_sets: If `True`, stores all Node and\n Element Sets in mesh_object as binary fields\n :param dict compression_options: Dictionary containing compression\n options items, see `set_chunkshape_and_compression` method for\n more details.\n \"\"\"\n\n Mesh_o = self.get_mesh_from_image(imagename, with_fields, ofTetras)\n # Rename mesh fields to avoid duplicate in content_index\n field_names = list(Mesh_o.nodeFields.keys())\n for key in field_names:\n Mesh_o.nodeFields[key+'_'+meshname] = Mesh_o.nodeFields.pop(key)\n field_names = list(Mesh_o.elemFields.keys())\n for key in field_names:\n Mesh_o.elemFields[key+'_'+meshname] = Mesh_o.elemFields.pop(key)\n self.add_mesh(Mesh_o, meshname, indexname, location, description,\n replace, bin_fields_from_sets,\n compression_options=compression_options)\n return\n\n def add_image(self, image_object=None, imagename='', indexname='',\n location='/', description='', replace=False,\n field_indexprefix='', compression_options=dict()):\n \"\"\"Create a 2D/3D Image group in the dataset from an ImageObject.\n\n An Image group is a HDF5 Group that contains arrays describing fields\n defined on an image (uniform grid of voxels/pixels). This methods adds\n an Image group to the dataset from a BasicTools\n :py:class:`ConstantRectilinearMesh` class instance.This class\n represents regular meshes of square/cubes, *i.e.* pixels/voxels.\n\n\n The image geometry and topology is defined by HDF5 attributes of the\n Image Group, that are:\n\n :nodes_dimension: np.array, number of grid points along each\n dimension of the Image. This number is array is equal to\n the `dimension` attribute array +1 for each value.\n :dimension: np.array, number of voxels along each dimension of the\n Image (Nx,Ny,Nz) or (Nx,Ny)\n :spacing: np.array, voxel size along each dimension (dx,dy,dz) or\n (dx, dy)\n :origin: np.array, coordinates of the image grid origin,\n corresponding to the first vertex of the voxel [0,0,0]\n or pixel [0,0]\n\n The Image group may also contain arrays of field values on the image.\n These fields can be elementFields (defined at pixel/voxel centers) or\n nodefields (defined at pixel/voxel vertexes). Their\n pathes, index names and content can be set using the class method\n :func:`add_field`. Fields defined on nodes must have a shape equal\n to the `nodes_dimension` attribute. Fields defined on elements must\n have a shape equal to the `dimension` attribute. Both can have an\n additional last dimension if they have a higher dimensionality than\n scalar fields (for instance [Nx,Ny,Nz,3] for a vector field).\n\n :param image_object: image to add to dataset. It is an instance from\n the :py:class:`ConstantRectilinearMesh` class of the BasicTools\n Python package.\n :param str imagename: name used to create the Image group in dataset\n :param str indexname: Index name used to reference the Image. If none\n is provided, `imagename` is used.\n :location str: Path, Name, Index Name or Alias of the parent group\n where the Image group is to be created\n :param str description: Description metadata for this 3D image\n :param bool replace: remove Image group in the dataset with the same\n name/location if `True` and such group exists\n :param dict compression_options: Dictionary containing compression\n options items, see `set_chunkshape_and_compression` method for\n more details.\n \"\"\"\n # Check if the image already exists as an empty image\n empty = False\n im_attrs = dict()\n old_descr = None\n try:\n gtype = self.get_attribute('group_type',indexname)\n if gtype == 'emptyImage':\n # we get the empty image attributes to transfer its metadata\n # to the new image group that will overwrite it\n empty = True\n im_attrs = self.get_dic_from_attributes(indexname)\n # remove old arguments for empty groups\n im_attrs.pop('empty')\n im_attrs.pop('group_type')\n old_descr = im_attrs.pop('description')\n except:\n pass\n if empty and (image_object is not None):\n replace=True\n ### Create or fetch image group\n image_group = self.add_group(imagename, location, indexname, replace)\n ### empty images creation\n if (image_object is None):\n self.add_attributes({'empty': True, 'group_type': 'emptyImage'},\n image_group._v_pathname)\n return\n else:\n self._check_image_object_support(image_object)\n ### Add image Grid to xdmf file\n self._add_image_to_xdmf(imagename, image_object)\n ### store image metadata as HDF5 attributes\n image_type = self._get_image_type(image_object)\n image_nodes_dim = np.array(image_object.GetDimensions())\n image_cell_dim = image_nodes_dim - np.ones(image_nodes_dim.shape,\n dtype=image_nodes_dim.dtype)\n if len(image_nodes_dim) == 2:\n image_xdmf_dim = image_nodes_dim[[1,0]]\n elif len(image_nodes_dim) == 3:\n image_xdmf_dim = image_nodes_dim[[2,1,0]]\n # Add image attributes\n if (description == '') and (old_descr is not None):\n description = im_attrs['description']\n Attribute_dic = {'nodes_dimension': image_nodes_dim,\n 'nodes_dimension_xdmf': image_xdmf_dim,\n 'dimension': image_cell_dim,\n 'spacing': np.array(image_object.GetSpacing()),\n 'origin': np.array(image_object.GetOrigin()),\n 'description': description,\n 'group_type': image_type,\n 'empty': False,\n 'xdmf_gridname': imagename}\n self.add_attributes(Attribute_dic, image_group._v_pathname)\n self.add_attributes(im_attrs, image_group._v_pathname)\n ### Add fields if some are stored in the image object\n for field_name, field in image_object.nodeFields.items():\n self.add_field(gridname=image_group._v_pathname,\n fieldname=field_name, array=field,\n indexname=field_indexprefix+field_name,\n compression_options=compression_options)\n for field_name, field in image_object.elemFields.items():\n self.add_field(gridname=image_group._v_pathname,\n fieldname=field_name, array=field,\n indexname=field_indexprefix+field_name,\n compression_options=compression_options)\n return image_object\n\n def add_image_from_field(self, field_array, fieldname, imagename='',\n indexname='', location='/', description=' ',\n replace=False, origin=None, spacing=None,\n is_scalar=True, is_elemField=True,\n compression_options=dict()):\n \"\"\"Create a 2D/3M Image group in the dataset from a field data array.\n\n Construct an image object from the inputed field array. This array is\n interpreted by default as an element field of a pixelized/voxelized\n grid. Hence, if the field is of shape (Nx,Ny), the image group will\n store a (Nx,Ny) image (*i.e.* a regular grid of Nx+1,Ny+1 nodes). If\n specified, the field can be interpreted as a nodal field (values at\n pixels/voxels vertexes). In this case the method will create a\n (Nx-1,Ny-1) image of (Nx,Ny) nodes. The same applies in 3D.\n\n If the field is not a scalar field, the last dimension of the field\n array is interpreted as the dimension containing the field components\n\n :param numpy.array field_array: data array of the field values on the\n image regular grid.\n :param str fieldname: add the field to HDF5 dataset and image Group\n with this name.\n :param str imagename: name used to create the Image group in dataset\n :param str indexname: Index name used to reference the Image. If none\n is provided, `imagename` is used.\n :location str: Path, Name, Index Name or Alias of the parent group\n where the Image group is to be created\n :param str description: Description metadata for this 3D image\n :param bool replace: remove Image group in the dataset with the same\n name/location if `True` and such group exists\n :param np.array(3,) origin: Coordinates of the first node of the\n regular grid of squares/cubes constituting the image geometry\n :param np.array(3,) spacing: Size along each dimension of the\n pixels/voxels composing the image.\n :param bool is_scalar: If `True` (default value), the field is\n considered as a scalar field to compute the image dimensions from\n the field array shape.\n :param bool is_elemField: If `True` (default value), the array is\n considered as a pixel/voxel wise field value array. If `False`, the\n field is considered as a nodal value array.\n :param dict compression_options: Dictionary containing compression\n options items, see `set_chunkshape_and_compression` method for\n more details.\n\n \"\"\"\n if is_scalar:\n field_dim = len(field_array.shape)\n field_dimensions = field_array.shape\n else:\n field_dim = len(field_array.shape)-1\n field_dimensions = field_array.shape[:-1]\n if spacing is None:\n spacing = np.ones((len(field_dimensions),))\n if origin is None:\n origin = np.zeros((len(field_dimensions),))\n if is_elemField:\n field_dimensions = field_dimensions + np.ones((field_dim,))\n image_object = ConstantRectilinearMesh(dim=field_dim)\n image_object.SetDimensions(field_dimensions)\n image_object.SetOrigin(origin)\n image_object.SetSpacing(spacing)\n image_object.elemFields[fieldname] = field_array\n self.add_image(image_object, imagename=imagename,\n indexname=indexname, location=location,\n description=description, replace=replace,\n compression_options=compression_options,\n field_indexprefix=(imagename+'_'))\n return\n\n def add_grid_time(self, gridname, time_list):\n \"\"\"Add a list of time values to a grid data group.\n\n If the grid has no time value, an xdmf grid temporal collection is\n created.\n\n :param str gridname: Path, name or indexname of the grid Group where\n to add time values.\n :param list(float) time_list: List of times to add to the grid. Can\n also be passed as a numpy array.\n \"\"\"\n # WARNING : BUG, XDMF grids must be in increasing time order\n # not ensured\n # TODO: Create a method sort xdmf grids with time\n # if time_list is passed as a numpy array, transform it into a list\n if isinstance(time_list, np.ndarray):\n time_list = time_list.tolist()\n if isinstance(time_list, float):\n time_list = [time_list]\n if isinstance(time_list, int):\n time_list = [time_list]\n time_list = sorted(time_list)\n # get xdmf node of main grid\n xdmf_gridname = self.get_attribute('xdmf_gridname',gridname)\n grid = self._find_xdmf_grid(xdmf_gridname)\n # Find out if grid is a uniform grid\n grid_type = grid.get('GridType')\n if grid_type == 'Uniform':\n grid0 = grid\n # Default setting considers the already present grid node as the\n # first time value of the time serie --> first grid of the\n # collection. All attributes (fields) already added to this grid\n # will be considered as attribute value at first time value.\n grid0.set('Name', xdmf_gridname + '_T0')\n # Remove old grid from xdmf tree\n p = grid.getparent()\n p.remove(grid)\n # Create a new grid\n grid = etree.Element(_tag='Grid', Name=xdmf_gridname,\n GridType='Collection',\n CollectionType='Temporal')\n # Add time element to grid0\n time0 = etree.Element(_tag='Time', Value=f'{time_list[0]}')\n grid0.append(time0)\n # Append old grid to new grid collection\n grid.append(grid0)\n # Append grid collection to Domain\n p.append(grid)\n # Create a time_list with only first time value\n self.add_attributes({'time_list':[time_list.pop(0)]},gridname)\n elif grid_type == 'Collection':\n grid0 = grid.getchildren()[0]\n else:\n raise ValueError(f'Grid {gridname} type is not Uniform nor'\n ' Collection.')\n # Get grid topology and Geometry nodes\n for ch in grid0.iterchildren():\n if ch.tag == 'Topology':\n topo = ch\n if ch.tag == 'Geometry':\n geo = ch\n # Get main grid time list\n time_list0 = self.get_attribute('time_list', gridname)\n if time_list0 is None:\n time_list0 = []\n index_count = len(time_list0)\n for T in time_list:\n if T not in time_list0:\n time_list0.append(T)\n # Create a new grid\n gridT_name = xdmf_gridname + f'_T{index_count}'\n gridT = etree.Element(_tag='Grid', Name=gridT_name,\n GridType='Uniform')\n # Add time element to grid\n timeT = etree.Element(_tag='Time', Value=f'{T}')\n gridT.append(timeT)\n # Append topology and geometry to grid\n gridT.append(topo.__copy__())\n gridT.append(geo.__copy__())\n index_count = index_count + 1\n # Append grid to grid collection\n grid.append(gridT)\n self.add_attributes({'time_list':time_list0},gridname)\n return\n\n def add_group(self, groupname, location='/', indexname='', replace=False):\n \"\"\"Create a standard HDF5 group at location with no grid properties.\n\n If the group parents in `location` do not exist, they are created.\n\n :param str groupname: Name of the group to create\n :param str location: Path where the group will be added in the HDF5\n dataset\n :param str indexname: Index name used to reference the Group. If none\n is provided, `groupname` is used.\n :param bool replace: remove 3DImage group in the dataset with the same\n name/location if `True` and such group exists\n :param bool createparents: if `True`, create parent nodes in `path` if\n they are not present in the dataset\n \"\"\"\n if (indexname == ''):\n indexname = groupname\n Group = self._init_SD_group(groupname, location,\n group_type='Group', replace=replace)\n if Group is None:\n raise tables.NodeError('Group {} could not be created or fetched.'\n ' Unknown error.'.format(groupname))\n self.add_to_index(indexname, Group._v_pathname)\n return Group\n\n def add_field(self, gridname, fieldname, array=None, location=None,\n indexname=None, chunkshape=None, replace=False,\n visualisation_type='Elt_mean', compression_options=dict(),\n time=None, bulk_padding=True):\n \"\"\"Add a field to a grid (Mesh or 2D/3DImage) group from a numpy array.\n\n This methods checks the compatibility of the input field array with the\n grid dimensionality and geometry, adds it to the HDF5 dataset, and\n the XDMF file. Metadata describing the field type, dimensionality are\n stored as field HDF node attributes. The path of the field is added to\n the grid Group as a HDF5 attribute.\n\n :param str gridname: Path, name or indexname of the grid Group on which\n the field will be added\n :param str fieldname: Name of the HDF5 node to create that will contain\n the field value array\n :param np.array array: Array containing the field values to add in the\n dataset\n ;param str location: Path, name or indexname of the Group in which the\n field array will be stored. This Group must be a children of the\n `gridname` Group. If not provided, the field is stored in the\n `gridname` Group.\n :param str indexname: Index name used to reference the field node\n :param tuple chunkshape: The shape of the data chunk to be read or\n written in a single HDF5 I/O operation\n :param bool replace: remove 3DImage group in the dataset with the same\n name/location if `True` and such group exists\n :param Filters filters: instance of :py:class:`tables.Filters` class\n specifying compression settings.\n :param str visualisation_type: Type of visualisation used to represent\n integration point fields with an element wise constant field.\n Possibilities are 'Elt_max' (maximum value per element), 'Elt_mean'\n (mean value per element), 'None' (no visualisation field).\n Default value is 'Elt_mean'\n :param dict compression_options: Dictionary containing compression\n options items, see `set_chunkshape_and_compression` method for\n more details.\n :param float time: Associate a time value for this field. IF a time\n value is provided, the suffix '_T{time_index}' is appended to\n the fieldname and indexname\n :param bool bulk_padding: If adding a field on a mesh that has as many\n bulk as boundary elements, forces field padding to `bulk` if True,\n or to `boundary` if false\n \"\"\"\n self._verbose_print('Adding field `{}` into Grid `{}`'\n ''.format(fieldname, gridname))\n # Fields can only be added to grid Groups --> sanity check\n if not(self._is_grid(gridname)):\n raise tables.NodeError('{} is not a grid, cannot add a field data'\n ' array in this group.'.format(gridname))\n # Get storage location for field data array\n if (location is None) and replace:\n # if replace, try to get the parent node of the possibly\n # existing node to replace\n node_field = self.get_node(fieldname)\n if node_field is not None:\n location = node_field._v_parent._v_pathname\n if location is None:\n # FIELD STORAGE DEFAULT CONVENTION :\n # fields are stored directly into the HDF5 grid group\n array_location = gridname\n else:\n # check if the given location is a subgroup of the grid group\n if self._is_children_of(location, gridname):\n array_location = location\n elif self.get_node(location) == self.get_node(gridname):\n array_location = location\n else:\n raise tables.NodeError('Cannot add field at location `{}`.'\n ' Field location must be a grid group'\n ' (Mesh or Image), or a grid group'\n ' children'.format(location))\n # Handle empty fields\n if array is None:\n node = self.add_data_array(array_location, fieldname, array,\n indexname, replace)\n # Add field path to grid node Field_list attribute\n self._append_field_index(gridname, indexname)\n gridpath = self._name_or_node_to_path(gridname)\n Attribute_dic = {'parent_grid_path': gridpath,\n 'node_type':'field_array'\n }\n self.add_attributes(Attribute_dic, nodename=indexname)\n return node\n # If needed, pad the field with 0s to comply with number of bulk and\n # boundary elements\n array, padding, vis_array = self._mesh_field_padding(array, gridname,\n bulk_padding)\n # Check if the array shape is consistent with the grid geometry\n # and returns field dimension, xdmf Center attribute\n field_type, dimensionality = self._check_field_compatibility(\n gridname,array.shape)\n\n # Apply indices transposition to assure consistency of the data\n # visualization in paraview with SampleData ordering and indexing\n # conventions\n if self._is_image(gridname):\n # indices transposition to ensure consistency between SampleData\n # and geometrical interpretation of coordinates in Paraview\n if self.get_attribute('group_type',gridname) == '2DImage':\n if len(array.shape) == 3:\n array = np.squeeze(array)\n array, transpose_indices = self._transpose_image_array(\n dimensionality, array)\n if dimensionality in ['Tensor6','Tensor']:\n # indices transposition to ensure consistency between SampleData\n # components oredering convention and SampleData ordering\n # convention\n array, transpose_components = self._transpose_field_comp(\n dimensionality, array)\n\n # get indexname or create one\n if indexname is None:\n grid_path = self._name_or_node_to_path(gridname)\n grid_indexname = self.get_indexname_from_path(grid_path)\n indexname = grid_indexname+'_'+fieldname\n\n # If time value is provided, find out if a new temporal grid must be\n # added to the xdmf file\n time_gridname = None\n time_suffix = ''\n if time is not None:\n time_list = self.get_attribute('time_list', gridname)\n if (time_list is None):\n time_list = [time]\n self.add_grid_time(gridname, time_list)\n else:\n if time not in time_list:\n time_list = [time]\n self.add_grid_time(gridname, time_list)\n time_list = self.get_attribute('time_list', gridname)\n time_gridname = self._get_xdmf_time_grid_name(gridname,time)\n # get time suffix from gridname\n import re\n time_suffix = re.findall('_T\\d+', time_gridname)[-1]\n # keep suffixless fieldname as attribute name for the xdmf\n # time grid collection (same field name for each grid associated\n # to a different time step)\n time_serie_name = fieldname\n # Add time suffix to field indexname and name\n fieldname = fieldname + time_suffix\n indexname = indexname + time_suffix\n # Add data array into HDF5 dataset\n node = self.add_data_array(array_location, fieldname, array, indexname,\n chunkshape, replace,\n compression_options=compression_options)\n # Create attributes of the field node\n gridpath = self._name_or_node_to_path(gridname)\n xdmf_gname = self.get_attribute('xdmf_gridname',gridname)\n if time_gridname is not None:\n xdmf_gname = time_gridname\n Attribute_dic = {'field_type': field_type,\n 'field_dimensionality': dimensionality,\n 'parent_grid_path': gridpath,\n 'xdmf_gridname': xdmf_gname, 'padding': padding,\n 'node_type':'field_array'\n }\n if time is not None:\n Attribute_dic['time'] = time\n Attribute_dic['time_serie_name'] = time_serie_name\n if self._is_image(gridname):\n Attribute_dic['transpose_indices'] = transpose_indices\n if dimensionality in ['Tensor6','Tensor']:\n Attribute_dic['transpose_components'] = transpose_components\n # Add field for visualization of Integration Points mesh fields\n if (field_type == 'IP_field') and not (visualisation_type=='None'):\n vis_array = self._IP_field_for_visualisation(vis_array,\n visualisation_type)\n visname = fieldname+f'_{visualisation_type}'\n visindexname = indexname+f'_{visualisation_type}'\n if dimensionality in ['Tensor6','Tensor']:\n vis_array, _ = self._transpose_field_comp(\n dimensionality, vis_array)\n node_vis = self.add_data_array(\n array_location, visname, vis_array, visindexname, chunkshape,\n replace, compression_options=compression_options)\n Attribute_dic['visualisation_type'] = visualisation_type\n self.add_attributes(Attribute_dic, nodename=visindexname)\n Attribute_dic['visualisation_field_path'] = node_vis._v_pathname\n self.add_attributes(Attribute_dic, nodename=indexname)\n # Add field description to XDMF file\n if (field_type == 'IP_field') and not (visualisation_type=='None'):\n self._add_field_to_xdmf(visindexname, vis_array)\n else:\n self._add_field_to_xdmf(indexname, array)\n # Add field path to grid node Field_list attribute\n self._append_field_index(gridname, indexname)\n return node\n\n def add_data_array(self, location, name, array=None, indexname=None,\n chunkshape=None, replace=False,\n compression_options=dict()):\n \"\"\"Add a data array node at the given location in the HDF5 dataset.\n\n The method uses the :py:class:`CArray` and\n :py:class:`tables.Filters` classes of the\n `Pytables <https://www.pytables.org/index.html>`_ package to add\n data arrays in the dataset and control their chunkshape and compression\n settings.\n\n :param str location: Path where the array will be added in the dataset\n :param str name: Name of the array to create\n :param np.array array: Array to store in the HDF5 node\n :param str indexname: Index name used to reference the node\n :param tuple chunkshape: The shape of the data chunk to be read or\n written in a single HDF5 I/O operation\n :param bool replace: remove 3DImage group in the dataset with the same\n name/location if `True` and such group exists\n :param Filters filters: instance of :py:class:`tables.Filters` class\n specifying compression settings.\n :param bool empty: if `True` create the path, Index Name in dataset and\n store an empty array. Set the node attribute `empty` to True.\n :param dict compression_options: Dictionary containing compression\n options items, see `set_chunkshape_and_compression` method for\n more details.\n\n \"\"\"\n self._verbose_print('Adding array `{}` into Group `{}`'\n ''.format(name, location))\n if array is None:\n empty = True\n else:\n empty=False\n # Safety checks\n saved_attrs = self._check_SD_array_init(name, location, replace, empty)\n # get location path\n location_path = self._name_or_node_to_path(location)\n # get compression options\n Filters = self._get_compression_opt(compression_options)\n # add to index\n if indexname is None:\n indexname = name\n self.add_to_index(indexname, os.path.join(location_path, name))\n # Create dataset node to store array\n if empty:\n Node = self.h5_dataset.create_carray(\n where=location_path, name=name, obj=np.array([0]),\n title=indexname)\n self.add_attributes({'empty': True, 'node_type':'data_array'},\n Node._v_pathname)\n else:\n if 'normalization' in compression_options:\n optn = compression_options['normalization']\n array, norm_attributes = self._data_normalization(array, optn)\n Node = self.h5_dataset.create_carray(\n where=location_path, name=name, filters=Filters,\n obj=array, chunkshape=chunkshape,\n title=indexname)\n self.add_attributes(saved_attrs, Node._v_pathname)\n self.add_attributes({'empty': False, 'node_type':'data_array'},\n Node._v_pathname)\n if 'normalization' in compression_options:\n if optn == 'standard_per_component':\n mean_array = norm_attributes.pop('norm_mean_array')\n std_array = norm_attributes.pop('norm_std_array')\n Mean = self.h5_dataset.create_carray(\n where=location_path, name=name+'_norm_mean',\n filters=Filters, obj=mean_array, chunkshape=chunkshape)\n Std = self.h5_dataset.create_carray(\n where=location_path, name=name+'_norm_std',\n filters=Filters, obj=std_array, chunkshape=chunkshape)\n norm_attributes['norm_mean_array_path'] = Mean._v_pathname\n norm_attributes['norm_std_array_path'] = Std._v_pathname\n self.add_attributes(norm_attributes, Node._v_pathname)\n return Node\n\n def add_table(self, location, name, description, indexname=None,\n chunkshape=None, replace=False, data=None,\n compression_options=dict()):\n \"\"\"Add a structured storage table in HDF5 dataset.\n\n :param str location: Path where the array will be added in the dataset\n :param str name: Name of the array to create\n :param IsDescription description: Definition of the table rows, can be\n a numpy dtype.\n :param str indexname: Index name used to reference the node\n composition as a sequence of named fields (analogous to Numpy\n structured arrays). It must be an instance of the\n :py:class:`tables.IsDescription` class from the\n `Pytables <https://www.pytables.org/index.html>`_ package\n :param tuple chunkshape: The shape of the data chunk to be read or\n written in a single HDF5 I/O operation\n :param bool replace: remove 3DImage group in the dataset with the same\n name/location if `True` and such group exists\n :param np.array(np.void) data: Array to store in the HDF5 node. `dtype`\n must be consistent with the table `description`.\n :param Filters filters: instance of :py:class:`tables.Filters` class\n specifying compression settings.\n :param dict compression_options: Dictionary containing compression\n options items, see `set_chunkshape_and_compression` method for\n more details.\n \"\"\"\n self._verbose_print('Adding table `{}` into Group `{}`'\n ''.format(name, location))\n # get location path\n location_path = self._name_or_node_to_path(location)\n if (location_path is None):\n msg = ('(add_table): location {} does not exist, table'\n ' cannot be added. Use optional argument'\n ' \"createparents=True\" to force location Group creation'\n ''.format(location))\n self._verbose_print(msg)\n return\n else:\n # check location nature\n if not(self._get_node_class(location) == 'GROUP'):\n msg = ('(add_table): location {} is not a Group nor '\n 'empty. Please choose an empty location or a HDF5 '\n 'Group to store table'.format(location))\n self._verbose_print(msg)\n return\n # check if array location exists and remove node if asked\n table_path = os.path.join(location_path, name)\n if self.h5_dataset.__contains__(table_path):\n if replace:\n msg = ('(add_table): existing node {} will be '\n 'overwritten and all of its childrens removed'\n ''.format(table_path))\n self._verbose_print(msg)\n self.remove_node(table_path, recursive=True)\n else:\n msg = ('(add_table): node {} already exists. To '\n 'overwrite, use optional argument \"replace=True\"'\n ''.format(table_path))\n self._verbose_print(msg)\n\n # get compression options\n Filters = self._get_compression_opt(compression_options)\n self._verbose_print('-- Compression Options for dataset {}'\n ''.format(name))\n # create table\n table = self.h5_dataset.create_table(where=location_path, name=name,\n description=description,\n filters=Filters,\n chunkshape=chunkshape)\n if data is not None:\n print(data.shape)\n table.append(data)\n print(table)\n table.flush()\n # add to index\n if indexname is None:\n warn_msg = (' (add_table) indexname not provided, '\n ' the table name `{}` is used as index name '\n ''.format(name))\n self._verbose_print(warn_msg)\n indexname = name\n self.add_to_index(indexname, table._v_pathname)\n self.add_attributes({'node_type':'structured_array'},\n table._v_pathname)\n return table\n\n def add_tablecols(self, tablename, description, data=None):\n \"\"\"Add new columns to a table node.\n\n :param tablename: Name, Path or Indexname of the table where the\n columns must be added.\n :type tablename: str\n :param description: Description of the fields constituting the\n new columns to add the table.\n :type description: np.dtype or tables.IsDescription\n :param data: values to add into the new columns, defaults to None. The\n dtype of this array must be constitent with the `description`\n argument.\n :type data: np.array, optional\n :raises ValueError: If `data.dtype` and `description` do no match\n \"\"\"\n table = self.get_node(tablename)\n current_dtype = tables.dtype_from_descr(table.description)\n if isinstance(description, tables.IsDescription):\n descr_dtype = tables.dtype_from_descr(description)\n elif isinstance(description, np.dtype):\n descr_dtype = description\n else:\n raise ValueError('description must be a tables.IsDescription'\n ' instance or a numpy.dtype instance.')\n new_dtype = SampleData._merge_dtypes(current_dtype,descr_dtype)\n new_desc = tables.descr_from_dtype(new_dtype)[0]\n self._update_table_columns(tablename, new_desc)\n # if data is provided, safety check. Must be adequate array dtype\n if data is not None:\n if not(data.dtype == descr_dtype):\n raise ValueError('Data provided to add to the new columns'\n ' dtype is not consistent with the new'\n ' columns description inputed.\\n'\n 'Provided data dtype : {}\\n'\n 'Provided description : {}\\n'\n ''.format(data.dtype, descr_dtype))\n for colname in descr_dtype.names:\n column = data[colname]\n self.set_tablecol(tablename, colname, column)\n return\n\n def add_string_array(self, name, location, indexname=None,\n replace=False, data=[]):\n \"\"\"Add an enlargeable array to store strings of max 255 characters.\n\n String arrays are typically used to store large list of strings that\n are too large to be stored as HDF5 attributes into the dataset.\n\n .. Warning::\n The string are stored as byte strings. You will need to\n use the str.decode() method to get the elements of the\n string_array as UTF-8 or ASCII formatted strings.\n\n To manipulate a string array use the 'get_node' method to get the\n array, and then manipulate as a list of binary strings.\n\n :param str name: Name of the array to create\n :param str location: Path where the array will be added in the dataset\n :param str indexname: Index name used to reference the node\n composition as a sequence of named fields (analogous to Numpy\n structured arrays). It must be an instance of the\n :py:class:`tables.IsDescription` class from the\n `Pytables <https://www.pytables.org/index.html>`_ package\n :param bool replace: remove array in the dataset with the same\n name/location if `True`\n :param list[str] data: List of strings to add to the string array upon\n creation.\n \"\"\"\n self._verbose_print('Adding String Array `{}` into Group `{}`'\n ''.format(name, location))\n # get location path\n location_path = self._name_or_node_to_path(location)\n if (location_path is None):\n msg = ('(add_string_array): location {} does not exist, string'\n ' array cannot be added.'\n ''.format(location))\n self._verbose_print(msg)\n return\n else:\n # check location nature\n if not(self._get_node_class(location) == 'GROUP'):\n msg = ('(add_string_array): location {} is not a Group. '\n 'Please choose an empty location or a HDF5 '\n 'Group to store table'.format(location))\n self._verbose_print(msg)\n return\n # check if array location exists and remove node if asked\n array_path = os.path.join(location_path, name)\n if self.h5_dataset.__contains__(array_path):\n if replace:\n msg = ('(add_string_array): existing node {} will be '\n 'overwritten and all of its childrens removed'\n ''.format(array_path))\n self._verbose_print(msg)\n self.remove_node(array_path, recursive=True)\n else:\n msg = ('(add_string_array): node {} already exists. To '\n 'overwrite, use optional argument \"replace=True\"'\n ''.format(array_path))\n self._verbose_print(msg)\n\n # Create String array\n string_atom = tables.StringAtom(itemsize=255)\n str_array = self.h5_dataset.create_earray(where=location_path,\n name=name,\n atom=string_atom,\n shape=(0,))\n # Append input string list\n if data is not None:\n str_array.append(data)\n # Determine if array is created empty\n if len(data) == 0:\n empty = True\n else:\n empty = False\n # add to index\n if indexname is None:\n warn_msg = (' (add_string_array) indexname not provided, '\n ' the string array name `{}` is used as index name '\n ''.format(name))\n self._verbose_print(warn_msg)\n indexname = name\n self.add_to_index(indexname, str_array._v_pathname)\n self.add_attributes({'node_type':'string_array', 'empty':empty},\n str_array._v_pathname)\n return str_array\n\n def append_string_array(self, name, data=[]):\n \"\"\"Append a list of strings to a string array node in the dataset.\n\n :param str name: Path, Indexname, Name or Alias of the string array\n to which append the list of strings.\n :param list(str) data: List of strings to append to the string array.\n \"\"\"\n Sarray = self.get_node(name)\n if Sarray is None:\n raise tables.NodeError(f'No string array named {name} in the'\n ' dataset.')\n for string in data:\n a_str = bytes(string,'utf-8')\n Sarray.append([a_str])\n if len(Sarray) > 0 and self.get_attribute('empty', name):\n self.add_attributes({'empty':False}, name)\n return\n\n def append_table(self, name, data):\n \"\"\"Append a numpy structured array to a table in the dataset.\n\n :param str name: Path, Indexname, Name or Alias of the string array\n to which append the list of strings.\n :param numpy.ndarray data: array to append to the table? Its `dtype`\n must match de table description.\n \"\"\"\n table = self.get_node(name)\n table.append(data)\n table.flush()\n return\n\n\n def add_attributes(self, dic, nodename):\n \"\"\"Add a dictionary entries as HDF5 Attributes to a Node or Group.\n\n :param dic dic: Python dictionary of items to store in HDF5 file as\n HDF5 Attributes\n :param str nodename: Path, Index name or Alias of the HDF5 node or\n group receiving the Attributes\n \"\"\"\n Node = self.get_node(nodename)\n for key, value in dic.items():\n Node._v_attrs[key] = value\n return\n\n def add_alias(self, aliasname, path=None, indexname=None):\n \"\"\"Add alias name to reference Node with inputed path or index name.\n\n :param str aliasname: name to add as alias to reference the node\n :param str path: Path of the node to reference with `aliasname`\n :param str indexname: indexname of the node to reference with\n `aliasname`\n \"\"\"\n if (path is None) and (indexname is None):\n msg = ('(add_alias) None path nor indexname inputed. Alias'\n 'addition aborted')\n self._verbose_print(msg)\n return\n Is_present = (self._is_in_index(aliasname)\n and self._is_alias(aliasname))\n if Is_present:\n msg = ('Alias`{}` already exists : duplicates not allowed'\n ''.format(aliasname))\n self._verbose_print(msg)\n else:\n if (indexname is None):\n indexname = self.get_indexname_from_path(path)\n if indexname in self.aliases:\n self.aliases[indexname].append(aliasname)\n else:\n self.aliases[indexname] = [aliasname]\n return\n\n def add_to_index(self, indexname, path, colname=None):\n \"\"\"Add path to index if indexname is not already in content_index.\n\n :param str indexname: name to add as indexname to reference the node\n :param str path: Path of the node to reference with `aliasname`\n :param str colname: if the node is a `table` node, set colname to\n reference a column (named field) of the table with this indexname\n \"\"\"\n Is_present = (self._is_in_index(indexname)\n or self._is_alias(indexname))\n if Is_present:\n raise ValueError('Name `{}` already in '\n 'content_index : duplicates not allowed in Index'\n ''.format(indexname))\n else:\n for item in self.content_index:\n if isinstance(self.content_index[item], list):\n index_path = self.content_index[item][0]\n index_colname = self.content_index[item][1]\n else:\n index_path = self.content_index[item]\n index_colname = None\n if (path == index_path) and (colname is index_colname):\n msg = (' (add_to_index) indexname provided for a path ({})'\n 'that already in index --> stored as alias name.'\n ''.format(path))\n self._verbose_print(msg)\n self.add_alias(aliasname=indexname, indexname=item)\n return\n if colname is None:\n self.content_index[indexname] = path\n else:\n self.content_index[indexname] = [path, colname]\n return\n\n def compute_mesh_elements_normals(\n self, meshname, element_tag, Normal_fieldname=None,\n align_vector=np.random.rand(3), as_nodal_field=False):\n \"\"\"Compute the normals of a set of boundary elements of a mesh group.\n\n The normals are stored as en element wise constant field in the mesh\n group.\n\n :param meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :type meshname: str\n :param element_tag: name of the element tag or element type whose\n normals must be computed\n :type element_tag: str\n :param Normal_fieldname: Name of the normals field to store on the\n mesh group. Defaults to 'Normals_element_tag_name'\n :type Normal_fieldname: TYPE, optional\n :param align_vector: All normals are oriented to have positive dot\n product with `align_vector`, defaults to [0,0,1]\n :type align_vector: np.array(3), optional\n :raises ValueError: Can only process elements of bidimensional\n topology (surface elements, like triangles, quadrilaterals...)\n \"\"\"\n # TODO: move in Grid utils\n import BasicTools.Containers.ElementNames as EN\n if Normal_fieldname is None:\n Normal_fieldname = 'Normals_' + element_tag\n\n # Step 0: identify to which element type or element tag\n mesh_elements = self.get_mesh_elem_types_and_number(meshname)\n mesh_el_tags = self.get_mesh_elem_tags_names(meshname)\n if element_tag in mesh_elements.keys():\n el_type = mesh_elements[element_tag]\n if element_tag in mesh_el_tags.keys():\n el_type = mesh_el_tags[element_tag]\n\n # Step 1: Find out type of element and assert that it is a 2D element\n # type\n if EN.dimension[el_type] != 2:\n raise ValueError('Can compute normals only for sets of elements'\n ' with a 2D topology.')\n\n # Step 2: Extract element set connectivity and global IDs\n if element_tag in mesh_elements.keys():\n connectivity = self.get_mesh_elements(\n meshname, with_tags=False, get_eltype_connectivity=element_tag)\n if element_tag in mesh_el_tags.keys():\n connectivity = self.get_mesh_elem_tag_connectivity(\n meshname, element_tag)\n element_IDs = self.get_mesh_elem_tag(meshname, element_tag)\n\n # Step 3: Compute normals\n mesh_nodes = self.get_mesh_nodes(meshname, as_numpy=True)\n vect_1 = ( mesh_nodes[connectivity[:,1],:]\n - mesh_nodes[connectivity[:,0],:])\n vect_2 = ( mesh_nodes[connectivity[:,2],:]\n - mesh_nodes[connectivity[:,1],:])\n normals = np.cross(vect_1, vect_2)\n # * normalize normals\n norms = np.linalg.norm(normals, axis=-1)\n normals[:,0] = normals[:,0] / norms\n normals[:,1] = normals[:,1] / norms\n normals[:,2] = normals[:,2] / norms\n # * align orientation of surface vectors\n idx = np.where(np.dot(normals,align_vector) < 0)\n normals[idx,:] = - normals[idx,:]\n\n # Step 4: Create element field to store normals on mesh group\n Nelem = np.sum(self.get_attribute('Number_of_elements', meshname))\n Elem_normals_field = np.zeros(shape=(Nelem,3))\n Elem_normals_field[element_IDs,:] = normals\n if as_nodal_field:\n Nodal_normals_field = np.zeros(shape=mesh_nodes.shape)\n for nodeId in np.unique(connectivity):\n E_idx, _ = np.where(connectivity == nodeId)\n idxx = element_IDs[E_idx]\n Nodal_normals_field[nodeId,:] = (\n np.sum(Elem_normals_field[idxx,:], axis=0)\n ) / len(idxx)\n # print('E_idx :', E_idx, 'idxx :', idxx)\n # print('local Normals :', Elem_normals_field[idxx,:])\n # print(Nodal_normals_field[nodeId,:])\n # print(np.linalg.norm(Nodal_normals_field[nodeId,:]))\n norms = np.linalg.norm(Nodal_normals_field, axis=-1)\n idx = np.where(norms > 0)\n Nodal_normals_field[idx,0] = Nodal_normals_field[idx,0]/norms[idx]\n Nodal_normals_field[idx,1] = Nodal_normals_field[idx,1]/norms[idx]\n Nodal_normals_field[idx,2] = Nodal_normals_field[idx,2]/norms[idx]\n Normals_field = Nodal_normals_field\n else:\n Normals_field = Elem_normals_field\n # Step 5: store Normal field in mesh group\n self.add_field(meshname, Normal_fieldname, Normals_field)\n return\n\n def get_indexname_from_path(self, node_path):\n \"\"\"Return the Index name of the node at given path.\n\n :param str node_path: Path of the node in the HDF5 data tree\n :return: Returns the Index name of the node\n \"\"\"\n key = ''\n for k in self.content_index.keys():\n if (self.content_index[k] == node_path):\n key = k\n break\n if not (key == ''):\n return key\n else:\n msg = 'No node with path {} referenced in content index'.format(\n node_path)\n self._verbose_print(msg)\n\n def get_mesh(self, meshname, with_tags=True, with_fields=True,\n as_numpy=True):\n \"\"\"Return data of a mesh group as BasicTools UnstructuredMesh object.\n\n This methods gathers the data of a 2DMesh or 3DMesh group, including\n nodes coordinates, elements types and connectivity and fields, into a\n BasicTools :class:`ConstantRectilinearMesh` object.\n\n :param str meshname: Name, Path or Indexname of the mesh group to get\n :param bool with_tags: If `True`, store the nodes and element tags\n (sets) into the mesh object\n :param bool with_fields: If `True`, store mesh group fields into the\n mesh_object, defaults to True\n :type with_fields: bool, optional\n :return: Mesh_object containing all data (nodes, elements, nodes and\n elements sets, fields), contained in the mesh data group.\n :rtype: BasicTools :class:`UnstructuredMesh` object.\n\n \"\"\"\n # Create mesh object\n mesh_object = UnstructuredMesh()\n # Get mesh nodes\n mesh_object.nodes = self.get_mesh_nodes(meshname, as_numpy)\n # No mesh ID for now --> create mesh Ids\n mesh_object.originalIDNodes = self.get_mesh_nodesID(meshname, as_numpy)\n # Get node tags\n if with_tags:\n self._load_nodes_tags(meshname, mesh_object, as_numpy=as_numpy)\n # Get mesh elements and element tags\n mesh_object.elements = self.get_mesh_elements(meshname,\n with_tags=with_tags,\n as_numpy=as_numpy)\n # Set mesh originalIds from 0 to Nelems\n Nelems = np.sum(self.get_attribute('Number_of_elements', meshname))\n originalIds = np.arange(Nelems) + 1\n mesh_object.SetElementsOriginalIDs(originalIds)\n # Get mesh fields\n mesh_group = self.get_node(meshname)\n mesh_indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n FIndex = mesh_indexname+'_Field_index'\n Field_index = self.get_node(FIndex)\n if with_fields and (Field_index is not None):\n for fieldname in Field_index:\n name = fieldname.decode('utf-8')\n field_type = self.get_attribute('field_type', name)\n if field_type == 'Nodal_field':\n data = self.get_field(name, unpad_field=True)\n mesh_object.nodeFields[name] = data\n elif field_type == 'Element_field':\n data = self.get_field(name, unpad_field=True)\n mesh_object.elemFields[name] = data\n mesh_object.PrepareForOutput()\n return mesh_object\n\n def get_mesh_from_image(self, imagename, with_fields=True, ofTetras=False):\n \"\"\"Return an UnstructuredMesh instance from an Image data group.\n\n :param str imagename: Name, Path or Indexname of the mesh group to get\n :param bool with_fields: If `True`, load the nodes and elements fields\n from the image group into the mesh object.\n :param bool ofTetras: if `True`, returns a mesh with tetrahedron\n elements. If `False`, return a rectilinera mesh of hexaedron\n elements.\n :return: Mesh_object containing all data (nodes, elements, nodes and\n elements sets, fields), corresponding to the Image data group\n content.\n :rtype: BasicTools :class:`UnstructuredMesh` object.\n \"\"\"\n mesh_CR = self.get_image(imagename, with_fields)\n mesh_obj = UMCT.CreateMeshFromConstantRectilinearMesh(mesh_CR,\n ofTetras)\n n_elems = mesh_obj.GetNumberOfNodes()\n if with_fields:\n for key,val in mesh_CR.nodeFields.items():\n mesh_obj.nodeFields[key] = val.reshape((n_elems,1))\n return mesh_obj\n\n def get_mesh_nodes(self, meshname, as_numpy=False):\n \"\"\"Return the mesh node coordinates as a HDF5 node or Numpy array.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :param bool as_numpy: if `True`, returns the Node as a `numpy.array`.\n If `False`, returns the node as a Node or Group object.\n :return: Return the mesh Nodes coordinates array as a\n :py:class:`tables.Node` object or a `numpy.array`\n \"\"\"\n nodes_path = self.get_attribute('nodes_path', meshname)\n return self.get_node(nodes_path, as_numpy)\n\n def get_mesh_nodesID(self, meshname, as_numpy=False):\n \"\"\"Return the mesh node ID as a HDF5 node or Numpy array.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :param bool as_numpy: if `True`, returns the Node as a `numpy.array`.\n If `False`, returns the node as a Node or Group object.\n :return: Return the mesh Nodes ID array as a\n :py:class:`tables.Node` object or a `numpy.array`\n \"\"\"\n nodes_path = self.get_attribute('nodesID_path', meshname)\n nodesID = self.get_node(nodes_path, as_numpy)\n if nodesID is None:\n Nnodes = self.get_mesh_nodes(meshname).shape[0]\n nodesID = np.arange(Nnodes)\n return nodesID\n\n def get_mesh_node_tag(self, meshname, node_tag, as_numpy=True):\n \"\"\"Returns the node IDs of a node tag of the mesh group.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :param str node_tag: name of the node tag whose IDs must be returned.\n :param bool as_numpy: if `True`, returns arrays in elements container\n as numpy array\n \"\"\"\n # Add prefix to node tag name if needed\n if not node_tag.startswith('NT_'):\n node_tag_nodename = 'NT_' + node_tag\n # get mesh group\n mesh_group = self.get_node(meshname)\n # get path of Element tag\n NT_path = os.path.join(mesh_group._v_pathname,'Geometry',\n 'NodeTags', node_tag_nodename)\n # get element tag type\n tag = self.get_node(NT_path, as_numpy=as_numpy)\n return tag\n\n def get_mesh_node_tag_coordinates(self, meshname, node_tag):\n \"\"\"Returns the node coordinates of a node tag of the mesh group.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :param str node_tag: name of the node tag whose IDs must be returned.\n :param bool as_numpy: if `True`, returns arrays in elements container\n as numpy array\n \"\"\"\n tag = self.get_mesh_node_tag(meshname, node_tag, as_numpy=True)\n Nodes = self.get_mesh_nodes(meshname, as_numpy=True)\n return Nodes[tag,:]\n\n def get_mesh_xdmf_connectivity(self, meshname, as_numpy=True):\n \"\"\"Return the mesh elements connectivity as HDF5 node or Numpy array.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :param bool as_numpy: if `True`, returns the Node as a `numpy.array`.\n If `False`, returns the node as a Node or Group object.\n :return: Return the mesh elements connectivity referenced in the XDMF\n file as a :py:class:`tables.Node` object or a `numpy.array`\n \"\"\"\n elems_path = self.get_attribute('elements_path', meshname)\n return self.get_node(elems_path, as_numpy)\n\n def get_mesh_elements(self, meshname, with_tags=True, as_numpy=True,\n get_eltype_connectivity=None):\n \"\"\"Return the mesh elements connectivity as HDF5 node or Numpy array.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :param bool with_tags: if `True`, loads the element tags in the\n returned elements container\n :param bool as_numpy: if `True`, returns arrays in elements container\n as numpy array\n :param str get_eltype_connectivity: if this argument is set to the name\n of an element type contained in the mesh, the method retuns the\n connectivity array of these elements, and not the BasicTools\n elements container.\n :return: Return the mesh elements container as a\n BasicTools :py:class:`AllElements` object\n \"\"\"\n # Create AllElementsContainer\n AElements = AllElements()\n connectivity = self.get_mesh_xdmf_connectivity(meshname, as_numpy)\n # Get Elements Metadata\n Mesh_attrs = self.get_dic_from_attributes(meshname)\n Topology = Mesh_attrs['Topology']\n element_type = Mesh_attrs['element_type']\n Nelems = Mesh_attrs['Number_of_elements']\n Xdmf_code = Mesh_attrs['Xdmf_elements_code']\n offset = 0\n # For each element type, create an Element container and fill\n # connectivity\n for i in range(len(element_type)):\n # Create elements container\n Elements = AElements.GetElementsOfType(element_type[i])\n # get parameters for element type elements in mesh\n Nnode_per_el = Elements.GetNumberOfNodesPerElement()\n Nvalues = (1+Nnode_per_el)*Nelems[i]\n id_offset = 1\n local_code = Xdmf_code[i]\n # For bar2 and point1 elements, 2 integers are stored as XDMF code\n # before each element connectivity\n if (element_type[i] == 'bar2') or (element_type[i] == 'point1'):\n Nvalues += Nelems[i]\n id_offset += 1\n Nnode_per_el += 1\n if Topology == 'Mixed':\n # Get connectivity chunk for this element type and reshape it\n local_connect = connectivity[offset:offset+Nvalues]\n local_connect = local_connect.reshape((Nelems[i],\n Nnode_per_el+1))\n # Safety check\n if not(np.all(local_connect[:,0] == local_code)):\n raise ValueError('Local connectivity for element type {}'\n ' is ill-shaped : Xdmf code value wrong'\n ' for at least one element.'\n ''.format(element_type[i]))\n if get_eltype_connectivity == element_type[i]:\n return local_connect[:,id_offset:]\n Elements.connectivity = local_connect[:,id_offset:]\n Elements.cpt = Nelems[i]\n offset = Nvalues\n elif Topology == 'Uniform':\n Elements.connectivity = connectivity.reshape((Nelems[i],\n Nnode_per_el))\n Elements.cpt = Nelems[i]\n if get_eltype_connectivity == element_type[i]:\n return Elements.connectivity\n if with_tags:\n self._load_elements_tags(meshname, AElements, as_numpy)\n return AElements\n\n def get_mesh_elem_types_and_number(self, meshname):\n \"\"\"Returns the list and types of elements tags defined on a mesh.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :return dict: keys are element types in the mesh and values are the\n number of elements for each element type.\n \"\"\"\n elem_types = self.get_attribute('element_type', meshname)\n elem_number = self.get_attribute('Number_of_elements', meshname)\n return {elem_types[i]:elem_number[i] for i in range(len(elem_types))}\n\n def get_mesh_elem_tag(self, meshname, element_tag, as_numpy=True,\n local_IDs=False):\n \"\"\"Returns the elements IDs of an element tag of the mesh group.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :param str element_tag: name of the element tag whose connectivity\n must be returned. Can also be one of the element types contained\n in the mesh. In this case, the complete global element IDs for\n these elements is return\n :param bool as_numpy: if `True`, returns arrays in elements container\n as numpy array\n :param bool local_IDs: if `True`, returns the local elements IDs for\n the element type, i.e. the indexes of elements in the local\n connectivity array that can be obtain with get_mesh_elements.\n \"\"\"\n # find out if the required element_tag is an element type of the mesh\n mesh_elements = self.get_mesh_elem_types_and_number(meshname)\n if element_tag in mesh_elements.keys():\n # return element type IDs\n offsets = self._get_mesh_elements_offsets(meshname)\n el_numbers = self.get_mesh_elem_types_and_number(meshname)\n tag = np.arange(el_numbers[element_tag])\n if not local_IDs:\n tag = tag + offsets[element_tag]\n else:\n # Return element tag IDs\n # Add prefix to element_tag name if needed\n if not element_tag.startswith('ET_'):\n el_tag_nodename = 'ET_' + element_tag\n el_tag_true_name = element_tag\n else:\n el_tag_true_name = element_tag[3:]\n # get mesh group\n mesh_group = self.get_node(meshname)\n # get path of Element tag\n ET_path = os.path.join(mesh_group._v_pathname,'Geometry',\n 'ElementsTags',el_tag_nodename)\n # get element tag type\n tag = self.get_node(ET_path, as_numpy=as_numpy)\n if local_IDs:\n tag_names = self.get_mesh_elem_tags_names(meshname)\n offsets = self._get_mesh_elements_offsets(meshname)\n tag = tag - offsets[tag_names[el_tag_true_name]]\n return tag\n\n def get_mesh_elem_tags_names(self, meshname):\n \"\"\"Returns the list and types of elements tags defined on a mesh.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :return dict: keys are element tag names in the mesh and values are the\n element type for each element tag.\n \"\"\"\n mesh_group = self.get_node(meshname)\n indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n Etag_list_indexname = indexname +'_ElTagsList'\n Etag_list = self.get_node(Etag_list_indexname)\n Etag_Etype_list_indexname = indexname +'_ElTagsTypeList'\n Etag_Etype_list = self.get_node(Etag_Etype_list_indexname)\n Tags_dict = {\n Etag_list[i].decode('utf-8'):Etag_Etype_list[i].decode('utf-8')\n for i in range(len(Etag_list))}\n return Tags_dict\n\n def get_mesh_elem_tag_connectivity(self, meshname, element_tag):\n \"\"\"Returns the list and types of elements tags defined on a mesh.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :param str element_tag: name of the element tag whose connectivity\n must be returned.\n \"\"\"\n # get element tag type\n tags = self.get_mesh_elem_tags_names(meshname)\n el_type = tags[element_tag]\n # get connectivity of element type\n type_connectivity = self.get_mesh_elements(\n meshname, get_eltype_connectivity=el_type)\n # get local element IDs in element tag\n local_IDs = self.get_mesh_elem_tag(meshname, element_tag,\n local_IDs=True)\n return type_connectivity[local_IDs,:]\n\n def get_mesh_node_tags_names(self, meshname):\n \"\"\"Returns the list of node tags defined on a mesh.\n\n :param str meshname: Name, Path, Index name or Alias of the Mesh group\n in dataset\n :return list node_tags: list of node tag names defined on this mesh\n \"\"\"\n mesh_group = self.get_node(meshname)\n indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n Ntag_list_indexname = indexname+'_NodeTagsList'\n NTags_list = self.get_node(Ntag_list_indexname).read()\n node_tags = []\n for tag in NTags_list:\n node_tags.append(tag.decode('utf-8'))\n return node_tags\n\n\n def get_image(self, imagename, with_fields=True):\n \"\"\"Return data of an image group as a BasicTools mesh object.\n\n This methods gathers the data of a 2DImage or 3DImage group, including\n grid geometry and fields, into a BasicTools\n :class:`ConstantRectilinearMesh` object.\n\n :param imagename: Name, Path or Indexname of the image group to get\n :type imagename: str\n :param bool with_fields: If `True`, load the nodes and elements fields\n from the image group into the mesh object.\n :return: Returns a BasicTools rectilinear mesh object with image group\n data.\n :rtype: :class:`ConstantRectilinearMesh`\n \"\"\"\n # Get image informations\n dimensions = self.get_attribute('nodes_dimension', imagename)\n spacing = self.get_attribute('spacing', imagename)\n origin = self.get_attribute('origin', imagename)\n # Create ConstantRectilinearMesh to serve as image_object\n image_object = ConstantRectilinearMesh(dim=len(dimensions))\n image_object.SetDimensions(dimensions)\n image_object.SetSpacing(spacing)\n image_object.SetOrigin(origin)\n # Get image fields\n image_group = self.get_node(imagename)\n FIndex_path = os.path.join(image_group._v_pathname,'Field_index')\n Field_index = self.get_node(FIndex_path)\n if with_fields and (Field_index is not None):\n for fieldname in Field_index:\n name = fieldname.decode('utf-8')\n field_type = self.get_attribute('field_type', name)\n if field_type == 'Nodal_field':\n data = self.get_field(fieldname=name)\n image_object.nodeFields[name] = data\n elif field_type == 'Element_field':\n data = self.get_field(fieldname=name)\n image_object.elemFields[name] = data\n return image_object\n\n def get_tablecol(self, tablename, colname):\n \"\"\"Return a column of a table as a numpy array.\n\n :param str tablename: Name, Path, Index name or Alias of the table in\n dataset\n :param str colname: Name of the column to get in the table (analogous\n to name of the field to get in a Numpy structured array)\n :return numpy.array data: returns the queried column data as a\n `numpy.array`\n \"\"\"\n data = None\n data_path = self._name_or_node_to_path(tablename)\n if data_path is None:\n msg = ('(get_tablecol) `tablename` not matched with a path or an'\n ' indexname. No data returned')\n self._verbose_print(msg)\n else:\n if self._is_table(name=data_path):\n msg = '(get_tablecol) Getting column {} from : {}:{}'.format(\n colname, self.h5_file, data_path)\n self._verbose_print(msg)\n table = self.get_node(name=data_path)\n data = table.col(colname)\n else:\n msg = ('(get_tablecol) Data is not an table node.')\n self._verbose_print(msg)\n return data\n\n def get_table_description(self, tablename, as_dtype=False):\n \"\"\"Get the description of the table as a description or Numpy dtype.\"\"\"\n if as_dtype:\n return self[tablename].dtype\n return self.get_node(tablename).description\n\n def get_grid_field_list(self, gridname):\n \"\"\"Return the list of fields stored on the grid.\n\n :param str gridname: Path, name or indexname of the grid Group on which\n the field will be added\n :return str Field_list: List of the name of the fields dataset stored\n in the hdf5 file and defined on the grid.\n \"\"\"\n grid_group = self.get_node(gridname)\n FIndex_path = os.path.join(grid_group._v_pathname,'Field_index')\n Field_index = self.get_node(FIndex_path)\n Field_list = []\n if Field_index is None:\n print(f'No Field_index node for grid {gridname}')\n return None\n for fieldname in Field_index:\n name = fieldname.decode('utf-8')\n Field_list.append(name)\n return Field_list\n\n def get_field(self, fieldname, unpad_field=True,\n get_visualisation_field=False):\n \"\"\"Return a padded or unpadded field from a grid data group as array.\n\n Use this method to get a mesh element wise field in its original form,\n i.e. bulk element fields (defined on elements of the same dimensonality\n than the mesh) or a boundary field (defined on elements of a lower\n dimensionality than the mesh).\n\n :param str fieldname: Name, Path, Index, Alias or Node of the field in\n dataset\n :param bool unpad_field: if `True` (default), remove the zeros added to\n to the field to comply with the mesh topology and return it with\n its original size (bulk or boundary field).\n \"\"\"\n field_type = self.get_attribute('field_type', fieldname)\n if (field_type == 'IP_field') and get_visualisation_field:\n field_path = self.get_attribute('visualisation_field_path',\n fieldname)\n field = self.get_node(field_path, as_numpy=True)\n else:\n field = self.get_node(fieldname, as_numpy=True)\n padding = self.get_attribute('padding', fieldname)\n parent_mesh = self.get_attribute('parent_grid_path', fieldname)\n pad_field = (padding != None) and (unpad_field)\n if (field_type == 'IP_field') and not get_visualisation_field:\n pad_field = False\n if pad_field:\n field = self._mesh_field_unpadding(field, parent_mesh, padding)\n if self._is_image(parent_mesh):\n dim = self.get_attribute('dimension', parent_mesh)\n field_dim = self.get_attribute('field_dimensionality', fieldname)\n if field_dim == 'Scalar':\n field = field.reshape(dim)\n elif ((field_dim == 'Vector') or (field_dim == 'Tensor6')\n or (field_dim == 'Tensor')):\n field = field.reshape(*dim, field.shape[-1])\n return field\n\n def get_node(self, name, as_numpy=False):\n \"\"\"Return a HDF5 node in the dataset.\n\n The node is returned as a :py:class:`tables.Node`,\n :py:class:`tables.Group` or a :py:class:`numpy.ndarray` depending\n on its nature, and the value of the `as_numpy` argument.\n\n :param str name: Name, Path, Index name or Alias of the Node in dataset\n :param bool as_numpy: if `True`, returns the Node as a `numpy.array`.\n If `False`, returns the node as a Node or Group object.\n :return: Return the node as a a :py:class:`tables.Node` or\n :py:class:`tables.Group` object depending on the nature of the\n node, or, returns it as a `numpy.array` if required and if the node\n is an array node.\n \"\"\"\n node = None\n colname = None\n node_path = self._name_or_node_to_path(name)\n if node_path is None:\n msg = ('(get_node) ERROR : Node name does not fit any hdf5 path'\n ' nor index name.')\n self._verbose_print(msg)\n else:\n if self._is_table(node_path):\n node = self.h5_dataset.get_node(node_path)\n if name in self.content_index:\n if isinstance(self.content_index[name], list):\n colname = self.content_index[name][1]\n elif name in node.colnames:\n colname = name\n if (colname is not None):\n node = node.col(colname)\n else:\n node = self.h5_dataset.get_node(node_path)\n if as_numpy and self._is_array(name) and (colname is None):\n # note : np.atleast_1d is used here to avoid returning a 0d\n # array when squeezing a scalar node\n node = np.atleast_1d(node.read())\n # Reverse data normalization if it has been applied\n # NOTE: it is very important to keep these lines before\n # those aiming at reversing transpositions for ordering\n # conventions as the arrays containing normalization parameters\n # comply to the in-memory ordering conventions\n norm = self.get_attribute('data_normalization', name)\n if norm == 'standard':\n mu = self.get_attribute('normalization_mean', name)\n std = self.get_attribute('normalization_std', name)\n node = (node * std) + mu\n elif norm == 'standard_per_component':\n mu = self.get_attribute('normalization_mean', name)\n std = self.get_attribute('normalization_std', name)\n for comp in range(node.shape[-1]):\n node[...,comp] = (node[..., comp]*std[comp]) + mu[comp]\n # Reverse indices transpositions apply to ensure compatibility\n # between SampleData and Paraview ordering conventions\n transpose_indices = self.get_attribute('transpose_indices',\n name)\n if transpose_indices is not None:\n node = node.transpose(transpose_indices)\n transpose_components = self.get_attribute('transpose_components',\n name)\n if transpose_components is not None:\n node = node[...,transpose_components]\n node = np.atleast_1d(node)\n return node\n\n def get_dic_from_attributes(self, nodename):\n \"\"\"Get all attributes from a HDF5 Node in the dataset as a dictionary.\n\n :param str nodename: Name, Path, Index name or Alias of the HDF5 group\n :return: Dictionary of the form ``{'Attribute_name': Attribute_value}``\n \"\"\"\n Node = self.get_node(nodename)\n dic = {}\n for key in Node._v_attrs._f_list():\n dic[key] = Node._v_attrs[key]\n return dic\n\n def get_attribute(self, attrname, nodename):\n \"\"\"Get a specific attribute value from a HDF5 Node in the dataset.\n\n :param str attrname: name of the attribute to get\n :param str nodename: Name, Path, Index name or Alias of the HDF5 group\n :return: Value of the attribute\n \"\"\"\n attribute = None\n data_path = self._name_or_node_to_path(nodename)\n if (data_path is None):\n self._verbose_print(' (get_attribute) neither indexname nor'\n ' node_path passed, node return aborted')\n else:\n try:\n attribute = self.h5_dataset.get_node_attr(where=data_path,\n attrname=attrname)\n except AttributeError:\n # self._verbose_print(' (get_attribute) node {} has no attribute'\n # ' `{}`'.format(nodename,attrname))\n return None\n if isinstance(attribute, bytes):\n attribute = attribute.decode()\n return attribute\n\n def get_file_disk_size(self, print_flag=True, convert=True):\n \"\"\"Get the disk size of the dataset.\n\n :param bool print_flag: print the disk size if `True`\n :param bool convert: convert disk size to a suitable memory unit if\n `True`. If `False`, return result in bytes.\n :return float fsize: Disk size of the dataset in `unit`\n :return str unit: Unit of `fsize`. `bytes` is the default\n \"\"\"\n units = ['bytes', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb']\n fsize = os.path.getsize(self.h5_path)\n k = 0\n unit = units[k]\n if convert:\n while fsize/1024 > 1:\n k = k+1\n fsize = fsize/1024\n unit = units[k]\n if print_flag:\n print('File size is {:9.3f} {} for file \\n {}'\n ''.format(fsize, unit, self.h5_file))\n return fsize, unit\n\n def get_node_disk_size(self, nodename, print_flag=True, convert=True):\n \"\"\"Get the disk size of a HDF5 node.\n\n :param str nodename: Name, Path, Index name or Alias of the HDF5 node\n :param bool print_flag: print the disk size if `True`\n :param bool convert: convert disk size to a suitable memory unit if\n `True`. If `False`, return result in bytes.\n :return float fsize: Disk size of the dataset in `unit`\n :return str unit: Unit of `fsize`. `bytes` is the default\n \"\"\"\n units = ['bytes', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb']\n if not self.__contains__(nodename):\n raise tables.NodeError('node `{}` not in {} instance'\n ''.format(nodename,\n self.__class__.__name__))\n if not self._is_array(nodename):\n print('Node {} is not a data array node'.format(nodename))\n return None\n node = self.get_node(nodename)\n nsize = node.size_on_disk\n k = 0\n unit = units[k]\n if convert:\n while nsize/1024 > 1:\n k = k+1\n nsize = nsize/1024\n unit = units[k]\n if print_flag:\n print('Node {} size on disk is {:9.3f} {}'.format(nodename,\n nsize, unit))\n return nsize, unit\n\n def get_sample_name(self):\n \"\"\"Return the sample name.\"\"\"\n return self.get_attribute(attrname='sample_name', nodename='/')\n\n def set_sample_name(self, sample_name):\n \"\"\"Set the sample name.\n\n :param str sample_name: a string for the sample name.\n \"\"\"\n self.add_attributes({'sample_name': sample_name}, '/')\n\n def get_description(self, node='/'):\n \"\"\"Get the string describing this node.\n\n By defaut the sample description is returned, from the root HDF5 Group.\n\n :param str nodename: the path or name of the node of interest.\n \"\"\"\n return self.get_attribute(attrname='description', nodename=node)\n\n def set_description(self, description, node='/'):\n \"\"\"Set the description of a node.\n\n By defaut this method sets the description of the complete sample, in\n the root HDF5 Group.\n\n :param str description: a string for the description of the node or\n sample.\n :param str node: the path or name of the node of interest ('/' by\n default).\n \"\"\"\n self.add_attributes({'description': description}, node)\n return\n\n def set_new_indexname(self, nodename, new_indexname):\n \"\"\"Change the indexname of a node in the dataset.\n\n Usefull to solve indexname duplicates issues that can arises when\n automatically adding elements to the dataset, that have the same name.\n\n :param nodename: Name, Path, Indexname or Alias of the node whose\n indexname is to be changed\n :type nodename: str\n :param new_indexname: New indexname for the node\n :type new_indexname: str\n \"\"\"\n path = self._name_or_node_to_path(nodename)\n old_indexname = self.get_indexname_from_path(path)\n index_content = self.content_index.pop(old_indexname)\n self.content_index[new_indexname] = index_content\n return\n\n\n def set_voxel_size(self, image_group, voxel_size):\n \"\"\"Set voxel size for an HDF5/XDMF image data group.\n\n The values are registered in the `spacing` Attribute of the 3DImage\n group.\n\n :param str image_data_group: Name, Path, Index name or Alias of the\n 3DImage group\n :param np.array voxel_size: (dx, dy, dz) array of the voxel size in\n each dimension of the 3Dimage\n \"\"\"\n old_spacing = self.get_attribute('spacing', image_group)\n if isinstance(voxel_size, float):\n voxel_size = np.ones(shape=(len(old_spacing),))*voxel_size\n if len(old_spacing) != len(voxel_size):\n raise ValueError('Dimension mismatch between image group old'\n f' grid spacing {old_spacing} and inputed'\n f' new grid spacing {voxel_size}')\n self.add_attributes({'spacing': np.array(voxel_size)},\n image_group)\n if len(voxel_size) == 2:\n VoxSize = voxel_size[[1,0]]\n elif len(voxel_size) == 3:\n VoxSize = voxel_size[[2,1,0]]\n xdmf_grid = self._find_xdmf_grid(image_group)\n # find out if the grid has subgrids (temporal grid collection)\n if xdmf_grid.getchildren()[0].tag == 'Grid':\n # grid collection\n for grid in xdmf_grid:\n geo = self._find_xdmf_geometry(grid)\n spacing_node = geo.getchildren()[1]\n spacing_text = str(VoxSize).strip('[').strip(']').replace(',', ' ')\n spacing_node.text = spacing_text\n else:\n geo = self._find_xdmf_geometry(xdmf_grid)\n spacing_node = geo.getchildren()[1]\n spacing_text = str(VoxSize).strip('[').strip(']').replace(',', ' ')\n spacing_node.text = spacing_text\n self.sync()\n return\n\n def set_origin(self, image_group, origin):\n \"\"\"Set origin coordinates for an HDF5/XDMF image data group.\n\n The origin corresponds to the first vertex of the first voxel, that is\n referenced by the [0,0,0] elements of arrays in the 3DImage group. The\n values are registered in the `origin` Attribute of the 3DImage group.\n\n :param str image_data_group: Name, Path, Index name or Alias of the\n 3DImage group\n :param np.array voxel_size: (Ox, Oy, Oz) array of the coordinates in\n each dimension of the origin of the 3Dimage\n \"\"\"\n old_origin = self.get_attribute('origin', image_group)\n if len(old_origin) != len(origin):\n raise ValueError('Dimension mismatch between image group origin'\n f' {old_origin} and inputed new origin'\n f' {origin}')\n self.add_attributes({'origin': origin}, image_group)\n if len(origin) == 2:\n Or = origin[[1,0]]\n elif len(origin) == 3:\n Or = origin[[2,1,0]]\n xdmf_grid = self._find_xdmf_grid(image_group)\n # find out if the grid has subgrids (temporal grid collection)\n if xdmf_grid.getchildren()[0].tag == 'Grid':\n # grid collection\n for grid in xdmf_grid:\n geo = self._find_xdmf_geometry(grid)\n origin_node = geo.getchildren()[0]\n origin_text = str(Or).strip('[').strip(']').replace(',', ' ')\n origin_node.text = origin_text\n else:\n geo = self._find_xdmf_geometry(xdmf_grid)\n origin_node = geo.getchildren()[0]\n origin_text = str(Or).strip('[').strip(']').replace(',', ' ')\n origin_node.text = origin_text\n self.sync()\n return\n\n def set_tablecol(self, tablename, colname, column):\n \"\"\"Store an array into a structured table column.\n\n If the column is not in the table description, a new field\n corresponding to the inputed column is added to the table description.\n\n :param str tablename: Name, Path, Index name or Alias of the table\n :param str colname: Name of the column to set (analogous to name of a\n field in a `Numpy` structured array)\n :param np.array column: array of values to set as column of the table.\n It's shape must match the column shape in table description.\n \"\"\"\n if not self._is_table(tablename):\n raise tables.NodeError('{} is not a structured table node'\n ''.format(tablename))\n table = self.get_node(tablename)\n col_shape = self.get_tablecol(tablename, colname).shape\n if (column.shape != col_shape):\n raise ValueError('inputed column shape {} does not match the shape'\n '{} of column {} in table {}'\n ''.format(column.shape, col_shape, colname,\n tablename))\n table.modify_column(column=column, colname=colname)\n table.flush()\n return\n\n def set_nodes_compression_chunkshape(self, node_list=None, chunkshape=None,\n compression_options=dict()):\n \"\"\"Set compression options for a list of nodes in the dataset.\n\n This methods sets the same set of compression options for a\n list of nodes in the dataset.\n\n :param list node_list: list of Name, Path, Index name or Alias of the\n HDF5 array nodes where to set the compression settings.\n :param tuple chunkshape: The shape of the data chunk to be read or\n written in a single HDF5 I/O operation\n :param dict compression_options: Dictionary containing compression\n options items (keys are options names, values are )\n\n .. rubric:: Compression Options\n\n Compression settings can be passed through the `compression_options`\n dictionary as follows:\n compression_options[option_name] = option_value\n These options are the Pytables package `Filters\n <https://www.pytables.org/_modules/tables/filters.html#Filters>`_\n class constructor parameters (see `PyTables` documentation for details)\n The list of available compression options is provided here:\n\n * complevel: Compression level for data. Allowed range is 0-9.\n A value of 0 (the default) disables compression.\n * complib: Compression library to use. Possibilities are:\n zlib' (the default), 'lzo', 'bzip2' and 'blosc'.\n * shuffle: Whether or not to use the *Shuffle* filter in the\n HDF5 library (may improve compression ratio).\n * bitshuffle: Whether or not to use the *BitShuffle* filter\n in the Blosc library (may improve compression ratio).\n * fletcher32: Whether or not to use the *Fletcher32* filter\n in the HDF5 library. This is used to add a checksum on each data\n chunk.\n * least_significant_digit:\n If specified, data will be truncated using\n ``around(scale*data)/scale``, where\n ``scale = 2**least_significant_digit``.\n In conjunction with enabling compression, this produces 'lossy',\n but significantly more efficient compression.\n\n .. important:: If the new compression settings reduce the size of the\n node in the dataset, the file size will not be changed. This is a\n standard behavior for HDF5 files, that preserves freed space in\n disk to add additional data in the future. If needed, use the\n :func:`repack_file` method to reduce file disk size after changing\n compression settings. This method is also called by the class\n instance destructor.\n\n .. note:: If compression settings are passed as additional keyword\n arguments, they are prioritised over the settings in the inputed\n Filter object.\n \"\"\"\n if node_list is None:\n node_list = []\n for node in self.h5_dataset.root:\n if self._is_array(node):\n node_list.append(node)\n for nodename in node_list:\n self.set_chunkshape_and_compression(nodename, chunkshape,\n compression_options)\n return\n\n def set_chunkshape_and_compression(self, nodename, chunkshape=None,\n compression_options=dict()):\n \"\"\"Set the chunkshape and compression settings for a HDF5 array node.\n\n :param str node: Name, Path, Index name or Alias of the node\n :param tuple chunkshape: The shape of the data chunk to be read or\n written in a single HDF5 I/O operation\n :param dict compression_options: Dictionary containing compression\n options items (keys are options names, values are )\n\n .. rubric:: Compression options\n\n Compression settings can be passed through the `compression_options`\n dictionary as follows:\n compression_options[option_name] = option_value\n See :func:`set_nodes_compression_chunkshape`, for the list of\n available compression options.\n\n .. important:: If the new compression settings reduce the size of the\n node in the dataset, the file size will not be changed. This is a\n standard behavior for HDF5 files, that preserves freed space in\n disk to add additional data in the future. If needed, use the\n :func:`repack_file` method to reduce file disk size after changing\n compression settings. This method is also called by the class\n instance destructor.\n\n .. note:: If compression settings are passed as additional keyword\n arguments, they are prioritised over the settings in the inputed\n Filter object.\n \"\"\"\n if not self._is_array(nodename):\n msg = ('(set_chunkshape) Cannot set chunkshape or compression'\n ' settings for a non array node')\n raise tables.NodeError(msg)\n # Get HDF5 node whose compression and chunkshape settings are to\n # be changed\n # chunkshape cannot be changed for a Pytables dataset node, and\n # changing compression settings can lead to errors or unexpected\n # behaviors\n # ==> New settings are set by reading rewriting data on the dataset\n # First get the hdf5 attributes of the target node\n attributes = self.get_dic_from_attributes(nodename)\n node_tmp = self.get_node(nodename)\n # Get node name, indexname and path\n nodename = node_tmp._v_name\n node_indexname = self.get_indexname_from_path(node_tmp._v_pathname)\n node_path = os.path.dirname(node_tmp._v_pathname)\n # Set new chunkshape if provided or get old one\n node_chunkshape = node_tmp.chunkshape\n if chunkshape is not None:\n node_chunkshape = chunkshape\n # Get node aliases\n if self.aliases.__contains__(node_indexname):\n node_aliases = self.aliases[node_indexname]\n else:\n node_aliases = []\n if self._is_table(nodename):\n # get stored array values\n array = node_tmp.read()\n description = node_tmp.description\n new_array = self.add_table(\n location=node_path, name=nodename, description=description,\n indexname=node_indexname, chunkshape=node_chunkshape,\n replace=True, data=array,\n compression_options=compression_options)\n elif self._is_field(nodename):\n array = self.get_field(nodename)\n parent_grid = self.get_attribute('parent_grid_path', nodename)\n visu_type = self.get_attribute('visualisation_type', nodename)\n if visu_type is None:\n visu_type = 'None'\n new_array = self.add_field(\n gridname=parent_grid, fieldname=nodename, array=array,\n indexname=node_indexname,\n chunkshape=node_chunkshape, replace=True,\n visualisation_type=visu_type,\n compression_options=compression_options)\n else:\n array = node_tmp.read()\n new_array = self.add_data_array(\n location=node_path, name=nodename, indexname=node_indexname,\n array=array, chunkshape=node_chunkshape,\n replace=True, compression_options=compression_options)\n for alias in node_aliases:\n self.add_alias(aliasname=alias, indexname=node_indexname)\n self.add_attributes(attributes, nodename)\n if self._verbose:\n self._verbose_print(self.print_node_compression_info(\n new_array._v_pathname))\n return\n\n def set_verbosity(self, verbosity=True):\n \"\"\"Set the verbosity of the instance methods to inputed boolean.\"\"\"\n self._verbose = verbosity\n return\n\n def remove_attribute(self, attrname, nodename):\n \"\"\"Remove an attribute from a node in the dataset.\n\n :param str attrname: name of the attribute to remove\n :type attrname: str\n :param nodename: Name, Path or Index name of the node to modify\n :type nodename: str\n \"\"\"\n node = self.get_node(nodename, as_numpy=False)\n node._v_attrs.__delitem__(attrname)\n return\n\n def remove_attributes(self, attr_list, nodename):\n \"\"\"Remove an attribute from a node in the dataset.\n\n :param str attr_list: list of the names of the attribute to remove\n :type attr_list: list\n :param nodename: Name, Path or Index name of the node to modify\n :type nodename: str\n \"\"\"\n for attr in attr_list:\n self.remove_attribute(attr, nodename)\n return\n\n def rename_node(self, nodename, newname, replace=False,\n new_indexname=None):\n \"\"\"Rename a node in the HDF5 tree, XDMF file and content index.\n\n This method do not change the indexname of the node, if one exists.\n\n :param nodename: Name, Path or Index name of the node to modify\n :type nodename: str\n :param newname: New name to give to the HDF5 node\n :type newname: str\n :param replace: If `True`, overwrite a possibily existing node with\n name `newname` defaults to False\n :type replace: bool, optional\n \"\"\"\n self.sync()\n node = self.get_node(nodename)\n indexname = self.get_indexname_from_path(node._v_pathname)\n if new_indexname is not None:\n self.content_index.pop(indexname)\n indexname = new_indexname\n elif indexname == node._v_name:\n self.content_index.pop(indexname)\n indexname = newname\n # change nodename in XDMF file\n xdmf_lines = []\n with open(self.xdmf_path, 'r') as f:\n old_xdmf_lines = f.readlines()\n for line in old_xdmf_lines:\n xdmf_lines.append(line.replace(node._v_name, newname))\n with open(self.xdmf_path, 'w') as f:\n f.writelines(xdmf_lines)\n # change HDF5 node name\n self.h5_dataset.rename_node(node, newname, overwrite=replace)\n # change index\n self.content_index[indexname] = node._v_pathname\n self.xdmf_tree = etree.parse(self.xdmf_path)\n self.sync()\n return\n\n def remove_node(self, name, recursive=False):\n \"\"\"Remove a node from the dataset.\n\n :param str name: Name, Path, Index name or Alias of the node to remove\n :param bool recursive: if `True` and the node is a Group, removes all\n childrens of the node as well.\n\n .. important:: After node removal, the file size will not be changed.\n This is a standard behavior for HDF5 files, that preserves freed\n space in disk to add additional data in the future. If needed, use\n the :func:`repack_file` method to reduce file disk size after\n changing compression settings. This method is also called by the\n class instance destructor.\n \"\"\"\n node_path = self._name_or_node_to_path(name)\n if node_path is None:\n msg = ('(remove_node) Node name does not fit any hdf5 path'\n ' nor index name. Node removal aborted.')\n self._verbose_print(msg)\n return\n Node = self.get_node(node_path)\n isGroup = (Node._v_attrs.CLASS == 'GROUP')\n if (isGroup) and not recursive:\n msg = ('Node {} is a hdf5 group. Use `recursive=True` keyword'\n ' argument to remove it and its childrens.'\n ''.format(node_path))\n self._verbose_print(msg)\n return\n\n # Remove visualisation field if node is a IP field node with an\n # additionnal visualisation values array\n IP_vis = self.get_attribute('visualisation_field_path', Node)\n if IP_vis is not None:\n IP = self.get_node(IP_vis)\n self.remove_node(IP)\n\n # Remove array used for per component data normalization.\n mean_path = self.get_attribute('norm_mean_array_path', Node)\n if mean_path is not None:\n mean = self.get_node(mean_path)\n self.remove_node(mean)\n std_path = self.get_attribute('norm_std_array_path', Node)\n if std_path is not None:\n Std = self.get_node(std_path)\n self.remove_node(Std)\n\n # Remove HDF5 node and its childrens\n self._verbose_print('Removing node {} in content index....'\n ''.format(Node._v_pathname))\n if isGroup and recursive:\n for child, child_node in Node._v_children.items():\n self.remove_node(child_node, recursive=True)\n self._remove_from_index(node_path=Node._v_pathname)\n # remove node in xdmf tree\n self._remove_from_xdmf(Node)\n Node._f_remove(recursive=True)\n else:\n print('')\n self._remove_from_index(node_path=Node._v_pathname)\n # remove node in xdmf tree\n self._remove_from_xdmf(Node)\n Node.remove()\n # synchronize HDF5 and XDMF file with node removal\n self.sync()\n self._verbose_print('Node {} sucessfully removed'.format(name))\n return\n\n def repack_h5file(self):\n \"\"\"Overwrite hdf5 file with a copy of itself to recover disk space.\n\n Manipulation to recover space leaved empty when removing data from\n the HDF5 tree or reducing a node space by changing its compression\n settings. This method is called also by the class destructor if the\n autorepack flag is `True`.\n \"\"\"\n self.sync()\n head, tail = os.path.split(self.h5_path)\n tmp_file = os.path.join(head, 'tmp_'+tail)\n self.h5_dataset.copy_file(tmp_file)\n self.h5_dataset.close()\n shutil.move(tmp_file, self.h5_path)\n self.h5_dataset = tables.File(self.h5_path, mode='r+')\n self._file_exist = True\n self._after_file_open()\n return\n\n @staticmethod\n def copy_sample(src_sample_file, dst_sample_file, overwrite=False,\n get_object=False, new_sample_name=None, autodelete=False):\n \"\"\"Initiate a new SampleData object and files from existing dataset.\n\n :param src src_sample_file: name of the dataset file to copy.\n :param src dst_sample_file: name of the new dataset files.\n :param bool overwrite: set to `True` to overwrite an existing dataset\n file with name `dst_sample_file` when copying.\n :param bool get_object: if `True` returns the SampleData instance\n :param str new_sample_name: name of the sample in the new dataset\n :param bool autodelete: remove copied dataset files when copied\n instance is destroyed.\n \"\"\"\n sample = SampleData(filename=src_sample_file)\n if new_sample_name is None:\n new_sample_name = sample.get_attribute('sample_name', '/')\n # copy HDF5 file\n dst_sample_file_h5 = os.path.splitext(dst_sample_file)[0] + '.h5'\n dst_sample_file_xdmf = os.path.splitext(dst_sample_file)[0] + '.xdmf'\n sample.h5_dataset.copy_file(dst_sample_file_h5, overwrite=overwrite)\n # copy XDMF file\n dst_xdmf_lines = []\n with open(sample.xdmf_path, 'r') as f:\n src_xdmf_lines = f.readlines()\n _, new_file = os.path.split(dst_sample_file_h5)\n for line in src_xdmf_lines:\n dst_xdmf_lines.append(line.replace(sample.h5_file, new_file))\n with open(dst_sample_file_xdmf, 'w') as f:\n f.writelines(dst_xdmf_lines)\n del sample\n new_sample = SampleData(filename=dst_sample_file_h5,\n autodelete=autodelete)\n new_sample.set_sample_name(new_sample_name)\n if get_object:\n return new_sample\n else:\n del new_sample\n return\n\n def create_elset_ids_field(self, meshname=None, store=True, fieldname=None,\n get_sets_IDs=True, tags_prefix='elset',\n remove_elset_fields=False):\n \"\"\"Create an element tag Id field on the inputed mesh.\n\n Creates a element wise field from the provided mesh,\n adding to each element the value of the Elset it belongs to.\n\n .. warning::\n\n - CAUTION : the methods is designed to work with non intersecting\n element tags/sets. In this case, the produce field will indicate\n the value of the last elset containing it for each element.\n\n :param str mesh: Name, Path or index name of the mesh on which an\n orientation map element field must be constructed\n :param bool store: If `True`, store the field on the mesh\n :param bool get_sets_IDs: If `True`, get the sets ID numbers from their\n names by substracting the input prefix. If `False`, use the set\n position in the mesh elset list as ID number.\n :param str tags_prefix: Remove from element sets/tags names\n prefix to determine the set/tag ID. This supposes that sets\n names have the form prefix+ID\n :param bool remove_elset_fields: If `True`, removes the elset\n indicator fields after construction of the elset id field.\n (default is `False`)\n \"\"\"\n if meshname is None:\n raise ValueError('meshname do not refer to an existing mesh')\n if not(self._is_mesh(meshname)) or self._is_empty(meshname):\n raise ValueError('meshname do not refer to a non empty mesh'\n 'group')\n # create empty element vector field\n Nelements = int(self.get_attribute('Number_of_elements',meshname))\n mesh = self.get_node(meshname)\n El_tag_path = os.path.join(mesh._v_pathname,'Geometry','ElementsTags')\n ID_field = np.zeros((Nelements,1),dtype=float)\n elem_tags = self.get_mesh_elem_tags_names(meshname)\n # if mesh is provided\n i = 0\n for set_name, set_type in elem_tags.items():\n elset_path = os.path.join(El_tag_path, 'ET_'+set_name)\n element_ids = self.get_node(elset_path, as_numpy=True)\n if get_sets_IDs:\n set_ID = int(set_name.strip(tags_prefix))\n else:\n set_ID = i\n i += 1\n ID_field[element_ids] = set_ID\n if remove_elset_fields:\n field_path = os.path.join(El_tag_path, 'field_'+set_name)\n self.remove_node(field_path)\n if store:\n if fieldname is None:\n fieldname = meshname+'_elset_ids'\n c_opt = {'complib':'zlib', 'complevel':1, 'shuffle':True}\n self.add_field(gridname=meshname, fieldname=fieldname,\n array=ID_field, replace=True,\n compression_options=c_opt)\n return ID_field\n\n # =========================================================================\n # SampleData private methods\n # =========================================================================\n def _init_file_object(self, sample_name='', sample_description=''):\n \"\"\"Initiate or create PyTable HDF5 file object.\"\"\"\n try:\n self.h5_dataset = tables.File(self.h5_path, mode='r+')\n self._verbose_print('-- Opening file \"{}\" '.format(self.h5_file),\n line_break=False)\n self._file_exist = True\n self._init_xml_tree()\n self._init_data_model()\n self._verbose_print('**** FILE CONTENT ****')\n self._verbose_print(SampleData.__repr__(self))\n except IOError:\n self._file_exist = False\n self._verbose_print('-- File \"{}\" not found : file'\n ' created'.format(self.h5_file),\n line_break=True)\n self.h5_dataset = tables.File(self.h5_path, mode='a')\n self._init_xml_tree()\n # Generic Data Model initialization\n self._init_data_model()\n # add sample name and description\n self.set_sample_name(sample_name)\n self.set_description(sample_description)\n return\n\n def _init_data_model(self):\n \"\"\"Initialize the minimal data model specified for the class.\"\"\"\n content_paths, content_type = self.minimal_data_model()\n self.minimal_content = content_paths\n self._init_content_index()\n self._verbose_print('Minimal data model initialization....')\n # Determine maximum path level in data model elements\n max_path_level = 0\n for key, value in content_paths.items():\n max_path_level = max(value.count('/'), max_path_level)\n for level in range(max_path_level):\n self._verbose_print(f'Initializing level {level+1} of data model')\n for key, value in content_paths.items():\n if value.count('/') != level+1:\n continue\n head, tail = os.path.split(value)\n # Find out if object is a description object\n is_descr = self._is_table_descr(content_type[key])\n if self.h5_dataset.__contains__(content_paths[key]):\n if self._is_table(content_paths[key]):\n msg = ('Updating table {}'.format(content_paths[key]))\n self._verbose_print(msg)\n self._update_table_columns(\n tablename=content_paths[key],\n Description=content_type[key])\n if self._is_empty(content_paths[key]):\n self._verbose_print('Warning: node {} specified in the'\n ' minimal data model for this class'\n ' is empty'\n ''.format(content_paths[key]))\n continue\n elif is_descr:\n msg = ('Adding empty Table {}'.format(content_paths[key]))\n self.add_table(location=head, name=tail, indexname=key,\n description=content_type[key])\n elif content_type[key] == 'Group':\n msg = f'Adding empty Group {content_paths[key]}'\n self.add_group(groupname=tail, location=head,\n indexname=key, replace=False)\n elif content_type[key] in SD_IMAGE_GROUPS.values():\n msg = f'Adding empty Image Group {content_paths[key]}'\n self.add_image(imagename=tail, indexname=key, location=head)\n elif content_type[key] in SD_MESH_GROUPS.values():\n msg = f'Adding empty Mesh Group {content_paths[key]}'\n self.add_mesh(meshname=tail, indexname=key, location=head)\n elif content_type[key] == 'data_array':\n msg = f'Adding empty data array {content_paths[key]}'\n self.add_data_array(location=head, name=tail,\n indexname=key)\n elif content_type[key] == 'field_array':\n msg = (f'Adding empty field {content_paths[key]} to'\n f' mesh group {head}')\n self.add_field(gridname=head, fieldname=tail,\n indexname=key)\n elif content_type[key] == 'string_array':\n msg = f'Adding empty string array {content_paths[key]}'\n self.add_string_array(name=tail, location=head,\n indexname=key)\n self._verbose_print('Minimal data model initialization done\\n')\n return\n\n def _init_xml_tree(self):\n \"\"\"Read xml tree structured in .xdmf file or initiate one.\"\"\"\n try:\n file_parser = etree.XMLParser(remove_blank_text=True)\n with open(self.xdmf_path, 'rb') as source:\n self.xdmf_tree = etree.parse(source, parser=file_parser)\n except OSError:\n # Non existent xdmf file.\n # A new .xdmf is created with the base node Xdmf and one Domain\n self._verbose_print('-- File \"{}\" not found : file'\n ' created'.format(self.xdmf_file),\n line_break=False)\n # create root element of xdmf tree structure\n E = lxml.builder.ElementMaker(\n namespace=\"http://www.w3.org/2003/XInclude\",\n nsmap={'xi': \"http://www.w3.org/2003/XInclude\"})\n root = E.root()\n root.tag = 'Xdmf'\n root.set(\"Version\", \"2.2\")\n self.xdmf_tree = etree.ElementTree(root)\n\n # create element Domain as a children of root\n self.xdmf_tree.getroot().append(etree.Element(\"Domain\"))\n\n # write file\n self.write_xdmf()\n return\n\n def _init_content_index(self):\n \"\"\"Initialize content_index dictionary.\"\"\"\n self.content_index = {}\n self.aliases = {}\n if self._file_exist:\n self.content_index = self.get_dic_from_attributes(\n nodename='/Index')\n self.aliases = self.get_dic_from_attributes(\n nodename='/Index/Aliases')\n else:\n self.h5_dataset.create_group('/', name='Index')\n self.h5_dataset.create_group('/Index', name='Aliases')\n return\n\n def _check_SD_array_init(self, arrayname='', location='/', replace=False,\n empty_input=False):\n \"\"\"Safety check to create data array into location in dataset.\"\"\"\n location_path = self._name_or_node_to_path(location)\n if location_path is None:\n msg = ('No location `{}`, cannot create array/table {}.'\n ' Create parent groups before adding the array/table.'\n ''.format(arrayname, location))\n raise tables.NodeError(msg)\n else:\n # check location nature\n if not(self._get_node_class(location) == 'GROUP'):\n msg = ('Location {} is not a HDF5 Group. Cannot create array/'\n 'table there.'.format(location))\n raise tables.NodeError(msg)\n # check if array location exists and remove node if asked\n array_path = os.path.join(location_path, arrayname)\n if self.__contains__(array_path):\n empty = self.get_attribute('empty', array_path)\n if empty and (not empty_input):\n # special case where we add data to a pre-existing\n # node --> need to save the attributes and remove the\n # empty array node\n msg = ('Existing node {} will be overwritten to recreate '\n 'array/table'.format(array_path))\n if not(empty):\n self._verbose_print(msg)\n attrs = self.get_dic_from_attributes(array_path)\n self.remove_node(array_path, recursive=True)\n return attrs\n if replace:\n msg = ('Existing node {} will be overwritten to recreate '\n 'array/table'.format(array_path))\n if not(empty):\n self._verbose_print(msg)\n self.remove_node(array_path, recursive=True)\n else:\n msg = ('Array/table {} already exists. To overwrite, use '\n 'optional argument \"replace=True\"'\n ''.format(array_path))\n raise tables.NodeError(msg)\n return dict()\n\n def _init_SD_group(self, groupname='', location='/',\n group_type='Group', replace=False):\n \"\"\"Create or fetch a SampleData Group and returns it.\"\"\"\n Group = None\n # init flags\n fetch_group = False\n # sanity checks\n if groupname == '':\n raise ValueError('Cannot create Group. Groupname must be'\n ' specified')\n if group_type not in SD_GROUP_TYPES:\n raise ValueError('{} is not a valid group type. Use on of {}'\n ''.format(group_type,SD_GROUP_TYPES))\n location = self._name_or_node_to_path(location)\n group_path = os.path.join(location, groupname)\n # check existence and emptiness\n if self.__contains__(group_path):\n if self._is_grid(group_path):\n if self._is_empty(group_path):\n fetch_group = True\n if not(fetch_group) and replace:\n self._verbose_print('Removing group {} to replace it by new'\n ' one.'.format(groupname))\n self.remove_node(name=group_path,recursive=True)\n if not(fetch_group or replace):\n msg = ('Group {} already exists. Set arg. `replace=True` to'\n ' replace it by a new Group.'.format(groupname))\n raise tables.NodeError(msg)\n # create or fetch group\n if fetch_group:\n Group = self.get_node(group_path)\n self._remove_from_index(Group._v_pathname)\n else:\n self._verbose_print('Creating {} group `{}` in file {} at {}'\n ''.format(group_type, groupname,\n self.h5_file,location))\n Group = self.h5_dataset.create_group(where=location,\n name=groupname,\n title=groupname,\n createparents=True)\n self.add_attributes(dic={'group_type': group_type}, nodename=Group)\n return Group\n\n @staticmethod\n def _merge_dtypes(dtype1, dtype2):\n \"\"\"Merge 2 numpy.void dtypes to creates a new one.\"\"\"\n descr = []\n for item in dtype1.descr:\n if not(item in descr) and not(item[0]==''):\n descr.append(item)\n for item in dtype2.descr:\n if not(item in descr) and not(item[0]==''):\n descr.append(item)\n return np.dtype(descr)\n\n def _update_table_columns(self, tablename, Description):\n \"\"\"Extends table with new fields in input Description.\"\"\"\n table = self.get_node(tablename)\n current_desc = table.description\n current_dtype = tables.dtype_from_descr(table.description)\n if isinstance(Description, np.dtype):\n desc_dtype = Description\n else:\n desc_dtype = tables.dtype_from_descr(Description)\n new_dtype = SampleData._merge_dtypes(current_dtype, desc_dtype)\n new_descr = tables.descr_from_dtype(new_dtype)[0]\n if current_dtype == new_dtype:\n self._verbose_print('Nothing to update for table `{}`'\n ''.format(tablename))\n return\n self._verbose_print('Updating `{}` with fields {}'\n ''.format(tablename, desc_dtype.fields))\n self._verbose_print('New table description is `{}`'\n ''.format(new_dtype.fields))\n Nrows = table.nrows\n tab_name = table._v_name\n tab_indexname = self.get_indexname_from_path(table._v_pathname)\n tab_path = os.path.dirname(table._v_pathname)\n tab_chunkshape = table.chunkshape\n tab_filters = table.filters\n tab_c_opts = self._get_compression_opt_from_filter(tab_filters)\n # Create a new array with modified dtype\n data = np.array(np.zeros((Nrows,)), dtype=new_dtype)\n self._verbose_print(f'data is: {data}')\n # Get data from old table\n for key in current_desc._v_names:\n data[key] = self.get_tablecol(tablename=tablename,\n colname=key)\n # get table aliases\n if self.aliases.__contains__(tab_indexname):\n tab_aliases = self.aliases[tab_indexname]\n else:\n tab_aliases = []\n # remove old table\n tab_attrs = self.get_dic_from_attributes(tab_indexname)\n self.remove_node(tab_name)\n # create new table\n new_tab = self.add_table(location=tab_path, name=tab_name,\n description=new_descr,\n indexname=tab_indexname,\n chunkshape=tab_chunkshape, replace=True,\n data=data, compression_options=tab_c_opts)\n for alias in tab_aliases:\n self.add_alias(aliasname=alias, indexname=new_tab._v_pathname)\n self.add_attributes(tab_attrs, tab_indexname)\n return\n\n def _remove_from_index(self, node_path):\n \"\"\"Remove a hdf5 node from content index dictionary.\"\"\"\n try:\n key = self.get_indexname_from_path(node_path)\n removed_path = self.content_index.pop(key)\n if key in self.aliases:\n self.aliases.pop(key)\n self._verbose_print('item {} : {} removed from context index'\n ' dictionary'.format(key, removed_path))\n except:\n self._verbose_print('node {} not found in content index values for'\n 'removal'.format(node_path))\n return\n\n def _remove_from_xdmf(self, nodename):\n \"\"\"Remove a Grid or Attribute Node from the xdmf tree.\"\"\"\n if self._is_grid(nodename):\n xdmf_grid = self._find_xdmf_grid(nodename)\n p = xdmf_grid.getparent()\n p.remove(xdmf_grid)\n elif self._is_field(nodename):\n xdmf_field, xdmf_grid = self._find_xdmf_field(nodename)\n xdmf_grid.remove(xdmf_field)\n return\n\n def _find_xdmf_grid(self, gridname):\n name = self.get_attribute('xdmf_gridname', gridname)\n if name is None:\n # in case we are looking for a temporal grid collection subgrid,\n # its name will be directly passed as argument to this method\n # but no node in the dataset will have this name.\n name = gridname\n for el in self.xdmf_tree.iterfind('.//Grid'):\n if el.get('Name') == name:\n return el\n return None\n\n def _get_xdmf_time_grid_name(self, gridname, time):\n name = self.get_attribute('xdmf_gridname', gridname)\n for el in self.xdmf_tree.iterfind('.//Grid'):\n if el.get('Name') == name:\n grid0 = el\n for ch_grid in grid0.iterchildren():\n for ch in ch_grid.iterchildren():\n if ch.tag == 'Time':\n if float(ch.get('Value')) == time:\n return ch_grid.get('Name')\n\n def _find_xdmf_geometry(self, xdmf_grid):\n for el in xdmf_grid:\n if el.tag == 'Geometry':\n return el\n return None\n\n def _find_xdmf_topologyy(self, gridname):\n xdmf_grid = self._find_xdmf_grid(gridname)\n for el in xdmf_grid:\n if el.tag == 'Topology':\n return el\n return None\n\n def _find_xdmf_field(self, fieldnodename):\n gridname = self.get_attribute('xdmf_gridname', fieldnodename)\n fieldname = self.get_attribute('xdmf_fieldname', fieldnodename)\n xdmf_grid = self._find_xdmf_grid(gridname)\n for el in xdmf_grid:\n if el.tag == 'Grid':\n for eel in el:\n if eel.get('Name') == fieldname:\n return eel, el\n else:\n if el.get('Name') == fieldname:\n return el, xdmf_grid\n return None\n\n def _name_or_node_to_path(self, name_or_node):\n \"\"\"Return path of `name` in content_index dic or HDF5 tree.\"\"\"\n path = None\n # name_or_node is a Node\n if isinstance(name_or_node, tables.Node):\n return name_or_node._v_pathname\n # name or node is none\n if name_or_node is None:\n return None\n # name_or_node is a string or else\n name_tmp = os.path.join('/', name_or_node)\n if self.h5_dataset.__contains__(name_tmp):\n # name is a path in hdf5 tree data\n path = name_tmp\n if name_or_node in self.content_index:\n # name is a key in content index\n path = self._get_path_with_indexname(name_or_node)\n if self._is_alias(name_or_node):\n # name is a an alias for a node path in content_index\n temp_name = self._is_alias_for(name_or_node)\n path = self._get_path_with_indexname(temp_name)\n # if not found with indexname or is not a path\n # find nodes or table column with this name.\n # If several nodes have this name return warn message and return None\n if path is None:\n count = 0\n path_list = []\n for node in self.h5_dataset:\n if (name_or_node == node._v_name):\n count = count + 1\n path_list.append(node._v_pathname)\n if node._v_attrs.CLASS == 'TABLE':\n if name_or_node in node.colnames:\n count = count + 1\n path_list.append(node._v_pathname)\n if count == 1:\n path = path_list[0]\n elif count > 1:\n msg = ('(_name_or_node_to_path) : more than 1 node ({}) with '\n 'name {} have been found :\\n {} \\n Use indexname to '\n 'distinguish nodes.'.format(count, name_or_node,\n path_list))\n self._verbose_print(msg)\n path = None\n return path\n\n def _is_empty(self, name):\n \"\"\"Find out if name or path references an empty node.\"\"\"\n if not self.__contains__(name):\n return True\n if self._is_table(name):\n tab = self.get_node(name)\n return tab.nrows <= 0\n else:\n return self.get_attribute('empty', name)\n\n def _is_image(self, name):\n \"\"\"Find out if name or path references an image groupe.\"\"\"\n return self._get_group_type(name) in SD_IMAGE_GROUPS.values()\n\n def _is_mesh(self, name):\n \"\"\"Find out if name or path references an image groupe.\"\"\"\n return self._get_group_type(name) in SD_MESH_GROUPS.values()\n\n def _is_array(self, name):\n \"\"\"Find out if name or path references an array dataset.\"\"\"\n name2 = self._name_or_node_to_path(name)\n Class = self._get_node_class(name2)\n List = ['CARRAY', 'EARRAY', 'VLARRAY', 'ARRAY', 'TABLE']\n return Class in List\n\n def _is_table(self, name):\n \"\"\"Find out if name or path references an array dataset.\"\"\"\n return self._get_node_class(name) == 'TABLE'\n\n def _is_table_descr(self, obj):\n \"\"\"Find out if name or path references an array dataset.\"\"\"\n is_descr=False\n try:\n is_descr = issubclass(obj, tables.IsDescription)\n except TypeError:\n is_descr=False\n if is_descr:\n return is_descr\n try:\n is_descr = (isinstance(obj, tables.IsDescription)\n or isinstance(obj, np.dtype))\n except TypeError:\n is_descr=False\n return is_descr\n\n def _is_group(self, name):\n \"\"\"Find out if name or path references a HDF5 Group.\"\"\"\n return self._get_node_class(name) == 'GROUP'\n\n def _is_grid(self, name):\n \"\"\"Find out if name or path references a image or mesh HDF5 Group.\"\"\"\n return self._get_group_type(name) in SD_GRID_GROUPS\n\n def _is_children_of(self, node, parent_group):\n \"\"\"Find out if location is a subgroup of the grid.\"\"\"\n if not self.__contains__(node):\n return False\n if not self.__contains__(parent_group):\n return False\n node_path = self._name_or_node_to_path(node)\n bool_return = False\n group = self.get_node(parent_group)\n for n in group._f_iter_nodes():\n if n._v_pathname == node_path:\n bool_return = True\n break\n else:\n if self._is_group(n._v_pathname):\n bool_return = self._is_children_of(node, n._v_pathname)\n if bool_return:\n break\n return bool_return\n\n\n def _is_field(self, fieldname):\n \"\"\"Checks conditions to consider node `name` as a field data node.\"\"\"\n test = self.get_attribute('field_type', fieldname)\n return (test is not None)\n\n def _is_in_index(self, name):\n return (name in self.content_index)\n\n def _is_alias(self, name):\n \"\"\"Check if name is an HDF5 node alias.\"\"\"\n Is_alias = False\n for item in self.aliases:\n if (name in self.aliases[item]):\n Is_alias = True\n break\n return Is_alias\n\n def _is_alias_for(self, name):\n \"\"\"Return the indexname for which input name is an alias.\"\"\"\n Indexname = None\n for item in self.aliases:\n if (name in self.aliases[item]):\n Indexname = item\n break\n return Indexname\n\n def _check_image_object_support(self, image_object):\n \"\"\"Return `True` if image_object type is supported by the class.\"\"\"\n if not(isinstance(image_object, ConstantRectilinearMesh)):\n raise ValueError('WARNING : unknown image object. Supported objects'\n ' are BasicTools ConstantRectilinearMesh'\n ' instances.')\n\n def _check_mesh_object_support(self, mesh_object):\n \"\"\"Return `True` if image_object type is supported by the class.\"\"\"\n if not(isinstance(mesh_object, MeshBase)):\n raise ValueError('WARNING : unknown mesh object. Supported objects'\n ' are BasicTools ConstantRectilinearMesh'\n ' instances.')\n\n def _check_field_compatibility(self, gridname, field_shape):\n \"\"\"Check if field dimension is compatible with the storing location.\"\"\"\n group_type = self._get_group_type(gridname)\n if self._is_empty(gridname):\n # method create_image from array\n raise ValueError('{} is an empty grid. Use add_image, add_mesh,'\n ' or add_image_from_field to initialize grid'\n ''.format(gridname))\n elif group_type in SD_IMAGE_GROUPS.values():\n field_type, dimensionality = self._compatibility_with_image(\n gridname, field_shape)\n elif group_type in SD_MESH_GROUPS.values():\n field_type, dimensionality = self._compatibility_with_mesh(\n gridname, field_shape)\n else:\n raise tables.NodeError('location {} is not a grid.'\n ''.format(gridname))\n return field_type, dimensionality\n\n def _compatibility_with_mesh(self, meshname, field_shape):\n \"\"\"Check if field has a number of values compatible with the mesh.\"\"\"\n # Safety check: field must be a vector or a (Nvalues,Dim) array\n if len(field_shape) > 2:\n raise ValueError('Forbidden field shape. The field array must be'\n ' of shape (Nvalues) or (Nvalues,Ndim). Received'\n ' {}'.format(field_shape))\n node_field = False\n elem_field = False\n Nnodes = self.get_attribute('number_of_nodes', meshname)\n Nelem = np.sum(self.get_attribute('Number_of_elements', meshname))\n Nelem_bulk = np.sum(self.get_attribute('Number_of_bulk_elements',\n meshname))\n Nfield_values = field_shape[0]\n if len(field_shape) == 2:\n Field_dim = field_shape[1]\n else:\n Field_dim = 1\n if Nfield_values == Nnodes:\n node_field = True\n field_type='Nodal_field'\n elif Nfield_values == Nelem:\n elem_field = True\n field_type='Element_field'\n elif (Nfield_values % Nelem_bulk) == 0:\n elem_field = True\n field_type = 'IP_field'\n compatibility = node_field or elem_field\n if not(compatibility):\n raise ValueError('Field number of values ({}) is not conformant'\n ' with mesh number of nodes ({}) or number of'\n ' elements ({}).'\n ''.format(Nfield_values, Nnodes, Nelem))\n if Field_dim not in XDMF_FIELD_TYPE:\n raise ValueError('Field dimensionnality `{}` is not know. '\n 'Supported dimensionnalities are Scalar (1),'\n 'Vector (3), Tensor6 (6), Tensor (9).'\n 'Maybe are you trying to add a 3D field into a'\n '3D grid.')\n return field_type, XDMF_FIELD_TYPE[Field_dim]\n\n def _compatibility_with_image(self, imagename, field_shape):\n \"\"\"Check if field has a number of values compatible with the image.\n\n Returns the type of field values (nodal or element field), and the\n dimensonality of the field in the XDMF convention (Scalar, Vector,\n Tensor6 or Tensor)\n \"\"\"\n node_field = True\n elem_field = True\n image_node_dim = self.get_attribute('nodes_dimension', imagename)\n image_cell_dim = self.get_attribute('dimension', imagename)\n # Should never be equal but sanity check\n if np.all(image_node_dim == image_cell_dim):\n raise ValueError('Image group {} has identical node and cell'\n ' dimensions. Please correct your image Group'\n ' attributes.')\n for i in range(len(image_cell_dim)):\n if np.any(image_node_dim[i] != field_shape[i]):\n node_field = False\n if np.any(image_cell_dim[i] != field_shape[i]):\n elem_field = False\n if node_field:\n field_type='Nodal_field'\n elif elem_field:\n field_type='Element_field'\n compatibility = node_field or elem_field\n if not compatibility:\n raise ValueError('Field number of values ({}) is not conformant'\n ' with image `{}` dimensions'\n ''.format(field_shape, imagename))\n else:\n if len(field_shape) == len(image_node_dim):\n dimension = 1\n else:\n dimension = field_shape[-1]\n if dimension not in XDMF_FIELD_TYPE:\n raise ValueError('Field dimensionnality `{}` is not know. '\n 'Supported dimensionnalities are Scalar (1),'\n 'Vector (3), Tensor6 (6), Tensor (9).'\n 'Maybe are you trying to add a 3D field into a'\n '3D grid.')\n return field_type, XDMF_FIELD_TYPE[dimension]\n\n def _mesh_field_padding(self, field, meshname, bulk_padding):\n \"\"\"Pad with zeros the mesh elem field to comply with size.\"\"\"\n if self._is_image(meshname):\n return field, 'None', None\n Nelem_bulk = np.sum(self.get_attribute('Number_of_bulk_elements',\n meshname))\n Nelem_boundary = np.sum(self.get_attribute(\n 'Number_of_boundary_elements', meshname))\n if Nelem_bulk == Nelem_boundary:\n force_padding = True\n else:\n force_padding = False\n padding = 'None'\n vis_field = None\n # reshape field if it is a 1D array\n if len(field.shape) == 1:\n field = field.reshape((len(field),1))\n if field.shape[0] == Nelem_bulk:\n padding = 'bulk'\n if force_padding:\n if not bulk_padding:\n padding = 'boundary'\n elif field.shape[0] == Nelem_boundary:\n padding = 'boundary'\n elif (field.shape[0] % Nelem_bulk) == 0:\n # if the number of values for the field is a multiplier of the\n # number of elements, it is considered that the array describes a\n # field integration point values and that it is stored as follows:\n # field[:,k] = [Val_elt1_IP1, Val_elt1_IP2, ...., Val_elt1_IPN,\n # Val_elt2_IP1, ...., Val_eltN_IPN]\n padding = 'bulk_IP'\n if force_padding:\n if not bulk_padding:\n padding = 'boundary_IP'\n elif Nelem_boundary != 0:\n if (field.shape[0] % Nelem_boundary) == 0:\n padding = 'boundary_IP'\n if padding == 'None':\n pass\n elif padding == 'bulk':\n Nelem_boundary = np.sum(self.get_attribute(\n 'Number_of_boundary_elements',meshname))\n pad_array = np.zeros(shape=(Nelem_boundary, field.shape[1]))\n field = np.concatenate((field, pad_array), axis=0)\n elif padding == 'boundary':\n Nelem_bulk = np.sum(self.get_attribute(\n 'Number_of_bulk_elements',meshname))\n pad_array = np.zeros(shape=(Nelem_bulk, field.shape[1]))\n field = np.concatenate((pad_array, field), axis=0)\n elif padding == 'bulk_IP':\n Nip_elt = field.shape[0] // Nelem_bulk\n new_shape = (Nelem_bulk,Nip_elt,*field.shape[1:])\n vis_field = field.reshape(new_shape)\n Nelem_boundary = np.sum(self.get_attribute(\n 'Number_of_boundary_elements',meshname))\n pad_array = np.zeros(shape=(Nelem_boundary, *vis_field.shape[1:]))\n vis_field = np.concatenate((vis_field, pad_array), axis=0)\n elif padding == 'boundary_IP':\n Nip_elt = field.shape[0] // Nelem_boundary\n new_shape = (Nelem_boundary,Nip_elt,*field.shape[1:])\n vis_field = field.reshape(new_shape)\n Nelem_bulk = np.sum(self.get_attribute(\n 'Number_of_bulk_elements',meshname))\n pad_array = np.zeros(shape=(Nelem_bulk, *vis_field.shape[1:]))\n vis_field = np.concatenate((pad_array, vis_field), axis=0)\n return field, padding, vis_field\n\n def _mesh_field_unpadding(self, field, parent_mesh, padding):\n \"\"\"Remove zeros to return field to original shape, before padding.\"\"\"\n Nelem_bulk = np.sum(self.get_attribute('Number_of_bulk_elements',\n parent_mesh))\n Nelem_boundary = np.sum(self.get_attribute(\n 'Number_of_boundary_elements', parent_mesh))\n if len(field.shape) == 1:\n L = field.shape[0]\n field = field.reshape((L,1))\n if (padding == 'bulk') or (padding == 'bulk_IP'):\n field = field[:Nelem_bulk,:]\n elif (padding == 'boundary') or (padding == 'boundary_IP'):\n field = field[Nelem_boundary,:]\n elif padding == 'None':\n pass\n else:\n raise Warning('Cannot unpad the field, unknown padding type `{}`'\n ''.format(padding))\n return np.atleast_1d(field)\n\n def _IP_field_for_visualisation(self, array, vis_type):\n # here it is supposed that the field has shape\n # [Nelem, Nip_per_elem, Ncomponent]\n if vis_type == 'Elt_max':\n array = np.max(array, axis=1)\n elif vis_type == 'Elt_mean':\n array = np.mean(array, axis=1)\n else:\n raise ValueError('Unkown integration point field visualisation'\n ' convention. Possibilities are \"Elt_max\",'\n ' \"Elt_mean\", \"None\"')\n return array\n\n def _add_mesh_geometry(self, mesh_object, mesh_group, replace,\n bin_fields_from_sets):\n \"\"\"Add Geometry data items of a mesh object to mesh group/xdmf.\"\"\"\n self._verbose_print('Adding Geometry for mesh group {}'\n ''.format(mesh_group._v_name))\n mesh_object.PrepareForOutput()\n # Get mesh group indexname\n indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n # create Geometry group\n geo_group = self.add_group(groupname='Geometry',\n location=mesh_group._v_pathname,\n indexname=indexname+'_Geometry',\n replace=replace)\n # Add Nodes, NodesID and NodeTags\n self._add_mesh_nodes(mesh_object, mesh_group, geo_group, replace)\n # Add Elements, ElementsID and ElementTags\n self._add_mesh_elements(mesh_object, mesh_group, geo_group, replace)\n\n def _add_mesh_nodes(self, mesh_object, mesh_group, geo_group, replace):\n \"\"\"Add Nodes, NodesID and NodeTags arrays in mesh geometry group.\"\"\"\n # Add Nodes coordinates\n self._verbose_print('Creating Nodes data set in group {} in file {}'\n ''.format(geo_group._v_pathname, self.h5_file))\n nodes_array = mesh_object.GetPosOfNodes()\n # Get mesh group indexname\n indexname_tmp = self.get_indexname_from_path(mesh_group._v_pathname)\n indexname = indexname_tmp+'_Nodes'\n Nodes = self.add_data_array(location=geo_group._v_pathname,\n name='Nodes', array=nodes_array,\n indexname=indexname)\n Node_attributes = {'number_of_nodes': mesh_object.nodes.shape[0],\n 'group_type': self._get_mesh_type(mesh_object),\n 'nodes_path':Nodes._v_pathname}\n self.add_attributes(Node_attributes, mesh_group._v_pathname)\n if isinstance(mesh_object, UnstructuredMesh):\n self._verbose_print('Creating Nodes ID data set in group {}'\n ' in file {}'\n ''.format(geo_group._v_pathname, self.h5_file))\n Nodes_ID = self.add_data_array(\n location=geo_group._v_pathname, name='Nodes_ID',\n array=mesh_object.originalIDNodes,\n indexname=indexname_tmp+'_Nodes_ID')\n Node_attributes = {'nodesID_path':Nodes_ID._v_pathname}\n self.add_attributes(Node_attributes, mesh_group._v_pathname)\n return\n\n def _add_mesh_elements(self, mesh_object, mesh_group, geo_group, replace):\n \"\"\"Add Elements, ElementsID and ElementsTags in mesh geometry group.\"\"\"\n # Determine Topology type\n if len(mesh_object.elements) > 1:\n topology_attributes = self._from_BT_mixed_topology(mesh_object)\n else:\n topology_attributes = self._from_BT_uniform_topology(mesh_object)\n # Add elements array\n self._add_topology(topology_attributes, mesh_object,mesh_group,\n geo_group, replace)\n self.add_attributes(topology_attributes, mesh_group._v_pathname)\n return\n\n def _add_nodes_elements_tags(self, mesh_object, mesh_group, replace,\n bin_fields_from_sets):\n \"\"\"Add Node and ElemTags in mesh geometry group from mesh object.\"\"\"\n indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n geo_group = self.get_node(indexname+'_Geometry')\n # Add node tags\n self._add_mesh_nodes_tags(mesh_object, mesh_group, geo_group, replace,\n bin_fields_from_sets)\n # Add element tags\n self._add_mesh_elems_tags(mesh_object, mesh_group, geo_group, replace,\n bin_fields_from_sets)\n return\n\n def _add_mesh_nodes_tags(self, mesh_object, mesh_group, geo_group,\n replace, bin_fields_from_sets):\n \"\"\"Add NodeTags arrays in mesh geometry group from mesh object.\"\"\"\n # create Noe tags group\n indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n Ntags_group = self.add_group(groupname='NodeTags',\n location=geo_group._v_pathname,\n indexname=indexname+'_NodeTags',\n replace=replace)\n Node_tags_list = []\n for tag in mesh_object.nodesTags:\n # Add the node list of the tag in a data array\n name = tag.name\n node_list = mesh_object.nodesTags[tag.name].GetIds()\n if len(node_list) == 0:\n continue\n Node_tags_list.append(name)\n node = self.add_data_array(location=Ntags_group._v_pathname,\n name='NT_'+name, array=node_list,\n replace=replace)\n # remove from index : Nodesets may be too numerous and overload\n # content index --> actual choice is to remove them from index\n self._remove_from_index(node._v_pathname)\n if bin_fields_from_sets:\n # Add node tags as fields in the dataset and XDMF file\n data = np.zeros((mesh_object.GetNumberOfNodes(),1),\n dtype=np.int8)\n data[node_list] = 1;\n c_opt = {'complib':'zlib', 'complevel':1, 'shuffle':True}\n node = self.add_field(mesh_group._v_pathname,\n fieldname='field_'+name,\n array=data, replace=replace,\n location=Ntags_group._v_pathname,\n compression_options=c_opt)\n # remove from index : Elsets may be too numerous and\n # overload content index --> actual choice is to remove\n # them from index\n self._remove_from_index(node._v_pathname)\n self.add_string_array(\n name='Node_tags_list', location=geo_group._v_pathname,\n indexname=indexname+'_NodeTagsList', data=Node_tags_list)\n return\n\n def _add_mesh_elems_tags(self, mesh_object, mesh_group, geo_group,\n replace, bin_fields_from_sets):\n \"\"\"Add ElementsTags arrays in mesh geometry group from mesh object.\"\"\"\n # create an dictionnary for the offset to apply to elem local Ids\n # for each element type\n element_type = self.get_attribute('element_type', mesh_group._v_name)\n offsets = self.get_attribute('Elements_offset', mesh_group._v_name)\n offset_dic = {element_type[i]:offsets[i] for i in range(len(offsets))}\n # create Noe tags group\n indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n Etags_group = self.add_group(groupname='ElementsTags',\n location=geo_group._v_pathname,\n indexname=indexname+'_ElemTags',\n replace=replace)\n Elem_tags_list = []\n Elem_tag_type_list = []\n for elem_type in mesh_object.elements:\n element_container = mesh_object.elements[elem_type]\n for tagname in element_container.tags.keys():\n name = tagname\n Elem_tags_list.append(name)\n Elem_tag_type_list.append(elem_type)\n elem_list = element_container.tags[tagname].GetIds()\n elem_list = elem_list + offset_dic[elem_type]\n if len(elem_list) == 0:\n continue\n node = self.add_data_array(location=Etags_group._v_pathname,\n name='ET_'+name, array=elem_list,\n replace=replace)\n # remove from index : Elsets may be too numerous and overload\n # content index --> actual choice is to remove them from index\n self._remove_from_index(node._v_pathname)\n if bin_fields_from_sets:\n # Add elem tags as fields in the dataset and XDMF file\n elem_list_field = mesh_object.GetElementsInTag(tagname)\n data = np.zeros((mesh_object.GetNumberOfElements(),1),\n dtype=np.int8)\n data[elem_list_field] = 1;\n c_opt = {'complib':'zlib', 'complevel':1, 'shuffle':True}\n node = self.add_field(mesh_group._v_pathname,\n fieldname='field_'+name,\n array=data, replace=replace,\n location=Etags_group._v_pathname,\n compression_options=c_opt)\n # remove from index : Elsets may be too numerous and\n # overload content index --> actual choice is to remove\n # them from index\n self._remove_from_index(node._v_pathname)\n self.add_string_array(\n name='Elem_tags_list', location=geo_group._v_pathname,\n indexname=indexname+'_ElTagsList', data=Elem_tags_list)\n self.add_string_array(\n name='Elem_tag_type_list', location=geo_group._v_pathname,\n indexname=indexname+'_ElTagsTypeList',\n data=Elem_tag_type_list)\n\n def _add_xdmf_node_element_set(self, subset_list_path, set_type='Cell',\n setname='', grid_name='',\n attributename=None):\n \"\"\"Adds an xdmf set with an optional attribute to the xdmf file.\n\n For now, only Node and Cell Sets supporting scalar attributes\n are handled.\n \"\"\"\n subset_list = self.get_node(subset_list_path)\n Xdmf_grid_node = self._find_xdmf_grid(grid_name)\n # Create xdmf Set node\n Set_xdmf = etree.Element(_tag='Set', Name=setname,\n SetType=set_type)\n # create Set Node/Cells subset\n Dimension = self._np_to_xdmf_str(subset_list.shape)\n NumberType = 'Int'\n Precision = str(subset_list.dtype).strip('int')\n Set_subset = etree.Element(_tag='DataItem', Format='HDF',\n Dimensions=Dimension,\n NumberType=NumberType,\n Precision=Precision)\n Set_subset.text = (self.h5_file + ':'\n + self._name_or_node_to_path(subset_list_path))\n # add Subset Data Item to Set node\n Set_xdmf.append(Set_subset)\n # Create Attribute element if required\n if attributename is not None:\n Attribute_xdmf = etree.Element(_tag='Attribute',\n Name=attributename,\n AttributeType='Scalar',\n Center=set_type)\n # create data item element\n data = np.ones(subset_list.shape, dtype='int8')\n Dimension = self._np_to_xdmf_str(data.shape)\n NumberType = 'Int'\n Precision = str(data.dtype).strip('int')\n Attribute_data = etree.Element(_tag='DataItem', Format='XML',\n Dimensions=Dimension,\n NumberType=NumberType,\n Precision=Precision)\n Attribute_data.text = self._np_to_xdmf_str(data)\n # add data item to attribute\n Attribute_xdmf.append(Attribute_data)\n # add attribute to Set\n Set_xdmf.append(Attribute_xdmf)\n # add Set node to Grid node\n Xdmf_grid_node.append(Set_xdmf)\n return\n\n def _load_nodes_tags(self, meshname, mesh_object, as_numpy=True):\n \"\"\"Add Node and ElemTags in mesh object from mesh geometry.\"\"\"\n mesh_group = self.get_node(meshname)\n indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n Ntags_group = self.get_node(indexname+'_NodeTags')\n if Ntags_group is not None:\n Ntag_list_indexname = indexname+'_NodeTagsList'\n Ntag_list = self.get_node(Ntag_list_indexname)\n for name in Ntag_list:\n tag_name = name.decode('utf-8')\n tag = mesh_object.GetNodalTag(tag_name)\n tag_path = os.path.join(Ntags_group._v_pathname,'NT_'+tag_name)\n tag.SetIds(self.get_node(tag_path, as_numpy))\n return mesh_object\n\n def _load_elements_tags(self, meshname, AllElements, as_numpy=True):\n \"\"\"Add Node and ElemTags in mesh object from mesh group.\"\"\"\n # get SD groups\n mesh_group = self.get_node(meshname)\n indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n Etags_group = self.get_node(indexname+'_ElemTags')\n # create an dictionnary for the offset to apply to elem local Ids\n # for each element type\n element_type = self.get_attribute('element_type', mesh_group._v_name)\n offsets = self.get_attribute('Elements_offset', mesh_group._v_name)\n offset_dic = {element_type[i]:offsets[i] for i in range(len(offsets))}\n # load element tags\n if Etags_group is not None:\n mesh_idname = self.get_indexname_from_path(mesh_group._v_pathname)\n Etag_list_indexname = mesh_idname+'_ElTagsList'\n Etag_list = self.get_node(Etag_list_indexname)\n Etag_Etype_list_indexname = mesh_idname+'_ElTagsTypeList'\n Etag_Etype_list = self.get_node(Etag_Etype_list_indexname)\n\n for i in range(len(Etag_list)):\n tag_name = Etag_list[i].decode('UTF-8')\n el_type = Etag_Etype_list[i].decode('UTF-8')\n elem_container = AllElements.GetElementsOfType(el_type)\n tag = elem_container.tags.CreateTag(tag_name,False)\n tag_path = os.path.join(Etags_group._v_pathname,'ET_'+tag_name)\n nodes_Ids = self.get_node(tag_path, as_numpy)\n ## Need to add local ids !! Substract the offset stored by\n ## get_mesh_elements\n tag.SetIds(nodes_Ids- offset_dic[el_type])\n return AllElements\n\n def _from_BT_mixed_topology(self, mesh_object):\n \"\"\"Read mesh elements information/metadata from mesh_object.\"\"\"\n import BasicTools.Containers.ElementNames as EN\n topology_attributes = {}\n topology_attributes['Topology'] = 'Mixed'\n element_type = []\n elements_offset = []\n Number_of_elements = []\n Number_of_bulk_elements = []\n Number_of_boundary_elements = []\n Xdmf_elements_code = []\n offset = 0\n # for each element type in the mesh_object, read type, number and\n # xdmf code for the elements\n # The process has 2 steps: 1 for bulk elements, then 1 for boundary\n # elements\n # First step for bulk elements\n for ntype, data in mesh_object.elements.items():\n if EN.dimension[ntype] == mesh_object.GetDimensionality():\n element_type.append(ntype)\n elements_offset.append(offset)\n offset += data.GetNumberOfElements()\n Number_of_elements.append(data.GetNumberOfElements())\n Xdmf_elements_code.append(XdmfNumber[ntype])\n Number_of_bulk_elements.append(data.GetNumberOfElements())\n elif EN.dimension[ntype] > mesh_object.GetDimensionality():\n raise ValueError('Elements dimensionality is higher than mesh'\n ' dimensionality.')\n # Second step for boundary elements\n for ntype, data in mesh_object.elements.items():\n if EN.dimension[ntype] < mesh_object.GetDimensionality():\n element_type.append(ntype)\n elements_offset.append(offset)\n offset += data.GetNumberOfElements()\n Number_of_elements.append(data.GetNumberOfElements())\n Xdmf_elements_code.append(XdmfNumber[ntype])\n Number_of_boundary_elements.append(data.GetNumberOfElements())\n elif EN.dimension[ntype] > mesh_object.GetDimensionality():\n raise ValueError('Elements dimensionality is higher than mesh'\n ' dimensionality.')\n # Return them in topology_attributes dic\n topology_attributes['element_type'] = element_type\n topology_attributes['Number_of_elements'] = np.array(\n Number_of_elements)\n topology_attributes['Elements_offset'] = np.array(\n elements_offset)\n topology_attributes['Number_of_bulk_elements'] = np.array(\n Number_of_bulk_elements)\n topology_attributes['Number_of_boundary_elements'] = np.array(\n Number_of_boundary_elements)\n topology_attributes['Xdmf_elements_code'] = Xdmf_elements_code\n return topology_attributes\n\n def _from_BT_uniform_topology(self, mesh_object):\n \"\"\"Read mesh elements information/metadata from mesh_object.\"\"\"\n topology_attributes = {}\n topology_attributes['Topology'] = 'Uniform'\n element_type = mesh_object.elements.keys()[0]\n topology_attributes['element_type'] = [element_type]\n n_elements = mesh_object.GetNumberOfElements()\n topology_attributes['Number_of_elements'] = np.array([n_elements])\n topology_attributes['Number_of_bulk_elements'] = np.array([n_elements])\n topology_attributes['Number_of_boundary_elements'] = np.array([0])\n topology_attributes['Elements_offset'] = [0]\n topology_attributes['Xdmf_elements_code'] = [XdmfName[element_type]]\n return topology_attributes\n\n def _add_topology(self,topology_attributes, mesh_object, mesh_group,\n geo_group, replace):\n \"\"\"Add Elements array into mesh geometry group from mesh_object.\"\"\"\n # Add Elements connectivity\n self._verbose_print('Creating Elements connectivity array in group {}'\n ' in file {}'\n ''.format(geo_group._v_pathname, self.h5_file))\n # Get mesh group indexname\n indexname_tmp = self.get_indexname_from_path(mesh_group._v_pathname)\n # Creating topology array\n data = np.empty((0,),dtype=np.int)\n for i in range(len(topology_attributes['element_type'])):\n element_type = topology_attributes['element_type'][i]\n elements = mesh_object.elements[element_type]\n data_tmp = elements.connectivity\n if topology_attributes['Topology'] == 'Mixed':\n # If mixed topology, add XDMF element type ID number\n # before Nodes ID\n xdmf_code = topology_attributes['Xdmf_elements_code'][i]\n type_col = np.ones(shape=(data_tmp.shape[0],1), dtype=np.int)\n if element_type == 'bar2':\n data_tmp = np.concatenate((2*type_col, data_tmp),1)\n if element_type == 'point1':\n data_tmp = np.concatenate((type_col, data_tmp),1)\n type_col = xdmf_code*type_col\n data_tmp = np.concatenate((type_col, data_tmp),1)\n data = np.concatenate((data, data_tmp.ravel()))\n # Add data array to HDF5 data set in mesh geometry node\n indexname = indexname_tmp+'_Elements'\n Elems = self.add_data_array(location=geo_group._v_pathname,\n name='Elements', array=data,\n indexname=indexname)\n self.add_attributes({'elements_path': Elems._v_pathname},\n mesh_group._v_pathname)\n return\n\n def _add_image_to_xdmf(self, imagename, image_object):\n \"\"\"Write grid geometry and topoly in xdmf tree/file.\"\"\"\n # add 1 to each dimension to get grid dimension (from cell number to\n # point number --> XDMF indicates Grid points)\n image_type = self._get_image_type(image_object)\n # Get image dimension with reverted shape to compensate for Paraview\n # X,Y,Z indexing convention\n Dimension_tmp = image_object.GetDimensions()\n Spacing_tmp = image_object.GetSpacing()\n Origin_tmp = image_object.GetOrigin()\n if len(Dimension_tmp) == 2:\n Dimension_tmp = Dimension_tmp[[1,0]]\n Spacing_tmp = Spacing_tmp[[1,0]]\n Origin_tmp = Origin_tmp[[1,0]]\n elif len(Dimension_tmp) == 3:\n Dimension_tmp = Dimension_tmp[[2,1,0]]\n Spacing_tmp = Spacing_tmp[[2,1,0]]\n Origin_tmp = Origin_tmp[[2,1,0]]\n Dimension = self._np_to_xdmf_str(Dimension_tmp)\n Spacing = self._np_to_xdmf_str(Spacing_tmp)\n Origin = self._np_to_xdmf_str(Origin_tmp)\n Dimensionality = str(image_object.GetDimensionality())\n self._verbose_print('Updating xdmf tree...', line_break=False)\n # Creatge Grid element\n image_xdmf = etree.Element(_tag='Grid', Name=imagename,\n GridType='Uniform')\n # Create Topology element\n Topotype = XDMF_IMAGE_TOPOLOGY[image_type]\n topology_xdmf = etree.Element(_tag='Topology', TopologyType=Topotype,\n Dimensions=Dimension)\n # Create Geometry element\n Geotype = XDMF_IMAGE_GEOMETRY[image_type]\n geometry_xdmf = etree.Element(_tag='Geometry', Type=Geotype)\n origin_data = etree.Element(_tag='DataItem', Format='XML',\n Dimensions=Dimensionality)\n origin_data.text = Origin\n spacing_data = etree.Element(_tag='DataItem', Format='XML',\n Dimensions=Dimensionality)\n spacing_data.text = Spacing\n # Add nodes DataItem as childrens of node Geometry\n geometry_xdmf.append(origin_data)\n geometry_xdmf.append(spacing_data)\n # Add Geometry and Topology as childrens of Grid\n image_xdmf.append(topology_xdmf)\n image_xdmf.append(geometry_xdmf)\n # Add Grid to node Domain and get XDMF pathes\n self.xdmf_tree.getroot()[0].append(image_xdmf)\n return\n\n def _add_mesh_to_xdmf(self, mesh_group):\n \"\"\"Write mesh grid element geometry and topoly in xdmf tree/file.\"\"\"\n # get mesh group\n mesh_path = mesh_group._v_pathname\n # Creatge Grid element\n mesh_xdmf = etree.Element(_tag='Grid', Name=mesh_group._v_name,\n GridType='Uniform')\n # Create Geometry element\n mesh_type = self.get_attribute('group_type', mesh_path)\n if mesh_type == '2DMesh':\n geometry_xdmf = etree.Element(_tag='Geometry', Type='XY')\n elif mesh_type == '3DMesh':\n geometry_xdmf = etree.Element(_tag='Geometry', Type='XYZ')\n # Add geometry DataItem\n mesh_indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n nodes = self.get_node(mesh_indexname+'_Nodes', as_numpy=False)\n Dim = self._np_to_xdmf_str(nodes.shape)\n geometry_data = etree.Element(_tag='DataItem', Format='HDF',\n Dimensions=Dim, NumberType='Float',\n Precision='64')\n geometry_data.text = self.h5_file + ':' + nodes._v_pathname\n # Add node DataItem as children of node Geometry\n geometry_xdmf.append(geometry_data)\n # Create Topology element\n Topology = self.get_attribute('Topology', mesh_path)\n if Topology == 'Uniform':\n Topotype = self.get_attribute('Xdmf_elements_code', mesh_path)[0]\n else:\n Topotype = 'Mixed'\n NElements_list = self.get_attribute('Number_of_elements', mesh_path)\n NElements = self._np_to_xdmf_str(np.sum(NElements_list))\n topology_xdmf = etree.Element(_tag='Topology', TopologyType=Topotype,\n NumberOfElements=NElements)\n # Create Topology DataItem\n indexname = self.get_indexname_from_path(mesh_group._v_pathname)\n elems = self.get_node(indexname+'_Elements', as_numpy=False)\n Dim = self._np_to_xdmf_str(elems.shape)\n topology_data = etree.Element(_tag='DataItem', Format='HDF',\n Dimensions=Dim, NumberType='Int',\n Precision='64')\n topology_data.text = self.h5_file + ':' + elems._v_pathname\n # Add node DataItem as children of node Topology\n topology_xdmf.append(topology_data)\n # Add Geometry and Topology as childrens of Grid\n mesh_xdmf.append(geometry_xdmf)\n mesh_xdmf.append(topology_xdmf)\n # Add Grid to node Domain\n self.xdmf_tree.getroot()[0].append(mesh_xdmf)\n return\n\n def _append_field_index(self, gridname, fieldname):\n \"\"\"Append field name to the field index of a grid group.\"\"\"\n grid = self.get_node(gridname)\n index_path = os.path.join(grid._v_pathname,'Field_index')\n Field_index = self.get_node(index_path)\n if Field_index is None:\n grid_indexname = self.get_indexname_from_path(grid._v_pathname)\n Field_index = self.add_string_array(\n 'Field_index', location=grid._v_pathname,\n indexname=grid_indexname+'_Field_index')\n test_str = bytes(fieldname,'utf-8')\n if test_str not in Field_index:\n Field_index.append([fieldname])\n return\n\n def _transpose_field_comp(self, dimensionality, array):\n \"\"\"Transpose fields components to comply with Paraview ordering.\"\"\"\n # based on the conventions:\n # Tensor6 is passed as [xx,yy,zz,xy,yz,zx]\n # Tensor is passed as [xx,yy,zz,xy,yz,zx,yx,zy,xz]\n if dimensionality == 'Tensor6':\n transpose_indices = [0,3,5,1,4,2]\n transpose_back = [0,3,5,1,4,2]\n if dimensionality == 'Tensor':\n transpose_indices = [0,3,8,6,1,4,5,7,2]\n transpose_back = [0,4,8,1,5,6,3,7,2]\n return array[...,transpose_indices], transpose_back\n\n def _transpose_image_array(self, dimensionality, array):\n \"\"\"Transpose the array X,Y,Z dimensions for XDMF conventions.\"\"\"\n if dimensionality in ['Vector', 'Tensor6', 'Tensor']:\n # vector or tensor field\n if len(array.shape) == 3:\n # 2D image\n transpose_indices = [1,0,2]\n elif len(array.shape) == 4:\n # 3D image\n transpose_indices = [2,1,0,3]\n elif dimensionality == 'Scalar':\n # scalar field\n if len(array.shape) == 2:\n # 2D image\n transpose_indices = [1,0]\n elif len(array.shape) == 3:\n # 3D image\n transpose_indices = [2,1,0]\n else:\n raise ValueError('Unknown field dimensionality. Possible values'\n ' are {}'.format(XDMF_FIELD_TYPE.values()))\n return array.transpose(transpose_indices), transpose_indices\n\n def _add_field_to_xdmf(self, fieldname, field):\n \"\"\"Write field data as Grid Attribute in xdmf tree/file.\"\"\"\n Node = self.get_node(fieldname)\n Grid_name = self.get_attribute('xdmf_gridname', fieldname)\n Xdmf_grid_node = self._find_xdmf_grid(Grid_name)\n field_type = self.get_attribute('field_type', fieldname)\n if field_type == 'Nodal_field':\n Center_type = 'Node'\n elif (field_type == 'Element_field') or (field_type == 'IP_field'):\n Center_type = 'Cell'\n else:\n raise ValueError('unknown field type, should be `Nodal_field`'\n ' or `Element_field`.')\n field_dimensionality = self.get_attribute('field_dimensionality',\n fieldname)\n # Get the time_serie field name if it exists time_serie_name\n time_serie_name = self.get_attribute('time_serie_name', fieldname)\n if time_serie_name is None:\n attr_name = Node._v_name\n else:\n attr_name = time_serie_name\n # create Attribute element\n Attribute_xdmf = etree.Element(_tag='Attribute', Name=attr_name,\n AttributeType=field_dimensionality,\n Center=Center_type)\n # Create data item element\n Dimension = self._np_to_xdmf_str(Node.shape)\n if (np.issubdtype(field.dtype, np.floating)):\n NumberType = 'Float'\n if (str(field.dtype) == 'float'):\n Precision = '32'\n else:\n Precision = '64'\n elif (np.issubdtype(field.dtype, np.integer)):\n NumberType = 'Int'\n Precision = str(field.dtype).strip('int')\n Attribute_data = etree.Element(_tag='DataItem', Format='HDF',\n Dimensions=Dimension,\n NumberType=NumberType,\n Precision=Precision)\n Attribute_data.text = (self.h5_file + ':'\n + self._name_or_node_to_path(fieldname))\n # if data normalization is used, a intermediate DataItem is created\n # to apply a linear function to the dataitem\n norm = self.get_attribute('data_normalization', fieldname)\n if norm == 'standard':\n mu = self.get_attribute('normalization_mean', fieldname)\n std = self.get_attribute('normalization_std', fieldname)\n Func = f'{std}*($0) + {mu}'\n Function_data = etree.Element(_tag='DataItem',\n ItemType='Function',\n Function=Func,\n Dimensions=Dimension)\n # add data item to function data item\n Function_data.append(Attribute_data)\n # add data item to attribute\n Attribute_xdmf.append(Function_data)\n elif norm == 'standard_per_component':\n # Create dataitem for per component mean\n mean_path = self.get_attribute('norm_mean_array_path', fieldname)\n Attribute_mean = etree.Element(_tag='DataItem', Format='HDF',\n Dimensions=Dimension,\n NumberType=NumberType,\n Precision=Precision)\n Attribute_mean.text = (self.h5_file + ':' + mean_path)\n # Create dataitem for per component std\n std_path = self.get_attribute('norm_std_array_path', fieldname)\n Attribute_std = etree.Element(_tag='DataItem', Format='HDF',\n Dimensions=Dimension,\n NumberType=NumberType,\n Precision=Precision)\n Attribute_std.text = (self.h5_file + ':' + std_path)\n # Create dataitem for Function\n Func = '($2*$0) + $1'\n Function_data = etree.Element(_tag='DataItem',\n ItemType='Function',\n Function=Func,\n Dimensions=Dimension)\n # add data items to function data item\n Function_data.append(Attribute_data)\n Function_data.append(Attribute_mean)\n Function_data.append(Attribute_std)\n # add function data item to attribute\n Attribute_xdmf.append(Function_data)\n else:\n # add data item to attribute\n Attribute_xdmf.append(Attribute_data)\n # add attribute to Grid\n Xdmf_grid_node.append(Attribute_xdmf)\n self.add_attributes({'xdmf_fieldname': Attribute_xdmf.get('Name')},\n fieldname)\n return\n\n def _get_node_class(self, name):\n \"\"\"Return Pytables Class type associated to the node name.\"\"\"\n return self.get_attribute(attrname='CLASS', nodename=name)\n\n def _get_path_with_indexname(self, indexname):\n \"\"\"Return node path from its indexname.\"\"\"\n if indexname in self.content_index.keys():\n if isinstance(self.content_index[indexname], list):\n return self.content_index[indexname][0]\n else:\n return self.content_index[indexname]\n else:\n raise tables.NodeError('Index contains no item named {}'\n ''.format(indexname))\n return\n\n def _get_group_type(self, groupname):\n \"\"\"Get SampleData HDF5 Group type (Mesh, Group or 3DImage).\"\"\"\n if groupname == '/':\n return 'GROUP'\n if self._is_group(groupname):\n grouptype = self.get_attribute(attrname='group_type',\n nodename=groupname)\n if grouptype is None:\n return 'GROUP'\n else:\n return grouptype\n else:\n return None\n\n def _get_image_type(self, image_object):\n try:\n return SD_IMAGE_GROUPS[image_object.GetDimensionality()]\n except:\n raise ValueError('Image dimension must correspond to a 2D or'\n '3D image.')\n\n def _get_mesh_type(self, mesh_object):\n try:\n return SD_MESH_GROUPS[mesh_object.nodes.shape[1]]\n except:\n raise ValueError('Mesh dimension must correspond to a 2D or'\n '3D mesh.')\n\n def _get_mesh_elements_offsets(self, meshname):\n types = self.get_attribute('element_type', meshname)\n offsets = self.get_attribute('Elements_offset', meshname)\n return {types[i]:offsets[i] for i in range(len(types))}\n\n def _get_parent_type(self, name):\n \"\"\"Get the SampleData group type of the node parent group.\"\"\"\n groupname = self._get_parent_name(name)\n return self._get_group_type(groupname)\n\n def _get_parent_name(self, name):\n \"\"\"Get the name of the node parent group.\"\"\"\n Node = self.get_node(name)\n Group = Node._g_getparent()\n return Group._v_name\n\n def _get_group_info(self, groupname, as_string=False, short=False):\n \"\"\"Print a human readable information on the Pytables Group object.\"\"\"\n s = ''\n Group = self.get_node(groupname)\n if Group is None:\n return f'No group named {groupname}'\n gname = Group._v_name\n if short:\n s = (' '*Group._v_depth)+'|--'\n gtype = self.get_attribute('group_type', Group)\n s += f'GROUP {gname}: {Group._v_pathname} ({gtype}) \\n'\n return s\n s += str('\\n GROUP {}\\n'.format(gname))\n s += str('=====================\\n')\n gparent_name = Group._v_parent._v_name\n s += str(' -- Parent Group : {}\\n'.format(gparent_name))\n s += str(' -- Group attributes : \\n')\n for attr in Group._v_attrs._v_attrnamesuser:\n value = Group._v_attrs[attr]\n s += str('\\t * {} : {}\\n'.format(attr, value))\n s += str(' -- Childrens : ')\n for child in Group._v_children:\n s += str('{}, '.format(child))\n s += str('\\n----------------')\n if not(as_string):\n print(s)\n s = ''\n return s\n\n def _get_array_node_info(self, nodename, as_string=False, short=False):\n \"\"\"Print a human readable information on the Pytables Group object.\"\"\"\n Node = self.get_node(nodename)\n if Node is None:\n return f'No group named {nodename}'\n size, unit = self.get_node_disk_size(nodename, print_flag=False)\n if short:\n s = (' '*Node._v_depth)+' --'\n ntype = self.get_attribute('node_type', Node)\n if self._is_empty(Node):\n empty_s = ' - empty'\n else:\n empty_s= ''\n s += f'NODE {Node._v_name}: {Node._v_pathname}'\n s += f' ({ntype}{empty_s}) ({size:9.3f} {unit})'\n return s+'\\n'\n s = ''\n s += str('\\n NODE: {}\\n'.format(Node._v_pathname))\n s += str('====================\\n')\n nparent_name = Node._v_parent._v_name\n s += str(' -- Parent Group : {}\\n'.format(nparent_name))\n s += str(' -- Node name : {}\\n'.format(Node._v_name))\n s += self.print_node_attributes(Node, as_string=True)\n s += str(' -- content : {}\\n'.format(str(Node)))\n if self._is_table(nodename):\n s += ' -- table description : \\n'\n s += repr(Node.description)+'\\n'\n s += str(' -- ')\n s += self.print_node_compression_info(nodename, as_string=True)\n s += str(' -- Node memory size : {:9.3f} {}\\n'.format(size, unit))\n s += str('----------------\\n')\n if not(as_string):\n print(s)\n s = ''\n return s\n\n def _get_compression_opt(self, compression_opts=dict()):\n \"\"\"Get inputed compression settings as `tables.Filters` instance.\"\"\"\n Filters = tables.Filters()\n # ------ read compression options in dict\n for option in compression_opts:\n if (option == 'complib'):\n Filters.complib = compression_opts[option]\n elif (option == 'complevel'):\n Filters.complevel = compression_opts[option]\n elif (option == 'shuffle'):\n Filters.shuffle = compression_opts[option]\n elif (option == 'bitshuffle'):\n Filters.bitshuffle = compression_opts[option]\n elif (option == 'checksum'):\n Filters.fletcher32 = compression_opts[option]\n elif (option == 'least_significant_digit'):\n Filters.least_significant_digit = compression_opts[option]\n return Filters\n\n def _get_compression_opt_from_filter(self, Filters):\n \"\"\"Get inputed compression settings as `tables.Filters` instance.\"\"\"\n c_opts = {}\n c_opts['complib'] = Filters.complib\n c_opts['complevel'] = Filters.complevel\n c_opts['shuffle'] = Filters.shuffle\n c_opts['bitshuffle'] = Filters.bitshuffle\n c_opts['least_significant_digit'] = Filters.least_significant_digit\n c_opts['bitshuffle'] = Filters.bitshuffle\n return c_opts\n\n @staticmethod\n def _data_normalization(array, normalization):\n \"\"\"Apply normalization to data array to improve compression ratios\"\"\"\n if normalization == 'standard':\n mu = np.mean(array)\n std= np.std(array)\n array = (array - mu) / std\n normalization_attributes = {'data_normalization':normalization,\n 'normalization_mean':mu,\n 'normalization_std':std}\n if normalization == 'standard_per_component':\n # Apply component per component\n mu = np.zeros((array.shape[-1]))\n std = np.zeros((array.shape[-1]))\n mu_array = np.zeros((array.shape))\n std_array = np.zeros((array.shape))\n for comp in range(array.shape[-1]):\n mu[comp] = np.mean(array[..., comp])\n std[comp] = np.std(array[..., comp])\n array[..., comp] = (array[..., comp] - mu[comp]) / std[comp]\n mu_array[..., comp] = mu[comp]\n std_array[..., comp] = std[comp]\n # Create normalization attributes\n normalization_attributes = {'data_normalization':normalization,\n 'normalization_mean':mu,\n 'normalization_std':std,\n 'norm_mean_array':mu_array,\n 'norm_std_array':std_array}\n return array, normalization_attributes\n\n def _read_mesh_from_file(self, file=''):\n \"\"\"Read a data array from a file, depending on the extension.\"\"\"\n mesh_object = None\n from BasicTools.IO.UniversalReader import ReadMesh\n mesh_object = ReadMesh(file)\n return mesh_object\n\n def _verbose_print(self, message, line_break=True):\n \"\"\"Print message if verbose flag is `True`.\"\"\"\n Msg = message\n if line_break:\n Msg = ('\\n' + Msg)\n if self._verbose:\n print(Msg)\n return\n\n def _np_to_xdmf_str(self, array):\n Retstr = str(array).strip('(').strip(')')\n Retstr = str(Retstr).strip('[').strip(']')\n Retstr = str(Retstr).replace(',', ' ')\n return Retstr\n"
] | [
[
"numpy.dot",
"numpy.issubdtype",
"numpy.squeeze",
"numpy.dtype",
"numpy.all",
"numpy.max",
"numpy.concatenate",
"numpy.mean",
"numpy.any",
"numpy.cross",
"numpy.where",
"numpy.unique",
"numpy.arange",
"numpy.atleast_1d",
"numpy.std",
"numpy.zeros",
"numpy.random.rand",
"numpy.array",
"numpy.sum",
"numpy.linalg.norm",
"numpy.ones",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zpc-666/Temporal-Action-Proposal-Generation-competition | [
"5ee01a60b562e0248e5915c78d175ea6aaf854c1"
] | [
"utils.py"
] | [
"import numpy as np\r\nimport os, pickle, tqdm, json\r\nimport paddle\r\nimport random\r\n\r\ndef set_seed_paddle(seed=1024):\r\n seed = int(seed)\r\n random.seed(seed)\r\n os.environ['PYTHONHASHSEED'] = str(seed)\r\n np.random.seed(seed)\r\n paddle.seed(seed)\r\n\r\ndef iou_with_anchors(anchors_min, anchors_max, box_min, box_max):\r\n \"\"\"Compute jaccard score between a box and the anchors.\r\n \"\"\"\r\n len_anchors = anchors_max - anchors_min\r\n int_xmin = np.maximum(anchors_min, box_min)\r\n int_xmax = np.minimum(anchors_max, box_max)\r\n inter_len = np.maximum(int_xmax - int_xmin, 0.)\r\n union_len = len_anchors - inter_len + box_max - box_min\r\n jaccard = np.divide(inter_len, union_len)\r\n return jaccard\r\n\r\n\r\ndef boundary_choose(score_list):\r\n \"\"\"Choose start and end boundary from score.\r\n \"\"\"\r\n max_score = max(score_list)\r\n mask_high = (score_list > max_score * 0.5)\r\n score_list = list(score_list)\r\n score_middle = np.array([0.0] + score_list + [0.0])\r\n score_front = np.array([0.0, 0.0] + score_list)\r\n score_back = np.array(score_list + [0.0, 0.0])\r\n mask_peak = ((score_middle > score_front) & (score_middle > score_back))\r\n mask_peak = mask_peak[1:-1]\r\n mask = (mask_high | mask_peak).astype('float32')\r\n return mask\r\n\r\n\r\ndef soft_nms(proposal_dict, alpha=0.4, t1=0.55, t2=0.9, dscale=4): #dscale指的是切片视频的持续时间\r\n '''\r\n proposal_dict: proposals generated by network;\r\n alpha: alpha value of Gaussian decaying function;\r\n t1, t2: threshold for soft nms.\r\n '''\r\n sorted_proposal = sorted(proposal_dict, key=lambda x:x[\"score\"], reverse=True)\r\n tstart = []\r\n tend = []\r\n tscore = []\r\n for pp in sorted_proposal:\r\n tstart.append(pp[\"segment\"][0])\r\n tend.append(pp[\"segment\"][1])\r\n tscore.append(pp[\"score\"])\r\n\r\n rstart = []\r\n rend = []\r\n rscore = []\r\n\r\n while len(tscore) > 1 and len(rscore) < 101:\r\n max_index = tscore.index(max(tscore))\r\n tmp_iou_list = iou_with_anchors(np.array(tstart), np.array(tend),\r\n tstart[max_index], tend[max_index])\r\n for idx in range(0, len(tscore)):\r\n if idx != max_index:\r\n tmp_iou = tmp_iou_list[idx]\r\n tmp_width = (tend[max_index] - tstart[max_index])/dscale #此处相比PaddleVideo中的做了修改,提高了AUC\r\n if tmp_iou > t1 + (t2 - t1) * tmp_width:\r\n tscore[idx] = tscore[idx] * np.exp(\r\n -np.square(tmp_iou) / alpha)\r\n\r\n rstart.append(tstart[max_index])\r\n rend.append(tend[max_index])\r\n rscore.append(tscore[max_index])\r\n tstart.pop(max_index)\r\n tend.pop(max_index)\r\n tscore.pop(max_index)\r\n\r\n new_proposal = []\r\n for i in range(len(rscore)):\r\n pp = {}\r\n pp['score'] = round(rscore[i], 2)\r\n pp[\"segment\"] = [round(rstart[i], 2), round(rend[i], 2)]\r\n new_proposal.append(pp)\r\n \r\n return new_proposal\r\n\r\n\r\ndef win_splitting_per_video_for_testing(root, feat_output_path, json_path, test_file_name=None, T=100, fps=25):\r\n # 划分测试视频,并建立视频信息json文件\r\n if not os.path.exists(feat_output_path):\r\n os.makedirs(feat_output_path)\r\n clip_ds = T/fps\r\n if test_file_name is None:\r\n test_file_name = os.listdir(root)\r\n else:\r\n test_file_name = [na[:-3]+'pkl' for na in test_file_name]\r\n\r\n print(f\"开始以窗口大小为{T},步长为{T//2}来划分每一条视频(保存的每个视频切片不必包含提案)...\")\r\n\r\n test_dict = {}\r\n for file_name in tqdm.tqdm(test_file_name):\r\n file_path = os.path.join(root, file_name)\r\n video_feat = pickle.load(open(file_path, \"rb\"))['image_feature']\r\n frames_len = len(video_feat)\r\n video_ds = frames_len/fps\r\n clip_count = 1\r\n for start_f in range(0, frames_len, T//2):\r\n end_f = start_f+T\r\n if end_f<frames_len:\r\n win_feat = video_feat[start_f:end_f]\r\n start_second = start_f/fps\r\n end_second = end_f/fps\r\n annotations = {\"clip_s\":start_second, \"clip_e\":end_second}\r\n\r\n else:\r\n win_feat = video_feat[frames_len-T:]\r\n start_second = (frames_len-T)/fps\r\n end_second = video_ds\r\n annotations = {\"clip_s\":start_second, \"clip_e\":end_second}\r\n\r\n clip_name = file_name[:-4]+\"_clip\"+str(clip_count) \r\n test_dict[clip_name+\".mp4\"] = {\"subset\":\"validation\", 'duration_second':clip_ds, 'annotations':annotations}\r\n\r\n with open(os.path.join(feat_output_path, clip_name+\".pkl\"), \"wb\") as f:\r\n pickle.dump({'image_feature':win_feat}, f)\r\n clip_count += 1\r\n \r\n print(feat_output_path+\"中共有\"+str(len(test_dict))+\"条切片数据!\")\r\n with open(json_path, 'w', encoding='utf-8') as f:\r\n json.dump(test_dict, f, ensure_ascii=False, indent=4)\r\n\r\n\r\ndef win_splitting_per_video_for_training(video_info,\r\n root, \r\n feat_output_path, \r\n train_json_path, \r\n val_gt_json_path,\r\n orig_val_gt_json_path,\r\n val_ratio=0.025,\r\n T=100, \r\n fps=25):\r\n # 划分视频,得到训练验证视频集及信息json文件\r\n num_videos = len(video_info)\r\n train_num = int(num_videos*(1-val_ratio))\r\n val_num = num_videos-train_num\r\n print(f\"总共{num_videos}条视频,其中{train_num}条视频划分后用于训练,其余{val_num}条视频用于验证!\")\r\n print(f\"开始以窗口大小为{T},步长为{T//2}来划分每一条视频(保存的每个视频切片至少包含一个完整的提案)...\")\r\n if not os.path.exists(feat_output_path):\r\n os.makedirs(feat_output_path)\r\n train_dict = {}\r\n val_dict = {}\r\n val_orig_dict = {}\r\n clip_ds = T/fps\r\n for i, items in enumerate(video_info):\r\n file_name = items['url'][:-3]+\"pkl\"\r\n file_path = os.path.join(root, file_name)\r\n if not os.path.exists(file_path):\r\n continue\r\n \r\n end_ids = [action[\"end_id\"] for action in items[\"actions\"]]\r\n #print(end_ids)\r\n if len(end_ids)==0:\r\n print(\"被丢弃的无效数据:\", items)\r\n continue\r\n \r\n video_annotations = [{\"segment\":[action[\"start_id\"], action[\"end_id\"]], \"label\":action[\"label_names\"][0]} for action in items[\"actions\"]] \r\n video_feat = pickle.load(open(file_path, \"rb\"))['image_feature']\r\n frames_len = len(video_feat)\r\n video_ds = frames_len/fps\r\n \r\n clip_count = 1\r\n for start_f in range(0, frames_len, T//2):\r\n end_f = start_f+T\r\n if end_f<frames_len:\r\n win_feat = video_feat[start_f:end_f]\r\n start_second = start_f/fps\r\n end_second = end_f/fps\r\n annotations = []\r\n for annt in video_annotations:\r\n if annt[\"segment\"][0]>=start_second and annt[\"segment\"][1]<=end_second:\r\n annotations.append({\"segment\": [annt[\"segment\"][0]-start_second, annt[\"segment\"][1]-start_second], \"label\":annt[\"label\"]})\r\n\r\n else:\r\n win_feat = video_feat[frames_len-T:]\r\n start_second = (frames_len-T)/fps\r\n end_second = video_ds\r\n annotations = []\r\n for annt in video_annotations:\r\n if annt[\"segment\"][0]>=start_second and annt[\"segment\"][1]<=end_second:\r\n annotations.append({\"segment\": [annt[\"segment\"][0]-start_second, annt[\"segment\"][1]-start_second], \"label\":annt[\"label\"]})\r\n \r\n if len(annotations)==0:\r\n clip_count += 1\r\n continue\r\n clip_name = items['url'][:-4]+\"_clip\"+str(clip_count)\r\n if i<train_num:\r\n train_dict[clip_name+\".mp4\"] = {\"subset\":\"train\", 'duration_second':clip_ds, 'annotations':annotations}\r\n else:\r\n train_dict[clip_name+\".mp4\"] = {\"subset\":\"validation\", 'duration_second':clip_ds, 'annotations':annotations}\r\n val_dict[clip_name+\".mp4\"] = {\"subset\":\"validation\", 'duration_second':clip_ds, 'annotations':annotations}\r\n assert len(win_feat)==T\r\n with open(os.path.join(feat_output_path, clip_name+\".pkl\"), \"wb\") as f:\r\n pickle.dump({'image_feature':win_feat}, f)\r\n clip_count += 1\r\n if i<train_num:\r\n os.remove(file_path)\r\n else:\r\n val_orig_dict[items['url']] = {\"subset\":\"validation\", 'num_frames':frames_len, 'annotations':video_annotations}\r\n\r\n print(feat_output_path+\"中共有\"+str(len(train_dict))+\"条切片数据!\")\r\n #生成训练所用的json文件\r\n with open(train_json_path, 'w', encoding='utf-8') as f:\r\n json.dump(train_dict, f, ensure_ascii=False, indent=4)\r\n #生成验证集保存的每个切片对应的提案标签的json文件\r\n with open(val_gt_json_path, 'w', encoding='utf-8') as f:\r\n new_val_dict = {'taxonomy': None, 'database': val_dict, 'version': None}\r\n json.dump(new_val_dict, f, ensure_ascii=False, indent=4)\r\n #生成验证集切分之前源视频对应的提案标签文件\r\n with open(orig_val_gt_json_path, 'w', encoding='utf-8') as f:\r\n val_orig_dict = {'taxonomy': None, 'database': val_orig_dict, 'version': None, 'fps': fps}\r\n json.dump(val_orig_dict, f, ensure_ascii=False, indent=4)\r\n\r\n\r\ndef merging_output_per_video(test_root, #未划分的原视频特征存放路径\r\n proposal_filename, #预测的待拼接回每个原视频的切片提案信息文件路径\r\n merging_output_filename, #合并后每个视频对应的预测提案信息,用于提交\r\n win_T=100, \r\n fps=25,\r\n snms_alpha=0.4, \r\n snms_t1=0.55,\r\n snms_t2=0.9):\r\n # 合并回提交文件\r\n test_file_name = os.listdir(test_root)\r\n with open(proposal_filename, 'r', encoding='utf-8') as f:\r\n pred_dict = json.load(f)\r\n\r\n new_pred_dict = {\"version\":pred_dict[\"version\"], \"external_data\": {}}\r\n results_dict = pred_dict[\"results\"]\r\n new_results_dict = {}\r\n for file_name in tqdm.tqdm(test_file_name):\r\n file_path = os.path.join(test_root, file_name)\r\n video_feat = pickle.load(open(file_path, \"rb\"))['image_feature']\r\n frames_len = len(video_feat)\r\n clip_count = 1\r\n proposal = []\r\n for start_f in range(0, frames_len, win_T//2):\r\n end_f = start_f+win_T\r\n if end_f<frames_len:\r\n start_second = start_f/fps\r\n\r\n else:\r\n start_second = (frames_len-win_T)/fps\r\n\r\n clip_name = file_name[:-4]+\"_clip\"+str(clip_count) \r\n if (clip_name[2:]+\".mp4\") not in results_dict.keys(): #bmn_metric.py 第279行\r\n print(\"无提案信息的视频:\", clip_name+\".mp4\")\r\n clip_count += 1\r\n continue\r\n if len(results_dict[clip_name[2:]+\".mp4\"])==0:\r\n print(\"无提案信息的视频:\", clip_name+\".mp4\") \r\n clip_count += 1\r\n continue \r\n for pp in results_dict[clip_name[2:]+\".mp4\"]:\r\n pp[\"segment\"][0] = pp[\"segment\"][0]+start_second\r\n pp[\"segment\"][1] = pp[\"segment\"][1]+start_second\r\n proposal.append(pp)\r\n clip_count += 1\r\n \r\n proposal = soft_nms(proposal, alpha=snms_alpha, t1=snms_t1, t2=snms_t2, dscale=win_T//fps)\r\n proposal = sorted(proposal, key=lambda x:x[\"segment\"][0], reverse=False)\r\n new_results_dict[file_name[:-4]] = proposal\r\n\r\n new_pred_dict[\"results\"] = new_results_dict\r\n with open(merging_output_filename, 'w') as f:\r\n json.dump(new_pred_dict, f)\r\n\r\ndef checking_submission(json_path1=\"\", json_path2=\"\"):\r\n with open(json_path1, 'r', encoding='utf-8') as f:\r\n results1 = json.load(f)[\"results\"]\r\n with open(json_path2, 'r', encoding='utf-8') as f:\r\n results2 = json.load(f)[\"results\"]\r\n for video_name in results1.keys():\r\n proposals1 = results1[video_name]\r\n proposals2 = results2[video_name]\r\n for pp1, pp2 in zip(proposals1, proposals2):\r\n if pp1[\"segment\"][0]!=pp2[\"segment\"][0] or pp1[\"segment\"][1]!=pp2[\"segment\"][1]:\r\n print(\"两份提交文件不一致!\")\r\n return\r\n print(\"两份提交文件完全一致!\")"
] | [
[
"numpy.square",
"numpy.maximum",
"numpy.minimum",
"numpy.random.seed",
"numpy.array",
"numpy.divide"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nightttt7/tool9 | [
"659054ce1acd681935f423509a7dfbdd887ae35f"
] | [
"tool9/func.py"
] | [
"__all__ = ['period', 'describe', 'ni', 'yearlyreturn', 'yearlyreturnm',\n 'exesssyearlyreturn', 'exesssyearlyreturnm', 'sr', 'srm', 'srf',\n 'srfm', 'var', 'es', 'drawdown', 'avedrawdown', 'maxdrawdown',\n 'portfolio_risk', 'period_4_plot', 'performance', 'performance1',\n 'performance2']\n\n\n# ----------------------------------------------------------------------------\n\n\ndef period(col, data):\n \"\"\"\n return the effective date period of one column\n \"\"\"\n start = data[col].first_valid_index()\n end = data[col].sort_index(ascending=False).first_valid_index()\n return([start, end])\n# how to use:\n# [start,end] = period('colname')\n# ----------------------------------------------------------------------------\n\n\ndef describe(col, data):\n \"\"\"\n return basic statistical descriptions\n \"\"\"\n import pandas as pd\n d = {}\n # number of observations\n d['Nobs'] = [data[col].count()]\n # mean\n d['Mean'] = [data[col].mean()]\n # std\n d['Std.'] = [data[col].std()]\n # mad\n d['Mad'] = [data[col].mad()]\n # min\n d['Min'] = [data[col].min()]\n # max\n d['Max'] = [data[col].max()]\n # skew\n d['Skew'] = [data[col].skew()]\n # excess kurt\n d['Excess Kurt'] = data[col].kurt()\n # acf lag=1\n d['acf lag=1'] = data[col].autocorr(1)\n # acf lag=5\n d['acf lag=5'] = data[col].autocorr(5)\n # acf lag=10\n d['acf lag=10'] = data[col].autocorr(10)\n # acf lag=20\n d['acf lag=20'] = data[col].autocorr(20)\n # turn to DataFrame\n output = pd.DataFrame(d)\n # rename index\n output.index = [col]\n return(output)\n# ----------------------------------------------------------------------------\n\n\n# function ni (no included)\ndef ni(col, data):\n return(data.loc[:, data.columns != col])\n# how to use:\n# col_ni = ni('colname')\n# ----------------------------------------------------------------------------\n\n\n# those functions is about the performance of log returns\n\n# lr: log returns, main input.\n# lrf: log risk free rate\n# because of the characteristic of logarithm, profit, var and es\n# reflect the relatively performances in log returns\n\n\n# function yearlyreturn\ndef yearlyreturn(lr):\n t = lr.mean()*252\n return t\n\n\n# function yearlyreturnm\ndef yearlyreturnm(lr):\n t = lr.mean()*12\n return t\n\n\n# function exesssyearlyreturn\ndef exesssyearlyreturn(lr, lrf):\n t = (lr.mean()-lrf.mean())*252\n return t\n\n\n# function exesssyearlyreturnm\ndef exesssyearlyreturnm(lr, lrf):\n t = (lr.mean()-lrf.mean())*12\n return t\n\n\n# function sr (yearly sharpe ratio (no risk free rate) for log returns)\ndef sr(lr):\n import numpy as np\n s = lr.std()\n t = (lr.mean()/s)*np.sqrt(252)\n return t\n\n\n# function srm\ndef srm(lr):\n import numpy as np\n s = lr.std()\n t = (lr.mean()/s)*np.sqrt(12)\n return t\n\n\n# function srf (yearly sharpe ratio for (excess) log returns)\n# use log risk-free rate to get the excess return\ndef srf(lr, lrf):\n import numpy as np\n s = (lr-lrf).std()\n t = ((lr.mean()-lrf.mean())/s)*np.sqrt(252)\n return t\n\n\n# function srfm\ndef srfm(lr, lrf):\n import numpy as np\n s = (lr-lrf).std()\n t = ((lr.mean()-lrf.mean())/s)*np.sqrt(12)\n return t\n\n\n# function var (value at risk for log returns)\n# with confindence level 0.95\ndef var(lr):\n import numpy as np\n n = int(np.ceil(lr.count()*0.95))\n t = lr.sort_values(ascending=False)[n-1]\n return t\n\n\n# function es (expected shortfall for log returns)\n# with confindence level 0.95\ndef es(lr):\n import numpy as np\n n = int(np.ceil(lr.count()*0.95))\n t = lr.sort_values(ascending=False)[n-1:].mean()\n return t\n\n\n# function drawdown (percentage drawdown)\n# (not log returns here)\n# attention: only this function returns a series\ndef drawdown(lr):\n import numpy as np\n clr = lr.cumsum()\n cummax = clr.cummax()\n t = clr-cummax\n t = np.exp(t)-1\n return t\n\n\n# function average drawdown\ndef avedrawdown(lr):\n t = drawdown(lr).mean()\n return t\n\n\n# function maxdrawdown (max percentage drawdown)\n# (not log returns here)\ndef maxdrawdown(lr):\n import numpy as np\n clr = lr.cumsum()\n cummax = clr.cummax()\n t = (clr-cummax).min()\n t = np.exp(t)-1\n return t\n\n\n# function performance\ndef performance(lr):\n import pandas as pd\n t = pd.DataFrame([yearlyreturn(lr), sr(lr), var(lr), es(lr),\n maxdrawdown(lr)])\n t.index = ['yearly return', 'sharpe ratio', 'VaR', 'ES', 'maxdrawdown']\n t.columns = ['performance']\n return t.T\n\n\n# function performance1\ndef performance1(lr, lrf):\n import pandas as pd\n t = pd.DataFrame([exesssyearlyreturn(lr, lrf), srf(lr, lrf), var(lr),\n es(lr), avedrawdown(lr), maxdrawdown(lr)])\n t.index = ['annualized excess return', 'Sharpe ratio',\n 'VaR', 'ES', 'Avg. DD', 'MDD']\n t.columns = ['performance']\n return t.T\n\n\n# function performance2\ndef performance2(lr, lrf):\n import pandas as pd\n t = pd.DataFrame([exesssyearlyreturnm(lr, lrf), srfm(lr, lrf), var(lr),\n es(lr), avedrawdown(lr), maxdrawdown(lr)])\n t.index = ['annualized excess return', 'Sharpe ratio',\n 'VaR', 'ES', 'Avg. DD', 'MDD']\n t.columns = ['performance']\n return t.T\n# ----------------------------------------------------------------------------\n\n\n# function portfolio_risk\ndef portfolio_risk(data_corr, data_vol, data_ratio):\n import numpy as np\n array_corr = data_corr.to_numpy()\n array_vol = np.diag(data_vol)\n array_cov = np.dot(np.dot(array_vol, array_corr), array_vol)\n array_ratio = np.array(data_ratio)\n return np.sqrt(\n np.dot(np.dot(array_ratio, array_cov), array_ratio.transpose())\n )\n# ----------------------------------------------------------------------------\n\n\n# function period_4_plot\ndef period_4_plot(start, end, n):\n import pandas as pd\n df = pd.DataFrame([[start, n], [end, n]])\n df[0] = pd.to_datetime(df[0])\n df.set_index(0, drop=True, inplace=True)\n return(df)\n# ----------------------------------------------------------------------------\n"
] | [
[
"numpy.diag",
"numpy.dot",
"pandas.to_datetime",
"numpy.sqrt",
"pandas.DataFrame",
"numpy.exp",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
dapopov-st/python-youtube-code | [
"770c9291988898f259ad28bbab5989acee8fb830"
] | [
"AI-plays-2048/game_ai.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\n\nNUMBER_OF_MOVES = 4\nSAMPLE_COUNT = 50\n\nSPM_SCALE_PARAM = 10\nSL_SCALE_PARAM = 4\nSEARCH_PARAM = 200\n\nfrom game_functions import initialize_game, random_move,\\\n move_down, move_left,\\\n move_right, move_up,\\\n check_for_win, add_new_tile\n\n \n\ndef get_search_params(move_number):\n searches_per_move = SPM_SCALE_PARAM * (1+(move_number // SEARCH_PARAM))\n search_length = SL_SCALE_PARAM * (1+(move_number // SEARCH_PARAM))\n return searches_per_move, search_length\n\ndef ai_move(board, searches_per_move, search_length):\n possible_first_moves = [move_left, move_up, move_down, move_right]\n first_move_scores = np.zeros(NUMBER_OF_MOVES)\n for first_move_index in range(NUMBER_OF_MOVES):\n first_move_function = possible_first_moves[first_move_index]\n board_with_first_move, first_move_made, first_move_score = first_move_function(board)\n if first_move_made:\n board_with_first_move = add_new_tile(board_with_first_move)\n first_move_scores[first_move_index] += first_move_score\n else:\n continue\n for _ in range(searches_per_move):\n move_number = 1\n search_board = np.copy(board_with_first_move)\n game_valid = True\n while game_valid and move_number < search_length:\n search_board, game_valid, score = random_move(search_board)\n if game_valid:\n search_board = add_new_tile(search_board)\n first_move_scores[first_move_index] += score\n move_number += 1\n best_move_index = np.argmax(first_move_scores)\n best_move = possible_first_moves[best_move_index]\n search_board, game_valid, score = best_move(board)\n return search_board, game_valid\n\ndef ai_play(board):\n move_number = 0\n valid_game = True\n while valid_game:\n move_number += 1\n number_of_simulations, search_length = get_search_params(move_number)\n board, valid_game = ai_move(board, number_of_simulations, search_length)\n if valid_game:\n board = add_two(board)\n if check_for_win(board):\n valid_game = False\n print(board)\n print(move_number)\n print(board)\n return np.amax(board)\n\ndef ai_plot(move_func):\n tick_locations = np.arange(1, 12)\n final_scores = []\n for _ in range(SAMPLE_COUNT):\n print('thing is ', _)\n board = initialize_game()\n game_is_win = ai(board)\n final_scores.append(game_is_win)\n all_counts = np.zeros(11)\n unique, counts = np.unique(np.array(final_scores), return_counts=True)\n unique = np.log2(unique).astype(int)\n index = 0\n\n for tick in tick_locations:\n if tick in unique:\n all_counts[tick-1] = counts[index]\n index += 1\n\n plt.bar(tick_locations, all_counts)\n plt.xticks(tick_locations, np.power(2, tick_locations))\n plt.xlabel(\"Score of Game\", fontsize = 24)\n plt.ylabel(f\"Frequency per {SAMPLE_COUNT} runs\", fontsize = 24)\n plt.show()\n\n\n\n\t\n"
] | [
[
"numpy.amax",
"numpy.log2",
"numpy.power",
"numpy.arange",
"numpy.copy",
"numpy.argmax",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wangxiang2713/tvm | [
"0467539b35fe4ab6b577dc60c627f9923e584c5f"
] | [
"tests/python/frontend/onnx/test_forward.py"
] | [
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport glob\nimport os\nimport re\n\nimport numpy as np\nimport pytest\nimport scipy\nimport torch\nimport torchvision\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\n\nimport onnx\nfrom onnx import TensorProto, helper, mapping, numpy_helper\n\n\ndef get_input_data_shape_dict(graph_def, input_data):\n if isinstance(input_data, list):\n input_names = {}\n shape_dict = {}\n for i, _ in enumerate(input_data):\n input_names[i] = graph_def.graph.input[i].name\n shape_dict[input_names[i]] = input_data[i].shape\n else:\n input_names = graph_def.graph.input[0].name\n shape_dict = {input_names: input_data.shape}\n\n return input_names, shape_dict\n\n\ndef get_tvm_output_with_vm(\n graph_def,\n input_data,\n target,\n dev,\n opset=None,\n freeze_params=False,\n convert_to_static=False,\n convert_config=None,\n):\n \"\"\"Generic function to execute and get tvm output with vm executor\"\"\"\n if not isinstance(input_data, list):\n input_data = [input_data]\n _, shape_dict = get_input_data_shape_dict(graph_def, input_data)\n\n mod, params = relay.frontend.from_onnx(\n graph_def,\n shape_dict,\n opset=opset,\n freeze_params=freeze_params,\n convert_config=convert_config,\n )\n\n if convert_to_static:\n mod = relay.transform.DynamicToStatic()(mod)\n\n result = relay.create_executor(\"vm\", mod=mod, device=dev, target=target).evaluate()(\n *input_data, **params\n )\n if isinstance(result, tvm.runtime.NDArray):\n return result.numpy()\n return [r.numpy() for r in result]\n\n\ndef get_tvm_output(\n graph_def,\n input_data,\n target,\n dev,\n output_shape=None,\n output_dtype=\"float32\",\n opset=None,\n opt_level=1,\n convert_config=None,\n):\n \"\"\"Generic function to execute and get tvm output\"\"\"\n # TODO: Resolve the issues and remove the following lines\n input_names, shape_dict = get_input_data_shape_dict(graph_def, input_data)\n\n mod, params = relay.frontend.from_onnx(\n graph_def, shape_dict, opset=opset, convert_config=convert_config\n )\n\n with tvm.transform.PassContext(opt_level=opt_level):\n graph, lib, params = relay.build(mod, target, params=params)\n\n m = graph_executor.create(graph, lib, dev)\n # set inputs\n if isinstance(input_data, list):\n for i, e in enumerate(input_names):\n # Its possible for some onnx inputs to not be needed in the tvm\n # module, confirm its present before setting.\n try:\n m.set_input(input_names[i], tvm.nd.array(input_data[i].astype(input_data[i].dtype)))\n except:\n continue\n else:\n m.set_input(input_names, tvm.nd.array(input_data.astype(input_data.dtype)))\n\n m.set_input(**params)\n # execute\n m.run()\n # get outputs\n if isinstance(output_shape, list):\n tvm_output_list = []\n for i, _ in enumerate(output_shape):\n tvm_output = m.get_output(i)\n tvm_output_list.append(tvm_output.numpy())\n return tvm_output_list\n else:\n tvm_output = m.get_output(0)\n return tvm_output.numpy()\n\n\ndef get_onnxruntime_output(model, inputs):\n import onnxruntime.backend\n\n rep = onnxruntime.backend.prepare(model.SerializeToString(), \"CPU\")\n if isinstance(inputs, list) and len(inputs) == 1:\n inp = inputs[0]\n else:\n inp = inputs\n output = rep.run(inp)\n # Unpack output if there's only a single value.\n if len(output) == 1:\n output = output[0]\n return output\n\n\ndef verify_with_ort_with_inputs(\n model,\n inputs,\n out_shape=None,\n target=None,\n dev=None,\n use_vm=False,\n opset=None,\n freeze_params=False,\n convert_to_static=False,\n dtype=\"float32\",\n rtol=1e-5,\n atol=1e-5,\n apply_softmax=False,\n opt_level=1,\n convert_config=None,\n):\n if opset is not None:\n model.opset_import[0].version = opset\n\n ort_out = get_onnxruntime_output(model, inputs)\n\n if use_vm:\n tvm_out = get_tvm_output_with_vm(\n model,\n inputs,\n target,\n dev,\n opset=opset,\n freeze_params=freeze_params,\n convert_to_static=convert_to_static,\n convert_config=convert_config,\n )\n else:\n tvm_out = get_tvm_output(\n model,\n inputs,\n target,\n dev,\n out_shape,\n dtype,\n opset=opset,\n opt_level=opt_level,\n convert_config=convert_config,\n )\n if not isinstance(tvm_out, list):\n tvm_out = [tvm_out]\n if not isinstance(ort_out, list):\n ort_out = [ort_out]\n for tvm_val, ort_val in zip(tvm_out, ort_out):\n if apply_softmax:\n ort_val = scipy.special.softmax(ort_val)\n tvm_val = scipy.special.softmax(tvm_val)\n tvm.testing.assert_allclose(ort_val, tvm_val, rtol=rtol, atol=atol)\n assert ort_val.dtype == tvm_val.dtype\n\n\ndef verify_with_ort(\n model,\n input_shapes,\n out_shape=None,\n target=None,\n dev=None,\n use_vm=False,\n opset=None,\n freeze_params=False,\n convert_to_static=False,\n dtype=\"float32\",\n rtol=1e-5,\n atol=1e-5,\n):\n inputs = [np.random.uniform(size=ishape).astype(dtype) for ishape in input_shapes]\n verify_with_ort_with_inputs(\n model,\n inputs,\n out_shape=out_shape,\n target=target,\n dev=dev,\n use_vm=use_vm,\n opset=opset,\n freeze_params=freeze_params,\n convert_to_static=convert_to_static,\n dtype=dtype,\n rtol=rtol,\n atol=atol,\n )\n\n\ndef quantize_and_verify_with_ort(onnx_model, input_names, input_shapes, target, dev):\n from onnxruntime.quantization import CalibrationDataReader, QuantType, quantize_static\n\n input_arrays = [np.random.random(shape).astype(\"float32\") for shape in input_shapes]\n\n class RandomDataReader(CalibrationDataReader):\n def __init__(self, n=10):\n input_dict = dict(zip(input_names, input_shapes))\n self.data = iter(\n [\n {\n name: np.random.random(shape).astype(\"float32\")\n for name, shape in input_dict.items()\n }\n for _ in range(n)\n ]\n )\n\n def get_next(self):\n return next(self.data, None)\n\n d = tvm.contrib.utils.tempdir()\n model_fp32 = os.path.join(d.temp_dir, \"model.onnx\")\n onnx.save_model(onnx_model, model_fp32)\n model_quant = os.path.join(d.temp_dir, \"model.quant.onnx\")\n quantized_model = quantize_static(model_fp32, model_quant, RandomDataReader())\n # opt_level=1 will cause error with qnn lowering\n model = onnx.load(model_quant)\n verify_with_ort_with_inputs(\n model, input_arrays, opt_level=2, target=target, dev=dev, use_vm=True\n )\n\n\ndef make_constant_node(name, data_type, dims, vals):\n return helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[name],\n value=helper.make_tensor(name=name, data_type=data_type, dims=dims, vals=vals),\n )\n\n\ndef is_version_greater_than(ver):\n return \"\".join(re.findall(r\"(\\d+\\.)(\\d+\\.)(\\d)\", onnx.__version__)[0]) > \"\".join(\n re.findall(r\"(\\d+\\.)(\\d+\\.)(\\d)\", ver)[0]\n )\n\n\[email protected]_targets\ndef test_reshape(target, dev):\n in_shape = (4, 3, 3, 4)\n ref_shape = (6, 2, 4, 3)\n\n ref_array = np.array(ref_shape)\n ref_node = onnx.helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[\"ref_in\"],\n value=onnx.helper.make_tensor(\n name=\"const_tensor\",\n data_type=onnx.TensorProto.INT32,\n dims=ref_array.shape,\n vals=ref_array.flatten().astype(int),\n ),\n )\n reshape_node = helper.make_node(\"Reshape\", [\"in\", \"ref_in\"], [\"out\"])\n\n graph = helper.make_graph(\n [ref_node, reshape_node],\n \"reshape_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(ref_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"reshape_test\")\n\n x = np.random.uniform(size=in_shape).astype(\"int32\")\n tvm_out = get_tvm_output(model, x, target, dev, ref_shape, \"float32\")\n tvm.testing.assert_allclose(ref_shape, tvm_out.shape)\n\n\[email protected]_targets\ndef test_double_reshape(target, dev):\n in_shape = (4, 3, 3, 4)\n ref_shape = (6, 2, 4, 3)\n\n ref_array = np.array(ref_shape)\n ref_node = onnx.helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[\"ref_in\"],\n value=onnx.helper.make_tensor(\n name=\"const_tensor\",\n data_type=onnx.TensorProto.INT32,\n dims=ref_array.shape,\n vals=ref_array.flatten().astype(int),\n ),\n )\n reshape_node1 = helper.make_node(\"Reshape\", [\"in\", \"ref_in\"], [\"out1\"])\n reshape_node2 = helper.make_node(\"Reshape\", [\"in\", \"ref_in\"], [\"out2\"])\n add_node = helper.make_node(\"Add\", [\"out1\", \"out2\"], [\"out\"])\n\n graph = helper.make_graph(\n [ref_node, reshape_node1, reshape_node2, add_node],\n \"reshape_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(ref_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"reshape_test\")\n\n x = np.random.uniform(size=in_shape).astype(\"int32\")\n tvm_out = get_tvm_output(model, x, target, dev, ref_shape, \"float32\")\n tvm.testing.assert_allclose(ref_shape, tvm_out.shape)\n\n\[email protected]_targets\ndef test_expand(target, dev):\n def _test_expand(name, data, shape, ref_data, dtype=\"int32\"):\n shape_array = np.array(shape)\n if dtype == \"int32\":\n shape_node = onnx.helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[\"shape\"],\n value=onnx.helper.make_tensor(\n name=\"const_tensor\",\n data_type=onnx.TensorProto.INT32,\n dims=shape_array.shape,\n vals=shape_array.flatten().astype(\"int32\"),\n ),\n )\n elif dtype == \"int64\":\n shape_node = onnx.helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[\"shape\"],\n value=onnx.helper.make_tensor(\n name=\"const_tensor\",\n data_type=onnx.TensorProto.INT64,\n dims=shape_array.shape,\n vals=shape_array.flatten().astype(\"int64\"),\n ),\n )\n else:\n raise \"Invalid dtype\"\n expand_node = helper.make_node(\"Expand\", [\"in\", \"shape\"], [\"out\"])\n\n graph = helper.make_graph(\n [shape_node, expand_node],\n \"expand_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(data.shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(ref_data.shape))],\n )\n\n model = helper.make_model(graph, producer_name=name)\n\n tvm_out = get_tvm_output_with_vm(model, data, target, dev, freeze_params=True)\n tvm.testing.assert_allclose(ref_data, tvm_out)\n\n in_shape = (3, 1)\n shape = (3, 4)\n data = np.random.uniform(size=in_shape).astype(np.float32)\n ref_data = np.tile(data, 4)\n _test_expand(\"expand_with_dim_unchanged_test\", data, shape, ref_data, \"int32\")\n _test_expand(\"expand_with_dim_unchanged_test\", data, shape, ref_data, \"int64\")\n\n in_shape = (3, 1)\n shape = (2, 1, 6)\n data = np.random.uniform(size=in_shape).astype(np.float32)\n ref_data = data * np.ones(shape, dtype=np.float32)\n _test_expand(\"expand_with_dim_changed_test\", data, shape, ref_data, \"int32\")\n _test_expand(\"expand_with_dim_changed_test\", data, shape, ref_data, \"int64\")\n\n\[email protected]_targets\ndef test_depth_to_space(target, dev):\n def verify_depth_to_space(inshape, outshape, mode, blockSize):\n node = onnx.helper.make_node(\n \"DepthToSpace\", inputs=[\"x\"], outputs=[\"y\"], blocksize=blockSize\n )\n\n graph = helper.make_graph(\n [node],\n \"depth_to_space_test\",\n inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(inshape))],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(outshape))],\n )\n\n model = helper.make_model(graph, producer_name=\"depth_to_space_test\")\n\n verify_with_ort(model, [inshape], [outshape], target, dev)\n\n # current onnx.checker use OpSet-1 version of DepthToSpace, which doesn't have a mode argument.\n # TO-DO, we can add mode argument to test CRD mode and DCR mode\n # in the future when we update to a newer onnx version.\n verify_depth_to_space((1, 8, 2, 3), (1, 2, 4, 6), mode=\"CRD\", blockSize=2)\n\n\[email protected]_targets\ndef test_space_to_depth(target, dev):\n def verify_space_to_depth(inshape, outshape, blockSize):\n node = onnx.helper.make_node(\n \"SpaceToDepth\", inputs=[\"x\"], outputs=[\"y\"], blocksize=blockSize\n )\n\n graph = helper.make_graph(\n [node],\n \"space_to_depth_test\",\n inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(inshape))],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(outshape))],\n )\n\n model = helper.make_model(graph, producer_name=\"space_to_depth_test\")\n\n verify_with_ort(model, [inshape], [outshape], target, dev)\n\n verify_space_to_depth((1, 1, 4, 6), (1, 4, 2, 3), 2)\n\n\[email protected]_targets\ndef test_shape(target, dev):\n in_shape = (4, 3, 3, 4)\n ref_shape = (6, 2, 4, 3)\n\n ref_array = np.array(ref_shape)\n ref_node = onnx.helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[\"ref_in\"],\n value=onnx.helper.make_tensor(\n name=\"const_tensor\",\n data_type=onnx.TensorProto.INT32,\n dims=ref_array.shape,\n vals=ref_array.flatten().astype(int),\n ),\n )\n reshape_node = helper.make_node(\"Reshape\", [\"in\", \"ref_in\"], [\"out\"])\n\n shape_node = helper.make_node(\"Shape\", [\"out\"], [\"final_out\"])\n\n graph = helper.make_graph(\n [ref_node, reshape_node, shape_node],\n \"shape_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n outputs=[helper.make_tensor_value_info(\"final_out\", TensorProto.FLOAT, list(ref_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"shape_test\")\n\n x = np.random.uniform(size=in_shape).astype(\"int32\")\n tvm_out = get_tvm_output(model, x, target, dev, ref_shape, \"int32\")\n tvm.testing.assert_allclose(ref_shape, tvm_out)\n\n\[email protected]_targets\ndef test_power(target, dev):\n def _test_power_iteration(x_shape, y_shape):\n if isinstance(y_shape, int):\n y_shape = [y_shape]\n\n x = np.random.uniform(size=x_shape).astype(np.float32)\n y = np.random.uniform(size=y_shape).astype(np.float32)\n\n np_res = np.power(x, y).astype(np.float32)\n\n res = helper.make_node(\"Pow\", [\"x\", \"y\"], [\"out\"])\n\n graph = helper.make_graph(\n [res],\n \"power_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(y_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(np_res.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"power_test\")\n\n tvm_out = get_tvm_output(model, [x, y], target, dev, np_res.shape)\n tvm.testing.assert_allclose(np_res, tvm_out, rtol=1e-5, atol=1e-5)\n\n _test_power_iteration((1, 3), (1))\n _test_power_iteration((2, 3), (2, 3))\n _test_power_iteration((2, 3), (1, 3))\n\n\[email protected]_targets\ndef test_range(target, dev):\n def verify_range(start, limit, delta, dtype):\n dtype_map = {\n \"float32\": TensorProto.FLOAT,\n \"int32\": TensorProto.INT32,\n \"int64\": TensorProto.INT64,\n }\n dtype_onnx = dtype_map[dtype]\n y = helper.make_node(\"Range\", [\"start\", \"limit\", \"delta\"], [\"output\"])\n graph = helper.make_graph(\n [y],\n \"range_test\",\n inputs=[\n helper.make_tensor_value_info(\"start\", dtype_onnx, []),\n helper.make_tensor_value_info(\"limit\", dtype_onnx, []),\n helper.make_tensor_value_info(\"delta\", dtype_onnx, []),\n ],\n outputs=[\n helper.make_tensor_value_info(\n \"output\", dtype_onnx, np.arange(start, limit, delta).shape\n )\n ],\n )\n model = helper.make_model(graph, producer_name=\"range_test\")\n inputs = [np.array(x).astype(dtype) for x in [start, limit, delta]]\n verify_with_ort_with_inputs(model, inputs, target=target, dev=dev, use_vm=True)\n\n for t in [\"float32\", \"int32\", \"int64\"]:\n verify_range(0, 10, 1, t)\n verify_range(2, 8, 2, t)\n verify_range(-3, 6, 4, t)\n verify_range(-2, -7, -1, t)\n\n\[email protected]_targets\ndef test_squeeze(target, dev):\n in_shape = (1, 3, 1, 3, 1, 1)\n out_shape = (3, 3)\n y = helper.make_node(\"Squeeze\", [\"in\"], [\"out\"], axes=[0, 2, 4, 5])\n\n graph = helper.make_graph(\n [y],\n \"squeeze_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"squeeze_test\")\n x = np.random.uniform(size=in_shape).astype(\"float32\")\n verify_with_ort_with_inputs(model, [x], [out_shape], target=target, dev=dev, opset=11)\n\n\[email protected]_targets\ndef test_flatten(target, dev):\n\n in_shape = (1, 3, 4, 4)\n axis = 1\n ref_shape = (1, 48)\n\n flatten_node = helper.make_node(\"Flatten\", [\"in\"], [\"out\"], axis=axis)\n\n graph = helper.make_graph(\n [flatten_node],\n \"flatten_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(ref_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"flatten_test\")\n verify_with_ort(model, [in_shape], target=target, dev=dev)\n\n\[email protected]_targets\ndef test_unsqueeze(target, dev):\n in_shape = (3, 3)\n axis = (0, 3, 4)\n out_shape = (1, 3, 3, 1, 1)\n y = helper.make_node(\"Unsqueeze\", [\"in\"], [\"out\"], axes=list(axis))\n\n graph = helper.make_graph(\n [y],\n \"squeeze_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"squeeze_test\")\n verify_with_ort(model, [in_shape], target=target, dev=dev, opset=11)\n\n\[email protected]_targets\ndef test_gather(target, dev):\n def verify_gather(in_shape, indices, axis, dtype):\n x = np.random.uniform(size=in_shape).astype(dtype)\n indices = np.array(indices, dtype=\"int64\")\n out_np = np.take(x, indices, axis=axis)\n\n y = helper.make_node(\"Gather\", [\"in\", \"indices\"], [\"out\"], axis=axis)\n\n graph = helper.make_graph(\n [y],\n \"gather_test\",\n inputs=[\n helper.make_tensor_value_info(\n \"in\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], list(in_shape)\n ),\n helper.make_tensor_value_info(\"indices\", TensorProto.INT64, list(indices.shape)),\n ],\n outputs=[\n helper.make_tensor_value_info(\n \"out\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], list(out_np.shape)\n )\n ],\n )\n model = helper.make_model(graph, producer_name=\"gather_test\")\n verify_with_ort_with_inputs(model, [x, indices], target=target, dev=dev, dtype=dtype)\n\n verify_gather((4,), [1], 0, \"int32\")\n verify_gather((1, 4), [0], 0, \"int32\")\n verify_gather((4,), [[[1, 0], [0, 1]]], 0, \"float32\")\n verify_gather((2, 2), [[[1, 0], [0, 1]]], 1, \"int32\")\n verify_gather((3, 3, 3), [[[1, 0]]], -1, \"int32\")\n verify_gather((4, 3, 5, 6), [[2, 1, 0, 0]], 0, \"float32\")\n\n\[email protected]_targets\ndef test_dynamic_gather(target, dev):\n dtype = \"float32\"\n in_shape = [2, 2]\n indices = 1\n axis = 1\n x = np.random.uniform(size=in_shape).astype(dtype)\n indices = np.array(indices, dtype=\"int64\")\n out_np = np.take(x, indices, axis=axis)\n\n indices = helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[\"indices\"],\n value=onnx.helper.make_tensor(\n name=\"const_indices\",\n data_type=onnx.TensorProto.INT64,\n dims=[],\n vals=[1],\n ),\n )\n y = helper.make_node(\"Gather\", [\"in\", \"indices\"], [\"out\"], axis=axis)\n\n graph = helper.make_graph(\n [indices, y],\n \"gather_test\",\n inputs=[\n helper.make_tensor_value_info(\n \"in\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], [\"?\", \"?\"]\n ),\n ],\n outputs=[\n helper.make_tensor_value_info(\n \"out\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], [\"?\"] * len(out_np.shape)\n )\n ],\n )\n model = helper.make_model(graph, producer_name=\"dynamic_gather_test\")\n\n mod, params = relay.frontend.from_onnx(model)\n\n result = relay.create_executor(\"vm\", mod=mod, device=dev, target=target).evaluate()(x, **params)\n tvm.testing.assert_allclose(out_np, result.numpy(), rtol=1e-5, atol=1e-5)\n\n\[email protected]_targets\ndef test_gatherelements(target, dev):\n def verify_gatherelements(in_shape, indices, axis):\n x = np.random.uniform(size=in_shape).astype(\"float32\")\n indices = np.array(indices, dtype=\"int32\")\n\n y = helper.make_node(\"GatherElements\", [\"data\", \"indices\"], [\"output\"], axis=axis)\n graph = helper.make_graph(\n [y],\n \"gather_elements_test\",\n inputs=[\n helper.make_tensor_value_info(\"data\", TensorProto.FLOAT, list(in_shape)),\n helper.make_tensor_value_info(\"indices\", TensorProto.INT32, list(indices.shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(in_shape))],\n )\n model = helper.make_model(graph, producer_name=\"gather_elements_test\")\n\n verify_with_ort_with_inputs(model, [x, indices], target=target, dev=dev)\n\n verify_gatherelements((4,), [3, 0, 2, 1], 0)\n verify_gatherelements((2, 2), [[1, 0], [0, 1]], 0)\n verify_gatherelements((2, 2), [[0, 0], [1, 0]], 1)\n verify_gatherelements((2, 2), [[1, 0], [0, 1]], 1)\n\n indices = [\n [[1, 0, 0], [1, 0, 1], [0, 1, 1]],\n [[1, 1, 1], [1, 2, 1], [1, 0, 1]],\n [[1, 2, 1], [1, 2, 1], [1, 2, 1]],\n ]\n\n verify_gatherelements((3, 3, 3), indices, 2)\n\n\[email protected]_targets\ndef test_scatter(target, dev):\n def verify_scatter(in_shape, indices, axis):\n x = np.random.uniform(size=in_shape).astype(\"float32\")\n indices = np.array(indices, dtype=\"int32\")\n updates = np.random.uniform(size=indices.shape).astype(\"float32\")\n\n y = helper.make_node(\n \"ScatterElements\", [\"data\", \"indices\", \"updates\"], [\"output\"], axis=axis\n )\n\n graph = helper.make_graph(\n [y],\n \"scatter_test\",\n inputs=[\n helper.make_tensor_value_info(\"data\", TensorProto.FLOAT, list(in_shape)),\n helper.make_tensor_value_info(\"indices\", TensorProto.INT32, list(indices.shape)),\n helper.make_tensor_value_info(\"updates\", TensorProto.FLOAT, list(indices.shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(in_shape))],\n )\n model = helper.make_model(graph, producer_name=\"scatter_test\")\n verify_with_ort_with_inputs(model, [x, indices, updates], target=target, dev=dev)\n\n verify_scatter((4,), [1], 0)\n verify_scatter((1, 4), [[0]], 0)\n verify_scatter((4,), [2, 3], 0)\n verify_scatter((2, 2), [[1, 0], [0, 1]], 1)\n verify_scatter((3, 3, 3), [[[-1, -3]]], -1)\n verify_scatter((4, 3, 5, 6), [[[[2, 1, 0, 0]]]], 0)\n\n\[email protected]_targets\ndef test_slice(target, dev):\n def _test_slice_iteration_v1(indata, outdata, starts, ends, axes=None):\n if axes:\n y = helper.make_node(\"Slice\", [\"in\"], [\"out\"], axes=axes, starts=starts, ends=ends)\n else:\n y = helper.make_node(\"Slice\", [\"in\"], [\"out\"], starts=starts, ends=ends)\n\n graph = helper.make_graph(\n [y],\n \"slice_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(indata.shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outdata.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"slice_test\")\n verify_with_ort_with_inputs(\n model, [indata], [outdata.shape], opset=1, target=target, dev=dev\n )\n\n def _test_slice_iteration_v10(indata, outdata, **attrs):\n starts = attrs[\"starts\"]\n ends = attrs[\"ends\"]\n axes = None if \"axes\" not in attrs else attrs[\"axes\"]\n steps = None if \"steps\" not in attrs else attrs[\"steps\"]\n starts = np.asarray(starts)\n ends = np.asarray(ends)\n inputs = [\n helper.make_tensor_value_info(\"data\", TensorProto.FLOAT, list(indata.shape)),\n helper.make_tensor_value_info(\"starts\", TensorProto.INT64, list(starts.shape)),\n helper.make_tensor_value_info(\"ends\", TensorProto.INT64, list(ends.shape)),\n ]\n initializer = [\n helper.make_tensor(\"starts\", TensorProto.INT64, list(starts.shape), starts),\n helper.make_tensor(\"ends\", TensorProto.INT64, list(ends.shape), ends),\n ]\n nodes = []\n\n if \"add_noop_to_input_attrs\" in attrs:\n\n def add_noop_to_input_attr(attr_name, attr):\n output_name = attr_name + \"_output\"\n\n ref_shape = list(np.array(attr).shape)\n ref_shape.insert(0, 1)\n ref_shape = tuple(ref_shape)\n ref_array = np.array(ref_shape)\n ref_node = onnx.helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[\"ref_in_\" + attr_name],\n value=onnx.helper.make_tensor(\n name=\"const_tensor__1_\" + attr_name,\n data_type=onnx.TensorProto.INT64,\n dims=ref_array.shape,\n vals=ref_array.flatten().astype(int),\n ),\n )\n in_shape = np.array(attr).shape\n in_array = np.array(in_shape)\n ref_node2 = onnx.helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[\"input_shape_\" + attr_name],\n value=onnx.helper.make_tensor(\n name=\"const_tensor__2_\" + attr_name,\n data_type=onnx.TensorProto.INT64,\n dims=in_array.shape,\n vals=in_array.flatten().astype(int),\n ),\n )\n\n reshape1_node = helper.make_node(\n \"Reshape\", [attr_name, \"ref_in_\" + attr_name], [\"reshape_\" + attr_name]\n )\n reshape2_node = helper.make_node(\n \"Reshape\", [\"reshape_\" + attr_name, \"input_shape_\" + attr_name], [output_name]\n )\n return [ref_node, ref_node2, reshape1_node, reshape2_node]\n\n slice_inputs = []\n for attr_name in [\"starts\", \"ends\", \"axes\", \"steps\"]:\n if attr_name not in attrs:\n continue\n if \"add_noop_to_input_attrs\" in attrs and attr_name in attrs[\"add_noop_to_input_attrs\"]:\n nodes.extend(add_noop_to_input_attr(attr_name, attrs[attr_name]))\n slice_inputs.append(attr_name + \"_output\")\n else:\n slice_inputs.append(attr_name)\n\n if axes:\n axes = np.asarray(axes)\n inputs.append(\n helper.make_tensor_value_info(\"axes\", TensorProto.INT64, list(axes.shape))\n )\n initializer.append(\n helper.make_tensor(\"axes\", TensorProto.INT64, list(axes.shape), axes)\n )\n\n if steps:\n assert axes is not None and len(axes) == len(steps)\n steps = np.asarray(steps)\n inputs.append(\n helper.make_tensor_value_info(\"steps\", TensorProto.INT64, list(axes.shape))\n )\n initializer.append(\n helper.make_tensor(\"steps\", TensorProto.INT64, list(steps.shape), steps)\n )\n\n y = helper.make_node(\"Slice\", [\"data\", *slice_inputs], [\"out\"])\n\n nodes.append(y)\n graph = helper.make_graph(\n nodes,\n \"slice_test\",\n inputs=inputs,\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outdata.shape))],\n initializer=initializer,\n )\n model = helper.make_model(graph, producer_name=\"slice_test\")\n verify_with_ort_with_inputs(\n model, [indata], opset=10, freeze_params=True, use_vm=True, target=target, dev=dev\n )\n\n x = np.random.randn(20, 10, 5).astype(np.float32)\n _test_slice_iteration_v1(x, x[0:3, 0:10], starts=(0, 0), ends=(3, 10), axes=(0, 1))\n _test_slice_iteration_v1(x, x[0:3, 0:10], starts=(0, 0), ends=(10, 3), axes=(1, 0))\n _test_slice_iteration_v1(x, x[:, :, 3:4], starts=(0, 0, 3), ends=(20, 10, 4))\n _test_slice_iteration_v1(x, x[:, 1:1000], starts=(1,), ends=(1000,), axes=(1,))\n _test_slice_iteration_v1(x, x[:, 0:-1], starts=(0,), ends=(-1,), axes=(1,))\n _test_slice_iteration_v10(x, x[0:3, 0:10], starts=(0, 0), ends=(3, 10), axes=(0, 1))\n _test_slice_iteration_v10(x, x[0:3, 0:10], starts=(0, 0), ends=(10, 3), axes=(1, 0))\n _test_slice_iteration_v10(x, x[:, :, 3:4], starts=(0, 0, 3), ends=(20, 10, 4))\n _test_slice_iteration_v10(x, x[:, 1:1000], starts=(1,), ends=(1000,), axes=(1,))\n _test_slice_iteration_v10(x, x[:, 0:-1], starts=(0,), ends=(-1,), axes=(1,))\n _test_slice_iteration_v10(\n x,\n x[0:3, 0:10],\n starts=(0, 0),\n ends=(3, 10),\n axes=(0, 1),\n add_noop_to_input_attrs=[\"starts\"],\n )\n _test_slice_iteration_v10(\n x, x[:, :, 3:4], starts=(0, 0, 3), ends=(20, 10, 4), add_noop_to_input_attrs=[\"ends\"]\n )\n _test_slice_iteration_v10(\n x, x[:, 1:1000], starts=(1,), ends=(1000,), axes=(1,), add_noop_to_input_attrs=[\"axes\"]\n )\n _test_slice_iteration_v10(\n x,\n x[:, 0:-1],\n starts=(0,),\n ends=(-1,),\n axes=(1,),\n add_noop_to_input_attrs=[\"starts\", \"ends\"],\n )\n _test_slice_iteration_v10(\n x,\n x[0:3, 0:10],\n starts=(0, 0),\n ends=(3, 10),\n axes=(0, 1),\n add_noop_to_input_attrs=[\"ends\", \"axes\"],\n )\n _test_slice_iteration_v10(\n x,\n x[:, :, 3:4],\n starts=(0, 0, 3),\n ends=(20, 10, 4),\n add_noop_to_input_attrs=[\"starts\", \"axes\"],\n )\n _test_slice_iteration_v10(\n x,\n x[:, 1:1000],\n starts=(1,),\n ends=(1000,),\n axes=(1,),\n add_noop_to_input_attrs=[\"starts\", \"ends\", \"axes\"],\n )\n x = np.random.randn(1, 1, 1, 128).astype(np.float32)\n _test_slice_iteration_v10(\n x, x, starts=(0, 0), ends=(9223372036854775807, 9223372036854775807), axes=(0, 3)\n )\n\n x = np.random.randn(4, 4).astype(np.float32)\n _test_slice_iteration_v10(\n x, x[:, 1::2], starts=(1,), ends=(9223372036854775807,), axes=(1,), steps=(2,)\n )\n _test_slice_iteration_v10(\n x,\n x[0::1, 1::2],\n starts=(0, 1),\n ends=(4, 4),\n axes=(0, 1),\n steps=(1, 2),\n )\n\n\ndef _test_onnx_op_elementwise(\n target, dev, inshape, outfunc, npargs, dtype, opname, kwargs, opset=None\n):\n indata = np.random.uniform(-1, 1, size=inshape).astype(dtype)\n outdata = outfunc(indata, **npargs)\n\n y = helper.make_node(opname, [\"in\"], [\"out\"], **kwargs)\n\n graph = helper.make_graph(\n [y],\n opname + \"_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(indata.shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outdata.shape))],\n )\n\n model = helper.make_model(graph, producer_name=opname + \"_test\")\n verify_with_ort_with_inputs(\n model, [indata], [outdata.shape], opset=opset, dtype=dtype, target=target, dev=dev\n )\n\n\[email protected]_targets\ndef test_floor(target, dev):\n _test_onnx_op_elementwise(target, dev, (2, 4, 5, 6), np.floor, {}, \"float32\", \"Floor\", {})\n\n\[email protected]_targets\ndef test_ceil(target, dev):\n _test_onnx_op_elementwise(target, dev, (2, 4, 5, 6), np.ceil, {}, \"float32\", \"Ceil\", {})\n\n\[email protected]_targets\ndef test_clip(target, dev):\n _test_onnx_op_elementwise(\n target,\n dev,\n (2, 4, 5, 6),\n np.clip,\n {\"a_min\": -1.0, \"a_max\": 1.0},\n \"float32\",\n \"Clip\",\n {\"min\": -1.0, \"max\": 1.0},\n opset=6,\n )\n\n _test_onnx_op_elementwise(\n target,\n dev,\n (2, 4, 5, 6),\n np.clip,\n {\"a_min\": -np.inf, \"a_max\": 1.0},\n \"float32\",\n \"Clip\",\n {\"max\": 1.0},\n opset=6,\n )\n\n _test_onnx_op_elementwise(\n target,\n dev,\n (2, 4, 5, 6),\n np.clip,\n {\"a_min\": -1.0, \"a_max\": np.inf},\n \"float32\",\n \"Clip\",\n {\"min\": -1.0},\n opset=6,\n )\n\n\[email protected]_targets\ndef test_clip_min_max_as_inputs(target, dev):\n input_shape = (2, 4, 5, 6)\n nodes = [\n make_constant_node(\"min\", onnx.TensorProto.FLOAT, (), [0.0]),\n make_constant_node(\"max\", onnx.TensorProto.FLOAT, (), [6.0]),\n ]\n input_names = [\"in\", \"min\", \"max\"]\n nodes.append(helper.make_node(\"Clip\", inputs=input_names, outputs=[\"out\"]))\n graph = helper.make_graph(\n nodes,\n \"clip_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(input_shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(input_shape))],\n )\n model = helper.make_model(graph, producer_name=\"clip_test\")\n\n verify_with_ort(model, [input_shape], out_shape=[input_shape], target=target, dev=dev)\n\n\[email protected]_targets\ndef test_round(target, dev):\n _test_onnx_op_elementwise(target, dev, (2, 4, 5, 6), np.round, {}, \"float32\", \"Round\", {})\n\n\ndef _test_finite_ops(target, dev, inshape, outfunc, npargs, dtype, opname, kwargs):\n indata = np.random.choice(a=[np.nan, np.inf, -np.inf, 0.5, 1.0, 0], size=inshape).astype(dtype)\n\n outdata = outfunc(indata, **npargs)\n y = helper.make_node(opname, [\"in\"], [\"out\"], **kwargs)\n\n graph = helper.make_graph(\n [y],\n opname + \"_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(indata.shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.BOOL, list(outdata.shape))],\n )\n\n model = helper.make_model(graph, producer_name=opname + \"_test\")\n verify_with_ort_with_inputs(\n model, [indata], [outdata.shape], dtype=dtype, target=target, dev=dev\n )\n\n\[email protected]_targets\ndef test_isinf(target, dev):\n _test_finite_ops(target, dev, (2, 4, 5, 6), np.isinf, {}, \"float32\", \"IsInf\", {})\n\n\[email protected]_targets\ndef test_isnan(target, dev):\n _test_finite_ops(target, dev, (2, 4, 5, 6), np.isnan, {}, \"float32\", \"IsNaN\", {})\n\n\[email protected]_targets\ndef test_gather_nd(target, dev):\n def verify_gather_nd(in_shape, indices, out_shape, dtype=\"float32\", batch_dims=0, opset=11):\n x = np.random.uniform(size=in_shape).astype(dtype)\n indices = np.array(indices, dtype=\"int64\")\n\n y = helper.make_node(\"GatherND\", [\"in\", \"indices\"], [\"out\"])\n\n if opset >= 12:\n batch_dims_attr = helper.make_attribute(\"batch_dims\", batch_dims)\n y.attribute.append(batch_dims_attr)\n\n graph = helper.make_graph(\n [y],\n \"gather_test\",\n inputs=[\n helper.make_tensor_value_info(\n \"in\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], list(in_shape)\n ),\n helper.make_tensor_value_info(\"indices\", TensorProto.INT64, list(indices.shape)),\n ],\n outputs=[\n helper.make_tensor_value_info(\n \"out\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], list(out_shape)\n )\n ],\n )\n model = helper.make_model(graph, producer_name=\"gather_test\")\n verify_with_ort_with_inputs(\n model, [x, indices], [out_shape], opset=opset, target=target, dev=dev\n )\n\n verify_gather_nd([2, 2], [[0, 0], [1, 1]], [2], \"int32\")\n verify_gather_nd([2, 2], [[1], [0]], [2, 2])\n verify_gather_nd([2, 2, 2], [[0, 1], [1, 0]], [2, 2])\n verify_gather_nd([2, 2, 2], [[[0, 1]], [[1, 0]]], [2, 1, 2])\n\n if is_version_greater_than(\"1.6.0\"):\n verify_gather_nd([2, 2, 2], [[1], [0]], [2, 2], batch_dims=1, opset=12)\n verify_gather_nd(\n (3, 2, 2, 3, 4),\n np.random.randint(low=0, high=2, size=(3, 2, 3), dtype=\"int64\"),\n (3, 2),\n batch_dims=2,\n opset=12,\n )\n\n\[email protected]_targets\ndef test_onehot(target, dev):\n indices_shape = [10]\n indices_array = np.random.randint(low=0, high=9, size=indices_shape, dtype=\"int32\")\n depth = 10\n values = np.asarray([0, 1]).astype(\"int32\")\n out_np = np.eye(depth)[indices_array.reshape(-1)]\n\n onehot_node = helper.make_node(\"OneHot\", [\"indices\", \"depth\", \"values\"], [\"out\"])\n\n graph = helper.make_graph(\n [onehot_node],\n \"onehot_test\",\n inputs=[\n helper.make_tensor_value_info(\"indices\", TensorProto.INT32, indices_shape),\n helper.make_tensor_value_info(\"depth\", TensorProto.INT32, [1]),\n helper.make_tensor_value_info(\"values\", TensorProto.INT32, values.shape),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.INT32, out_np.shape)],\n )\n\n model = helper.make_model(graph, producer_name=\"onehot_test\")\n\n # TODO(jwfromm): Replace test against np with test against onnxrt once we update versions.\n tvm_out = get_tvm_output_with_vm(\n model, [indices_array, np.array([depth]).astype(\"int32\"), values], target, dev\n )\n tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5)\n\n\[email protected]_targets\ndef test_gemm(target, dev):\n def verify_gemm(a_shape, b_shape, c_shape=None, freeze_params=False, dtype=\"float32\"):\n out_shape = [a_shape[0], b_shape[1]]\n a_array = np.random.uniform(size=a_shape).astype(dtype)\n b_array = np.random.uniform(size=b_shape).astype(dtype)\n input_names = [\"a\", \"b\"]\n ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n input_nodes = [\n helper.make_tensor_value_info(\"a\", ONNX_DTYPE, list(a_shape)),\n helper.make_tensor_value_info(\"b\", ONNX_DTYPE, list(b_shape)),\n ]\n input_values = [a_array, b_array]\n if c_shape is not None:\n c_array = np.random.uniform(size=c_shape).astype(dtype)\n input_names.append(\"c\")\n input_nodes.append(helper.make_tensor_value_info(\"c\", ONNX_DTYPE, list(c_shape)))\n input_values.append(c_array)\n\n gemm_node = helper.make_node(\"Gemm\", input_names, [\"out\"])\n\n graph = helper.make_graph(\n [gemm_node],\n \"gemm_test\",\n inputs=input_nodes,\n outputs=[helper.make_tensor_value_info(\"out\", ONNX_DTYPE, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"gemm_test\")\n atol = 1e-5\n rtol = 1e-5\n if dtype == \"float16\":\n atol = 1e-3\n rtol = 1e-3\n verify_with_ort_with_inputs(\n model,\n input_values,\n freeze_params=freeze_params,\n dtype=dtype,\n atol=atol,\n rtol=rtol,\n target=target,\n dev=dev,\n )\n\n verify_gemm(a_shape=(4, 3), b_shape=(3, 4))\n verify_gemm(a_shape=(4, 3), b_shape=(3, 4), c_shape=(4,))\n verify_gemm(a_shape=(4, 3), b_shape=(3, 4), c_shape=(4,), freeze_params=True)\n verify_gemm(a_shape=(4, 3), b_shape=(3, 4), c_shape=(4,), freeze_params=True, dtype=\"float16\")\n\n\[email protected]_targets\ndef test_matmul(target, dev):\n a_shape = (4, 3)\n b_shape = (3, 4)\n out_shape = [a_shape[0], b_shape[1]]\n\n a_array = np.random.uniform(size=a_shape).astype(\"float32\")\n b_array = np.random.uniform(size=b_shape).astype(\"float32\")\n\n mul_node = helper.make_node(\"MatMul\", [\"a\", \"b\"], [\"out\"])\n\n graph = helper.make_graph(\n [mul_node],\n \"matmul_test\",\n inputs=[\n helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"matmul_test\")\n verify_with_ort_with_inputs(model, [a_array, b_array], target=target, dev=dev)\n\n\[email protected]_targets\ndef test_batch_matmul(target, dev):\n def verify_batch_matmul(a_shape, b_shape, out_shape, convert_config=None):\n a_array = np.random.uniform(size=a_shape).astype(\"float32\")\n b_array = np.random.uniform(size=b_shape).astype(\"float32\")\n\n mul_node = helper.make_node(\"MatMul\", [\"a\", \"b\"], [\"out\"])\n\n graph = helper.make_graph(\n [mul_node],\n \"matmul_test\",\n inputs=[\n helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, out_shape)],\n )\n\n model = helper.make_model(graph, producer_name=\"matmul_test\")\n verify_with_ort_with_inputs(\n model,\n [a_array, b_array],\n use_vm=True,\n target=target,\n dev=dev,\n convert_config=convert_config,\n )\n\n verify_batch_matmul((2, 3, 4, 3), (2, 3, 3, 4), (2, 3, 4, 4))\n verify_batch_matmul((2, 4, 3), (3, 4), (2, 4, 4))\n verify_batch_matmul((2, 3, 4, 3), (3, 4), (2, 3, 4, 4))\n # Test implicit broadcasting.\n verify_batch_matmul((4, 3), (2, 3, 4), (2, 4, 4))\n verify_batch_matmul((2, 4, 3), (1, 3, 4), (2, 4, 4))\n verify_batch_matmul((1, 4, 3), (2, 3, 4), (2, 4, 4))\n verify_batch_matmul((4, 32, 16), (16, 32), (4, 32, 32))\n verify_batch_matmul((4, 32, 16, 32), (32, 16), (4, 32, 16, 16))\n # Test transb=False\n verify_batch_matmul(\n (2, 3, 4, 3),\n (2, 3, 3, 4),\n (2, 3, 4, 4),\n convert_config={\"use_nt_batch_matmul\": False},\n )\n\n\ndef verify_simple_dynamic_model(a_shape, b_shape, target, dev):\n def verify_model(model, a_shape, b_shape):\n a_array = np.random.uniform(size=a_shape).astype(\"float32\")\n b_array = np.random.uniform(size=b_shape).astype(\"float32\")\n # matmul\n out_np = np.matmul(a_array, b_array)\n # relu\n out_np[out_np < 0] = 0\n\n tvm_out = model(a_array, b_array).numpy()\n tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5)\n\n mul_node = helper.make_node(\"MatMul\", [\"a\", \"b\"], [\"out\"])\n relu_node = helper.make_node(\"Relu\", [\"out\"], [\"relu\"])\n\n a_array = np.random.uniform(size=a_shape).astype(\"float32\")\n b_array = np.random.uniform(size=b_shape).astype(\"float32\")\n # matmul\n out_np = np.matmul(a_array, b_array)\n\n graph = helper.make_graph(\n [mul_node, relu_node],\n \"matmul_test\",\n inputs=[\n helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"relu\", TensorProto.FLOAT, list(out_np.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"matmul_test\")\n\n a_anys = [relay.Any()] * len(a_shape)\n b_anys = [relay.Any()] * len(b_shape)\n\n mod, params = relay.frontend.from_onnx(model, {\"a\": a_anys, \"b\": b_anys})\n model = relay.create_executor(\"vm\", mod=mod, device=dev, target=target).evaluate()\n verify_model(model, a_shape, b_shape)\n verify_model(model, [a * 2 for a in a_shape], [b * 2 for b in b_shape])\n verify_model(model, [a * 3 for a in a_shape], [b * 3 for b in b_shape])\n\n\n# TODO(mbrookhart, electriclilies): Add CUDA as a target once batch matmul is fixed\[email protected]_targets(\"llvm\")\ndef test_batch_matmul_dynamic_model(target, dev):\n verify_simple_dynamic_model((2, 3, 4, 3), (2, 3, 3, 4), target, dev)\n verify_simple_dynamic_model((2, 4, 3), (3, 4), target, dev)\n verify_simple_dynamic_model((2, 3, 4, 3), (3, 4), target, dev)\n\n\[email protected]_targets\ndef test_lrn(target, dev):\n def verify_lrn(shape, nsize, dtype, alpha=None, beta=None, bias=None):\n in_array = np.random.uniform(size=shape).astype(dtype)\n\n if alpha == None and beta == None and bias == None:\n alpha = 0.0001\n beta = 0.75\n bias = 1.0\n node = onnx.helper.make_node(\"LRN\", inputs=[\"in\"], outputs=[\"out\"], size=nsize)\n else:\n node = onnx.helper.make_node(\n \"LRN\", inputs=[\"in\"], outputs=[\"out\"], alpha=alpha, beta=beta, bias=bias, size=nsize\n )\n\n graph = helper.make_graph(\n [node],\n \"lrn_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(shape))],\n )\n model = helper.make_model(graph, producer_name=\"lrn_test\")\n verify_with_ort_with_inputs(model, [in_array], target=target, dev=dev)\n\n verify_lrn((5, 5, 5, 5), 3, \"float32\")\n verify_lrn((5, 5, 5, 5), 3, \"float32\", alpha=0.0002, beta=0.5, bias=2.0)\n\n\[email protected]_targets\ndef test_instance_norm(target, dev):\n def verify_instance_norm(shape, axis=1):\n x = np.random.randn(*shape).astype(np.float32)\n gamma = np.random.randn(shape[1]).astype(np.float32)\n beta = np.random.randn(shape[1]).astype(np.float32)\n epsilon = 1e-5\n\n node = onnx.helper.make_node(\n \"InstanceNormalization\",\n inputs=[\"x\", \"gamma\", \"beta\"],\n outputs=[\"y\"],\n epsilon=epsilon,\n )\n graph = helper.make_graph(\n [node],\n \"instance_norm_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(shape)),\n helper.make_tensor_value_info(\"gamma\", TensorProto.FLOAT, (shape[1],)),\n helper.make_tensor_value_info(\"beta\", TensorProto.FLOAT, (shape[1],)),\n ],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(shape))],\n )\n model = helper.make_model(graph, producer_name=\"instance_norm_test\")\n verify_with_ort_with_inputs(\n model, [x, gamma, beta], out_shape=[shape], target=target, dev=dev\n )\n\n verify_instance_norm((2, 3, 4, 5))\n verify_instance_norm((32, 64, 80, 64))\n verify_instance_norm((8, 6, 5))\n verify_instance_norm((8, 7, 6, 5, 4))\n\n\[email protected]_targets\ndef test_upsample_nearest(target, dev):\n scale = 2\n in_shape = (1, 1, 3, 3)\n out_shape = (1, 1, 3 * scale, 3 * scale)\n y = helper.make_node(\"Upsample\", [\"in\"], [\"out\"], mode=\"nearest\", scales=[1.0, 1.0, 2.0, 2.0])\n\n in_array = np.random.uniform(size=in_shape).astype(np.float32)\n\n graph = helper.make_graph(\n [y],\n \"upsample_nearest_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"upsample_nearest_test\")\n verify_with_ort_with_inputs(model, [in_array], [out_shape], opset=7, target=target, dev=dev)\n\n\[email protected]_targets\ndef test_upsample3d_nearest(target, dev):\n scale = 2\n in_shape = (1, 1, 3, 3, 3)\n out_shape = (1, 1, 3 * scale, 3 * scale, 3 * scale)\n y = helper.make_node(\n \"Upsample\", [\"in\"], [\"out\"], mode=\"nearest\", scales=[1.0, 1.0, 2.0, 2.0, 2.0]\n )\n\n in_array = np.random.uniform(size=in_shape).astype(np.float32)\n\n graph = helper.make_graph(\n [y],\n \"upsample_nearest_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"upsample_nearest_test\")\n # Upsample is deprecated after opset 9\n verify_with_ort_with_inputs(model, [in_array], [out_shape], opset=7, target=target, dev=dev)\n\n\[email protected]_targets\ndef test_upsample_bilinear(target, dev):\n scale = 2\n in_shape = (1, 1, 3, 3)\n out_shape = (1, 1, 3 * scale, 3 * scale)\n y = helper.make_node(\"Upsample\", [\"in\"], [\"out\"], mode=\"linear\", scales=[1.0, 1.0, 2.0, 2.0])\n\n in_array = np.random.uniform(size=in_shape).astype(np.float32)\n\n graph = helper.make_graph(\n [y],\n \"upsample_bilinear_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"upsample_bilinear_test\")\n verify_with_ort_with_inputs(model, [in_array], [out_shape], opset=7, target=target, dev=dev)\n\n\[email protected]_targets\ndef test_upsample3d_trilinear(target, dev):\n scale = 2\n in_shape = (1, 1, 3, 3, 3)\n out_shape = (1, 1, 3 * scale, 3 * scale, 3 * scale)\n y = helper.make_node(\"Upsample\", [\"in\", \"scales\"], [\"out\"], mode=\"linear\")\n scales = [1.0, 1.0, 2.0, 2.0, 2.0]\n in_array = np.random.uniform(size=in_shape).astype(np.float32)\n out_array = tvm.topi.testing.resize3d_python(\n in_array,\n (scale, scale, scale),\n \"NCDHW\",\n \"linear\",\n coordinate_transformation_mode=\"asymmetric\",\n )\n\n ref_array = np.array(scales)\n ref_node = helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[\"scales\"],\n value=onnx.helper.make_tensor(\n name=\"const_tensor\",\n data_type=TensorProto.FLOAT,\n dims=ref_array.shape,\n vals=ref_array.flatten().astype(float),\n ),\n )\n\n graph = helper.make_graph(\n [ref_node, y],\n \"upsample_trilinear_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(in_shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"upsample_trilinear_test\")\n # TODO(jwfromm): Trilinear upsampling not supported in 1.0.0 onnxruntime.\n # Replace topi comparison with verify_with_ort once we update.\n tvm_out = get_tvm_output(model, in_array, target, dev, out_shape, \"float32\")\n tvm.testing.assert_allclose(out_array, tvm_out, rtol=1e-5, atol=1e-5)\n\n\[email protected]_targets\ndef test_softmax(target, dev):\n def verify_softmax(inshape, axis):\n opname = \"Softmax\"\n indata = np.random.uniform(size=inshape).astype(np.float32)\n outshape = inshape\n y = helper.make_node(opname, [\"in\"], [\"out\"])\n if axis is not None:\n axis_attr = helper.make_attribute(\"axis\", axis)\n y.attribute.append(axis_attr)\n\n graph = helper.make_graph(\n [y],\n opname + \"_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(indata.shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outshape))],\n )\n\n model = helper.make_model(graph, producer_name=opname + \"_test\")\n verify_with_ort_with_inputs(model, [indata], target=target, dev=dev)\n\n verify_softmax((1, 10), None)\n verify_softmax((1, 10), 1)\n\n\[email protected]_targets\ndef test_forward_min(target, dev):\n def verify_min(input_dim):\n dtype = \"float32\"\n\n a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n a_np2 = np.random.uniform(size=input_dim).astype(dtype)\n a_np3 = np.random.uniform(size=input_dim).astype(dtype)\n\n min_node = helper.make_node(\"Min\", [\"a_np1\", \"a_np2\", \"a_np3\"], [\"out\"])\n\n graph = helper.make_graph(\n [min_node],\n \"Min_test\",\n inputs=[\n helper.make_tensor_value_info(\"a_np1\", TensorProto.FLOAT, list(input_dim)),\n helper.make_tensor_value_info(\"a_np2\", TensorProto.FLOAT, list(input_dim)),\n helper.make_tensor_value_info(\"a_np3\", TensorProto.FLOAT, list(input_dim)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(input_dim))],\n )\n\n model = helper.make_model(graph, producer_name=\"Min_test\")\n verify_with_ort_with_inputs(model, [a_np1, a_np2, a_np3], target=target, dev=dev)\n\n verify_min((1, 3, 20, 20))\n verify_min((20, 20))\n\n\[email protected]_targets\ndef test_forward_max(target, dev):\n def verify_max(input_dim):\n dtype = \"float32\"\n\n a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n a_np2 = np.random.uniform(size=input_dim).astype(dtype)\n a_np3 = np.random.uniform(size=input_dim).astype(dtype)\n\n max_node = helper.make_node(\"Max\", [\"a_np1\", \"a_np2\", \"a_np3\"], [\"out\"])\n\n graph = helper.make_graph(\n [max_node],\n \"Max_test\",\n inputs=[\n helper.make_tensor_value_info(\"a_np1\", TensorProto.FLOAT, list(input_dim)),\n helper.make_tensor_value_info(\"a_np2\", TensorProto.FLOAT, list(input_dim)),\n helper.make_tensor_value_info(\"a_np3\", TensorProto.FLOAT, list(input_dim)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(input_dim))],\n )\n\n model = helper.make_model(graph, producer_name=\"Max_test\")\n verify_with_ort_with_inputs(model, [a_np1, a_np2, a_np3], target=target, dev=dev)\n\n verify_max((1, 3, 20, 20))\n verify_max((20, 20))\n\n\[email protected]_targets\ndef test_forward_mean(target, dev):\n def verify_mean(input_dim):\n dtype = \"float32\"\n\n a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n a_np2 = np.random.uniform(size=input_dim).astype(dtype)\n a_np3 = np.random.uniform(size=input_dim).astype(dtype)\n\n mean_node = helper.make_node(\"Mean\", [\"a_np1\", \"a_np2\", \"a_np3\"], [\"out\"])\n\n graph = helper.make_graph(\n [mean_node],\n \"Mean_test\",\n inputs=[\n helper.make_tensor_value_info(\"a_np1\", TensorProto.FLOAT, list(input_dim)),\n helper.make_tensor_value_info(\"a_np2\", TensorProto.FLOAT, list(input_dim)),\n helper.make_tensor_value_info(\"a_np3\", TensorProto.FLOAT, list(input_dim)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(input_dim))],\n )\n\n model = helper.make_model(graph, producer_name=\"Mean_test\")\n verify_with_ort_with_inputs(model, [a_np1, a_np2, a_np3], target=target, dev=dev)\n\n verify_mean((1, 3, 20, 20))\n verify_mean((20, 20))\n\n\[email protected]_targets\ndef test_forward_hardsigmoid(target, dev):\n def verify_hardsigmoid(input_dim, alpha, beta):\n dtype = \"float32\"\n\n a_np1 = np.random.uniform(size=input_dim).astype(dtype)\n\n hardsigmoid_node = helper.make_node(\n \"HardSigmoid\", [\"a_np1\"], [\"out\"], alpha=alpha, beta=beta\n )\n\n graph = helper.make_graph(\n [hardsigmoid_node],\n \"HardSigmoid_test\",\n inputs=[helper.make_tensor_value_info(\"a_np1\", TensorProto.FLOAT, list(input_dim))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(input_dim))],\n )\n\n model = helper.make_model(graph, producer_name=\"HardSigmoid_test\")\n verify_with_ort_with_inputs(model, [a_np1], target=target, dev=dev)\n\n verify_hardsigmoid((1, 3, 20, 20), 0.5, 0.6)\n verify_hardsigmoid((20, 20), 0.3, 0.4)\n\n\n# TODO (mbrookhart, electriclilies) Fix argmin on GPU and enable this test\[email protected]_failing_targets(\"cuda\")\[email protected]_targets\ndef test_forward_arg_min_max(target, dev):\n def verify_argreduce(input_dim, op_name, axis=None, keepdims=None):\n a_np1 = np.random.uniform(-10, 10, input_dim).astype(np.int32)\n out_shape = list(a_np1.shape)\n def_axis = axis if axis is not None else 0\n if keepdims == 1 or keepdims == None:\n out_shape[def_axis] = 1\n else:\n out_shape.pop(def_axis)\n\n node = onnx.helper.make_node(op_name, inputs=[\"a_np1\"], outputs=[\"out\"])\n\n if keepdims is not None:\n keepdims_attr = helper.make_attribute(\"keepdims\", keepdims)\n node.attribute.append(keepdims_attr)\n if axis is not None:\n axis_attr = helper.make_attribute(\"axis\", axis)\n node.attribute.append(axis_attr)\n\n graph = helper.make_graph(\n [node],\n \"argreduce_test\",\n inputs=[helper.make_tensor_value_info(\"a_np1\", TensorProto.INT32, list(a_np1.shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.INT64, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"argreduce_test\")\n verify_with_ort_with_inputs(model, [a_np1], target=target, dev=dev)\n\n \"\"\"Verify argmin and argmax\"\"\"\n verify_argreduce([3, 4, 4], \"ArgMin\")\n verify_argreduce([3, 4, 4], \"ArgMax\")\n verify_argreduce([3, 4, 4], \"ArgMin\", axis=1)\n verify_argreduce([3, 4, 4], \"ArgMax\", axis=0)\n verify_argreduce([3, 4, 4], \"ArgMin\", keepdims=0)\n verify_argreduce([3, 4, 4], \"ArgMax\", keepdims=1)\n for axis in [None, 0, 1, 2]:\n for keepdims in [None, True, False]:\n verify_argreduce([3, 4, 4], \"ArgMin\", axis, keepdims)\n verify_argreduce([3, 4, 4], \"ArgMax\", axis, keepdims)\n\n\[email protected]_targets\ndef test_constantofshape(target, dev):\n def verify_constantofshape(input_dim, value, dtype):\n fill_node = helper.make_node(\n \"ConstantOfShape\",\n [\"input\"],\n [\"output\"],\n value=helper.make_tensor(\n \"value\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], (1,), (value,)\n ),\n )\n\n inputs = [helper.make_tensor_value_info(\"input\", TensorProto.INT64, [len(input_dim)])]\n\n graph = helper.make_graph(\n [fill_node],\n \"fill_test\",\n inputs,\n outputs=[\n helper.make_tensor_value_info(\n \"output\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], input_dim\n )\n ],\n )\n\n model = helper.make_model(graph, producer_name=\"fill_test\")\n input_np = np.array(input_dim).astype(\"int64\")\n verify_with_ort_with_inputs(model, [input_np], use_vm=True, target=target, dev=dev)\n\n verify_constantofshape((2, 3, 4, 5), 10, \"float32\")\n verify_constantofshape((3, 3), 0, \"int32\")\n verify_constantofshape((1, 2, 3), -1, \"float32\")\n\n\[email protected]_targets\ndef test_pad(target, dev):\n def verify_pad(indata, pads, mode=\"constant\", value=0.0):\n indata = np.array(indata).astype(np.float32)\n # numpy expect result\n len_dim = len(pads) // 2\n np_pads = [(pads[i], pads[i + len_dim]) for i in range(len_dim)]\n # onnx graph\n if mode in [\"edge\", \"reflect\"]:\n outdata = np.pad(indata, pad_width=np_pads, mode=mode)\n node = helper.make_node(\n \"Pad\",\n inputs=[\"input\"],\n outputs=[\"output\"],\n mode=mode,\n pads=pads,\n )\n else:\n outdata = np.pad(indata, pad_width=np_pads, mode=\"constant\", constant_values=value)\n node = helper.make_node(\n \"Pad\", inputs=[\"input\"], outputs=[\"output\"], mode=\"constant\", pads=pads, value=value\n )\n graph = helper.make_graph(\n [node],\n \"pad_test\",\n inputs=[helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(indata.shape))],\n outputs=[\n helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(outdata.shape))\n ],\n )\n model = helper.make_model(graph, producer_name=\"pad_test\")\n verify_with_ort_with_inputs(\n model, [indata], [outdata.shape], dtype=\"float32\", opset=2, target=target, dev=dev\n )\n\n def verify_pad_v11(indata, pads, mode=\"constant\", value=0.0):\n indata = np.array(indata).astype(np.float32)\n # numpy expect result\n len_dim = len(pads) // 2\n np_pads = [(pads[i], pads[i + len_dim]) for i in range(len_dim)]\n pads = np.array(pads)\n # onnx graph\n if mode in [\"edge\", \"reflect\"]:\n inputs = [indata]\n outdata = np.pad(indata, pad_width=np_pads, mode=mode)\n node = helper.make_node(\"Pad\", inputs=[\"input\", \"pads\"], outputs=[\"output\"], mode=mode)\n graph = helper.make_graph(\n [node],\n \"pad_test\",\n inputs=[\n helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(indata.shape)),\n helper.make_tensor_value_info(\"pads\", TensorProto.INT64, (len(pads),)),\n ],\n initializer=[helper.make_tensor(\"pads\", TensorProto.INT64, (len(pads),), pads)],\n outputs=[\n helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(outdata.shape))\n ],\n )\n else:\n inputs = [indata]\n outdata = np.pad(indata, pad_width=np_pads, mode=\"constant\", constant_values=value)\n node = helper.make_node(\n \"Pad\",\n inputs=[\"input\", \"pads\", \"constant_value\"],\n outputs=[\"output\"],\n mode=\"constant\",\n )\n graph = helper.make_graph(\n [node],\n \"pad_test\",\n inputs=[\n helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(indata.shape)),\n helper.make_tensor_value_info(\"pads\", TensorProto.INT64, (len(pads),)),\n helper.make_tensor_value_info(\"constant_value\", TensorProto.FLOAT, (1,)),\n ],\n initializer=[\n helper.make_tensor(\"pads\", TensorProto.INT64, (len(pads),), pads),\n helper.make_tensor(\"constant_value\", TensorProto.FLOAT, (1,), [value]),\n ],\n outputs=[\n helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, list(outdata.shape))\n ],\n )\n model = helper.make_model(graph, producer_name=\"pad_test\")\n verify_with_ort_with_inputs(model, inputs, opset=11, use_vm=True, target=target, dev=dev)\n\n verify_pad(np.random.randn(2, 2).astype(np.float32), [0, 1, 0, 0], \"constant\", 0.0)\n verify_pad(np.random.randn(2, 3).astype(np.float32), [1, 0, 0, 1], \"constant\", 0.0)\n verify_pad(np.random.randn(3, 2).astype(np.float32), [0, 0, 1, 0], \"constant\", 5.0)\n verify_pad(np.random.randn(1, 3, 4, 5).astype(np.float32), [0, 0, 1, 1, 0, 0, 1, 1], \"edge\")\n verify_pad(np.random.randn(1, 3, 4, 5).astype(np.float32), [0, 0, 1, 1, 0, 0, 1, 1], \"reflect\")\n\n verify_pad_v11(np.random.randn(2, 2).astype(np.float32), [0, 1, 0, 0], \"constant\", 0.0)\n verify_pad_v11(np.random.randn(2, 3).astype(np.float32), [1, 0, 0, 1], \"constant\", 0.0)\n verify_pad_v11(np.random.randn(3, 2).astype(np.float32), [0, 0, 1, 0], \"constant\", 5.0)\n verify_pad_v11(np.random.randn(1, 3, 4, 5).astype(np.float32), [0, 0, 1, 1, 0, 0, 1, 1], \"edge\")\n verify_pad_v11(\n np.random.randn(1, 3, 4, 5).astype(np.float32), [0, 0, 1, 1, 0, 0, 1, 1], \"reflect\"\n )\n\n\[email protected]_targets\ndef test_all_reduce_funcs(target, dev):\n def verify_reduce_func(func, data, axis, keepdims):\n inshape = data.shape\n outshape = np.sum(data, axis=axis, keepdims=keepdims == 1).shape\n\n if axis:\n node = onnx.helper.make_node(\n func, inputs=[\"x\"], outputs=[\"y\"], axes=axis, keepdims=keepdims\n )\n else:\n node = onnx.helper.make_node(func, inputs=[\"x\"], outputs=[\"y\"], keepdims=keepdims)\n\n graph = helper.make_graph(\n [node],\n \"reduce_test\",\n inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(inshape))],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(outshape))],\n )\n\n model = helper.make_model(graph, producer_name=\"reduce_test\")\n\n verify_with_ort_with_inputs(\n model,\n [data],\n [outshape],\n opset=11,\n target=target,\n dev=dev,\n rtol=1e-4,\n atol=1e-4,\n )\n\n funcs = [\n \"ReduceMax\",\n \"ReduceMean\",\n \"ReduceMin\",\n \"ReduceProd\",\n \"ReduceSum\",\n \"ReduceSumSquare\",\n \"ReduceLogSum\",\n \"ReduceLogSumExp\",\n \"ReduceL1\",\n \"ReduceL2\",\n ]\n\n for func in funcs:\n for keepdims in [True, False]:\n verify_reduce_func(\n func, np.random.randn(3, 2, 2).astype(np.float32), axis=None, keepdims=keepdims\n )\n\n verify_reduce_func(\n func, np.random.randn(3, 2, 3).astype(np.float32), axis=None, keepdims=keepdims\n )\n\n verify_reduce_func(\n func, np.random.randn(3, 3, 3).astype(np.float32), axis=(1,), keepdims=keepdims\n )\n\n verify_reduce_func(\n func, np.random.randn(3, 3, 3, 1).astype(np.float32), axis=(1, 2), keepdims=keepdims\n )\n\n verify_reduce_func(\n func, np.random.randn(3, 3, 3, 1).astype(np.float32), axis=(1,), keepdims=keepdims\n )\n\n verify_reduce_func(\n func, np.random.randn(1, 3, 4, 1).astype(np.float32), axis=(1,), keepdims=keepdims\n )\n\n\[email protected]_targets\ndef test_split(target, dev):\n def verify_split(indata, outdatas, split, axis=0, pass_split=True, opset=11):\n indata = np.array(indata).astype(np.float32)\n outdatas = [np.array(o).astype(np.float32) for o in outdatas]\n inputs = [helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(indata.shape))]\n input_names = [\"input\"]\n initializer = []\n\n if split:\n split_index = range(len(split))\n else:\n split_index = range(len(outdatas))\n\n if pass_split:\n if opset >= 13:\n input_names.append(\"split\")\n np_split = np.array(split).astype(np.int64)\n inputs.append(\n helper.make_tensor_value_info(\"split\", TensorProto.INT64, list(np_split.shape))\n )\n indata = [indata, np_split]\n initializer.append(\n helper.make_tensor(\"split\", TensorProto.INT64, list(np_split.shape), np_split)\n )\n node = helper.make_node(\n \"Split\",\n inputs=input_names,\n outputs=[\"output_{}\".format(i) for i in range(len(split_index))],\n axis=axis,\n )\n\n if pass_split and opset < 13:\n split_attr = helper.make_attribute(\"split\", split)\n node.attribute.append(split_attr)\n\n graph = helper.make_graph(\n [node],\n \"split_test\",\n inputs=inputs,\n initializer=initializer,\n outputs=[\n helper.make_tensor_value_info(\n \"output_{}\".format(i), TensorProto.FLOAT, list(outdatas[i].shape)\n )\n for i in range(len(split_index))\n ],\n )\n model = helper.make_model(graph, producer_name=\"split_test\")\n verify_with_ort_with_inputs(\n model,\n indata,\n out_shape=list(range(len(split_index))),\n opset=opset,\n target=target,\n dev=dev,\n )\n\n # 1D\n verify_split([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], [2, 2, 2], 0)\n verify_split(\n [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], [2, 2, 2], 0, False\n )\n verify_split([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [[1.0, 2.0], [3.0], [4.0, 5.0, 6.0]], [2, 1, 3], 0)\n # 2D\n verify_split(\n [[1.0, 2.0, 3.0, 4.0], [7.0, 8.0, 9.0, 10.0]],\n [[[1.0, 2.0], [7.0, 8.0]], [[3.0, 4.0], [9.0, 10.0]]],\n [2, 2],\n 1,\n )\n # Split evenly (unstack)\n verify_split([1, 2, 3], [[1], [2], [3]], False, 0, False)\n # Split a single value to a single value\n verify_split([1], [[1]], [1], pass_split=True)\n\n\[email protected]_targets\ndef test_binary_ops(target, dev):\n in_shape = (1, 2, 3, 3)\n dtype = \"float32\"\n out_shape = in_shape\n\n def verify_binary_ops(op, x, y, out_type=\"float32\"):\n z = helper.make_node(op, [\"in1\", \"in2\"], [\"out\"])\n graph = helper.make_graph(\n [z],\n \"_test\",\n inputs=[\n helper.make_tensor_value_info(\"in1\", TensorProto.FLOAT, x.shape),\n helper.make_tensor_value_info(\"in2\", TensorProto.FLOAT, y.shape),\n ],\n outputs=[\n helper.make_tensor_value_info(\n \"out\", mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(out_type)], list(out_shape)\n )\n ],\n )\n model = helper.make_model(graph, producer_name=\"_test\")\n verify_with_ort_with_inputs(model, [x, y], target=target, dev=dev)\n\n x = np.random.uniform(size=in_shape).astype(dtype)\n y = np.random.uniform(size=in_shape).astype(dtype)\n z = np.random.uniform(size=(3,)).astype(dtype)\n verify_binary_ops(\"Add\", x, y)\n verify_binary_ops(\"Add\", x, z)\n verify_binary_ops(\"Sub\", x, y)\n verify_binary_ops(\"Sub\", x, z)\n verify_binary_ops(\"Mul\", x, y)\n verify_binary_ops(\"Mul\", x, z)\n verify_binary_ops(\"Div\", x, y)\n verify_binary_ops(\"Div\", x, z)\n verify_binary_ops(\"Sum\", x, y)\n verify_binary_ops(\"Sum\", x, z)\n verify_binary_ops(\"Greater\", x, y, \"bool\")\n verify_binary_ops(\"Greater\", x, z, \"bool\")\n verify_binary_ops(\"GreaterOrEqual\", x, y, \"bool\")\n verify_binary_ops(\"GreaterOrEqual\", x, z, \"bool\")\n verify_binary_ops(\"Less\", x, y, \"bool\")\n verify_binary_ops(\"Less\", x, z, \"bool\")\n verify_binary_ops(\"LessOrEqual\", x, y, \"bool\")\n verify_binary_ops(\"LessOrEqual\", x, z, \"bool\")\n verify_binary_ops(\"Equal\", x, y, \"bool\")\n verify_binary_ops(\"Equal\", x, z, \"bool\")\n\n\[email protected]_targets\ndef test_unary_ops(target, dev):\n in_shape = (1, 2, 3, 3)\n dtype = \"float32\"\n out_shape = in_shape\n\n def verify_unary_ops(op, x, rtol=1e-5, atol=1e-5, dtype=\"float32\"):\n x = x.astype(dtype)\n ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n z = helper.make_node(op, [\"in1\"], [\"out\"])\n graph = helper.make_graph(\n [z],\n \"_test\",\n inputs=[\n helper.make_tensor_value_info(\"in1\", ONNX_DTYPE, list(in_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", ONNX_DTYPE, list(out_shape))],\n )\n model = helper.make_model(graph, producer_name=\"_test\")\n verify_with_ort_with_inputs(model, [x], rtol=rtol, atol=atol, target=target, dev=dev)\n\n x = np.random.uniform(size=in_shape)\n verify_unary_ops(\"Neg\", x)\n verify_unary_ops(\"Abs\", x)\n verify_unary_ops(\"Reciprocal\", x)\n verify_unary_ops(\"Reciprocal\", x, dtype=\"float16\")\n verify_unary_ops(\"Sqrt\", x)\n verify_unary_ops(\"Relu\", x)\n verify_unary_ops(\"Exp\", x)\n verify_unary_ops(\"Log\", x)\n verify_unary_ops(\"Log\", x)\n verify_unary_ops(\"Acos\", x)\n verify_unary_ops(\"Acosh\", x)\n verify_unary_ops(\"Asin\", x)\n verify_unary_ops(\"Asinh\", x)\n verify_unary_ops(\"Atan\", x)\n verify_unary_ops(\"Atanh\", x)\n verify_unary_ops(\"Cos\", x)\n verify_unary_ops(\"Cosh\", x)\n verify_unary_ops(\"Sin\", x)\n verify_unary_ops(\"Sinh\", x)\n verify_unary_ops(\"Tan\", x)\n verify_unary_ops(\"Tanh\", x)\n verify_unary_ops(\"Sigmoid\", x)\n verify_unary_ops(\"Softsign\", x)\n\n\[email protected]_targets\ndef test_leaky_relu(target, dev):\n def leaky_relu_x(x, alpha):\n return np.where(x >= 0, x, x * alpha)\n\n _test_onnx_op_elementwise(\n target,\n dev,\n (2, 4, 5, 6),\n leaky_relu_x,\n {\"alpha\": 0.25},\n \"float32\",\n \"LeakyRelu\",\n {\"alpha\": 0.25},\n )\n\n\[email protected]_targets\ndef test_elu(target, dev):\n def elu_x(x, alpha):\n return np.where(x > 0, x, alpha * (np.exp(x) - 1.0))\n\n _test_onnx_op_elementwise(\n target, dev, (2, 4, 5, 6), elu_x, {\"alpha\": 0.25}, \"float32\", \"Elu\", {\"alpha\": 0.25}\n )\n\n\[email protected]_targets\ndef test_selu(target, dev):\n def selu_x(x, alpha, gamma):\n return gamma * np.where(x > 0, x, alpha * (np.exp(x) - 1.0))\n\n _test_onnx_op_elementwise(\n target,\n dev,\n (2, 4, 5, 6),\n selu_x,\n {\"alpha\": 0.25, \"gamma\": 0.3},\n \"float32\",\n \"Selu\",\n {\"alpha\": 0.25, \"gamma\": 0.3},\n )\n\n\[email protected]_targets\ndef test_prelu(target, dev):\n def verify_prelu(x_shape, a_shape):\n node = helper.make_node(\"PRelu\", inputs=[\"X\", \"slope\"], outputs=[\"Y\"])\n\n graph = helper.make_graph(\n [node],\n \"prelu_test\",\n inputs=[\n helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(x_shape)),\n helper.make_tensor_value_info(\"slope\", TensorProto.FLOAT, list(a_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(x_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"prelu_test\")\n\n verify_with_ort(\n model,\n [x_shape, a_shape],\n out_shape=[list(x_shape)],\n use_vm=True,\n convert_to_static=True,\n target=target,\n dev=dev,\n )\n\n verify_prelu([3, 4, 5, 6], [1, 4, 1, 1])\n verify_prelu([1, 8, 5, 6], [1, 8, 1, 1])\n verify_prelu([2, 12, 16, 16], [1, 12, 1, 1])\n verify_prelu([2, 12, 16, 16], [1]) # Test alpha broadcasting.\n verify_prelu([3, 1], [3, 1]) # Test non NCHW workload.\n\n\[email protected]_targets\ndef test_ThresholdedRelu(target, dev):\n def ThresholdedRelu_x(x, alpha):\n out_np = np.clip(x, alpha, np.inf)\n out_np[out_np == alpha] = 0\n return out_np\n\n _test_onnx_op_elementwise(\n target,\n dev,\n (2, 4, 5, 6),\n ThresholdedRelu_x,\n {\"alpha\": 0.25},\n \"float32\",\n \"ThresholdedRelu\",\n {\"alpha\": 0.25},\n )\n\n\[email protected]_targets\ndef test_LogSoftmax(target, dev):\n _test_onnx_op_elementwise(\n target,\n dev,\n (1, 4),\n tvm.topi.testing.log_softmax_python,\n {},\n \"float32\",\n \"LogSoftmax\",\n {\"axis\": 1},\n )\n\n\ndef check_torch_conversion(model, input_size, target, dev):\n dummy_input = torch.randn(*input_size)\n file_name = \"{}.onnx\".format(model.__name__)\n # Set verbose=True for more output\n torch.onnx.export(model(), dummy_input, file_name, export_params=True, verbose=False)\n onnx_model = onnx.load(file_name)\n input_data = np.random.uniform(size=input_size).astype(\"float32\")\n verify_with_ort_with_inputs(\n onnx_model, [input_data], apply_softmax=True, target=target, dev=dev\n )\n\n\[email protected]_targets\ndef test_resnet(target, dev):\n check_torch_conversion(torchvision.models.resnet18, (1, 3, 224, 224), target, dev)\n # check_torch_conversion(torchvision.models.resnet101, (1,3,224,224))\n\n\n# def test_alexnet():\n# Torch's ONNX export does not support the adaptive pooling used by AlexNet?\n# check_torch_conversion(torchvision.models.alexnet, (1,3,224,224))\n\n# Torch's ONNX export does not support the adaptive pooling used by vgg16?\n# def test_vgg16():\n# check_torch_conversion(torchvision.models.vgg16, (1,3,224,224))\n\n# TODO(@jroesch): Update Torch + ONNX to support this import.\n# def test_squeezenet():\n# # Torch's ONNX export does not support the max pooling used by Squezenet\n# check_torch_conversion(torchvision.models.squeezenet1_0, (1,3,224,224))\n\n\[email protected]_targets\ndef test_densenet(target, dev):\n check_torch_conversion(torchvision.models.densenet161, (1, 3, 224, 224), target, dev)\n\n\[email protected]_targets\ndef test_inception(target, dev):\n check_torch_conversion(torchvision.models.inception_v3, (1, 3, 224, 224), target, dev)\n\n\n# TODO(@jroesch): Update Torch + ONNX to support this import.\n# def test_googlenet():\n# check_torch_conversion(torchvision.models.googlenet, (1,3,224,224))\n\n# TODO(@jroesch): Update Torch + ONNX to support this import.\n# def test_shufflenetv2():\n# check_torch_conversion(torchvision.models.shufflenetv2, (1,3,224,224))\n\n\[email protected]_targets\ndef test_sign(target, dev):\n def Sign_x(x):\n return np.sign(x)\n\n _test_onnx_op_elementwise(target, dev, (3, 4, 5, 6), Sign_x, {}, \"float32\", \"Sign\", {})\n\n\[email protected]_targets\ndef test_not(target, dev):\n def verify_not(indata, dtype):\n x = indata.astype(dtype)\n\n node = helper.make_node(\n \"Not\",\n inputs=[\"in\"],\n outputs=[\"out\"],\n )\n\n graph = helper.make_graph(\n [node],\n \"not_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.BOOL, list(x.shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.BOOL, list(x.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"not_test\")\n verify_with_ort_with_inputs(model, [x], target=target, dev=dev)\n\n # 2d\n verify_not(indata=(np.random.randn(3, 4) > 0), dtype=bool)\n # 3d\n verify_not(indata=(np.random.randn(3, 4, 5) > 0), dtype=bool)\n # 4d\n verify_not(indata=(np.random.randn(3, 4, 5, 6) > 0), dtype=bool)\n\n\[email protected]_targets\ndef test_and(target, dev):\n def verify_and(indata, dtype):\n x = indata[0].astype(dtype)\n y = indata[1].astype(dtype)\n outdata = np.logical_and(x, y)\n\n node = helper.make_node(\n \"And\",\n inputs=[\"in1\", \"in2\"],\n outputs=[\"out\"],\n )\n\n graph = helper.make_graph(\n [node],\n \"and_test\",\n inputs=[\n helper.make_tensor_value_info(\"in1\", TensorProto.BOOL, list(x.shape)),\n helper.make_tensor_value_info(\"in2\", TensorProto.BOOL, list(y.shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.BOOL, list(outdata.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"and_test\")\n verify_with_ort_with_inputs(model, [x, y], [outdata.shape], target=target, dev=dev)\n\n # 2d\n x = np.random.randn(3, 4) > 0\n y = np.random.randn(3, 4) > 0\n verify_and(indata=[x, y], dtype=bool)\n\n # 3d\n x = np.random.randn(3, 4, 5) > 0\n y = np.random.randn(3, 4, 5) > 0\n verify_and(indata=[x, y], dtype=bool)\n\n # 4d\n x = np.random.randn(3, 4, 5, 6) > 0\n y = np.random.randn(3, 4, 5, 6) > 0\n verify_and(indata=[x, y], dtype=bool)\n\n # 3d vs 1d\n x = np.random.randn(3, 4, 5) > 0\n y = np.random.randn(5) > 0\n verify_and(indata=[x, y], dtype=bool)\n\n # 3d vs 2d\n x = np.random.randn(3, 4, 5) > 0\n y = np.random.randn(4, 5) > 0\n verify_and(indata=[x, y], dtype=bool)\n\n\[email protected]_targets\ndef test_tile(target, dev):\n def verify_tile_v6(indata, repeats, outdata):\n node = helper.make_node(\"Tile\", inputs=[\"input\", \"repeats\"], outputs=[\"out\"])\n graph = helper.make_graph(\n [node],\n \"tile_test\",\n inputs=[\n helper.make_tensor_value_info(\"input\", TensorProto.FLOAT, list(indata.shape)),\n helper.make_tensor_value_info(\"repeats\", TensorProto.INT64, list(repeats.shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outdata.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"tile_test\")\n verify_with_ort_with_inputs(\n model, [indata, repeats], use_vm=True, opset=6, target=target, dev=dev\n )\n\n x = np.random.rand(2, 3, 4, 5).astype(np.float32)\n repeats = np.random.randint(low=1, high=10, size=(np.ndim(x),)).astype(np.int64)\n z = np.tile(x, repeats)\n verify_tile_v6(x, repeats, z)\n\n\[email protected]_targets\ndef test_erf(target, dev):\n def verify_erf(indata, outdata):\n node = helper.make_node(\"Erf\", inputs=[\"in\"], outputs=[\"out\"])\n graph = helper.make_graph(\n [node],\n \"erf_test\",\n inputs=[helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(indata.shape))],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(outdata.shape))],\n )\n model = helper.make_model(graph, producer_name=\"erf_test\")\n verify_with_ort_with_inputs(model, [indata], [outdata.shape], target=target, dev=dev)\n\n x = np.random.rand(2, 3, 4, 6).astype(np.float32)\n z = scipy.special.erf(x)\n verify_erf(x, z)\n\n\[email protected]_targets\ndef test_where(target, dev):\n def verify_where(condition, x, y, dtype, outdata, dynamic=False):\n node_list = []\n where_inputs = [\"condition\", \"x\", \"y\"]\n if dynamic:\n shape_node = helper.make_node(\"Shape\", [\"x\"], [\"shape\"])\n reshape_node = helper.make_node(\"Reshape\", [\"x\", \"shape\"], [\"X\"])\n where_inputs[1] = \"X\"\n node_list += [shape_node, reshape_node]\n node = helper.make_node(\"Where\", inputs=where_inputs, outputs=[\"out\"])\n node_list.append(node)\n graph = helper.make_graph(\n node_list,\n \"where_test\",\n inputs=[\n helper.make_tensor_value_info(\"condition\", TensorProto.BOOL, list(condition.shape)),\n helper.make_tensor_value_info(\"x\", dtype, list(x.shape)),\n helper.make_tensor_value_info(\"y\", dtype, list(y.shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", dtype, list(outdata.shape))],\n )\n model = helper.make_model(graph, producer_name=\"where_test\")\n verify_with_ort_with_inputs(\n model, [condition, x, y], [outdata.shape], use_vm=True, target=target, dev=dev\n )\n\n condition = np.array([[1, 0], [1, 1]], dtype=bool)\n x = np.array([[1, 2], [3, 4]], dtype=np.int64)\n y = np.array([[9, 8], [7, 6]], dtype=np.int64)\n outdata = np.where(condition, x, y)\n verify_where(condition, x, y, TensorProto.INT64, outdata)\n\n x = np.array([[1, 2], [3, 4]], dtype=np.float32)\n y = np.array([[9, 8], [7, 6]], dtype=np.float32)\n outdata = np.where(condition, x, y)\n verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n\n x = np.array(1, dtype=np.float32)\n y = np.array([2], dtype=np.float32)\n outdata = np.where(condition, x, y)\n verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n\n x = np.array([2], dtype=np.float32)\n y = np.array(1, dtype=np.float32)\n outdata = np.where(condition, x, y)\n verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n\n condition = np.array(1, dtype=bool)\n x = np.array([[1, 2], [3, 4]], dtype=np.float32)\n y = np.array([[5, 6], [7, 8]], dtype=np.float32)\n outdata = np.where(condition, x, y)\n verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n\n x = np.array([[1, 2], [3, 4]], dtype=np.float32)\n y = np.array([[1], [7]], dtype=np.float32)\n outdata = np.where(condition, x, y)\n verify_where(condition, x, y, TensorProto.FLOAT, outdata)\n verify_where(condition, x, y, TensorProto.FLOAT, outdata, dynamic=True)\n\n\[email protected]_targets\ndef test_or(target, dev):\n def verify_or(indata, dtype):\n x = indata[0].astype(dtype)\n y = indata[1].astype(dtype)\n outdata = np.logical_or(x, y)\n\n node = helper.make_node(\n \"Or\",\n inputs=[\"in1\", \"in2\"],\n outputs=[\"out\"],\n )\n\n graph = helper.make_graph(\n [node],\n \"or_test\",\n inputs=[\n helper.make_tensor_value_info(\"in1\", TensorProto.BOOL, list(x.shape)),\n helper.make_tensor_value_info(\"in2\", TensorProto.BOOL, list(y.shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.BOOL, list(outdata.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"or_test\")\n verify_with_ort_with_inputs(model, [x, y], [outdata.shape], target=target, dev=dev)\n\n # 2d\n x = np.random.randn(3, 4) > 0\n y = np.random.randn(3, 4) > 0\n verify_or(indata=[x, y], dtype=bool)\n\n # 3d\n x = np.random.randn(3, 4, 5) > 0\n y = np.random.randn(3, 4, 5) > 0\n verify_or(indata=[x, y], dtype=bool)\n\n # 4d\n x = np.random.randn(3, 4, 5, 6) > 0\n y = np.random.randn(3, 4, 5, 6) > 0\n verify_or(indata=[x, y], dtype=bool)\n\n # 3d vs 1d\n x = np.random.randn(3, 4, 5) > 0\n y = np.random.randn(5) > 0\n verify_or(indata=[x, y], dtype=bool)\n\n # 3d vs 2d\n x = np.random.randn(3, 4, 5) > 0\n y = np.random.randn(4, 5) > 0\n verify_or(indata=[x, y], dtype=bool)\n\n\[email protected]_targets\ndef test_batch_norm(target, dev):\n def verify_batch_norm(in_shape):\n batchnorm = onnx.helper.make_node(\n \"BatchNormalization\", inputs=[\"x\", \"scale\", \"B\", \"mean\", \"var\"], outputs=[\"Y\"]\n )\n\n graph = helper.make_graph(\n [batchnorm],\n \"batchnorm_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(in_shape)),\n helper.make_tensor_value_info(\"scale\", TensorProto.FLOAT, [in_shape[1]]),\n helper.make_tensor_value_info(\"B\", TensorProto.FLOAT, [in_shape[1]]),\n helper.make_tensor_value_info(\"mean\", TensorProto.FLOAT, [in_shape[1]]),\n helper.make_tensor_value_info(\"var\", TensorProto.FLOAT, [in_shape[1]]),\n ],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(in_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"batchnorm_test\")\n # X, scale, b, mean, var\n inshapes = [in_shape, in_shape[1], in_shape[1], in_shape[1], in_shape[1]]\n verify_with_ort(model, inshapes, out_shape=[in_shape], target=target, dev=dev)\n\n verify_batch_norm([1, 3, 224, 224])\n verify_batch_norm([1, 3, 24, 24])\n verify_batch_norm([16, 3, 24, 24])\n verify_batch_norm([16, 16, 24, 24])\n verify_batch_norm([16, 16, 10, 10])\n\n\[email protected]_targets\ndef test_batch_norm_dynamic_subgraph(target, dev):\n def verify_batch_norm_dynamic_subgraph(in_shape, o_shape):\n\n batchnorm = onnx.helper.make_node(\n \"BatchNormalization\", inputs=[\"x\", \"scale\", \"B\", \"mean\", \"var\"], outputs=[\"Y\"]\n )\n\n shape_node = helper.make_node(\"Shape\", [\"Y\"], [\"shape\"])\n reshape_node = helper.make_node(\"Reshape\", [\"in\", \"shape\"], [\"out\"])\n graph = helper.make_graph(\n [batchnorm, shape_node, reshape_node],\n \"batchnorm_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(in_shape)),\n helper.make_tensor_value_info(\"in\", TensorProto.FLOAT, list(o_shape)),\n helper.make_tensor_value_info(\"scale\", TensorProto.FLOAT, [in_shape[1]]),\n helper.make_tensor_value_info(\"B\", TensorProto.FLOAT, [in_shape[1]]),\n helper.make_tensor_value_info(\"mean\", TensorProto.FLOAT, [in_shape[1]]),\n helper.make_tensor_value_info(\"var\", TensorProto.FLOAT, [in_shape[1]]),\n ],\n outputs=[helper.make_tensor_value_info(\"out\", TensorProto.FLOAT, list(in_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"batchnorm_test\")\n\n # X, inp, scale, b, mean, var\n inshapes = [in_shape, o_shape, in_shape[1], in_shape[1], in_shape[1], in_shape[1]]\n verify_with_ort(model, inshapes, out_shape=[in_shape], use_vm=True, target=target, dev=dev)\n\n verify_batch_norm_dynamic_subgraph([16, 16, 10, 10], [160, 160])\n\n\[email protected]_targets\ndef test_conv(target, dev):\n def verify_conv(\n x_shape,\n w_shape,\n y_shape,\n padding,\n kernel_shape,\n strides,\n dilations,\n group=1,\n auto_pad=\"NOTSET\",\n unset_pad=False,\n ):\n if unset_pad:\n node = helper.make_node(\n \"Conv\",\n inputs=[\"x\", \"W\"],\n outputs=[\"y\"],\n kernel_shape=kernel_shape,\n # Default values for other attributes:\n strides=strides,\n dilations=dilations,\n group=group,\n )\n elif padding is None:\n ## autopadding with unset default attributes\n kwargs = {}\n if not all([s == 1 for s in strides]):\n kwargs[\"strides\"] = strides\n if not all([d == 1 for d in dilations]):\n kwargs[\"dilations\"] = dilations\n\n node = helper.make_node(\n \"Conv\",\n inputs=[\"x\", \"W\"],\n outputs=[\"y\"],\n # Default values for other attributes:\n auto_pad=auto_pad,\n group=group,\n **kwargs,\n )\n else:\n node = helper.make_node(\n \"Conv\",\n inputs=[\"x\", \"W\"],\n outputs=[\"y\"],\n kernel_shape=kernel_shape,\n # Default values for other attributes:\n strides=strides,\n dilations=dilations,\n group=group,\n pads=padding,\n )\n\n graph = helper.make_graph(\n [node],\n \"conv_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n helper.make_tensor_value_info(\"W\", TensorProto.FLOAT, list(w_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(y_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"conv_test\")\n\n verify_with_ort(\n model,\n [x_shape, w_shape],\n [y_shape],\n use_vm=True,\n convert_to_static=True,\n target=target,\n dev=dev,\n )\n\n def repeat(N, D):\n return tuple([N for _ in range(D)])\n\n for D in [1, 2, 3]:\n # Convolution with padding\n verify_conv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(5, D),\n 2 * repeat(1, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n # Convolution with asymmetric padding\n verify_conv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(4, D),\n repeat(0, D) + repeat(1, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n # Convolution without padding\n verify_conv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(3, D),\n 2 * repeat(0, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n # Convolution with autopadding\n verify_conv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(5, D),\n None,\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n auto_pad=\"SAME_UPPER\",\n )\n # Convolution with valid autopadding\n verify_conv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(3, D),\n None,\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n auto_pad=\"VALID\",\n )\n # Convolution with unset padding\n verify_conv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(3, D),\n 2 * repeat(0, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n True,\n )\n # Convolution with non uniform stride\n verify_conv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(3, D),\n None,\n repeat(3, D),\n repeat(2, D),\n repeat(1, D),\n auto_pad=\"SAME_UPPER\",\n )\n # Convolution with dilation\n verify_conv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(5, D),\n 2 * repeat(2, D),\n repeat(3, D),\n repeat(1, D),\n repeat(2, D),\n )\n\n # TODO(jwfromm): Merge with other tests once group_conv3d is supported.\n for D in [1, 2]:\n # Group Convolution\n verify_conv(\n (1, 8) + repeat(5, D),\n (8, 1) + repeat(3, D),\n (1, 8) + repeat(5, D),\n 2 * repeat(1, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n group=8,\n )\n\n\[email protected]_targets\ndef test_convtranspose(target, dev):\n def verify_convtranspose_with_padding(\n x_shape,\n w_shape,\n padding,\n kernel_shape,\n strides,\n dilations,\n auto_pad=\"NOTSET\",\n unset_pad=False,\n group=1,\n ):\n node = helper.make_node(\n \"ConvTranspose\",\n inputs=[\"x\", \"W\"],\n outputs=[\"y\"],\n kernel_shape=kernel_shape,\n # Default values for other attributes:\n strides=strides,\n dilations=dilations,\n )\n if not unset_pad:\n if padding is None:\n pad_attr = helper.make_attribute(\"auto_pad\", auto_pad)\n else:\n pad_attr = helper.make_attribute(\"pads\", padding)\n node.attribute.append(pad_attr)\n\n if group is not None:\n group_attr = helper.make_attribute(\"group\", group)\n node.attribute.append(group_attr)\n\n graph = helper.make_graph(\n [node],\n \"convtranspose_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n helper.make_tensor_value_info(\"W\", TensorProto.FLOAT, list(w_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, [\"?\"] * len(x_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"convtranspose_pad_test\")\n\n verify_with_ort(\n model, [x_shape, w_shape], use_vm=True, convert_to_static=True, target=target, dev=dev\n )\n\n def verify_convtranspose(x_shape, w_shape, y_shape, p, group=1):\n node = onnx.helper.make_node(\n \"ConvTranspose\",\n inputs=[\"x\", \"W\"],\n outputs=[\"y\"],\n strides=[3, 2],\n kernel_shape=[3, 3],\n pads=p,\n )\n\n if group is not None:\n group_attr = helper.make_attribute(\"group\", group)\n node.attribute.append(group_attr)\n\n graph = helper.make_graph(\n [node],\n \"verify_convtranspose_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n helper.make_tensor_value_info(\"W\", TensorProto.FLOAT, list(w_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(y_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"convtranspose_test\")\n verify_with_ort(model, [x_shape, w_shape], y_shape, opset=11, target=target, dev=dev)\n\n # Convolution Transpose with padding\n # (1, 1, 3, 3) input tensor\n # (1, 2, 3, 3) tensor for convolution weights\n # (1, 2, 7, 3) output tensor\n # [1, 2, 1, 2] list for pads\n verify_convtranspose((1, 1, 3, 3), (1, 2, 3, 3), (1, 2, 7, 3), [1, 2, 1, 2])\n # Test undefined groups.\n verify_convtranspose((1, 1, 3, 3), (1, 2, 3, 3), (1, 2, 7, 3), [1, 2, 1, 2], group=None)\n\n def repeat(N, D):\n return tuple([N for _ in range(D)])\n\n # Once onnxruntime update is complete\n for D in [1, 2, 3]:\n # Convolution with padding\n verify_convtranspose_with_padding(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n 2 * repeat(1, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n # Convolution without padding\n verify_convtranspose_with_padding(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n 2 * repeat(0, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n # Convolution with unset padding\n verify_convtranspose_with_padding(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n 2 * repeat(0, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n True,\n )\n # Convolution with autopadding\n verify_convtranspose_with_padding(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n None,\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n auto_pad=\"SAME_UPPER\",\n )\n # Convolution with valid autopadding\n verify_convtranspose_with_padding(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n None,\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n auto_pad=\"VALID\",\n )\n # Convolution with non uniform stride\n verify_convtranspose_with_padding(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n None,\n repeat(3, D),\n repeat(2, D),\n repeat(1, D),\n auto_pad=\"SAME_UPPER\",\n )\n # Convolution with dilation\n # TODO(mbrookhart): Relay doesn't currently support convtranspose with dilation\n # verify_convtranspose_with_padding(\n # (1, 1) + repeat(5, D),\n # (1, 1) + repeat(3, D),\n # 2 * repeat(2, D),\n # repeat(3, D),\n # repeat(1, D),\n # repeat(2, D),\n # )\n\n\[email protected]_targets\ndef test_unsqueeze_constant(target, dev):\n from torch.nn import Linear, Module, Sequential\n\n class Flatten(Module):\n def forward(self, input):\n return input.view(input.size(0), -1)\n\n import tempfile\n\n with tempfile.NamedTemporaryFile() as fp:\n file_name = fp.name\n input_size = (1, 16, 32, 32)\n dummy_input = torch.randn(*input_size)\n layer = Sequential(Flatten(), Linear(16 * 32 * 32, 64))\n torch.onnx.export(layer, dummy_input, file_name, export_params=True)\n\n onnx_model = onnx.load(file_name)\n relay.frontend.from_onnx(onnx_model, {\"0\": input_size})\n\n\[email protected]_targets\ndef test_pooling(target, dev):\n def verify_pooling(x_shape, kernel_shape, strides, pads, out_shape, mode, auto_pad=\"NOTSET\"):\n x_np = np.random.uniform(size=x_shape).astype(\"float32\")\n\n if mode == \"max\":\n node_type = \"MaxPool\"\n elif mode == \"average\":\n node_type = \"AveragePool\"\n else:\n raise ValueError(\"Pool method {} is not supported.\".format(mode))\n\n pool_node = helper.make_node(\n node_type, inputs=[\"x\"], outputs=[\"y\"], kernel_shape=kernel_shape, strides=strides\n )\n\n if pads is None:\n pad_attr = helper.make_attribute(\"auto_pad\", auto_pad)\n else:\n pad_attr = helper.make_attribute(\"pads\", pads)\n pool_node.attribute.append(pad_attr)\n\n if mode == \"max\":\n storage_attr = helper.make_attribute(\"storage_order\", 0)\n pool_node.attribute.append(storage_attr)\n\n graph = helper.make_graph(\n [pool_node],\n \"pooling_test\",\n inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape))],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"pooling_test\")\n verify_with_ort(\n model,\n [x_shape],\n [out_shape],\n use_vm=False,\n convert_to_static=True,\n target=target,\n dev=dev,\n )\n\n for mode in [\"max\", \"average\"]:\n # Pool1D\n verify_pooling(\n x_shape=[1, 1, 32],\n kernel_shape=[3],\n strides=[1],\n pads=[1, 1],\n out_shape=[1, 1, 32],\n mode=mode,\n )\n # Pool2D\n verify_pooling(\n x_shape=[1, 1, 32, 32],\n kernel_shape=[3, 3],\n strides=[1, 1],\n pads=[1, 1, 1, 1],\n out_shape=[1, 1, 32, 32],\n mode=mode,\n )\n\n # Pool1D with stride\n verify_pooling(\n x_shape=[1, 1, 32],\n kernel_shape=[3],\n strides=[2],\n pads=[1, 1],\n out_shape=[1, 1, 16],\n mode=mode,\n )\n # Pool2D with stride\n verify_pooling(\n x_shape=[1, 1, 32, 32],\n kernel_shape=[3, 3],\n strides=[2, 2],\n pads=[1, 1, 1, 1],\n out_shape=[1, 1, 16, 16],\n mode=mode,\n )\n\n # Pool1D with stride and autopadding\n verify_pooling(\n x_shape=[1, 1, 32],\n kernel_shape=[3],\n strides=[2],\n pads=None,\n out_shape=[1, 1, 16],\n mode=mode,\n auto_pad=\"SAME_UPPER\",\n )\n # Pool2D with stride and autopadding\n verify_pooling(\n x_shape=[1, 1, 32, 32],\n kernel_shape=[3, 3],\n strides=[2, 2],\n pads=None,\n out_shape=[1, 1, 16, 16],\n mode=mode,\n auto_pad=\"SAME_UPPER\",\n )\n\n # Pool3D with stride\n verify_pooling(\n x_shape=[1, 1, 32, 32, 32],\n kernel_shape=[3, 3, 3],\n strides=[2, 2, 2],\n pads=[1, 1, 1, 1, 1, 1],\n out_shape=[1, 1, 16, 16, 16],\n mode=mode,\n )\n\n # Pool3D with stride and autopadding\n verify_pooling(\n x_shape=[1, 1, 32, 32, 32],\n kernel_shape=[3, 3, 3],\n strides=[2, 2, 2],\n pads=None,\n out_shape=[1, 1, 16, 16, 16],\n mode=mode,\n auto_pad=\"SAME_UPPER\",\n )\n\n\[email protected]_targets\ndef test_global_pooling(target, dev):\n def verify_global_pooling(x_shape, mode):\n out_shape = x_shape[:2] + [1] * (len(x_shape) - 2)\n\n if mode == \"max\":\n node_type = \"GlobalMaxPool\"\n elif mode == \"average\":\n node_type = \"GlobalAveragePool\"\n else:\n raise ValueError(\"Pool method {} is not supported.\".format(mode))\n\n pool_node = helper.make_node(node_type, inputs=[\"x\"], outputs=[\"y\"])\n\n graph = helper.make_graph(\n [pool_node],\n \"global_pooling_test\",\n inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape))],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"global_pooling_test\")\n verify_with_ort(\n model,\n [x_shape],\n [out_shape],\n use_vm=False,\n convert_to_static=True,\n target=target,\n dev=dev,\n )\n\n # Test each pooling mode across all N-D inputs.\n for mode in [\"average\", \"max\"]:\n # 1D Pooling (NCW)\n verify_global_pooling([1, 8, 8], mode)\n verify_global_pooling([4, 1, 4], mode)\n # 2D Pooling (NCHW)\n verify_global_pooling([1, 8, 8, 8], mode)\n verify_global_pooling([4, 1, 6, 4], mode)\n # 3D Pooling (NCDHW)\n verify_global_pooling([1, 8, 6, 8, 8], mode)\n verify_global_pooling([4, 1, 2, 6, 4], mode)\n\n\[email protected]_targets\ndef test_qlinear_average_pool(target, dev):\n def verify_qlinear_average_pool(\n x_shape, kernel_shape, strides, pads, out_shape, auto_pad=\"NOTSET\"\n ):\n input_nodes = [\n helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(x_shape)),\n ]\n\n output_nodes = [\n helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(out_shape)),\n ]\n\n input_names = [\"X\"]\n\n node = helper.make_node(\n \"AveragePool\",\n inputs=input_names,\n outputs=[\"Y\"],\n kernel_shape=kernel_shape,\n strides=strides,\n )\n\n if pads is None:\n pad_attr = helper.make_attribute(\"auto_pad\", auto_pad)\n else:\n pad_attr = helper.make_attribute(\"pads\", pads)\n node.attribute.append(pad_attr)\n\n graph = helper.make_graph(\n [node],\n \"qlinear_average_pool_test\",\n inputs=input_nodes,\n outputs=output_nodes,\n )\n\n model = helper.make_model(graph, producer_name=\"qlinear_average_pool_Test\")\n quantize_and_verify_with_ort(model, input_names, [x_shape], target, dev)\n\n # Pool1D\n verify_qlinear_average_pool(\n x_shape=[1, 1, 32],\n kernel_shape=[3],\n strides=[1],\n pads=[1, 1],\n out_shape=[1, 1, 32],\n )\n # Pool2D\n verify_qlinear_average_pool(\n x_shape=[1, 1, 32, 32],\n kernel_shape=[3, 3],\n strides=[1, 1],\n pads=[1, 1, 1, 1],\n out_shape=[1, 1, 32, 32],\n )\n\n # Pool1D with stride\n verify_qlinear_average_pool(\n x_shape=[1, 1, 32],\n kernel_shape=[3],\n strides=[2],\n pads=[1, 1],\n out_shape=[1, 1, 16],\n )\n # Pool2D with stride\n verify_qlinear_average_pool(\n x_shape=[1, 1, 32, 32],\n kernel_shape=[3, 3],\n strides=[2, 2],\n pads=[1, 1, 1, 1],\n out_shape=[1, 1, 16, 16],\n )\n\n # Pool1D with stride and autopadding\n verify_qlinear_average_pool(\n x_shape=[1, 1, 32],\n kernel_shape=[3],\n strides=[2],\n pads=None,\n out_shape=[1, 1, 16],\n auto_pad=\"SAME_UPPER\",\n )\n # Pool2D with stride and autopadding\n verify_qlinear_average_pool(\n x_shape=[1, 1, 32, 32],\n kernel_shape=[3, 3],\n strides=[2, 2],\n pads=None,\n out_shape=[1, 1, 16, 16],\n auto_pad=\"SAME_UPPER\",\n )\n\n # Pool3D with stride\n verify_qlinear_average_pool(\n x_shape=[1, 1, 32, 32, 32],\n kernel_shape=[3, 3, 3],\n strides=[2, 2, 2],\n pads=[1, 1, 1, 1, 1, 1],\n out_shape=[1, 1, 16, 16, 16],\n )\n\n # Pool3D with stride and autopadding\n verify_qlinear_average_pool(\n x_shape=[1, 1, 32, 32, 32],\n kernel_shape=[3, 3, 3],\n strides=[2, 2, 2],\n pads=None,\n out_shape=[1, 1, 16, 16, 16],\n auto_pad=\"SAME_UPPER\",\n )\n\n\[email protected]_targets\ndef test_qlinear_global_average_pool(target, dev):\n def verify_qlinear_global_average_pool(x_shape):\n out_shape = x_shape[:2] + [1] * (len(x_shape) - 2)\n\n node_type = \"GlobalAveragePool\"\n\n input_names = [\"X\"]\n\n pool_node = helper.make_node(node_type, inputs=input_names, outputs=[\"Y\"])\n\n graph = helper.make_graph(\n [pool_node],\n \"qlinear_global_average_pool_test\",\n inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(x_shape))],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"qlinear_global_average_pool_test\")\n quantize_and_verify_with_ort(model, input_names, [x_shape], target, dev)\n\n # 1D Pooling (NCW)\n verify_qlinear_global_average_pool([1, 8, 8])\n verify_qlinear_global_average_pool([4, 1, 4])\n\n # 2D Pooling (NCHW)\n verify_qlinear_global_average_pool([1, 8, 8, 8])\n verify_qlinear_global_average_pool([4, 1, 6, 4])\n\n # 3D Pooling (NCDHW)\n verify_qlinear_global_average_pool([1, 8, 6, 8, 8])\n verify_qlinear_global_average_pool([4, 1, 2, 6, 4])\n\n\[email protected]_targets\ndef test_mod(target, dev):\n def verify_mod(x_shape, y_shape, fmod, out_shape, dtype=\"float32\"):\n x_np = np.random.uniform(-100.0, 100.0, x_shape).astype(dtype)\n y_np = np.random.uniform(-100.0, 100.0, y_shape).astype(dtype)\n y_np = np.where(y_np == 0, 1, y_np) # remove 0's to avoid division by zero error\n\n mod_node = helper.make_node(\"Mod\", inputs=[\"x\", \"y\"], outputs=[\"z\"], fmod=fmod)\n\n onnx_dtype = TensorProto.FLOAT if dtype == \"float32\" else TensorProto.INT32\n graph = helper.make_graph(\n [mod_node],\n \"mod_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", onnx_dtype, list(x_shape)),\n helper.make_tensor_value_info(\"y\", onnx_dtype, list(y_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"z\", onnx_dtype, list(out_shape))],\n )\n model = helper.make_model(graph, producer_name=\"mod_test\")\n verify_with_ort_with_inputs(model, [x_np, y_np], [out_shape], target=target, dev=dev)\n\n # Mod\n verify_mod(\n x_shape=[1, 32, 32], y_shape=[1, 1, 32], fmod=0, out_shape=(1, 32, 32), dtype=\"int32\"\n )\n verify_mod(\n x_shape=[1, 32, 32, 32],\n y_shape=[1, 32, 32, 32],\n fmod=0,\n out_shape=(1, 32, 32, 32),\n dtype=\"int32\",\n )\n\n # fmod\n verify_mod(\n x_shape=[1, 32, 32], y_shape=[1, 32, 32], fmod=1, out_shape=(1, 32, 32), dtype=\"int32\"\n )\n verify_mod(x_shape=[1, 1, 32, 32], y_shape=[1, 32, 32, 32], fmod=1, out_shape=(1, 32, 32, 32))\n verify_mod(x_shape=[1, 32, 32, 32], y_shape=[1, 1, 32, 32], fmod=1, out_shape=(1, 32, 32, 32))\n verify_mod(\n x_shape=[1, 32, 32, 32],\n y_shape=[1, 32, 32, 32],\n fmod=1,\n out_shape=(1, 32, 32, 32),\n dtype=\"int32\",\n )\n verify_mod(x_shape=[1, 32, 32, 32], y_shape=[1, 32, 32, 32], fmod=1, out_shape=(1, 32, 32, 32))\n\n\[email protected]_targets\ndef test_xor(target, dev):\n def verify_xor(x_shape, y_shape):\n x_np = np.random.choice(a=[False, True], size=x_shape).astype(\"bool\")\n y_np = np.random.choice(a=[False, True], size=y_shape).astype(\"bool\")\n\n np_out = np.logical_xor(x_np, y_np)\n out_shape = np_out.shape\n\n xor_node = helper.make_node(\"Xor\", inputs=[\"x\", \"y\"], outputs=[\"z\"])\n\n onnx_dtype = TensorProto.BOOL\n graph = helper.make_graph(\n [xor_node],\n \"xor_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", onnx_dtype, list(x_shape)),\n helper.make_tensor_value_info(\"y\", onnx_dtype, list(y_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"z\", onnx_dtype, list(out_shape))],\n )\n model = helper.make_model(graph, producer_name=\"xor_test\")\n verify_with_ort_with_inputs(model, [x_np, y_np], [out_shape], target=target, dev=dev)\n\n # XOR\n verify_xor(x_shape=[1, 32, 32], y_shape=[1, 32, 32])\n\n # Xor broadcast\n verify_xor(x_shape=[1, 32, 32], y_shape=[1, 1, 32])\n\n\[email protected]_targets\ndef test_max_roi_pool(target, dev):\n def verify_max_roi_pool(x_shape, rois_shape, pooled_shape, spatial_scale, out_shape):\n if spatial_scale is None:\n pool_node = helper.make_node(\n \"MaxRoiPool\", inputs=[\"x\", \"rois\"], outputs=[\"y\"], pooled_shape=pooled_shape\n )\n else:\n pool_node = helper.make_node(\n \"MaxRoiPool\",\n inputs=[\"x\", \"rois\"],\n outputs=[\"y\"],\n pooled_shape=pooled_shape,\n spatial_scale=spatial_scale,\n )\n\n graph = helper.make_graph(\n [pool_node],\n \"pool_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape)),\n helper.make_tensor_value_info(\"rois\", TensorProto.FLOAT, list(rois_shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"pool_test\")\n verify_with_ort(model, [x_shape, rois_shape], [out_shape], target=target, dev=dev)\n\n verify_max_roi_pool(\n x_shape=[1, 3, 6, 6],\n rois_shape=[3, 5],\n pooled_shape=[1, 1],\n spatial_scale=None,\n out_shape=[3, 3, 1, 1],\n )\n\n verify_max_roi_pool(\n x_shape=[1, 3, 10, 10],\n rois_shape=[4, 5],\n pooled_shape=[2, 2],\n spatial_scale=2.0,\n out_shape=[4, 3, 2, 2],\n )\n\n\[email protected]_targets\ndef test_lppool(target, dev):\n def verify_lppool(x_shape, kernel_shape, p, strides, pads, out_shape, auto_pad=\"NOTSET\"):\n kwargs = {}\n if p is not None:\n kwargs[\"p\"] = p\n if pads is None:\n pool_node = helper.make_node(\n \"LpPool\",\n inputs=[\"x\"],\n outputs=[\"y\"],\n kernel_shape=kernel_shape,\n auto_pad=auto_pad,\n strides=strides,\n **kwargs,\n )\n else:\n pool_node = helper.make_node(\n \"LpPool\",\n inputs=[\"x\"],\n outputs=[\"y\"],\n kernel_shape=kernel_shape,\n pads=pads,\n strides=strides,\n **kwargs,\n )\n\n graph = helper.make_graph(\n [pool_node],\n \"lppool_test\",\n inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape))],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"lppool_test\")\n verify_with_ort(\n model,\n [x_shape],\n [out_shape],\n use_vm=True,\n convert_to_static=True,\n target=target,\n dev=dev,\n )\n\n # Pool1D\n verify_lppool(\n x_shape=[1, 1, 32], kernel_shape=[3], p=2, strides=[1], pads=[1, 1], out_shape=[1, 1, 32]\n )\n\n # Pool2D\n verify_lppool(\n x_shape=[1, 1, 32, 32],\n kernel_shape=[3, 3],\n p=2,\n strides=[1, 1],\n pads=[1, 1, 1, 1],\n out_shape=[1, 1, 32, 32],\n )\n\n # Pool1D with stride\n verify_lppool(\n x_shape=[1, 1, 32], kernel_shape=[3], p=2, strides=[2], pads=[1, 1], out_shape=[1, 1, 16]\n )\n\n # Pool2D with stride\n verify_lppool(\n x_shape=[1, 1, 32, 32],\n kernel_shape=[3, 3],\n p=2,\n strides=[2, 2],\n pads=[1, 1, 1, 1],\n out_shape=[1, 1, 16, 16],\n )\n\n # Pool1D with stride and autopadding\n verify_lppool(\n x_shape=[1, 1, 32],\n kernel_shape=[3],\n p=2,\n strides=[2],\n pads=None,\n out_shape=[1, 1, 16],\n auto_pad=\"SAME_UPPER\",\n )\n\n # Pool2D with stride and autopadding\n verify_lppool(\n x_shape=[1, 1, 32, 32],\n kernel_shape=[3, 3],\n p=2,\n strides=[2, 2],\n pads=None,\n out_shape=[1, 1, 16, 16],\n auto_pad=\"SAME_UPPER\",\n )\n\n # Pool3D with stride\n verify_lppool(\n x_shape=[1, 1, 32, 32, 32],\n kernel_shape=[3, 3, 3],\n p=2,\n strides=[2, 2, 2],\n pads=[1, 1, 1, 1, 1, 1],\n out_shape=[1, 1, 16, 16, 16],\n )\n\n # Pool3D with stride and autopadding\n verify_lppool(\n x_shape=[1, 1, 32, 32, 32],\n kernel_shape=[3, 3, 3],\n p=2,\n strides=[2, 2, 2],\n pads=None,\n out_shape=[1, 1, 16, 16, 16],\n auto_pad=\"SAME_UPPER\",\n )\n # Pool2D with empty p\n verify_lppool(\n x_shape=[1, 1, 32, 32],\n kernel_shape=[3, 3],\n p=None,\n strides=[1, 1],\n pads=[1, 1, 1, 1],\n out_shape=[1, 1, 32, 32],\n )\n\n\ndef verify_global_lppool(x_shape, p, out_shape, target, dev):\n pool_node = helper.make_node(\n \"GlobalLpPool\",\n inputs=[\"x\"],\n outputs=[\"y\"],\n p=p,\n )\n\n graph = helper.make_graph(\n [pool_node],\n \"global_lppool_test\",\n inputs=[helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x_shape))],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(out_shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"global_lppool_test\")\n verify_with_ort(\n model, [x_shape], out_shape, use_vm=True, convert_to_static=True, target=target, dev=dev\n )\n\n\[email protected]_targets\ndef test_global_lppool(target, dev):\n\n # LpPool1D\n verify_global_lppool(x_shape=[1, 15, 16], p=2, out_shape=[1, 15, 1], target=target, dev=dev)\n\n # LpPool2D\n verify_global_lppool(\n x_shape=[1, 15, 32, 32], p=2, out_shape=[1, 15, 1, 1], target=target, dev=dev\n )\n\n # LpPool2D\n verify_global_lppool(\n x_shape=[1, 15, 32, 32], p=3, out_shape=[1, 15, 1, 1], target=target, dev=dev\n )\n\n # LpPool3D\n verify_global_lppool(\n x_shape=[1, 15, 3, 32, 32], p=2, out_shape=[1, 15, 1, 1, 1], target=target, dev=dev\n )\n\n\ndef verify_rnn(\n seq_length,\n batch_size,\n input_size,\n hidden_size,\n rnn_type=\"LSTM\",\n use_bias=False,\n activations=None,\n alphas=None,\n betas=None,\n use_initial_state=False,\n use_peep=False,\n linear_before_reset=False,\n directions=1,\n rtol=1e-5,\n atol=1e-5,\n target=None,\n dev=None,\n):\n if rnn_type == \"LSTM\":\n multiplier = 4\n elif rnn_type == \"GRU\":\n multiplier = 3\n else:\n raise NotImplementedError(f\"{rnn_type} RNNs not yet supported.\")\n\n if directions not in [1, 2]:\n raise ValueError(f\"Direction should be either 1 or 2 (for bidirectional LSTMs)\")\n\n def get_inputs():\n input_names = []\n input_values = []\n input_tensors = []\n\n def register(np_arr, name, shape=None):\n input_values.append(np_arr)\n input_names.append(name)\n\n # Map of numpy dtypes to the protobuf equivalent\n dtype_map = {\n \"float32\": TensorProto.FLOAT,\n \"int32\": TensorProto.INT32,\n \"int8\": TensorProto.INT8,\n }\n\n if np_arr.dtype.name not in dtype_map:\n raise ValueError(f\"Unknown dtype we don't know how to handle {np.dtype.name}\")\n if shape is None:\n shape = list(np_arr.shape)\n proto_type = dtype_map[np_arr.dtype.name]\n input_tensors.append(helper.make_tensor_value_info(name, proto_type, shape))\n\n x_np = np.random.uniform(size=(seq_length, batch_size, input_size)).astype(\"float32\")\n w_np = np.random.uniform(size=(directions, multiplier * hidden_size, input_size)).astype(\n \"float32\"\n )\n r_np = np.random.uniform(size=(directions, multiplier * hidden_size, hidden_size)).astype(\n \"float32\"\n )\n register(x_np, \"X\")\n register(w_np, \"W\")\n register(r_np, \"R\")\n\n if use_bias:\n b_np = np.random.uniform(size=(directions, multiplier * 2 * hidden_size)).astype(\n \"float32\"\n )\n register(b_np, \"B\")\n\n if use_initial_state:\n assert use_bias == True, \"Initial states must have bias specified.\"\n sequence_np = np.repeat(seq_length, batch_size).astype(\"int32\")\n register(sequence_np, \"sequence_lens\")\n\n initial_h_np = np.random.uniform(size=(directions, batch_size, hidden_size)).astype(\n \"float32\"\n )\n register(initial_h_np, \"initial_h\")\n\n if rnn_type == \"LSTM\":\n initial_c_np = np.random.uniform(size=(directions, batch_size, hidden_size)).astype(\n \"float32\"\n )\n register(initial_c_np, \"initial_c\")\n\n if use_peep and rnn_type == \"LSTM\":\n assert use_initial_state == True, \"Peepholes require initial state to be specified.\"\n p_np = np.random.uniform(size=(directions, 3 * hidden_size)).astype(\"float32\")\n register(p_np, \"P\")\n\n return input_names, input_tensors, input_values\n\n input_names, input_tensors, input_values = get_inputs()\n\n def get_outputs():\n output_names = []\n graph_outputs = []\n output_shapes = []\n\n def register(name, shape, proto_type):\n output_names.append(name)\n graph_outputs.append(helper.make_tensor_value_info(name, proto_type, list(shape)))\n output_shapes.append(list(shape))\n\n register(\"Y\", [seq_length, directions, batch_size, hidden_size], TensorProto.FLOAT)\n register(\"Y_h\", [directions, batch_size, hidden_size], TensorProto.FLOAT)\n\n if rnn_type == \"LSTM\":\n register(\"Y_c\", [directions, batch_size, hidden_size], TensorProto.FLOAT)\n\n return output_names, graph_outputs, output_shapes\n\n output_names, graph_outputs, output_shapes = get_outputs()\n\n rnn_node = helper.make_node(\n rnn_type, inputs=input_names, outputs=output_names, hidden_size=hidden_size\n )\n if activations is not None:\n activations_attr = helper.make_attribute(\"activations\", activations)\n rnn_node.attribute.append(activations_attr)\n if directions == 2:\n direction_attr = helper.make_attribute(\"direction\", \"bidirectional\")\n rnn_node.attribute.append(direction_attr)\n if alphas is not None:\n alphas_attr = helper.make_attribute(\"activation_alpha\", alphas)\n rnn_node.attribute.append(alphas_attr)\n if betas is not None:\n betas_attr = helper.make_attribute(\"activation_beta\", betas)\n rnn_node.attribute.append(betas_attr)\n if linear_before_reset and rnn_type == \"GRU\":\n lbr_attr = helper.make_attribute(\"linear_before_reset\", 1)\n rnn_node.attribute.append(lbr_attr)\n\n graph = helper.make_graph([rnn_node], \"rnn_test\", inputs=input_tensors, outputs=graph_outputs)\n\n model = helper.make_model(graph, producer_name=\"rnn_test\")\n\n verify_with_ort_with_inputs(\n model, input_values, output_shapes, atol=atol, rtol=rtol, target=target, dev=dev\n )\n\n\[email protected]_targets\ndef test_lstm(target, dev):\n for directions in [1, 2]:\n # No bias.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=False,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n # large batch.\n verify_rnn(\n seq_length=4,\n batch_size=8,\n input_size=16,\n hidden_size=32,\n use_bias=True,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n # Non power of two.\n verify_rnn(\n seq_length=3,\n batch_size=3,\n input_size=16,\n hidden_size=40,\n use_bias=True,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n # Long sequence.\n verify_rnn(\n seq_length=8,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=True,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n # Large hidden.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=128,\n use_bias=True,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n # Large input.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=64,\n hidden_size=32,\n use_bias=True,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n\n # Different activation testing.\n # Default value hardsigmoid.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=False,\n activations=[\"HardSigmoid\", \"Tanh\", \"Tanh\"] * directions,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n # Multiple parametrized activations.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=False,\n activations=[\"HardSigmoid\", \"LeakyRelu\", \"Tanh\"] * directions,\n alphas=[2.0, 0.5, 0.0] * directions,\n betas=[0.3, 0.0, 0.0] * directions,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n # All parametrized with new Affine activation.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=False,\n activations=[\"HardSigmoid\", \"LeakyRelu\", \"Affine\"] * directions,\n alphas=[2.0, 0.5, 0.8] * directions,\n betas=[0.3, 0.1, 0.0] * directions,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n\n # Testing with initial state and peepholes\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=True,\n use_initial_state=True,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=True,\n use_initial_state=True,\n use_peep=True,\n rnn_type=\"LSTM\",\n directions=directions,\n target=target,\n dev=dev,\n )\n\n\[email protected]_targets\ndef test_gru(target, dev):\n # Set seed for test reproduction\n np.random.seed(137)\n for directions in [1, 2]:\n # No bias.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=False,\n rnn_type=\"GRU\",\n directions=directions,\n rtol=1e-6,\n atol=1e-6,\n target=target,\n dev=dev,\n )\n # large batch. linear before reset\n verify_rnn(\n seq_length=4,\n batch_size=8,\n input_size=16,\n hidden_size=32,\n use_bias=True,\n rnn_type=\"GRU\",\n linear_before_reset=True,\n directions=directions,\n target=target,\n dev=dev,\n )\n # Non power of two.\n verify_rnn(\n seq_length=3,\n batch_size=3,\n input_size=16,\n hidden_size=40,\n use_bias=True,\n rnn_type=\"GRU\",\n directions=directions,\n rtol=1e-6,\n atol=1e-6,\n target=target,\n dev=dev,\n )\n # Long sequence.\n verify_rnn(\n seq_length=8,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=True,\n rnn_type=\"GRU\",\n directions=directions,\n rtol=1e-6,\n atol=1e-6,\n target=target,\n dev=dev,\n )\n # Large hidden.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=128,\n use_bias=True,\n rnn_type=\"GRU\",\n directions=directions,\n rtol=1e-6,\n atol=1e-6,\n target=target,\n dev=dev,\n )\n # Large input.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=64,\n hidden_size=32,\n use_bias=True,\n rnn_type=\"GRU\",\n directions=directions,\n rtol=1e-6,\n atol=1e-6,\n target=target,\n dev=dev,\n )\n\n # Different activation testing.\n # Default value hardsigmoid.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=False,\n activations=[\"HardSigmoid\", \"Softsign\"] * directions,\n rnn_type=\"GRU\",\n directions=directions,\n rtol=1e-6,\n atol=1e-6,\n target=target,\n dev=dev,\n )\n # Multiple parametrized activations.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=False,\n activations=[\"HardSigmoid\", \"LeakyRelu\"] * directions,\n alphas=[2.0, 0.5] * directions,\n betas=[0.3, 0.0] * directions,\n rnn_type=\"GRU\",\n directions=directions,\n rtol=1e-8,\n atol=1e-8,\n target=target,\n dev=dev,\n )\n # All parametrized with new Affine activation.\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=False,\n activations=[\"HardSigmoid\", \"Affine\"] * directions,\n alphas=[2.0, 0.8] * directions,\n betas=[0.3, 0.1] * directions,\n rnn_type=\"GRU\",\n directions=directions,\n rtol=1e-8,\n atol=1e-8,\n target=target,\n dev=dev,\n )\n\n # Testing with initial state\n verify_rnn(\n seq_length=2,\n batch_size=1,\n input_size=16,\n hidden_size=32,\n use_bias=True,\n use_initial_state=True,\n rnn_type=\"GRU\",\n directions=directions,\n rtol=1e-6,\n atol=1e-6,\n target=target,\n dev=dev,\n )\n\n\[email protected]_targets\ndef test_resize(target, dev):\n def verify(ishape, oshape, scales, mode, coord_trans=\"asymmetric\", alpha=0.5, exclude=False):\n nodes = [\n make_constant_node(\"roi\", onnx.TensorProto.FLOAT, (0,), []),\n make_constant_node(\"scales\", onnx.TensorProto.FLOAT, (len(scales),), scales),\n ]\n input_names = [\"X\", \"roi\", \"scales\"]\n if oshape != []:\n nodes.append(\n make_constant_node(\"sizes\", onnx.TensorProto.INT64, (len(oshape),), oshape)\n )\n input_names.append(\"sizes\")\n nodes.append(\n helper.make_node(\n \"Resize\",\n inputs=input_names,\n outputs=[\"Y\"],\n mode=mode,\n coordinate_transformation_mode=coord_trans,\n cubic_coeff_a=alpha,\n exclude_outside=exclude,\n )\n )\n\n if oshape == []:\n oshape = [round(dim * scale) for (dim, scale) in zip(ishape, scales)]\n graph = helper.make_graph(\n nodes,\n \"resize_test\",\n inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, ishape)],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, oshape)],\n )\n\n model = helper.make_model(graph, producer_name=\"resize_test\")\n\n verify_with_ort(\n model,\n [ishape],\n [oshape],\n use_vm=True,\n opset=11,\n freeze_params=True,\n target=target,\n dev=dev,\n )\n\n for ndim in [1, 2, 3]:\n method = \"nearest\"\n for coord_trans in [\"asymmetric\", \"align_corners\", \"half_pixel\"]:\n # upsampling\n verify([1, 16] + [32] * ndim, [1, 16] + [64] * ndim, [], method, coord_trans)\n # downsampling\n verify([1, 16] + [32] * ndim, [1, 16] + [16] * ndim, [], method, coord_trans)\n # scales are specified instead of sizes\n verify([1, 16] + [32] * ndim, [], [1, 1] + [0.5] * ndim, method, coord_trans)\n verify([1, 16] + [32] * ndim, [], [1, 1] + [2] * ndim, method, coord_trans)\n\n method = \"linear\"\n # upsampling\n verify([1, 16] + [32] * ndim, [1, 16] + [64] * ndim, [], method)\n # downsampling\n verify([1, 16] + [32] * ndim, [1, 16] + [16] * ndim, [], method)\n # scales are specified instead of sizes\n verify([1, 16] + [32] * ndim, [], [1, 1] + [0.5] * ndim, method)\n verify([1, 16] + [32] * ndim, [], [1, 1] + [2] * ndim, method)\n\n if ndim == 2:\n # ONNX Runtime only supports cubic interpolation for 2D images\n method = \"cubic\"\n for alpha in [0.5, 0.75]:\n for exclude in [True, False]:\n # upsampling\n verify(\n [1, 16] + [32] * ndim,\n [1, 16] + [64] * ndim,\n [],\n method,\n alpha=alpha,\n exclude=exclude,\n )\n # downsampling\n verify(\n [1, 16] + [32] * ndim,\n [1, 16] + [16] * ndim,\n [],\n method,\n alpha=alpha,\n exclude=exclude,\n )\n # scales are specified instead of sizes\n verify(\n [1, 16] + [32] * ndim,\n [],\n [1, 1] + [0.5] * ndim,\n method,\n alpha=alpha,\n exclude=exclude,\n )\n verify(\n [1, 16] + [32] * ndim,\n [],\n [1, 1] + [2] * ndim,\n method,\n alpha=alpha,\n exclude=exclude,\n )\n\n def verify_opset_10(ishape, scales, mode):\n nodes = [\n make_constant_node(\"scales\", onnx.TensorProto.FLOAT, (len(scales),), scales),\n ]\n input_names = [\"X\", \"scales\"]\n nodes.append(\n helper.make_node(\n \"Resize\",\n inputs=input_names,\n outputs=[\"Y\"],\n mode=mode,\n )\n )\n\n oshape = [round(dim * scale) for (dim, scale) in zip(ishape, scales)]\n graph = helper.make_graph(\n nodes,\n \"resize_test\",\n inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, ishape)],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, oshape)],\n )\n\n model = helper.make_model(graph, producer_name=\"resize_test\")\n verify_with_ort(\n model,\n [ishape],\n [oshape],\n use_vm=True,\n freeze_params=True,\n opset=10,\n target=target,\n dev=dev,\n )\n\n verify_opset_10([1, 16, 32, 32], [1, 1, 2, 2], \"nearest\")\n verify_opset_10([1, 16, 32, 32], [1, 1, 0.5, 0.5], \"linear\")\n\n\[email protected]_targets\ndef test_nonzero(target, dev):\n def verify_nonzero(indata, outdata, dtype):\n node = helper.make_node(\n \"NonZero\",\n inputs=[\"X\"],\n outputs=[\"Y\"],\n )\n\n graph = helper.make_graph(\n [node],\n \"nonzero_test\",\n inputs=[helper.make_tensor_value_info(\"X\", TensorProto.INT64, list(indata.shape))],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.INT64, list(outdata.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"nonzero_test\")\n\n verify_with_ort_with_inputs(\n model, [indata], dtype=\"int64\", use_vm=True, opset=9, target=target, dev=dev\n )\n\n input_data = np.array([[1, 0], [1, 1]], dtype=np.int64)\n result = np.array((np.nonzero(input_data))) # expected output [[0, 1, 1], [0, 0, 1]]\n verify_nonzero(input_data, result, dtype=np.int64)\n\n input_data = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]], dtype=np.int64)\n result = np.array((np.nonzero(input_data))) # expected output [[0, 1, 2, 2], [0, 1, 0, 1]]\n verify_nonzero(input_data, result, dtype=np.int64)\n\n\[email protected]_targets\ndef test_topk(target, dev):\n def verify_topk(input_dims, K, axis=-1):\n output_dims = list(input_dims)\n output_dims[axis] = K\n\n node = helper.make_node(\n \"TopK\", inputs=[\"X\", \"K\"], outputs=[\"Values\", \"Indicies\"], axis=axis\n )\n\n graph = helper.make_graph(\n [node],\n \"topk_test\",\n inputs=[\n helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(input_dims)),\n helper.make_tensor_value_info(\n \"K\",\n TensorProto.INT64,\n [\n 1,\n ],\n ),\n ],\n outputs=[\n helper.make_tensor_value_info(\"Values\", TensorProto.FLOAT, output_dims),\n helper.make_tensor_value_info(\"Indicies\", TensorProto.INT64, output_dims),\n ],\n )\n\n model = helper.make_model(graph, producer_name=\"topk_test\")\n\n indata = np.random.uniform(-10, 10, input_dims).astype(np.float32)\n verify_with_ort_with_inputs(\n model, [indata, np.array([K])], use_vm=True, target=target, dev=dev\n )\n\n for n in [12, 32]:\n for shape in [[n], [n, n], [n, n, n]]:\n for k in [1, 5, 10]:\n verify_topk(shape, k)\n\n verify_topk([n, n, n], 5, 0)\n verify_topk([n, n, n], 5, 1)\n verify_topk([n, n, n], 5, 2)\n\n\[email protected]_targets\ndef test_roi_align(target, dev):\n def verify_roi_align(\n input_dims,\n num_roi,\n output_height,\n output_width,\n sampling_ratio=0,\n spatial_scale=1.0,\n mode=\"avg\",\n ):\n output_dims = [num_roi, input_dims[1], output_height, output_width]\n\n node = helper.make_node(\n \"RoiAlign\",\n inputs=[\"X\", \"rois\", \"batch_indicies\"],\n outputs=[\"Y\"],\n mode=mode,\n output_height=output_height,\n output_width=output_width,\n sampling_ratio=sampling_ratio,\n spatial_scale=spatial_scale,\n )\n\n graph = helper.make_graph(\n [node],\n \"roialign_test\",\n inputs=[\n helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(input_dims)),\n helper.make_tensor_value_info(\"rois\", TensorProto.FLOAT, [num_roi, 4]),\n helper.make_tensor_value_info(\n \"batch_indicies\",\n TensorProto.INT64,\n [\n num_roi,\n ],\n ),\n ],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, output_dims)],\n )\n\n model = helper.make_model(graph, producer_name=\"roialign_test\")\n\n np_data = np.random.uniform(size=input_dims).astype(\"float32\")\n np_rois = np.random.uniform(size=[num_roi, 4]).astype(\"float32\") * input_dims[2]\n np_batch_indicies = np.random.randint(low=0, high=input_dims[0], size=num_roi)\n\n verify_with_ort_with_inputs(\n model,\n [np_data, np_rois, np_batch_indicies],\n out_shape=[output_dims],\n target=target,\n dev=dev,\n )\n\n verify_roi_align((1, 4, 16, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0)\n verify_roi_align((4, 4, 16, 32), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0)\n verify_roi_align((1, 8, 16, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0)\n verify_roi_align((1, 4, 8, 8), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0)\n verify_roi_align((1, 4, 16, 16), 16, 5, 7, sampling_ratio=0, spatial_scale=1.0)\n verify_roi_align((1, 4, 16, 12), 8, 7, 3, sampling_ratio=0, spatial_scale=1.0)\n verify_roi_align((1, 4, 16, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=0.5)\n verify_roi_align((3, 4, 12, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=1.5)\n verify_roi_align((5, 4, 16, 14), 32, 7, 7, sampling_ratio=1, spatial_scale=1.0)\n verify_roi_align((1, 4, 16, 16), 32, 7, 7, sampling_ratio=2, spatial_scale=1.0)\n\n # ONNX implementation of roi_align with max mode is incorrect, so we don't compare outputs here.\n\n\[email protected]_targets\ndef test_non_max_suppression(target, dev):\n def verify_nms(\n boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, output_dims\n ):\n input_names = [\"boxes\", \"scores\", \"max_output_boxes_per_class\", \"iou_threshold\"]\n input_nodes = [\n helper.make_tensor_value_info(\"boxes\", TensorProto.FLOAT, boxes.shape),\n helper.make_tensor_value_info(\"scores\", TensorProto.FLOAT, scores.shape),\n helper.make_tensor_value_info(\n \"max_output_boxes_per_class\", TensorProto.INT64, max_output_boxes_per_class.shape\n ),\n helper.make_tensor_value_info(\"iou_threshold\", TensorProto.FLOAT, iou_threshold.shape),\n ]\n inputs = [boxes, scores, max_output_boxes_per_class, iou_threshold]\n if score_threshold is not None:\n input_names.append(\"score_threshold\")\n input_nodes.append(\n helper.make_tensor_value_info(\n \"score_threshold\", TensorProto.FLOAT, score_threshold.shape\n )\n )\n inputs.append(score_threshold)\n node = helper.make_node(\n \"NonMaxSuppression\",\n inputs=input_names,\n outputs=[\"Y\"],\n center_point_box=0,\n )\n\n graph = helper.make_graph(\n [node],\n \"nms_test\",\n inputs=input_nodes,\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.INT64, output_dims)],\n )\n\n model = helper.make_model(graph, producer_name=\"nms_test\")\n\n verify_with_ort_with_inputs(model, inputs, use_vm=True, target=target, dev=dev)\n\n boxes = np.array(\n [\n [\n [0.0, 0.0, 0.3, 0.3],\n [0.0, 0.0, 0.4, 0.4],\n [0.0, 0.0, 0.5, 0.5],\n [0.5, 0.5, 0.9, 0.9],\n [0.5, 0.5, 1.0, 1.0],\n ],\n [\n [0.0, 0.0, 0.3, 0.3],\n [0.0, 0.0, 0.4, 0.4],\n [0.5, 0.5, 0.95, 0.95],\n [0.5, 0.5, 0.96, 0.96],\n [0.5, 0.5, 1.0, 1.0],\n ],\n ]\n ).astype(\"float32\")\n\n scores = np.array(\n [\n [[0.1, 0.2, 0.6, 0.3, 0.9], [0.1, 0.2, 0.6, 0.3, 0.9]],\n [[0.1, 0.2, 0.6, 0.3, 0.9], [0.1, 0.2, 0.6, 0.3, 0.9]],\n ]\n ).astype(\"float32\")\n max_output_boxes_per_class = np.array(2).astype(\"int64\")\n iou_threshold = np.array(0.8).astype(\"float32\")\n output_dims = [8, 3]\n verify_nms(boxes, scores, max_output_boxes_per_class, iou_threshold, None, output_dims)\n\n boxes = np.array(\n [\n [\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0],\n ]\n ]\n ).astype(np.float32)\n scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\n max_output_boxes_per_class = np.array([3]).astype(np.int64)\n iou_threshold = np.array([0.5]).astype(np.float32)\n score_threshold = np.array([0.4]).astype(np.float32)\n output_dims = [2, 3]\n verify_nms(\n boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, output_dims\n )\n\n\[email protected]_targets\ndef test_loop(target, dev):\n def verify_cond_loop():\n y_in = helper.make_tensor_value_info(\"y_in\", TensorProto.FLOAT, [1])\n y_out = helper.make_tensor_value_info(\"y_out\", TensorProto.FLOAT, [1])\n scan_out = helper.make_tensor_value_info(\"scan_out\", TensorProto.FLOAT, [1])\n cond_in = helper.make_tensor_value_info(\"cond_in\", TensorProto.BOOL, [])\n cond_out = helper.make_tensor_value_info(\"cond_out\", TensorProto.BOOL, [])\n iter_count = helper.make_tensor_value_info(\"iter_count\", TensorProto.INT64, [])\n\n y = np.array([-2]).astype(np.float32)\n\n five_const_node = helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[\"five\"],\n value=helper.make_tensor(\n name=\"const_tensor_five\", data_type=TensorProto.FLOAT, dims=(), vals=[5]\n ),\n )\n\n iter_cast_node = helper.make_node(\n \"Cast\", inputs=[\"iter_count\"], outputs=[\"iter_cast\"], to=onnx.TensorProto.FLOAT\n )\n\n y_add_node = helper.make_node(\"Add\", inputs=[\"y_in\", \"iter_cast\"], outputs=[\"y_out\"])\n\n less_node = helper.make_node(\"Less\", inputs=[\"y_out\", \"five\"], outputs=[\"cond_less\"])\n\n squeeze_node = helper.make_node(\"Squeeze\", inputs=[\"cond_less\"], outputs=[\"cond_squeeze\"])\n\n cond_cast_node = helper.make_node(\n \"Cast\", inputs=[\"cond_squeeze\"], outputs=[\"cond_out\"], to=onnx.TensorProto.BOOL\n )\n\n scan_identity_node = helper.make_node(\"Identity\", inputs=[\"y_out\"], outputs=[\"scan_out\"])\n\n loop_body = helper.make_graph(\n [\n five_const_node,\n iter_cast_node,\n y_add_node,\n less_node,\n squeeze_node,\n cond_cast_node,\n scan_identity_node,\n ],\n \"loop_body\",\n [iter_count, cond_in, y_in],\n [cond_out, y_out, scan_out],\n )\n\n loop_node = helper.make_node(\n \"Loop\",\n inputs=[\"trip_count\", \"cond\", \"y\"],\n outputs=[\"res_y\", \"res_scan\"],\n body=loop_body,\n )\n\n trip_count = np.array(5).astype(np.int64)\n res_y = np.array([13]).astype(np.float32)\n cond = np.array(1).astype(bool)\n loop_graph = onnx.helper.make_graph(\n [loop_node],\n \"loop_outer\",\n inputs=[\n onnx.helper.make_tensor_value_info(\"trip_count\", onnx.TensorProto.INT64, []),\n onnx.helper.make_tensor_value_info(\"cond\", onnx.TensorProto.BOOL, []),\n onnx.helper.make_tensor_value_info(\"y\", onnx.TensorProto.FLOAT, [1]),\n ],\n outputs=[\n onnx.helper.make_tensor_value_info(\"res_y\", onnx.TensorProto.FLOAT, [1]),\n onnx.helper.make_tensor_value_info(\"res_scan\", onnx.TensorProto.FLOAT, [5, 1]),\n ],\n )\n loop_model = onnx.helper.make_model(loop_graph)\n\n # Set a high trip count so that condition trips first.\n trip_count = np.array(40).astype(np.int64)\n cond = np.array(1).astype(bool)\n input_vals = [trip_count, cond, y]\n verify_with_ort_with_inputs(\n loop_model,\n input_vals,\n use_vm=True,\n freeze_params=True,\n opset=11,\n target=target,\n dev=dev,\n )\n\n def verify_count_loop():\n y_in = helper.make_tensor_value_info(\"y_in\", TensorProto.FLOAT, [])\n y_out = helper.make_tensor_value_info(\"y_out\", TensorProto.FLOAT, [])\n scan_out = helper.make_tensor_value_info(\"scan_out\", TensorProto.FLOAT, [])\n cond_in = helper.make_tensor_value_info(\"cond_in\", TensorProto.BOOL, [])\n cond_out = helper.make_tensor_value_info(\"cond_out\", TensorProto.BOOL, [])\n iter_count = helper.make_tensor_value_info(\"iter_count\", TensorProto.INT64, [])\n\n y = np.array(-2).astype(np.float32)\n\n iter_cast_node = helper.make_node(\n \"Cast\", inputs=[\"iter_count\"], outputs=[\"iter_cast\"], to=onnx.TensorProto.FLOAT\n )\n\n y_add_node = helper.make_node(\"Add\", inputs=[\"y_in\", \"iter_cast\"], outputs=[\"y_out\"])\n\n identity_node = helper.make_node(\"Identity\", inputs=[\"cond_in\"], outputs=[\"cond_out\"])\n\n scan_identity_node = helper.make_node(\"Identity\", inputs=[\"y_out\"], outputs=[\"scan_out\"])\n\n loop_body = helper.make_graph(\n [identity_node, iter_cast_node, y_add_node, scan_identity_node],\n \"loop_body\",\n [iter_count, cond_in, y_in],\n [cond_out, y_out, scan_out],\n )\n\n loop_node = helper.make_node(\n \"Loop\",\n inputs=[\"trip_count\", \"cond\", \"y\"],\n outputs=[\"res_y\", \"res_scan\"],\n body=loop_body,\n )\n\n trip_count = np.array(5).astype(np.int64)\n res_y = np.array([13]).astype(np.float32)\n cond = np.array(1).astype(bool)\n loop_graph = onnx.helper.make_graph(\n [loop_node],\n \"loop_outer\",\n inputs=[\n onnx.helper.make_tensor_value_info(\"trip_count\", onnx.TensorProto.INT64, []),\n onnx.helper.make_tensor_value_info(\"cond\", onnx.TensorProto.BOOL, []),\n onnx.helper.make_tensor_value_info(\"y\", onnx.TensorProto.FLOAT, []),\n ],\n outputs=[\n onnx.helper.make_tensor_value_info(\"res_y\", onnx.TensorProto.FLOAT, []),\n onnx.helper.make_tensor_value_info(\"res_scan\", onnx.TensorProto.FLOAT, [5]),\n ],\n )\n loop_model = onnx.helper.make_model(loop_graph)\n\n trip_count = np.array(5).astype(np.int64)\n cond = np.array(1).astype(bool)\n input_vals = [trip_count, cond, y]\n verify_with_ort_with_inputs(\n loop_model,\n input_vals,\n use_vm=True,\n freeze_params=True,\n opset=11,\n target=target,\n dev=dev,\n )\n\n def verify_tensor_loop(shapeless_output=False):\n y_in = helper.make_tensor_value_info(\"y_in\", TensorProto.FLOAT, [3, 3, 3, 3])\n y_out = helper.make_tensor_value_info(\"y_out\", TensorProto.FLOAT, [3, 3, 3, 3])\n scan_out = helper.make_tensor_value_info(\"scan_out\", TensorProto.FLOAT, [3, 3, 3, 3])\n cond_in = helper.make_tensor_value_info(\"cond_in\", TensorProto.BOOL, [])\n cond_out = helper.make_tensor_value_info(\"cond_out\", TensorProto.BOOL, [])\n iter_count = helper.make_tensor_value_info(\"iter_count\", TensorProto.INT64, [])\n\n y = np.random.normal(size=[3, 3, 3, 3]).astype(np.float32)\n\n iter_cast_node = helper.make_node(\n \"Cast\", inputs=[\"iter_count\"], outputs=[\"iter_cast\"], to=onnx.TensorProto.FLOAT\n )\n\n y_add_node = helper.make_node(\"Add\", inputs=[\"y_in\", \"iter_cast\"], outputs=[\"y_out\"])\n\n identity_node = helper.make_node(\"Identity\", inputs=[\"cond_in\"], outputs=[\"cond_out\"])\n\n scan_identity_node = helper.make_node(\"Identity\", inputs=[\"y_out\"], outputs=[\"scan_out\"])\n\n loop_body = helper.make_graph(\n [identity_node, iter_cast_node, y_add_node, scan_identity_node],\n \"loop_body\",\n [iter_count, cond_in, y_in],\n [cond_out, y_out, scan_out],\n )\n\n loop_node = helper.make_node(\n \"Loop\",\n inputs=[\"trip_count\", \"cond\", \"y\"],\n outputs=[\"res_y\", \"res_scan\"],\n body=loop_body,\n )\n\n trip_count = np.array(5).astype(np.int64)\n cond = np.array(1).astype(bool)\n\n # Allow testing of malformed nodes since pytorch likes to create these.\n if shapeless_output:\n scan_shape = None\n else:\n scan_shape = [5, 3, 3, 3, 3]\n\n loop_graph = onnx.helper.make_graph(\n [loop_node],\n \"loop_outer\",\n inputs=[\n onnx.helper.make_tensor_value_info(\"trip_count\", onnx.TensorProto.INT64, []),\n onnx.helper.make_tensor_value_info(\"cond\", onnx.TensorProto.BOOL, []),\n onnx.helper.make_tensor_value_info(\"y\", onnx.TensorProto.FLOAT, [3, 3, 3, 3]),\n ],\n outputs=[\n onnx.helper.make_tensor_value_info(\"res_y\", onnx.TensorProto.FLOAT, [3, 3, 3, 3]),\n onnx.helper.make_tensor_value_info(\"res_scan\", onnx.TensorProto.FLOAT, scan_shape),\n ],\n )\n loop_model = onnx.helper.make_model(loop_graph)\n\n trip_count = np.array(5).astype(np.int64)\n cond = np.array(1).astype(bool)\n input_vals = [trip_count, cond, y]\n verify_with_ort_with_inputs(\n loop_model,\n input_vals,\n use_vm=True,\n freeze_params=True,\n convert_to_static=True,\n opset=11,\n target=target,\n dev=dev,\n )\n\n # Test a loop that exits once a condition is met.\n verify_cond_loop()\n # Test a loop that exits after a fixed number of iterations with scalar outputs.\n verify_count_loop()\n # Test a loop that uses an array output.\n verify_tensor_loop()\n # Test a loop that is malformed and has no output shape defined.\n verify_tensor_loop(shapeless_output=True)\n\n\[email protected]_targets\ndef test_if(target, dev):\n def verify_if(cond_array, num_outputs):\n # Given a bool scalar input cond.\n # return constant tensor x if cond is True, otherwise return constant tensor y.\n\n def append_constant_nodes(nodes, outputs, expected, name):\n outputs.append(onnx.helper.make_tensor_value_info(name, onnx.TensorProto.FLOAT, [5]))\n\n expected.append(np.random.randn(5).astype(\"float32\"))\n\n nodes.append(\n onnx.helper.make_node(\n \"Constant\",\n inputs=[],\n outputs=[name],\n value=numpy_helper.from_array(expected[-1]),\n )\n )\n\n if_outputs = []\n graph_outputs = []\n\n then_nodes, then_outs, then_expected = [], [], []\n else_nodes, else_outs, else_expected = [], [], []\n\n for i in range(num_outputs):\n append_constant_nodes(then_nodes, then_outs, then_expected, \"then_out{}\".format(i))\n append_constant_nodes(else_nodes, else_outs, else_expected, \"else_out{}\".format(i))\n\n if_outputs.append(\"res{}\".format(i))\n graph_outputs.append(\n onnx.helper.make_tensor_value_info(\"res{}\".format(i), onnx.TensorProto.FLOAT, [5]),\n )\n\n then_body = onnx.helper.make_graph(then_nodes, \"then_body\", [], then_outs)\n else_body = onnx.helper.make_graph(else_nodes, \"else_body\", [], else_outs)\n\n if_node = onnx.helper.make_node(\n \"If\", inputs=[\"cond\"], outputs=if_outputs, then_branch=then_body, else_branch=else_body\n )\n\n if_graph = onnx.helper.make_graph(\n [if_node],\n \"if_outer\",\n inputs=[\n onnx.helper.make_tensor_value_info(\"cond\", onnx.TensorProto.BOOL, []),\n ],\n outputs=graph_outputs,\n )\n\n if_model = onnx.helper.make_model(if_graph)\n if cond_array:\n cond = np.array([1]).astype(\"bool\")\n else:\n cond = np.array(1).astype(\"bool\")\n correct_out = then_expected if cond else else_expected\n\n # TODO(jwfromm): Onnxruntime 1.0.0 is buggy with If statements. Replace this with\n # verify_with_ort once we update versions.\n tvm_out = get_tvm_output_with_vm(if_model, [cond], target, dev, freeze_params=True)\n if not isinstance(tvm_out, list):\n tvm_out = [tvm_out]\n for i in range(len(tvm_out)):\n tvm.testing.assert_allclose(correct_out[i], tvm_out[i], rtol=1e-05, atol=1e-05)\n\n # Confirm that if works with cond as an array or scalar.\n verify_if(cond_array=False, num_outputs=1)\n verify_if(cond_array=False, num_outputs=2)\n verify_if(cond_array=True, num_outputs=1)\n verify_if(cond_array=True, num_outputs=2)\n\n\[email protected]_targets\ndef test_size(target, dev):\n def verify_size(indata):\n node = helper.make_node(\n \"Size\",\n inputs=[\"X\"],\n outputs=[\"Y\"],\n )\n\n graph = helper.make_graph(\n [node],\n \"size_test\",\n inputs=[helper.make_tensor_value_info(\"X\", TensorProto.INT64, list(indata.shape))],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.INT64, [])],\n )\n\n model = helper.make_model(graph, producer_name=\"size_test\")\n\n verify_with_ort_with_inputs(\n model, [indata], dtype=\"int64\", use_vm=True, opset=11, target=target, dev=dev\n )\n\n input_data = np.array([[1, 0], [1, 1]], dtype=np.int64)\n verify_size(input_data)\n\n input_data = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]], dtype=np.int64)\n verify_size(input_data)\n\n\[email protected]_targets\ndef test_maxunpool(target, dev):\n def verify_maxunpool(data, indices, kernel_shape, strides, output_shape=None, pads=None):\n input_names = [\"xT\", \"xI\"]\n input_info = [\n helper.make_tensor_value_info(\"xT\", TensorProto.FLOAT, list(data.shape)),\n helper.make_tensor_value_info(\"xI\", TensorProto.INT64, list(indices.shape)),\n ]\n input_values = [data, indices]\n if output_shape is not None:\n input_names.append(\"output_shape\")\n input_info.append(\n helper.make_tensor_value_info(\n \"output_shape\", TensorProto.INT64, list(output_shape.shape)\n )\n )\n input_values.append(output_shape)\n else:\n # Compute expected output shape\n output_shape = np.asarray(([1, 1] + list(strides))) * np.asarray(list(data.shape))\n output_shape += np.asarray(([0, 0] + list(kernel_shape))) - np.asarray(\n ([0, 0] + list(strides))\n )\n if pads is not None:\n output_shape -= np.asarray(\n [0, 0] + list(np.sum(np.reshape(list(pads), [-1, 2]), axis=-1))\n )\n output_shape = [int(i) for i in output_shape]\n\n node = helper.make_node(\n \"MaxUnpool\", inputs=input_names, outputs=[\"y\"], kernel_shape=kernel_shape\n )\n\n if pads is not None:\n pad_attr = helper.make_attribute(\"pads\", pads)\n node.attribute.append(pad_attr)\n\n if strides is not None:\n strides_attr = helper.make_attribute(\"strides\", strides)\n node.attribute.append(strides_attr)\n\n graph = helper.make_graph(\n [node],\n \"maxunpool_test\",\n inputs=input_info,\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, output_shape)],\n )\n\n model = helper.make_model(graph, producer_name=\"size_test\")\n\n verify_with_ort_with_inputs(\n model, input_values, use_vm=True, opset=11, target=target, dev=dev\n )\n\n # Basic test\n xT = np.array([[[[5, 6], [7, 8]]]], dtype=np.float32)\n xI = np.array([[[[0, 7], [13, 15]]]], dtype=np.int64)\n verify_maxunpool(xT, xI, [2, 2], strides=[2, 2])\n # Small stride\n verify_maxunpool(xT, xI, [2, 2], strides=[1, 1])\n # Big kernel\n verify_maxunpool(xT, xI, [3, 3], strides=[2, 2])\n # With output shape\n output_shape = np.array((1, 1, 5, 5), dtype=np.int64)\n verify_maxunpool(xT, xI, [2, 2], strides=[2, 2], output_shape=output_shape)\n # With explicit reverse padding\n pads = np.asarray([1, 1, 1, 1]).astype(np.int64)\n verify_maxunpool(xT, xI, [2, 2], strides=[2, 2], pads=pads)\n\n\[email protected]_targets\ndef test_softplus(target, dev):\n def verify_softplus(indata):\n node = helper.make_node(\n \"Softplus\",\n inputs=[\"X\"],\n outputs=[\"Y\"],\n )\n\n graph = helper.make_graph(\n [node],\n \"softplus_test\",\n inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(indata.shape))],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(indata.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"softplus_test\")\n\n verify_with_ort_with_inputs(\n model, [indata], dtype=\"float32\", use_vm=True, opset=11, target=target, dev=dev\n )\n\n # Simple case with all signs.\n input_data = np.array([[-1, 0, 1]], dtype=np.float32)\n verify_softplus(input_data)\n # More fancy case.\n input_data = np.random.randn(1, 32, 32, 3).astype(\"float32\")\n verify_softplus(input_data)\n\n\[email protected]_targets\ndef test_cumsum(target, dev):\n def verify_cumsum(indata, axis, exclusive=0, reverse=0, type=\"float32\"):\n cumsum_node = onnx.helper.make_node(\n \"CumSum\",\n inputs=[\"X\", \"axis\"],\n outputs=[\"Y\"],\n )\n if exclusive != 0:\n exclusive_attr = helper.make_attribute(\"exclusive\", exclusive)\n cumsum_node.attribute.append(exclusive_attr)\n if reverse != 0:\n reverse_attr = helper.make_attribute(\"reverse\", reverse)\n cumsum_node.attribute.append(reverse_attr)\n nodes = [\n make_constant_node(\"axis\", onnx.TensorProto.INT32, [1], [axis]),\n cumsum_node,\n ]\n if type == \"float32\":\n tensor_type = TensorProto.FLOAT\n else:\n tensor_type = TensorProto.INT32\n type = \"int32\"\n\n graph = helper.make_graph(\n nodes,\n \"cumsum_test\",\n inputs=[\n helper.make_tensor_value_info(\"X\", tensor_type, list(indata.shape)),\n ],\n outputs=[helper.make_tensor_value_info(\"Y\", tensor_type, list(indata.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"cumsum_test\")\n\n verify_with_ort_with_inputs(\n model, [indata], dtype=type, use_vm=True, opset=11, target=target, dev=dev\n )\n\n data = (\n np.array(\n [\n 1.0,\n 2.0,\n 3.0,\n 4.0,\n 5.0,\n 6.0,\n 7.0,\n 8.0,\n 9.0,\n 10.0,\n 11.0,\n 12.0,\n ]\n )\n .astype(np.float32)\n .reshape((3, 4))\n )\n\n verify_cumsum(data, 0)\n verify_cumsum(data, 1)\n verify_cumsum(data, 0, 1, 0)\n verify_cumsum(data, 1, 1, 0)\n verify_cumsum(data, 0, 0, 1)\n verify_cumsum(data, 1, 0, 1)\n verify_cumsum(data, 1, 1, 1)\n data = np.random.randn(1, 32, 32, 3).astype(\"float32\")\n verify_cumsum(data, 1)\n data = np.random.randn(1, 32, 32, 3).astype(\"int32\")\n verify_cumsum(data, 0, type=\"int32\")\n verify_cumsum(data, 1, type=\"int32\")\n verify_cumsum(data, 0, 1, 0, type=\"int32\")\n verify_cumsum(data, 1, 1, 0, type=\"int32\")\n verify_cumsum(data, 0, 0, 1, type=\"int32\")\n verify_cumsum(data, 1, 0, 1, type=\"int32\")\n verify_cumsum(data, 1, 1, 1, type=\"int32\")\n\n\[email protected]_targets\ndef test_eyelike(target, dev):\n def verify_eyelike(indata):\n node = helper.make_node(\n \"EyeLike\",\n inputs=[\"X\"],\n outputs=[\"Y\"],\n )\n\n graph = helper.make_graph(\n [node],\n \"eyelike_test\",\n inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list(indata.shape))],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list(indata.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"eyelike_test\")\n\n verify_with_ort_with_inputs(\n model, [indata], dtype=\"float32\", opset=9, target=target, dev=dev\n )\n\n input_data = np.zeros((5, 5), dtype=np.float32)\n verify_eyelike(input_data)\n\n\n\"\"\"\n The following parametrized tests loads the tests that ONNX ships as\n serialized ONNX files, inputs, and outputs. The goal of this test\n is to ensure the ONNX importer is in line with the ONNX specification.\n To allow these tests to run in CI before all pass, a number of tests that\n are not yet supported are skipped.\n\"\"\"\n\nonnx_test_node_dir = os.path.join(os.path.dirname(onnx.__file__), \"backend\", \"test\", \"data\", \"node\")\n\nonnx_test_folders = sorted(\n dirname\n for dirname in os.listdir(onnx_test_node_dir)\n if dirname.startswith(\"test\") and os.path.isdir(os.path.join(onnx_test_node_dir, dirname))\n)\n\nunsupported_onnx_tests = [\n \"test_cast_BFLOAT16_to_FLOAT\",\n \"test_cast_DOUBLE_to_FLOAT16\",\n \"test_cast_FLOAT_to_BFLOAT16\",\n \"test_cast_FLOAT_to_STRING\",\n \"test_cast_STRING_to_FLOAT\",\n \"test_convtranspose_dilations\",\n \"test_convtranspose_output_shape\",\n \"test_cumsum_1d\",\n \"test_cumsum_1d_exclusive\",\n \"test_cumsum_1d_reverse\",\n \"test_cumsum_1d_reverse_exclusive\",\n \"test_cumsum_2d_axis_0\",\n \"test_cumsum_2d_axis_1\",\n \"test_cumsum_2d_negative_axis\",\n \"test_det_2d\",\n \"test_det_nd\",\n \"test_dropout_default\",\n \"test_dropout_default_mask\",\n \"test_dropout_default_mask_ratio\",\n \"test_dropout_default_ratio\",\n \"test_if_seq\",\n \"test_loop11\",\n \"test_loop13_seq\",\n \"test_matmulinteger\",\n \"test_maxpool_2d_same_lower\",\n \"test_maxpool_2d_same_upper\",\n \"test_maxpool_with_argmax_2d_precomputed_pads\",\n \"test_maxpool_with_argmax_2d_precomputed_strides\",\n \"test_maxunpool_export_with_output_shape\",\n \"test_mvn\",\n # When unsqueeze is fully supported, remaining nllloss tests should work:\n \"test_nllloss_NC_expanded\",\n \"test_nllloss_NCd1_expanded\",\n \"test_nllloss_NCd1_ii_expanded\",\n \"test_nllloss_NCd1_mean_weight_negative_ii_expanded\",\n \"test_nllloss_NCd1_weight_expanded\",\n \"test_nllloss_NCd1_weight_ii_expanded\",\n \"test_nllloss_NCd1d2_expanded\",\n \"test_nllloss_NCd1d2_no_weight_reduction_mean_ii_expanded\",\n \"test_nllloss_NCd1d2_reduction_mean_expanded\",\n \"test_nllloss_NCd1d2_reduction_sum_expanded\",\n \"test_nllloss_NCd1d2_with_weight_expanded\",\n \"test_nllloss_NCd1d2_with_weight_reduction_mean_expanded\",\n \"test_nllloss_NCd1d2_with_weight_reduction_sum_expanded\",\n \"test_nllloss_NCd1d2_with_weight_reduction_sum_ii_expanded\",\n \"test_nllloss_NCd1d2d3_none_no_weight_negative_ii_expanded\",\n \"test_nllloss_NCd1d2d3_sum_weight_high_ii_expanded\",\n \"test_nllloss_NCd1d2d3d4d5_mean_weight_expanded\",\n \"test_nllloss_NCd1d2d3d4d5_none_no_weight_expanded\",\n \"test_qlinearmatmul_2D\",\n \"test_qlinearmatmul_3D\",\n \"test_range_float_type_positive_delta_expanded\",\n \"test_range_int32_type_negative_delta_expanded\",\n \"test_reduce_sum_default_axes_keepdims_example\",\n \"test_reduce_sum_default_axes_keepdims_random\",\n \"test_reduce_sum_do_not_keepdims_example\",\n \"test_reduce_sum_do_not_keepdims_random\",\n \"test_reduce_sum_empty_axes_input_noop_example\",\n \"test_reduce_sum_empty_axes_input_noop_random\",\n \"test_reduce_sum_keepdims_example\",\n \"test_reduce_sum_keepdims_random\",\n \"test_reduce_sum_negative_axes_keepdims_example\",\n \"test_reduce_sum_negative_axes_keepdims_random\",\n \"test_resize_downsample_sizes_cubic\",\n \"test_resize_downsample_sizes_linear_pytorch_half_pixel\",\n \"test_resize_downsample_sizes_nearest\",\n \"test_resize_tf_crop_and_resize\",\n \"test_resize_upsample_sizes_cubic\",\n \"test_resize_upsample_sizes_nearest\",\n \"test_resize_upsample_sizes_nearest_ceil_half_pixel\",\n \"test_resize_upsample_sizes_nearest_floor_align_corners\",\n \"test_resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric\",\n \"test_rnn_seq_length\",\n \"test_round\",\n \"test_scan9_sum\",\n \"test_scan_sum\",\n \"test_sequence_insert_at_back\",\n \"test_sequence_insert_at_front\",\n \"test_simple_rnn_defaults\",\n \"test_simple_rnn_with_initial_bias\",\n \"test_split_variable_parts_1d\",\n \"test_split_variable_parts_2d\",\n \"test_split_variable_parts_default_axis\",\n \"test_split_zero_size_splits\",\n \"test_strnormalizer_export_monday_casesensintive_lower\",\n \"test_strnormalizer_export_monday_casesensintive_nochangecase\",\n \"test_strnormalizer_export_monday_casesensintive_upper\",\n \"test_strnormalizer_export_monday_empty_output\",\n \"test_strnormalizer_export_monday_insensintive_upper_twodim\",\n \"test_strnormalizer_nostopwords_nochangecase\",\n \"test_tfidfvectorizer_tf_batch_onlybigrams_skip0\",\n \"test_tfidfvectorizer_tf_batch_onlybigrams_skip5\",\n \"test_tfidfvectorizer_tf_batch_uniandbigrams_skip5\",\n \"test_tfidfvectorizer_tf_only_bigrams_skip0\",\n \"test_tfidfvectorizer_tf_onlybigrams_levelempty\",\n \"test_tfidfvectorizer_tf_onlybigrams_skip5\",\n \"test_tfidfvectorizer_tf_uniandbigrams_skip5\",\n \"test_training_dropout\",\n \"test_training_dropout_default\",\n \"test_training_dropout_default_mask\",\n \"test_training_dropout_mask\",\n \"test_training_dropout_zero_ratio\",\n \"test_training_dropout_zero_ratio_mask\",\n # These unsqueeze tests work, but take 2+ hrs to run\n \"test_unsqueeze_three_axes\",\n \"test_unsqueeze_two_axes\",\n \"test_unsqueeze_unsorted_axes\",\n \"test_unique_sorted_with_axis\",\n \"test_unique_sorted_with_axis_3d\",\n \"test_unique_sorted_with_negative_axis\",\n \"test_upsample_nearest\",\n]\n\n\ntarget_skips = {\n \"cuda\": [\n \"test_range_float_type_positive_delta_expanded\",\n \"test_range_int32_type_positive_delta_expanded\",\n \"test_mod_mixed_sign_float16\",\n \"test_qlinearconv\",\n \"test_resize_upsample_sizes_nearest\",\n ]\n}\n\n\[email protected](\"onnx_test\", onnx_test_folders)\[email protected]_targets\ndef test_onnx_nodes(target, dev, onnx_test):\n target_kind = tvm.target.Target(target).kind.name\n\n if onnx_test in unsupported_onnx_tests:\n pytest.skip(f\"Onnx test '{onnx_test}' not yet supported by TVM\")\n\n target_specific_skips = target_skips.get(target_kind, [])\n if onnx_test in target_specific_skips:\n pytest.skip(f\"Onnx test '{onnx_test}' not yet supported by TVM on {target_kind} targets\")\n\n test_dir = os.path.join(onnx_test_node_dir, onnx_test)\n\n atol = 1e-5\n rtol = 1e-5\n if \"roialign\" in test_dir:\n # for some reason the ONNX test crops the\n # roialign results to 4 decimal places\n atol = 1e-4\n\n if \"_sce_\" in test_dir:\n # complicated loss functions like SoftmaxCrossEntropy can have minor variations\n # in accuracy depending on implementation\n atol = 1e-4\n\n onnx_model = onnx.load(test_dir + \"/model.onnx\")\n inputs = []\n outputs = []\n for dataset in glob.glob(test_dir + \"/*/\"):\n tensors = sorted(glob.glob(dataset + \"/*.pb\"))\n for tensor in tensors:\n new_tensor = onnx.TensorProto()\n with open(tensor, \"rb\") as f:\n new_tensor.ParseFromString(f.read())\n if \"input\" in tensor.split(\"/\")[-1]:\n inputs.append(numpy_helper.to_array(new_tensor))\n elif \"output\" in tensor.split(\"/\")[-1]:\n outputs.append(numpy_helper.to_array(new_tensor))\n else:\n raise ImportError(str(tensor) + \" not labeled as an import or an output\")\n\n tvm_val = get_tvm_output_with_vm(onnx_model, inputs, target, dev)\n if len(outputs) == 1:\n tvm.testing.assert_allclose(outputs[0], tvm_val, rtol=rtol, atol=atol)\n else:\n for output, val in zip(outputs, tvm_val):\n tvm.testing.assert_allclose(output, val, rtol=rtol, atol=atol)\n\n\ndef test_wrong_input():\n node = helper.make_node(\n \"Softplus\",\n inputs=[\"X\"],\n outputs=[\"Y\"],\n )\n\n graph = helper.make_graph(\n [node],\n \"softplus_test\",\n inputs=[helper.make_tensor_value_info(\"X\", TensorProto.FLOAT, list([5]))],\n outputs=[helper.make_tensor_value_info(\"Y\", TensorProto.FLOAT, list([5]))],\n )\n model = helper.make_model(graph, producer_name=\"softplus_test\")\n\n # Check that the graph can import correctly with proper shape definitions.\n correct_shape_dict = {\"X\": [5]}\n relay.frontend.from_onnx(model, shape=correct_shape_dict)\n\n # Check that an assertion is triggered when an input not in the graph is provided.\n wrong_shape_dict = {\"Z\": [5]}\n with pytest.raises(AssertionError):\n relay.frontend.from_onnx(model, shape=wrong_shape_dict)\n\n\[email protected]_targets\ndef test_aten(target, dev):\n torch.set_grad_enabled(False)\n\n def _convert_to_onnx(model, inputs):\n file_name = \"{}.onnx\".format(\"aten_model\")\n torch.onnx.export(\n model,\n inputs,\n file_name,\n export_params=True,\n verbose=False,\n opset_version=10,\n operator_export_type=torch.onnx.OperatorExportTypes.ONNX_ATEN,\n )\n onnx_model = onnx.load(file_name)\n assert 's: \"embedding_bag\"' in str(onnx_model)\n return onnx_model\n\n def verify_embedding_bag(num_embedding, embedding_dim, data_shape, num_bags=None):\n dummy_data = torch.randint(0, num_embedding - 1, data_shape)\n tvm_inputs = [dummy_data.numpy()]\n model = torch.nn.EmbeddingBag(num_embedding, embedding_dim)\n onnx_model = _convert_to_onnx(model, dummy_data)\n torch_out = model(dummy_data)\n tvm_out = get_tvm_output_with_vm(\n onnx_model,\n tvm_inputs,\n freeze_params=True,\n convert_to_static=True,\n target=target,\n dev=dev,\n )\n tvm.testing.assert_allclose(torch_out.numpy(), tvm_out, atol=5e-7)\n\n verify_embedding_bag(10, 3, [2, 10])\n verify_embedding_bag(32, 2, [3, 3])\n\n\[email protected]_targets\ndef test_index_put(target, dev):\n class _index_put_model(torch.nn.Module):\n def __init__(self, indices, values, accumulate):\n super(_index_put_model, self).__init__()\n self.indices = indices\n self.values = values\n self.accumulate = accumulate\n\n def forward(self, x):\n return x.index_put(self.indices, self.values, self.accumulate)\n\n def _convert_to_onnx(model, dummy_data):\n file_name = \"{}.onnx\".format(\"aten_model\")\n torch.onnx.export(\n model,\n dummy_data,\n file_name,\n export_params=True,\n verbose=False,\n opset_version=11,\n operator_export_type=torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK,\n )\n onnx_model = onnx.load(file_name)\n return onnx_model\n\n def verify_index_put(data_shape, indices, accumulate):\n dummy_data = torch.ones(data_shape)\n tvm_inputs = [dummy_data.numpy()]\n values = torch.rand(indices[0].size())\n model = _index_put_model(indices, values, accumulate)\n onnx_model = _convert_to_onnx(model, dummy_data)\n torch_out = model(dummy_data)\n\n tvm_out = get_tvm_output_with_vm(\n onnx_model, tvm_inputs, target, dev, freeze_params=True, convert_to_static=True\n )\n tvm.testing.assert_allclose(torch_out.numpy(), tvm_out)\n\n shape = (3, 5)\n xidx = torch.tensor([0, 1, 2, 2])\n yidx = torch.tensor([0, 1, 3, 4])\n verify_index_put(shape, [xidx, yidx], True)\n\n shape = (3, 5, 3)\n xidx = torch.tensor([0, 1, 2, 2, 0])\n yidx = torch.tensor([0, 1, 3, 4, 0])\n zidx = torch.tensor([0, 1, 1, 2, 0])\n verify_index_put(shape, [xidx, yidx, zidx], False)\n\n def verify_index_put_slice(data_shape, value_shape, accumulate):\n dummy_data = torch.ones(data_shape)\n tvm_inputs = [dummy_data.numpy()]\n indices = []\n index_shape = [1] * len(value_shape)\n index_shape[0] = -1\n for i in range(len(value_shape)):\n indices.append(torch.arange(0, value_shape[i]).reshape(tuple(index_shape)))\n index_shape.pop()\n values = torch.rand(value_shape)\n\n model = _index_put_model(indices, values, accumulate)\n onnx_model = _convert_to_onnx(model, dummy_data)\n torch_out = model(dummy_data)\n\n tvm_out = get_tvm_output_with_vm(\n onnx_model, tvm_inputs, target, dev, freeze_params=True, convert_to_static=True\n )\n tvm.testing.assert_allclose(torch_out.numpy(), tvm_out)\n\n verify_index_put_slice((3, 3), (2, 2), False)\n verify_index_put_slice((2, 3, 4), (1, 2, 3), True)\n verify_index_put_slice((2, 3, 4, 5), (1, 2, 3, 1), False)\n\n\[email protected]_targets\ndef test_reverse_sequence(target, dev):\n def verify_reverse_sequence(x, sequence_lens, batch_axis, time_axis):\n node = onnx.helper.make_node(\n \"ReverseSequence\",\n inputs=[\"x\", \"sequence_lens\"],\n outputs=[\"y\"],\n time_axis=time_axis,\n batch_axis=batch_axis,\n )\n\n graph = helper.make_graph(\n [node],\n \"reverse_sequence_test\",\n inputs=[\n helper.make_tensor_value_info(\"x\", TensorProto.FLOAT, list(x.shape)),\n helper.make_tensor_value_info(\n \"sequence_lens\", TensorProto.INT64, list(sequence_lens.shape)\n ),\n ],\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.FLOAT, list(x.shape))],\n )\n\n model = helper.make_model(graph, producer_name=\"reverse_sequence_test\")\n verify_with_ort_with_inputs(model, [x, sequence_lens], [x.shape], target=target, dev=dev)\n\n x = np.array(\n [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]],\n dtype=np.float32,\n )\n sequence_lens = np.array([1, 2, 3, 4], dtype=np.int64)\n verify_reverse_sequence(x, sequence_lens, 0, 1)\n\n sequence_lens = np.array([4, 3, 2, 1], dtype=np.int64)\n verify_reverse_sequence(x, sequence_lens, 1, 0)\n\n\[email protected]_failing_targets(\"cuda\")\[email protected]_targets\ndef test_qlinearconv(target, dev):\n def verify_qlinearconv(\n x_shape,\n w_shape,\n y_shape,\n padding,\n kernel_shape,\n strides,\n dilations,\n auto_pad=\"NOTSET\",\n bias=False,\n ):\n\n x_array = np.random.randint(low=0, high=255, size=x_shape).astype(\"uint8\")\n w_array = np.random.uniform(low=0, high=255, size=w_shape).astype(\"uint8\")\n\n initializer = [\n helper.make_tensor(\"x_scale\", TensorProto.FLOAT, (), [np.random.rand()]),\n helper.make_tensor(\"x_zero_point\", TensorProto.UINT8, (), [np.random.randint(0, 255)]),\n helper.make_tensor(\"w_scale\", TensorProto.FLOAT, (), [np.random.rand()]),\n helper.make_tensor(\"w_zero_point\", TensorProto.UINT8, (), [np.random.randint(0, 255)]),\n helper.make_tensor(\"y_scale\", TensorProto.FLOAT, (), [np.random.rand()]),\n helper.make_tensor(\"y_zero_point\", TensorProto.UINT8, (), [np.random.randint(0, 255)]),\n ]\n\n input_nodes = [\n helper.make_tensor_value_info(\"x\", TensorProto.UINT8, list(x_shape)),\n helper.make_tensor_value_info(\"w\", TensorProto.UINT8, list(w_shape)),\n ]\n input_names = [\n \"x\",\n \"x_scale\",\n \"x_zero_point\",\n \"w\",\n \"w_scale\",\n \"w_zero_point\",\n \"y_scale\",\n \"y_zero_point\",\n ]\n input_values = [x_array, w_array]\n\n if bias is True:\n b_shape = w_shape[0:1]\n b_array = np.random.randint(low=0, high=65536, size=b_shape).astype(\"int32\")\n input_nodes.append(helper.make_tensor_value_info(\"B\", TensorProto.INT32, list(b_shape)))\n input_names.append(\"B\")\n input_values.append(b_array)\n\n if padding is None:\n ## autopadding with unset default attributes\n kwargs = {}\n if not all([s == 1 for s in strides]):\n kwargs[\"strides\"] = strides\n if not all([d == 1 for d in dilations]):\n kwargs[\"dilations\"] = dilations\n\n node = helper.make_node(\n \"QLinearConv\",\n inputs=input_names,\n outputs=[\"y\"],\n # Default values for other attributes:\n auto_pad=auto_pad,\n **kwargs,\n )\n else:\n node = helper.make_node(\n \"QLinearConv\",\n inputs=input_names,\n outputs=[\"y\"],\n kernel_shape=kernel_shape,\n # Default values for other attributes:\n strides=strides,\n dilations=dilations,\n # groups=1\n pads=padding,\n )\n\n graph = helper.make_graph(\n [node],\n \"conv_test\",\n inputs=input_nodes,\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.UINT8, list(y_shape))],\n initializer=initializer,\n )\n model = helper.make_model(graph, producer_name=\"qlinearconv_test\")\n # opt_level=1 will cause error\n verify_with_ort_with_inputs(model, input_values, opt_level=2, target=target, dev=dev)\n\n def repeat(N, D):\n return tuple([N for _ in range(D)])\n\n # only support QLinearConv2d because only support qnn.conv2d\n D = 2\n\n # Convolution with padding\n verify_qlinearconv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(5, D),\n 2 * repeat(1, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n\n # Convolution with bias\n verify_qlinearconv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(5, D),\n 2 * repeat(1, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n bias=True,\n )\n\n # Convolution with asymmetric padding\n verify_qlinearconv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(4, D),\n repeat(0, D) + repeat(1, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n # Convolution without padding\n verify_qlinearconv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(3, D),\n 2 * repeat(0, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n # Convolution with autopadding\n verify_qlinearconv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(5, D),\n None,\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n auto_pad=\"SAME_UPPER\",\n )\n # Convolution with valid autopadding\n verify_qlinearconv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(3, D),\n None,\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n auto_pad=\"VALID\",\n )\n # Convolution with non uniform stride\n verify_qlinearconv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(3, D),\n None,\n repeat(3, D),\n repeat(2, D),\n repeat(1, D),\n auto_pad=\"SAME_UPPER\",\n )\n # Convolution with dilation\n verify_qlinearconv(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(5, D),\n 2 * repeat(2, D),\n repeat(3, D),\n repeat(1, D),\n repeat(2, D),\n )\n\n\[email protected]_targets\ndef test_qlinearconcat(target, dev):\n def verify_qlinearconcat(shapes, out_shape, axis=None):\n input_names = []\n input_values = []\n input_nodes = []\n for i in range(len(shapes)):\n tensor_name = chr(ord(\"a\") + i)\n shape = shapes[i]\n node = helper.make_tensor_value_info(tensor_name, TensorProto.FLOAT, list(shape))\n\n input_names.append(tensor_name)\n input_values.append(np.random.random(shape).astype(\"float32\"))\n input_nodes.append(node)\n\n node = helper.make_node(\"Concat\", input_names, [\"C\"])\n if axis is not None:\n axis_attr = helper.make_attribute(\"axis\", axis)\n node.attribute.append(axis_attr)\n graph = helper.make_graph(\n [node],\n \"qlinearconcat_test\",\n inputs=input_nodes,\n outputs=[helper.make_tensor_value_info(\"C\", TensorProto.FLOAT, list(out_shape))],\n )\n model = helper.make_model(graph, producer_name=\"qlinearconcat_test\")\n quantize_and_verify_with_ort(model, input_names, shapes, target, dev)\n\n verify_qlinearconcat([[2, 1], [2, 1]], [4, 1], 0)\n verify_qlinearconcat([[2, 1], [2, 1]], [2, 2], 1)\n verify_qlinearconcat([[1, 2], [2, 2], [3, 2]], [6, 2], 0)\n\n\[email protected]_targets\ndef test_qlinearadd(target, dev):\n def verify_qlinearadd(a_shape, b_shape, c_shape):\n\n a_array = np.random.random(a_shape).astype(\"float32\")\n b_array = np.random.random(b_shape).astype(\"float32\")\n\n input_nodes = [\n helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n ]\n input_names = [\n \"a\",\n \"b\",\n ]\n input_values = [a_array, b_array]\n\n node = helper.make_node(\"Add\", [\"a\", \"b\"], [\"C\"])\n graph = helper.make_graph(\n [node],\n \"qlinearadd_test\",\n inputs=input_nodes,\n outputs=[helper.make_tensor_value_info(\"C\", TensorProto.FLOAT, list(c_shape))],\n )\n model = helper.make_model(graph, producer_name=\"qlinearadd_test\")\n quantize_and_verify_with_ort(model, input_names, [a_shape, b_shape], target, dev)\n\n verify_qlinearadd([4, 2], [4, 2], [4, 2])\n verify_qlinearadd([4, 2], [2], [4, 2])\n verify_qlinearadd([5, 1, 7], [2, 7], [5, 2, 7])\n\n\[email protected]_targets\ndef test_qlinearmul(target, dev):\n def verify_qlinearmul(a_shape, b_shape, c_shape):\n\n a_array = np.random.random(a_shape).astype(\"float32\")\n b_array = np.random.random(b_shape).astype(\"float32\")\n\n input_nodes = [\n helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape)),\n helper.make_tensor_value_info(\"b\", TensorProto.FLOAT, list(b_shape)),\n ]\n input_names = [\n \"a\",\n \"b\",\n ]\n input_values = [a_array, b_array]\n\n node = helper.make_node(\"Mul\", input_names, [\"C\"])\n graph = helper.make_graph(\n [node],\n \"qlinearmul_test\",\n inputs=input_nodes,\n outputs=[helper.make_tensor_value_info(\"C\", TensorProto.FLOAT, list(c_shape))],\n )\n model = helper.make_model(graph, producer_name=\"qlinearmul_test\")\n quantize_and_verify_with_ort(model, input_names, [a_shape, b_shape], target, dev)\n\n verify_qlinearmul([7], [7], [7])\n verify_qlinearmul([4, 2], [4, 2], [4, 2])\n verify_qlinearmul([4, 2], [2], [4, 2])\n verify_qlinearmul([5, 1, 7], [2, 7], [5, 2, 7])\n\n\[email protected]_targets\ndef test_qlinearsigmoid(target, dev):\n def verify_qlinearsigmoid(a_shape):\n\n a_array = np.random.random(a_shape).astype(\"float32\")\n\n input_nodes = [helper.make_tensor_value_info(\"a\", TensorProto.FLOAT, list(a_shape))]\n\n input_values = [a_array]\n\n node = helper.make_node(\"Sigmoid\", [\"a\"], [\"B\"])\n graph = helper.make_graph(\n [node],\n \"qlinearsigmoid_test\",\n inputs=input_nodes,\n outputs=[helper.make_tensor_value_info(\"B\", TensorProto.FLOAT, list(a_shape))],\n )\n model = helper.make_model(graph, producer_name=\"qlinearsigmoid_test\")\n quantize_and_verify_with_ort(model, [\"a\"], [a_shape], target, dev)\n\n verify_qlinearsigmoid([4, 2])\n verify_qlinearsigmoid([5])\n verify_qlinearsigmoid([3, 4, 5])\n verify_qlinearsigmoid([])\n\n\[email protected]_targets\ndef test_random_uniform(target, dev):\n def get_random_uniform(shape, dtype=\"float32\", high=1.0, low=0.0, seed=None):\n ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n node = helper.make_node(\n \"RandomUniform\", [], [\"out\"], shape=shape, dtype=ONNX_DTYPE, high=high, low=low\n )\n if seed is not None:\n seed_attr = helper.make_attribute(\"seed\", seed)\n node.attribute.append(seed_attr)\n\n graph = helper.make_graph(\n [node],\n \"random_uniform_test\",\n inputs=[],\n outputs=[helper.make_tensor_value_info(\"out\", ONNX_DTYPE, shape)],\n )\n model = helper.make_model(graph, producer_name=\"random_uniform_test\")\n return get_tvm_output_with_vm(model, [], target=target, dev=dev)\n\n # Check that function runs and produces proper shape.\n vals = get_random_uniform([10], dtype=\"float32\")\n assert list(vals.shape) == [10]\n assert vals.dtype == \"float32\"\n\n # Test N-D tensor generation.\n vals = get_random_uniform([1, 3, 100, 100], dtype=\"float32\")\n assert list(vals.shape) == [1, 3, 100, 100]\n\n # Check that bounds aren't exceeded.\n vals = get_random_uniform(shape=[100], high=100, low=-100)\n assert list(vals.shape) == [100]\n assert all(vals >= -100) and all(vals <= 100)\n\n # Check that a fixed seed produces the same values when run twice.\n vals_1 = get_random_uniform(shape=[10], seed=1)\n vals_2 = get_random_uniform(shape=[10], seed=1)\n assert all(vals_1 == vals_2)\n\n # Test against an expected output with a fixed seed.\n real = get_random_uniform(shape=[10], seed=5)\n expected = np.asarray(\n [\n 0.043976,\n 0.96656,\n 0.292199,\n 0.904297,\n 0.25167,\n 0.521778,\n 0.778985,\n 0.085463,\n 0.939846,\n 0.194201,\n ]\n )\n tvm.testing.assert_allclose(real, expected, rtol=1e-5)\n\n\[email protected]_targets\ndef test_convinteger(target, dev):\n def verify_convinteger(\n x_shape,\n w_shape,\n y_shape,\n padding,\n kernel_shape,\n strides,\n dilations,\n auto_pad=\"NOTSET\",\n dtype=\"uint8\",\n ):\n x_array = np.random.randint(low=0, high=255, size=x_shape).astype(dtype)\n w_array = np.random.uniform(low=0, high=255, size=w_shape).astype(dtype)\n x_zero_point_array = np.random.randint(0, 255, size=[1]).astype(dtype)\n w_zero_point_array = np.random.randint(0, 255, size=[1]).astype(dtype)\n\n ONNX_DTYPE = mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)]\n input_nodes = [\n helper.make_tensor_value_info(\"x\", ONNX_DTYPE, list(x_shape)),\n helper.make_tensor_value_info(\"w\", ONNX_DTYPE, list(w_shape)),\n ]\n initializer = [\n helper.make_tensor(\"x_zero_point\", ONNX_DTYPE, [], x_zero_point_array),\n helper.make_tensor(\"w_zero_point\", ONNX_DTYPE, [], w_zero_point_array),\n ]\n input_names = [\"x\", \"w\", \"x_zero_point\", \"w_zero_point\"]\n input_values = [x_array, w_array]\n\n if padding is None:\n ## autopadding with unset default attributes\n kwargs = {}\n if not all([s == 1 for s in strides]):\n kwargs[\"strides\"] = strides\n if not all([d == 1 for d in dilations]):\n kwargs[\"dilations\"] = dilations\n\n node = helper.make_node(\n \"ConvInteger\",\n inputs=input_names,\n outputs=[\"y\"],\n # Default values for other attributes:\n auto_pad=auto_pad,\n **kwargs,\n )\n else:\n node = helper.make_node(\n \"ConvInteger\",\n inputs=input_names,\n outputs=[\"y\"],\n kernel_shape=kernel_shape,\n # Default values for other attributes:\n strides=strides,\n dilations=dilations,\n # groups=1\n pads=padding,\n )\n\n graph = helper.make_graph(\n [node],\n \"convinteger_test\",\n inputs=input_nodes,\n initializer=initializer,\n outputs=[helper.make_tensor_value_info(\"y\", TensorProto.INT32, list(y_shape))],\n )\n model = helper.make_model(graph, producer_name=\"convinteger_test\")\n # opt_level=1 will cause error\n verify_with_ort_with_inputs(model, input_values, target=target, dev=dev, opt_level=2)\n\n def repeat(N, D):\n return tuple([N for _ in range(D)])\n\n # only support 2D ConvInteger because we only support qnn.conv2d for now.\n D = 2\n\n # Convolution with padding\n verify_convinteger(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(5, D),\n 2 * repeat(1, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n\n # Convolution with asymmetric padding\n verify_convinteger(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(4, D),\n repeat(0, D) + repeat(1, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n # Convolution without padding\n verify_convinteger(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(3, D),\n 2 * repeat(0, D),\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n )\n # Convolution with autopadding\n verify_convinteger(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(5, D),\n None,\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n auto_pad=\"SAME_UPPER\",\n )\n # Convolution with valid autopadding\n verify_convinteger(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(3, D),\n None,\n repeat(3, D),\n repeat(1, D),\n repeat(1, D),\n auto_pad=\"VALID\",\n )\n # Convolution with non uniform stride\n verify_convinteger(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(3, D),\n None,\n repeat(3, D),\n repeat(2, D),\n repeat(1, D),\n auto_pad=\"SAME_UPPER\",\n )\n # Convolution with dilation\n verify_convinteger(\n (1, 1) + repeat(5, D),\n (1, 1) + repeat(3, D),\n (1, 1) + repeat(5, D),\n 2 * repeat(2, D),\n repeat(3, D),\n repeat(1, D),\n repeat(2, D),\n )\n\n\nif __name__ == \"__main__\":\n test_flatten()\n test_reshape()\n test_shape()\n test_expand()\n test_power()\n test_squeeze()\n test_unsqueeze()\n test_slice()\n test_floor()\n test_ceil()\n test_round()\n test_isinf()\n test_isnan()\n test_clip()\n test_clip_min_max_as_inputs()\n test_onehot()\n test_gemm()\n test_matmul()\n test_gather()\n test_gatherelements()\n test_gather_nd()\n test_scatter()\n test_lrn()\n test_instance_norm()\n test_upsample_nearest()\n test_upsample_bilinear()\n test_forward_min()\n test_forward_max()\n test_forward_mean()\n test_forward_hardsigmoid()\n test_forward_arg_min_max()\n test_softmax()\n test_constantofshape()\n test_all_reduce_funcs()\n test_pad()\n test_split()\n test_binary_ops()\n test_unary_ops()\n test_leaky_relu()\n test_elu()\n test_selu()\n test_prelu()\n test_ThresholdedRelu()\n test_LogSoftmax()\n test_resnet()\n test_inception()\n test_densenet()\n test_sign()\n test_not()\n test_and()\n test_tile()\n test_erf()\n test_where()\n test_or()\n test_depth_to_space()\n test_space_to_depth()\n test_batch_norm()\n test_batch_norm_dynamic_subgraph()\n test_conv()\n test_convtranspose()\n test_unsqueeze_constant()\n test_pooling()\n test_lppool()\n test_lstm()\n test_gru()\n test_resize()\n test_nonzero()\n test_topk()\n test_mod()\n test_xor()\n test_max_roi_pool()\n test_roi_align()\n test_range()\n test_loop()\n test_size()\n test_maxunpool()\n test_softplus()\n test_cumsum()\n test_wrong_input()\n test_aten()\n test_index_put()\n test_reverse_sequence()\n test_eyelike()\n test_qlinearconcat()\n test_qlinearconv()\n test_random_uniform()\n test_convinteger()\n test_batch_matmul()\n test_global_lppool()\n"
] | [
[
"numpy.logical_xor",
"torch.randint",
"numpy.take",
"numpy.asarray",
"numpy.dtype",
"torch.set_grad_enabled",
"numpy.random.randn",
"numpy.exp",
"numpy.where",
"scipy.special.softmax",
"torch.nn.EmbeddingBag",
"numpy.random.randint",
"torch.onnx.export",
"torch.ones",
"numpy.pad",
"numpy.clip",
"torch.randn",
"numpy.eye",
"numpy.arange",
"numpy.matmul",
"torch.tensor",
"torch.rand",
"torch.arange",
"numpy.repeat",
"scipy.special.erf",
"numpy.zeros",
"numpy.nonzero",
"numpy.random.choice",
"numpy.power",
"numpy.logical_or",
"torch.nn.Linear",
"numpy.ndim",
"numpy.random.rand",
"numpy.logical_and",
"numpy.array",
"numpy.sum",
"numpy.random.random",
"numpy.random.seed",
"numpy.tile",
"numpy.ones",
"numpy.sign",
"numpy.random.normal",
"numpy.random.uniform"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sailist/ASRFrame | [
"484cf1ee5beec4c39439de683c5b4c1f1ea3a94a"
] | [
"util/layer_viso.py"
] | [
"'''\n作者:挥挥洒洒\n来源:CSDN\n原文:https://blog.csdn.net/u010420283/article/details/80303231\n版权声明:本文为博主原创文章,转载请附上博文链接!\n'''\n\n# 暂时没有使用\n\nfrom keras.models import load_model\nfrom keras import backend as K\nimport matplotlib.pyplot as plt\n\n\n\n\ndef main():\n model = load_model('data/checkpoints/inception.026-1.07.hdf5') # replaced by your model name\n # Get all our test images.\n image = 'v_ApplyLipstick_g01_c01-0105.jpg'\n images = plt.imread('v_ApplyLipstick_g01_c01-0105.jpg')\n plt.imshow(\"Image\", images)\n # Turn the image into an array.\n\n # 设置可视化的层\n layer_1 = K.function([model.layers[0].input], [model.layers[1].output])\n f1 = layer_1([image_arr])[0]\n for _ in range(32):\n show_img = f1[:, :, :, _]\n show_img.shape = [149, 149]\n plt.subplot(4, 8, _ + 1)\n plt.subplot(4, 8, _ + 1)\n plt.imshow(show_img, cmap='gray')\n plt.axis('off')\n plt.show()\n # conv layer: 299\n layer_1 = K.function([model.layers[0].input], [model.layers[299].output])\n f1 = layer_1([image_arr])[0]\n for _ in range(81):\n show_img = f1[:, :, :, _]\n show_img.shape = [8, 8]\n plt.subplot(9, 9, _ + 1)\n plt.imshow(show_img, cmap='gray')\n plt.axis('off')\n plt.show()\n print('This is the end !')\n\n"
] | [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.imread",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lucasthim/auto-fuzzy | [
"1aa8f246973ad95c326e785f41614db0cb99b71c"
] | [
"deprecated/ensemble/senfis/calcula_media.py"
] | [
"import glob\nimport os\nimport re\nimport numpy as np\nimport autoFIS.autoFIS.utils_autofis as toolfis\n\n\ndef summary_multiple(successful_classifiers, metrics_train, metrics_test, metrics_rules):\n r0 = successful_classifiers\n ac_train, auc_train = metrics_train[0:2]\n ac_test, auc_test = metrics_test[0:2]\n r1 = \"%.4f, %.4f\" % (np.mean(ac_train), np.std(ac_train))\n r2 = \"%.4f, %.4f\" % (np.mean(ac_test), np.std(ac_test))\n r3 = \"%.4f, %.4f\" % (np.mean(auc_train), np.std(auc_train))\n r4 = \"%.4f, %.4f\" % (np.mean(auc_test), np.std(ac_test))\n r5 = np.mean(metrics_rules[0])\n r6 = np.mean(metrics_rules[1])\n r7 = r6 / r5\n return r0, r1, r2, r3, r4, r5, r6, r7\n\n\ndef template_results(nome, results): # Sirve para OneCV y OneZip\n r0, r1, r2, r3, r4, r5, r6, r7 = results\n summary = \"\"\"\n {x}\n Successful classifiers: {x0}\n Accuracy training: {x1}\n Accuracy Testing: {x2}\n AUC Training: {x3}\n AUC Testing: {x4}\n Number of Rules: {x5}\n Total Rule Length: {x6} / Average: {x7:.4f}\n \"\"\".format(x=nome, x0=r0, x1=r1, x2=r2, x3=r3, x4=r4, x5=r5, x6=r6, x7=float(r7))\n return summary\n\n\ndef main():\n\n directory = os.getcwd()\n os.chdir(f'{directory}/2019-01-31_06-42-36/15')\n for filename in glob.glob('Report*.txt'):\n\n with open(filename, 'r') as file_tmp:\n\n suc_classifiers, ac_train, auc_train, ac_test, auc_test, num_rules, rule_len = [], [], [], [], [], [], []\n for line in file_tmp.read().splitlines():\n\n if \"Successful classifiers: \" in line:\n suc_classifiers.append(re.search(r'\\[(.*?)\\]', line).group(1))\n elif \"Accuracy training: \" in line:\n ac_train.append(float(re.findall(\"\\d+\\.\\d+\", line)[0]))\n elif \"AUC Training: \" in line:\n if len(re.findall(\"\\d+\\.\\d+\", line)) == 0:\n auc_train.append(0)\n else:\n auc_train.append(float(re.findall(\"\\d+\\.\\d+\", line)[0]))\n elif \"Accuracy Testing: \" in line:\n ac_test.append(float(re.findall(\"\\d+\\.\\d+\", line)[0]))\n elif \"AUC Testing: \" in line:\n if len(re.findall(\"\\d+\\.\\d+\", line)) == 0:\n auc_test.append(0)\n else: \n auc_test.append(float(re.findall(\"\\d+\\.\\d+\", line)[0]))\n elif \"Number of Rules: \" in line:\n num_rules.append(int(re.findall(\"\\d+\", line)[0]))\n elif \"Total Rule Length: \" in line:\n rule_len.append(int(re.findall(\"\\d+\", line)[0]))\n\n results = toolfis.summary_multiple(suc_classifiers[1], [ac_train, auc_train],\n [ac_test, auc_test], [num_rules, rule_len])\n\n abstract = toolfis.template_results('Summary_CVs\\n -----------', results)\n underline = \"\\n%s\\n\" % (110 * \"=\")\n\n file = open(filename, 'a+')\n file.write(underline)\n file.write(abstract)\n\n file.close()\n\nmain()\n"
] | [
[
"numpy.std",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
timbobailey/AVO-plotter | [
"3d76bfe4dae1e79f6a1042d91636373e0fdb8a2c"
] | [
"avonumericals.py"
] | [
"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom bruges.reflection import reflection as avomodel\n\n\nclass AVONumerical:\n ''' A class to isolate the AVO calls from the main gui'''\n # Extents and step of sliders\n # min, max, step\n vpextents = (100, 10000, 50) # m/s\n vsextents = (100, 10000, 50) # m/s\n rhoextents = (1000, 3500, 50) # kg/cc\n\n # Initial values for sliders, text and AVO model\n # upper medium value, lower medium value\n vpinitial = (3110, 1980) # m/s\n vsinitial = (2360, 2720) # m/s\n rhoinitial = (1920, 3050) # kg/cc\n\n theta = (0, 50, 1)\n thetarange = np.arange(theta[0], theta[1], theta[2])\n\n def __init__(self, maingui):\n self.maingui = maingui\n\n def getavo(self, method='zoe'):\n if method == 'zoe':\n return avomodel.zoeppritz_rpp(self.maingui.horizontalSlider_vp1.value(), self.maingui.horizontalSlider_vs1.value(),\n self.maingui.horizontalSlider_rho1.value() / 1000,\n self.maingui.horizontalSlider_vp2.value(), self.maingui.horizontalSlider_vs2.value(),\n self.maingui.horizontalSlider_rho2.value() / 1000, AVONumerical.thetarange)\n\n elif method == 'shuey':\n return avomodel.shuey(self.maingui.horizontalSlider_vp1.value(), self.maingui.horizontalSlider_vs1.value(),\n self.maingui.horizontalSlider_rho1.value() / 1000,\n self.maingui.horizontalSlider_vp2.value(), self.maingui.horizontalSlider_vs2.value(),\n self.maingui.horizontalSlider_rho2.value() / 1000, AVONumerical.thetarange)\n\n elif method == 'ar':\n return avomodel.akirichards(self.maingui.horizontalSlider_vp1.value(), self.maingui.horizontalSlider_vs1.value(),\n self.maingui.horizontalSlider_rho1.value() / 1000,\n self.maingui.horizontalSlider_vp2.value(), self.maingui.horizontalSlider_vs2.value(),\n self.maingui.horizontalSlider_rho2.value() / 1000, AVONumerical.thetarange)\n\n\n def getig(self):\n g, i = -0.1, 0.1\n return i, g\n\n def getthetarange(self):\n return AVONumerical.thetarange\n\n def getthetamin(self):\n pass\n\n def getthetamax(self):\n pass\n\n def getinitialproperties(self):\n pass\n\n"
] | [
[
"numpy.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
isLinXu/YOLOv5_Efficient | [
"1f50b44cafdc942b3f222a072bee726722fda5ca"
] | [
"yolov5_master/predict.py"
] | [
"'''\n@author: linxu\n@contact: [email protected]\n@time: 2021-8-16 上午09:56\n@desc: 模型执行-主函数\n'''\n\nimport os\nimport shutil\nimport time\nfrom pathlib import Path\n\nimport cv2\nimport torch\nfrom numpy import random\nfrom yolov5_master.utils.general import (check_img_size, non_max_suppression, scale_coords, xyxy2xywh)\nfrom yolov5_master.utils.plots import plot_one_box\nfrom yolov5_master.utils.torch_utils import time_synchronized\nfrom yolov5_master.utils.datasets import LoadStreams, LoadImages\nfrom yolov5_master.utils.torch_utils import select_device\n\nid2name = {0: 'person',\n 1: 'bicycle',\n 2: 'car',\n 3: 'motorcycle',\n 4: 'airplane',\n 5: 'bus',\n 6: 'train',\n 7: 'truck',\n 8: 'boat',\n 9: 'traffic light',\n 10: 'fire hydrant',\n 11: 'stop sign',\n 12: 'parking meter',\n 13: 'bench',\n 14: 'bird',\n 15: 'cat',\n 16: 'dog',\n 17: 'horse',\n 18: 'sheep',\n 19: 'cow',\n 20: 'elephant',\n 21: 'bear',\n 22: 'zebra',\n 23: 'giraffe',\n 24: 'backpack',\n 25: 'umbrella',\n 26: 'handbag',\n 27: 'tie',\n 28: 'suitcase',\n 29: 'frisbee',\n 30: 'skis',\n 31: 'snowboard',\n 32: 'sports ball',\n 33: 'kite',\n 34: 'baseball bat',\n 35: 'baseball glove',\n 36: 'skateboard',\n 37: 'surfboard',\n 38: 'tennis racket',\n 39: 'bottle',\n 40: 'wine glass',\n 41: 'cup',\n 42: 'fork',\n 43: 'knife',\n 44: 'spoon',\n 45: 'bowl',\n 46: 'banana',\n 47: 'apple',\n 48: 'sandwich',\n 49: 'orange',\n 50: 'broccoli',\n 51: 'carrot',\n 52: 'hot dog',\n 53: 'pizza',\n 54: 'donut',\n 55: 'cake',\n 56: 'chair',\n 57: 'couch',\n 58: 'potted plant',\n 59: 'bed',\n 60: 'dining table',\n 61: 'toilet',\n 62: 'tv',\n 63: 'laptop',\n 64: 'mouse',\n 65: 'remote',\n 66: 'keyboard',\n 67: 'cell phone',\n 68: 'microwave',\n 69: 'oven',\n 70: 'toaster',\n 71: 'sink',\n 72: 'refrigerator',\n 73: 'book',\n 74: 'clock',\n 75: 'vase',\n 76: 'scissors',\n 77: 'teddy bear',\n 78: 'hair drier',\n 79: 'toothbrush'}\n\ndef predict(opt, model, img):\n global boxes_detected\n out, source, view_img, save_img, save_txt, imgsz = \\\n opt['output'], opt['source'], opt['view_img'], opt['save_img'], opt['save_txt'], opt['imgsz']\n\n # webcam = source.isnumeric() or source.startswith(('rtsp://', 'rtmp://', 'http://')) or source.endswith('.txt')\n # Initialize\n device = select_device(opt['device']) # 选择设备\n if os.path.exists(out):\n shutil.rmtree(out) # delete output folder\n os.makedirs(out) # make new output folder\n half = device.type != 'cpu' # half precision only supported on CUDA\n\n im0_shape = img.shape # 记下原始图片的尺寸\n # print('im0_shape = %s \\n' % str(im0_shape))\n\n # Load model\n # model = attempt_load(weights, map_location=device) # load FP32 model\n imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size\n if half:\n model.half() # to FP16\n\n # Set Dataloader\n dataset = LoadImages(opt['source'], img_size=imgsz)\n\n # Get names and colors\n names = model.module.names if hasattr(model, 'module') else model.names\n colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]\n\n # Run inference\n t0 = time.time()\n img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img\n _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once\n for path, img, im0s, _ in dataset:\n img = torch.from_numpy(img).to(device)\n img = img.half() if half else img.float() # uint8 to fp16/32\n img /= 255.0 # 0 - 255 to 0.0 - 1.0\n if img.ndimension() == 3:\n img = img.unsqueeze(0)\n\n # Inference\n t1 = time_synchronized()\n\n # 前向推理\n pred = model(img, augment=opt['augment'])[0]\n # Apply NMS(非极大抑制)\n pred = non_max_suppression(pred, opt['conf_thres'], opt['iou_thres'], classes=opt['classes'],\n agnostic=opt['agnostic_nms'])\n\n t2 = time_synchronized()\n\n # Process detections\n for i, det in enumerate(pred): # detections per image\n p, s, im0 = path, '', im0s\n save_path = str(Path(out) / Path(p).name) # 保存路径\n txt_path = str(Path(out) / Path(p).stem) + ('_%g' % dataset.frame if dataset.mode == 'video' else '')\n gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh\n if det is not None and len(det):\n # Rescale boxes from img_size to im0 size\n det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()\n\n # Print results\n for c in det[:, -1].unique():\n n = (det[:, -1] == c).sum() # detections per class\n s += '%g %ss, ' % (n, names[int(c)]) # add to string\n\n # Write results\n boxes_detected = [] # 检测结果\n for *xyxy, conf, cls in reversed(det):\n xyxy_list = (torch.tensor(xyxy).view(1, 4)).view(-1).tolist()\n boxes_detected.append({\"name\": id2name[int(cls.item())],\n \"conf\": str(conf.item()),\n \"bbox\": [int(xyxy_list[0]), int(xyxy_list[1]), int(xyxy_list[2]),\n int(xyxy_list[3])]\n })\n if save_txt: # Write to file\n xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh\n with open(txt_path + '.txt', 'a') as f:\n f.write(('%g ' * 5 + '\\n') % (cls, *xywh)) # label format\n\n if save_img or view_img: # Add bbox to image\n label = '%s %.2f' % (names[int(cls)], conf)\n plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)\n # Print time (inference + NMS)\n print('%sDone. (%.3fs)' % (s, t2 - t1))\n # Save results (image with detections)\n if save_img:\n if dataset.mode == 'images':\n cv2.imwrite(save_path, im0)\n\n results = {\"results\": boxes_detected}\n print(results)\n return results"
] | [
[
"torch.tensor",
"numpy.random.randint",
"torch.from_numpy",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cpcdoy/rust-bert | [
"c9e8e960a8d76706a0d0afde5e76d30592b161e8"
] | [
"utils/download-dependencies_gpt2-large.py"
] | [
"from transformers import GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP\nfrom transformers.tokenization_gpt2 import PRETRAINED_VOCAB_FILES_MAP\nfrom transformers.file_utils import get_from_cache, hf_bucket_url\nfrom pathlib import Path\nimport shutil\nimport os\nimport numpy as np\nimport torch\nimport subprocess\n\nconfig_path = GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP[\"gpt2-large\"]\nvocab_path = PRETRAINED_VOCAB_FILES_MAP[\"vocab_file\"][\"gpt2-large\"]\nmerges_path = PRETRAINED_VOCAB_FILES_MAP[\"merges_file\"][\"gpt2-large\"]\nweights_path = \"gpt2-large\"\n\ntarget_path = Path.home() / 'rustbert' / 'gpt2-large'\n\ntemp_config = get_from_cache(config_path)\ntemp_vocab = get_from_cache(vocab_path)\ntemp_merges = get_from_cache(merges_path)\ntemp_weights = get_from_cache(hf_bucket_url(weights_path, filename=\"pytorch_model.bin\", use_cdn=True))\n\nos.makedirs(str(target_path), exist_ok=True)\n\nconfig_path = str(target_path / 'config.json')\nvocab_path = str(target_path / 'vocab.txt')\nmerges_path = str(target_path / 'merges.txt')\nmodel_path = str(target_path / 'model.bin')\n\nshutil.copy(temp_config, config_path)\nshutil.copy(temp_vocab, vocab_path)\nshutil.copy(temp_merges, merges_path)\nshutil.copy(temp_weights, model_path)\n\nweights = torch.load(temp_weights, map_location='cpu')\nnps = {}\nfor k, v in weights.items():\n nps['transformer.' + k] = np.ascontiguousarray(v.cpu().numpy())\n if k == 'wte.weight':\n nps['lm_head.weight'] = np.ascontiguousarray(v.cpu().numpy())\n\nnp.savez(target_path / 'model.npz', **nps)\n\nsource = str(target_path / 'model.npz')\ntarget = str(target_path / 'model.ot')\n\ntoml_location = (Path(__file__).resolve() / '..' / '..' / 'Cargo.toml').resolve()\n\nsubprocess.call(\n ['cargo', 'run', '--bin=convert-tensor', '--manifest-path=%s' % toml_location, '--', source, target])\n\nos.remove(str(target_path / 'model.bin'))\nos.remove(str(target_path / 'model.npz'))"
] | [
[
"numpy.savez",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tmills/uda | [
"c9843dc5d955a6ea124f99caa2d3517d91b3d6a7"
] | [
"scripts/learn_pivots_dual_domain.py"
] | [
"#!/usr/bin/env python3\nimport sys\nfrom os.path import join,exists,dirname\nimport random\nfrom datetime import datetime\nimport time\n\nimport numpy as np\nfrom numpy.random import randint\nfrom sklearn.datasets import load_svmlight_file\nfrom torch.autograd import Function, Variable\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch\nfrom torch import FloatTensor\n\nfrom uda_common import read_feature_groups, read_feature_lookup\n\n# the concepts here come from: https://github.com/fungtion/DANN/blob/master/models/model.py\nclass GradientBlockerF(Function):\n @staticmethod\n def forward(ctx, x):\n return x.view_as(x)\n\n @staticmethod\n def backward(ctx, grad_output):\n # zero out the gradient so it doesn't affect any weights prior to this layer\n output = 0 * grad_output\n return output, None\n\n# Instead of this, may be able to just regularize by forcing off-diagonal to zero\n# didn't work bc/ of memory issues\nclass StraightThroughLayer(nn.Module):\n def __init__(self, input_features):\n super(StraightThroughLayer, self).__init__()\n self.vector = nn.Parameter( torch.ones(1, input_features) )\n\n def forward(self, input_data):\n output = torch.mul(input_data, self.vector)\n return output\n \n\nclass PivotLearnerModel(nn.Module):\n\n def __init__(self, input_features):\n super(PivotLearnerModel, self).__init__()\n # Feature takes you from input to the \"representation\"\n self.feature = nn.Sequential()\n # straight through layer just does an element-wise product with a weight vector\n num_features = input_features\n # self.vector = nn.Parameter( torch.randn(1, input_features) )\n self.feature.add_module('input_layer', StraightThroughLayer(input_features))\n # Standard feed forward layer:\n # num_features = 200\n # self.feature.add_module('input_layer', nn.Linear(input_features, num_features))\n # self.feature.add_module('relu', nn.ReLU(True))\n\n # task_classifier maps from a feature representation to a task prediction\n self.task_classifier = nn.Sequential()\n self.task_classifier.add_module('task_binary', nn.Linear(num_features, 1))\n self.task_classifier.add_module('task_sigmoid', nn.Sigmoid())\n \n # domain classifier maps from a feature representation to a domain prediction\n self.domain_classifier = nn.Sequential()\n # hidden_nodes = 100\n # self.domain_classifier.add_module('domain_hidden', nn.Linear(num_features, hidden_nodes, bias=False))\n # self.domain_classifier.add_module('relu', nn.ReLU(True))\n\n # No bias because bias could learn data prevalence\n self.domain_classifier.add_module('domain_classifier', nn.Linear(num_features, 1, bias=False))\n # # self.domain_classifier.add_module('domain_predict', nn.Linear(100, 1))\n self.domain_classifier.add_module('domain_sigmoid', nn.Sigmoid())\n \n # self.domain_classifier2 = nn.Sequential()\n # self.domain_classifier2.add_module('domain_linear', nn.Linear(num_features, 1, bias=False))\n # # # self.domain_classifier.add_module('domain_predict', nn.Linear(100, 1))\n # self.domain_classifier2.add_module('domain_sigmoid', nn.Sigmoid())\n\n def forward(self, input_data):\n feature = self.feature(input_data)\n\n # Get task prediction\n task_prediction = self.task_classifier(feature)\n\n # Get domain prediction\n domain_prediction = self.domain_classifier( GradientBlockerF.apply(feature) )\n\n # Copy weights over to the confusion side (and don't modify them)\n # self.confusion_layer.weight.data = self.domain_classifier.domain_classifier.weight.data\n domain_weights = Variable(self.domain_classifier.domain_classifier.weight.data, requires_grad=False)\n # domain_bias = Variable(self.domain_classifier.domain_classifier.bias.data, requires_grad=False)\n\n # confused_prediction = nn.functional.sigmoid( torch.dot(domain_weights, feature) ) \n confused_prediction = nn.functional.sigmoid( torch.matmul(domain_weights, feature.t()) )\n\n return task_prediction, domain_prediction, confused_prediction\n\ndef confusion_loss_fn(system, gold):\n # doesn't work\n # return torch.abs(system - 0.5)\n # doesn't work -- just makes things close to 0.5\n # return torch.pow(system - 0.5, 2)\n return nn.functional.binary_cross_entropy(1-system, gold)\n\ndef main(args):\n if len(args) < 1:\n sys.stderr.write(\"Required arguments: <data file> [backward True|False]\\n\")\n sys.exit(-1)\n \n cuda = False \n if torch.cuda.is_available():\n cuda = True\n \n if len(args) > 1:\n backward = bool(args[1])\n print(\"Direction is backward based on args=%s\" % (args[1]))\n else:\n backward = False\n print(\"Direction is forward by default\")\n\n # constants:\n runs_to_average = 10\n goal_ind = 2\n domain_weight = 0.1\n confusion_weight = 0.1\n reg_weight = 0.1\n lr = 0.01\n epochs = 10000\n\n date_str = datetime.now().isoformat()\n\n # Read the data:\n sys.stderr.write(\"Reading source data from %s\\n\" % (args[0]))\n all_X, all_y = load_svmlight_file(args[0])\n maxes = all_X.max(0).toarray()\n non_binary = np.where(maxes != 1.0)[1]\n \n all_X[:,0] = 0\n all_X[:,non_binary] = 0\n \n # y is 1,2 by default, map to -1,1 for sigmoid training\n all_y -= 1 # 0/1\n\n num_instances, num_feats = all_X.shape\n\n domain_map = read_feature_groups(join(dirname(args[0]), 'reduced-feature-groups.txt'))\n domain_inds = domain_map['Domain']\n\n feature_map = read_feature_lookup(join(dirname(args[0]), 'reduced-features-lookup.txt'))\n\n direction = 1 if backward else 0\n sys.stderr.write(\"using domain %s as source, %s as target\\n\" %\n (feature_map[domain_inds[direction]],feature_map[domain_inds[1-direction]]))\n\n source_instance_inds = np.where(all_X[:,domain_inds[direction]].toarray() > 0)[0]\n X_source = all_X[source_instance_inds,:]\n X_source[:, domain_inds[direction]] = 0\n X_source[:, domain_inds[1-direction]] = 0\n\n y_source = all_y[source_instance_inds]\n num_train_instances = int(X_source.shape[0] * 0.8)\n X_task_train = X_source[:num_train_instances,:]\n y_task_train = y_source[:num_train_instances]\n X_task_valid = X_source[num_train_instances:, :]\n y_task_valid = y_source[num_train_instances:]\n\n target_instance_inds = np.where(all_X[:,domain_inds[1-direction]].toarray() > 0)[0]\n X_target = all_X[target_instance_inds,:]\n X_target[:, domain_inds[direction]] = 0\n X_target[:, domain_inds[1-direction]] = 0\n num_target_train = int(X_target.shape[0] * 0.8)\n X_target_train = X_target[:num_target_train,:]\n X_target_valid = X_target[num_target_train:, :]\n num_target_instances = X_target_train.shape[0]\n\n model = PivotLearnerModel(num_feats)\n task_loss_fn = nn.BCELoss()\n domain_loss_fn = nn.BCELoss()\n l1_loss = nn.L1Loss()\n \n\n if cuda:\n model.cuda()\n task_loss_fn.cuda()\n domain_loss_fn.cuda()\n\n optimizer = optim.Adam(model.parameters())\n # optimizer = optim.SGD(model.parameters(), lr=lr)\n model.train()\n\n # Main training loop\n inds = np.arange(num_train_instances)\n best_qualifying_f1 = 0\n\n weight_vecs = np.zeros( (runs_to_average, num_feats))\n\n for run in range(runs_to_average):\n for epoch in range(epochs):\n epoch_loss = 0\n random.shuffle(inds)\n\n epoch_start = time.time()\n # Do a training epoch:\n for source_ind in inds:\n model.zero_grad()\n\n # standardized_X = (X_train[source_ind,:].toarray() - X_mean) / X_std\n source_batch = Variable(FloatTensor(X_task_train[source_ind,:].toarray()))# read input\n source_task_labels = Variable(torch.unsqueeze(FloatTensor([y_task_train[source_ind],]), 1))# read task labels\n source_domain_labels = Variable(torch.unsqueeze(FloatTensor([0.,]), 1)) # set to 0\n\n if cuda:\n source_batch = source_batch.cuda()\n source_task_labels = source_task_labels.cuda()\n source_domain_labels = source_domain_labels.cuda()\n \n # Get the task loss and domain loss for the source instance:\n task_out, source_domain_out, source_confusion_out = model.forward(source_batch)\n task_loss = task_loss_fn(task_out, source_task_labels)\n domain_loss = domain_loss_fn(source_domain_out, source_domain_labels)\n confusion_loss = confusion_loss_fn(source_confusion_out, source_domain_labels)\n reg_term = l1_loss(model.feature.input_layer.vector, torch.zeros_like(model.feature.input_layer.vector))\n\n # Randomly select a target instance:\n target_ind = randint(num_target_instances)\n target_batch = Variable(FloatTensor(X_target_train[target_ind,:].toarray())) # read input\n target_domain_labels = Variable(torch.unsqueeze(FloatTensor([1.,]), 1)) # set to 1\n\n if cuda:\n target_batch = target_batch.cuda()\n target_domain_labels = target_domain_labels.cuda()\n \n # Get the domain loss for the target instances:\n _, target_domain_out, target_confusion_out = model.forward(target_batch)\n target_domain_loss = domain_loss_fn(target_domain_out, target_domain_labels)\n target_confusion_loss = confusion_loss_fn(target_confusion_out, target_domain_labels)\n\n # Get sum loss update weights:\n # domain adaptation:\n total_loss = (task_loss + \n domain_weight * (domain_loss + target_domain_loss) + \n confusion_weight * (confusion_loss + target_confusion_loss) +\n reg_weight * reg_term)\n\n total_loss.backward()\n epoch_loss += total_loss\n\n optimizer.step()\n\n # At the end of every epoch, examine domain accuracy and how many non-zero parameters we have\n source_eval_X = X_task_valid\n source_eval_y = y_task_valid\n source_task_out, source_domain_out, source_confusion_out = model.forward( Variable(FloatTensor(source_eval_X.toarray())).cuda() )\n # If this goes down that means its getting more confused about the domain\n domain_out_stdev = source_domain_out.std()\n\n # source domain is 0, count up predictions where 1 - prediction = 1\n source_domain_preds = np.round(source_domain_out.cpu().data.numpy())\n source_predicted_count = np.sum(1 - source_domain_preds)\n\n\n target_eval_X = X_target_valid\n _, target_domain_out, target_confusion_out = model.forward( Variable(FloatTensor(target_eval_X.toarray())).cuda() )\n # if using sigmoid output (0/1) with BCELoss\n target_domain_preds = np.round(target_domain_out.cpu().data.numpy())\n target_predicted_count = np.sum(target_domain_preds)\n\n domain_acc = (source_predicted_count + target_predicted_count) / (source_eval_X.shape[0] + target_eval_X.shape[0])\n\n # predictions of 1 are the positive class: tps are where prediction and gold are 1\n source_y_pred = np.round(source_task_out.cpu().data.numpy()[:,0])\n tps = np.sum(source_y_pred * source_eval_y)\n true_preds = source_y_pred.sum()\n true_labels = source_eval_y.sum()\n\n recall = tps / true_labels\n prec = 1 if tps == 0 else tps / true_preds\n f1 = 2 * recall * prec / (recall+prec)\n\n try:\n weights = model.feature.input_layer.vector\n num_zeros = (weights.data==0).sum() \n near_zeros = (torch.abs(weights.data)<0.000001).sum()\n\n print(\"Min (abs) weight: %f\" % (torch.abs(weights).min()))\n print(\"Max (abs) weight: %f\" % (torch.abs(weights).max()))\n print(\"Ave weight: %f\" % (torch.abs(weights).mean()))\n except:\n num_zeros = near_zeros = -1\n\n epoch_len = time.time() - epoch_start\n print(\"[Source] Epoch %d [%0.1fs]: loss=%f\\tnear_zero=%d\\tnum_insts=%d\\tdom_acc=%f\\tdom_std=%f\\tP=%f\\tR=%f\\tF=%f\" % (epoch, epoch_len, epoch_loss, near_zeros, len(source_eval_y), domain_acc, domain_out_stdev, prec, recall, f1))\n\n if f1 > 0.8 and f1 > best_qualifying_f1 and abs(domain_acc - 0.5) < 0.05:\n # This model meets our criteria so save its weights and short circuit\n vec = np.abs(model.feature.input_layer.vector.data.cpu().numpy())\n weight_vecs[run_num] = vec\n next\n \n # If we haven't broken then reset epoch to 0;\n # print(\"This model is the most accurate-to-date that is confused between domains so we're writing it.\")\n # best_qualifying_f1 = f1\n # torch.save(model, 'model_epoch%04d_dt=%s.pt' % (epoch, date_str))\n\n # All of our runs are done so take the average weights and grab the 200 best:\n ave_weights = weight_vecs.mean(0)\n inds = np.argsort(ave_weights)\n pivot_inds = inds[0, -num_pivots:]\n pivot_inds.sort()\n for x in pivot_inds:\n print(x)\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n\n"
] | [
[
"torch.abs",
"torch.FloatTensor",
"torch.cuda.is_available",
"sklearn.datasets.load_svmlight_file",
"numpy.where",
"torch.nn.L1Loss",
"numpy.random.randint",
"torch.autograd.Variable",
"torch.ones",
"numpy.arange",
"torch.nn.Sigmoid",
"torch.mul",
"numpy.zeros",
"torch.nn.Sequential",
"torch.zeros_like",
"torch.nn.BCELoss",
"torch.nn.Linear",
"numpy.argsort",
"numpy.sum",
"torch.nn.functional.binary_cross_entropy"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
djlduckett/Genome_Resources | [
"7d0e17c349606464f11a20ce3f04acdc57202cd6"
] | [
"1snp_by_id.py"
] | [
"#!/usr/bin/env python\n\n###Imports###\nimport numpy as np\nimport pandas as pd\nimport re\nimport sys\nimport collections\n\n###Definitions###\nvcf_file = sys.argv[1]\n\n###Functions###\n\ndef get_header_lines(vcf_file):\n lines = []\n comment = True \n with open(vcf_file, 'r') as f:\n while comment == True: # while line begins with '##'\n line = f.readline()\n comment = bool(re.search('##', line))\n if comment == True:\n lines.append(line)\n return(lines)\n\n\n###Main###\nheader_lines = get_header_lines(vcf_file) # get vcf header lines with '##'\nvcf_df = pd.read_table(vcf_file, delimiter = '\\t', header = 1, skiprows = len(header_lines) - 1) # read in vcf\ntotal_snps = len(vcf_df.index) # get starting number of snps\nprint(\"Total SNPs: %s\" % total_snps)\n\nid = vcf_df['ID'] # get IDs\nloci = id.apply(lambda x: x.split('_')[0]) # get locus names\n\nd = collections.defaultdict(list)\nfor key, value in zip(loci.values, loci.index): # create dictionary with locus ids as keys and indices as values\n d[key].append(value)\n\nsingle_snp_inds = [int(np.random.choice(ind_list, 1)) for ind_list in d.values()] # sample a single snp index for each locus \n\nsingle_snp_df = vcf_df.iloc[single_snp_inds] # use single snp indices to subsample vcf dataframe\n\nsingle_snps = len(single_snp_df) # get number of subsampled snps\nprint(\"Subsampled SNPs: %s\" % single_snps)\n\nout_file = ''.join([vcf_file.split('vcf')[0], '1snp.vcf'])\n\nwith open(out_file, 'a') as out:\n out.write(''.join(header_lines)) # write vcf header lines\n single_snp_df.to_csv(out, sep = '\\t', header = True, index = False)"
] | [
[
"numpy.random.choice"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tritas/bitl | [
"f394e633e38f983fed10c3e672af7be2883cbdbb"
] | [
"bitl/policies/oful.py"
] | [
"# -*- coding: utf-8 -*-\n# Author: Aris Tritas, Nithin Holla\n# License: BSD 3-clause\n\nimport numpy as np\nfrom scipy.optimize import minimize\n\n\nclass OFUL(object):\n # Constructor function\n \"\"\"\n Optimism-in-the-face-of-Uncertainty linear bandits\n \"\"\"\n\n def __init__(\n self,\n n_actions,\n action_features,\n horizon,\n dimensions,\n lambda_=1.0,\n delta=0.001,\n C=1.0,\n R=0.5,\n S=0.5,\n ):\n self.action_features = np.asarray(action_features)\n self.n_actions = n_actions\n self.n_features = dimensions\n\n self.horizon = horizon\n self.lambda_ = lambda_\n self.delta = delta\n self.C = C\n self.R = R\n self.s = S\n self.S = None\n self.t = None\n self.n_draws = None\n self._means = None\n self._theta_star = None\n self._Vt = None # Matrix Vt\n self._detVt = None # Determinant of Vt\n self._detV_tau = None\n\n self._features = None\n self._rewards = None\n\n # Initialize the class variables\n def initialize(self):\n \"\"\" Reset \"\"\"\n self._detV_tau = 1\n self.S = self.s\n self.t = 0\n\n self.n_draws = np.zeros(self.n_actions, dtype=np.int32)\n self._means = np.zeros(self.n_actions, dtype=np.float64)\n self._Vt = self.lambda_ * np.identity(self.n_features)\n self._detVt = np.linalg.det(self._Vt)\n\n self._theta_star = np.zeros(self.n_features, dtype=np.float64)\n self._features = np.zeros((0, self.n_features), dtype=np.float64)\n self._rewards = np.zeros((0, 1), dtype=np.float64)\n\n def select_arm(self, *args):\n \"\"\" Choose the best arm as per OFUL \"\"\"\n for i in range(self.n_actions):\n if self.n_draws[i] == 0:\n return i\n\n # Compute theta_hat\n temp1 = np.dot(self._features.T, self._features)\n temp2 = np.linalg.inv(temp1 + self.lambda_ * np.eye(len(temp1)))\n temp3 = np.dot(temp2, self._features.T)\n theta_hat = np.dot(temp3, self._rewards)\n theta_hat = np.ravel(theta_hat)\n\n # Compute Vt\n self._Vt += temp1\n self._detVt = np.linalg.det(self._Vt)\n\n # Saving computation\n sparsity_cond = np.sum(self._theta_star == 0) == self.n_features\n det_growth_cond = self._detVt > (1 + self.C) * self._detV_tau\n if sparsity_cond or det_growth_cond:\n # Compute the ellipsoidal bound centered at theta_hat\n temp = np.linalg.det(self.lambda_ * np.eye(self.t))\n log_det = np.sqrt(\n 2 * np.log((np.sqrt(self._detVt) * temp) / self.delta)\n )\n bound = self.R * log_det + np.sqrt(self.lambda_) * self.S\n\n # Optimize the objective function and return the best arm\n max_obj = -np.infty\n obj = np.zeros(self.n_actions)\n for arm in range(self.n_actions):\n x = self.action_features[arm]\n opt_args = (self._Vt, (theta_hat - self._theta_star), bound)\n cons = dict(type=\"ineq\", fun=cons_func, args=opt_args)\n\n opt_res = minimize(\n fun=obj_func,\n x0=theta_hat,\n args=(x, self._theta_star),\n method=\"SLSQP\",\n constraints=cons,\n )\n theta_est = opt_res[\"x\"]\n obj[arm] = np.dot(theta_est, x)\n\n if obj[arm] > max_obj and obj[arm] != 0:\n self._theta_star = theta_est\n max_obj = obj[arm]\n self._detV_tau = self._detVt\n self.S = np.sqrt(\n np.dot(self._theta_star.T, self._theta_star)\n )\n\n return np.argmax(obj)\n else:\n return np.array(\n [\n np.dot(self._theta_star, self.action_features[arm])\n for arm in range(self.n_actions)\n ]\n ).argmax()\n\n def update(self, arm, reward):\n \"\"\" Update the class variables after observation of reward \"\"\"\n self.t += 1\n self.n_draws[arm] += 1\n n = self.n_draws[arm]\n self._means[arm] = ((n - 1) / float(n)) * self._means[arm] + (\n 1 / float(n)\n ) * reward\n\n self._features = np.vstack((self._features, self.action_features[arm]))\n self._rewards = np.vstack((self._rewards, reward))\n\n\ndef cons_func(x, A, v, b):\n \"\"\" Compute the constraint function for inequality\n Difference between the bound and the weighted norm \"\"\"\n return b - np.sqrt(np.dot(np.dot(v.T, A), v))\n\n\ndef obj_func(x, x1, x2):\n \"\"\" Compute objective function - scalar product \"\"\"\n # Objective function is -value to solve maximization problem\n # using minimize function\n return np.dot(x1.T, x2) * -1\n"
] | [
[
"numpy.dot",
"numpy.sqrt",
"numpy.asarray",
"numpy.eye",
"numpy.linalg.det",
"numpy.argmax",
"numpy.identity",
"scipy.optimize.minimize",
"numpy.ravel",
"numpy.zeros",
"numpy.sum",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
rohanblueboybaijal/face_classification | [
"395fde734dffbf93f2ea72e322d2229368c2c40e"
] | [
"src/petcat.py"
] | [
"from statistics import mode\n\nimport cv2\nimport matplotlib.pyplot as plt\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nimport numpy as np\n\nfrom utils.datasets import get_labels\n\ndef detect_faces(detection_model, gray_image_array):\n return detection_model.detectMultiScale(gray_image_array, 1.3, 5)\n\ndef draw_text(coordinates, image_array, text, color, x_offset=0, y_offset=0,\n font_scale=2, thickness=2):\n x, y = coordinates[:2]\n cv2.putText(image_array, text, (x + x_offset, y + y_offset),\n cv2.FONT_HERSHEY_SIMPLEX,\n font_scale, color, thickness, cv2.LINE_AA)\n\n\ndef draw_bounding_box(face_coordinates, image_array, color):\n x, y, w, h = face_coordinates\n cv2.rectangle(image_array, (x, y), (x + w, y + h), color, 2)\n\n\ndef apply_offsets(face_coordinates, offsets):\n x, y, width, height = face_coordinates\n x_off, y_off = offsets\n return (x - x_off, x + width + x_off, y - y_off, y + height + y_off)\n\n\ndef load_detection_model(model_path):\n detection_model = cv2.CascadeClassifier(model_path)\n return detection_model\n\ndef preprocess_input(x, v2=True):\n x = x.astype('float32')\n x = x / 255.0\n if v2:\n x = x - 0.5\n x = x * 2.0\n return x\n\n\n\n\n\n# parameters for loading data and images\ndetection_model_path = '../trained_models/detection_models/haarcascade_frontalface_default.xml'\nemotion_model_path = '../trained_models/emotion_models/fer2013_mini_XCEPTION.102-0.66.hdf5'\nemotion_labels = get_labels('fer2013')\n\n# hyper-parameters for bounding boxes shape\nframe_window = 10\nemotion_offsets = (20, 40)\n\n# loading models\nface_detection = load_detection_model(detection_model_path)\nemotion_classifier = load_model(emotion_model_path, compile=False)\n\n# getting input model shapes for inference\nemotion_target_size = emotion_classifier.input_shape[1:3]\n\n# starting lists for calculating modes\nemotion_window = []\n\n# starting video streaming\ncv2.namedWindow('window_frame')\nvideo_capture = cv2.VideoCapture(0)\nwhile True:\n bgr_image = video_capture.read()[1]\n gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)\n rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)\n faces = detect_faces(face_detection, gray_image)\n\n for face_coordinates in faces:\n\n x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)\n gray_face = gray_image[y1:y2, x1:x2]\n try:\n gray_face = cv2.resize(gray_face, (emotion_target_size))\n except:\n continue\n\n gray_face = preprocess_input(gray_face, True)\n gray_face = np.expand_dims(gray_face, 0)\n gray_face = np.expand_dims(gray_face, -1)\n emotion_prediction = emotion_classifier.predict(gray_face)\n emotion_probability = np.max(emotion_prediction)\n emotion_label_arg = np.argmax(emotion_prediction)\n emotion_text = emotion_labels[emotion_label_arg]\n emotion_window.append(emotion_text)\n\n if len(emotion_window) > frame_window:\n emotion_window.pop(0)\n try:\n emotion_mode = mode(emotion_window)\n except:\n continue\n\n if emotion_text == 'angry':\n color = emotion_probability * np.asarray((255, 0, 0))\n elif emotion_text == 'sad':\n color = emotion_probability * np.asarray((0, 0, 255))\n elif emotion_text == 'happy':\n color = emotion_probability * np.asarray((255, 255, 0))\n elif emotion_text == 'surprise':\n color = emotion_probability * np.asarray((0, 255, 255))\n else:\n color = emotion_probability * np.asarray((0, 255, 0))\n\n color = color.astype(int)\n color = color.tolist()\n\n draw_bounding_box(face_coordinates, rgb_image, color)\n draw_text(face_coordinates, rgb_image, emotion_mode,\n color, 0, -45, 1, 1)\n\n bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)\n cv2.imshow('window_frame', bgr_image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\nvideo_capture.release()\ncv2.destroyAllWindows()"
] | [
[
"numpy.asarray",
"numpy.max",
"numpy.expand_dims",
"numpy.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
avolkov1/keras_experiments | [
"333fad99dfd0d789b86c6976c5b3f9929edd6a67"
] | [
"examples/variational_autoencoder/variational_autoencoder_deconv_tfdataset_mgpu.py"
] | [
"'''This script demonstrates how to build a variational autoencoder\nwith Keras and deconvolution layers.\n\nReference: \"Auto-Encoding Variational Bayes\" https://arxiv.org/abs/1312.6114\n\nUsing Tensorflow queue and asynchronous training.\n\noriginal implementation:\nhttps://github.com/fchollet/keras/blob/master/examples/variational_autoencoder_deconv.py\n\nrun:\n python variational_autoencoder_deconv_tfdataset_mgpu.py --mgpu --epochs=30\n'''\n\nimport sys\nimport argparse as ap\n\nimport numpy as np\n\n# try:\n# import Tkinter # @UnusedImport\n# import matplotlib.pyplot as plt\n# except ImportError:\n# import matplotlib\n# matplotlib.use('Agg')\n# import matplotlib.pyplot as plt\nimport matplotlib\ntry:\n matplotlib.use('Agg')\nexcept Exception:\n raise\nimport matplotlib.pyplot as plt\n\nfrom scipy.stats import norm\n\nimport tensorflow as tf\ntry:\n Dataset = tf.data.Dataset\nexcept Exception:\n from tensorflow.contrib.data import Dataset\n\nfrom keras.layers import Input\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.datasets import mnist\nfrom keras.optimizers import RMSprop # , TFOptimizer\n\nfrom keras_exp.multigpu import (get_available_gpus, print_mgpu_modelsummary)\nfrom keras_exp.multigpu import make_parallel\n\nfrom keras_exp.callbacks.timing import BatchTiming, SamplesPerSec\n\nfrom vae_common import (\n CustomFormatter,\n make_shared_layers_dict, make_vae, get_encoded, get_decoded)\n\n\ndef parser_(desc):\n parser = ap.ArgumentParser(description=desc,\n formatter_class=CustomFormatter)\n\n parser.add_argument(\n '--mgpu', action='store', nargs='?', type=int,\n const=-1, # if mgpu is specified but value not provided then -1\n # if mgpu is not specified then defaults to 0 - single gpu\n # mgpu = 0 if getattr(args, 'mgpu', None) is None else args.mgpu\n default=ap.SUPPRESS,\n help='S|Run on multiple-GPUs using all available GPUs on a system.\\n'\n 'If not passed does not use multiple GPU. If passed uses all GPUs.\\n'\n 'Optionally specify a number to use that many GPUs. Another\\n'\n 'approach is to specify CUDA_VISIBLE_DEVICES=0,1,... when calling\\n'\n 'script and specify --mgpu to use this specified device list.\\n'\n 'This option is only supported with TensorFlow backend.\\n')\n\n parser.add_argument('--epochs', type=int, default=5,\n help='Number of epochs to run training for.')\n\n args = parser.parse_args()\n\n return args\n\n\ndef main(argv=None):\n '''\n '''\n main.__doc__ = __doc__\n argv = sys.argv if argv is None else sys.argv.extend(argv)\n desc = main.__doc__ # .format(os.path.basename(__file__))\n # CLI parser\n args = parser_(desc)\n\n mgpu = 1 if getattr(args, 'mgpu', None) is None else args.mgpu\n\n # input image dimensions\n img_rows, img_cols, img_chns = 28, 28, 1\n # number of convolutional filters to use\n filters = 64\n # convolution kernel size\n num_conv = 3\n\n gpus_list = get_available_gpus(mgpu)\n ngpus = len(gpus_list)\n\n batch_size = 128 * ngpus\n if K.image_data_format() == 'channels_first':\n original_img_size = (img_chns, img_rows, img_cols)\n else:\n original_img_size = (img_rows, img_cols, img_chns)\n latent_dim = 2\n intermediate_dim = 128\n epsilon_std = 1.0\n epochs = args.epochs # 5\n\n # train the VAE on MNIST digits\n (x_train, _), (x_test, y_test) = mnist.load_data()\n\n x_train = x_train.astype('float32') / 255.\n x_train = x_train.reshape((x_train.shape[0],) + original_img_size)\n x_test = x_test.astype('float32') / 255.\n x_test = x_test.reshape((x_test.shape[0],) + original_img_size)\n\n print('x_train.shape:', x_train.shape)\n\n train_samples = x_train.shape[0]\n steps_per_epoch = int(round(float(train_samples) / batch_size + 0.5))\n\n # Create the dataset and its associated one-shot iterator.\n buffer_size = 10000\n dataset = Dataset.from_tensor_slices(x_train)\n dataset = dataset.repeat()\n dataset = dataset.shuffle(buffer_size)\n dataset = dataset.batch(batch_size)\n iterator = dataset.make_one_shot_iterator()\n x_train_batch = iterator.get_next()\n\n ldict = make_shared_layers_dict(\n img_chns, img_rows, img_cols, batch_size, filters,\n num_conv, intermediate_dim, latent_dim, epsilon_std)\n # ldict is a dictionary that holds all layers. Since these layers are\n # instantiated once, they are shared amongs vae, encoder, and generator.\n\n x = Input(tensor=x_train_batch)\n vae_serial = make_vae(ldict, x)\n # : :type vae: Model\n vae = make_parallel(vae_serial, gpus_list)\n\n lr = 0.001 * ngpus\n opt = RMSprop(lr) # 'rmsprop'\n # opt = tf.train.RMSPropOptimizer(lr)\n # opt = TFOptimizer(opt)\n vae.compile(optimizer=opt, loss=None)\n # vae.summary()\n print_mgpu_modelsummary(vae)\n\n callbacks = [BatchTiming(), SamplesPerSec(batch_size)]\n\n # Fit the model using data from the TF data tensors.\n vae.fit(steps_per_epoch=steps_per_epoch, epochs=epochs,\n callbacks=callbacks)\n\n x = Input(shape=original_img_size)\n vae_val = make_vae(ldict, x)\n vae_val.compile(optimizer=opt, loss=None)\n loss = vae_val.evaluate(x=x_test, y=None, batch_size=batch_size // ngpus)\n print('\\n\\nVAE VALIDATION LOSS: {}'.format(loss))\n\n x = Input(shape=original_img_size)\n z_mean, _ = get_encoded(ldict, x)\n encoder = Model(x, z_mean)\n # : :type encoder: Model\n\n decoder_input = Input(shape=(latent_dim,))\n x_decoded_mean_squash = get_decoded(ldict, decoder_input)\n generator = Model(decoder_input, x_decoded_mean_squash)\n # : :type generator: Model\n\n # display a 2D plot of the digit classes in the latent space\n x_test_encoded = encoder.predict(x_test, batch_size=batch_size)\n plt.figure(figsize=(6, 6))\n plt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], c=y_test)\n plt.colorbar()\n # plt.show()\n plt.savefig('vae_scatter.ps')\n plt.close()\n\n # display a 2D manifold of the digits\n n = 15 # figure with 15x15 digits\n digit_size = 28\n figure = np.zeros((digit_size * n, digit_size * n))\n # Linearly spaced coordinates on the unit square were transformed through\n # the inverse CDF (ppf) of the Gaussian\n # To produce values of the latent variables z, since the prior of the\n # latent space is Gaussian\n grid_x = norm.ppf(np.linspace(0.05, 0.95, n))\n grid_y = norm.ppf(np.linspace(0.05, 0.95, n))\n\n for i, yi in enumerate(grid_x):\n for j, xi in enumerate(grid_y):\n z_sample = np.array([[xi, yi]])\n z_sample = np.tile(z_sample, batch_size).reshape(batch_size, 2)\n x_decoded = generator.predict(z_sample, batch_size=batch_size)\n digit = x_decoded[0].reshape(digit_size, digit_size)\n figure[i * digit_size: (i + 1) * digit_size,\n j * digit_size: (j + 1) * digit_size] = digit\n\n plt.figure(figsize=(10, 10))\n plt.imshow(figure, cmap='Greys_r')\n # plt.show()\n plt.savefig('vae_digit.ps')\n plt.close()\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.scatter",
"numpy.linspace",
"matplotlib.use",
"numpy.tile",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.close",
"numpy.array",
"numpy.zeros",
"tensorflow.contrib.data.Dataset.from_tensor_slices",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.5",
"1.2",
"1.4"
]
}
] |
iPriest001/my_mmdetection_v218 | [
"229c7da16908d08abcf65f55b241184f6b61b47d"
] | [
"mmdet/models/necks/fpn_AAR1.py"
] | [
"import warnings\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.cnn import ConvModule, xavier_init\nfrom mmcv.runner import auto_fp16\nimport numpy as np\nfrom timm.models.layers import DropPath, to_2tuple, trunc_normal_\n\nfrom ..builder import NECKS\n\n\nclass AdaptiveAngleConv(nn.Module):\n def __init__(self, in_channel, out_channel, kernel_size=3, stride=1, padding=1, angle_list=[0]):\n super(AdaptiveAngleConv, self).__init__()\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.angle_list = angle_list\n self.branches = len(angle_list)\n self.baseline_conv = nn.Conv2d(in_channel, out_channel, (kernel_size, kernel_size), (stride, stride), (padding, padding))\n\n def forward(self, x):\n y = self.baseline_conv(x)\n y_45 = F.conv2d(x, self._rotate_kernel(self.baseline_conv.weight, self.angle_list[1]), bias=self.baseline_conv.bias, stride=self.stride, padding=self.padding)\n y_90 = F.conv2d(x, self._rotate_kernel(self.baseline_conv.weight, self.angle_list[2]), bias=self.baseline_conv.bias, stride=self.stride, padding=self.padding)\n y_135 = F.conv2d(x, self._rotate_kernel(self.baseline_conv.weight, self.angle_list[3]), bias=self.baseline_conv.bias, stride=self.stride, padding=self.padding)\n y_180 = F.conv2d(x, self._rotate_kernel(self.baseline_conv.weight, self.angle_list[4]), bias=self.baseline_conv.bias, stride=self.stride, padding=self.padding)\n y_225 = F.conv2d(x, self._rotate_kernel(self.baseline_conv.weight, self.angle_list[5]), bias=self.baseline_conv.bias, stride=self.stride, padding=self.padding)\n y_270 = F.conv2d(x, self._rotate_kernel(self.baseline_conv.weight, self.angle_list[6]), bias=self.baseline_conv.bias, stride=self.stride, padding=self.padding)\n y_315 = F.conv2d(x, self._rotate_kernel(self.baseline_conv.weight, self.angle_list[7]), bias=self.baseline_conv.bias, stride=self.stride, padding=self.padding)\n return [y, y_45, y_90, y_135, y_180, y_225, y_270, y_315]\n\n def _rotate_kernel(self, original_kernel, angle): # only 3*3 kernel\n n = angle // 45\n orig_tran = original_kernel.permute(2, 3, 0, 1)\n new_kernel = torch.zeros_like(orig_tran)\n if n == 1 : # 45 degree\n new_kernel[0][1:][:][:] = orig_tran[0][:2][:][:]\n new_kernel[1][2][:][:] = orig_tran[0][2][:][:]\n new_kernel[2][2][:][:] = orig_tran[1][2][:][:]\n new_kernel[2][:2][:][:] = orig_tran[2][1:][:][:]\n new_kernel[0][0][:][:] = orig_tran[1][0][:][:]\n new_kernel[1][0][:][:] = orig_tran[2][0][:][:]\n new_kernel[1][1][:][:] = orig_tran[1][1][:][:]\n new_kernel = new_kernel.permute(2, 3, 0, 1)\n\n if n == 2: # 90 degree\n l = len(orig_tran)\n for i in range(l):\n for j in range(l):\n new_kernel[j][l - 1 - i][:][:] = orig_tran[i][j][:][:]\n new_kernel = new_kernel.permute(2, 3, 0, 1)\n\n\n if n == 3: # 135 degree\n new_kernel[1][2][:][:] = orig_tran[0][0][:][:]\n new_kernel[2][2][:][:] = orig_tran[0][1][:][:]\n new_kernel[2][0][:][:] = orig_tran[1][2][:][:]\n new_kernel[2][1][:][:] = orig_tran[0][2][:][:]\n new_kernel[0][0][:][:] = orig_tran[2][1][:][:]\n new_kernel[1][0][:][:] = orig_tran[2][2][:][:]\n new_kernel[0][1][:][:] = orig_tran[2][0][:][:]\n new_kernel[0][2][:][:] = orig_tran[1][0][:][:]\n new_kernel[1][1][:][:] = orig_tran[1][1][:][:]\n new_kernel = new_kernel.permute(2, 3, 0, 1)\n\n if n == 4: # 180 degree\n l = len(orig_tran)\n for i in range(l):\n for j in range(l):\n new_kernel[i][j][:][:] = orig_tran[l - 1 - i][l - 1 - j][:][:]\n new_kernel = new_kernel.permute(2, 3, 0, 1)\n\n if n == 5:\n new_kernel[2][1][:][:] = orig_tran[0][0][:][:]\n new_kernel[2][0][:][:] = orig_tran[0][1][:][:]\n new_kernel[1][0][:][:] = orig_tran[0][2][:][:]\n new_kernel[0][0][:][:] = orig_tran[1][2][:][:]\n new_kernel[0][1][:][:] = orig_tran[2][2][:][:]\n new_kernel[0][2][:][:] = orig_tran[2][1][:][:]\n new_kernel[1][2][:][:] = orig_tran[2][0][:][:]\n new_kernel[2][2][:][:] = orig_tran[1][0][:][:]\n new_kernel[1][1][:][:] = orig_tran[1][1][:][:]\n new_kernel = new_kernel.permute(2, 3, 0, 1)\n\n if n == 6: # 270 degree\n l = len(orig_tran)\n for i in range(l):\n for j in range(l):\n new_kernel[l - 1 - j][i][:][:] = orig_tran[i][j][:][:]\n new_kernel = new_kernel.permute(2, 3, 0, 1)\n\n if n == 7: # 315 degree\n new_kernel[1][0][:][:] = orig_tran[0][0][:][:]\n new_kernel[0][0][:][:] = orig_tran[0][1][:][:]\n new_kernel[0][1][:][:] = orig_tran[0][2][:][:]\n new_kernel[0][2][:][:] = orig_tran[1][2][:][:]\n new_kernel[1][2][:][:] = orig_tran[2][2][:][:]\n new_kernel[2][2][:][:] = orig_tran[2][1][:][:]\n new_kernel[2][1][:][:] = orig_tran[2][0][:][:]\n new_kernel[2][0][:][:] = orig_tran[1][0][:][:]\n new_kernel[1][1][:][:] = orig_tran[1][1][:][:]\n new_kernel = new_kernel.permute(2, 3, 0, 1)\n\n return new_kernel\n\n\nclass SKConv(nn.Module):\n def __init__(self, features, M, r, L=32):\n \"\"\" Constructor\n Args:\n features: input channel dimensionality.\n WH: input spatial dimensionality, used for GAP kernel size.\n M: the number of branchs.\n G: num of convolution groups.\n r: the radio for compute d, the length of z.\n stride: stride, default 1.\n L: the minimum dim of the vector z in paper, default 32.\n \"\"\"\n super(SKConv, self).__init__()\n d = max(int(features / r), L)\n self.features = features\n self.bn_relus = nn.ModuleList()\n for i in range(M-1): # 45, 90, 135, 180\n self.bn_relus.append(nn.Sequential(\n nn.BatchNorm2d(features),\n nn.ReLU(inplace=False)\n ))\n # self.gap = nn.AvgPool2d(int(WH/stride))\n self.fc = nn.Linear(features, d)\n self.fcs = nn.ModuleList([])\n for i in range(M-1):\n self.fcs.append(\n nn.Linear(d, features)\n )\n self.softmax = nn.Softmax(dim=1)\n self.branch = M-1\n\n def forward(self, X):\n feas = []\n for i in range(self.branch):\n feas.append(self.bn_relus[i](X[i+1]).unsqueeze_(dim=1))\n feas = torch.cat(feas, dim=1)\n fea_U = torch.sum(feas, dim=1)\n fea_s = fea_U.mean(-1).mean(-1)\n fea_z = self.fc(fea_s)\n for i, fc in enumerate(self.fcs):\n vector = fc(fea_z).unsqueeze_(dim=1)\n if i == 0:\n attention_vectors = vector\n else:\n attention_vectors = torch.cat([attention_vectors, vector], dim=1)\n attention_vectors = self.softmax(attention_vectors)\n attention_vectors = attention_vectors.unsqueeze(-1).unsqueeze(-1)\n fea_v = (feas * attention_vectors).sum(dim=1)\n fea_v += X[0] # residual structure\n return fea_v\n\n\[email protected]_module()\nclass FPN_AAR1(nn.Module):\n def __init__(self,\n in_channels,\n out_channels,\n num_outs,\n start_level=0,\n end_level=-1,\n add_extra_convs=False,\n extra_convs_on_inputs=True,\n relu_before_extra_convs=False,\n no_norm_on_lateral=False,\n conv_cfg=None,\n norm_cfg=None,\n act_cfg=None,\n upsample_cfg=dict(mode='nearest')):\n super(FPN_AAR1, self).__init__()\n assert isinstance(in_channels, list)\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.num_ins = len(in_channels)\n self.num_outs = num_outs\n self.relu_before_extra_convs = relu_before_extra_convs\n self.no_norm_on_lateral = no_norm_on_lateral\n self.fp16_enabled = False\n self.upsample_cfg = upsample_cfg.copy()\n\n if end_level == -1:\n self.backbone_end_level = self.num_ins\n assert num_outs >= self.num_ins - start_level\n else:\n # if end_level < inputs, no extra level is allowed\n self.backbone_end_level = end_level\n assert end_level <= len(in_channels)\n assert num_outs == end_level - start_level\n self.start_level = start_level\n self.end_level = end_level\n self.add_extra_convs = add_extra_convs\n assert isinstance(add_extra_convs, (str, bool))\n if isinstance(add_extra_convs, str):\n # Extra_convs_source choices: 'on_input', 'on_lateral', 'on_output'\n assert add_extra_convs in ('on_input', 'on_lateral', 'on_output')\n elif add_extra_convs: # True\n if extra_convs_on_inputs:\n # TODO: deprecate `extra_convs_on_inputs`\n warnings.simplefilter('once')\n warnings.warn(\n '\"extra_convs_on_inputs\" will be deprecated in v2.9.0,'\n 'Please use \"add_extra_convs\"', DeprecationWarning)\n self.add_extra_convs = 'on_input'\n else:\n self.add_extra_convs = 'on_output'\n\n self.lateral_convs = nn.ModuleList()\n self.fpn_rotate_convs = nn.ModuleList() # rotate_convolution , M angle branch\n self.fusions = nn.ModuleList() # add fusion module SK-Net\n\n for i in range(self.start_level, self.backbone_end_level):\n l_conv = ConvModule(\n in_channels[i],\n out_channels,\n 1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg if not self.no_norm_on_lateral else None,\n act_cfg=act_cfg,\n inplace=False)\n\n fpn_rotate_conv = AdaptiveAngleConv(\n out_channels,\n out_channels,\n 3,\n 1,\n 1,\n angle_list=[0, 45, 90, 135, 180, 225, 270, 315]\n )\n fusion = SKConv(256, 8, 2, 32)\n\n self.lateral_convs.append(l_conv)\n self.fpn_rotate_convs.append(fpn_rotate_conv)\n self.fusions.append(fusion)\n\n # add extra conv layers (e.g., RetinaNet)\n extra_levels = num_outs - self.backbone_end_level + self.start_level\n if self.add_extra_convs and extra_levels >= 1:\n for i in range(extra_levels):\n if i == 0 and self.add_extra_convs == 'on_input':\n in_channels = self.in_channels[self.backbone_end_level - 1]\n else:\n in_channels = out_channels\n\n extra_fpn_conv = ConvModule(\n in_channels,\n out_channels,\n 3,\n stride=2,\n padding=1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=act_cfg,\n inplace=False)\n self.fpn_rotate_convs.append(extra_fpn_conv)\n\n\n # default init_weights for conv(msra) and norm in ConvModule\n def init_weights(self):\n \"\"\"Initialize the weights of FPN module.\"\"\"\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n xavier_init(m, distribution='uniform')\n elif isinstance(m, nn.LayerNorm):\n nn.init.constant_(m.bias, 0)\n nn.init.constant_(m.weight, 1.0)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1.0)\n m.bias.data.zero_()\n\n @auto_fp16()\n def forward(self, inputs):\n \"\"\"Forward function.\"\"\"\n assert len(inputs) == len(self.in_channels)\n\n # build laterals\n laterals = [\n lateral_conv(inputs[i + self.start_level])\n for i, lateral_conv in enumerate(self.lateral_convs)\n ]\n\n # build top-down path\n used_backbone_levels = len(laterals)\n for i in range(used_backbone_levels - 1, 0, -1):\n # In some cases, fixing `scale factor` (e.g. 2) is preferred, but\n # it cannot co-exist with `size` in `F.interpolate`.\n if 'scale_factor' in self.upsample_cfg:\n laterals[i - 1] += F.interpolate(laterals[i],\n **self.upsample_cfg)\n else:\n prev_shape = laterals[i - 1].shape[2:]\n laterals[i - 1] += F.interpolate(\n laterals[i], size=prev_shape, **self.upsample_cfg)\n\n # build outputs\n # part 1: from original levels\n # convolution: local\n conv_outs = [\n self.fpn_rotate_convs[i](laterals[i]) for i in range(used_backbone_levels)\n ]\n # local-global fusion\n outs = [\n self.fusions[i](conv_outs[i]) for i in range(used_backbone_levels)\n ]\n\n # part 2: add extra levels\n if self.num_outs > len(outs):\n # use max pool to get more levels on top of outputs\n # (e.g., Faster R-CNN, Mask R-CNN)\n if not self.add_extra_convs:\n for i in range(self.num_outs - used_backbone_levels):\n outs.append(F.max_pool2d(outs[-1], 1, stride=2))\n # add conv layers on top of original feature maps (RetinaNet)\n else:\n if self.add_extra_convs == 'on_input':\n extra_source = inputs[self.backbone_end_level - 1]\n elif self.add_extra_convs == 'on_lateral':\n extra_source = laterals[-1]\n elif self.add_extra_convs == 'on_output':\n extra_source = outs[-1]\n else:\n raise NotImplementedError\n outs.append(self.fpn_rotate_convs[used_backbone_levels](extra_source))\n for i in range(used_backbone_levels + 1, self.num_outs):\n if self.relu_before_extra_convs:\n outs.append(self.fpn_rotate_convs[i](F.relu(outs[-1])))\n else:\n outs.append(self.fpn_rotate_convs[i](outs[-1]))\n return tuple(outs)\n"
] | [
[
"torch.nn.Softmax",
"torch.cat",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.zeros_like",
"torch.sum",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.nn.functional.interpolate",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.functional.max_pool2d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ranok92/deepirl | [
"88c7e76986243cf0b988d8d7dc0eef6b58e07864"
] | [
"experiments/run_experiment_drone_rl.py"
] | [
"import pdb\nimport sys # NOQA\n\nsys.path.insert(0, \"..\") # NOQA: E402\n\nimport numpy as np\nimport argparse\nimport torch.multiprocessing as mp\nimport os\n\nimport git\nimport gym\nimport glob\nfrom logger.logger import Logger\nimport matplotlib\nimport datetime, time\n\n# from debugtools import compile_results\nfrom utils import step_wrapper, reset_wrapper, seed_all\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--policy-path\", type=str, nargs=\"?\", default=None)\nparser.add_argument(\"--reward-path\", type=str, nargs=\"?\", default=None)\nparser.add_argument(\n \"--play\", action=\"store_true\", help=\"play given or latest stored policy.\"\n)\nparser.add_argument(\n \"--play-user\", action=\"store_true\", help=\"lets the user play the game\"\n)\nparser.add_argument(\n \"--dont-save\",\n action=\"store_true\",\n help=\"don't save the policy network weights.\",\n)\nparser.add_argument(\"--render\", action=\"store_true\", help=\"show the env.\")\nparser.add_argument(\"--num-trajs\", type=int, default=10)\nparser.add_argument(\"--view-reward\", action=\"store_true\")\n\nparser.add_argument(\n \"--policy-net-hidden-dims\", nargs=\"*\", type=int, default=[256]\n)\nparser.add_argument(\n \"--reward-net-hidden-dims\", nargs=\"*\", type=int, default=[256]\n)\n\nparser.add_argument(\"--lr\", type=float, default=0.0001)\nparser.add_argument(\"--on-server\", action=\"store_true\")\n\nparser.add_argument(\n \"--feat-extractor\",\n type=str,\n default=None,\n help=\"The name of the \\\n feature extractor to be used in the experiment.\",\n)\nparser.add_argument(\n \"--save-folder\",\n type=str,\n default=None,\n help=\"The name of the folder to \\\n store experiment related information.\",\n)\n\nparser.add_argument(\n \"--annotation-file\",\n type=str,\n default=\"../envs/expert_datasets/university_students/annotation/processed/frame_skip_1/students003_processed_corrected.txt\",\n help=\"The location of the annotation file to \\\n be used to run the environment.\",\n)\n\nparser.add_argument(\n \"--total-episodes\", type=int, default=1000, help=\"Total episodes of RL\"\n)\nparser.add_argument(\n \"--max-ep-length\",\n type=int,\n default=200,\n help=\"Max length of a single episode.\",\n)\n\nparser.add_argument(\"--replace-subject\", action=\"store_true\")\nparser.add_argument(\"--seed\", type=int, default=789)\n\nparser.add_argument(\n \"--subject\",\n type=int,\n default=None,\n help=\"The id of the pedestrian to replace during training or \\\n testing.\",\n)\n\nparser.add_argument(\n \"--exp-trajectory-path\",\n type=str,\n default=None,\n help=\"The name of the directory in which \\\n the expert trajectories are stored.(Relative path)\",\n)\n\nparser.add_argument(\n \"--segment-size\",\n type=int,\n default=None,\n help=\"Size of each trajectory segment.\",\n)\nparser.add_argument(\n \"--rl-method\",\n type=str,\n default=\"ActorCritic\",\n help=\"The RL trainer to be used.\",\n)\n\nparser.add_argument(\n '--store-raw-states',\n action=\"store_true\",\n help=\"Set to true if you want to store the trajectory of the policy in the form\\\n of raw state dictionary. \"\n)\n\nparser.add_argument(\n '--entropy-coeff',\n type=float,\n default=0.001,\n help='Coefficient value for the entropy term for policy update.' \n)\n\nparser.add_argument(\"--play-interval\", type=int, default=100)\nparser.add_argument(\"--replay-buffer-sample-size\", type=int, default=1000)\nparser.add_argument(\"--replay-buffer-size\", type=int, default=5000)\nparser.add_argument(\"--entropy-target\", type=float, default=0.3)\nparser.add_argument(\"--gamma\", type=float, default=0.99)\n\n\ndef main():\n\n #####for the logger\n ts = time.time()\n st = datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%d %H:%M:%S\")\n ###################\n\n args = parser.parse_args()\n\n seed_all(args.seed)\n\n if args.on_server:\n\n matplotlib.use(\"Agg\")\n # pygame without monitor\n os.environ[\"SDL_VIDEODRIVER\"] = \"dummy\"\n\n from matplotlib import pyplot as plt\n\n mp.set_start_method(\"spawn\")\n\n from rlmethods.b_actor_critic import ActorCritic\n from rlmethods.soft_ac import SoftActorCritic, QSoftActorCritic\n from rlmethods.rlutils import ReplayBuffer\n\n from envs.gridworld_drone import GridWorldDrone\n from featureExtractor.drone_feature_extractor import (\n DroneFeatureSAM1,\n DroneFeatureOccup,\n DroneFeatureRisk,\n DroneFeatureRisk_v2,\n VasquezF1,\n VasquezF2,\n VasquezF3,\n Fahad,\n GoalConditionedFahad,\n )\n from featureExtractor.gridworld_featureExtractor import (\n FrontBackSide,\n LocalGlobal,\n OneHot,\n SocialNav,\n FrontBackSideSimple,\n )\n from featureExtractor.drone_feature_extractor import (\n DroneFeatureRisk_speed,\n DroneFeatureRisk_speedv2,\n )\n\n from featureExtractor.drone_feature_extractor import VasquezF1\n\n save_folder = None\n\n if not args.dont_save and not args.play:\n\n if not args.save_folder:\n print(\"Provide save folder.\")\n exit()\n\n policy_net_dims = \"-policy_net-\"\n for dim in args.policy_net_hidden_dims:\n policy_net_dims += str(dim)\n policy_net_dims += \"-\"\n\n reward_net_dims = \"-reward_net-\"\n for dim in args.reward_net_hidden_dims:\n reward_net_dims += str(dim)\n reward_net_dims += \"-\"\n\n save_folder = (\n \"./results/\"\n + args.save_folder\n + st\n + args.feat_extractor\n + \"-seed-\"\n + str(args.seed)\n + policy_net_dims\n + reward_net_dims\n + \"-total-ep-\"\n + str(args.total_episodes)\n + \"-max-ep-len-\"\n + str(args.max_ep_length)\n )\n\n experiment_logger = Logger(save_folder, \"experiment_info.txt\")\n experiment_logger.log_header(\"Arguments for the experiment :\")\n repo = git.Repo(search_parent_directories=True)\n experiment_logger.log_info({'From branch : ' : repo.active_branch.name})\n experiment_logger.log_info({'Commit number : ' : repo.head.object.hexsha})\n experiment_logger.log_info(vars(args))\n\n window_size = 9\n step_size = 2\n agent_width = 10\n obs_width = 10\n grid_size = 10\n\n feat_ext = None\n # initialize the feature extractor to be used\n if args.feat_extractor == \"Onehot\":\n feat_ext = OneHot(grid_rows=10, grid_cols=10)\n if args.feat_extractor == \"SocialNav\":\n feat_ext = SocialNav(fieldList=[\"agent_state\", \"goal_state\"])\n if args.feat_extractor == \"FrontBackSideSimple\":\n feat_ext = FrontBackSideSimple(\n thresh1=1,\n thresh2=2,\n thresh3=3,\n thresh4=4,\n step_size=step_size,\n agent_width=agent_width,\n obs_width=obs_width,\n )\n\n if args.feat_extractor == \"LocalGlobal\":\n feat_ext = LocalGlobal(\n window_size=11,\n grid_size=grid_size,\n agent_width=agent_width,\n obs_width=obs_width,\n step_size=step_size,\n )\n\n if args.feat_extractor == \"DroneFeatureSAM1\":\n\n feat_ext = DroneFeatureSAM1(\n agent_width=agent_width,\n obs_width=obs_width,\n step_size=step_size,\n grid_size=grid_size,\n thresh1=15,\n thresh2=30,\n )\n\n if args.feat_extractor == \"DroneFeatureOccup\":\n\n feat_ext = DroneFeatureOccup(\n agent_width=agent_width,\n obs_width=obs_width,\n step_size=step_size,\n grid_size=grid_size,\n window_size=window_size,\n )\n\n if args.feat_extractor == \"DroneFeatureRisk\":\n\n feat_ext = DroneFeatureRisk(\n agent_width=agent_width,\n obs_width=obs_width,\n step_size=step_size,\n grid_size=grid_size,\n show_agent_persp=False,\n thresh1=15,\n thresh2=30,\n )\n\n if args.feat_extractor == \"DroneFeatureRisk_v2\":\n\n feat_ext = DroneFeatureRisk_v2(\n agent_width=agent_width,\n obs_width=obs_width,\n step_size=step_size,\n grid_size=grid_size,\n show_agent_persp=False,\n thresh1=15,\n thresh2=30,\n )\n\n if args.feat_extractor == \"DroneFeatureRisk_speed\":\n\n feat_ext = DroneFeatureRisk_speed(\n agent_width=agent_width,\n obs_width=obs_width,\n step_size=step_size,\n grid_size=grid_size,\n show_agent_persp=False,\n return_tensor=False,\n thresh1=10,\n thresh2=15,\n )\n\n if args.feat_extractor == \"DroneFeatureRisk_speedv2\":\n\n feat_ext = DroneFeatureRisk_speedv2(\n agent_width=agent_width,\n obs_width=obs_width,\n step_size=step_size,\n grid_size=grid_size,\n show_agent_persp=False,\n return_tensor=False,\n thresh1=18,\n thresh2=30,\n )\n\n if args.feat_extractor == \"VasquezF1\":\n feat_ext = VasquezF1(agent_width * 6, 0.5, 1.0)\n\n if args.feat_extractor == \"VasquezF2\":\n feat_ext = VasquezF1(agent_width * 6, 0.5, 1.0)\n\n if args.feat_extractor == \"VasquezF3\":\n feat_ext = VasquezF3(agent_width)\n\n if args.feat_extractor == \"Fahad\":\n feat_ext = Fahad(36, 60, 0.5, 1.0)\n\n if args.feat_extractor == \"GoalConditionedFahad\":\n feat_ext = GoalConditionedFahad(36, 60, 0.5, 1.0)\n\n if feat_ext is None:\n print(\"Please enter proper feature extractor!\")\n exit()\n # log feature extractor info\n\n if not args.dont_save and not args.play:\n\n experiment_logger.log_header(\"Parameters of the feature extractor :\")\n experiment_logger.log_info(feat_ext.__dict__)\n\n # initialize the environment\n if args.replace_subject:\n replace_subject = True\n else:\n replace_subject = False\n\n env = GridWorldDrone(\n display=args.render,\n is_onehot=False,\n seed=args.seed,\n obstacles=None,\n show_trail=False,\n is_random=True,\n annotation_file=args.annotation_file,\n subject=args.subject,\n tick_speed=60,\n obs_width=10,\n step_size=step_size,\n agent_width=agent_width,\n replace_subject=replace_subject,\n segment_size=args.segment_size,\n external_control=True,\n step_reward=0.001,\n show_comparison=True,\n consider_heading=True,\n show_orientation=True,\n # rows=200, cols=200, width=grid_size)\n rows=576,\n cols=720,\n width=grid_size,\n )\n\n # env = gym.make('Acrobot-v1')\n # log environment info\n if not args.dont_save and not args.play:\n\n experiment_logger.log_header(\"Environment details :\")\n experiment_logger.log_info(env.__dict__)\n\n # initialize RL\n\n if args.rl_method == \"ActorCritic\":\n model = ActorCritic(\n env,\n feat_extractor=feat_ext,\n gamma=1,\n log_interval=100,\n max_episode_length=args.max_ep_length,\n hidden_dims=args.policy_net_hidden_dims,\n save_folder=save_folder,\n lr=args.lr,\n entropy_coeff=args.entropy_coeff,\n max_episodes=args.total_episodes,\n )\n\n if args.rl_method == \"SAC\":\n\n replay_buffer = ReplayBuffer(args.replay_buffer_size)\n\n model = SoftActorCritic(\n env,\n replay_buffer,\n feat_ext,\n buffer_sample_size=args.replay_buffer_sample_size,\n entropy_tuning=True,\n play_interval=args.play_interval,\n entropy_target=args.entropy_target,\n gamma=args.gamma,\n learning_rate=args.lr,\n )\n\n if args.rl_method == \"discrete_QSAC\":\n\n replay_buffer = ReplayBuffer(args.replay_buffer_size)\n\n model = QSoftActorCritic(\n env,\n replay_buffer,\n feat_ext,\n buffer_sample_size=args.replay_buffer_sample_size,\n entropy_tuning=True,\n play_interval=args.play_interval,\n entropy_target=args.entropy_target,\n gamma=args.gamma,\n learning_rate=args.lr,\n )\n # log RL info\n if not args.dont_save and not args.play:\n\n experiment_logger.log_header(\"Details of the RL method :\")\n experiment_logger.log_info(model.__dict__)\n\n if args.policy_path is not None:\n\n from debugtools import numericalSort\n\n policy_file_list = []\n reward_across_models = []\n # print(args.policy_path)\n if os.path.isfile(args.policy_path):\n policy_file_list.append(args.policy_path)\n if os.path.isdir(args.policy_path):\n policy_names = glob.glob(os.path.join(args.policy_path, \"*.pt\"))\n policy_file_list = sorted(policy_names, key=numericalSort)\n\n xaxis = np.arange(len(policy_file_list))\n\n if not args.play and not args.play_user:\n # no playing of any kind, so training\n\n if args.reward_path is None:\n\n if args.policy_path:\n model.policy.load(args.policy_path)\n\n if args.rl_method == \"SAC\" or args.rl_method == \"discrete_QSAC\":\n model.train(args.total_episodes, args.max_ep_length)\n\n else:\n model.train()\n\n else:\n from irlmethods.deep_maxent import RewardNet\n\n state_size = feat_ext.extract_features(env.reset()).shape[0]\n reward_net = RewardNet(state_size, args.reward_net_hidden_dims)\n reward_net.load(args.reward_path)\n print(next(reward_net.parameters()).is_cuda)\n model.train(reward_net=reward_net)\n\n if not args.dont_save:\n model.policy.save(save_folder + \"/policy-models/\")\n\n if args.play:\n # env.tickSpeed = 15\n from debugtools import compile_results\n\n xaxis = []\n counter = 1\n plt.figure(0)\n avg_reward_list = []\n frac_good_run_list = []\n print(policy_file_list)\n for policy_file in policy_file_list:\n\n print(\"Playing for policy :\", policy_file)\n model.policy.load(policy_file)\n policy_folder = policy_file.strip().split(\"/\")[0:-2]\n save_folder = \"\"\n for p in policy_folder:\n save_folder = save_folder + p + \"/\"\n\n print(\"The final save folder \", save_folder)\n # env.tickSpeed = 10\n assert args.policy_path is not None, \"pass a policy to play from!\"\n if args.exp_trajectory_path is not None:\n from irlmethods.irlUtils import calculate_expert_svf\n\n expert_svf = calculate_expert_svf(\n args.exp_trajectory_path,\n max_time_steps=args.max_ep_length,\n feature_extractor=feat_ext,\n gamma=1,\n )\n # reward_across_models.append(model.generate_trajectory(args.num_trajs, args.render))\n if args.exp_trajectory_path is None:\n\n if args.dont_save:\n rewards, state_info, sub_info = model.generate_trajectory(\n args.num_trajs, args.render\n )\n else:\n rewards, state_info, sub_info = model.generate_trajectory(\n args.num_trajs,\n args.render,\n store_raw=args.store_raw_states,\n path=save_folder + \"/agent_generated_trajectories/\",\n )\n else:\n\n if args.dont_save:\n rewards, state_info, sub_info = model.generate_trajectory(\n args.num_trajs, args.render, expert_svf=expert_svf\n )\n else:\n rewards, state_info, sub_info = model.generate_trajectory(\n args.num_trajs,\n args.render,\n path=save_folder + \"/agent_generated_trajectories/\",\n expert_svf=expert_svf,\n )\n\n avg_reward, good_run_frac = compile_results(\n rewards, state_info, sub_info\n )\n\n avg_reward_list.append(avg_reward)\n frac_good_run_list.append(good_run_frac)\n plt.plot(avg_reward_list, c=\"r\")\n plt.plot(frac_good_run_list, c=\"g\")\n plt.draw()\n plt.show()\n\n if args.play_user:\n env.tickSpeed = 200\n\n model.generate_trajectory_user(\n args.num_trajs, args.render, path=\"./user_generated_trajectories/\"\n )\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"torch.multiprocessing.set_start_method",
"matplotlib.use",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
erfanMhi/Deep-Reinforcement-Learning-CS285-Pytroch | [
"6da04f367e52a451c202ae7e5477994c1d149baf"
] | [
"hw4/cs285/policies/argmax_policy.py"
] | [
"import torch\nimport tensorflow as tf\n\nfrom cs285.infrastructure.torch_utils import convert_args_to_tensor\n\nclass ArgMaxPolicy(object):\n\n def __init__(self, critic, device='cpu'):\n self.critic = critic\n self.device = device\n\n @convert_args_to_tensor()\n def get_action(self, obs):\n\n # TODO: Make use of self.action by passing these input observations into self.critic\n # HINT: you'll want to populate the critic's obs_t_ph placeholder\n \n with torch.no_grad():\n if len(obs.shape) > 1:\n observation = obs.to(self.device)\n else:\n observation = obs[None].to(self.device)\n # TODO: Define what action this policy should return\n # HINT1: the critic's q_t_values indicate the goodness of observations, \n # so they should be used to decide the action to perform\n return torch.argmax(self.critic.q_t_values(observation), dim=1).cpu().numpy()"
] | [
[
"torch.no_grad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lace/entente | [
"49805e0f7117098f35826eb6a23e1ad7ad22c136"
] | [
"entente/landmarks/test_landmarker.py"
] | [
"from entente.landmarks.landmarker import Landmarker\nfrom entente.landmarks.serialization import dump_landmarks\nfrom lacecore import Mesh, shapes\nimport numpy as np\nimport pytest\n\n\ndef source_target_landmarks():\n source_mesh = shapes.cube(np.zeros(3), 1.0)\n target_mesh = (\n source_mesh.transform()\n .uniform_scale(5.0)\n .translate(np.array([0, 3.5, 1.0]))\n .end()\n )\n\n landmarks = {\n \"origin\": np.zeros(3),\n \"near_opposite_corner\": np.array([0.8, 0.9, 1.0]),\n }\n\n expected_landmarks = {\n \"origin\": np.array([0.0, 3.5, 1.0]),\n \"near_opposite_corner\": np.array([4.0, 8.0, 6.0]),\n }\n\n return source_mesh, target_mesh, landmarks, expected_landmarks\n\n\ndef test_landmarker(tmp_path):\n source_mesh, target_mesh, landmarks, expected_landmarks = source_target_landmarks()\n\n landmarker = Landmarker(source_mesh, landmarks)\n\n transferred = landmarker.transfer_landmarks_onto(target_mesh)\n np.testing.assert_array_equal(transferred[\"origin\"], expected_landmarks[\"origin\"])\n np.testing.assert_array_equal(\n transferred[\"near_opposite_corner\"], expected_landmarks[\"near_opposite_corner\"]\n )\n\n source_mesh_path = str(tmp_path / \"source.obj\")\n landmark_path = str(tmp_path / \"landmarks.json\")\n\n source_mesh.write_obj(source_mesh_path)\n dump_landmarks(landmarks, landmark_path)\n\n landmarker = Landmarker.load(\n source_mesh_path=source_mesh_path, landmark_path=landmark_path\n )\n transferred = landmarker.transfer_landmarks_onto(target_mesh)\n np.testing.assert_array_equal(transferred[\"origin\"], expected_landmarks[\"origin\"])\n np.testing.assert_array_equal(\n transferred[\"near_opposite_corner\"], expected_landmarks[\"near_opposite_corner\"]\n )\n\n\ndef test_landmarker_wrong_topology():\n source_mesh = shapes.cube(np.zeros(3), 1.0)\n\n # Create a second mesh with a different topology.\n target_mesh = source_mesh.faces_flipped()\n\n # Landmarks are empty; we don't get that far.\n landmarker = Landmarker(source_mesh, {})\n\n with pytest.raises(ValueError, match=\"Target mesh must have the same topology\"):\n landmarker.transfer_landmarks_onto(target_mesh)\n\n\ndef test_landmarker_quad():\n tri_mesh = shapes.cube(np.zeros(3), 1.0)\n quad_mesh = Mesh(v=np.zeros((0, 3)), f=np.zeros((0, 4), dtype=np.int64))\n\n with pytest.raises(ValueError, match=\"Source mesh should be triangulated\"):\n # Landmarks are empty; we don't get that far.\n Landmarker(quad_mesh, {})\n\n landmarker = Landmarker(tri_mesh, {})\n with pytest.raises(ValueError, match=\"Target mesh must be triangulated\"):\n landmarker.transfer_landmarks_onto(quad_mesh)\n"
] | [
[
"numpy.testing.assert_array_equal",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
datavaluepeople/tentaclio | [
"eb6920a0e115c6c08043063a8c1013d812ec34c8"
] | [
"tests/functional/postgres/test_client.py"
] | [
"import pandas as pd\nimport pytest\nimport sqlalchemy as sqla\n\n\nTEST_TABLE_NAME = \"test_table\"\nTEST_COLUMNS = [\"column_int\", \"column_str\", \"column_float\"]\nTEST_VALUES = [1, \"test_1\", 123.456]\n\n\ndef _client(db_client):\n test_meta = sqla.MetaData()\n sqla.Table(\n # Meta\n TEST_TABLE_NAME,\n test_meta,\n # Columns\n sqla.Column(TEST_COLUMNS[0], sqla.Integer),\n sqla.Column(TEST_COLUMNS[1], sqla.String(256)),\n sqla.Column(TEST_COLUMNS[2], sqla.Float),\n )\n db_client.set_schema(test_meta)\n yield db_client\n db_client.delete_schema(test_meta)\n\n\[email protected]\ndef fixture_client(db_client):\n yield from _client(db_client)\n\n\[email protected]\ndef fixture_client_app_name(db_client_application_name):\n yield from _client(db_client_application_name)\n\n\[email protected]\ndef fixture_df():\n df = pd.DataFrame(data=[TEST_VALUES], columns=TEST_COLUMNS)\n return df\n\n\nclass TestPostgresClient:\n def test_executing_and_querying_sql(self, fixture_client):\n sql_insert = f\"\"\"INSERT INTO {TEST_TABLE_NAME} VALUES\n ({TEST_VALUES[0]}, '{TEST_VALUES[1]}', {TEST_VALUES[2]});\"\"\"\n sql_query = f\"SELECT * FROM {TEST_TABLE_NAME};\"\n\n fixture_client.execute(sql_insert)\n result = fixture_client.query(sql_query)\n\n assert list(result.fetchone()) == TEST_VALUES\n\n def test_executing_and_querying_sql_app_name(self, fixture_client_app_name):\n \"\"\"Sanity check for when setting the application name. \"\"\"\n sql_insert = f\"\"\"INSERT INTO {TEST_TABLE_NAME} VALUES\n ({TEST_VALUES[0]}, '{TEST_VALUES[1]}', {TEST_VALUES[2]});\"\"\"\n sql_query = f\"SELECT * FROM {TEST_TABLE_NAME};\"\n\n fixture_client_app_name.execute(sql_insert)\n result = fixture_client_app_name.query(sql_query)\n\n assert list(result.fetchone()) == TEST_VALUES\n\n def test_dumping_and_getting_df(self, fixture_client, fixture_df):\n fixture_client.dump_df(fixture_df, TEST_TABLE_NAME)\n retrieved_df = fixture_client.get_df(f\"SELECT * FROM {TEST_TABLE_NAME};\")\n\n assert retrieved_df.equals(fixture_df)\n\n def test_dumping_and_getting_df_unsafe(self, fixture_client, fixture_df):\n fixture_client.dump_df(fixture_df, TEST_TABLE_NAME)\n retrieved_df = fixture_client.get_df_unsafe(f\"SELECT * FROM {TEST_TABLE_NAME};\")\n\n assert retrieved_df.equals(fixture_df)\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
runeg96/vgn | [
"24278b80935f2a9cd51d20c9e2c5bfe6da4ce53a"
] | [
"src/vgn/utils/btsim.py"
] | [
"import time\n\nimport numpy as np\nimport pybullet\nfrom pybullet_utils import bullet_client\n\n\nfrom vgn.utils.transform import Rotation, Transform\n\nassert pybullet.isNumpyEnabled(), \"Pybullet needs to be built with NumPy\"\n\n\nclass BtWorld(object):\n \"\"\"Interface to a PyBullet physics server.\n\n Attributes:\n dt: Time step of the physics simulation.\n rtf: Real time factor. If negative, the simulation is run as fast as possible.\n sim_time: Virtual time elpased since the last simulation reset.\n \"\"\"\n\n def __init__(self, gui=True):\n connection_mode = pybullet.GUI if gui else pybullet.DIRECT\n self.p = bullet_client.BulletClient(connection_mode)\n\n self.gui = gui\n self.dt = 1.0 / 240.0\n self.solver_iterations = 150\n\n self.reset()\n\n def set_gravity(self, gravity):\n self.p.setGravity(*gravity)\n\n def load_urdf(self, urdf_path, pose, scale=1.0):\n body = Body.from_urdf(self.p, urdf_path, pose, scale)\n self.bodies[body.uid] = body\n return body\n\n def remove_body(self, body):\n self.p.removeBody(body.uid)\n del self.bodies[body.uid]\n\n def add_constraint(self, *argv, **kwargs):\n \"\"\"See `Constraint` below.\"\"\"\n constraint = Constraint(self.p, *argv, **kwargs)\n return constraint\n\n def add_camera(self, intrinsic, near, far):\n camera = Camera(self.p, intrinsic, near, far)\n return camera\n\n def get_contacts(self, bodyA):\n points = self.p.getContactPoints(bodyA.uid)\n contacts = []\n for point in points:\n contact = Contact(\n bodyA=self.bodies[point[1]],\n bodyB=self.bodies[point[2]],\n point=point[5],\n normal=point[7],\n depth=point[8],\n force=point[9],\n )\n contacts.append(contact)\n return contacts\n\n def reset(self):\n self.p.resetSimulation()\n self.p.setPhysicsEngineParameter(\n fixedTimeStep=self.dt, numSolverIterations=self.solver_iterations\n )\n self.bodies = {}\n self.sim_time = 0.0\n\n def step(self):\n self.p.stepSimulation()\n self.sim_time += self.dt\n if self.gui:\n time.sleep(self.dt)\n\n def save_state(self):\n return self.p.saveState()\n\n def restore_state(self, state_uid):\n self.p.restoreState(stateId=state_uid)\n\n def close(self):\n self.p.disconnect()\n\n\nclass Body(object):\n \"\"\"Interface to a multibody simulated in PyBullet.\n\n Attributes:\n uid: The unique id of the body within the physics server.\n name: The name of the body.\n joints: A dict mapping joint names to Joint objects.\n links: A dict mapping link names to Link objects.\n \"\"\"\n\n def __init__(self, physics_client, body_uid):\n self.p = physics_client\n self.uid = body_uid\n self.name = self.p.getBodyInfo(self.uid)[1].decode(\"utf-8\")\n self.joints, self.links = {}, {}\n for i in range(self.p.getNumJoints(self.uid)):\n joint_info = self.p.getJointInfo(self.uid, i)\n joint_name = joint_info[1].decode(\"utf8\")\n self.joints[joint_name] = Joint(self.p, self.uid, i)\n link_name = joint_info[12].decode(\"utf8\")\n self.links[link_name] = Link(self.p, self.uid, i)\n\n @classmethod\n def from_urdf(cls, physics_client, urdf_path, pose, scale):\n body_uid = physics_client.loadURDF(\n str(urdf_path),\n pose.translation,\n pose.rotation.as_quat(),\n globalScaling=scale,\n )\n return cls(physics_client, body_uid)\n\n def get_pose(self):\n pos, ori = self.p.getBasePositionAndOrientation(self.uid)\n return Transform(Rotation.from_quat(ori), np.asarray(pos))\n\n def set_pose(self, pose):\n self.p.resetBasePositionAndOrientation(\n self.uid, pose.translation, pose.rotation.as_quat()\n )\n\n def get_velocity(self):\n linear, angular = self.p.getBaseVelocity(self.uid)\n return linear, angular\n\n\nclass Link(object):\n \"\"\"Interface to a link simulated in Pybullet.\n\n Attributes:\n link_index: The index of the joint.\n \"\"\"\n\n def __init__(self, physics_client, body_uid, link_index):\n self.p = physics_client\n self.body_uid = body_uid\n self.link_index = link_index\n\n def get_pose(self):\n link_state = self.p.getLinkState(self.body_uid, self.link_index)\n pos, ori = link_state[0], link_state[1]\n return Transform(Rotation.from_quat(ori), pos)\n\n\nclass Joint(object):\n \"\"\"Interface to a joint simulated in PyBullet.\n\n Attributes:\n joint_index: The index of the joint.\n lower_limit: Lower position limit of the joint.\n upper_limit: Upper position limit of the joint.\n effort: The maximum joint effort.\n \"\"\"\n\n def __init__(self, physics_client, body_uid, joint_index):\n self.p = physics_client\n self.body_uid = body_uid\n self.joint_index = joint_index\n\n joint_info = self.p.getJointInfo(body_uid, joint_index)\n self.lower_limit = joint_info[8]\n self.upper_limit = joint_info[9]\n self.effort = joint_info[10]\n\n def get_position(self):\n joint_state = self.p.getJointState(self.body_uid, self.joint_index)\n return joint_state[0]\n\n def set_position(self, position, kinematics=False):\n if kinematics:\n self.p.resetJointState(self.body_uid, self.joint_index, position)\n self.p.setJointMotorControl2(\n self.body_uid,\n self.joint_index,\n pybullet.POSITION_CONTROL,\n targetPosition=position,\n force=self.effort,\n )\n\n\nclass Constraint(object):\n \"\"\"Interface to a constraint in PyBullet.\n\n Attributes:\n uid: The unique id of the constraint within the physics server.\n \"\"\"\n\n def __init__(\n self,\n physics_client,\n parent,\n parent_link,\n child,\n child_link,\n joint_type,\n joint_axis,\n parent_frame,\n child_frame,\n ):\n \"\"\"\n Create a new constraint between links of bodies.\n\n Args:\n parent:\n parent_link: None for the base.\n child: None for a fixed frame in world coordinates.\n\n \"\"\"\n self.p = physics_client\n parent_body_uid = parent.uid\n parent_link_index = parent_link.link_index if parent_link else -1\n child_body_uid = child.uid if child else -1\n child_link_index = child_link.link_index if child_link else -1\n\n self.uid = self.p.createConstraint(\n parentBodyUniqueId=parent_body_uid,\n parentLinkIndex=parent_link_index,\n childBodyUniqueId=child_body_uid,\n childLinkIndex=child_link_index,\n jointType=joint_type,\n jointAxis=joint_axis,\n parentFramePosition=parent_frame.translation,\n parentFrameOrientation=parent_frame.rotation.as_quat(),\n childFramePosition=child_frame.translation,\n childFrameOrientation=child_frame.rotation.as_quat(),\n )\n\n def change(self, **kwargs):\n self.p.changeConstraint(self.uid, **kwargs)\n\n\nclass Contact(object):\n \"\"\"Contact point between two multibodies.\n\n Attributes:\n point: Contact point.\n normal: Normal vector from ... to ...\n depth: Penetration depth\n force: Contact force acting on body ...\n \"\"\"\n\n def __init__(self, bodyA, bodyB, point, normal, depth, force):\n self.bodyA = bodyA\n self.bodyB = bodyB\n self.point = point\n self.normal = normal\n self.depth = depth\n self.force = force\n\n\nclass Camera(object):\n \"\"\"Virtual RGB-D camera based on the PyBullet camera interface.\n\n Attributes:\n intrinsic: The camera intrinsic parameters.\n \"\"\"\n\n def __init__(self, physics_client, intrinsic, near, far):\n self.intrinsic = intrinsic\n self.near = near\n self.far = far\n self.proj_matrix = _build_projection_matrix(intrinsic, near, far)\n self.p = physics_client\n\n def render(self, extrinsic):\n \"\"\"Render synthetic RGB and depth images.\n\n Args:\n extrinsic: Extrinsic parameters, T_cam_ref.\n \"\"\"\n # Construct OpenGL compatible view and projection matrices.\n gl_view_matrix = extrinsic.as_matrix()\n gl_view_matrix[2, :] *= -1 # flip the Z axis\n gl_view_matrix = gl_view_matrix.flatten(order=\"F\")\n gl_proj_matrix = self.proj_matrix.flatten(order=\"F\")\n\n result = self.p.getCameraImage(\n width=self.intrinsic.width,\n height=self.intrinsic.height,\n viewMatrix=gl_view_matrix,\n projectionMatrix=gl_proj_matrix,\n renderer=pybullet.ER_TINY_RENDERER,\n )\n\n rgb, z_buffer = result[2][:, :, :3], result[3]\n depth = (\n 1.0 * self.far * self.near / (self.far - (self.far - self.near) * z_buffer)\n )\n return rgb, depth\n\n\ndef _build_projection_matrix(intrinsic, near, far):\n perspective = np.array(\n [\n [intrinsic.fx, 0.0, -intrinsic.cx, 0.0],\n [0.0, intrinsic.fy, -intrinsic.cy, 0.0],\n [0.0, 0.0, near + far, near * far],\n [0.0, 0.0, -1.0, 0.0],\n ]\n )\n ortho = _gl_ortho(0.0, intrinsic.width, intrinsic.height, 0.0, near, far)\n return np.matmul(ortho, perspective)\n\n\ndef _gl_ortho(left, right, bottom, top, near, far):\n ortho = np.diag(\n [2.0 / (right - left), 2.0 / (top - bottom), -2.0 / (far - near), 1.0]\n )\n ortho[0, 3] = -(right + left) / (right - left)\n ortho[1, 3] = -(top + bottom) / (top - bottom)\n ortho[2, 3] = -(far + near) / (far - near)\n return ortho\n"
] | [
[
"numpy.diag",
"numpy.array",
"numpy.matmul",
"numpy.asarray"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
roshanr11/solaris | [
"1032f089c311c008a1a8fb297d8b46a991febcb1"
] | [
"solaris/eval/base.py"
] | [
"import shapely.wkt\nimport geopandas as gpd\nimport pandas as pd\nfrom tqdm import tqdm\nimport os\nfrom . import iou\nfrom fiona.errors import DriverError\nfrom fiona._err import CPLE_OpenFailedError\n\n\nclass Evaluator():\n \"\"\"Object to test IoU for predictions and ground truth polygons.\n\n Attributes\n ----------\n ground_truth_fname : str\n The filename for the ground truth CSV or JSON.\n ground_truth_GDF : :class:`geopandas.GeoDataFrame`\n A :class:`geopandas.GeoDataFrame` containing the ground truth vector\n labels.\n ground_truth_GDF_Edit : :class:`geopandas.GeoDataFrame`\n A copy of ``ground_truth_GDF`` which will be manipulated during\n processing.\n proposal_GDF : :class:`geopandas.GeoDataFrame`\n The proposal :class:`geopandas.GeoDataFrame`, added using\n ``load_proposal()``.\n\n Arguments\n ---------\n ground_truth_vector_file : str\n Path to .geojson file for ground truth.\n\n \"\"\"\n\n def __init__(self, ground_truth_vector_file):\n # Load Ground Truth : Ground Truth should be in geojson or shape file\n try:\n if ground_truth_vector_file.lower().endswith('json'):\n self.load_truth(ground_truth_vector_file)\n elif ground_truth_vector_file.lower().endswith('csv'):\n self.load_truth(ground_truth_vector_file, truthCSV=True)\n self.ground_truth_fname = ground_truth_vector_file\n except AttributeError: # handles passing gdf instead of path to file\n self.ground_truth_GDF = ground_truth_vector_file\n self.ground_truth_fname = 'GeoDataFrame variable'\n self.ground_truth_sindex = self.ground_truth_GDF.sindex # get sindex\n # create deep copy of ground truth file for calculations\n self.ground_truth_GDF_Edit = self.ground_truth_GDF.copy(deep=True)\n self.proposal_GDF = gpd.GeoDataFrame([]) # initialize proposal GDF\n\n def __repr__(self):\n return 'Evaluator {}'.format(os.path.split(\n self.ground_truth_fname)[-1])\n\n def get_iou_by_building(self):\n \"\"\"Returns a copy of the ground truth table, which includes a\n per-building IoU score column after eval_iou_spacenet_csv() has run.\n \"\"\"\n\n output_ground_truth_GDF = self.ground_truth_GDF.copy(deep=True)\n return output_ground_truth_GDF\n\n def eval_iou_spacenet_csv(self, miniou=0.5, iou_field_prefix=\"iou_score\",\n imageIDField=\"ImageId\", debug=False, min_area=0):\n \"\"\"Evaluate IoU between the ground truth and proposals in CSVs.\n\n Arguments\n ---------\n miniou : float , optional\n Minimum intersection over union score to qualify as a successful\n object detection event. Defaults to ``0.5``.\n iou_field_prefix : str , optional\n The name of the IoU score column in ``self.proposal_GDF``. Defaults\n to ``\"iou_score\"`` .\n imageIDField : str , optional\n The name of the column corresponding to the image IDs in the\n ground truth data. Defaults to ``\"ImageId\"``.\n debug : bool , optional\n Argument for verbose execution during debugging. Defaults to\n ``False`` (silent execution).\n min_area : float or int , optional\n Minimum area of a ground truth polygon to be considered during\n evaluation. Often set to ``20`` in SpaceNet competitions. Defaults\n to ``0`` (consider all ground truth polygons).\n\n Returns\n -------\n scoring_dict_list : list\n list of score output dicts for each image in the ground\n truth and evaluated image datasets. The dicts contain\n the following keys: ::\n\n ('imageID', 'iou_field', 'TruePos', 'FalsePos', 'FalseNeg',\n 'Precision', 'Recall', 'F1Score')\n\n \"\"\"\n # Get List of all ImageID in both ground truth and proposals\n imageIDList = []\n imageIDList.extend(list(self.ground_truth_GDF[imageIDField].unique()))\n if not self.proposal_GDF.empty:\n imageIDList.extend(list(self.proposal_GDF[imageIDField].unique()))\n imageIDList = list(set(imageIDList))\n iou_field = iou_field_prefix\n scoring_dict_list = []\n self.ground_truth_GDF[iou_field] = 0.\n iou_index = self.ground_truth_GDF.columns.get_loc(iou_field)\n id_cols = 2\n ground_truth_ids = self.ground_truth_GDF.iloc[:, :id_cols]\n\n for imageID in tqdm(imageIDList):\n self.ground_truth_GDF_Edit = self.ground_truth_GDF[\n self.ground_truth_GDF[imageIDField] == imageID\n ].copy(deep=True)\n self.ground_truth_GDF_Edit = self.ground_truth_GDF_Edit[\n self.ground_truth_GDF_Edit.area >= min_area\n ]\n proposal_GDF_copy = self.proposal_GDF[self.proposal_GDF[\n imageIDField] == imageID].copy(deep=True)\n proposal_GDF_copy = proposal_GDF_copy[proposal_GDF_copy.area\n > min_area]\n if debug:\n print(iou_field)\n for _, pred_row in proposal_GDF_copy.iterrows():\n if debug:\n print(pred_row.name)\n if pred_row.geometry.area > 0:\n pred_poly = pred_row.geometry\n iou_GDF = iou.calculate_iou(pred_poly,\n self.ground_truth_GDF_Edit)\n # Get max iou\n if not iou_GDF.empty:\n max_index = iou_GDF['iou_score'].idxmax(axis=0,\n skipna=True)\n max_iou_row = iou_GDF.loc[max_index]\n # Update entry in full ground truth table\n previous_iou = self.ground_truth_GDF.iloc[\n max_index, iou_index]\n new_iou = max_iou_row[iou_field]\n if new_iou > previous_iou:\n self.ground_truth_GDF.iloc[max_index, iou_index] \\\n = new_iou\n if max_iou_row['iou_score'] > miniou:\n self.proposal_GDF.loc[pred_row.name, iou_field] \\\n = max_iou_row['iou_score']\n self.ground_truth_GDF_Edit \\\n = self.ground_truth_GDF_Edit.drop(\n max_iou_row.name, axis=0)\n else:\n self.proposal_GDF.loc[pred_row.name, iou_field] = 0\n else:\n self.proposal_GDF.loc[pred_row.name, iou_field] = 0\n else:\n self.proposal_GDF.loc[pred_row.name, iou_field] = 0\n if debug:\n print(self.proposal_GDF.loc[pred_row.name])\n\n if self.proposal_GDF.empty:\n TruePos = 0\n FalsePos = 0\n else:\n proposal_GDF_copy = self.proposal_GDF[\n self.proposal_GDF[imageIDField] == imageID].copy(deep=True)\n proposal_GDF_copy = proposal_GDF_copy[\n proposal_GDF_copy.area > min_area]\n if not proposal_GDF_copy.empty:\n if iou_field in proposal_GDF_copy.columns:\n TruePos = proposal_GDF_copy[\n proposal_GDF_copy[iou_field] >= miniou].shape[0]\n FalsePos = proposal_GDF_copy[\n proposal_GDF_copy[iou_field] < miniou].shape[0]\n else:\n print(\"iou field {} missing\".format(iou_field))\n TruePos = 0\n FalsePos = 0\n else:\n print(\"Empty Proposal Id\")\n TruePos = 0\n FalsePos = 0\n\n # false negatives is the number of objects remaining in ground\n # truth after pulling out matched objects\n FalseNeg = self.ground_truth_GDF_Edit[\n self.ground_truth_GDF_Edit.area > 0].shape[0]\n if float(TruePos+FalsePos) > 0:\n Precision = TruePos / float(TruePos + FalsePos)\n else:\n Precision = 0\n if float(TruePos + FalseNeg) > 0:\n Recall = TruePos / float(TruePos + FalseNeg)\n else:\n Recall = 0\n if Recall * Precision > 0:\n F1Score = 2*Precision*Recall/(Precision+Recall)\n else:\n F1Score = 0\n\n score_calc = {'imageID': imageID,\n 'iou_field': iou_field,\n 'TruePos': TruePos,\n 'FalsePos': FalsePos,\n 'FalseNeg': FalseNeg,\n 'Precision': Precision,\n 'Recall': Recall,\n 'F1Score': F1Score\n }\n scoring_dict_list.append(score_calc)\n\n return scoring_dict_list\n\n def eval_iou(self, miniou=0.5, iou_field_prefix='iou_score',\n ground_truth_class_field='', calculate_class_scores=True,\n class_list=['all']):\n \"\"\"Evaluate IoU between the ground truth and proposals.\n\n Arguments\n ---------\n miniou : float, optional\n Minimum intersection over union score to qualify as a successful\n object detection event. Defaults to ``0.5``.\n iou_field_prefix : str, optional\n The name of the IoU score column in ``self.proposal_GDF``. Defaults\n to ``\"iou_score\"``.\n ground_truth_class_field : str, optional\n The column in ``self.ground_truth_GDF`` that indicates the class of\n each polygon. Required if using ``calculate_class_scores``.\n calculate_class_scores : bool, optional\n Should class-by-class scores be calculated? Defaults to ``True``.\n class_list : list, optional\n List of classes to be scored. Defaults to ``['all']`` (score all\n classes).\n\n Returns\n -------\n scoring_dict_list : list\n list of score output dicts for each image in the ground\n truth and evaluated image datasets. The dicts contain\n the following keys: ::\n\n ('class_id', 'iou_field', 'TruePos', 'FalsePos', 'FalseNeg',\n 'Precision', 'Recall', 'F1Score')\n\n \"\"\"\n\n scoring_dict_list = []\n\n if calculate_class_scores:\n if not ground_truth_class_field:\n raise ValueError('Must provide ground_truth_class_field '\n 'if using calculate_class_scores.')\n if class_list == ['all']:\n class_list = list(\n self.ground_truth_GDF[ground_truth_class_field].unique())\n if not self.proposal_GDF.empty:\n class_list.extend(\n list(self.proposal_GDF['__max_conf_class'].unique()))\n class_list = list(set(class_list))\n\n for class_id in class_list:\n iou_field = \"{}_{}\".format(iou_field_prefix, class_id)\n if class_id is not 'all': # this is probably unnecessary now\n self.ground_truth_GDF_Edit = self.ground_truth_GDF[\n self.ground_truth_GDF[\n ground_truth_class_field] == class_id].copy(deep=True)\n else:\n self.ground_truth_GDF_Edit = self.ground_truth_GDF.copy(\n deep=True)\n\n for _, pred_row in tqdm(self.proposal_GDF.iterrows()):\n if pred_row['__max_conf_class'] == class_id \\\n or class_id == 'all':\n pred_poly = pred_row.geometry\n iou_GDF = iou.calculate_iou(pred_poly,\n self.ground_truth_GDF_Edit)\n # Get max iou\n if not iou_GDF.empty:\n max_iou_row = iou_GDF.loc[iou_GDF['iou_score'].idxmax(\n axis=0, skipna=True)]\n if max_iou_row['iou_score'] > miniou:\n self.proposal_GDF.loc[pred_row.name, iou_field] \\\n = max_iou_row['iou_score']\n self.ground_truth_GDF_Edit \\\n = self.ground_truth_GDF_Edit.drop(\n max_iou_row.name, axis=0)\n else:\n self.proposal_GDF.loc[pred_row.name, iou_field] = 0\n else:\n self.proposal_GDF.loc[pred_row.name, iou_field] = 0\n\n if self.proposal_GDF.empty:\n TruePos = 0\n FalsePos = 0\n else:\n try:\n TruePos = self.proposal_GDF[\n self.proposal_GDF[iou_field] >= miniou].shape[0]\n FalsePos = self.proposal_GDF[\n self.proposal_GDF[iou_field] < miniou].shape[0]\n except KeyError: # handle missing iou_field\n print(\"iou field {} missing\")\n TruePos = 0\n FalsePos = 0\n\n # number of remaining rows in ground_truth_gdf_edit after removing\n # matches is number of false negatives\n FalseNeg = self.ground_truth_GDF_Edit.shape[0]\n if float(TruePos+FalsePos) > 0:\n Precision = TruePos / float(TruePos + FalsePos)\n else:\n Precision = 0\n if float(TruePos + FalseNeg) > 0:\n Recall = TruePos / float(TruePos + FalseNeg)\n else:\n Recall = 0\n if Recall*Precision > 0:\n F1Score = 2*Precision*Recall/(Precision+Recall)\n else:\n F1Score = 0\n\n score_calc = {'class_id': class_id,\n 'iou_field': iou_field,\n 'TruePos': TruePos,\n 'FalsePos': FalsePos,\n 'FalseNeg': FalseNeg,\n 'Precision': Precision,\n 'Recall': Recall,\n 'F1Score': F1Score\n }\n scoring_dict_list.append(score_calc)\n\n return scoring_dict_list\n\n def eval_iou_return_GDFs(self, miniou=0.5, iou_field_prefix='iou_score',\n ground_truth_class_field='', calculate_class_scores=True,\n class_list=['all']):\n \"\"\"Evaluate IoU between the ground truth and proposals.\n Arguments\n ---------\n miniou : float, optional\n Minimum intersection over union score to qualify as a successful\n object detection event. Defaults to ``0.5``.\n iou_field_prefix : str, optional\n The name of the IoU score column in ``self.proposal_GDF``. Defaults\n to ``\"iou_score\"``.\n ground_truth_class_field : str, optional\n The column in ``self.ground_truth_GDF`` that indicates the class of\n each polygon. Required if using ``calculate_class_scores``.\n calculate_class_scores : bool, optional\n Should class-by-class scores be calculated? Defaults to ``True``.\n class_list : list, optional\n List of classes to be scored. Defaults to ``['all']`` (score all\n classes).\n Returns\n -------\n scoring_dict_list : list\n list of score output dicts for each image in the ground\n truth and evaluated image datasets. The dicts contain\n the following keys: ::\n ('class_id', 'iou_field', 'TruePos', 'FalsePos', 'FalseNeg',\n 'Precision', 'Recall', 'F1Score')\n True_Pos_gdf : gdf\n A geodataframe containing only true positive predictions\n False_Neg_gdf : gdf\n A geodataframe containing only false negative predictions\n False_Pos_gdf : gdf\n A geodataframe containing only false positive predictions\n \"\"\"\n\n scoring_dict_list = []\n\n if calculate_class_scores:\n if not ground_truth_class_field:\n raise ValueError('Must provide ground_truth_class_field if using calculate_class_scores.')\n if class_list == ['all']:\n class_list = list(\n self.ground_truth_GDF[ground_truth_class_field].unique())\n if not self.proposal_GDF.empty:\n class_list.extend(\n list(self.proposal_GDF['__max_conf_class'].unique()))\n class_list = list(set(class_list))\n\n for class_id in class_list:\n iou_field = \"{}_{}\".format(iou_field_prefix, class_id)\n if class_id is not 'all': # this is probably unnecessary now\n self.ground_truth_GDF_Edit = self.ground_truth_GDF[\n self.ground_truth_GDF[\n ground_truth_class_field] == class_id].copy(deep=True)\n else:\n self.ground_truth_GDF_Edit = self.ground_truth_GDF.copy(\n deep=True)\n\n for _, pred_row in tqdm(self.proposal_GDF.iterrows()):\n if pred_row['__max_conf_class'] == class_id or class_id == 'all':\n pred_poly = pred_row.geometry\n iou_GDF = iou.calculate_iou(pred_poly,\n self.ground_truth_GDF_Edit)\n # Get max iou\n if not iou_GDF.empty:\n max_iou_row = iou_GDF.loc[iou_GDF['iou_score'].idxmax(\n axis=0, skipna=True)]\n if max_iou_row['iou_score'] > miniou:\n self.proposal_GDF.loc[pred_row.name, iou_field] = max_iou_row['iou_score']\n self.ground_truth_GDF_Edit = self.ground_truth_GDF_Edit.drop(max_iou_row.name, axis=0)\n else:\n self.proposal_GDF.loc[pred_row.name, iou_field] = 0\n else:\n self.proposal_GDF.loc[pred_row.name, iou_field] = 0\n\n if self.proposal_GDF.empty:\n TruePos = 0\n FalsePos = 0\n else:\n try:\n True_Pos_gdf = self.proposal_GDF[\n self.proposal_GDF[iou_field] >= miniou]\n TruePos = True_Pos_gdf.shape[0]\n if TruePos == 0:\n True_Pos_gdf = None\n False_Pos_gdf = self.proposal_GDF[\n self.proposal_GDF[iou_field] < miniou]\n FalsePos = False_Pos_gdf.shape[0]\n if FalsePos == 0:\n False_Pos_gdf = None\n except KeyError: # handle missing iou_field\n print(\"iou field {} missing\")\n TruePos = 0\n FalsePos = 0\n False_Pos_gdf = None\n True_Pos_gdf = None\n\n # number of remaining rows in ground_truth_gdf_edit after removing\n # matches is number of false negatives\n False_Neg_gdf = self.ground_truth_GDF_Edit\n FalseNeg = False_Neg_gdf.shape[0]\n if FalseNeg == 0:\n False_Neg_gdf = None\n if float(TruePos + FalsePos) > 0:\n Precision = TruePos / float(TruePos + FalsePos)\n else:\n Precision = 0\n if float(TruePos + FalseNeg) > 0:\n Recall = TruePos / float(TruePos + FalseNeg)\n else:\n Recall = 0\n if Recall * Precision > 0:\n F1Score = 2 * Precision * Recall / (Precision + Recall)\n else:\n F1Score = 0\n\n score_calc = {'class_id': class_id,\n 'iou_field': iou_field,\n 'TruePos': TruePos,\n 'FalsePos': FalsePos,\n 'FalseNeg': FalseNeg,\n 'Precision': Precision,\n 'Recall': Recall,\n 'F1Score': F1Score\n }\n scoring_dict_list.append(score_calc)\n\n return scoring_dict_list, True_Pos_gdf, False_Neg_gdf, False_Pos_gdf\n\n def load_proposal(self, proposal_vector_file, conf_field_list=['conf'],\n proposalCSV=False, pred_row_geo_value='PolygonWKT_Pix',\n conf_field_mapping=None):\n \"\"\"Load in a proposal geojson or CSV.\n\n Arguments\n ---------\n proposal_vector_file : str\n Path to the file containing proposal vector objects. This can be\n a .geojson or a .csv.\n conf_field_list : list, optional\n List of columns corresponding to confidence value(s) in the\n proposal vector file. Defaults to ``['conf']``.\n proposalCSV : bool, optional\n Is the proposal file a CSV? Defaults to no (``False``), in which\n case it's assumed to be a .geojson.\n pred_row_geo_value : str, optional\n The name of the geometry-containing column in the proposal vector\n file. Defaults to ``'PolygonWKT_Pix'``. Note: this method assumes\n the geometry is in WKT format.\n conf_field_mapping : dict, optional\n ``'__max_conf_class'`` column value:class ID mapping dict for\n multiclass use. Only required in multiclass cases.\n\n Returns\n -------\n ``0`` upon successful completion.\n\n Notes\n -----\n Loads in a .geojson or .csv-formatted file of proposal polygons for\n comparison to the ground truth and stores it as part of the\n ``Evaluator`` instance. This method assumes the geometry contained in\n the proposal file is in WKT format.\n\n \"\"\"\n\n # Load Proposal if proposal_vector_file is a path to a file\n if os.path.isfile(proposal_vector_file):\n # if it's a CSV format, first read into a pd df and then convert\n # to gpd gdf by loading in geometries using shapely\n if proposalCSV:\n pred_data = pd.read_csv(proposal_vector_file)\n self.proposal_GDF = gpd.GeoDataFrame(\n pred_data, geometry=[\n shapely.wkt.loads(pred_row[pred_row_geo_value])\n for idx, pred_row in pred_data.iterrows()\n ]\n )\n else: # if it's a .geojson\n try:\n self.proposal_GDF = gpd.read_file(\n proposal_vector_file).dropna()\n except (CPLE_OpenFailedError, DriverError):\n self.proposal_GDF = gpd.GeoDataFrame(geometry=[])\n\n if conf_field_list:\n self.proposal_GDF['__total_conf'] = self.proposal_GDF[\n conf_field_list].max(axis=1)\n self.proposal_GDF['__max_conf_class'] = self.proposal_GDF[\n conf_field_list].idxmax(axis=1)\n else:\n # set arbitrary (meaningless) values otherwise\n self.proposal_GDF['__total_conf'] = 1.0\n self.proposal_GDF['__max_conf_class'] = 1\n\n if conf_field_mapping is not None:\n self.proposal_GDF['__max_conf_class'] = [\n conf_field_mapping[item] for item in\n self.proposal_GDF['__max_conf_class'].values]\n self.proposal_GDF = self.proposal_GDF.sort_values(\n by='__total_conf', ascending=False)\n else:\n self.proposal_GDF = gpd.GeoDataFrame(geometry=[])\n\n def load_truth(self, ground_truth_vector_file, truthCSV=False,\n truth_geo_value='PolygonWKT_Pix'):\n \"\"\"Load in the ground truth geometry data.\n\n Arguments\n ---------\n ground_truth_vector_file : str\n Path to the ground truth vector file. Must be either .geojson or\n .csv format.\n truthCSV : bool, optional\n Is the ground truth a CSV? Defaults to ``False``, in which case\n it's assumed to be a .geojson.\n truth_geo_value : str, optional\n Column of the ground truth vector file that corresponds to\n geometry.\n\n Returns\n -------\n Nothing.\n\n Notes\n -----\n Loads the ground truth vector data into the ``Evaluator`` instance.\n\n \"\"\"\n if truthCSV:\n truth_data = pd.read_csv(ground_truth_vector_file)\n self.ground_truth_GDF = gpd.GeoDataFrame(\n truth_data, geometry=[\n shapely.wkt.loads(truth_row[truth_geo_value])\n for idx, truth_row in truth_data.iterrows()])\n else:\n try:\n self.ground_truth_GDF = gpd.read_file(ground_truth_vector_file)\n except (CPLE_OpenFailedError, DriverError): # empty geojson\n self.ground_truth_GDF = gpd.GeoDataFrame({'sindex': [],\n 'condition': [],\n 'geometry': []})\n # force calculation of spatialindex\n self.ground_truth_sindex = self.ground_truth_GDF.sindex\n # create deep copy of ground truth file for calculations\n self.ground_truth_GDF_Edit = self.ground_truth_GDF.copy(deep=True)\n\n def eval(self, type='iou'):\n pass\n\n\ndef eval_base(ground_truth_vector_file, csvFile=False,\n truth_geo_value='PolygonWKT_Pix'):\n \"\"\"Deprecated API to Evaluator.\n\n .. deprecated:: 0.3\n Use :class:`Evaluator` instead.\"\"\"\n\n return Evaluator(ground_truth_vector_file)\n"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
sarang-IITKgp/scikit-microwave-design | [
"a8567c2d40eebde93af5989c43d6e3008167e137"
] | [
"src/skmd/network.py"
] | [
"\"\"\"Module containing the basic Microwave netwrok object\"\"\"\n\nimport numpy as np\n\nclass Network:\n\tdef __init__(self, p11, p12, p21, p22, parameter='abcd',Z0=50,omega=None):\n\t\t\"\"\"For conversion from ABCD <-> S, it is assumed that the network has equal and real characteristic impedance on both the ports.\"\"\"\n\t\t#self.Z01 = Z01 # Terminating impedance at port-1 for conversion [ABCD] <-> [S]. \n\t\t#self.Z02 = Z02 # Terminating impedance at port-2 for conversion [ABCD] <-> [S]. \n\t\tself.Z0 = Z0\n\t\tself.omega = omega\n\t\tif self.omega is not None:\n\t\t\tself.freq = omega/(2*np.pi)\n\t\telse :\n\t\t\tself.freq = None\n\t\t\n\t\t\t\n\t\tif parameter == 's' or parameter == 'S':\n\t\t\t\n\t\t\tself.S11 = p11\n\t\t\tself.S12 = p12\n\t\t\tself.S21 = p21\n\t\t\tself.S22 = p22\n\t\t\t\n\t\t\tself.S_to_ABCD()\n\t\t\t#print('S defined')\n\t\t\n\t\tif parameter == 'abcd' or parameter == 'ABCD':\n\t\t\t\n\t\t\tself.A = p11\n\t\t\tself.B = p12\n\t\t\tself.C = p21\n\t\t\tself.D = p22\n\t\t\t\n\t\t\t\n\t\t\tself.ABCD_to_S()\n\t\t\t#print('ABCD defined')\n\t\t\n\tdef ABCD_to_S(self,):\n\t\tself.S11 = (self.A + self.B/self.Z0 - self.C*self.Z0 - self.D)/(self.A + self.B/self.Z0 + self.C*self.Z0 + self.D)\n\t\tself.S12 = 2*(self.A*self.D - self.B*self.C)/(self.A + self.B/self.Z0 + self.C*self.Z0 + self.D)\n\t\tself.S21 = 2/(self.A + self.B/self.Z0 + self.C*self.Z0 + self.D)\n\t\tself.S22 = (-self.A + self.B/self.Z0 - self.C*self.Z0 + self.D)/(self.A + self.B/self.Z0 + self.C*self.Z0 + self.D)\n\t\t#print('computed ABCD to S')\n\t\t\n\tdef S_to_ABCD(self,):\n\t\tself.A = ((1+self.S11)*(1-self.S22) + self.S12*self.S21)/(2*self.S21)\n\t\tself.B = self.Z0* ((1+self.S11)*(1+self.S22) - self.S12*self.S21)/(2*self.S21)\n\t\tself.C = (1/self.Z0)*((1-self.S11)*(1-self.S22) - self.S12*self.S21)/(2*self.S21)\n\t\tself.D = \t\t((1-self.S11)*(1+self.S22) + self.S12*self.S21)/(2*self.S21)\n\t\t#print('computed S to ABCD')\n\t\t\n\tdef input_admittance(self,YL):\n\t\t\"\"\"Returns the input admittance of a network at port-1, when Port-2 \n\t\tis terminated by YL\n\t\t\t\t\t _______________\n\t\t\t\t\t|\t\t\t\t|\n\t\to-----------|---------------|-----------o\n\t\t\t \t\t|\t\t\t\t|\t\t _|__\n\t\t\t |-->\t|\t[ABCD]\t\t|\t\t |_YL_|\n\t\t\tYin\t\t|\t\t\t\t|\t\t\t|\n\t\to-----------|---------------|-----------o\n\t\t\t\t\t|_______________|\n\t\tYL should be of the same dimensions as A,B,C,D. Or YL can be a scalar.\n\t\t\"\"\"\n\t\tYin = (self.C+self.D*YL)/(self.A+self.B*YL)\n\t\treturn Yin\n\t\n\tdef input_impedance(self,ZL):\n\t\t\n\t\t\"\"\"Returns the input impedance of a network at port-1, when Port-2 \n\t\tis terminated by ZL\n\t\t\t\t\t _______________\n\t\t\t\t\t|\t\t\t\t|\n\t\to-----------|---------------|-----------o\n\t\t\t \t\t|\t\t\t\t|\t\t _|__\n\t\t\t |-->\t|\t[ABCD]\t\t|\t\t |_ZL_|\n\t\t\tZin\t\t|\t\t\t\t|\t\t\t|\n\t\to-----------|---------------|-----------o\n\t\t\t\t\t|_______________|\n\t\tZL should be of the same dimensions as A,B,C,D. Or ZL can be scalar. \n\t\t\"\"\"\n\t\tZin = (self.A*ZL + self.B)/(self.C*ZL + self.D)\n\t\treturn Zin\n\t\t\n\tdef input_reflection(self,ZL,Z0=50):\n\t\t\"\"\"Returns the reflection coefficient of a network at port-1, when Port-2 \n\t\tis terminated by ZL. The characteristic impedance of the input line Z0. By defalut Z0 is assumed to be 50 Ohm. \n\t\t\t\t\t _______________\n\t\t\t\t\t|\t\t\t\t|\n\t\to-----------|---------------|-----------o\n\t\t\t \t\t|\t\t\t\t|\t\t _|__\n\t\tZ0\t |-->\t|\t[ABCD]\t\t|\t\t |_ZL_|\n\t\t\tS11\t\t|\t\t\t\t|\t\t\t|\n\t\to-----------|---------------|-----------o\n\t\t\t\t\t|_______________|\n\t\tZL should be of the same dimensions as A,B,C,D. Or ZL can be scalar. \n\t\t\"\"\"\n\t\tZin = (self.A*ZL + self.B)/(self.C*ZL + self.D)\n\t\t\n\t\tS11 = (Zin-Z0)/(Zin+Z0)\n\t\t\n\t\treturn S11\n\t\t\n\t\t\n\tdef __mul__(self, other):\n\t\t\n\t\tA1 = self.A\n\t\tA2 = other.A\n\t\tB1 = self.B\n\t\tB2 = other.B\n\t\tC1 = self.C\n\t\tC2 = other.C\n\t\tD1 = self.D\n\t\tD2 = other.D\n\t\t\n\t\t\n\t\tA = A1*A2 + B1*C2\n\t\tB = A1*B2 + B1*D2\n\t\tC = C1*A2 + D1*C2\n\t\tD = C1*B2 + D1*D2\n\t\treturn Network(A,B,C,D,parameter='abcd',omega=self.omega)\n \n \n\tdef __pow__(self,N):\n\t\t\n\t\tNW_cascade = self\n\t\tfor itr in range(N-1):\n\t\t\tNW_cascade = NW_cascade*self\n\t\treturn NW_cascade\n\t\t\n\tdef __rshift__(self,other):\n\t\t\"\"\"De-embedding from left.\n\t\tNW1>>NW2. 'other' is NW2.\n\t\tReturns a network with [ABCD1]^-1 * [ABCD2]\"\"\"\n\t\tA1 = self.A\n\t\tA2 = other.A\n\t\t\n\t\tB1 = self.B\n\t\tB2 = other.B\n\t\t\n\t\tC1 = self.C\n\t\tC2 = other.C\n\t\t\n\t\tD1 = self.D\n\t\tD2 = other.D\n\t\t\n\t\tDelta_1 = A1*D1 - B1*C1\n\t\t\n\t\tA = ( D1*A2 - B1*C2)/Delta_1\n\t\tB = ( D1*B2 - B1*D2)/Delta_1\n\t\tC = (-C1*A2 + A1*C2)/Delta_1\n\t\tD = (-C1*B2 + A1*D2)/Delta_1\n\t\t\t\t\n\t\treturn Network(A,B,C,D,parameter='abcd',omega=self.omega)\n\t\n\tdef __lshift__(self,other):\n\t\t\"\"\"De-embedding from right.\n\t\tNW1<<NW2. 'other' is NW2.\n\t\tReturns a network with [ABCD1] * [ABCD2]^-1\"\"\"\n\t\tA1 = self.A\n\t\tA2 = other.A\n\t\t\n\t\tB1 = self.B\n\t\tB2 = other.B\n\t\t\n\t\tC1 = self.C\n\t\tC2 = other.C\n\t\t\n\t\tD1 = self.D\n\t\tD2 = other.D\n\t\t\n\t\tDelta_2 = A2*D2 - B2*C2\n\t\t\n\t\tA = ( A1*D2 - B1*C2)/Delta_2\n\t\tB = (-A1*B2 + B1*A2)/Delta_2\n\t\tC = ( C1*D2 - D1*C2)/Delta_2\n\t\tD = (-C1*B2 + D1*A2)/Delta_2\n\t\t\n\t\t\t\t\n\t\treturn Network(A,B,C,D,parameter='abcd',omega=self.omega)\n\t# End class Network:\n\t\n\t\n\ndef from_Tx_line(l,Z0,gamma,omega=None):\n\t\"\"\"This function takes the following input paramters,\n\tl = length of the transmission line. Should be a scalar.\n\tZ0 = Characteristics impedance of the transmission line. Should be a scalar or an array of the same dimensions as beta.\n\tgamma = propagation constant of the transmission line. Should be the an array of the same dimensions as omega.\n\t--------------------------------------------------------------------\n\tThe function returns the ABCD parameters of a transmission line section of length l.\n\t\n\t\n\to--------------------------------------o\n\t\t\tZ0, \\gamma = \\alpha + j\\beta\n\to--------------------------------------o\n\t|<-------------- l ------------------->|\n\t\n\tBased on equations on Page-185, 'Microwave engineering' by D. M. Pozar\n\t\"\"\"\n\t\n\tA = np.cosh(gamma*l)\n\tB = Z0*np.sinh(gamma*l)\n\tC = (1/Z0)*np.sinh(gamma*l) \n\tD = np.cosh(gamma*l)\n\treturn Network(A, B, C, D,parameter='abcd',omega=omega)\n\n\ndef from_series_Z(Z,omega=None):\n\t\"\"\" Returns a network object for the following\n\to-----------------|Z|--------------------o\n\t\t\t\t\t[ABCD]\n\to----------------------------------------o\n\tBased on equations on Page-185, 'Microwave engineering' by D. M. Pozar\n\t\"\"\"\n\tA = np.ones_like(Z)\n\tB = Z\n\tC = np.zeros_like(Z)\n\tD = np.ones_like(Z)\n\treturn Network(A, B, C, D,parameter='abcd',omega=omega)\n\t\n\ndef from_shunt_Y(Y,omega=None):\n\t\"\"\" Returns a network object for the following\n\to--------------------------------------o\n\t\t\t\t\t _|_\n\t\t\t\t\t |_Y_|\n\t\t\t\t\t\t|\n\to--------------------------------------o\n\tBased on equations on Page-185, 'Microwave engineering' by D. M. Pozar\n\t\"\"\"\n\tA = np.ones_like(Y)\n\tB = np.zeros_like(Y)\n\tC = Y\n\tD = np.ones_like(Y)\n\treturn Network(A, B, C, D,parameter='abcd',omega=omega)\n\n\ndef from_PI_Y(Y1,Y2,Y3,omega=None):\n\t\"\"\" Returns a network object for the following\n\t\t\t\t\t ____\n\to----------------|_Y3_|---------------------o\n\t\t\t _|__ _|__\n\t\t\t |_Y1_| |_Y2_|\n\t\t\t\t| \t\t\t |\n\to-------------------------------------------o\n\tBased on equations on Page-185, 'Microwave engineering' by D. M. Pozar\n\t\"\"\"\n\tA = 1 + Y2/Y3\n\tB = 1/Y3\n\tC = Y1 + Y2 + Y1*Y2/Y3\n\tD = 1 + Y1/Y3\n\treturn Network(A, B, C, D,parameter='abcd',omega=omega)\n\n\ndef from_T_Z(Z1,Z2,Z3,omega=None):\n\t\"\"\" Returns a network object for the following\n\t\t\t\t____\t\t\t____\n\to----------|_Z1_|----------|_Z2_|-------o\n\t\t\t\t\t\t_|__ \n\t\t\t\t\t |_Z3_| \n\t\t\t\t\t\t | \n\to--------------------------------------o\n\tBased on equations on Page-185, 'Microwave engineering' by D. M. Pozar\n\t\"\"\"\n\tA = 1 + Z1/Z3\n\tB = Z1 + Z2 + Z1*Z2/Z3\n\tC = 1/Z3\n\tD = 1 + Z2/Z3\n\treturn Network(A, B, C, D,parameter='abcd',omega=omega)\n\n#def Tx_line_par_to_Z0_gamma(R,G,L,C,omega):\n\t#\"\"\"Computes the characteristic impedance and propagation constant gamma = alpha + j beta\n\t#Input:-\n\t#R := Series resistance per unit length\n\t#G := Shunt resistance per unit length\n\t#L := Series inductance per unit length\n\t#C := Shunt capacitance per unit length\n\t#omega := Frequency in radians per second \n\t#-----------------------------------------\n\t#Output:-\n\t#Z0 := Characteristic impedance\n\t#gamma := Propagation constant\n\t#\"\"\"\n\t#Z0 = np.sqrt((R+1j*omega*L )/(G+1j*omega*C)) \n\t#gamma = np.sqrt((R+1j*omega*L )*(G+1j*omega*C))\n\t#return Z0, gamma\n\n"
] | [
[
"numpy.zeros_like",
"numpy.ones_like",
"numpy.cosh",
"numpy.sinh"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NavpreetDevpuri/Python | [
"04f156a8973d6156a4357e0717d9eb0aa264d086"
] | [
"neural_network/2_hidden_layers_neural_network.py"
] | [
"\"\"\"\nReferences:\n - http://neuralnetworksanddeeplearning.com/chap2.html (Backpropagation)\n - https://en.wikipedia.org/wiki/Sigmoid_function (Sigmoid activation function)\n - https://en.wikipedia.org/wiki/Feedforward_neural_network (Feedforward)\n\"\"\"\n\nimport numpy\n\n\nclass TwoHiddenLayerNeuralNetwork:\n def __init__(self, input_array: numpy.ndarray, output_array: numpy.ndarray) -> None:\n \"\"\"\n This function initializes the TwoHiddenLayerNeuralNetwork class with random\n weights for every layer and initializes predicted output with zeroes.\n\n input_array : input values for training the neural network (i.e training data) .\n output_array : expected output values of the given inputs.\n \"\"\"\n\n # Input values provided for training the model.\n self.input_array = input_array\n\n # Random initial weights are assigned where first argument is the\n # number of nodes in previous layer and second argument is the\n # number of nodes in the next layer.\n\n # Random initial weights are assigned.\n # self.input_array.shape[1] is used to represent number of nodes in input layer.\n # First hidden layer consists of 4 nodes.\n self.input_layer_and_first_hidden_layer_weights = numpy.random.rand(\n self.input_array.shape[1], 4\n )\n\n # Random initial values for the first hidden layer.\n # First hidden layer has 4 nodes.\n # Second hidden layer has 3 nodes.\n self.first_hidden_layer_and_second_hidden_layer_weights = numpy.random.rand(\n 4, 3\n )\n\n # Random initial values for the second hidden layer.\n # Second hidden layer has 3 nodes.\n # Output layer has 1 node.\n self.second_hidden_layer_and_output_layer_weights = numpy.random.rand(3, 1)\n\n # Real output values provided.\n self.output_array = output_array\n\n # Predicted output values by the neural network.\n # Predicted_output array initially consists of zeroes.\n self.predicted_output = numpy.zeros(output_array.shape)\n\n def feedforward(self) -> numpy.ndarray:\n \"\"\"\n The information moves in only one direction i.e. forward from the input nodes,\n through the two hidden nodes and to the output nodes.\n There are no cycles or loops in the network.\n\n Return layer_between_second_hidden_layer_and_output\n (i.e the last layer of the neural network).\n\n >>> input_val = numpy.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=float)\n >>> output_val = numpy.array(([0], [0], [0]), dtype=float)\n >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val)\n >>> res = nn.feedforward()\n >>> array_sum = numpy.sum(res)\n >>> numpy.isnan(array_sum)\n False\n \"\"\"\n # Layer_between_input_and_first_hidden_layer is the layer connecting the\n # input nodes with the first hidden layer nodes.\n self.layer_between_input_and_first_hidden_layer = sigmoid(\n numpy.dot(self.input_array, self.input_layer_and_first_hidden_layer_weights)\n )\n\n # layer_between_first_hidden_layer_and_second_hidden_layer is the layer\n # connecting the first hidden set of nodes with the second hidden set of nodes.\n self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid(\n numpy.dot(\n self.layer_between_input_and_first_hidden_layer,\n self.first_hidden_layer_and_second_hidden_layer_weights,\n )\n )\n\n # layer_between_second_hidden_layer_and_output is the layer connecting\n # second hidden layer with the output node.\n self.layer_between_second_hidden_layer_and_output = sigmoid(\n numpy.dot(\n self.layer_between_first_hidden_layer_and_second_hidden_layer,\n self.second_hidden_layer_and_output_layer_weights,\n )\n )\n\n return self.layer_between_second_hidden_layer_and_output\n\n def back_propagation(self) -> None:\n \"\"\"\n Function for fine-tuning the weights of the neural net based on the\n error rate obtained in the previous epoch (i.e., iteration).\n Updation is done using derivative of sogmoid activation function.\n\n >>> input_val = numpy.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=float)\n >>> output_val = numpy.array(([0], [0], [0]), dtype=float)\n >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val)\n >>> res = nn.feedforward()\n >>> nn.back_propagation()\n >>> updated_weights = nn.second_hidden_layer_and_output_layer_weights\n >>> (res == updated_weights).all()\n False\n \"\"\"\n\n updated_second_hidden_layer_and_output_layer_weights = numpy.dot(\n self.layer_between_first_hidden_layer_and_second_hidden_layer.T,\n 2\n * (self.output_array - self.predicted_output)\n * sigmoid_derivative(self.predicted_output),\n )\n updated_first_hidden_layer_and_second_hidden_layer_weights = numpy.dot(\n self.layer_between_input_and_first_hidden_layer.T,\n numpy.dot(\n 2\n * (self.output_array - self.predicted_output)\n * sigmoid_derivative(self.predicted_output),\n self.second_hidden_layer_and_output_layer_weights.T,\n )\n * sigmoid_derivative(\n self.layer_between_first_hidden_layer_and_second_hidden_layer\n ),\n )\n updated_input_layer_and_first_hidden_layer_weights = numpy.dot(\n self.input_array.T,\n numpy.dot(\n numpy.dot(\n 2\n * (self.output_array - self.predicted_output)\n * sigmoid_derivative(self.predicted_output),\n self.second_hidden_layer_and_output_layer_weights.T,\n )\n * sigmoid_derivative(\n self.layer_between_first_hidden_layer_and_second_hidden_layer\n ),\n self.first_hidden_layer_and_second_hidden_layer_weights.T,\n )\n * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer),\n )\n\n self.input_layer_and_first_hidden_layer_weights += (\n updated_input_layer_and_first_hidden_layer_weights\n )\n self.first_hidden_layer_and_second_hidden_layer_weights += (\n updated_first_hidden_layer_and_second_hidden_layer_weights\n )\n self.second_hidden_layer_and_output_layer_weights += (\n updated_second_hidden_layer_and_output_layer_weights\n )\n\n def train(self, output: numpy.ndarray, iterations: int, give_loss: bool) -> None:\n \"\"\"\n Performs the feedforwarding and back propagation process for the\n given number of iterations.\n Every iteration will update the weights of neural network.\n\n output : real output values,required for calculating loss.\n iterations : number of times the weights are to be updated.\n give_loss : boolean value, If True then prints loss for each iteration,\n If False then nothing is printed\n\n >>> input_val = numpy.array(([0, 0, 0], [0, 1, 0], [0, 0, 1]), dtype=float)\n >>> output_val = numpy.array(([0], [1], [1]), dtype=float)\n >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val)\n >>> first_iteration_weights = nn.feedforward()\n >>> nn.back_propagation()\n >>> updated_weights = nn.second_hidden_layer_and_output_layer_weights\n >>> (first_iteration_weights == updated_weights).all()\n False\n \"\"\"\n for iteration in range(1, iterations + 1):\n self.output = self.feedforward()\n self.back_propagation()\n if give_loss:\n loss = numpy.mean(numpy.square(output - self.feedforward()))\n print(f\"Iteration {iteration} Loss: {loss}\")\n\n def predict(self, input: numpy.ndarray) -> int:\n \"\"\"\n Predict's the output for the given input values using\n the trained neural network.\n\n The output value given by the model ranges in-between 0 and 1.\n The predict function returns 1 if the model value is greater\n than the threshold value else returns 0,\n as the real output values are in binary.\n\n >>> input_val = numpy.array(([0, 0, 0], [0, 1, 0], [0, 0, 1]), dtype=float)\n >>> output_val = numpy.array(([0], [1], [1]), dtype=float)\n >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val)\n >>> nn.train(output_val, 1000, False)\n >>> nn.predict([0,1,0]) in (0, 1)\n True\n \"\"\"\n\n # Input values for which the predictions are to be made.\n self.array = input\n\n self.layer_between_input_and_first_hidden_layer = sigmoid(\n numpy.dot(self.array, self.input_layer_and_first_hidden_layer_weights)\n )\n\n self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid(\n numpy.dot(\n self.layer_between_input_and_first_hidden_layer,\n self.first_hidden_layer_and_second_hidden_layer_weights,\n )\n )\n\n self.layer_between_second_hidden_layer_and_output = sigmoid(\n numpy.dot(\n self.layer_between_first_hidden_layer_and_second_hidden_layer,\n self.second_hidden_layer_and_output_layer_weights,\n )\n )\n\n return int(self.layer_between_second_hidden_layer_and_output > 0.6)\n\n\ndef sigmoid(value: numpy.ndarray) -> numpy.ndarray:\n \"\"\"\n Applies sigmoid activation function.\n\n return normalized values\n\n >>> sigmoid(numpy.array(([1, 0, 2], [1, 0, 0]), dtype=numpy.float64))\n array([[0.73105858, 0.5 , 0.88079708],\n [0.73105858, 0.5 , 0.5 ]])\n \"\"\"\n return 1 / (1 + numpy.exp(-value))\n\n\ndef sigmoid_derivative(value: numpy.ndarray) -> numpy.ndarray:\n \"\"\"\n Provides the derivative value of the sigmoid function.\n\n returns derivative of the sigmoid value\n\n >>> sigmoid_derivative(numpy.array(([1, 0, 2], [1, 0, 0]), dtype=numpy.float64))\n array([[ 0., 0., -2.],\n [ 0., 0., 0.]])\n \"\"\"\n return (value) * (1 - (value))\n\n\ndef example() -> int:\n \"\"\"\n Example for \"how to use the neural network class and use the\n respected methods for the desired output\".\n Calls the TwoHiddenLayerNeuralNetwork class and\n provides the fixed input output values to the model.\n Model is trained for a fixed amount of iterations then the predict method is called.\n In this example the output is divided into 2 classes i.e. binary classification,\n the two classes are represented by '0' and '1'.\n\n >>> example() in (0, 1)\n True\n \"\"\"\n # Input values.\n input = numpy.array(\n (\n [0, 0, 0],\n [0, 0, 1],\n [0, 1, 0],\n [0, 1, 1],\n [1, 0, 0],\n [1, 0, 1],\n [1, 1, 0],\n [1, 1, 1],\n ),\n dtype=numpy.float64,\n )\n\n # True output values for the given input values.\n output = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=numpy.float64)\n\n # Calling neural network class.\n neural_network = TwoHiddenLayerNeuralNetwork(input_array=input, output_array=output)\n\n # Calling training function.\n # Set give_loss to True if you want to see loss in every iteration.\n neural_network.train(output=output, iterations=10, give_loss=False)\n\n return neural_network.predict(numpy.array(([1, 1, 1]), dtype=numpy.float64))\n\n\nif __name__ == \"__main__\":\n example()\n"
] | [
[
"numpy.dot",
"numpy.random.rand",
"numpy.array",
"numpy.exp",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method | [
"ac0a27e31d64edc8ae8912b6ed10005029868c90"
] | [
"src/visualization/visualize.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef plot_area(results,interesting_ = ['B_W_hat','B_F_hat','B_E_hat','B_L_hat'], ax=None):\n \"\"\"Plot area with annotations\n\n Parameters\n ----------\n results : [type]\n [description]\n interesting_ : list, optional\n [description], by default ['B_W_hat','B_F_hat','B_E_hat','B_L_hat']\n ax : [type], optional\n [description], by default None\n\n Returns\n -------\n [type]\n axes\n \"\"\"\n \n if ax is None:\n fig,ax=plt.subplots()\n \n results.plot.area(y=interesting_, ax=ax)\n \n ## Fancy annotation:\n xs = []\n for component_ in interesting_:\n values=results[component_]\n \n A = np.trapz(values, x=results.index)\n xA = np.trapz(values*results.index, x=results.index)\n \n x = xA/A\n xs.append(x)\n \n ys = []\n y=0\n \n for x,component_ in zip(xs,interesting_):\n values=results[component_]\n \n dy = np.interp(x, values.index, values)/2\n y+=dy\n ys.append(y)\n y+=dy\n \n \n for x,y,component_ in zip(xs,ys,interesting_):\n values=results[component_]\n \n ax.annotate('%s' % component_, xy=(x,y))\n \n values_old = values\n \n return ax"
] | [
[
"numpy.trapz",
"numpy.interp",
"matplotlib.pyplot.subplots"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sourav-roni/multiphenotype_methods | [
"f93863f5b457e9816951830fcc12d804ec9f4588"
] | [
"ds/sparse_variational_age_autoencoder.py"
] | [
"import numpy as np\nfrom multiphenotype_utils import (get_continuous_features_as_matrix, add_id, remove_id_and_get_mat, \n partition_dataframe_into_binary_and_continuous, divide_idxs_into_batches)\nimport pandas as pd\nimport tensorflow as tf\nfrom dimreducer import DimReducer\n\nfrom general_autoencoder import GeneralAutoencoder\nfrom standard_autoencoder import StandardAutoencoder\nfrom variational_autoencoder import VariationalAutoencoder\nfrom variational_age_autoencoder import VariationalAgeAutoencoder\n\n\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior() \n\nclass SparseVariationalAgeAutoencoder(VariationalAgeAutoencoder):\n \"\"\"\n Implements a variational autoencoder with an age prior and sparsity.\n \"\"\" \n def __init__(self,\n k_age,\n Z_age_coef,\n sparsity_weighting = .1,\n **kwargs):\n\n super(SparseVariationalAgeAutoencoder, self).__init__(k_age = k_age, \n Z_age_coef = Z_age_coef, \n **kwargs) \n # Does not include input_dim, but includes last hidden layer\n # self.encoder_layer_sizes = encoder_layer_sizes\n\n self.k_age = k_age\n self.Z_age_coef = Z_age_coef\n assert self.k >= self.k_age\n self.need_ages = True\n\n self.sparsity_weighting = sparsity_weighting\n \n # assert we only have a single decoder layer (otherwise the sparsity loss doesn't make sense). \n #assert(len([layer_name for layer_name in self.weights if 'decoder' in layer_name]) == 1)\n \n def get_regularization_loss(self, ages, Z_mu, Z_sigma):\n \"\"\"\n Uses self.X, self.Xr, self.Z_sigma, self.Z_mu, self.kl_weighting\n \"\"\"\n kl_div_loss = super(SparseVariationalAgeAutoencoder, self).get_regularization_loss(ages, Z_mu, Z_sigma)\n \n decoder_layer_number = 0\n layer_name = 'decoder_h%i' % decoder_layer_number\n while layer_name in self.weights:\n print('adding sparsity loss to decoder layer ' + layer_name)\n if decoder_layer_number == 0:\n combined_weight_matrix = tf.abs(self.weights[layer_name])\n else:\n combined_weight_matrix = tf.matmul(combined_weight_matrix, tf.abs(self.weights[layer_name]))\n decoder_layer_number += 1\n layer_name = 'decoder_h%i' % decoder_layer_number\n \n sparsity_loss = tf.reduce_sum(tf.abs(combined_weight_matrix))\n regularization_loss = kl_div_loss + sparsity_loss * self.sparsity_weighting\n\n return regularization_loss\n"
] | [
[
"tensorflow.compat.v1.abs",
"tensorflow.compat.v1.disable_v2_behavior"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zld126126/MyPython | [
"960a75d6e3d5049ab0cba6f4c682845cdb96c341"
] | [
"my_tensorflow/my_tensorflow.py"
] | [
"# -*- coding: UTF-8 -*-\nimport tensorflow as tf\n\n# 当直接运行包含main函数的程序时,main函数才会被执行\ndef main():\n print(\"你好!我是一个TensorFlow示例...\")\nif __name__ == '__main__':\n main() \n\n# 定义一个随机数(标量)\nrandom_float = tf.random.uniform(shape=())\n\n# 定义一个有2个元素的零向量\nzero_vector = tf.zeros(shape=(2))\n\n# 定义两个2×2的常量矩阵\nA = tf.constant([[1., 2.], [3., 4.]])\nB = tf.constant([[5., 6.], [7., 8.]])\n\n# 查看矩阵A的形状、类型和值\nprint(\"A.shape:\", A.shape) # 输出(2, 2),即矩阵的长和宽均为2\nprint(\"A.dtype:\", A.dtype) # 输出<dtype: 'float32'>\nprint(\"A.numpy:\", A.numpy()) # 输出[[1. 2.]#[3. 4.]]\n\nC = tf.add(A, B) # 计算矩阵A和B的和\nD = tf.matmul(A, B) # 计算矩阵A和B的乘积\nprint(\"C:\", C)\nprint(\"D:\", D)\n"
] | [
[
"tensorflow.matmul",
"tensorflow.constant",
"tensorflow.zeros",
"tensorflow.random.uniform",
"tensorflow.add"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
}
] |
dharunya0609/lifelines | [
"e2af3132db5a8090672612ad912fcaa1533ebdd3"
] | [
"perf_tests/weibull_perf_test.py"
] | [
"# -*- coding: utf-8 -*-\n\nif __name__ == \"__main__\":\n import pandas as pd\n import numpy as np\n import time\n\n from lifelines import WeibullFitter\n\n data = (\n [{\"start\": 0, \"stop\": 2, \"E\": False}] * (1000 - 376)\n + [{\"start\": 2, \"stop\": 5, \"E\": False}] * (376 - 82)\n + [{\"start\": 5, \"stop\": 10, \"E\": False}] * (82 - 7)\n + [{\"start\": 10, \"stop\": 1e10, \"E\": False}] * 7\n )\n\n df = pd.DataFrame.from_records(data)\n print(df)\n\n df = df.groupby([\"start\", \"stop\", \"E\"]).size().reset_index()\n print(df)\n\n wb = WeibullFitter()\n start_time = time.time()\n wb.fit_interval_censoring(df[\"start\"], df[\"stop\"], df[\"E\"], weights=df[0])\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n wb.print_summary(5)\n"
] | [
[
"pandas.DataFrame.from_records"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
spscah/strava-grab | [
"ab29a4bd2349aec01cc74cdbea26c8f3079904c6"
] | [
"refresh-all-activities.py"
] | [
"import pandas as pd\nimport requests\nimport json\nimport time\n\n# based on https://medium.com/swlh/using-python-to-connect-to-stravas-api-and-analyse-your-activities-dummies-guide-5f49727aac86 \n\n## Get the tokens from file to connect to Strava\nwith open('strava_tokens.json') as json_file:\n strava_tokens = json.load(json_file)## If access_token has expired then use the refresh_token to get the new access_token\n\nif strava_tokens['expires_at'] < time.time():#Make Strava auth API call with current refresh token\n\n\n with open(\"creds.json\") as creds_file: \n creds = json.load(creds_file)\n\n client_id = creds[\"Client ID\"]\n client_secret = creds[\"Client Secret\"]\n\n response = requests.post(\n url = 'https://www.strava.com/oauth/token',\n data = {\n 'client_id': client_id,\n 'client_secret': client_secret,\n 'grant_type': 'refresh_token',\n 'refresh_token': strava_tokens['refresh_token']\n }\n )#Save response as json in new variable\n new_strava_tokens = response.json()# Save new tokens to file\n with open('strava_tokens.json', 'w') as outfile:\n json.dump(new_strava_tokens, outfile)\n #Use new Strava tokens from now\n strava_tokens = new_strava_tokens\n #Loop through all activities\n\npage = 1\nurl = \"https://www.strava.com/api/v3/activities\"\naccess_token = strava_tokens['access_token']## Create the dataframe ready for the API call to store your activity data\ncols = [\n \"id\",\n \"name\",\n \"start_date_local\",\n \"type\",\n \"distance\",\n \"moving_time\",\n \"elapsed_time\",\n \"average_heartrate\",\n \"gear_id\",\n \"total_elevation_gain\",\n \"end_latlng\",\n \"external_id\"\n ]\n\n\nactivities = pd.DataFrame(\n columns = cols \n \n)\n\nwhile True: \n # get page of activities from Strava\n r = requests.get(url + '?access_token=' + access_token + '&per_page=200' + '&page=' + str(page))\n r = r.json()# if no results then exit loop\n if (not r):\n break\n \n # otherwise add new data to dataframe\n for x in range(len(r)):\n for c in cols: \n activities.loc[x + (page-1)*200, c] = r[x][c]\n # increment page\n page += 1\n \nactivities.to_csv('strava_activities.csv')"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
gustavocidornelas/fused-multimodal-emotion | [
"a15a1313f6e0848d8fc8c5aa796e92effa2f8e8b"
] | [
"model/model_multimodal_attention.py"
] | [
"\"\"\"\nCreated on Tue May 14, 2019\n\n@author: Gustavo Cid Ornelas\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom model_audio import *\n\nclass MultimodalAttentionModel:\n \"\"\"\n Class that creates the graph for the multimodal model with global attention\n\n \"\"\"\n\n def __init__(self, text_input, label_batch, batch_size, num_categories, learning_rate, dict_size, hidden_dim_text,\n num_layers_text, dr_prob_text, multimodal_model_status, audio_input, num_filters_audio,\n filter_lengths_audio, n_pool_audio, audio_len, dr_prob_audio, hidden_dim_audio, num_layers_audio):\n # general\n self.text_input = text_input\n self.audio_input = audio_input\n self.labels = label_batch\n self.batch_size = batch_size\n self.num_categories = num_categories\n self.learning_rate = learning_rate\n self.loss = 0.0\n self.batch_loss = None\n self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')\n self.multimodal_model_status = multimodal_model_status\n\n # embedding layer\n self.dict_size = dict_size\n self.embed_dim = 300 # using GloVe\n\n # text recurrent layers\n self.hidden_dim_text = hidden_dim_text\n self.num_layers_text = num_layers_text\n self.dr_prob_text = dr_prob_text\n\n # output layer\n self.y_labels = []\n self.M = None\n self.b = None\n\n # audio network\n self.num_filters_audio = num_filters_audio\n self.filter_lengths_audio = filter_lengths_audio\n self.n_pool_audio = n_pool_audio\n self.audio_input_len = audio_len\n self.dr_prob_audio = dr_prob_audio\n self.hidden_dim_audio = hidden_dim_audio\n self.num_layers_audio = num_layers_audio\n self.conv_out_length = int(audio_len / (n_pool_audio[0] * n_pool_audio[1]))\n\n # attention score\n self.W1 = tf.keras.layers.Dense(hidden_dim_text)\n self.W2 = tf.keras.layers.Dense(hidden_dim_text)\n self.V = tf.keras.layers.Dense(1)\n\n def _create_audio_model(self):\n \"\"\"\n Creates the audio model in the graph\n \"\"\"\n print('Creating the audio model...')\n # instantiating object of the class AudioModel\n audio_model = AudioModel(self.audio_input, self.labels, self.batch_size, self.num_categories,\n self.learning_rate, self.num_filters_audio, self.filter_lengths_audio,\n self.audio_input_len, self.n_pool_audio, self.hidden_dim_audio, self.num_layers_audio,\n self.dr_prob_audio)\n\n # building the audio model's graph\n audio_model._create_conv_layers()\n audio_model._create_recursive_net()\n\n # getting the audio hidden states for the current batch\n self.audio_hidden_states = tf.stack(audio_model.outputs_enc, axis=2)\n\n def _create_placeholders(self):\n \"\"\"\n Creates the placeholder for the pre-trained embedding\n \"\"\"\n print('Creating placeholders...')\n self.embedding_GloVe = tf.placeholder(tf.float32, shape=[self.dict_size, self.embed_dim],\n name='embedding_placeholder')\n\n def _create_embedding(self):\n \"\"\"\n Creates the embedding matrix and embeds the input that will be fed to the RNN\n \"\"\"\n print('Creating embedding...')\n\n with tf.name_scope('embedding_layer'):\n self.embedding_matrix = tf.Variable(tf.random_normal([self.dict_size, self.embed_dim], mean=0.0,\n stddev=0.01, dtype=tf.float32, seed=None),\n trainable=True, name='embed_matrix')\n\n self.embedded_input = tf.nn.embedding_lookup(self.embedding_matrix, self.text_input, name='embedded_input')\n\n def _initialize_embedding(self):\n \"\"\"\n Initializes the embedding matrix with the pre-trained embedding (GloVe)\n \"\"\"\n print('Initializing embedding with GloVe...')\n\n self.embedding_init = self.embedding_matrix.assign(self.embedding_GloVe)\n\n def gru_cell(self):\n \"\"\"\n Creates an instance of a Gated Recurrent Unit (GRU) cell\n\n Returns\n ----------\n (GRUCell object): instance of a GRU cell\n \"\"\"\n # a single instance of the GRU\n return tf.contrib.rnn.GRUCell(num_units=self.hidden_dim_text)\n\n def gru_dropout_cell(self):\n \"\"\"\n Implements a cell instance with dropout wrapper applied\n\n Returns\n ----------\n (DropoutWrapper object): instance of a GRU cell with the specified dropout probability\n \"\"\"\n # specified dropout between the layers\n return tf.contrib.rnn.DropoutWrapper(self.gru_cell(), input_keep_prob=self.dr_prob_text,\n output_keep_prob=self.dr_prob_text)\n\n def attention_mechanism(self, text_hidden_state):\n \"\"\"\n Implements Luong's or Bahdanau's attention mechanism between the current text model's hidden state and all of\n the audio model hidden states and returns the context vector\n\n Parameters\n ----------\n text_hidden_state (tensor): tensor of shape [batch_size, hidden_dim_text] with the current hidden states of the\n text model for the batch\n\n Returns\n ----------\n transformed_hidden_state (tensor): tensor of shape [batch_size, hidden_dim_text] with the transformed hidden\n state (after applying attention)\n \"\"\"\n # reshaping the tensors\n audio_hidden_states = tf.reshape(self.audio_hidden_states, [-1, self.conv_out_length, self.hidden_dim_audio])\n text_hidden_state = tf.reshape(text_hidden_state, [-1, 1, self.hidden_dim_text])\n\n # calculating the scores (similarity between the current text hidden state and all of the audio hidden states)\n # score = tf.matmul(audio_hidden_states, text_hidden_state) # Luong's attention\n score = self.V(tf.nn.tanh(self.W1(audio_hidden_states) + self.W2(text_hidden_state))) # Bahdanau's attention\n\n # calculating the attention weights\n attention_weights = tf.nn.softmax(score, dim=1, name='attention_weights')\n\n # performing the weighted sum of the audio hidden states\n weighted_states = tf.multiply(audio_hidden_states, attention_weights)\n context_vector = tf.reduce_sum(weighted_states, axis=1)\n\n # concatenating the context vector with the current text hidden state\n text_hidden_state = tf.reshape(text_hidden_state, [-1, self.hidden_dim_text])\n concatenated_state = tf.concat([context_vector, text_hidden_state], axis=1)\n\n # projecting back to the same dimensions as the hidden states\n transformed_hidden_state = tf.tanh(tf.matmul(concatenated_state, self.W_c))\n\n return transformed_hidden_state\n\n def _create_recursive_net(self):\n \"\"\"\n Creates the RNN with GRUs and dropout, as specified\n \"\"\"\n print('Creating the recurrent layers...')\n\n with tf.name_scope('RNN'):\n # splitting the embedded input to be fed to the RNN as a list\n rnn_input = tf.split(self.embedded_input, 128, axis=1)\n\n # reshaping the elements in rnn_input to be fed to the RNN\n rnn_input = [input_element[:, 0, :] for input_element in rnn_input]\n\n # creating the list with the specified number of layers of GRU cells with dropout\n cell_enc = tf.nn.rnn_cell.MultiRNNCell([self.gru_dropout_cell() for _ in range(self.num_layers_text)],\n state_is_tuple=False)\n\n # initializing list with the outputs\n self.outputs_enc = []\n self.W_c = tf.Variable(tf.random_uniform([self.hidden_dim_audio + self.hidden_dim_text,\n self.hidden_dim_text],\n minval=-0.25,\n maxval=0.25,\n dtype=tf.float32,\n seed=None\n ),\n trainable=True,\n name='project_weight')\n\n # unrolling the RNN manually\n for time_step, input in enumerate(rnn_input):\n\n # checking if it is the first time step\n if time_step == 0:\n # initialize hidden state of the text RNN with the last state from the audio RNN\n output, text_hidden_state = cell_enc(input, self.audio_hidden_states[:, :, -1])\n self.outputs_enc.append(output)\n else:\n # get the transformed hidden state with attention\n new_hidden_state = self.attention_mechanism(text_hidden_state)\n\n # feed the transformed hidden state to the RNN\n output, text_hidden_state = cell_enc(input, new_hidden_state)\n self.outputs_enc.append(output)\n\n # adding hidden states to collection to be restored later\n hidden_states = tf.stack(self.outputs_enc, axis=2)\n tf.add_to_collection('hidden_states', hidden_states)\n\n # self.final_encoder = self.last_states_enc[-1]\n self.final_encoder = text_hidden_state\n\n def _create_output_layers(self):\n \"\"\"\n Creates the output layer (fully connected layer)\n \"\"\"\n print('Creating the output layers...')\n\n # defining the output layer\n with tf.name_scope('output_layer'):\n self.M = tf.Variable(tf.random_uniform([self.hidden_dim_text, self.num_categories],\n minval=-0.25,\n maxval=0.25,\n dtype=tf.float32,\n seed=None),\n trainable=True, name='W')\n\n self.b = tf.Variable(tf.zeros([1], dtype=tf.float32), trainable=True, name='b')\n\n self.batch_prediction = tf.add(tf.matmul(self.final_encoder, self.M), self.b, name='batch_prediction')\n\n with tf.name_scope('loss'):\n # batch loss\n self.batch_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=self.batch_prediction, labels=self.labels)\n self.loss = tf.reduce_mean(self.batch_loss, name='mean_batch_loss')\n\n # batch accuracy\n self.accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.batch_prediction, 1),\n tf.argmax(self.labels, 1)), tf.float32), name='mean_batch_accuracy')\n\n def _create_optimizer(self):\n \"\"\"\n Defining the optimizer (Adam)\n \"\"\"\n print('Creating the optimizer...')\n\n with tf.name_scope('audio_optimizer'):\n # Adam optimizer with the specified learning rate\n opt_func = tf.train.AdamOptimizer(learning_rate=self.learning_rate)\n gvs = opt_func.compute_gradients(self.loss)\n # applying gradient clipping\n gvs_cap = [(tf.clip_by_value(t=grad, clip_value_min=-10.0, clip_value_max=10.0), var) for grad, var in gvs]\n self.optimizer = opt_func.apply_gradients(grads_and_vars=gvs_cap, global_step=self.global_step)\n\n def _create_summary(self):\n \"\"\"\n Creating the TensorBoard summary. Displays the mean training loss and mean training accuracy\n \"\"\"\n print('Creating summary...')\n\n with tf.name_scope('summary'):\n tf.summary.scalar('mean_loss', self.loss)\n tf.summary.scalar('mean_accuracy', self.accuracy)\n self.summary_op = tf.summary.merge_all()\n\n def build_graph(self):\n \"\"\"\n Method that builds the graph for the multimodal model with attention\n \"\"\"\n self._create_audio_model()\n self._create_placeholders()\n self._create_embedding()\n self._initialize_embedding()\n self._create_recursive_net()\n self._create_output_layers()\n self._create_optimizer()\n self._create_summary()\n"
] | [
[
"tensorflow.concat",
"tensorflow.contrib.rnn.GRUCell",
"tensorflow.zeros",
"tensorflow.stack",
"tensorflow.reduce_sum",
"tensorflow.nn.sigmoid_cross_entropy_with_logits",
"tensorflow.train.AdamOptimizer",
"tensorflow.summary.scalar",
"tensorflow.Variable",
"tensorflow.name_scope",
"tensorflow.argmax",
"tensorflow.matmul",
"tensorflow.keras.layers.Dense",
"tensorflow.placeholder",
"tensorflow.summary.merge_all",
"tensorflow.split",
"tensorflow.add_to_collection",
"tensorflow.nn.embedding_lookup",
"tensorflow.clip_by_value",
"tensorflow.nn.softmax",
"tensorflow.multiply",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.random_uniform",
"tensorflow.random_normal"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
douglastome/msc2018continual-learning | [
"b5b92dc7ac36362a51cd812a1abab68424ed009e"
] | [
"src/vggish_slim.py"
] | [
"# Copyright 2017 The TensorFlow Authors All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# NOTICE: this file has been modified by Douglas Feitosa Tome in 2018.\n# The modified version of this file is licensed under the License above.\n# ==============================================================================\n\n\"\"\"Defines the 'VGGish' model used to generate AudioSet embedding features.\n\nThe public AudioSet release (https://research.google.com/audioset/download.html)\nincludes 128-D features extracted from the embedding layer of a VGG-like model\nthat was trained on a large Google-internal YouTube dataset. Here we provide\na TF-Slim definition of the same model, without any dependences on libraries\ninternal to Google. We call it 'VGGish'.\n\nNote that we only define the model up to the embedding layer, which is the\npenultimate layer before the final classifier layer. We also provide various\nhyperparameter values (in vggish_params.py) that were used to train this model\ninternally.\n\nFor comparison, here is TF-Slim's VGG definition:\nhttps://github.com/tensorflow/models/blob/master/research/slim/nets/vgg.py\n\"\"\"\n\nimport tensorflow as tf\nimport vggish_params as params\n\nslim = tf.contrib.slim\n\n\ndef define_vggish_slim(training=False):\n \"\"\"Defines the VGGish TensorFlow model.\n\n All ops are created in the current default graph, under the scope 'vggish/'.\n\n The input is a placeholder named 'vggish/input_features' of type float32 and\n shape [batch_size, num_frames, num_bands] where batch_size is variable and\n num_frames and num_bands are constants, and [num_frames, num_bands] represents\n a log-mel-scale spectrogram patch covering num_bands frequency bands and\n num_frames time frames (where each frame step is usually 10ms). This is\n produced by computing the stabilized log(mel-spectrogram + params.LOG_OFFSET).\n The output is an op named 'vggish/embedding' which produces the activations of\n a 128-D embedding layer, which is usually the penultimate layer when used as\n part of a full model with a final classifier layer.\n\n Args:\n training: If true, all parameters are marked trainable.\n\n Returns:\n The op 'vggish/embeddings'.\n \"\"\"\n # Defaults:\n # - All weights are initialized to N(0, INIT_STDDEV).\n # - All biases are initialized to 0.\n # - All activations are ReLU.\n # - All convolutions are 3x3 with stride 1 and SAME padding.\n # - All max-pools are 2x2 with stride 2 and SAME padding.\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n weights_initializer=tf.truncated_normal_initializer(\n stddev=params.INIT_STDDEV),\n biases_initializer=tf.zeros_initializer(),\n activation_fn=tf.nn.relu,\n trainable=training), \\\n slim.arg_scope([slim.conv2d],\n kernel_size=[3, 3], stride=1, padding='SAME'), \\\n slim.arg_scope([slim.max_pool2d],\n kernel_size=[2, 2], stride=2, padding='SAME'), \\\n tf.variable_scope('vggish'):\n # Input: a batch of 2-D log-mel-spectrogram patches.\n features = tf.placeholder(\n tf.float32, shape=(params.BATCH_SIZE, params.NUM_FRAMES, params.NUM_BANDS),\n name='input_features')\n # Reshape to 4-D so that we can convolve a batch with conv2d().\n reshaped_features = tf.reshape(features, [-1, params.NUM_FRAMES, params.NUM_BANDS, 1])\n\n # The VGG stack of alternating convolutions and max-pools.\n net = slim.conv2d(reshaped_features, 64, scope='conv1')\n net = slim.max_pool2d(net, scope='pool1')\n net = slim.conv2d(net, 128, scope='conv2')\n net = slim.max_pool2d(net, scope='pool2')\n net = slim.repeat(net, 2, slim.conv2d, 256, scope='conv3')\n net = slim.max_pool2d(net, scope='pool3')\n net = slim.repeat(net, 2, slim.conv2d, 512, scope='conv4')\n net = slim.max_pool2d(net, scope='pool4')\n\n # Flatten before entering fully-connected layers\n net = slim.flatten(net)\n net = slim.repeat(net, 2, slim.fully_connected, 4096, scope='fc1')\n # The embedding layer.\n net = slim.fully_connected(net, params.EMBEDDING_SIZE, scope='fc2')\n return tf.identity(net, name='embedding')\n\n\ndef load_vggish_slim_checkpoint(session, checkpoint_path):\n \"\"\"Loads a pre-trained VGGish-compatible checkpoint.\n\n This function can be used as an initialization function (referred to as\n init_fn in TensorFlow documentation) which is called in a Session after\n initializating all variables. When used as an init_fn, this will load\n a pre-trained checkpoint that is compatible with the VGGish model\n definition. Only variables defined by VGGish will be loaded.\n\n Args:\n session: an active TensorFlow session.\n checkpoint_path: path to a file containing a checkpoint that is\n compatible with the VGGish model definition.\n \"\"\"\n # Get the list of names of all VGGish variables that exist in\n # the checkpoint (i.e., all inference-mode VGGish variables).\n with tf.Graph().as_default():\n define_vggish_slim(training=False)\n vggish_var_names = [v.name for v in tf.global_variables()]\n\n # Get the list of all currently existing variables that match\n # the list of variable names we just computed.\n vggish_vars = [v for v in tf.global_variables() if v.name in vggish_var_names]\n\n # Use a Saver to restore just the variables selected above.\n saver = tf.train.Saver(vggish_vars, name='vggish_load_pretrained',\n write_version=1)\n saver.restore(session, checkpoint_path)\n"
] | [
[
"tensorflow.Graph",
"tensorflow.zeros_initializer",
"tensorflow.reshape",
"tensorflow.identity",
"tensorflow.placeholder",
"tensorflow.global_variables",
"tensorflow.truncated_normal_initializer",
"tensorflow.variable_scope",
"tensorflow.train.Saver"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
luoyan407/predict_trustworthiness | [
"8f394fc511b9aa31a766a30f0e1b059481aa5f76"
] | [
"src/checkpoint.py"
] | [
"import os\nimport torch\nfrom tensorflow.io import gfile\nimport numpy as np\n\n\ndef load_pretrained_d_oracle(path):\n \"\"\" Load weights from a given checkpoint path in npz/pth \"\"\"\n if path.endswith('npz'):\n keys, values = load_jax(path)\n state_dict = convert_jax_pytorch(keys, values)\n elif path.endswith('pth'):\n state_dict = torch.load(path)['state_dict']\n else:\n raise ValueError(\"checkpoint format {} not supported yet!\".format(path.split('.')[-1]))\n\n return state_dict\n\ndef load_pretrained_oracle_and_head(path):\n \"\"\" Load weights from a given checkpoint path in npz/pth \"\"\"\n if path.endswith('npz'):\n keys, values = load_jax(path)\n state_dict = convert_jax_pytorch(keys, values)\n elif path.endswith('pth'):\n state_dict = torch.load(path)['state_dict']\n state_dict_head = torch.load(path)['state_dict_head']\n else:\n raise ValueError(\"checkpoint format {} not supported yet!\".format(path.split('.')[-1]))\n\n return state_dict, state_dict_head\n\ndef load_checkpoint(path):\n \"\"\" Load weights from a given checkpoint path in npz/pth \"\"\"\n if path.endswith('npz'):\n keys, values = load_jax(path)\n state_dict = convert_jax_pytorch(keys, values)\n elif path.endswith('pth'):\n state_dict = torch.load(path)['state_dict']\n else:\n raise ValueError(\"checkpoint format {} not supported yet!\".format(path.split('.')[-1]))\n\n return state_dict\n\n\ndef load_jax(path):\n \"\"\" Loads params from a npz checkpoint previously stored with `save()` in jax implemetation \"\"\"\n with gfile.GFile(path, 'rb') as f:\n ckpt_dict = np.load(f, allow_pickle=False)\n keys, values = zip(*list(ckpt_dict.items()))\n return keys, values\n\n\ndef save_jax_to_pytorch(jax_path, save_path):\n model_name = jax_path.split('/')[-1].split('.')[0]\n keys, values = load_jax(jax_path)\n state_dict = convert_jax_pytorch(keys, values)\n checkpoint = {'state_dict': state_dict}\n torch.save(checkpoint, os.path.join(save_path, model_name + '.pth'))\n\n\ndef replace_names(names):\n \"\"\" Replace jax model names with pytorch model names \"\"\"\n new_names = []\n for name in names:\n if name == 'Transformer':\n new_names.append('transformer')\n elif name == 'encoder_norm':\n new_names.append('norm')\n elif 'encoderblock' in name:\n num = name.split('_')[-1]\n new_names.append('encoder_layers')\n new_names.append(num)\n elif 'LayerNorm' in name:\n num = name.split('_')[-1]\n if num == '0':\n new_names.append('norm{}'.format(1))\n elif num == '2':\n new_names.append('norm{}'.format(2))\n elif 'MlpBlock' in name:\n new_names.append('mlp')\n elif 'Dense' in name:\n num = name.split('_')[-1]\n new_names.append('fc{}'.format(int(num) + 1))\n elif 'MultiHeadDotProductAttention' in name:\n new_names.append('attn')\n elif name == 'kernel' or name == 'scale':\n new_names.append('weight')\n elif name == 'bias':\n new_names.append(name)\n elif name == 'posembed_input':\n new_names.append('pos_embedding')\n elif name == 'pos_embedding':\n new_names.append('pos_embedding')\n elif name == 'embedding':\n new_names.append('embedding')\n elif name == 'head':\n new_names.append('classifier')\n elif name == 'cls':\n new_names.append('cls_token')\n else:\n new_names.append(name)\n return new_names\n\n\ndef convert_jax_pytorch(keys, values):\n \"\"\" Convert jax model parameters with pytorch model parameters \"\"\"\n state_dict = {}\n for key, value in zip(keys, values):\n\n # convert name to torch names\n names = key.split('/')\n torch_names = replace_names(names)\n torch_key = '.'.join(w for w in torch_names)\n\n # convert values to tensor and check shapes\n tensor_value = torch.tensor(value, dtype=torch.float)\n # check shape\n num_dim = len(tensor_value.shape)\n\n if num_dim == 1:\n tensor_value = tensor_value.squeeze()\n elif num_dim == 2 and torch_names[-1] == 'weight':\n # for normal weight, transpose it\n tensor_value = tensor_value.T\n elif num_dim == 3 and torch_names[-1] == 'weight' and torch_names[-2] in ['query', 'key', 'value']:\n feat_dim, num_heads, head_dim = tensor_value.shape\n # for multi head attention q/k/v weight\n tensor_value = tensor_value\n elif num_dim == 2 and torch_names[-1] == 'bias' and torch_names[-2] in ['query', 'key', 'value']:\n # for multi head attention q/k/v bias\n tensor_value = tensor_value\n elif num_dim == 3 and torch_names[-1] == 'weight' and torch_names[-2] == 'out':\n # for multi head attention out weight\n tensor_value = tensor_value\n elif num_dim == 4 and torch_names[-1] == 'weight':\n tensor_value = tensor_value.permute(3, 2, 0, 1)\n\n # print(\"{}: {}\".format(torch_key, tensor_value.shape))\n state_dict[torch_key] = tensor_value\n return state_dict\n\n\nif __name__ == '__main__':\n save_jax_to_pytorch('/Users/leon/Downloads/jax/imagenet21k+imagenet2012_ViT-L_16-224.npz', '/Users/leon/Downloads/pytorch')\n\n\n"
] | [
[
"tensorflow.io.gfile.GFile",
"numpy.load",
"torch.load",
"torch.tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shreyasajal/PredictIn-1 | [
"e458f3cf2b0cff1a6924bc83c8f3bdb6fc1f255d"
] | [
"static/cssFolder/app.py"
] | [
"from flask import Flask, render_template, url_for, request\nimport numpy as np\nimport pandas as pd\nimport joblib\n \nfilename = 'model.pkl'\nreg = joblib.load(filename)\n\napp= Flask(__name__)\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/aboutus')\ndef aboutus():\n return render_template('aboutus.html') \n\[email protected]('/result', methods = ['POST'])\ndef result():\n formDictionary = request.form\n \n country = request.form['country']\n accType = request.form['accType']\n headline = request.form['headline']\n bio = request.form['bio']\n followers = int( request.form['followers'] )\n profile_link = request.form['profile_link']\n mediaType = request.form['mediaType']\n post_content = request.form['post_content']\n num_links = int( request.form['num_links'] )\n\n article=0\n document=0\n image=0\n poll=0\n text=0\n video=0\n\n if mediaType=='article':\n article=1\n elif mediaType=='document':\n document=1 \n elif mediaType=='image':\n image=1 \n elif mediaType=='poll':\n poll=1 \n elif mediaType=='text':\n text=1 \n elif mediaType=='video':\n video=1 \n\n from function_for_input import input_variables\n num_hashtags,contlen,relevance_score,post_type,confidence=input_variables(post_content,bio,headline)\n num_hashtags=int(num_hashtags)\n contlen=int(contlen)\n relevance_score=int(relevance_score)\n conf=int(confidence)\n\n achievement=0\n call_to_action=0\n insights=0\n job_opening=0\n other=0\n if post_type=='achievement':\n achievement=1\n elif post_type=='call to action':\n call_to_action=1 \n elif post_type=='insights':\n insights=1 \n elif post_type=='job opening':\n job_opening=1 \n elif post_type=='other':\n other=1 \n \n\n \n\n arr=np.array([ [followers,article,document,image,poll,text,video,achievement,call_to_action,insights,job_opening,other,num_hashtags,num_links, contlen, conf, relevance_score] ])\n X_test = pd.DataFrame(arr,columns=[ 'followers', 'article', 'document', 'image', 'poll', 'text', 'video', 'achievement', 'call to action', 'insights', 'job opening', 'other', 'num_hashtags', 'num_links', 'contlen', 'conf', 'relevance_score'])\n post_reach = reg.predict(X_test)\n post_reach=post_reach[0]\n \n post_reach=round(float(post_reach),4) \n \n\n return render_template('result.html', post_reach=post_reach ) \n\n\n\nif __name__=='__main__':\n app.run(debug=True)\n"
] | [
[
"numpy.array",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
gritYCDA/shape_deform | [
"5780f59f39164e01dcda668c4c57df92876561a1"
] | [
"train_ae.py"
] | [
"import os\nimport time\nimport argparse\nimport torch\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\nfrom lib.auto_encoder import PointCloudAE\nfrom lib.loss import ChamferLoss\nfrom data.shape_dataset import ShapeDataset\nfrom lib.utils import setup_logger\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--num_point', type=int, default=1024, help='number of points, needed if use points')\nparser.add_argument('--emb_dim', type=int, default=512, help='dimension of latent embedding [default: 512]')\nparser.add_argument('--h5_file', type=str, default='data/obj_models/ShapeNetCore_4096.h5', help='h5 file')\nparser.add_argument('--batch_size', type=int, default=32, help='batch size')\nparser.add_argument('--num_workers', type=int, default=10, help='number of data loading workers')\nparser.add_argument('--gpu', type=str, default='0', help='GPU to use')\nparser.add_argument('--lr', type=float, default=0.0001, help='initial learning rate')\nparser.add_argument('--start_epoch', type=int, default=1, help='which epoch to start')\nparser.add_argument('--max_epoch', type=int, default=50, help='max number of epochs to train')\nparser.add_argument('--resume_model', type=str, default='', help='resume from saved model')\nparser.add_argument('--result_dir', type=str, default='results/ae_points', help='directory to save train results')\nopt = parser.parse_args()\n\nopt.repeat_epoch = 10\nopt.decay_step = 5000\nopt.decay_rate = [1.0, 0.6, 0.3, 0.1]\n\n\ndef train_net():\n # set result directory\n if not os.path.exists(opt.result_dir):\n os.makedirs(opt.result_dir)\n tb_writer = tf.summary.FileWriter(opt.result_dir)\n logger = setup_logger('train_log', os.path.join(opt.result_dir, 'log.txt'))\n for key, value in vars(opt).items():\n logger.info(key + ': ' + str(value))\n os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu\n # model & loss\n estimator = PointCloudAE(opt.emb_dim, opt.num_point)\n estimator.cuda()\n criterion = ChamferLoss()\n if opt.resume_model != '':\n estimator.load_state_dict(torch.load(opt.resume_model))\n # dataset\n train_dataset = ShapeDataset(opt.h5_file, mode='train', augment=True)\n train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=opt.batch_size,\n shuffle=True, num_workers=opt.num_workers)\n val_dataset = ShapeDataset(opt.h5_file, mode='val', augment=False)\n val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=opt.batch_size,\n shuffle=False, num_workers=opt.num_workers)\n # train\n st_time = time.time()\n global_step = ((train_dataset.length + opt.batch_size - 1) // opt.batch_size) * opt.repeat_epoch * (opt.start_epoch - 1)\n decay_count = -1\n for epoch in range(opt.start_epoch, opt.max_epoch+1):\n # train one epoch\n logger.info('Time {0}'.format(time.strftime(\"%Hh %Mm %Ss\", time.gmtime(time.time() - st_time)) + \\\n ', ' + 'Epoch %02d' % epoch + ', ' + 'Training started'))\n # create optimizer and adjust learning rate if needed\n if global_step // opt.decay_step > decay_count:\n decay_count += 1\n if decay_count < len(opt.decay_rate):\n current_lr = opt.lr * opt.decay_rate[decay_count]\n optimizer = torch.optim.Adam(estimator.parameters(), lr=current_lr)\n batch_idx = 0\n estimator.train()\n for rep in range(opt.repeat_epoch):\n for i, data in enumerate(train_dataloader):\n # label must be zero_indexed\n batch_xyz, batch_label = data\n batch_xyz = batch_xyz[:, :, :3].cuda()\n optimizer.zero_grad()\n embedding, point_cloud = estimator(batch_xyz)\n loss, _, _ = criterion(point_cloud, batch_xyz)\n summary = tf.Summary(value=[tf.Summary.Value(tag='learning_rate', simple_value=current_lr),\n tf.Summary.Value(tag='train_loss', simple_value=loss)])\n # backward\n loss.backward()\n optimizer.step()\n global_step += 1\n batch_idx += 1\n # write results to tensorboard\n tb_writer.add_summary(summary, global_step)\n if batch_idx % 10 == 0:\n logger.info('Batch {0} Loss:{1:f}'.format(batch_idx, loss))\n logger.info('>>>>>>>>----------Epoch {:02d} train finish---------<<<<<<<<'.format(epoch))\n # evaluate one epoch\n logger.info('Time {0}'.format(time.strftime(\"%Hh %Mm %Ss\", time.gmtime(time.time() - st_time)) + \\\n ', ' + 'Epoch %02d' % epoch + ', ' + 'Testing started'))\n estimator.eval()\n val_loss = 0.0\n for i, data in enumerate(val_dataloader, 1):\n batch_xyz, batch_label = data\n batch_xyz = batch_xyz[:, :, :3].cuda()\n embedding, point_cloud = estimator(batch_xyz)\n loss, _, _ = criterion(point_cloud, batch_xyz)\n val_loss += loss.item()\n logger.info('Batch {0} Loss:{1:f}'.format(i, loss))\n val_loss = val_loss / i\n summary = tf.Summary(value=[tf.Summary.Value(tag='val_loss', simple_value=val_loss)])\n tb_writer.add_summary(summary, global_step)\n logger.info('Epoch {0:02d} test average loss: {1:06f}'.format(epoch, val_loss))\n logger.info('>>>>>>>>----------Epoch {:02d} test finish---------<<<<<<<<'.format(epoch))\n # save model after each epoch\n torch.save(estimator.state_dict(), '{0}/model_{1:02d}.pth'.format(opt.result_dir, epoch))\n\n\nif __name__ == '__main__':\n train_net()\n"
] | [
[
"tensorflow.compat.v1.Summary.Value",
"torch.load",
"tensorflow.compat.v1.summary.FileWriter",
"tensorflow.compat.v1.disable_v2_behavior",
"torch.utils.data.DataLoader"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhupengjia/BERT-pytorch | [
"7efd2b5a631f18ebc83cd16886b8c6ee77a40750"
] | [
"bert_pytorch/dataset/dataset.py"
] | [
"from torch.utils.data import Dataset\nimport tqdm\nimport torch\nimport random\n\n\nclass BERTDataset(Dataset):\n def __init__(self, corpus_path, vocab, seq_len, encoding=\"utf-8\", corpus_lines=None):\n self.vocab = vocab\n self.seq_len = seq_len\n\n with open(corpus_path, \"r\", encoding=encoding) as f:\n self.datas = [line[:-1].split(\"\\t\")\n for line in tqdm.tqdm(f, desc=\"Loading Dataset\", total=corpus_lines)]\n\n def __len__(self):\n return len(self.datas)\n\n def __getitem__(self, item):\n t1, (t2, is_next_label) = self.datas[item][0], self.random_sent(item)\n t1_random, t1_label = self.random_word(t1)\n t2_random, t2_label = self.random_word(t2)\n\n # [CLS] tag = SOS tag, [SEP] tag = EOS tag\n t1 = [self.vocab.sos_index] + t1_random + [self.vocab.eos_index]\n t2 = t2_random + [self.vocab.eos_index]\n\n t1_label = [self.vocab.pad_index] + t1_label + [self.vocab.pad_index]\n t2_label = t2_label + [self.vocab.pad_index]\n\n segment_label = ([1 for _ in range(len(t1))] + [2 for _ in range(len(t2))])[:self.seq_len]\n bert_input = (t1 + t2)[:self.seq_len]\n bert_label = (t1_label + t2_label)[:self.seq_len]\n\n padding = [self.vocab.pad_index for _ in range(self.seq_len - len(bert_input))]\n bert_input.extend(padding), bert_label.extend(padding), segment_label.extend(padding)\n\n output = {\"bert_input\": bert_input,\n \"bert_label\": bert_label,\n \"segment_label\": segment_label,\n \"is_next\": is_next_label}\n\n return {key: torch.tensor(value) for key, value in output.items()}\n\n def random_word(self, sentence):\n tokens = sentence.split()\n output_label = []\n\n for i, token in enumerate(tokens):\n prob = random.random()\n if prob < 0.15:\n # 80% randomly change token to make token\n if prob < prob * 0.8:\n tokens[i] = self.vocab.mask_index\n\n # 10% randomly change token to random token\n elif prob * 0.8 <= prob < prob * 0.9:\n tokens[i] = random.randrange(len(self.vocab))\n\n # 10% randomly change token to current token\n elif prob >= prob * 0.9:\n tokens[i] = self.vocab.stoi.get(token, self.vocab.unk_index)\n\n output_label.append(self.vocab.stoi.get(token, self.vocab.unk_index))\n\n else:\n tokens[i] = self.vocab.stoi.get(token, self.vocab.unk_index)\n output_label.append(0)\n\n return tokens, output_label\n\n def random_sent(self, index):\n # output_text, label(isNotNext:0, isNext:1)\n if random.random() > 0.5:\n return self.datas[index][1], 1\n else:\n return self.datas[random.randrange(len(self.datas))][1], 0\n"
] | [
[
"torch.tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tunir27/ICDCN-2019 | [
"98a976d7d4c0b50f67c1bb95a67f3125168a6107"
] | [
"Chennai_Floods_code/network2(backup).py"
] | [
"import pandas as pd\nimport codecs\nimport numpy as np\nimport networkx as nx\nfrom networkx.drawing.nx_agraph import graphviz_layout\nimport re\nimport matplotlib.pyplot as plt\n\n#data = pd.read_csv('edges.csv')\nDG=nx.DiGraph()\ndata = codecs.open('Cluster2 Tweets.txt',\"r\",encoding=\"utf-8\")\nregex = r\"\\w*crocodile\\w*\"\nval_map={}\nslist=[]\ntlist=[]\nolist=[]\n\n#plt.figure(figsize=(10,10))\nfor i in data:\n d=i.split(',')\n matches = re.finditer(regex,d[2])\n for match in matches:\n if match:\n #print(i)\n #sor=d[1]\n #tar=d[0]\n #print(\"sor\",sor)\n #print(\"tar\",tar)\n sor=d[1].replace('[','').replace(\"'\",'').strip()\n tar=d[0].replace(\"'\",'').replace(\" \",'').replace('[','').strip()\n #print((sor,tar))\n if sor==tar:\n #print((sor,tar,d[2]))\n olist.append(sor)\n DG.add_node(sor)\n val_map.update({sor: 'y'})\n else:\n slist.append(sor)\n tlist.append(tar)\n DG.add_edge(sor,tar)\n val_map.update({tar: 'r',sor:'b'})\n\nprint(len(set(slist)))\nprint(len(set(tlist)))\nprint(len(set(olist)))\nvalues = [val_map.get(node, 0.25) for node in DG.nodes()]\npos = nx.spring_layout(DG,scale=2)\ndegrees = [val for (node, val) in DG.degree()]\n#print(DG.degree())\n#print(sorted(DG.degree, key=lambda x: x[1], reverse=True))\n#nx.draw(DG,pos,with_labels=True,font_size=15,node_color=values)\nnx.draw(DG,pos=graphviz_layout(DG),node_color=values)\nplt.show()\n\n\n\n\n##for i in data.iterrows():\n## s=i[1]['Source']\n## t=i[1]['Target']\n## for j in datan.iterrows():\n## if s==j[1]['Id']:\n## i[1]['Source']=j[1]['Label']\n## if t==j[1]['Id']:\n## i[1]['Target']=j[1]['Label']\n##\n## print(i)\n##\n##FG = nx.from_pandas_edgelist(data, source='Source', target='Target', edge_attr=True,)\n##print(\"Load Done\")\n###nx.draw_networkx(FG, with_labels=True)\n##nx.write_graphml(FG,\"Tweet.graphml\") \n"
] | [
[
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
qumoptly/OpenFermion | [
"9851b393698da29b63229e0f8457578ac5675a01"
] | [
"src/openfermion/utils/_reduced_hamiltonian_test.py"
] | [
"import os\nimport numpy as np\nimport openfermion as of\nfrom openfermion.config import DATA_DIRECTORY\nfrom openfermion.hamiltonians import MolecularData\nfrom openfermion.ops import InteractionOperator\nfrom openfermion.utils._reduced_hamiltonian import make_reduced_hamiltonian\n\n\ndef test_mrd_return_type():\n filename = os.path.join(DATA_DIRECTORY, \"H2_sto-3g_singlet_0.7414.hdf5\")\n molecule = MolecularData(filename=filename)\n reduced_ham = make_reduced_hamiltonian(molecule.get_molecular_hamiltonian(),\n molecule.n_electrons)\n\n assert isinstance(reduced_ham, InteractionOperator)\n\n\ndef test_constant_one_body():\n filename = os.path.join(DATA_DIRECTORY, \"H2_sto-3g_singlet_0.7414.hdf5\")\n molecule = MolecularData(filename=filename)\n reduced_ham = make_reduced_hamiltonian(molecule.get_molecular_hamiltonian(),\n molecule.n_electrons)\n\n assert np.isclose(reduced_ham.constant, molecule.nuclear_repulsion)\n assert np.allclose(reduced_ham.one_body_tensor, 0)\n\n\ndef test_fci_energy():\n filename = os.path.join(DATA_DIRECTORY, \"H2_sto-3g_singlet_0.7414.hdf5\")\n molecule = MolecularData(filename=filename)\n reduced_ham = make_reduced_hamiltonian(molecule.get_molecular_hamiltonian(),\n molecule.n_electrons)\n np_ham = of.get_number_preserving_sparse_operator(\n of.get_fermion_operator(reduced_ham),\n molecule.n_qubits,\n num_electrons=molecule.n_electrons,\n spin_preserving=True)\n\n w, _ = np.linalg.eigh(np_ham.toarray())\n assert np.isclose(molecule.fci_energy, w[0])\n\n filename = os.path.join(DATA_DIRECTORY, \"H1-Li1_sto-3g_singlet_1.45.hdf5\")\n molecule = MolecularData(filename=filename)\n reduced_ham = make_reduced_hamiltonian(molecule.get_molecular_hamiltonian(),\n molecule.n_electrons)\n np_ham = of.get_number_preserving_sparse_operator(\n of.get_fermion_operator(reduced_ham),\n molecule.n_qubits,\n num_electrons=molecule.n_electrons,\n spin_preserving=True)\n\n w, _ = np.linalg.eigh(np_ham.toarray())\n assert np.isclose(molecule.fci_energy, w[0])\n"
] | [
[
"numpy.allclose",
"numpy.isclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cresset-group/forcebalance | [
"78a48d0e9ee9b5a8f3295cee8a811ad4cfcd2aa6"
] | [
"src/lipid.py"
] | [
"\"\"\" @package forcebalance.lipid Matching of lipid bulk properties. Under development.\n\nauthor Lee-Ping Wang\n@date 04/2012\n\"\"\"\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom builtins import str\nfrom builtins import zip\nfrom builtins import map\nfrom builtins import range\nimport abc\nimport os\nimport shutil\nfrom forcebalance.finite_difference import *\nfrom forcebalance.nifty import *\nfrom forcebalance.nifty import _exec\nfrom forcebalance.target import Target\nimport numpy as np\nfrom forcebalance.molecule import Molecule\nfrom re import match, sub\nimport subprocess\nfrom subprocess import PIPE\ntry:\n from lxml import etree\nexcept: pass\nfrom pymbar import pymbar\nimport itertools\nfrom collections import defaultdict, namedtuple, OrderedDict\nimport csv\nimport copy\n\nfrom forcebalance.output import getLogger\nlogger = getLogger(__name__)\n\ndef weight_info(W, PT, N_k, verbose=True):\n C = []\n N = 0\n W += 1.0e-300\n I = np.exp(-1*np.sum((W*np.log(W))))\n for ns in N_k:\n C.append(sum(W[N:N+ns]))\n N += ns\n C = np.array(C)\n if verbose:\n logger.info(\"MBAR Results for Phase Point %s, Box, Contributions:\\n\" % str(PT))\n logger.info(str(C) + '\\n')\n logger.info(\"InfoContent: % .2f snapshots (%.2f %%)\\n\" % (I, 100*I/len(W)))\n return C\n\n# NPT_Trajectory = namedtuple('NPT_Trajectory', ['fnm', 'Rhos', 'pVs', 'Energies', 'Grads', 'mEnergies', 'mGrads', 'Rho_errs', 'Hvap_errs'])\n\nclass Lipid(Target):\n \n \"\"\" Subclass of Target for lipid property matching.\"\"\"\n\n def __init__(self,options,tgt_opts,forcefield):\n # Initialize base class\n super(Lipid,self).__init__(options,tgt_opts,forcefield)\n # Weight of the density\n self.set_option(tgt_opts,'w_rho',forceprint=True)\n # Weight of the thermal expansion coefficient\n self.set_option(tgt_opts,'w_alpha',forceprint=True)\n # Weight of the isothermal compressibility\n self.set_option(tgt_opts,'w_kappa',forceprint=True)\n # Weight of the isobaric heat capacity\n self.set_option(tgt_opts,'w_cp',forceprint=True)\n # Weight of the dielectric constant\n self.set_option(tgt_opts,'w_eps0',forceprint=True)\n # Weight of the area per lipid\n self.set_option(tgt_opts,'w_al',forceprint=True)\n # Weight of the bilayer isothermal compressibility\n self.set_option(tgt_opts,'w_lkappa',forceprint=True)\n # Weight of the deuterium order parameter\n self.set_option(tgt_opts,'w_scd',forceprint=True)\n # Normalize the property contributions to the objective function\n self.set_option(tgt_opts,'w_normalize',forceprint=True)\n # Optionally pause on the zeroth step\n self.set_option(tgt_opts,'manual')\n # Number of time steps in the lipid \"equilibration\" run\n self.set_option(tgt_opts,'lipid_eq_steps',forceprint=True)\n # Number of time steps in the lipid \"production\" run\n self.set_option(tgt_opts,'lipid_md_steps',forceprint=True)\n # Number of time steps in the gas \"equilibration\" run\n self.set_option(tgt_opts,'gas_eq_steps',forceprint=False)\n # Number of time steps in the gas \"production\" run\n self.set_option(tgt_opts,'gas_md_steps',forceprint=False)\n # Cutoff for nonbonded interactions in the liquid\n if tgt_opts['nonbonded_cutoff'] is not None:\n self.set_option(tgt_opts,'nonbonded_cutoff')\n # Cutoff for vdW interactions if different from other nonbonded interactions\n if tgt_opts['vdw_cutoff'] is not None:\n self.set_option(tgt_opts,'vdw_cutoff')\n # Time step length (in fs) for the lipid production run\n self.set_option(tgt_opts,'lipid_timestep',forceprint=True)\n # Time interval (in ps) for writing coordinates\n self.set_option(tgt_opts,'lipid_interval',forceprint=True)\n # Time step length (in fs) for the gas production run\n self.set_option(tgt_opts,'gas_timestep',forceprint=True)\n # Time interval (in ps) for writing coordinates\n self.set_option(tgt_opts,'gas_interval',forceprint=True)\n # Minimize the energy prior to running any dynamics\n self.set_option(tgt_opts,'minimize_energy',forceprint=True)\n # Isolated dipole (debye) for analytic self-polarization correction.\n self.set_option(tgt_opts,'self_pol_mu0',forceprint=True)\n # Molecular polarizability (ang**3) for analytic self-polarization correction.\n self.set_option(tgt_opts,'self_pol_alpha',forceprint=True)\n # Set up the simulation object for self-polarization correction.\n self.do_self_pol = (self.self_pol_mu0 > 0.0 and self.self_pol_alpha > 0.0)\n # Enable anisotropic periodic box\n self.set_option(tgt_opts,'anisotropic_box',forceprint=True)\n # Whether to save trajectories (0 = never, 1 = delete after good step, 2 = keep all)\n self.set_option(tgt_opts,'save_traj')\n\n #======================================#\n # Variables which are set here #\n #======================================#\n ## LPW 2018-02-11: This is set to True if the target calculates\n ## a single-point property over several existing snapshots.\n self.loop_over_snapshots = False\n # List of trajectory files that may be deleted if self.save_traj == 1.\n self.last_traj = []\n # Extra files to be copied back at the end of a run.\n self.extra_output = []\n # Read the reference data\n self.read_data()\n # Read in lipid starting coordinates.\n if 'n_ic' in self.RefData:\n # Linked IC folder into the temp-directory.\n self.nptfiles += [\"IC\"]\n # Store IC frames in a dictionary.\n self.lipid_mols = OrderedDict()\n self.lipid_mols_new = OrderedDict()\n for pt in self.PhasePoints:\n pt_label = \"IC/%sK-%s%s\" % (pt[0], pt[1], pt[2])\n if not os.path.exists(os.path.join(self.root, self.tgtdir, pt_label, self.lipid_coords)):\n raise RuntimeError(\"Initial condition files don't exist; please provide IC directory\")\n # Create molecule object for each IC.\n all_ic = Molecule(os.path.join(self.root, self.tgtdir, pt_label, self.lipid_coords))\n self.lipid_mols[pt] = []\n n_uniq_ic = int(self.RefData['n_ic'][pt])\n if n_uniq_ic > len(all_ic):\n raise RuntimeError(\"Number of frames in initial conditions .gro file is less than the number of parallel simulations requested in data.csv\")\n # Index ICs by pressure and temperature in a dictionary.\n for ic in range(n_uniq_ic):\n self.lipid_mols[pt].append(all_ic[ic])\n else:\n # Read in lipid starting coordinates.\n if not os.path.exists(os.path.join(self.root, self.tgtdir, self.lipid_coords)): \n logger.error(\"%s doesn't exist; please provide lipid_coords option\\n\" % self.lipid_coords)\n raise RuntimeError\n self.lipid_mol = Molecule(os.path.join(self.root, self.tgtdir, self.lipid_coords), toppbc=True)\n # Extra files to be linked into the temp-directory.\n self.nptfiles += [self.lipid_coords]\n # Scripts to be copied from the ForceBalance installation directory.\n self.scripts += ['npt_lipid.py']\n # Prepare the temporary directory.\n self.prepare_temp_directory()\n # Build keyword dictionary to pass to engine.\n if self.do_self_pol:\n self.gas_engine_args.update(self.OptionDict)\n self.gas_engine_args.update(options)\n del self.gas_engine_args['name']\n # Create engine object for gas molecule to do the polarization correction.\n self.gas_engine = self.engine_(target=self, mol=self.gas_mol, name=\"selfpol\", **self.gas_engine_args)\n # Don't read indicate.log when calling meta_indicate()\n self.read_indicate = False\n self.write_indicate = False\n # Don't read objective.p when calling meta_get()\n self.read_objective = False\n #======================================#\n # UNDER DEVELOPMENT #\n #======================================#\n # Put stuff here that I'm not sure about. :)\n np.set_printoptions(precision=4, linewidth=100)\n np.seterr(under='ignore')\n ## Saved force field mvals for all iterations\n self.SavedMVal = {}\n ## Saved trajectories for all iterations and all temperatures\n self.SavedTraj = defaultdict(dict)\n ## Evaluated energies for all trajectories (i.e. all iterations and all temperatures), using all mvals\n self.MBarEnergy = defaultdict(lambda:defaultdict(dict))\n\n def prepare_temp_directory(self):\n \"\"\" Prepare the temporary directory by copying in important files. \"\"\"\n abstempdir = os.path.join(self.root,self.tempdir)\n for f in self.nptfiles:\n LinkFile(os.path.join(self.root, self.tgtdir, f), os.path.join(abstempdir, f))\n for f in self.scripts:\n LinkFile(os.path.join(os.path.split(__file__)[0],\"data\",f),os.path.join(abstempdir,f))\n\n def read_data(self):\n # Read the 'data.csv' file. The file should contain guidelines.\n with open(os.path.join(self.tgtdir,'data.csv'),'r') as f: R0 = list(csv.reader(f))\n # All comments are erased.\n R1 = [[sub('#.*$','',word) for word in line] for line in R0 if len(line[0]) > 0 and line[0][0] != \"#\"]\n # All empty lines are deleted and words are converted to lowercase.\n R = [[wrd.lower() for wrd in line] for line in R1 if any([len(wrd) for wrd in line]) > 0]\n global_opts = OrderedDict()\n found_headings = False\n known_vars = ['mbar','rho','hvap','alpha','kappa','cp','eps0','cvib_intra',\n 'cvib_inter','cni','devib_intra','devib_inter', 'al', 'scd', 'n_ic', 'lkappa']\n self.RefData = OrderedDict()\n for line in R:\n if line[0] == \"global\":\n # Global options are mainly denominators for the different observables.\n if isfloat(line[2]):\n global_opts[line[1]] = float(line[2])\n elif line[2].lower() == 'false':\n global_opts[line[1]] = False\n elif line[2].lower() == 'true':\n global_opts[line[1]] = True\n elif not found_headings:\n found_headings = True\n headings = line\n if len(set(headings)) != len(headings):\n logger.error('Column headings in data.csv must be unique\\n')\n raise RuntimeError\n if 'p' not in headings:\n logger.error('There must be a pressure column heading labeled by \"p\" in data.csv\\n')\n raise RuntimeError\n if 't' not in headings:\n logger.error('There must be a temperature column heading labeled by \"t\" in data.csv\\n')\n raise RuntimeError\n elif found_headings:\n try:\n # Temperatures are in kelvin.\n t = [float(val) for head, val in zip(headings,line) if head == 't'][0]\n # For convenience, users may input the pressure in atmosphere or bar.\n pval = [float(val.split()[0]) for head, val in zip(headings,line) if head == 'p'][0]\n punit = [val.split()[1] if len(val.split()) >= 1 else \"atm\" for head, val in zip(headings,line) if head == 'p'][0]\n unrec = set([punit]).difference(['atm','bar']) \n if len(unrec) > 0:\n logger.error('The pressure unit %s is not recognized, please use bar or atm\\n' % unrec[0])\n raise RuntimeError\n # This line actually reads the reference data and inserts it into the RefData dictionary of dictionaries.\n for head, val in zip(headings,line):\n if head == 't' or head == 'p' : continue\n if isfloat(val):\n self.RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] = float(val.strip())\n elif val.lower() == 'true':\n self.RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] = True\n elif val.lower() == 'false':\n self.RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] = False\n elif head == 'scd':\n self.RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] = np.array(list(map(float, val.split())))\n except:\n logger.error(line + '\\n')\n logger.error('Encountered an error reading this line!\\n')\n raise RuntimeError\n else:\n logger.error(line + '\\n')\n logger.error('I did not recognize this line!\\n')\n raise RuntimeError\n # Check the reference data table for validity.\n default_denoms = defaultdict(int)\n PhasePoints = None\n RefData_copy = copy.deepcopy(self.RefData)\n for head in self.RefData:\n if head == 'n_ic':\n continue\n if head not in known_vars+[i+\"_wt\" for i in known_vars]:\n # Only hard-coded properties may be recognized.\n logger.error(\"The column heading %s is not recognized in data.csv\\n\" % head)\n raise RuntimeError\n if head in known_vars:\n if head+\"_wt\" not in self.RefData:\n # If the phase-point weights are not specified in the reference data file, initialize them all to one.\n RefData_copy[head+\"_wt\"] = OrderedDict([(key, 1.0) for key in self.RefData[head]])\n wts = np.array(list(RefData_copy[head+\"_wt\"].values()))\n dat = np.array(list(self.RefData[head].values()))\n # S_cd specifies an array of averages (one for each tail node). Find avg over axis 0.\n avg = np.average(dat, weights=wts, axis=0)\n if len(wts) > 1:\n # If there is more than one data point, then the default denominator is the\n # standard deviation of the experimental values.\n if head == 'scd':\n default_denoms[head+\"_denom\"] = np.average(np.sqrt(np.dot(wts, (dat-avg)**2)/wts.sum()))\n else:\n default_denoms[head+\"_denom\"] = np.sqrt(np.dot(wts, (dat-avg)**2)/wts.sum())\n else:\n # If there is only one data point, then the denominator is just the single\n # data point itself.\n if head == 'scd':\n default_denoms[head+\"_denom\"] = np.average(np.sqrt(np.abs(dat[0])))\n else:\n default_denoms[head+\"_denom\"] = np.sqrt(np.abs(dat[0]))\n self.PhasePoints = list(self.RefData[head].keys())\n # This prints out all of the reference data.\n # printcool_dictionary(self.RefData[head],head)\n self.RefData = RefData_copy\n # Create labels for the directories.\n self.Labels = [\"%.2fK-%.1f%s\" % i for i in self.PhasePoints]\n logger.debug(\"global_opts:\\n%s\\n\" % str(global_opts))\n logger.debug(\"default_denoms:\\n%s\\n\" % str(default_denoms))\n for opt in global_opts:\n if \"_denom\" in opt:\n # Record entries from the global_opts dictionary so they can be retrieved from other methods.\n self.set_option(global_opts,opt,default=default_denoms[opt])\n else:\n self.set_option(global_opts,opt)\n\n def check_files(self, there):\n there = os.path.abspath(there)\n havepts = 0\n if all([i in os.listdir(there) for i in self.Labels]):\n for d in os.listdir(there):\n if d in self.Labels:\n if os.path.exists(os.path.join(there, d, 'npt_result.p')):\n havepts += 1\n if (float(havepts)/len(self.Labels)) > 0.75:\n return 1\n else:\n return 0\n def npt_simulation(self, temperature, pressure, simnum):\n \"\"\" Submit a NPT simulation to the Work Queue. \"\"\"\n wq = getWorkQueue()\n if not os.path.exists('npt_result.p'):\n link_dir_contents(os.path.join(self.root,self.rundir),os.getcwd())\n self.last_traj += [os.path.join(os.getcwd(), i) for i in self.extra_output]\n self.lipid_mol[simnum%len(self.lipid_mol)].write(self.lipid_coords, ftype='tinker' if self.engname == 'tinker' else None)\n cmdstr = '%s python npt_lipid.py %s %.3f %.3f' % (self.nptpfx, self.engname, temperature, pressure)\n if wq is None:\n logger.info(\"Running condensed phase simulation locally.\\n\")\n logger.info(\"You may tail -f %s/npt.out in another terminal window\\n\" % os.getcwd())\n _exec(cmdstr, copy_stderr=True, outfnm='npt.out')\n else:\n queue_up(wq, command = cmdstr+' &> npt.out',\n input_files = self.nptfiles + self.scripts + ['forcebalance.p'],\n output_files = ['npt_result.p', 'npt.out'] + self.extra_output, tgt=self)\n\n def polarization_correction(self,mvals):\n d = self.gas_engine.get_multipole_moments(optimize=True)['dipole']\n if not in_fd():\n logger.info(\"The molecular dipole moment is % .3f debye\\n\" % np.linalg.norm(d))\n # Taken from the original OpenMM interface code, this is how we calculate the conversion factor.\n # dd2 = ((np.linalg.norm(d)-self.self_pol_mu0)*debye)**2\n # eps0 = 8.854187817620e-12 * coulomb**2 / newton / meter**2\n # epol = 0.5*dd2/(self.self_pol_alpha*angstrom**3*4*np.pi*eps0)/(kilojoule_per_mole/AVOGADRO_CONSTANT_NA)\n # In [2]: eps0 = 8.854187817620e-12 * coulomb**2 / newton / meter**2\n # In [7]: 1.0 * debye ** 2 / (1.0 * angstrom**3*4*np.pi*eps0) / (kilojoule_per_mole/AVOGADRO_CONSTANT_NA)\n # Out[7]: 60.240179789402056\n convert = 60.240179789402056\n dd2 = (np.linalg.norm(d)-self.self_pol_mu0)**2\n epol = 0.5*convert*dd2/self.self_pol_alpha\n return epol\n\n def indicate(self): \n AGrad = hasattr(self, 'Gp')\n PrintDict = OrderedDict()\n def print_item(key, heading, physunit):\n if self.Xp[key] > 0:\n printcool_dictionary(self.Pp[key], title='%s %s%s\\nTemperature Pressure Reference Calculated +- Stdev Delta Weight Term ' % \n (self.name, heading, \" (%s) \" % physunit if physunit else \"\"), bold=True, color=4, keywidth=15)\n bar = printcool(\"%s objective function: % .3f%s\" % (heading, self.Xp[key], \", Derivative:\" if AGrad else \"\"))\n if AGrad:\n self.FF.print_map(vals=self.Gp[key])\n logger.info(bar)\n PrintDict[heading] = \"% 10.5f % 8.3f % 14.5e\" % (self.Xp[key], self.Wp[key], self.Xp[key]*self.Wp[key])\n\n print_item(\"Rho\", \"Density\", \"kg m^-3\")\n print_item(\"Alpha\", \"Thermal Expansion Coefficient\", \"10^-4 K^-1\")\n print_item(\"Kappa\", \"Isothermal Compressibility\", \"10^-6 bar^-1\")\n print_item(\"Cp\", \"Isobaric Heat Capacity\", \"cal mol^-1 K^-1\")\n print_item(\"Eps0\", \"Dielectric Constant\", None)\n print_item(\"Al\", \"Average Area per Lipid\", \"nm^2\")\n print_item(\"Scd\", \"Deuterium Order Parameter\", None)\n print_item(\"LKappa\", \"Bilayer Isothermal Compressibility\", \"mN/m\")\n\n PrintDict['Total'] = \"% 10s % 8s % 14.5e\" % (\"\",\"\",self.Objective)\n\n Title = \"%s Condensed Phase Properties:\\n %-20s %40s\" % (self.name, \"Property Name\", \"Residual x Weight = Contribution\")\n printcool_dictionary(PrintDict,color=4,title=Title,keywidth=31)\n return\n\n def objective_term(self, points, expname, calc, err, grad, name=\"Quantity\", SubAverage=False):\n if expname in self.RefData:\n exp = self.RefData[expname]\n Weights = self.RefData[expname+\"_wt\"]\n Denom = getattr(self,expname+\"_denom\")\n else:\n # If the reference data doesn't exist then return nothing.\n return 0.0, np.zeros(self.FF.np), np.zeros((self.FF.np,self.FF.np)), None\n \n Sum = sum(Weights.values())\n for i in Weights:\n Weights[i] /= Sum\n logger.info(\"Weights have been renormalized to \" + str(sum(Weights.values())) + \"\\n\")\n # Use least-squares or hyperbolic (experimental) objective.\n LeastSquares = True\n\n logger.info(\"Physical quantity %s uses denominator = % .4f\\n\" % (name, Denom))\n if not LeastSquares:\n # If using a hyperbolic functional form\n # we still want the contribution to the \n # objective function to be the same when\n # Delta = Denom.\n Denom /= 3 ** 0.5\n \n Objective = 0.0\n Gradient = np.zeros(self.FF.np)\n Hessian = np.zeros((self.FF.np,self.FF.np))\n Objs = {}\n GradMap = []\n avgCalc = 0.0\n avgExp = 0.0\n avgGrad = np.zeros(self.FF.np)\n for i, PT in enumerate(points):\n avgCalc += Weights[PT]*calc[PT]\n avgExp += Weights[PT]*exp[PT]\n avgGrad += Weights[PT]*grad[PT]\n for i, PT in enumerate(points):\n if SubAverage:\n G = grad[PT]-avgGrad\n Delta = calc[PT] - exp[PT] - avgCalc + avgExp\n else:\n G = grad[PT]\n Delta = calc[PT] - exp[PT]\n if hasattr(Delta, \"__len__\"):\n Delta = np.average(Delta)\n if LeastSquares:\n # Least-squares objective function.\n ThisObj = Weights[PT] * Delta ** 2 / Denom**2\n Objs[PT] = ThisObj\n ThisGrad = 2.0 * Weights[PT] * Delta * G / Denom**2\n GradMap.append(G)\n Objective += ThisObj\n Gradient += ThisGrad\n # Gauss-Newton approximation to the Hessian.\n Hessian += 2.0 * Weights[PT] * (np.outer(G, G)) / Denom**2\n else:\n # L1-like objective function.\n D = Denom\n S = Delta**2 + D**2\n ThisObj = Weights[PT] * (S**0.5-D) / Denom\n ThisGrad = Weights[PT] * (Delta/S**0.5) * G / Denom\n ThisHess = Weights[PT] * (1/S**0.5-Delta**2/S**1.5) * np.outer(G,G) / Denom\n Objs[PT] = ThisObj\n GradMap.append(G)\n Objective += ThisObj\n Gradient += ThisGrad\n Hessian += ThisHess\n GradMapPrint = [[\"#PhasePoint\"] + self.FF.plist]\n for PT, g in zip(points,GradMap):\n GradMapPrint.append([' %8.2f %8.1f %3s' % PT] + [\"% 9.3e\" % i for i in g])\n o = wopen('gradient_%s.dat' % name)\n for line in GradMapPrint:\n print(' '.join(line), file=o)\n o.close()\n \n Delta = np.array([calc[PT] - exp[PT] for PT in points])\n delt = {PT : r for PT, r in zip(points,Delta)}\n if expname == 'scd': \n print_out = OrderedDict([(' %8.2f %8.1f %3s' % PT, '\\n %s' % (' '.join('\\t \\t \\t %9.6f %9.6f +- %-7.6f % 7.6f \\n' % F for F in zip(exp[PT], calc[PT], flat(err[PT]), delt[PT])))) for PT in calc])\n else:\n print_out = OrderedDict([(' %8.2f %8.1f %3s' % PT, \"%9.3f %9.3f +- %-7.3f % 7.3f % 9.5f % 9.5f\" % (exp[PT],calc[PT],err[PT],delt[PT],Weights[PT],Objs[PT])) for PT in calc])\n\n return Objective, Gradient, Hessian, print_out\n\n def submit_jobs(self, mvals, AGrad=True, AHess=True):\n # This routine is called by Objective.stage() will run before \"get\".\n # It submits the jobs to the Work Queue and the stage() function will wait for jobs to complete.\n #\n # First dump the force field to a pickle file\n lp_dump((self.FF,mvals,self.OptionDict,AGrad),'forcebalance.p')\n\n # Give the user an opportunity to copy over data from a previous (perhaps failed) run.\n if (not self.evaluated) and self.manual:\n warn_press_key(\"Now's our chance to fill the temp directory up with data!\\n(Considering using 'read' or 'continue' for better checkpointing)\", timeout=7200)\n\n # If self.save_traj == 1, delete the trajectory files from a previous good optimization step.\n if self.evaluated and self.goodstep and self.save_traj < 2:\n for fn in self.last_traj:\n if os.path.exists(fn):\n os.remove(fn)\n self.last_traj = []\n\n # Set up and run the NPT simulations.\n snum = 0\n for label, pt in zip(self.Labels, self.PhasePoints):\n T = pt[0]\n P = pt[1]\n Punit = pt[2]\n if Punit == 'bar':\n P *= 1.0 / 1.01325\n if not os.path.exists(label):\n os.makedirs(label)\n os.chdir(label)\n if 'n_ic' in self.RefData:\n n_uniq_ic = int(self.RefData['n_ic'][pt])\n # Loop over parallel trajectories.\n for trj in range(n_uniq_ic):\n rel_trj = \"trj_%i\" % trj\n # Create directories for each parallel simulation.\n if not os.path.exists(rel_trj):\n os.makedirs(rel_trj)\n os.chdir(rel_trj)\n # Pull each simulation molecule from the lipid_mols dictionary.\n # lipid_mols is a dictionary of paths to either the initial \n # geometry files, or the geometries from the final frame of the \n # previous iteration.\n self.lipid_mol = self.lipid_mols[pt][trj]\n self.lipid_mol.write(self.lipid_coords)\n if not self.lipid_coords in self.nptfiles:\n self.nptfiles += [self.lipid_coords]\n self.npt_simulation(T,P,snum)\n os.chdir('..')\n else:\n self.npt_simulation(T,P,snum)\n os.chdir('..')\n snum += 1\n\n def get(self, mvals, AGrad=True, AHess=True):\n \n \"\"\"\n Fitting of lipid bulk properties. This is the current major\n direction of development for ForceBalance. Basically, fitting\n the QM energies / forces alone does not always give us the\n best simulation behavior. In many cases it makes more sense\n to try and reproduce some experimentally known data as well.\n\n In order to reproduce experimentally known data, we need to\n run a simulation and compare the simulation result to\n experiment. The main challenge here is that the simulations\n are computationally intensive (i.e. they require energy and\n force evaluations), and furthermore the results are noisy. We\n need to run the simulations automatically and remotely\n (i.e. on clusters) and a good way to calculate the derivatives\n of the simulation results with respect to the parameter values.\n\n This function contains some experimentally known values of the\n density and enthalpy of vaporization (Hvap) of lipid water.\n It launches the density and Hvap calculations on the cluster,\n and gathers the results / derivatives. The actual calculation\n of results / derivatives is done in a separate file.\n\n After the results come back, they are gathered together to form\n an objective function.\n\n @param[in] mvals Mathematical parameter values\n @param[in] AGrad Switch to turn on analytic gradient\n @param[in] AHess Switch to turn on analytic Hessian\n @return Answer Contribution to the objective function\n \n \"\"\"\n\n mbar_verbose = False\n\n Answer = {}\n\n Results = {}\n Points = [] # These are the phase points for which data exists.\n BPoints = [] # These are the phase points for which we are doing MBAR for the condensed phase.\n tt = 0\n for label, PT in zip(self.Labels, self.PhasePoints):\n if 'n_ic' in self.RefData:\n self.lipid_mols[PT] = [Molecule(last_frame) for last_frame in self.lipid_mols[PT]]\n n_uniq_ic = int(self.RefData['n_ic'][PT])\n for ic in range(n_uniq_ic):\n if os.path.exists('./%s/trj_%s/npt_result.p' % (label, ic)):\n # Read in each each parallel simulation's data, and concatenate each property time series.\n ts = lp_load('./%s/trj_%s/npt_result.p' % (label, ic))\n if ic == 0:\n ts_concat = list(ts)\n else:\n for d_arr in range(len(ts)):\n if isinstance(ts[d_arr], np.ndarray):\n # Gradients need a unique append format.\n if d_arr == 5:\n ts_concat[d_arr] = np.append(ts_concat[d_arr], ts[d_arr], axis = 1)\n else:\n ts_concat[d_arr] = np.append(ts_concat[d_arr], ts[d_arr], axis = 0)\n if isinstance(ts_concat[d_arr], list):\n ts_concat[d_arr] = [np.append(ts_concat[d_arr][i], ts[d_arr][i], axis = 1) for i in range(len(ts_concat[d_arr]))]\n # Write concatenated time series to a pickle file.\n if ic == (int(n_uniq_ic) - 1):\n lp_dump((ts_concat), './%s/npt_result.p' % label)\n if os.path.exists('./%s/npt_result.p' % label):\n logger.info('Reading information from ./%s/npt_result.p\\n' % label)\n Points.append(PT)\n Results[tt] = lp_load('./%s/npt_result.p' % label)\n tt += 1\n else:\n logger.warning('The file ./%s/npt_result.p does not exist so we cannot read it\\n' % label)\n pass\n # for obs in self.RefData:\n # del self.RefData[obs][PT]\n if len(Points) == 0:\n logger.error('The lipid simulations have terminated with \\x1b[1;91mno readable data\\x1b[0m - this is a problem!\\n')\n raise RuntimeError\n\n # Assign variable names to all the stuff in npt_result.p\n Rhos, Vols, Potentials, Energies, Dips, Grads, GDips, \\\n Rho_errs, Alpha_errs, Kappa_errs, Cp_errs, Eps0_errs, NMols, Als, Al_errs, Scds, Scd_errs, LKappa_errs = ([Results[t][i] for t in range(len(Points))] for i in range(18))\n # Determine the number of molecules\n if len(set(NMols)) != 1:\n logger.error(str(NMols))\n logger.error('The above list should only contain one number - the number of molecules\\n')\n raise RuntimeError\n else:\n NMol = list(set(NMols))[0]\n \n R = np.array(list(itertools.chain(*list(Rhos))))\n V = np.array(list(itertools.chain(*list(Vols))))\n E = np.array(list(itertools.chain(*list(Energies))))\n Dx = np.array(list(itertools.chain(*list(d[:,0] for d in Dips))))\n Dy = np.array(list(itertools.chain(*list(d[:,1] for d in Dips))))\n Dz = np.array(list(itertools.chain(*list(d[:,2] for d in Dips))))\n G = np.hstack(tuple(Grads))\n GDx = np.hstack(tuple(gd[0] for gd in GDips))\n GDy = np.hstack(tuple(gd[1] for gd in GDips))\n GDz = np.hstack(tuple(gd[2] for gd in GDips))\n A = np.array(list(itertools.chain(*list(Als))))\n S = np.array(list(itertools.chain(*list(Scds))))\n\n Rho_calc = OrderedDict([])\n Rho_grad = OrderedDict([])\n Rho_std = OrderedDict([])\n Alpha_calc = OrderedDict([])\n Alpha_grad = OrderedDict([])\n Alpha_std = OrderedDict([])\n Kappa_calc = OrderedDict([])\n Kappa_grad = OrderedDict([])\n Kappa_std = OrderedDict([])\n Cp_calc = OrderedDict([])\n Cp_grad = OrderedDict([])\n Cp_std = OrderedDict([])\n Eps0_calc = OrderedDict([])\n Eps0_grad = OrderedDict([])\n Eps0_std = OrderedDict([])\n Al_calc = OrderedDict([])\n Al_grad = OrderedDict([])\n Al_std = OrderedDict([])\n LKappa_calc = OrderedDict([])\n LKappa_grad = OrderedDict([])\n LKappa_std = OrderedDict([])\n Scd_calc = OrderedDict([])\n Scd_grad = OrderedDict([])\n Scd_std = OrderedDict([])\n\n # The unit that converts atmospheres * nm**3 into kj/mol :)\n pvkj=0.061019351687175\n \n # Run MBAR using the total energies. Required for estimates that use the kinetic energy.\n BSims = len(BPoints)\n Shots = len(Energies[0])\n Shots_m = [len(i) for i in Energies]\n N_k = np.ones(BSims)*Shots\n # Use the value of the energy for snapshot t from simulation k at potential m\n U_kln = np.zeros([BSims,BSims,Shots])\n for m, PT in enumerate(BPoints):\n T = PT[0]\n P = PT[1] / 1.01325 if PT[2] == 'bar' else PT[1]\n beta = 1. / (kb * T)\n for k in range(BSims):\n # The correct Boltzmann factors include PV.\n # Note that because the Boltzmann factors are computed from the conditions at simulation \"m\",\n # the pV terms must be rescaled to the pressure at simulation \"m\".\n kk = Points.index(BPoints[k])\n U_kln[k, m, :] = Energies[kk] + P*Vols[kk]*pvkj\n U_kln[k, m, :] *= beta\n W1 = None\n if len(BPoints) > 1:\n logger.info(\"Running MBAR analysis on %i states...\\n\" % len(BPoints))\n mbar = pymbar.MBAR(U_kln, N_k, verbose=mbar_verbose, relative_tolerance=5.0e-8)\n W1 = mbar.getWeights()\n logger.info(\"Done\\n\")\n elif len(BPoints) == 1:\n W1 = np.ones((BPoints*Shots,BPoints))\n W1 /= BPoints*Shots\n \n def fill_weights(weights, phase_points, mbar_points, snapshots):\n \"\"\" Fill in the weight matrix with MBAR weights where MBAR was run, \n and equal weights otherwise. \"\"\"\n new_weights = np.zeros([len(phase_points)*snapshots,len(phase_points)])\n for m, PT in enumerate(phase_points):\n if PT in mbar_points:\n mm = mbar_points.index(PT)\n for kk, PT1 in enumerate(mbar_points):\n k = phase_points.index(PT1)\n logger.debug(\"Will fill W2[%i:%i,%i] with W1[%i:%i,%i]\\n\" % (k*snapshots,k*snapshots+snapshots,m,kk*snapshots,kk*snapshots+snapshots,mm))\n new_weights[k*snapshots:(k+1)*snapshots,m] = weights[kk*snapshots:(kk+1)*snapshots,mm]\n else:\n logger.debug(\"Will fill W2[%i:%i,%i] with equal weights\\n\" % (m*snapshots,(m+1)*snapshots,m))\n new_weights[m*snapshots:(m+1)*snapshots,m] = 1.0/snapshots\n return new_weights\n \n W2 = fill_weights(W1, Points, BPoints, Shots)\n\n if self.do_self_pol:\n EPol = self.polarization_correction(mvals)\n GEPol = np.array([(f12d3p(fdwrap(self.polarization_correction, mvals, p), h = self.h, f0 = EPol)[0] if p in self.pgrad else 0.0) for p in range(self.FF.np)])\n bar = printcool(\"Self-polarization correction to \\nenthalpy of vaporization is % .3f kJ/mol%s\" % (EPol, \", Derivative:\" if AGrad else \"\"))\n if AGrad:\n self.FF.print_map(vals=GEPol)\n logger.info(bar)\n \n for i, PT in enumerate(Points):\n T = PT[0]\n P = PT[1] / 1.01325 if PT[2] == 'bar' else PT[1]\n PV = P*V*pvkj\n H = E + PV\n # The weights that we want are the last ones.\n W = flat(W2[:,i])\n C = weight_info(W, PT, np.ones(len(Points), dtype=int)*Shots, verbose=mbar_verbose)\n Gbar = flat(np.dot(G,col(W)))\n mBeta = -1/kb/T\n Beta = 1/kb/T\n kT = kb*T\n # Define some things to make the analytic derivatives easier.\n def avg(vec):\n return np.dot(W,vec)\n def covde(vec):\n return flat(np.dot(G,col(W*vec))) - avg(vec)*Gbar\n def deprod(vec):\n return flat(np.dot(G,col(W*vec)))\n ## Density.\n Rho_calc[PT] = np.dot(W,R)\n Rho_grad[PT] = mBeta*(flat(np.dot(G,col(W*R))) - np.dot(W,R)*Gbar)\n ## Ignore enthalpy.\n ## Thermal expansion coefficient.\n Alpha_calc[PT] = 1e4 * (avg(H*V)-avg(H)*avg(V))/avg(V)/(kT*T)\n GAlpha1 = -1 * Beta * deprod(H*V) * avg(V) / avg(V)**2\n GAlpha2 = +1 * Beta * avg(H*V) * deprod(V) / avg(V)**2\n GAlpha3 = deprod(V)/avg(V) - Gbar\n GAlpha4 = Beta * covde(H)\n Alpha_grad[PT] = 1e4 * (GAlpha1 + GAlpha2 + GAlpha3 + GAlpha4)/(kT*T)\n ## Isothermal compressibility.\n bar_unit = 0.06022141793 * 1e6\n Kappa_calc[PT] = bar_unit / kT * (avg(V**2)-avg(V)**2)/avg(V)\n GKappa1 = +1 * Beta**2 * avg(V**2) * deprod(V) / avg(V)**2\n GKappa2 = -1 * Beta**2 * avg(V) * deprod(V**2) / avg(V)**2\n GKappa3 = +1 * Beta**2 * covde(V)\n Kappa_grad[PT] = bar_unit*(GKappa1 + GKappa2 + GKappa3)\n ## Isobaric heat capacity.\n Cp_calc[PT] = 1000/(4.184*NMol*kT*T) * (avg(H**2) - avg(H)**2)\n if hasattr(self,'use_cvib_intra') and self.use_cvib_intra:\n logger.debug(\"Adding \" + str(self.RefData['devib_intra'][PT]) + \" to the heat capacity\\n\")\n Cp_calc[PT] += self.RefData['devib_intra'][PT]\n if hasattr(self,'use_cvib_inter') and self.use_cvib_inter:\n logger.debug(\"Adding \" + str(self.RefData['devib_inter'][PT]) + \" to the heat capacity\\n\")\n Cp_calc[PT] += self.RefData['devib_inter'][PT]\n GCp1 = 2*covde(H) * 1000 / 4.184 / (NMol*kT*T)\n GCp2 = mBeta*covde(H**2) * 1000 / 4.184 / (NMol*kT*T)\n GCp3 = 2*Beta*avg(H)*covde(H) * 1000 / 4.184 / (NMol*kT*T)\n Cp_grad[PT] = GCp1 + GCp2 + GCp3\n ## Static dielectric constant.\n prefactor = 30.348705333964077\n D2 = avg(Dx**2)+avg(Dy**2)+avg(Dz**2)-avg(Dx)**2-avg(Dy)**2-avg(Dz)**2\n Eps0_calc[PT] = 1.0 + prefactor*(D2/avg(V))/T\n GD2 = 2*(flat(np.dot(GDx,col(W*Dx))) - avg(Dx)*flat(np.dot(GDx,col(W)))) - Beta*(covde(Dx**2) - 2*avg(Dx)*covde(Dx))\n GD2 += 2*(flat(np.dot(GDy,col(W*Dy))) - avg(Dy)*flat(np.dot(GDy,col(W)))) - Beta*(covde(Dy**2) - 2*avg(Dy)*covde(Dy))\n GD2 += 2*(flat(np.dot(GDz,col(W*Dz))) - avg(Dz)*flat(np.dot(GDz,col(W)))) - Beta*(covde(Dz**2) - 2*avg(Dz)*covde(Dz))\n Eps0_grad[PT] = prefactor*(GD2/avg(V) - mBeta*covde(V)*D2/avg(V)**2)/T\n ## Average area per lipid\n Al_calc[PT] = np.dot(W,A)\n Al_grad[PT] = mBeta*(flat(np.dot(G,col(W*A))) - np.dot(W,A)*Gbar)\n ## Bilayer Isothermal compressibility.\n A_m2 = A * 1e-18\n kbT = 1.3806488e-23 * T\n LKappa_calc[PT] = (1e3 * 2 * kbT / 128) * (avg(A_m2) / (avg(A_m2**2)-avg(A_m2)**2))\n al_avg = avg(A_m2)\n al_sq_avg = avg(A_m2**2)\n al_avg_sq = al_avg**2\n al_var = al_sq_avg - al_avg_sq\n GLKappa1 = covde(A_m2) / al_var\n GLKappa2 = (al_avg / al_var**2) * (covde(A_m2**2) - (2 * al_avg * covde(A)))\n LKappa_grad[PT] = (1e3 * 2 * kbT / 128) * (GLKappa1 - GLKappa2)\n ## Deuterium order parameter\n Scd_calc[PT] = np.dot(W,S)\n # LPW: In case I did not do the conversion correctly, the line of code previously here was:\n # Scd_grad[PT] = mBeta * (flat(np.average(np.mat(G) * (S * W[:, np.newaxis]), axis = 1)) - np.average(np.average(S * W[:, np.newaxis], axis = 0), axis = 0) * Gbar) \n Scd_grad[PT] = mBeta * (flat(np.average(np.dot(G, (S * W[:, np.newaxis])), axis = 1)) - np.average(np.average(S * W[:, np.newaxis], axis = 0), axis = 0) * Gbar) \n ## Estimation of errors.\n Rho_std[PT] = np.sqrt(sum(C**2 * np.array(Rho_errs)**2))\n Alpha_std[PT] = np.sqrt(sum(C**2 * np.array(Alpha_errs)**2)) * 1e4\n Kappa_std[PT] = np.sqrt(sum(C**2 * np.array(Kappa_errs)**2)) * 1e6\n Cp_std[PT] = np.sqrt(sum(C**2 * np.array(Cp_errs)**2))\n Eps0_std[PT] = np.sqrt(sum(C**2 * np.array(Eps0_errs)**2))\n Al_std[PT] = np.sqrt(sum(C**2 * np.array(Al_errs)**2))\n # LPW: In case I did not do the conversion correctly, the line of code previously here was:\n # Scd_std[PT] = np.sqrt(sum(np.mat(C**2) * np.array(Scd_errs)**2))\n Scd_std[PT] = np.sqrt(sum(np.dot(row(C**2), np.array(Scd_errs)**2)))\n LKappa_std[PT] = np.sqrt(sum(C**2 * np.array(LKappa_errs)**2)) * 1e6\n\n # Get contributions to the objective function\n X_Rho, G_Rho, H_Rho, RhoPrint = self.objective_term(Points, 'rho', Rho_calc, Rho_std, Rho_grad, name=\"Density\")\n X_Alpha, G_Alpha, H_Alpha, AlphaPrint = self.objective_term(Points, 'alpha', Alpha_calc, Alpha_std, Alpha_grad, name=\"Thermal Expansion\")\n X_Kappa, G_Kappa, H_Kappa, KappaPrint = self.objective_term(Points, 'kappa', Kappa_calc, Kappa_std, Kappa_grad, name=\"Compressibility\")\n X_Cp, G_Cp, H_Cp, CpPrint = self.objective_term(Points, 'cp', Cp_calc, Cp_std, Cp_grad, name=\"Heat Capacity\")\n X_Eps0, G_Eps0, H_Eps0, Eps0Print = self.objective_term(Points, 'eps0', Eps0_calc, Eps0_std, Eps0_grad, name=\"Dielectric Constant\")\n X_Al, G_Al, H_Al, AlPrint = self.objective_term(Points, 'al', Al_calc, Al_std, Al_grad, name=\"Avg Area per Lipid\")\n X_Scd, G_Scd, H_Scd, ScdPrint = self.objective_term(Points, 'scd', Scd_calc, Scd_std, Scd_grad, name=\"Deuterium Order Parameter\")\n X_LKappa, G_LKappa, H_LKappa, LKappaPrint = self.objective_term(Points, 'lkappa', LKappa_calc, LKappa_std, LKappa_grad, name=\"Bilayer Compressibility\")\n\n Gradient = np.zeros(self.FF.np)\n Hessian = np.zeros((self.FF.np,self.FF.np))\n\n if X_Rho == 0: self.w_rho = 0.0\n if X_Alpha == 0: self.w_alpha = 0.0\n if X_Kappa == 0: self.w_kappa = 0.0\n if X_Cp == 0: self.w_cp = 0.0\n if X_Eps0 == 0: self.w_eps0 = 0.0\n if X_Al == 0: self.w_al = 0.0\n if X_Scd == 0: self.w_scd = 0.0\n if X_LKappa == 0: self.w_lkappa = 0.0\n\n if self.w_normalize:\n w_tot = self.w_rho + self.w_alpha + self.w_kappa + self.w_cp + self.w_eps0 + self.w_al + self.w_scd + self.w_lkappa\n else:\n w_tot = 1.0\n w_1 = self.w_rho / w_tot\n w_3 = self.w_alpha / w_tot\n w_4 = self.w_kappa / w_tot\n w_5 = self.w_cp / w_tot\n w_6 = self.w_eps0 / w_tot\n w_7 = self.w_al / w_tot\n w_8 = self.w_scd / w_tot\n w_9 = self.w_lkappa / w_tot\n\n Objective = w_1 * X_Rho + w_3 * X_Alpha + w_4 * X_Kappa + w_5 * X_Cp + w_6 * X_Eps0 + w_7 * X_Al + w_8 * X_Scd + w_9 * X_LKappa\n if AGrad:\n Gradient = w_1 * G_Rho + w_3 * G_Alpha + w_4 * G_Kappa + w_5 * G_Cp + w_6 * G_Eps0 + w_7 * G_Al + w_8 * G_Scd + w_9 * G_LKappa\n if AHess:\n Hessian = w_1 * H_Rho + w_3 * H_Alpha + w_4 * H_Kappa + w_5 * H_Cp + w_6 * H_Eps0 + w_7 * H_Al + w_8 * H_Scd + w_9 * H_LKappa\n\n if not in_fd():\n self.Xp = {\"Rho\" : X_Rho, \"Alpha\" : X_Alpha, \n \"Kappa\" : X_Kappa, \"Cp\" : X_Cp, \"Eps0\" : X_Eps0, \"Al\" : X_Al, \"Scd\" : X_Scd, \"LKappa\" : X_LKappa}\n self.Wp = {\"Rho\" : w_1, \"Alpha\" : w_3, \n \"Kappa\" : w_4, \"Cp\" : w_5, \"Eps0\" : w_6, \"Al\" : w_7, \"Scd\" : w_8, \"LKappa\" : w_9}\n self.Pp = {\"Rho\" : RhoPrint, \"Alpha\" : AlphaPrint, \n \"Kappa\" : KappaPrint, \"Cp\" : CpPrint, \"Eps0\" : Eps0Print, \"Al\" : AlPrint, \"Scd\" : ScdPrint, \"LKappa\": LKappaPrint}\n if AGrad:\n self.Gp = {\"Rho\" : G_Rho, \"Alpha\" : G_Alpha, \n \"Kappa\" : G_Kappa, \"Cp\" : G_Cp, \"Eps0\" : G_Eps0, \"Al\" : G_Al, \"Scd\" : G_Scd, \"LKappa\" : G_LKappa}\n self.Objective = Objective\n\n Answer = {'X':Objective, 'G':Gradient, 'H':Hessian}\n return Answer\n"
] | [
[
"numpy.dot",
"numpy.log",
"numpy.abs",
"numpy.set_printoptions",
"numpy.linalg.norm",
"numpy.ones",
"numpy.seterr",
"numpy.append",
"numpy.average",
"numpy.outer",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ales-erjavec/openTSNE | [
"bd0924b10f3e4c9112ee7778950d88e3f5de920f"
] | [
"openTSNE/affinity.py"
] | [
"import logging\nimport operator\nfrom functools import reduce\n\nimport numpy as np\nimport scipy.sparse as sp\n\nfrom openTSNE import _tsne\nfrom openTSNE import nearest_neighbors\nfrom openTSNE import utils\nfrom openTSNE.utils import is_package_installed\n\nlog = logging.getLogger(__name__)\n\n\nclass Affinities:\n \"\"\"Compute the affinities between samples.\n\n t-SNE takes as input an affinity matrix :math:`P`, and does not really care\n about anything else from the data. This means we can use t-SNE for any data\n where we are able to express interactions between samples with an affinity\n matrix.\n\n Attributes\n ----------\n P: array_like\n The :math:`N \\\\times N` affinity matrix expressing interactions between\n :math:`N` initial data samples.\n\n verbose: bool\n\n \"\"\"\n\n def __init__(self, verbose=False):\n self.P = None\n self.verbose = verbose\n self.knn_index: nearest_neighbors.KNNIndex = None\n\n def to_new(self, data, return_distances=False):\n \"\"\"Compute the affinities of new samples to the initial samples.\n\n This is necessary for embedding new data points into an existing\n embedding.\n\n Parameters\n ----------\n data: np.ndarray\n The data points to be added to the existing embedding.\n\n return_distances: bool\n If needed, the function can return the indices of the nearest\n neighbors and their corresponding distances.\n\n Returns\n -------\n P: array_like\n An :math:`N \\\\times M` affinity matrix expressing interactions\n between :math:`N` new data points the initial :math:`M` data\n samples.\n\n indices: np.ndarray\n Returned if ``return_distances=True``. The indices of the :math:`k`\n nearest neighbors in the existing embedding for every new data\n point.\n\n distances: np.ndarray\n Returned if ``return_distances=True``. The distances to the\n :math:`k` nearest neighbors in the existing embedding for every new\n data point.\n\n \"\"\"\n\n @property\n def n_samples(self):\n if self.knn_index is None:\n raise RuntimeError(\"`knn_index` is not set!\")\n return self.knn_index.n_samples\n\n\nclass PerplexityBasedNN(Affinities):\n \"\"\"Compute affinities using nearest neighbors.\n\n Please see the :ref:`parameter-guide` for more information.\n\n Parameters\n ----------\n data: np.ndarray\n The data matrix.\n\n perplexity: float\n Perplexity can be thought of as the continuous :math:`k` number of\n nearest neighbors, for which t-SNE will attempt to preserve distances.\n\n method: str\n Specifies the nearest neighbor method to use. Can be ``exact``, ``annoy``,\n ``pynndescent``, ``hnsw``, ``approx``, or ``auto`` (default). ``approx`` uses Annoy\n if the input data matrix is not a sparse object and if Annoy supports\n the given metric. Otherwise it uses Pynndescent. ``auto`` uses exact\n nearest neighbors for N<1000 and the same heuristic as ``approx`` for N>=1000.\n\n metric: Union[str, Callable]\n The metric to be used to compute affinities between points in the\n original space.\n\n metric_params: dict\n Additional keyword arguments for the metric function.\n\n symmetrize: bool\n Symmetrize affinity matrix. Standard t-SNE symmetrizes the interactions\n but when embedding new data, symmetrization is not performed.\n\n n_jobs: int\n The number of threads to use while running t-SNE. This follows the\n scikit-learn convention, ``-1`` meaning all processors, ``-2`` meaning\n all but one, etc.\n\n random_state: Union[int, RandomState]\n If the value is an int, random_state is the seed used by the random\n number generator. If the value is a RandomState instance, then it will\n be used as the random number generator. If the value is None, the random\n number generator is the RandomState instance used by `np.random`.\n\n verbose: bool\n\n k_neighbors: int or ``auto``\n The number of neighbors to use in the kNN graph. If ``auto`` (default),\n it is set to three times the perplexity.\n\n knn_index: Optional[nearest_neighbors.KNNIndex]\n Optionally, a precomptued ``openTSNE.nearest_neighbors.KNNIndex`` object\n can be specified. This option will ignore any KNN-related parameters.\n When ``knn_index`` is specified, ``data`` must be set to None.\n\n \"\"\"\n\n def __init__(\n self,\n data=None,\n perplexity=30,\n method=\"auto\",\n metric=\"euclidean\",\n metric_params=None,\n symmetrize=True,\n n_jobs=1,\n random_state=None,\n verbose=False,\n k_neighbors=\"auto\",\n knn_index=None,\n ):\n # This can't work if neither data nor the knn index are specified\n if data is None and knn_index is None:\n raise ValueError(\n \"At least one of the parameters `data` or `knn_index` must be specified!\"\n )\n # This can't work if both data and the knn index are specified\n if data is not None and knn_index is not None:\n raise ValueError(\n \"Both `data` or `knn_index` were specified! Please pass only one.\"\n )\n\n # Find the nearest neighbors\n if knn_index is None:\n n_samples = data.shape[0]\n\n if k_neighbors == \"auto\":\n _k_neighbors = min(n_samples - 1, int(3 * perplexity))\n else:\n _k_neighbors = k_neighbors\n\n self.perplexity = self.check_perplexity(perplexity, _k_neighbors)\n if _k_neighbors > int(3 * self.perplexity):\n log.warning(\n \"The k_neighbors value is over 3 times larger than the perplexity value. \"\n \"This may result in an unnecessary slowdown.\"\n )\n\n self.knn_index = get_knn_index(\n data, method, _k_neighbors, metric, metric_params, n_jobs,\n random_state, verbose\n )\n\n else:\n self.knn_index = knn_index\n self.perplexity = self.check_perplexity(perplexity, self.knn_index.k)\n log.info(\"KNN index provided. Ignoring KNN-related parameters.\")\n\n self.__neighbors, self.__distances = self.knn_index.build()\n\n with utils.Timer(\"Calculating affinity matrix...\", verbose):\n self.P = joint_probabilities_nn(\n self.__neighbors,\n self.__distances,\n [self.perplexity],\n symmetrize=symmetrize,\n n_jobs=n_jobs,\n )\n\n self.symmetrize = symmetrize\n self.n_jobs = n_jobs\n self.verbose = verbose\n\n def set_perplexity(self, new_perplexity):\n \"\"\"Change the perplexity of the affinity matrix.\n\n Note that we only allow setting the perplexity to a value not larger\n than the number of neighbors used for the original perplexity. This\n restriction exists because setting a higher perplexity value requires\n recomputing all the nearest neighbors, which can take a long time.\n To avoid potential confusion as to why execution time is slow, this\n is not allowed. If you would like to increase the perplexity above\n that value, simply create a new instance.\n\n Parameters\n ----------\n new_perplexity: float\n The new perplexity.\n\n \"\"\"\n # If the value hasn't changed, there's nothing to do\n if new_perplexity == self.perplexity:\n return\n # Verify that the perplexity isn't negative\n new_perplexity = self.check_perplexity(new_perplexity, np.inf)\n # Verify that the perplexity isn't too large for the kNN graph\n if new_perplexity > self.__neighbors.shape[1]:\n raise RuntimeError(\n \"The desired perplexity `%.2f` is larger than the kNN graph \"\n \"allows. This would need to recompute the nearest neighbors, \"\n \"which is not efficient. Please create a new `%s` instance \"\n \"with the increased perplexity.\"\n % (new_perplexity, self.__class__.__name__)\n )\n # Warn if the perplexity is larger than the heuristic\n if 3 * new_perplexity > self.__neighbors.shape[1]:\n log.warning(\n \"The new perplexity is quite close to the computed number of \"\n \"nearest neighbors. The results may be unexpected. Consider \"\n \"creating a new `%s` instance with the increased perplexity.\"\n % (self.__class__.__name__)\n )\n\n # Recompute the affinity matrix\n self.perplexity = new_perplexity\n k_neighbors = int(3 * new_perplexity)\n\n with utils.Timer(\n \"Perplexity changed. Recomputing affinity matrix...\", self.verbose\n ):\n self.P = joint_probabilities_nn(\n self.__neighbors[:, :k_neighbors],\n self.__distances[:, :k_neighbors],\n [self.perplexity],\n symmetrize=self.symmetrize,\n n_jobs=self.n_jobs,\n )\n\n def to_new(\n self, data, perplexity=None, return_distances=False, k_neighbors=\"auto\"\n ):\n \"\"\"Compute the affinities of new samples to the initial samples.\n\n This is necessary for embedding new data points into an existing\n embedding.\n\n Please see the :ref:`parameter-guide` for more information.\n\n Parameters\n ----------\n data: np.ndarray\n The data points to be added to the existing embedding.\n\n perplexity: float\n Perplexity can be thought of as the continuous :math:`k` number of\n nearest neighbors, for which t-SNE will attempt to preserve\n distances.\n\n return_distances: bool\n If needed, the function can return the indices of the nearest\n neighbors and their corresponding distances.\n\n k_neighbors: int or ``auto``\n The number of neighbors to query kNN graph for. If ``auto``\n (default), it is set to three times the perplexity.\n\n Returns\n -------\n P: array_like\n An :math:`N \\\\times M` affinity matrix expressing interactions\n between :math:`N` new data points the initial :math:`M` data\n samples.\n\n indices: np.ndarray\n Returned if ``return_distances=True``. The indices of the :math:`k`\n nearest neighbors in the existing embedding for every new data\n point.\n\n distances: np.ndarray\n Returned if ``return_distances=True``. The distances to the\n :math:`k` nearest neighbors in the existing embedding for every new\n data point.\n\n \"\"\"\n\n perplexity = perplexity if perplexity is not None else self.perplexity\n\n if k_neighbors == \"auto\":\n _k_neighbors = min(self.n_samples, int(3 * perplexity))\n else:\n _k_neighbors = k_neighbors\n\n perplexity = self.check_perplexity(perplexity, _k_neighbors)\n\n neighbors, distances = self.knn_index.query(data, _k_neighbors)\n\n with utils.Timer(\"Calculating affinity matrix...\", self.verbose):\n P = joint_probabilities_nn(\n neighbors,\n distances,\n [perplexity],\n symmetrize=False,\n normalization=\"point-wise\",\n n_reference_samples=self.n_samples,\n n_jobs=self.n_jobs,\n )\n\n if return_distances:\n return P, neighbors, distances\n\n return P\n\n def check_perplexity(self, perplexity, k_neighbors):\n if perplexity <= 0:\n raise ValueError(\"Perplexity must be >=0. %.2f given\" % perplexity)\n\n if perplexity > k_neighbors:\n old_perplexity, perplexity = perplexity, k_neighbors / 3\n log.warning(\n \"Perplexity value %d is too high. Using perplexity %.2f instead\"\n % (old_perplexity, perplexity)\n )\n\n return perplexity\n\n\ndef get_knn_index(\n data, method, k, metric, metric_params=None, n_jobs=1, random_state=None, verbose=False\n):\n # If we're dealing with a precomputed distance matrix, our job is very easy\n # so we can skip all the remaining checks\n if metric == \"precomputed\":\n return nearest_neighbors.PrecomputedDistanceMatrix(data, k=k)\n\n preferred_approx_method = nearest_neighbors.Annoy\n if is_package_installed(\"pynndescent\") and (sp.issparse(data) or metric not in [\n \"cosine\",\n \"euclidean\",\n \"manhattan\",\n \"hamming\",\n \"dot\",\n \"l1\",\n \"l2\",\n \"taxicab\",\n ]):\n preferred_approx_method = nearest_neighbors.NNDescent\n\n if data.shape[0] < 1000:\n preferred_method = nearest_neighbors.Sklearn\n else:\n preferred_method = preferred_approx_method\n\n methods = {\n \"exact\": nearest_neighbors.Sklearn,\n \"auto\": preferred_method,\n \"approx\": preferred_approx_method,\n \"annoy\": nearest_neighbors.Annoy,\n \"pynndescent\": nearest_neighbors.NNDescent,\n \"hnsw\": nearest_neighbors.HNSW\n }\n if isinstance(method, nearest_neighbors.KNNIndex):\n knn_index = method\n\n elif method not in methods:\n raise ValueError(\n \"Unrecognized nearest neighbor algorithm `%s`. Please choose one \"\n \"of the supported methods or provide a valid `KNNIndex` instance.\" % method\n )\n else:\n knn_index = methods[method](\n data=data,\n k=k,\n metric=metric,\n metric_params=metric_params,\n n_jobs=n_jobs,\n random_state=random_state,\n verbose=verbose,\n )\n\n return knn_index\n\n\ndef joint_probabilities_nn(\n neighbors,\n distances,\n perplexities,\n symmetrize=True,\n normalization=\"pair-wise\",\n n_reference_samples=None,\n n_jobs=1,\n):\n \"\"\"Compute the conditional probability matrix P_{j|i}.\n\n This method computes an approximation to P using the nearest neighbors.\n\n Parameters\n ----------\n neighbors: np.ndarray\n A `n_samples * k_neighbors` matrix containing the indices to each\n points\" nearest neighbors in descending order.\n distances: np.ndarray\n A `n_samples * k_neighbors` matrix containing the distances to the\n neighbors at indices defined in the neighbors parameter.\n perplexities: double\n The desired perplexity of the probability distribution.\n symmetrize: bool\n Whether to symmetrize the probability matrix or not. Symmetrizing is\n used for typical t-SNE, but does not make sense when embedding new data\n into an existing embedding.\n normalization: str\n The normalization scheme to use for the affinities. Standard t-SNE\n considers interactions between all the data points, therefore the entire\n affinity matrix is regarded as a probability distribution, and must sum\n to 1. When embedding new points, we only consider interactions to\n existing points, and treat each point separately. In this case, we\n row-normalize the affinity matrix, meaning each point gets its own\n probability distribution.\n n_reference_samples: int\n The number of samples in the existing (reference) embedding. Needed to\n properly construct the sparse P matrix.\n n_jobs: int\n Number of threads.\n\n Returns\n -------\n csr_matrix\n A `n_samples * n_reference_samples` matrix containing the probabilities\n that a new sample would appear as a neighbor of a reference point.\n\n \"\"\"\n assert normalization in (\n \"pair-wise\",\n \"point-wise\",\n ), f\"Unrecognized normalization scheme `{normalization}`.\"\n\n n_samples, k_neighbors = distances.shape\n\n if n_reference_samples is None:\n n_reference_samples = n_samples\n\n # Compute asymmetric pairwise input similarities\n conditional_P = _tsne.compute_gaussian_perplexity(\n np.array(distances, dtype=float),\n np.array(perplexities, dtype=float),\n num_threads=n_jobs,\n )\n conditional_P = np.asarray(conditional_P)\n\n P = sp.csr_matrix(\n (\n conditional_P.ravel(),\n neighbors.ravel(),\n range(0, n_samples * k_neighbors + 1, k_neighbors),\n ),\n shape=(n_samples, n_reference_samples),\n )\n\n # Symmetrize the probability matrix\n if symmetrize:\n P = (P + P.T) / 2\n\n if normalization == \"pair-wise\":\n P /= np.sum(P)\n elif normalization == \"point-wise\":\n P = sp.diags(np.asarray(1 / P.sum(axis=1)).ravel()) @ P\n\n return P\n\n\nclass FixedSigmaNN(Affinities):\n \"\"\"Compute affinities using using nearest neighbors and a fixed bandwidth\n for the Gaussians in the ambient space.\n\n Using a fixed Gaussian bandwidth can enable us to find smaller clusters of\n data points than we might be able to using the automatically determined\n bandwidths using perplexity. Note however that this requires mostly trial\n and error.\n\n Parameters\n ----------\n data: np.ndarray\n The data matrix.\n\n sigma: float\n The bandwidth to use for the Gaussian kernels in the ambient space.\n\n k: int\n The number of nearest neighbors to consider for each kernel.\n\n method: str\n Specifies the nearest neighbor method to use. Can be ``exact``, ``annoy``,\n ``pynndescent``, ``hnsw``, ``approx``, or ``auto`` (default). ``approx`` uses Annoy\n if the input data matrix is not a sparse object and if Annoy supports\n the given metric. Otherwise it uses Pynndescent. ``auto`` uses exact\n nearest neighbors for N<1000 and the same heuristic as ``approx`` for N>=1000.\n\n\n metric: Union[str, Callable]\n The metric to be used to compute affinities between points in the\n original space.\n\n metric_params: dict\n Additional keyword arguments for the metric function.\n\n symmetrize: bool\n Symmetrize affinity matrix. Standard t-SNE symmetrizes the interactions\n but when embedding new data, symmetrization is not performed.\n\n n_jobs: int\n The number of threads to use while running t-SNE. This follows the\n scikit-learn convention, ``-1`` meaning all processors, ``-2`` meaning\n all but one, etc.\n\n random_state: Union[int, RandomState]\n If the value is an int, random_state is the seed used by the random\n number generator. If the value is a RandomState instance, then it will\n be used as the random number generator. If the value is None, the random\n number generator is the RandomState instance used by `np.random`.\n\n verbose: bool\n\n knn_index: Optional[nearest_neighbors.KNNIndex]\n Optionally, a precomptued ``openTSNE.nearest_neighbors.KNNIndex`` object\n can be specified. This option will ignore any KNN-related parameters.\n When ``knn_index`` is specified, ``data`` must be set to None.\n\n \"\"\"\n\n def __init__(\n self,\n data=None,\n sigma=None,\n k=30,\n method=\"auto\",\n metric=\"euclidean\",\n metric_params=None,\n symmetrize=True,\n n_jobs=1,\n random_state=None,\n verbose=False,\n knn_index=None,\n ):\n # Sigma must be specified, but has default set to none, so the parameter\n # order makes more sense\n if sigma is None:\n raise ValueError(\"`sigma` must be specified!\")\n\n # This can't work if neither data nor the knn index are specified\n if data is None and knn_index is None:\n raise ValueError(\n \"At least one of the parameters `data` or `knn_index` must be specified!\"\n )\n # This can't work if both data and the knn index are specified\n if data is not None and knn_index is not None:\n raise ValueError(\n \"Both `data` or `knn_index` were specified! Please pass only one.\"\n )\n\n # Find the nearest neighbors\n if knn_index is None:\n if k >= data.shape[0]:\n raise ValueError(\n \"`k` (%d) cannot be larger than N-1 (%d).\" % (k, data.shape[0])\n )\n\n self.knn_index = get_knn_index(\n data, method, k, metric, metric_params, n_jobs, random_state, verbose\n )\n\n else:\n self.knn_index = knn_index\n log.info(\"KNN index provided. Ignoring KNN-related parameters.\")\n\n neighbors, distances = self.knn_index.build()\n\n with utils.Timer(\"Calculating affinity matrix...\", verbose):\n # Compute asymmetric pairwise input similarities\n conditional_P = np.exp(-(distances ** 2) / (2 * sigma ** 2))\n conditional_P /= np.sum(conditional_P, axis=1)[:, np.newaxis]\n\n n_samples = self.knn_index.n_samples\n P = sp.csr_matrix(\n (\n conditional_P.ravel(),\n neighbors.ravel(),\n range(0, n_samples * k + 1, k),\n ),\n shape=(n_samples, n_samples),\n )\n\n # Symmetrize the probability matrix\n if symmetrize:\n P = (P + P.T) / 2\n\n # Convert weights to probabilities\n P /= np.sum(P)\n\n self.sigma = sigma\n self.P = P\n self.n_jobs = n_jobs\n self.verbose = verbose\n\n def to_new(self, data, k=None, sigma=None, return_distances=False):\n \"\"\"Compute the affinities of new samples to the initial samples.\n\n This is necessary for embedding new data points into an existing\n embedding.\n\n Parameters\n ----------\n data: np.ndarray\n The data points to be added to the existing embedding.\n\n k: int\n The number of nearest neighbors to consider for each kernel.\n\n sigma: float\n The bandwidth to use for the Gaussian kernels in the ambient space.\n\n return_distances: bool\n If needed, the function can return the indices of the nearest\n neighbors and their corresponding distances.\n\n Returns\n -------\n P: array_like\n An :math:`N \\\\times M` affinity matrix expressing interactions\n between :math:`N` new data points the initial :math:`M` data\n samples.\n\n indices: np.ndarray\n Returned if ``return_distances=True``. The indices of the :math:`k`\n nearest neighbors in the existing embedding for every new data\n point.\n\n distances: np.ndarray\n Returned if ``return_distances=True``. The distances to the\n :math:`k` nearest neighbors in the existing embedding for every new\n data point.\n\n \"\"\"\n n_samples = data.shape[0]\n n_reference_samples = self.n_samples\n\n if k is None:\n k = self.knn_index.k\n elif k >= n_reference_samples:\n raise ValueError(\n \"`k` (%d) cannot be larger than the number of reference \"\n \"samples (%d).\" % (k, self.n_samples)\n )\n\n if sigma is None:\n sigma = self.sigma\n\n # Find nearest neighbors and the distances to the new points\n neighbors, distances = self.knn_index.query(data, k)\n\n with utils.Timer(\"Calculating affinity matrix...\", self.verbose):\n # Compute asymmetric pairwise input similarities\n conditional_P = np.exp(-(distances ** 2) / (2 * sigma ** 2))\n\n # Convert weights to probabilities\n conditional_P /= np.sum(conditional_P, axis=1)[:, np.newaxis]\n\n P = sp.csr_matrix(\n (\n conditional_P.ravel(),\n neighbors.ravel(),\n range(0, n_samples * k + 1, k),\n ),\n shape=(n_samples, n_reference_samples),\n )\n\n if return_distances:\n return P, neighbors, distances\n\n return P\n\n\nclass MultiscaleMixture(Affinities):\n \"\"\"Calculate affinities using a Gaussian mixture kernel.\n\n Instead of using a single perplexity to compute the affinities between data\n points, we can use a multiscale Gaussian kernel instead. This allows us to\n incorporate long range interactions.\n\n Please see the :ref:`parameter-guide` for more information.\n\n Parameters\n ----------\n data: np.ndarray\n The data matrix.\n\n perplexities: List[float]\n A list of perplexity values, which will be used in the multiscale\n Gaussian kernel. Perplexity can be thought of as the continuous\n :math:`k` number of nearest neighbors, for which t-SNE will attempt to\n preserve distances.\n\n method: str\n Specifies the nearest neighbor method to use. Can be ``exact``, ``annoy``,\n ``pynndescent``, ``hnsw``, ``approx``, or ``auto`` (default). ``approx`` uses Annoy\n if the input data matrix is not a sparse object and if Annoy supports\n the given metric. Otherwise it uses Pynndescent. ``auto`` uses exact\n nearest neighbors for N<1000 and the same heuristic as ``approx`` for N>=1000.\n\n metric: Union[str, Callable]\n The metric to be used to compute affinities between points in the\n original space.\n\n metric_params: dict\n Additional keyword arguments for the metric function.\n\n symmetrize: bool\n Symmetrize affinity matrix. Standard t-SNE symmetrizes the interactions\n but when embedding new data, symmetrization is not performed.\n\n n_jobs: int\n The number of threads to use while running t-SNE. This follows the\n scikit-learn convention, ``-1`` meaning all processors, ``-2`` meaning\n all but one, etc.\n\n random_state: Union[int, RandomState]\n If the value is an int, random_state is the seed used by the random\n number generator. If the value is a RandomState instance, then it will\n be used as the random number generator. If the value is None, the random\n number generator is the RandomState instance used by `np.random`.\n\n verbose: bool\n\n knn_index: Optional[nearest_neighbors.KNNIndex]\n Optionally, a precomptued ``openTSNE.nearest_neighbors.KNNIndex`` object\n can be specified. This option will ignore any KNN-related parameters.\n When ``knn_index`` is specified, ``data`` must be set to None.\n\n \"\"\"\n\n def __init__(\n self,\n data=None,\n perplexities=None,\n method=\"auto\",\n metric=\"euclidean\",\n metric_params=None,\n symmetrize=True,\n n_jobs=1,\n random_state=None,\n verbose=False,\n knn_index=None,\n ):\n # Perplexities must be specified, but has default set to none, so the\n # parameter order makes more sense\n if perplexities is None:\n raise ValueError(\"`perplexities` must be specified!\")\n\n # This can't work if neither data nor the knn index are specified\n if data is None and knn_index is None:\n raise ValueError(\n \"At least one of the parameters `data` or `knn_index` must be specified!\"\n )\n # This can't work if both data and the knn index are specified\n if data is not None and knn_index is not None:\n raise ValueError(\n \"Both `data` or `knn_index` were specified! Please pass only one.\"\n )\n\n # Find the nearest neighbors\n if knn_index is None:\n # We will compute the nearest neighbors to the max value of perplexity,\n # smaller values can just use indexing to truncate unneeded neighbors\n n_samples = data.shape[0]\n perplexities = self.check_perplexities(perplexities, n_samples)\n max_perplexity = np.max(perplexities)\n k_neighbors = min(n_samples - 1, int(3 * max_perplexity))\n\n self.knn_index = get_knn_index(\n data, method, k_neighbors, metric, metric_params, n_jobs, random_state, verbose\n )\n\n else:\n self.knn_index = knn_index\n log.info(\"KNN index provided. Ignoring KNN-related parameters.\")\n\n self.__neighbors, self.__distances = self.knn_index.build()\n\n with utils.Timer(\"Calculating affinity matrix...\", verbose):\n self.P = self._calculate_P(\n self.__neighbors,\n self.__distances,\n perplexities,\n symmetrize=symmetrize,\n n_jobs=n_jobs,\n )\n\n self.perplexities = perplexities\n self.symmetrize = symmetrize\n self.n_jobs = n_jobs\n self.verbose = verbose\n\n @staticmethod\n def _calculate_P(\n neighbors,\n distances,\n perplexities,\n symmetrize=True,\n normalization=\"pair-wise\",\n n_reference_samples=None,\n n_jobs=1,\n ):\n return joint_probabilities_nn(\n neighbors,\n distances,\n perplexities,\n symmetrize=symmetrize,\n normalization=normalization,\n n_reference_samples=n_reference_samples,\n n_jobs=n_jobs,\n )\n\n def set_perplexities(self, new_perplexities):\n \"\"\"Change the perplexities of the affinity matrix.\n\n Note that we only allow lowering the perplexities or restoring them to\n their original maximum value. This restriction exists because setting a\n higher perplexity value requires recomputing all the nearest neighbors,\n which can take a long time. To avoid potential confusion as to why\n execution time is slow, this is not allowed. If you would like to\n increase the perplexity above the initial value, simply create a new\n instance.\n\n Parameters\n ----------\n new_perplexities: List[float]\n The new list of perplexities.\n\n \"\"\"\n if np.array_equal(self.perplexities, new_perplexities):\n return\n\n new_perplexities = self.check_perplexities(new_perplexities, self.n_samples)\n max_perplexity = np.max(new_perplexities)\n k_neighbors = min(self.n_samples - 1, int(3 * max_perplexity))\n\n if k_neighbors > self.__neighbors.shape[1]:\n raise RuntimeError(\n \"The largest perplexity `%.2f` is larger than the initial one \"\n \"used. This would need to recompute the nearest neighbors, \"\n \"which is not efficient. Please create a new `%s` instance \"\n \"with the increased perplexity.\"\n % (max_perplexity, self.__class__.__name__)\n )\n\n self.perplexities = new_perplexities\n with utils.Timer(\n \"Perplexity changed. Recomputing affinity matrix...\", self.verbose\n ):\n self.P = self._calculate_P(\n self.__neighbors[:, :k_neighbors],\n self.__distances[:, :k_neighbors],\n self.perplexities,\n symmetrize=self.symmetrize,\n n_jobs=self.n_jobs,\n )\n\n def to_new(self, data, perplexities=None, return_distances=False):\n \"\"\"Compute the affinities of new samples to the initial samples.\n\n This is necessary for embedding new data points into an existing\n embedding.\n\n Please see the :ref:`parameter-guide` for more information.\n\n Parameters\n ----------\n data: np.ndarray\n The data points to be added to the existing embedding.\n\n perplexities: List[float]\n A list of perplexity values, which will be used in the multiscale\n Gaussian kernel. Perplexity can be thought of as the continuous\n :math:`k` number of nearest neighbors, for which t-SNE will attempt\n to preserve distances.\n\n return_distances: bool\n If needed, the function can return the indices of the nearest\n neighbors and their corresponding distances.\n\n Returns\n -------\n P: array_like\n An :math:`N \\\\times M` affinity matrix expressing interactions\n between :math:`N` new data points the initial :math:`M` data\n samples.\n\n indices: np.ndarray\n Returned if ``return_distances=True``. The indices of the :math:`k`\n nearest neighbors in the existing embedding for every new data\n point.\n\n distances: np.ndarray\n Returned if ``return_distances=True``. The distances to the\n :math:`k` nearest neighbors in the existing embedding for every new\n data point.\n\n \"\"\"\n perplexities = perplexities if perplexities is not None else self.perplexities\n perplexities = self.check_perplexities(perplexities, self.n_samples)\n\n max_perplexity = np.max(perplexities)\n k_neighbors = min(self.n_samples - 1, int(3 * max_perplexity))\n\n neighbors, distances = self.knn_index.query(data, k_neighbors)\n\n with utils.Timer(\"Calculating affinity matrix...\", self.verbose):\n P = self._calculate_P(\n neighbors,\n distances,\n perplexities,\n symmetrize=False,\n normalization=\"point-wise\",\n n_reference_samples=self.n_samples,\n n_jobs=self.n_jobs,\n )\n\n if return_distances:\n return P, neighbors, distances\n\n return P\n\n def check_perplexities(self, perplexities, n_samples):\n \"\"\"Check and correct/truncate perplexities.\n\n If a perplexity is too large, it is corrected to the largest allowed\n value. It is then inserted into the list of perplexities only if that\n value doesn't already exist in the list.\n\n \"\"\"\n usable_perplexities = []\n for perplexity in sorted(perplexities):\n if perplexity <= 0:\n raise ValueError(\"Perplexity must be >=0. %.2f given\" % perplexity)\n\n if 3 * perplexity > n_samples - 1:\n new_perplexity = (n_samples - 1) / 3\n\n if new_perplexity in usable_perplexities:\n log.warning(\n \"Perplexity value %d is too high. Dropping \"\n \"because the max perplexity is already in the \"\n \"list.\" % perplexity\n )\n else:\n usable_perplexities.append(new_perplexity)\n log.warning(\n \"Perplexity value %d is too high. Using \"\n \"perplexity %.2f instead\" % (perplexity, new_perplexity)\n )\n else:\n usable_perplexities.append(perplexity)\n\n return usable_perplexities\n\n\nclass Multiscale(MultiscaleMixture):\n \"\"\"Calculate affinities using averaged Gaussian perplexities.\n\n In contrast to :class:`MultiscaleMixture`, which uses a Gaussian mixture\n kernel, here, we first compute single scale Gaussian kernels, convert them\n to probability distributions, then average them out between scales.\n\n Please see the :ref:`parameter-guide` for more information.\n\n Parameters\n ----------\n data: np.ndarray\n The data matrix.\n\n perplexities: List[float]\n A list of perplexity values, which will be used in the multiscale\n Gaussian kernel. Perplexity can be thought of as the continuous\n :math:`k` number of nearest neighbors, for which t-SNE will attempt to\n preserve distances.\n\n method: str\n Specifies the nearest neighbor method to use. Can be ``exact``, ``annoy``,\n ``pynndescent``, ``hnsw``, ``approx``, or ``auto`` (default). ``approx`` uses Annoy\n if the input data matrix is not a sparse object and if Annoy supports\n the given metric. Otherwise it uses Pynndescent. ``auto`` uses exact\n nearest neighbors for N<1000 and the same heuristic as ``approx`` for N>=1000.\n\n metric: Union[str, Callable]\n The metric to be used to compute affinities between points in the\n original space.\n\n metric_params: dict\n Additional keyword arguments for the metric function.\n\n symmetrize: bool\n Symmetrize affinity matrix. Standard t-SNE symmetrizes the interactions\n but when embedding new data, symmetrization is not performed.\n\n n_jobs: int\n The number of threads to use while running t-SNE. This follows the\n scikit-learn convention, ``-1`` meaning all processors, ``-2`` meaning\n all but one, etc.\n\n random_state: Union[int, RandomState]\n If the value is an int, random_state is the seed used by the random\n number generator. If the value is a RandomState instance, then it will\n be used as the random number generator. If the value is None, the random\n number generator is the RandomState instance used by `np.random`.\n\n verbose: bool\n\n knn_index: Optional[nearest_neighbors.KNNIndex]\n Optionally, a precomptued ``openTSNE.nearest_neighbors.KNNIndex`` object\n can be specified. This option will ignore any KNN-related parameters.\n When ``knn_index`` is specified, ``data`` must be set to None.\n\n \"\"\"\n\n @staticmethod\n def _calculate_P(\n neighbors,\n distances,\n perplexities,\n symmetrize=True,\n normalization=\"pair-wise\",\n n_reference_samples=None,\n n_jobs=1,\n ):\n # Compute normalized probabilities for each perplexity\n partial_Ps = [\n joint_probabilities_nn(\n neighbors,\n distances,\n [perplexity],\n symmetrize=symmetrize,\n normalization=normalization,\n n_reference_samples=n_reference_samples,\n n_jobs=n_jobs,\n )\n for perplexity in perplexities\n ]\n # Sum them together, then normalize\n P = reduce(operator.add, partial_Ps, 0)\n\n # Take care to properly normalize the affinity matrix\n if normalization == \"pair-wise\":\n P /= np.sum(P)\n elif normalization == \"point-wise\":\n P = sp.diags(np.asarray(1 / P.sum(axis=1)).ravel()) @ P\n\n return P\n\n\nclass Uniform(Affinities):\n \"\"\"Compute affinities using using nearest neighbors and uniform kernel in\n the ambient space.\n\n Parameters\n ----------\n data: np.ndarray\n The data matrix.\n\n k_neighbors: int\n\n method: str\n Specifies the nearest neighbor method to use. Can be ``exact``, ``annoy``,\n ``pynndescent``, ``hnsw``, ``approx``, or ``auto`` (default). ``approx`` uses Annoy\n if the input data matrix is not a sparse object and if Annoy supports\n the given metric. Otherwise it uses Pynndescent. ``auto`` uses exact\n nearest neighbors for N<1000 and the same heuristic as ``approx`` for N>=1000.\n\n\n metric: Union[str, Callable]\n The metric to be used to compute affinities between points in the\n original space.\n\n metric_params: dict\n Additional keyword arguments for the metric function.\n\n symmetrize: bool\n Symmetrize affinity matrix. Standard t-SNE symmetrizes the interactions\n but when embedding new data, symmetrization is not performed.\n\n n_jobs: int\n The number of threads to use while running t-SNE. This follows the\n scikit-learn convention, ``-1`` meaning all processors, ``-2`` meaning\n all but one, etc.\n\n random_state: Union[int, RandomState]\n If the value is an int, random_state is the seed used by the random\n number generator. If the value is a RandomState instance, then it will\n be used as the random number generator. If the value is None, the random\n number generator is the RandomState instance used by `np.random`.\n\n verbose: bool\n\n knn_index: Optional[nearest_neighbors.KNNIndex]\n Optionally, a precomptued ``openTSNE.nearest_neighbors.KNNIndex`` object\n can be specified. This option will ignore any KNN-related parameters.\n When ``knn_index`` is specified, ``data`` must be set to None.\n\n \"\"\"\n\n def __init__(\n self,\n data=None,\n k_neighbors=30,\n method=\"auto\",\n metric=\"euclidean\",\n metric_params=None,\n symmetrize=True,\n n_jobs=1,\n random_state=None,\n verbose=False,\n knn_index=None,\n ):\n # This can't work if neither data nor the knn index are specified\n if data is None and knn_index is None:\n raise ValueError(\n \"At least one of the parameters `data` or `knn_index` must be specified!\"\n )\n # This can't work if both data and the knn index are specified\n if data is not None and knn_index is not None:\n raise ValueError(\n \"Both `data` or `knn_index` were specified! Please pass only one.\"\n )\n\n if knn_index is None:\n if k_neighbors >= data.shape[0]:\n raise ValueError(\n \"`k_neighbors` (%d) cannot be larger than N-1 (%d).\" %\n (k_neighbors, data.shape[0])\n )\n\n self.knn_index = get_knn_index(\n data, method, k_neighbors, metric, metric_params, n_jobs, random_state, verbose\n )\n\n else:\n self.knn_index = knn_index\n log.info(\"KNN index provided. Ignoring KNN-related parameters.\")\n\n neighbors, distances = self.knn_index.build()\n\n k_neighbors = self.knn_index.k\n n_samples = self.knn_index.n_samples\n P = sp.csr_matrix(\n (\n np.ones_like(distances).ravel(),\n neighbors.ravel(),\n range(0, n_samples * k_neighbors + 1, k_neighbors),\n ),\n shape=(n_samples, n_samples),\n )\n\n # Symmetrize the probability matrix\n if symmetrize:\n P = (P + P.T) / 2\n\n # Convert weights to probabilities\n P /= np.sum(P)\n\n self.P = P\n self.verbose = verbose\n self.n_jobs = n_jobs\n\n def to_new(self, data, k_neighbors=None, return_distances=False):\n \"\"\"Compute the affinities of new samples to the initial samples.\n\n This is necessary for embedding new data points into an existing\n embedding.\n\n Parameters\n ----------\n data: np.ndarray\n The data points to be added to the existing embedding.\n\n k_neighbors: int\n The number of nearest neighbors to consider.\n\n return_distances: bool\n If needed, the function can return the indices of the nearest\n neighbors and their corresponding distances.\n\n Returns\n -------\n P: array_like\n An :math:`N \\\\times M` affinity matrix expressing interactions\n between :math:`N` new data points the initial :math:`M` data\n samples.\n\n indices: np.ndarray\n Returned if ``return_distances=True``. The indices of the :math:`k`\n nearest neighbors in the existing embedding for every new data\n point.\n\n distances: np.ndarray\n Returned if ``return_distances=True``. The distances to the\n :math:`k` nearest neighbors in the existing embedding for every new\n data point.\n\n \"\"\"\n n_samples = data.shape[0]\n n_reference_samples = self.n_samples\n\n if k_neighbors is None:\n k_neighbors = self.knn_index.k\n elif k_neighbors >= n_reference_samples:\n raise ValueError(\n \"`k` (%d) cannot be larger than the number of reference \"\n \"samples (%d).\" % (k_neighbors, self.n_samples)\n )\n\n # Find nearest neighbors and the distances to the new points\n neighbors, distances = self.knn_index.query(data, k_neighbors)\n\n values = np.ones_like(distances)\n values /= np.sum(values, axis=1)[:, np.newaxis]\n\n P = sp.csr_matrix(\n (\n values.ravel(),\n neighbors.ravel(),\n range(0, n_samples * k_neighbors + 1, k_neighbors),\n ),\n shape=(n_samples, n_reference_samples),\n )\n\n if return_distances:\n return P, neighbors, distances\n\n return P\n"
] | [
[
"numpy.ones_like",
"scipy.sparse.issparse",
"numpy.array_equal",
"numpy.asarray",
"numpy.max",
"numpy.exp",
"numpy.array",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
rizwandel/optagan | [
"e929b2fa25522bb43e949b8ed4d77d074422b4fe"
] | [
"optagan/run_latent_generation.py"
] | [
"#!/usr/bin/env python3\n# coding=utf-8\n# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. 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\"\"\" Conditional text generation with the auto-regressive models of the library (GPT/GPT-2/Transformer-XL/XLNet)\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport argparse\nimport glob\nimport logging\nimport os\nimport pickle\nimport random\n\n\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom torch.utils.data import DataLoader, Dataset, SequentialSampler, RandomSampler, TensorDataset\nfrom torch.utils.data.distributed import DistributedSampler\nfrom tqdm import tqdm, trange\n\n\nfrom func import GPT2Config, OpenAIGPTConfig, XLNetConfig, TransfoXLConfig, BertConfig\nfrom func import GPT2LMHeadModel, GPT2Tokenizer, GPT2ForLatentConnector\nfrom func import OpenAIGPTLMHeadModel, OpenAIGPTTokenizer\nfrom func import XLNetLMHeadModel, XLNetTokenizer\nfrom func import TransfoXLLMHeadModel, TransfoXLTokenizer\nfrom func import BertForLatentConnector, BertTokenizer\n\nfrom collections import defaultdict\nfrom modules import VAE\nfrom utils import (TextDataset_Split, TextDataset_2Tokenizers, BucketingDataLoader)\n\n\nimport pdb\n\n\nlogging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt = '%m/%d/%Y %H:%M:%S',\n level = logging.INFO)\nlogger = logging.getLogger(__name__)\n\nMAX_LENGTH = int(10000) # Hardcoded max length to avoid infinite loop\n\nALL_MODELS = sum((tuple(conf.pretrained_config_archive_map.keys()) for conf in (GPT2Config, OpenAIGPTConfig, XLNetConfig, TransfoXLConfig)), ())\n\nMODEL_CLASSES = {\n 'gpt2': (GPT2Config, GPT2ForLatentConnector, GPT2Tokenizer),\n 'bert': (BertConfig, BertForLatentConnector, BertTokenizer)\n}\n\n# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia\n# in https://github.com/rusiaaman/XLNet-gen#methodology\n# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e\nPADDING_TEXT = \"\"\" In 1991, the remains of Russian Tsar Nicholas II and his family\n(except for Alexei and Maria) are discovered.\nThe voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the\nremainder of the story. 1883 Western Siberia,\na young Grigori Rasputin is asked by his father and a group of men to perform magic.\nRasputin has a vision and denounces one of the men as a horse thief. Although his\nfather initially slaps him for making such an accusation, Rasputin watches as the\nman is chased outside and beaten. Twenty years later, Rasputin sees a vision of\nthe Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,\nwith people, even a bishop, begging for his blessing. <eod> </s> <eos>\"\"\"\n\n\ndef set_seed(args):\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n\ndef load_and_cache_examples(args, tokenizer, evaluate=False):\n if isinstance(tokenizer, list):\n dataset = TextDataset_2Tokenizers(tokenizer, args, file_path=args.eval_data_file if evaluate else args.train_data_file, block_size=args.block_size)\n else:\n dataset = TextDataset_Split(tokenizer, args, file_path=args.eval_data_file if evaluate else args.train_data_file, block_size=args.block_size)\n return dataset\n\ndef build_dataload_and_cache_examples(args, tokenizer, evaluate=False):\n if isinstance(tokenizer, list):\n if not evaluate:\n args.batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)\n file_path=args.train_data_file\n else:\n args.batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) \n file_path=args.eval_data_file\n dataloader = BucketingDataLoader(file_path, args.batch_size, args.max_seq_length, tokenizer, args, bucket=100, shuffle=False)\n else:\n pass \n return dataloader\n\n\ndef top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):\n \"\"\" Filter a distribution of logits using top-k and/or nucleus (top-p) filtering\n Args:\n logits: logits distribution shape (vocabulary size)\n top_k > 0: keep only top k tokens with highest probability (top-k filtering).\n top_p > 0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).\n Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)\n From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317\n \"\"\"\n assert logits.dim() == 1 # batch size 1 for now - could be updated for more but the code would be less clear\n top_k = min(top_k, logits.size(-1)) # Safety check\n if top_k > 0:\n # Remove all tokens with a probability less than the last token of the top-k\n indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]\n logits[indices_to_remove] = filter_value\n\n if top_p > 0.0:\n sorted_logits, sorted_indices = torch.sort(logits, descending=True)\n cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)\n\n # Remove tokens with cumulative probability above the threshold\n sorted_indices_to_remove = cumulative_probs > top_p\n # Shift the indices to the right to keep also the first token above the threshold\n sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()\n sorted_indices_to_remove[..., 0] = 0\n\n indices_to_remove = sorted_indices[sorted_indices_to_remove]\n logits[indices_to_remove] = filter_value\n return logits\n\n\ndef sample_sequence(model, length, context, num_samples=1, temperature=1, top_k=0, top_p=0.0, is_xlnet=False, device='cpu'):\n context = torch.tensor(context, dtype=torch.long, device=device)\n context = context.unsqueeze(0).repeat(num_samples, 1)\n generated = context\n with torch.no_grad():\n for _ in trange(length):\n\n inputs = {'input_ids': generated}\n if is_xlnet: \n # XLNet is a direct (predict same token, not next token) and bi-directional model by default\n # => need one additional dummy token in the input (will be masked), attention mask and target mapping (see model docstring)\n input_ids = torch.cat((generated, torch.zeros((1, 1), dtype=torch.long, device=device)), dim=1)\n perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float, device=device)\n perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token\n target_mapping = torch.zeros((1, 1, input_ids.shape[1]), dtype=torch.float, device=device)\n target_mapping[0, 0, -1] = 1.0 # predict last token\n inputs = {'input_ids': input_ids, 'perm_mask': perm_mask, 'target_mapping': target_mapping}\n\n outputs = model(**inputs) # Note: we could also use 'past' with GPT-2/Transfo-XL/XLNet (cached hidden-states)\n next_token_logits = outputs[0][0, -1, :] / temperature\n filtered_logits = top_k_top_p_filtering(next_token_logits, top_k=top_k, top_p=top_p)\n next_token = torch.multinomial(F.softmax(filtered_logits, dim=-1), num_samples=1)\n generated = torch.cat((generated, next_token.unsqueeze(0)), dim=1)\n return generated\n\ndef sample_sequence_conditional(model, length, context, past=None, num_samples=1, temperature=1, top_k=0, top_p=0.0, device='cpu', decoder_tokenizer=None):\n\n context = torch.tensor(context, dtype=torch.long, device=device)\n context = context.unsqueeze(0).repeat(num_samples, 1)\n generated = context\n with torch.no_grad():\n while True:\n # for _ in trange(length):\n inputs = {'input_ids': generated, 'past': past}\n outputs = model(**inputs) # Note: we could also use 'past' with GPT-2/Transfo-XL/XLNet (cached hidden-states)\n next_token_logits = outputs[0][0, -1, :] / temperature\n filtered_logits = top_k_top_p_filtering(next_token_logits, top_k=top_k, top_p=top_p)\n next_token = torch.multinomial(F.softmax(filtered_logits, dim=-1), num_samples=1)\n generated = torch.cat((generated, next_token.unsqueeze(0)), dim=1)\n\n # pdb.set_trace()\n if next_token.unsqueeze(0)[0,0].item() == decoder_tokenizer.encode('<EOS>')[0]:\n break\n\n return generated\n\n\ndef latent_code_from_text(text, tokenizer_encoder, model_encoder, args):\n tokenized1 = tokenizer_encoder.encode(text)\n tokenized1 = [101] + tokenized1 + [102]\n coded1 = torch.Tensor([tokenized1])\n coded1 =torch.Tensor.long(coded1)\n with torch.no_grad():\n x0 = coded1\n x0 = x0.to(args.device)\n pooled_hidden_fea = model_encoder(x0, attention_mask=(x0 > 0).float())[1]\n mean, logvar = model_encoder.linear(pooled_hidden_fea).chunk(2, -1)\n latent_z = mean.squeeze(1) \n coded_length = len(tokenized1)\n return latent_z, coded_length\n\ndef text_from_latent_code(latent_z, model_decoder, args, tokenizer_decoder):\n past = latent_z\n context_tokens = tokenizer_decoder.encode('<BOS>')\n length = 128 # maximum length, but not used \n out = sample_sequence_conditional(\n model=model_decoder,\n context=context_tokens,\n past=past,\n length= length, # Chunyuan: Fix length; or use <EOS> to complete a sentence\n temperature=args.temperature,\n top_k=args.top_k,\n top_p=args.top_p,\n device=args.device,\n decoder_tokenizer = tokenizer_decoder\n )\n text_x1 = tokenizer_decoder.decode(out[0,:].tolist(), clean_up_tokenization_spaces=True)\n text_x1 = text_x1.split()[1:-1]\n text_x1 = ' '.join(text_x1)\n return text_x1\n\n\n# a wrapper function to choose between different play modes\ndef evaluate_latent_space(args, model_encoder, model_decoder, encoder_tokenizer, decoder_tokenizer, prefix=\"\"):\n\n eval_dataloader = build_dataload_and_cache_examples(args, [encoder_tokenizer, decoder_tokenizer], evaluate=False)\n\n # Eval!\n logger.info(\"***** Running recontruction evaluation {} *****\".format(prefix))\n logger.info(\" Num examples = %d\", len(eval_dataloader))\n logger.info(\" Batch size = %d\", args.per_gpu_eval_batch_size)\n \n model_encoder.eval()\n model_decoder.eval()\n\n # model_vae = model_vae.module if hasattr(model_vae, 'module') else model_vae # Take care of distributed/parallel training\n\n if args.play_mode == 'reconstrction':\n result = calc_rec(model_encoder, model_decoder, eval_dataloader, encoder_tokenizer, decoder_tokenizer, args, ns=100)\n result_file_name = \"eval_recontruction_results.txt\"\n elif args.play_mode == 'interpolation':\n result = calc_interpolate(model_encoder, model_decoder, eval_dataloader, encoder_tokenizer, decoder_tokenizer, args, ns=100)\n result_file_name = \"eval_interpolation_results.txt\"\n else:\n logger.info(\"Please specify the corrent play mode [reconstrction, interpolation]\")\n \n\n eval_output_dir = args.output_dir\n output_eval_file = os.path.join(eval_output_dir, result_file_name)\n\n with open(output_eval_file, \"w\") as writer:\n logger.info(\"***** Eval {} results *****\".format(args.play_mode))\n for key in sorted(result.keys()):\n logger.info(\" %s \\n %s\", key, str(result[key]))\n writer.write(\"%s \\n %s\\n\" % (key, str(result[key])))\n\n return result\n\n\ndef calc_rec(model_encoder, model_decoder, eval_dataloader, encoder_tokenizer, decoder_tokenizer, args, ns=1):\n\n count = 0\n result = defaultdict(str)\n for batch in tqdm(eval_dataloader, desc=\"Evaluating recontruction\"):\n # pdb.set_trace()\n x0, x1, x_lengths = batch\n\n max_len_values, _ = x_lengths.max(0)\n x0 = x0[:,:max_len_values[0]]\n x1 = x1[:,:max_len_values[1]]\n\n x0 = x0.to(args.device)\n x1 = x1.to(args.device)\n x_lengths = x_lengths.to(args.device)\n\n context_tokens = decoder_tokenizer.encode('<BOS>')\n\n with torch.no_grad():\n\n text_x0 = encoder_tokenizer.decode(x0[0,:x_lengths[0,0]].tolist(), clean_up_tokenization_spaces=True)[0]\n # result[\"INPUT TEXT \" + str(count)].append(text_x0)\n\n pooled_hidden_fea = model_encoder(x0, attention_mask=(x0 > 0).float())[1]\n \n # Connect hidden feature to the latent space\n # latent_z, loss_kl = model_vae.connect(pooled_hidden_fea)\n mean, logvar = model_encoder.linear(pooled_hidden_fea).chunk(2, -1)\n latent_z = mean.squeeze(1)\n\n past = latent_z\n out = sample_sequence_conditional(\n model=model_decoder,\n context=context_tokens,\n past=past,\n length=x_lengths[0,1], # Chunyuan: Fix length; or use <EOS> to complete a sentence\n temperature=args.temperature,\n top_k=args.top_k,\n top_p=args.top_p,\n device=args.device,\n decoder_tokenizer = decoder_tokenizer\n )\n text_x1 = decoder_tokenizer.decode(out[0,:].tolist(), clean_up_tokenization_spaces=True)\n text_x1 = text_x1.split()[1:-1]\n text_x1 = ' '.join(text_x1) + '\\n'\n result[text_x0] = text_x1\n\n count += 1\n if count>args.total_sents:\n break\n \n\n return result\n\n\n\n\ndef calc_interpolate(model_encoder, model_decoder, eval_dataloader, encoder_tokenizer, decoder_tokenizer, args, ns=1):\n\n count = 0\n latent_codes = []\n sample_interval = 0\n for batch in tqdm(eval_dataloader, desc=\"Evaluating interpolation\"):\n # pdb.set_trace()\n x0, x1, x_lengths = batch\n\n max_len_values, _ = x_lengths.max(0)\n x0 = x0[:,:max_len_values[0]]\n x0 = x0.to(args.device)\n x_lengths = x_lengths.to(args.device)\n\n\n with torch.no_grad():\n if sample_interval == 0 or sample_interval == args.total_sents:\n text_x0 = encoder_tokenizer.decode(x0[0,:x_lengths[0,0]].tolist(), clean_up_tokenization_spaces=True)[0]\n pooled_hidden_fea = model_encoder(x0, attention_mask=(x0 > 0).float())[1]\n \n # Connect hidden feature to the latent space\n mean, logvar = model_encoder.linear(pooled_hidden_fea).chunk(2, -1)\n latent_z = mean.squeeze(1)\n \n latent_codes.append(latent_z)\n\n if sample_interval == 5: \n latent_codes.append(latent_z)\n sample_interval = 0\n continue\n else: \n sample_interval += 1\n continue\n\n count += 1\n if count>args.total_sents:\n break \n\n context_tokens = decoder_tokenizer.encode('<BOS>')\n result = defaultdict(str)\n latent_codes_interpolation = []\n num_steps = args.num_interpolation_steps\n for step in range(num_steps+1):\n latent_z = latent_codes[0] + (latent_codes[1] - latent_codes[0]) * step * 1.0/num_steps\n\n past = latent_z\n out = sample_sequence_conditional(\n model=model_decoder,\n context=context_tokens,\n past=past,\n length=x_lengths[0,1], # Chunyuan: Fix length; or use <EOS> to complete a sentence\n temperature=args.temperature,\n top_k=args.top_k,\n top_p=args.top_p,\n device=args.device,\n decoder_tokenizer = decoder_tokenizer\n )\n text_x1 = decoder_tokenizer.decode(out[0,:].tolist(), clean_up_tokenization_spaces=True)\n text_x1 = text_x1.split()[1:-1]\n text_x1 = ' '.join(text_x1) \n result[step] = text_x1\n\n return result\n\n\ndef interpolate(model_encoder, model_decoder, tokenizer_encoder, tokenizer_decoder, args):\n # and then in the main function \n latent_z1, coded_length1 = latent_code_from_text(args.sent_source, tokenizer_encoder, model_encoder, args)\n latent_z2, coded_length2 = latent_code_from_text(args.sent_target, tokenizer_encoder, model_encoder, args)\n result = defaultdict(str)\n\n num_steps = args.num_interpolation_steps + 1\n for step in range(num_steps+1):\n latent_z = latent_z1 + (latent_z2 - latent_z1) * step * 1.0/num_steps\n text_interpolate = text_from_latent_code(latent_z, model_decoder, args, tokenizer_decoder)\n \n result[step] = text_interpolate\n print(text_interpolate)\n\n return result\n\n\ndef analogy(model_encoder, model_decoder, tokenizer_encoder, tokenizer_decoder, args):\n \n latent_z1, coded_length1 = latent_code_from_text(args.sent_source, tokenizer_encoder, model_encoder, args)\n latent_z2, coded_length2 = latent_code_from_text(args.sent_target, tokenizer_encoder, model_encoder, args)\n latent_z3, coded_length3 = latent_code_from_text(args.sent_input, tokenizer_encoder, model_encoder, args)\n \n result = defaultdict(str)\n\n latent_z = latent_z3 + args.degree_to_target * (latent_z2 - latent_z1) \n \n text_analogy = text_from_latent_code(latent_z, model_decoder, args, tokenizer_decoder)\n result[0] = text_analogy\n print(text_analogy)\n\n return result\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--train_data_file\", default=None, type=str, required=True,\n help=\"The input training data file (a text file).\")\n parser.add_argument(\"--eval_data_file\", default=None, type=str,\n help=\"An input evaluation data file to evaluate the perplexity on (a text file).\")\n parser.add_argument(\"--checkpoint_dir\", default=None, type=str, required=True,\n help=\"The directory where checkpoints are saved.\")\n parser.add_argument(\"--output_dir\", default=None, type=str, required=True,\n help=\"The output directory where the model predictions and checkpoints will be written.\")\n parser.add_argument(\"--dataset\", default='Snli', type=str, help=\"The dataset.\")\n\n ## Variational auto-encoder\n parser.add_argument(\"--latent_size\", default=32, type=int, help=\"Latent space dimension.\")\n parser.add_argument(\"--total_sents\", default=10, type=int, help=\"Total sentences to test recontruction.\")\n parser.add_argument(\"--num_interpolation_steps\", default=10, type=int, help=\"Total sentences to test recontruction.\")\n parser.add_argument(\"--play_mode\", default=\"interpolation\", type=str,\n help=\"interpolation or reconstruction.\")\n\n\n ## Encoder options\n parser.add_argument(\"--encoder_model_type\", default=\"bert\", type=str,\n help=\"The encoder model architecture to be fine-tuned.\")\n parser.add_argument(\"--encoder_model_name_or_path\", default=\"bert-base-cased\", type=str,\n help=\"The encoder model checkpoint for weights initialization.\")\n parser.add_argument(\"--encoder_config_name\", default=\"\", type=str,\n help=\"Optional pretrained config name or path if not the same as model_name_or_path\")\n parser.add_argument(\"--encoder_tokenizer_name\", default=\"\", type=str,\n help=\"Optional pretrained tokenizer name or path if not the same as model_name_or_path\")\n\n ## Decoder options\n parser.add_argument(\"--decoder_model_type\", default=\"gpt2\", type=str,\n help=\"The decoder model architecture to be fine-tuned.\")\n parser.add_argument(\"--decoder_model_name_or_path\", default=\"bert-base-cased\", type=str,\n help=\"The decoder model checkpoint for weights initialization.\")\n parser.add_argument(\"--decoder_config_name\", default=\"\", type=str,\n help=\"Optional pretrained config name or path if not the same as model_name_or_path\")\n parser.add_argument(\"--decoder_tokenizer_name\", default=\"\", type=str,\n help=\"Optional pretrained tokenizer name or path if not the same as model_name_or_path\")\n\n\n parser.add_argument(\"--per_gpu_train_batch_size\", default=1, type=int,\n help=\"Batch size per GPU/CPU for training.\")\n parser.add_argument(\"--per_gpu_eval_batch_size\", default=1, type=int,\n help=\"Batch size per GPU/CPU for evaluation.\")\n parser.add_argument('--gloabl_step_eval', type=int, default=661,\n help=\"Evaluate the results at the given global step\")\n\n parser.add_argument(\"--max_seq_length\", default=512, type=int,\n help=\"Optional input sequence length before tokenization. The sequence will be dropped if it is longer the max_seq_length\")\n\n # Interact with users\n parser.add_argument(\"--interact_with_user_input\", action='store_true', help=\"Use user input to interact_with.\")\n parser.add_argument(\"--sent_source\", type=str, default=\"\")\n parser.add_argument(\"--sent_target\", type=str, default=\"\")\n parser.add_argument(\"--sent_input\", type=str, default=\"\")\n parser.add_argument(\"--degree_to_target\", type=float, default=\"1.0\")\n\n ## Variational auto-encoder\n parser.add_argument(\"--nz\", default=32, type=int,\n help=\"Latent space dimension.\")\n\n parser.add_argument(\"--prompt\", type=str, default=\"\")\n parser.add_argument(\"--padding_text\", type=str, default=\"\")\n parser.add_argument(\"--length\", type=int, default=20)\n parser.add_argument(\"--temperature\", type=float, default=1.0)\n parser.add_argument(\"--top_k\", type=int, default=0)\n parser.add_argument(\"--top_p\", type=float, default=1.0)\n parser.add_argument(\"--no_cuda\", action='store_true',\n help=\"Avoid using CUDA when available\")\n parser.add_argument('--seed', type=int, default=42,\n help=\"random seed for initialization\")\n\n parser.add_argument(\"--block_size\", default=-1, type=int,\n help=\"Optional input sequence length after tokenization.\"\n \"The training dataset will be truncated in block of this size for training.\"\n \"Default to the model max input length for single sentence inputs (take into account special tokens).\")\n parser.add_argument(\"--do_lower_case\", action='store_true',\n help=\"Set this flag if you are using an uncased model.\")\n\n parser.add_argument(\"--use_philly\", action='store_true',\n help=\"Use Philly for computing.\")\n\n args = parser.parse_args()\n\n args.device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n args.n_gpu = torch.cuda.device_count()\n\n set_seed(args)\n\n args.encoder_model_type = args.encoder_model_type.lower()\n args.decoder_model_type = args.decoder_model_type.lower()\n global_step = args.gloabl_step_eval\n\n output_encoder_dir = os.path.join(args.checkpoint_dir, 'checkpoint-encoder-{}'.format(global_step))\n output_decoder_dir = os.path.join(args.checkpoint_dir, 'checkpoint-decoder-{}'.format(global_step)) \n checkpoints = [ [output_encoder_dir, output_decoder_dir] ]\n logger.info(\"Evaluate the following checkpoints: %s\", checkpoints)\n\n # Load a trained Encoder model and vocabulary that you have fine-tuned\n encoder_config_class, encoder_model_class, encoder_tokenizer_class = MODEL_CLASSES[args.encoder_model_type]\n model_encoder = encoder_model_class.from_pretrained(output_encoder_dir, latent_size=args.latent_size)\n tokenizer_encoder = encoder_tokenizer_class.from_pretrained(args.encoder_tokenizer_name if args.encoder_tokenizer_name else args.encoder_model_name_or_path, do_lower_case=args.do_lower_case)\n\n model_encoder.to(args.device)\n if args.block_size <= 0:\n args.block_size = tokenizer_encoder.max_len_single_sentence # Our input block size will be the max possible for the model\n args.block_size = min(args.block_size, tokenizer_encoder.max_len_single_sentence)\n\n # Load a trained Decoder model and vocabulary that you have fine-tuned\n decoder_config_class, decoder_model_class, decoder_tokenizer_class = MODEL_CLASSES[args.decoder_model_type]\n model_decoder = decoder_model_class.from_pretrained(output_decoder_dir, latent_size=args.latent_size)\n tokenizer_decoder = decoder_tokenizer_class.from_pretrained(args.decoder_tokenizer_name if args.decoder_tokenizer_name else args.decoder_model_name_or_path, do_lower_case=args.do_lower_case)\n model_decoder.to(args.device)\n if args.block_size <= 0:\n args.block_size = tokenizer_decoder.max_len_single_sentence # Our input block size will be the max possible for the model\n args.block_size = min(args.block_size, tokenizer_decoder.max_len_single_sentence)\n\n # Load full model\n # output_full_dir = os.path.join(args.checkpoint_dir, 'checkpoint-full-{}'.format(global_step)) # Paolo\n # checkpoint = torch.load(os.path.join(output_full_dir, 'training.bin'), map_location=torch.device('cpu')) # Paolo\n\n # Chunyuan: Add Padding token to GPT2\n special_tokens_dict = {'pad_token': '<PAD>', 'bos_token': '<BOS>', 'eos_token': '<EOS>'}\n num_added_toks = tokenizer_decoder.add_special_tokens(special_tokens_dict)\n print('We have added', num_added_toks, 'tokens to GPT2')\n model_decoder.resize_token_embeddings(len(tokenizer_decoder)) # Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e. the length of the tokenizer.\n assert tokenizer_decoder.pad_token == '<PAD>'\n\n \n # Evaluation\n # model_vae = VAE(model_encoder, model_decoder, tokenizer_encoder, tokenizer_decoder, args) # Paolo\n # model_vae.load_state_dict(checkpoint['model_state_dict']) # Paolo\n # logger.info(\"Pre-trained Optimus is successfully loaded\") # Paolo\n # model_vae.to(args.device) # Paolo\n\n if args.interact_with_user_input:\n\n if args.play_mode == 'interpolation':\n if len(args.sent_source) > 0 and len(args.sent_source) > 0:\n result = interpolate(model_encoder, model_decoder, tokenizer_encoder, tokenizer_decoder, args)\n else:\n print('Please check: specify the source and target sentences!')\n\n if args.play_mode == 'analogy':\n if len(args.sent_source) > 0 and len(args.sent_source) > 0 and len(args.sent_input) > 0:\n result = analogy(model_encoder, model_decoder, tokenizer_encoder, tokenizer_decoder, args)\n else:\n print('Please check: specify the source, target and input analogy sentences!')\n\n\n else:\n result = evaluate_latent_space(args, model_encoder, model_decoder, tokenizer_encoder, tokenizer_decoder, prefix=global_step)\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"torch.nn.functional.softmax",
"torch.Tensor",
"numpy.random.seed",
"torch.zeros",
"torch.manual_seed",
"torch.tensor",
"torch.no_grad",
"torch.sort",
"torch.cuda.manual_seed_all",
"torch.cuda.is_available",
"torch.topk",
"torch.Tensor.long",
"torch.cuda.device_count"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
26medias/GAN-toolkit | [
"8d4d0cc8a8e8bd74e4af9abac19994c7e2f68f6f"
] | [
"verifier/face_verifier.py"
] | [
"from .facenet.inception_resnet_v1 import InceptionResNetV1\nfrom keras.layers import Lambda, Input\nfrom keras.models import Model\nfrom keras import backend as K\nimport tensorflow as tf\nimport numpy as np\nfrom scipy.spatial import distance\nfrom pathlib import Path\n\nFILE_PATH = str(Path(__file__).parent.resolve())\n\nclass FaceVerifier():\n def __init__(self, resolution=None, weights_path=\"/content/face-recognition/facenet_keras_weights_VGGFace2.h5\", classes=512):\n self.weights_path = weights_path\n self.input_resolution = 160\n self.latent_dim = classes\n \n self.net = self.build_networks(resolution, classes=classes) \n self.net.trainable = False\n \n self.detector = False\n \n def build_networks(self, resolution=None, classes=128):\n \"\"\"\n FaceNet().net expects input images that have pixels normalized to [-1, +1].\n \"\"\"\n input_tensor \t= Input((resolution, resolution, 3))\n facenet \t\t= InceptionResNetV1(weights_path=self.weights_path, classes=classes)\n facenet \t\t= Model(facenet.inputs, facenet.layers[-1].output) # layers[-1] is a BN layers\n rescale_layer\t= self.rescale()\n preprocess_layer= self.preprocess()\n l2_normalize \t= self.l2_norm()\n output_tensor\t= l2_normalize(facenet(preprocess_layer(rescale_layer(input_tensor)))) \n \n return Model(input_tensor, output_tensor)\n \n def set_detector(self, detector):\n self.detector = detector\n \n def preprocess(self): \n def preprocess_facenet(x):\n \"\"\" \n tf.image.per_image_standardization\n K.mean & K.std axis being [-3,-2,-1] or [-1,-2,-3] does nor affect output\n since the output shape is [batch_size, 1, 1, 1].\n \"\"\"\n x = (x - 127.5) / 128\n x = K.map_fn(lambda im: tf.image.per_image_standardization(im), x)\n return x \n \n input_tensor = Input((None, None, 3)) \n x = Lambda(\n lambda x: tf.image.resize_bilinear(\n x, \n [self.input_resolution, self.input_resolution]\n ))(input_tensor)\n output_tensor = Lambda(preprocess_facenet)(x) \n return Model(input_tensor, output_tensor)\n \n def rescale(self):\n \"\"\"\n Scale image fomr range [-1, +1] to [0, 255].\n \"\"\"\n def scale(x):\n return (x + 1) / 2 * 255\n \n input_tensor = Input((None, None, 3)) \n output_tensor = Lambda(scale)(input_tensor)\n return Model(input_tensor, output_tensor)\n \n def l2_norm(self): \n input_tensor = Input((self.latent_dim,))\n output_tensor = Lambda(lambda x: K.l2_normalize(x))(input_tensor)\n return Model(input_tensor, output_tensor)\n \n def verify(self, im1, im2, threshold=0.5, with_detection=False, return_distance=True):\n emb1 = self.extract_embeddings(im1, with_detection=with_detection)\n emb2 = self.extract_embeddings(im2, with_detection=with_detection)\n \n dist = self.compute_cosine_distance(emb1, emb2)\n is_same_person = (dist <= threshold)\n if return_distance:\n return is_same_person, dist\n else:\n return is_same_person\n \n def extract_embeddings(self, im, with_detection=False):\n if with_detection:\n try:\n faces = self.detector.detect_face(im, with_landmarks=False)\n except:\n raise NameError(\"Error occured duaring face detection. \\\n Please check if face detector has been set through set_detector().\")\n if len(faces) > 1:\n print(\"Multiple faces detected, only the most confident one is used for verification.\")\n most_conf_idx = np.argmax(faces, axis=0)[-1]\n faces = faces[most_conf_idx:most_conf_idx+1]\n x0, y0, x1, y1, _ = faces[0].astype(np.int32)\n face = im[x0:x1, y0:y1]\n else:\n face = im\n \n input_array = face[np.newaxis, ...] \n input_array = input_array / 255 * 2 - 1\n embeddings = self.net.predict([input_array])\n return embeddings \n \n @staticmethod\n def compute_cosine_distance(emb1, emb2):\n return distance.cosine(emb1, emb2)\n \n "
] | [
[
"tensorflow.image.resize_bilinear",
"numpy.argmax",
"scipy.spatial.distance.cosine",
"tensorflow.image.per_image_standardization"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": [
"1.10"
]
}
] |
VirkSaab/Medical-VQA | [
"6d77963cc81940fc680a18d931e0d88a3264f5fa"
] | [
"mvqag/experiments/abnormality/2020.py"
] | [
"import torch\nimport torch.nn as nn\nimport torchvision.transforms as T\nimport pandas as pd\nfrom typing import Dict, List\nfrom torchcontrib.optim import SWA\nfrom pathlib import Path\nfrom mvqag import CNF_PATH\nfrom mvqag.utils import load_yaml, load_json, get_recent_githash, load_qa_file\nfrom mvqag.data import (\n VQADataset,\n DataLoaders,\n Tokenizer,\n vqa_collate_fn,\n generate_new_questions_dataframe\n)\nfrom mvqag.model import VQANet, SANNet\nfrom mvqag.train import (\n get_device,\n get_metrics,\n LabelSmoothingCrossEntropyWithSuperLoss,\n LabelSmoothingCrossEntropy,\n SuperLoss,\n VQATrainer,\n TrainingLogger,\n Checkpointer,\n mixup_data_vqa,\n mixup_criterion_vqa,\n)\n\n\nclass PrepareCLEF2020DataWithQ:\n def __init__(self, CNF) -> None:\n self.n_classes = CNF.data.n_classes\n self.QG = CNF.data.QG\n\n # TRAINING DATA\n # This is the main dataset for training\n train20_df = self._make_dataframe(\n columns=CNF.clef_cols.default,\n qa_path=CNF.paths.clef_20_train_qa,\n imgs_path=CNF.paths.clef_20_train_imgs,\n is_main_df=True\n )\n # Get categorical abnormality classes\n self.classes = train20_df.A.unique().tolist()\n if self.n_classes == 330:\n if 'no' in self.classes:\n self.classes.remove('no')\n if 'yes' in self.classes:\n self.classes.remove('yes')\n self.classes = sorted(self.classes)\n assert len(self.classes) == self.n_classes\n # Remove yes/no classes from train20_df\n train20_df = pd.DataFrame([\n row for row in train20_df.itertuples() if row.A in self.classes\n ]).drop(\"Index\", axis=1)\n\n # Filter abnormality data from other ImageCLEF datasets\n train19_df = self._make_dataframe(\n columns=CNF.clef_cols.default,\n qa_path=CNF.paths.clef_19_train_qa,\n imgs_path=CNF.paths.clef_19_train_imgs\n )\n val19_df = self._make_dataframe(\n columns=CNF.clef_cols.default,\n qa_path=CNF.paths.clef_19_val_qa,\n imgs_path=CNF.paths.clef_19_val_imgs\n )\n test19_df = self._make_dataframe(\n columns=CNF.clef_cols.test19,\n qa_path=CNF.paths.clef_19_test_qa,\n imgs_path=CNF.paths.clef_19_test_imgs\n )\n test19_df = test19_df.drop('Task', axis=1)\n training_dfs = [train19_df, val19_df, test19_df, train20_df]\n self.train_df = pd.concat(\n training_dfs, ignore_index=True\n ).reset_index(drop=True)\n\n self.val_df = self._make_dataframe(\n columns=CNF.clef_cols.default,\n qa_path=CNF.paths.clef_20_val_qa,\n imgs_path=CNF.paths.clef_20_val_imgs\n )\n\n # Augmentation\n self.train_tfms = T.Compose([\n T.Resize(size=(CNF.model.inp_size + 8, CNF.model.inp_size + 8)),\n # T.AutoAugment(),\n T.RandomCrop(size=(CNF.model.inp_size, CNF.model.inp_size)),\n T.RandomHorizontalFlip(),\n T.ToTensor(),\n T.Normalize(\n mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)\n )\n ])\n self.val_tfms = T.Compose([\n T.Resize(size=(CNF.model.inp_size, CNF.model.inp_size)),\n T.ToTensor(),\n T.Normalize(\n mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)\n )\n ])\n # Generate new questions for training dataset\n if CNF.data.QG:\n print(f\"Before QG: # training samples = {self.train_df.shape[0]}\")\n self.train_df = self._generate_questions(self.train_df,\n CNF.task_keywords)\n print(f\"After QG: # training samples = {self.train_df.shape[0]}\")\n self.tokenizer = Tokenizer.from_list(\n self.train_df.Q.unique().tolist(),\n max_len=CNF.model.max_len\n )\n # Make dataset classes\n self.trainset = VQADataset(\n self.train_df, self.train_tfms, self.classes, self.tokenizer\n )\n self.valset = VQADataset(\n self.val_df, self.val_tfms, self.classes, self.tokenizer\n )\n # Make dataloaders\n self.dls = DataLoaders.from_dataset(\n trainset=self.trainset,\n train_bs=CNF.train.bs,\n valset=self.valset,\n val_bs=1,\n collate_fn=vqa_collate_fn\n )\n\n def _make_dataframe(self,\n columns,\n qa_path,\n imgs_path,\n is_main_df=False):\n df = load_qa_file(qa_filepath=qa_path, columns=columns)\n df['PATH'] = df.ID.apply(lambda x: f\"{imgs_path}/{x}.jpg\")\n if not is_main_df:\n df = pd.DataFrame([\n row for row in df.itertuples() if row.A in self.classes\n ]).drop(\"Index\", axis=1)\n return df\n\n def _generate_questions(\n self,\n train_df: pd.DataFrame,\n task_keywords: Dict[str, List[str]]\n ) -> pd.DataFrame:\n new_train_df = generate_new_questions_dataframe(\n train_df, task_keywords\n )\n new_train_df = new_train_df[new_train_df.Task == 'abnormality']\n new_train_df = new_train_df[new_train_df.SubTask == 'categorical']\n return new_train_df\n\n def check(self):\n print(f\"Data augmentation:\\n\\t{self.train_tfms}\", end='')\n print(f\"\\n\\t{self.val_tfms}\")\n print(f\"# training samples = {self.train_df.shape}\")\n print(f\"# validation samples = {self.val_df.shape}\")\n if self.n_classes == 330:\n assert self.train_df.shape == (4963, 4)\n assert self.val_df.shape == (472, 4)\n elif self.n_classes == 332:\n if self.QG:\n assert self.train_df.shape == (39704, 6)\n else:\n assert self.train_df.shape == (6583, 4)\n assert self.val_df.shape == (500, 4)\n else:\n _errmsg = f\"check not added for classes = {self.n_classes}\"\n raise NotImplementedError(_errmsg)\n assert self.train_df.A.nunique() <= self.n_classes\n assert self.val_df.A.nunique() <= self.n_classes\n assert len(self.trainset) == self.train_df.shape[0]\n assert len(self.valset) == self.val_df.shape[0]\n\n batch = next(iter(self.dls.trainloader))\n print(f\"data batch:\")\n print(f\"\\tV = {batch['inputs']['V'].shape}\")\n print(f\"\\tQ = {batch['inputs']['Q']['input_ids'].shape}\")\n print(f\"\\tA = {batch['target'].shape}\")\n print(\"data check: [green]PASSED[/green]\")\n\n\nclass CLEFTrainer(VQATrainer):\n def __init__(self, dls, net, loss_fn, optm_fn, device,\n metrics=None,\n checkpointer=None,\n logger=None,\n step_lrs=None,\n epoch_lrs=None,\n mixup: float = 0.):\n super().__init__(dls, net, loss_fn, optm_fn, device, metrics,\n checkpointer, logger, step_lrs, epoch_lrs)\n self.mixup = mixup\n\n def train_one_batch(self, batch):\n target = batch['target'].to(self.device)\n V = batch['inputs']['V'].to(self.device)\n Q = {\n k: v.to(self.device) for k, v in batch['inputs']['Q'].items()\n }\n if self.mixup > 0.0:\n Q = Q['input_ids']\n mixed_v, a_a, a_b, q_a, q_b, lam = mixup_data_vqa(\n V, Q, target, alpha=self.mixup, use_cuda=True\n )\n output_a = self.net(mixed_v, {'input_ids': q_a})\n output_b = self.net(mixed_v, {'input_ids': q_b})\n loss = mixup_criterion_vqa(\n self.loss_fn, output_a, output_b, a_a, a_b, lam)\n output = (lam * output_a) + ((1 - lam) * output_b)\n else:\n output = self.net(V, Q)\n loss = self.loss_fn(output, target)\n # Backpropagation\n self.optm_fn.zero_grad()\n loss.backward()\n self.optm_fn.step()\n return loss, output, target\n\n def val_one_batch(self, batch):\n target = batch['target'].to(self.device)\n V = batch['inputs']['V'].to(self.device)\n Q = {\n k: v.to(self.device) for k, v in batch['inputs']['Q'].items()\n }\n output = self.net(V, Q)\n\n # test time augmentation\n assert V.dim() == 4, 'You need to provide a [B,C,H,W] image to flip'\n Vs_flip = torch.flip(V, [3])\n output_flip = self.net(Vs_flip, Q)\n output = (output + output_flip) / 2.0\n\n loss = self.loss_fn(output, target)\n return loss, output, target\n\n\ndef run(CNF: dict, dm=None, ret_model_and_dm: bool = False):\n # ---------------------------------------- SETTINGS:\n # Set seed\n torch.manual_seed(CNF.seed)\n torch.cuda.manual_seed(CNF.seed)\n torch.cuda.manual_seed_all(CNF.seed)\n\n # Set device\n CNF.device, CNF.cuda_ids = get_device()\n # Get the githash of last commit\n CNF.recent_githash = get_recent_githash()\n\n # ---------------------------------------- DATA:\n if dm is None:\n dm = PrepareCLEF2020DataWithQ(CNF)\n dm.check()\n\n # ---------------------------------------- MODEL:\n model_name = f\"{CNF.model.vnet_name}_{CNF.model.qnet_name}\"\n print(f\"Loading {model_name} model...\", end=' ')\n if CNF.model.use_SAN:\n CNF.wandb_run_name += f\"+{model_name}+SAN\"\n model = SANNet(\n n_classes=CNF.data.n_classes,\n vnet_name=CNF.model.vnet_name,\n qnet_name=CNF.model.qnet_name,\n vocab_dim=dm.tokenizer.vocab_dim,\n emb_dim=CNF.model.emb_dim,\n vdp=CNF.model.vdp,\n qdp=CNF.model.qdp\n )\n else:\n CNF.wandb_run_name += f\"+{model_name}\"\n model = VQANet(\n n_classes=CNF.data.n_classes,\n vnet_name=CNF.model.vnet_name,\n qnet_name=CNF.model.qnet_name,\n vocab_dim=dm.tokenizer.vocab_dim,\n emb_dim=CNF.model.emb_dim,\n hid_dim=1024,\n bidirect=True,\n vdp=CNF.model.vdp,\n qdp=CNF.model.qdp\n )\n model.to(CNF.device)\n model = torch.nn.DataParallel(model, device_ids=CNF.cuda_ids)\n print('done.')\n\n # ---------------------------------------- TRAIN:\n optm_fn = torch.optim.SGD(model.parameters(),\n lr=CNF.optm.lr,\n momentum=CNF.optm.mom,\n weight_decay=CNF.optm.wd,\n )\n if CNF.loss.fn.lower() == 'lscesl':\n loss_fn = LabelSmoothingCrossEntropyWithSuperLoss(rank=CNF.device)\n elif CNF.loss.fn.lower() == 'superloss':\n loss_fn = SuperLoss(rank=CNF.device)\n elif CNF.loss.fn.lower() == 'crossentropy':\n loss_fn = nn.CrossEntropyLoss(\n reduction='mean',\n label_smoothing=CNF.loss.smoothing\n )\n elif CNF.loss.fn.lower() == 'celsv2':\n loss_fn = LabelSmoothingCrossEntropy(classes=CNF.data.n_classes)\n else:\n raise NotImplementedError(f'Loss_fn {CNF.loss.fn} not supported.')\n print(f\"Criterion = {CNF.loss.fn}\")\n epoch_lrs = torch.optim.lr_scheduler.StepLR(optm_fn,\n step_size=20,\n gamma=0.60)\n logger = TrainingLogger(\n logs_dir=CNF.paths.logs_dir, config=CNF, run_name=CNF.wandb_run_name\n )\n checkpointer = Checkpointer(chkpts_dir=CNF.paths.chkpts_dir,\n chkpt_of=[{'ValAccuracyMicro': 'max'}])\n if CNF.train.use_swa: # Stochastic Weight Averaging\n optm_fn = SWA(optm_fn, swa_start=20, swa_freq=5, swa_lr=0.005)\n trainer = CLEFTrainer(dls=dm.dls,\n net=model,\n loss_fn=loss_fn,\n optm_fn=optm_fn,\n device=CNF.device,\n metrics=get_metrics(CNF.data.n_classes),\n logger=logger,\n checkpointer=checkpointer,\n epoch_lrs=epoch_lrs,\n mixup=CNF.train.vqa_mixup\n )\n if CNF.is_test_run:\n trainer.train(2, max_train_iters=5, max_val_iters=5)\n else:\n trainer.train(CNF.train.n_epochs)\n if CNF.train.use_swa:\n optm_fn.swap_swa_sgd()\n\n if ret_model_and_dm:\n return trainer.net, dm\n \n\nif __name__ == '__main__':\n # * EXPERIMENT NUMBER\n EXP_NO = 2\n\n # * Baseline settings\n CNF = load_yaml(CNF_PATH)\n CNF.data.n_classes = 332\n CNF.data.QG = False # Questions generation\n CNF.model.use_SAN = False # If False, use multiplication fusion\n CNF.train.use_swa = False # Stochastic Weight Averaging\n CNF.wandb_run_name = '/'.join(__file__.split('.')[0].split('/')[-2:])\n CNF.wandb_run_name = f\"{EXP_NO}-{CNF.wandb_run_name}+332\"\n\n CNF.is_test_run = False\n\n if EXP_NO == 1:\n # * EXP 1 - our baseline with SYSU curated dataset\n # Baseline experiment\n pass\n\n elif EXP_NO == 2:\n CNF.loss.fn = 'celsv2'\n CNF.train.vqa_mixup = 0.1\n CNF.wandb_run_name += '+VQAMixUp'\n\n elif EXP_NO == 3:\n CNF.loss.smoothing = 0.1\n CNF.train.vqa_mixup = 0.1\n CNF.wandb_run_name += '+VQAMixUp+LabelSmoothing'\n\n elif EXP_NO == 4:\n CNF.model.vnet_name = 'vgg16mixpool'\n CNF.loss.smoothing = 0.1\n CNF.train.vqa_mixup = 0.1\n CNF.wandb_run_name += '+VQAMixUp+LabelSmoothing'\n\n elif EXP_NO == 5:\n CNF.model.vnet_name = 'vgg16mixpool'\n CNF.loss.fn = 'lscesl'\n CNF.train.vqa_mixup = 0.1\n CNF.wandb_run_name += '+VQAMixup+LSCESL'\n\n elif EXP_NO == 6:\n CNF.train.use_swa = True\n CNF.wandb_run_name += '+SWA'\n\n elif EXP_NO == 7:\n CNF.train.use_swa = True\n CNF.train.vqa_mixup = 0.1\n CNF.wandb_run_name += '+SWA+VQAMixUp'\n\n elif EXP_NO == 8:\n CNF.data.QG = True\n CNF.train.vqa_mixup = 0.1\n CNF.loss.smoothing = 0.1\n CNF.wandb_run_name += '+QG+VQAMixUp+LabelSmoothing'\n\n elif EXP_NO == 9:\n CNF.data.QG = True\n CNF.model.use_SAN = True\n CNF.train.vqa_mixup = 0.1\n CNF.loss.smoothing = 0.1\n CNF.wandb_run_name += '+QG+VQAMixUp+LabelSmoothing'\n\n elif EXP_NO == 10:\n CNF.data.QG = True\n CNF.model.use_SAN = True\n CNF.train.vqa_mixup = 0.1\n CNF.loss.smoothing = 0.1\n CNF.loss.fn = 'lscesl'\n CNF.wandb_run_name += '+QG+VQAMixUp+LSCESL'\n\n elif EXP_NO == 11:\n CNF.data.QG = True\n CNF.model.vnet_name = 'vgg16mixpool'\n CNF.model.use_SAN = True\n CNF.train.vqa_mixup = 0.1\n CNF.loss.smoothing = 0.1\n CNF.loss.fn = 'lscesl'\n CNF.wandb_run_name += '+QG+VQAMixUp+LSCESL'\n\n elif EXP_NO == 12:\n CNF.data.QG = True\n CNF.model.vnet_name = 'vgg16mixpool'\n CNF.loss.fn = 'lscesl'\n CNF.train.vqa_mixup = 0.1\n CNF.wandb_run_name += '+QG+VQAMixup+LSCESL'\n\n elif EXP_NO == 13:\n CNF.model.vnet_name = 'vgg16mixpool'\n CNF.model.use_SAN = True\n CNF.train.vqa_mixup = 0.1\n CNF.loss.smoothing = 0.1\n CNF.wandb_run_name += '+VQAMixUp+LabelSmoothing'\n\n elif EXP_NO == 14:\n CNF.data.QG = True\n CNF.wandb_run_name += '+QG'\n\n elif EXP_NO == 15:\n CNF.model.use_SAN = True\n\n elif EXP_NO == 16:\n CNF.data.QG = True\n CNF.model.use_SAN = True\n CNF.loss.fn = 'celsv2' # to run on older pytorch versions\n CNF.loss.smoothing = 0.1\n CNF.train.vqa_mixup = 0.1\n CNF.wandb_run_name += '+VQAMixUp+QG+LabelSmoothing'\n\n \n # Sanity check\n assert CNF.train.bs == 32\n run(CNF)\n"
] | [
[
"torch.flip",
"pandas.concat",
"torch.nn.CrossEntropyLoss",
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.cuda.manual_seed_all",
"torch.nn.DataParallel",
"torch.optim.lr_scheduler.StepLR"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
manigalati/ACDC2017 | [
"e27e4b13ff5dc81eba5594c8b745d580b9603ea3"
] | [
"dataset_utils.py"
] | [
"# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport SimpleITK as sitk\nimport os\nfrom multiprocessing import pool\nimport pickle\nimport numpy as np\nfrom skimage.transform import resize\n\ndef resize_image(image, old_spacing, new_spacing, order=3):\n new_shape = (int(np.round(old_spacing[0]/new_spacing[0]*float(image.shape[0]))),\n int(np.round(old_spacing[1]/new_spacing[1]*float(image.shape[1]))),\n int(np.round(old_spacing[2]/new_spacing[2]*float(image.shape[2]))))\n return resize(image, new_shape, order=order, mode='edge')\n\nstr_to_ind = {'DCM':0, 'HCM':1, 'MINF':2, 'NOR':3, 'RV':4}\nind_to_str = {}\nfor k in str_to_ind.keys():\n ind_to_str[str_to_ind[k]] = k\n\n\ndef view_patient_raw_data(patient, width=400, height=400):\n import batchviewer\n a = []\n a.append(patient['ed_data'][None])\n a.append(patient['ed_gt'][None])\n a.append(patient['es_data'][None])\n a.append(patient['es_gt'][None])\n batchviewer.view_batch(np.vstack(a), width, height)\n\n\ndef convert_to_one_hot(seg):\n vals = np.unique(seg)\n res = np.zeros([len(vals)] + list(seg.shape), seg.dtype)\n for c in range(len(vals)):\n res[c][seg == c] = 1\n return res\n\n\ndef preprocess_image(itk_image, is_seg=False, spacing_target=(1, 0.5, 0.5), keep_z_spacing=False):\n spacing = np.array(itk_image.GetSpacing())[[2, 1, 0]]\n image = sitk.GetArrayFromImage(itk_image).astype(float)\n if keep_z_spacing:\n spacing_target = list(spacing_target)\n spacing_target[0] = spacing[0]\n if not is_seg:\n order_img = 3\n if not keep_z_spacing:\n order_img = 1\n image = resize_image(image, spacing, spacing_target, order=order_img).astype(np.float32)\n image -= image.mean()\n image /= image.std()\n else:\n tmp = convert_to_one_hot(image)\n vals = np.unique(image)\n results = []\n for i in range(len(tmp)):\n results.append(resize_image(tmp[i].astype(float), spacing, spacing_target, 1)[None])\n image = vals[np.vstack(results).argmax(0)]\n return image\n\n\ndef load_dataset(ids=range(101), root_dir=\"/home/fabian/drives/E132-Projekte/ACDC/new_dataset_preprocessed_for_2D_v2/\"):\n print(root_dir)\n with open(os.path.join(root_dir, \"patient_info.pkl\"), 'rb') as f:\n patient_info = pickle.load(f)\n\n data = {}\n for i in ids:\n if os.path.isfile(os.path.join(root_dir, \"pat_%03.0d.npy\"%i)):\n a = np.load(os.path.join(root_dir, \"pat_%03.0d.npy\"%i), mmap_mode='r')\n data[i] = {}\n data[i]['height'] = patient_info[i]['height']\n data[i]['weight'] = patient_info[i]['weight']\n data[i]['pathology'] = patient_info[i]['pathology']\n data[i]['ed_data'] = a[0, :]\n data[i]['ed_gt'] = a[1, :]\n data[i]['es_data'] = a[2, :]\n data[i]['es_gt'] = a[3, :]\n return data\n\n\n\ndef process_patient(args):\n id, patient_info, folder, folder_out, keep_z_spc = args\n #print id\n # if id in [286, 288]:\n # return\n patient_folder = os.path.join(folder, \"patient%03.0d\"%id)\n if not os.path.isdir(patient_folder):\n return\n images = {}\n\n fname = os.path.join(patient_folder, \"patient%03.0d_frame%02.0d.nii.gz\" % (id, patient_info[id]['ed']))\n if os.path.isfile(fname):\n images[\"ed\"] = sitk.ReadImage(fname)\n fname = os.path.join(patient_folder, \"patient%03.0d_frame%02.0d_gt.nii.gz\" % (id, patient_info[id]['ed']))\n if os.path.isfile(fname):\n images[\"ed_seg\"] = sitk.ReadImage(fname)\n fname = os.path.join(patient_folder, \"patient%03.0d_frame%02.0d.nii.gz\" % (id, patient_info[id]['es']))\n if os.path.isfile(fname):\n images[\"es\"] = sitk.ReadImage(fname)\n fname = os.path.join(patient_folder, \"patient%03.0d_frame%02.0d_gt.nii.gz\" % (id, patient_info[id]['es']))\n if os.path.isfile(fname):\n images[\"es_seg\"] = sitk.ReadImage(fname)\n\n print(id, images[\"es_seg\"].GetSpacing())\n\n for k in images.keys():\n #print k\n images[k] = preprocess_image(images[k], is_seg=(k == \"ed_seg\" or k == \"es_seg\"),\n spacing_target=(10, 1.25, 1.25), keep_z_spacing=keep_z_spc)\n\n img_as_list = []\n for k in ['ed', 'ed_seg', 'es', 'es_seg']:\n if k not in images.keys():\n print(id, \"has missing key:\", k)\n img_as_list.append(images[k][None])\n try:\n all_img = np.vstack(img_as_list)\n except:\n print(id, \"has a problem with spacings\")\n np.save(os.path.join(folder_out, \"pat_%03.0d\" % id), all_img.astype(np.float32))\n\n\n\ndef generate_patient_info(folder):\n patient_info={}\n for id in range(151):\n fldr = os.path.join(folder, 'patient%03.0d'%id)\n if not os.path.isdir(fldr):\n print(\"could not find dir of patient \", id)\n continue\n nfo = np.loadtxt(os.path.join(fldr, \"Info.cfg\"), dtype=str, delimiter=': ')\n patient_info[id] = {}\n patient_info[id]['ed'] = int(nfo[0, 1])\n patient_info[id]['es'] = int(nfo[1, 1])\n patient_info[id]['height'] = float(nfo[3, 1])\n patient_info[id]['pathology'] = nfo[2, 1]\n patient_info[id]['weight'] = float(nfo[5, 1])\n return patient_info\n\n\ndef run_preprocessing(folder=\"/media/fabian/My Book/datasets/ACDC/training/\",\n folder_out = \"/media/fabian/DeepLearningData/datasets/ACDC_forReal_orig_Z/\", keep_z_spacing=True):\n patient_info = generate_patient_info(folder)\n\n if not os.path.isdir(folder_out):\n os.mkdir(folder_out)\n with open(os.path.join(folder_out, \"patient_info.pkl\"), 'wb') as f:\n pickle.dump(patient_info, f)\n\n # beware of z spacing!!! see process_patient for more info!\n ids = range(101)\n p = pool.Pool(8)\n p.map(process_patient, zip(ids, [patient_info]*101, [folder]*101, [folder_out]*101, [keep_z_spacing]*101))\n p.close()\n p.join()\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", help=\"folder where the extracted training data is\", type=str)\n parser.add_argument(\"-out2d\", help=\"folder where to save the data for the 2d network\", type=str)\n parser.add_argument(\"-out3d\", help=\"folder where to save the data for the 3d network\", type=str)\n args = parser.parse_args()\n run_preprocessing(args.i, args.out2d, True)\n run_preprocessing(args.i, args.out3d, False)\n"
] | [
[
"numpy.vstack",
"numpy.unique"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.