repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
possible_versions
list
danielhers/stanza
[ "d747a7b781da203c286ec51e3842fecb8b0abb15", "d747a7b781da203c286ec51e3842fecb8b0abb15" ]
[ "stanza/models/pos/model.py", "stanza/models/depparse/trainer.py" ]
[ "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence, pack_sequence, PackedSequence\n\nfrom stanza.models.common.biaffine import BiaffineScorer\nfrom stanza.models.common.hlstm import HighwayLSTM\nfrom stanza.models.common.dropout import WordDropout\nfrom stanza.models.common.vocab import CompositeVocab\nfrom stanza.models.common.char_model import CharacterModel\n\nclass Tagger(nn.Module):\n def __init__(self, args, vocab, emb_matrix=None, share_hid=False):\n super().__init__()\n\n self.vocab = vocab\n self.args = args\n self.share_hid = share_hid\n self.unsaved_modules = []\n\n def add_unsaved_module(name, module):\n self.unsaved_modules += [name]\n setattr(self, name, module)\n\n # input layers\n input_size = 0\n if self.args['word_emb_dim'] > 0:\n # frequent word embeddings\n self.word_emb = nn.Embedding(len(vocab['word']), self.args['word_emb_dim'], padding_idx=0)\n input_size += self.args['word_emb_dim']\n\n if not share_hid:\n # upos embeddings\n self.upos_emb = nn.Embedding(len(vocab['upos']), self.args['tag_emb_dim'], padding_idx=0)\n\n if self.args['char'] and self.args['char_emb_dim'] > 0:\n self.charmodel = CharacterModel(args, vocab)\n self.trans_char = nn.Linear(self.args['char_hidden_dim'], self.args['transformed_dim'], bias=False)\n input_size += self.args['transformed_dim']\n\n if self.args['pretrain']: \n # pretrained embeddings, by default this won't be saved into model file\n add_unsaved_module('pretrained_emb', nn.Embedding.from_pretrained(torch.from_numpy(emb_matrix), freeze=True))\n self.trans_pretrained = nn.Linear(emb_matrix.shape[1], self.args['transformed_dim'], bias=False)\n input_size += self.args['transformed_dim']\n \n # recurrent layers\n self.taggerlstm = HighwayLSTM(input_size, self.args['hidden_dim'], self.args['num_layers'], batch_first=True, bidirectional=True, dropout=self.args['dropout'], rec_dropout=self.args['rec_dropout'], highway_func=torch.tanh)\n self.drop_replacement = nn.Parameter(torch.randn(input_size) / np.sqrt(input_size))\n self.taggerlstm_h_init = nn.Parameter(torch.zeros(2 * self.args['num_layers'], 1, self.args['hidden_dim']))\n self.taggerlstm_c_init = nn.Parameter(torch.zeros(2 * self.args['num_layers'], 1, self.args['hidden_dim']))\n\n # classifiers\n self.upos_hid = nn.Linear(self.args['hidden_dim'] * 2, self.args['deep_biaff_hidden_dim'])\n self.upos_clf = nn.Linear(self.args['deep_biaff_hidden_dim'], len(vocab['upos']))\n self.upos_clf.weight.data.zero_()\n self.upos_clf.bias.data.zero_()\n\n if share_hid:\n clf_constructor = lambda insize, outsize: nn.Linear(insize, outsize)\n else:\n self.xpos_hid = nn.Linear(self.args['hidden_dim'] * 2, self.args['deep_biaff_hidden_dim'] if not isinstance(vocab['xpos'], CompositeVocab) else self.args['composite_deep_biaff_hidden_dim'])\n self.ufeats_hid = nn.Linear(self.args['hidden_dim'] * 2, self.args['composite_deep_biaff_hidden_dim'])\n clf_constructor = lambda insize, outsize: BiaffineScorer(insize, self.args['tag_emb_dim'], outsize)\n\n if isinstance(vocab['xpos'], CompositeVocab):\n self.xpos_clf = nn.ModuleList()\n for l in vocab['xpos'].lens():\n self.xpos_clf.append(clf_constructor(self.args['composite_deep_biaff_hidden_dim'], l))\n else:\n self.xpos_clf = clf_constructor(self.args['deep_biaff_hidden_dim'], len(vocab['xpos']))\n if share_hid:\n self.xpos_clf.weight.data.zero_()\n self.xpos_clf.bias.data.zero_()\n\n self.ufeats_clf = nn.ModuleList()\n for l in vocab['feats'].lens():\n if share_hid:\n self.ufeats_clf.append(clf_constructor(self.args['deep_biaff_hidden_dim'], l))\n self.ufeats_clf[-1].weight.data.zero_()\n self.ufeats_clf[-1].bias.data.zero_()\n else:\n self.ufeats_clf.append(clf_constructor(self.args['composite_deep_biaff_hidden_dim'], l))\n\n # criterion\n self.crit = nn.CrossEntropyLoss(ignore_index=0) # ignore padding\n\n self.drop = nn.Dropout(args['dropout'])\n self.worddrop = WordDropout(args['word_dropout'])\n\n def forward(self, word, word_mask, wordchars, wordchars_mask, upos, xpos, ufeats, pretrained, word_orig_idx, sentlens, wordlens):\n \n def pack(x):\n return pack_padded_sequence(x, sentlens, batch_first=True)\n \n inputs = []\n if self.args['word_emb_dim'] > 0:\n word_emb = self.word_emb(word)\n word_emb = pack(word_emb)\n inputs += [word_emb]\n\n if self.args['pretrain']:\n pretrained_emb = self.pretrained_emb(pretrained)\n pretrained_emb = self.trans_pretrained(pretrained_emb)\n pretrained_emb = pack(pretrained_emb)\n inputs += [pretrained_emb]\n\n def pad(x):\n return pad_packed_sequence(PackedSequence(x, word_emb.batch_sizes), batch_first=True)[0]\n\n if self.args['char'] and self.args['char_emb_dim'] > 0:\n char_reps = self.charmodel(wordchars, wordchars_mask, word_orig_idx, sentlens, wordlens)\n char_reps = PackedSequence(self.trans_char(self.drop(char_reps.data)), char_reps.batch_sizes)\n inputs += [char_reps]\n\n lstm_inputs = torch.cat([x.data for x in inputs], 1)\n lstm_inputs = self.worddrop(lstm_inputs, self.drop_replacement)\n lstm_inputs = self.drop(lstm_inputs)\n lstm_inputs = PackedSequence(lstm_inputs, inputs[0].batch_sizes)\n\n lstm_outputs, _ = self.taggerlstm(lstm_inputs, sentlens, hx=(self.taggerlstm_h_init.expand(2 * self.args['num_layers'], word.size(0), self.args['hidden_dim']).contiguous(), self.taggerlstm_c_init.expand(2 * self.args['num_layers'], word.size(0), self.args['hidden_dim']).contiguous()))\n lstm_outputs = lstm_outputs.data\n\n upos_hid = F.relu(self.upos_hid(self.drop(lstm_outputs)))\n upos_pred = self.upos_clf(self.drop(upos_hid))\n\n preds = [pad(upos_pred).max(2)[1]]\n\n upos = pack(upos).data\n loss = self.crit(upos_pred.view(-1, upos_pred.size(-1)), upos.view(-1))\n\n if self.share_hid:\n xpos_hid = upos_hid\n ufeats_hid = upos_hid\n\n clffunc = lambda clf, hid: clf(self.drop(hid))\n else:\n xpos_hid = F.relu(self.xpos_hid(self.drop(lstm_outputs)))\n ufeats_hid = F.relu(self.ufeats_hid(self.drop(lstm_outputs)))\n\n if self.training:\n upos_emb = self.upos_emb(upos)\n else:\n upos_emb = self.upos_emb(upos_pred.max(1)[1])\n\n clffunc = lambda clf, hid: clf(self.drop(hid), self.drop(upos_emb))\n\n xpos = pack(xpos).data\n if isinstance(self.vocab['xpos'], CompositeVocab):\n xpos_preds = []\n for i in range(len(self.vocab['xpos'])):\n xpos_pred = clffunc(self.xpos_clf[i], xpos_hid)\n loss += self.crit(xpos_pred.view(-1, xpos_pred.size(-1)), xpos[:, i].view(-1))\n xpos_preds.append(pad(xpos_pred).max(2, keepdim=True)[1])\n preds.append(torch.cat(xpos_preds, 2))\n else:\n xpos_pred = clffunc(self.xpos_clf, xpos_hid)\n loss += self.crit(xpos_pred.view(-1, xpos_pred.size(-1)), xpos.view(-1))\n preds.append(pad(xpos_pred).max(2)[1])\n\n ufeats_preds = []\n ufeats = pack(ufeats).data\n for i in range(len(self.vocab['feats'])):\n ufeats_pred = clffunc(self.ufeats_clf[i], ufeats_hid)\n loss += self.crit(ufeats_pred.view(-1, ufeats_pred.size(-1)), ufeats[:, i].view(-1))\n ufeats_preds.append(pad(ufeats_pred).max(2, keepdim=True)[1])\n preds.append(torch.cat(ufeats_preds, 2))\n\n return loss, preds\n", "\"\"\"\nA trainer class to handle training and testing of models.\n\"\"\"\n\nimport sys\nimport logging\nimport torch\nfrom torch import nn\n\nfrom stanza.models.common.trainer import Trainer as BaseTrainer\nfrom stanza.models.common import utils, loss\nfrom stanza.models.common.chuliu_edmonds import chuliu_edmonds_one_root\nfrom stanza.models.depparse.model import Parser\nfrom stanza.models.pos.vocab import MultiVocab\n\nlogger = logging.getLogger('stanza')\n\ndef unpack_batch(batch, use_cuda):\n \"\"\" Unpack a batch from the data loader. \"\"\"\n if use_cuda:\n inputs = [b.cuda() if b is not None else None for b in batch[:11]]\n else:\n inputs = batch[:11]\n orig_idx = batch[11]\n word_orig_idx = batch[12]\n sentlens = batch[13]\n wordlens = batch[14]\n return inputs, orig_idx, word_orig_idx, sentlens, wordlens\n\nclass Trainer(BaseTrainer):\n \"\"\" A trainer for training models. \"\"\"\n def __init__(self, args=None, vocab=None, pretrain=None, model_file=None, use_cuda=False):\n self.use_cuda = use_cuda\n if model_file is not None:\n # load everything from file\n self.load(model_file, pretrain)\n else:\n # build model from scratch\n self.args = args\n self.vocab = vocab\n self.model = Parser(args, vocab, emb_matrix=pretrain.emb if pretrain is not None else None)\n self.parameters = [p for p in self.model.parameters() if p.requires_grad]\n if self.use_cuda:\n self.model.cuda()\n else:\n self.model.cpu()\n self.optimizer = utils.get_optimizer(self.args['optim'], self.parameters, self.args['lr'], betas=(0.9, self.args['beta2']), eps=1e-6)\n\n def update(self, batch, eval=False):\n inputs, orig_idx, word_orig_idx, sentlens, wordlens = unpack_batch(batch, self.use_cuda)\n word, word_mask, wordchars, wordchars_mask, upos, xpos, ufeats, pretrained, lemma, head, deprel = inputs\n\n if eval:\n self.model.eval()\n else:\n self.model.train()\n self.optimizer.zero_grad()\n loss, _ = self.model(word, word_mask, wordchars, wordchars_mask, upos, xpos, ufeats, pretrained, lemma, head, deprel, word_orig_idx, sentlens, wordlens)\n loss_val = loss.data.item()\n if eval:\n return loss_val\n\n loss.backward()\n torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.args['max_grad_norm'])\n self.optimizer.step()\n return loss_val\n\n def predict(self, batch, unsort=True):\n inputs, orig_idx, word_orig_idx, sentlens, wordlens = unpack_batch(batch, self.use_cuda)\n word, word_mask, wordchars, wordchars_mask, upos, xpos, ufeats, pretrained, lemma, head, deprel = inputs\n\n self.model.eval()\n batch_size = word.size(0)\n _, preds = self.model(word, word_mask, wordchars, wordchars_mask, upos, xpos, ufeats, pretrained, lemma, head, deprel, word_orig_idx, sentlens, wordlens)\n head_seqs = [chuliu_edmonds_one_root(adj[:l, :l])[1:] for adj, l in zip(preds[0], sentlens)] # remove attachment for the root\n deprel_seqs = [self.vocab['deprel'].unmap([preds[1][i][j+1][h] for j, h in enumerate(hs)]) for i, hs in enumerate(head_seqs)]\n\n pred_tokens = [[[str(head_seqs[i][j]), deprel_seqs[i][j]] for j in range(sentlens[i]-1)] for i in range(batch_size)]\n if unsort:\n pred_tokens = utils.unsort(pred_tokens, orig_idx)\n return pred_tokens\n\n def save(self, filename, skip_modules=True):\n model_state = self.model.state_dict()\n # skip saving modules like pretrained embeddings, because they are large and will be saved in a separate file\n if skip_modules:\n skipped = [k for k in model_state.keys() if k.split('.')[0] in self.model.unsaved_modules]\n for k in skipped:\n del model_state[k]\n params = {\n 'model': model_state,\n 'vocab': self.vocab.state_dict(),\n 'config': self.args\n }\n try:\n torch.save(params, filename)\n logger.info(\"Model saved to {}\".format(filename))\n except BaseException:\n logger.warning(\"Saving failed... continuing anyway.\")\n\n def load(self, filename, pretrain):\n \"\"\"\n Load a model from file, with preloaded pretrain embeddings. Here we allow the pretrain to be None or a dummy input,\n and the actual use of pretrain embeddings will depend on the boolean config \"pretrain\" in the loaded args.\n \"\"\"\n try:\n checkpoint = torch.load(filename, lambda storage, loc: storage)\n except BaseException:\n logger.exception(\"Cannot load model from {}\".format(filename))\n sys.exit(1)\n self.args = checkpoint['config']\n self.vocab = MultiVocab.load_state_dict(checkpoint['vocab'])\n # load model\n emb_matrix = None\n if self.args['pretrain'] and pretrain is not None: # we use pretrain only if args['pretrain'] == True and pretrain is not None\n emb_matrix = pretrain.emb\n self.model = Parser(self.args, self.vocab, emb_matrix=emb_matrix)\n self.model.load_state_dict(checkpoint['model'], strict=False)\n\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.nn.Dropout", "numpy.sqrt", "torch.cat", "torch.zeros", "torch.randn", "torch.nn.ModuleList", "torch.from_numpy", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.Linear", "torch.nn.utils.rnn.PackedSequence" ], [ "torch.load", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aleaf/usgs-map-gwmodels
[ "284a79484a4531ce725bf07371c3c342ad1791c0" ]
[ "mapgwm/tests/test_swflows.py" ]
[ "import os\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom mapgwm.obs import preprocess_obs\nfrom mapgwm.swflows import aggregrate_values_to_stress_periods, preprocess_flows, combine_measured_estimated_values\n\n\[email protected]()\ndef obsdata():\n return pd.DataFrame({'datetime': ['2001-01-01', # per 0, site 2000\n '2002-01-01', # per 0, site 2001\n '2002-02-02', # per 0, site 2001\n '2014-10-02', # per 1, site 2002\n '2015-01-01', # per 1, site 2002\n '2015-01-02', # per 1, site 2002\n '2015-01-02', # per 1, site 2000\n '2017-01-01', # site 2003\n '2018-01-01', # site 2003\n '2019-01-01'], # site 2000\n 'flow_m3d': [1, 1, 0, 4, 2, 3, 2, 1, 0, 10],\n 'comment': ['measured',\n 'measured',\n 'measured',\n 'estimated',\n 'estimated',\n 'estimated',\n 'estimated',\n 'measured',\n 'measured',\n 'estimated'\n ],\n 'site_no': [2000,\n 2001,\n 2001,\n 2002,\n 2002,\n 2002,\n 2000,\n 2003,\n 2003,\n 2000\n ],\n 'line_id': [1002000,\n 1002001,\n 1002001,\n 1002002,\n 1002002,\n 1002002,\n 1002000,\n 1002003,\n 1002003,\n 1002000\n ]\n })\n\n\[email protected]()\ndef times():\n start_datetime = pd.to_datetime(['2001-01-01', '2014-10-01'])\n end_datetime = pd.to_datetime(['2014-09-30', '2015-09-30'])\n perlen = [(edt - sdt).days for edt, sdt in zip(start_datetime, end_datetime)]\n times = pd.DataFrame({'start_datetime': start_datetime,\n 'end_datetime': end_datetime,\n 'per': [0, 1],\n 'perlen': perlen,\n 'steady': False})\n return times\n\n\[email protected]('category_col', (None, 'comment'))\[email protected]('keep_columns', (None, ['site_no']))\ndef test_aggregrate_values_to_stress_periods(obsdata, times, category_col, keep_columns):\n results = aggregrate_values_to_stress_periods(obsdata, times,\n datetime_col='datetime',\n values_col='flow_m3d',\n id_col='line_id',\n category_col=category_col,\n keep_columns=keep_columns\n )\n sortby = ['per']\n if keep_columns is not None and 'site_no' in keep_columns:\n sortby.append('site_no')\n results.sort_values(by=sortby, inplace=True)\n # there should be results for each site, for each period\n # including -9999 period that represents anything outside of the\n # model timeframe\n if keep_columns is not None and 'site_no' in keep_columns:\n assert np.array_equal(results.site_no.values,\n np.array([2000, 2001, 2002, 2003]*3))\n # rows without measurements should be indicated as filled\n assert np.array_equal(((results.n_estimated == 0) & (results.n_measured == 0)),\n results.filled.values)\n # expected values for filled based on whether site had any measurements in period\n assert results.filled.tolist() == [False, True, True, False, # 2000 and 2003 both had measurements outside model period\n False, False, True, True,\n False, True, False, True]\n assert np.array_equal(results.Q_avg.values,\n np.array([10.00000, # 2000 value outside model period\n 0.500000,\n 3.000000,\n 0.500000,\n 1.000000, # 2000 value in per 0\n 0.500000,\n 3.000000,\n 0.500000,\n 2.000000, # 2000 value in per 1\n 0.500000,\n 3.000000,\n 0.500000]))\n # standard deviations should be nan in rows with fewer than two measurements\n assert np.array_equal(((results.n_estimated < 2) & (results.n_measured < 2)),\n np.isnan(results.Q_std.values))\n if keep_columns is not None and 'site_no' in keep_columns:\n assert results.loc[(results.per == -9999) &\n (results.site_no == 2003), 'Q_std'].values[0] == \\\n np.std([0, 1], ddof=1)\n assert results.loc[(results.per == 1) &\n (results.site_no == 2002), 'Q_std'].values[0] == \\\n np.std([4, 3, 2], ddof=1)\n\n\[email protected](('datafile,'\n 'metadata_file,'\n 'flow_data_cols,'\n 'site_no_col,'\n 'x_coord_col,'\n 'y_coord_col,'\n 'flow_qualifier_column,'\n 'line_id_col,'\n 'include_sites,'\n 'source_crs,'\n 'outfile'),\n (('swflows/13Feb2020_rf_output_with_site_numbers.csv',\n None, ['predicted_total_flow', 'predicted_bf'],\n 'site_no', 'X', 'Y', 'category', 'comid', None, 4269,\n 'preprocessed_flows_rf.csv'),\n ('swflows/nwis_dvs.csv', 'swflows/nwis_dv_sites.csv', ['q_cfs', 'qbase_cfs'], 'site_no',\n 'dec_long_va', 'dec_lat_va', None, None, None, 4269,\n 'preprocessed_flows_nwis.csv'))\n )\ndef test_preprocess_obs(test_data_path, datafile, metadata_file, flow_data_cols, site_no_col,\n x_coord_col, y_coord_col, flow_qualifier_column,\n line_id_col, include_sites, source_crs,\n test_output_folder, outfile):\n datafile = Path(test_data_path, datafile)\n if metadata_file is not None:\n metadata_file = Path(test_data_path, metadata_file)\n\n geographic_groups = [test_data_path / 'extents/CompositeHydrographArea.shp',\n test_data_path / 'extents/MAP_generalized_regions.shp'\n ]\n outfile = test_output_folder / outfile\n column_renames = {'predicted_total_flow': 'qtotal_m3d',\n 'predicted_bf': 'qbase_m3d',\n 'qbase_cfs': 'qbase_m3d',\n 'q_cfs': 'qtotal_m3d',\n 'station_nm': 'name'}\n data, metadata = preprocess_obs(datafile,\n metadata_file,\n data_columns=flow_data_cols,\n start_date='2008-01-01',\n active_area=os.path.join(test_data_path, 'extents/ms_delta.shp'),\n datetime_col='datetime',\n site_no_col=site_no_col,\n line_id_col=line_id_col,\n x_coord_col=x_coord_col,\n y_coord_col=y_coord_col,\n qualifier_column=flow_qualifier_column,\n include_sites=None,\n include_line_ids=None,\n source_crs=source_crs,\n source_length_units='ft3',\n source_time_units='s',\n dest_length_units='m3',\n dest_time_units='d',\n geographic_groups=geographic_groups,\n geographic_groups_col='obsgroup',\n column_renames=column_renames,\n outfile=outfile\n )\n assert outfile.exists()\n assert Path(outfile.parent, outfile.stem + '_info.csv').exists()\n expected_data_columns = ['site_no']\n # check that line IDs are included with time series if there is a line_id column\n if line_id_col is not None:\n expected_data_columns.append('line_id')\n expected_data_columns += ['datetime', 'obsprefix'] + flow_data_cols + ['category']\n expected_data_columns = [column_renames.get(c, c) for c in expected_data_columns]\n assert np.all(data.columns == expected_data_columns)\n assert data.index.name == 'datetime'\n assert not any({'site_no', 'x', 'y', 'start_dt', 'end_dt', 'n', 'name',\n 'obsprefix', 'group'}.difference(metadata.columns))\n\n # check that units were converted to m3/d\n flow_col = 'qbase_m3d'\n if 'predicted_total_flow' in flow_data_cols:\n assert np.all(data.qtotal_m3d >= data.qbase_m3d * .8)\n assert data[flow_col].max() > 1e6\n\n\ndef test_combine_measured_estimated_values(test_output_folder):\n\n # data from NWIS based on measurements\n nwis_timeseries_file = test_output_folder / 'preprocessed_flows_nwis.csv'\n\n # estimates from RF model\n rf_timeseries_file = test_output_folder / 'preprocessed_flows_rf.csv'\n\n results = combine_measured_estimated_values(nwis_timeseries_file, rf_timeseries_file,\n measured_values_data_col='qbase_m3d', estimated_values_data_col='qbase_m3d',\n resample_freq='MS')\n expected_cols = ['site_no', 'line_id', 'datetime', 'obsprefix', 'category', \n 'est_qtotal_m3d', 'est_qbase_m3d',\n 'meas_qtotal_m3d', 'meas_qbase_m3d', 'obsval']\n assert np.all(results.columns == expected_cols)\n for col in ['site_no', 'datetime', 'category', 'obsval']:\n assert not results[col].isna().any()\n" ]
[ [ "pandas.to_datetime", "numpy.array_equal", "numpy.isnan", "pandas.DataFrame", "numpy.all", "numpy.std", "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": [] } ]
Pratheeba14/visualizing-the-weather-data-set
[ "d0451646db52f0d88fda6b334de22d8392d14230" ]
[ "code.py" ]
[ "# --------------\n# Import the required Libraries\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport calendar\r\nimport seaborn as sns\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n\r\n# Generate a line chart that visualizes the readings in the months\r\n\r\ndef line_chart(df,period,col):\r\n \r\n \"\"\" A line chart that visualizes the readings in the months\r\n \r\n This function accepts the dataframe df ,period(day/month/year) and col(feature), which plots the aggregated value of the feature based on the periods. Ensure the period labels are properly named.\r\n \r\n Keyword arguments:\r\n df - Pandas dataframe which has the data.\r\n period - Period of time over which you want to aggregate the data\r\n col - Feature of the dataframe\r\n \r\n \"\"\"\r\n return sns.lineplot(calendar.month_name[1:],df.groupby(period)[col].mean(),sort=False)\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Function to perform univariate analysis of categorical columns\r\ndef plot_categorical_columns(df):\r\n \"\"\" Univariate analysis of categorical columns\r\n \r\n This function accepts the dataframe df which analyzes all the variable in the data and performs the univariate analysis using bar plot.\r\n \r\n Keyword arguments:\r\n df - Pandas dataframe which has the data.\r\n \r\n \"\"\"\r\n categorical=df.select_dtypes(include=object)\r\n fig, ax = plt.subplots(2, 4, figsize=(20, 10))\r\n for variable, subplot in zip(categorical, ax.flatten()):\r\n sns.countplot(df[variable], ax=subplot)\r\n for label in subplot.get_xticklabels():\r\n label.set_rotation(90)\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Function to plot continous plots\r\ndef plot_cont(df,plt_typ):\r\n \"\"\" Univariate analysis of Numerical columns\r\n \r\n This function accepts the dataframe df, plt_type(boxplot/distplot) which analyzes all the variable in the data and performs the univariate analysis using boxplot or distplot plot.\r\n \r\n Keyword arguments:\r\n df - Pandas dataframe which has the data.\r\n plt_type - type of plot through which you want to visualize the data\r\n \r\n \"\"\"\r\n numerical=df.select_dtypes(exclude=object)\r\n fig, ax = plt.subplots(3, 2, figsize=(10,8))\r\n for variable, subplot in zip(numerical, ax.flatten()):\r\n plt_typ(df[variable], ax=subplot)\r\n for label in subplot.get_xticklabels():\r\n label.set_rotation(90)\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Function to plot grouped values based on the feature\r\ndef group_values(df,col1,agg1,col2):\r\n \"\"\" Agrregate values by grouping\r\n \r\n This function accepts a dataframe, 2 column(feature) and aggregated function(agg1) which groupby the dataframe based on the column and plots the bar plot.\r\n \r\n Keyword arguments:\r\n df - Pandas dataframe which has the data.\r\n col1 - Feature of the dataframe on which values will be aggregated.\r\n agg1 - Dictionary of aggregate functions with feature as the key and func as the value\r\n col2 - Feature of the dataframe to be plot against grouped data.\r\n \r\n Returns:\r\n grouping - Dataframe with all columns on which it is grouped on.\r\n \"\"\"\r\n return df.groupby(col1)[col2].agg(agg1)\r\n \r\n \r\n\r\n\r\n\r\n\r\n# Read the Data and pass the parameter as parse_dates=True, index_col='Date/Time'\r\nweather_df=pd.read_csv(path,parse_dates=True,index_col=\"Date/Time\")\r\ncategorical=weather_df.select_dtypes(include=object)\r\nnumerical=weather_df.select_dtypes(exclude=object)\r\n\r\n# Lets try to generate a line chart that visualizes the temperature readings in the months.\r\n# Call the function line_chart() with the appropriate parameters.\r\nline_chart(weather_df,weather_df.index.month,\"Temp (C)\")\r\nplt.xticks(rotation=90)\r\nplt.title(\"Temperature Trend,2012\")\r\n\r\n\r\n# Now let's perform the univariate analysis of categorical features.\r\n# Call the \"function plot_categorical_columns()\" with appropriate parameters.\r\nplot_categorical_columns(weather_df)\r\n\r\n\r\n# Let's plot the Univariate analysis of Numerical columns.\r\n# Call the function \"plot_cont()\" with the appropriate parameters to plot distplot\r\nplot_cont(weather_df,sns.distplot)\r\n\r\n\r\n# Call the function \"plot_cont()\" with the appropriate parameters to plot boxplot\r\nplot_cont(weather_df,sns.boxplot)\r\n\r\n# Groupby the data by Weather and plot the graph of the mean visibility during different weathers. Call the function group_values to plot the graph.\r\n# Feel free to try on diffrent features and aggregated functions like max, min.\r\n\r\ngroup_values(weather_df,\"Weather\",\"mean\",\"Visibility (km)\")\r\ngroup_values(weather_df,\"Weather\",\"mean\",\"Visibility (km)\").plot.bar()\r\ngroup_values(weather_df,\"Weather\",\"max\",\"Rel Hum (%)\")\r\ngroup_values(weather_df,\"Weather\",\"min\",\"Wind Spd (km/h)\")\r\n\n\n\n" ]
[ [ "matplotlib.pyplot.xticks", "pandas.read_csv", "matplotlib.pyplot.subplots", "matplotlib.pyplot.title" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
manjunathnilugal/PyBaMM
[ "a31e2095600bb92e913598ac4d02b2b6b77b31c1", "65d5cba534b4f163670e753714964aaa75d6a2d2" ]
[ "tests/unit/test_solvers/test_casadi_algebraic_solver.py", "pybamm/spatial_methods/spatial_method.py" ]
[ "#\n# Tests for the Casadi Algebraic Solver class\n#\nimport casadi\nimport pybamm\nimport unittest\nimport numpy as np\nfrom scipy.optimize import least_squares\nimport tests\n\n\nclass TestCasadiAlgebraicSolver(unittest.TestCase):\n def test_algebraic_solver_init(self):\n solver = pybamm.CasadiAlgebraicSolver(tol=1e-4)\n self.assertEqual(solver.tol, 1e-4)\n\n solver.tol = 1e-5\n self.assertEqual(solver.tol, 1e-5)\n\n def test_simple_root_find(self):\n # Simple system: a single algebraic equation\n var = pybamm.Variable(\"var\")\n model = pybamm.BaseModel()\n model.algebraic = {var: var + 2}\n model.initial_conditions = {var: 2}\n\n # create discretisation\n disc = pybamm.Discretisation()\n disc.process_model(model)\n\n # Solve\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, np.linspace(0, 1, 10))\n np.testing.assert_array_equal(solution.y, -2)\n\n def test_simple_root_find_correct_initial_guess(self):\n # Simple system: a single algebraic equation\n var = pybamm.Variable(\"var\")\n model = pybamm.BaseModel()\n model.algebraic = {var: var + 2}\n # initial guess gives right answer\n model.initial_conditions = {var: -2}\n\n # create discretisation\n disc = pybamm.Discretisation()\n disc.process_model(model)\n\n # Solve\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, np.linspace(0, 1, 10))\n np.testing.assert_array_equal(solution.y, -2)\n\n def test_root_find_fail(self):\n class Model:\n y0 = np.array([2])\n t = casadi.MX.sym(\"t\")\n y = casadi.MX.sym(\"y\")\n p = casadi.MX.sym(\"p\")\n length_scales = {}\n rhs = {}\n casadi_algebraic = casadi.Function(\"alg\", [t, y, p], [y ** 2 + 1])\n bounds = (np.array([-np.inf]), np.array([np.inf]))\n interpolant_extrapolation_events_eval = []\n\n def algebraic_eval(self, t, y, inputs):\n # algebraic equation has no real root\n return y ** 2 + 1\n\n model = Model()\n\n solver = pybamm.CasadiAlgebraicSolver()\n with self.assertRaisesRegex(\n pybamm.SolverError, \"Could not find acceptable solution: .../casadi\"\n ):\n solver._integrate(model, np.array([0]), {})\n solver = pybamm.CasadiAlgebraicSolver(extra_options={\"error_on_fail\": False})\n with self.assertRaisesRegex(\n pybamm.SolverError, \"Could not find acceptable solution: solver terminated\"\n ):\n solver._integrate(model, np.array([0]), {})\n\n # Model returns Nan\n class NaNModel:\n y0 = np.array([-2])\n t = casadi.MX.sym(\"t\")\n y = casadi.MX.sym(\"y\")\n p = casadi.MX.sym(\"p\")\n rhs = {}\n casadi_algebraic = casadi.Function(\"alg\", [t, y, p], [y ** 0.5])\n bounds = (np.array([-np.inf]), np.array([np.inf]))\n interpolant_extrapolation_events_eval = []\n\n def algebraic_eval(self, t, y, inputs):\n # algebraic equation has no real root\n return y ** 0.5\n\n model = NaNModel()\n with self.assertRaisesRegex(\n pybamm.SolverError,\n \"Could not find acceptable solution: solver returned NaNs\",\n ):\n solver._integrate(model, np.array([0]), {})\n\n def test_model_solver_with_time(self):\n # Create model\n model = pybamm.BaseModel()\n var1 = pybamm.Variable(\"var1\")\n var2 = pybamm.Variable(\"var2\")\n model.algebraic = {var1: var1 - 3 * pybamm.t, var2: 2 * var1 - var2}\n model.initial_conditions = {var1: pybamm.Scalar(1), var2: pybamm.Scalar(4)}\n model.variables = {\"var1\": var1, \"var2\": var2}\n\n disc = pybamm.Discretisation()\n disc.process_model(model)\n\n # Solve\n t_eval = np.linspace(0, 1)\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, t_eval)\n\n sol = np.vstack((3 * t_eval, 6 * t_eval))\n np.testing.assert_array_almost_equal(solution.y, sol)\n np.testing.assert_array_almost_equal(solution[\"var1\"].data.flatten(), sol[0, :])\n np.testing.assert_array_almost_equal(solution[\"var2\"].data.flatten(), sol[1, :])\n\n def test_model_solver_with_time_not_changing(self):\n # Create model\n model = pybamm.BaseModel()\n var1 = pybamm.Variable(\"var1\")\n var2 = pybamm.Variable(\"var2\")\n model.algebraic = {var1: var1 - 3, var2: 2 * var1 - var2}\n model.initial_conditions = {var1: pybamm.Scalar(1), var2: pybamm.Scalar(4)}\n model.variables = {\"var1\": var1, \"var2\": var2}\n\n disc = pybamm.Discretisation()\n disc.process_model(model)\n\n # Solve\n t_eval = np.linspace(0, 1)\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, t_eval)\n\n sol = np.vstack((3 + 0 * t_eval, 6 + 0 * t_eval))\n np.testing.assert_array_almost_equal(solution.y, sol)\n\n def test_model_solver_with_bounds(self):\n # Note: we need a better test case to test this functionality properly\n # Create model\n model = pybamm.BaseModel()\n var1 = pybamm.Variable(\"var1\", bounds=(0, 10))\n model.algebraic = {var1: pybamm.sin(var1) + 1}\n model.initial_conditions = {var1: pybamm.Scalar(3)}\n model.variables = {\"var1\": var1}\n\n # Solve\n solver = pybamm.CasadiAlgebraicSolver(tol=1e-12)\n solution = solver.solve(model)\n np.testing.assert_array_almost_equal(solution[\"var1\"].data, 3 * np.pi / 2)\n\n def test_solve_with_input(self):\n # Simple system: a single algebraic equation\n var = pybamm.Variable(\"var\")\n model = pybamm.BaseModel()\n model.algebraic = {var: var + pybamm.InputParameter(\"param\")}\n model.initial_conditions = {var: 2}\n\n # create discretisation\n disc = pybamm.Discretisation()\n disc.process_model(model)\n\n # Solve\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, np.linspace(0, 1, 10), inputs={\"param\": 7})\n np.testing.assert_array_equal(solution.y, -7)\n\n\nclass TestCasadiAlgebraicSolverSensitivity(unittest.TestCase):\n def test_solve_with_symbolic_input(self):\n # Simple system: a single algebraic equation\n var = pybamm.Variable(\"var\")\n model = pybamm.BaseModel()\n model.algebraic = {var: var + pybamm.InputParameter(\"param\")}\n model.initial_conditions = {var: 2}\n model.variables = {\"var\": var}\n\n # create discretisation\n disc = pybamm.Discretisation()\n disc.process_model(model)\n\n # Solve\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, [0])\n np.testing.assert_array_equal(solution[\"var\"].value({\"param\": 7}), -7)\n np.testing.assert_array_equal(solution[\"var\"].value({\"param\": 3}), -3)\n np.testing.assert_array_equal(solution[\"var\"].sensitivity({\"param\": 3}), -1)\n\n def test_least_squares_fit(self):\n # Simple system: a single algebraic equation\n var = pybamm.Variable(\"var\", domain=\"negative electrode\")\n model = pybamm.BaseModel()\n p = pybamm.InputParameter(\"p\")\n q = pybamm.InputParameter(\"q\")\n model.algebraic = {var: (var - p)}\n model.initial_conditions = {var: 3}\n model.variables = {\"objective\": (var - q) ** 2 + (p - 3) ** 2}\n\n # create discretisation\n disc = tests.get_discretisation_for_testing()\n disc.process_model(model)\n\n # Solve\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, [0])\n sol_var = solution[\"objective\"]\n\n def objective(x):\n return sol_var.value({\"p\": x[0], \"q\": x[1]}).full().flatten()\n\n # without jacobian\n lsq_sol = least_squares(objective, [2, 2], method=\"lm\")\n np.testing.assert_array_almost_equal(lsq_sol.x, [3, 3], decimal=3)\n\n def jac(x):\n return sol_var.sensitivity({\"p\": x[0], \"q\": x[1]})\n\n # with jacobian\n lsq_sol = least_squares(objective, [2, 2], jac=jac, method=\"lm\")\n np.testing.assert_array_almost_equal(lsq_sol.x, [3, 3], decimal=3)\n\n def test_solve_with_symbolic_input_1D_scalar_input(self):\n var = pybamm.Variable(\"var\", \"negative electrode\")\n model = pybamm.BaseModel()\n param = pybamm.InputParameter(\"param\")\n model.algebraic = {var: var + param}\n model.initial_conditions = {var: 2}\n model.variables = {\"var\": var}\n\n # create discretisation\n disc = tests.get_discretisation_for_testing()\n disc.process_model(model)\n\n # Solve - scalar input\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, [0])\n np.testing.assert_array_equal(solution[\"var\"].value({\"param\": 7}), -7)\n np.testing.assert_array_equal(solution[\"var\"].value({\"param\": 3}), -3)\n np.testing.assert_array_equal(solution[\"var\"].sensitivity({\"param\": 3}), -1)\n\n def test_solve_with_symbolic_input_1D_vector_input(self):\n var = pybamm.Variable(\"var\", \"negative electrode\")\n model = pybamm.BaseModel()\n param = pybamm.InputParameter(\"param\", \"negative electrode\")\n model.algebraic = {var: var + param}\n model.initial_conditions = {var: 2}\n model.variables = {\"var\": var}\n\n # create discretisation\n disc = tests.get_discretisation_for_testing()\n disc.process_model(model)\n\n # Solve - scalar input\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, [0])\n n = disc.mesh[\"negative electrode\"].npts\n\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, [0])\n p = np.linspace(0, 1, n)[:, np.newaxis]\n np.testing.assert_array_almost_equal(\n solution[\"var\"].value({\"param\": 3 * np.ones(n)}), -3\n )\n np.testing.assert_array_almost_equal(\n solution[\"var\"].value({\"param\": 2 * p}), -2 * p\n )\n np.testing.assert_array_almost_equal(\n solution[\"var\"].sensitivity({\"param\": 3 * np.ones(n)}), -np.eye(40)\n )\n np.testing.assert_array_almost_equal(\n solution[\"var\"].sensitivity({\"param\": p}), -np.eye(40)\n )\n\n def test_solve_with_symbolic_input_in_initial_conditions(self):\n # Simple system: a single algebraic equation\n var = pybamm.Variable(\"var\")\n model = pybamm.BaseModel()\n model.algebraic = {var: var + 2}\n model.initial_conditions = {var: pybamm.InputParameter(\"param\")}\n model.variables = {\"var\": var}\n\n # create discretisation\n disc = pybamm.Discretisation()\n disc.process_model(model)\n\n # Solve\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, [0])\n np.testing.assert_array_equal(solution[\"var\"].value({\"param\": 7}), -2)\n np.testing.assert_array_equal(solution[\"var\"].value({\"param\": 3}), -2)\n np.testing.assert_array_equal(solution[\"var\"].sensitivity({\"param\": 3}), 0)\n\n def test_least_squares_fit_input_in_initial_conditions(self):\n # Simple system: a single algebraic equation\n var = pybamm.Variable(\"var\", domain=\"negative electrode\")\n model = pybamm.BaseModel()\n p = pybamm.InputParameter(\"p\")\n q = pybamm.InputParameter(\"q\")\n model.algebraic = {var: (var - p)}\n model.initial_conditions = {var: p}\n model.variables = {\"objective\": (var - q) ** 2 + (p - 3) ** 2}\n\n # create discretisation\n disc = tests.get_discretisation_for_testing()\n disc.process_model(model)\n\n # Solve\n solver = pybamm.CasadiAlgebraicSolver()\n solution = solver.solve(model, [0])\n sol_var = solution[\"objective\"]\n\n def objective(x):\n return sol_var.value({\"p\": x[0], \"q\": x[1]}).full().flatten()\n\n # without jacobian\n lsq_sol = least_squares(objective, [2, 2], method=\"lm\")\n np.testing.assert_array_almost_equal(lsq_sol.x, [3, 3], decimal=3)\n\n\nif __name__ == \"__main__\":\n print(\"Add -v for more debug output\")\n import sys\n\n if \"-v\" in sys.argv:\n debug = True\n pybamm.settings.debug_mode = True\n unittest.main()\n", "#\n# A general spatial method class\n#\nimport pybamm\nimport numpy as np\nfrom scipy.sparse import eye, kron, coo_matrix, csr_matrix, vstack\n\n\nclass SpatialMethod:\n \"\"\"\n A general spatial methods class, with default (trivial) behaviour for some spatial\n operations.\n All spatial methods will follow the general form of SpatialMethod in\n that they contain a method for broadcasting variables onto a mesh,\n a gradient operator, and a divergence operator.\n\n Parameters\n ----------\n mesh : :class: `pybamm.Mesh`\n Contains all the submeshes for discretisation\n \"\"\"\n\n def __init__(self, options=None):\n\n self.options = {\"extrapolation\": {\"order\": \"linear\", \"use bcs\": False}}\n\n # update double-layered dict\n if options:\n for opt, val in options.items():\n if isinstance(val, dict):\n self.options[opt].update(val)\n else:\n self.options[opt] = val\n\n self._mesh = None\n\n def build(self, mesh):\n # add npts_for_broadcast to mesh domains for this particular discretisation\n for dom in mesh.keys():\n mesh[dom].npts_for_broadcast_to_nodes = mesh[dom].npts\n self._mesh = mesh\n\n def _get_auxiliary_domain_repeats(self, auxiliary_domains):\n \"\"\"\n Helper method to read the 'auxiliary_domain' meshes\n \"\"\"\n if \"secondary\" in auxiliary_domains:\n sec_mesh_npts = self.mesh.combine_submeshes(\n *auxiliary_domains[\"secondary\"]\n ).npts\n else:\n sec_mesh_npts = 1\n if \"tertiary\" in auxiliary_domains:\n tert_mesh_npts = self.mesh.combine_submeshes(\n *auxiliary_domains[\"tertiary\"]\n ).npts\n else:\n tert_mesh_npts = 1\n if \"quaternary\" in auxiliary_domains:\n quat_mesh_npts = self.mesh.combine_submeshes(\n *auxiliary_domains[\"quaternary\"]\n ).npts\n else:\n quat_mesh_npts = 1\n return sec_mesh_npts * tert_mesh_npts * quat_mesh_npts\n\n @property\n def mesh(self):\n return self._mesh\n\n def spatial_variable(self, symbol):\n \"\"\"\n Convert a :class:`pybamm.SpatialVariable` node to a linear algebra object that\n can be evaluated (here, a :class:`pybamm.Vector` on either the nodes or the\n edges).\n\n Parameters\n -----------\n symbol : :class:`pybamm.SpatialVariable`\n The spatial variable to be discretised.\n\n Returns\n -------\n :class:`pybamm.Vector`\n Contains the discretised spatial variable\n \"\"\"\n symbol_mesh = self.mesh.combine_submeshes(*symbol.domain)\n repeats = self._get_auxiliary_domain_repeats(symbol.auxiliary_domains)\n if symbol.evaluates_on_edges(\"primary\"):\n entries = np.tile(symbol_mesh.edges, repeats)\n else:\n entries = np.tile(symbol_mesh.nodes, repeats)\n return pybamm.Vector(\n entries, domain=symbol.domain, auxiliary_domains=symbol.auxiliary_domains\n )\n\n def broadcast(self, symbol, domain, auxiliary_domains, broadcast_type):\n \"\"\"\n Broadcast symbol to a specified domain.\n\n Parameters\n ----------\n symbol : :class:`pybamm.Symbol`\n The symbol to be broadcasted\n domain : iterable of strings\n The domain to broadcast to\n auxiliary_domains : dict of strings\n The auxiliary domains for broadcasting\n broadcast_type : str\n The type of broadcast: 'primary to node', 'primary to edges', 'secondary to\n nodes', 'secondary to edges', 'tertiary to nodes', 'tertiary to edges',\n 'full to nodes' or 'full to edges'\n\n Returns\n -------\n broadcasted_symbol: class: `pybamm.Symbol`\n The discretised symbol of the correct size for the spatial method\n \"\"\"\n\n primary_domain_size = sum(\n self.mesh[dom].npts_for_broadcast_to_nodes for dom in domain\n )\n secondary_domain_size = self._get_auxiliary_domain_repeats(\n {k: v for k, v in auxiliary_domains.items() if k == \"secondary\"}\n )\n tertiary_domain_size = self._get_auxiliary_domain_repeats(\n {k: v for k, v in auxiliary_domains.items() if k == \"tertiary\"}\n )\n auxiliary_domains_size = self._get_auxiliary_domain_repeats(auxiliary_domains)\n full_domain_size = primary_domain_size * auxiliary_domains_size\n if broadcast_type.endswith(\"to edges\"):\n # add one point to each domain for broadcasting to edges\n primary_domain_size += 1\n full_domain_size = primary_domain_size * auxiliary_domains_size\n secondary_domain_size += 1\n tertiary_domain_size += 1\n\n if broadcast_type.startswith(\"primary\"):\n # Make copies of the child stacked on top of each other\n sub_vector = np.ones((primary_domain_size, 1))\n if symbol.shape_for_testing == ():\n out = symbol * pybamm.Vector(sub_vector)\n else:\n # Repeat for secondary points\n matrix = csr_matrix(kron(eye(symbol.shape_for_testing[0]), sub_vector))\n out = pybamm.Matrix(matrix) @ symbol\n out.domain = domain\n elif broadcast_type.startswith(\"secondary\"):\n # Make copies of the child stacked on top of each other\n identity = eye(symbol.shape[0])\n matrix = vstack([identity for _ in range(secondary_domain_size)])\n out = pybamm.Matrix(matrix) @ symbol\n elif broadcast_type.startswith(\"tertiary\"):\n # Make copies of the child stacked on top of each other\n identity = eye(symbol.shape[0])\n matrix = vstack([identity for _ in range(tertiary_domain_size)])\n out = pybamm.Matrix(matrix) @ symbol\n elif broadcast_type.startswith(\"full\"):\n out = symbol * pybamm.Vector(np.ones(full_domain_size), domain=domain)\n\n out.auxiliary_domains = auxiliary_domains.copy()\n return out\n\n def gradient(self, symbol, discretised_symbol, boundary_conditions):\n \"\"\"\n Implements the gradient for a spatial method.\n\n Parameters\n ----------\n symbol: :class:`pybamm.Symbol`\n The symbol that we will take the gradient of.\n discretised_symbol: :class:`pybamm.Symbol`\n The discretised symbol of the correct size\n\n boundary_conditions : dict\n The boundary conditions of the model\n ({symbol.id: {\"left\": left bc, \"right\": right bc}})\n\n Returns\n -------\n :class: `pybamm.Array`\n Contains the result of acting the discretised gradient on\n the child discretised_symbol\n \"\"\"\n raise NotImplementedError\n\n def divergence(self, symbol, discretised_symbol, boundary_conditions):\n \"\"\"\n Implements the divergence for a spatial method.\n\n Parameters\n ----------\n symbol: :class:`pybamm.Symbol`\n The symbol that we will take the gradient of.\n discretised_symbol: :class:`pybamm.Symbol`\n The discretised symbol of the correct size\n boundary_conditions : dict\n The boundary conditions of the model\n ({symbol.id: {\"left\": left bc, \"right\": right bc}})\n\n Returns\n -------\n :class: `pybamm.Array`\n Contains the result of acting the discretised divergence on\n the child discretised_symbol\n \"\"\"\n raise NotImplementedError\n\n def laplacian(self, symbol, discretised_symbol, boundary_conditions):\n \"\"\"\n Implements the laplacian for a spatial method.\n\n Parameters\n ----------\n symbol: :class:`pybamm.Symbol`\n The symbol that we will take the gradient of.\n discretised_symbol: :class:`pybamm.Symbol`\n The discretised symbol of the correct size\n boundary_conditions : dict\n The boundary conditions of the model\n ({symbol.id: {\"left\": left bc, \"right\": right bc}})\n\n Returns\n -------\n :class: `pybamm.Array`\n Contains the result of acting the discretised laplacian on\n the child discretised_symbol\n \"\"\"\n raise NotImplementedError\n\n def gradient_squared(self, symbol, discretised_symbol, boundary_conditions):\n \"\"\"\n Implements the inner product of the gradient with itself for a spatial method.\n\n Parameters\n ----------\n symbol: :class:`pybamm.Symbol`\n The symbol that we will take the gradient of.\n discretised_symbol: :class:`pybamm.Symbol`\n The discretised symbol of the correct size\n boundary_conditions : dict\n The boundary conditions of the model\n ({symbol.id: {\"left\": left bc, \"right\": right bc}})\n\n Returns\n -------\n :class: `pybamm.Array`\n Contains the result of taking the inner product of the result of acting\n the discretised gradient on the child discretised_symbol with itself\n \"\"\"\n raise NotImplementedError\n\n def integral(self, child, discretised_child, integration_dimension):\n \"\"\"\n Implements the integral for a spatial method.\n\n Parameters\n ----------\n child: :class:`pybamm.Symbol`\n The symbol to which is being integrated\n discretised_child: :class:`pybamm.Symbol`\n The discretised symbol of the correct size\n integration_dimension : str, optional\n The dimension in which to integrate (default is \"primary\")\n\n Returns\n -------\n :class: `pybamm.Array`\n Contains the result of acting the discretised integral on\n the child discretised_symbol\n \"\"\"\n raise NotImplementedError\n\n def indefinite_integral(self, child, discretised_child, direction):\n \"\"\"\n Implements the indefinite integral for a spatial method.\n\n Parameters\n ----------\n child: :class:`pybamm.Symbol`\n The symbol to which is being integrated\n discretised_child: :class:`pybamm.Symbol`\n The discretised symbol of the correct size\n direction : str\n The direction of integration\n\n Returns\n -------\n :class: `pybamm.Array`\n Contains the result of acting the discretised indefinite integral on\n the child discretised_symbol\n \"\"\"\n raise NotImplementedError\n\n def boundary_integral(self, child, discretised_child, region):\n \"\"\"\n Implements the boundary integral for a spatial method.\n\n Parameters\n ----------\n child: :class:`pybamm.Symbol`\n The symbol to which is being integrated\n discretised_child: :class:`pybamm.Symbol`\n The discretised symbol of the correct size\n region: str\n The region of the boundary over which to integrate. If region is None\n (default) the integration is carried out over the entire boundary. If\n region is `negative tab` or `positive tab` then the integration is only\n carried out over the appropriate part of the boundary corresponding to\n the tab.\n\n Returns\n -------\n :class: `pybamm.Array`\n Contains the result of acting the discretised boundary integral on\n the child discretised_symbol\n \"\"\"\n raise NotImplementedError\n\n def delta_function(self, symbol, discretised_symbol):\n \"\"\"\n Implements the delta function on the approriate side for a spatial method.\n\n Parameters\n ----------\n symbol: :class:`pybamm.Symbol`\n The symbol to which is being integrated\n discretised_symbol: :class:`pybamm.Symbol`\n The discretised symbol of the correct size\n \"\"\"\n raise NotImplementedError\n\n def internal_neumann_condition(\n self, left_symbol_disc, right_symbol_disc, left_mesh, right_mesh\n ):\n \"\"\"\n A method to find the internal neumann conditions between two symbols\n on adjacent subdomains.\n\n Parameters\n ----------\n left_symbol_disc : :class:`pybamm.Symbol`\n The discretised symbol on the left subdomain\n right_symbol_disc : :class:`pybamm.Symbol`\n The discretised symbol on the right subdomain\n left_mesh : list\n The mesh on the left subdomain\n right_mesh : list\n The mesh on the right subdomain\n \"\"\"\n\n raise NotImplementedError\n\n def preprocess_external_variables(self, var):\n return {}\n\n def boundary_value_or_flux(self, symbol, discretised_child, bcs=None):\n \"\"\"\n Returns the boundary value or flux using the approriate expression for the\n spatial method. To do this, we create a sparse vector 'bv_vector' that extracts\n either the first (for side=\"left\") or last (for side=\"right\") point from\n 'discretised_child'.\n\n Parameters\n -----------\n symbol: :class:`pybamm.Symbol`\n The boundary value or flux symbol\n discretised_child : :class:`pybamm.StateVector`\n The discretised variable from which to calculate the boundary value\n bcs : dict (optional)\n The boundary conditions. If these are supplied and \"use bcs\" is True in\n the options, then these will be used to improve the accuracy of the\n extrapolation.\n\n Returns\n -------\n :class:`pybamm.MatrixMultiplication`\n The variable representing the surface value.\n \"\"\"\n\n if bcs is None:\n bcs = {}\n if self._get_auxiliary_domain_repeats(discretised_child.auxiliary_domains) > 1:\n raise NotImplementedError(\"Cannot process 2D symbol in base spatial method\")\n if isinstance(symbol, pybamm.BoundaryGradient):\n raise TypeError(\"Cannot process BoundaryGradient in base spatial method\")\n n = sum(self.mesh[dom].npts for dom in discretised_child.domain)\n if symbol.side == \"left\":\n # coo_matrix takes inputs (data, (row, col)) and puts data[i] at the point\n # (row[i], col[i]) for each index of data. Here we just want a single point\n # with value 1 at (0,0).\n # Convert to a csr_matrix to allow indexing and other functionality\n left_vector = csr_matrix(coo_matrix(([1], ([0], [0])), shape=(1, n)))\n bv_vector = pybamm.Matrix(left_vector)\n elif symbol.side == \"right\":\n # as above, but now we want a single point with value 1 at (0, n-1)\n right_vector = csr_matrix(coo_matrix(([1], ([0], [n - 1])), shape=(1, n)))\n bv_vector = pybamm.Matrix(right_vector)\n\n out = bv_vector @ discretised_child\n # boundary value removes domain\n out.clear_domains()\n return out\n\n def mass_matrix(self, symbol, boundary_conditions):\n \"\"\"\n Calculates the mass matrix for a spatial method.\n\n Parameters\n ----------\n symbol: :class:`pybamm.Variable`\n The variable corresponding to the equation for which we are\n calculating the mass matrix.\n boundary_conditions : dict\n The boundary conditions of the model\n ({symbol.id: {\"left\": left bc, \"right\": right bc}})\n\n Returns\n -------\n :class:`pybamm.Matrix`\n The (sparse) mass matrix for the spatial method.\n \"\"\"\n # NOTE: for different spatial methods the matrix may need to be adjusted\n # to account for Dirichlet boundary conditions. Here, we just have the default\n # behaviour that the mass matrix is the identity.\n\n # Create appropriate submesh by combining submeshes in domain\n submesh = self.mesh.combine_submeshes(*symbol.domain)\n\n # Get number of points in primary dimension\n n = submesh.npts\n\n # Create mass matrix for primary dimension\n prim_mass = eye(n)\n\n # Get number of points in secondary dimension\n second_dim_repeats = self._get_auxiliary_domain_repeats(symbol.domains)\n\n # Convert to csr_matrix as required by some solvers\n mass = csr_matrix(kron(eye(second_dim_repeats), prim_mass))\n return pybamm.Matrix(mass)\n\n def process_binary_operators(self, bin_op, left, right, disc_left, disc_right):\n \"\"\"Discretise binary operators in model equations. Default behaviour is to\n return a new binary operator with the discretised children.\n\n Parameters\n ----------\n bin_op : :class:`pybamm.BinaryOperator`\n Binary operator to discretise\n left : :class:`pybamm.Symbol`\n The left child of `bin_op`\n right : :class:`pybamm.Symbol`\n The right child of `bin_op`\n disc_left : :class:`pybamm.Symbol`\n The discretised left child of `bin_op`\n disc_right : :class:`pybamm.Symbol`\n The discretised right child of `bin_op`\n\n Returns\n -------\n :class:`pybamm.BinaryOperator`\n Discretised binary operator\n\n \"\"\"\n return bin_op._binary_new_copy(disc_left, disc_right)\n\n def concatenation(self, disc_children):\n \"\"\"Discrete concatenation object.\n\n Parameters\n ----------\n disc_children : list\n List of discretised children\n\n Returns\n -------\n :class:`pybamm.DomainConcatenation`\n Concatenation of the discretised children\n \"\"\"\n return pybamm.domain_concatenation(disc_children, self.mesh)\n" ]
[ [ "numpy.linspace", "scipy.optimize.least_squares", "numpy.eye", "numpy.ones", "numpy.testing.assert_array_equal", "numpy.array", "numpy.vstack", "numpy.testing.assert_array_almost_equal" ], [ "scipy.sparse.eye", "scipy.sparse.coo_matrix", "numpy.tile", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.10", "1.4", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "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": [] } ]
cmbruns/vr_samples
[ "8dee056766bccca1a602c6dd58fd0a641c5033a5", "8dee056766bccca1a602c6dd58fd0a641c5033a5" ]
[ "src/python/photosphere_pyopenvr1.py", "src/python/vrprim/mesh/glfw_triangle.py" ]
[ "#!/bin/env python\r\n\r\n# Example program for viewing a 360 photosphere in a virtual reality headset\r\n\r\nimport os\r\nfrom textwrap import dedent\r\n\r\nimport numpy\r\nfrom OpenGL.GL import * # @UnusedWildImport # this comment squelches IDE warnings\r\nfrom OpenGL.GL.shaders import compileShader, compileProgram\r\nfrom PIL import Image\r\n\r\nfrom openvr.glframework.glfw_app import GlfwApp\r\nfrom openvr.gl_renderer import OpenVrGlRenderer\r\n\r\nclass SphericalPanorama(object):\r\n def __init__(self, image):\r\n self.image = image\r\n self.shader = None\r\n self.vao = None\r\n\r\n def init_gl(self):\r\n self.vao = glGenVertexArrays(1)\r\n glBindVertexArray(self.vao)\r\n # Set up photosphere image texture for OpenGL\r\n self.texture_handle = glGenTextures(1)\r\n glBindTexture(GL_TEXTURE_2D, self.texture_handle);\r\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\r\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);\r\n glTexImage2D(GL_TEXTURE_2D, \r\n 0, \r\n GL_RGB8, \r\n self.image.shape[1], # width \r\n self.image.shape[0], # height\r\n 0,\r\n GL_RGB, \r\n GL_UNSIGNED_BYTE, \r\n self.image);\r\n glBindTexture(GL_TEXTURE_2D, 0);\r\n # Set up shaders for rendering\r\n vertex_shader = compileShader(dedent(\r\n \"\"\"#version 450 core\r\n #line 46\r\n \r\n layout(location = 1) uniform mat4 projection = mat4(1);\r\n layout(location = 2) uniform mat4 model_view = mat4(1);\r\n\r\n out vec3 viewDir;\r\n \r\n // projected screen quad\r\n const vec4 SCREEN_QUAD[4] = vec4[4](\r\n vec4(-1, -1, 1, 1),\r\n vec4( 1, -1, 1, 1),\r\n vec4( 1, 1, 1, 1),\r\n vec4(-1, 1, 1, 1));\r\n \r\n const int TRIANGLE_STRIP_INDICES[4] = int[4](\r\n 0, 1, 3, 2);\r\n \r\n void main() \r\n {\r\n int vertexIndex = TRIANGLE_STRIP_INDICES[gl_VertexID];\r\n gl_Position = vec4(SCREEN_QUAD[vertexIndex]);\r\n mat4 xyzFromNdc = inverse(projection * model_view);\r\n vec4 campos = xyzFromNdc * vec4(0, 0, 0, 1);\r\n vec4 vpos = xyzFromNdc * SCREEN_QUAD[vertexIndex];\r\n viewDir = vpos.xyz/vpos.w - campos.xyz/campos.w;\r\n }\r\n \"\"\"),\r\n GL_VERTEX_SHADER)\r\n fragment_shader = compileShader(dedent(\r\n \"\"\"\\\r\n #version 450 core\r\n #line 85\r\n \r\n layout(binding = 0) uniform sampler2D image;\r\n \r\n in vec3 viewDir;\r\n \r\n out vec4 pixelColor;\r\n \r\n const float PI = 3.1415926535897932384626433832795;\r\n \r\n void main() \r\n {\r\n vec3 d = viewDir;\r\n float longitude = 0.5 * atan(d.z, d.x) / PI + 0.5; // range [0-1]\r\n float r = length(d.xz);\r\n float latitude = -atan(d.y, r) / PI + 0.5; // range [0-1]\r\n \r\n pixelColor = \r\n texture(image, vec2(longitude, latitude));\r\n }\r\n \"\"\"),\r\n GL_FRAGMENT_SHADER)\r\n self.shader = compileProgram(vertex_shader, fragment_shader)\r\n\r\n def display_gl(self, modelview, projection):\r\n glBindVertexArray(self.vao)\r\n glBindTexture(GL_TEXTURE_2D, self.texture_handle)\r\n glUseProgram(self.shader)\r\n glUniformMatrix4fv(1, 1, False, projection)\r\n glUniformMatrix4fv(2, 1, False, modelview)\r\n glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)\r\n\r\n def dispose_gl(self):\r\n glDeleteTextures([self.texture_handle,])\r\n if self.shader is not None:\r\n glDeleteProgram(self.shader)\r\n glDeleteVertexArrays(1, [self.vao,])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # Open equirectangular photosphere\r\n src_folder = os.path.dirname(os.path.abspath(__file__))\r\n img_path = os.path.join(src_folder, '../../assets/images/_0010782_stitch2.jpg')\r\n img = Image.open(img_path)\r\n arr = numpy.array(img)\r\n actor = SphericalPanorama(arr)\r\n renderer = OpenVrGlRenderer(actor)\r\n with GlfwApp(renderer, \"photosphere test\") as glfwApp:\r\n glfwApp.run_loop()\r\n\r\n", "# Python GLFW hello world example based on C++ guide at \r\n# http://www.glfw.org/docs/latest/quick.html\r\n\r\nimport sys\r\n\r\nimport glfw\r\nimport numpy\r\nfrom OpenGL import GL\r\nfrom OpenGL.GL.shaders import compileShader, compileProgram\r\nfrom OpenGL.arrays import vbo\r\n\r\nfrom openvr.glframework.glmatrix import rotate_z, ortho, pack\r\n\r\n\r\ndef main():\r\n # Initialize GLFW OpenGL API\r\n glfw.set_error_callback(error_callback)\r\n if not glfw.init():\r\n raise Exception(\"GLFW Initialization error\")\r\n # Use modern OpenGL version 4.5 core\r\n glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)\r\n glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 5)\r\n glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)\r\n # Create OpenGL window and context\r\n window = glfw.create_window(640, 480, \"Triangle Viewer\", None, None)\r\n if not window:\r\n glfw.terminate()\r\n raise RuntimeError(\"Failed to create glfw window\")\r\n glfw.make_context_current(window)\r\n glfw.swap_interval(1)\r\n # Create vertex array object, apparently required for modern OpenGL\r\n vao = GL.glGenVertexArrays(1)\r\n GL.glBindVertexArray(vao)\r\n # Create triangle geometry: corner 2D location and colors\r\n vertices = vbo.VBO(numpy.array([\r\n [-0.6, -0.4, 1.0, 0.0, 0.0], # x, y, r, g, b\r\n [0.6, -0.4, 0.0, 1.0, 0.0],\r\n [0.0, 0.6, 0.0, 0.0, 1.0],\r\n ], dtype='float32'))\r\n vertices.bind()\r\n # hard-code shader parameter location indices\r\n mvp_location = 0\r\n vpos_location = 0\r\n vcol_location = 1\r\n GL.glEnableVertexAttribArray(vpos_location)\r\n fsize = vertices.dtype.itemsize # 4 bytes per float32\r\n GL.glVertexAttribPointer(vpos_location, 2, GL.GL_FLOAT, False,\r\n fsize * 5, vertices + fsize * 0)\r\n GL.glEnableVertexAttribArray(vcol_location)\r\n GL.glVertexAttribPointer(vcol_location, 3, GL.GL_FLOAT, False,\r\n fsize * 5, vertices + fsize * 2)\r\n # Create GLSL shader program\r\n vertex_shader = compileShader(\r\n \"\"\"#version 450 core\r\n #line 55\r\n \r\n layout(location = %d) uniform mat4 MVP = mat4(1);\r\n \r\n layout(location = %d) in vec2 vPos;\r\n layout(location = %d) in vec3 vCol;\r\n \r\n out vec3 color;\r\n\r\n void main() \r\n {\r\n gl_Position = MVP * vec4(vPos, 0.0, 1.0);\r\n color = vCol;\r\n }\r\n \"\"\" % (mvp_location, vpos_location, vcol_location),\r\n GL.GL_VERTEX_SHADER)\r\n fragment_shader = compileShader(\r\n \"\"\"#version 450 core\r\n #line 73\r\n\r\n in vec3 color;\r\n out vec4 fragColor;\r\n\r\n void main() \r\n {\r\n fragColor = vec4(color, 1);\r\n }\r\n \"\"\",\r\n GL.GL_FRAGMENT_SHADER)\r\n program = compileProgram(vertex_shader, fragment_shader)\r\n # Repeatedly draw until some event stops the program\r\n while not glfw.window_should_close(window):\r\n glfw.make_context_current(window)\r\n width, height = glfw.get_framebuffer_size(window)\r\n GL.glViewport(0, 0, width, height)\r\n GL.glClear(GL.GL_COLOR_BUFFER_BIT)\r\n m = rotate_z(glfw.get_time()) # modelview matrix, m\r\n ratio = width / float(height)\r\n # projection matrix, p\r\n p = ortho(-ratio, ratio, -1.0, 1.0, 1.0, -1.0)\r\n mvp = m * p\r\n GL.glBindVertexArray(vao)\r\n GL.glUseProgram(program)\r\n GL.glUniformMatrix4fv(mvp_location, 1, False, pack(mvp))\r\n GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)\r\n glfw.swap_buffers(window)\r\n glfw.poll_events()\r\n # Clean up and exit\r\n glfw.make_context_current(window)\r\n glfw.destroy_window(window)\r\n glfw.terminate()\r\n sys.exit(0)\r\n\r\n\r\ndef error_callback(description):\r\n raise RuntimeError(description)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n" ]
[ [ "numpy.array" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
robin-ai-ml/Face.KeyPoints
[ "c9812cc8d21d5a6a6e764cff3bf8798cd653c437" ]
[ "face.keypoints.py" ]
[ "\nfrom __future__ import division\nfrom keras.backend.tensorflow_backend import set_session\nimport tensorflow as tf\n\n\nimport numpy as np\nimport time\nimport os\nimport cv2\nimport kmodel\nfrom utils import transparentOverlay\n\nos.environ['KERAS_BACKEND'] = 'tensorflow'\nprint(tf.__version__)\nconfig = tf.ConfigProto(log_device_placement=True, allow_soft_placement=True,\n gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.7))\n# allow_growth=True per_process_gpu_memory_fraction = 0.3\n#per_process_gpu_memory_fraction = 0.3\n\nsess = tf.Session(config=config)\nset_session(sess)\n\n\n# os.environ['KMP_DUPLICATE_LIB_OK']='True'\n\n# 加载预先训练好的模型\n#my_model = kmodel.load_trained_model('yuan_model_mac')\n# 加载自己训练好的模型(测试时取消下面行的注释)\nmy_model = kmodel.load_trained_model('face_keypoints_detection_cnn_model')\n\n# 创建人脸检测器\nface_cascade = cv2.CascadeClassifier(\n 'cascades/haarcascade_frontalface_default.xml')\n\n#smileCascade = cv2.CascadeClassifier('cascades/haarcascade_smile.xml')\n\n# 加载摄像头\ncamera = cv2.VideoCapture(0)\n\n# 加载一个太阳眼镜图像\nsunglasses = cv2.imread('sunglass.png', cv2.IMREAD_UNCHANGED)\n\n# 死循环\nwhile True:\n # time.sleep(0.01)\n\n # 从摄像头获取一张图像\n (_, frame) = camera.read()\n frame = cv2.flip(frame, 1)\n frame2 = np.copy(frame)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # 检测所有的人脸\n faces = face_cascade.detectMultiScale(gray, 1.25, 6)\n\n # 对每一个检测到的人脸\n for (x, y, w, h) in faces:\n\n # 只包含人脸的图像\n gray_face = gray[y:y+h, x:x+w]\n color_face = frame[y:y+h, x:x+w]\n\n # 将人脸图像的值 normalize 在 [0, 1] 之间\n gray_normalized = gray_face / 255\n\n # 缩放灰度图人脸到 96x96 匹配网络的输入\n original_shape = gray_face.shape # A Copy for future reference\n face_resized = cv2.resize(\n gray_normalized, (96, 96), interpolation=cv2.INTER_AREA)\n face_resized = face_resized.reshape(1, 96, 96, 1)\n\n # 预测关键点坐标\n keypoints = my_model.predict(face_resized)\n\n # 将关键点坐标的值从 [-1, 1] 之间转换为 [0, 96] 之间\n keypoints = keypoints * 48 + 48\n\n # 缩放彩色图人脸到 96x96 匹配关键点\n face_resized_color = cv2.resize(\n color_face, (96, 96), interpolation=cv2.INTER_AREA)\n face_resized_color2 = np.copy(face_resized_color)\n\n # 将网络输出的30个值配对为15个tuple对\n points = []\n for i, co in enumerate(keypoints[0][0::2]):\n points.append((co, keypoints[0][1::2][i]))\n\n # 按照关键点的 left_eyebrow_outer_end_x[7], right_eyebrow_outer_end_x[9]确定眼镜的宽度\n sunglass_width = int((points[7][0]-points[9][0])*1.1)\n\n # 按照关键点的 nose_tip_y[10], right_eyebrow_inner_end_y[8]确定眼镜的高度\n sunglass_height = int((points[10][1]-points[8][1])/1.1)\n sunglass_resized = cv2.resize(\n sunglasses, (sunglass_width, sunglass_height), interpolation=cv2.INTER_CUBIC)\n face_resized_color = transparentOverlay(face_resized_color, sunglass_resized, pos=(\n int(points[9][0]), int(points[9][1])), scale=1)\n\n # 将覆盖了眼镜的 face_resized_color 图像转为摄像头捕捉到的原始图像中的大小\n frame[y:y+h, x:x+w] = cv2.resize(face_resized_color,\n original_shape, interpolation=cv2.INTER_CUBIC)\n\n # 在人脸图像中显示关键点坐标\n for keypoint in points:\n cv2.circle(face_resized_color2, keypoint, 1, (0, 255, 0), 1)\n\n frame2[y:y+h, x:x+w] = cv2.resize(face_resized_color2,\n original_shape, interpolation=cv2.INTER_CUBIC)\n\n \n\n # 显示加了眼镜的图像\n cv2.imshow(\"With Glass\", frame)\n # 显示添加了关键点的图像\n cv2.imshow(\"With Keypoints\", frame2)\n\n # 当 'q' 键被点击, 退出循环\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\n# 释放摄像头, 关闭窗口\ncamera.release()\ncv2.destroyAllWindows()\n" ]
[ [ "numpy.copy", "tensorflow.GPUOptions", "tensorflow.Session" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
LeeCenY/turicreate
[ "fb2f3bf313e831ceb42a2e10aacda6e472ea8d93" ]
[ "src/unity/python/turicreate/toolkits/_mps_utils.py" ]
[ "# -*- coding: utf-8 -*-\n# Copyright © 2018 Apple Inc. All rights reserved.\n#\n# Use of this source code is governed by a BSD-3-clause license that can\n# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n\"\"\"\nPython API for MPS neural network backend\n\"\"\"\nfrom __future__ import print_function as _\nfrom __future__ import division as _\nfrom __future__ import absolute_import as _\nimport os as _os\nimport ctypes as _ctypes\nimport numpy as _np\nimport six as _six\nfrom copy import deepcopy as _deepcopy\nfrom turicreate import config as _tc_config\nfrom ._internal_utils import _mac_ver\n\n\nclass MpsGraphNetworkType(object):\n kSingleReLUGraphNet = 0\n kSingleConvGraphNet = 1\n kSingleBNGraphNet = 2\n kSingleMPGraphNet = 3\n kODGraphNet = 4\n\n\nclass MpsGraphMode(object):\n Train = 0\n TrainReturnGrad = 1\n Inference = 2\n\n\nclass MpsLowLevelNetworkType(object):\n kSingleReLUNet = 0\n kSingleConvNet = 1\n kSingleBNNet = 2\n kSingleMPNet = 3\n kSingle1DConvNet = 4\n kODNet = 5\n kSingleDropOut = 6\n kSingleFcNet = 7\n kSingleSoftMaxNet = 8\n kActivityClassifierNet= 9\n kSingleLstmNet = 10\n\nclass MpsLowLevelMode(object):\n kLowLevelModeTrain = 0\n kLowLevelModeInference = 1\n kLowLevelModeTest = 2\n\n\ndef _decode_bytes_to_native_string(s):\n if _six.PY3:\n return s.decode()\n else:\n return s\n\n\ndef mps_to_mxnet(weight):\n if weight.ndim == 1:\n return weight\n elif weight.ndim == 4:\n return weight.transpose(0, 3, 1, 2)\n else:\n raise ValueError('Not supported')\n\n\ndef mxnet_to_mps(weight):\n if weight.ndim == 1:\n return weight\n elif weight.ndim == 4:\n return weight.transpose(0, 2, 3, 1)\n else:\n raise ValueError('Not supported')\n\ndef ac_weights_mps_to_mxnet(mps_weights, lstm_h_size):\n import mxnet as _mx\n aux_params = {}\n mxnet_weights = {}\n for key in mps_weights:\n if key == 'conv_weight':\n mxnet_weights[key] = _mx.nd.array(_np.squeeze(mps_weights[key]))\n elif \"running\" in key:\n w = _mx.nd.array(_np.squeeze(mps_weights[key]))\n new_key = key.replace(\"running\", \"moving\")\n aux_params[new_key] = w\n else:\n w = _mx.nd.array(_np.squeeze(mps_weights[key]))\n mxnet_weights[key] = w\n\n bias_shape = mxnet_weights['lstm_h2h_i_bias'].shape\n\n mock_lstm = _mx.rnn.LSTMCell(prefix='lstm_', num_hidden=lstm_h_size)\n for gate_name in mock_lstm._gate_names:\n mxnet_weights['lstm_i2h' + gate_name + '_bias'] = _mx.nd.array(_np.zeros((bias_shape)))\n\n mxnet_weights = mock_lstm.pack_weights(mxnet_weights)\n\n return mxnet_weights, aux_params\n\ndef ac_weights_mxnet_to_mps(arg_params, aux_params, lstm_h_size):\n import mxnet as _mx\n mxnet_weights = arg_params.copy()\n mxnet_weights.update(aux_params)\n\n mock_lstm = _mx.rnn.LSTMCell(prefix='lstm_', num_hidden=lstm_h_size)\n mxnet_weights = mock_lstm.unpack_weights(mxnet_weights)\n mps_weights = {}\n for key in mxnet_weights:\n w = mxnet_weights[key].asnumpy()\n if 'moving' in key:\n new_key = key.replace(\"moving\", \"running\")\n mps_weights[new_key] = w\n elif key.startswith('conv') and key.endswith('weight'):\n w = mxnet_weights[key].asnumpy()\n mps_weights[key] = w[..., _np.newaxis, :]\n elif key.startswith('dense') and key.endswith('weight'):\n mps_weights[key] = w[:, _np.newaxis, _np.newaxis]\n else:\n mps_weights[key] = w\n\n return mps_weights\n\ndef _prepare_network_parameters(arg_dict):\n items = []\n for name, arr in arg_dict.items():\n arr = _np.asarray(arr, dtype=_np.float32)\n items.append((name, MpsFloatArray(arr)))\n\n name = (_ctypes.c_char_p * len(items))()\n arr = (_ctypes.c_void_p * len(items))()\n for i in range(len(items)):\n name[i] = _ctypes.c_char_p(items[i][0].encode())\n arr[i] = items[i][1].handle\n return items, name, arr\n\n_g_TCMPS_LIB = None\n\ndef _load_tcmps_lib():\n \"\"\"\n Load global singleton of tcmps lib handler.\n\n This function is used not used at the top level, so\n that the shared library is loaded lazily only when needed.\n \"\"\"\n global _g_TCMPS_LIB\n if _g_TCMPS_LIB is None:\n # This library requires macOS 10.14 or above\n if _mac_ver() < (10, 14):\n return None\n\n # The symbols defined in libtcmps are now exposed directly by\n # libunity_shared. Eventually the object_detector and\n # activity_classifier toolkits will use the same Python/C++ bridge as\n # the other toolkits, and this usage of ctypes will go away.\n file_dir = _os.path.dirname(__file__)\n lib_path = _os.path.abspath(_os.path.join(file_dir, _os.pardir, 'libunity_shared.dylib'))\n try:\n _g_TCMPS_LIB = _ctypes.CDLL(lib_path, _ctypes.RTLD_LOCAL)\n except OSError:\n pass\n return _g_TCMPS_LIB\n\n\ndef has_fast_mps_support():\n \"\"\"\n Returns True if the environment has MPS backend support\n and a high-power (fast) device is available.\n \"\"\"\n lib = _load_tcmps_lib()\n if lib is None:\n return False\n\n c_bool = _ctypes.c_bool()\n ret = lib.TCMPSHasHighPowerMetalDevice(_ctypes.byref(c_bool))\n return ret == 0 and c_bool.value\n\n\ndef use_mps():\n \"\"\"\n Returns True if MPS can and should be used.\n \"\"\"\n return _tc_config.get_num_gpus() != 0 and has_fast_mps_support()\n\n\ndef mps_device_name():\n \"\"\"\n Returns name of MPS device that will be used, else None.\n \"\"\"\n lib = _load_tcmps_lib()\n if lib is None:\n return None\n\n n = 256\n c_name = (_ctypes.c_char * n)()\n ret = lib.TCMPSMetalDeviceName(_ctypes.byref(c_name), _ctypes.c_int32(n))\n if ret == 0:\n return _decode_bytes_to_native_string(c_name.value)\n else:\n return None\n\n\ndef mps_device_memory_limit():\n \"\"\"\n Returns the memory size in bytes that can be effectively allocated on the\n MPS device that will be used, or None if no suitable device is available.\n \"\"\"\n lib = _load_tcmps_lib()\n if lib is None:\n return None\n\n c_size = _ctypes.c_uint64()\n ret = lib.TCMPSMetalDeviceMemoryLimit(_ctypes.byref(c_size))\n return c_size.value if ret == 0 else None\n\n\ndef _xavier_init(weight):\n shape = weight.shape\n dim = len(shape)\n if dim < 2:\n raise ValueError(\"Xavier init expects at least 2 dimensions\")\n\n scale = 1\n n_in = shape[0]\n n_out = shape[-1]\n\n if dim > 2:\n scale = _np.prod(shape[1:-1])\n\n c = _np.sqrt(3. / (0.5 * (n_in * scale + n_out * scale)))\n return _np.random.uniform(-c, c, shape).astype(_np.float32)\n\ndef _shape_tuple_from_ctypes(shape_ptr, dim):\n # size_t* shape_ptr\n assert isinstance(shape_ptr, _ctypes.POINTER(_ctypes.c_size_t))\n\n # size_t dim\n assert isinstance(dim, _ctypes.c_size_t)\n\n # Wrap size_t* as size_t[dim]\n shape_buf = (_ctypes.c_size_t * dim.value).from_address(\n _ctypes.addressof(shape_ptr.contents))\n\n # Convert size_t[dim] to tuple\n return tuple(shape_buf)\n\ndef _numpy_array_from_ctypes(data_ptr, shape_ptr, dim):\n # float* data_ptr\n assert isinstance(data_ptr, _ctypes.POINTER(_ctypes.c_float))\n\n shape = _shape_tuple_from_ctypes(shape_ptr, dim)\n\n # Wrap float* to float[size]\n size = _np.prod(shape)\n data_buf = (_ctypes.c_float * size).from_address(\n _ctypes.addressof(data_ptr.contents))\n\n # Convert float[size] to numpy\n return _np.fromiter(data_buf, _np.float32, size).reshape(shape)\n\nclass MpsFloatArray(object):\n \"\"\"\n A Python wrapper owning a C++ float_array created by the TCMPS backend.\n\n This class exists to simplify conversions from numpy to the TCMPS format and\n to simplify memory management. Instances usually just serve as arguments to\n the methods on MpsGraphAPI and MpsLowLevelAPI, below.\n \"\"\"\n\n def __init__(self, x):\n \"\"\"Wrap an existing TCMPSFloatArrayRef or a numpy array\"\"\"\n\n # Load TCMPS backend library.\n self._LIB = _load_tcmps_lib()\n assert self._LIB is not None, \"Cannot use MpsFloatArray without libtcmps.dylib\"\n\n # If `x` is a void*, assume it's the right type and just wrap it.\n if isinstance(x, _ctypes.c_void_p):\n self.handle = x\n return\n\n assert isinstance(x, _np.ndarray)\n\n # Convert the input if necessary to contain a contiguous float array.\n self.data = x\n if self.data.dtype != _np.float32:\n self.data = self.data.astype(_np.float32)\n if not self.data.flags.c_contiguous:\n self.data = self.data.copy()\n assert self.data.flags.c_contiguous, \"Data must be row-major\"\n\n # Obtain a pointer to the internal float array (and obtain size).\n data_ptr = self.data.ctypes.data_as(_ctypes.POINTER(_ctypes.c_void_p))\n sz = _ctypes.c_size_t(self.data.size)\n\n # Copy the shape so that it contains a size_t array.\n self.shape = _np.array(self.data.shape).astype(_np.uintp)\n shape_ptr = self.shape.ctypes.data_as(_ctypes.POINTER(_ctypes.c_size_t))\n dim = _ctypes.c_size_t(self.data.ndim)\n\n # Call into TCMPS to create a wrapper around self.data and self.shape.\n # Those two properties must outlive the resulting self.handle.\n self.handle = _ctypes.c_void_p()\n status_code = self._LIB.TCMPSCreateFloatArray(\n _ctypes.byref(self.handle), data_ptr, sz, shape_ptr, dim)\n assert status_code == 0, \"Error calling TCMPSCreateFloatArray\"\n\n def __del__(self):\n status_code = self._LIB.TCMPSDeleteFloatArray(self.handle)\n assert status_code == 0, \"Error calling TCMPSDeleteFloatArray\"\n\n def shape(self):\n \"\"\"Copy the shape from TCMPS as a new numpy ndarray.\"\"\"\n\n # Create C variables that will serve as out parameters for TCMPS.\n shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr\n dim = _ctypes.c_size_t() # size_t dim\n\n # Obtain pointer into memory owned by the C++ object self.handle.\n status_code = self._LIB.TCMPSGetFloatArrayShape(\n self.handle, _ctypes.byref(shape_ptr), _ctypes.byref(dim))\n assert status_code == 0, \"Error calling TCMPSGetFloatArrayShape\"\n\n return _shape_tuple_from_ctypes(shape_ptr, dim)\n\n def asnumpy(self):\n \"\"\"Copy the data from TCMPS into a new numpy ndarray\"\"\"\n\n # Create C variables that will serve as out parameters for TCMPS.\n data_ptr = _ctypes.POINTER(_ctypes.c_float)() # float* data_ptr\n shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr\n dim = _ctypes.c_size_t() # size_t dim\n\n # Obtain pointers into memory owned by the C++ object self.handle.\n # Note that this may trigger synchronization with another thread\n # producing the data.\n status_code = self._LIB.TCMPSReadFloatArray(\n self.handle, _ctypes.byref(data_ptr), _ctypes.byref(shape_ptr),\n _ctypes.byref(dim))\n assert status_code == 0, \"Error calling TCMPSReadFloatArray\"\n\n return _numpy_array_from_ctypes(data_ptr, shape_ptr, dim)\n\n\nclass MpsFloatArrayIterator(object):\n \"\"\"\n A Python wrapper owning a sequence of name/float_array pairs output from the\n TCMPS backend.\n\n This class exists to simplify conversions from the output of TCMPS export\n functions. It implements the iterator protocol, so that a Python dict\n (mapping parameter names for numpy arrays) can be initialized directly from\n an instance of this class.\n \"\"\"\n\n def __init__(self, handle):\n \"\"\"Wrap the output of a TCMPSExport* function.\"\"\"\n self._LIB = _load_tcmps_lib()\n assert self._LIB is not None, \"Cannot use MpsFloatArrayIterator without libtcmps.dylib\"\n\n self.handle = handle\n\n def __del__(self):\n status_code = self._LIB.TCMPSDeleteFloatArrayMapIterator(self.handle)\n assert status_code == 0, \"Error calling TCMPSDeleteFloatArrayMapIterator\"\n\n def __iter__(self):\n return self\n\n def __next__(self):\n # Create C variables that will serve as out parameters for TCMPS.\n name_ptr = _ctypes.c_char_p() # char* name_ptr\n data_ptr = _ctypes.POINTER(_ctypes.c_float)() # float* data_ptr\n shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr\n dim = _ctypes.c_size_t() # size_t dim\n\n # Obtain pointers into memory owned by the C++ object self.handle.\n status_code = self._LIB.TCMPSNextFloatArray(\n self.handle, _ctypes.byref(name_ptr), _ctypes.byref(data_ptr),\n _ctypes.byref(shape_ptr), _ctypes.byref(dim))\n\n if status_code != 0:\n raise StopIteration\n\n # Convert char* to Python string\n name = _decode_bytes_to_native_string(name_ptr.value)\n\n # Convert data to numpy\n array = _numpy_array_from_ctypes(data_ptr, shape_ptr, dim)\n\n return (name, array)\n\n def next(self):\n return self.__next__()\n\n\n#----------------------------------------------------------\n#\n# MPS Graph level API, currently used by Object detector\n#\n#----------------------------------------------------------\n\n\nclass MpsGraphAPI(object):\n def __init__(self, network_id):\n self.handle = _ctypes.c_void_p()\n self._LIB = _load_tcmps_lib()\n assert self._LIB is not None, \"Cannot use MpsGraphAPI without libtcmps.dylib\"\n self._LIB.TCMPSCreateGraphModule(_ctypes.byref(self.handle))\n self._buf_out_fp16 = None\n self._buf_loss = None\n self._ishape = None\n self._oshape = None\n self.network_id = network_id\n # current state, for reloading weights\n self._cur_config = {}\n self._cur_learning_rate = None\n\n def __del__(self):\n self._LIB.TCMPSDeleteGraphModule(self.handle)\n\n def init(self, n, c_in, h_in, w_in, c_out, h_out, w_out, config=None, weights=None):\n if weights is None:\n weights = {}\n if config is None:\n config = {\n 'learning_rate': 1e-3,\n 'gradient_clipping': 0.025,\n 'weight_decay': 0.00005,\n 'momentum': 0.9,\n }\n\n self._mode = int(config.get('mode', MpsGraphMode.TrainReturnGrad))\n self._is_train = self._mode in {MpsGraphMode.TrainReturnGrad, MpsGraphMode.Train}\n\n config_items, config_name, config_arr = _prepare_network_parameters(config)\n weights_items, weights_name, weights_arr = _prepare_network_parameters(weights)\n self._LIB.TCMPSInitGraph(\n self.handle,\n self.network_id,\n _ctypes.c_int32(n),\n _ctypes.c_int32(c_in),\n _ctypes.c_int32(h_in),\n _ctypes.c_int32(w_in),\n _ctypes.c_int32(c_out),\n _ctypes.c_int32(h_out),\n _ctypes.c_int32(w_out),\n config_name, config_arr, _ctypes.c_int32(len(config_items)),\n weights_name, weights_arr, _ctypes.c_int32(len(weights_items)),\n )\n self._cur_config = _deepcopy(config)\n if self._mode == MpsGraphMode.TrainReturnGrad:\n sz = n * c_in * h_in * w_in\n else:\n sz = n * c_out * h_out * w_out\n self._buf_out_fp16 = (_ctypes.c_float * (sz // 2))()\n self._buf_loss = (_ctypes.c_float * n)()\n self._ishape = (n, h_in, w_in, c_in)\n self._oshape = (n, h_out, w_out, c_out)\n\n def train(self, input, label):\n \"\"\"\n Submits an input batch to the model. Returns a MpsFloatArray\n representing the batch loss. Calling asnumpy() on this value will wait\n for the batch to finish and yield the loss as a numpy array.\n \"\"\"\n\n assert self._mode == MpsGraphMode.Train\n assert input.shape == self._ishape\n assert label.shape == self._oshape\n\n input_array = MpsFloatArray(input)\n label_array = MpsFloatArray(label)\n result_handle = _ctypes.c_void_p()\n status_code = self._LIB.TCMPSTrainGraph(\n self.handle, input_array.handle, label_array.handle,\n _ctypes.byref(result_handle))\n\n assert status_code == 0, \"Error calling TCMPSTrainGraph\"\n assert result_handle, \"TCMPSTrainGraph unexpectedly returned NULL pointer\"\n\n result = MpsFloatArray(result_handle)\n\n # Output from training should be a one-dimensional array of loss values,\n # one per example in the batch.\n assert result.shape() == (self._oshape[0],)\n\n return result\n\n def predict(self, input):\n \"\"\"\n Submits an input batch to the model. Returns a MpsFloatArray\n representing the model predictions. Calling asnumpy() on this value will\n wait for the batch to finish and yield the predictions as a numpy array.\n \"\"\"\n\n assert self._mode == MpsGraphMode.Inference\n assert input.shape == self._ishape\n\n input_array = MpsFloatArray(input)\n result_handle = _ctypes.c_void_p()\n status_code = self._LIB.TCMPSPredictGraph(\n self.handle, input_array.handle, _ctypes.byref(result_handle))\n\n assert status_code == 0, \"Error calling TCMPSPredictGraph\"\n assert result_handle, \"TCMPSPredictGraph unexpectedly returned NULL pointer\"\n\n result = MpsFloatArray(result_handle)\n assert result.shape() == self._oshape\n\n return result\n\n def train_return_grad(self, input, grad):\n \"\"\"\n Performs a forward pass from the input batch, followed by a backward\n pass using the provided gradient (in place of a loss function). Returns\n a MpsFloatArray representing the output (final gradient) of the backward\n pass. Calling asnumpy() on this value will wait for the batch to finish\n and yield the output as a numpy array.\n \"\"\"\n\n assert self._mode == MpsGraphMode.TrainReturnGrad\n assert input.shape == self._ishape\n assert grad.shape == self._oshape\n\n input_array = MpsFloatArray(input)\n grad_array = MpsFloatArray(grad)\n result_handle = _ctypes.c_void_p()\n status_code = self._LIB.TCMPSTrainGraph(\n self.handle, input_array.handle, grad_array.handle,\n _ctypes.byref(result_handle))\n\n assert status_code == 0, \"Error calling TCMPSTrainReturnGradGraph\"\n assert result_handle, \"TCMPSTrainReturnGradGraph unexpectedly returned NULL pointer\"\n\n result = MpsFloatArray(result_handle)\n assert result.shape() == self._ishape\n\n return result\n\n def set_learning_rate(self, new_lr):\n self._cur_learning_rate = new_lr\n self._LIB.TCMPSSetLearningRateGraph(self.handle, _ctypes.c_float(new_lr))\n\n def load(self, weights):\n self._LIB.TCMPSDeleteGraphModule(self.handle)\n self.handle = _ctypes.c_void_p()\n self._LIB.TCMPSCreateGraphModule(_ctypes.byref(self.handle),\n _ctypes.c_int(self._mode))\n n, h_in, w_in, c_in = self._ishape\n _, h_out, w_out, c_out = self._oshape\n self.init(n, c_in, h_in, w_in, c_out, h_out, w_out,\n config=self._cur_config, weights=weights)\n # Reload state\n if self._cur_learning_rate:\n self.set_learning_rate(self._cur_learning_rate)\n\n def export(self):\n iter_handle = _ctypes.c_void_p()\n status_code = self._LIB.TCMPSExportGraph(self.handle,\n _ctypes.byref(iter_handle))\n assert status_code == 0\n return dict(MpsFloatArrayIterator(iter_handle))\n\n\n#----------------------------------------------------------\n#\n# MPS Graph level API, currently used by Activity Classifier\n#\n#----------------------------------------------------------\n\nclass MpsLowLevelAPI(object):\n def __init__(self, network_id=MpsLowLevelNetworkType.kActivityClassifierNet):\n self.handle = _ctypes.c_void_p()\n self._LIB = _load_tcmps_lib()\n assert self._LIB is not None, \"Cannot use MpsLowLevelAPI without libtcmps.dylib\"\n self._LIB.TCMPSCreateCNNModule(_ctypes.byref(self.handle))\n self._buf = None\n self._buf_g = None\n self._ishape = None\n self._oshape = None\n self.network_id = network_id\n\n def __del__(self):\n self._LIB.TCMPSDeleteCNNModule(self.handle)\n\n def init(self, n, c_in, h_in, w_in, c_out, h_out, w_out, updater=1, config={}):\n config_items, config_name, config_arr = _prepare_network_parameters(config)\n self._LIB.TCMPSInit(\n self.handle,\n self.network_id,\n _ctypes.c_int32(n),\n _ctypes.c_int32(c_in),\n _ctypes.c_int32(h_in),\n _ctypes.c_int32(w_in),\n _ctypes.c_int32(c_out),\n _ctypes.c_int32(h_out),\n _ctypes.c_int32(w_out),\n _ctypes.c_int32(updater),\n config_name, config_arr, _ctypes.c_int32(len(config_items)),\n )\n sz = n * c_out * h_out * w_out\n self._buf = (_ctypes.c_float * sz)()\n sz = n * c_in * h_in * w_in\n self._buf_g = (_ctypes.c_float * sz)()\n\n self._ishape = (n, h_in, w_in, c_in)\n self._oshape = (n, h_out, w_out, c_out)\n\n def load(self, weights):\n weights_items, weights_name, weights_arr = _prepare_network_parameters(weights)\n self._LIB.TCMPSLoad(self.handle, weights_name, weights_arr, _ctypes.c_int32(len(weights_items)))\n\n def export(self):\n iter_handle = _ctypes.c_void_p()\n status_code = self._LIB.TCMPSExport(self.handle,\n _ctypes.byref(iter_handle))\n assert status_code == 0\n return dict(MpsFloatArrayIterator(iter_handle))\n\n def initalize_weights(self):\n args = self.export()\n for key, val in args.items():\n if key.endswith(\"weight\"):\n args[key] = _xavier_init(val)\n self.load(args)\n\n def _loss_or_iteration_call(self, lib_method, input, labels, weights):\n expected_label_shape = (self._oshape[:-1] + (1,))\n assert input.shape == self._ishape\n assert labels.shape == expected_label_shape\n assert weights.shape == expected_label_shape\n\n input_array = MpsFloatArray(input)\n labels_array = MpsFloatArray(labels)\n weights_array = MpsFloatArray(weights)\n output_handle = _ctypes.c_void_p()\n loss_handle = _ctypes.c_void_p()\n status_code = lib_method(\n self.handle,\n input_array.handle, labels_array.handle, weights_array.handle,\n _ctypes.byref(output_handle), _ctypes.byref(loss_handle))\n\n assert status_code == 0, \"Error calling TCMPS\"\n assert output_handle, \"TCMPS unexpectedly returned NULL pointer\"\n assert loss_handle, \"TCMPS unexpectedly returned NULL pointer\"\n\n output = MpsFloatArray(output_handle)\n loss = MpsFloatArray(loss_handle)\n\n assert output.shape() == self._oshape\n assert loss.shape() == (self._oshape[0], 1, 1, 1)\n\n return (output, loss)\n\n def train(self, input, labels, weights):\n return self._loss_or_iteration_call(self._LIB.TCMPSTrain, input, labels,\n weights)\n\n def predict_with_loss(self, input, labels, weights):\n return self._loss_or_iteration_call(self._LIB.TCMPSPredict, input,\n labels, weights)\n\n def predict(self, input):\n assert input.shape == self._ishape\n\n input_array = MpsFloatArray(input)\n output_handle = _ctypes.c_void_p()\n status_code = self._LIB.TCMPSPredict(\n self.handle, input_array.handle, None, None,\n _ctypes.byref(output_handle), None)\n\n assert status_code == 0, \"Error calling TCMPSPredict\"\n assert output_handle, \"TCMPSPredict unexpectedly returned NULL pointer\"\n\n output = MpsFloatArray(output_handle)\n assert output.shape() == self._oshape\n\n return output\n" ]
[ [ "numpy.sqrt", "numpy.asarray", "numpy.squeeze", "numpy.prod", "numpy.random.uniform", "numpy.fromiter", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
blacksph3re/garage
[ "b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507", "b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507", "b4abe07f0fa9bac2cb70e4a3e315c2e7e5b08507" ]
[ "tests/garage/np/test_functions.py", "tests/fixtures/envs/dummy/dummy_box_env.py", "tests/fixtures/envs/dummy/dummy_discrete_pixel_env_baselines.py" ]
[ "# yapf: disable\nimport warnings\n\nimport numpy as np\n\nfrom garage.np import (concat_tensor_dict_list, explained_variance_1d,\n pad_batch_array, pad_tensor,\n stack_and_pad_tensor_dict_list, stack_tensor_dict_list)\n\n# yapf: enable\n\ndata = [\n dict(obs=[1, 1, 1], act=[2, 2, 2], info=dict(lala=[1, 1], baba=[2, 2])),\n dict(obs=[1, 1, 1], act=[2, 2, 2], info=dict(lala=[1, 1], baba=[2, 2]))\n]\ndata2 = [\n dict(obs=[1, 1, 1], act=[2, 2, 2], info=dict(lala=[1, 1], baba=[2, 2])),\n dict(obs=[1, 1, 1], act=[2, 2, 2], info=dict(lala=[1, 1]))\n]\nmax_len = 10\ntensor = [1, 1, 1]\n\n\ndef test_concat_tensor_dict_list():\n results = concat_tensor_dict_list(data)\n assert results['obs'].shape == (6, )\n assert results['act'].shape == (6, )\n assert results['info']['lala'].shape == (4, )\n assert results['info']['baba'].shape == (4, )\n\n results = concat_tensor_dict_list(data2)\n assert results['obs'].shape == (6, )\n assert results['act'].shape == (6, )\n assert results['info']['lala'].shape == (4, )\n assert results['info']['baba'].shape == (2, )\n\n\ndef test_stack_tensor_dict_list():\n results = stack_tensor_dict_list(data)\n assert results['obs'].shape == (2, 3)\n assert results['act'].shape == (2, 3)\n assert results['info']['lala'].shape == (2, 2)\n assert results['info']['baba'].shape == (2, 2)\n\n results = stack_tensor_dict_list(data2)\n assert results['obs'].shape == (2, 3)\n assert results['act'].shape == (2, 3)\n assert results['info']['lala'].shape == (2, 2)\n assert results['info']['baba'].shape == (2, )\n\n\ndef test_pad_tensor():\n results = pad_tensor(tensor, max_len)\n assert len(tensor) == 3\n assert np.array_equal(results, [1, 1, 1, 0, 0, 0, 0, 0, 0, 0])\n\n results = pad_tensor(tensor, max_len, mode='last')\n assert np.array_equal(results, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n\n\ndef test_explained_variance_1d():\n y = np.array([1, 2, 3, 4, 5, 0, 0, 0, 0, 0])\n y_hat = np.array([2, 3, 4, 5, 6, 0, 0, 0, 0, 0])\n valids = np.array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0])\n result = explained_variance_1d(y, y_hat, valids)\n assert result == 1.0\n result = explained_variance_1d(y, y_hat)\n np.testing.assert_almost_equal(result, 0.95)\n\n\ndef test_stack_and_pad_tensor_dict_list():\n result = stack_and_pad_tensor_dict_list(data, max_len=5)\n assert np.array_equal(result['obs'],\n np.array([[1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]))\n assert np.array_equal(result['info']['lala'],\n np.array([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0]]))\n assert np.array_equal(result['info']['baba'],\n np.array([[2, 2, 0, 0, 0], [2, 2, 0, 0, 0]]))\n\n\ndef test_pad_batch_array_warns_on_too_long():\n with warnings.catch_warnings(record=True) as warns:\n warnings.simplefilter('always')\n result = pad_batch_array(np.ones(9), [5, 2, 2], 2)\n assert len(warns) == 1\n assert 'longer length than requested' in str(warns[0].message)\n assert (result == np.asarray([[1., 1., 1., 1., 1.], [1., 1., 0., 0., 0.],\n [1., 1., 0., 0., 0.]])).all()\n", "\"\"\"Dummy akro.Box environment for testing purpose.\"\"\"\nimport akro\nimport numpy as np\n\nfrom tests.fixtures.envs.dummy import DummyEnv\n\n\nclass DummyBoxEnv(DummyEnv):\n \"\"\"A dummy gym.spaces.Box environment.\n\n Args:\n random (bool): If observations are randomly generated or not.\n obs_dim (iterable): Observation space dimension.\n action_dim (iterable): Action space dimension.\n\n \"\"\"\n\n def __init__(self, random=True, obs_dim=(4, ), action_dim=(2, )):\n super().__init__(random, obs_dim, action_dim)\n\n @property\n def observation_space(self):\n \"\"\"Return an observation space.\n\n Returns:\n gym.spaces: The observation space of the environment.\n\n \"\"\"\n return akro.Box(low=-1, high=1, shape=self._obs_dim, dtype=np.float32)\n\n @property\n def action_space(self):\n \"\"\"Return an action space.\n\n Returns:\n gym.spaces: The action space of the environment.\n\n \"\"\"\n return akro.Box(low=-5.0,\n high=5.0,\n shape=self._action_dim,\n dtype=np.float32)\n\n def reset(self):\n \"\"\"Reset the environment.\n\n Returns:\n np.ndarray: The observation obtained after reset.\n\n \"\"\"\n return np.ones(self._obs_dim, dtype=np.float32)\n\n def step(self, action):\n \"\"\"Step the environment.\n\n Args:\n action (int): Action input.\n\n Returns:\n np.ndarray: Observation.\n float: Reward.\n bool: If the environment is terminated.\n dict: Environment information.\n\n \"\"\"\n return self.observation_space.sample(), 0, False, dict(dummy='dummy')\n", "import gym\nimport numpy as np\n\nfrom tests.fixtures.envs.dummy import DummyEnv\n\n\nclass LazyFrames(object):\n def __init__(self, frames):\n \"\"\"\n LazyFrames class from baselines.\n\n Openai baselines use this class for FrameStack environment\n wrapper. It is used for testing garage.envs.wrappers.AtariEnv.\n garge.envs.wrapper.AtariEnv is used when algorithms are trained\n using baselines wrappers, e.g. during benchmarking.\n \"\"\"\n self._frames = frames\n self._out = None\n\n def _force(self):\n if self._out is None:\n self._out = np.concatenate(self._frames, axis=-1)\n self._frames = None\n return self._out\n\n def __array__(self, dtype=None):\n out = self._force()\n if dtype is not None:\n out = out.astype(dtype)\n return out\n\n\nclass DummyDiscretePixelEnvBaselines(DummyEnv):\n \"\"\"\n A dummy discrete pixel environment.\n\n This environment is for testing garge.envs.wrapper.AtariEnv.\n \"\"\"\n\n def __init__(self):\n super().__init__(random=False, obs_dim=(10, 10, 3), action_dim=5)\n self._observation_space = gym.spaces.Box(\n low=0, high=255, shape=self._obs_dim, dtype=np.uint8)\n\n @property\n def observation_space(self):\n \"\"\"Return an observation space.\"\"\"\n return self._observation_space\n\n @property\n def action_space(self):\n \"\"\"Return an action space.\"\"\"\n return gym.spaces.Discrete(self._action_dim)\n\n def step(self, action):\n \"\"\"gym.Env step function.\"\"\"\n obs = self.observation_space.sample()\n return LazyFrames([obs]), 0, True, dict()\n\n def reset(self, **kwargs):\n \"\"\"gym.Env reset function.\"\"\"\n obs = np.ones(self._obs_dim, dtype=np.uint8)\n return LazyFrames([obs])\n" ]
[ [ "numpy.array_equal", "numpy.asarray", "numpy.ones", "numpy.testing.assert_almost_equal", "numpy.array" ], [ "numpy.ones" ], [ "numpy.concatenate", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
laijingtao/landlab
[ "871151bff814e672b4f09f091b6347367758c764", "871151bff814e672b4f09f091b6347367758c764", "871151bff814e672b4f09f091b6347367758c764", "4f43055060b544b34e71eba7062c09866ad93640" ]
[ "landlab/components/sink_fill/pit_remove.py", "landlab/grid/divergence.py", "landlab/components/weathering/exponential_weathering.py", "landlab/grid/raster_mappers.py" ]
[ "\"\"\"\npit_remove.py\nImplementation of algorithm described by Planchon(2001)\n\nCreated by JL, Oct 2015\n\"\"\"\n\nimport numpy\n\nimport landlab\nfrom landlab import Component, FieldError\nfrom landlab.grid.base import BAD_INDEX_VALUE\n\n\nclass PitRemove(Component):\n\n\tdef __init__(self, input_grid):\n\n\t\tself._grid = input_grid\n\n\t\t(self._nrows, self._ncols) = self._grid.shape\n\t\tself._R0 = numpy.array([0, self._nrows-1, 0, self._nrows-1, 0, self._nrows-1, 0, self._nrows-1])\n\t\tself._C0 = numpy.array([0, self._ncols-1, self._ncols-1, 0, self._ncols-1, 0, 0, self._ncols-1])\n\t\tself._dR = numpy.array([0, 0, 1, -1, 0, 0, 1, -1])\n\t\tself._dC = numpy.array([1, -1, 0, 0, -1, 1, 0, 0])\n\t\tself._fR = numpy.array([1, -1, -self._nrows+1, self._nrows-1, 1, -1, -self._nrows+1, self._nrows-1])\n\t\tself._fC = numpy.array([-self._ncols+1, self._ncols-1, -1, 1, self._ncols-1, -self._ncols+1, 1, -1])\n\n\t\tself._neighbor_dR = numpy.array([0, 0, 1, -1, 1, 1, -1, -1])\n\t\tself._neighbor_dC = numpy.array([1, -1, 0, 0, 1, -1, 1, -1])\n\t\tself._neighbors = numpy.concatenate((self._grid.neighbors_at_node, self._grid.diagonals_at_node), axis=1)\n\t\tself._neighbors[self._neighbors == BAD_INDEX_VALUE] = -1\n\n\t\tself._huge_number = 32767\n\n\n\tdef _get_node_id(self, r, c):\n\n\t\treturn r*self._ncols+c\n\n\n\tdef _get_node_coord(self, nodeid):\n\n\t\tr = self._grid.node_y[nodeid]/self._grid.dx\n\t\tc = self._grid.node_x[nodeid]/self._grid.dx\n\n\t\treturn r, c\n\n\n\tdef _next_node(self, node, i):\n\t\t#For the given node and scan direction i, this function calculates the ID of the next node to consider\n\n\t\t(r, c) = self._get_node_coord(node)\n\n\t\tr = r+self._dR[i]\n\t\tc = c+self._dC[i]\n\n\t\tif r<0 or c<0 or r>=self._nrows or c>=self._ncols:\n\t\t\tr = r+self._fR[i]\n\t\t\tc = c+self._fC[i]\n\t\t\tif r<0 or c<0 or r>=self._nrows or c>=self._ncols:\n\t\t\t\treturn -1\n\n\t\treturn self._get_node_id(r, c)\n\n\n\tdef _do_upstream_node(self, node, depth=1):\n\t\t#go upstream\n\n\t\tif depth>900:\n\t\t\treturn \n\n\t\tfor i in range(8):\n\t\t\tneighbor_node = self._neighbors[node][i]\n\t\t\tif neighbor_node==-1:\n\t\t\t\tcontinue\n\t\t\tif self._w[neighbor_node]!=self._huge_number:\n\t\t\t\tcontinue\n\t\t\tif self._z[neighbor_node]>=self._w[node]:\n\t\t\t\tself._w[neighbor_node]=self._z[neighbor_node]\n\t\t\t\tself._do_upstream_node(neighbor_node, depth+1)\n\n\t\treturn \n\n\n\tdef pit_fill(self):\n\t\t#fill pit\n\n\t\t#initialisation\n\t\tself._z = self._grid['node']['topographic__elevation']\n\t\tself._w = numpy.zeros(self._grid.number_of_nodes, dtype='float')\n\t\tn = self._grid.number_of_nodes\n\t\t(border, ) = numpy.where(numpy.logical_or(self._grid.status_at_node==1, self._grid.status_at_node==2))\n\t\tfor i in range(n):\n\t\t\tif i in border:\n\t\t\t\tself._w[i] = self._z[i]\n\t\t\telse:\n\t\t\t\tself._w[i] = self._huge_number\n\n\t\t#explore from the border\n\t\tfor i in border:\n\t\t\tself._do_upstream_node(i)\n\n\t\t#iteratively scan the DEM\n\t\tvictory = False\n\t\twhile not(victory):\n\t\t\tfor scan in range(8):\n\t\t\t\tr = self._R0[scan]\n\t\t\t\tc = self._C0[scan]\n\t\t\t\tnode = self._get_node_id(r, c)\n\t\t\t\tsomething_done = False\n\t\t\t\twhile node!=-1:\n\t\t\t\t\tif self._w[node]>self._z[node]:\n\t\t\t\t\t\tfor i in range(8):\n\t\t\t\t\t\t\tneighbor_node = self._neighbors[node][i]\n\t\t\t\t\t\t\tif neighbor_node==-1:\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\tif self._z[node]>=self._w[neighbor_node]:\n\t\t\t\t\t\t\t\tself._w[node] = self._z[node]\n\t\t\t\t\t\t\t\tsomething_done = True\n\t\t\t\t\t\t\t\tself._do_upstream_node(node)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tif self._w[node]>self._w[neighbor_node]:\n\t\t\t\t\t\t\t\tself._w[node] = self._w[neighbor_node]\n\t\t\t\t\t\t\t\tsomething_done = True\n\t\t\t\t\tnode = self._next_node(node, scan)\n\t\t\t\tif something_done == False:\n\t\t\t\t\tvictory = True\n\t\t\t\t\tbreak\n\n\t\tself._grid['node']['topographic__elevation'] = self._w\n\n\t\treturn self._grid\n\n", "#! /usr/bin/env python\n\"\"\"Calculate vector divergence and related quantities at nodes or cells.\"\"\"\nimport numpy as np\nfrom landlab.utils.decorators import use_field_name_or_array\n\n\n\n@use_field_name_or_array('link')\ndef calc_flux_div_at_node(grid, unit_flux, out=None):\n \"\"\"Calculate divergence of link-based fluxes at nodes.\n\n Given a flux per unit width across each face in the grid, calculate the net\n outflux (or influx, if negative) divided by cell area, at each node (zero\n or \"out\" value for nodes without cells).\n\n Construction::\n\n calc_flux_div_at_node(grid, unit_flux_at_links, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux : ndarray or field name\n Flux per unit width along links (x number of links) or across faces\n (x number of faces).\n\n Returns\n -------\n ndarray (x number of nodes)\n Flux divergence at nodes.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> lg = rg.calc_grad_at_link(z) # there are 17 links\n >>> lg\n array([ 0. , 0. , 0. , 0. , 5. , 3.6, 0. , 5. , -1.4, -3.6, 0. ,\n -5. , -3.6, 0. , 0. , 0. , 0. ])\n >>> calc_flux_div_at_node(rg, -lg)\n array([ 0. , 0. , 0. , 0. , 0. , 1.64, 0.94, 0. , 0. ,\n 0. , 0. , 0. ])\n >>> fg = lg[rg.link_at_face] # there are 7 faces\n >>> fg\n array([ 5. , 3.6, 5. , -1.4, -3.6, -5. , -3.6])\n >>> calc_flux_div_at_node(rg, -fg)\n array([ 0. , 0. , 0. , 0. , 0. , 1.64, 0.94, 0. , 0. ,\n 0. , 0. , 0. ])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> unit_flux_at_links = np.zeros(rg.number_of_links)\n >>> unit_flux_at_links[rg.active_links] = -lg[rg.active_links]\n >>> calc_flux_div_at_node(rg, unit_flux_at_links)\n array([ 0. , 0. , 0. , 0. , 0. , 1.14, 0.22, 0. , 0. ,\n 0. , 0. , 0. ])\n >>> unit_flux_at_faces = np.zeros(rg.number_of_faces)\n >>> unit_flux_at_faces[rg.active_faces] = -fg[rg.active_faces]\n >>> calc_flux_div_at_node(rg, unit_flux_at_faces)\n array([ 0. , 0. , 0. , 0. , 0. , 1.14, 0.22, 0. , 0. ,\n 0. , 0. , 0. ])\n\n Notes\n -----\n Performs a numerical flux divergence operation on nodes.\n\n LLCATS: NINF GRAD\n \"\"\"\n if unit_flux.size not in (grid.number_of_links, grid.number_of_faces):\n raise ValueError('Parameter unit_flux must be num links or num faces '\n 'long')\n if out is None:\n out = grid.zeros(at='node')\n elif out.size != grid.number_of_nodes:\n raise ValueError('output buffer length mismatch with number of nodes')\n\n if unit_flux.size == grid.number_of_links:\n out[grid.node_at_cell] = _calc_net_face_flux_at_cell(grid, \n unit_flux[grid.link_at_face]) \\\n / grid.area_of_cell\n elif unit_flux.size == grid.number_of_faces:\n out[grid.node_at_cell] = _calc_net_face_flux_at_cell(grid, unit_flux) \\\n / grid.area_of_cell\n\n return out\n\n\n@use_field_name_or_array('link')\ndef calc_net_flux_at_node(grid, unit_flux_at_links, out=None):\n \"\"\"Calculate net link fluxes at nodes.\n\n Given a flux per unit width along each link in the grid, calculate the net\n outflux (or influx, if negative) at each node. Fluxes are treated as zero\n for links that have no faces, and net fluxes are treated as zero for nodes\n that have no cell.\n\n Construction::\n\n calc_net_flux_at_node(grid, unit_flux_at_links, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux_at_links : ndarray or field name\n Flux per unit width associated with links.\n out : ndarray, optional\n Buffer to hold the result.\n\n Returns\n -------\n ndarray (x number of cells)\n Net flux at nodes.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> lg = rg.calc_grad_at_link(z) # there are 17 links\n >>> lg\n array([ 0. , 0. , 0. , 0. , 5. , 3.6, 0. , 5. , -1.4, -3.6, 0. ,\n -5. , -3.6, 0. , 0. , 0. , 0. ])\n >>> calc_net_flux_at_node(rg, -lg)\n array([ 0., 0., 0., 0., 0., 164., 94., 0., 0.,\n 0., 0., 0.])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> unit_flux_at_links = np.zeros(rg.number_of_links)\n >>> unit_flux_at_links[rg.active_links] = -lg[rg.active_links]\n >>> nlfn = calc_net_flux_at_node(rg, unit_flux_at_links)\n >>> np.round(nlfn)\n array([ 0., 0., 0., 0., 0., 114., 22., 0., 0.,\n 0., 0., 0.])\n\n >>> from landlab import HexModelGrid\n >>> hg = HexModelGrid(3, 3, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation', noclobber=False)\n >>> z[4] = 50.0\n >>> z[5] = 36.0\n >>> lg = hg.calc_grad_at_link(z) # there are ? links\n >>> lg\n array([ 0. , 0. , 0. , 5. , 5. , 3.6, 3.6, 0. , 5. , -1.4, -3.6,\n 0. , -5. , -5. , -3.6, -3.6, 0. , 0. , 0. ])\n >>> nlfn = calc_net_flux_at_node(hg, -lg)\n >>> np.round(nlfn)\n array([ 0., 0., 0., 0., 152., 96., 0., 0., 0., 0.])\n\n Notes\n -----\n This is essentially a line integral for the fluxes along the boundaries of\n each cell. Hence, the resulting output has dimensions of total flux (so,\n if the unit flux happens to be mass per time per face width, the output\n will be in mass per unit time). Because a line integral is undefined where\n there are no cells (i.e., perimeter nodes), the result is given as zeros\n for these nodes. The current algorithm uses fancy indexing (calling\n _calc_net_face_flux_at_cells) and could probably be made faster.\n\n LLCATS: NINF GRAD\n \"\"\"\n if out is None:\n out = grid.zeros(at='node')\n\n out[grid.node_at_cell] = _calc_net_face_flux_at_cell(grid, \n unit_flux_at_links[grid.link_at_face])\n return out\n\n\n@use_field_name_or_array('face')\ndef _calc_net_face_flux_at_cell(grid, unit_flux_at_faces, out=None):\n \"\"\"Calculate net face fluxes at cells.\n\n Given a flux per unit width across each face in the grid, calculate the net\n outflux (or influx, if negative) at each cell.\n\n Construction::\n\n _calc_net_face_flux_at_cell(grid, unit_flux_at_faces, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux_at_faces : ndarray or field name\n Flux per unit width associated with faces.\n out : ndarray, optional\n Buffer to hold the result.\n\n Returns\n -------\n ndarray (x number of cells)\n Net flux at cells.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> lg = rg.calc_grad_at_link(z)\n >>> fg = lg[rg.link_at_face] # there are 7 faces\n >>> fg\n array([ 5. , 3.6, 5. , -1.4, -3.6, -5. , -3.6])\n >>> _calc_net_face_flux_at_cell(rg, -fg)\n array([ 164., 94.])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> unit_flux_at_faces = np.zeros(rg.number_of_faces)\n >>> unit_flux_at_faces[rg.active_faces] = -fg[rg.active_faces]\n >>> _calc_net_face_flux_at_cell(rg, unit_flux_at_faces)\n array([ 114., 22.])\n\n >>> from landlab import HexModelGrid\n >>> hg = HexModelGrid(3, 3, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation', noclobber=False)\n >>> z[4] = 50.0\n >>> z[5] = 36.0\n >>> lg = hg.calc_grad_at_link(z)\n >>> fg = lg[hg.link_at_face] # there are 11 faces\n >>> fg\n array([ 5. , 5. , 3.6, 3.6, 5. , -1.4, -3.6, -5. , -5. , -3.6, -3.6])\n >>> nffc = _calc_net_face_flux_at_cell(hg, -fg)\n >>> np.round(nffc)\n array([ 152., 96.])\n\n Notes\n -----\n This is essentially a line integral for the fluxes along the boundaries of\n each cell. Hence, the resulting output has dimensions of total flux (so,\n if the unit flux happens to be mass per time per face width, the output\n will be in mass per unit time).\n \"\"\"\n if out is None:\n out = grid.empty(at='cell')\n total_flux = unit_flux_at_faces * grid.width_of_face\n out = np.zeros(grid.number_of_cells)\n fac = grid.faces_at_cell\n for c in range(grid.link_dirs_at_node.shape[1]):\n out -= total_flux[fac[:,c]] \\\n * grid.link_dirs_at_node[grid.node_at_cell,c]\n return out\n\n\n@use_field_name_or_array('face')\ndef _calc_face_flux_divergence_at_cell(grid, unit_flux_at_faces):\n \"\"\"Calculate divergence of face-based fluxes at cells.\n\n Given a flux per unit width across each face in the grid, calculate the net\n outflux (or influx, if negative) divided by cell area, at each cell.\n\n Construction::\n\n _calc_face_flux_divergence_at_cell(grid, unit_flux_at_faces, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux_at_faces : ndarray or field name\n Flux per unit width associated with faces.\n\n Returns\n -------\n ndarray (x number of cells)\n Flux divergence at cells.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> lg = rg.calc_grad_at_link(z)\n >>> lg[rg.link_at_face]\n array([ 5. , 3.6, 5. , -1.4, -3.6, -5. , -3.6])\n >>> _calc_face_flux_divergence_at_cell(rg, -lg[rg.link_at_face])\n array([ 1.64, 0.94])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> unit_flux_at_faces = np.zeros(rg.number_of_faces)\n >>> fg = lg[rg.link_at_face]\n >>> unit_flux_at_faces[rg.active_faces] = -fg[rg.active_faces]\n >>> _calc_face_flux_divergence_at_cell(rg, unit_flux_at_faces)\n array([ 1.14, 0.22])\n\n Notes\n -----\n Performs a numerical flux divergence operation on cells.\n \"\"\"\n return _calc_net_face_flux_at_cell(grid, unit_flux_at_faces) \\\n / grid.area_of_cell\n\n\n@use_field_name_or_array('face')\ndef _calc_net_active_face_flux_at_cell(grid, unit_flux_at_faces, out=None):\n \"\"\"Calculate net face fluxes at cells, ignoring values on inactive faces.\n\n Given a flux per unit width across each face in the grid, calculate the net\n outflux (or influx, if negative) at each cell. Same as\n `_calc_net_face_flux_at_cell` except that flux values on inactive faces\n are ignored.\n\n Construction::\n\n _calc_net_active_face_flux_at_cell(grid, unit_flux_at_faces, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux_at_faces : ndarray or field name (x number of faces)\n Flux per unit width associated with faces.\n out : ndarray, optional\n Buffer to hold the result.\n\n Returns\n -------\n ndarray (x number of cells)\n Net flux at cells.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> fg = rg.calc_grad_at_link(z)[rg.link_at_face] # there are 7 faces\n >>> fg\n array([ 5. , 3.6, 5. , -1.4, -3.6, -5. , -3.6])\n >>> _calc_net_active_face_flux_at_cell(rg, -fg)\n array([ 164., 94.])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> _calc_net_active_face_flux_at_cell(rg, -fg)\n array([ 114., 22.])\n\n >>> from landlab import HexModelGrid\n >>> hg = HexModelGrid(3, 3, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation', noclobber=False)\n >>> z[4] = 50.0\n >>> z[5] = 36.0\n >>> fg = hg.calc_grad_at_link(z)[hg.link_at_face] # there are 11 faces\n >>> fg\n array([ 5. , 5. , 3.6, 3.6, 5. , -1.4, -3.6, -5. , -5. , -3.6, -3.6])\n >>> nffc = _calc_net_active_face_flux_at_cell(hg, -fg)\n >>> np.round(nffc)\n array([ 152., 96.])\n\n Notes\n -----\n This is essentially a line integral for the fluxes along the boundaries of\n each cell. Hence, the resulting output has dimensions of total flux (so,\n if the unit flux happens to be mass per time per face width, the output\n will be in mass per unit time).\n \"\"\"\n if out is None:\n out = grid.empty(at='cell')\n total_flux = unit_flux_at_faces * grid.width_of_face\n out = np.zeros(grid.number_of_cells)\n fac = grid.faces_at_cell\n for c in range(grid.active_link_dirs_at_node.shape[1]):\n out -= total_flux[fac[:,c]] \\\n * grid.active_link_dirs_at_node[grid.node_at_cell,c]\n return out\n\n\n@use_field_name_or_array('face')\ndef _calc_active_face_flux_divergence_at_cell(grid, unit_flux_at_faces):\n \"\"\"Calculate divergence of face-based fluxes at cells, ignoring values on\n inactive faces.\n\n Given a flux per unit width across each face in the grid, calculate the net\n outflux (or influx, if negative) divided by cell area, at each cell. Same\n as `_calc_face_flux_divergence_at_cell` except that flux values at inactive\n faces are ignored.\n\n Construction::\n\n _calc_active_face_flux_divergence_at_cell(grid, unit_flux_at_faces,\n out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux_at_faces : ndarray or field name (x number of faces)\n Flux per unit width associated with faces.\n\n Returns\n -------\n ndarray (x number of cells)\n Flux divergence at cells.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> fg = rg.calc_grad_at_link(z)[rg.link_at_face] # there are 7 faces\n >>> fg\n array([ 5. , 3.6, 5. , -1.4, -3.6, -5. , -3.6])\n >>> _calc_active_face_flux_divergence_at_cell(rg, -fg)\n array([ 1.64, 0.94])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> _calc_active_face_flux_divergence_at_cell(rg, -fg)\n array([ 1.14, 0.22])\n\n Notes\n -----\n Performs a numerical flux divergence operation on cells.\n \"\"\"\n return _calc_net_active_face_flux_at_cell(grid, unit_flux_at_faces) \\\n / grid.area_of_cell\n\n\n@use_field_name_or_array('link')\ndef _calc_net_active_link_flux_at_node(grid, unit_flux_at_links, out=None):\n \"\"\"Calculate net link fluxes at nodes, ignoring fluxes on inactive links.\n\n Given a flux per unit width along each link in the grid, calculate the net\n outflux (or influx, if negative) at each node. Fluxes are treated as zero\n for links that have no faces, and net fluxes are treated as zero for nodes\n that have no cell. Same as `_calc_net_link_flux_at_node` except that it\n ignores any flux values on inactive links.\n\n Construction::\n\n _calc_net_active_link_flux_at_node(grid, unit_flux_at_links, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux_at_links : ndarray or field name (x number of links)\n Flux per unit width associated with links.\n out : ndarray, optional\n Buffer to hold the result.\n\n Returns\n -------\n ndarray (x number of cells)\n Net flux at nodes.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> lg = rg.calc_grad_at_link(z) # there are 17 links\n >>> lg\n array([ 0. , 0. , 0. , 0. , 5. , 3.6, 0. , 5. , -1.4, -3.6, 0. ,\n -5. , -3.6, 0. , 0. , 0. , 0. ])\n >>> _calc_net_active_link_flux_at_node(rg, -lg)\n array([ 0., 0., 0., 0., 0., 164., 94., 0., 0.,\n 0., 0., 0.])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> nlfn = _calc_net_active_link_flux_at_node(rg, -lg)\n >>> np.round(nlfn)\n array([ 0., 0., 0., 0., 0., 114., 22., 0., 0.,\n 0., 0., 0.])\n\n >>> from landlab import HexModelGrid\n >>> hg = HexModelGrid(3, 3, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation', noclobber=False)\n >>> z[4] = 50.0\n >>> z[5] = 36.0\n >>> lg = hg.calc_grad_at_link(z) # there are ? links\n >>> lg\n array([ 0. , 0. , 0. , 5. , 5. , 3.6, 3.6, 0. , 5. , -1.4, -3.6,\n 0. , -5. , -5. , -3.6, -3.6, 0. , 0. , 0. ])\n >>> nlfn = _calc_net_active_link_flux_at_node(hg, -lg)\n >>> np.round(nlfn)\n array([ 0., 0., 0., 0., 152., 96., 0., 0., 0., 0.])\n\n Notes\n -----\n This is essentially a line integral for the fluxes along the boundaries of\n each cell. Hence, the resulting output has dimensions of total flux (so,\n if the unit flux happens to be mass per time per face width, the output\n will be in mass per unit time). Because a line integral is undefined where\n there are no cells (i.e., perimeter nodes), the result is given as zeros\n for these nodes. The current algorithm uses fancy indexing (calling\n _calc_net_face_flux_at_cells) and could probably be made faster.\n \"\"\"\n if out is None:\n out = grid.zeros(at='node')\n\n out[grid.node_at_cell] = _calc_net_active_face_flux_at_cell(grid, \n unit_flux_at_links[grid.link_at_face])\n return out\n\n\n@use_field_name_or_array('link')\ndef _calc_active_link_flux_divergence_at_node(grid, unit_flux_at_links, \n out=None):\n \"\"\"Calculate divergence of link-based fluxes at nodes, ignoring any fluxes\n at inactive links.\n\n Given a flux per unit width across each face in the grid, calculate the net\n outflux (or influx, if negative) divided by cell area, at each node (zero\n or \"out\" value for nodes without cells).\n\n Construction::\n\n _calc_active_link_flux_divergence_at_node(grid, unit_flux_at_links, \n out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux_at_links : ndarray or field name (x number of links)\n Flux per unit width associated with links.\n\n Returns\n -------\n ndarray (x number of nodes)\n Flux divergence at nodes.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> lg = rg.calc_grad_at_link(z) # there are 17 links\n >>> lg\n array([ 0. , 0. , 0. , 0. , 5. , 3.6, 0. , 5. , -1.4, -3.6, 0. ,\n -5. , -3.6, 0. , 0. , 0. , 0. ])\n >>> _calc_active_link_flux_divergence_at_node(rg, -lg)\n array([ 0. , 0. , 0. , 0. , 0. , 1.64, 0.94, 0. , 0. ,\n 0. , 0. , 0. ])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> _calc_active_link_flux_divergence_at_node(rg, -lg)\n array([ 0. , 0. , 0. , 0. , 0. , 1.14, 0.22, 0. , 0. ,\n 0. , 0. , 0. ])\n\n Notes\n -----\n Performs a numerical flux divergence operation on nodes.\n \"\"\"\n if out is None:\n out = grid.zeros(at='node')\n \n out[grid.node_at_cell] = _calc_net_active_face_flux_at_cell(grid, \n unit_flux_at_links[grid.link_at_face]) \\\n / grid.area_of_cell\n return out\n\n\n@use_field_name_or_array('face')\ndef _calc_net_face_flux_at_node(grid, unit_flux_at_faces, out=None):\n \"\"\"Calculate net face fluxes at nodes.\n\n Given a flux per unit width across each face in the grid, calculate the net\n outflux (or influx, if negative) at each node (nodes without cells are\n zero, or unchanged from `out` parameter if provided)\n\n Construction::\n\n _calc_net_face_flux_at_node(grid, unit_flux_at_faces, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux_at_faces : ndarray or field name\n Flux per unit width associated with faces.\n out : ndarray, optional\n Buffer to hold the result.\n\n Returns\n -------\n ndarray (x number of nodes)\n Net flux at nodes.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> fg = rg.calc_grad_at_link(z)[rg.link_at_face] # there are 7 faces\n >>> fg\n array([ 5. , 3.6, 5. , -1.4, -3.6, -5. , -3.6])\n >>> _calc_net_face_flux_at_node(rg, -fg)\n array([ 0., 0., 0., 0., 0., 164., 94., 0., 0.,\n 0., 0., 0.])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> unit_flux_at_faces = np.zeros(rg.number_of_faces)\n >>> unit_flux_at_faces[rg.active_faces] = -fg[rg.active_faces]\n >>> _calc_net_face_flux_at_node(rg, unit_flux_at_faces)\n array([ 0., 0., 0., 0., 0., 114., 22., 0., 0.,\n 0., 0., 0.])\n\n >>> from landlab import HexModelGrid\n >>> hg = HexModelGrid(3, 3, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation', noclobber=False)\n >>> z[4] = 50.0\n >>> z[5] = 36.0\n >>> fg = hg.calc_grad_at_link(z)[hg.link_at_face] # there are 11 faces\n >>> fg\n array([ 5. , 5. , 3.6, 3.6, 5. , -1.4, -3.6, -5. , -5. , -3.6, -3.6])\n >>> nffc = _calc_net_face_flux_at_node(hg, -fg)\n >>> np.round(nffc)\n array([ 0., 0., 0., 0., 152., 96., 0., 0., 0., 0.])\n\n Notes\n -----\n Like _calc_net_face_flux_at_cells, this essentially performs a line integral\n for the fluxes along the boundaries of each cell. Nodes without cells are\n either assigned a zero value, or if `out` is provided, they retain their\n previous values.\n \"\"\"\n if out is None:\n out = grid.zeros(at='node')\n\n out[grid.node_at_cell] = _calc_net_face_flux_at_cell(grid, \n unit_flux_at_faces)\n return out\n\n\n@use_field_name_or_array('face')\ndef _calc_net_active_face_flux_at_node(grid, unit_flux_at_faces, out=None):\n \"\"\"Calculate net face fluxes at nodes, ignore inactive faces.\n\n Given a flux per unit width across each face in the grid, calculate the net\n outflux (or influx, if negative) at each node (nodes without cells are\n zero, or unchanged from `out` parameter if provided). Same as\n `_calc_net_face_flux_at_node` except that it ignores inactive faces.\n\n Construction::\n\n _calc_net_active_face_flux_at_node(grid, unit_flux_at_faces, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux_at_faces : ndarray or field name (x number of faces)\n Flux per unit width associated with faces.\n out : ndarray, optional\n Buffer to hold the result.\n\n Returns\n -------\n ndarray (x number of nodes)\n Net flux at nodes.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> fg = rg.calc_grad_at_link(z)[rg.link_at_face] # there are 7 faces\n >>> fg\n array([ 5. , 3.6, 5. , -1.4, -3.6, -5. , -3.6])\n >>> _calc_net_active_face_flux_at_node(rg, -fg)\n array([ 0., 0., 0., 0., 0., 164., 94., 0., 0.,\n 0., 0., 0.])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> _calc_net_active_face_flux_at_node(rg, -fg)\n array([ 0., 0., 0., 0., 0., 114., 22., 0., 0.,\n 0., 0., 0.])\n\n >>> from landlab import HexModelGrid\n >>> hg = HexModelGrid(3, 3, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation', noclobber=False)\n >>> z[4] = 50.0\n >>> z[5] = 36.0\n >>> fg = hg.calc_grad_at_link(z)[hg.link_at_face] # there are 11 faces\n >>> fg\n array([ 5. , 5. , 3.6, 3.6, 5. , -1.4, -3.6, -5. , -5. , -3.6, -3.6])\n >>> nffc = _calc_net_active_face_flux_at_node(hg, -fg)\n >>> np.round(nffc)\n array([ 0., 0., 0., 0., 152., 96., 0., 0., 0., 0.])\n\n Notes\n -----\n Like _calc_net_face_flux_at_cells, this essentially performs a line integral\n for the fluxes along the boundaries of each cell. Nodes without cells are\n either assigned a zero value, or if `out` is provided, they retain their\n previous values.\n \"\"\"\n if out is None:\n out = grid.zeros(at='node')\n\n out[grid.node_at_cell] = _calc_net_active_face_flux_at_cell(grid, \n unit_flux_at_faces)\n return out\n\n\n@use_field_name_or_array('face')\ndef _calc_active_face_flux_divergence_at_node(grid, unit_flux_at_faces, out=None):\n \"\"\"Calculate divergence of face-based fluxes at nodes (active faces only).\n\n Given a flux per unit width across each face in the grid, calculate the net\n outflux (or influx, if negative) divided by cell area, at each node that\n lies within a cell.\n\n Construction::\n\n _calc_active_face_flux_divergence_at_node(grid, unit_flux_at_faces,\n out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A ModelGrid.\n unit_flux_at_faces : ndarray or field name (x number of faces)\n Flux per unit width associated with faces.\n out : ndarray (x number of nodes), optional\n Buffer to hold the result.\n\n Returns\n -------\n ndarray (x number of nodes)\n Flux divergence at nodes.\n\n Examples\n --------\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n >>> rg = RasterModelGrid(3, 4, 10.0)\n >>> z = rg.add_zeros('node', 'topographic__elevation')\n >>> z[5] = 50.0\n >>> z[6] = 36.0\n >>> fg = rg.calc_grad_at_link(z)[rg.link_at_face] # there are 7 faces\n >>> fg\n array([ 5. , 3.6, 5. , -1.4, -3.6, -5. , -3.6])\n >>> _calc_active_face_flux_divergence_at_node(rg, -fg)\n array([ 0. , 0. , 0. , 0. , 0. , 1.64, 0.94, 0. , 0. ,\n 0. , 0. , 0. ])\n >>> rg.set_status_at_node_on_edges(right=CLOSED_BOUNDARY)\n >>> rg.set_status_at_node_on_edges(top=CLOSED_BOUNDARY)\n >>> _calc_active_face_flux_divergence_at_node(rg, -fg)\n array([ 0. , 0. , 0. , 0. , 0. , 1.14, 0.22, 0. , 0. ,\n 0. , 0. , 0. ])\n\n Notes\n -----\n Performs a numerical flux divergence operation on cells, and returns the\n result in an array of length equal to the number of nodes. Nodes without\n cells (those on the grid perimeter) are not affected (i.e., their value\n is either zero, or if `out` is given, whatever the prior value in `out`\n was).\n \"\"\"\n if out is None:\n out = grid.zeros(at='node')\n out[grid.node_at_cell] = \\\n _calc_net_active_face_flux_at_cell(grid, unit_flux_at_faces) \\\n / grid.area_of_cell\n return out\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 8 08:32:48 2016\n\n@author: RCGlade\n\"\"\"\n\nfrom landlab import Component, CLOSED_BOUNDARY\nimport numpy as np\n\n\n\nclass ExponentialWeatherer(Component):\n \n \"\"\"\n This component implements exponential weathering of bedrock on hillslopes. \n Uses exponential soil production function in the style of Ahnert (1976).\n \n Parameters\n ----------\n grid: ModelGrid\n Landlab ModelGrid object\n wstar: float\n\tcharacteristic weathering depth\n wnot: float\n\tmaximum weathering rate for bare bedrock \n \n \n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab import RasterModelGrid\n >>> from landlab.components import ExponentialWeatherer\n >>> mg = RasterModelGrid((5, 5))\n >>> soilz = mg.add_zeros('node', 'soil__depth')\n >>> soilrate = mg.add_ones('node', 'soil_production__rate')\n >>> expw = ExponentialWeatherer(mg)\n >>> expw.calc_soil_prod_rate()\n >>> np.allclose(mg.at_node['soil_production__rate'], 1.)\n True\n \"\"\"\n\n _name = 'ExponentialWeatherer'\n\n _input_var_names = (\n 'soil__depth',\n )\n \n _output_var_names = (\n 'soil_production__rate',\n )\n \n _var_units = {\n 'soil__depth' : 'm',\n 'soil_production__rate' : 'm/yr',\n }\n \n _var_mapping = {\n 'soil__depth' : 'node',\n 'soil_production__rate' : 'node',\n \n }\n \n _var_doc = {\n 'soil__depth':\n 'depth of soil/weather bedrock',\n 'soil_production__rate':\n 'rate of soil production at nodes',\n\n }\n\n def __init__(self, grid, max_soil_production_rate=1.0,\n soil_production_decay_depth=1.0, **kwds):\n \n #Store grid and parameters\n self._grid = grid\n self.wstar = soil_production_decay_depth\n self.w0 = max_soil_production_rate\n\n # Create fields: \n # soil depth\n if 'soil__depth' in grid.at_node:\n self.depth = grid.at_node['soil__depth']\n else:\n self.depth = grid.add_zeros('node', 'soil__depth')\n\n # weathering rate\n if 'soil_production__rate' in grid.at_node:\n self.soil_prod_rate = grid.at_node['soil_production__rate']\n else:\n self.soil_prod_rate = grid.add_zeros('node',\n 'soil_production__rate')\n\n # Why not just use core nodes?\n self._active_nodes = self.grid.status_at_node != CLOSED_BOUNDARY\n\n \n def calc_soil_prod_rate(self, **kwds):\n \"\"\"Calculate soil production rate.\n \"\"\"\n \n # apply exponential function\n self.soil_prod_rate[self._active_nodes] = (\n self.w0\n * np.exp(-self.depth[self._active_nodes] / self.wstar))\n", "#! /usr/bin/env python\n\"\"\"Grid element mappers that are specific to raster grids.\n\nMapping functions unique to raster grids\n+++++++++++++++++++++++\n\n.. autosummary::\n :toctree: generated/\n\n ~landlab.grid.raster_mappers.map_sum_of_inlinks_to_node\n ~landlab.grid.raster_mappers.map_mean_of_inlinks_to_node\n ~landlab.grid.raster_mappers.map_max_of_inlinks_to_node\n ~landlab.grid.raster_mappers.map_min_of_inlinks_to_node\n ~landlab.grid.raster_mappers.map_sum_of_outlinks_to_node\n ~landlab.grid.raster_mappers.map_mean_of_outlinks_to_node\n ~landlab.grid.raster_mappers.map_max_of_outlinks_to_node\n ~landlab.grid.raster_mappers.map_min_of_outlinks_to_node\n ~landlab.grid.raster_mappers.map_mean_of_links_to_node\n ~landlab.grid.raster_mappers.map_mean_of_horizontal_links_to_node\n ~landlab.grid.raster_mappers.map_mean_of_horizontal_active_links_to_node\n ~landlab.grid.raster_mappers.map_mean_of_vertical_links_to_node\n ~landlab.grid.raster_mappers.map_mean_of_vertical_active_links_to_node\n\n\"\"\"\n\nfrom __future__ import division\n\nimport numpy as np\n\nfrom landlab.grid.structured_quad import links\n\n\ndef map_sum_of_inlinks_to_node(grid, var_name, out=None):\n \"\"\"Map the sum of links entering a node to the node.\n\n map_sum_of_inlinks_to_node takes an array *at the links* and finds the\n inlink values for each node in the grid. it sums the inlinks and returns\n values at the nodes.\n\n .. note::\n\n This considers all inactive links to have a value of 0.\n\n Construction::\n\n map_sum_of_inlinks_to_node(grid, var_name, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_sum_of_inlinks_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_sum_of_inlinks_to_node(rmg, 'z')\n array([ 0., 0., 1., 2., 3., 11., 13., 15., 10., 25., 27.,\n 29.])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n values_at_links = np.append(values_at_links, 0)\n\n south, west = links._node_in_link_ids(grid.shape)\n south, west = south.reshape(south.size), west.reshape(west.size)\n out[:] = values_at_links[south] + values_at_links[west]\n\n return out\n\n\ndef map_mean_of_inlinks_to_node(grid, var_name, out=None):\n \"\"\"Map the mean of links entering a node to the node.\n\n map_mean_of_inlinks_to_node takes an array *at the links* and finds the\n inlink values for each node in the grid. It finds the average of\n the inlinks and returns values at the nodes.\n\n This considers all inactive links to have a value of 0.\n\n Construction::\n\n map_mean_of_inlinks_to_node(grid, var_name, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_mean_of_inlinks_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_mean_of_inlinks_to_node(rmg, 'z')\n array([ 0. , 0. , 0.5, 1. , 1.5, 5.5, 6.5, 7.5, 5. ,\n 12.5, 13.5, 14.5])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n values_at_links = np.append(values_at_links, 0)\n south, west = links._node_in_link_ids(grid.shape)\n south, west = south.reshape(south.size), west.reshape(west.size)\n out[:] = 0.5 * (values_at_links[south] + values_at_links[west])\n\n return out\n\n\ndef map_max_of_inlinks_to_node(grid, var_name, out=None):\n \"\"\"Map the maximum of links entering a node to the node.\n\n map_max_of_inlinks_to_node takes an array *at the links* and finds the\n inlink values for each node in the grid. it finds the maximum value at the\n the inlinks and returns values at the nodes.\n\n .. note::\n\n This considers all inactive links to have a value of 0.\n\n Construction::\n\n map_max_of_inlinks_to_node(grid, var_name, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_max_of_inlinks_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_max_of_inlinks_to_node(rmg, 'z')\n array([ 0., 0., 1., 2.,\n 3., 7., 8., 9.,\n 10., 14., 15., 16.])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n values_at_links = np.append(values_at_links, 0)\n south, west = links._node_in_link_ids(grid.shape)\n south, west = south.reshape(south.size), west.reshape(west.size)\n out[:] = np.maximum(values_at_links[south], values_at_links[west])\n\n return out\n\n\ndef map_min_of_inlinks_to_node(grid, var_name, out=None):\n \"\"\"Map the minimum of links entering a node to the node.\n\n map_min_of_inlinks_to_node takes an array *at the links* and finds the\n inlink values for each node in the grid. it finds the minimum value at the\n the inlinks and returns values at the nodes.\n\n .. note::\n\n This considers all inactive links to have a value of 0.\n\n Construction::\n\n map_min_of_inlinks_to_node(grid, var_name, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_min_of_inlinks_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_min_of_inlinks_to_node(rmg, 'z')\n array([ 0., 0., 0., 0., 0., 4., 5., 6., 0., 11., 12.,\n 13.])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n values_at_links = np.append(values_at_links, 0)\n south, west = links._node_in_link_ids(grid.shape)\n south, west = south.reshape(south.size), west.reshape(west.size)\n out[:] = np.minimum(values_at_links[south], values_at_links[west])\n\n return out\n\n\ndef map_sum_of_outlinks_to_node(grid, var_name, out=None):\n \"\"\"Map the sum of links leaving a node to the node.\n\n map_sum_of_outlinks_to_node takes an array *at the links* and finds the\n outlink values for each node in the grid. it sums the outlinks and returns\n values at the nodes.\n\n .. note::\n\n This considers all inactive links to have a value of 0.\n\n Construction::\n\n map_sum_of_outlinks_to_node(grid, var_name, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_sum_of_outlinks_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_sum_of_outlinks_to_node(rmg, 'z')\n array([ 3., 5., 7., 6., 17., 19., 21., 13., 14., 15., 16.,\n 0.])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n values_at_links = np.append(values_at_links, 0)\n north, east = links._node_out_link_ids(grid.shape)\n north, east = north.reshape(north.size), east.reshape(east.size)\n out[:] = values_at_links[north] + values_at_links[east]\n\n return out\n\n\ndef map_mean_of_outlinks_to_node(grid, var_name, out=None):\n \"\"\"Map the mean of links leaving a node to the node.\n\n map_mean_of_outlinks_to_node takes an array *at the links* and finds the\n outlink values for each node in the grid. it finds the average of\n the outlinks and returns values at the nodes.\n\n .. note::\n\n This considers all inactive links to have a value of 0.\n\n Construction::\n\n map_mean_of_outlinks_to_node(grid, var_name, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_mean_of_outlinks_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_mean_of_outlinks_to_node(rmg, 'z')\n array([ 1.5, 2.5, 3.5, 3. , 8.5, 9.5, 10.5, 6.5, 7. ,\n 7.5, 8. , 0. ])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n values_at_links = np.append(values_at_links, 0)\n north, east = links._node_out_link_ids(grid.shape)\n north, east = north.reshape(north.size), east.reshape(east.size)\n out[:] = 0.5 * (values_at_links[north] + values_at_links[east])\n\n return out\n\n\ndef map_max_of_outlinks_to_node(grid, var_name, out=None):\n \"\"\"Map the max of links leaving a node to the node.\n\n map_max_of_outlinks_to_node takes an array *at the links* and finds the\n outlink values for each node in the grid. it finds the maximum value at the\n the outlinks and returns values at the nodes.\n\n .. note::\n\n This considers all inactive links to have a value of 0.\n\n Construction::\n\n map_max_of_outlinks_to_node(grid, var_name, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_max_of_outlinks_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_max_of_outlinks_to_node(rmg, 'z')\n array([ 3., 4., 5., 6., 10., 11., 12., 13., 14., 15., 16.,\n 0.])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n values_at_links = np.append(values_at_links, 0)\n north, east = links._node_out_link_ids(grid.shape)\n north, east = north.reshape(north.size), east.reshape(east.size)\n np.maximum(values_at_links[north], values_at_links[east], out=out)\n\n return out\n\n\ndef map_min_of_outlinks_to_node(grid, var_name, out=None):\n \"\"\"Map the min of links leaving a node to the node.\n\n map_min_of_outlinks_to_node takes an array *at the links* and finds the\n outlink values for each node in the grid. It finds the minimum value at the\n the outlinks and returns values at the nodes.\n\n .. note::\n\n This considers all inactive links to have a value of 0.\n\n Construction::\n\n map_min_of_outlinks_to_node(grid, var_name, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_min_of_outlinks_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_min_of_outlinks_to_node(rmg, 'z')\n array([ 0., 1., 2., 0., 7., 8., 9., 0., 0., 0., 0., 0.])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n values_at_links = np.append(values_at_links, 0)\n north, east = links._node_out_link_ids(grid.shape)\n north, east = north.reshape(north.size), east.reshape(east.size)\n np.minimum(values_at_links[north], values_at_links[east], out=out)\n\n return out\n\n\ndef map_mean_of_links_to_node(grid, var_name, out=None):\n \"\"\"Map the mean of links touching a node to the node.\n\n map_mean_all_links_to_node takes an array *at the links* and finds the\n average of all ~existing~ link neighbor values for each node in the grid.\n it returns values at the nodes.\n\n .. note::\n\n This considers all inactive links to have a value of 0.\n\n Construction::\n\n map_mean_of_links_to_node(grid, var_name, out=None)\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_mean_of_links_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_mean_of_links_to_node(rmg, 'z')\n array([ 1.5 , 1.66666667, 2.66666667, 4. ,\n 6.66666667, 7.5 , 8.5 , 9.33333333,\n 12. , 13.33333333, 14.33333333, 14.5 ])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n values_at_links = np.append(values_at_links, 0)\n\n north, east = links._node_out_link_ids(grid.shape)\n north, east = north.reshape(north.size), east.reshape(east.size)\n south, west = links._node_in_link_ids(grid.shape)\n south, west = south.reshape(south.size), west.reshape(west.size)\n\n number_of_links = links.number_of_links_per_node(grid.shape)\n number_of_links = number_of_links.reshape(number_of_links.size)\n number_of_links.astype(float, copy=False)\n out[:] = (values_at_links[north] + values_at_links[east] +\n values_at_links[south] + values_at_links[west]) / number_of_links\n\n return out\n\n\ndef map_mean_of_horizontal_links_to_node(grid, var_name, out=None):\n \"\"\"\n Map the mean of links in the x direction touching a node to the node.\n\n map_mean_of_horizontal_links_to_node takes an array *at the links* and\n finds the average of all horizontal (x-direction) link neighbor values\n for each node in the grid.\n It returns an array at the nodes of the mean of these values. If a link\n is absent, it is ignored.\n Note that here a positive returned value means flux to the east, and\n a negative to the west.\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_mean_of_horizontal_links_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_mean_of_horizontal_links_to_node(rmg, 'z')\n array([ 0. , 0.5, 1.5, 2. , 7. , 7.5, 8.5, 9. , 14. ,\n 14.5, 15.5, 16. ])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n hoz_links = grid.links_at_node[:, [0, 2]]\n hoz_link_dirs = np.fabs(grid.link_dirs_at_node[:, [0, 2]])\n # ^retain \"true\" directions of links\n valid_links = values_at_links[hoz_links]*hoz_link_dirs # invalids = 0\n num_valid_links = hoz_link_dirs.sum(axis=1)\n np.divide(valid_links.sum(axis=1), num_valid_links, out=out)\n return out\n\n\ndef map_mean_of_horizontal_active_links_to_node(grid, var_name, out=None):\n \"\"\"\n Map the mean of active links in the x direction touching node to the node.\n\n map_mean_of_horizontal_active_links_to_node takes an array *at the links*\n and finds the average of all horizontal (x-direction) link neighbor values\n for each node in the grid.\n It returns an array at the nodes of the mean of these values. If a link\n is absent, it is ignored. If a node has no active links, it receives 0.\n Note that here a positive returned value means flux to the east, and\n a negative to the west.\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_mean_of_horizontal_active_links_to_node\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', -np.arange(17, dtype=float))\n >>> rmg.status_at_node[rmg.nodes_at_left_edge] = CLOSED_BOUNDARY\n >>> map_mean_of_horizontal_active_links_to_node(rmg, 'z')\n array([ 0. , 0. , 0. , 0. , 0. , -8. , -8.5, -9. , 0. , 0. , 0. ,\n 0. ])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.zeros(centering='node', dtype=float)\n else:\n out.fill(0.)\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n hoz_links = grid.links_at_node[:, [0, 2]]\n hoz_link_dirs = np.fabs(grid.active_link_dirs_at_node[:, [0, 2]])\n # ^retain \"true\" directions of links; no inactives now\n valid_links = values_at_links[hoz_links]*hoz_link_dirs # invalids = 0\n num_valid_links = hoz_link_dirs.sum(axis=1)\n good_nodes = num_valid_links != 0\n out[good_nodes] = (valid_links.sum(axis=1)[good_nodes] /\n num_valid_links[good_nodes])\n return out\n\n\ndef map_mean_of_vertical_links_to_node(grid, var_name, out=None):\n \"\"\"\n Map the mean of links in the y direction touching a node to the node.\n\n map_mean_of_vertical_links_to_node takes an array *at the links* and\n finds the average of all vertical (y-direction) link neighbor values\n for each node in the grid.\n It returns an array at the nodes of the mean of these values. If a link\n is absent, it is ignored.\n Note that here a positive returned value means flux to the north, and\n a negative to the south.\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_mean_of_vertical_links_to_node\n >>> from landlab import RasterModelGrid\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', np.arange(17.))\n >>> map_mean_of_vertical_links_to_node(rmg, 'z')\n array([ 3. , 4. , 5. , 6. , 6.5, 7.5, 8.5, 9.5, 10. ,\n 11. , 12. , 13. ])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.empty(centering='node')\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n vert_links = grid.links_at_node[:, [1, 3]]\n vert_link_dirs = np.fabs(grid.link_dirs_at_node[:, [1, 3]])\n # ^retain \"true\" directions of links\n valid_links = values_at_links[vert_links]*vert_link_dirs # invalids = 0\n num_valid_links = vert_link_dirs.sum(axis=1)\n np.divide(valid_links.sum(axis=1), num_valid_links, out=out)\n return out\n\n\ndef map_mean_of_vertical_active_links_to_node(grid, var_name, out=None):\n \"\"\"\n Map the mean of active links in the y direction touching node to the node.\n\n map_mean_of_vertical_active_links_to_node takes an array *at the links*\n and finds the average of all vertical (y-direction) link neighbor values\n for each node in the grid.\n It returns an array at the nodes of the mean of these values. If a link\n is absent, it is ignored. If a node has no active links, it receives 0.\n Note that here a positive returned value means flux to the north, and\n a negative to the south.\n\n Parameters\n ----------\n grid : ModelGrid\n A landlab ModelGrid.\n var_name : array or field name\n Values defined at links.\n out : ndarray, optional\n Buffer to place mapped values into or `None` to create a new array.\n\n Returns\n -------\n ndarray\n Mapped values at nodes.\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.raster_mappers import map_mean_of_vertical_active_links_to_node\n >>> from landlab import RasterModelGrid, CLOSED_BOUNDARY\n\n >>> rmg = RasterModelGrid((3, 4))\n >>> _ = rmg.add_field('link', 'z', -np.arange(17, dtype=float))\n >>> rmg.status_at_node[rmg.nodes_at_bottom_edge] = CLOSED_BOUNDARY\n >>> map_mean_of_vertical_active_links_to_node(rmg, 'z')\n array([ 0., 0., 0., 0., 0., -11., -12., 0., 0., -11., -12.,\n 0.])\n\n LLCATS: NINF LINF MAP\n \"\"\"\n if out is None:\n out = grid.zeros(centering='node', dtype=float)\n else:\n out.fill(0.)\n\n if type(var_name) is str:\n values_at_links = grid.at_link[var_name]\n else:\n values_at_links = var_name\n vert_links = grid.links_at_node[:, [1, 3]]\n vert_link_dirs = np.fabs(grid.active_link_dirs_at_node[:, [1, 3]])\n # ^retain \"true\" directions of links; no inactives now\n valid_links = values_at_links[vert_links]*vert_link_dirs # invalids = 0\n num_valid_links = vert_link_dirs.sum(axis=1)\n good_nodes = num_valid_links != 0\n out[good_nodes] = (valid_links.sum(axis=1)[good_nodes] /\n num_valid_links[good_nodes])\n return out\n" ]
[ [ "numpy.concatenate", "numpy.logical_or", "numpy.array", "numpy.zeros" ], [ "numpy.zeros" ], [ "numpy.exp" ], [ "numpy.append", "numpy.maximum", "numpy.minimum", "numpy.fabs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
danvolk/LineHTR
[ "a3a97e4af69ca9d15379868fafddb80c781831aa" ]
[ "src/DataLoader.py" ]
[ "from __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport random\n\nimport cv2\nimport numpy as np\n\nfrom helpers import preprocessor\n\n\nclass FilePaths:\n \"\"\" Filenames and paths to data \"\"\"\n fnCharList = '../model/charList.txt'\n fnWordCharList = '../model/wordCharList.txt'\n fnCorpus = '../data/corpus.txt'\n fnAccuracy = '../model/accuracy.txt'\n fnTrain = '../data/train/'\n fnInfer = '../data/test/'\n\n\nclass Sample:\n \"\"\" Sample from the dataset \"\"\"\n\n def __init__(self, gtText, filePath):\n self.gtText = gtText\n self.filePath = filePath\n\n\nclass Batch:\n \"\"\" Batch containing images and ground truth texts \"\"\"\n\n def __init__(self, gtTexts, imgs):\n self.imgs = np.stack(imgs, axis=0)\n self.gtTexts = gtTexts\n\n\nclass DataLoader:\n \"\"\" Loads data from data folder \"\"\"\n\n def __init__(self, filePath, batchSize, imgSize, maxTextLen):\n \"\"\" Loader for dataset at given location, preprocess images and text according to parameters \"\"\"\n\n assert filePath[-1] == '/'\n\n self.currIdx = 0\n self.batchSize = batchSize\n self.imgSize = imgSize\n self.samples = []\n\n # Read json lables file\n # Dataset folder should contain a labels.json file inside, with key is the file name of images and value is the label\n with open(filePath + 'labels.json') as json_data:\n label_file = json.load(json_data)\n\n # Log\n print(\"Loaded\", len(label_file), \"images\")\n\n # Put sample into list\n for fileName, gtText in label_file.items():\n self.samples.append(Sample(gtText, filePath + fileName))\n\n self.charList = list(open(FilePaths.fnCharList).read())\n\n # Split into training and validation set: 90% - 10%\n splitIdx = int(0.9 * len(self.samples))\n self.trainSamples = self.samples[:splitIdx]\n self.validationSamples = self.samples[splitIdx:]\n\n print(\"Train on\", len(self.trainSamples), \"images. Validate on\",\n len(self.validationSamples), \"images.\")\n\n # Number of randomly chosen samples per epoch for training\n self.numTrainSamplesPerEpoch = 10000 # ZYU NOTE: original is 5500\n\n # Start with train set\n self.trainSet()\n\n # List of all chars in dataset\n #self.charList = sorted(list(chars))\n\n def trainSet(self):\n \"\"\" Switch to randomly chosen subset of training set \"\"\"\n self.currIdx = 0\n random.shuffle(self.trainSamples)\n self.samples = self.trainSamples[:self.numTrainSamplesPerEpoch]\n\n def validationSet(self):\n \"\"\" Switch to validation set \"\"\"\n self.currIdx = 0\n self.samples = self.validationSamples\n\n def getIteratorInfo(self):\n \"\"\" Current batch index and overall number of batches \"\"\"\n return (self.currIdx // self.batchSize + 1, len(self.samples) // self.batchSize)\n\n def hasNext(self):\n \"\"\" Iterator \"\"\"\n return self.currIdx + self.batchSize <= len(self.samples)\n\n def getNext(self):\n \"\"\" Iterator \"\"\"\n batchRange = range(self.currIdx, self.currIdx + self.batchSize)\n gtTexts = [self.samples[i].gtText for i in batchRange]\n imgs = [preprocessor(self.samples[i].filePath,\n self.imgSize, binary=True) for i in batchRange]\n self.currIdx += self.batchSize\n return Batch(gtTexts, imgs)\n" ]
[ [ "numpy.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JetRunner/transformers
[ "8e0cf02467bce017885cd3dc1f37c84794dd7da4" ]
[ "src/transformers/modeling_flaubert.py" ]
[ "# coding=utf-8\n# Copyright 2019-present CNRS, Facebook Inc. and the HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\" PyTorch Flaubert model, based on XLM. \"\"\"\n\n\nimport logging\nimport random\n\nimport torch\nfrom torch.nn import functional as F\n\nfrom .configuration_flaubert import FlaubertConfig\nfrom .file_utils import add_start_docstrings, add_start_docstrings_to_callable\nfrom .modeling_xlm import (\n XLMForQuestionAnswering,\n XLMForQuestionAnsweringSimple,\n XLMForSequenceClassification,\n XLMModel,\n XLMWithLMHeadModel,\n get_masks,\n)\n\n\nlogger = logging.getLogger(__name__)\n\nFLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"flaubert/flaubert_small_cased\",\n \"flaubert/flaubert_base_uncased\",\n \"flaubert/flaubert_base_cased\",\n \"flaubert/flaubert_large_cased\",\n # See all Flaubert models at https://huggingface.co/models?filter=flaubert\n]\n\n\nFLAUBERT_START_DOCSTRING = r\"\"\"\n\n This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`_ sub-class.\n Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general\n usage and behavior.\n\n Parameters:\n config (:class:`~transformers.FlaubertConfig`): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the configuration.\n Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.\n\"\"\"\n\nFLAUBERT_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using :class:`transformers.BertTokenizer`.\n See :func:`transformers.PreTrainedTokenizer.encode` and\n :func:`transformers.PreTrainedTokenizer.encode_plus` for details.\n\n `What are input IDs? <../glossary.html#input-ids>`__\n attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n\n `What are attention masks? <../glossary.html#attention-mask>`__\n token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Segment token indices to indicate first and second portions of the inputs.\n Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``\n corresponds to a `sentence B` token\n\n `What are token type IDs? <../glossary.html#token-type-ids>`_\n position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Indices of positions of each input sequence tokens in the position embeddings.\n Selected in the range ``[0, config.max_position_embeddings - 1]``.\n\n `What are position IDs? <../glossary.html#position-ids>`_\n lengths (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):\n Length of each sentence that can be used to avoid performing attention on padding token indices.\n You can also use `attention_mask` for the same result (see above), kept here for compatbility.\n Indices selected in ``[0, ..., input_ids.size(-1)]``:\n cache (:obj:`Dict[str, torch.FloatTensor]`, `optional`, defaults to :obj:`None`):\n dictionary with ``torch.FloatTensor`` that contains pre-computed\n hidden-states (key and values in the attention blocks) as computed by the model\n (see `cache` output below). Can be used to speed up sequential decoding.\n The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.\n head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`):\n Mask to nullify selected heads of the self-attention modules.\n Mask values selected in ``[0, 1]``:\n :obj:`1` indicates the head is **not masked**, :obj:`0` indicates the head is **masked**.\n inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):\n Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.\n This is useful if you want more control over how to convert `input_ids` indices into associated vectors\n than the model's internal embedding lookup matrix.\n output_attentions (:obj:`bool`, `optional`, defaults to :obj:`None`):\n If set to ``True``, the attentions tensors of all attention layers are returned. See ``attentions`` under returned tensors for more detail.\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare Flaubert Model transformer outputting raw hidden-states without any specific head on top.\",\n FLAUBERT_START_DOCSTRING,\n)\nclass FlaubertModel(XLMModel):\n\n config_class = FlaubertConfig\n\n def __init__(self, config): # , dico, is_encoder, with_output):\n super().__init__(config)\n self.layerdrop = getattr(config, \"layerdrop\", 0.0)\n self.pre_norm = getattr(config, \"pre_norm\", False)\n\n @add_start_docstrings_to_callable(FLAUBERT_INPUTS_DOCSTRING)\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n langs=None,\n token_type_ids=None,\n position_ids=None,\n lengths=None,\n cache=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n ):\n r\"\"\"\n Return:\n :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.XLMConfig`) and inputs:\n last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):\n Sequence of hidden-states at the output of the last layer of the model.\n hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):\n Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape :obj:`(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or ``config.output_attentions=True``):\n Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape\n :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n\n Examples::\n\n from transformers import FlaubertTokenizer, FlaubertModel\n import torch\n\n tokenizer = FlaubertTokenizer.from_pretrained('flaubert-base-cased')\n model = FlaubertModel.from_pretrained('flaubert-base-cased')\n input_ids = torch.tensor(tokenizer.encode(\"Le chat mange une pomme.\", add_special_tokens=True)).unsqueeze(0) # Batch size 1\n outputs = model(input_ids)\n last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple\n\n \"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n\n # removed: src_enc=None, src_len=None\n if input_ids is not None:\n bs, slen = input_ids.size()\n else:\n bs, slen = inputs_embeds.size()[:-1]\n\n if lengths is None:\n if input_ids is not None:\n lengths = (input_ids != self.pad_index).sum(dim=1).long()\n else:\n lengths = torch.LongTensor([slen] * bs)\n # mask = input_ids != self.pad_index\n\n # check inputs\n assert lengths.size(0) == bs\n assert lengths.max().item() <= slen\n # input_ids = input_ids.transpose(0, 1) # batch size as dimension 0\n # assert (src_enc is None) == (src_len is None)\n # if src_enc is not None:\n # assert self.is_decoder\n # assert src_enc.size(0) == bs\n\n # generate masks\n mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)\n # if self.is_decoder and src_enc is not None:\n # src_mask = torch.arange(src_len.max(), dtype=torch.long, device=lengths.device) < src_len[:, None]\n\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n # position_ids\n if position_ids is None:\n position_ids = torch.arange(slen, dtype=torch.long, device=device)\n position_ids = position_ids.unsqueeze(0).expand((bs, slen))\n else:\n assert position_ids.size() == (bs, slen) # (slen, bs)\n # position_ids = position_ids.transpose(0, 1)\n\n # langs\n if langs is not None:\n assert langs.size() == (bs, slen) # (slen, bs)\n # langs = langs.transpose(0, 1)\n\n # Prepare head mask if needed\n head_mask = self.get_head_mask(head_mask, self.config.n_layers)\n\n # do not recompute cached elements\n if cache is not None and input_ids is not None:\n _slen = slen - cache[\"slen\"]\n input_ids = input_ids[:, -_slen:]\n position_ids = position_ids[:, -_slen:]\n if langs is not None:\n langs = langs[:, -_slen:]\n mask = mask[:, -_slen:]\n attn_mask = attn_mask[:, -_slen:]\n\n # embeddings\n if inputs_embeds is None:\n inputs_embeds = self.embeddings(input_ids)\n\n tensor = inputs_embeds + self.position_embeddings(position_ids).expand_as(inputs_embeds)\n if langs is not None and self.use_lang_emb and self.config.n_langs > 1:\n tensor = tensor + self.lang_embeddings(langs)\n if token_type_ids is not None:\n tensor = tensor + self.embeddings(token_type_ids)\n tensor = self.layer_norm_emb(tensor)\n tensor = F.dropout(tensor, p=self.dropout, training=self.training)\n tensor *= mask.unsqueeze(-1).to(tensor.dtype)\n\n # transformer layers\n hidden_states = ()\n attentions = ()\n for i in range(self.n_layers):\n # LayerDrop\n dropout_probability = random.uniform(0, 1)\n if self.training and (dropout_probability < self.layerdrop):\n continue\n\n if self.output_hidden_states:\n hidden_states = hidden_states + (tensor,)\n\n # self attention\n if not self.pre_norm:\n attn_outputs = self.attentions[i](\n tensor, attn_mask, cache=cache, head_mask=head_mask[i], output_attentions=output_attentions,\n )\n attn = attn_outputs[0]\n if output_attentions:\n attentions = attentions + (attn_outputs[1],)\n attn = F.dropout(attn, p=self.dropout, training=self.training)\n tensor = tensor + attn\n tensor = self.layer_norm1[i](tensor)\n else:\n tensor_normalized = self.layer_norm1[i](tensor)\n attn_outputs = self.attentions[i](tensor_normalized, attn_mask, cache=cache, head_mask=head_mask[i])\n attn = attn_outputs[0]\n if output_attentions:\n attentions = attentions + (attn_outputs[1],)\n attn = F.dropout(attn, p=self.dropout, training=self.training)\n tensor = tensor + attn\n\n # encoder attention (for decoder only)\n # if self.is_decoder and src_enc is not None:\n # attn = self.encoder_attn[i](tensor, src_mask, kv=src_enc, cache=cache)\n # attn = F.dropout(attn, p=self.dropout, training=self.training)\n # tensor = tensor + attn\n # tensor = self.layer_norm15[i](tensor)\n\n # FFN\n if not self.pre_norm:\n tensor = tensor + self.ffns[i](tensor)\n tensor = self.layer_norm2[i](tensor)\n else:\n tensor_normalized = self.layer_norm2[i](tensor)\n tensor = tensor + self.ffns[i](tensor_normalized)\n\n tensor *= mask.unsqueeze(-1).to(tensor.dtype)\n\n # Add last hidden state\n if self.output_hidden_states:\n hidden_states = hidden_states + (tensor,)\n\n # update cache length\n if cache is not None:\n cache[\"slen\"] += tensor.size(1)\n\n # move back sequence length to dimension 0\n # tensor = tensor.transpose(0, 1)\n\n outputs = (tensor,)\n if self.output_hidden_states:\n outputs = outputs + (hidden_states,)\n if output_attentions:\n outputs = outputs + (attentions,)\n return outputs # outputs, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\n \"\"\"The Flaubert Model transformer with a language modeling head on top\n (linear layer with weights tied to the input embeddings). \"\"\",\n FLAUBERT_START_DOCSTRING,\n)\nclass FlaubertWithLMHeadModel(XLMWithLMHeadModel):\n \"\"\"\n This class overrides :class:`~transformers.XLMWithLMHeadModel`. Please check the\n superclass for the appropriate documentation alongside usage examples.\n \"\"\"\n\n config_class = FlaubertConfig\n\n def __init__(self, config):\n super().__init__(config)\n self.transformer = FlaubertModel(config)\n self.init_weights()\n\n\n@add_start_docstrings(\n \"\"\"Flaubert Model with a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. \"\"\",\n FLAUBERT_START_DOCSTRING,\n)\nclass FlaubertForSequenceClassification(XLMForSequenceClassification):\n \"\"\"\n This class overrides :class:`~transformers.XLMForSequenceClassification`. Please check the\n superclass for the appropriate documentation alongside usage examples.\n \"\"\"\n\n config_class = FlaubertConfig\n\n def __init__(self, config):\n super().__init__(config)\n self.transformer = FlaubertModel(config)\n self.init_weights()\n\n\n@add_start_docstrings(\n \"\"\"Flaubert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of\n the hidden-states output to compute `span start logits` and `span end logits`). \"\"\",\n FLAUBERT_START_DOCSTRING,\n)\nclass FlaubertForQuestionAnsweringSimple(XLMForQuestionAnsweringSimple):\n \"\"\"\n This class overrides :class:`~transformers.XLMForQuestionAnsweringSimple`. Please check the\n superclass for the appropriate documentation alongside usage examples.\n \"\"\"\n\n config_class = FlaubertConfig\n\n def __init__(self, config):\n super().__init__(config)\n self.transformer = FlaubertModel(config)\n self.init_weights()\n\n\n@add_start_docstrings(\n \"\"\"Flaubert Model with a beam-search span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of\n the hidden-states output to compute `span start logits` and `span end logits`). \"\"\",\n FLAUBERT_START_DOCSTRING,\n)\nclass FlaubertForQuestionAnswering(XLMForQuestionAnswering):\n \"\"\"\n This class overrides :class:`~transformers.XLMForQuestionAnswering`. Please check the\n superclass for the appropriate documentation alongside usage examples.\n \"\"\"\n\n config_class = FlaubertConfig\n\n def __init__(self, config):\n super().__init__(config)\n self.transformer = FlaubertModel(config)\n self.init_weights()\n" ]
[ [ "torch.LongTensor", "torch.arange", "torch.nn.functional.dropout" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vitobellini/tfautorec
[ "5501e37f428416dcd59352722949662f38f60a61" ]
[ "autorec-gpus.py" ]
[ "import random\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\nimport re\nimport time\n\nfrom sklearn import preprocessing\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_integer('num_gpus', 4, \"How many GPUs to use.\")\n\nk = 10\n\nepochs = 10000\ndisplay_step = 10\n\nlearning_rate = 0.03\n\nbatch_size = 250\n\ntrain_data = \"./train-1m.tsv\"\ntest_data = \"./test-1m.tsv\"\n\n\ndef inference(x):\n num_hidden_1 = 10 # 1st layer num features\n num_hidden_2 = 5 # 2nd layer num features (the latent dim)\n\n initializer = tf.random_normal_initializer\n\n encoder_h1 = tf.get_variable('encoder_h1', [num_input, num_hidden_1], initializer=initializer,\n dtype=tf.float64)\n\n encoder_h2 = tf.get_variable('encoder_h2', [num_hidden_1, num_hidden_2], initializer=initializer,\n dtype=tf.float64)\n\n decoder_h1 = tf.get_variable('decoder_h1', [num_hidden_2, num_hidden_1], initializer=initializer,\n dtype=tf.float64)\n\n decoder_h2 = tf.get_variable('decoder_h2', [num_hidden_1, num_input], initializer=initializer,\n dtype=tf.float64)\n\n encoder_b1 = tf.get_variable('encoder_b1', [num_hidden_1], initializer=initializer, dtype=tf.float64)\n encoder_b2 = tf.get_variable('encoder_b2', [num_hidden_2], initializer=initializer, dtype=tf.float64)\n decoder_b1 = tf.get_variable('decoder_b1', [num_hidden_1], initializer=initializer, dtype=tf.float64)\n decoder_b2 = tf.get_variable('decoder_b2', [num_input], initializer=initializer, dtype=tf.float64)\n\n def encoder(x_encoder):\n # Encoder Hidden layer with sigmoid activation #1\n layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x_encoder, encoder_h1), encoder_b1))\n\n # Encoder Hidden layer with sigmoid activation #2\n layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, encoder_h2), encoder_b2))\n\n return layer_2\n\n # Building the decoder\n\n def decoder(x_decoder):\n # Decoder Hidden layer with sigmoid activation #1\n layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x_decoder, decoder_h1), decoder_b1))\n\n # Decoder Hidden layer with sigmoid activation #2\n layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, decoder_h2), decoder_b2))\n\n return layer_2\n\n # Construct model\n\n encoder_op = encoder(x)\n decoder_op = decoder(encoder_op)\n\n return decoder_op\n\n\ndef model_loss(y_hat, y):\n # Calculate the average loss across the batch.\n\n mse = tf.losses.mean_squared_error(y, y_hat)\n mean = tf.reduce_mean(mse, name='mse')\n\n tf.add_to_collection('losses', mean)\n\n return tf.add_n(tf.get_collection('losses'), name='total_loss')\n\n\ndef tower_loss(scope, inputs, y):\n \"\"\"Calculate the total loss on a single tower running the model.\n Args:\n scope: unique prefix string identifying the tower, e.g. 'tower_0'\n inputs: 4D tensor of shape [batch_size, users, items].\n y: Labels. 4D tensor of shape [batch_size, users, items].\n Returns:\n Tensor of shape [] containing the total loss for a batch of data\n \"\"\"\n\n # Build inference Graph.\n y_hat = inference(inputs)\n\n # Build the portion of the Graph calculating the losses. Note that we will\n # assemble the total_loss using a custom function below.\n _ = model_loss(y_hat, y)\n\n # Assemble all of the losses for the current tower only.\n losses = tf.get_collection('losses', scope)\n\n # Calculate the total loss for the current tower.\n total_loss = tf.add_n(losses, name='total_loss')\n\n # Attach a scalar summary to all individual losses and the total loss; do the\n # same for the averaged version of the losses.\n for l in losses + [total_loss]:\n # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training\n # session. This helps the clarity of presentation on tensorboard.\n loss_name = re.sub('%s_[0-9]*/' % \"tower\", '', l.op.name)\n tf.summary.scalar(loss_name, l)\n\n return total_loss\n\n\ndef average_gradients(tower_grads):\n \"\"\"Calculate the average gradient for each shared variable across all towers.\n Note that this function provides a synchronization point across all towers.\n Args:\n tower_grads: List of lists of (gradient, variable) tuples. The outer list\n is over individual gradients. The inner list is over the gradient\n calculation for each tower.\n Returns:\n List of pairs of (gradient, variable) where the gradient has been averaged\n across all towers.\n \"\"\"\n average_grads = []\n for grad_and_vars in zip(*tower_grads):\n # Note that each grad_and_vars looks like the following:\n # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))\n grads = []\n for g, _ in grad_and_vars:\n # Add 0 dimension to the gradients to represent the tower.\n expanded_g = tf.expand_dims(g, 0)\n\n # Append on a 'tower' dimension which we will average over below.\n grads.append(expanded_g)\n\n # Average over the 'tower' dimension.\n grad = tf.concat(axis=0, values=grads)\n grad = tf.reduce_mean(grad, 0)\n\n # Keep in mind that the Variables are redundant because they are shared\n # across towers. So .. we will just return the first tower's pointer to\n # the Variable.\n v = grad_and_vars[0][1]\n grad_and_var = (grad, v)\n average_grads.append(grad_and_var)\n return average_grads\n\n\n# Reading dataset\n\ndf = pd.read_csv(train_data, sep='\\t', names=['user', 'item', 'rating', 'timestamp'], header=None)\ndf = df.drop('timestamp', axis=1)\n\nnum_items = df.item.nunique()\nnum_users = df.user.nunique()\n\nprint(\"USERS: {} ITEMS: {}\".format(num_users, num_items))\n\n\n# Normalize in [0, 1]\n\nr = df['rating'].values.astype(float)\nmin_max_scaler = preprocessing.MinMaxScaler()\nx_scaled = min_max_scaler.fit_transform(r.reshape(-1, 1))\ndf_normalized = pd.DataFrame(x_scaled)\ndf['rating'] = df_normalized\n\n\n# Convert DataFrame in user-item matrix\n\nmatrix = df.pivot(index='user', columns='item', values='rating')\nmatrix.fillna(0, inplace=True)\n\n\n# Users and items ordered as they are in matrix\n\nusers = matrix.index.tolist()\nitems = matrix.columns.tolist()\n\nmatrix = matrix.as_matrix()\n\nprint(\"Matrix shape: {}\".format(matrix.shape))\n\n# Network Parameters\n\nnum_input = num_items # num of items\n\nX = tf.placeholder(tf.float64, [None, num_input])\n\n# Targets are the input data.\n\ny_true = X\n\n\n# Define loss and optimizer, minimize the squared error\n\noptimizer = tf.train.RMSPropOptimizer(learning_rate)\n\npredictions = pd.DataFrame()\n\n# Define evaluation metrics\n\neval_x = tf.placeholder(tf.int32, )\neval_y = tf.placeholder(tf.int32, )\npre, pre_op = tf.metrics.precision(labels=eval_x, predictions=eval_y)\n\nwith tf.device(\"/cpu:0\"):\n global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False)\n\n num_batches = int(matrix.shape[0] / batch_size)\n\n matrix = np.array_split(matrix, num_batches)\n\n current_batch = 0\n\n # Calculate the gradients for each model tower\n tower_grads = []\n reuseVariables = False\n for j in range(0, len(matrix), FLAGS.num_gpus):\n with tf.variable_scope(tf.get_variable_scope(), reuse=reuseVariables):\n r = list(range(FLAGS.num_gpus))\n random.shuffle(r)\n for i in r:\n with tf.device('/gpu:%d' % i):\n with tf.name_scope('%s_%d' % (\"tower\", i)) as scope:\n # Dequeues one batch for the GPU\n loss = tower_loss(scope, matrix[current_batch], matrix[current_batch])\n\n # Reuse variables for the next tower.\n tf.get_variable_scope().reuse_variables()\n\n # Calculate the gradients for the batch of data on this tower.\n grads = optimizer.compute_gradients(loss)\n\n # Keep track of the gradients across all towers.\n tower_grads.append(grads)\n\n current_batch = j + i\n reuseVariables = True\n\n # We must calculate the mean of each gradient. Note that this is the\n # synchronization point across all towers.\n grads = average_gradients(tower_grads)\n\n # Apply the gradients to adjust the shared variables.\n apply_gradient_op = optimizer.apply_gradients(grads, global_step=global_step)\n\n # Group all updates to into a single train op.\n train_op = tf.group(apply_gradient_op) #variables_averages_op\n\n # Initialize the variables (i.e. assign their default value)\n init = tf.global_variables_initializer()\n local_init = tf.local_variables_initializer()\n\n config = tf.ConfigProto(allow_soft_placement=True)\n with tf.Session(config=config) as session:\n session.run(init)\n session.run(local_init)\n\n tf.train.start_queue_runners(sess=session)\n\n start = time.time()\n\n for i in range(epochs):\n avg_cost = 0\n\n _, l = session.run([train_op, loss])\n avg_cost += l\n\n print(\"Epoch: {} Loss: {}\".format(i + 1, avg_cost))\n\n print(time.time()-start)\n\n print(\"Predictions...\")\n\n matrix = np.concatenate(matrix, axis=0)\n\n with tf.variable_scope(tf.get_variable_scope(), reuse=True):\n preds = session.run(inference(X), feed_dict={X: matrix})\n\n predictions = predictions.append(pd.DataFrame(preds))\n\n predictions = predictions.stack().reset_index(name='rating')\n predictions.columns = ['user', 'item', 'rating']\n predictions['user'] = predictions['user'].map(lambda value: users[value])\n predictions['item'] = predictions['item'].map(lambda value: items[value])\n\n print(\"Filtering out items in training set\")\n\n keys = ['user', 'item']\n i1 = predictions.set_index(keys).index\n i2 = df.set_index(keys).index\n\n recs = predictions[~i1.isin(i2)]\n recs = recs.sort_values(['user', 'rating'], ascending=[True, False])\n recs = recs.groupby('user').head(k)\n recs.to_csv('recs.tsv', sep='\\t', index=False, header=False)\n\n" ]
[ [ "tensorflow.get_variable", "tensorflow.device", "tensorflow.concat", "pandas.DataFrame", "numpy.concatenate", "tensorflow.group", "tensorflow.add_n", "tensorflow.summary.scalar", "sklearn.preprocessing.MinMaxScaler", "pandas.read_csv", "tensorflow.get_collection", "tensorflow.metrics.precision", "tensorflow.app.flags.DEFINE_integer", "tensorflow.ConfigProto", "tensorflow.name_scope", "tensorflow.Session", "tensorflow.matmul", "tensorflow.train.RMSPropOptimizer", "tensorflow.placeholder", "tensorflow.get_variable_scope", "tensorflow.global_variables_initializer", "tensorflow.add_to_collection", "tensorflow.losses.mean_squared_error", "tensorflow.local_variables_initializer", "tensorflow.reduce_mean", "tensorflow.train.start_queue_runners", "tensorflow.expand_dims", "tensorflow.constant_initializer", "numpy.array_split" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
navashiva/alphafold
[ "be37a41d6f83e4145bd4912cbe8bf6a24af80c29" ]
[ "alphafold/relax/relax.py" ]
[ "# Copyright 2021 DeepMind Technologies Limited\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\"\"\"Amber relaxation.\"\"\"\nfrom typing import Any, Dict, Sequence, Tuple\nfrom alphafold.common import protein\nfrom alphafold.relax import amber_minimize\nfrom alphafold.relax import utils\nimport numpy as np\n\n\nclass AmberRelaxation(object):\n \"\"\"Amber relaxation.\"\"\"\n\n def __init__(self,\n *,\n max_iterations: int,\n tolerance: float,\n stiffness: float,\n exclude_residues: Sequence[int],\n max_outer_iterations: int):\n \"\"\"Initialize Amber Relaxer.\n\n Args:\n max_iterations: Maximum number of L-BFGS iterations. 0 means no max.\n tolerance: kcal/mol, the energy tolerance of L-BFGS.\n stiffness: kcal/mol A**2, spring constant of heavy atom restraining\n potential.\n exclude_residues: Residues to exclude from per-atom restraining.\n Zero-indexed.\n max_outer_iterations: Maximum number of violation-informed relax\n iterations. A value of 1 will run the non-iterative procedure used in\n CASP14. Use 20 so that >95% of the bad cases are relaxed. Relax finishes\n as soon as there are no violations, hence in most cases this causes no\n slowdown. In the worst case we do 20 outer iterations.\n \"\"\"\n\n self._max_iterations = max_iterations\n self._tolerance = tolerance\n self._stiffness = stiffness\n self._exclude_residues = exclude_residues\n self._max_outer_iterations = max_outer_iterations\n\n def process(self, *,\n prot: protein.Protein) -> Tuple[str, Dict[str, Any], np.ndarray]:\n \"\"\"Runs Amber relax on a prediction, adds hydrogens, returns PDB string.\"\"\"\n out = amber_minimize.run_pipeline(\n prot=prot, max_iterations=self._max_iterations,\n tolerance=self._tolerance, stiffness=self._stiffness,\n exclude_residues=self._exclude_residues,\n max_outer_iterations=self._max_outer_iterations)\n min_pos = out['pos']\n start_pos = out['posinit']\n rmsd = np.sqrt(np.sum((start_pos - min_pos)**2) / start_pos.shape[0])\n debug_data = {\n 'initial_energy': out['einit'],\n 'final_energy': out['efinal'],\n 'attempts': out['min_attempts'],\n 'rmsd': rmsd\n }\n pdb_str = amber_minimize.clean_protein(prot)\n min_pdb = utils.overwrite_pdb_coordinates(pdb_str, min_pos)\n min_pdb = utils.overwrite_b_factors(min_pdb, prot.b_factors)\n utils.assert_equal_nonterminal_atom_types(\n protein.from_pdb_string(min_pdb).atom_mask,\n prot.atom_mask)\n violations = out['structural_violations'][\n 'total_per_residue_violations_mask']\n return min_pdb, debug_data, violations\n" ]
[ [ "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mpahl/omniconverter
[ "09e00222b407a31b7887dd77d1b97ff27a519629" ]
[ "omniconverter/stata_to_statistics.py" ]
[ "import re\nimport pandas as pd\nimport numpy as np\nimport os,sys, yaml, csv\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nfrom omniconverter import Converter #todoooooooooooooooo\n\ndef stata_to_statistics(study_name, input_csv, input_path, output_path, input_path_de=\"\"):\n filereader = pd.read_csv(input_csv, delimiter=\",\", header = 0)\n\n for data, weight, split, analysis_unit, period, sub_type in zip(\n filereader.filename, filereader.weight, filereader.split,\n filereader.analysis_unit, filereader.period, filereader.sub_type\n ):\n d1 = Converter()\n try:\n d1.read_stata(input_path + data + \".dta\")\n except:\n logger.warning(\"Unable to find \" + data + \".dta in \" + input_path + \".\")\n continue\n \n metadata_de=\"\"\n if input_path_de != \"\":\n d2 = Dataset()\n try:\n d2.read_stata(input_path_de + data + \".dta\")\n metadata_de=d2.metadata\n except:\n logger.warning(\"Unable to find \" + data + \".dta in \" + input_path_de + \".\")\n continue\n\n d1.write_stats(\n output_path + data + \"_stats.json\", split=split, weight=weight,\n analysis_unit=analysis_unit, period=period, sub_type=sub_type,\n study=study_name, metadata_de=metadata_de\n )\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
binkiklou/Leon_Nowsden_Steals_Code
[ "7a5ceaa9d6504ef9a1365e4a882ccb811562f141" ]
[ "RUN_THIS.py" ]
[ "# Import our libs\r\nfrom numpy import exp, array, random, dot\r\n# Define our data\r\ntraining_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])\r\ntraining_set_outputs = array([[0, 1, 1, 0]]).T\r\n# Use our lib \r\nrandom.seed(1)\r\n# We do maths \r\nsynaptic_weights = 2 * random.random((3, 1)) - 1\r\nfor iteration in range(10000):\r\n output = 1 / (1 + exp(-(dot(training_set_inputs, synaptic_weights))))\r\n synaptic_weights += dot(training_set_inputs.T, (training_set_outputs - output) * output * (1 - output))\r\navr = 1 / (1 + exp(-(dot(array([1, 0, 0]), synaptic_weights))))\r\n# This shows our result\r\nprint(\"Our result is\",avr)\r\n\r\n\r\n\r\n\r\n\r\n" ]
[ [ "numpy.dot", "numpy.array", "numpy.random.random", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Tiasa/StyleRecognitioninMusic
[ "775d631e3a688ba0d31f615115f45fd7580d1b5e" ]
[ "GlobalGrammars/MDSPlotter.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import cm\nimport subprocess\nimport sys\n# from mpl_toolkits.mplot3d import axes3d, Axes3D\n\ndef getDefName(definition):\n if definition == 1:\n return \"d(x,y) = max {K(x|y*),K(y|x*)} / max{K(x), K(y)}\"\n elif definition == 2:\n return \"d(x,y) = (K(x|y*) + K(y|x*))/K(x,y)\"\n elif definition == 4:\n return \"d(x,y)=(K(xy)-min{K(x),K(y)})/ max{K(x),K(y)}\"\n else:\n return \"d(x,y) = (K(x|y*) + K(y|x*))/K(x)+K(y)\"\n\ndef TwoDimPlotter(output, plotFileName, outputFolder ,labelAxes):\n for fileNo in range(len(output)):\n dataPoints = []\n artists = []\n with open(output[fileNo]) as MDSFile:\n for line in MDSFile:\n if len(line) > 0:\n x = []\n y = []\n line = line.split()\n artists.append(\" \".join(line[0].split(\"_\")))\n i = 1\n while i < len(line):\n x.append(float(line[i]))\n y.append(float(line[i+1]))\n i+=2\n dataPoints.append((np.asarray(x),np.asarray(y)))\n cmap = plt.get_cmap('gnuplot')\n colors =[\"red\",\"blue\",\"green\",\"orange\",\"black\",\"violet\"]#[cmap(i) for i in np.linspace(0, 1, len(artists))]#\n fig = plt.figure(fileNo)\n ax = fig.add_subplot(1, 1, 1, facecolor=\"1.0\")\n for i in range(len(artists)):\n #if artists[i]==\"The Beatles\" or artists[i]==\"Prince\" or artists[i]==\"Elvis Presley\" or artists[i]==\"Simon and Garfunkel\":\n x, y = dataPoints[i]\n color = colors[i]\n artist = artists[i]\n ax.scatter(x, y, alpha=1, c=color,\n edgecolors='none', s=30, label=artist)\n #ax.annotate(artist, (x[0], y[0]))\n plt.title(getDefName(int(output[fileNo].split(\".\")[0][-1])))\n box = ax.get_position()\n ax.set_position([box.x0, box.y0 + box.height * 0.1,\n box.width, box.height * 0.9])\n ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),\n fancybox=True, shadow=True, ncol=len(artists))\n if labelAxes:\n ax.set_xlabel('Vocal Distance')\n ax.set_ylabel('Melody Distance')\n fig.savefig(outputFolder+'/'+plotFileName+str(fileNo)+'.png',bbox_inches = \"tight\")\n plt.close(fig)\n\ndef create3DPlot(pitchFolderLoc):\n output = [pitchFolderLoc+'/3DScalingWithDef1.txt',pitchFolderLoc+'/3DScalingWithDef2.txt',pitchFolderLoc+'/3DScalingWithDef3.txt',pitchFolderLoc+'/3DScalingWithDef4.txt']\n for fileNo in range(len(output)):\n dataPoints = []\n artists = []\n with open(output[fileNo]) as MDSFile:\n for line in MDSFile:\n if len(line) > 0:\n x = []\n y = []\n z = []\n line = line.split()\n artists.append(\" \".join(line[0].split(\"_\")))\n i = 1\n while i < len(line):\n x.append(float(line[i]))\n y.append(float(line[i + 1]))\n z.append(float(line[i + 2]))\n i += 3\n dataPoints.append((np.asarray(x), np.asarray(y), np.asarray(z)))\n colors = cm.rainbow(np.linspace(0,1,len(artists))) #[\"red\",\"blue\",\"green\",\"black\"]#\n fig = plt.figure(fileNo)\n ax = fig.add_subplot(111, projection='3d')\n for i in range(len(artists)):\n x, y, z = dataPoints[i]\n color = colors[i]\n artist = artists[i]\n ax.scatter(x, y, z, c=color,\n label=artist)\n plt.title(getDefName(int(output[fileNo].split(\".\")[0][-1])))\n box = ax.get_position()\n ax.set_position([box.x0, box.y0 + box.height * 0.1,\n box.width, box.height * 0.9])\n ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),\n fancybox=True, shadow=True, ncol=len(artists))\n fig.savefig(pitchFolderLoc + '/Clustering3D' + str(fileNo) + '.png')\n\n ax.set_xlabel('X Coordinate')\n ax.set_ylabel('Y Coordinate')\n ax.set_zlabel('Z Coordinate')\n\n # plt.show()\n plt.close(fig)\n\n\n\ndef create2DPlot(pitchFolderLoc):\n\n output = [pitchFolderLoc+'/2DScalingWithDef2.txt']\n TwoDimPlotter(output,'MultiDimScaling',pitchFolderLoc,False)\n\n\n\n\ndef create2DPlotRock(outputFolderLoc):\n # outputE = [outputFolderLoc+'/2DEuclidean4ArtistsWithDef2.txt']\n # TwoDimPlotter(outputE, 'Euclidean4',outputFolderLoc, False)\n # outputM = [outputFolderLoc+'/2DManhattan4ArtistsWithDef2.txt']\n # TwoDimPlotter(outputM, 'Manhattan4', outputFolderLoc, False)\n # outputP = [outputFolderLoc+'/2DProjections4ArtistsWithDef2.txt']\n # TwoDimPlotter(outputP, 'Projections4', outputFolderLoc, True)\n\n outputE = [outputFolderLoc + '/2DEuclidean2ArtistsWithDef2.txt']\n TwoDimPlotter(outputE, 'Euclidean2',outputFolderLoc, False)\n outputM = [outputFolderLoc + '/2DManhattan2ArtistsWithDef2.txt']\n TwoDimPlotter(outputM, 'Manhattan2',outputFolderLoc, False)\n outputP = [outputFolderLoc + '/2DProjections2ArtistsWithDef2.txt']\n TwoDimPlotter(outputP, 'Projections2',outputFolderLoc, True)\n\ndef testCombinedApproximationAccuracy(phylipGeneratorLoc, folderLoc):\n startingNumstep = 1400\n datapoints = []\n kxyDefinition = [\"K(x,y) = K(x100000y)\",\"K(x,y) = K(x)+K(y)\"]\n for definition in range(2):\n x = []\n y = []\n for i in range(12):\n numSteps = startingNumstep + (i * 100)\n pitchFolderLoc = folderLoc + \"/numSteps\" + str(numSteps)\n file1 = pitchFolderLoc + \"/1_dt.pitch\"\n file2 = pitchFolderLoc + \"/2_dt.pitch\"\n output = subprocess.check_output(['java', '-classpath',\n phylipGeneratorLoc + '/mdsj.jar:' + phylipGeneratorLoc,\n 'GrammarTest',\n str(definition+1),\n file1,\n file2])\n x.append(numSteps)\n y.append(float(output.strip()))\n datapoints.append((np.asarray(x), np.asarray(y)))\n cmap = plt.get_cmap('gnuplot')\n colors = [\"red\", \"blue\", \"green\", \"orange\", \"black\",\n \"violet\"] # [cmap(i) for i in np.linspace(0, 1, len(artists))]#\n fig = plt.figure(1)\n ax = fig.add_subplot(1, 1, 1) #, facecolor=\"1.0\")\n for i in range(2):\n # if artists[i]==\"The Beatles\" or artists[i]==\"Prince\" or artists[i]==\"Elvis Presley\" or artists[i]==\"Simon and Garfunkel\":\n x, y = datapoints[i]\n color = colors[i]\n kxyDef = kxyDefinition[i]\n ax.scatter(x, y, alpha=1, c=color,\n edgecolors='none', s=30, label=kxyDef)\n # ax.annotate(artist, (x[0], y[0]))\n plt.title('Testing Accuracy of K(x,y) Definitions')\n box = ax.get_position()\n ax.set_position([box.x0, box.y0 + box.height * 0.1,\n box.width, box.height * 0.9])\n ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),\n fancybox=True, shadow=True, ncol=2)\n\n ax.set_xlabel('Number of Steps')\n ax.set_ylabel('K complexity')\n plt.show()\n #fig.savefig(outputFolder + '/' + plotFileName + str(fileNo) + '.png', bbox_inches=\"tight\")\n #plt.close(fig)\nif __name__=='__main__':\n arguments = sys.argv\n # if len(arguments) == 3:\n # phylipGeneratorLoc = arguments[1]\n # folderLoc = arguments[2]\n # testCombinedApproximationAccuracy(phylipGeneratorLoc,folderLoc)\n\n if len(arguments) == 3:\n phylipGeneratorLoc = arguments[1]\n pitchFolderLoc = arguments[2]\n subprocess.check_output(['java', '-classpath',\n phylipGeneratorLoc + '/mdsj.jar:' + phylipGeneratorLoc,\n 'Analyzer',\n pitchFolderLoc])\n #print output\n create2DPlot(pitchFolderLoc)\n\n\n # if len(arguments) ==5:\n # phylipGeneratorLoc = arguments[1]\n # outputFolderLoc = arguments[2]\n # vocalFolderLoc = arguments[3]\n # melodyFolderLoc = arguments[4]\n # subprocess.check_output(['java', '-classpath',\n # phylipGeneratorLoc + '/mdsj.jar:' + phylipGeneratorLoc,\n # 'Analyzer',\n # outputFolderLoc,\n # vocalFolderLoc,\n # melodyFolderLoc])\n # create2DPlotRock(outputFolderLoc)\n\n\n # if len(arguments) == 4:\n # phylipGeneratorLoc = arguments[1]\n # referenceFileLoc = arguments[2]\n # pitchFolderLoc = arguments[3]\n # subprocess.check_output(['java', '-classpath',\n # phylipGeneratorLoc + '/mdsj.jar:' + phylipGeneratorLoc,\n # 'Analyzer', referenceFileLoc,\n # pitchFolderLoc])\n # create2DPlot(pitchFolderLoc)\n\n" ]
[ [ "matplotlib.pyplot.title", "numpy.asarray", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.close", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
moonbzyx/ctp
[ "e5f663352124ac8033912c5867cc5ac2cecbb662" ]
[ "tests/kbcr/models/test_masking.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nimport torch\nfrom torch import nn\n\nfrom kbcr.kernels import GaussianKernel\nfrom kbcr.models import NeuralKB\nfrom kbcr.models.reasoning import SimpleHoppy\nfrom kbcr.reformulators import SymbolicReformulator\n\nimport pytest\n\n\[email protected]\ndef test_masking_v1():\n nb_entities = 10\n nb_predicates = 5\n embedding_size = 10\n\n init_size = 1.0\n\n rs = np.random.RandomState(0)\n\n for _ in range(1):\n for position in [0, 1]:\n for st in ['min', 'concat']:\n with torch.no_grad():\n triples = [\n ('a', 'p', 'b'),\n ('c', 'q', 'd')\n ]\n entity_to_index = {'a': 0, 'b': 1, 'c': 2, 'd': 3}\n predicate_to_index = {'p': 0, 'q': 1}\n\n kernel = GaussianKernel()\n\n entity_embeddings = nn.Embedding(nb_entities, embedding_size * 2, sparse=True)\n predicate_embeddings = nn.Embedding(nb_predicates, embedding_size * 2, sparse=True)\n\n entity_embeddings.weight.data *= init_size\n predicate_embeddings.weight.data *= init_size\n\n fact_rel = torch.from_numpy(np.array([predicate_to_index[p] for (_, p, _) in triples]))\n fact_arg1 = torch.from_numpy(np.array([entity_to_index[s] for (s, _, _) in triples]))\n fact_arg2 = torch.from_numpy(np.array([entity_to_index[o] for (_, _, o) in triples]))\n facts = [fact_rel, fact_arg1, fact_arg2]\n\n model = NeuralKB(entity_embeddings=entity_embeddings, predicate_embeddings=predicate_embeddings,\n kernel=kernel, facts=facts, scoring_type=st)\n\n xs_np = rs.randint(nb_entities, size=32)\n xp_np = rs.randint(nb_predicates, size=32)\n xo_np = rs.randint(nb_entities, size=32)\n xi_np = np.array([position] * xs_np.shape[0])\n\n xs_np[0] = 0\n xp_np[0] = 0\n xo_np[0] = 1\n\n xs_np[1] = 2\n xp_np[1] = 1\n xo_np[1] = 3\n\n xs = torch.from_numpy(xs_np)\n xp = torch.from_numpy(xp_np)\n xo = torch.from_numpy(xo_np)\n xi = torch.from_numpy(xi_np)\n\n xs_emb = entity_embeddings(xs)\n xp_emb = predicate_embeddings(xp)\n xo_emb = entity_embeddings(xo)\n\n model.mask_indices = xi\n\n scores = model.forward(xp_emb, xs_emb, xo_emb)\n inf = model.score(xp_emb, xs_emb, xo_emb)\n\n if position == 0:\n assert inf[0] < 0.5\n assert inf[1] > 0.9\n elif position == 1:\n assert inf[0] > 0.9\n assert inf[1] < 0.5\n\n scores_sp, scores_po = scores\n\n inf = inf.cpu().numpy()\n scores_sp = scores_sp.cpu().numpy()\n scores_po = scores_po.cpu().numpy()\n\n for i in range(xs.shape[0]):\n np.testing.assert_allclose(inf[i], scores_sp[i, xo[i]], rtol=1e-5, atol=1e-5)\n np.testing.assert_allclose(inf[i], scores_po[i, xs[i]], rtol=1e-5, atol=1e-5)\n\n\[email protected]\ndef test_masking_v2():\n nb_entities = 10\n nb_predicates = 5\n embedding_size = 10\n\n rs = np.random.RandomState(0)\n\n for _ in range(1):\n for position in [0, 1, 2]:\n for st in ['min', 'concat']:\n with torch.no_grad():\n triples = [\n ('a', 'p', 'b'),\n ('b', 'q', 'c'),\n ('a', 'p', 'c')\n ]\n entity_to_index = {'a': 0, 'b': 1, 'c': 2, 'd': 3}\n predicate_to_index = {'p': 0, 'q': 1}\n\n kernel = GaussianKernel()\n\n entity_emb = nn.Embedding(nb_entities, embedding_size * 2, sparse=True)\n predicate_emb = nn.Embedding(nb_predicates, embedding_size * 2, sparse=True)\n\n fact_rel = torch.from_numpy(np.array([predicate_to_index[p] for (_, p, _) in triples]))\n fact_arg1 = torch.from_numpy(np.array([entity_to_index[s] for (s, _, _) in triples]))\n fact_arg2 = torch.from_numpy(np.array([entity_to_index[o] for (_, _, o) in triples]))\n facts = [fact_rel, fact_arg1, fact_arg2]\n\n base = NeuralKB(entity_embeddings=entity_emb, predicate_embeddings=predicate_emb,\n kernel=kernel, facts=facts, scoring_type=st)\n\n indices = torch.from_numpy(np.array([predicate_to_index['p'], predicate_to_index['q']]))\n reformulator = SymbolicReformulator(predicate_emb, indices)\n model = SimpleHoppy(base, entity_emb, hops=reformulator)\n\n xs_np = rs.randint(nb_entities, size=32)\n xp_np = rs.randint(nb_predicates, size=32)\n xo_np = rs.randint(nb_entities, size=32)\n xi_np = np.array([position] * xs_np.shape[0])\n\n xs_np[0] = 0\n xp_np[0] = 0\n xo_np[0] = 1\n\n xs_np[1] = 1\n xp_np[1] = 1\n xo_np[1] = 2\n\n xs_np[2] = 0\n xp_np[2] = 0\n xo_np[2] = 2\n\n xs = torch.from_numpy(xs_np)\n xp = torch.from_numpy(xp_np)\n xo = torch.from_numpy(xo_np)\n xi = torch.from_numpy(xi_np)\n\n xs_emb = entity_emb(xs)\n xp_emb = predicate_emb(xp)\n xo_emb = entity_emb(xo)\n\n # xi = None\n base.mask_indices = xi\n\n scores = model.forward(xp_emb, xs_emb, xo_emb)\n inf = model.score(xp_emb, xs_emb, xo_emb)\n\n if position in {0, 1}:\n assert inf[2] < 0.5\n else:\n assert inf[2] > 0.9\n\n scores_sp, scores_po = scores\n\n inf = inf.cpu().numpy()\n scores_sp = scores_sp.cpu().numpy()\n scores_po = scores_po.cpu().numpy()\n\n for i in range(xs.shape[0]):\n np.testing.assert_allclose(inf[i], scores_sp[i, xo[i]], rtol=1e-5, atol=1e-5)\n np.testing.assert_allclose(inf[i], scores_po[i, xs[i]], rtol=1e-5, atol=1e-5)\n\n\nif __name__ == '__main__':\n pytest.main([__file__])\n" ]
[ [ "torch.from_numpy", "torch.nn.Embedding", "torch.no_grad", "numpy.testing.assert_allclose", "numpy.array", "numpy.random.RandomState" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
birlrobotics/birlBaxter_demos
[ "a4871cbf2587a759c958c8451746554e1663e829" ]
[ "deep_tracking/deeptracking/data/frame.py" ]
[ "\"\"\"\n Keeps a reference to a rgb and depth images (given an id). keeps data on disk or ram depending on need\n\n date : 2017-23-03\n\"\"\"\n\n__author__ = \"Mathieu Garon\"\n__version__ = \"0.0.1\"\n\nimport numpngw\nimport os\nimport numpy as np\nfrom PIL import Image\n\n\nclass Frame:\n def __init__(self, rgb, depth, id):\n self.rgb = rgb\n self.depth = depth\n self.id = id\n\n def is_on_disk(self):\n return self.rgb is None and self.depth is None\n\n def exists(self, path):\n return os.path.exists(os.path.join(path, '{}.png').format(self.id)) and \\\n os.path.exists(os.path.join(path, '{}d.png').format(self.id))\n\n def get_rgb_depth(self, path, keep_in_ram=False):\n \"\"\"\n getter to images, if keep in ram is false, the reference wont be kept by this object\n :param path:\n :param keep_in_ram:\n :return:\n \"\"\"\n if self.is_on_disk():\n self.load(path)\n rgb = self.rgb\n depth = self.depth\n if not keep_in_ram:\n self.clear_image()\n return rgb, depth\n\n def clear_image(self):\n self.rgb = None\n self.depth = None\n\n def dump(self, path):\n if not self.is_on_disk():\n numpngw.write_png(os.path.join(path, '{}.png').format(self.id), self.rgb)\n numpngw.write_png(os.path.join(path, '{}d.png').format(self.id), self.depth.astype(np.uint16))\n self.clear_image()\n\n def load(self, path):\n self.rgb = np.array(Image.open(os.path.join(path, self.id + \".png\")))\n self.depth = np.array(Image.open(os.path.join(path, self.id + \"d.png\"))).astype(np.uint16)\n\n\nclass FrameNumpy(Frame):\n def __init__(self, rgb, depth, id):\n super().__init__(rgb, depth, id)\n\n def dump(self, path):\n if not self.is_on_disk():\n depth8 = self.numpy_int16_to_uint8(self.depth)\n frame = np.concatenate((self.rgb, depth8), axis=2)\n np.save(os.path.join(path, self.id), frame)\n self.clear_image()\n\n def load(self, path):\n frame = np.load(os.path.join(path, \"{}.npy\".format(self.id)))\n self.depth = self.numpy_uint8_to_int16(frame[:, :, 3:])\n self.rgb = frame[:, :, 0:3]\n\n @staticmethod\n def numpy_int16_to_uint8(depth):\n x, y = depth.shape\n out = np.ndarray((x, y, 2), dtype=np.uint8)\n out[:, :, 0] = np.right_shift(depth, 8)\n out[:, :, 1] = depth.astype(np.uint8)\n return out\n\n @staticmethod\n def numpy_uint8_to_int16(depth8):\n x, y, c = depth8.shape\n out = np.ndarray((x, y), dtype=np.int16)\n out[:, :] = depth8[:, :, 0]\n out = np.left_shift(out, 8)\n out[:, :] += depth8[:, :, 1]\n return out\n" ]
[ [ "numpy.right_shift", "numpy.left_shift", "numpy.ndarray", "numpy.concatenate" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
truatpasteurdotfr/AMPL
[ "68dd7a8004272d22ef5d975c57e1e9149c820f8b" ]
[ "atomsci/ddm/pipeline/transformations.py" ]
[ "\"\"\"\nClasses providing different methods of transforming response data and/or features in datasets, beyond those\nprovided by DeepChem.\n\"\"\"\n\nimport logging\nimport os\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport umap\n\nimport deepchem as dc\nfrom deepchem.trans.transformers import Transformer, NormalizationTransformer\nfrom sklearn.preprocessing import RobustScaler, Imputer\n\nlogging.basicConfig(format='%(asctime)-15s %(message)s')\nlog = logging.getLogger('ATOM')\n\ndef get_statistics_missing_ydata(dataset):\n \"\"\"Compute and return statistics of this dataset.\n\n This updated version gives the option to check for and ignore missing\n values for the y variable only. The x variable still assumes no\n missing values.\n \"\"\"\n y_means = np.zeros(len(dataset.get_task_names()))\n y_m2 = np.zeros(len(dataset.get_task_names()))\n dy = np.zeros(len(dataset.get_task_names()))\n n = np.zeros(len(dataset.get_task_names()))\n for _, y, w, _ in dataset.itersamples():\n for it in range(len(y)) :\n ## set weights to 0 for missing data\n if np.isnan(y[it]) :\n assert(w[i]==0)\n if w[it]!=0 and not np.isnan(y[it]) :\n #print(\"huh\",w[it],y[it]) \n n[it]+=1\n dy[it] = y[it] - y_means[it]\n y_means[it] += dy[it] / n[it]\n y_m2[it] += dy[it] * (y[it] - y_means[it])\n \n print(\"n_cnt\",n)\n print(\"y_means\",y_means)\n y_stds=np.zeros(len(n))\n for it in range(len(n)) :\n if n[it] >= 2:\n y_stds[it] = np.sqrt(y_m2[it] / n[it])\n print(\"y_stds\",y_stds)\n return y_means, y_stds\n \n# ****************************************************************************************\ndef create_feature_transformers(params, model_dataset):\n \"\"\"Fit a scaling and centering transformation to the feature matrix of the given dataset, and return a\n DeepChem transformer object holding its parameters.\n\n Args:\n params (argparse.namespace: Object containing the parameter list\n model_dataset (ModelDataset): Contains the dataset to be transformed.\n Returns:\n (list of DeepChem transformer objects): list of transformers for the feature matrix\n \"\"\"\n if params.feature_transform_type == 'umap':\n # Map feature vectors using UMAP for dimension reduction\n if model_dataset.split_strategy == 'k_fold_cv':\n log.warning(\"Warning: UMAP transformation may produce misleading results when used with K-fold split strategy.\")\n train_dset = model_dataset.train_valid_dsets[0][0]\n transformers_x = [UMAPTransformer(params, train_dset)]\n elif params.transformers==True:\n # TODO: Transformers on responses and features should be controlled only by parameters\n # response_transform_type and feature_transform_type, rather than params.transformers.\n\n # Scale and center feature matrix if featurization type calls for it\n transformers_x = model_dataset.featurization.create_feature_transformer(model_dataset.dataset)\n else:\n transformers_x = []\n\n return transformers_x\n\n# ****************************************************************************************\ndef get_transformer_specific_metadata(params):\n \"\"\"Returns a dictionary of parameters related to the currently selected transformer(s).\n\n Args:\n params (argparse.namespace: Object containing the parameter list\n\n Returns:\n meta_dict (dict): Nested dictionary of parameters and values for each currently active\n transformer.\n \"\"\"\n meta_dict = {}\n if params.feature_transform_type == 'umap':\n umap_dict = dict(\n umap_dim = params.umap_dim,\n umap_metric = params.umap_metric,\n umap_targ_wt = params.umap_targ_wt,\n umap_neighbors = params.umap_neighbors,\n umap_min_dist = params.umap_min_dist )\n meta_dict['UmapSpecific'] = umap_dict\n return meta_dict\n\n# ****************************************************************************************\n\nclass UMAPTransformer(Transformer):\n \"\"\"\n Dimension reduction transformations using the UMAP algorithm.\n\n Attributes:\n mapper (UMAP) : UMAP transformer\n scaler (RobustScaler): Centering/scaling transformer\n\n \"\"\"\n def __init__(self, params, dataset):\n \"\"\"Initializes a UMAPTransformer object.\n\n Args:\n params (Namespace): Contains parameters used to instantiate the transformer.\n dataset (Dataset): Dataset used to \"train\" the projection mapping.\n \"\"\"\n\n # TODO: decide whether to make n_epochs a parameter\n #default_n_epochs = None\n default_n_epochs = 500\n\n if params.prediction_type == 'classification':\n target_metric = 'categorical'\n else:\n target_metric = 'l2'\n self.scaler = RobustScaler()\n # Use Imputer to replace missing values (NaNs) with means for each column\n self.imputer = Imputer()\n scaled_X = self.scaler.fit_transform(self.imputer.fit_transform(dataset.X))\n self.mapper = umap.UMAP(n_neighbors=params.umap_neighbors, \n n_components=params.umap_dim,\n metric=params.umap_metric,\n target_metric=target_metric,\n target_weight=params.umap_targ_wt,\n min_dist=params.umap_min_dist,\n n_epochs=default_n_epochs)\n # TODO: How to deal with multitask data?\n self.mapper.fit(scaled_X, y=dataset.y.flatten())\n\n # ****************************************************************************************\n def transform(self, dataset, parallel=False):\n return super(UMAPTransformer, self).transform(dataset, parallel=parallel)\n\n # ****************************************************************************************\n def transform_array(self, X, y, w):\n X = self.mapper.transform(self.scaler.transform(self.imputer.transform(X)))\n return (X, y, w)\n\n # ****************************************************************************************\n def untransform(self, z):\n \"\"\"Reverses stored transformation on provided data.\"\"\"\n raise NotImplementedError(\"Can't reverse a UMAP transformation\")\n # ****************************************************************************************\n\n \n# ****************************************************************************************\n\nclass NormalizationTransformerMissingData(NormalizationTransformer):\n \"\"\"\n Test extension to check for missing data\n \"\"\"\n def __init__(self,\n transform_X=False,\n transform_y=False,\n transform_w=False,\n dataset=None,\n transform_gradients=False,\n move_mean=True) :\n \n if transform_X :\n X_means, X_stds = dataset.get_statistics(X_stats=True, y_stats=False)\n self.X_means = X_means\n self.X_stds = X_stds\n elif transform_y:\n y_means, y_stds = get_statistics_missing_ydata(dataset)\n self.y_means = y_means\n # Control for pathological case with no variance.\n y_stds = np.array(y_stds)\n y_stds[y_stds == 0] = 1.\n self.y_stds = y_stds\n self.transform_gradients = transform_gradients\n self.move_mean = move_mean\n if self.transform_gradients:\n true_grad, ydely_means = get_grad_statistics(dataset)\n self.grad = np.reshape(true_grad, (true_grad.shape[0], -1, 3))\n self.ydely_means = ydely_means\n\n ## skip the NormalizationTransformer initialization and go to base class\n super(NormalizationTransformer, self).__init__(\n transform_X=transform_X,\n transform_y=transform_y,\n transform_w=transform_w,\n dataset=dataset)\n\n\n" ]
[ [ "numpy.sqrt", "numpy.isnan", "sklearn.preprocessing.RobustScaler", "numpy.reshape", "sklearn.preprocessing.Imputer", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
madilovic/AALI
[ "1348f905ecda0b63775d1d42f15a17e599226490" ]
[ "AALI.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 28 09:38:30 2020\n\n@author: Muhamed Adilovic\n\"\"\"\n\nimport os\nimport argparse\nimport pandas as pd\nfrom Bio.PDB.PDBParser import PDBParser\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-o\", \"--output\", choices=[\"exact\", \"tf\"], default=\"exact\",\n help = \"set output type: exact distance or true/false\")\n parser.add_argument(\"-in\", \"--in_folder\", default=\"PDBs\",\n help = \"set the folder containing pdb files\")\n parser.add_argument(\"-t\", \"--threshold\", type=int, default=4,\n help = \"set the threshold value for generating True/False output\")\n parser.add_argument(\"-out\", \"--out_folder\", default=\"output\",\n help = \"set the folder which will contain the results\")\n parser.add_argument(\"-c\", \"--combined\", choices=[\"yes\", \"no\"], default=\"no\",\n help = \"choose whether to show all distances or the smallest ones\")\n parser.add_argument(\"-m\", \"--mode\", choices=[\"CA\", \"residue\"], default=\"residue\",\n help = \"choose whether to check distance against CA or \\\n all atoms in amino acid and pick the smallest one\")\n parser.add_argument(\"-chl\", \"--check_ligand\", choices=[\"yes\", \"no\"], default=\"yes\",\n help = \"choose whether to check amino acids against ligands\")\n parser.add_argument(\"-chw\", \"--check_water\", choices=[\"yes\", \"no\"], default=\"no\",\n help = \"choose whether to check amino acids against water\")\n parser.add_argument(\"-s\", \"--skip\", choices=[\"yes\", \"no\"], default=\"no\",\n help = \"choose whether to analyze the pdb file even if \\\n it doesn't have water or ligands\")\n parser.add_argument(\"-j\", \"--join\", choices=[\"yes\", \"no\"], default=\"no\",\n help = \"choose whether to join all output csv files into one\")\n args = parser.parse_args()\n return args\n\nthreshold_w = int('4')\n\n# TODO\n# Implement support for verbose\n# Printing out the percentage of work done\n\n# TODO\n# Implement adding a column with protein name in case of join == 'yes'\n\ndef get_heteros(structure):\n \"\"\"\n Parameters\n ----------\n structure : Biopython protein structure object made with PDBParser().\n\n Returns\n -------\n heteros : a list of hetero residues in a protein model.\n \"\"\"\n heteros = []\n\n for model in structure:\n for chain in model:\n for residue in chain.get_list():\n if is_hetero(residue):\n heteros.append(residue)\n return heteros\n\ndef get_water(structure):\n \"\"\"\n Parameters\n ----------\n structure : Biopython protein structure object made with PDBParser().\n\n Returns\n -------\n water : a list of water molecules in a protein model.\n \"\"\"\n water = []\n\n for model in structure:\n for chain in model:\n for residue in chain.get_list():\n if is_water(residue):\n water.append(residue)\n return water\n\ndef get_hetero_names(structure):\n \"\"\"\n Parameters\n ----------\n structure : Biopython protein structure object made with PDBParser().\n\n Returns\n -------\n hetero_names : a list of hetero residue names in a protein model.\n \"\"\"\n hetero_names = []\n for model in structure:\n for chain in model:\n for residue in chain.get_list():\n if is_hetero(residue):\n hetero_names.append(residue.get_resname())\n return hetero_names\n\ndef get_AA_names_nums(structure):\n \"\"\"\n Parameters\n ----------\n structure : Biopython protein structure object made with PDBParser().\n\n Returns\n -------\n AA_names : a list of amino acid names in a protein model.\n AA_nums : a list of animo acid number IDs in a protein model.\n \"\"\"\n AA_names = []\n AA_nums = []\n AA_model = []\n AA_chain = []\n for model in structure:\n model_id = model._id\n for chain in model:\n chain_id = chain._id\n for residue in chain.get_list():\n if is_nonAA(residue):\n continue\n AA_names.append(residue.get_resname())\n AA_nums.append(residue.get_id()[1])\n AA_model.append(model_id)\n AA_chain.append(chain_id) \n return AA_names, AA_nums, AA_model, AA_chain\n \ndef is_nonAA(residue):\n \"\"\"\n Parameters\n ----------\n residue : a residue from a protein structure object made with PDBParser().\n\n Returns\n -------\n Boolean\n True if residue is hetero or water, False otherwise.\n \"\"\"\n residue_id = residue.get_id()\n hetfield = residue_id[0]\n return (hetfield[0] == 'H') or (hetfield[0] == 'W')\n\ndef is_hetero(residue):\n \"\"\"\n Parameters\n ----------\n residue : a residue from a protein structure object made with PDBParser().\n\n Returns\n -------\n Boolean\n True if residue is hetero, False otherwise.\n \"\"\"\n residue_id = residue.get_id()\n hetfield = residue_id[0]\n return hetfield[0] == 'H'\n\ndef is_water(residue):\n \"\"\"\n Parameters\n ----------\n residue : a residue from a protein structure object made with PDBParser().\n\n Returns\n -------\n Boolean\n True if residue is water, False otherwise.\n \"\"\"\n residue_id = residue.get_id()\n hetfield = residue_id[0]\n return hetfield[0] == 'W'\n\ndef check_distance_CA(AA, H):\n \"\"\"\n Parameters\n ----------\n AA : amino acid from a protein structure object made with PDBParser().\n H : hetero residue from a protein structure object made with PDBParser().\n\n Returns\n -------\n distance : the distance between CA of AA and H's closest atom.\n \"\"\" \n distance = []\n for atom in H:\n distance.append(AA['CA']-atom)\n return min(distance)\n\ndef check_distance_residue(AA, H):\n \"\"\"\n Parameters\n ----------\n AA : amino acid from a protein structure object made with PDBParser().\n H : hetero residue from a protein structure object made with PDBParser().\n\n Returns\n -------\n distance : the smallest distance between the two residues\n (includes all atoms in calculation).\n \"\"\" \n distance = []\n for atom_AA in AA:\n for atom_H in H:\n distance.append(atom_AA-atom_H)\n return min(distance)\n\ndef check_distance_protein(structure, H):\n \"\"\"\n Parameters\n ----------\n structure : Biopython protein structure object made with PDBParser().\n H : hetero residue from a protein structure object made with PDBParser().\n\n Returns\n -------\n distances : the list of smallest distances between each amino acid from \n protein structure and a given ligand H.\n \"\"\" \n distances = []\n for model in structure:\n for chain in model:\n for residue in chain.get_list():\n if is_nonAA(residue):\n continue\n if args.mode == 'residue':\n distances.append(check_distance_residue(residue, H))\n elif args.mode == 'CA':\n distances.append(check_distance_CA(residue, H)) \n return distances\n\ndef check_all_H(structure):\n \"\"\"\n Parameters\n ----------\n structure : Biopython protein structure object made with PDBParser().\n\n Returns\n -------\n all_ligands : dataframe of all distances between each amino acid residue \n and ligand from the protein structure.\n \"\"\" \n heteros = get_heteros(structure)\n hetero_names = get_hetero_names(structure)\n all_ligands = pd.DataFrame()\n # handling a case if output = 'exact'\n if args.output == 'exact':\n for i in range(len(heteros)):\n all_ligands[hetero_names[i]] = check_distance_protein(structure, heteros[i])\n if args.combined == 'yes':\n all_ligands = all_ligands.min(axis=1)\n all_ligands.name = 'ligand_distance'\n # handling a case if output = 'tf'\n elif args.output == 'tf':\n for i in range(len(heteros)):\n column_id = hetero_names[i]+'_'+str(args.threshold)\n all_ligands[column_id] = check_distance_protein(structure, heteros[i])\n all_ligands = all_ligands < args.threshold\n if args.combined == 'yes':\n all_ligands = all_ligands.any(axis=1)\n all_ligands.name = 'ligand_'+str(args.threshold)\n return all_ligands\n\ndef check_all_W(structure):\n \"\"\"\n Parameters\n ----------\n structure : Biopython protein structure object made with PDBParser().\n\n Returns\n -------\n all_water : dataframe of all distances between each amino acid residue \n and water molecules from the protein structure.\n \"\"\" \n water = get_water(structure)\n all_water = pd.DataFrame()\n # handling a case if output = 'exact'\n if args.output == 'exact':\n for i in range(len(water)):\n all_water[str(i)] = check_distance_protein(structure, water[i])\n all_water = all_water.min(axis=1)\n all_water.name = 'water_distance'\n # handling a case if output = 'tf'\n elif args.output == 'tf':\n for i in range(len(water)):\n all_water[str(i)] = check_distance_protein(structure, water[i])\n all_water = all_water < threshold_w\n all_water = all_water.any(axis=1)\n all_water.name = 'water_'+str(threshold_w)\n return all_water\n\ndef combine(structure):\n \"\"\"\n Parameters\n ----------\n structure : Biopython protein structure object made with PDBParser().\n\n Returns\n -------\n dataframe : containing every amino acid name and ID number, toegether with\n all distances between each amino acid residue and ligand from the protein \n structure.\n None : in cases where the protein is supposed to be skipped\n \"\"\"\n # TODO\n # Add support to generate an empty column if no ligand/water is present\n # and skip == no\n \n AA_names, AA_nums, AA_model, AA_chain = get_AA_names_nums(structure)\n result = pd.DataFrame()\n result['AA_name'] = AA_names\n result['AA_num'] = AA_nums\n result['model'] = AA_model\n result['chain'] = AA_chain\n heteros = get_heteros(structure)\n water = get_water(structure)\n # handle different types of checks...\n if args.check_ligand == 'yes' and args.check_water == 'yes':\n if args.skip == 'yes' and len(heteros) == 0 and len(water) == 0:\n return\n H_distances = check_all_H(structure)\n W_distances = check_all_W(structure)\n return pd.concat([result,H_distances,W_distances], axis=1)\n elif args.check_ligand == 'yes':\n if args.skip == 'yes' and len(heteros) == 0:\n return\n H_distances = check_all_H(structure)\n return pd.concat([result,H_distances], axis=1)\n elif args.check_water == 'yes':\n if args.skip == 'yes' and len(water) == 0:\n return\n W_distances = check_all_W(structure)\n return pd.concat([result,W_distances], axis=1)\n else:\n print('Please use \"yes\" for at least one of the two: chek_water or check_ligand.')\n return\n\ndef main(args):\n if not os.path.exists(args.out_folder):\n os.mkdir(args.out_folder)\n \n proteins = []\n \n for file in os.listdir(args.in_folder):\n if file.endswith('.pdb'):\n proteins.append(file)\n \n if args.join == 'yes':\n result_joined = pd.DataFrame()\n \n for protein in proteins:\n ID = protein.replace('.pdb', '')\n parser = PDBParser()\n protein_path = args.in_folder+'/'+protein\n structure = parser.get_structure(ID, protein_path)\n \n result = combine(structure)\n if result is None:\n print('No ligands and/or water present in ', ID)\n continue\n if args.join == 'no':\n result_path = args.out_folder+'/'+ID+'.csv'\n result.to_csv(result_path)\n elif args.join == 'yes':\n result_joined = pd.concat([result_joined,result])\n \n if args.join == 'yes':\n result_joined_path = args.out_folder+'/'+'AALI_contacts.csv'\n result_joined.to_csv(result_joined_path)\n\nif __name__ == '__main__':\n args = parse_args()\n main(args)\n\n \n \n \n \n " ]
[ [ "pandas.concat", "pandas.DataFrame" ] ]
[ { "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": [] } ]
vishalbelsare/fracdiff-1
[ "0d034b6e2328b50238784fb3831785d89113912d" ]
[ "fracdiff/sklearn/tol.py" ]
[ "# found module but no type hints or library stubs\nimport numpy as np # type:ignore\n\nfrom fracdiff.fdiff import fdiff_coef\n\n\ndef window_from_tol_coef(n: float, tol_coef: float, max_window: int = 2 ** 12) -> int:\n \"\"\"\n Return length of window determined from tolerance to memory loss.\n\n Tolerance of smallness of coefficient to determine the length of window.\n That is, `window_` is chosen as the minimum integer that makes the\n absolute value of the `window`-th fracdiff coefficient is smaller than\n `tol_coef`.\n\n Parameters\n ----------\n - n : int\n Order of fractional differentiation.\n - tol_coef : float in range (0, 1)\n ...\n\n Notes\n -----\n The window for small `d` or `tol_(memory|coef)` can become extremely large.\n For instance, window grows with the order of `tol_coef ** (-1 / d)`.\n\n Returns\n -------\n window : int\n Length of window\n\n Examples\n --------\n >>> window_from_tol_coef(0.5, 0.1)\n 4\n >>> fdiff_coef(0.5, 3)[-1]\n -0.125\n >>> fdiff_coef(0.5, 4)[-1]\n -0.0625\n \"\"\"\n coef = np.abs(fdiff_coef(n, max_window))\n return int(np.searchsorted(-coef, -tol_coef) + 1) # index -> length\n\n\ndef window_from_tol_memory(\n n: float, tol_memory: float, max_window: int = 2 ** 12\n) -> int:\n \"\"\"\n Return length of window determined from tolerance to memory loss.\n\n Minimum lenght of window that makes the absolute value of the sum of fracdiff\n coefficients from `window_ + 1`-th term is smaller than `tol_memory`.\n If `window` is not None, ignored.\n\n Notes\n -----\n The window for small `d` or `tol_(memory|coef)` can become extremely large.\n For instance, window grows with the order of `tol_coef ** (-1 / d)`.\n\n Parameters\n ----------\n - n : int\n Order of fractional differentiation.\n - tol_memory : float in range (0, 1)\n Tolerance of lost memory.\n\n Returns\n -------\n window : int\n Length of window\n\n Examples\n --------\n >>> window_from_tol_memory(0.5, 0.2)\n 9\n >>> np.sum(fdiff_coef(0.5, 10000)[9:])\n -0.19073...\n >>> np.sum(fdiff_coef(0.5, 10000)[8:])\n -0.20383...\n \"\"\"\n lost_memory = np.abs(np.cumsum(fdiff_coef(n, max_window)))\n return int(np.searchsorted(-lost_memory, -tol_memory) + 1) # index -> length\n" ]
[ [ "numpy.searchsorted" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dallaval5u/snewpdag
[ "756e9226405b250af15519b85188c63df9139c90" ]
[ "snewpdag/plugins/renderers/Histogram1D.py" ]
[ "\"\"\"\n1D Histogram renderer\n\nConfiguration options:\n title: histogram title (top of plot)\n xlabel: x axis label\n ylabel: y axis label\n filename: output filename, with fields\n {0} renderer name\n {1} count index, starting from 0\n {2} burst_id from update data (default 0 if no such field)\n\nMight be nice to allow options to be configured here as well.\n\nInput data:\n action - only respond to 'report'\n burst_id - burst identifier\n xlow\n xhigh\n bins - uniform bin contents\n in_field - optional, dictionary name of input\n (otherwise look in payload dictionary itself)\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom snewpdag.dag import Node\n\nclass Histogram1D(Node):\n def __init__(self, title, xlabel, ylabel, filename, **kwargs):\n self.title = title\n self.xlabel = xlabel\n self.ylabel = ylabel\n self.filename = filename # include pattern to include index\n self.in_field = kwargs.pop('in_field', None)\n self.count = 0 # number of histograms made\n super().__init__(**kwargs)\n\n def render(self, burst_id, xlo, xhi, bins):\n n = len(bins)\n step = (xhi - xlo) / n\n x = np.arange(xlo, xhi, step)\n\n fig, ax = plt.subplots()\n ax.bar(x, bins, width=step, align='edge')\n #ax.plot(x, bins)\n ax.set_xlabel(self.xlabel)\n ax.set_ylabel(self.ylabel)\n ax.set_title('{0} (burst {1} count {2})'.format(\n self.title, burst_id, self.count))\n fig.tight_layout()\n\n fname = self.filename.format(self.name, self.count, burst_id)\n plt.savefig(fname)\n self.count += 1\n\n def report(self, data):\n burst_id = data.get('burst_id', 0)\n d = data[self.in_field] if self.in_field else data\n self.render(burst_id, d['xlow'], d['xhigh'], d['bins'])\n return True\n\n" ]
[ [ "numpy.arange", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
garyxcheng/federated
[ "ba7133ead6127af71ea9356e26bfd05c02f8324a", "ba7133ead6127af71ea9356e26bfd05c02f8324a", "ba7133ead6127af71ea9356e26bfd05c02f8324a", "ba7133ead6127af71ea9356e26bfd05c02f8324a", "ba7133ead6127af71ea9356e26bfd05c02f8324a", "ba7133ead6127af71ea9356e26bfd05c02f8324a", "ba7133ead6127af71ea9356e26bfd05c02f8324a", "ba7133ead6127af71ea9356e26bfd05c02f8324a", "ba7133ead6127af71ea9356e26bfd05c02f8324a", "ba7133ead6127af71ea9356e26bfd05c02f8324a" ]
[ "reconstruction/stackoverflow/models.py", "gans/experiments/emnist/preprocessing/filtered_emnist_data_utils_test.py", "fedopt_guide/stackoverflow_transformer/centralized_main_test.py", "fedopt_guide/training_loop_test.py", "gans/experiments/emnist/eval/emnist_eval_util_test.py", "targeted_attack/attacked_fedavg.py", "generalization/utils/centralized_training_loop_test.py", "shrink_unshrink/emnist_fedavg_main.py", "large_cohort/processes/q_ffl.py", "dual_encoder/movielens/movielens_data_gen_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\"\"\"Stackoverflow reconstruction models.\"\"\"\nimport collections\nimport tensorflow as tf\n\nfrom reconstruction import keras_utils\nfrom reconstruction import reconstruction_model\n\n\nclass GlobalEmbedding(tf.keras.layers.Layer):\n \"\"\"A custom Keras Embedding layer used for the global embeddings.\n\n The `GlobalEmbedding`s correspond to embeddings with input dimension size\n vocabulary_size + 3 (pad/bos/eos). The updates to these embeddings are sent\n to the server.\n \"\"\"\n\n def __init__(\n self,\n total_vocab_size: int,\n embedding_dim: int,\n mask_zero: bool = True,\n initializer: tf.keras.initializers = tf.keras.initializers.random_uniform, # pytype: disable=invalid-annotation # typed-keras\n **kwargs):\n super(GlobalEmbedding, self).__init__(**kwargs)\n self.total_vocab_size = total_vocab_size\n self.embedding_dim = embedding_dim\n self.mask_zero = mask_zero\n self.initializer = initializer\n\n def build(self, input_shape):\n self.embeddings = self.add_weight(\n shape=(self.total_vocab_size, self.embedding_dim),\n initializer=self.initializer,\n name='global_embedding',\n )\n\n def call(self, inputs):\n embedding_inputs = tf.where(inputs < self.total_vocab_size, inputs,\n tf.zeros_like(input=inputs))\n embeddings = tf.nn.embedding_lookup(self.embeddings, embedding_inputs)\n return tf.where(\n tf.expand_dims(inputs < self.total_vocab_size, axis=-1), embeddings,\n tf.zeros_like(input=embeddings))\n\n def compute_mask(self, inputs, mask=None):\n if not self.mask_zero:\n return None\n return tf.not_equal(inputs, 0)\n\n\nclass LocalEmbedding(tf.keras.layers.Layer):\n \"\"\"A custom Keras Embedding layer used for the local embeddings.\n\n The `LocalEmbedding`s correspond to embeddings of input size\n number of out of vocabulary buckets.\n These embeddings are reconstructed locally at the beginning of every round,\n and their updates never leave the device.\n \"\"\"\n\n def __init__(\n self,\n input_dim: int,\n embedding_dim: int,\n total_vocab_size: int,\n mask_zero: bool = True,\n initializer: tf.keras.initializers = tf.keras.initializers.random_uniform, # pytype: disable=invalid-annotation # typed-keras\n **kwargs):\n super(LocalEmbedding, self).__init__(**kwargs)\n self.input_dim = input_dim\n self.embedding_dim = embedding_dim\n self.mask_zero = mask_zero\n self.total_vocab_size = total_vocab_size\n self.initializer = initializer\n\n def build(self, input_shape):\n self.embeddings = self.add_weight(\n shape=(self.input_dim, self.embedding_dim),\n initializer=self.initializer,\n name='local_embedding',\n )\n\n def call(self, inputs):\n embedding_inputs = tf.where(inputs >= self.total_vocab_size,\n inputs - self.total_vocab_size,\n tf.zeros_like(input=inputs))\n embeddings = tf.nn.embedding_lookup(self.embeddings, embedding_inputs)\n return tf.where(\n tf.expand_dims(inputs >= self.total_vocab_size, axis=-1), embeddings,\n tf.zeros_like(input=embeddings))\n\n def compute_mask(self, inputs, mask=None):\n if not self.mask_zero:\n return None\n return tf.not_equal(inputs, 0)\n\n\ndef create_recurrent_reconstruction_model(\n vocab_size: int = 10000,\n num_oov_buckets: int = 1,\n embedding_size: int = 96,\n latent_size: int = 670,\n num_layers: int = 1,\n input_spec=None,\n global_variables_only: bool = False,\n name: str = 'rnn_recon_embeddings',\n) -> reconstruction_model.ReconstructionModel:\n \"\"\"Creates a recurrent model with a partially reconstructed embedding layer.\n\n Constructs a recurrent model for next word prediction, with the embedding\n layer divided in two parts:\n - A global_embedding, which shares its parameter updates with the server.\n - A locally reconstructed local_embedding layer, reconstructed at the\n beginning of every round, that never leaves the device. This local\n embedding layer corresponds to the out of vocabulary buckets.\n\n Args:\n vocab_size: Size of vocabulary to use.\n num_oov_buckets: Number of out of vocabulary buckets.\n embedding_size: The size of the embedding.\n latent_size: The size of the recurrent state.\n num_layers: The number of layers.\n input_spec: A structure of `tf.TensorSpec`s specifying the type of arguments\n the model expects. Notice this must be a compound structure of two\n elements, specifying both the data fed into the model to generate\n predictions, as its first element, as well as the expected type of the\n ground truth as its second.\n global_variables_only: If True, the returned `ReconstructionModel` contains\n all model variables as global variables. This can be useful for\n baselines involving aggregating all variables.\n name: (Optional) string to name the returned `tf.keras.Model`.\n\n Returns:\n `ReconstructionModel` tracking global and local variables for a recurrent\n model.\n \"\"\"\n\n if vocab_size < 0:\n raise ValueError('The vocab_size is expected to be greater than, or equal '\n 'to 0. Got {}'.format(vocab_size))\n\n if num_oov_buckets <= 0:\n raise ValueError('The number of out of vocabulary buckets is expected to '\n 'be greater than 0. Got {}'.format(num_oov_buckets))\n\n global_layers = []\n local_layers = []\n\n total_vocab_size = vocab_size + 3 # pad/bos/eos.\n extended_vocab_size = total_vocab_size + num_oov_buckets # pad/bos/eos + oov.\n inputs = tf.keras.layers.Input(shape=(None,), dtype=tf.int64)\n\n global_embedding = GlobalEmbedding(\n total_vocab_size=total_vocab_size,\n embedding_dim=embedding_size,\n mask_zero=True,\n name='global_embedding_layer')\n global_layers.append(global_embedding)\n\n local_embedding = LocalEmbedding(\n input_dim=num_oov_buckets,\n embedding_dim=embedding_size,\n total_vocab_size=total_vocab_size,\n mask_zero=True,\n name='local_embedding_layer')\n local_layers.append(local_embedding)\n\n projected = tf.keras.layers.Add()(\n [global_embedding(inputs),\n local_embedding(inputs)])\n\n for i in range(num_layers):\n layer = tf.keras.layers.LSTM(\n latent_size, return_sequences=True, name='lstm_' + str(i))\n global_layers.append(layer)\n processed = layer(projected)\n # A projection changes dimension from rnn_layer_size to\n # input_embedding_size.\n projection = tf.keras.layers.Dense(\n embedding_size, name='projection_' + str(i))\n global_layers.append(projection)\n projected = projection(processed)\n\n # We predict the OOV tokens as part of the output vocabulary.\n last_layer = tf.keras.layers.Dense(\n extended_vocab_size, activation=None, name='last_layer')\n global_layers.append(last_layer)\n logits = last_layer(projected)\n\n model = tf.keras.Model(inputs=inputs, outputs=logits, name=name)\n\n if input_spec is None:\n input_spec = collections.OrderedDict(\n x=tf.TensorSpec(shape=(None,), dtype=tf.int64),\n y=tf.TensorSpec(shape=(None,), dtype=tf.int64))\n\n # Merge local layers into global layers if needed.\n if global_variables_only:\n global_layers.extend(local_layers)\n local_layers = []\n\n return keras_utils.from_keras_model(\n keras_model=model,\n global_layers=global_layers,\n local_layers=local_layers,\n input_spec=input_spec)\n", "# Copyright 2021, 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\nimport tensorflow as tf\n\nfrom gans.experiments.emnist.preprocessing import filtered_emnist_data_utils\n\n\nclass FilteredEmnistDataUtilsTest(tf.test.TestCase):\n\n def test_get_filtered_client_data_for_training(self):\n filtered_emnist_data_utils.get_filtered_client_data_for_training(\n None, None, batch_size=10)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2021, 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\nimport os\nimport pandas as pd\nimport tensorflow as tf\nfrom fedopt_guide.stackoverflow_transformer import centralized_main\n\n\nclass CentralizedMainTest(tf.test.TestCase):\n\n def test_run_centralized(self):\n num_epochs = 1\n batch_size = 16\n root_output_dir = self.create_tempdir()\n exp_name = 'test_run_centralized'\n\n centralized_main.run_centralized(\n tf.keras.optimizers.SGD(learning_rate=0.01),\n num_epochs,\n batch_size,\n vocab_size=10,\n dim_embed=2,\n dim_model=2,\n dim_hidden=2,\n num_heads=1,\n num_layers=1,\n experiment_name=exp_name,\n root_output_dir=root_output_dir,\n max_batches=100)\n\n self.assertTrue(tf.io.gfile.exists(root_output_dir))\n log_dir = os.path.join(root_output_dir, 'logdir', exp_name)\n train_log_dir = os.path.join(log_dir, 'train')\n validation_log_dir = os.path.join(log_dir, 'validation')\n self.assertTrue(tf.io.gfile.exists(log_dir))\n self.assertTrue(tf.io.gfile.exists(train_log_dir))\n self.assertTrue(tf.io.gfile.exists(validation_log_dir))\n\n results_dir = os.path.join(root_output_dir, 'results', exp_name)\n self.assertTrue(tf.io.gfile.exists(results_dir))\n metrics_file = os.path.join(results_dir, 'metric_results.csv')\n self.assertTrue(tf.io.gfile.exists(metrics_file))\n\n metrics_csv = pd.read_csv(metrics_file)\n self.assertLen(\n metrics_csv.index,\n num_epochs,\n msg='The output metrics CSV should have {} rows, equal to the number of'\n 'training epochs.'.format(num_epochs))\n\n self.assertIn(\n 'loss',\n metrics_csv.columns,\n msg='The output metrics CSV should have a column \"loss\" if training is'\n 'successful.')\n self.assertIn(\n 'val_loss',\n metrics_csv.columns,\n msg='The output metrics CSV should have a column \"val_loss\" if '\n 'validation metric computation is successful.')\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# 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\nimport collections\nimport os\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nfrom fedopt_guide import training_loop\n\n_Batch = collections.namedtuple('Batch', ['x', 'y'])\n\n_COMPATIBILITY_ERROR_MESSAGE = (\n 'The iterative_process argument must be of '\n 'type`tff.templates.IterativeProcess`, and must have an '\n 'attribute `get_model_weights`, which must be a `tff.Computation`. This '\n 'computation must accept as input the state of `iterative_process`, and '\n 'its output must be a nested structure of tensors matching the expected '\n 'shape of the first input argument to `evaluation_fn`.')\n\n\ndef _keras_model_builder():\n # Create a simple linear regression model, single output.\n model = tf.keras.Sequential([\n tf.keras.layers.Dense(\n 1,\n kernel_initializer='zeros',\n bias_initializer='zeros',\n input_shape=(1,))\n ])\n return model\n\n\ndef _compiled_keras_model_builder():\n model = _keras_model_builder()\n model.compile(loss=tf.keras.losses.MeanSquaredError())\n return model\n\n\ndef _create_tf_dataset_for_client(client_id, batch_data=True):\n # Create client data for y = 2*x+3\n np.random.seed(client_id)\n x = np.random.rand(6, 1).astype(np.float32)\n y = 2 * x + 3\n dataset = tf.data.Dataset.from_tensor_slices(\n collections.OrderedDict([('x', x), ('y', y)]))\n if batch_data:\n dataset = dataset.batch(2)\n return dataset\n\n\ndef _get_input_spec():\n return _create_tf_dataset_for_client(0).element_spec\n\n\ndef _tff_model_fn():\n return tff.learning.from_keras_model(\n keras_model=_keras_model_builder(),\n input_spec=_get_input_spec(),\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=[tf.keras.metrics.MeanSquaredError()])\n\n\ndef _build_federated_averaging_process():\n return tff.learning.build_federated_averaging_process(\n _tff_model_fn,\n client_optimizer_fn=tf.keras.optimizers.SGD,\n server_optimizer_fn=tf.keras.optimizers.SGD)\n\n\ndef _evaluation_fn():\n fed_eval_fn = tff.learning.build_federated_evaluation(_tff_model_fn)\n fed_data = _federated_data()\n\n def eval_fn(model, round_num):\n del round_num\n return fed_eval_fn(model, fed_data)\n\n return eval_fn\n\n\ndef _federated_data():\n return [_create_tf_dataset_for_client(1), _create_tf_dataset_for_client(2)]\n\n\nclass TrainingLoopArgumentsTest(tf.test.TestCase):\n\n def test_raises_non_iterative_process(self):\n bad_iterative_process = _build_federated_averaging_process().next\n\n def client_datasets_fn(round_num):\n del round_num\n return _federated_data()\n\n def evaluation_fn(model, round_num):\n del model, round_num\n return {}\n\n root_output_dir = self.get_temp_dir()\n with self.assertRaises(TypeError):\n training_loop.run(\n iterative_process=[bad_iterative_process],\n train_client_datasets_fn=client_datasets_fn,\n evaluation_fn=evaluation_fn,\n total_rounds=10,\n experiment_name='non_iterative_process',\n root_output_dir=root_output_dir)\n\n def test_raises_non_callable_train_client_dataset(self):\n iterative_process = _build_federated_averaging_process()\n client_dataset = _create_tf_dataset_for_client(3)\n\n def evaluation_fn(model, round_num):\n del model, round_num\n return {}\n\n root_output_dir = self.get_temp_dir()\n with self.assertRaises(TypeError):\n training_loop.run(\n iterative_process=iterative_process,\n train_client_datasets_fn=client_dataset,\n evaluation_fn=evaluation_fn,\n total_rounds=10,\n experiment_name='non_callable_client_dataset',\n root_output_dir=root_output_dir)\n\n def test_raises_non_callable_evaluate_fn(self):\n iterative_process = _build_federated_averaging_process()\n\n def client_datasets_fn(round_num):\n del round_num\n return _federated_data()\n\n metrics_dict = {}\n root_output_dir = self.get_temp_dir()\n with self.assertRaises(TypeError):\n training_loop.run(\n iterative_process=iterative_process,\n train_client_datasets_fn=client_datasets_fn,\n evaluation_fn=metrics_dict,\n total_rounds=10,\n experiment_name='non_callable_evaluate',\n root_output_dir=root_output_dir)\n\n def test_raises_non_str_output_dir(self):\n iterative_process = _build_federated_averaging_process()\n\n def client_datasets_fn(round_num):\n del round_num\n return _federated_data()\n\n def evaluation_fn(model, round_num):\n del model, round_num\n return {}\n\n with self.assertRaises(TypeError):\n training_loop.run(\n iterative_process=iterative_process,\n train_client_datasets_fn=client_datasets_fn,\n evaluation_fn=evaluation_fn,\n total_rounds=10,\n experiment_name='non_str_output_dir',\n root_output_dir=1)\n\n def test_raises_no_get_model_weights_attribute_in_state(self):\n\n class BadIterativeProcess(tff.templates.IterativeProcess):\n\n def __init__(self):\n pass\n\n def initialize(self):\n return {}\n\n def next(self, state, data):\n return {}\n\n iterative_process = BadIterativeProcess()\n\n def client_datasets_fn(round_num):\n del round_num\n return _federated_data()\n\n def evaluation_fn(model, round_num):\n del model, round_num\n return {}\n\n with self.assertRaisesRegex(\n training_loop.IterativeProcessCompatibilityError,\n _COMPATIBILITY_ERROR_MESSAGE):\n training_loop.run(\n iterative_process=iterative_process,\n train_client_datasets_fn=client_datasets_fn,\n evaluation_fn=evaluation_fn,\n total_rounds=10,\n experiment_name='bad_iterative_process')\n\n def test_raises_non_callable_get_model_weights_attribute(self):\n\n class BadIterativeProcess(tff.templates.IterativeProcess):\n\n def __init__(self):\n pass\n\n def initialize(self):\n return {}\n\n def next(self, state, data):\n return {}\n\n iterative_process = BadIterativeProcess()\n iterative_process.get_model_weights = 2\n\n def client_datasets_fn(round_num):\n del round_num\n return _federated_data()\n\n def evaluation_fn(model, round_num):\n del model, round_num\n return {}\n\n with self.assertRaisesRegex(\n training_loop.IterativeProcessCompatibilityError,\n _COMPATIBILITY_ERROR_MESSAGE):\n training_loop.run(\n iterative_process=iterative_process,\n train_client_datasets_fn=client_datasets_fn,\n evaluation_fn=evaluation_fn,\n total_rounds=10,\n experiment_name='bad_iterative_process')\n\n def test_raises_non_tff_computation_get_model_weights_attribute(self):\n\n class BadIterativeProcess(tff.templates.IterativeProcess):\n\n def __init__(self):\n pass\n\n def initialize(self):\n return {}\n\n def next(self, state, data):\n return {}\n\n def get_model_weights(self, state):\n return {}\n\n iterative_process = BadIterativeProcess()\n\n def client_datasets_fn(round_num):\n del round_num\n return _federated_data()\n\n def evaluation_fn(model, round_num):\n del model, round_num\n return {}\n\n with self.assertRaisesRegex(\n training_loop.IterativeProcessCompatibilityError,\n _COMPATIBILITY_ERROR_MESSAGE):\n\n training_loop.run(\n iterative_process=iterative_process,\n train_client_datasets_fn=client_datasets_fn,\n evaluation_fn=evaluation_fn,\n total_rounds=10,\n experiment_name='bad_iterative_process')\n\n\nclass ExperimentRunnerTest(tf.test.TestCase):\n\n def test_fedavg_training_decreases_loss(self):\n iterative_process = _build_federated_averaging_process()\n\n def client_datasets_fn(round_num):\n del round_num\n return _federated_data()\n\n def test_fn(model):\n keras_model = _compiled_keras_model_builder()\n model.assign_weights_to(keras_model)\n batch = next(iter(_create_tf_dataset_for_client(5)))\n return {'loss': keras_model.evaluate(batch['x'], batch['y'])}\n\n initial_state = iterative_process.initialize()\n initial_model = iterative_process.get_model_weights(initial_state)\n\n root_output_dir = self.get_temp_dir()\n final_state = training_loop.run(\n iterative_process=iterative_process,\n train_client_datasets_fn=client_datasets_fn,\n evaluation_fn=_evaluation_fn(),\n total_rounds=1,\n experiment_name='fedavg_decreases_loss',\n root_output_dir=root_output_dir)\n final_model = iterative_process.get_model_weights(final_state)\n self.assertLess(\n test_fn(final_model)['loss'],\n test_fn(initial_model)['loss'])\n\n def test_checkpoint_manager_saves_state(self):\n experiment_name = 'checkpoint_manager_saves_state'\n iterative_process = _build_federated_averaging_process()\n\n def client_datasets_fn(round_num):\n del round_num\n return _federated_data()\n\n def evaluation_fn(model, round_num):\n del model, round_num\n return {}\n\n root_output_dir = self.get_temp_dir()\n final_state = training_loop.run(\n iterative_process=iterative_process,\n train_client_datasets_fn=client_datasets_fn,\n evaluation_fn=evaluation_fn,\n total_rounds=1,\n experiment_name=experiment_name,\n root_output_dir=root_output_dir)\n final_model = iterative_process.get_model_weights(final_state)\n\n ckpt_manager = tff.simulation.FileCheckpointManager(\n os.path.join(root_output_dir, 'checkpoints', experiment_name))\n restored_state, restored_round = ckpt_manager.load_latest_checkpoint(\n final_state)\n\n self.assertEqual(restored_round, 0)\n\n keras_model = _compiled_keras_model_builder()\n restored_model = iterative_process.get_model_weights(restored_state)\n\n restored_model.assign_weights_to(keras_model)\n batch = next(iter(_create_tf_dataset_for_client(5)))\n restored_loss = keras_model.test_on_batch(batch['x'], batch['y'])\n\n final_model.assign_weights_to(keras_model)\n final_loss = keras_model.test_on_batch(batch['x'], batch['y'])\n self.assertEqual(final_loss, restored_loss)\n\n def test_fn_writes_metrics(self):\n experiment_name = 'test_metrics'\n iterative_process = _build_federated_averaging_process()\n\n def client_datasets_fn(round_num):\n del round_num\n return _federated_data()\n\n def test_fn(model):\n keras_model = _compiled_keras_model_builder()\n model.assign_weights_to(keras_model)\n batch = next(iter(_create_tf_dataset_for_client(5)))\n return {'loss': keras_model.evaluate(batch['x'], batch['y'])}\n\n root_output_dir = self.get_temp_dir()\n training_loop.run(\n iterative_process=iterative_process,\n train_client_datasets_fn=client_datasets_fn,\n evaluation_fn=_evaluation_fn(),\n total_rounds=1,\n experiment_name=experiment_name,\n root_output_dir=root_output_dir,\n rounds_per_eval=10,\n test_fn=test_fn)\n\n csv_file = os.path.join(root_output_dir, 'results', experiment_name,\n 'experiment.metrics.csv')\n metrics_manager = tff.simulation.CSVMetricsManager(csv_file)\n fieldnames, metrics = metrics_manager.get_metrics()\n self.assertLen(metrics, 2)\n self.assertIn('test/loss', fieldnames)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2019, 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\"\"\"Test the GAN evaluation metrics for EMNIST.\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom gans.experiments.emnist import emnist_data_utils\nfrom gans.experiments.emnist.classifier import emnist_classifier_model as ecm\n\nfrom gans.experiments.emnist.eval import emnist_eval_util as eeu\n\n\nclass EmnistEvalUtilTest(tf.test.TestCase):\n\n def setUp(self):\n super().setUp()\n client_data = emnist_data_utils.create_real_images_tff_client_data(\n split='synthetic')\n images_ds = client_data.create_tf_dataset_for_client(\n client_data.client_ids[0])\n images_ds = emnist_data_utils.preprocess_img_dataset(\n images_ds, shuffle=False)\n images_ds_iterator = iter(images_ds)\n self.real_images = next(images_ds_iterator)\n\n np.random.seed(seed=123456)\n self.fake_images = tf.constant(\n np.random.random((32, 28, 28, 1)), dtype=tf.float32)\n\n def test_emnist_score(self):\n score = eeu.emnist_score(self.fake_images,\n ecm.get_trained_emnist_classifier_model())\n self.assertAllClose(score, 1.1598, rtol=0.0001, atol=0.0001)\n\n score = eeu.emnist_score(self.real_images,\n ecm.get_trained_emnist_classifier_model())\n self.assertAllClose(score, 3.9547, rtol=0.0001, atol=0.0001)\n\n def test_emnist_frechet_distance(self):\n distance = eeu.emnist_frechet_distance(\n self.real_images, self.fake_images,\n ecm.get_trained_emnist_classifier_model())\n self.assertAllClose(distance, 568.6883, rtol=0.0001, atol=0.0001)\n\n distance = eeu.emnist_frechet_distance(\n self.real_images, self.real_images,\n ecm.get_trained_emnist_classifier_model())\n self.assertAllClose(distance, 0.0)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2019, 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\"\"\"An implementation of the Targeted Attacks in Federated Learning.\n\nThis is intended to implement and simulate existing targeted attacks in\nfederated learning systems. Most of the implementations are based on\n'tff.ressearch.basedline_fedavg'. Similar simulation scripts can be used by\nreplacing relevant functions and plugging-in correct parameters.\n\nBased on the following papers:\n\nAnalyzing Federated Learning through an Adversarial Lens\n Arjun Nitin Bhagoji, Supriyo Chakraborty, Prateek Mittal,\n Seraphin Calo ICML 2019.\n https://arxiv.org/abs/1811.12470\n\nHow To Back door Federated Learning\n Eugene Bagdasaryan, Andreas Veit, Yiqing Hua, Deborah Estrin,\n Vitaly Shmatikov\n https://arxiv.org/abs/1807.00459\n\"\"\"\n\nimport collections\n\nimport attr\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\n\[email protected](eq=False, frozen=True)\nclass ClientOutput(object):\n \"\"\"Structure for outputs returned from clients during federated optimization.\n\n Fields:\n - `weights_delta`: A dictionary of updates to the model's trainable\n variables.\n - `weights_delta_weight`: Weight to be used in a weighted mean when\n aggregating `weights_delta`.\n - `model_output`: A structure matching\n `tff.learning.Model.report_local_outputs`, reflecting the results of\n training on the input dataset.\n - `optimizer_output`: Additional metrics or other outputs defined by the\n optimizer.\n \"\"\"\n weights_delta = attr.ib()\n weights_delta_weight = attr.ib()\n model_output = attr.ib()\n optimizer_output = attr.ib()\n\n\[email protected](eq=False, frozen=True)\nclass ServerState(object):\n \"\"\"Structure for state on the server.\n\n Fields:\n - `model`: A dictionary of model's trainable variables.\n - `optimizer_state`: Variables of optimizer.\n \"\"\"\n model = attr.ib()\n optimizer_state = attr.ib()\n delta_aggregate_state = attr.ib()\n\n\ndef _create_optimizer_vars(model, optimizer):\n model_weights = _get_weights(model)\n delta = tf.nest.map_structure(tf.zeros_like, model_weights.trainable)\n grads_and_vars = tf.nest.map_structure(\n lambda x, v: (-1.0 * x, v), tf.nest.flatten(delta),\n tf.nest.flatten(model_weights.trainable))\n optimizer.apply_gradients(grads_and_vars, name='server_update')\n return optimizer.variables()\n\n\ndef _get_weights(model):\n return tff.learning.framework.ModelWeights.from_model(model)\n\n\ndef _get_norm(weights):\n \"\"\"Compute the norm of a weight matrix.\n\n Args:\n weights: a OrderedDict specifying weight matrices at different layers.\n\n Returns:\n The norm of all layer weight matrices.\n \"\"\"\n return tf.linalg.global_norm(tf.nest.flatten(weights))\n\n\[email protected]\ndef server_update(model, server_optimizer, server_optimizer_vars, server_state,\n weights_delta, new_delta_aggregate_state):\n \"\"\"Updates `server_state` based on `weights_delta`.\n\n Args:\n model: A `tff.learning.Model`.\n server_optimizer: A `tf.keras.optimizers.Optimizer`.\n server_optimizer_vars: A list of previous variables of server_optimzer.\n server_state: A `ServerState`, the state to be updated.\n weights_delta: An update to the trainable variables of the model.\n new_delta_aggregate_state: An update to the server state.\n\n Returns:\n An updated `ServerState`.\n \"\"\"\n model_weights = _get_weights(model)\n tf.nest.map_structure(lambda a, b: a.assign(b),\n (model_weights, server_optimizer_vars),\n (server_state.model, server_state.optimizer_state))\n\n grads_and_vars = tf.nest.map_structure(\n lambda x, v: (-1.0 * x, v), tf.nest.flatten(weights_delta),\n tf.nest.flatten(model_weights.trainable))\n server_optimizer.apply_gradients(grads_and_vars, name='server_update')\n\n return tff.structure.update_struct(\n server_state,\n model=model_weights,\n optimizer_state=server_optimizer_vars,\n delta_aggregate_state=new_delta_aggregate_state)\n\n\nclass ClientExplicitBoosting:\n \"\"\"Client tensorflow logic for explicit boosting.\"\"\"\n\n def __init__(self, boost_factor):\n \"\"\"Specify the boosting parameter.\n\n Args:\n boost_factor: A 'tf.float32' specifying how malicious update is boosted.\n \"\"\"\n self.boost_factor = boost_factor\n\n @tf.function\n def __call__(self, model, optimizer, benign_dataset, malicious_dataset,\n client_type, initial_weights):\n \"\"\"Updates client model with client potentially being malicious.\n\n Args:\n model: A `tff.learning.Model`.\n optimizer: A 'tf.keras.optimizers.Optimizer'.\n benign_dataset: A 'tf.data.Dataset' consisting of benign dataset.\n malicious_dataset: A 'tf.data.Dataset' consisting of malicious dataset.\n client_type: A 'tf.bool' indicating whether the client is malicious; iff\n `True` the client will construct its update using `malicious_dataset`,\n otherwise will construct the update using `benign_dataset`.\n initial_weights: A `tff.learning.Model.weights` from server.\n\n Returns:\n A 'ClientOutput`.\n \"\"\"\n model_weights = _get_weights(model)\n\n @tf.function\n def reduce_fn(num_examples_sum, batch):\n \"\"\"Runs `tff.learning.Model.train_on_batch` on local client batch.\"\"\"\n with tf.GradientTape() as tape:\n output = model.forward_pass(batch)\n gradients = tape.gradient(output.loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n return num_examples_sum + tf.shape(output.predictions)[0]\n\n @tf.function\n def compute_benign_update():\n \"\"\"compute benign update sent back to the server.\"\"\"\n tf.nest.map_structure(lambda a, b: a.assign(b), model_weights,\n initial_weights)\n\n num_examples_sum = benign_dataset.reduce(\n initial_state=tf.constant(0), reduce_func=reduce_fn)\n\n weights_delta_benign = tf.nest.map_structure(lambda a, b: a - b,\n model_weights.trainable,\n initial_weights.trainable)\n\n aggregated_outputs = model.report_local_outputs()\n\n return weights_delta_benign, aggregated_outputs, num_examples_sum\n\n @tf.function\n def compute_malicious_update():\n \"\"\"compute malicious update sent back to the server.\"\"\"\n result = compute_benign_update()\n weights_delta_benign, aggregated_outputs, num_examples_sum = result\n\n tf.nest.map_structure(lambda a, b: a.assign(b), model_weights,\n initial_weights)\n\n malicious_dataset.reduce(\n initial_state=tf.constant(0), reduce_func=reduce_fn)\n\n weights_delta_malicious = tf.nest.map_structure(lambda a, b: a - b,\n model_weights.trainable,\n initial_weights.trainable)\n\n weights_delta = tf.nest.map_structure(\n tf.add, weights_delta_benign,\n tf.nest.map_structure(lambda delta: delta * self.boost_factor,\n weights_delta_malicious))\n\n return weights_delta, aggregated_outputs, num_examples_sum\n\n result = tf.cond(\n tf.equal(client_type, True), compute_malicious_update,\n compute_benign_update)\n weights_delta, aggregated_outputs, num_examples_sum = result\n\n weights_delta_weight = tf.cast(num_examples_sum, tf.float32)\n\n weight_norm = _get_norm(weights_delta)\n\n return ClientOutput(\n weights_delta, weights_delta_weight, aggregated_outputs,\n collections.OrderedDict({\n 'num_examples': num_examples_sum,\n 'weight_norm': weight_norm,\n }))\n\n\ndef build_server_init_fn(model_fn, server_optimizer_fn,\n aggregation_process_init):\n \"\"\"Builds a `tff.Computation` that returns initial `ServerState`.\n\n Args:\n model_fn: A no-arg function that returns a `tff.learning.Model`.\n server_optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer`.\n aggregation_process_init: A `tff.Computation` that initializes the\n aggregator state.\n\n Returns:\n A `tff.tf_computation` that returns initial `ServerState`.\n \"\"\"\n\n @tff.tf_computation\n def server_init_tf():\n model = model_fn()\n server_optimizer = server_optimizer_fn()\n # Create optimizer variables so we have a place to assign the optimizer's\n # state.\n server_optimizer_vars = _create_optimizer_vars(model, server_optimizer)\n return _get_weights(model), server_optimizer_vars\n\n @tff.federated_computation\n def server_init():\n initial_model, server_optimizer_state = tff.federated_eval(\n server_init_tf, tff.SERVER)\n return tff.federated_zip(\n ServerState(\n model=initial_model,\n optimizer_state=server_optimizer_state,\n delta_aggregate_state=aggregation_process_init()))\n\n return server_init\n\n\ndef build_server_update_fn(model_fn, server_optimizer_fn, server_state_type,\n model_weights_type):\n \"\"\"Builds a `tff.tf_computation` that updates `ServerState`.\n\n Args:\n model_fn: A no-arg function that returns a `tff.learning.Model`.\n server_optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer`.\n server_state_type: type_signature of server state.\n model_weights_type: type_signature of model weights.\n\n Returns:\n A `tff.tf_computation` that updates `ServerState`.\n \"\"\"\n\n @tff.tf_computation(server_state_type, model_weights_type.trainable,\n server_state_type.delta_aggregate_state)\n def server_update_tf(server_state, model_delta, new_delta_aggregate_state):\n \"\"\"Updates the `server_state`.\n\n Args:\n server_state: The `ServerState`.\n model_delta: The model difference from clients.\n new_delta_aggregate_state: An update to the server state.\n\n Returns:\n The updated `ServerState`.\n \"\"\"\n model = model_fn()\n server_optimizer = server_optimizer_fn()\n # Create optimizer variables so we have a place to assign the optimizer's\n # state.\n server_optimizer_vars = _create_optimizer_vars(model, server_optimizer)\n\n return server_update(model, server_optimizer, server_optimizer_vars,\n server_state, model_delta, new_delta_aggregate_state)\n\n return server_update_tf\n\n\ndef build_client_update_fn(model_fn, optimizer_fn, client_update_tf,\n tf_dataset_type, model_weights_type):\n \"\"\"Builds a `tff.tf_computation` in the presense of malicious clients.\n\n Args:\n model_fn: A no-arg function that returns a `tff.learning.Model`.\n optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer`.\n client_update_tf: A 'tf.function' that computes the ClientOutput\n tf_dataset_type: type_signature of dataset.\n model_weights_type: type_signature of model weights.\n\n Returns:\n A `tff.tf_computation` for local model optimization with type signature:\n '@tff.tf_computation(tf_dataset_type, tf_dataset_type,\n tf.bool, model_weights_type)'\n \"\"\"\n\n @tff.tf_computation(tf_dataset_type, tf_dataset_type, tf.bool,\n model_weights_type)\n def client_delta_tf(benign_dataset, malicious_dataset, client_type,\n initial_model_weights):\n \"\"\"Performs client local model optimization.\n\n Args:\n benign_dataset: A 'tf.data.Dataset' consisting of benign dataset\n malicious_dataset: A 'tf.data.Dataset' consisting of malicious dataset\n client_type: A 'tf.bool' indicating whether the client is malicious\n initial_model_weights: A `tff.learning.Model.weights` from server.\n\n Returns:\n A 'ClientOutput`.\n \"\"\"\n # Create variables here in the graph context, before calling the tf.function\n # below.\n model = model_fn()\n optimizer = optimizer_fn()\n return client_update_tf(model, optimizer, benign_dataset, malicious_dataset,\n client_type, initial_model_weights)\n\n return client_delta_tf\n\n\ndef build_run_one_round_fn_attacked(server_update_fn, client_update_fn,\n aggregation_process,\n dummy_model_for_metadata,\n federated_server_state_type,\n federated_dataset_type):\n \"\"\"Builds a `tff.federated_computation` for a round of training.\n\n Args:\n server_update_fn: A function for updates in the server.\n client_update_fn: A function for updates in the clients.\n aggregation_process: A 'tff.templates.AggregationProcess' that takes in\n model deltas placed@CLIENTS to an aggregated model delta placed@SERVER.\n dummy_model_for_metadata: A dummy `tff.learning.Model`.\n federated_server_state_type: type_signature of federated server state.\n federated_dataset_type: type_signature of federated dataset.\n\n Returns:\n A `tff.federated_computation` for a round of training.\n \"\"\"\n\n federated_bool_type = tff.type_at_clients(tf.bool)\n\n @tff.federated_computation(federated_server_state_type,\n federated_dataset_type, federated_dataset_type,\n federated_bool_type)\n def run_one_round(server_state, federated_dataset, malicious_dataset,\n malicious_clients):\n \"\"\"Orchestration logic for one round of computation.\n\n Args:\n server_state: A `ServerState`.\n federated_dataset: A federated `tf.Dataset` with placement `tff.CLIENTS`.\n malicious_dataset: A federated `tf.Dataset` with placement `tff.CLIENTS`.\n consisting of malicious datasets.\n malicious_clients: A federated `tf.bool` with placement `tff.CLIENTS`.\n\n Returns:\n A tuple of updated `ServerState` and the result of\n `tff.learning.Model.federated_output_computation`.\n \"\"\"\n\n client_model = tff.federated_broadcast(server_state.model)\n\n client_outputs = tff.federated_map(\n client_update_fn,\n (federated_dataset, malicious_dataset, malicious_clients, client_model))\n\n weight_denom = client_outputs.weights_delta_weight\n\n if aggregation_process.is_weighted:\n aggregate_output = aggregation_process.next(\n server_state.delta_aggregate_state,\n client_outputs.weights_delta,\n weight=weight_denom)\n else:\n aggregate_output = aggregation_process.next(\n server_state.delta_aggregate_state, client_outputs.weights_delta)\n new_delta_aggregate_state = aggregate_output.state\n round_model_delta = aggregate_output.result\n\n server_state = tff.federated_map(\n server_update_fn,\n (server_state, round_model_delta, new_delta_aggregate_state))\n\n aggregated_outputs = dummy_model_for_metadata.federated_output_computation(\n client_outputs.model_output)\n if isinstance(aggregated_outputs.type_signature, tff.StructType):\n aggregated_outputs = tff.federated_zip(aggregated_outputs)\n\n return server_state, aggregated_outputs\n\n return run_one_round\n\n\ndef build_federated_averaging_process_attacked(\n model_fn,\n client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.1),\n server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0),\n model_update_aggregation_factory=None,\n client_update_tf=ClientExplicitBoosting(boost_factor=1.0)):\n \"\"\"Builds the TFF computations for optimization using federated averaging with potentially malicious clients.\n\n Args:\n model_fn: A no-arg function that returns a `tff.learning.Model`.\n client_optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer`, use during local client training.\n server_optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer`, use to apply updates to the global model.\n model_update_aggregation_factory: An optional\n `tff.aggregators.AggregationFactory` that contstructs\n `tff.templates.AggregationProcess` for aggregating the client model\n updates on the server. If `None`, uses a default constructed\n `tff.aggregators.MeanFactory`, creating a stateless mean aggregation.\n client_update_tf: a 'tf.function' computes the ClientOutput.\n\n Returns:\n A `tff.templates.IterativeProcess`.\n \"\"\"\n with tf.Graph().as_default():\n dummy_model_for_metadata = model_fn()\n weights_type = tff.learning.framework.weights_type_from_model(\n dummy_model_for_metadata)\n\n if model_update_aggregation_factory is None:\n model_update_aggregation_factory = tff.aggregators.MeanFactory()\n\n if isinstance(model_update_aggregation_factory,\n tff.aggregators.WeightedAggregationFactory):\n aggregation_process = model_update_aggregation_factory.create(\n weights_type.trainable, tff.TensorType(tf.float32))\n else:\n aggregation_process = model_update_aggregation_factory.create(\n weights_type.trainable)\n\n server_init = build_server_init_fn(model_fn, server_optimizer_fn,\n aggregation_process.initialize)\n server_state_type = server_init.type_signature.result.member\n server_update_fn = build_server_update_fn(model_fn, server_optimizer_fn,\n server_state_type,\n server_state_type.model)\n tf_dataset_type = tff.SequenceType(dummy_model_for_metadata.input_spec)\n\n client_update_fn = build_client_update_fn(model_fn, client_optimizer_fn,\n client_update_tf, tf_dataset_type,\n server_state_type.model)\n\n federated_server_state_type = tff.type_at_server(server_state_type)\n\n federated_dataset_type = tff.type_at_clients(tf_dataset_type)\n\n run_one_round_tff = build_run_one_round_fn_attacked(\n server_update_fn, client_update_fn, aggregation_process,\n dummy_model_for_metadata, federated_server_state_type,\n federated_dataset_type)\n\n return tff.templates.IterativeProcess(\n initialize_fn=server_init, next_fn=run_one_round_tff)\n\n\nclass ClientProjectBoost:\n \"\"\"Client tensorflow logic for norm bounded attack.\"\"\"\n\n def __init__(self, boost_factor, norm_bound, round_num):\n \"\"\"Specify the attacking parameter.\n\n Args:\n boost_factor: A 'tf.float32' specifying how malicious update is boosted.\n norm_bound: A 'tf.float32' specifying the norm bound before boosting.\n round_num: A 'tf.int32' specifying the number of iterative rounds.\n \"\"\"\n self.boost_factor = boost_factor\n self.norm_bound = norm_bound\n self.round_num = round_num\n\n @tf.function\n def __call__(self, model, optimizer, benign_dataset, malicious_dataset,\n client_is_malicious, initial_weights):\n \"\"\"Updates client model with client potentially being malicious.\n\n Args:\n model: A `tff.learning.Model`.\n optimizer: A 'tf.keras.optimizers.Optimizer'.\n benign_dataset: A 'tf.data.Dataset' consisting of benign dataset.\n malicious_dataset: A 'tf.data.Dataset' consisting of malicious dataset.\n client_is_malicious: A 'tf.bool' showing whether the client is malicious.\n initial_weights: A `tff.learning.Model.weights` from server.\n\n Returns:\n A 'ClientOutput`.\n \"\"\"\n model_weights = _get_weights(model)\n\n @tf.function\n def clip_by_norm(gradient, norm):\n \"\"\"Clip the gradient by its l2 norm.\"\"\"\n norm = tf.cast(norm, tf.float32)\n delta_norm = _get_norm(gradient)\n\n if delta_norm < norm:\n return gradient\n else:\n delta_mul_factor = tf.math.divide_no_nan(norm, delta_norm)\n return tf.nest.map_structure(lambda g: g * delta_mul_factor, gradient)\n\n @tf.function\n def project_weights(weights, initial_weights, norm):\n \"\"\"Project the weight onto l2 ball around initial_weights with radius norm.\"\"\"\n weights_delta = tf.nest.map_structure(lambda a, b: a - b, weights,\n initial_weights)\n\n return tf.nest.map_structure(tf.add, clip_by_norm(weights_delta, norm),\n initial_weights)\n\n @tf.function\n def reduce_fn(num_examples_sum, batch):\n \"\"\"Runs `tff.learning.Model.train_on_batch` on local client batch.\"\"\"\n with tf.GradientTape() as tape:\n output = model.forward_pass(batch)\n gradients = tape.gradient(output.loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n return num_examples_sum + tf.shape(output.predictions)[0]\n\n @tf.function\n def compute_benign_update():\n \"\"\"compute benign update sent back to the server.\"\"\"\n tf.nest.map_structure(lambda a, b: a.assign(b), model_weights,\n initial_weights)\n\n num_examples_sum = benign_dataset.reduce(\n initial_state=tf.constant(0), reduce_func=reduce_fn)\n\n weights_delta_benign = tf.nest.map_structure(lambda a, b: a - b,\n model_weights.trainable,\n initial_weights.trainable)\n\n aggregated_outputs = model.report_local_outputs()\n\n return weights_delta_benign, aggregated_outputs, num_examples_sum\n\n @tf.function\n def compute_malicious_update():\n \"\"\"compute malicious update sent back to the server.\"\"\"\n\n _, aggregated_outputs, num_examples_sum = compute_benign_update()\n\n tf.nest.map_structure(lambda a, b: a.assign(b), model_weights,\n initial_weights)\n\n for _ in range(self.round_num):\n benign_dataset.reduce(\n initial_state=tf.constant(0), reduce_func=reduce_fn)\n malicious_dataset.reduce(\n initial_state=tf.constant(0), reduce_func=reduce_fn)\n\n tf.nest.map_structure(\n lambda a, b: a.assign(b), model_weights.trainable,\n project_weights(model_weights.trainable, initial_weights.trainable,\n tf.cast(self.norm_bound, tf.float32)))\n\n weights_delta_malicious = tf.nest.map_structure(lambda a, b: a - b,\n model_weights.trainable,\n initial_weights.trainable)\n weights_delta = tf.nest.map_structure(\n lambda update: self.boost_factor * update, weights_delta_malicious)\n\n return weights_delta, aggregated_outputs, num_examples_sum\n\n if client_is_malicious:\n result = compute_malicious_update()\n else:\n result = compute_benign_update()\n weights_delta, aggregated_outputs, num_examples_sum = result\n\n weights_delta_weight = tf.cast(num_examples_sum, tf.float32)\n weight_norm = _get_norm(weights_delta)\n\n return ClientOutput(\n weights_delta, weights_delta_weight, aggregated_outputs,\n collections.OrderedDict({\n 'num_examples': num_examples_sum,\n 'weight_norm': weight_norm,\n }))\n", "# Copyright 2021, 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\nimport itertools\nimport os.path\n\nfrom absl.testing import parameterized\nimport pandas as pd\nimport tensorflow as tf\n\nfrom generalization.utils import centralized_training_loop\nfrom generalization.utils import metric_utils\n\n\ndef create_dataset():\n # Create a dataset with 4 examples:\n dataset = tf.data.Dataset.from_tensor_slices((\n [\n [1.0, 2.0],\n [3.0, 4.0],\n ],\n [\n [5.0],\n [6.0],\n ],\n ))\n # Repeat the dataset 2 times with batches of 3 examples,\n # producing 3 minibatches (the last one with only 2 examples).\n return dataset.repeat(3).batch(2)\n\n\ndef create_sequential_model(input_dims=2):\n dense_layer = tf.keras.layers.Dense(\n 1,\n kernel_initializer='zeros',\n bias_initializer='zeros',\n input_shape=(input_dims,),\n name='dense') # specify names to facilitate testing.\n return tf.keras.Sequential([dense_layer], name='sequential')\n\n\ndef compiled_keras_model(input_dims=2,\n optimizer=tf.keras.optimizers.SGD(learning_rate=0.01)):\n model = create_sequential_model(input_dims)\n model.compile(\n loss=tf.keras.losses.MeanSquaredError(),\n optimizer=optimizer,\n metrics=[tf.keras.metrics.MeanSquaredError()])\n return model\n\n\nclass CentralizedTrainingLoopTest(tf.test.TestCase, parameterized.TestCase):\n\n def assertMetricDecreases(self, metric, expected_len):\n self.assertLen(metric, expected_len)\n self.assertLess(metric[-1], metric[0])\n\n @parameterized.named_parameters(\n ('train_train_eval={},train_val={},val={}'.format(*eval_fn_bools),\n *eval_fn_bools)\n for eval_fn_bools in itertools.product([False, True], repeat=3))\n def test_training_reduces_loss(self, use_part_train_eval_fn, use_part_val_fn,\n use_unpart_fn):\n keras_model = compiled_keras_model()\n dataset = create_dataset()\n eval_fn = lambda model: model.evaluate(dataset, return_dict=True, verbose=0)\n\n part_train_eval_fn = eval_fn if use_part_train_eval_fn else None\n part_val_fn = eval_fn if use_part_val_fn else None\n unpart_fn = eval_fn if use_unpart_fn else None\n\n history = centralized_training_loop.run(\n keras_model=keras_model,\n train_dataset=dataset,\n part_train_eval_fn=part_train_eval_fn,\n part_val_fn=part_val_fn,\n unpart_fn=unpart_fn,\n num_epochs=5)\n\n expected_metrics = ['loss', 'mean_squared_error',\n 'epoch_time_in_seconds'] # running training metrics\n\n for eval_fn, prefix in ((part_train_eval_fn,\n metric_utils.PART_TRAIN_EVAL_METRICS_PREFIX),\n (part_val_fn, metric_utils.PART_VAL_METRICS_PREFIX),\n (unpart_fn, metric_utils.UNPART_METRICS_PREFIX)):\n if eval_fn is not None:\n for metric in ('loss', 'mean_squared_error'):\n prefixed_metric = prefix + metric\n self.assertIn(prefixed_metric, history.history.keys())\n self.assertMetricDecreases(\n history.history[prefixed_metric], expected_len=5)\n\n expected_metrics.append(prefixed_metric)\n expected_metrics.append(prefix + metric_utils.TIME_KEY)\n\n self.assertCountEqual(history.history.keys(), expected_metrics)\n\n def test_lr_callback(self):\n optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)\n keras_model = compiled_keras_model(optimizer=optimizer)\n dataset = create_dataset()\n history = centralized_training_loop.run(\n keras_model=keras_model,\n train_dataset=dataset,\n num_epochs=10,\n decay_epochs=8,\n lr_decay=0.5)\n\n self.assertCountEqual(\n history.history.keys(),\n ['loss', 'mean_squared_error', 'epoch_time_in_seconds', 'lr'])\n self.assertAllClose(history.history['lr'], [0.1] * 8 + [0.05] * 2)\n\n\nclass CentralizedTrainingLoopWithDefaultCallbacksTest(tf.test.TestCase,\n parameterized.TestCase):\n \"\"\"Integrated test with `metric_utils.configure_default_callbacks()`.\"\"\"\n\n def test_checkpoint_callback_can_restore(self):\n keras_model = compiled_keras_model()\n dataset = create_dataset()\n exp_name = 'test_ckpt'\n root_output_dir = self.get_temp_dir()\n\n checkpoiont_callback, _ = metric_utils.configure_default_callbacks(\n root_output_dir=root_output_dir,\n experiment_name=exp_name,\n epochs_per_checkpoint=1)\n\n centralized_training_loop.run(\n keras_model=keras_model,\n train_dataset=dataset,\n num_epochs=2,\n checkpoint_callback=checkpoiont_callback)\n\n self.assertTrue(tf.io.gfile.exists(root_output_dir))\n ckpt_dir = os.path.join(root_output_dir, 'checkpoints', exp_name)\n self.assertTrue(tf.io.gfile.exists(ckpt_dir))\n\n restored_model = compiled_keras_model()\n restored_model.load_weights(ckpt_dir)\n self.assertAllEqual(\n keras_model.get_config(),\n restored_model.get_config(),\n )\n\n @parameterized.named_parameters(\n ('train_train_eval={},train_val={},val={},test={}'.format(*eval_fn_bools),\n *eval_fn_bools)\n for eval_fn_bools in itertools.product([False, True], repeat=4))\n def test_writing_with_various_evaluation_combination_to_csv(\n self, use_part_train_eval_fn, use_part_val_fn, use_unpart_fn,\n use_test_fn):\n keras_model = compiled_keras_model()\n dataset = create_dataset()\n exp_name = 'write_eval_metrics'\n root_output_dir = self.get_temp_dir()\n eval_fn = lambda model: model.evaluate(dataset, return_dict=True, verbose=0)\n\n _, metrics_callbacks = metric_utils.configure_default_callbacks(\n root_output_dir=root_output_dir,\n experiment_name=exp_name,\n epochs_per_checkpoint=1)\n\n part_train_eval_fn = eval_fn if use_part_train_eval_fn else None\n part_val_fn = eval_fn if use_part_val_fn else None\n unpart_fn = eval_fn if use_unpart_fn else None\n test_fn = eval_fn if use_test_fn else None\n\n centralized_training_loop.run(\n keras_model=keras_model,\n train_dataset=dataset,\n num_epochs=2,\n part_train_eval_fn=part_train_eval_fn,\n part_val_fn=part_val_fn,\n unpart_fn=unpart_fn,\n test_fn=test_fn,\n metrics_callbacks=metrics_callbacks)\n\n log_dir = os.path.join(root_output_dir, 'logdir', exp_name)\n self.assertTrue(tf.io.gfile.exists(log_dir))\n\n results_dir = os.path.join(root_output_dir, 'results', exp_name)\n self.assertTrue(tf.io.gfile.exists(results_dir))\n metrics_file = os.path.join(results_dir, 'experiment.metrics.csv')\n self.assertTrue(tf.io.gfile.exists(metrics_file))\n metrics_csv = pd.read_csv(metrics_file, index_col=0)\n\n # Build expected columns.\n expected_columns = ['loss', 'mean_squared_error',\n 'epoch_time_in_seconds'] # running training metrics\n\n for eval_fn, prefix in ((part_train_eval_fn,\n metric_utils.PART_TRAIN_EVAL_METRICS_PREFIX),\n (part_val_fn, metric_utils.PART_VAL_METRICS_PREFIX),\n (unpart_fn, metric_utils.UNPART_METRICS_PREFIX),\n (test_fn, metric_utils.TEST_METRICS_PREFIX)):\n\n if eval_fn is not None:\n expected_columns.extend([\n prefix + metric\n for metric in ('loss', 'mean_squared_error', metric_utils.TIME_KEY)\n ])\n expected_num_rows = 2 if test_fn is None else 3\n self.assertEqual(metrics_csv.shape,\n (expected_num_rows, len(expected_columns)))\n self.assertCountEqual(metrics_csv.columns, expected_columns)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2020, The TensorFlow Federated Authors.\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\"\"\"Simple FedAvg to train EMNIST.\n\nThis is intended to be a minimal stand-alone experiment script built on top of\ncore TFF.\n\"\"\"\n\nimport collections\nimport functools\n\nfrom absl import app\nfrom absl import flags\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nfrom shrink_unshrink import simple_fedavg_tf\nfrom shrink_unshrink import simple_fedavg_tff\n\n# Training hyperparameters\nflags.DEFINE_integer('total_rounds', 256, 'Number of total training rounds.')\nflags.DEFINE_integer('rounds_per_eval', 1, 'How often to evaluate')\nflags.DEFINE_integer('train_clients_per_round', 2,\n 'How many clients to sample per round.')\nflags.DEFINE_integer('client_epochs_per_round', 1,\n 'Number of epochs in the client to take per round.')\nflags.DEFINE_integer('batch_size', 16, 'Batch size used on the client.')\nflags.DEFINE_integer('test_batch_size', 128, 'Minibatch size of test data.')\n\n# Optimizer configuration (this defines one or more flags per optimizer).\nflags.DEFINE_float('server_learning_rate', 1.0, 'Server learning rate.')\nflags.DEFINE_float('client_learning_rate', 0.1, 'Client learning rate.')\n\nFLAGS = flags.FLAGS\n\n\ndef get_emnist_dataset():\n \"\"\"Loads and preprocesses the EMNIST dataset.\n\n Returns:\n A `(emnist_train, emnist_test)` tuple where `emnist_train` is a\n `tff.simulation.datasets.ClientData` object representing the training data\n and `emnist_test` is a single `tf.data.Dataset` representing the test data\n of all clients.\n \"\"\"\n emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data(\n only_digits=True)\n\n def element_fn(element):\n return collections.OrderedDict(\n x=tf.expand_dims(element['pixels'], -1), y=element['label'])\n\n def preprocess_train_dataset(dataset):\n # Use buffer_size same as the maximum client dataset size,\n # 418 for Federated EMNIST\n return dataset.map(element_fn).shuffle(buffer_size=418).repeat(\n count=FLAGS.client_epochs_per_round).batch(\n FLAGS.batch_size, drop_remainder=False)\n\n def preprocess_test_dataset(dataset):\n return dataset.map(element_fn).batch(\n FLAGS.test_batch_size, drop_remainder=False)\n\n emnist_train = emnist_train.preprocess(preprocess_train_dataset)\n emnist_test = preprocess_test_dataset(\n emnist_test.create_tf_dataset_from_all_clients())\n return emnist_train, emnist_test\n\n\ndef create_original_fedavg_cnn_model(only_digits=True):\n \"\"\"The CNN model used in https://arxiv.org/abs/1602.05629.\n\n Args:\n only_digits: If True, uses a final layer with 10 outputs, for use with the\n digits only EMNIST dataset. If False, uses 62 outputs for the larger\n dataset.\n\n Returns:\n An uncompiled `tf.keras.Model`.\n \"\"\"\n data_format = 'channels_last'\n input_shape = [28, 28, 1]\n\n max_pool = functools.partial(\n tf.keras.layers.MaxPooling2D,\n pool_size=(2, 2),\n padding='same',\n data_format=data_format)\n conv2d = functools.partial(\n tf.keras.layers.Conv2D,\n kernel_size=5,\n padding='same',\n data_format=data_format,\n activation=tf.nn.relu)\n\n model = tf.keras.models.Sequential([\n conv2d(filters=32, input_shape=input_shape),\n max_pool(),\n conv2d(filters=64),\n max_pool(),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation=tf.nn.relu),\n tf.keras.layers.Dense(10 if only_digits else 62),\n ])\n\n return model\n\n\ndef server_optimizer_fn():\n return tf.keras.optimizers.SGD(learning_rate=FLAGS.server_learning_rate)\n\n\ndef client_optimizer_fn():\n return tf.keras.optimizers.SGD(learning_rate=FLAGS.client_learning_rate)\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n # If GPU is provided, TFF will by default use the first GPU like TF. The\n # following lines will configure TFF to use multi-GPUs and distribute client\n # computation on the GPUs. Note that we put server computatoin on CPU to avoid\n # potential out of memory issue when a large number of clients is sampled per\n # round. The client devices below can be an empty list when no GPU could be\n # detected by TF.\n client_devices = tf.config.list_logical_devices('GPU')\n server_device = tf.config.list_logical_devices('CPU')[0]\n tff.backends.native.set_local_python_execution_context(\n server_tf_device=server_device, client_tf_devices=client_devices)\n\n train_data, test_data = get_emnist_dataset()\n\n def tff_model_fn():\n \"\"\"Constructs a fully initialized model for use in federated averaging.\"\"\"\n keras_model = create_original_fedavg_cnn_model(only_digits=True)\n loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n return simple_fedavg_tf.KerasModelWrapper(keras_model,\n test_data.element_spec, loss)\n\n iterative_process = simple_fedavg_tff.build_federated_shrink_unshrink_process(\n server_model_fn=tff_model_fn,\n client_model_fn=tff_model_fn,\n server_optimizer_fn=server_optimizer_fn,\n client_optimizer_fn=client_optimizer_fn)\n server_state = iterative_process.initialize()\n\n metric = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')\n model = tff_model_fn()\n for round_num in range(FLAGS.total_rounds):\n sampled_clients = np.random.choice(\n train_data.client_ids,\n size=FLAGS.train_clients_per_round,\n replace=False)\n sampled_train_data = [\n train_data.create_tf_dataset_for_client(client)\n for client in sampled_clients\n ]\n server_state, train_metrics = iterative_process.next(\n server_state, sampled_train_data)\n print(f'Round {round_num} training loss: {train_metrics}')\n if round_num % FLAGS.rounds_per_eval == 0:\n model.from_weights(server_state.model_weights)\n accuracy = simple_fedavg_tf.keras_evaluate(model.keras_model, test_data,\n metric)\n print(f'Round {round_num} validation accuracy: {accuracy * 100.0}')\n\n\nif __name__ == '__main__':\n app.run(main)\n", "# Copyright 2021, 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\"\"\"An implementation of the q-Fair Federated Learning (q-FFL) algorithm.\n\nBased on the paper:\n\nFair Resource Allocation in Federated Learning.\n Tian Li, Maziar Sanjabi, Ahmad Beirami, Virginia Smith. ICLR 2020.\n https://arxiv.org/abs/1602.05629\n\nNote that the primary distinction between this implementation and the algorithm\ndescribed in the paper above is that the paper weights each client by their loss\nafter training. This requires an extra pass over each client's dataset. In order\nto reduce training time on clients, we use the loss computed as the client\ntrains to do the weighting in q-FFL.\n\"\"\"\n\nfrom typing import Any, Callable, Optional\n\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nDEFAULT_SERVER_OPTIMIZER_FN = lambda: tf.keras.optimizers.SGD(learning_rate=1.0)\n\n\ndef build_keras_output_to_loss_fn(\n metric_builder=Callable[[], tf.keras.metrics.Metric]):\n \"\"\"Creates a function that computes the result of a `tf.keras` metric.\"\"\"\n\n def output_to_loss_fn(output):\n loss_variables = output['loss']\n metric = metric_builder()\n tf.nest.map_structure(lambda a, b: a.assign(b), metric.variables,\n loss_variables)\n return metric.result()\n\n return output_to_loss_fn\n\n\ndef build_q_ffl_process(\n model_fn: Callable[[], tff.learning.Model],\n fairness_parameter: tf.Tensor,\n client_optimizer_fn: Callable[[], tf.keras.optimizers.Optimizer],\n server_optimizer_fn: Callable[\n [], tf.keras.optimizers.Optimizer] = DEFAULT_SERVER_OPTIMIZER_FN,\n broadcast_process: Optional[tff.templates.MeasuredProcess] = None,\n model_update_aggregation_factory: Optional[\n tff.aggregators.WeightedAggregationFactory] = None,\n use_experimental_simulation_loop: bool = False,\n output_to_loss_fn: Optional[Callable[[Any], tf.Tensor]] = None,\n) -> tff.templates.IterativeProcess:\n \"\"\"Builds an iterative process that performs q-FFL.\n\n This function creates a `tff.templates.IterativeProcess` that performs\n a variant of federated averaging on client models, where client updates are\n weighted according by their loss raised to the power `fairness_parameter`.\n\n The iterative process has the following methods inherited from\n `tff.templates.IterativeProcess`:\n\n * `initialize`: A `tff.Computation` with the functional type signature\n `( -> S@SERVER)`, where `S` is a `tff.learning.framework.ServerState`\n representing the initial state of the server.\n * `next`: A `tff.Computation` with the functional type signature\n `(<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>)` where `S` is a\n `tff.learning.framework.ServerState` whose type matches that of the output\n of `initialize`, and `{B*}@CLIENTS` represents the client datasets, where\n `B` is the type of a single batch. This computation returns a\n `tff.learning.framework.ServerState` representing the updated server state\n and metrics that are the result of\n `tff.learning.Model.federated_output_computation` during client training\n and any other metrics from broadcast and aggregation processes.\n\n The iterative process also has the following method not inherited from\n `tff.templates.IterativeProcess`:\n\n * `get_model_weights`: A `tff.Computation` that takes as input the\n a `tff.learning.framework.ServerState`, and returns a\n `tff.learning.ModelWeights` containing the state's model weights.\n\n The internal logic of the resulting iterative process is the same as\n `tff.learning.build_federated_averaging_process`, but with a custom weighting\n function.\n\n Args:\n model_fn: A no-arg function that returns a `tff.learning.Model`. This method\n must *not* capture TensorFlow tensors or variables and use them. The model\n must be constructed entirely from scratch on each invocation, returning\n the same pre-constructed model each call will result in an error.\n fairness_parameter: A scalar tensor governing the exponent in the client\n weights. Must be convertible to a scalar `tf.float32`.\n client_optimizer_fn: A no-arg callable that returns a `tf.keras.Optimizer`.\n server_optimizer_fn: A no-arg callable that returns a `tf.keras.Optimizer`.\n By default, this uses `tf.keras.optimizers.SGD` with a learning rate of\n 1.0.\n broadcast_process: a `tff.templates.MeasuredProcess` that broadcasts the\n model weights on the server to the clients. It must support the signature\n `(input_values@SERVER -> output_values@CLIENT)`. If set to default None,\n the server model is broadcast to the clients using the default\n tff.federated_broadcast.\n model_update_aggregation_factory: An optional\n `tff.aggregators.WeightedAggregationFactory` that constructs\n `tff.templates.AggregationProcess` for aggregating the client model\n updates on the server. If `None`, uses `tff.aggregators.MeanFactory`.\n use_experimental_simulation_loop: Controls the reduce loop function for\n input dataset. An experimental reduce loop is used for simulation. It is\n currently necessary to set this flag to True for performant GPU\n simulations.\n output_to_loss_fn: An optional callable that takes the result of\n `model_fn().report_local_outputs()` and returns a scalar tensor\n representing the loss of the model. If set to `None`, this method will\n assume that the loss will attempt to be extracted\n `model_fn().report_local_outputs()['loss']`.\n\n Returns:\n A `tff.templates.IterativeProcess`.\n \"\"\"\n if output_to_loss_fn is None:\n output_to_loss_fn = lambda x: x['loss']\n\n def client_weighting(client_output):\n loss = output_to_loss_fn(client_output)\n return tf.math.pow(loss, fairness_parameter)\n\n return tff.learning.build_federated_averaging_process(\n model_fn=model_fn,\n client_optimizer_fn=client_optimizer_fn,\n server_optimizer_fn=server_optimizer_fn,\n client_weighting=client_weighting,\n broadcast_process=broadcast_process,\n model_update_aggregation_factory=model_update_aggregation_factory,\n use_experimental_simulation_loop=use_experimental_simulation_loop)\n", "# Copyright 2021, 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\nimport collections\nimport os\nimport tempfile\n\nfrom absl.testing import absltest\nimport pandas as pd\nimport tensorflow as tf\n\nfrom dual_encoder.movielens import movielens_data_gen\n\n_TEST_DIR = 'dual_encoder/movielens/testdata'\n\n\ndef _int64_feature(value_list):\n \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n return tf.train.Feature(int64_list=tf.train.Int64List(value=value_list))\n\n\nclass MovielensDataGenTest(absltest.TestCase):\n\n def setUp(self):\n super().setUp()\n\n self.example_1 = tf.train.Example(\n features=tf.train.Features(\n feature={\n 'context': _int64_feature([1, 0, 0]),\n 'label': _int64_feature([5])\n }))\n\n self.example_2 = tf.train.Example(\n features=tf.train.Features(\n feature={\n 'context': _int64_feature([1, 5, 0]),\n 'label': _int64_feature([3])\n }))\n\n self.example_3 = tf.train.Example(\n features=tf.train.Features(\n feature={\n 'context': _int64_feature([1, 5, 3]),\n 'label': _int64_feature([3])\n }))\n\n self.example_4 = tf.train.Example(\n features=tf.train.Features(\n feature={\n 'context': _int64_feature([3, 0, 0]),\n 'label': _int64_feature([1])\n }))\n\n self.ratings_df = pd.DataFrame(\n {\n 'UserID': [1, 1, 1, 7, 1, 3, 3, 4],\n 'MovieID': [1, 3, 5, 2, 3, 1, 3, 2],\n 'Rating': [1, 2, 4, 3, 2, 3, 5, 1],\n 'Timestamp': [1, 2, 1, 4, 5, 9, 1, 3]\n })\n self.timelines = collections.defaultdict(list)\n self.timelines = {1: [1, 5, 3, 3],\n 7: [2],\n 3: [3, 1],\n 4: [2]\n }\n\n # Parameters\n self.tmp_dir = tempfile.mkdtemp()\n\n def test_read_ratings(self):\n test_ratings_df = movielens_data_gen.read_ratings(_TEST_DIR, self.tmp_dir)\n # The assertListEqual doesn't compare the datatype (e.g. 1 & 1.0 equal).\n self.assertListEqual(list(test_ratings_df.columns),\n list(self.ratings_df.columns))\n self.assertListEqual(list(test_ratings_df['UserID']),\n list(self.ratings_df['UserID']))\n self.assertListEqual(list(test_ratings_df['MovieID']),\n list(self.ratings_df['MovieID']))\n self.assertListEqual(list(test_ratings_df['Rating']),\n list(self.ratings_df['Rating']))\n self.assertListEqual(list(test_ratings_df['Timestamp']),\n list(self.ratings_df['Timestamp']))\n\n def test_split_ratings_df(self):\n test_train_ratings_df, test_val_ratings_df, test_test_ratings_df = (\n movielens_data_gen.split_ratings_df(self.ratings_df, 0.3, 0.3))\n self.assertListEqual(list(test_train_ratings_df['UserID']), [1, 1, 1, 1])\n self.assertListEqual(list(test_val_ratings_df['UserID']), [3, 3])\n self.assertListEqual(list(test_test_ratings_df['UserID']), [7, 4])\n\n def test_split_ratings_df_empty_val(self):\n test_train_ratings_df, test_val_ratings_df, test_test_ratings_df = (\n movielens_data_gen.split_ratings_df(self.ratings_df, 0.3, 0.0))\n self.assertListEqual(list(test_train_ratings_df['UserID']), [1, 1, 1, 1])\n self.assertEmpty(list(test_val_ratings_df['UserID']))\n self.assertListEqual(list(test_test_ratings_df['UserID']), [7, 3, 3, 4])\n\n def test_split_ratings_df_empty_test(self):\n test_train_ratings_df, test_val_ratings_df, test_test_ratings_df = (\n movielens_data_gen.split_ratings_df(self.ratings_df, 0.3, 0.7))\n self.assertListEqual(list(test_train_ratings_df['UserID']), [1, 1, 1, 1])\n self.assertListEqual(list(test_val_ratings_df['UserID']), [7, 3, 3, 4])\n self.assertEmpty(list(test_test_ratings_df['UserID']))\n\n def test_convert_to_timelines(self):\n test_timelines = movielens_data_gen.convert_to_timelines(self.ratings_df)\n self.assertDictEqual(test_timelines, self.timelines)\n\n def test_generate_examples_from_a_single_timeline(self):\n test_timeline = self.timelines[1]\n test_examples = (\n movielens_data_gen.generate_examples_from_a_single_timeline(\n test_timeline, 3, 0))\n test_parsed_examples = []\n for serialized_example in test_examples:\n example = tf.train.Example()\n example.ParseFromString(serialized_example)\n test_parsed_examples.append(example)\n self.assertLen(test_examples, 3)\n self.assertListEqual(test_parsed_examples,\n [self.example_1, self.example_2, self.example_3])\n\n def test_generate_examples_from_timelines(self):\n test_train_examples, test_val_examples, test_test_examples = (\n movielens_data_gen.generate_examples_from_timelines(\n self.timelines, 2, 3, 0, 0.5, 0.3, 2))\n\n test_parsed_train_examples = []\n test_parsed_val_examples = []\n test_parsed_test_examples = []\n\n for serialized_example in test_train_examples:\n example = tf.train.Example()\n example.ParseFromString(serialized_example)\n test_parsed_train_examples.append(example)\n\n for serialized_example in test_val_examples:\n example = tf.train.Example()\n example.ParseFromString(serialized_example)\n test_parsed_val_examples.append(example)\n\n for serialized_example in test_test_examples:\n example = tf.train.Example()\n example.ParseFromString(serialized_example)\n test_parsed_test_examples.append(example)\n\n self.assertLen(test_train_examples, 2)\n self.assertLen(test_val_examples, 1)\n self.assertLen(test_test_examples, 1)\n self.assertListEqual(test_parsed_train_examples,\n [self.example_2, self.example_3])\n self.assertListEqual(test_parsed_val_examples,\n [self.example_4])\n self.assertListEqual(test_parsed_test_examples,\n [self.example_1])\n\n def test_write_tfrecords(self):\n examples = [self.example_1.SerializeToString(),\n self.example_2.SerializeToString()]\n filename = os.path.join(self.tmp_dir, 'test.tfrecord')\n movielens_data_gen.write_tfrecords(examples, filename)\n self.assertTrue(os.path.exists(filename))\n\n def test_generate_examples_per_user(self):\n test_examples_per_user = (\n movielens_data_gen.generate_examples_per_user(\n self.timelines, 2, 3, 0))\n self.assertListEqual(list(test_examples_per_user.keys()), [1, 3])\n self.assertLen(test_examples_per_user[1], 3)\n self.assertLen(test_examples_per_user[3], 1)\n\n def test_generate_examples_per_user_max_example_zero(self):\n test_examples_per_user = (\n movielens_data_gen.generate_examples_per_user(\n self.timelines, 2, 3, 0, 0))\n self.assertListEqual(list(test_examples_per_user.keys()), [1, 3])\n self.assertLen(test_examples_per_user[1], 3)\n self.assertLen(test_examples_per_user[3], 1)\n\n def test_generate_examples_per_user_max_example_nonzero(self):\n test_examples_per_user = (\n movielens_data_gen.generate_examples_per_user(\n self.timelines, 2, 3, 0, 2))\n self.assertListEqual(list(test_examples_per_user.keys()), [1, 3])\n self.assertLen(test_examples_per_user[1], 2)\n self.assertLen(test_examples_per_user[3], 1)\n\n def test_shuffle_examples_across_users(self):\n examples = {1: [1, 2, 3],\n 2: [9, 5, 4],\n 3: [7, 6]}\n shuffled_examples = {1: [9, 7, 2],\n 2: [4, 6, 1],\n 3: [5, 3]}\n test_shuffled_examples = (\n movielens_data_gen.shuffle_examples_across_users(examples, seed=1))\n self.assertDictEqual(test_shuffled_examples, shuffled_examples)\n\n def test_decode_example_with_use_example_weight(self):\n test_timeline = self.timelines[1]\n test_example = (\n movielens_data_gen.generate_examples_from_a_single_timeline(\n test_timeline, 3, 0))[1]\n test_decoded_example = movielens_data_gen.decode_example(test_example)\n self.assertLen(test_decoded_example, 2)\n self.assertListEqual([1, 5, 0], list(test_decoded_example[0]['context']))\n self.assertEqual([3], test_decoded_example[0]['label'])\n self.assertEqual(1.0, test_decoded_example[1])\n\n def test_decode_example_without_use_example_weight(self):\n test_timeline = self.timelines[1]\n test_example = (\n movielens_data_gen.generate_examples_from_a_single_timeline(\n test_timeline, 3, 0))[1]\n test_decoded_example = movielens_data_gen.decode_example(\n test_example, False)\n print(test_decoded_example)\n self.assertLen(test_decoded_example, 2)\n self.assertListEqual([1, 5, 0], list(test_decoded_example[0]['context']))\n self.assertEqual([3], test_decoded_example[0]['label'])\n self.assertEqual([3], test_decoded_example[1])\n\n def test_create_tf_datasets(self):\n test_examples_per_user = (\n movielens_data_gen.generate_examples_per_user(\n self.timelines, 2, 3, 0))\n test_dataset_per_user = (\n movielens_data_gen.create_tf_datasets(test_examples_per_user,\n batch_size=1,\n num_local_epochs=1))\n\n self.assertLen(test_dataset_per_user, 2)\n self.assertLen(list(test_dataset_per_user[0].as_numpy_iterator()), 3)\n self.assertLen(list(test_dataset_per_user[1].as_numpy_iterator()), 1)\n\n def test_create_tf_datasets_batch_size(self):\n test_examples_per_user = (\n movielens_data_gen.generate_examples_per_user(\n self.timelines, 2, 3, 0))\n test_dataset_per_user = (\n movielens_data_gen.create_tf_datasets(test_examples_per_user,\n batch_size=2,\n num_local_epochs=1))\n\n self.assertLen(test_dataset_per_user, 2)\n self.assertLen(list(test_dataset_per_user[0].as_numpy_iterator()), 2)\n self.assertLen(list(test_dataset_per_user[1].as_numpy_iterator()), 1)\n\n def test_create_tf_datasets_num_local_epochs(self):\n test_examples_per_user = (\n movielens_data_gen.generate_examples_per_user(\n self.timelines, 2, 3, 0, 0))\n test_dataset_per_user = (\n movielens_data_gen.create_tf_datasets(test_examples_per_user,\n batch_size=1,\n num_local_epochs=2))\n\n self.assertLen(test_dataset_per_user, 2)\n self.assertLen(list(test_dataset_per_user[0].as_numpy_iterator()), 6)\n self.assertLen(list(test_dataset_per_user[1].as_numpy_iterator()), 2)\n\n def test_create_client_datasets(self):\n test_client_datasets = (\n movielens_data_gen.create_client_datasets(\n self.ratings_df,\n min_timeline_len=2,\n max_context_len=3,\n max_examples_per_user=0,\n pad_id=0,\n shuffle_across_users=False,\n batch_size=2,\n num_local_epochs=1))\n self.assertLen(test_client_datasets, 2)\n self.assertLen(list(test_client_datasets[0].as_numpy_iterator()), 2)\n self.assertLen(list(test_client_datasets[1].as_numpy_iterator()), 1)\n\n\nif __name__ == '__main__':\n absltest.main()\n" ]
[ [ "tensorflow.not_equal", "tensorflow.keras.layers.Dense", "tensorflow.expand_dims", "tensorflow.keras.Model", "tensorflow.zeros_like", "tensorflow.TensorSpec", "tensorflow.keras.layers.Add", "tensorflow.nn.embedding_lookup", "tensorflow.keras.layers.Input" ], [ "tensorflow.test.main" ], [ "tensorflow.io.gfile.exists", "pandas.read_csv", "tensorflow.test.main", "tensorflow.keras.optimizers.SGD" ], [ "numpy.random.seed", "tensorflow.keras.losses.MeanSquaredError", "tensorflow.keras.layers.Dense", "tensorflow.keras.metrics.MeanSquaredError", "tensorflow.test.main", "numpy.random.rand" ], [ "numpy.random.random", "tensorflow.test.main", "numpy.random.seed" ], [ "tensorflow.Graph", "tensorflow.constant", "tensorflow.shape", "tensorflow.cast", "tensorflow.equal", "tensorflow.GradientTape", "tensorflow.nest.flatten", "tensorflow.math.divide_no_nan", "tensorflow.nest.map_structure", "tensorflow.keras.optimizers.SGD" ], [ "pandas.read_csv", "tensorflow.io.gfile.exists", "tensorflow.keras.layers.Dense", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.keras.losses.MeanSquaredError", "tensorflow.keras.Sequential", "tensorflow.test.main", "tensorflow.keras.metrics.MeanSquaredError", "tensorflow.keras.optimizers.SGD" ], [ "numpy.random.choice", "tensorflow.keras.losses.SparseCategoricalCrossentropy", "tensorflow.keras.layers.Dense", "tensorflow.config.list_logical_devices", "tensorflow.expand_dims", "tensorflow.keras.metrics.SparseCategoricalAccuracy", "tensorflow.keras.layers.Flatten", "tensorflow.keras.optimizers.SGD" ], [ "tensorflow.math.pow", "tensorflow.keras.optimizers.SGD" ], [ "tensorflow.train.Example", "pandas.DataFrame", "tensorflow.train.Int64List" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "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": [] } ]
sunhwan/griddata
[ "b7fb22ad242b0f0a6735fd5f35c3f2ee8e7f4b3f" ]
[ "griddata/grid.py" ]
[ "\"\"\"\nInitialize grid format data and allow conversion between formats and\nresampling of data\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nfrom scipy import interpolate\nfrom scipy import ndimage\n\nclass Grid(object):\n \"\"\"Grid data class that reads/converts grid-format data. Internally\n the elements are kept in C order.\n\n Args:\n file (:obj:`file`): File object to the file containing grid-format data.\n format (str): Grid-format data format.\n \"\"\"\n\n ndim = None\n n_elements = None\n _shape = ()\n spacing = ()\n _origin = None\n _center = None\n _center = None\n _elements = None\n\n def __init__(self):\n pass\n\n @property\n def elements(self):\n return self.get_elements()\n\n def get_elements(self, order='C'):\n \"\"\"Return the elements in 1D array. The array is ordered in C-order.\"\"\"\n if order not in ('C', 'F'):\n raise NotImplementedError\n\n n_elements = self.n_elements\n return self._elements.reshape(self.shape).ravel(order=order)\n\n @elements.setter\n def elements(self, elements):\n if self.n_elements is not None:\n assert len(elements) == self.n_elements, f'{len(elements)} != {len(self.n_elements)}'\n self.set_elements(elements)\n\n def set_elements(self, elements, order='C'):\n if order not in ('C', 'F'):\n raise NotImplementedError\n n_elements = len(elements)\n self._elements = np.array(elements).reshape(self.shape, order=order).ravel()\n\n @property\n def ndelements(self, order='C'):\n \"\"\"Reshape the elements array into ndarray\"\"\"\n if order not in ('C', 'F'):\n raise NotImplementedError\n ndelements = self._elements.reshape(self.shape)\n if order == 'C':\n return ndelements\n return ndelements.ravel(order=order).reshape(self.shape, order=order)\n\n @property\n def center(self):\n if self._center is not None:\n return self._center\n try:\n ndim = self.ndim\n center = [None for _ in range(self.ndim)]\n for i in range(self.ndim):\n center[i] = self._origin[i] + int(float(self.shape[i])/2) * self.spacing[i]\n self._center = center\n return self._center\n except:\n raise ValueError\n\n @center.setter\n def center(self, center):\n self._center = center\n self.ndim = len(center)\n\n @property\n def origin(self):\n if self._origin:\n return self._origin\n try:\n ndim = self.ndim\n _origin = [None for _ in range(self.ndim)]\n for i in range(self.ndim):\n _origin[i] = self._center[i] - int(float(self.shape[i])/2) * self.spacing[i]\n self._origin = _origin\n return self._origin\n except:\n raise ValueError\n\n @origin.setter\n def origin(self, origin):\n self._origin = origin\n self.ndim = len(origin)\n\n @property\n def shape(self):\n return self._shape\n\n @shape.setter\n def shape(self, shape):\n self._shape = shape\n self.ndim = len(shape)\n self.n_elements = np.cumprod(shape)[-1]\n\n def points(self, order='C'):\n if order not in ('C', 'F'):\n raise NotImplementedError\n origin = self.origin\n shape = self.shape\n spacing = self.spacing\n ix, iy, iz = [np.array([origin[i]+_*spacing[i] for _ in range(shape[i])]) for i in range(self.ndim)]\n Z = np.meshgrid(ix, iy, iz, indexing='ij')\n points = np.empty((self.n_elements, self.ndim), dtype=np.float)\n for i in range(self.ndim):\n points[:,i] = Z[i].reshape(1, self.n_elements, order=order)\n return points\n\n def reorient(self, shape, center, u, spacing=None, bounds_error=False, fill_value=0):\n if not spacing:\n spacing = self.spacing\n\n grid = Grid()\n grid.n_elements = np.cumprod(shape)[-1]\n grid.spacing = spacing\n grid.shape = shape\n grid.center = center\n\n # prepare for large array for storing the rotated map and prevent cropping upon rotation\n big_shape = np.ones(self.ndim, dtype=np.integer) * np.max([self.shape, shape])\n ndelements = np.zeros(big_shape)\n offset = [int((big_shape[0] - self.shape[0]) / 2.0),\n int((big_shape[1] - self.shape[1]) / 2.0),\n int((big_shape[2] - self.shape[2]) / 2.0)]\n ndelements[offset[0]:offset[0] + self.shape[0],\n offset[1]:offset[1] + self.shape[1],\n offset[2]:offset[2] + self.shape[2]] = self.ndelements\n\n # good introduction on affine transform\n # https://stackoverflow.com/a/20161742/532799\n c_in = 0.5 * np.array(ndelements.shape)\n c_out = 0.5 * np.array(ndelements.shape)\n offset = c_in - c_out.dot(u['rot'])\n\n new = ndimage.affine_transform(ndelements, u['rot'].T, offset=offset, order=3)\n offset = [int((big_shape[0] - shape[0]) / 2.0),\n int((big_shape[1] - shape[1]) / 2.0),\n int((big_shape[2] - shape[2]) / 2.0)]\n grid.elements = new[offset[0]:offset[0] + shape[0],\n offset[1]:offset[1] + shape[1],\n offset[2]:offset[2] + shape[2]].flatten()\n return grid\n\n def resample(self, shape, center, spacing=None, bounds_error=False, fill_value=0):\n if not spacing:\n spacing = self.spacing\n\n grid = Grid()\n grid.n_elements = np.cumprod(shape)[-1]\n grid.spacing = spacing\n grid.shape = shape\n grid.center = center\n points = [np.arange(self.origin[i], self.origin[i]+self.spacing[i]*self.shape[i], self.spacing[i]) for i in range(self.ndim)]\n g = interpolate.RegularGridInterpolator(points, self.ndelements, bounds_error=bounds_error, fill_value=fill_value)\n\n origin = grid.origin\n points = [np.arange(origin[i], origin[i]+shape[i]*spacing[i], spacing[i]) for i in range(self.ndim)]\n ndpoints = np.meshgrid(*points, indexing='ij')\n points = np.array([ndpoints[i].reshape(grid.n_elements) for i in range(self.ndim)]).T\n grid.elements = g(points)\n return grid\n\n def gaussian_filter(self, sigma=1.):\n grid = Grid()\n grid.n_elements = np.cumprod(self.shape)[-1]\n grid.spacing = self.spacing\n grid.shape = self.shape\n grid.center = self.center\n ndelements = ndimage.gaussian_filter(self.ndelements, sigma=sigma)\n grid.elements = ndelements.flatten()\n return grid\n\n def _gridcheck(self, h):\n \"\"\"Validate grid h is same shape as the current grid\"\"\"\n if not isinstance(h, Grid):\n raise TypeError\n assert h.n_elements == self.n_elements\n assert h.spacing == self.spacing\n assert h.shape == self.shape\n\n def copy(self):\n grid = Grid()\n grid.n_elements = self.n_elements\n grid.spacing = self.spacing\n grid.shape = self.shape\n grid.origin = self.origin\n return grid\n\n def log(self):\n idx = ~(self.elements == 0)\n self.elements[idx] = np.log(self.elements[idx])\n return self\n\n def exp(self):\n self.elements = np.exp(self.elements)\n return self\n\n def __sub__(self, h):\n self._gridcheck(h)\n grid = self.copy()\n grid.elements = self.elements - h.elements\n return grid\n\n def __add__(self, h):\n self._gridcheck(h)\n grid = self.copy()\n grid.elements = self.elements + h.elements\n return grid\n\n def __mul__(self, factor):\n self.elements = self.elements * factor\n return self\n\n __rmul__ = __mul__\n\n def __truediv__(self, factor):\n self.elements = self.elements / factor\n return self\n\n" ]
[ [ "numpy.log", "scipy.ndimage.gaussian_filter", "scipy.ndimage.affine_transform", "numpy.arange", "scipy.interpolate.RegularGridInterpolator", "numpy.ones", "numpy.max", "numpy.cumprod", "numpy.exp", "numpy.array", "numpy.meshgrid", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.14", "1.6", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] } ]
WouterDls/simpeg
[ "6b8ef01e123d3bab24aa6a2364200f7114017d06" ]
[ "tutorials/03-gravity/plot_1a_gravity_anomaly.py" ]
[ "\"\"\"\nForward Simulation of Gravity Anomaly Data on a Tensor Mesh\n===========================================================\n\nHere we use the module *SimPEG.potential_fields.gravity* to predict gravity\nanomaly data for a synthetic density contrast model. The simulation is\ncarried out on a tensor mesh. For this tutorial, we focus on the following:\n\n - How to create gravity surveys\n - How to predict gravity anomaly data for a density contrast model\n - How to include surface topography\n - The units of the density contrast model and resulting data\n\n\n\"\"\"\n\n#########################################################################\n# Import Modules\n# --------------\n#\n\nimport numpy as np\nfrom scipy.interpolate import LinearNDInterpolator\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport os\n\nfrom discretize import TensorMesh\nfrom discretize.utils import mkvc\n\nfrom SimPEG.utils import plot2Ddata, model_builder, surface2ind_topo\nfrom SimPEG import maps\nfrom SimPEG.potential_fields import gravity\n\nsave_output = False\n\n# sphinx_gallery_thumbnail_number = 2\n\n#############################################\n# Defining Topography\n# -------------------\n#\n# Surface topography is defined as an (N, 3) numpy array. We create it here but\n# the topography could also be loaded from a file.\n#\n\n[x_topo, y_topo] = np.meshgrid(np.linspace(-200, 200, 41), np.linspace(-200, 200, 41))\nz_topo = -15 * np.exp(-(x_topo ** 2 + y_topo ** 2) / 80 ** 2)\nx_topo, y_topo, z_topo = mkvc(x_topo), mkvc(y_topo), mkvc(z_topo)\ntopo_xyz = np.c_[x_topo, y_topo, z_topo]\n\n\n#############################################\n# Defining the Survey\n# -------------------\n#\n# Here, we define survey that will be used for the forward simulation. Gravity\n# surveys are simple to create. The user only needs an (N, 3) array to define\n# the xyz locations of the observation locations, and a list of field components\n# which are to be measured.\n#\n\n# Define the observation locations as an (N, 3) numpy array or load them.\nx = np.linspace(-80.0, 80.0, 17)\ny = np.linspace(-80.0, 80.0, 17)\nx, y = np.meshgrid(x, y)\nx, y = mkvc(x.T), mkvc(y.T)\nfun_interp = LinearNDInterpolator(np.c_[x_topo, y_topo], z_topo)\nz = fun_interp(np.c_[x, y]) + 5.0\nreceiver_locations = np.c_[x, y, z]\n\n# Define the component(s) of the field we want to simulate as strings within\n# a list. Here we simulate only the vertical component of gravity anomaly.\ncomponents = [\"gz\"]\n\n# Use the observation locations and components to define the receivers. To\n# simulate data, the receivers must be defined as a list.\nreceiver_list = gravity.receivers.Point(receiver_locations, components=components)\n\nreceiver_list = [receiver_list]\n\n# Defining the source field.\nsource_field = gravity.sources.SourceField(receiver_list=receiver_list)\n\n# Defining the survey\nsurvey = gravity.survey.Survey(source_field)\n\n\n#############################################\n# Defining a Tensor Mesh\n# ----------------------\n#\n# Here, we create the tensor mesh that will be used to predict gravity anomaly\n# data.\n#\n\ndh = 5.0\nhx = [(dh, 5, -1.3), (dh, 40), (dh, 5, 1.3)]\nhy = [(dh, 5, -1.3), (dh, 40), (dh, 5, 1.3)]\nhz = [(dh, 5, -1.3), (dh, 15)]\nmesh = TensorMesh([hx, hy, hz], \"CCN\")\n\n########################################################\n# Density Contrast Model and Mapping on Tensor Mesh\n# -------------------------------------------------\n#\n# Here, we create the density contrast model that will be used to predict\n# gravity anomaly data and the mapping from the model to the mesh. The model\n# consists of a less dense block and a more dense sphere.\n#\n\n# Define density contrast values for each unit in g/cc\nbackground_density = 0.0\nblock_density = -0.2\nsphere_density = 0.2\n\n# Find the indices for the active mesh cells (e.g. cells below surface)\nind_active = surface2ind_topo(mesh, topo_xyz)\n\n# Define mapping from model to active cells. The model consists of a value for\n# each cell below the Earth's surface.\nnC = int(ind_active.sum())\nmodel_map = maps.IdentityMap(nP=nC)\n\n# Define model. Models in SimPEG are vector arrays.\nmodel = background_density * np.ones(nC)\n\n# You could find the indicies of specific cells within the model and change their\n# value to add structures.\nind_block = (\n (mesh.gridCC[ind_active, 0] > -50.0)\n & (mesh.gridCC[ind_active, 0] < -20.0)\n & (mesh.gridCC[ind_active, 1] > -15.0)\n & (mesh.gridCC[ind_active, 1] < 15.0)\n & (mesh.gridCC[ind_active, 2] > -50.0)\n & (mesh.gridCC[ind_active, 2] < -30.0)\n)\nmodel[ind_block] = block_density\n\n# You can also use SimPEG utilities to add structures to the model more concisely\nind_sphere = model_builder.getIndicesSphere(np.r_[35.0, 0.0, -40.0], 15.0, mesh.gridCC)\nind_sphere = ind_sphere[ind_active]\nmodel[ind_sphere] = sphere_density\n\n# Plot Density Contrast Model\nfig = plt.figure(figsize=(9, 4))\nplotting_map = maps.InjectActiveCells(mesh, ind_active, np.nan)\n\nax1 = fig.add_axes([0.1, 0.12, 0.73, 0.78])\nmesh.plotSlice(\n plotting_map * model,\n normal=\"Y\",\n ax=ax1,\n ind=int(mesh.nCy / 2),\n grid=True,\n clim=(np.min(model), np.max(model)),\n pcolorOpts={\"cmap\": \"viridis\"},\n)\nax1.set_title(\"Model slice at y = 0 m\")\nax1.set_xlabel(\"x (m)\")\nax1.set_ylabel(\"z (m)\")\n\nax2 = fig.add_axes([0.85, 0.12, 0.05, 0.78])\nnorm = mpl.colors.Normalize(vmin=np.min(model), vmax=np.max(model))\ncbar = mpl.colorbar.ColorbarBase(\n ax2, norm=norm, orientation=\"vertical\", cmap=mpl.cm.viridis\n)\ncbar.set_label(\"$g/cm^3$\", rotation=270, labelpad=15, size=12)\n\nplt.show()\n\n\n#######################################################\n# Simulation: Gravity Anomaly Data on Tensor Mesh\n# -----------------------------------------------\n#\n# Here we demonstrate how to predict gravity anomaly data using the integral\n# formulation.\n#\n\n# Define the forward simulation. By setting the 'store_sensitivities' keyword\n# argument to \"forward_only\", we simulate the data without storing the sensitivities\nsimulation = gravity.simulation.Simulation3DIntegral(\n survey=survey,\n mesh=mesh,\n rhoMap=model_map,\n actInd=ind_active,\n store_sensitivities=\"forward_only\",\n)\n\n# Compute predicted data for some model\ndpred = simulation.dpred(model)\n\n# Plot\nfig = plt.figure(figsize=(7, 5))\n\nax1 = fig.add_axes([0.1, 0.1, 0.75, 0.85])\nplot2Ddata(receiver_list[0].locations, dpred, ax=ax1, contourOpts={\"cmap\": \"bwr\"})\nax1.set_title(\"Gravity Anomaly (Z-component)\")\nax1.set_xlabel(\"x (m)\")\nax1.set_ylabel(\"y (m)\")\n\nax2 = fig.add_axes([0.82, 0.1, 0.03, 0.85])\nnorm = mpl.colors.Normalize(vmin=-np.max(np.abs(dpred)), vmax=np.max(np.abs(dpred)))\ncbar = mpl.colorbar.ColorbarBase(\n ax2, norm=norm, orientation=\"vertical\", cmap=mpl.cm.bwr, format=\"%.1e\"\n)\ncbar.set_label(\"$mgal$\", rotation=270, labelpad=15, size=12)\n\nplt.show()\n\n\n#######################################################\n# Optional: Exporting Results\n# ---------------------------\n#\n# Write the data, topography and true model\n#\n\nif save_output:\n\n dir_path = os.path.dirname(__file__).split(os.path.sep)\n dir_path.extend([\"outputs\"])\n dir_path = os.path.sep.join(dir_path) + os.path.sep\n\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n\n fname = dir_path + \"gravity_topo.txt\"\n np.savetxt(fname, np.c_[topo_xyz], fmt=\"%.4e\")\n\n np.random.seed(737)\n maximum_anomaly = np.max(np.abs(dpred))\n noise = 0.01 * maximum_anomaly * np.random.rand(len(dpred))\n fname = dir_path + \"gravity_data.obs\"\n np.savetxt(fname, np.c_[receiver_locations, dpred + noise], fmt=\"%.4e\")\n" ]
[ [ "numpy.abs", "numpy.linspace", "numpy.savetxt", "numpy.random.seed", "numpy.min", "numpy.ones", "matplotlib.colorbar.ColorbarBase", "numpy.max", "scipy.interpolate.LinearNDInterpolator", "numpy.exp", "numpy.meshgrid", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Jewelryland/YelpRecSys
[ "56a2a272432549076cd6c76b6f3fb50921a68743" ]
[ "RecSys/recsys_cf_svdpp.py" ]
[ "# -*- coding: utf-8 -*-\n__author__ = 'Adward'\n\n# Python utils imports\nimport os\nimport sys\nfrom time import time\nimport sqlite3\n\n# Standard scientific Python imports\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.sparse import csr_matrix, hstack, coo_matrix\nfrom scipy.sparse.linalg import svds\n\n# Import classifiers and performance metrics\nfrom sklearn.preprocessing import *\nfrom sklearn.cross_validation import StratifiedKFold, ShuffleSplit\nfrom sklearn.metrics import *\nfrom sklearn.decomposition import TruncatedSVD\nimport warnings\n\n# Constant values\nDATA_PATH = '/Users/Adward/OneDrive/YelpData/'\nDB_PATH = os.path.join(DATA_PATH, 'yelp.sqlite')\nCODE_PATH = os.path.join(os.path.dirname(__file__))\n# review_n = 2225213\n# user_n = 552339\n# business_n = 77445\n\n\nclass SVDPlusPlus(object):\n def __init__(self, n_components=2, max_iter=5, random_state=None, tol=0.1):\n self.n_components = n_components\n self.max_iter = max_iter\n self.random_state = random_state\n self.tol = tol\n self.P = None\n self.Q = None\n self.bias_i = None\n self.bias_u = None\n self.item_weights = None\n self.miu = 0\n\n # def fit(self, X, y=None):\n # self.fit_transform(X)\n # return self\n\n def fit(self, X, R_test=None, lambda_=0.04, gamma=0.15, verbose=False, warm_start=True):\n warnings.filterwarnings('error')\n # If sparse and not csr or csc, convert to csr\n if sp.issparse(X) and X.getformat() not in [\"csr\", \"csc\"]:\n X = X.tocsr()\n\n k = self.n_components\n n_user, n_item = X.shape\n if k >= n_item:\n raise ValueError(\"n_components must be < n_features;\"\n \"got %d >= %d\" % (k, n_item))\n\n print(\"init item & user biases vectors, together with global means...\") if verbose else None\n self.miu = X.sum(0).sum() / X.getnnz(0).sum() # global average of ratings\n for row in range(len(X.data)):\n X.data[row] -= self.miu\n\n sums = X.sum(0) # 1 x item_n\n nnzs = X.getnnz(0)\n self.bias_i = np.zeros((n_item, ))\n for j in range(n_item):\n nz = nnzs[j]\n if nz:\n self.bias_i[j] = sums[0, j] / nz\n\n sums = X.sum(1) # user_n x 1\n nnzs = X.getnnz(1)\n self.bias_u = np.zeros((n_user, ))\n for i in range(n_user):\n nz = nnzs[i]\n if nz:\n self.bias_u[i] = sums[i, 0] / nz\n\n print(\"extract global and local biases from data...\") if verbose else None\n X_csc = X.tocsc()\n for row in range(len(X.data)):\n X.data[row] -= \\\n self.bias_i[X.indices[row]] + self.bias_u[X_csc.indices[row]] + self.miu\n\n print(\"init latent factor dense matrix P, Q...\") if verbose else None\n if warm_start:\n svd = TruncatedSVD(n_components=self.n_components)\n svd.fit(X)\n self.P = svd.transform(X) # numpy.ndarray\n self.Q = svd.components_.T\n else:\n self.P = np.random.randn(n_user, k) / 1e5\n self.Q = np.random.randn(n_item, k) / 1e5\n\n print(\"init movie weights dense matrix (n_item x k)...\") if verbose else None\n self.item_weights = np.random.randn(n_item, k) / 1e5\n\n print(\"start gradient descent of svd++...\") if verbose else None\n for step in range(self.max_iter):\n t = time()\n for uid in range(n_user):\n Ru_ids = range(X.indptr[uid], X.indptr[uid+1])\n Ru_cols = np.array([X.indices[row] for row in Ru_ids])\n if len(Ru_cols) == 0:\n continue\n urcnt = np.sqrt(len(Ru_ids))\n pu_append = self.item_weights[Ru_cols, :].sum(0) / urcnt\n for row in Ru_ids:\n iid = X.indices[row]\n pu = self.P[uid, :]\n qi = self.Q[iid, :]\n r_pred = self.miu + self.bias_i[iid] + self.bias_u[uid] + qi.dot(pu + pu_append)\n err = X.data[row] - r_pred\n if err < self.tol:\n continue\n # synchronized update gradient descents\n bu_new = self.bias_u[uid] + gamma * (err - lambda_ * self.bias_u[uid])\n bi_new = self.bias_i[iid] + gamma * (err - lambda_ * self.bias_i[iid])\n pu_new = pu + gamma * (err * qi - lambda_ * pu)\n try:\n qi_new = qi + gamma * (err * (pu + pu_append) - lambda_ * qi)\n except:\n print(qi, err, pu, pu_append)\n # y_new = item_weights + gamma * (err / urcnt - lambda_) * qi\n # real updating\n self.bias_u[uid] = bu_new\n self.bias_i[iid] = bi_new\n self.P[uid, :] = pu_new\n self.Q[iid, :] = qi_new\n self.item_weights[iid, :] += gamma * (err / urcnt - lambda_) * qi\n\n # if uid % 10000 == 0:\n # print(uid * 100 / 552339, '%')\n gamma *= 0.93\n print('Finishing round', step, 'and', time()-t, 's used.') if verbose else None\n\n # predicting\n if R_test is None:\n return\n self.predict_and_score(R_test)\n\n def predict_and_score(self, R):\n if sp.issparse(R) and R.getformat() not in [\"csr\", \"csc\"]:\n R = R.tocsr()\n nnz = len(R.data)\n r_pred = np.zeros((nnz, ))\n n_user, n_item = R.shape\n pred_idx = -1\n for uid in range(n_user):\n Ru_ids = range(R.indptr[uid], R.indptr[uid+1])\n Ru_cols = np.array([R.indices[row] for row in Ru_ids])\n if len(Ru_cols) == 0:\n continue\n urcnt = np.sqrt(len(Ru_ids))\n pu_append = self.item_weights[Ru_cols, :].sum(0) / urcnt\n for row in Ru_ids:\n pred_idx += 1\n iid = R.indices[row]\n pu = self.P[uid, :]\n qi = self.Q[iid, :]\n r_pred[pred_idx] = round(self.miu + self.bias_i[iid] + self.bias_u[uid]\n + qi.dot(pu + pu_append))\n if r_pred[pred_idx] < 1:\n r_pred[pred_idx] = 1\n elif r_pred[pred_idx] > 5:\n r_pred[pred_idx] = 5\n\n # scoring\n print(r_pred)\n rmse = mean_squared_error(y_true=R.data, y_pred=r_pred) ** 0.5\n mae = mean_absolute_error(y_true=R.data, y_pred=r_pred)\n print('RMSE:', rmse, 'MAE:', mae)\n print(classification_report(R.data, r_pred))\n\n def gen_latent_feature_space(self):\n if self.P is None:\n raise ValueError(\"Must be executed after SVD model is fitted. \")\n\n with sqlite3.connect(DB_PATH) as conn:\n cur = conn.execute('SELECT user_id FROM user')\n uid_idx = {}\n line_n = 0\n for row in cur:\n uid_idx[row[0]] = line_n\n line_n += 1\n\n cur = conn.execute('SELECT business_id FROM business')\n bid_idx = {}\n line_n = 0\n for row in cur:\n bid_idx[row[0]] = line_n\n line_n += 1\n\n cur_r = conn.execute('SELECT business_id, user_id FROM review')\n X_part = [np.append(self.Q[bid_idx[bid]], self.P[uid_idx[uid]])\n for bid, uid in cur_r]\n return np.array(X_part)\n\n\nif __name__ == '__main__':\n R_train = np.load(os.path.join(CODE_PATH, 'r_matrix_train.npy'))[()]\n R_test = np.load(os.path.join(CODE_PATH, 'r_matrix_test.npy'))[()]\n svdpp = SVDPlusPlus(n_components=5, max_iter=1, tol=0.1)\n svdpp.fit(R_train, R_test, verbose=True, warm_start=False)" ]
[ [ "sklearn.decomposition.TruncatedSVD", "scipy.sparse.issparse", "numpy.append", "numpy.random.randn", "numpy.array", "numpy.zeros" ] ]
[ { "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": [] } ]
IntelLabs/OSCAR
[ "25d1dea35727379117e11b7238b5a0d1ed19acad" ]
[ "oscar/attacks/static_patch.py" ]
[ "#\n# Copyright (C) 2020 Intel Corporation\n#\n# SPDX-License-Identifier: BSD-3-Clause\n#\n\nfrom art.attacks.attack import EvasionAttack\nfrom art.utils import check_and_transform_label_format\nfrom art.estimators.estimator import BaseEstimator, LossGradientsMixin\nfrom art.estimators.classification.classifier import ClassifierMixin\n\nimport numpy as np\nfrom typing import Union\n\n\nclass StaticPatch(EvasionAttack):\n \"\"\"\n Apply Static Patch attack to video input with shape (NTHWC),\n where the patch is same through all frames within a video.\n \"\"\"\n attack_params = EvasionAttack.attack_params + [\n \"norm\",\n \"eps\",\n \"eps_step\",\n \"targeted\",\n \"num_random_init\",\n \"batch_size\",\n \"max_iter\",\n \"verbose\",\n \"patch_ratio\",\n \"xmin\",\n \"ymin\",\n \"patch_width\",\n \"patch_height\"\n ]\n\n _estimator_requirements = (BaseEstimator, LossGradientsMixin, ClassifierMixin)\n\n def __init__(\n self,\n estimator,\n norm: Union[int, float, str] = np.inf,\n eps: Union[int, float, np.ndarray] = 0.3,\n eps_step: Union[int, float, np.ndarray] = 0.1,\n max_iter: int = 10,\n targeted: bool = False,\n num_random_init: int = 0,\n batch_size: int = 1,\n verbose: bool = True,\n xmin: int = 0,\n ymin: int = 0,\n patch_ratio: float = 0,\n patch_width: int = 0,\n patch_height: int = 0,\n ):\n super().__init__(estimator=estimator)\n\n self.norm = norm\n self.eps = eps # Keep for science scenario's security curve\n self.eps_step = eps_step\n self.max_iter = max_iter\n self.targeted = targeted\n self.num_random_init = num_random_init\n self.batch_size = batch_size\n self.verbose = verbose\n self.xmin = xmin\n self.ymin = ymin\n self.patch_ratio = patch_ratio\n self.patch_width = patch_width\n self.patch_height = patch_height\n self._check_params()\n\n if self.norm not in [np.inf, \"inf\"]:\n raise ValueError(\n \"Currently only Linf norm is supported\"\n )\n\n if (self.patch_width <= 0 or self.patch_height <= 0) and self.patch_ratio <= 0:\n raise ValueError(\n \"kwargs did not define 'patch_height' and 'patch_width', or it did not define 'patch_ratio'\"\n )\n\n def generate(self, x, y=None, **generate_kwargs):\n # input x should be with shape (NTHWC)\n assert x.ndim == 5, \"This attack is designed for videos with shape (NTHWC)\"\n assert x.shape[-1] == 3, \"Input should have 3 channels in the last dimension\"\n\n width, height = x.shape[-2], x.shape[-3]\n if self.xmin >= width:\n raise ValueError(\"'xmin' should be smaller than input width\")\n if self.ymin >= height:\n raise ValueError(\"'ymin' should be smaller than input height\")\n\n patch_width = self.patch_width\n patch_height = self.patch_height\n\n if self.patch_ratio > 0:\n # Make patch shape a square\n patch_width = int(min(width, height) * self.patch_ratio ** 0.5)\n patch_height = patch_width\n\n xmax = min(self.xmin + patch_width, width)\n ymax = min(self.ymin + patch_height, height)\n\n if y is None:\n if self.targeted:\n raise ValueError(\"Targeted Static Patch attack requires labels 'y'\")\n y = self.estimator.predict(x).argmax()\n y = np.expand_dims(y, 0)\n targets = check_and_transform_label_format(y, self.estimator.nb_classes)\n\n mask = np.zeros(shape=x.shape[1:], dtype=bool)\n mask[:, self.ymin:ymax, self.xmin:xmax, :] = 1\n init_patch = np.mean(self.estimator.clip_values, dtype=np.float32)\n\n # Fix me: add batching\n assert self.batch_size == 1\n for random_init in range(max(1, self.num_random_init)):\n # Set the masked area in x\n if random_init > 0:\n init_patch = np.float32(np.random.uniform(0.4, 0.6))\n x_masked = x * ~mask + init_patch * mask\n\n # Apply a constant patch to all frames\n for _ in range(self.max_iter):\n grad = self.estimator.loss_gradient(x=x_masked, y=targets) * (1 - 2 * int(self.targeted))\n grad = np.where(mask == 0.0, 0.0, grad)\n assert grad.shape == x_masked.shape\n\n # Average masked gradients through all frames with shape (NTHWC)\n ave_grad = np.mean(grad, axis=1, keepdims=True)\n\n perturbs = np.sign(ave_grad) * self.eps_step\n x_masked = x_masked + perturbs\n clip_min, clip_max = self.estimator.clip_values\n x_masked = np.clip(x_masked, clip_min, clip_max)\n\n y_pred = self.estimator.predict(x_masked).argmax()\n if y_pred != y:\n break\n\n return x_masked\n\n" ]
[ [ "numpy.expand_dims", "numpy.clip", "numpy.sign", "numpy.mean", "numpy.random.uniform", "numpy.where", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sanixa/CADA-VAE-pytorch
[ "9383c3067ce84f351c72a285d6da5724dcd710a6" ]
[ "model/single_experiment.py" ]
[ "\n### execute this function to train and test the vae-model\n\nfrom vaemodel import Model\nimport numpy as np\nimport pickle\nimport torch\nimport os\nimport argparse\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--dataset')\nparser.add_argument('--num_shots',type=int)\nparser.add_argument('--generalized', type = str2bool)\nargs = parser.parse_args()\n\n\n########################################\n# the basic hyperparameters\n########################################\nhyperparameters = {\n 'num_shots': 0,\n 'device': 'cuda',\n 'model_specifics': {'cross_reconstruction': True,\n 'name': 'CADA',\n 'distance': 'wasserstein',\n 'warmup': {'beta': {'factor': 0.25,\n 'end_epoch': 93,\n 'start_epoch': 0},\n 'cross_reconstruction': {'factor': 2.37,\n 'end_epoch': 75,\n 'start_epoch': 21},\n 'distance': {'factor': 8.13,\n 'end_epoch': 22,\n 'start_epoch': 6}}},\n\n 'lr_gen_model': 0.00015,\n 'generalized': True,\n 'batch_size': 50,\n 'xyu_samples_per_class': {'SUN': (200, 0, 400, 0),\n 'APY': (200, 0, 400, 0),\n 'CUB': (200, 0, 400, 0),\n 'AWA2': (200, 0, 400, 0),\n 'FLO': (200, 0, 400, 0),\n 'plant': (200, 0, 400, 0),\n 'AWA1': (200, 0, 400, 0)},\n 'epochs': 100,\n 'loss': 'l1',\n 'auxiliary_data_source' : 'attributes',\n 'lr_cls': 0.001,\n 'dataset': 'CUB',\n 'hidden_size_rule': {'resnet_features': (1560, 1660),\n 'attributes': (1450, 665),\n 'sentences': (1450, 665) },\n 'latent_size': 64\n}\n\n# The training epochs for the final classifier, for early stopping,\n# as determined on the validation spit\n\ncls_train_steps = [\n {'dataset': 'SUN', 'num_shots': 0, 'generalized': True, 'cls_train_steps': 21},\n {'dataset': 'SUN', 'num_shots': 0, 'generalized': False, 'cls_train_steps': 30},\n {'dataset': 'SUN', 'num_shots': 1, 'generalized': True, 'cls_train_steps': 22},\n {'dataset': 'SUN', 'num_shots': 1, 'generalized': False, 'cls_train_steps': 96},\n {'dataset': 'SUN', 'num_shots': 5, 'generalized': True, 'cls_train_steps': 29},\n {'dataset': 'SUN', 'num_shots': 5, 'generalized': False, 'cls_train_steps': 78},\n {'dataset': 'SUN', 'num_shots': 2, 'generalized': True, 'cls_train_steps': 29},\n {'dataset': 'SUN', 'num_shots': 2, 'generalized': False, 'cls_train_steps': 61},\n {'dataset': 'SUN', 'num_shots': 10, 'generalized': True, 'cls_train_steps': 79},\n {'dataset': 'SUN', 'num_shots': 10, 'generalized': False, 'cls_train_steps': 94},\n {'dataset': 'AWA1', 'num_shots': 0, 'generalized': True, 'cls_train_steps': 33},\n {'dataset': 'AWA1', 'num_shots': 0, 'generalized': False, 'cls_train_steps': 25},\n {'dataset': 'AWA1', 'num_shots': 1, 'generalized': True, 'cls_train_steps': 40},\n {'dataset': 'AWA1', 'num_shots': 1, 'generalized': False, 'cls_train_steps': 81},\n {'dataset': 'AWA1', 'num_shots': 5, 'generalized': True, 'cls_train_steps': 89},\n {'dataset': 'AWA1', 'num_shots': 5, 'generalized': False, 'cls_train_steps': 62},\n {'dataset': 'AWA1', 'num_shots': 2, 'generalized': True, 'cls_train_steps': 56},\n {'dataset': 'AWA1', 'num_shots': 2, 'generalized': False, 'cls_train_steps': 59},\n {'dataset': 'AWA1', 'num_shots': 10, 'generalized': True, 'cls_train_steps': 100},\n {'dataset': 'AWA1', 'num_shots': 10, 'generalized': False, 'cls_train_steps': 50},\n {'dataset': 'CUB', 'num_shots': 0, 'generalized': True, 'cls_train_steps': 23},\n {'dataset': 'CUB', 'num_shots': 0, 'generalized': False, 'cls_train_steps': 22},\n {'dataset': 'CUB', 'num_shots': 1, 'generalized': True, 'cls_train_steps': 34},\n {'dataset': 'CUB', 'num_shots': 1, 'generalized': False, 'cls_train_steps': 46},\n {'dataset': 'CUB', 'num_shots': 5, 'generalized': True, 'cls_train_steps': 64},\n {'dataset': 'CUB', 'num_shots': 5, 'generalized': False, 'cls_train_steps': 73},\n {'dataset': 'CUB', 'num_shots': 2, 'generalized': True, 'cls_train_steps': 39},\n {'dataset': 'CUB', 'num_shots': 2, 'generalized': False, 'cls_train_steps': 31},\n {'dataset': 'CUB', 'num_shots': 10, 'generalized': True, 'cls_train_steps': 85},\n {'dataset': 'CUB', 'num_shots': 10, 'generalized': False, 'cls_train_steps': 67},\n {'dataset': 'AWA2', 'num_shots': 0, 'generalized': True, 'cls_train_steps': 29},\n {'dataset': 'AWA2', 'num_shots': 0, 'generalized': False, 'cls_train_steps': 39},\n {'dataset': 'AWA2', 'num_shots': 1, 'generalized': True, 'cls_train_steps': 44},\n {'dataset': 'AWA2', 'num_shots': 1, 'generalized': False, 'cls_train_steps': 96},\n {'dataset': 'AWA2', 'num_shots': 5, 'generalized': True, 'cls_train_steps': 99},\n {'dataset': 'AWA2', 'num_shots': 5, 'generalized': False, 'cls_train_steps': 100},\n {'dataset': 'AWA2', 'num_shots': 2, 'generalized': True, 'cls_train_steps': 69},\n {'dataset': 'AWA2', 'num_shots': 2, 'generalized': False, 'cls_train_steps': 79},\n {'dataset': 'AWA2', 'num_shots': 10, 'generalized': True, 'cls_train_steps': 86},\n {'dataset': 'AWA2', 'num_shots': 10, 'generalized': False, 'cls_train_steps': 78},\n {'dataset': 'plant', 'num_shots': 0, 'generalized': True, 'cls_train_steps': 86}\n ]\n\n##################################\n# change some hyperparameters here\n##################################\nhyperparameters['dataset'] = args.dataset\nhyperparameters['num_shots']= args.num_shots\nhyperparameters['generalized']= args.generalized\n\nhyperparameters['cls_train_steps'] = [x['cls_train_steps'] for x in cls_train_steps\n if all([hyperparameters['dataset']==x['dataset'],\n hyperparameters['num_shots']==x['num_shots'],\n hyperparameters['generalized']==x['generalized'] ])][0]\n\nprint('***')\nprint(hyperparameters['cls_train_steps'] )\nif hyperparameters['generalized']:\n if hyperparameters['num_shots']==0:\n hyperparameters['samples_per_class'] = {'CUB': (200, 0, 400, 0), 'SUN': (200, 0, 400, 0),\n 'APY': (200, 0, 400, 0), 'AWA1': (200, 0, 400, 0),\n 'AWA2': (200, 0, 400, 0), 'FLO': (200, 0, 400, 0), 'plant': (200, 0, 400, 0)}\n else:\n hyperparameters['samples_per_class'] = {'CUB': (200, 0, 200, 200), 'SUN': (200, 0, 200, 200),\n 'APY': (200, 0, 200, 200), 'AWA1': (200, 0, 200, 200),\n 'AWA2': (200, 0, 200, 200), 'FLO': (200, 0, 200, 200)}\nelse:\n if hyperparameters['num_shots']==0:\n hyperparameters['samples_per_class'] = {'CUB': (0, 0, 200, 0), 'SUN': (0, 0, 200, 0),\n 'APY': (0, 0, 200, 0), 'AWA1': (0, 0, 200, 0),\n 'AWA2': (0, 0, 200, 0), 'FLO': (0, 0, 200, 0)}\n else:\n hyperparameters['samples_per_class'] = {'CUB': (0, 0, 200, 200), 'SUN': (0, 0, 200, 200),\n 'APY': (0, 0, 200, 200), 'AWA1': (0, 0, 200, 200),\n 'AWA2': (0, 0, 200, 200), 'FLO': (0, 0, 200, 200)}\n\n\nmodel = Model( hyperparameters)\nmodel.to(hyperparameters['device'])\n\n\"\"\"\n########################################\n### load model where u left\n########################################\nsaved_state = torch.load('./saved_models/CADA_trained.pth.tar')\nmodel.load_state_dict(saved_state['state_dict'])\nfor d in model.all_data_sources_without_duplicates:\n model.encoder[d].load_state_dict(saved_state['encoder'][d])\n model.decoder[d].load_state_dict(saved_state['decoder'][d])\n########################################\n\"\"\"\n\n\nlosses = model.train_vae()\n\nu,s,h,history = model.train_classifier()\n\n\nif hyperparameters['generalized']==True:\n acc = [hi[2] for hi in history]\nelif hyperparameters['generalized']==False:\n acc = [hi[1] for hi in history]\n\nprint(acc[-1])\n\n\nstate = {\n 'state_dict': model.state_dict() ,\n 'hyperparameters':hyperparameters,\n 'encoder':{},\n 'decoder':{}\n }\nfor d in model.all_data_sources:\n state['encoder'][d] = model.encoder[d].state_dict()\n state['decoder'][d] = model.decoder[d].state_dict()\n\n\ntorch.save(state, 'CADA_trained.pth.tar')\nprint('>> saved')\n" ]
[ [ "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tian-yu/INF552
[ "1a754c0d7ccfbc731abaa8fa42249cb1e1f30a71" ]
[ "hw4/Logistic_Regression.py" ]
[ "#\n# INF 552 Homework 4\n# Part: Logistic Regression\n# Group Members: Tianyu Zhang (zhan198), Minyi Huang (minyihua), Jeffy Merin Jacob (jeffyjac)\n# Date: 3/09/2018\n# Programming Language: Python 3.6\n#\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.linear_model import LogisticRegression\n\nnumber_of_iterations = 7000\ninput = np.loadtxt(\"classification.txt\", delimiter=',', usecols=(0, 1, 2), unpack=True).T\nprint(input)\n\nlabels = np.transpose(np.loadtxt(\"classification.txt\", delimiter=',', usecols=(4), unpack=True))\nprint(labels)\n\ndef showData(input, labels):\n fig = plt.figure(figsize=(12,8))\n ax = fig.gca(projection='3d')\n cm = plt.cm.get_cmap('PiYGh4')\n ax.scatter(input[:, 0], input[:, 1], input[:, 2],\n c = labels, vmin=-1.2, vmax=1.1, cmap=cm)\n plt.show()\n\ndef sigmoidFunction(s):\n return np.exp(s) / (1 + np.exp(s))\n\ndef E_out(input, labels, weights):\n dot_product = np.dot(input, weights)\n result = (input.shape[1]) * np.sum(np.log(1 + np.exp((-1) * labels * dot_product)))\n return result\n\n# def getGradient(input, labels, weights):\n# dot_product = np.dot(input, weights)\n# item_1 = 1 / (1 + np.exp((-1) * labels * dot_product))\n# item_2 = (-1) * np.exp((-1) * labels * dot_product)\n# item_3 = labels[:, np.newaxis] * input\n# # item_3 = np.dot(labels, input)\n# gradient = (input.shape[1]) * np.sum((item_1 * item_2)[:, np.newaxis] * item_3)\n# return gradient\n\ndef getGradient(input, labels, weights):\n dot_product = np.dot(input, weights)\n item_1 = 1 / (1 + np.exp((-1) * np.dot(labels, dot_product)))\n item_2 = (-1) * np.exp((-1) * np.dot(labels, dot_product))\n # item_3 = labels[:, np.newaxis] * input\n item_3 = np.dot(labels, input)\n gradient = (input.shape[1]) * np.sum(np.dot(np.dot(item_1, item_2), item_3))\n return gradient\n\ndef logisitic_regresssion_loop(input, labels, number_of_iterations, learning_rate, with_intercept=False):\n if with_intercept :\n intercept = np.ones((input.shape[0], 1))\n input = np.hstack((intercept, input))\n\n weights = np.random.rand(input.shape[1])\n for i in range(number_of_iterations):\n weights -= learning_rate * getGradient(input, labels, weights)\n\n # Printing E_out value for debugging\n # if i % 1000 == 0:\n # print (E_out(input, labels, weights))\n return input, weights\n\n\n# def calculateAccuracy(input, labels, weights):\n# predication = np.round(sigmoidFunction(np.dot(input, weights)))\n# accuracy = (predication == labels).sum().astype(float) / len(predication)\n# return accuracy\n\n# def calculateAccuracy(input, labels, weights):\n# dot_product = np.dot(input, weights)\n# s = labels[:, np.newaxis] * dot_product\n# accuracy = np.exp(np.sum(np.log(sigmoidFunction(s))))\n# return accuracy\n\ndef calculateAccuracy(input, labels, weights):\n dot_product = np.dot(input, weights)\n s = labels[:, np.newaxis] * dot_product\n accuracy = np.mean(sigmoidFunction(s))\n return accuracy\n\ndef showPrediction(input, labels, predication):\n fig = plt.figure(figsize=(12, 8))\n ax = fig.gca(projection='3d')\n cm = plt.cm.get_cmap('bwr')\n error_map = np.array(predication != labels)\n error_map = error_map.astype(int)\n ax.scatter(input[:, 0], input[:, 1], input[:, 2],\n c=error_map, vmin=0, vmax=1, cmap=cm)\n plt.show()\n\ninput_intercepted, weights = logisitic_regresssion_loop(input, labels, number_of_iterations, learning_rate=0.00001, with_intercept=True)\naccuracy = calculateAccuracy(input_intercepted, labels, weights)\n\nsk_logistic = LogisticRegression(fit_intercept=True, C = 1e16)\nsk_logistic.fit(input, labels)\n\n\nprint(\"\\nAfter {number_of_iterations} iterations\\n\".format(number_of_iterations = number_of_iterations))\nprint(\"Weights of our model:\\t\")\nprint(weights)\nprint(\"Weights of scikit-learn:\\t\")\nprint(np.append(sk_logistic.intercept_, sk_logistic.coef_[0]))\nprint(\"\\n\")\n\nprint(\"Accuracy of our model:\\t{a}\".format(a = accuracy))\n# print(clf.n_iter_)\nprint(\"Accuracy of scikit-learn:\\t{a}\".format(a = sk_logistic.score(input, labels)))\n\n# showPrediction(input, labels, np.round(sigmoidFunction(np.dot(input_intercepted, weights))))\n# showPrediction(input, labels, sk_logistic.predict(input))" ]
[ [ "numpy.dot", "numpy.hstack", "sklearn.linear_model.LogisticRegression", "matplotlib.pyplot.cm.get_cmap", "numpy.ones", "numpy.append", "numpy.random.rand", "numpy.exp", "numpy.array", "matplotlib.pyplot.show", "numpy.loadtxt", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
velasquezg1/python-challenge
[ "1a1ea80ae2d3f63a8e2cfc2ca41d499660466cf0" ]
[ "PyPoll.py" ]
[ "import pandas as pd\r\n\r\ndat=pd.read_csv('election_data.csv')\r\ndat=dat.reset_index()\r\ntotalvotes=len(dat.index)\r\nx=dat.iloc[:,3]\r\nl1=[]\r\nfor i in range(0,totalvotes):\r\n if(x[i] not in l1):\r\n l1.append(x[i])\r\nl2=[0]*len(l1)\r\nfor i in l1:\r\n for j in x:\r\n if(i==j):\r\n l2[l1.index(i)]+=1 \r\nsum1=sum(l2)\r\nl3=[0.0]*len(l2) \r\nfor i in range(0,len(l2)):\r\n l3[i]=l2[i]/sum1\r\n\r\nwinner=l1[l2.index(max(l2))]\r\n\r\nprint('Total Votes: ',totalvotes)\r\nfor i in range(0,len(l2)):\r\n #print(l1[i]+\" \"+str(l3[i]*100.0)+\"% (\"+str(l2[i])+\")\")\r\n print(f'{l1[i]} {l3[i]*100.0:.3f}% {l2[i]}')\r\n\r\nprint(\"Winner: \",winner)\r\n\r\nf = open('PyPoll.txt','a')\r\n\r\nf.write('Total Votes: '+str(totalvotes))\r\nfor i in range(0,len(l2)):\r\n f.write(f'\\n{l1[i]} {l3[i]*100.0:.3f}% {l2[i]}')\r\nf.write('\\nWinner: '+str(winner))\r\nf.close()\r\n\r\n\r\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
pcandoalmeida/pandas
[ "d81e226bbf0c3918e15c37f4ba810c2c264a35f3" ]
[ "pandas/core/indexes/numeric.py" ]
[ "from typing import TYPE_CHECKING, Any\n\nimport numpy as np\n\nfrom pandas._libs import index as libindex, lib\nfrom pandas._typing import Dtype\nfrom pandas.util._decorators import Appender, cache_readonly\n\nfrom pandas.core.dtypes.cast import astype_nansafe\nfrom pandas.core.dtypes.common import (\n is_bool,\n is_bool_dtype,\n is_dtype_equal,\n is_extension_array_dtype,\n is_float,\n is_float_dtype,\n is_integer_dtype,\n is_scalar,\n is_signed_integer_dtype,\n is_unsigned_integer_dtype,\n needs_i8_conversion,\n pandas_dtype,\n)\nfrom pandas.core.dtypes.generic import (\n ABCFloat64Index,\n ABCInt64Index,\n ABCRangeIndex,\n ABCSeries,\n ABCUInt64Index,\n)\nfrom pandas.core.dtypes.missing import isna\n\nfrom pandas.core import algorithms\nimport pandas.core.common as com\nfrom pandas.core.indexes.base import (\n Index,\n InvalidIndexError,\n _index_shared_docs,\n maybe_extract_name,\n)\nfrom pandas.core.ops import get_op_result_name\n\nif TYPE_CHECKING:\n from pandas import Series\n\n_num_index_shared_docs = dict()\n\n\nclass NumericIndex(Index):\n \"\"\"\n Provide numeric type operations.\n\n This is an abstract class.\n \"\"\"\n\n _is_numeric_dtype = True\n\n def __new__(cls, data=None, dtype=None, copy=False, name=None):\n cls._validate_dtype(dtype)\n name = maybe_extract_name(name, data, cls)\n\n # Coerce to ndarray if not already ndarray or Index\n if not isinstance(data, (np.ndarray, Index)):\n if is_scalar(data):\n raise cls._scalar_data_error(data)\n\n # other iterable of some kind\n if not isinstance(data, (ABCSeries, list, tuple)):\n data = list(data)\n\n data = np.asarray(data, dtype=dtype)\n\n if issubclass(data.dtype.type, str):\n cls._string_data_error(data)\n\n if copy or not is_dtype_equal(data.dtype, cls._default_dtype):\n subarr = np.array(data, dtype=cls._default_dtype, copy=copy)\n cls._assert_safe_casting(data, subarr)\n else:\n subarr = data\n\n if subarr.ndim > 1:\n # GH#13601, GH#20285, GH#27125\n raise ValueError(\"Index data must be 1-dimensional\")\n\n subarr = np.asarray(subarr)\n return cls._simple_new(subarr, name=name)\n\n @classmethod\n def _validate_dtype(cls, dtype: Dtype) -> None:\n if dtype is None:\n return\n validation_metadata = {\n \"int64index\": (is_signed_integer_dtype, \"signed integer\"),\n \"uint64index\": (is_unsigned_integer_dtype, \"unsigned integer\"),\n \"float64index\": (is_float_dtype, \"float\"),\n \"rangeindex\": (is_signed_integer_dtype, \"signed integer\"),\n }\n\n validation_func, expected = validation_metadata[cls._typ]\n if not validation_func(dtype):\n raise ValueError(\n f\"Incorrect `dtype` passed: expected {expected}, received {dtype}\"\n )\n\n @Appender(_index_shared_docs[\"_maybe_cast_slice_bound\"])\n def _maybe_cast_slice_bound(self, label, side, kind):\n assert kind in [\"loc\", \"getitem\", None]\n\n # we will try to coerce to integers\n return self._maybe_cast_indexer(label)\n\n @Appender(_index_shared_docs[\"_shallow_copy\"])\n def _shallow_copy(self, values=None, **kwargs):\n if values is not None and not self._can_hold_na:\n # Ensure we are not returning an Int64Index with float data:\n return self._shallow_copy_with_infer(values=values, **kwargs)\n return super()._shallow_copy(values=values, **kwargs)\n\n def _convert_for_op(self, value):\n \"\"\"\n Convert value to be insertable to ndarray.\n \"\"\"\n if is_bool(value) or is_bool_dtype(value):\n # force conversion to object\n # so we don't lose the bools\n raise TypeError\n\n return value\n\n def _convert_tolerance(self, tolerance, target):\n tolerance = np.asarray(tolerance)\n if target.size != tolerance.size and tolerance.size > 1:\n raise ValueError(\"list-like tolerance size must match target index size\")\n if not np.issubdtype(tolerance.dtype, np.number):\n if tolerance.ndim > 0:\n raise ValueError(\n f\"tolerance argument for {type(self).__name__} must contain \"\n \"numeric elements if it is list type\"\n )\n else:\n raise ValueError(\n f\"tolerance argument for {type(self).__name__} must be numeric \"\n f\"if it is a scalar: {repr(tolerance)}\"\n )\n return tolerance\n\n @classmethod\n def _assert_safe_casting(cls, data, subarr):\n \"\"\"\n Subclasses need to override this only if the process of casting data\n from some accepted dtype to the internal dtype(s) bears the risk of\n truncation (e.g. float to int).\n \"\"\"\n pass\n\n def _concat_same_dtype(self, indexes, name):\n result = type(indexes[0])(np.concatenate([x._values for x in indexes]))\n return result.rename(name)\n\n @property\n def is_all_dates(self) -> bool:\n \"\"\"\n Checks that all the labels are datetime objects.\n \"\"\"\n return False\n\n @Appender(Index.insert.__doc__)\n def insert(self, loc: int, item):\n # treat NA values as nans:\n if is_scalar(item) and isna(item):\n item = self._na_value\n return super().insert(loc, item)\n\n def _union(self, other, sort):\n # Right now, we treat union(int, float) a bit special.\n # See https://github.com/pandas-dev/pandas/issues/26778 for discussion\n # We may change union(int, float) to go to object.\n # float | [u]int -> float (the special case)\n # <T> | <T> -> T\n # <T> | <U> -> object\n needs_cast = (is_integer_dtype(self.dtype) and is_float_dtype(other.dtype)) or (\n is_integer_dtype(other.dtype) and is_float_dtype(self.dtype)\n )\n if needs_cast:\n first = self.astype(\"float\")\n second = other.astype(\"float\")\n return first._union(second, sort)\n else:\n return super()._union(other, sort)\n\n\n_num_index_shared_docs[\n \"class_descr\"\n] = \"\"\"\n Immutable ndarray implementing an ordered, sliceable set. The basic object\n storing axis labels for all pandas objects. %(klass)s is a special case\n of `Index` with purely %(ltype)s labels. %(extra)s.\n\n Parameters\n ----------\n data : array-like (1-dimensional)\n dtype : NumPy dtype (default: %(dtype)s)\n copy : bool\n Make a copy of input ndarray.\n name : object\n Name to be stored in the index.\n\n Attributes\n ----------\n None\n\n Methods\n -------\n None\n\n See Also\n --------\n Index : The base pandas Index type.\n\n Notes\n -----\n An Index instance can **only** contain hashable objects.\n\"\"\"\n\n_int64_descr_args = dict(klass=\"Int64Index\", ltype=\"integer\", dtype=\"int64\", extra=\"\")\n\n\nclass IntegerIndex(NumericIndex):\n \"\"\"\n This is an abstract class for Int64Index, UInt64Index.\n \"\"\"\n\n _default_dtype: np.dtype\n\n def __contains__(self, key) -> bool:\n \"\"\"\n Check if key is a float and has a decimal. If it has, return False.\n \"\"\"\n hash(key)\n try:\n if is_float(key) and int(key) != key:\n return False\n return key in self._engine\n except (OverflowError, TypeError, ValueError):\n return False\n\n @property\n def inferred_type(self) -> str:\n \"\"\"\n Always 'integer' for ``Int64Index`` and ``UInt64Index``\n \"\"\"\n return \"integer\"\n\n @property\n def asi8(self) -> np.ndarray:\n # do not cache or you'll create a memory leak\n return self.values.view(self._default_dtype)\n\n @Appender(_index_shared_docs[\"_convert_scalar_indexer\"])\n def _convert_scalar_indexer(self, key, kind=None):\n assert kind in [\"loc\", \"getitem\", \"iloc\", None]\n\n # don't coerce ilocs to integers\n if kind != \"iloc\":\n key = self._maybe_cast_indexer(key)\n return super()._convert_scalar_indexer(key, kind=kind)\n\n\nclass Int64Index(IntegerIndex):\n __doc__ = _num_index_shared_docs[\"class_descr\"] % _int64_descr_args\n\n _typ = \"int64index\"\n _can_hold_na = False\n _engine_type = libindex.Int64Engine\n _default_dtype = np.dtype(np.int64)\n\n def _wrap_joined_index(self, joined, other):\n name = get_op_result_name(self, other)\n return Int64Index(joined, name=name)\n\n @classmethod\n def _assert_safe_casting(cls, data, subarr):\n \"\"\"\n Ensure incoming data can be represented as ints.\n \"\"\"\n if not issubclass(data.dtype.type, np.signedinteger):\n if not np.array_equal(data, subarr):\n raise TypeError(\"Unsafe NumPy casting, you must explicitly cast\")\n\n def _is_compatible_with_other(self, other) -> bool:\n return super()._is_compatible_with_other(other) or all(\n isinstance(obj, (ABCInt64Index, ABCFloat64Index, ABCRangeIndex))\n for obj in [self, other]\n )\n\n\nInt64Index._add_numeric_methods()\nInt64Index._add_logical_methods()\n\n_uint64_descr_args = dict(\n klass=\"UInt64Index\", ltype=\"unsigned integer\", dtype=\"uint64\", extra=\"\"\n)\n\n\nclass UInt64Index(IntegerIndex):\n __doc__ = _num_index_shared_docs[\"class_descr\"] % _uint64_descr_args\n\n _typ = \"uint64index\"\n _can_hold_na = False\n _engine_type = libindex.UInt64Engine\n _default_dtype = np.dtype(np.uint64)\n\n @Appender(_index_shared_docs[\"_convert_arr_indexer\"])\n def _convert_arr_indexer(self, keyarr):\n # Cast the indexer to uint64 if possible so that the values returned\n # from indexing are also uint64.\n dtype = None\n if is_integer_dtype(keyarr) or (\n lib.infer_dtype(keyarr, skipna=False) == \"integer\"\n ):\n dtype = np.uint64\n\n return com.asarray_tuplesafe(keyarr, dtype=dtype)\n\n @Appender(_index_shared_docs[\"_convert_index_indexer\"])\n def _convert_index_indexer(self, keyarr):\n # Cast the indexer to uint64 if possible so\n # that the values returned from indexing are\n # also uint64.\n if keyarr.is_integer():\n return keyarr.astype(np.uint64)\n return keyarr\n\n def _wrap_joined_index(self, joined, other):\n name = get_op_result_name(self, other)\n return UInt64Index(joined, name=name)\n\n @classmethod\n def _assert_safe_casting(cls, data, subarr):\n \"\"\"\n Ensure incoming data can be represented as uints.\n \"\"\"\n if not issubclass(data.dtype.type, np.unsignedinteger):\n if not np.array_equal(data, subarr):\n raise TypeError(\"Unsafe NumPy casting, you must explicitly cast\")\n\n def _is_compatible_with_other(self, other) -> bool:\n return super()._is_compatible_with_other(other) or all(\n isinstance(obj, (ABCUInt64Index, ABCFloat64Index)) for obj in [self, other]\n )\n\n\nUInt64Index._add_numeric_methods()\nUInt64Index._add_logical_methods()\n\n_float64_descr_args = dict(\n klass=\"Float64Index\", dtype=\"float64\", ltype=\"float\", extra=\"\"\n)\n\n\nclass Float64Index(NumericIndex):\n __doc__ = _num_index_shared_docs[\"class_descr\"] % _float64_descr_args\n\n _typ = \"float64index\"\n _engine_type = libindex.Float64Engine\n _default_dtype = np.float64\n\n @property\n def inferred_type(self) -> str:\n \"\"\"\n Always 'floating' for ``Float64Index``\n \"\"\"\n return \"floating\"\n\n @Appender(_index_shared_docs[\"astype\"])\n def astype(self, dtype, copy=True):\n dtype = pandas_dtype(dtype)\n if needs_i8_conversion(dtype):\n raise TypeError(\n f\"Cannot convert Float64Index to dtype {dtype}; integer \"\n \"values are required for conversion\"\n )\n elif is_integer_dtype(dtype) and not is_extension_array_dtype(dtype):\n # TODO(jreback); this can change once we have an EA Index type\n # GH 13149\n arr = astype_nansafe(self.values, dtype=dtype)\n return Int64Index(arr)\n return super().astype(dtype, copy=copy)\n\n @Appender(_index_shared_docs[\"_convert_scalar_indexer\"])\n def _convert_scalar_indexer(self, key, kind=None):\n assert kind in [\"loc\", \"getitem\", \"iloc\", None]\n\n if kind == \"iloc\":\n self._validate_indexer(\"positional\", key, \"iloc\")\n\n return key\n\n @Appender(_index_shared_docs[\"_convert_slice_indexer\"])\n def _convert_slice_indexer(self, key: slice, kind=None):\n\n if kind == \"iloc\":\n return super()._convert_slice_indexer(key, kind=kind)\n\n # translate to locations\n return self.slice_indexer(key.start, key.stop, key.step, kind=kind)\n\n def _format_native_types(\n self, na_rep=\"\", float_format=None, decimal=\".\", quoting=None, **kwargs\n ):\n from pandas.io.formats.format import FloatArrayFormatter\n\n formatter = FloatArrayFormatter(\n self.values,\n na_rep=na_rep,\n float_format=float_format,\n decimal=decimal,\n quoting=quoting,\n fixed_width=False,\n )\n return formatter.get_result_as_array()\n\n def get_value(self, series: \"Series\", key):\n \"\"\"\n We always want to get an index value, never a value.\n \"\"\"\n if not is_scalar(key):\n raise InvalidIndexError\n\n loc = self.get_loc(key)\n return self._get_values_for_loc(series, loc)\n\n def equals(self, other) -> bool:\n \"\"\"\n Determines if two Index objects contain the same elements.\n \"\"\"\n if self is other:\n return True\n\n if not isinstance(other, Index):\n return False\n\n # need to compare nans locations and make sure that they are the same\n # since nans don't compare equal this is a bit tricky\n try:\n if not isinstance(other, Float64Index):\n other = self._constructor(other)\n if not is_dtype_equal(self.dtype, other.dtype) or self.shape != other.shape:\n return False\n left, right = self._ndarray_values, other._ndarray_values\n return ((left == right) | (self._isnan & other._isnan)).all()\n except (TypeError, ValueError):\n return False\n\n def __contains__(self, other: Any) -> bool:\n hash(other)\n if super().__contains__(other):\n return True\n\n return is_float(other) and np.isnan(other) and self.hasnans\n\n @Appender(_index_shared_docs[\"get_loc\"])\n def get_loc(self, key, method=None, tolerance=None):\n if is_bool(key):\n # Catch this to avoid accidentally casting to 1.0\n raise KeyError(key)\n\n if is_float(key) and np.isnan(key):\n nan_idxs = self._nan_idxs\n if not len(nan_idxs):\n raise KeyError(key)\n elif len(nan_idxs) == 1:\n return nan_idxs[0]\n return nan_idxs\n\n return super().get_loc(key, method=method, tolerance=tolerance)\n\n @cache_readonly\n def is_unique(self) -> bool:\n return super().is_unique and self._nan_idxs.size < 2\n\n @Appender(Index.isin.__doc__)\n def isin(self, values, level=None):\n if level is not None:\n self._validate_index_level(level)\n return algorithms.isin(np.array(self), values)\n\n def _is_compatible_with_other(self, other) -> bool:\n return super()._is_compatible_with_other(other) or all(\n isinstance(\n obj, (ABCInt64Index, ABCFloat64Index, ABCUInt64Index, ABCRangeIndex),\n )\n for obj in [self, other]\n )\n\n\nFloat64Index._add_numeric_methods()\nFloat64Index._add_logical_methods_disabled()\n" ]
[ [ "numpy.asarray", "pandas.core.dtypes.common.is_extension_array_dtype", "numpy.issubdtype", "pandas.core.dtypes.common.is_dtype_equal", "numpy.dtype", "numpy.concatenate", "pandas.core.common.asarray_tuplesafe", "pandas.core.indexes.base.maybe_extract_name", "pandas.core.ops.get_op_result_name", "pandas.io.formats.format.FloatArrayFormatter", "pandas.core.dtypes.common.is_float_dtype", "pandas.core.dtypes.common.is_float", "pandas.core.dtypes.common.is_integer_dtype", "pandas.util._decorators.Appender", "pandas.core.dtypes.common.pandas_dtype", "numpy.isnan", "numpy.array", "pandas.core.dtypes.common.needs_i8_conversion", "pandas.core.dtypes.common.is_bool", "pandas.core.dtypes.cast.astype_nansafe", "pandas.core.dtypes.common.is_bool_dtype", "numpy.array_equal", "pandas.core.dtypes.common.is_scalar", "pandas.core.dtypes.missing.isna", "pandas._libs.lib.infer_dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
GAIA-vision/GAIA-ssl
[ "7ac33fe2b8af0791caa89dfa789f03a3e20c9fa4", "3c22806a9337278a48dcbcc1fcc40082b8fe5af5" ]
[ "gaiassl/models/DynamicMOCO.py", "tools/search_by_distance.py" ]
[ "# standard lib\nimport pdb\n\n# 3rd-party lib\nimport torch\nimport torch.nn as nn\n\n# mm lib\nfrom openselfsup.utils import print_log\nfrom openselfsup.models import builder, MODELS\n\n\n# local lib\nfrom .base import BaseSSLearner\n\n\[email protected]_module\nclass DynamicMOCO(BaseSSLearner):\n \"\"\"DynamicMOCO.\n\n Implementation of \"Momentum Contrast for Unsupervised Visual\n Representation Learning (https://arxiv.org/abs/1911.05722)\".\n Part of the code is borrowed from:\n \"https://github.com/facebookresearch/moco/blob/master/moco/builder.py\".\n\n Args:\n backbone (dict): Config dict for module of backbone ConvNet.\n neck (dict): Config dict for module of deep features to compact feature vectors.\n Default: None.\n head (dict): Config dict for module of loss functions. Default: None.\n pretrained (str, optional): Path to pre-trained weights. Default: None.\n queue_len (int): Number of negative keys maintained in the queue.\n Default: 65536.\n feat_dim (int): Dimension of compact feature vectors. Default: 128.\n momentum (float): Momentum coefficient for the momentum-updated encoder.\n Default: 0.999.\n \"\"\"\n\n def __init__(self,\n backbone,\n neck=None,\n head=None,\n pretrained=None,\n queue_len=65536,\n feat_dim=128,\n momentum=0.999,\n same_arch=False,\n not_update_encoder_k=False,\n **kwargs):\n super().__init__()\n self.encoder_q = nn.Sequential(\n builder.build_backbone(backbone), builder.build_neck(neck))\n self.encoder_k = nn.Sequential(\n builder.build_backbone(backbone), builder.build_neck(neck))\n self.backbone = self.encoder_q[0]\n for param in self.encoder_k.parameters():\n param.requires_grad = False\n self.head = builder.build_head(head)\n self.init_weights(pretrained=pretrained)\n\n self.queue_len = queue_len\n self.momentum = momentum\n self.same_arch = same_arch\n self.not_update_encoder_k = not_update_encoder_k\n\n # create the queue\n self.register_buffer(\"queue\", torch.randn(feat_dim, queue_len))\n self.queue = nn.functional.normalize(self.queue, dim=0)\n self.register_buffer(\"queue_ptr\", torch.zeros(1, dtype=torch.long))\n \n # \n def fresh_encoder_q(self):\n '''Initialize the weights of encoder_q\n '''\n self.encoder_q[0].init_weights(pretrained=None)\n self.encoder_q[1].init_weights(init_linear='kaiming')\n \n def init_weights(self, pretrained=None):\n \"\"\"Initialize the weights of model.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Default: None.\n \"\"\"\n if pretrained is not None:\n print_log('load model from: {}'.format(pretrained), logger='root')\n self.encoder_q[0].init_weights(pretrained=pretrained)\n self.encoder_q[1].init_weights(init_linear='kaiming')\n for param_q, param_k in zip(self.encoder_q.parameters(),\n self.encoder_k.parameters()):\n param_k.data.copy_(param_q.data)\n\n @torch.no_grad()\n def _momentum_update_key_encoder(self):\n \"\"\"Momentum update of the key encoder.\"\"\"\n for param_q, param_k in zip(self.encoder_q.parameters(),\n self.encoder_k.parameters()):\n param_k.data = param_k.data * self.momentum + \\\n param_q.data * (1. - self.momentum)\n\n @torch.no_grad()\n def _dequeue_and_enqueue(self, keys):\n \"\"\"Update queue.\"\"\"\n # gather keys before updating queue\n keys = concat_all_gather(keys)\n\n batch_size = keys.shape[0]\n\n ptr = int(self.queue_ptr)\n assert self.queue_len % batch_size == 0 # for simplicity\n\n # replace the keys at ptr (dequeue and enqueue)\n self.queue[:, ptr:ptr + batch_size] = keys.transpose(0, 1)\n ptr = (ptr + batch_size) % self.queue_len # move pointer\n\n self.queue_ptr[0] = ptr\n\n @torch.no_grad()\n def _batch_shuffle_ddp(self, x):\n \"\"\"Batch shuffle, for making use of BatchNorm.\n\n *** Only support DistributedDataParallel (DDP) model. ***\n \"\"\"\n # gather from all gpus\n batch_size_this = x.shape[0]\n x_gather = concat_all_gather(x)\n batch_size_all = x_gather.shape[0]\n\n num_gpus = batch_size_all // batch_size_this\n\n # random shuffle index\n idx_shuffle = torch.randperm(batch_size_all).cuda()\n\n # broadcast to all gpus\n torch.distributed.broadcast(idx_shuffle, src=0)\n\n # index for restoring\n idx_unshuffle = torch.argsort(idx_shuffle)\n\n # shuffled index for this gpu\n gpu_idx = torch.distributed.get_rank()\n idx_this = idx_shuffle.view(num_gpus, -1)[gpu_idx]\n\n return x_gather[idx_this], idx_unshuffle\n\n @torch.no_grad()\n def _batch_unshuffle_ddp(self, x, idx_unshuffle):\n \"\"\"Undo batch shuffle.\n\n *** Only support DistributedDataParallel (DDP) model. ***\n \"\"\"\n # gather from all gpus\n batch_size_this = x.shape[0]\n x_gather = concat_all_gather(x)\n batch_size_all = x_gather.shape[0]\n\n num_gpus = batch_size_all // batch_size_this\n\n # restored index for this gpu\n gpu_idx = torch.distributed.get_rank()\n idx_this = idx_unshuffle.view(num_gpus, -1)[gpu_idx]\n\n return x_gather[idx_this]\n\n def forward_train(self, img, **kwargs):\n \"\"\"Forward computation during training.\n\n Args:\n img (Tensor): Input of two concatenated images of shape (N, 2, C, H, W).\n Typically these should be mean centered and std scaled.\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n assert img.dim() == 5, \\\n \"Input must have 5 dims, got: {}\".format(img.dim())\n im_q = img[:, 0, ...].contiguous()\n im_k = img[:, 1, ...].contiguous()\n # compute query features\n q = self.encoder_q(im_q)[0] # queries: NxC\n q = nn.functional.normalize(q, dim=1)\n\n # compute key features\n with torch.no_grad(): # no gradient to keys\n if getattr(self, '_deploying', None) is None:\n if not self.not_update_encoder_k:\n #assert 1==2,'not update'\n self._momentum_update_key_encoder() # update the key encoder\n\n # shuffle for making use of BN\n im_k, idx_unshuffle = self._batch_shuffle_ddp(im_k)\n\n k = self.encoder_k(im_k)[0] # keys: NxC\n k = nn.functional.normalize(k, dim=1)\n\n # undo shuffle\n k = self._batch_unshuffle_ddp(k, idx_unshuffle)\n\n # compute logits\n # Einstein sum is more intuitive\n # positive logits: Nx1\n l_pos = torch.einsum('nc,nc->n', [q, k]).unsqueeze(-1)\n # negative logits: NxK\n l_neg = torch.einsum('nc,ck->nk', [q, self.queue.clone().detach()])\n\n losses = self.head(l_pos, l_neg)\n self._dequeue_and_enqueue(k)\n\n return losses\n\n def forward_test(self, img, **kwargs):\n pass\n \n def forward_dummpy(self, img, **kwargs):\n assert img.dim() == 4, \\\n \"Input must have 4 dims, got: {}\".format(img.dim())\n return self.backbone(img)\n\n def forward_get_embedding(self, img, extract_from='encoder_q', **kwargs):\n #pdb.set_trace()\n \n label = kwargs.get('label', None)\n\n if img.dim() == 5:\n img = img[:, 0, ...].contiguous()\n\n with torch.no_grad():\n \n if extract_from == 'encoder_q':\n if label is not None:\n # tensor [N, D], tensor[N]\n return self.encoder_q(img)[0],label\n return self.encoder_q(img)[0]\n else:\n if label is not None:\n return self.encoder_k(img)[0],label\n return self.encoder_k(img)[0]\n\n def forward(self, img, mode='train', **kwargs):\n if mode == 'train':\n return self.forward_train(img, **kwargs)\n elif mode == 'test':\n return self.forward_test(img, **kwargs)\n elif mode == 'extract':\n if img.dim() == 5:\n img = img[:, 0, ...].contiguous()\n return self.backbone(img)\n elif mode == 'get_embedding':\n return self.forward_get_embedding(img, **kwargs) \n else:\n raise Exception(\"No such mode: {}\".format(mode))\n\n # TODO: deal with neck in encoder\n def manipulate_encoder_q(self, arch_meta):\n self.encoder_q[0].manipulate_arch(arch_meta)\n\n def manipulate_encoder_k(self, arch_meta):\n if self.same_arch:\n state = self.encoder_q[0].state()\n self.encoder_k[0].manipulate_arch(state)\n else:\n self.encoder_k[0].manipulate_arch(arch_meta)\n\n def manipulate_head(self, arch_meta):\n raise NotImplementedError\n\n# utils\[email protected]_grad()\ndef concat_all_gather(tensor):\n \"\"\"Performs all_gather operation on the provided tensors.\n\n *** Warning ***: torch.distributed.all_gather has no gradient.\n \"\"\"\n tensors_gather = [\n torch.ones_like(tensor)\n for _ in range(torch.distributed.get_world_size())\n ]\n torch.distributed.all_gather(tensors_gather, tensor, async_op=False)\n\n output = torch.cat(tensors_gather, dim=0)\n return output\n", "# standard lib\nimport os\nimport pdb\nimport time\nimport json\nimport copy\nimport argparse\nimport importlib\nimport os.path as osp\nfrom copy import deepcopy\n\n# 3rd-parth lib\nimport torch\nimport torch.distributed as dist\n\n# mm lib\nimport mmcv\nfrom mmcv import Config\nfrom mmcv.runner import init_dist, get_dist_info, load_state_dict\nfrom mmcv.parallel import MMDataParallel, MMDistributedDataParallel\n\nfrom openselfsup import __version__\nfrom openselfsup.apis import set_random_seed\nfrom openselfsup.datasets import build_dataset, build_dataloader\nfrom openselfsup.models import build_model\nfrom openselfsup.utils import collect_env, get_root_logger, traverse_replace\n\n# gaia lib\nimport gaiavision\nfrom gaiavision import broadcast_object\nfrom gaiavision.model_space import (ModelSpaceManager,\n build_sample_rule,\n build_model_sampler,\n unfold_dict,\n fold_dict)\n\nimport gaiassl\nfrom gaiassl.datasets import ScaleManipulator, manipulate_dataset\nfrom gaiassl.apis import multi_gpu_test_with_distance,multi_gpu_test_with_dense_distance\n\n\nDISTANCES = {\n 'mse': torch.nn.MSELoss,\n 'kl': torch.nn.KLDivLoss,\n 'ressl':torch.nn.KLDivLoss \n}\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Search a model')\n parser.add_argument('config', help='train config file path')\n parser.add_argument('checkpoint', help='train config file path')\n parser.add_argument(\n '--dense',\n type=bool,\n default=False,\n help='whether compare dense feature similarity')\n parser.add_argument(\n '--model_space_path',\n type=str,\n help='path of file that records model information')\n parser.add_argument(\n '--work_dir',\n type=str,\n default=None,\n help='the dir to save logs and models')\n parser.add_argument(\n '--gpus',\n type=int,\n default=1,\n help='number of gpus to use '\n '(only applicable to non-distributed training)')\n parser.add_argument('--seed', type=int, default=None, help='random seed')\n parser.add_argument('--out-name', default='metrics.json', help='output result file name')\n parser.add_argument('--metric-tag', default='distance',\n help='tag of metric in search process')\n parser.add_argument(\n '--deterministic',\n action='store_true',\n help='whether to set deterministic options for CUDNN backend.')\n parser.add_argument(\n '--launcher',\n choices=['none', 'pytorch', 'slurm', 'mpi'],\n default='none',\n help='job launcher')\n parser.add_argument('--local_rank', type=int, default=0)\n parser.add_argument('--port', type=int, default=29500,\n help='port only works when launcher==\"slurm\"')\n args = parser.parse_args()\n if 'LOCAL_RANK' not in os.environ:\n os.environ['LOCAL_RANK'] = str(args.local_rank)\n\n metric_dir = os.path.join(args.work_dir, 'search_subnet')\n args.metric_dir = metric_dir\n\n return args\n\n\ndef main():\n args = parse_args()\n\n cfg = Config.fromfile(args.config)\n # set cudnn_benchmark\n if cfg.get('cudnn_benchmark', False):\n torch.backends.cudnn.benchmark = True\n # update configs according to CLI args\n if args.work_dir is not None:\n cfg.work_dir = args.work_dir\n cfg.gpus = args.gpus\n\n # check memcached package exists\n if importlib.util.find_spec('mc') is None:\n traverse_replace(cfg, 'memcached', False)\n\n # init distributed env first, since logger depends on the dist info.\n if args.launcher == 'none':\n distributed = False\n assert cfg.model.type not in \\\n ['DeepCluster', 'MOCO', 'SimCLR', 'ODC', 'NPID'], \\\n \"{} does not support non-dist training.\".format(cfg.model.type)\n else:\n distributed = True\n if args.launcher == 'slurm':\n cfg.dist_params['port'] = args.port\n init_dist(args.launcher, **cfg.dist_params)\n rank, world_size = get_dist_info()\n\n # create work_dir\n mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))\n os.makedirs(args.metric_dir, exist_ok=True)\n save_path = os.path.join(args.metric_dir, args.out_name)\n # init the logger before other steps\n timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())\n log_file = osp.join(cfg.work_dir, 'train_{}.log'.format(timestamp))\n logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)\n\n # init the meta dict to record some important information such as\n # environment info and seed, which will be logged\n meta = dict()\n # log env info\n env_info_dict = collect_env()\n env_info = '\\n'.join([('{}: {}'.format(k, v))\n for k, v in env_info_dict.items()])\n dash_line = '-' * 60 + '\\n'\n logger.info('Environment info:\\n' + dash_line + env_info + '\\n' +\n dash_line)\n meta['env_info'] = env_info\n\n # log some basic info\n logger.info('Distributed training: {}'.format(distributed))\n logger.info('Config:\\n{}'.format(cfg.text))\n\n # load model information, CLI > cfg\n if args.model_space_path is not None:\n cfg.model_space_path = args.model_space_path\n assert cfg.get('model_space_path', None) is not None\n logger.info('Model space:\\n{}'.format(cfg.model_space_path))\n\n # set random seeds\n if args.seed is not None:\n logger.info('Set random seed to {}, deterministic: {}'.format(\n args.seed, args.deterministic))\n set_random_seed(args.seed, deterministic=args.deterministic)\n cfg.seed = args.seed\n meta['seed'] = args.seed\n\n # prepare model and pretrained weights\n model = build_model(cfg.model)\n ckpt = torch.load(args.checkpoint)['state_dict']\n\n load_state_dict(model, ckpt)\n model = MMDistributedDataParallel(\n model.cuda(),\n device_ids=[torch.cuda.current_device()],\n broadcast_buffers=False)\n\n #pdb.set_trace()\n distance = cfg.get('distance', 'cosine')\n \n # collect model of interests\n sampled_model_metas = []\n model_space = ModelSpaceManager.load(cfg.model_space_path)\n rule = build_sample_rule(cfg.model_sampling_rules)\n sub_model_space = model_space.ms_manager.apply_rule(rule)\n model_metas = sub_model_space.ms_manager.pack()\n dist.barrier()\n if rank == 0:\n print(\"Please notice, the encoder_k always keeps largest architecture\")\n for each in model_metas:\n each['arch'].pop('encoder_k')\n #pdb.set_trace()\n # set up distance\n\n\n model_metas_no_id = copy.deepcopy(model_metas)\n for each in model_metas_no_id:\n each.pop('index')\n new_model_metas_no_id = []\n new_model_metas = []\n \n for each_no_id, each in zip(model_metas_no_id, model_metas):\n \n if each_no_id not in new_model_metas_no_id:\n new_model_metas.append(each)\n new_model_metas_no_id.append(each_no_id)\n model_metas = new_model_metas\n \n\n #pdb.set_trace()\n for i, model_meta in enumerate(model_metas):\n # sync model_meta between ranks\n model_meta = broadcast_object(model_meta)\n \n\n dataset = build_dataset(cfg.data.train)\n teacher_data_loader = build_dataloader(\n dataset,\n imgs_per_gpu=cfg.data.imgs_per_gpu,\n workers_per_gpu=cfg.data.workers_per_gpu,\n dist=True,\n shuffle=False)\n\n student_data_loader = build_dataloader(\n dataset,\n imgs_per_gpu=cfg.data.imgs_per_gpu,\n workers_per_gpu=cfg.data.workers_per_gpu,\n dist=True,\n shuffle=False)\n\n #pdb.set_trace()\n\n # TODO:run test\n print(\"start running\")\n if args.dense:\n print(\"dense\")\n outputs = multi_gpu_test_with_dense_distance(model, model_meta, teacher_data_loader, student_data_loader, distance, rank)\n else:\n print(\"global\")\n outputs = multi_gpu_test_with_distance(model, model_meta, teacher_data_loader, student_data_loader, distance, rank)\n print(\"End\")\n #pdb.set_trace()\n result_model_meta = deepcopy(model_meta)\n metrics = {}\n \n if rank == 0:\n # TODO: replace the ugly workaround\n koi = list(outputs.keys())\n for name in koi:\n metrics[name] = outputs[name]\n \n metric_meta = result_model_meta.setdefault('metric', {})\n metric_meta[args.metric_tag] = metrics\n result_model_meta['metric'] = metric_meta\n sampled_model_metas.append(result_model_meta)\n logger.info('-- model meta:')\n logger.info(json.dumps(sampled_model_metas[-1], indent=4))\n dist.barrier()\n\n if rank == 0:\n sub_model_space = ModelSpaceManager.load(sampled_model_metas)\n sub_model_space.ms_manager.dump(save_path)\n dist.barrier()\n\n if rank == 0:\n sub_model_space = ModelSpaceManager.load(sampled_model_metas)\n sub_model_space.ms_manager.dump(save_path)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.nn.functional.normalize", "torch.distributed.broadcast", "torch.cat", "torch.zeros", "torch.randn", "torch.randperm", "torch.distributed.all_gather", "torch.einsum", "torch.no_grad", "torch.distributed.get_rank", "torch.argsort", "torch.ones_like", "torch.distributed.get_world_size" ], [ "torch.cuda.current_device", "torch.distributed.barrier", "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Alex-Tremayne/Numerical-Grav-Sim
[ "bdde57f922a0687c02c5b232ad605caca385aeae" ]
[ "source/main.py" ]
[ "# These imports tell python that we want to use code from our other files\r\nimport particle\r\nimport physics\r\n\r\n# These imports are from installed python packages\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom celluloid import Camera\r\n\r\n# This is a function\r\n# Functions in code work much like a mathematical function\r\n# First we begin by telling the code what the functions takes as inputs\r\ndef initialise(num_particles, bounds, velocity, mass, radius=1):\r\n\t'''\r\n\tdef : short for define, this is how all functions start\r\n\r\n\tinitialise : this is the name we give the funciton, it can be anything, \r\n\t\tas long as there are no spaces. \r\n\r\n\tnum_particles, bounds, velocity, mass : These are the inputs to the function,\r\n\t\tit will not be able to do anything if they are not provided\r\n\r\n\tradius=1 : this is also an input, however by setting it equal to 1, we have\r\n\t\tprovided it with a default value, so we don't need to pass anything in unless we want a different value\r\n\t\r\n\tThis is everything we need to set up the inputs of a python function. All these inputs will be \r\n\t\taccessible as variables inside the function body\r\n\r\n\tNext we write code that tells the function how to turn the inputs into output(s)\r\n\r\n\t'''\r\n\r\n\tassert bounds.size == velocity.size # This is just to check that the dimensions are the same\r\n\r\n\tparticles = np.array([]) # Create an empty numpy array, numpy arrays are fast and very feature packed!\r\n\r\n\tfor x in range(num_particles): # This is a loop, it will run num_particles times, \r\n\t\t\t\t\t\t\t\t # each time it loops x will increase by 1 until it reaches num_particles-1\r\n\t\t\t\t\t\t\t\t # x starts with a value of 0\r\n\t\t#print(x)\r\n\t\ttemp = particle.particle(np.multiply(bounds, np.random.rand(bounds.size)), np.copy(velocity), mass, radius)\r\n\t\t\t# Here we create a temporary particle\r\n\t\tparticles = np.append(particles, temp) # We then stick it on the end of the particles array\r\n\r\n\t'''\r\n\tEverything above here is an intermediate step. In this case, it is creating a variable called particles\r\n\tWhen it's finished, we need to tell the function that we would like to use it as the output.\r\n\t\r\n\tThis is done using the \"return\" keyword, essentially saying return this object to whatever called the function\r\n\r\n\t'''\r\n\r\n\treturn particles\r\n\r\n\r\n\r\n\r\n# Here we use the initialise function to define an array of particles\r\nparticles = initialise(10, np.array([10.0, 10.0]), np.array([0.0, 0.0]), 100.0)\r\n\r\n\r\nfor item in particles: # This loop just spits out the starting coordinates of the particles, just to check everything worked\r\n\tprint(item.coord)\r\n\r\n# To create the animation, we need a figure and a camera\r\nfig = plt.figure()\r\ncamera = Camera(fig) # The camera will make an animation by sticking the figures together and saving it\r\n\r\nfor x in range(6000): \r\n\t\r\n\r\n\tphysics.eulerSemiImplicit(1, 0.001, particles)\r\n\r\n\t# Get coords\r\n\tcoords = np.asarray([item.coord for item in particles])\r\n\tx, y = coords.T\r\n\r\n\tplt.plot(x, y, \"o\", color=\"blue\")\r\n\tplt.xlim(0,10)\r\n\tplt.ylim(0,10)\r\n\tcamera.snap()\r\n\r\nanimation = camera.animate()\r\n \r\n#Saving the animation\r\nanimation.save('grav_sim.gif', fps=600)\r\n" ]
[ [ "numpy.asarray", "matplotlib.pyplot.ylim", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlim", "numpy.append", "numpy.copy", "numpy.random.rand", "numpy.array", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MichaelLutter/mimo
[ "8a6a770ee90cbd6fd5cc12141d19442a3477af2c" ]
[ "examples/gauss/vi_gauss.py" ]
[ "import numpy as np\nimport numpy.random as npr\n\nfrom mimo import distributions\n\ndim, nb_samples, nb_datasets = 3, 500, 5\ndist = distributions.Gaussian(mu=npr.randn(dim), sigma=5. * np.diag(npr.rand(dim)))\ndata = [dist.rvs(size=nb_samples) for _ in range(nb_datasets)]\nprint(\"True mean\" + \"\\n\", dist.mu.T, \"\\n\" + \"True sigma\" + \"\\n\", dist.sigma)\n\nhypparams = dict(mu=np.zeros((dim, )), kappa=0.05, psi=np.eye(dim), nu=2 * dim + 1)\nprior = distributions.NormalInverseWishart(**hypparams)\n\nmodel = distributions.BayesianGaussian(prior=prior)\nmodel.meanfieldupdate(data)\nprint(\"Meanfield mean\"+\"\\n\", model.mu.T, \"\\n\"+\"Meanfield sigma\"+\"\\n\", model.sigma)\n" ]
[ [ "numpy.eye", "numpy.random.randn", "numpy.random.rand", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JLCaraveo/sklearn-projects-Platzi
[ "d2556dd90479a9057bd78face993fefd8ad47a5f" ]
[ "production_project/utils.py" ]
[ "import pandas as pd\nimport joblib\n\n\nclass Utils:\n\n def load_from_csv(self, path):\n return pd.read_csv(path)\n\n\n def load_from_mysql(self):\n pass\n\n\n def features_target(self, df, drop_columns, target):\n x = df.drop(drop_columns, axis=1)\n y = df[target]\n\n return x, y\n\n\n def model_export(self, clf, score):\n print(score)\n joblib.dump(clf, './models/best_model.pkl')\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
fxjeane/RenderManForBlender
[ "28618f67ba6ca2fe4a698786ca0427972b11f0cf", "28618f67ba6ca2fe4a698786ca0427972b11f0cf" ]
[ "rfb_utils/object_utils.py", "rman_translators/rman_mesh_translator.py" ]
[ "import bpy\nimport numpy as np\nfrom .prefs_utils import get_pref\nfrom . import string_utils\n\ndef get_db_name(ob, rman_type='', psys=None):\n db_name = '' \n\n if psys:\n db_name = '%s|%s-%s' % (ob.name_full, psys.name, psys.settings.type)\n\n elif rman_type != '' and rman_type != 'NONE':\n if rman_type == 'META':\n db_name = '%s-META' % (ob.name.split('.')[0])\n elif rman_type == 'EMPTY':\n db_name = '%s' % ob.name_full \n else:\n db_name = '%s-%s' % (ob.name_full, rman_type)\n elif isinstance(ob, bpy.types.Camera):\n db_name = ob.name_full\n return db_name\n elif isinstance(ob, bpy.types.Material):\n mat_name = ob.name_full.replace('.', '_')\n db_name = '%s' % mat_name\n elif isinstance(ob, bpy.types.Object):\n if ob.type == 'MESH':\n db_name = '%s-MESH' % ob.name_full\n elif ob.type == 'LIGHT':\n db_name = '%s-LIGHT' % ob.data.name_full\n elif ob.type == 'CAMERA':\n db_name = ob.name_full\n return db_name\n elif ob.type == 'EMPTY':\n db_name = '%s' % ob.name_full \n\n\n return string_utils.sanitize_node_name(db_name)\n\ndef get_group_db_name(ob_inst):\n if isinstance(ob_inst, bpy.types.DepsgraphObjectInstance):\n if ob_inst.is_instance:\n ob = ob_inst.instance_object\n parent = ob_inst.parent\n psys = ob_inst.particle_system\n if psys:\n group_db_name = \"%s|%s|%s|%d|%d\" % (parent.name_full, ob.name_full, psys.name, ob_inst.persistent_id[1], ob_inst.persistent_id[0])\n else:\n group_db_name = \"%s|%s|%d|%d\" % (parent.name_full, ob.name_full, ob_inst.persistent_id[1], ob_inst.persistent_id[0])\n else:\n ob = ob_inst.object\n group_db_name = \"%s\" % (ob.name_full)\n else:\n group_db_name = \"%s\" % (ob_inst.name_full)\n\n return string_utils.sanitize_node_name(group_db_name)\n\ndef is_portal_light(ob):\n if ob.type != 'LIGHT':\n return False\n rm = ob.data.renderman\n return (rm.renderman_light_role == 'RMAN_LIGHT' and rm.get_light_node_name() == 'PxrPortalLight')\n\ndef is_particle_instancer(psys, particle_settings=None):\n psys_settings = particle_settings\n if not psys_settings:\n psys_settings = psys.settings\n\n if psys_settings.type == 'HAIR' and psys_settings.render_type != 'PATH':\n return True \n if psys_settings.type == 'EMITTER' and psys_settings.render_type in ['COLLECTION', 'OBJECT']:\n return True\n\n return False \n\ndef get_meta_family(ob):\n return ob.name.split('.')[0]\n\ndef is_subd_last(ob):\n return ob.modifiers and \\\n ob.modifiers[len(ob.modifiers) - 1].type == 'SUBSURF'\n\n\ndef is_subd_displace_last(ob):\n if len(ob.modifiers) < 2:\n return False\n\n return (ob.modifiers[len(ob.modifiers) - 2].type == 'SUBSURF' and\n ob.modifiers[len(ob.modifiers) - 1].type == 'DISPLACE')\n\ndef is_fluid(ob):\n for mod in ob.modifiers:\n if mod.type == \"FLUID\" and mod.domain_settings:\n return True\n return False \n\ndef is_subdmesh(ob):\n rm = ob.renderman\n if not rm:\n return False\n\n rman_subdiv_scheme = getattr(ob.data.renderman, 'rman_subdiv_scheme', 'none')\n\n if rm.primitive == 'AUTO' and rman_subdiv_scheme == 'none':\n return (is_subd_last(ob) or is_subd_displace_last(ob))\n else:\n return (rman_subdiv_scheme != 'none') \n\n# handle special case of fluid sim a bit differently\ndef is_deforming_fluid(ob):\n if ob.modifiers:\n mod = ob.modifiers[len(ob.modifiers) - 1]\n return mod.type == 'FLUID' and mod.fluid_type == 'DOMAIN'\n\ndef _is_deforming_(ob):\n deforming_modifiers = ['ARMATURE', 'MESH_SEQUENCE_CACHE', 'CAST', 'CLOTH', 'CURVE', 'DISPLACE',\n 'HOOK', 'LATTICE', 'MESH_DEFORM', 'SHRINKWRAP', 'EXPLODE',\n 'SIMPLE_DEFORM', 'SMOOTH', 'WAVE', 'SOFT_BODY',\n 'SURFACE', 'MESH_CACHE', 'FLUID_SIMULATION',\n 'DYNAMIC_PAINT']\n if ob.modifiers:\n # special cases for auto subd/displace detection\n if len(ob.modifiers) == 1 and is_subd_last(ob):\n return False\n if len(ob.modifiers) == 2 and is_subd_displace_last(ob):\n return False\n\n for mod in ob.modifiers:\n if mod.type in deforming_modifiers:\n return True\n if ob.data and hasattr(ob.data, 'shape_keys') and ob.data.shape_keys:\n return True\n\n return is_deforming_fluid(ob)\n\ndef is_transforming(ob, recurse=False):\n transforming = (ob.animation_data is not None)\n if not transforming and ob.parent:\n transforming = is_transforming(ob.parent, recurse=True)\n if not transforming and ob.parent.type == 'CURVE' and ob.parent.data:\n transforming = ob.parent.data.use_path\n return transforming\n\ndef _detect_primitive_(ob):\n\n if isinstance(ob, bpy.types.ParticleSystem):\n return ob.settings.type\n\n rm = ob.renderman\n rm_primitive = getattr(rm, 'primitive', 'AUTO')\n\n if rm_primitive == 'AUTO':\n if ob.type == 'MESH':\n if is_fluid(ob):\n return 'FLUID' \n return 'MESH'\n elif ob.type == 'VOLUME':\n return 'OPENVDB'\n elif ob.type == 'LIGHT':\n if ob.data.renderman.renderman_light_role == 'RMAN_LIGHTFILTER':\n return 'LIGHTFILTER'\n return ob.type\n elif ob.type == 'FONT':\n return 'MESH' \n elif ob.type in ['CURVE']:\n return 'CURVE'\n elif ob.type == 'SURFACE':\n if get_pref('rman_render_nurbs_as_mesh', True):\n return 'MESH'\n return 'NURBS'\n elif ob.type == \"META\":\n return \"META\"\n elif ob.type == 'CAMERA':\n return 'CAMERA'\n elif ob.type == 'EMPTY':\n return 'EMPTY'\n elif ob.type == 'GPENCIL':\n return 'GPENCIL'\n else:\n return ob.type\n else:\n return rm_primitive \n\ndef get_active_material(ob):\n mat = None\n if ob.renderman.rman_material_override:\n mat = ob.renderman.rman_material_override\n \n if mat:\n return mat\n\n material_slots = getattr(ob, 'material_slots', None)\n if ob.type == 'EMPTY':\n material_slots = getattr(ob.original, 'material_slots', None) \n if not material_slots:\n return None\n\n if len(material_slots) > 0:\n for mat_slot in material_slots:\n mat = mat_slot.material\n if mat:\n break\n return mat\n\ndef _get_used_materials_(ob):\n if ob.type == 'MESH' and len(ob.data.materials) > 0:\n if len(ob.data.materials) == 1:\n return [ob.data.materials[0]]\n mat_ids = []\n mesh = ob.data\n num_materials = len(ob.data.materials)\n for p in mesh.polygons:\n if p.material_index not in mat_ids:\n mat_ids.append(p.material_index)\n if num_materials == len(mat_ids):\n break\n return [mesh.materials[i] for i in mat_ids]\n else:\n return [ob.active_material] \n\ndef _get_mesh_points_(mesh):\n nvertices = len(mesh.vertices)\n P = np.zeros(nvertices*3, dtype=np.float32)\n mesh.vertices.foreach_get('co', P)\n P = np.reshape(P, (nvertices, 3))\n return P.tolist()\n\ndef _get_mesh_(mesh, get_normals=False):\n\n P = _get_mesh_points_(mesh)\n N = [] \n\n npolygons = len(mesh.polygons)\n fastnvertices = np.zeros(npolygons, dtype=np.int)\n mesh.polygons.foreach_get('loop_total', fastnvertices)\n nverts = fastnvertices.tolist()\n\n loops = len(mesh.loops)\n fastvertices = np.zeros(loops, dtype=np.int)\n mesh.loops.foreach_get('vertex_index', fastvertices)\n verts = fastvertices.tolist()\n\n if get_normals:\n fastsmooth = np.zeros(npolygons, dtype=np.int)\n mesh.polygons.foreach_get('use_smooth', fastsmooth)\n if mesh.use_auto_smooth or True in fastsmooth:\n mesh.calc_normals_split()\n fastnormals = np.zeros(loops*3, dtype=np.float32)\n mesh.loops.foreach_get('normal', fastnormals)\n fastnormals = np.reshape(fastnormals, (loops, 3))\n N = fastnormals.tolist() \n else: \n fastnormals = np.zeros(npolygons*3, dtype=np.float32)\n mesh.polygons.foreach_get('normal', fastnormals)\n fastnormals = np.reshape(fastnormals, (npolygons, 3))\n N = fastnormals.tolist()\n\n return (nverts, verts, P, N)", "from .rman_translator import RmanTranslator\nfrom ..rman_sg_nodes.rman_sg_mesh import RmanSgMesh\nfrom ..rfb_utils import object_utils\nfrom ..rfb_utils import string_utils\nfrom ..rfb_utils import property_utils\nfrom ..rfb_utils import scenegraph_utils\nfrom ..rfb_logger import rfb_log\n\nimport bpy\nimport math\nimport numpy as np\n\ndef _get_mats_faces_(nverts, material_ids):\n\n mats = {}\n for face_id, num_verts in enumerate(nverts):\n mat_id = material_ids[face_id]\n if mat_id not in mats:\n mats[mat_id] = []\n mats[mat_id].append(face_id)\n return mats\n\ndef _is_multi_material_(ob, mesh):\n if len(ob.data.materials) < 2 or len(mesh.polygons) == 0:\n return False\n\n first_mat = mesh.polygons[0].material_index\n for p in mesh.polygons:\n if p.material_index != first_mat:\n return True\n return False\n\n# requires facevertex interpolation\ndef _get_mesh_uv_(mesh, name=\"\"):\n uvs = []\n if not name:\n uv_loop_layer = mesh.uv_layers.active\n else:\n # assuming uv loop layers and uv textures share identical indices\n #idx = mesh.uv_textures.keys().index(name)\n #uv_loop_layer = mesh.uv_layers[idx]\n uv_loop_layer = mesh.uv_layers.get(name, None)\n\n if uv_loop_layer is None:\n return None\n\n uv_count = len(uv_loop_layer.data)\n fastuvs = np.zeros(uv_count * 2)\n uv_loop_layer.data.foreach_get(\"uv\", fastuvs)\n fastuvs = fastuvs.reshape(uv_count, 2) \n uvs = fastuvs.tolist()\n\n return uvs\n\ndef _get_mesh_vcol_(mesh, name=\"\"):\n vcol_layer = mesh.vertex_colors[name] if name != \"\" \\\n else mesh.vertex_colors.active\n\n if vcol_layer is None:\n return None\n\n vcol_count = len(vcol_layer.data)\n fastvcols = np.zeros(vcol_count * 4)\n vcol_layer.data.foreach_get(\"color\", fastvcols)\n fastvcols = np.reshape(fastvcols, (vcol_count, 4))\n pre_cols = fastvcols.tolist() \n \n cols = [ [c[0], c[1], c[2]] for c in pre_cols ]\n\n return cols \n\ndef _get_mesh_vattr_(mesh, name=\"\"):\n if not name in mesh.attributes and mesh != \"\":\n rfb_log().error(\"Cannot find color attribute \")\n return None\n vattr_layer = mesh.attributes[name] if name != \"\" \\\n else mesh.attributes.active\n\n if vattr_layer is None:\n return None\n\n vcol_count = len(vattr_layer.data)\n fastvattrs = np.zeros(vcol_count * 4)\n vattr_layer.data.foreach_get(\"color\", fastvattrs)\n fastvattrs = np.reshape(fastvattrs, (vcol_count, 4))\n pre_cols = fastvattrs.tolist() \n \n attrs = [ [a[0], a[1], a[2]] for a in pre_cols ]\n\n return attrs \n\ndef _get_mesh_vgroup_(ob, mesh, name=\"\"):\n vgroup = ob.vertex_groups[name] if name != \"\" else ob.vertex_groups.active\n weights = []\n\n if vgroup is None:\n return None\n\n for v in mesh.vertices:\n if len(v.groups) == 0:\n weights.append(0.0)\n else:\n weights.extend([g.weight for g in v.groups\n if g.group == vgroup.index])\n\n return weights\n\ndef _get_material_ids(ob, geo): \n fast_material_ids = np.zeros(len(geo.polygons), dtype=np.int)\n geo.polygons.foreach_get(\"material_index\", fast_material_ids)\n material_ids = fast_material_ids.tolist()\n return material_ids\n\ndef _export_reference_pose(ob, rm, rixparams, vertex_detail):\n rman__Pref = []\n rman__WPref = []\n rman__Nref = []\n rman__WNref = []\n for rp in rm.reference_pose:\n if rp.has_Pref:\n rman__Pref.append( rp.rman__Pref)\n if rp.has_WPref:\n rman__WPref.append( rp.rman__WPref)\n if rp.has_Nref:\n rman__Nref.append( rp.rman__Nref)\n if rp.has_WPref:\n rman__WNref.append( rp.rman__WNref)\n\n if rman__Pref:\n if len(rman__Pref) == vertex_detail:\n rixparams.SetPointDetail('__Pref', rman__Pref, 'vertex')\n else:\n rfb_log().error(\"Number of Pref primvars do not match. Please re-freeze the reference position.\")\n\n if rman__WPref:\n if len(rman__WPref) == vertex_detail:\n rixparams.SetPointDetail('__WPref', rman__WPref, 'vertex')\n else:\n rfb_log().error(\"Number of WPref primvars do not match. Please re-freeze the reference position.\")\n \n if rman__Nref:\n if len(rman__Nref) == vertex_detail:\n rixparams.SetNormalDetail('__Nref', rman__Nref, 'vertex')\n else:\n rfb_log().error(\"Number of Nref primvars do not match. Please re-freeze the reference position.\")\n \n if rman__WNref:\n if len(rman__WNref) == vertex_detail:\n rixparams.SetNormalDetail('__WNref', rman__WNref, 'vertex')\n else:\n rfb_log().error(\"Number of WNref primvars do not match. Please re-freeze the reference position.\")\n \n '''\n if rman__Pref:\n rixparams.SetPointDetail('__Pref', rman__Pref, 'vertex')\n if rman__WPref:\n rixparams.SetPointDetail('__WPref', rman__WPref, 'vertex')\n if rman__Nref:\n rixparams.SetNormalDetail('__Nref', rman__Nref, 'vertex')\n if rman__WNref:\n rixparams.SetNormalDetail('__WNref', rman__WNref, 'vertex')\n '''\n\ndef export_tangents(ob, geo, rixparams, uvmap=\"\", name=\"\"):\n # also export the tangent and bitangent vectors\n try:\n if uvmap == \"\":\n geo.calc_tangents(uvmap=geo.uv_layers.active.name) \n else:\n geo.calc_tangents(uvmap=uvmap)\n loops = len(geo.loops)\n fasttangent = np.zeros(loops*3, dtype=np.float32)\n geo.loops.foreach_get('tangent', fasttangent)\n fasttangent = np.reshape(fasttangent, (loops, 3))\n tangents = fasttangent.tolist() \n\n fastbitangent = np.zeros(loops*3, dtype=np.float32)\n geo.loops.foreach_get('bitangent', fastbitangent)\n bitangent = fastbitangent.tolist() \n geo.free_tangents() \n\n if name == \"\":\n rixparams.SetVectorDetail('Tn', tangents, 'facevarying')\n rixparams.SetVectorDetail('Bn', bitangent, 'facevarying') \n else:\n rixparams.SetVectorDetail('%s_Tn' % name, tangents, 'facevarying')\n rixparams.SetVectorDetail('%s_Bn' % name, bitangent, 'facevarying') \n except RuntimeError as err:\n rfb_log().debug(\"Can't export tangent vectors: %s\" % str(err)) \n\ndef _get_primvars_(ob, rman_sg_mesh, geo, rixparams):\n #rm = ob.data.renderman\n # Stange problem here : ob seems to not be in sync with the scene\n # when a geometry node is active...\n rm = ob.original.data.renderman\n\n vertex_detail = rman_sg_mesh.npoints \n facevarying_detail = rman_sg_mesh.nverts \n\n if rm.export_default_uv:\n uvs = _get_mesh_uv_(geo)\n if uvs and len(uvs) > 0:\n detail = \"facevarying\" if facevarying_detail == len(uvs) else \"vertex\"\n rixparams.SetFloatArrayDetail(\"st\", uvs, 2, detail)\n export_tangents(ob, geo, rixparams) \n\n if rm.export_default_vcol:\n vcols = _get_mesh_vcol_(geo)\n if vcols and len(vcols) > 0:\n detail = \"facevarying\" if facevarying_detail == len(vcols) else \"vertex\"\n rixparams.SetColorDetail(\"Cs\", vcols, detail)\n\n # reference pose\n if hasattr(rm, 'reference_pose'):\n _export_reference_pose(ob, rm, rixparams, vertex_detail)\n \n # custom prim vars\n for p in rm.prim_vars:\n if p.data_source == 'VERTEX_COLOR':\n vcols = _get_mesh_vcol_(geo, p.data_name)\n \n if vcols and len(vcols) > 0:\n detail = \"facevarying\" if facevarying_detail == len(vcols) else \"vertex\"\n rixparams.SetColorDetail(p.name, vcols, detail)\n \n elif p.data_source == 'UV_TEXTURE':\n uvs = _get_mesh_uv_(geo, p.data_name)\n if uvs and len(uvs) > 0:\n detail = \"facevarying\" if facevarying_detail == len(uvs) else \"vertex\"\n rixparams.SetFloatArrayDetail(p.name, uvs, 2, detail)\n if p.export_tangents:\n export_tangents(ob, geo, rixparams, uvmap=p.data_name, name=p.name) \n\n elif p.data_source == 'VERTEX_GROUP':\n weights = _get_mesh_vgroup_(ob, geo, p.data_name)\n if weights and len(weights) > 0:\n detail = \"facevarying\" if facevarying_detail == len(weights) else \"vertex\"\n rixparams.SetFloatDetail(p.name, weights, detail)\n elif p.data_source == 'VERTEX_ATTR_COLOR':\n vattr = _get_mesh_vattr_(geo, p.data_name) \n if vattr and len(vattr) > 0:\n detail = \"facevarying\" if facevarying_detail == len(vattr) else \"vertex\"\n rixparams.SetColorDetail(p.data_name, vattr, detail)\n\n rm_scene = rman_sg_mesh.rman_scene.bl_scene.renderman\n for prop_name, meta in rm.prop_meta.items():\n if 'primvar' not in meta:\n continue\n\n val = getattr(rm, prop_name)\n if not val:\n continue\n\n if 'inheritable' in meta:\n if float(val) == meta['inherit_true_value']:\n if hasattr(rm_scene, prop_name):\n val = getattr(rm_scene, prop_name)\n\n ri_name = meta['primvar']\n is_array = False\n array_len = -1\n if 'arraySize' in meta:\n is_array = True\n array_len = meta['arraySize']\n param_type = meta['renderman_type']\n property_utils.set_rix_param(rixparams, param_type, ri_name, val, is_reference=False, is_array=is_array, array_len=array_len, node=rm)\n\nclass RmanMeshTranslator(RmanTranslator):\n\n def __init__(self, rman_scene):\n super().__init__(rman_scene)\n self.bl_type = 'MESH' \n\n def _get_subd_tags_(self, ob, mesh, primvar):\n creases = []\n\n # only do creases 1 edge at a time for now,\n # detecting chains might be tricky..\n for e in mesh.edges:\n if e.crease > 0.0:\n creases.append((e.vertices[0], e.vertices[1],\n e.crease * e.crease * 10))\n # squared, to match blender appareance better\n #: range 0 - 10 (infinitely sharp)\n\n tags = ['interpolateboundary', 'facevaryinginterpolateboundary']\n nargs = [1, 0, 0, 1, 0, 0]\n intargs = [ int(ob.data.renderman.rman_subdivInterp),\n int(ob.data.renderman.rman_subdivFacevaryingInterp)]\n floatargs = []\n stringargs = [] \n\n if len(creases) > 0:\n for c in creases:\n tags.append('crease')\n nargs.extend([2, 1, 0])\n intargs.extend([c[0], c[1]])\n floatargs.append(c[2]) \n\n primvar.SetStringArray(self.rman_scene.rman.Tokens.Rix.k_Ri_subdivtags, tags, len(tags))\n primvar.SetIntegerArray(self.rman_scene.rman.Tokens.Rix.k_Ri_subdivtagnargs, nargs, len(nargs))\n primvar.SetIntegerArray(self.rman_scene.rman.Tokens.Rix.k_Ri_subdivtagintargs, intargs, len(intargs))\n primvar.SetFloatArray(self.rman_scene.rman.Tokens.Rix.k_Ri_subdivtagfloatargs, floatargs, len(floatargs))\n primvar.SetStringArray(self.rman_scene.rman.Tokens.Rix.k_Ri_subdivtagstringtags, stringargs, len(stringargs)) \n\n def export(self, ob, db_name):\n \n sg_node = self.rman_scene.sg_scene.CreateMesh(db_name)\n rman_sg_mesh = RmanSgMesh(self.rman_scene, sg_node, db_name)\n\n if self.rman_scene.do_motion_blur:\n rman_sg_mesh.is_transforming = object_utils.is_transforming(ob)\n rman_sg_mesh.is_deforming = object_utils._is_deforming_(ob)\n\n return rman_sg_mesh\n\n def export_deform_sample(self, rman_sg_mesh, ob, time_sample, sg_node=None):\n\n mesh = None\n mesh = ob.to_mesh()\n if not sg_node:\n sg_node = rman_sg_mesh.sg_node\n primvar = sg_node.GetPrimVars()\n P = object_utils._get_mesh_points_(mesh)\n npoints = len(P)\n\n if rman_sg_mesh.npoints != npoints:\n primvar.SetTimes([])\n sg_node.SetPrimVars(primvar)\n rman_sg_mesh.is_transforming = False\n rman_sg_mesh.is_deforming = False\n if rman_sg_mesh.is_multi_material:\n for c in rman_sg_mesh.multi_material_children:\n pvar = c.GetPrimVars()\n pvar.SetTimes( [] ) \n c.SetPrimVars(pvar) \n return \n\n primvar.SetPointDetail(self.rman_scene.rman.Tokens.Rix.k_P, P, \"vertex\", time_sample) \n\n sg_node.SetPrimVars(primvar)\n\n if rman_sg_mesh.is_multi_material:\n for c in rman_sg_mesh.multi_material_children:\n pvar = c.GetPrimVars()\n pvar.SetPointDetail(self.rman_scene.rman.Tokens.Rix.k_P, P, \"vertex\", time_sample) \n c.SetPrimVars(pvar)\n\n ob.to_mesh_clear() \n\n def update(self, ob, rman_sg_mesh, input_mesh=None, sg_node=None):\n rm = ob.renderman\n mesh = input_mesh\n if not mesh:\n mesh = ob.to_mesh()\n if not mesh:\n return True\n\n if not sg_node:\n sg_node = rman_sg_mesh.sg_node\n\n rman_sg_mesh.is_subdiv = object_utils.is_subdmesh(ob)\n use_smooth_normals = getattr(ob.data.renderman, 'rman_smoothnormals', False)\n get_normals = (rman_sg_mesh.is_subdiv == 0 and not use_smooth_normals)\n (nverts, verts, P, N) = object_utils._get_mesh_(mesh, get_normals=get_normals)\n \n # if this is empty continue:\n if nverts == []:\n if not input_mesh:\n ob.to_mesh_clear()\n rman_sg_mesh.npoints = 0\n rman_sg_mesh.npolys = 0\n rman_sg_mesh.nverts = 0\n rman_sg_mesh.is_transforming = False\n rman_sg_mesh.is_deforming = False\n return None\n\n npolys = len(nverts) \n npoints = len(P)\n numnverts = len(verts)\n\n rman_sg_mesh.npoints = npoints\n rman_sg_mesh.npolys = npolys\n rman_sg_mesh.nverts = numnverts\n\n sg_node.Define( npolys, npoints, numnverts )\n rman_sg_mesh.is_multi_material = _is_multi_material_(ob, mesh)\n \n primvar = sg_node.GetPrimVars()\n primvar.Clear()\n\n if rman_sg_mesh.is_deforming and len(rman_sg_mesh.deform_motion_steps) > 1:\n super().set_primvar_times(rman_sg_mesh.deform_motion_steps, primvar)\n \n primvar.SetPointDetail(self.rman_scene.rman.Tokens.Rix.k_P, P, \"vertex\")\n _get_primvars_(ob, rman_sg_mesh, mesh, primvar) \n\n primvar.SetIntegerDetail(self.rman_scene.rman.Tokens.Rix.k_Ri_nvertices, nverts, \"uniform\")\n primvar.SetIntegerDetail(self.rman_scene.rman.Tokens.Rix.k_Ri_vertices, verts, \"facevarying\") \n\n if rman_sg_mesh.is_subdiv:\n creases = self._get_subd_tags_(ob, mesh, primvar)\n if ob.data.renderman.rman_subdiv_scheme == 'none':\n # we were tagged as a subdiv by a modifier\n sg_node.SetScheme(self.rman_scene.rman.Tokens.Rix.k_catmullclark) \n else:\n sg_node.SetScheme(ob.data.renderman.rman_subdiv_scheme) \n\n else:\n sg_node.SetScheme(None)\n if N:\n if len(N) == numnverts:\n primvar.SetNormalDetail(self.rman_scene.rman.Tokens.Rix.k_N, N, \"facevarying\") \n else:\n primvar.SetNormalDetail(self.rman_scene.rman.Tokens.Rix.k_N, N, \"uniform\") \n subdiv_scheme = getattr(ob.data.renderman, 'rman_subdiv_scheme', 'none')\n rman_sg_mesh.subdiv_scheme = subdiv_scheme\n\n if rman_sg_mesh.is_multi_material:\n material_ids = _get_material_ids(ob, mesh)\n for mat_id, faces in \\\n _get_mats_faces_(nverts, material_ids).items():\n\n mat = ob.data.materials[mat_id]\n if not mat:\n continue\n sg_material = self.rman_scene.rman_materials.get(mat.original, None)\n\n if mat_id == 0:\n primvar.SetIntegerArray(self.rman_scene.rman.Tokens.Rix.k_shade_faceset, faces, len(faces))\n scenegraph_utils.set_material(sg_node, sg_material.sg_node)\n else: \n sg_sub_mesh = self.rman_scene.sg_scene.CreateMesh(\"\")\n sg_sub_mesh.Define( npolys, npoints, numnverts ) \n if rman_sg_mesh.is_subdiv:\n sg_sub_mesh.SetScheme(self.rman_scene.rman.Tokens.Rix.k_catmullclark)\n pvars = sg_sub_mesh.GetPrimVars() \n if rman_sg_mesh.is_deforming and len(rman_sg_mesh.deform_motion_steps) > 1:\n super().set_primvar_times(rman_sg_mesh.deform_motion_steps, pvars)\n pvars.Inherit(primvar)\n pvars.SetIntegerArray(self.rman_scene.rman.Tokens.Rix.k_shade_faceset, faces, len(faces)) \n sg_sub_mesh.SetPrimVars(pvars)\n # call export_object_primvars so we can get things like displacement bound\n super().export_object_primvars(ob, rman_sg_mesh, sg_sub_mesh)\n scenegraph_utils.set_material(sg_sub_mesh, sg_material.sg_node)\n sg_node.AddChild(sg_sub_mesh)\n rman_sg_mesh.multi_material_children.append(sg_sub_mesh)\n else:\n rman_sg_mesh.multi_material_children = []\n\n sg_node.SetPrimVars(primvar)\n\n if not input_mesh:\n ob.to_mesh_clear() \n\n return True " ]
[ [ "numpy.reshape", "numpy.zeros" ], [ "numpy.reshape", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jamayfieldjr/iem
[ "275b77a65f3b12e26e6cbdb230786b9c7d2b9c9a", "275b77a65f3b12e26e6cbdb230786b9c7d2b9c9a", "275b77a65f3b12e26e6cbdb230786b9c7d2b9c9a", "275b77a65f3b12e26e6cbdb230786b9c7d2b9c9a", "275b77a65f3b12e26e6cbdb230786b9c7d2b9c9a" ]
[ "scripts/ingestors/madis/extract_hfmetar.py", "scripts/iemre/init_daily.py", "htdocs/plotting/auto/scripts100/p130.py", "scripts/ingestors/other/cobs_ingest.py", "htdocs/iemre/multiday.py" ]
[ "\"\"\"Pull in what's available for HFMETAR MADIS data\n\nRun from RUN_10MIN.sh\nRun from RUN_40_AFTER.sh for two hours ago\n\"\"\"\nfrom __future__ import print_function\nimport os\nimport sys\nimport datetime\nimport warnings\n\nimport pytz\nimport numpy as np\nfrom tqdm import tqdm\nfrom metar import Metar\nfrom netCDF4 import chartostring\nfrom metpy.units import units, masked_array\nfrom pyiem.datatypes import temperature, distance, pressure\nfrom pyiem.observation import Observation\nfrom pyiem.util import get_dbconn, ncopen\nfrom pyiem.reference import TRACE_VALUE\n\nwarnings.simplefilter('ignore', RuntimeWarning)\n\n\ndef vsbyfmt(val):\n \"\"\" Tricky formatting of vis\"\"\"\n if val == 0:\n return 0\n if val <= 0.125:\n return \"1/8\"\n if val <= 0.25:\n return \"1/4\"\n if val <= 0.375:\n return \"3/8\"\n if val <= 0.5:\n return \"1/2\"\n if val <= 1.1:\n return \"1\"\n if val <= 1.6:\n return \"1 1/2\"\n if val <= 2.1:\n return \"2\"\n if val <= 2.6:\n return \"2 1/2\"\n return int(val)\n\n\ndef process(ncfn):\n \"\"\"Process this file \"\"\"\n pgconn = get_dbconn('iem')\n icursor = pgconn.cursor()\n xref = {}\n icursor.execute(\"\"\"\n SELECT id, network from stations where\n network ~* 'ASOS' or network = 'AWOS' and country = 'US'\n \"\"\")\n for row in icursor:\n xref[row[0]] = row[1]\n icursor.close()\n nc = ncopen(ncfn)\n data = {}\n for vname in ['stationId', 'observationTime', 'temperature', 'dewpoint',\n 'altimeter', # Pa\n 'windDir',\n 'windSpeed', # mps\n 'windGust', # mps\n 'visibility', # m\n 'precipAccum', 'presWx', 'skyCvr',\n 'skyCovLayerBase', 'autoRemark', 'operatorRemark']:\n data[vname] = nc.variables[vname][:]\n for qc in ['QCR', 'QCD']:\n vname2 = vname + qc\n if vname2 in nc.variables:\n data[vname2] = nc.variables[vname2][:]\n for vname in ['temperature', 'dewpoint']:\n data[vname+\"C\"] = temperature(data[vname], 'K').value('C')\n data[vname] = temperature(data[vname], 'K').value('F')\n for vname in ['windSpeed', 'windGust']:\n data[vname] = masked_array(\n data[vname], units('meter / second')\n ).to(units('knots')).magnitude\n\n data['altimeter'] = pressure(data['altimeter'], 'PA').value(\"IN\")\n data['skyCovLayerBase'] = distance(data['skyCovLayerBase'],\n 'M').value(\"FT\")\n data['visibility'] = distance(data['visibility'], 'M').value(\"MI\")\n data['precipAccum'] = distance(data['precipAccum'], 'MM').value(\"IN\")\n stations = chartostring(data['stationId'][:])\n presentwxs = chartostring(data['presWx'][:])\n skycs = chartostring(data['skyCvr'][:])\n autoremarks = chartostring(data['autoRemark'][:])\n opremarks = chartostring(data['operatorRemark'][:])\n\n def decision(i, fieldname, tolerance):\n \"\"\"Our decision if we are going to take a HFMETAR value or not\"\"\"\n if data[fieldname][i] is np.ma.masked:\n return None\n if data[\"%sQCR\" % (fieldname, )][i] == 0:\n return data[fieldname][i]\n # Now we have work to do\n departure = np.ma.max(\n np.ma.abs(data['%sQCD' % (fieldname, )][i, :]))\n # print(\"departure: %s tolerance: %s\" % (departure, tolerance))\n if departure <= tolerance:\n return data[fieldname][i]\n return None\n\n for i, sid in tqdm(enumerate(stations), total=len(stations),\n disable=(not sys.stdout.isatty())):\n sid3 = sid[1:] if sid[0] == 'K' else sid\n ts = datetime.datetime(1970, 1, 1) + datetime.timedelta(\n seconds=data['observationTime'][i])\n ts = ts.replace(tzinfo=pytz.UTC)\n\n mtr = \"%s %sZ AUTO \" % (sid, ts.strftime(\"%d%H%M\"))\n network = xref.get(sid3, 'ASOS')\n iem = Observation(sid3, network, ts)\n\n # 06019G23KT\n val = decision(i, 'windDir', 15)\n if val is not None:\n iem.data['drct'] = int(val)\n mtr += \"%03i\" % (iem.data['drct'], )\n else:\n mtr += \"///\"\n\n val = decision(i, 'windSpeed', 10)\n if val is not None:\n iem.data['sknt'] = int(val)\n mtr += \"%02i\" % (iem.data['sknt'], )\n else:\n mtr += \"//\"\n\n val = decision(i, 'windGust', 10)\n if val is not None and val > 0:\n iem.data['gust'] = int(val)\n mtr += \"G%02i\" % (iem.data['gust'],)\n mtr += \"KT \"\n\n val = decision(i, 'visibility', 4)\n if val is not None:\n iem.data['vsby'] = float(val)\n mtr += \"%sSM \" % (vsbyfmt(iem.data['vsby']), )\n\n presentwx = presentwxs[i]\n if presentwx != '':\n # database storage is comma delimited\n iem.data['wxcodes'] = presentwx.split(\" \")\n mtr += \"%s \" % (presentwx,)\n\n for _i, (skyc, _l) in enumerate(\n zip(skycs[i], data['skyCovLayerBase'][i])):\n if skyc != '':\n iem.data['skyc%s' % (_i+1,)] = skyc\n if skyc != 'CLR':\n iem.data['skyl%s' % (_i+1,)] = int(_l)\n mtr += \"%s%03i \" % (skyc, int(_l) / 100)\n else:\n mtr += \"CLR \"\n\n t = \"\"\n tgroup = \"T\"\n val = decision(i, 'temperature', 10)\n if val is not None:\n # Recall the pain enabling this\n # iem.data['tmpf'] = float(data['temperature'][i])\n tmpc = float(data['temperatureC'][i])\n t = \"%s%02i/\" % (\"M\" if tmpc < 0 else \"\",\n tmpc if tmpc > 0 else (0 - tmpc))\n tgroup += \"%s%03i\" % (\"1\" if tmpc < 0 else \"0\",\n (tmpc if tmpc > 0 else (0 - tmpc)) * 10.)\n val = decision(i, 'dewpoint', 10)\n if val is not None:\n # iem.data['dwpf'] = float(data['dewpoint'][i])\n tmpc = float(data['dewpointC'][i])\n if t != \"\":\n t = \"%s%s%02i \" % (t, \"M\" if tmpc < 0 else \"\",\n tmpc if tmpc > 0 else 0 - tmpc)\n tgroup += \"%s%03i\" % (\"1\" if tmpc < 0 else \"0\",\n (tmpc if tmpc > 0 else (0 - tmpc)) * 10.)\n if len(t) > 4:\n mtr += t\n val = decision(i, 'altimeter', 20)\n if val is not None:\n iem.data['alti'] = float(round(val, 2))\n mtr += \"A%4i \" % (iem.data['alti'] * 100.,)\n\n mtr += \"RMK \"\n val = decision(i, 'precipAccum', 25)\n if val is not None:\n if val >= 0.01:\n iem.data['phour'] = float(round(val, 2))\n mtr += \"P%04i \" % (iem.data['phour'] * 100.,)\n elif val < 0.01 and val > 0:\n # Trace\n mtr += \"P0000 \"\n iem.data['phour'] = TRACE_VALUE\n\n if tgroup != \"T\":\n mtr += \"%s \" % (tgroup, )\n\n if autoremarks[i] != '' or opremarks[i] != '':\n mtr += \"%s %s \" % (autoremarks[i], opremarks[i])\n mtr += \"MADISHF\"\n # Eat our own dogfood\n try:\n Metar.Metar(mtr)\n iem.data['raw'] = mtr\n except Exception as exp:\n print(\n \"dogfooding extract_hfmetar %s resulted in %s\" % (mtr, exp)\n )\n continue\n\n for key in iem.data:\n if isinstance(iem.data[key], np.float32):\n print(\"key: %s type: %s\" % (key, type(iem.data[key])))\n icursor = pgconn.cursor()\n if not iem.save(icursor, force_current_log=True,\n skip_current=True):\n print((\"extract_hfmetar: unknown station? %s %s %s\\n%s\"\n ) % (sid3, network, ts, mtr))\n\n icursor.close()\n pgconn.commit()\n\n\ndef find_fn(argv):\n \"\"\"Figure out which file to run for\"\"\"\n if len(argv) == 5:\n utcnow = datetime.datetime(int(argv[1]), int(argv[2]), int(argv[3]),\n int(argv[4]))\n return utcnow.strftime(\"/mesonet/data/madis/hfmetar/%Y%m%d_%H00.nc\")\n else:\n utcnow = datetime.datetime.utcnow()\n start = 0 if len(argv) == 1 else int(argv[1])\n for i in range(start, 5):\n ts = utcnow - datetime.timedelta(hours=i)\n fn = ts.strftime(\"/mesonet/data/madis/hfmetar/%Y%m%d_%H00.nc\")\n if os.path.isfile(fn):\n return fn\n sys.exit()\n\n\ndef main(argv):\n \"\"\"Do Something\"\"\"\n fn = find_fn(argv)\n process(fn)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n", "\"\"\"Generate the IEMRE daily analysis file for a year\"\"\"\nfrom __future__ import print_function\nimport datetime\nimport sys\n\nimport geopandas as gpd\nimport numpy as np\nfrom pyiem import iemre\nfrom pyiem.grid.zs import CachingZonalStats\nfrom pyiem.util import get_dbconn, ncopen\n\n\ndef init_year(ts):\n \"\"\"\n Create a new NetCDF file for a year of our specification!\n \"\"\"\n\n fn = iemre.get_daily_ncname(ts.year)\n nc = ncopen(fn, 'w')\n nc.title = \"IEM Daily Reanalysis %s\" % (ts.year,)\n nc.platform = \"Grided Observations\"\n nc.description = \"IEM daily analysis on a 0.125 degree grid\"\n nc.institution = \"Iowa State University, Ames, IA, USA\"\n nc.source = \"Iowa Environmental Mesonet\"\n nc.project_id = \"IEM\"\n nc.realization = 1\n nc.Conventions = 'CF-1.0'\n nc.contact = \"Daryl Herzmann, [email protected], 515-294-5978\"\n nc.history = (\"%s Generated\"\n ) % (datetime.datetime.now().strftime(\"%d %B %Y\"),)\n nc.comment = \"No Comment at this time\"\n\n # Setup Dimensions\n nc.createDimension('lat', iemre.NY)\n nc.createDimension('lon', iemre.NX)\n days = ((ts.replace(year=ts.year+1)) - ts).days\n nc.createDimension('time', int(days))\n\n # Setup Coordinate Variables\n lat = nc.createVariable('lat', np.float, ('lat',))\n lat.units = \"degrees_north\"\n lat.long_name = \"Latitude\"\n lat.standard_name = \"latitude\"\n lat.axis = \"Y\"\n lat[:] = iemre.YAXIS\n\n lon = nc.createVariable('lon', np.float, ('lon',))\n lon.units = \"degrees_east\"\n lon.long_name = \"Longitude\"\n lon.standard_name = \"longitude\"\n lon.axis = \"X\"\n lon[:] = iemre.XAXIS\n\n tm = nc.createVariable('time', np.float, ('time',))\n tm.units = \"Days since %s-01-01 00:00:0.0\" % (ts.year,)\n tm.long_name = \"Time\"\n tm.standard_name = \"time\"\n tm.axis = \"T\"\n tm.calendar = \"gregorian\"\n tm[:] = np.arange(0, int(days))\n\n # Tracked variables\n hasdata = nc.createVariable('hasdata', np.int8, ('lat', 'lon'))\n hasdata.units = '1'\n hasdata.long_name = 'Analysis Available for Grid Cell'\n hasdata.coordinates = \"lon lat\"\n hasdata[:] = 0\n\n high = nc.createVariable('high_tmpk', np.uint16, ('time', 'lat', 'lon'),\n fill_value=65535)\n high.units = \"K\"\n high.scale_factor = 0.01\n high.long_name = \"2m Air Temperature Daily High\"\n high.standard_name = \"2m Air Temperature\"\n high.coordinates = \"lon lat\"\n\n low = nc.createVariable('low_tmpk', np.uint16, ('time', 'lat', 'lon'),\n fill_value=65535)\n low.units = \"K\"\n low.scale_factor = 0.01\n low.long_name = \"2m Air Temperature Daily Low\"\n low.standard_name = \"2m Air Temperature\"\n low.coordinates = \"lon lat\"\n\n high12 = nc.createVariable('high_tmpk_12z', np.uint16,\n ('time', 'lat', 'lon'),\n fill_value=65535)\n high12.units = \"K\"\n high12.scale_factor = 0.01\n high12.long_name = \"2m Air Temperature 24 Hour Max at 12 UTC\"\n high12.standard_name = \"2m Air Temperature\"\n high12.coordinates = \"lon lat\"\n\n low12 = nc.createVariable('low_tmpk_12z', np.uint16,\n ('time', 'lat', 'lon'),\n fill_value=65535)\n low12.units = \"K\"\n low12.scale_factor = 0.01\n low12.long_name = \"2m Air Temperature 12 Hour Min at 12 UTC\"\n low12.standard_name = \"2m Air Temperature\"\n low12.coordinates = \"lon lat\"\n\n p01d = nc.createVariable('p01d', np.uint16, ('time', 'lat', 'lon'),\n fill_value=65535)\n p01d.units = 'mm'\n p01d.scale_factor = 0.01\n p01d.long_name = 'Precipitation'\n p01d.standard_name = 'Precipitation'\n p01d.coordinates = \"lon lat\"\n p01d.description = \"Precipitation accumulation for the day\"\n\n p01d12 = nc.createVariable('p01d_12z', np.uint16, ('time', 'lat', 'lon'),\n fill_value=65535)\n p01d12.units = 'mm'\n p01d12.scale_factor = 0.01\n p01d12.long_name = 'Precipitation'\n p01d12.standard_name = 'Precipitation'\n p01d12.coordinates = \"lon lat\"\n p01d12.description = \"24 Hour Precipitation Ending 12 UTC\"\n\n # 0 -> 65535 so 0 to 6553.5\n rsds = nc.createVariable('rsds', np.uint16, ('time', 'lat', 'lon'),\n fill_value=65535)\n rsds.units = \"W m-2\"\n rsds.scale_factor = 0.1\n rsds.long_name = 'surface_downwelling_shortwave_flux_in_air'\n rsds.standard_name = 'surface_downwelling_shortwave_flux_in_air'\n rsds.coordinates = \"lon lat\"\n rsds.description = \"Global Shortwave Irradiance\"\n\n snow = nc.createVariable('snow_12z', np.uint16, ('time', 'lat', 'lon'),\n fill_value=65535)\n snow.units = 'mm'\n snow.scale_factor = 0.01\n snow.long_name = 'Snowfall'\n snow.standard_name = 'Snowfall'\n snow.coordinates = \"lon lat\"\n snow.description = \"Snowfall accumulation for the day\"\n\n # 0 to 6553.5\n snowd = nc.createVariable('snowd_12z', np.uint16, ('time', 'lat', 'lon'),\n fill_value=65535)\n snowd.units = 'mm'\n snowd.scale_factor = 0.1\n snowd.long_name = 'Snow Depth'\n snowd.standard_name = 'Snow Depth'\n snowd.coordinates = \"lon lat\"\n snowd.description = \"Snow depth at time of observation\"\n\n v1 = nc.createVariable('avg_dwpk', np.uint16, ('time', 'lat', 'lon'),\n fill_value=65535)\n v1.units = 'K'\n v1.scale_factor = 0.01\n v1.long_name = '2m Average Dew Point Temperature'\n v1.standard_name = 'Dewpoint'\n v1.coordinates = \"lon lat\"\n v1.description = \"Dew Point average computed by averaging mixing ratios\"\n\n v2 = nc.createVariable('wind_speed', np.uint16, ('time', 'lat', 'lon'),\n fill_value=65535)\n v2.units = 'm s-1'\n v2.scale_factor = 0.001\n v2.long_name = 'Wind Speed'\n v2.standard_name = 'Wind Speed'\n v2.coordinates = \"lon lat\"\n v2.description = \"Daily averaged wind speed magnitude\"\n\n v1 = nc.createVariable(\n 'power_swdn', np.float, ('time', 'lat', 'lon'),\n fill_value=1.e20)\n v1.units = 'MJ d-1'\n v1.long_name = 'All Sky Insolation Incident on a Horizontal Surface'\n v1.standard_name = (\n 'All Sky Insolation Incident on a Horizontal Surface'\n )\n v1.coordinates = \"lon lat\"\n v1.description = \"from NASA POWER\"\n\n nc.close()\n\n\ndef compute_hasdata(year):\n \"\"\"Compute the has_data grid\"\"\"\n nc = ncopen(iemre.get_daily_ncname(year), 'a', timeout=300)\n czs = CachingZonalStats(iemre.AFFINE)\n pgconn = get_dbconn('postgis')\n states = gpd.GeoDataFrame.from_postgis(\"\"\"\n SELECT the_geom, state_abbr from states\n where state_abbr not in ('AK', 'HI')\n \"\"\", pgconn, index_col='state_abbr', geom_col='the_geom')\n data = np.flipud(nc.variables['hasdata'][:, :])\n czs.gen_stats(data, states['the_geom'])\n for nav in czs.gridnav:\n grid = np.ones((nav.ysz, nav.xsz))\n grid[nav.mask] = 0.\n jslice = slice(nav.y0, nav.y0 + nav.ysz)\n islice = slice(nav.x0, nav.x0 + nav.xsz)\n data[jslice, islice] = np.where(grid > 0, 1, data[jslice, islice])\n nc.variables['hasdata'][:, :] = np.flipud(data)\n nc.close()\n\n\ndef main(argv):\n \"\"\"Go Main Go\"\"\"\n year = int(argv[1])\n init_year(datetime.datetime(year, 1, 1))\n compute_hasdata(year)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n", "\"\"\"temps vs high and low\"\"\"\n\nimport numpy as np\nfrom pandas.io.sql import read_sql\nfrom pyiem.plot.use_agg import plt\nfrom pyiem.util import get_autoplot_context, get_dbconn\nfrom pyiem.exceptions import NoDataFound\n\n\ndef get_description():\n \"\"\" Return a dict describing how to call this plotter \"\"\"\n desc = dict()\n desc['data'] = True\n desc['description'] = \"\"\"This chart displays the average high and low\n temperature by month for days with or without snowcover reported. There\n are a number of caveats due to the timing of the daily temperature and\n snow cover report. Also with the quality of the snow cover data.\"\"\"\n desc['arguments'] = [\n dict(type='station', name='station', default='IATDSM',\n label='Select Station:', network='IACLIMATE'),\n ]\n return desc\n\n\ndef plotter(fdict):\n \"\"\" Go \"\"\"\n pgconn = get_dbconn('coop')\n ctx = get_autoplot_context(fdict, get_description())\n station = ctx['station'].upper()\n table = \"alldata_%s\" % (station[:2], )\n df = read_sql(\"\"\"\n SELECT year, month,\n avg(high) as avg_high_all, avg(low) as avg_low_all,\n avg(case when snowd > 0 then high else null end) as avg_high_snow,\n avg(case when snowd > 0 then low else null end) as avg_low_snow,\n avg(case when snowd = 0 then high else null end) as avg_high_nosnow,\n avg(case when snowd = 0 then low else null end) as avg_low_nosnow,\n sum(case when snowd > 0 then 1 else 0 end) as coverdays\n from \"\"\" + table + \"\"\"\n WHERE station = %s\n GROUP by year, month\n \"\"\", pgconn, params=(station, ), index_col=None)\n if df.empty:\n raise NoDataFound(\"No data found.\")\n\n # Only use months that had at least one day of snowcover\n df2 = df[df['coverdays'] > 0]\n df3 = df2.groupby('month').mean()\n\n (fig, ax) = plt.subplots(2, 1)\n for i, lbl in enumerate(['high', 'low']):\n ys = df3.loc[[11, 12, 1, 2, 3], 'avg_%s_nosnow' % (lbl, )]\n ax[i].bar(np.arange(5) - 0.2, ys.values, width=0.4, align='center',\n label='Without Snowcover', fc='brown', zorder=4)\n for x, y in enumerate(ys):\n ax[i].text(x - 0.2, y + 2, \"%.0f\" % (y, ), ha='center',\n color='brown')\n\n ys2 = df3.loc[[11, 12, 1, 2, 3], 'avg_%s_snow' % (lbl, )]\n ax[i].bar(np.arange(5) + 0.2, ys2.values, width=0.4, align='center',\n label='With Snowcover', fc='blue', zorder=4)\n for x, y in enumerate(ys2):\n ax[i].text(x + 0.2, y + 2, \"%.0f\" % (y, ), ha='center',\n color='blue')\n\n ys3 = df3.loc[[11, 12, 1, 2, 3], 'avg_%s_all' % (lbl, )]\n ax[i].scatter(np.arange(5), ys3.values, marker='s', s=50, zorder=5,\n label='Overall', c='yellow')\n for x, y in enumerate(ys3):\n ax[i].text(x - 0.05, y, \"%.0f\" % (y, ), ha='right', zorder=6,\n va='top', color='yellow')\n ax[i].set_xticks(range(5))\n ax[i].set_xticklabels(['Nov', 'Dec', 'Jan', 'Feb', 'Mar'])\n ax[i].legend(ncol=3, fontsize=10)\n ax[i].grid(True)\n ax[i].set_ylim([(ys2.min() - 10), (ys.max() + 20)])\n\n ax[0].set_title((\"%s [%s]\\nSnow Cover Impact on Average Temp [%s-%s]\"\n ) % (ctx['_nt'].sts[station]['name'], station,\n df2['year'].min(), df2['year'].max()))\n ax[0].set_ylabel(r\"Avg High Temp $^\\circ$F\")\n ax[1].set_ylabel(r\"Avg Low Temp $^\\circ$F\")\n\n return fig, df\n\n\nif __name__ == '__main__':\n plotter(dict())\n", "\"\"\"Ingest the COBS data file\n\n Run from RUN_20_AFTER.sh\n\"\"\"\nfrom __future__ import print_function\nimport datetime\nimport os\nimport sys\n\nimport pandas as pd\nimport pytz\nfrom pint import UnitRegistry\nfrom pyiem.observation import Observation\nfrom pyiem.util import get_dbconn\n\nUREG = UnitRegistry()\nQUANTITY = UREG.Quantity\nSID = 'OT0012'\nDIRPATH = \"/mnt/mesonet/home/mesonet/ot/ot0005/incoming/Pederson\"\n\nHOURLYCONV = {'Batt_Volt': 'battery',\n 'PTemp_C': None, # Panel Temperature ?\n 'Rain_in_Tot': 'phour',\n 'SlrW_Avg': 'srad',\n 'SlrMJ_Tot': None,\n 'AirTF_Avg': 'tmpf',\n 'RH': 'relh',\n 'WS_mph_Avg': 'sknt',\n 'WS_mph_Max': 'gust',\n 'WindDir': 'drct',\n 'WS_mph_S_WVT': None,\n 'WindDir_D1_WVT': None,\n 'T107_F_Avg': 'c1tmpf'} # 4 inch soil temp\n\nDAILYCONV = {'Batt_Volt_Min': None,\n 'PTemp_C_Max': None,\n 'PTemp_C_Min': None,\n 'Rain_in_Tot': 'pday',\n 'SlrW_Avg': None,\n 'SlrW_Max': None,\n 'SlrW_TMx': None,\n 'SlrMJ_Tot': 'srad_mj',\n 'AirTF_Max': 'max_tmpf',\n 'AirTF_TMx': None,\n 'AirTF_Min': 'min_tmpf',\n 'AirTF_TMn': None,\n 'AirTF_Avg': None,\n 'RH_Max': 'max_rh',\n 'RH_TMx': None,\n 'RH_Min': 'min_rh',\n 'RH_TMn': None,\n 'WS_mph_Max': 'gust',\n 'WS_mph_TMx': None,\n 'WS_mph_S_WVT': None,\n 'WindDir_D1_WVT': None,\n 'T107_F_Max': None,\n 'T107_F_TMx': None,\n 'T107_F_Min': None,\n 'T107_F_TMn': None,\n 'T107_F_Avg': None}\n\n\ndef sum_hourly(hdf, date, col):\n \"\"\"Figure out the sum based on the hourly data\"\"\"\n # TODO 6z is a quasi bug here as we also total precip\n sts = datetime.datetime(date.year, date.month, date.day, 6)\n sts = sts.replace(tzinfo=pytz.utc)\n ets = sts + datetime.timedelta(hours=24)\n df2 = hdf[(hdf['valid'] > sts) & (hdf['valid'] < ets)]\n if df2.empty:\n # print(\"ingest_cobs found no hourly data for date: %s\" % (date,))\n return None\n return float(df2[col].sum())\n\n\ndef clean(key, value):\n \"\"\"\"Clean the values\"\"\"\n if key.startswith('WS'):\n return QUANTITY(value, UREG.mph).to(UREG.knots).m\n if key.startswith('RH') and value > 100:\n return 100.\n if pd.isnull(value):\n return None\n return float(value)\n\n\ndef database(lastob, ddf, hdf, force_currentlog):\n \"\"\"Do the tricky database work\"\"\"\n # This should be okay as we are always going to CST\n maxts = hdf['TIMESTAMP'].max().replace(\n tzinfo=pytz.timezone(\"America/Chicago\"))\n if lastob is not None and maxts <= lastob:\n # print(\"maxts: %s lastob: %s\" % (maxts, lastob))\n return\n iemdb = get_dbconn('iem')\n icursor = iemdb.cursor()\n if lastob is None:\n df2 = hdf\n else:\n df2 = hdf[hdf['valid'] > lastob]\n for _, row in df2.iterrows():\n localts = row['valid'].tz_convert(pytz.timezone(\"America/Chicago\"))\n # Find, if it exists, the summary table entry here\n daily = ddf[ddf['date'] == localts.date()]\n ob = Observation(SID, 'OT', localts)\n if len(daily.index) == 1:\n for key, value in DAILYCONV.items():\n if value is None:\n continue\n # print(\"D: %s -> %s\" % (key, value))\n ob.data[value] = clean(key, daily.iloc[0][key])\n # print(\"date: %s srad_mj: %s\" % (localts.date(), ob.data['srad_mj']))\n if ob.data['srad_mj'] is None:\n ob.data['srad_mj'] = sum_hourly(hdf, localts.date(), 'SlrMJ_Tot')\n if ob.data['pday'] is None:\n ob.data['pday'] = sum_hourly(hdf, localts.date(), 'Rain_in_Tot')\n for key, value in HOURLYCONV.items():\n if value is None:\n continue\n # print(\"H: %s -> %s\" % (key, value))\n ob.data[value] = clean(key, row[key])\n ob.save(icursor, force_current_log=force_currentlog,\n skip_current=force_currentlog)\n icursor.close()\n iemdb.commit()\n\n\ndef get_last():\n \"\"\"Get the last timestamp\"\"\"\n pgconn = get_dbconn('iem', user='nobody')\n cursor = pgconn.cursor()\n cursor.execute(\"\"\"SELECT valid at time zone 'UTC'\n from current c JOIN stations t\n ON (c.iemid = t.iemid) where t.id = %s\n \"\"\", (SID,))\n return cursor.fetchone()[0].replace(tzinfo=pytz.utc)\n\n\ndef campbell2df(year):\n \"\"\"\"Process the file for any timestamps after the lastob\"\"\"\n dailyfn = \"%s/%s/Daily.dat\" % (DIRPATH, year)\n hourlyfn = \"%s/%s/Hourly.dat\" % (DIRPATH, year)\n if not os.path.isfile(dailyfn):\n dailyfn = \"%s/%s/Daily.dat\" % (DIRPATH, year - 1)\n if not os.path.isfile(dailyfn):\n print(\"cobs_ingest.py missing %s\" % (dailyfn,))\n return None, None\n if not os.path.isfile(hourlyfn):\n hourlyfn = \"%s/%s/Hourly.dat\" % (DIRPATH, year - 1)\n if not os.path.isfile(hourlyfn):\n print(\"cobs_ingest.py missing %s\" % (hourlyfn,))\n return None, None\n\n ddf = pd.read_csv(dailyfn, header=0, na_values=[\"7999\", \"NAN\"],\n skiprows=[0, 2, 3], quotechar='\"', warn_bad_lines=True)\n ddf['TIMESTAMP'] = pd.to_datetime(ddf['TIMESTAMP'])\n # Timestamps should be moved back one day\n ddf['date'] = (ddf['TIMESTAMP'] - datetime.timedelta(hours=12)).dt.date\n hdf = pd.read_csv(hourlyfn, header=0, na_values=[\"7999\", \"NAN\"],\n skiprows=[0, 2, 3], quotechar='\"', warn_bad_lines=True)\n hdf['TIMESTAMP'] = pd.to_datetime(hdf['TIMESTAMP'])\n hdf['SlrMJ_Tot'] = pd.to_numeric(hdf['SlrMJ_Tot'], errors='coerce')\n # Move all timestamps to UTC +6\n hdf['valid'] = (hdf['TIMESTAMP'] +\n datetime.timedelta(hours=6)).dt.tz_localize(pytz.UTC)\n return ddf, hdf\n\n\ndef main(argv):\n \"\"\"Go for it!\"\"\"\n if len(argv) > 1:\n print(\"Running special request\")\n for year in range(2017, 2018):\n ddf, hdf = campbell2df(year)\n if ddf is not None:\n database(None, ddf, hdf, True)\n else:\n lastob = get_last()\n now = datetime.datetime.now()\n ddf, hdf = campbell2df(now.year)\n if ddf is not None:\n database(lastob, ddf, hdf, False)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n", "#!/usr/bin/env python\n\"\"\"Provide multiday values for IEMRE and friends\"\"\"\nimport sys\nimport cgi\nimport datetime\nimport json\nfrom json import encoder\nimport warnings\n\nimport numpy as np\nfrom pyiem import iemre, datatypes\nfrom pyiem.util import ncopen, ssw\nimport pyiem.prism as prismutil\n\nwarnings.simplefilter(\"ignore\", UserWarning)\nencoder.FLOAT_REPR = lambda o: format(o, '.2f')\nencoder.c_make_encoder = None\n\n\ndef clean(val):\n \"\"\"My filter\"\"\"\n if val is None or np.isnan(val) or np.ma.is_masked(val):\n return None\n return float(val)\n\n\ndef send_error(msg):\n \"\"\" Send an error when something bad happens(tm)\"\"\"\n ssw('Content-type: application/json\\n\\n')\n ssw(json.dumps({'error': msg}))\n sys.exit()\n\n\ndef main():\n \"\"\"Go Main Go\"\"\"\n form = cgi.FieldStorage()\n ts1 = datetime.datetime.strptime(form.getfirst(\"date1\"), \"%Y-%m-%d\")\n ts2 = datetime.datetime.strptime(form.getfirst(\"date2\"), \"%Y-%m-%d\")\n if ts1 > ts2:\n send_error(\"date1 larger than date2\")\n if ts1.year != ts2.year:\n send_error(\"multi-year query not supported yet...\")\n # Make sure we aren't in the future\n tsend = datetime.date.today()\n if ts2.date() > tsend:\n ts2 = datetime.datetime.now() - datetime.timedelta(days=1)\n\n lat = float(form.getfirst(\"lat\"))\n lon = float(form.getfirst(\"lon\"))\n if lon < iemre.WEST or lon > iemre.EAST:\n send_error(\"lon value outside of bounds: %s to %s\" % (iemre.WEST,\n iemre.EAST))\n if lat < iemre.SOUTH or lat > iemre.NORTH:\n send_error(\"lat value outside of bounds: %s to %s\" % (iemre.SOUTH,\n iemre.NORTH))\n # fmt = form[\"format\"][0]\n\n i, j = iemre.find_ij(lon, lat)\n offset1 = iemre.daily_offset(ts1)\n offset2 = iemre.daily_offset(ts2) + 1\n\n # Get our netCDF vars\n with ncopen(iemre.get_daily_ncname(ts1.year)) as nc:\n hightemp = datatypes.temperature(\n nc.variables['high_tmpk'][offset1:offset2, j, i], 'K').value(\"F\")\n high12temp = datatypes.temperature(\n nc.variables['high_tmpk_12z'][offset1:offset2, j, i],\n 'K'\n ).value(\"F\")\n lowtemp = datatypes.temperature(\n nc.variables['low_tmpk'][offset1:offset2, j, i], 'K').value(\"F\")\n low12temp = datatypes.temperature(\n nc.variables['low_tmpk_12z'][offset1:offset2, j, i],\n 'K'\n ).value(\"F\")\n precip = nc.variables['p01d'][offset1:offset2, j, i] / 25.4\n precip12 = nc.variables['p01d_12z'][offset1:offset2, j, i] / 25.4\n\n # Get our climatology vars\n c2000 = ts1.replace(year=2000)\n coffset1 = iemre.daily_offset(c2000)\n c2000 = ts2.replace(year=2000)\n coffset2 = iemre.daily_offset(c2000) + 1\n with ncopen(iemre.get_dailyc_ncname()) as cnc:\n chigh = datatypes.temperature(\n cnc.variables['high_tmpk'][coffset1:coffset2, j, i],\n 'K').value(\"F\")\n clow = datatypes.temperature(\n cnc.variables['low_tmpk'][coffset1:coffset2, j, i],\n 'K').value(\"F\")\n cprecip = cnc.variables['p01d'][coffset1:coffset2, j, i] / 25.4\n\n if ts1.year > 1980:\n i2, j2 = prismutil.find_ij(lon, lat)\n with ncopen(\"/mesonet/data/prism/%s_daily.nc\" % (ts1.year, )) as nc:\n prism_precip = nc.variables['ppt'][offset1:offset2, j2, i2] / 25.4\n else:\n prism_precip = [None]*(offset2-offset1)\n\n if ts1.year > 2010:\n j2 = int((lat - iemre.SOUTH) * 100.0)\n i2 = int((lon - iemre.WEST) * 100.0)\n with ncopen(iemre.get_daily_mrms_ncname(ts1.year)) as nc:\n mrms_precip = nc.variables['p01d'][offset1:offset2, j2, i2] / 25.4\n else:\n mrms_precip = [None]*(offset2-offset1)\n\n res = {'data': [], }\n\n for i in range(0, offset2 - offset1):\n now = ts1 + datetime.timedelta(days=i)\n res['data'].append({'date': now.strftime(\"%Y-%m-%d\"),\n 'mrms_precip_in': clean(mrms_precip[i]),\n 'prism_precip_in': clean(prism_precip[i]),\n 'daily_high_f': clean(hightemp[i]),\n '12z_high_f': clean(high12temp[i]),\n 'climate_daily_high_f': clean(chigh[i]),\n 'daily_low_f': clean(lowtemp[i]),\n '12z_low_f': clean(low12temp[i]),\n 'climate_daily_low_f': clean(clow[i]),\n 'daily_precip_in': clean(precip[i]),\n '12z_precip_in': clean(precip12[i]),\n 'climate_daily_precip_in': clean(cprecip[i])\n })\n\n ssw('Content-type: application/json\\n\\n')\n ssw(json.dumps(res))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.ma.abs" ], [ "numpy.flipud", "numpy.where", "numpy.ones" ], [ "numpy.arange", "pandas.io.sql.read_sql" ], [ "pandas.to_numeric", "pandas.read_csv", "pandas.to_datetime", "pandas.isnull" ], [ "numpy.isnan", "numpy.ma.is_masked" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.13", "1.16", "1.9", "1.18", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
Linus4world/mrs-gan
[ "64669251584a7421cce3a5173983a2275dcb438a" ]
[ "models/auxiliaries/CBAM.py" ]
[ "#https://blog.paperspace.com/attention-mechanisms-in-computer-vision-cbam/#:~:text=Spatial%20attention%20represents%20the%20attention,features%20that%20define%20that%20bird.\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import OrderedDict\n# from modules.aux.auxiliary import get_adaptive_pooling_layer, get_conv_layer, get_norm_layer\nfrom models.auxiliaries.auxiliary import get_conv, get_adaptive_pooling\n\n\n__all__ = ['citation', 'ChannelGate', 'SpatialGate', 'CBAM1d', 'CBAM2d', 'CBAM3d']\n\n\ncitation = OrderedDict({'Title': 'CBAM: Convolutional Block Attention Module',\n 'Authors': 'Sanghyun Woo, Jongchan Park, Joon-Young Lee, In So Kweon',\n 'Year': '2018',\n 'Journal': 'ECCV',\n 'Institution': 'Korea Advanced Institute of Science and Technology, Lunit Inc., and Adobe Research',\n 'URL': 'https://arxiv.org/pdf/1807.06521.pdf',\n 'Notes': 'Added the possiblity to switch from SE to eCA in the ChannelGate and updated deprecated sigmoid',\n 'Source Code': 'Modified from: https://github.com/Jongchan/attention-module'})\n\n\nclass BasicConv(nn.Module):\n def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True, bias=False, dim=1):\n super(BasicConv, self).__init__()\n self.out_channels = out_planes\n self.conv = get_conv()(in_planes, out_planes, kernel_size, groups=groups, stride=stride, padding=padding, bias=bias)\n self.bn = nn.InstanceNorm1d(out_planes,eps=1e-5, momentum=0.01, affine=True) if bn else None\n self.relu = nn.ReLU() if relu else None\n \n def forward(self, x):\n x = self.conv(x)\n if self.bn is not None:\n x = self.bn(x)\n if self.relu is not None:\n x = self.relu(x)\n return x\n\n\nclass EfficientChannelAttention(nn.Module):\n def __init__(self, num_channels, gamma=2, b=1, dim=1):\n super(EfficientChannelAttention, self).__init__()\n t =int(torch.abs((torch.log2(torch.tensor(num_channels, dtype=torch.float64)) + b) / gamma))\n k = t if t % 2 else t + 1\n\n self.conv = get_conv()(1, 1, kernel_size=k, stride=1, padding=int(k/2), bias=False)\n # self.sigmoid = nn.Sigmoid()\n \n def forward(self, x):\n out = x.transpose(-1,-2)\n out = self.conv(out)\n # out = self.sigmoid(out)\n out = out.transpose(-1, -2)\n return out\n\nclass ChannelGate(nn.Module):\n def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max'], method='efficient', dim=1):\n super(ChannelGate, self).__init__()\n self.gate_channels = gate_channels\n self.avg_pool = get_adaptive_pooling('avg')(1)\n self.max_pool = get_adaptive_pooling('max')(1)\n self.sigmoid = nn.Sigmoid()\n if method=='efficient':\n self.attention = EfficientChannelAttention(gate_channels, dim=dim)\n elif method=='mlp':\n self.attention = nn.Sequential(\n nn.Flatten(),\n nn.Linear(gate_channels, gate_channels // reduction_ratio),\n nn.ReLU(),\n nn.Linear(gate_channels // reduction_ratio, gate_channels)\n )\n self.pool_types = pool_types\n \n def forward(self, x):\n channel_att_sum = None\n for pool_type in self.pool_types:\n if pool_type=='avg':\n avg_pool = self.avg_pool(x)\n channel_att_raw = self.attention(avg_pool)\n elif pool_type=='max':\n max_pool = self.max_pool(x)\n channel_att_raw = self.attention(max_pool)\n else:\n raise ValueError(x)\n\n if channel_att_sum is None:\n channel_att_sum = channel_att_raw\n else:\n channel_att_sum = channel_att_sum + channel_att_raw\n channel_att_sum = self.sigmoid(channel_att_sum)\n scale = channel_att_sum.expand_as(x) if channel_att_sum.dim()>=3 else channel_att_sum.unsqueeze(-1).expand_as(x)\n return x * scale\n\nclass ChannelPool(nn.Module):\n def forward(self, x):\n return torch.cat( (torch.max(x,1)[0].unsqueeze(1), torch.mean(x,1).unsqueeze(1)), dim=1 )\n\nclass SpatialGate(nn.Module):\n def __init__(self, dim):\n super(SpatialGate, self).__init__()\n kernel_size = 7\n self.compress = ChannelPool()\n self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=(kernel_size-1) // 2, relu=False, dim=dim)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n x_compress = self.compress(x)\n x_out = self.spatial(x_compress)\n scale = self.sigmoid(x_out) # broadcasting\n return x * scale\n\nclass CBAM1d(nn.Module):\n def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max'], no_spatial=False, no_channel=False):\n super(CBAM1d, self).__init__()\n if no_channel:\n self.ChannelGate = nn.Identity()\n else:\n self.ChannelGate = ChannelGate(gate_channels, reduction_ratio, pool_types, dim=1)\n # self.ChannelGate = ChannelGate(gate_channels, reduction_ratio, pool_types, dim=1)\n self.no_spatial=no_spatial\n if not no_spatial:\n self.SpatialGate = SpatialGate(dim=1)\n\n def forward(self, x):\n x_out = self.ChannelGate(x)\n if not self.no_spatial:\n x_out = self.SpatialGate(x_out)\n return x_out\n\nclass CBAM2d(nn.Module):\n def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max'], no_spatial=False):\n super(CBAM2d, self).__init__()\n self.ChannelGate = ChannelGate(gate_channels, reduction_ratio, pool_types, dim=2)\n self.no_spatial=no_spatial\n if not no_spatial:\n self.SpatialGate = SpatialGate(dim=2)\n\n def forward(self, x):\n x_out = self.ChannelGate(x)\n if not self.no_spatial:\n x_out = self.SpatialGate(x_out)\n return x_out\n\nclass CBAM3d(nn.Module):\n def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max'], no_spatial=False):\n super(CBAM3d, self).__init__()\n self.ChannelGate = ChannelGate(gate_channels, reduction_ratio, pool_types, dim=3)\n self.no_spatial=no_spatial\n if not no_spatial:\n self.SpatialGate = SpatialGate(dim=3)\n\n def forward(self, x):\n x_out = self.ChannelGate(x)\n if not self.no_spatial:\n x_out = self.SpatialGate(x_out)\n return x_out" ]
[ [ "torch.mean", "torch.max", "torch.nn.InstanceNorm1d", "torch.nn.Flatten", "torch.nn.Sigmoid", "torch.tensor", "torch.nn.Linear", "torch.nn.Identity", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vishalbelsare/carculator
[ "44516a5f3e7f7f42f0d0d7a5c2bd5af3d17d0fd4", "44516a5f3e7f7f42f0d0d7a5c2bd5af3d17d0fd4" ]
[ "carculator/noise_emissions.py", "carculator/internal_noise.py" ]
[ "import numexpr as ne\nimport numpy as np\n\n\nclass NoiseEmissionsModel:\n \"\"\"\n Calculate propulsion and rolling noise emissions for combustion, hybrid and electric vehicles, based on CNOSSOS model.\n\n :param cycle: Driving cycle. Pandas Series of second-by-second speeds (km/h) or name (str)\n of cycle e.g., \"WLTC\",\"WLTC 3.1\",\"WLTC 3.2\",\"WLTC 3.3\",\"WLTC 3.4\",\"CADC Urban\",\"CADC Road\",\n \"CADC Motorway\",\"CADC Motorway 130\",\"CADC\",\"NEDC\".\n :type cycle: pandas.Series\n\n \"\"\"\n\n def __init__(self, cycle, cycle_name):\n\n self.cycle = cycle\n self.cycle_name = cycle_name\n self.cycle_environment = {\n \"WLTC\": {\n \"urban start\": 0,\n \"urban stop\": 590,\n \"suburban start\": 591,\n \"suburban stop\": 1023,\n \"rural start\": 1024,\n \"rural stop\": 1801,\n },\n \"WLTC 3.1\": {\"urban start\": 0, \"urban stop\": 590},\n \"WLTC 3.2\": {\"suburban start\": 0, \"suburban stop\": 433},\n \"WLTC 3.3\": {\"rural start\": 0, \"rural stop\": 455},\n \"WLTC 3.4\": {\"rural start\": 0, \"rural stop\": 323},\n \"CADC Urban\": {\"urban start\": 0, \"urban stop\": 994},\n \"CADC Road\": {\"suburban start\": 0, \"suburban stop\": 1082},\n \"CADC Motorway\": {\"rural start\": 0, \"rural stop\": 1068},\n \"CADC Motorway 130\": {\"rural start\": 0, \"rural stop\": 1068},\n \"CADC\": {\n \"urban start\": 0,\n \"urban stop\": 994,\n \"suburban start\": 995,\n \"suburban stop\": 2077,\n \"rural start\": 2078,\n \"rural stop\": 3144,\n },\n \"NEDC\": {\n \"urban start\": 0,\n \"urban stop\": 780,\n \"rural start\": 781,\n \"rural stop\": 1180,\n },\n }\n\n def rolling_noise(self):\n \"\"\"Calculate noise from rolling friction.\n Model from CNOSSOS-EU project\n (http://publications.jrc.ec.europa.eu/repository/bitstream/JRC72550/cnossos-eu%20jrc%20reference%20report_final_on%20line%20version_10%20august%202012.pdf)\n\n\n :returns: A numpy array with rolling noise (dB) for each 8 octaves, per second of driving cycle\n :rtype: numpy.array\n\n \"\"\"\n cycle = np.array(self.cycle)\n array = np.tile(\n np.log10(cycle / 70, out=np.zeros_like(cycle), where=(cycle != 0)), 8\n ).reshape((8, cycle.shape[0], cycle.shape[-1]))\n\n constants = np.array((79.7, 85.7, 84.5, 90.2, 97.3, 93.9, 84.1, 74.3)).reshape(\n (-1, 1)\n )\n coefficients = np.array((30, 41.5, 38.9, 25.7, 32.5, 37.2, 39, 40)).reshape(\n (-1, 1)\n )\n\n array = array * coefficients[..., None] + constants[..., None]\n\n return array\n\n def propulsion_noise(self, powertrain_type):\n \"\"\"Calculate noise from propulsion engine and gearbox.\n Model from CNOSSOS-EU project\n (http://publications.jrc.ec.europa.eu/repository/bitstream/JRC72550/cnossos-eu%20jrc%20reference%20report_final_on%20line%20version_10%20august%202012.pdf)\n\n For electric cars, special coefficients are applied from\n (`Pallas et al. 2016 <https://www.sciencedirect.com/science/article/pii/S0003682X16301608>`_ )\n\n Also, for electric cars, a warning signal of 56 dB is added when the car drives at 20 km/h or lower.\n\n :returns: A numpy array with propulsion noise (dB) for all 8 octaves, per second of driving cycle\n :rtype: numpy.array\n\n \"\"\"\n cycle = np.array(self.cycle)\n\n # Noise sources are calculated for speeds above 20 km/h.\n if powertrain_type in (\"combustion\", \"electric\"):\n array = np.tile((cycle - 70) / 70, 8).reshape(\n (8, cycle.shape[0], cycle.shape[-1])\n )\n constants = np.array(\n (94.5, 89.2, 88, 85.9, 84.2, 86.9, 83.3, 76.1)\n ).reshape((-1, 1))\n coefficients = np.array((-1.3, 7.2, 7.7, 8, 8, 8, 8, 8)).reshape((-1, 1))\n array = array * coefficients[..., None] + constants[..., None]\n\n if powertrain_type == \"electric\":\n # For electric cars, we add correction factors\n # We also add a 56 dB loud sound signal when the speed is below 20 km/h.\n correction = np.array((0, 1.7, 4.2, 15, 15, 15, 13.8, 0))[:, None, None]\n array -= correction\n\n # Warming signal for electric cars of 56 dB at 20 km/h or lower\n array[:, cycle < 20] = 56\n\n else:\n # For non plugin-hybrids, apply electric engine noise coefficient up to 30 km/h\n # and combustion engine noise coefficients above 30 km/h\n electric = self.propulsion_noise(\"electric\")\n electric_mask = cycle < 30\n\n array = self.propulsion_noise(\"combustion\")\n array[:, electric_mask] = electric[:, electric_mask]\n\n return array\n\n def get_sound_power_per_compartment(self, powertrain_type):\n \"\"\"\n Calculate sound energy (in J/s) over the driving cycle duration from sound power (in dB).\n The sound energy sums are further divided into `geographical compartments`: urban, suburban and rural.\n\n * *urban*: from 0 to 50 km/k\n * *suburban*: from 51 km/h to 80 km/h\n * *rural*: above 80 km/h\n\n\n :return: Sound energy (in Joules) per km driven, per geographical compartment.\n :rtype: numpy.array\n \"\"\"\n\n if powertrain_type not in (\"combustion\", \"electric\", \"hybrid\"):\n raise TypeError(\"The powertrain type is not valid.\")\n\n # rolling noise, in dB, for each second of the driving cycle\n rolling = self.rolling_noise()\n # propulsion noise, in dB, for each second of the driving cycle\n propulsion = self.propulsion_noise(powertrain_type)\n\n # sum of rolling and propulsion noise sources\n c = self.cycle\n\n total_noise = ne.evaluate(\n \"where(c != 0, 10 * log10((10 ** (rolling / 10)) + (10 ** (propulsion / 10))), 0)\"\n )\n\n # convert dBs to Watts (or J/s)\n sound_power = ne.evaluate(\"(10 ** -12) * (10 ** (total_noise / 10))\")\n\n # If the driving cycle selected is one of the driving cycles for which carculator has specifications,\n # we use the driving cycle \"official\" road section types to compartmentalize emissions.\n # If the driving cycle selected is instead specified by the user (passed directly as an array), we used\n # speed levels to compartmentalize emissions.\n\n if self.cycle_name in self.cycle_environment:\n distance = (self.cycle / 3600).sum(axis=0)\n\n if \"urban start\" in self.cycle_environment[self.cycle_name]:\n start = self.cycle_environment[self.cycle_name][\"urban start\"]\n stop = self.cycle_environment[self.cycle_name][\"urban stop\"]\n urban = np.sum(sound_power[:, start:stop], axis=1) / distance\n\n else:\n urban = np.zeros((8, self.cycle.shape[-1]))\n\n if \"suburban start\" in self.cycle_environment[self.cycle_name]:\n start = self.cycle_environment[self.cycle_name][\"suburban start\"]\n stop = self.cycle_environment[self.cycle_name][\"suburban stop\"]\n suburban = np.sum(sound_power[:, start:stop], axis=1) / distance\n else:\n suburban = np.zeros((8, self.cycle.shape[-1]))\n\n if \"rural start\" in self.cycle_environment[self.cycle_name]:\n start = self.cycle_environment[self.cycle_name][\"rural start\"]\n stop = self.cycle_environment[self.cycle_name][\"rural stop\"]\n rural = np.sum(sound_power[:, start:stop], axis=1) / distance\n\n else:\n rural = np.zeros((8, self.cycle.shape[-1]))\n\n else:\n distance = (self.cycle / 3600).sum(axis=0)\n\n # sum sound power over duration (J/s * s --> J) and divide by distance (--> J / km) and further\n # divide into compartments\n urban = ne.evaluate(\"sum(where(c <= 50, sound_power, 0), 1)\") / distance\n suburban = (\n ne.evaluate(\"sum(where((c > 50) & (c <= 80), sound_power, 0), 1)\")\n / distance\n )\n rural = ne.evaluate(\"sum(where(c > 80, sound_power, 0), 1)\") / distance\n\n return np.vstack([urban, suburban, rural])[..., None].transpose(1, 2, 0)[\n ..., None, None\n ]\n", "import numexpr as ne\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\nfrom . import DATA_DIR\n\n\nclass InternalNoiseModel:\n \"\"\"\n Calculate internal noise function ofpowertrain and size, based on http://www.auto-decibel-db.com/index.html.\n\n :param cycle: Driving cycle. Pandas Series of second-by-second speeds (km/h) or name (str)\n of cycle e.g., \"WLTC\",\"WLTC 3.1\",\"WLTC 3.2\",\"WLTC 3.3\",\"WLTC 3.4\",\"CADC Urban\",\"CADC Road\",\n \"CADC Motorway\",\"CADC Motorway 130\",\"CADC\",\"NEDC\".\n :type cycle: pandas.Series\n\n \"\"\"\n\n def __init__(self, cycle):\n\n self.cycle = cycle\n\n self.noise_coeff = self.get_noise_coefficients()\n\n @staticmethod\n def get_noise_coefficients():\n\n filename = \"internal_noise_coefficients.csv\"\n filepath = DATA_DIR / filename\n if not filepath.is_file():\n raise FileNotFoundError(\n \"The dictionary of noise coefficients could not be found.\"\n )\n\n with open(filepath) as f:\n csv_list = [[val.strip() for val in r.split(\";\")] for r in f.readlines()]\n (_, _, *header), *data = csv_list\n\n csv_dict = {}\n for row in data:\n key, sub_key, *values = row\n values = [float(v) for v in values]\n if key not in csv_dict:\n csv_dict[key] = {sub_key: values}\n else:\n csv_dict[key][sub_key] = values\n\n list_pt = [\n \"ICEV-p\",\n \"ICEV-d\",\n \"ICEV-g\",\n \"PHEV-p\",\n \"PHEV-d\",\n \"FCEV\",\n \"BEV\",\n \"HEV-p\",\n \"HEV-d\",\n ]\n list_size = [\n \"Large\",\n \"Lower medium\",\n \"Medium\",\n \"Mini\",\n \"Medium SUV\",\n \"Small\",\n \"Van\",\n \"Micro\",\n \"Large SUV\",\n ]\n\n arr = np.zeros((len(list_size), len(list_pt), 6))\n\n for pt in csv_dict:\n for size in csv_dict[pt]:\n arr[list_size.index(size), list_pt.index(pt), :] = csv_dict[pt][size]\n\n return arr\n\n def calculate_noise(self):\n # Instantiate the interpolation function\n # x = speed points (i.e., idle, 50 km/h, 80 km/h, 100 km/h, 120 km/h and 140 km/h)\n # y = dBs\n f = interp1d([0.0, 50.0, 80.0, 100.0, 120.0, 140.0], self.noise_coeff)\n\n # get dBs for every second of the driving cycle\n noise = f(self.cycle)\n\n # convert dBs to Watts (or joule.s^-1)\n noise = (10 ** -12) * (10 ** (noise / 10))\n\n # sum dBs along driving cycle to get joules\n noise = noise.sum(axis=2)\n\n # return a 9 by 7 arrays\n noise[noise < 1e-8] = np.nan\n return noise.reshape(7, 9, 1, 1)\n" ]
[ [ "numpy.tile", "numpy.zeros_like", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.vstack" ], [ "scipy.interpolate.interp1d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
nathanllww/slivka-irv
[ "6688ac88a34387df476d51f66d291e9f3b6454aa" ]
[ "wildcat_connection/csv.py" ]
[ "import os\nimport datetime\nimport pandas as pd\nfrom .constants import SUBMISSION_ID_COLNAME, QUESTION_RANK_SEPARATOR\nfrom . import BALLOT_FOLDER\nfrom .utils import isnan, wc_update_catcher\n\n\nclass WildcatConnectionCSV:\n \"\"\"\n Class for converting a Wildcat Connection exported ballot CSV into\n the ballot format for the `irv` module.\n\n Attributes\n ----------\n csv_filepath: str\n Filepath to Wildcat Connection CSV\n question_num_candidates: dict[str, int]\n Maps question name to number of candidates.\n question_formatted_ballots: dict[str, str]\n Maps question name to formatted ballot string.\n See `IRVElection` for information about the ballot format\n question_spoilt_ballots: dict[str, list[str]]\n Maps question name to list of SubmissionIDs with spoilt ballots.\n\n Parameters\n ----------\n csv_filepath : str\n Filepath to Wildcat Connection exported CSV.\n \"\"\"\n @wc_update_catcher\n def __init__(self, csv_filepath: str):\n self.csv_filepath = csv_filepath\n self.__df: pd.DataFrame = self._get_dataframe()\n self.question_num_candidates: dict[str, int] = self._get_question_num_candidates()\n formatted_ballots, spoilt_ballots = self._get_ballot_formatted_strings()\n self.question_formatted_ballots: dict[str, str] = formatted_ballots\n self.question_spoilt_ballots: dict[str, list[str]] = spoilt_ballots\n\n def _get_dataframe(self) -> pd.DataFrame:\n df = pd.read_csv(self.csv_filepath, header=[1], dtype=str)\n df[SUBMISSION_ID_COLNAME] = df[SUBMISSION_ID_COLNAME].astype(int)\n df = df.set_index(SUBMISSION_ID_COLNAME)\n return df\n\n @staticmethod\n def _valid_rank_set(rank_set: set[int]) -> bool:\n \"\"\"\n Checks if `rank_set` is a set of all numbers from 1 to `len(rank_set)`\n \"\"\"\n return rank_set == set(range(1, len(rank_set) + 1))\n\n def _get_question_num_candidates(self) -> dict[str, int]:\n \"\"\"\n Helper function for __init__\n\n Generates questions from DataFrame, and number of rankings for each question.\n Raises ValueError if duplicate columns exist.\n\n `self.__df` should already be populated.\n\n Returns\n -------\n question_num_candidates : dict[str, int]\n Dictionary mapping question name to number of candidates.\n \"\"\"\n question_ranks = [col.split(QUESTION_RANK_SEPARATOR) for col in self.__df.columns\n if col != SUBMISSION_ID_COLNAME]\n tracked = {}\n for question, rank in question_ranks:\n try:\n rank = int(rank)\n except ValueError:\n raise ValueError(f\"Duplicate Question: {question}\")\n tracked_ranks = tracked.setdefault(question, set())\n if rank in tracked_ranks:\n raise ValueError(f\"Duplicate Question: {question}\")\n tracked_ranks.add(rank)\n for question, rank_set in tracked.items():\n if not self._valid_rank_set(rank_set):\n raise ValueError(\n f\"\"\"\n Question {question} does not contain rank choices from 1 to {len(rank_set)}\n It contains: {rank_set}\n \"\"\"\n )\n return {question: len(rank_set) for question, rank_set in tracked.items()}\n\n def _get_one_ballot_format(self, question: str, num_candidates: int) -> tuple[str, list[str]]:\n \"\"\"\n Helper function to `_get_ballot_formatted_strings`\n\n Parameters\n ----------\n question : str\n Question name\n num_candidates : int\n Number of candidates\n Returns\n -------\n ballot_string : str\n Formatted ballot string\n spoiled_ballots : list[str]\n List of Submission IDs of spoiled ballots\n \"\"\"\n def _is_spoiled(row: list[str]) -> bool:\n for i in range(1, len(row)):\n if isnan(row[i-1]) and not isnan(row[i]):\n return True\n return False\n\n columns = [f\"{question}{QUESTION_RANK_SEPARATOR}{rank}\"\n for rank in range(1, num_candidates + 1)]\n valid_rows = []\n spoiled_ballots = []\n for submission_id, row in self.__df[columns].iterrows():\n row = row.tolist()\n if _is_spoiled(row):\n spoiled_ballots.append(submission_id)\n else:\n valid_rows.append(\",\".join([item for item in row if not isnan(item)]))\n\n ballot_string = \"\\n\".join(valid_rows)\n return ballot_string, spoiled_ballots\n\n def _get_ballot_formatted_strings(self) -> tuple[dict[str, str], dict[str, list[str]]]:\n \"\"\"\n For each question, get the ballot formatted string and the submission ids of spoilt ballots.\n\n `self.__df` and `self.question_num_candidates` should already be populated.\n\n Returns\n -------\n question_formatted_ballots : dict[str, str]\n Contains the formatted ballot string for each question.\n question_spoilt_ballots : dict[str, list[str]]\n Contains the Submission IDs of the spoilt ballots for each question.\n\n \"\"\"\n question_formatted_ballots, question_spoilt_ballots = {}, {}\n for question, num_candidates in self.question_num_candidates.items():\n ballot_string, spoiled_ballots = self._get_one_ballot_format(question, num_candidates)\n question_formatted_ballots[question] = ballot_string\n question_spoilt_ballots[question] = spoiled_ballots\n\n return question_formatted_ballots, question_spoilt_ballots\n\n def get_ballot_folder(self) -> str:\n \"\"\"\n Gets folder where ballots will be saved. Uses BALLOT_FOLDER constant.\n\n Returns\n -------\n ballot_folder : str\n \"\"\"\n csv_basename = os.path.basename(self.csv_filepath).split('.')[0]\n timestamp_str = str(datetime.datetime.now())\n return os.path.join(BALLOT_FOLDER, f\"{csv_basename}-{timestamp_str}\")\n\n def save_to_files(self, include_spoilt_ballots: bool = False) -> None:\n \"\"\"\n Saves ballots to folder.\n\n Each question is saved to a different file in the following format.\n\n - ballot_folder\n - question 1.csv\n - question 1_spoilt.txt\n - question 2.csv\n - question 2_spoilt.txt\n\n Parameters\n ----------\n include_spoilt_ballots: bool, optional\n Whether to make another file for spoilt ballots.\n Default: False\n \"\"\"\n folder = self.get_ballot_folder()\n os.makedirs(folder)\n for question, ballot_str in self.question_formatted_ballots:\n with open(os.path.join(folder, f\"{question}.csv\")) as file:\n file.write(ballot_str)\n if include_spoilt_ballots:\n with open(os.path.join(folder, f\"{question}_spoilt.txt\")):\n file.writelines(self.question_spoilt_ballots[question])\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Qiming-Wu/auto_LiRPA
[ "7e1fbf12d857ef8d411d80eef1bd73d9ae4ba3be" ]
[ "tests/test_conv.py" ]
[ "import torch\nimport argparse\nimport os\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom auto_LiRPA import BoundedModule, BoundedTensor\nfrom auto_LiRPA.perturbations import *\n\nparser = argparse.ArgumentParser()\nargs, unknown = parser.parse_known_args() \n\nclass Flatten(nn.Module):\n def __init__(self):\n super(Flatten, self).__init__()\n \n def forward(self, x):\n return x.view((x.shape[0], -1))\n\n\nclass cnn_model(nn.Module):\n def __init__(self, layers, padding, stride):\n super(cnn_model, self).__init__()\n self.module_list = []\n channel = 1\n length = 28\n for i in range(layers):\n self.module_list.append(nn.Conv2d(channel, 3, 4, stride = stride, padding = padding))\n channel = 3\n length = (length + 2 * padding - 4)//stride + 1\n assert length > 0\n self.module_list.append(nn.ReLU())\n self.module_list.append(Flatten())\n self.module_list.append(nn.Linear(3 * length * length, 256))\n self.module_list.append(nn.Linear(256, 10))\n\n self.model = nn.Sequential(*self.module_list)\n\n def forward(self, x):\n x = self.model(x)\n \n return x\n\n\ndef test():\n torch.manual_seed(1)\n torch.cuda.manual_seed_all(1)\n\n models = [2, 3]\n paddings = [1, 2]\n strides = [1, 3]\n\n N = 2\n n_classes = 10\n image = torch.randn(N, 1, 28, 28)\n image = image.to(torch.float32) / 255.0\n\n for layer_num in models:\n for padding in paddings:\n for stride in strides:\n # print(layer_num, padding, stride)\n try:\n model_ori = cnn_model(layer_num, padding, stride)\n except:\n continue\n\n\n model = BoundedModule(model_ori, torch.empty_like(image), device=\"cpu\", bound_opts={\"conv_mode\": \"patches\"})\n eps = 0.3\n norm = np.inf\n ptb = PerturbationLpNorm(norm=norm, eps=eps)\n image = BoundedTensor(image, ptb)\n pred = model(image)\n lb, ub = model.compute_bounds()\n\n model = BoundedModule(model_ori, torch.empty_like(image), device=\"cpu\", bound_opts={\"conv_mode\": \"matrix\"})\n pred = model(image)\n lb_ref, ub_ref = model.compute_bounds()\n\n assert lb.shape == ub.shape == torch.Size((N, n_classes)) \n assert torch.allclose(lb, lb_ref)\n assert torch.allclose(ub, ub_ref)\n\n # print(\"passed\")\n\nif __name__ == '__main__':\n test()" ]
[ [ "torch.nn.Sequential", "torch.Size", "torch.empty_like", "torch.manual_seed", "torch.randn", "torch.nn.Conv2d", "torch.nn.Linear", "torch.cuda.manual_seed_all", "torch.allclose", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sytelus/fast-autoaugment
[ "a53708699dce1233ce2a0bf0416ae2278007d506" ]
[ "FastAutoAugment/common/data.py" ]
[ "from torch.utils.data.dataloader import DataLoader\nimport os\nimport sys\nfrom typing import List, Tuple, Union, Optional\n\nimport torch\nimport torchvision\nfrom PIL import Image\n\nfrom torch.utils.data import \\\n SubsetRandomSampler, Sampler, Subset, ConcatDataset, Dataset, random_split\nfrom torchvision.transforms import transforms\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nfrom .aug_policies import arsaug_policy, autoaug_policy, autoaug_paper_cifar10,\\\n fa_reduced_cifar10, fa_reduced_svhn, fa_resnet50_rimagenet\nfrom .augmentations import *\nfrom ..common.common import get_logger\nfrom .common import utils\nfrom .imagenet import ImageNet\nfrom ..common.config import Config\n\nclass LimitDataset(Dataset):\n def __init__(self, dataset, n):\n self.dataset = dataset\n self.n = n\n if hasattr(dataset, 'targets'):\n self.targets = dataset.targets[:n]\n\n def __len__(self):\n return self.n\n\n def __getitem__(self, i):\n return self.dataset[i]\n\nDatasetLike = Union[Dataset, Subset, ConcatDataset, LimitDataset]\n\n\ndef get_data(conf_loader:Config)\\\n -> Tuple[Optional[DataLoader], Optional[DataLoader], Optional[DataLoader]]:\n # region conf vars\n # dataset\n conf_data = conf_loader['dataset']\n ds_name = conf_data['name']\n max_batches = conf_data['max_batches']\n dataroot = conf_data['dataroot']\n\n aug = conf_loader['aug']\n cutout = conf_loader['cutout']\n val_ratio = conf_loader['val_ratio']\n val_fold = conf_loader['val_fold']\n horovod = conf_loader['horovod']\n load_train = conf_loader['load_train']\n train_batch = conf_loader['train_batch']\n train_workers = conf_loader['train_workers']\n load_test = conf_loader['load_test']\n test_batch = conf_loader['test_batch']\n test_workers = conf_loader['test_workers']\n # endregion\n\n train_dl, val_dl, test_dl, *_ = get_dataloaders(dataroot, ds_name,\n load_train=load_train, train_batch_size=train_batch,\n load_test=load_test, test_batch_size=test_batch,\n aug=aug, cutout=cutout, val_ratio=val_ratio, val_fold=val_fold,\n train_workers=train_workers, test_workers=test_workers, horovod=horovod,\n max_batches=max_batches)\n\n assert train_dl is not None\n return train_dl, val_dl, test_dl\n\ndef get_dataloaders(dataroot:str, dataset:str,\n load_train:bool, train_batch_size:int,\n load_test:bool, test_batch_size:int,\n aug, cutout:int, val_ratio:float, val_fold=0,\n train_workers:Optional[int]=None, test_workers:Optional[int]=None,\n horovod=False, target_lb=-1, max_batches:int=-1) \\\n -> Tuple[Optional[DataLoader], Optional[DataLoader],\n Optional[DataLoader], Optional[Sampler]]:\n\n logger = get_logger()\n\n # if debugging in vscode, workers > 0 gets termination\n if utils.is_debugging():\n train_workers = test_workers = 0\n logger.warn('Debugger is detected, lower performance settings may be used.')\n if train_workers is None:\n train_workers = torch.cuda.device_count() * 4\n if test_workers is None:\n test_workers = torch.cuda.device_count() * 4\n logger.info(f'train_workers = {train_workers}, test_workers={test_workers}')\n\n # get usual random crop/flip transforms\n transform_train, transform_test = get_transforms(dataset, aug, cutout)\n\n trainset, testset = _get_datasets(dataset, dataroot,\n load_train, load_test, transform_train, transform_test,\n train_max_size=max_batches*train_batch_size,\n test_max_size=max_batches*test_batch_size)\n\n # TODO: below will never get executed, set_preaug does not exist in PyTorch\n # if total_aug is not None and augs is not None:\n # trainset.set_preaug(augs, total_aug)\n # logger.info('set_preaug-')\n\n trainloader, validloader, testloader, train_sampler = None, None, None, None\n\n if trainset:\n # sample validation set from trainset if cv_ration > 0\n train_sampler, valid_sampler = _get_train_sampler(val_ratio, val_fold,\n trainset, horovod, target_lb)\n trainloader = torch.utils.data.DataLoader(trainset,\n batch_size=train_batch_size, shuffle=True if train_sampler is None else False,\n num_workers=train_workers, pin_memory=True,\n sampler=train_sampler, drop_last=True)\n if train_sampler is not None:\n validloader = torch.utils.data.DataLoader(trainset,\n batch_size=train_batch_size, shuffle=False,\n num_workers=train_workers, pin_memory=True, #TODO: set n_workers per ratio?\n sampler=valid_sampler, drop_last=False)\n # else validloader is left as None\n if testset:\n testloader = torch.utils.data.DataLoader(testset,\n batch_size=test_batch_size, shuffle=False,\n num_workers=test_workers, pin_memory=True,\n sampler=None, drop_last=False\n )\n\n assert val_ratio > 0.0 or validloader is None\n\n logger.info('Dataset batches: train={}, val={}, test={}'.format(\n len(trainloader) if trainloader is not None else 'None',\n len(validloader) if validloader is not None else 'None',\n len(testloader) if testloader is not None else 'None'))\n\n # we have to return train_sampler because of horovod\n return trainloader, validloader, testloader, train_sampler\n\ndef get_transforms(dataset, aug:Union[List, str], cutout:int):\n if 'imagenet' in dataset:\n return _get_imagenet_transforms()\n\n if dataset == 'cifar10':\n MEAN = [0.49139968, 0.48215827, 0.44653124]\n STD = [0.24703233, 0.24348505, 0.26158768]\n transf = [\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip()\n ]\n elif dataset == 'cifar100':\n MEAN = [0.507, 0.487, 0.441]\n STD = [0.267, 0.256, 0.276]\n transf = [\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip()\n ]\n elif dataset == 'svhn':\n MEAN = [0.4914, 0.4822, 0.4465]\n STD = [0.2023, 0.1994, 0.20100]\n transf = [\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip()\n ]\n elif dataset == 'mnist':\n MEAN = [0.13066051707548254]\n STD = [0.30810780244715075]\n transf = [\n transforms.RandomAffine(degrees=15, translate=(0.1, 0.1),\n scale=(0.9, 1.1), shear=0.1)\n ]\n elif dataset == 'fashionmnist':\n MEAN = [0.28604063146254594]\n STD = [0.35302426207299326]\n transf = [\n transforms.RandomAffine(degrees=15, translate=(0.1, 0.1),\n scale=(0.9, 1.1), shear=0.1),\n transforms.RandomVerticalFlip()\n ]\n else:\n raise ValueError('dataset not recognized: {}'.format(dataset))\n\n normalize = [\n transforms.ToTensor(),\n transforms.Normalize(MEAN, STD)\n ]\n\n train_transform = transforms.Compose(transf + normalize)\n test_transform = transforms.Compose(normalize)\n\n # add additional aug and cutout transformations\n _add_augs(train_transform, aug, cutout)\n\n return train_transform, test_transform\n\nclass CutoutDefault:\n \"\"\"\n Reference : https://github.com/quark0/darts/blob/master/cnn/utils.py\n \"\"\"\n def __init__(self, length):\n self.length = length\n\n def __call__(self, img):\n h, w = img.size(1), img.size(2)\n mask = np.ones((h, w), np.float32)\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - self.length // 2, 0, h)\n y2 = np.clip(y + self.length // 2, 0, h)\n x1 = np.clip(x - self.length // 2, 0, w)\n x2 = np.clip(x + self.length // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n mask = torch.from_numpy(mask)\n mask = mask.expand_as(img)\n img *= mask\n return img\n\nclass Augmentation:\n def __init__(self, policies):\n self.policies = policies\n\n def __call__(self, img):\n for _ in range(1):\n policy = random.choice(self.policies)\n for name, pr, level in policy:\n if random.random() > pr:\n continue\n img = apply_augment(img, name, level)\n return img\n\n\nclass SubsetSampler(Sampler):\n r\"\"\"Samples elements from a given list of indices, without replacement.\n\n Arguments:\n indices (sequence): a sequence of indices\n \"\"\"\n\n def __init__(self, indices):\n self.indices = indices\n\n def __iter__(self):\n return (i for i in self.indices)\n\n def __len__(self):\n return len(self.indices)\n\ndef _get_datasets(dataset, dataroot, load_train:bool, load_test:bool,\n transform_train, transform_test, train_max_size:int, test_max_size:int)\\\n ->Tuple[DatasetLike, DatasetLike]:\n logger = get_logger()\n trainset, testset = None, None\n\n if dataset == 'cifar10':\n if load_train:\n # NOTE: train transforms will also be applied to validation set\n trainset = torchvision.datasets.CIFAR10(root=dataroot, train=True,\n download=True, transform=transform_train)\n if load_test:\n testset = torchvision.datasets.CIFAR10(root=dataroot, train=False,\n download=True, transform=transform_test)\n elif dataset == 'mnist':\n if load_train:\n trainset = torchvision.datasets.MNIST(root=dataroot, train=True,\n download=True, transform=transform_train)\n if load_test:\n testset = torchvision.datasets.MNIST(root=dataroot, train=False,\n download=True, transform=transform_test)\n elif dataset == 'fashionmnist':\n if load_train:\n trainset = torchvision.datasets.FashionMNIST(root=dataroot,\n train=True, download=True, transform=transform_train)\n if load_test:\n testset = torchvision.datasets.FashionMNIST(root=dataroot,\n train=False, download=True, transform=transform_test)\n elif dataset == 'reduced_cifar10':\n if load_train:\n trainset = torchvision.datasets.CIFAR10(root=dataroot, train=True,\n download=True, transform=transform_train)\n sss = StratifiedShuffleSplit(n_splits=1, test_size=46000) # 4000\n sss = sss.split(list(range(len(trainset))), trainset.targets)\n train_idx, valid_idx = next(sss)\n targets = [trainset.targets[idx] for idx in train_idx]\n trainset = Subset(trainset, train_idx)\n trainset.targets = targets\n if load_test:\n testset = torchvision.datasets.CIFAR10(root=dataroot, train=False,\n download=True, transform=transform_test)\n elif dataset == 'cifar100':\n if load_train:\n trainset = torchvision.datasets.CIFAR100(root=dataroot, train=True,\n download=True, transform=transform_train)\n if load_test:\n testset = torchvision.datasets.CIFAR100(root=dataroot, train=False,\n download=True, transform=transform_test)\n elif dataset == 'svhn':\n if load_train:\n trainset = torchvision.datasets.SVHN(root=dataroot, split='train',\n download=True, transform=transform_train)\n extraset = torchvision.datasets.SVHN(root=dataroot, split='extra',\n download=True, transform=transform_train)\n trainset = ConcatDataset([trainset, extraset])\n if load_test:\n testset = torchvision.datasets.SVHN(root=dataroot, split='test',\n download=True, transform=transform_test)\n elif dataset == 'reduced_svhn':\n if load_train:\n trainset = torchvision.datasets.SVHN(root=dataroot, split='train',\n download=True, transform=transform_train)\n sss = StratifiedShuffleSplit(n_splits=1, test_size=73257-1000) #1000\n sss = sss.split(list(range(len(trainset))), trainset.targets)\n train_idx, valid_idx = next(sss)\n targets = [trainset.targets[idx] for idx in train_idx]\n trainset = Subset(trainset, train_idx)\n trainset.targets = targets\n if load_test:\n testset = torchvision.datasets.SVHN(root=dataroot, split='test',\n download=True, transform=transform_test)\n elif dataset == 'imagenet':\n if load_train:\n trainset = ImageNet(root=os.path.join(dataroot, 'imagenet-pytorch'),\n transform=transform_train)\n # compatibility\n trainset.targets = [lb for _, lb in trainset.samples]\n if load_test:\n testset = ImageNet(root=os.path.join(dataroot, 'imagenet-pytorch'),\n split='val', transform=transform_test)\n elif dataset == 'reduced_imagenet':\n # randomly chosen indices\n idx120 = [904, 385, 759, 884, 784, 844, 132, 214, 990, 786, 979, 582,\n 104, 288, 697, 480, 66, 943, 308, 282, 118, 926, 882, 478, 133, 884,\n 570, 964, 825, 656, 661, 289, 385, 448, 705, 609, 955, 5, 703, 713, 695,\n 811, 958, 147, 6, 3, 59, 354, 315, 514, 741, 525, 685, 673, 657, 267,\n 575, 501, 30, 455, 905, 860, 355, 911, 24, 708, 346, 195, 660, 528, 330,\n 511, 439, 150, 988, 940, 236, 803, 741, 295, 111, 520, 856, 248, 203,\n 147, 625, 589, 708, 201, 712, 630, 630, 367, 273, 931, 960, 274, 112,\n 239, 463, 355, 955, 525, 404, 59, 981, 725, 90, 782, 604, 323, 418, 35,\n 95, 97, 193, 690, 869, 172]\n if load_train:\n trainset = ImageNet(root=os.path.join(dataroot, 'imagenet-pytorch'),\n transform=transform_train)\n # compatibility\n trainset.targets = [lb for _, lb in trainset.samples]\n\n sss = StratifiedShuffleSplit(n_splits=1,\n test_size=len(trainset) - 500000, random_state=0) # 4000\n sss = sss.split(list(range(len(trainset))), trainset.targets)\n train_idx, valid_idx = next(sss)\n\n # filter out\n train_idx = list(filter(lambda x: trainset.labels[x] in idx120, train_idx))\n valid_idx = list(filter(lambda x: trainset.labels[x] in idx120, valid_idx))\n\n targets = [idx120.index(trainset.targets[idx]) for idx in train_idx]\n for idx in range(len(trainset.samples)):\n if trainset.samples[idx][1] not in idx120:\n continue\n trainset.samples[idx] = (trainset.samples[idx][0],\n idx120.index(trainset.samples[idx][1]))\n trainset = Subset(trainset, train_idx)\n trainset.targets = targets\n logger.info('reduced_imagenet train={}'.format(len(trainset)))\n if load_test:\n testset = ImageNet(root=os.path.join(dataroot, 'imagenet-pytorch'),\n split='val', transform=transform_test)\n test_idx = list(filter(lambda x: testset.samples[x][1] in \\\n idx120, range(len(testset))))\n for idx in range(len(testset.samples)):\n if testset.samples[idx][1] not in idx120:\n continue\n testset.samples[idx] = (testset.samples[idx][0],\n idx120.index(testset.samples[idx][1]))\n testset = Subset(testset, test_idx)\n else:\n raise ValueError('invalid dataset name=%s' % dataset)\n\n if train_max_size > 0:\n logger.warn('Trainset trimmed to max_batches = {}'.format(train_max_size))\n trainset = LimitDataset(trainset, train_max_size)\n if test_max_size > 0:\n logger.warn('Testset trimmed to max_batches = {}'.format(test_max_size))\n testset = LimitDataset(testset, test_max_size)\n\n return trainset, testset\n\n# target_lb allows to filter dataset for a specific class, not used\ndef _get_train_sampler(val_ratio:float, val_fold:int, trainset, horovod,\n target_lb:int=-1)->Tuple[Optional[Sampler], Sampler]:\n \"\"\"Splits train set into train, validation sets, stratified rand sampling.\n\n Arguments:\n val_ratio {float} -- % of data to put in valid set\n val_fold {int} -- Total of 5 folds are created, val_fold specifies which\n one to use\n target_lb {int} -- If >= 0 then trainset is filtered for only that\n target class ID\n \"\"\"\n logger = get_logger()\n assert val_fold >= 0\n\n train_sampler, valid_sampler = None, None\n if val_ratio > 0.0: # if val_ratio is not specified then sampler is empty\n \"\"\"stratified shuffle val_ratio will yield return total of n_splits,\n each val_ratio containing tuple of train and valid set with valid set\n size portion = val_ratio, while samples for each class having same\n proportions as original dataset\"\"\"\n\n logger.info('Validation set ratio = {}'.format(val_ratio))\n\n # TODO: random_state should be None so np.random is used\n # TODO: keep hardcoded n_splits=5?\n sss = StratifiedShuffleSplit(n_splits=5, test_size=val_ratio,\n random_state=0)\n sss = sss.split(list(range(len(trainset))), trainset.targets)\n\n # we have 5 plits, but will select only one of them by val_fold\n for _ in range(val_fold + 1):\n train_idx, valid_idx = next(sss)\n\n if target_lb >= 0:\n train_idx = [i for i in train_idx if trainset.targets[i] == target_lb]\n valid_idx = [i for i in valid_idx if trainset.targets[i] == target_lb]\n\n # NOTE: we apply random sampler for validation set as well because\n # this set is used for training alphas for darts\n train_sampler = SubsetRandomSampler(train_idx)\n valid_sampler = SubsetRandomSampler(valid_idx)\n\n if horovod: # train sampler for horovod\n import horovod.torch as hvd\n train_sampler = torch.utils.data.distributed.DistributedSampler(\n train_sampler, num_replicas=hvd.size(), rank=hvd.rank())\n else:\n logger.info('Validation set is not produced')\n\n # this means no sampling, validation set would be empty\n valid_sampler = SubsetSampler([])\n\n if horovod: # train sampler for horovod\n import horovod.torch as hvd\n train_sampler = torch.utils.data.distributed.DistributedSampler(\n valid_sampler, num_replicas=hvd.size(), rank=hvd.rank())\n # else train_sampler is None\n return train_sampler, valid_sampler\n\n\ndef _add_augs(transform_train, aug:Union[List, str], cutout:int):\n logger = get_logger()\n\n # TODO: recheck: total_aug remains None in original fastaug code\n total_aug = augs = None\n\n logger.info(f'Additional augmentation = \"{aug}\"')\n if isinstance(aug, list):\n transform_train.transforms.insert(0, Augmentation(aug))\n elif aug:\n if aug == 'fa_reduced_cifar10':\n transform_train.transforms.insert(0, Augmentation(fa_reduced_cifar10()))\n\n elif aug == 'fa_reduced_imagenet':\n transform_train.transforms.insert(0, Augmentation(fa_resnet50_rimagenet()))\n\n elif aug == 'fa_reduced_svhn':\n transform_train.transforms.insert(0, Augmentation(fa_reduced_svhn()))\n\n elif aug == 'arsaug':\n transform_train.transforms.insert(0, Augmentation(arsaug_policy()))\n elif aug == 'autoaug_cifar10':\n transform_train.transforms.insert(0, Augmentation(autoaug_paper_cifar10()))\n elif aug == 'autoaug_extend':\n transform_train.transforms.insert(0, Augmentation(autoaug_policy()))\n elif aug in ['default', 'inception', 'inception320']:\n pass\n else:\n raise ValueError('Augmentations not found: %s' % aug)\n\n # add cutout transform\n # TODO: use PyTorch built-in cutout\n logger.info('Cutout = {}'.format(cutout))\n if cutout > 0:\n transform_train.transforms.append(CutoutDefault(cutout))\n\n return total_aug, augs\n\ndef _get_imagenet_transforms():\n transform_train, transform_test = None, None\n\n _IMAGENET_PCA = {\n 'eigval': [0.2175, 0.0188, 0.0045],\n 'eigvec': [\n [-0.5675, 0.7192, 0.4009],\n [-0.5808, -0.0045, -0.8140],\n [-0.5836, -0.6948, 0.4203],\n ]\n }\n\n transform_train = transforms.Compose([\n transforms.RandomResizedCrop(224, scale=(0.08, 1.0),\n interpolation=Image.BICUBIC),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(\n brightness=0.4,\n contrast=0.4,\n saturation=0.4,\n ),\n transforms.ToTensor(),\n # TODO: Lightning is not used in original darts paper\n Lighting(0.1, _IMAGENET_PCA['eigval'], _IMAGENET_PCA['eigvec']),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])\n\n transform_test = transforms.Compose([\n transforms.Resize(256, interpolation=Image.BICUBIC),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])\n\n return transform_train, transform_test\n\n" ]
[ [ "torch.utils.data.SubsetRandomSampler", "torch.utils.data.DataLoader", "torch.from_numpy", "torch.utils.data.ConcatDataset", "torch.utils.data.Subset", "torch.cuda.device_count", "sklearn.model_selection.StratifiedShuffleSplit" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dsys/pavlov
[ "6357019cf8bb32ff204c269e5b4cbc690bda984b" ]
[ "src/fast-hamm/server.py" ]
[ "from flask import Flask, jsonify, request\nimport argparse\nimport msgpack\nimport numpy as np\nimport os\nimport rocksdb\n\nparser = argparse.ArgumentParser()\nparser.add_argument('database', metavar='DATABASE', help='path to the database')\nparser.add_argument('--port', type=int, default=5000, help='path to the database')\nargs = parser.parse_args()\n\ndb_opts = rocksdb.Options()\ndb_opts.create_if_missing = True\ndb_opts.max_open_files = 300000\ndb_opts.write_buffer_size = 67108864\ndb_opts.max_write_buffer_number = 3\ndb_opts.target_file_size_base = 67108864\ndb_opts.table_factory = rocksdb.BlockBasedTableFactory(\n filter_policy=rocksdb.BloomFilterPolicy(10),\n block_cache=rocksdb.LRUCache(2 * (1024 ** 3)),\n block_cache_compressed=rocksdb.LRUCache(500 * (1024 ** 2)))\n\ndb = rocksdb.DB(args.database, db_opts)\n\napp = Flask(__name__)\n\[email protected]('/_ping', methods=['GET'])\ndef handle_ping():\n return jsonify({ 'data': 'pong' })\n\[email protected]('/<index>', methods=['GET', 'POST', 'DELETE'])\ndef handle_index(index):\n db_start_key = (index + '/').encode('utf-8')\n if request.method == 'GET':\n it = db.iterkeys()\n it.seek(db_start_key)\n count = 0\n if request.args.get('list', False):\n keys = []\n for db_key in it:\n if not db_key.startswith(db_start_key): break\n count += 1\n _index, key = db_key.decode('utf-8').split('/')\n keys.append(key)\n return jsonify({ 'count': count, 'keys': keys })\n else:\n for db_key in it:\n if not db_key.startswith(db_start_key): break\n count += 1\n return jsonify({ 'count': count })\n elif request.method == 'POST':\n try:\n results = []\n vec = np.array([int(x) for x in list(request.json['vec'])])\n rank = len(vec)\n max_dist = int(request.json.get('max', 10))\n it = db.iteritems()\n it.seek(db_start_key)\n for db_key, db_val in it:\n if not db_key.startswith(db_start_key): break\n other_vec = np.array(msgpack.unpackb(db_val))\n if rank != len(other_vec):\n continue\n dist = np.count_nonzero(vec != other_vec)\n if dist <= max_dist:\n _index, key = db_key.decode('utf-8').split('/')\n results.append({ 'key': key, 'dist': dist })\n return jsonify({ 'data': results })\n except KeyError as err:\n return jsonify({\n 'errors': [{ 'message': 'missing arg: ' + str(err) }]\n }), 400\n except (TypeError, ValueError) as err:\n return jsonify({\n 'errors': [{ 'message': 'invalid value: ' + str(err) }]\n }), 400\n else:\n it = db.iterkeys()\n it.seek(db_start_key)\n count = 0\n batch = rocksdb.WriteBatch()\n for db_key in it:\n if not db_key.startswith(db_start_key): break\n batch.delete(db_key)\n count += 1\n db.write(batch)\n return jsonify({ 'data': count })\n\[email protected]('/<index>/<key>', methods=['GET', 'PUT', 'DELETE'])\ndef handle_vector(index, key):\n db_key = (index + '/' + key).encode('utf-8')\n if request.method == 'GET':\n db_val = db.get(db_key)\n if db_val is None:\n return jsonify({ 'errors': [{ 'message': 'not found' }] }), 404\n val = ''.join(str(x) for x in msgpack.unpackb(db_val))\n return jsonify({ 'data': val })\n elif request.method == 'PUT':\n if request.json is None:\n return jsonify({ 'errors': [{ 'message': 'body required' }] }), 400\n try:\n vec = [int(x) for x in list(request.json['vec'])]\n db_val = msgpack.packb(vec)\n db.put(db_key, db_val)\n return jsonify({ 'data': True })\n except ValueError as err:\n return jsonify({ 'errors': [{ 'message': 'invalid value: ' + str(err) }] }), 400\n else:\n db.delete(db_key)\n return jsonify({ 'data': True })\n\napp.run(host='0.0.0.0', port=args.port)\n" ]
[ [ "numpy.count_nonzero" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
smarthi/tensorflow
[ "55b01593515817992821423fec19733bca91c918", "55b01593515817992821423fec19733bca91c918", "55b01593515817992821423fec19733bca91c918", "55b01593515817992821423fec19733bca91c918" ]
[ "tensorflow/python/training/training.py", "tensorflow/contrib/learn/python/learn/datasets/text_datasets.py", "tensorflow/contrib/tensor_forest/python/topn.py", "tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined_benchmark_test.py" ]
[ "# Copyright 2015 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\n# pylint: disable=line-too-long\n\"\"\"This library provides a set of classes and functions that helps train models.\n\n## Optimizers\n\nThe Optimizer base class provides methods to compute gradients for a loss and\napply gradients to variables. A collection of subclasses implement classic\noptimization algorithms such as GradientDescent and Adagrad.\n\nYou never instantiate the Optimizer class itself, but instead instantiate one\nof the subclasses.\n\n@@Optimizer\n\n@@GradientDescentOptimizer\n@@AdadeltaOptimizer\n@@AdagradOptimizer\n@@AdagradDAOptimizer\n@@MomentumOptimizer\n@@AdamOptimizer\n@@FtrlOptimizer\n@@ProximalGradientDescentOptimizer\n@@ProximalAdagradOptimizer\n@@RMSPropOptimizer\n\n## Gradient Computation\n\nTensorFlow provides functions to compute the derivatives for a given\nTensorFlow computation graph, adding operations to the graph. The\noptimizer classes automatically compute derivatives on your graph, but\ncreators of new Optimizers or expert users can call the lower-level\nfunctions below.\n\n@@gradients\n@@AggregationMethod\n\n@@stop_gradient\n\n@@hessians\n\n\n## Gradient Clipping\n\nTensorFlow provides several operations that you can use to add clipping\nfunctions to your graph. You can use these functions to perform general data\nclipping, but they're particularly useful for handling exploding or vanishing\ngradients.\n\n@@clip_by_value\n@@clip_by_norm\n@@clip_by_average_norm\n@@clip_by_global_norm\n@@global_norm\n\n## Decaying the learning rate\n@@exponential_decay\n@@inverse_time_decay\n@@natural_exp_decay\n@@piecewise_constant\n@@polynomial_decay\n\n## Moving Averages\n\nSome training algorithms, such as GradientDescent and Momentum often benefit\nfrom maintaining a moving average of variables during optimization. Using the\nmoving averages for evaluations often improve results significantly.\n\n@@ExponentialMovingAverage\n\n## Coordinator and QueueRunner\n\nSee [Threading and Queues](../../how_tos/threading_and_queues/index.md)\nfor how to use threads and queues. For documentation on the Queue API,\nsee [Queues](../../api_docs/python/io_ops.md#queues).\n\n@@Coordinator\n@@QueueRunner\n@@add_queue_runner\n@@start_queue_runners\n\n## Distributed execution\n\nSee [Distributed TensorFlow](../../how_tos/distributed/index.md) for\nmore information about how to configure a distributed TensorFlow program.\n\n@@Server\n@@Supervisor\n@@SessionManager\n@@ClusterSpec\n@@replica_device_setter\n@@MonitoredTrainingSession\n@@MonitoredSession\n@@SingularMonitoredSession\n@@Scaffold\n@@SessionCreator\n@@ChiefSessionCreator\n@@WorkerSessionCreator\n\n## Reading Summaries from Event Files\n\nSee [Summaries and\nTensorBoard](../../how_tos/summaries_and_tensorboard/index.md) for an\noverview of summaries, event files, and visualization in TensorBoard.\n\n@@summary_iterator\n\n## Training Utilities\n\n@@global_step\n@@basic_train_loop\n@@get_global_step\n@@assert_global_step\n@@write_graph\n@@SessionRunHook\n@@LoggingTensorHook\n@@StopAtStepHook\n@@CheckpointSaverHook\n@@NewCheckpointReader\n@@StepCounterHook\n@@NanLossDuringTrainingError\n@@NanTensorHook\n@@SummarySaverHook\n@@GlobalStepWaiterHook\n@@SessionRunArgs\n@@SessionRunContext\n@@SessionRunValues\n@@LooperThread\n\"\"\"\n# pylint: enable=line-too-long\n\n# Optimizers.\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys as _sys\n\nfrom tensorflow.python.ops import io_ops as _io_ops\nfrom tensorflow.python.ops import state_ops as _state_ops\nfrom tensorflow.python.util.all_util import remove_undocumented\n\n# pylint: disable=g-bad-import-order,unused-import\nfrom tensorflow.python.training.adadelta import AdadeltaOptimizer\nfrom tensorflow.python.training.adagrad import AdagradOptimizer\nfrom tensorflow.python.training.adagrad_da import AdagradDAOptimizer\nfrom tensorflow.python.training.proximal_adagrad import ProximalAdagradOptimizer\nfrom tensorflow.python.training.adam import AdamOptimizer\nfrom tensorflow.python.training.ftrl import FtrlOptimizer\nfrom tensorflow.python.training.momentum import MomentumOptimizer\nfrom tensorflow.python.training.moving_averages import ExponentialMovingAverage\nfrom tensorflow.python.training.optimizer import Optimizer\nfrom tensorflow.python.training.rmsprop import RMSPropOptimizer\nfrom tensorflow.python.training.gradient_descent import GradientDescentOptimizer\nfrom tensorflow.python.training.proximal_gradient_descent import ProximalGradientDescentOptimizer\nfrom tensorflow.python.training.sync_replicas_optimizer import SyncReplicasOptimizer\n\n# Utility classes for training.\nfrom tensorflow.python.training.coordinator import Coordinator\nfrom tensorflow.python.training.coordinator import LooperThread\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import\nfrom tensorflow.python.training.queue_runner import *\n\n# For the module level doc.\nfrom tensorflow.python.training import input as _input\nfrom tensorflow.python.training.input import *\n# pylint: enable=wildcard-import\n\nfrom tensorflow.python.training.basic_session_run_hooks import LoggingTensorHook\nfrom tensorflow.python.training.basic_session_run_hooks import StopAtStepHook\nfrom tensorflow.python.training.basic_session_run_hooks import CheckpointSaverHook\nfrom tensorflow.python.training.basic_session_run_hooks import StepCounterHook\nfrom tensorflow.python.training.basic_session_run_hooks import NanLossDuringTrainingError\nfrom tensorflow.python.training.basic_session_run_hooks import NanTensorHook\nfrom tensorflow.python.training.basic_session_run_hooks import SummarySaverHook\nfrom tensorflow.python.training.basic_session_run_hooks import GlobalStepWaiterHook\nfrom tensorflow.python.training.basic_loops import basic_train_loop\nfrom tensorflow.python.training.device_setter import replica_device_setter\nfrom tensorflow.python.training.monitored_session import Scaffold\nfrom tensorflow.python.training.monitored_session import MonitoredTrainingSession\nfrom tensorflow.python.training.monitored_session import SessionCreator\nfrom tensorflow.python.training.monitored_session import ChiefSessionCreator\nfrom tensorflow.python.training.monitored_session import WorkerSessionCreator\nfrom tensorflow.python.training.monitored_session import MonitoredSession\nfrom tensorflow.python.training.monitored_session import SingularMonitoredSession\nfrom tensorflow.python.training.saver import Saver\nfrom tensorflow.python.training.saver import checkpoint_exists\nfrom tensorflow.python.training.saver import generate_checkpoint_state_proto\nfrom tensorflow.python.training.saver import get_checkpoint_mtimes\nfrom tensorflow.python.training.saver import get_checkpoint_state\nfrom tensorflow.python.training.saver import latest_checkpoint\nfrom tensorflow.python.training.saver import update_checkpoint_state\nfrom tensorflow.python.training.saver import export_meta_graph\nfrom tensorflow.python.training.saver import import_meta_graph\nfrom tensorflow.python.training.session_run_hook import SessionRunHook\nfrom tensorflow.python.training.session_run_hook import SessionRunArgs\nfrom tensorflow.python.training.session_run_hook import SessionRunContext\nfrom tensorflow.python.training.session_run_hook import SessionRunValues\nfrom tensorflow.python.training.session_manager import SessionManager\nfrom tensorflow.python.training.summary_io import summary_iterator\nfrom tensorflow.python.training.supervisor import Supervisor\nfrom tensorflow.python.training.training_util import write_graph\nfrom tensorflow.python.training.training_util import global_step\nfrom tensorflow.python.training.training_util import get_global_step\nfrom tensorflow.python.training.training_util import assert_global_step\nfrom tensorflow.python.pywrap_tensorflow import do_quantize_training_on_graphdef\nfrom tensorflow.python.pywrap_tensorflow import NewCheckpointReader\n\n# pylint: disable=wildcard-import\n# Training data protos.\nfrom tensorflow.core.example.example_pb2 import *\nfrom tensorflow.core.example.feature_pb2 import *\nfrom tensorflow.core.protobuf.saver_pb2 import *\n\n# Utility op. Open Source. TODO(touts): move to nn?\nfrom tensorflow.python.training.learning_rate_decay import *\n# pylint: enable=wildcard-import\n\n# Distributed computing support.\nfrom tensorflow.core.protobuf.tensorflow_server_pb2 import ClusterDef\nfrom tensorflow.core.protobuf.tensorflow_server_pb2 import JobDef\nfrom tensorflow.core.protobuf.tensorflow_server_pb2 import ServerDef\nfrom tensorflow.python.training.server_lib import ClusterSpec\nfrom tensorflow.python.training.server_lib import Server\n\n# Symbols whitelisted for export without documentation.\n_allowed_symbols = [\n # TODO(cwhipkey): review these and move to contrib or expose through\n # documentation.\n \"generate_checkpoint_state_proto\", # Used internally by saver.\n \"checkpoint_exists\", # Only used in test?\n \"get_checkpoint_mtimes\", # Only used in test?\n\n # Legacy: remove.\n \"do_quantize_training_on_graphdef\", # At least use grah_def, not graphdef.\n # No uses within tensorflow.\n \"queue_runner\", # Use tf.train.start_queue_runner etc directly.\n # This is also imported internally.\n\n # TODO(drpng): document these. The reference in howtos/distributed does\n # not link.\n \"SyncReplicasOptimizer\",\n # Protobufs:\n \"BytesList\", # from example_pb2.\n \"ClusterDef\",\n \"Example\", # from example_pb2\n \"Feature\", # from example_pb2\n \"Features\", # from example_pb2\n \"FeatureList\", # from example_pb2\n \"FeatureLists\", # from example_pb2\n \"FloatList\", # from example_pb2.\n \"Int64List\", # from example_pb2.\n \"JobDef\",\n \"SaverDef\", # From saver_pb2.\n \"SequenceExample\", # from example_pb2.\n \"ServerDef\",\n]\n# Include extra modules for docstrings because:\n# * Input methods in tf.train are documented in io_ops.\n# * Saver methods in tf.train are documented in state_ops.\nremove_undocumented(__name__, _allowed_symbols,\n [_sys.modules[__name__], _io_ops, _state_ops])\n", "# Copyright 2016 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\n\"\"\"Text datasets.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport tarfile\n\nimport numpy as np\n\nfrom tensorflow.contrib.learn.python.learn.datasets import base\nfrom tensorflow.python.platform import gfile\n\nDBPEDIA_URL = 'https://github.com/le-scientifique/torchDatasets/blob/master/dbpedia_csv.tar.gz'\n\n\ndef maybe_download_dbpedia(data_dir):\n \"\"\"Download if DBpedia data is not present.\"\"\"\n train_path = os.path.join(data_dir, 'dbpedia_csv/train.csv')\n test_path = os.path.join(data_dir, 'dbpedia_csv/test.csv')\n if not (gfile.Exists(train_path) and gfile.Exists(test_path)):\n archive_path = base.maybe_download(\n 'dbpedia_csv.tar.gz', data_dir, DBPEDIA_URL)\n tfile = tarfile.open(archive_path, 'r:*')\n tfile.extractall(data_dir)\n\n\ndef load_dbpedia(size='small', test_with_fake_data=False):\n \"\"\"Get DBpedia datasets from CSV files.\"\"\"\n if not test_with_fake_data:\n data_dir = os.path.join(os.getenv('TF_EXP_BASE_DIR', ''), 'dbpedia_data')\n maybe_download_dbpedia(data_dir)\n\n train_path = os.path.join(data_dir, 'dbpedia_csv', 'train.csv')\n test_path = os.path.join(data_dir, 'dbpedia_csv', 'test.csv')\n\n if size == 'small':\n # Reduce the size of original data by a factor of 1000.\n base.shrink_csv(train_path, 1000)\n base.shrink_csv(test_path, 1000)\n train_path = train_path.replace('train.csv', 'train_small.csv')\n test_path = test_path.replace('test.csv', 'test_small.csv')\n else:\n module_path = os.path.dirname(__file__)\n train_path = os.path.join(module_path, 'data', 'text_train.csv')\n test_path = os.path.join(module_path, 'data', 'text_test.csv')\n\n train = base.load_csv_without_header(\n train_path, target_dtype=np.int32, features_dtype=np.str, target_column=0)\n test = base.load_csv_without_header(\n test_path, target_dtype=np.int32, features_dtype=np.str, target_column=0)\n\n return base.Datasets(train=train, validation=None, test=test)\n", "# Copyright 2016 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\"\"\"A collection that allows repeated access to its top-scoring items.\"\"\"\n# pylint: disable=g-bad-name\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.tensor_forest.python.ops import tensor_forest_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variable_scope\n\n\nclass TopN(object):\n \"\"\"A collection that allows repeated access to its top-scoring items.\n\n A TopN supports the following three operations:\n 1) insert(ids, scores). ids is a 1-d int64 Tensor and scores is a 1-d\n float Tensor. scores[i] is the score associated with ids[i]. It is\n totally fine to re-insert ids that have already been inserted into the\n collection.\n\n 2) remove(ids)\n\n 3) ids, scores = get_best(n). scores will contain the n highest (most\n positive) scores currently in the TopN, and ids their corresponding ids.\n n is a 1-d int32 Tensor with shape (1).\n\n TopN is implemented using a short-list of the top scoring items. At\n construction time, the size of the short-list must be specified, and it\n is an error to call GetBest(n) with an n greater than that size.\n \"\"\"\n\n def __init__(self, max_id, shortlist_size=100, name_prefix=''):\n \"\"\"Creates a new TopN.\"\"\"\n self.shortlist_size = shortlist_size\n # id_to_score contains all the scores we are tracking.\n self.id_to_score = variable_scope.get_variable(\n name=name_prefix + 'id_to_score',\n dtype=dtypes.float32,\n shape=[max_id],\n initializer=init_ops.constant_initializer(dtypes.float32.min))\n # sl_ids and sl_scores together satisfy four invariants:\n # 1) If sl_ids[i] != -1, then\n # id_to_score[sl_ids[i]] = sl_scores[i] >= sl_scores[0]\n # 2) sl_ids[0] is the number of i > 0 for which sl_ids[i] != -1.\n # 3) If id_to_score[i] > sl_scores[0], then\n # sl_ids[j] = i for some j.\n # 4) If sl_ids[i] == -1, then sl_scores[i] = tf.float32.min.\n self.sl_ids = variable_scope.get_variable(\n name=name_prefix + 'shortlist_ids',\n dtype=dtypes.int64,\n shape=[shortlist_size + 1],\n initializer=init_ops.constant_initializer(-1))\n # Ideally, we would set self.sl_ids[0] = 0 here. But then it is hard\n # to pass that control dependency to the other other Ops. Instead, we\n # have insert, remove and get_best all deal with the fact that\n # self.sl_ids[0] == -1 actually means the shortlist size is 0.\n self.sl_scores = variable_scope.get_variable(\n name=name_prefix + 'shortlist_scores',\n dtype=dtypes.float32,\n shape=[shortlist_size + 1],\n initializer=init_ops.constant_initializer(dtypes.float32.min))\n # TopN keeps track of its internal data dependencies, so the user\n # doesn't have to.\n self.last_ops = []\n\n def insert(self, ids, scores):\n \"\"\"Insert the ids and scores into the TopN.\"\"\"\n with ops.control_dependencies(self.last_ops):\n scatter_op = state_ops.scatter_update(self.id_to_score, ids, scores)\n larger_scores = math_ops.greater(scores, self.sl_scores[0])\n\n def shortlist_insert():\n larger_ids = array_ops.boolean_mask(\n math_ops.to_int64(ids), larger_scores)\n larger_score_values = array_ops.boolean_mask(scores, larger_scores)\n shortlist_ids, new_ids, new_scores = tensor_forest_ops.top_n_insert(\n self.sl_ids, self.sl_scores, larger_ids, larger_score_values)\n u1 = state_ops.scatter_update(self.sl_ids, shortlist_ids, new_ids)\n u2 = state_ops.scatter_update(self.sl_scores, shortlist_ids, new_scores)\n return control_flow_ops.group(u1, u2)\n\n # We only need to insert into the shortlist if there are any\n # scores larger than the threshold.\n cond_op = control_flow_ops.cond(\n math_ops.reduce_any(larger_scores), shortlist_insert,\n control_flow_ops.no_op)\n with ops.control_dependencies([cond_op]):\n self.last_ops = [scatter_op, cond_op]\n\n def remove(self, ids):\n \"\"\"Remove the ids (and their associated scores) from the TopN.\"\"\"\n with ops.control_dependencies(self.last_ops):\n scatter_op = state_ops.scatter_update(\n self.id_to_score,\n ids,\n array_ops.ones_like(\n ids, dtype=dtypes.float32) * dtypes.float32.min)\n # We assume that removed ids are almost always in the shortlist,\n # so it makes no sense to hide the Op behind a tf.cond\n shortlist_ids_to_remove, new_length = tensor_forest_ops.top_n_remove(\n self.sl_ids, ids)\n u1 = state_ops.scatter_update(\n self.sl_ids,\n array_ops.concat_v2([[0], shortlist_ids_to_remove], 0),\n array_ops.concat_v2(\n [new_length, array_ops.ones_like(shortlist_ids_to_remove) * -1],\n 0))\n u2 = state_ops.scatter_update(\n self.sl_scores,\n shortlist_ids_to_remove,\n dtypes.float32.min * array_ops.ones_like(\n shortlist_ids_to_remove, dtype=dtypes.float32))\n self.last_ops = [scatter_op, u1, u2]\n\n def get_best(self, n):\n \"\"\"Return the indices and values of the n highest scores in the TopN.\"\"\"\n\n def refresh_shortlist():\n \"\"\"Update the shortlist with the highest scores in id_to_score.\"\"\"\n new_scores, new_ids = nn_ops.top_k(self.id_to_score, self.shortlist_size)\n smallest_new_score = math_ops.reduce_min(new_scores)\n new_length = math_ops.reduce_sum(\n math_ops.to_int32(math_ops.greater(new_scores, dtypes.float32.min)))\n u1 = self.sl_ids.assign(\n math_ops.to_int64(array_ops.concat_v2([[new_length], new_ids], 0)))\n u2 = self.sl_scores.assign(\n array_ops.concat_v2([[smallest_new_score], new_scores], 0))\n self.last_ops = [u1, u2]\n return control_flow_ops.group(u1, u2)\n\n # We only need to refresh the shortlist if n is greater than the\n # current shortlist size (which is stored in sl_ids[0]).\n with ops.control_dependencies(self.last_ops):\n cond_op = control_flow_ops.cond(n > self.sl_ids[0], refresh_shortlist,\n control_flow_ops.no_op)\n with ops.control_dependencies([cond_op]):\n topk_values, topk_indices = nn_ops.top_k(\n self.sl_scores,\n math_ops.minimum(n, math_ops.to_int32(self.sl_ids[0])))\n # topk_indices are the indices into the shortlist, we want to return\n # the indices into id_to_score\n gathered_indices = array_ops.gather(self.sl_ids, topk_indices)\n return gathered_indices, topk_values\n\n def get_and_remove_best(self, n):\n # TODO(thomaswc): Replace this with a version of get_best where\n # refresh_shortlist grabs the top n + shortlist_size.\n top_ids, unused_top_vals = self.get_best(n)\n remove_op = self.remove(top_ids)\n return array_ops.identity(top_ids, control_inputs=remove_op)\n", "# Copyright 2016 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\"\"\"Regression test for DNNLinearCombinedEstimator.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport tempfile\nfrom tensorflow.contrib.layers.python.layers import feature_column\nfrom tensorflow.contrib.learn.python.learn.datasets import base\nfrom tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined\nfrom tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils\nfrom tensorflow.contrib.learn.python.learn.estimators import run_config\nfrom tensorflow.contrib.learn.python.learn.estimators import test_data\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import adagrad\nfrom tensorflow.python.training import ftrl\nfrom tensorflow.python.training import server_lib\n\nFLAGS = tf.flags.FLAGS\n\n# Desired training steps, reported in benchmark. Actual steps might be slightly\n# more than this since supervisor training runs for a non-detrministic number of\n# steps.\n_ITERS = 100\n\n_METRIC_KEYS = {\n 'accuracy',\n 'auc',\n 'accuracy/threshold_0.500000_mean',\n 'loss',\n 'precision/positive_threshold_0.500000_mean',\n 'recall/positive_threshold_0.500000_mean',\n}\n\n\nclass DNNLinearCombinedClassifierBenchmark(test.Benchmark):\n\n def _assertSingleClassMetrics(self, metrics):\n estimator_test_utils.assert_in_range(0.9, 1.0, 'auc', metrics)\n estimator_test_utils.assert_in_range(0.9, 1.0,\n 'accuracy/threshold_0.500000_mean',\n metrics)\n estimator_test_utils.assert_in_range(\n 0.9, 1.0, 'precision/positive_threshold_0.500000_mean', metrics)\n estimator_test_utils.assert_in_range(\n 0.9, 1.0, 'recall/positive_threshold_0.500000_mean', metrics)\n self._assertCommonMetrics(metrics)\n\n def _assertCommonMetrics(self, metrics):\n estimator_test_utils.assert_in_range(_ITERS, _ITERS + 5, 'global_step',\n metrics)\n estimator_test_utils.assert_in_range(0.9, 1.0, 'accuracy', metrics)\n estimator_test_utils.assert_in_range(0.0, 0.2, 'loss', metrics)\n self.report_benchmark(\n iters=metrics['global_step'],\n extras={k: v\n for k, v in metrics.items() if k in _METRIC_KEYS})\n\n def benchmarkMatrixData(self):\n iris = test_data.prepare_iris_data_for_logistic_regression()\n cont_feature = feature_column.real_valued_column('feature', dimension=4)\n bucketized_feature = feature_column.bucketized_column(\n cont_feature, test_data.get_quantile_based_buckets(iris.data, 10))\n\n classifier = dnn_linear_combined.DNNLinearCombinedClassifier(\n model_dir=tempfile.mkdtemp(),\n linear_feature_columns=(bucketized_feature,),\n dnn_feature_columns=(cont_feature,),\n dnn_hidden_units=(3, 3))\n\n input_fn = test_data.iris_input_logistic_fn\n metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate(\n input_fn=input_fn, steps=100)\n self._assertSingleClassMetrics(metrics)\n\n def benchmarkTensorData(self):\n\n def _input_fn():\n iris = test_data.prepare_iris_data_for_logistic_regression()\n features = {}\n for i in range(4):\n # The following shows how to provide the Tensor data for\n # RealValuedColumns.\n features.update({\n str(i):\n array_ops.reshape(\n constant_op.constant(\n iris.data[:, i], dtype=dtypes.float32), (-1, 1))\n })\n # The following shows how to provide the SparseTensor data for\n # a SparseColumn.\n features['dummy_sparse_column'] = sparse_tensor.SparseTensor(\n values=('en', 'fr', 'zh'),\n indices=((0, 0), (0, 1), (60, 0)),\n dense_shape=(len(iris.target), 2))\n labels = array_ops.reshape(\n constant_op.constant(\n iris.target, dtype=dtypes.int32), (-1, 1))\n return features, labels\n\n iris = test_data.prepare_iris_data_for_logistic_regression()\n cont_features = [\n feature_column.real_valued_column(str(i)) for i in range(4)\n ]\n linear_features = [\n feature_column.bucketized_column(\n cont_features[i],\n test_data.get_quantile_based_buckets(iris.data[:, i], 10))\n for i in range(4)\n ]\n linear_features.append(\n feature_column.sparse_column_with_hash_bucket(\n 'dummy_sparse_column', hash_bucket_size=100))\n\n classifier = dnn_linear_combined.DNNLinearCombinedClassifier(\n model_dir=tempfile.mkdtemp(),\n linear_feature_columns=linear_features,\n dnn_feature_columns=cont_features,\n dnn_hidden_units=(3, 3))\n\n metrics = classifier.fit(input_fn=_input_fn, steps=_ITERS).evaluate(\n input_fn=_input_fn, steps=100)\n self._assertSingleClassMetrics(metrics)\n\n def benchmarkCustomOptimizer(self):\n iris = test_data.prepare_iris_data_for_logistic_regression()\n cont_feature = feature_column.real_valued_column('feature', dimension=4)\n bucketized_feature = feature_column.bucketized_column(\n cont_feature, test_data.get_quantile_based_buckets(iris.data, 10))\n\n classifier = dnn_linear_combined.DNNLinearCombinedClassifier(\n model_dir=tempfile.mkdtemp(),\n linear_feature_columns=(bucketized_feature,),\n linear_optimizer=ftrl.FtrlOptimizer(learning_rate=0.1),\n dnn_feature_columns=(cont_feature,),\n dnn_hidden_units=(3, 3),\n dnn_optimizer=adagrad.AdagradOptimizer(learning_rate=0.1))\n\n input_fn = test_data.iris_input_logistic_fn\n metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate(\n input_fn=input_fn, steps=100)\n self._assertSingleClassMetrics(metrics)\n\n def benchmarkMultiClass(self):\n iris = base.load_iris()\n cont_feature = feature_column.real_valued_column('feature', dimension=4)\n bucketized_feature = feature_column.bucketized_column(\n cont_feature, test_data.get_quantile_based_buckets(iris.data, 10))\n\n classifier = dnn_linear_combined.DNNLinearCombinedClassifier(\n n_classes=3,\n linear_feature_columns=(bucketized_feature,),\n dnn_feature_columns=(cont_feature,),\n dnn_hidden_units=(3, 3))\n\n input_fn = test_data.iris_input_multiclass_fn\n metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate(\n input_fn=input_fn, steps=100)\n self._assertCommonMetrics(metrics)\n\n def benchmarkPartitionedVariables(self):\n\n def _input_fn():\n features = {\n 'language':\n sparse_tensor.SparseTensor(\n values=('en', 'fr', 'zh'),\n indices=((0, 0), (0, 1), (2, 0)),\n dense_shape=(3, 2))\n }\n labels = constant_op.constant(((1,), (0,), (0,)))\n return features, labels\n\n # The given hash_bucket_size results in variables larger than the\n # default min_slice_size attribute, so the variables are partitioned.\n sparse_feature = feature_column.sparse_column_with_hash_bucket(\n 'language', hash_bucket_size=2e7)\n embedding_feature = feature_column.embedding_column(\n sparse_feature, dimension=1)\n\n tf_config = {\n 'cluster': {\n run_config.TaskType.PS: ['fake_ps_0', 'fake_ps_1']\n }\n }\n with test.mock.patch.dict('os.environ',\n {'TF_CONFIG': json.dumps(tf_config)}):\n config = run_config.RunConfig()\n # Because we did not start a distributed cluster, we need to pass an\n # empty ClusterSpec, otherwise the device_setter will look for\n # distributed jobs, such as \"/job:ps\" which are not present.\n config._cluster_spec = server_lib.ClusterSpec({})\n\n classifier = dnn_linear_combined.DNNLinearCombinedClassifier(\n linear_feature_columns=(sparse_feature,),\n dnn_feature_columns=(embedding_feature,),\n dnn_hidden_units=(3, 3),\n config=config)\n\n metrics = classifier.fit(input_fn=_input_fn, steps=_ITERS).evaluate(\n input_fn=_input_fn, steps=100)\n self._assertCommonMetrics(metrics)\n\n\nif __name__ == '__main__':\n test.main()\n" ]
[ [ "tensorflow.python.util.all_util.remove_undocumented" ], [ "tensorflow.contrib.learn.python.learn.datasets.base.Datasets", "tensorflow.python.platform.gfile.Exists", "tensorflow.contrib.learn.python.learn.datasets.base.load_csv_without_header", "tensorflow.contrib.learn.python.learn.datasets.base.shrink_csv", "tensorflow.contrib.learn.python.learn.datasets.base.maybe_download" ], [ "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.ops.math_ops.to_int64", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.contrib.tensor_forest.python.ops.tensor_forest_ops.top_n_insert", "tensorflow.contrib.tensor_forest.python.ops.tensor_forest_ops.top_n_remove", "tensorflow.python.ops.math_ops.to_int32", "tensorflow.python.ops.math_ops.greater", "tensorflow.python.ops.nn_ops.top_k", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.ops.math_ops.reduce_min", "tensorflow.python.ops.math_ops.reduce_any", "tensorflow.python.ops.array_ops.boolean_mask", "tensorflow.python.ops.init_ops.constant_initializer", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.state_ops.scatter_update", "tensorflow.python.ops.control_flow_ops.cond", "tensorflow.python.ops.array_ops.concat_v2" ], [ "tensorflow.contrib.layers.python.layers.feature_column.embedding_column", "tensorflow.python.training.ftrl.FtrlOptimizer", "tensorflow.python.training.server_lib.ClusterSpec", "tensorflow.contrib.learn.python.learn.datasets.base.load_iris", "tensorflow.contrib.layers.python.layers.feature_column.sparse_column_with_hash_bucket", "tensorflow.python.training.adagrad.AdagradOptimizer", "tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.platform.test.main", "tensorflow.contrib.learn.python.learn.estimators.test_data.prepare_iris_data_for_logistic_regression", "tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range", "tensorflow.contrib.layers.python.layers.feature_column.real_valued_column", "tensorflow.contrib.learn.python.learn.estimators.test_data.get_quantile_based_buckets", "tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined.DNNLinearCombinedClassifier", "tensorflow.python.framework.constant_op.constant" ] ]
[ { "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" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
balbasty/nitorch
[ "d30c3125a8a66ea1434f2b39ed03338afd9724b4", "d30c3125a8a66ea1434f2b39ed03338afd9724b4", "d30c3125a8a66ea1434f2b39ed03338afd9724b4", "d30c3125a8a66ea1434f2b39ed03338afd9724b4" ]
[ "nitorch/tools/img_statistics.py", "nitorch/nn/experimental/_fancyvxm.py", "nitorch/nn/modules/norm.py", "nitorch/nn/modules/hyper.py" ]
[ "\"\"\"Functions simillar of inspired by the SPM package:\n\n\"\"\"\n\nimport nibabel as nib\nimport torch\nimport math\nfrom nitorch.core.kernels import smooth\nfrom nitorch.vb.mixtures import GMM\nfrom nitorch.vb.mixtures import RMM\nfrom nitorch.spatial import im_gradient\nfrom nitorch.core.constants import inf\nfrom nitorch.plot import show_slices\nfrom nitorch import io\nfrom nitorch.core.dtypes import dtype as dtype_info\n\n\ndef estimate_fwhm(dat, vx=None, verbose=0, mn=-inf, mx=inf):\n \"\"\"Estimates full width at half maximum (FWHM) and noise standard\n deviation (sd) of a 2D or 3D image.\n\n It is assumed that the image has been generated as:\n dat = Ky + n,\n where K is Gaussian smoothing with some FWHM and n is\n additive Gaussian noise. FWHM and n are estimated.\n\n Args:\n dat (torch.tensor): Image data (X, Y) | (X, Y, Z).\n vx (float, optional): Voxel size. Defaults to (1, 1, 1).\n verbose (int, optional): Verbosity level (0|1|2):\n 0: No verbosity\n 1: Print FWHM and sd to screen\n 2: 1 + show mask\n Defaults to 0.\n mn (float, optional): Exclude values in dat below mn, default=-inf.\n mx (float, optional): Exclude values in dat above mx, default=-inf.\n\n Returns:\n fwhm (torch.tensor): Estimated FWHM (2,) | (3,).\n sd (torch.tensor): Estimated noise standard deviation.\n\n Reference:\n Appendix A of:\n Groves AR, Beckmann CF, Smith SM, Woolrich MW.\n Linked independent component analysis for multimodal data fusion.\n Neuroimage. 2011 Feb 1;54(3):2198-217.\n\n \"\"\"\n if vx is None:\n vx = (1.0,) * 3\n # Parameters\n device = dat.device\n dtype = dat.dtype\n logtwo = torch.tensor(2.0, device=device, dtype=dtype).log()\n one = torch.tensor(1.0, device=device, dtype=dtype)\n ndim = len(dat.shape)\n # Make mask\n msk = (dat > mn) & (dat <= mx)\n if verbose >= 2:\n show_slices(msk)\n # Compute image gradient\n g = im_gradient(dat, which='central', vx=vx, bound='circular')\n g[~msk.repeat((ndim, 1, 1, 1))] = 0\n g = g.abs()\n if ndim == 3:\n g = g.sum(dim=3, dtype=torch.float64)\n g = g.sum(dim=2, dtype=torch.float64).sum(dim=1, dtype=torch.float64)\n # Make dat have zero mean\n x0 = dat[msk] - dat[msk].mean()\n # Compute FWHM\n fwhm = torch.sqrt(4.0 * logtwo) * torch.sum(x0.abs(), dtype=torch.float64)\n fwhm = fwhm / g\n if verbose >= 1:\n print('FWHM={}'.format(fwhm))\n # Compute noise standard deviation\n sx = smooth('gauss', fwhm[0], x=0, dtype=dtype, device=device)[0][0, 0, 0]\n sy = smooth('gauss', fwhm[1], x=0, dtype=dtype, device=device)[0][0, 0, 0]\n sz = 1.0\n if ndim == 3:\n sz = smooth('gauss', fwhm[2], x=0, dtype=dtype, device=device)[0][0, 0, 0]\n sc = (sx * sy * sz) / ndim\n sc = torch.min(sc, one)\n sd = torch.sqrt(torch.sum(x0 ** 2, dtype=torch.float64) / (x0.numel() * sc))\n if verbose >= 1:\n print('sd={}'.format(sd))\n \n return fwhm, sd\n\n\ndef estimate_noise(dat, show_fit=False, fig_num=1, num_class=2,\n mu_noise=None, max_iter=10000, verbose=0,\n bins=1024):\n \"\"\"Estimate noise from a nifti image by fitting either a GMM or an RMM \n to the image's intensity histogram.\n\n Args:\n dat (str or tensor): Tensor or path to nifti file.\n show_fit (bool, optional): Defaults to False.\n fig_num (bool, optional): Defaults to 1.\n num_class (int, optional): Number of mixture classes (only for GMM).\n Defaults to 2.\n mu_noise (float, optional): Mean of noise class, defaults to None,\n in which case the class with the smallest sd is assumed the noise\n class.\n max_iter (int, optional) Maxmimum number of algorithm iterations.\n Defaults to 10000.\n verbose (int, optional) Display progress. Defaults to 0.\n 0: None.\n 1: Print summary when finished.\n 2: 1 + Log-likelihood plot.\n 3: 1 + 2 + print convergence.\n bins (int, optional): Number of histogram bins, default=1024.\n\n Returns:\n sd_noise (torch.Tensor): Standard deviation of background class.\n sd_not_noise (torch.Tensor): Standard deviation of foreground class.\n mu_noise (torch.Tensor): Mean of background class.\n mu_not_noise (torch.Tensor): Mean of foreground class.\n\n \"\"\"\n slope = None\n if isinstance(dat, str):\n dat = io.map(dat)\n if isinstance(dat, io.MappedArray):\n slope = dat.slope\n if not slope and not dtype_info(dat.dtype).if_floating_point:\n slope = 1\n dat = dat.fdata(rand=True)\n dat = torch.as_tensor(dat).flatten()\n if not slope and not dat.dtype.is_floating_point:\n slope = 1\n dat = dat.float()\n device = dat.device\n dat[~torch.isfinite(dat)] = 0\n dat = dat.double()\n\n # Mask and get min/max\n mn = dat.min().round()\n msk = (dat != 0)\n msk &= dat != dat.max()\n dat, msk = dat[msk], None\n mx = torch.max(dat).round()\n if slope:\n # ensure bin width aligns with integer width\n width = (mx - mn) / bins\n width = (width / slope).ceil() * slope\n mx = mn + bins * width\n\n # Histogram bin data\n W, dat = torch.histc(dat, bins=bins, min=mn, max=mx).double(), None\n x = torch.linspace(mn, mx, steps=bins, device=device).double()\n\n # fit mixture model\n if mn < 0: # Make GMM model\n model = GMM(num_class=num_class)\n else: # Make RMM model\n model = RMM(num_class=num_class)\n\n # Fit GMM using Numpy\n model.fit(x, W=W, verbose=verbose, max_iter=max_iter, show_fit=show_fit, fig_num=fig_num)\n\n # Get means and mixing proportions\n mu, _ = model.get_means_variances()\n mu = mu.squeeze()\n mp = model.mp\n if mn < 0: # GMM\n sd = torch.sqrt(model.Cov).squeeze()\n else: # RMM\n sd = model.sig\n\n # Get std and mean of noise class\n if mu_noise:\n # Closest to mu_bg\n _, ix_noise = torch.min(torch.abs(mu - mu_noise), dim=0)\n mu_noise = mu[ix_noise]\n sd_noise = sd[ix_noise]\n else:\n # With smallest sd\n sd_noise, ix_noise = torch.min(sd, dim=0)\n mu_noise = mu[ix_noise]\n # Get std and mean of other classes (means and sds weighted by mps)\n rng = torch.arange(0, num_class, device=device)\n rng = torch.cat([rng[0:ix_noise], rng[ix_noise + 1:]])\n mu1 = mu[rng]\n sd1 = sd[rng]\n w = mp[rng]\n w = w / torch.sum(w)\n mu_not_noise = sum(w * mu1)\n sd_not_noise = sum(w * sd1)\n\n return sd_noise, sd_not_noise, mu_noise, mu_not_noise\n", "import torch\nimport torch.nn as tnn\nfrom nitorch.nn.base import Module\nfrom ..modules.cnn import UNet\nfrom ..modules.spatial import GridPull, GridPush, GridExp\nfrom ..modules.registration import VoxelMorph\nfrom nitorch import spatial\nfrom nitorch.core.utils import expand\nfrom nitorch.core.py import make_list\n\n\nclass VoxelMorphSymmetric(Module):\n \"\"\"VoxelMorph network with a symmetric loss.\n\n Contrary to what's done in voxelmorph, I predict a midpoint image\n and warp it to both native spaces.\n\n NOTE:\n It doesn't seem to work very well for pairs of images. There's\n just two much of each in the midpoint, and the deformation\n just tries to squeeze values it doesn't want out.\n \"\"\"\n\n def __init__(self, dim, encoder=None, decoder=None, kernel_size=3,\n interpolation='linear', grid_bound='dft', image_bound='dct2'):\n super().__init__()\n self.unet = UNet(dim,\n input_channels=2,\n output_channels=dim+1,\n encoder=encoder,\n decoder=decoder,\n kernel_size=kernel_size,\n activation=tnn.LeakyReLU(0.2))\n self.exp = GridExp(fwd=True, inv=True,\n interpolation=interpolation,\n bound=grid_bound)\n self.pull = GridPull(interpolation=interpolation,\n bound=image_bound)\n self.dim = dim\n\n def forward(self, source, target):\n # checks\n if len(source.shape) != self.dim+2:\n raise ValueError('Expected `source` to have shape (B, C, *spatial) '\n 'with len(spatial) == {} but found {}.'\n .format(self.dim, source.shape))\n if len(target.shape) != self.dim+2:\n raise ValueError('Expected `target` to have shape (B, C, *spatial) '\n 'with len(spatial) == {} but found {}.'\n .format(self.dim, target.shape))\n if not (target.shape[0] == source.shape[0] or\n target.shape[0] == 1 or source.shape[0] == 1):\n raise ValueError('Batch dimensions of `source` and `target` are '\n 'not compatible: got {} and {}'\n .format(source.shape[0], target.shape[0]))\n if target.shape[2:] != source.shape[2:]:\n raise ValueError('Spatial dimensions of `source` and `target` are '\n 'not compatible: got {} and {}'\n .format(source.shape[2:], target.shape[2:]))\n\n # chain operations\n source_and_target = torch.cat((source, target), dim=1)\n velocity_and_template = self.unet(source_and_target)\n template = velocity_and_template[:, -1:, ...]\n velocity = velocity_and_template[:, :-1, ...]\n velocity = spatial.channel2grid(velocity)\n grid, igrid = self.exp(velocity)\n deformed_to_source = self.pull(template, grid)\n deformed_to_target = self.pull(template, igrid)\n\n return deformed_to_source, deformed_to_target, velocity, template\n\n\nclass VoxelMorphPlus(Module):\n \"\"\"A VoxelMorph network augmented with a morphing field.\n \"\"\"\n\n def __init__(self, dim, encoder=None, decoder=None, kernel_size=3,\n interpolation='linear', grid_bound='dft', image_bound='dct2'):\n super().__init__()\n self.unet = UNet(dim,\n input_channels=2,\n output_channels=dim+1,\n encoder=encoder,\n decoder=decoder,\n kernel_size=kernel_size,\n activation=tnn.LeakyReLU(0.2))\n self.exp = GridExp(interpolation=interpolation,\n bound=grid_bound)\n self.pull = GridPull(interpolation=interpolation,\n bound=image_bound)\n self.dim = dim\n\n def forward(self, source, target):\n # checks\n if len(source.shape) != self.dim+2:\n raise ValueError('Expected `source` to have shape (B, C, *spatial)'\n ' with len(spatial) == {} but found {}.'\n .format(self.dim, source.shape))\n if len(target.shape) != self.dim+2:\n raise ValueError('Expected `target` to have shape (B, C, *spatial)'\n ' with len(spatial) == {} but found {}.'\n .format(self.dim, target.shape))\n if not (target.shape[0] == source.shape[0] or\n target.shape[0] == 1 or source.shape[0] == 1):\n raise ValueError('Batch dimensions of `source` and `target` are '\n 'not compatible: got {} and {}'\n .format(source.shape[0], target.shape[0]))\n if target.shape[2:] != source.shape[2:]:\n raise ValueError('Spatial dimensions of `source` and `target` are '\n 'not compatible: got {} and {}'\n .format(source.shape[2:], target.shape[2:]))\n\n # chain operations\n source_and_target = torch.cat((source, target), dim=1)\n velocity_and_morph = self.unet(source_and_target)\n morph = velocity_and_morph[:, -1:, ...]\n velocity = velocity_and_morph[:, :-1, ...]\n velocity = spatial.channel2grid(velocity)\n grid = self.exp(velocity)\n deformed_source = self.pull(source+morph, grid)\n\n return deformed_source, velocity, morph\n\n\nclass DiffeoMovie(Module):\n \"\"\"Compute the deformation at intermediate time steps.\n\n The output tensor has time steps in the channel dimension, which\n can be used as frames in an animation.\n \"\"\"\n\n def __init__(self, nb_frames=100, interpolation='linear',\n grid_bound='dft', image_bound='dct2'):\n\n super().__init__()\n self.nb_frames = nb_frames\n self.exp = GridExp(interpolation=interpolation,\n bound=grid_bound)\n self.pull = GridPull(interpolation=interpolation,\n bound=image_bound)\n\n def forward(self, image, velocity):\n\n if image.shape[1] != 1:\n raise ValueError('DiffeoMovie only accepts single channel '\n 'images (for now).')\n scale = torch.linspace(0, 1, self.nb_frames)\n frames = []\n for s in scale:\n grid = self.exp(velocity * s)\n frames.append(self.pull(image, grid))\n frames = torch.cat(frames, dim=1)\n\n return frames\n\n\nclass IterativeVoxelMorph(VoxelMorph):\n \"\"\"VoxelMorph warps a source/moving image to a fixed/target image.\n\n This network aims to bridge the gap between UNets and iterative\n optimization methods. The network is 'residual' (it predicts the\n difference between the previous velocity estimate and the optimal\n one), 'recurrent' (there is a core voxelmorph network that is\n applied iteratively) and 'adjoint' (since a spatial transformer T is\n applied after the UNet, its adjoint T' is applied before)\n \"\"\"\n\n def __init__(self, dim, max_iter=None, residual=True, feed=None,\n *args, **kwargs):\n \"\"\"\n\n Parameters\n ----------\n dim : int\n Dimensionality of the input (1|2|3)\n max_iter : int or [int, int], default=[1, 20]\n Number of iterations of the recurrent network.\n If list, max_iter is randomly sampled in the corresponding\n range at each minibatch.\n encoder : list[int], optional\n Number of channels after each encoding layer of the UNet.\n decoder : list[int], optional\n Number of channels after each decoding layer of the Unet.\n kernel_size : int or list[int], default=3\n Kernel size of the UNet.\n interpolation : int, default=1\n Interpolation order.\n grid_bound : bound_type, default='dft'\n Boundary conditions of the velocity field.\n image_bound : bound_type, default='dct2'\n Boundary conditions of the image.\n \"\"\"\n if feed is None:\n # possible feeds\n # target, push(target), source, push(pull(source)),\n # push(ones), push(pull(ones)), velocity\n feed = ['push(target)', 'source', 'velocity']\n input_channels = sum(dim if f == 'velocity' else 1 for f in feed)\n super().__init__(dim, *args, **kwargs, _input_channels=input_channels)\n self.feed = feed\n self.residual = residual\n self.push = GridPush(interpolation=self.pull.interpolation,\n bound=self.pull.bound)\n if max_iter is None:\n max_iter = [1, 20]\n if isinstance(max_iter, range):\n inf = max_iter.start if max_iter.start else 1\n sup = max_iter.stop if max_iter.stop else max(1, inf)\n max_iter = [inf, sup]\n max_iter = make_list(max_iter, 2)\n if max_iter[0] == max_iter[1]:\n max_iter = max_iter[0]\n self.max_iter = max_iter\n\n def forward(self, source, target, *, _loss=None, _metric=None):\n \"\"\"\n\n Parameters\n ----------\n source : tensor (batch, channel, *spatial)\n Source/moving image\n target : tensor (batch, channel, *spatial)\n Target/fixed image\n\n _loss : dict, optional\n If provided, all registered losses are computed and appended.\n _metric : dict, optional\n If provided, all registered metrics are computed and appended.\n\n Returns\n -------\n deformed_source : tensor (batch, channel, *spatial)\n Deformed source image\n velocity : tensor (batch,, *spatial, len(spatial))\n Velocity field\n\n \"\"\"\n lm = {'_loss': _loss, '_metric': _metric}\n\n # checks\n if len(source.shape) != self.dim+2:\n raise ValueError('Expected `source` to have shape (B, C, *spatial)'\n ' with len(spatial) == {} but found {}.'\n .format(self.dim, source.shape))\n if len(target.shape) != self.dim+2:\n raise ValueError('Expected `target` to have shape (B, C, *spatial)'\n ' with len(spatial) == {} but found {}.'\n .format(self.dim, target.shape))\n if not (target.shape[0] == source.shape[0] or\n target.shape[0] == 1 or source.shape[0] == 1):\n raise ValueError('Batch dimensions of `source` and `target` are '\n 'not compatible: got {} and {}'\n .format(source.shape[0], target.shape[0]))\n if target.shape[2:] != source.shape[2:]:\n raise ValueError('Spatial dimensions of `source` and `target` are '\n 'not compatible: got {} and {}'\n .format(source.shape[2:], target.shape[2:]))\n\n # parameters\n batch = source.shape[0]\n channels = source.shape[1]\n shape = source.shape[2:]\n dtype = source.dtype\n device = source.device\n max_iter = self.max_iter\n if isinstance(max_iter, list):\n # random number of iterations\n max_iter = torch.randint(max_iter[0], max_iter[1], [],\n dtype=torch.long,\n device=torch.device('cpu')).item()\n\n # initialize\n ones = torch.ones((1, 1, *shape), dtype=dtype, device=device)\n velocity = torch.zeros((), dtype=dtype, device=device)\n grid = spatial.identity_grid(shape, dtype=dtype, device=device)\n grid = grid[None, ...]\n\n # chain operations\n for n_iter in range(max_iter):\n # broadcast velocity just in case\n velocity = expand(velocity, [batch, *shape, self.dim])\n\n # concatenate inputs to the UNet\n input_unet = []\n for f in self.feed:\n if f == 'source':\n input_unet += [source]\n elif f == 'pull(source)':\n input_unet += [self.pull(source, grid)]\n elif f == 'push(pull(source))':\n input_unet += [self.push(self.pull(source, grid), grid)]\n elif f == 'target':\n input_unet += [target]\n elif f == 'push(target)':\n input_unet += [self.push(target, grid)]\n elif f == 'push(pull(ones))':\n c = self.push(self.pull(ones, grid), grid)\n c = expand(c, [batch, 1, *shape])\n input_unet += [c]\n elif f == 'push(ones)':\n c = self.push(ones, grid)\n c = expand(c, [batch, 1, *shape])\n input_unet += [c]\n elif f == 'velocity':\n input_unet += [spatial.grid2channel(velocity)]\n else:\n raise ValueError('Unknown feed tensor {}'.format(f))\n input_unet = torch.cat(input_unet, dim=1)\n\n # increment velocity\n increment = self.unet(input_unet, **lm)\n increment = spatial.channel2grid(increment)\n if self.residual:\n velocity = velocity + increment\n else:\n velocity = increment\n velocity_small = self.resize(velocity)\n grid = self.exp(velocity_small)\n grid = self.resize(grid, shape=target.shape[2:])\n deformed_source = self.pull(source, grid)\n\n # compute loss and metrics\n self.compute(_loss, _metric,\n image=[deformed_source, target],\n velocity=[velocity])\n\n return deformed_source, velocity\n", "\"\"\"Batch norm layer\"\"\"\nimport torch\nfrom torch import nn as tnn\nfrom nitorch.nn.base import Module, nitorchmodule\n\n\nclass BatchNorm(Module):\n \"\"\"Batch normalization layer.\n\n BatchNorm computes statistics across [batch, *spatial].\n \"\"\"\n def __init__(self, dim, nb_channels, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n dim : {1, 2, 3}\n Spatial dimension\n nb_channels : int\n Number of channels in the input image\n eps : float, default=1e-5\n A value added to the denominator for numerical stability\n momentum : float, default=0.1\n The value used for the running_mean and running_var computation.\n Can be set to ``None`` for cumulative moving average\n (i.e. simple average).\n affine : bool, default=True\n When ``True``, this module has learnable affine parameters.\n track_running_stats : bool, default=True\n If``True``, track the running mean and variance.\n If ``False``, do not track such statistics and use batch\n statistics instead in both training and eval modes if the\n running mean and variance are ``None``\n\n \"\"\"\n super().__init__()\n\n # Store dimension\n self.dim = dim\n\n # Select Layer\n if dim == 1:\n self.norm = nitorchmodule(tnn.BatchNorm1d)(nb_channels, *args, **kwargs)\n elif dim == 2:\n self.norm = nitorchmodule(tnn.BatchNorm2d)(nb_channels, *args, **kwargs)\n elif dim == 3:\n self.norm = nitorchmodule(tnn.BatchNorm3d)(nb_channels, *args, **kwargs)\n else:\n NotImplementedError('BatchNorm is only implemented in 1, 2, or 3D.')\n\n def forward(self, x):\n \"\"\"Forward pass.\n\n Parameters\n ----------\n x : (batch, channel, *spatial) tensor\n Input tensor\n\n Returns\n -------\n x : (batch, channel, *spatial) tensor\n Normalized tensor\n\n \"\"\"\n return self.norm(x)\n\n in_channels = property(lambda self: self.norm.num_features)\n out_channels = property(lambda self: self.norm.num_features)\n\n @staticmethod\n def shape(x):\n if torch.is_tensor(x):\n return tuple(x.shape)\n return tuple(x)\n\n def __str__(self):\n s = [f'{self.norm.num_features}']\n if self.norm.eps != 1e-5:\n s += [f'eps={self.norm.eps}']\n if self.norm.momentum != 0.1:\n s += [f'momentum={self.norm.momentum}']\n if not self.norm.affine:\n s += [f'affine=False']\n if not self.norm.track_running_stats:\n s += [f'track_running_stats=False']\n s = ', '.join(s)\n return f'BatchNorm({s})'\n \n __repr__ = __str__\n\n\nclass InstanceNorm(Module):\n \"\"\"Instance normalization layer.\n\n InstanceNorm computes statistics across [*spatial].\n \"\"\"\n\n def __init__(self, dim, nb_channels, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n dim : {1, 2, 3}\n Spatial dimension\n nb_channels : int\n Number of channels in the input image\n eps : float, default=1e-5\n A value added to the denominator for numerical stability\n momentum : float, default=0.1\n The value used for the running_mean and running_var computation.\n Can be set to ``None`` for cumulative moving average\n (i.e. simple average).\n affine : bool, default=True\n When ``True``, this module has learnable affine parameters.\n track_running_stats : bool, default=True\n If``True``, track the running mean and variance.\n If ``False``, do not track such statistics and use batch\n statistics instead in both training and eval modes if the\n running mean and variance are ``None``\n\n \"\"\"\n super().__init__()\n\n # Store dimension\n self.dim = dim\n\n # Select Layer\n if dim == 1:\n self.norm = nitorchmodule(tnn.InstanceNorm1d)(nb_channels, *args, **kwargs)\n elif dim == 2:\n self.norm = nitorchmodule(tnn.InstanceNorm2d)(nb_channels, *args, **kwargs)\n elif dim == 3:\n self.norm = nitorchmodule(tnn.InstanceNorm3d)(nb_channels, *args, **kwargs)\n else:\n NotImplementedError('InstanceNorm is only implemented in 1, 2, or 3D.')\n\n def forward(self, x):\n \"\"\"Forward pass.\n\n Parameters\n ----------\n x : (batch, channel, *spatial) tensor\n Input tensor\n\n Returns\n -------\n x : (batch, channel, *spatial) tensor\n Normalized tensor\n\n \"\"\"\n return self.norm(x)\n\n in_channels = property(lambda self: self.norm.num_features)\n out_channels = property(lambda self: self.norm.num_features)\n\n @staticmethod\n def shape(x):\n if torch.is_tensor(x):\n return tuple(x.shape)\n return tuple(x)\n\n def __str__(self):\n s = [f'{self.norm.num_features}']\n if self.norm.eps != 1e-5:\n s += [f'eps={self.norm.eps}']\n if self.norm.momentum != 0.1:\n s += [f'momentum={self.norm.momentum}']\n if not self.norm.affine:\n s += [f'affine=False']\n if not self.norm.track_running_stats:\n s += [f'track_running_stats=False']\n s = ', '.join(s)\n return f'InstanceNorm({s})'\n\n __repr__ = __str__\n\n\nclass GroupNorm(Module):\n \"\"\"Group normalization layer.\n\n GroupNorm computes statistics across [channels//groups, *spatial].\n\n .. `groups=nb_channels` is equivalent to InstanceNorm\n .. `groups=1` is equivalent to (a certain type of) LayerNorm\n \"\"\"\n\n def __init__(self, dim, nb_channels, groups, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n dim : {1, 2, 3}\n Spatial dimension\n nb_channels : int\n Number of channels in the input image\n groups : int\n Number of groups to separate the channels into\n eps : float, default=1e-5\n A value added to the denominator for numerical stability\n affine : bool, default=True\n When ``True``, this module has learnable affine parameters.\n\n \"\"\"\n # Note that `dim` is not used, but we keep it for consistency\n # with [Batch,Instance]Norm.\n super().__init__()\n\n # Store dimension\n self.dim = dim\n self.norm = nitorchmodule(tnn.GroupNorm(groups, nb_channels, *args, **kwargs))\n\n def forward(self, x):\n \"\"\"Forward pass.\n\n Parameters\n ----------\n x : (batch, channel, *spatial) tensor\n Input tensor\n\n Returns\n -------\n x : (batch, channel, *spatial) tensor\n Normalized tensor\n\n \"\"\"\n return self.norm(x)\n\n in_channels = property(lambda self: self.norm.num_features)\n out_channels = property(lambda self: self.norm.num_features)\n\n @staticmethod\n def shape(x):\n if torch.is_tensor(x):\n return tuple(x.shape)\n return tuple(x)\n\n def __str__(self):\n s = [f'{self.norm.num_features}//{self.norm.groups}']\n if self.norm.eps != 1e-5:\n s += [f'eps={self.norm.eps}']\n if not self.norm.affine:\n s += [f'affine=False']\n s = ', '.join(s)\n return f'GroupNorm({s})'\n\n __repr__ = __str__\n\n\nclass LayerNorm(GroupNorm):\n \"\"\"Layer normalization layer.\n\n LayerNorm computes statistics across [channels, *spatial].\n\n This layer targets computed vision tasks and is less versatile than\n PyTorch's LayerNorm class. We actually use `GroupNorm` to implement it.\n \"\"\"\n\n def __init__(self, dim, nb_channels, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n dim : {1, 2, 3}\n Spatial dimension\n nb_channels : int\n Number of channels in the input image\n eps : float, default=1e-5\n A value added to the denominator for numerical stability\n affine : bool, default=True\n When ``True``, this module has learnable affine parameters.\n\n \"\"\"\n super().__init__(dim, nb_channels, nb_channels, *args, **kwargs)\n\n def __str__(self):\n s = []\n if self.batchnorm.eps != 1e-5:\n s += [f'eps={self.norm.eps}']\n if not self.norm.affine:\n s += [f'affine=False']\n s = ', '.join(s)\n return f'LayerNorm({s})'\n\n __repr__ = __str__\n\n\ndef norm_from_name(name):\n \"\"\"Return a normalization Class from its name.\n\n Parameters\n ----------\n name : str\n Normalization name. Registered functions are:\n - 'batch' : BatchNorm == Normalize across [batch, *spatial]\n - 'instance' : InstanceNorm == Normalize across [*spatial]\n - 'layer' : LayerNorm == Normalize across [channel, *spatial]\n - 'group' : GroupNorm == Normalize across [channel//groups, *spatial]\n\n Returns\n -------\n Norm : type(Module)\n A normalization class\n\n \"\"\"\n name = name.lower()\n if name == 'batch':\n return BatchNorm\n if name == 'instance':\n return InstanceNorm\n if name == 'layer':\n return LayerNorm\n if name == 'group':\n return GroupNorm\n raise KeyError(f'Normalization {name} is not registered.')\n\n\ndef make_norm_from_name(name, dim, nb_channels, *args, **kwargs):\n \"\"\"Return an instantiated normalization from its name.\n\n Parameters\n ----------\n name : str or int\n Normalization name. Registered functions are:\n - 'batch' : BatchNorm == Normalize across [batch, *spatial]\n - 'instance' : InstanceNorm == Normalize across [*spatial]\n - 'layer' : LayerNorm == Normalize across [channel, *spatial]\n - int : GroupNorm == Normalize across [channel//groups, *spatial]\n dim : int\n Number of spatial dimensions\n nb_channels : int\n Number of input channels\n eps : float, default=1e-5\n A value added to the denominator for numerical stability\n affine : bool, default=True\n When ``True``, this module has learnable affine parameters.\n\n\n Returns\n -------\n activation : Module\n An instantiated activation module\n\n \"\"\"\n groups = 0\n if isinstance(name, int):\n groups = name\n name = 'group'\n klass = norm_from_name(name)\n if groups:\n return klass(dim, nb_channels, groups, *args, **kwargs)\n return klass(dim, nb_channels, *args, **kwargs)\n", "\"\"\"Utilities to build hyper-networks\"\"\"\nfrom typing import Sequence, Optional\nimport inspect\nimport copy\nimport torch\nimport torch.nn as tnn\nfrom nitorch.core import py\nfrom ..base import Module\nfrom .conv import ActivationLike\nfrom ..activations import make_activation_from_name\n\n\nclass HyperNet(Module):\n \"\"\"\n Generic hypernetwork.\n\n An hyper-network is a network whose weights are generated dynamically\n by a meta-network from a set of input features.\n\n Its forward pass is: HyperNet(x, feat) = SubNet(MetaNet(feat))(x)\n \"\"\"\n\n # TODO: we maybe want to make it easier for people to build\n # specializations of this class where not all weights are\n # instantiated by the hyper network, but are trainable instead.\n # We could define a filter function that selects which submodules\n # of the main network have hyper-weights. Or have a `parameters`\n # argument (like in optimizers) that let the user specify\n # which parameters are dynamic.\n\n def __init__(self,\n in_features: int,\n network: Module,\n nodes: Optional[Sequence[str or Module]] = None,\n layers: Sequence[int] = (128,)*6,\n activation: ActivationLike = 'relu',\n final_activation: ActivationLike = None,\n ):\n \"\"\"\n\n Parameters\n ----------\n in_features : int\n Number of input meta-features.\n network : Module\n Instantiated sub network, whose weights are dynamically generated.\n This network *will* be modified in place.\n nodes : [sequence of] str or Module, optional\n Names or references of sub-modules, whose weights are\n hyper-generated. Names can include global patterns such as\n '*' or '**'.\n layers : sequence[int], default=(128,)*6\n Number of output channels after each layer of the hyper-network.\n activation : activation_like, default='relu'\n Activation after each layer of the hyper-network.\n final_activation : activation_like, default=None\n Final activation before the generated network weights.\n\n \"\"\"\n super().__init__()\n if nodes is not None and isinstance(nodes, (str, tnn.Module)):\n nodes = [nodes]\n self.nodes = set(nodes) if nodes is not None else None\n\n # make hypernetwork\n nb_weights = sum(w.numel() for w in self._get_weights(network))\n layers = [in_features, *layers]\n hyper = []\n for i in range(len(layers)-1):\n hyper.append(tnn.Linear(layers[i], layers[i+1]))\n a = self._make_activation(activation)\n if a:\n hyper.append(a)\n hyper.append(tnn.Linear(layers[-1], nb_weights))\n a = self._make_activation(final_activation)\n if a:\n hyper.append(a)\n self.hyper = tnn.Sequential(*hyper)\n\n # save main network\n self.network = network\n for param in self._get_weights(self.network):\n param.requires_grad_(False)\n\n @property\n def in_features(self):\n return self.hyper[0].in_features\n\n @classmethod\n def detach_(cls, network):\n \"\"\"Detach all weights of a generated network.\n\n Parameters\n ----------\n network : Module\n\n Returns\n -------\n network : Module\n\n \"\"\"\n for param in network.parameters():\n param.detach_()\n return network\n\n @classmethod\n def _make_activation(cls, activation):\n if not activation:\n return None\n if isinstance(activation, str):\n return make_activation_from_name(activation)\n return (activation() if inspect.isclass(activation)\n else activation if callable(activation)\n else None)\n\n def _make_chunks(self, x):\n \"\"\"Cut output of hypernetwork into weights with correct shape\"\"\"\n offset = 0\n all_shapes = [p.shape for p in self.network.parameters()]\n for shape in all_shapes:\n numel = py.prod(shape)\n w = x[offset:offset+numel].reshape(shape)\n offset += numel\n yield w\n\n def _prefix_in_nodes(self, prefix, nodes):\n \"\"\"Check if a module full-name is in the list of mutable nodes\"\"\"\n def _isequal(x, y):\n if x == y:\n return True\n elif y == '*':\n return True\n return False\n\n for node in nodes:\n if not isinstance(node, str):\n continue\n prefix = prefix.split('.')\n node = node.split('.')\n if '**' in node:\n node = (node[:node.index('**')]\n + ['*'] * max(0, len(prefix)-len(nodes))\n + node[node.index('**')+1:])\n if '**' in node:\n raise ValueError('There can be only one ** ellipsis in pattern')\n if len(node) != len(prefix):\n continue\n if all(_isequal(x, y) for x, y in zip(prefix, node)):\n return True\n return False\n\n def _get_weights(self, x, memo=None, nodes=None, prefix=''):\n \"\"\"Get all hyper-generated weights of the main module\n\n Parameters\n ----------\n x : Module\n Current module whose weights can be mutated.\n memo : set[Module]\n Sub-modules that have already been visited.\n nodes : set[str or Module]\n Set of nodes, whose parameters can be mutated.\n prefix : str\n Full name of the current module.\n\n Yields\n ------\n Parameter\n\n \"\"\"\n if memo is None:\n memo = set()\n if x in memo:\n return\n if nodes is None:\n if self.nodes is None:\n nodes = None\n else:\n nodes = set(self.nodes)\n\n if nodes is None or x in nodes or self._prefix_in_nodes(prefix, nodes):\n if nodes is not None:\n nodes = nodes.union(set(x.children()))\n for param in x.parameters(recurse=False):\n yield param\n\n memo.add(x)\n for name, module in x.named_children():\n subprefix = prefix + ('.' if prefix else '') + name\n for param in self._get_weights(module, memo, nodes, subprefix):\n yield param\n\n def _set_weights(self, x, w, memo=None, nodes=None, prefix=''):\n \"\"\"Sets the weights of the main module\n\n Parameters\n ----------\n x : Module\n Current module whose weights must be mutated.\n w : iterator[tensor]\n Iterator over new weights.\n memo : set[Module]\n Sub-modules that have already been visited.\n nodes : set[str or Module]\n Set of nodes, whose parameters must be mutated.\n prefix : str\n Full name of the current module.\n\n \"\"\"\n # It's a bit tricky to mutate the network weights without breaking the\n # computational graph. The current implementation is probably less\n # efficient than something where we define lots of Meta Modules,\n # but I think that this one is easier to play with (we can just pass\n # it any \"classic\" network)\n\n if memo is None:\n memo = set()\n if x in memo:\n return\n if nodes is None:\n if self.nodes is None:\n nodes = None\n else:\n nodes = set(self.nodes)\n\n if nodes is None or x in nodes or self._prefix_in_nodes(prefix, nodes):\n if nodes is not None:\n nodes = nodes.union(set(x.children()))\n param_names = [p[0] for p in x.named_parameters(recurse=False)]\n for name in param_names:\n w1 = next(w)\n old = getattr(x, name)\n delattr(x, name)\n new = tnn.Parameter(old.detach().clone(), requires_grad=False)\n setattr(x, name, new)\n getattr(x, name).copy_(w1)\n\n memo.add(x)\n for name, module in x.named_children():\n subprefix = prefix + ('.' if prefix else '') + name\n self._set_weights(module, w, memo, nodes, subprefix)\n\n def make_networks(self, feat, detach=False):\n \"\"\"Generate networks from features\n\n Parameters\n ----------\n feat : (batch, in_features) tensor\n Input features\n detach : bool, default=False\n Detach all weights in the returned gradients.\n\n Returns\n -------\n networks : list[Module]\n\n \"\"\"\n weights = self.hyper(feat)\n networks = []\n for batch_weights in weights:\n network = copy.deepcopy(self.network)\n self._set_weights(network, self._make_chunks(batch_weights))\n if detach:\n network = self.detach_(network)\n networks.append(network)\n return networks\n\n def forward(self, x, feat):\n \"\"\"\n\n Parameters\n ----------\n x : (batch, ...)\n Input of the main network\n feat : (batch, in_features) tensor\n Input to the hyper-network\n\n Returns\n -------\n y : (batch, ...) tensor\n Output of the main network\n\n \"\"\"\n # generate hyper weights\n weights = self.hyper(feat)\n\n if len(weights) == 1:\n self._set_weights(self.network, self._make_chunks(weights[0]))\n return self.network(x)\n\n # we have to loop over batches because network weights cannot have\n # a batch dimension\n output = []\n for batch_weights, batch_input in zip(weights, x):\n self._set_weights(self.network, self._make_chunks(batch_weights))\n output.append(self.network(batch_input[None]))\n output = torch.cat(output)\n return output\n" ]
[ [ "torch.abs", "torch.linspace", "torch.max", "torch.histc", "torch.cat", "torch.sqrt", "torch.min", "torch.sum", "torch.tensor", "torch.isfinite", "torch.arange", "torch.as_tensor" ], [ "torch.linspace", "torch.ones", "torch.zeros", "torch.cat", "torch.nn.LeakyReLU", "torch.device" ], [ "torch.nn.GroupNorm", "torch.is_tensor" ], [ "torch.nn.Linear", "torch.nn.Sequential", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DouCir/mmdetection
[ "44613202c379d85315ed47ca670fd9853f90c3a5" ]
[ "mmdet/datasets/custom_datasets/coder_single_dataset.py" ]
[ "from ..custom import CustomDataset\nimport os.path as osp\n\nimport mmcv\nimport numpy as np\nfrom ..utils import to_tensor, random_scale\nfrom ..transforms import ImageTransform\nimport cv2\n\n\nclass CoderSingleDataset(CustomDataset):\n def __init__(self,\n ann_file,\n img_prefix,\n img_scale,\n img_norm_cfg,\n img_norm_cfg_t,\n size_divisor=None,\n proposal_file=None,\n num_max_proposals=1000,\n flip_ratio=0,\n with_mask=False,\n with_crowd=True,\n with_label=True,\n test_mode=False):\n self.img_norm_cfg_t = img_norm_cfg_t\n # transforms\n self.img_transform_t = ImageTransform(\n size_divisor=size_divisor, **self.img_norm_cfg_t)\n super(CoderSingleDataset, self).__init__(\n ann_file=ann_file,\n img_prefix=img_prefix,\n img_scale=img_scale,\n img_norm_cfg=img_norm_cfg,\n size_divisor=size_divisor,\n proposal_file=proposal_file,\n num_max_proposals=num_max_proposals,\n flip_ratio=flip_ratio,\n with_mask=with_mask,\n with_crowd=with_crowd,\n with_label=with_label,\n test_mode=test_mode)\n\n def prepare_train_img(self, idx):\n img_info = self.img_infos[idx]\n flag = img_info['flag']\n # load image(rgb)\n img_temp = mmcv.imread(osp.join(self.img_prefix, img_info['filename']))\n if img_temp.shape[2] == 1:\n img = np.zeros((img_temp.shape[0], img_temp.shape[1], 3))\n img[:, :, 0] = img_temp\n img[:, :, 1] = img_temp\n img[:, :, 2] = img_temp\n else:\n img = img_temp\n # load image(thermal)\n img_t_path = osp.join(self.img_prefix, img_info['filename']).replace('visible', 'lwir')\n img_t = cv2.imread(img_t_path) # three channels,??? img_t[:,:,0]==img_t[:,:,2]!= img_t[:,:,1]\n img_t[:, :, 1] = img_t[:, :, 0]\n if img_t[0].max() > 140:\n a = 10\n # apply transforms\n flip = True if np.random.rand() < self.flip_ratio else False\n img_scale = random_scale(self.img_scales) # sample a scale\n img, img_shape, pad_shape, scale_factor = self.img_transform(\n img, img_scale, flip)\n img_t, img_shape_t, pad_shape_t, scale_factor_t = self.img_transform_t(\n img_t, img_scale, flip)\n\n data = dict(\n img_rgb_out=to_tensor(img),\n img_thermal_out=to_tensor(img_t))\n # default multispectral\n ori_shape = (img_info['height'], img_info['width'], 3)\n img_meta = dict(\n ori_shape=ori_shape,\n img_shape=img_shape,\n pad_shape=pad_shape,\n scale_factor=scale_factor,\n flip=flip)\n\n data['img_meta'] = img_meta\n data['img_rgb_in'] = to_tensor(img)\n data['img_thermal_in'] = to_tensor(img_t)\n return data\n\n def prepare_test_img(self, idx):\n return self.prepare_train_img(idx)\n" ]
[ [ "numpy.zeros", "numpy.random.rand" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Yasuo-orphan/SelfKG
[ "52f71c186ab4ad2db8de6cadf4e498d6e563ee96" ]
[ "script/preprocess/DWY_neighbor_token.py" ]
[ "import settings\nimport pandas as pd\nfrom loader.DWY_Neighbor import NeighborsLoader\nfrom loader.DBP15k import DBP15kLoader\nfrom script.preprocess.get_token import Token\nfrom settings import *\nimport numpy as np\nimport torch\n\nclass NeighborToken(object):\n def __init__(self, dbpToken, loader):\n self.loader = loader\n self.id_features_dict = dbpToken.id_features_dict\n\n self.id_adj_tensor_dict = {}\n\n def get_adj(valid_len):\n adj = torch.zeros(NEIGHBOR_SIZE, NEIGHBOR_SIZE).bool()\n for i in range(0, valid_len):\n adj[i, i] = 1\n adj[0, i] = 1\n adj[i, 0] = 1\n return adj\n\n def get_token():\n id_neighbors_dict = {}\n loader_id_neighbors_dict_copy = self.loader.id_neighbors_dict\n\n\n for entity_id, neighbors_dict in loader_id_neighbors_dict_copy.items():\n id_neighbors_dict[entity_id]=[]\n id_neighbors_dict[entity_id].append(self.id_features_dict[entity_id])\n for rel, neighbor in neighbors_dict.items():\n for neigh in neighbor:\n id_neighbors_dict[entity_id].append(self.id_features_dict[neigh])\n for k, v in id_neighbors_dict.items():\n if len(v) < NEIGHBOR_SIZE:\n self.id_adj_tensor_dict[k] = get_adj(len(v))\n id_neighbors_dict[k] = v + [[ord(' ')]*TOKEN_LEN] * (NEIGHBOR_SIZE - len(v))\n else:\n self.id_adj_tensor_dict[k] = get_adj(NEIGHBOR_SIZE)\n id_neighbors_dict[k] = v[:NEIGHBOR_SIZE]\n return id_neighbors_dict\n\n self.id_neighbors_dict = get_token()\n\n\n" ]
[ [ "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vxsharma-14/DIFFUS
[ "d70633890b8fb2e7b3dde918eb13b263f7a035ef" ]
[ "docs/source/examples/tutorial-02-diffusion-1D-solvers-FTCS.py" ]
[ "# ***********************************************************************\r\n#\r\n# FILE tutorial-02-diffusion-1D-solvers-FTCS.py\r\n#\r\n# AUTHOR Dr. Vishal Sharma\r\n#\r\n# VERSION 1.0.0-alpha4\r\n#\r\n# WEBSITE https://github.com/vxsharma-14/project-NAnPack\r\n#\r\n# NAnPack Learner's Edition is distributed under the MIT License.\r\n#\r\n# Copyright (c) 2020 Vishal Sharma\r\n#\r\n# Permission is hereby granted, free of charge, to any person\r\n# obtaining a copy of this software and associated documentation\r\n# files (the \"Software\"), to deal in the Software without restriction,\r\n# including without limitation the rights to use, copy, modify, merge,\r\n# publish, distribute, sublicense, and/or sell copies of the Software,\r\n# and to permit persons to whom the Software is furnished to do so,\r\n# subject to the following conditions:\r\n#\r\n# The above copyright notice and this permission notice shall be\r\n# included in all copies or substantial portions of the Software.\r\n#\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\r\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\r\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n# SOFTWARE.\r\n#\r\n# You should have received a copy of the MIT License along with\r\n# NAnPack Learner's Edition.\r\n#\r\n# ***********************************************************************\r\n\"\"\"Script to solve 1D diffusion equation using a parabolic solver.\r\n\r\nExample Description:\r\n This is a classical application in fluid mechanics where the fluid is\r\n bounded between two parallel plates. The upper plate remains stationary\r\n and\r\n the lower plate is suddenly accelerated in x-direction at velocity u.\r\n It is required to find the velocity profile between the plates for the\r\n given initial and boundary conditions.\r\n\r\n U at (t=0.0, 0.0<y<H) = 0.0 m/s # Initial condition\r\n U at (t=0.0, y=0.0) = 40.0 m/s # Initial condition\r\n U at (t>0.0, y=0.0) = 40.0 m/s # Boundary condition at lower plate\r\n U at (t>0.0, y=H) = 0.0 # Boundary condition at upper plate\r\n\r\n Viscosity of fluid= 2.17e-4 m2/s\r\n H = 0.04 m\r\n dY = 0.001 m\r\n\"\"\"\r\n# Import modules\r\nimport matplotlib.pyplot as plt\r\nimport nanpack.preprocess as pre\r\nfrom nanpack.grid import RectangularGrid\r\nfrom nanpack.parabolicsolvers import FTCS\r\nimport nanpack.postprocess as post\r\nfrom nanpack.benchmark import ParallelPlateFlow\r\n\r\n\r\ndef diffusion1D():\r\n \"\"\"Compute the numerical solution.\"\"\"\r\n config_file = \"path/to/project/input/config.ini\"\r\n cfg = pre.RunConfig(config_file)\r\n # Define initial conditions\r\n cfg.U[0] = 40.0\r\n cfg.U[1:] = 0.0\r\n\r\n U = BC(cfg.U)\r\n\r\n X, _ = RectangularGrid(cfg.dX, cfg.iMax)\r\n diffX, _ = pre.DiffusionNumbers(cfg.Dimension, cfg.diff, cfg.dT,\r\n cfg.dX)\r\n\r\n # Start iterations\r\n Error = 1.0\r\n n = 0\r\n\r\n while n <= cfg.nMax and Error > cfg.ConvCrit:\r\n Error = 0.0\r\n n += 1\r\n Uold = U.copy()\r\n U = FTCS(Uold, diffX)\r\n Error = post.AbsoluteError(U, Uold)\r\n # Update BC\r\n U = BC(U)\r\n post.MonitorConvergence(cfg, n, Error)\r\n # Write output to file\r\n post.WriteSolutionToFile(U, n, cfg.nWrite, cfg.nMax,\r\n cfg.OutFileName, cfg.dX)\r\n # Write convergence history log to a file\r\n post.WriteConvHistToFile(cfg, n, Error)\r\n\r\n # Write output to file\r\n post.WriteSolutionToFile(U, n, cfg.nWrite, cfg.nMax,\r\n cfg.OutFileName, cfg.dX)\r\n # Obtain analytical solution\r\n Uana = ParallelPlateFlow(40.0, X, cfg.diff, cfg.totTime, 20)\r\n # Write convergence history log to a file\r\n post.WriteConvHistToFile(cfg, n, Error)\r\n plt.rc(\"font\", family=\"serif\", size=8)\r\n fig, ax = plt.subplots(dpi=150)\r\n plt.plot(U, X, \">-.b\", linewidth=0.5, label=\"FTCS\",\r\n markersize=5, markevery=5)\r\n plt.plot(Uana, X, \"o:r\", linewidth=0.5, label=\"Analytical\",\r\n markersize=5, markevery=5)\r\n plt.xlabel('Velocity (m/s)')\r\n plt.ylabel('Plate distance (m)')\r\n plt.legend()\r\n plt.title(f\"Velocity profile\\nat t={cfg.totTime} sec\", fontsize=8)\r\n plt.show()\r\n\r\n\r\ndef BC(U):\r\n \"\"\"Return the dependent variable with the updated boundary values.\"\"\"\r\n U[0] = 40.0\r\n U[-1] = 0.0\r\n\r\n return U\r\n\r\n\r\nif __name__ == \"__main__\":\r\n diffusion1D()\r\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "matplotlib.pyplot.rc", "matplotlib.pyplot.subplots", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ppwwyyxx/tensorpack
[ "f8fa2108c7ba85a69e0d7b81f2737d8284fdaa67" ]
[ "tensorpack/train/trainers.py" ]
[ "# -*- coding: utf-8 -*-\n# File: trainers.py\n\nimport multiprocessing as mp\nimport os\nimport sys\nimport tensorflow as tf\nfrom tensorpack.compat import tfv1\n\nfrom ..callbacks import CallbackFactory, RunOp\nfrom ..graph_builder.distributed import DistributedParameterServerBuilder, DistributedReplicatedBuilder\nfrom ..graph_builder.training import (\n AsyncMultiGPUBuilder, SyncMultiGPUParameterServerBuilder, SyncMultiGPUReplicatedBuilder)\nfrom ..graph_builder.utils import override_to_local_variable\nfrom ..input_source import FeedfreeInput, QueueInput\nfrom ..tfutils import get_global_step_var\nfrom ..tfutils.common import get_tf_version_tuple\nfrom ..tfutils.distributed import get_distributed_session_creator\nfrom ..tfutils.sesscreate import NewSessionCreator\nfrom ..tfutils.tower import TrainTowerContext\nfrom ..utils import logger\nfrom ..utils.argtools import map_arg\nfrom ..utils.develop import HIDE_DOC, deprecated\nfrom .tower import SingleCostTrainer\n\n__all__ = ['NoOpTrainer', 'SimpleTrainer',\n 'QueueInputTrainer',\n 'SyncMultiGPUTrainer',\n 'SyncMultiGPUTrainerReplicated',\n 'SyncMultiGPUTrainerParameterServer',\n 'AsyncMultiGPUTrainer',\n 'DistributedTrainerParameterServer',\n 'DistributedTrainerReplicated',\n 'HorovodTrainer', 'BytePSTrainer']\n\n\ndef _int_to_range(x):\n if isinstance(x, int):\n assert x > 0, \"Argument cannot be {}!\".format(x)\n return list(range(x))\n return x\n\n\nclass SimpleTrainer(SingleCostTrainer):\n \"\"\"\n Single-GPU single-cost single-tower trainer.\n \"\"\"\n def _setup_graph(self, input, get_cost_fn, get_opt_fn):\n logger.info(\"Building graph for a single training tower ...\")\n with TrainTowerContext(''):\n grads = self._make_get_grad_fn(input, get_cost_fn, get_opt_fn)()\n opt = get_opt_fn()\n self.train_op = opt.apply_gradients(grads, name='train_op')\n return []\n\n\nclass NoOpTrainer(SimpleTrainer):\n \"\"\"\n A special trainer that builds the graph (if given a tower function)\n and does nothing in each step.\n It is used to only run the callbacks.\n\n Note that `steps_per_epoch` and `max_epochs` are still valid options.\n \"\"\"\n def run_step(self):\n self.hooked_sess.run([])\n\n\n# Only exists for type check & back-compatibility\nclass QueueInputTrainer(SimpleTrainer):\n @deprecated(\"SimpleTrainer is sufficient!\", \"2019-12-31\")\n def _setup_graph(self, input, get_cost_fn, get_opt_fn):\n assert isinstance(input, QueueInput), input\n return super(QueueInputTrainer, self)._setup_graph(input, get_cost_fn, get_opt_fn)\n\n\nclass SyncMultiGPUTrainerParameterServer(SingleCostTrainer):\n\n __doc__ = SyncMultiGPUParameterServerBuilder.__doc__ + \"\"\"\n\n Attributes:\n devices (list[int]): List of GPU ids.\n\n \"\"\"\n\n @map_arg(gpus=_int_to_range)\n def __init__(self, gpus, ps_device=None):\n \"\"\"\n Args:\n gpus ([int]): list of GPU ids.\n ps_device: either 'gpu' or 'cpu', where variables are stored.\n The default value is subject to change.\n \"\"\"\n self.devices = gpus\n if ps_device is None:\n ps_device = 'gpu' if len(gpus) <= 2 else 'cpu'\n self._builder = SyncMultiGPUParameterServerBuilder(gpus, ps_device)\n super(SyncMultiGPUTrainerParameterServer, self).__init__()\n\n def _setup_graph(self, input, get_cost_fn, get_opt_fn):\n if len(self.devices) > 1:\n assert isinstance(input, FeedfreeInput), input\n tower_fn = self._make_get_grad_fn(input, get_cost_fn, get_opt_fn)\n grad_list = self._builder.call_for_each_tower(tower_fn)\n self.train_op = self._builder.build(grad_list, get_opt_fn)\n return []\n\n\ndef SyncMultiGPUTrainer(gpus):\n \"\"\"\n Return a default multi-GPU trainer, if you don't care about the details.\n It may not be the most efficient one for your task.\n\n Args:\n gpus (list[int]): list of GPU ids.\n \"\"\"\n return SyncMultiGPUTrainerParameterServer(gpus, ps_device='cpu')\n\n\nclass AsyncMultiGPUTrainer(SingleCostTrainer):\n\n __doc__ = AsyncMultiGPUBuilder.__doc__ + \"\"\"\n\n Attributes:\n devices (list[int]): List of GPU ids.\n\n \"\"\"\n\n @map_arg(gpus=_int_to_range)\n def __init__(self, gpus, scale_gradient=True):\n \"\"\"\n Args:\n gpus ([int]): list of GPU ids.\n scale_gradient (bool): if True, will scale each gradient by ``1.0/nr_gpu``.\n \"\"\"\n self.devices = gpus\n self._builder = AsyncMultiGPUBuilder(gpus, scale_gradient)\n super(AsyncMultiGPUTrainer, self).__init__()\n\n def _setup_graph(self, input, get_cost_fn, get_opt_fn):\n if len(self.devices) > 1:\n assert isinstance(input, FeedfreeInput), input\n tower_fn = self._make_get_grad_fn(input, get_cost_fn, get_opt_fn)\n grad_list = self._builder.call_for_each_tower(tower_fn)\n self.train_op = self._builder.build(grad_list, get_opt_fn)\n return []\n\n\nclass SyncMultiGPUTrainerReplicated(SingleCostTrainer):\n\n __doc__ = SyncMultiGPUReplicatedBuilder.__doc__ + \"\"\"\n\n Attributes:\n devices (list[int]): List of GPU ids.\n\n BROADCAST_EVERY_EPOCH (bool):\n Whether to broadcast the variables every epoch.\n Theoretically this is a no-op (because the variables\n are supposed to be in-sync).\n But this cheap operation may help prevent\n certain numerical issues in practice.\n\n Note that in cases such as BatchNorm, the variables may not be in sync:\n e.g., non-master worker may not maintain EMAs.\n\n For benchmark, disable this option.\n \"\"\"\n\n @map_arg(gpus=_int_to_range)\n def __init__(self, gpus, average=True, mode=None):\n \"\"\"\n Args:\n gpus (int or [int]): list of GPU ids.\n average (bool): whether to average or sum gradients.\n mode (str or None): Gradient aggregation mode.\n Supported values: ['nccl', 'hierarchical', 'cpu', 'gpu'].\n These modes may differ in speed.\n Default to pick automatically by heuristics.\n \"hierarchical\" mode was designed for DGX-like 8-GPU machines.\n \"\"\"\n self.devices = gpus\n if mode is not None:\n mode = mode.lower()\n\n # Heuristics about mode selection:\n if mode == 'hierarchical' and len(gpus) != 8:\n logger.warn(\"mode='hierarchical' requires 8 GPUs. Will fallback to default mode.\")\n mode = None\n if mode is None:\n if len(gpus) == 8:\n mode = 'hierarchical'\n else:\n # https://github.com/tensorflow/tensorflow/issues/41539\n mode = 'nccl' if get_tf_version_tuple() < (1, 15) else 'gpu'\n if mode == 'cpu' and get_tf_version_tuple() >= (2, 0):\n # cpu mode causes the entire model to get located on cpu\n mode = 'gpu'\n if mode == 'nccl' and get_tf_version_tuple() >= (1, 15):\n logger.warning(\n \"NCCL in TensorFlow has a serious bug that is likely to trigger in TF>=1.15. \"\n \"Try 'mode=None' to use a better default mode.\")\n\n self._builder = SyncMultiGPUReplicatedBuilder(gpus, average, mode)\n self.BROADCAST_EVERY_EPOCH = True\n\n super(SyncMultiGPUTrainerReplicated, self).__init__()\n\n def _setup_graph(self, input, get_cost_fn, get_opt_fn):\n if len(self.devices) > 1:\n assert isinstance(input, FeedfreeInput), input\n tower_fn = self._make_get_grad_fn(input, get_cost_fn, get_opt_fn)\n grad_list = self._builder.call_for_each_tower(tower_fn)\n self.train_op, post_init_op = self._builder.build(grad_list, get_opt_fn)\n\n if post_init_op is not None:\n cb = RunOp(\n post_init_op,\n run_before=True,\n run_as_trigger=self.BROADCAST_EVERY_EPOCH,\n verbose=True)\n cb.name_scope = \"SyncVariables\"\n return [cb]\n else:\n return []\n\n\n# deprecated\nclass DistributedTrainerBase(SingleCostTrainer):\n\n devices = None\n\n def __init__(self, gpus, server):\n super(DistributedTrainerBase, self).__init__()\n self.devices = gpus\n self.server = server\n self.job_name = server.server_def.job_name\n logger.info(\"Distributed training on cluster:\\n\" + str(server.server_def.cluster))\n\n def join(self):\n logger.info(\"Calling server.join() on {}:{}\".format(self.job_name, self.server.server_def.task_index))\n logger.info(\"Kill me with 'kill {}'\".format(os.getpid()))\n self.server.join() # this function will never return tensorflow#4713\n raise RuntimeError(\"This is a bug. Server.join() for should never return!\")\n\n @HIDE_DOC\n def initialize(self, session_creator, session_init):\n if not isinstance(session_creator, NewSessionCreator) or \\\n session_creator.user_provided_config:\n raise ValueError(\n \"You are not allowed to set session_creator or session_config for distributed training! \"\n \"To use a custom session config, pass it to tf.train.Server.\")\n super(DistributedTrainerBase, self).initialize(\n get_distributed_session_creator(self.server), session_init)\n\n\n# This is slow. deprecated in favor of horovod\nclass DistributedTrainerParameterServer(DistributedTrainerBase):\n\n __doc__ = DistributedParameterServerBuilder.__doc__\n\n @map_arg(gpus=_int_to_range)\n def __init__(self, gpus, server, caching_device='cpu'):\n \"\"\"\n Args:\n gpus ([int]): list of GPU ids.\n server (tf.train.Server): the server with ps and workers.\n caching_device (str): either 'cpu' or 'gpu'. The device to cache variables copied from PS\n \"\"\"\n super(DistributedTrainerParameterServer, self).__init__(gpus, server)\n assert self.job_name in ['ps', 'worker'], self.job_name\n if self.job_name == 'ps':\n self.join()\n\n self._builder = DistributedParameterServerBuilder(gpus, server, caching_device)\n self.is_chief = self._builder.is_chief\n\n def _setup_graph(self, input, get_cost_fn, get_opt_fn):\n assert isinstance(input, FeedfreeInput), input\n self.train_op = self._builder.build(\n self._make_get_grad_fn(input, get_cost_fn, get_opt_fn), get_opt_fn)\n return []\n\n\n# This is slow. deprecated in favor of horovod\nclass DistributedTrainerReplicated(DistributedTrainerBase):\n\n __doc__ = DistributedReplicatedBuilder.__doc__\n\n @map_arg(gpus=_int_to_range)\n def __init__(self, gpus, server):\n \"\"\"\n Args:\n gpus (list[int]): list of GPU ids.\n server (tf.train.Server): the server with ps and workers.\n \"\"\"\n super(DistributedTrainerReplicated, self).__init__(gpus, server)\n assert self.job_name in ['ps', 'worker'], self.job_name\n if self.job_name == 'ps':\n self.join()\n\n self._builder = DistributedReplicatedBuilder(gpus, server)\n self.is_chief = self._builder.is_chief\n\n def _setup_input(self, input_signature, input):\n with override_to_local_variable():\n get_global_step_var() # gs should be local\n # input source may create variables (queue size summary)\n # TODO This is not good because we don't know from here\n # whether something should be global or local. We now assume\n # they should be local.\n assert not input.setup_done()\n return input.setup(input_signature)\n\n def _setup_graph(self, input, get_cost_fn, get_opt_fn):\n assert isinstance(input, FeedfreeInput), input\n self.train_op, initial_sync_op, model_sync_op = self._builder.build(\n self._make_get_grad_fn(input, get_cost_fn, get_opt_fn), get_opt_fn)\n\n callbacks = []\n # Initial syncing vars from PS\n cb = RunOp(lambda: initial_sync_op,\n run_before=True, run_as_trigger=False, verbose=True)\n cb.chief_only = False\n callbacks.append(cb)\n\n # Sync model_variables to PS, only chief needs to do this\n if model_sync_op:\n cb = RunOp(lambda: model_sync_op,\n run_before=False, run_as_trigger=True, verbose=True)\n logger.warn(\"For efficiency, local MODEL_VARIABLES are only synced to PS once \"\n \"every epoch. Be careful if you save the model more frequently than this.\")\n callbacks.append(cb)\n return callbacks\n\n @property\n def _main_tower_vs_name(self):\n return \"tower0\"\n\n\nclass HorovodTrainer(SingleCostTrainer):\n \"\"\"\n Horovod trainer, support both multi-GPU and distributed training.\n\n To use for multi-GPU training:\n\n .. code-block:: bash\n\n # First, change trainer to HorovodTrainer(), then\n CUDA_VISIBLE_DEVICES=0,1,2,3 NCCL_DEBUG=INFO horovodrun -np 4 --output-filename mylog python train.py\n\n To use for distributed training:\n\n .. code-block:: bash\n\n # First, change trainer to HorovodTrainer(), then\n horovodrun -np 8 -H server1:4,server2:4 --output-filename mylog \\\\\n python train.py\n\n Note:\n 1. To reach the maximum speed in your system, there are many options to tune\n in Horovod installation, horovodrun arguments, and in the MPI command line.\n See Horovod docs for details.\n\n 2. Due to a TF bug (#8136), you must not initialize CUDA context before the trainer starts training.\n Therefore TF functions like `is_gpu_available()` or `list_local_devices()`\n must be avoided.\n You can, however, use `tf.config.experimental.list_physical_devices('GPU')`, introduced in TF 1.14.\n\n 3. Horovod supports both MPI and gloo. There are a few drawbacks of the MPI backend:\n\n + MPI does not like `fork()`. If your code (e.g. dataflow) contains multiprocessing, it may cause problems.\n + MPI sometimes fails to kill all processes in the end. Be sure to check it afterwards.\n\n The gloo backend is recommended though it may come with very minor slow down.\n To use gloo backend, see\n `horovod documentation <https://github.com/horovod/horovod#running-horovod>`_ for more details.\n\n 4. Keep in mind that there is one process running the script per GPU, therefore:\n\n + Make sure your InputSource has reasonable randomness.\n\n + If your data processing is heavy, doing it in a single dedicated process might be\n a better choice than doing them repeatedly in each process.\n\n + You need to make sure log directories in each process won't conflict.\n You can set it only for the chief process, or set a different one for each process.\n\n + Callbacks have an option to be run only in the chief process, or in all processes.\n See :meth:`Callback.set_chief_only()`. Most callbacks have a reasonable\n default already, but certain callbacks may need your customization.\n Report an issue if you find any bad defaults.\n\n + You can use Horovod API such as `hvd.rank()` to know which process you are and choose\n different code path. Chief process has rank 0.\n\n 5. Due to these caveats, see\n `ResNet-Horovod <https://github.com/tensorpack/benchmarks/tree/master/ResNet-Horovod>`_\n for a full example which has handled these common issues.\n This example can train ImageNet in roughly an hour following the paper's setup.\n\n Attributes:\n BROADCAST_EVERY_EPOCH (bool):\n Whether to broadcast the variables every epoch.\n Theoretically this is a no-op (because the variables\n are supposed to be in-sync).\n But this cheap operation may help prevent certain numerical issues in practice.\n\n Note that in cases such as BatchNorm, the variables may not be in sync:\n e.g., non-master worker may not maintain EMAs.\n\n For benchmark, disable this option.\n \"\"\"\n\n def __init__(self, average=True, compression=None):\n \"\"\"\n Args:\n average (bool): whether to average or sum the gradients across processes.\n compression: `hvd.Compression.fp16` or `hvd.Compression.none`\n \"\"\"\n if 'pyarrow' in sys.modules:\n logger.warn(\"Horovod and pyarrow may conflict due to pyarrow bugs.\")\n # lazy import\n import horovod.tensorflow as hvd\n import horovod\n hvd_version = tuple(map(int, horovod.__version__.split('.')[:3]))\n self.hvd = hvd\n\n hvd.init()\n self.is_chief = hvd.rank() == 0\n self._local_rank = hvd.local_rank()\n self._rank = hvd.rank()\n self._average = average\n self._compression = compression\n self._has_compression = hvd_version >= (0, 15, 0)\n logger.info(\"[HorovodTrainer] local rank={}\".format(self._local_rank))\n super(HorovodTrainer, self).__init__()\n\n self.BROADCAST_EVERY_EPOCH = True\n\n def mpi_enabled(self):\n \"\"\"\n Returns:\n bool: whether hvd is currently running under MPI\n \"\"\"\n try:\n return self.hvd.mpi_enabled()\n except AttributeError:\n return False\n\n def allreduce(self, grads):\n if self.hvd.size() == 1:\n return grads\n # copied from https://github.com/uber/horovod/blob/master/horovod/tensorflow/__init__.py\n averaged_gradients = []\n with tf.name_scope(\"AllReduce\"):\n for grad, var in grads:\n if grad is not None:\n if self._compression is not None and self._has_compression:\n avg_grad = self.hvd.allreduce(grad, average=self._average, compression=self._compression)\n else:\n avg_grad = self.hvd.allreduce(grad, average=self._average)\n averaged_gradients.append((avg_grad, var))\n else:\n averaged_gradients.append((None, var))\n return averaged_gradients\n\n def _setup_graph(self, input, get_cost_fn, get_opt_fn):\n with TrainTowerContext(''):\n grads = self._make_get_grad_fn(input, get_cost_fn, get_opt_fn)()\n grads = self.allreduce(grads)\n\n opt = get_opt_fn()\n self.train_op = opt.apply_gradients(grads, name='train_op')\n\n cb = CallbackFactory(\n before_train=self.broadcast,\n trigger=self.broadcast if self.BROADCAST_EVERY_EPOCH else None\n ).set_chief_only(False)\n return [cb]\n\n def broadcast(self, _):\n logger.info(\"Broadcasting {} global variables ...\".format(self._num_global_variables))\n # the op will be created in initialize()\n self.sess.run(self._broadcast_op)\n\n @HIDE_DOC\n def initialize(self, session_creator, session_init):\n # broadcast_op should be the last setup_graph: it needs to be created\n # \"right before\" the graph is finalized,\n # because it needs to capture all the variables (which may be created by callbacks).\n self._num_global_variables = len(tfv1.global_variables())\n self._broadcast_op = self.hvd.broadcast_global_variables(0)\n\n # it's important that our NewSessionCreator does not finalize the graph\n if not isinstance(session_creator, NewSessionCreator):\n raise ValueError(\n \"session_creator has to be `NewSessionCreator` for horovod/byteps training! \")\n # NOTE It will fail if GPU was already detected before initializing the session\n # https://github.com/tensorflow/tensorflow/issues/8136\n session_creator.config.gpu_options.visible_device_list = str(self._local_rank)\n try:\n session_creator.config.inter_op_parallelism_threads = mp.cpu_count() // self.hvd.local_size()\n except AttributeError: # old horovod does not have local_size\n pass\n super(HorovodTrainer, self).initialize(session_creator, session_init)\n\n # This broadcast belongs to the \"intialize\" stage\n # It should not be delayed to the \"before_train\" stage.\n # TODO:\n # 1. a allgather helper to concat strings\n # 2. check variables on each rank match each other, print warnings, and broadcast the common set.\n if self.is_chief:\n logger.info(\"Broadcasting initialization of {} global variables ...\".format(self._num_global_variables))\n else:\n logger.info(\"Rank {} waiting for initialization of {} variables ...\".format(\n self._rank, self._num_global_variables))\n self.sess.run(self._broadcast_op)\n\n\nclass BytePSTrainer(HorovodTrainer):\n \"\"\"\n BytePS trainer. Supports both multi-GPU and distributed training.\n It achieves better scalability than horovod in distributed training, if the model is communication\n intensive and you have properly set up the machines following its\n `best practices <https://github.com/bytedance/byteps/blob/master/docs/best-practice.md>`_\n which requires a few extra bandwidth servers than horovod.\n\n To use it, switch the trainer, and refer to BytePS documentation on how to\n launch server/scheduler/workers.\n\n Attributes:\n hvd (module): the byteps module that contains horovod-compatible APIs\n like `rank(),size()`.\n This attribute exists so that downstream code that uses these APIs\n does not need to worry about which library is being used under the hood.\n \"\"\"\n def __init__(self, average=True):\n \"\"\"\n Args:\n average (bool): whether to average or sum the gradients across processes.\n \"\"\"\n import byteps.tensorflow as bps\n self.hvd = bps # BytePS has the same interface as Horovod\n self.hvd.allreduce = bps.push_pull # https://github.com/bytedance/byteps/issues/8\n assert os.environ.get(\"DMLC_ROLE\", None) == \"worker\"\n assert \"DMLC_WORKER_ID\" in os.environ and \"DMLC_NUM_WORKER\" in os.environ\n bps.init()\n self.is_chief = bps.rank() == 0\n\n self._local_rank = bps.local_rank()\n self._rank = bps.rank()\n self._average = average\n\n self._compression = None\n self._has_compression = False\n logger.info(\"[BytePSTrainer] local rank={}\".format(self._local_rank))\n SingleCostTrainer.__init__(self)\n\n def mpi_enabled(self):\n \"\"\"\n Returns:\n bool: whether hvd is currently running under MPI\n \"\"\"\n return False\n" ]
[ [ "tensorflow.name_scope" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
andreArtelt/ceml
[ "364d4630d6a01592c2ab86f2d53dbb7feb682381" ]
[ "tests/sklearn/test_sklearn_randomforest.py" ]
[ "# -*- coding: utf-8 -*-\nimport sys\nsys.path.insert(0,'..')\n\nimport numpy as np\nnp.random.seed(42)\nimport sklearn\nfrom sklearn.datasets import load_iris, load_boston\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\n\nfrom ceml.sklearn import generate_counterfactual\n\n\ndef test_randomforest_classifier():\n # Load data\n X, y = load_iris(return_X_y=True)\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=4242)\n\n # Create and fit model\n model = RandomForestClassifier(n_estimators=10, random_state=42)\n model.fit(X_train, y_train)\n\n # Select data point for explaining its prediction\n x_orig = X_test[1:4][0,:]\n assert model.predict([x_orig]) == 2\n\n # Compute counterfactual\n features_whitelist = None\n\n x_cf, y_cf, delta = generate_counterfactual(model, x_orig, 0, features_whitelist=features_whitelist, regularization=\"l1\", C=0.01, optimizer=\"nelder-mead\", return_as_dict=False)\n assert y_cf == 0\n assert model.predict(np.array([x_cf])) == 0\n\n x_cf, y_cf, delta = generate_counterfactual(model, x_orig, 0, features_whitelist=features_whitelist, regularization=None, optimizer=\"nelder-mead\", return_as_dict=False)\n assert y_cf == 0\n assert model.predict(np.array([x_cf])) == 0\n\n features_whitelist = [0, 2]\n\n x_cf, y_cf, delta = generate_counterfactual(model, x_orig, 0, features_whitelist=features_whitelist, regularization=\"l1\", C=1.0, optimizer=\"nelder-mead\", return_as_dict=False)\n assert y_cf == 0\n assert model.predict(np.array([x_cf])) == 0\n assert all([True if i in features_whitelist else delta[i] == 0. for i in range(x_orig.shape[0])])\n\n x_cf, y_cf, delta = generate_counterfactual(model, x_orig, 0, features_whitelist=features_whitelist, regularization=None, optimizer=\"nelder-mead\", return_as_dict=False)\n assert y_cf == 0\n assert model.predict(np.array([x_cf])) == 0\n assert all([True if i in features_whitelist else delta[i] == 0. for i in range(x_orig.shape[0])])\n\n\ndef test_randomforest_regressor():\n # Load data\n X, y = load_boston(return_X_y=True)\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=4242)\n\n # Create and fit model\n model = RandomForestRegressor(n_estimators=10, random_state=42)\n model.fit(X_train, y_train)\n\n # Select data point for explaining its prediction\n x_orig = X_test[1:4][0,:]\n y_orig_pred = model.predict([x_orig])\n assert y_orig_pred >= 19. and y_orig_pred < 21.\n\n # Compute counterfactual\n y_target = 25.\n y_target_done = lambda z: np.abs(z - y_target) < 1.\n\n features_whitelist = None\n\n x_cf, y_cf, delta = generate_counterfactual(model, x_orig, y_target_done, features_whitelist=features_whitelist, regularization=\"l1\", C=1.0, return_as_dict=False)\n assert y_target_done(y_cf)\n assert y_target_done(model.predict(np.array([x_cf])))\n\n x_cf, y_cf, delta = generate_counterfactual(model, x_orig, y_target_done, features_whitelist=features_whitelist, regularization=None, return_as_dict=False)\n assert y_target_done(y_cf)\n assert y_target_done(model.predict(np.array([x_cf])))\n\n features_whitelist = [0, 2, 4, 5, 7, 8, 9, 12]\n \n x_cf, y_cf, delta = generate_counterfactual(model, x_orig, y_target_done, features_whitelist=features_whitelist, regularization=\"l1\", C=1.0, return_as_dict=False)\n assert y_target_done(y_cf)\n assert y_target_done(model.predict(np.array([x_cf])))\n assert all([True if i in features_whitelist else delta[i] == 0. for i in range(x_orig.shape[0])])\n\n x_cf, y_cf, delta = generate_counterfactual(model, x_orig, y_target_done, features_whitelist=features_whitelist, regularization=None, return_as_dict=False)\n assert y_target_done(y_cf)\n assert y_target_done(model.predict(np.array([x_cf])))\n assert all([True if i in features_whitelist else delta[i] == 0. for i in range(x_orig.shape[0])])" ]
[ [ "sklearn.ensemble.RandomForestRegressor", "numpy.abs", "numpy.random.seed", "sklearn.ensemble.RandomForestClassifier", "sklearn.datasets.load_iris", "sklearn.model_selection.train_test_split", "sklearn.datasets.load_boston", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ouakif/tensorflow
[ "6efce9a74d4ba2ba2182d92ac1e4f144b5d755d2", "63c45aacf30e819b00e74b85bd1c9f11b0760cd3", "63c45aacf30e819b00e74b85bd1c9f11b0760cd3", "63c45aacf30e819b00e74b85bd1c9f11b0760cd3" ]
[ "tensorflow/python/data/ops/iterator_ops.py", "tensorflow/python/keras/layers/convolutional_test.py", "tensorflow/python/ops/linalg/linear_operator_householder.py", "tensorflow/python/keras/engine/network_test.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\"\"\"Python wrappers for Iterators.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport threading\nimport warnings\n\nfrom tensorflow.python.data.ops import optional_ops\nfrom tensorflow.python.data.util import nest\nfrom tensorflow.python.data.util import structure\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import type_spec\nfrom tensorflow.python.ops import gen_dataset_ops\nfrom tensorflow.python.training.saver import BaseSaverBuilder\nfrom tensorflow.python.training.tracking import base as trackable\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n# NOTE(mrry): It is legitimate to call `Iterator.get_next()` multiple\n# times, e.g. when you are distributing different elements to multiple\n# devices in a single step. However, a common pitfall arises when\n# users call `Iterator.get_next()` in each iteration of their training\n# loop. `Iterator.get_next()` adds ops to the graph, and executing\n# each op allocates resources (including threads); as a consequence,\n# invoking it in every iteration of a training loop causes slowdown\n# and eventual resource exhaustion. To guard against this outcome, we\n# log a warning when the number of uses crosses a threshold of suspicion.\nGET_NEXT_CALL_WARNING_THRESHOLD = 32\n\nGET_NEXT_CALL_WARNING_MESSAGE = (\n \"An unusually high number of `Iterator.get_next()` calls was detected. \"\n \"This often indicates that `Iterator.get_next()` is being called inside \"\n \"a training loop, which will cause gradual slowdown and eventual resource \"\n \"exhaustion. If this is the case, restructure your code to call \"\n \"`next_element = iterator.get_next()` once outside the loop, and use \"\n \"`next_element` as the input to some computation that is invoked inside \"\n \"the loop.\")\n\n# Collection of all IteratorResources in the `Graph`.\nGLOBAL_ITERATORS = \"iterators\"\n\n\ndef _device_stack_is_empty():\n if context.executing_eagerly():\n return context.context().device_name is None\n # pylint: disable=protected-access\n device_stack = ops.get_default_graph()._device_functions_outer_to_inner\n # pylint: enable=protected-access\n return not bool(device_stack)\n\n\n@tf_export(v1=[\"data.Iterator\"])\nclass Iterator(trackable.Trackable):\n \"\"\"Represents the state of iterating through a `Dataset`.\"\"\"\n\n def __init__(self, iterator_resource, initializer, output_types,\n output_shapes, output_classes):\n \"\"\"Creates a new iterator from the given iterator resource.\n\n Note: Most users will not call this initializer directly, and will\n instead use `Dataset.make_initializable_iterator()` or\n `Dataset.make_one_shot_iterator()`.\n\n Args:\n iterator_resource: A `tf.resource` scalar `tf.Tensor` representing the\n iterator.\n initializer: A `tf.Operation` that should be run to initialize this\n iterator.\n output_types: A nested structure of `tf.DType` objects corresponding to\n each component of an element of this iterator.\n output_shapes: A nested structure of `tf.TensorShape` objects\n corresponding to each component of an element of this iterator.\n output_classes: A nested structure of Python `type` objects corresponding\n to each component of an element of this iterator.\n \"\"\"\n self._iterator_resource = iterator_resource\n self._initializer = initializer\n\n if (output_types is None or output_shapes is None\n or output_classes is None):\n raise ValueError(\"If `structure` is not specified, all of \"\n \"`output_types`, `output_shapes`, and `output_classes`\"\n \" must be specified.\")\n self._element_spec = structure.convert_legacy_structure(\n output_types, output_shapes, output_classes)\n self._flat_tensor_shapes = structure.get_flat_tensor_shapes(\n self._element_spec)\n self._flat_tensor_types = structure.get_flat_tensor_types(\n self._element_spec)\n\n self._string_handle = gen_dataset_ops.iterator_to_string_handle(\n self._iterator_resource)\n self._get_next_call_count = 0\n ops.add_to_collection(GLOBAL_ITERATORS, self._iterator_resource)\n\n @staticmethod\n def from_structure(output_types,\n output_shapes=None,\n shared_name=None,\n output_classes=None):\n \"\"\"Creates a new, uninitialized `Iterator` with the given structure.\n\n This iterator-constructing method can be used to create an iterator that\n is reusable with many different datasets.\n\n The returned iterator is not bound to a particular dataset, and it has\n no `initializer`. To initialize the iterator, run the operation returned by\n `Iterator.make_initializer(dataset)`.\n\n The following is an example\n\n ```python\n iterator = Iterator.from_structure(tf.int64, tf.TensorShape([]))\n\n dataset_range = Dataset.range(10)\n range_initializer = iterator.make_initializer(dataset_range)\n\n dataset_evens = dataset_range.filter(lambda x: x % 2 == 0)\n evens_initializer = iterator.make_initializer(dataset_evens)\n\n # Define a model based on the iterator; in this example, the model_fn\n # is expected to take scalar tf.int64 Tensors as input (see\n # the definition of 'iterator' above).\n prediction, loss = model_fn(iterator.get_next())\n\n # Train for `num_epochs`, where for each epoch, we first iterate over\n # dataset_range, and then iterate over dataset_evens.\n for _ in range(num_epochs):\n # Initialize the iterator to `dataset_range`\n sess.run(range_initializer)\n while True:\n try:\n pred, loss_val = sess.run([prediction, loss])\n except tf.errors.OutOfRangeError:\n break\n\n # Initialize the iterator to `dataset_evens`\n sess.run(evens_initializer)\n while True:\n try:\n pred, loss_val = sess.run([prediction, loss])\n except tf.errors.OutOfRangeError:\n break\n ```\n\n Args:\n output_types: A nested structure of `tf.DType` objects corresponding to\n each component of an element of this dataset.\n output_shapes: (Optional.) A nested structure of `tf.TensorShape` objects\n corresponding to each component of an element of this dataset. If\n omitted, each component will have an unconstrainted shape.\n shared_name: (Optional.) If non-empty, this iterator will be shared under\n the given name across multiple sessions that share the same devices\n (e.g. when using a remote server).\n output_classes: (Optional.) A nested structure of Python `type` objects\n corresponding to each component of an element of this iterator. If\n omitted, each component is assumed to be of type `tf.Tensor`.\n\n Returns:\n An `Iterator`.\n\n Raises:\n TypeError: If the structures of `output_shapes` and `output_types` are\n not the same.\n \"\"\"\n output_types = nest.map_structure(dtypes.as_dtype, output_types)\n if output_shapes is None:\n output_shapes = nest.map_structure(\n lambda _: tensor_shape.TensorShape(None), output_types)\n else:\n output_shapes = nest.map_structure_up_to(output_types,\n tensor_shape.as_shape,\n output_shapes)\n if output_classes is None:\n output_classes = nest.map_structure(lambda _: ops.Tensor, output_types)\n nest.assert_same_structure(output_types, output_shapes)\n output_structure = structure.convert_legacy_structure(\n output_types, output_shapes, output_classes)\n if shared_name is None:\n shared_name = \"\"\n if _device_stack_is_empty():\n with ops.device(\"/cpu:0\"):\n iterator_resource = gen_dataset_ops.iterator_v2(\n container=\"\",\n shared_name=shared_name,\n output_types=structure.get_flat_tensor_types(\n output_structure),\n output_shapes=structure.get_flat_tensor_shapes(\n output_structure))\n else:\n iterator_resource = gen_dataset_ops.iterator_v2(\n container=\"\",\n shared_name=shared_name,\n output_types=structure.get_flat_tensor_types(output_structure),\n output_shapes=structure.get_flat_tensor_shapes(\n output_structure))\n return Iterator(iterator_resource, None, output_types, output_shapes,\n output_classes)\n\n @staticmethod\n def from_string_handle(string_handle,\n output_types,\n output_shapes=None,\n output_classes=None):\n \"\"\"Creates a new, uninitialized `Iterator` based on the given handle.\n\n This method allows you to define a \"feedable\" iterator where you can choose\n between concrete iterators by feeding a value in a `tf.Session.run` call.\n In that case, `string_handle` would be a `tf.compat.v1.placeholder`, and you\n would\n feed it with the value of `tf.data.Iterator.string_handle` in each step.\n\n For example, if you had two iterators that marked the current position in\n a training dataset and a test dataset, you could choose which to use in\n each step as follows:\n\n ```python\n train_iterator = tf.data.Dataset(...).make_one_shot_iterator()\n train_iterator_handle = sess.run(train_iterator.string_handle())\n\n test_iterator = tf.data.Dataset(...).make_one_shot_iterator()\n test_iterator_handle = sess.run(test_iterator.string_handle())\n\n handle = tf.compat.v1.placeholder(tf.string, shape=[])\n iterator = tf.data.Iterator.from_string_handle(\n handle, train_iterator.output_types)\n\n next_element = iterator.get_next()\n loss = f(next_element)\n\n train_loss = sess.run(loss, feed_dict={handle: train_iterator_handle})\n test_loss = sess.run(loss, feed_dict={handle: test_iterator_handle})\n ```\n\n Args:\n string_handle: A scalar `tf.Tensor` of type `tf.string` that evaluates to\n a handle produced by the `Iterator.string_handle()` method.\n output_types: A nested structure of `tf.DType` objects corresponding to\n each component of an element of this dataset.\n output_shapes: (Optional.) A nested structure of `tf.TensorShape` objects\n corresponding to each component of an element of this dataset. If\n omitted, each component will have an unconstrainted shape.\n output_classes: (Optional.) A nested structure of Python `type` objects\n corresponding to each component of an element of this iterator. If\n omitted, each component is assumed to be of type `tf.Tensor`.\n\n Returns:\n An `Iterator`.\n \"\"\"\n output_types = nest.map_structure(dtypes.as_dtype, output_types)\n if output_shapes is None:\n output_shapes = nest.map_structure(\n lambda _: tensor_shape.TensorShape(None), output_types)\n else:\n output_shapes = nest.map_structure_up_to(output_types,\n tensor_shape.as_shape,\n output_shapes)\n if output_classes is None:\n output_classes = nest.map_structure(lambda _: ops.Tensor, output_types)\n nest.assert_same_structure(output_types, output_shapes)\n output_structure = structure.convert_legacy_structure(\n output_types, output_shapes, output_classes)\n string_handle = ops.convert_to_tensor(string_handle, dtype=dtypes.string)\n if _device_stack_is_empty():\n with ops.device(\"/cpu:0\"):\n iterator_resource = gen_dataset_ops.iterator_from_string_handle_v2(\n string_handle,\n output_types=structure.get_flat_tensor_types(output_structure),\n output_shapes=structure.get_flat_tensor_shapes(output_structure))\n else:\n iterator_resource = gen_dataset_ops.iterator_from_string_handle_v2(\n string_handle,\n output_types=structure.get_flat_tensor_types(output_structure),\n output_shapes=structure.get_flat_tensor_shapes(output_structure))\n return Iterator(iterator_resource, None, output_types, output_shapes,\n output_classes)\n\n @property\n def initializer(self):\n \"\"\"A `tf.Operation` that should be run to initialize this iterator.\n\n Returns:\n A `tf.Operation` that should be run to initialize this iterator\n\n Raises:\n ValueError: If this iterator initializes itself automatically.\n \"\"\"\n if self._initializer is not None:\n return self._initializer\n else:\n # TODO(mrry): Consider whether one-shot iterators should have\n # initializers that simply reset their state to the beginning.\n raise ValueError(\"Iterator does not have an initializer.\")\n\n def make_initializer(self, dataset, name=None):\n \"\"\"Returns a `tf.Operation` that initializes this iterator on `dataset`.\n\n Args:\n dataset: A `Dataset` with compatible structure to this iterator.\n name: (Optional.) A name for the created operation.\n\n Returns:\n A `tf.Operation` that can be run to initialize this iterator on the given\n `dataset`.\n\n Raises:\n TypeError: If `dataset` and this iterator do not have a compatible\n element structure.\n \"\"\"\n with ops.name_scope(name, \"make_initializer\") as name:\n # NOTE(mrry): Cannot depend on `dataset_ops.get_legacy_output*()` due\n # to that creating a circular dependency.\n # pylint: disable=protected-access\n dataset_output_types = nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_types(),\n dataset.element_spec)\n dataset_output_shapes = nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_shapes(),\n dataset.element_spec)\n dataset_output_classes = nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_classes(),\n dataset.element_spec)\n # pylint: enable=protected-access\n\n nest.assert_same_structure(self.output_types, dataset_output_types)\n nest.assert_same_structure(self.output_shapes, dataset_output_shapes)\n for iterator_class, dataset_class in zip(\n nest.flatten(self.output_classes),\n nest.flatten(dataset_output_classes)):\n if iterator_class is not dataset_class:\n raise TypeError(\n \"Expected output classes %r but got dataset with output class %r.\"\n % (self.output_classes, dataset_output_classes))\n for iterator_dtype, dataset_dtype in zip(\n nest.flatten(self.output_types), nest.flatten(dataset_output_types)):\n if iterator_dtype != dataset_dtype:\n raise TypeError(\n \"Expected output types %r but got dataset with output types %r.\" %\n (self.output_types, dataset_output_types))\n for iterator_shape, dataset_shape in zip(\n nest.flatten(self.output_shapes), nest.flatten(\n dataset_output_shapes)):\n if not iterator_shape.is_compatible_with(dataset_shape):\n raise TypeError(\"Expected output shapes compatible with %r but got \"\n \"dataset with output shapes %r.\" %\n (self.output_shapes, dataset_output_shapes))\n with ops.colocate_with(self._iterator_resource):\n return gen_dataset_ops.make_iterator(\n dataset._variant_tensor, self._iterator_resource, name=name) # pylint: disable=protected-access\n\n def get_next(self, name=None):\n \"\"\"Returns a nested structure of `tf.Tensor`s representing the next element.\n\n In graph mode, you should typically call this method *once* and use its\n result as the input to another computation. A typical loop will then call\n `tf.Session.run` on the result of that computation. The loop will terminate\n when the `Iterator.get_next()` operation raises\n `tf.errors.OutOfRangeError`. The following skeleton shows how to use\n this method when building a training loop:\n\n ```python\n dataset = ... # A `tf.data.Dataset` object.\n iterator = dataset.make_initializable_iterator()\n next_element = iterator.get_next()\n\n # Build a TensorFlow graph that does something with each element.\n loss = model_function(next_element)\n optimizer = ... # A `tf.compat.v1.train.Optimizer` object.\n train_op = optimizer.minimize(loss)\n\n with tf.compat.v1.Session() as sess:\n try:\n while True:\n sess.run(train_op)\n except tf.errors.OutOfRangeError:\n pass\n ```\n\n NOTE: It is legitimate to call `Iterator.get_next()` multiple times, e.g.\n when you are distributing different elements to multiple devices in a single\n step. However, a common pitfall arises when users call `Iterator.get_next()`\n in each iteration of their training loop. `Iterator.get_next()` adds ops to\n the graph, and executing each op allocates resources (including threads); as\n a consequence, invoking it in every iteration of a training loop causes\n slowdown and eventual resource exhaustion. To guard against this outcome, we\n log a warning when the number of uses crosses a fixed threshold of\n suspiciousness.\n\n Args:\n name: (Optional.) A name for the created operation.\n\n Returns:\n A nested structure of `tf.Tensor` objects.\n \"\"\"\n self._get_next_call_count += 1\n if self._get_next_call_count > GET_NEXT_CALL_WARNING_THRESHOLD:\n warnings.warn(GET_NEXT_CALL_WARNING_MESSAGE)\n\n # pylint: disable=protected-access\n flat_ret = gen_dataset_ops.iterator_get_next(\n self._iterator_resource,\n output_types=self._flat_tensor_types,\n output_shapes=self._flat_tensor_shapes,\n name=name)\n return structure.from_tensor_list(self._element_spec, flat_ret)\n\n def string_handle(self, name=None):\n \"\"\"Returns a string-valued `tf.Tensor` that represents this iterator.\n\n Args:\n name: (Optional.) A name for the created operation.\n\n Returns:\n A scalar `tf.Tensor` of type `tf.string`.\n \"\"\"\n if name is None:\n return self._string_handle\n else:\n return gen_dataset_ops.iterator_to_string_handle(\n self._iterator_resource, name=name)\n\n @property\n @deprecation.deprecated(\n None, \"Use `tf.compat.v1.data.get_output_classes(iterator)`.\")\n def output_classes(self):\n \"\"\"Returns the class of each component of an element of this iterator.\n\n The expected values are `tf.Tensor` and `tf.SparseTensor`.\n\n Returns:\n A nested structure of Python `type` objects corresponding to each\n component of an element of this dataset.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access\n self._element_spec)\n\n @property\n @deprecation.deprecated(\n None, \"Use `tf.compat.v1.data.get_output_shapes(iterator)`.\")\n def output_shapes(self):\n \"\"\"Returns the shape of each component of an element of this iterator.\n\n Returns:\n A nested structure of `tf.TensorShape` objects corresponding to each\n component of an element of this dataset.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access\n self._element_spec)\n\n @property\n @deprecation.deprecated(\n None, \"Use `tf.compat.v1.data.get_output_types(iterator)`.\")\n def output_types(self):\n \"\"\"Returns the type of each component of an element of this iterator.\n\n Returns:\n A nested structure of `tf.DType` objects corresponding to each component\n of an element of this dataset.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access\n self._element_spec)\n\n @property\n def element_spec(self):\n \"\"\"The type specification of an element of this iterator.\n\n Returns:\n A nested structure of `tf.TypeSpec` objects matching the structure of an\n element of this iterator and specifying the type of individual components.\n \"\"\"\n return self._element_spec\n\n def _gather_saveables_for_checkpoint(self):\n\n def _saveable_factory(name):\n return _IteratorSaveable(self._iterator_resource, name)\n\n return {\"ITERATOR\": _saveable_factory}\n\n\n_uid_counter = 0\n_uid_lock = threading.Lock()\n\n\ndef _generate_shared_name(prefix):\n with _uid_lock:\n global _uid_counter\n uid = _uid_counter\n _uid_counter += 1\n return \"{}{}\".format(prefix, uid)\n\n\nclass IteratorResourceDeleter(object):\n \"\"\"An object which cleans up an iterator resource handle.\n\n An alternative to defining a __del__ method on an object. Even if the parent\n object is part of a reference cycle, the cycle will be collectable.\n \"\"\"\n\n def __init__(self, handle, device, deleter):\n self._deleter = deleter\n self._handle = handle\n self._device = device\n self._eager_mode = context.executing_eagerly()\n\n def __del__(self):\n with ops.device(self._device):\n # Make sure the resource is deleted in the same mode as it was created in.\n if self._eager_mode:\n with context.eager_mode():\n gen_dataset_ops.delete_iterator(\n handle=self._handle, deleter=self._deleter)\n else:\n with context.graph_mode():\n gen_dataset_ops.delete_iterator(\n handle=self._handle, deleter=self._deleter)\n\n\nclass OwnedIterator(trackable.Trackable, composite_tensor.CompositeTensor):\n \"\"\"An iterator producing tf.Tensor objects from a tf.data.Dataset.\n\n The iterator resource created through `OwnedIterator` is owned by the Python\n object and the life time of the underlying resource is tied to the life time\n of the `OwnedIterator` object. This makes `OwnedIterator` appropriate for use\n in eager mode and inside of tf.functions.\n \"\"\"\n\n def __init__(self, dataset=None, components=None, element_spec=None):\n \"\"\"Creates a new iterator from the given dataset.\n\n If `dataset` is not specified, the iterator will be created from the given\n tensor components and element structure. In particular, the alternative for\n constructing the iterator is used when the iterator is reconstructed from\n it `CompositeTensor` representation.\n\n Args:\n dataset: A `tf.data.Dataset` object.\n components: Tensor components to construct the iterator from.\n element_spec: A nested structure of `TypeSpec` objects that\n represents the type specification of elements of the iterator.\n\n Raises:\n ValueError: If `dataset` is not provided and either `components` or\n `element_spec` is not provided. Or `dataset` is provided and either\n `components` and `element_spec` is provided.\n \"\"\"\n\n error_message = \"Either `dataset` or both `components` and \"\n \"`element_spec` need to be provided.\"\n\n self._device = context.context().device_name\n\n if dataset is None:\n if (components is None or element_spec is None):\n raise ValueError(error_message)\n # pylint: disable=protected-access\n self._element_spec = element_spec\n self._flat_output_types = structure.get_flat_tensor_types(\n self._element_spec)\n self._flat_output_shapes = structure.get_flat_tensor_shapes(\n self._element_spec)\n self._iterator_resource, self._deleter = components\n # Delete the resource when this object is deleted\n self._resource_deleter = IteratorResourceDeleter(\n handle=self._iterator_resource,\n device=self._device,\n deleter=self._deleter)\n else:\n if (components is not None or element_spec is not None):\n raise ValueError(error_message)\n if (_device_stack_is_empty() or\n context.context().device_spec.device_type != \"CPU\"):\n with ops.device(\"/cpu:0\"):\n self._create_iterator(dataset)\n else:\n self._create_iterator(dataset)\n\n def _create_iterator(self, dataset):\n # pylint: disable=protected-access\n dataset = dataset._apply_options()\n\n # Store dataset reference to ensure that dataset is alive when this iterator\n # is being used. For example, `tf.data.Dataset.from_generator` registers\n # a few py_funcs that are needed in `self._next_internal`. If the dataset\n # is deleted, this iterator crashes on `self.__next__(...)` call.\n self._dataset = dataset\n\n ds_variant = dataset._variant_tensor\n self._element_spec = dataset.element_spec\n self._flat_output_types = structure.get_flat_tensor_types(\n self._element_spec)\n self._flat_output_shapes = structure.get_flat_tensor_shapes(\n self._element_spec)\n with ops.colocate_with(ds_variant):\n self._iterator_resource, self._deleter = (\n gen_dataset_ops.anonymous_iterator_v2(\n output_types=self._flat_output_types,\n output_shapes=self._flat_output_shapes))\n gen_dataset_ops.make_iterator(ds_variant, self._iterator_resource)\n # Delete the resource when this object is deleted\n self._resource_deleter = IteratorResourceDeleter(\n handle=self._iterator_resource,\n device=self._device,\n deleter=self._deleter)\n\n def __iter__(self):\n return self\n\n def __next__(self): # For Python 3 compatibility\n return self.next()\n\n def _next_internal(self):\n \"\"\"Returns a nested structure of `tf.Tensor`s containing the next element.\n \"\"\"\n if not context.executing_eagerly():\n with ops.device(self._device):\n ret = gen_dataset_ops.iterator_get_next(\n self._iterator_resource,\n output_types=self._flat_output_types,\n output_shapes=self._flat_output_shapes)\n return structure.from_compatible_tensor_list(self._element_spec, ret)\n\n # This runs in sync mode as iterators use an error status to communicate\n # that there is no more data to iterate over.\n # TODO(b/77291417): Fix\n with context.execution_mode(context.SYNC):\n with ops.device(self._device):\n # TODO(ashankar): Consider removing this ops.device() contextmanager\n # and instead mimic ops placement in graphs: Operations on resource\n # handles execute on the same device as where the resource is placed.\n # NOTE(mrry): Here we use the \"_sync\" variant of `iterator_get_next`\n # because in eager mode this code will run synchronously on the calling\n # thread. Therefore we do not need to make a defensive context switch\n # to a background thread, and can achieve a small constant performance\n # boost by invoking the iterator synchronously.\n ret = gen_dataset_ops.iterator_get_next_sync(\n self._iterator_resource,\n output_types=self._flat_output_types,\n output_shapes=self._flat_output_shapes)\n\n try:\n # Fast path for the case `self._structure` is not a nested structure.\n return self._element_spec._from_compatible_tensor_list(ret) # pylint: disable=protected-access\n except AttributeError:\n return structure.from_compatible_tensor_list(self._element_spec, ret)\n\n @property\n def _type_spec(self):\n return IteratorSpec(self.element_spec)\n\n def next(self):\n \"\"\"Returns a nested structure of `Tensor`s containing the next element.\"\"\"\n try:\n return self._next_internal()\n except errors.OutOfRangeError:\n raise StopIteration\n\n @property\n @deprecation.deprecated(\n None, \"Use `tf.compat.v1.data.get_output_classes(iterator)`.\")\n def output_classes(self):\n \"\"\"Returns the class of each component of an element of this iterator.\n\n The expected values are `tf.Tensor` and `tf.SparseTensor`.\n\n Returns:\n A nested structure of Python `type` objects corresponding to each\n component of an element of this dataset.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access\n self._element_spec)\n\n @property\n @deprecation.deprecated(\n None, \"Use `tf.compat.v1.data.get_output_shapes(iterator)`.\")\n def output_shapes(self):\n \"\"\"Returns the shape of each component of an element of this iterator.\n\n Returns:\n A nested structure of `tf.TensorShape` objects corresponding to each\n component of an element of this dataset.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access\n self._element_spec)\n\n @property\n @deprecation.deprecated(\n None, \"Use `tf.compat.v1.data.get_output_types(iterator)`.\")\n def output_types(self):\n \"\"\"Returns the type of each component of an element of this iterator.\n\n Returns:\n A nested structure of `tf.DType` objects corresponding to each component\n of an element of this dataset.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access\n self._element_spec)\n\n @property\n def element_spec(self):\n \"\"\"The type specification of an element of this iterator.\n\n Returns:\n A nested structure of `tf.TypeSpec` objects matching the structure of an\n element of this iterator and specifying the type of individual components.\n \"\"\"\n return self._element_spec\n\n def get_next(self, name=None):\n \"\"\"Returns a nested structure of `tf.Tensor`s containing the next element.\n\n Args:\n name: (Optional.) A name for the created operation. Currently unused.\n\n Returns:\n A nested structure of `tf.Tensor` objects.\n\n Raises:\n `tf.errors.OutOfRangeError`: If the end of the dataset has been reached.\n \"\"\"\n del name\n return self._next_internal()\n\n def _gather_saveables_for_checkpoint(self):\n\n def _saveable_factory(name):\n return _IteratorSaveable(self._iterator_resource, name)\n\n return {\"ITERATOR\": _saveable_factory}\n\n\n# TODO(jsimsa): Export this as \"tf.data.IteratorSpec\".\nclass IteratorSpec(type_spec.TypeSpec):\n \"\"\"Type specification for `OwnedIterator`.\"\"\"\n\n __slots__ = [\"_element_spec\"]\n\n def __init__(self, element_spec):\n self._element_spec = element_spec\n\n @property\n def value_type(self):\n return OwnedIterator\n\n def _serialize(self):\n return (self._element_spec,)\n\n @property\n def _component_specs(self):\n return (\n tensor_spec.TensorSpec([], dtypes.resource),\n tensor_spec.TensorSpec([], dtypes.variant),\n )\n\n def _to_components(self, value):\n return (value._iterator_resource, value._deleter) # pylint: disable=protected-access\n\n def _from_components(self, components):\n return OwnedIterator(\n dataset=None,\n components=components,\n element_spec=self._element_spec)\n\n @staticmethod\n def from_value(value):\n return IteratorSpec(value.element_spec) # pylint: disable=protected-access\n\n\n# TODO(b/71645805): Expose trackable stateful objects from dataset.\nclass _IteratorSaveable(BaseSaverBuilder.SaveableObject):\n \"\"\"SaveableObject for saving/restoring iterator state.\"\"\"\n\n def __init__(self, iterator_resource, name):\n serialized_iterator = gen_dataset_ops.serialize_iterator(iterator_resource)\n specs = [\n BaseSaverBuilder.SaveSpec(serialized_iterator, \"\", name + \"_STATE\")\n ]\n super(_IteratorSaveable, self).__init__(iterator_resource, specs, name)\n\n def restore(self, restored_tensors, restored_shapes):\n with ops.colocate_with(self.op):\n return gen_dataset_ops.deserialize_iterator(self.op, restored_tensors[0])\n\n\n@tf_export(\"data.experimental.get_next_as_optional\")\ndef get_next_as_optional(iterator):\n \"\"\"Returns an `Optional` that contains the next value from the iterator.\n\n If `iterator` has reached the end of the sequence, the returned `Optional`\n will have no value.\n\n Args:\n iterator: A `tf.compat.v1.data.Iterator` object.\n\n Returns:\n An `Optional` object representing the next value from the iterator (if it\n has one) or no value.\n \"\"\"\n # pylint: disable=protected-access\n return optional_ops._OptionalImpl(\n gen_dataset_ops.iterator_get_next_as_optional(\n iterator._iterator_resource,\n output_types=structure.get_flat_tensor_types(iterator.element_spec),\n output_shapes=structure.get_flat_tensor_shapes(\n iterator.element_spec)), iterator.element_spec)\n", "# Copyright 2016 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\"\"\"Tests for convolutional layers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras import keras_parameterized\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.platform import test\n\n\n@keras_parameterized.run_all_keras_modes\nclass Conv1DTest(keras_parameterized.TestCase):\n\n def _run_test(self, kwargs, expected_output_shape):\n num_samples = 2\n stack_size = 3\n length = 7\n\n with self.cached_session(use_gpu=True):\n testing_utils.layer_test(\n keras.layers.Conv1D,\n kwargs=kwargs,\n input_shape=(num_samples, length, stack_size),\n expected_output_shape=expected_output_shape)\n\n @parameterized.named_parameters(\n ('padding_valid', {'padding': 'valid'}, (None, 5, 2)),\n ('padding_same', {'padding': 'same'}, (None, 7, 2)),\n ('padding_same_dilation_2', {'padding': 'same', 'dilation_rate': 2},\n (None, 7, 2)),\n ('padding_same_dilation_3', {'padding': 'same', 'dilation_rate': 3},\n (None, 7, 2)),\n ('padding_causal', {'padding': 'causal'}, (None, 7, 2)),\n ('strides', {'strides': 2}, (None, 3, 2)),\n ('dilation_rate', {'dilation_rate': 2}, (None, 3, 2)),\n )\n def test_conv1d(self, kwargs, expected_output_shape):\n kwargs['filters'] = 2\n kwargs['kernel_size'] = 3\n self._run_test(kwargs, expected_output_shape)\n\n def test_conv1d_regularizers(self):\n kwargs = {\n 'filters': 3,\n 'kernel_size': 3,\n 'padding': 'valid',\n 'kernel_regularizer': 'l2',\n 'bias_regularizer': 'l2',\n 'activity_regularizer': 'l2',\n 'strides': 1\n }\n with self.cached_session(use_gpu=True):\n layer = keras.layers.Conv1D(**kwargs)\n layer.build((None, 5, 2))\n self.assertEqual(len(layer.losses), 2)\n layer(keras.backend.variable(np.ones((1, 5, 2))))\n self.assertEqual(len(layer.losses), 3)\n\n def test_conv1d_constraints(self):\n k_constraint = lambda x: x\n b_constraint = lambda x: x\n\n kwargs = {\n 'filters': 3,\n 'kernel_size': 3,\n 'padding': 'valid',\n 'kernel_constraint': k_constraint,\n 'bias_constraint': b_constraint,\n 'strides': 1\n }\n with self.cached_session(use_gpu=True):\n layer = keras.layers.Conv1D(**kwargs)\n layer.build((None, 5, 2))\n self.assertEqual(layer.kernel.constraint, k_constraint)\n self.assertEqual(layer.bias.constraint, b_constraint)\n\n\n@keras_parameterized.run_all_keras_modes\nclass Conv2DTest(keras_parameterized.TestCase):\n\n def _run_test(self, kwargs, expected_output_shape):\n num_samples = 2\n stack_size = 3\n num_row = 7\n num_col = 6\n\n with self.cached_session(use_gpu=True):\n testing_utils.layer_test(\n keras.layers.Conv2D,\n kwargs=kwargs,\n input_shape=(num_samples, num_row, num_col, stack_size),\n expected_output_shape=expected_output_shape)\n\n @parameterized.named_parameters(\n ('padding_valid', {'padding': 'valid'}, (None, 5, 4, 2)),\n ('padding_same', {'padding': 'same'}, (None, 7, 6, 2)),\n ('padding_same_dilation_2', {'padding': 'same', 'dilation_rate': 2},\n (None, 7, 6, 2)),\n ('strides', {'strides': (2, 2)}, (None, 3, 2, 2)),\n ('dilation_rate', {'dilation_rate': (2, 2)}, (None, 3, 2, 2)),\n # Only runs on GPU with CUDA, channels_first is not supported on CPU.\n # TODO(b/62340061): Support channels_first on CPU.\n ('data_format', {'data_format': 'channels_first'}),\n )\n def test_conv2d(self, kwargs, expected_output_shape=None):\n kwargs['filters'] = 2\n kwargs['kernel_size'] = (3, 3)\n if 'data_format' not in kwargs or test.is_gpu_available(cuda_only=True):\n self._run_test(kwargs, expected_output_shape)\n\n def test_conv2d_regularizers(self):\n kwargs = {\n 'filters': 3,\n 'kernel_size': 3,\n 'padding': 'valid',\n 'kernel_regularizer': 'l2',\n 'bias_regularizer': 'l2',\n 'activity_regularizer': 'l2',\n 'strides': 1\n }\n with self.cached_session(use_gpu=True):\n layer = keras.layers.Conv2D(**kwargs)\n layer.build((None, 5, 5, 2))\n self.assertEqual(len(layer.losses), 2)\n layer(keras.backend.variable(np.ones((1, 5, 5, 2))))\n self.assertEqual(len(layer.losses), 3)\n\n def test_conv2d_constraints(self):\n k_constraint = lambda x: x\n b_constraint = lambda x: x\n\n kwargs = {\n 'filters': 3,\n 'kernel_size': 3,\n 'padding': 'valid',\n 'kernel_constraint': k_constraint,\n 'bias_constraint': b_constraint,\n 'strides': 1\n }\n with self.cached_session(use_gpu=True):\n layer = keras.layers.Conv2D(**kwargs)\n layer.build((None, 5, 5, 2))\n self.assertEqual(layer.kernel.constraint, k_constraint)\n self.assertEqual(layer.bias.constraint, b_constraint)\n\n\n@keras_parameterized.run_all_keras_modes\nclass Conv3DTest(keras_parameterized.TestCase):\n\n def _run_test(self, kwargs, expected_output_shape):\n num_samples = 2\n stack_size = 3\n num_row = 7\n num_col = 6\n depth = 5\n\n with self.cached_session(use_gpu=True):\n testing_utils.layer_test(\n keras.layers.Conv3D,\n kwargs=kwargs,\n input_shape=(num_samples, depth, num_row, num_col, stack_size),\n expected_output_shape=expected_output_shape)\n\n @parameterized.named_parameters(\n ('padding_valid', {'padding': 'valid'}, (None, 3, 5, 4, 2)),\n ('padding_same', {'padding': 'same'}, (None, 5, 7, 6, 2)),\n ('strides', {'strides': (2, 2, 2)}, (None, 2, 3, 2, 2)),\n ('dilation_rate', {'dilation_rate': (2, 2, 2)}, (None, 1, 3, 2, 2)),\n # Only runs on GPU with CUDA, channels_first is not supported on CPU.\n # TODO(b/62340061): Support channels_first on CPU.\n ('data_format', {'data_format': 'channels_first'}),\n )\n def test_conv3d(self, kwargs, expected_output_shape=None):\n kwargs['filters'] = 2\n kwargs['kernel_size'] = (3, 3, 3)\n if 'data_format' not in kwargs or test.is_gpu_available(cuda_only=True):\n self._run_test(kwargs, expected_output_shape)\n\n def test_conv3d_regularizers(self):\n kwargs = {\n 'filters': 3,\n 'kernel_size': 3,\n 'padding': 'valid',\n 'kernel_regularizer': 'l2',\n 'bias_regularizer': 'l2',\n 'activity_regularizer': 'l2',\n 'strides': 1\n }\n with self.cached_session(use_gpu=True):\n layer = keras.layers.Conv3D(**kwargs)\n layer.build((None, 5, 5, 5, 2))\n self.assertEqual(len(layer.losses), 2)\n self.assertEqual(len(layer.losses), 2)\n layer(keras.backend.variable(np.ones((1, 5, 5, 5, 2))))\n self.assertEqual(len(layer.losses), 3)\n\n def test_conv3d_constraints(self):\n k_constraint = lambda x: x\n b_constraint = lambda x: x\n\n kwargs = {\n 'filters': 3,\n 'kernel_size': 3,\n 'padding': 'valid',\n 'kernel_constraint': k_constraint,\n 'bias_constraint': b_constraint,\n 'strides': 1\n }\n with self.cached_session(use_gpu=True):\n layer = keras.layers.Conv3D(**kwargs)\n layer.build((None, 5, 5, 5, 2))\n self.assertEqual(layer.kernel.constraint, k_constraint)\n self.assertEqual(layer.bias.constraint, b_constraint)\n\n def test_conv3d_dynamic_shape(self):\n input_data = np.random.random((1, 3, 3, 3, 3)).astype(np.float32)\n with self.cached_session(use_gpu=True):\n # Won't raise error here.\n testing_utils.layer_test(\n keras.layers.Conv3D,\n kwargs={\n 'data_format': 'channels_last',\n 'filters': 3,\n 'kernel_size': 3\n },\n input_shape=(None, None, None, None, 3),\n input_data=input_data)\n if test.is_gpu_available(cuda_only=True):\n testing_utils.layer_test(\n keras.layers.Conv3D,\n kwargs={\n 'data_format': 'channels_first',\n 'filters': 3,\n 'kernel_size': 3\n },\n input_shape=(None, 3, None, None, None),\n input_data=input_data)\n\n\n@keras_parameterized.run_all_keras_modes\nclass ConvSequentialTest(keras_parameterized.TestCase):\n\n def _run_test(self, conv_layer_cls, kwargs, input_shape1, input_shape2,\n expected_output_shape1, expected_output_shape2):\n kwargs['filters'] = 1\n kwargs['kernel_size'] = 3\n kwargs['dilation_rate'] = 2\n with self.cached_session(use_gpu=True):\n layer = conv_layer_cls(**kwargs)\n output1 = layer(np.zeros(input_shape1))\n self.assertEqual(output1.shape, expected_output_shape1)\n output2 = layer(np.zeros(input_shape2))\n self.assertEqual(output2.shape, expected_output_shape2)\n\n @parameterized.named_parameters(\n ('padding_valid', {'padding': 'valid'},\n (1, 8, 2), (1, 5, 2), (1, 4, 1), (1, 1, 1)),\n ('padding_same', {'padding': 'same'},\n (1, 8, 2), (1, 5, 2), (1, 8, 1), (1, 5, 1)),\n ('padding_causal', {'padding': 'causal'},\n (1, 8, 2), (1, 5, 2), (1, 8, 1), (1, 5, 1)),\n )\n def test_conv1d(self, kwargs, input_shape1, input_shape2,\n expected_output_shape1, expected_output_shape2):\n self._run_test(keras.layers.Conv1D, kwargs, input_shape1, input_shape2,\n expected_output_shape1, expected_output_shape2)\n\n @parameterized.named_parameters(\n ('padding_valid', {'padding': 'valid'},\n (1, 7, 6, 2), (1, 6, 5, 2), (1, 3, 2, 1), (1, 2, 1, 1)),\n ('padding_same', {'padding': 'same'},\n (1, 7, 6, 2), (1, 6, 5, 2), (1, 7, 6, 1), (1, 6, 5, 1)),\n )\n def test_conv2d(self, kwargs, input_shape1, input_shape2,\n expected_output_shape1, expected_output_shape2):\n self._run_test(keras.layers.Conv2D, kwargs, input_shape1, input_shape2,\n expected_output_shape1, expected_output_shape2)\n\n @parameterized.named_parameters(\n ('padding_valid', {'padding': 'valid'},\n (1, 5, 7, 6, 2), (1, 8, 6, 5, 2), (1, 1, 3, 2, 1), (1, 4, 2, 1, 1)),\n ('padding_same', {'padding': 'same'},\n (1, 5, 7, 6, 2), (1, 8, 6, 5, 2), (1, 5, 7, 6, 1), (1, 8, 6, 5, 1)),\n )\n def test_conv3d(self, kwargs, input_shape1, input_shape2,\n expected_output_shape1, expected_output_shape2):\n self._run_test(keras.layers.Conv3D, kwargs, input_shape1, input_shape2,\n expected_output_shape1, expected_output_shape2)\n\n\n@keras_parameterized.run_all_keras_modes\nclass ZeroPaddingTest(keras_parameterized.TestCase):\n\n def test_zero_padding_1d(self):\n num_samples = 2\n input_dim = 2\n num_steps = 5\n shape = (num_samples, num_steps, input_dim)\n inputs = np.ones(shape)\n\n with self.cached_session(use_gpu=True):\n # basic test\n testing_utils.layer_test(\n keras.layers.ZeroPadding1D,\n kwargs={'padding': 2},\n input_shape=inputs.shape)\n testing_utils.layer_test(\n keras.layers.ZeroPadding1D,\n kwargs={'padding': (1, 2)},\n input_shape=inputs.shape)\n\n # correctness test\n layer = keras.layers.ZeroPadding1D(padding=2)\n layer.build(shape)\n output = layer(keras.backend.variable(inputs))\n if context.executing_eagerly():\n np_output = output.numpy()\n else:\n np_output = keras.backend.eval(output)\n for offset in [0, 1, -1, -2]:\n np.testing.assert_allclose(np_output[:, offset, :], 0.)\n np.testing.assert_allclose(np_output[:, 2:-2, :], 1.)\n\n layer = keras.layers.ZeroPadding1D(padding=(1, 2))\n layer.build(shape)\n output = layer(keras.backend.variable(inputs))\n if context.executing_eagerly():\n np_output = output.numpy()\n else:\n np_output = keras.backend.eval(output)\n for left_offset in [0]:\n np.testing.assert_allclose(np_output[:, left_offset, :], 0.)\n for right_offset in [-1, -2]:\n np.testing.assert_allclose(np_output[:, right_offset, :], 0.)\n np.testing.assert_allclose(np_output[:, 1:-2, :], 1.)\n layer.get_config()\n\n # test incorrect use\n with self.assertRaises(ValueError):\n keras.layers.ZeroPadding1D(padding=(1, 1, 1))\n with self.assertRaises(ValueError):\n keras.layers.ZeroPadding1D(padding=None)\n\n def test_zero_padding_2d(self):\n num_samples = 2\n stack_size = 2\n input_num_row = 4\n input_num_col = 5\n for data_format in ['channels_first', 'channels_last']:\n inputs = np.ones((num_samples, input_num_row, input_num_col, stack_size))\n inputs = np.ones((num_samples, stack_size, input_num_row, input_num_col))\n\n # basic test\n with self.cached_session(use_gpu=True):\n testing_utils.layer_test(\n keras.layers.ZeroPadding2D,\n kwargs={'padding': (2, 2),\n 'data_format': data_format},\n input_shape=inputs.shape)\n testing_utils.layer_test(\n keras.layers.ZeroPadding2D,\n kwargs={'padding': ((1, 2), (3, 4)),\n 'data_format': data_format},\n input_shape=inputs.shape)\n\n # correctness test\n with self.cached_session(use_gpu=True):\n layer = keras.layers.ZeroPadding2D(\n padding=(2, 2), data_format=data_format)\n layer.build(inputs.shape)\n output = layer(keras.backend.variable(inputs))\n if context.executing_eagerly():\n np_output = output.numpy()\n else:\n np_output = keras.backend.eval(output)\n if data_format == 'channels_last':\n for offset in [0, 1, -1, -2]:\n np.testing.assert_allclose(np_output[:, offset, :, :], 0.)\n np.testing.assert_allclose(np_output[:, :, offset, :], 0.)\n np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, :], 1.)\n elif data_format == 'channels_first':\n for offset in [0, 1, -1, -2]:\n np.testing.assert_allclose(np_output[:, :, offset, :], 0.)\n np.testing.assert_allclose(np_output[:, :, :, offset], 0.)\n np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, :], 1.)\n\n layer = keras.layers.ZeroPadding2D(\n padding=((1, 2), (3, 4)), data_format=data_format)\n layer.build(inputs.shape)\n output = layer(keras.backend.variable(inputs))\n if context.executing_eagerly():\n np_output = output.numpy()\n else:\n np_output = keras.backend.eval(output)\n if data_format == 'channels_last':\n for top_offset in [0]:\n np.testing.assert_allclose(np_output[:, top_offset, :, :], 0.)\n for bottom_offset in [-1, -2]:\n np.testing.assert_allclose(np_output[:, bottom_offset, :, :], 0.)\n for left_offset in [0, 1, 2]:\n np.testing.assert_allclose(np_output[:, :, left_offset, :], 0.)\n for right_offset in [-1, -2, -3, -4]:\n np.testing.assert_allclose(np_output[:, :, right_offset, :], 0.)\n np.testing.assert_allclose(np_output[:, 1:-2, 3:-4, :], 1.)\n elif data_format == 'channels_first':\n for top_offset in [0]:\n np.testing.assert_allclose(np_output[:, :, top_offset, :], 0.)\n for bottom_offset in [-1, -2]:\n np.testing.assert_allclose(np_output[:, :, bottom_offset, :], 0.)\n for left_offset in [0, 1, 2]:\n np.testing.assert_allclose(np_output[:, :, :, left_offset], 0.)\n for right_offset in [-1, -2, -3, -4]:\n np.testing.assert_allclose(np_output[:, :, :, right_offset], 0.)\n np.testing.assert_allclose(np_output[:, :, 1:-2, 3:-4], 1.)\n\n # test incorrect use\n with self.assertRaises(ValueError):\n keras.layers.ZeroPadding2D(padding=(1, 1, 1))\n with self.assertRaises(ValueError):\n keras.layers.ZeroPadding2D(padding=None)\n\n def test_zero_padding_3d(self):\n num_samples = 2\n stack_size = 2\n input_len_dim1 = 4\n input_len_dim2 = 5\n input_len_dim3 = 3\n\n inputs = np.ones((num_samples, input_len_dim1, input_len_dim2,\n input_len_dim3, stack_size))\n\n with self.cached_session(use_gpu=True):\n # basic test\n testing_utils.layer_test(\n keras.layers.ZeroPadding3D,\n kwargs={'padding': (2, 2, 2)},\n input_shape=inputs.shape)\n\n # correctness test\n layer = keras.layers.ZeroPadding3D(padding=(2, 2, 2))\n layer.build(inputs.shape)\n output = layer(keras.backend.variable(inputs))\n if context.executing_eagerly():\n np_output = output.numpy()\n else:\n np_output = keras.backend.eval(output)\n for offset in [0, 1, -1, -2]:\n np.testing.assert_allclose(np_output[:, offset, :, :, :], 0.)\n np.testing.assert_allclose(np_output[:, :, offset, :, :], 0.)\n np.testing.assert_allclose(np_output[:, :, :, offset, :], 0.)\n np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, 2:-2, :], 1.)\n\n # test incorrect use\n with self.assertRaises(ValueError):\n keras.layers.ZeroPadding3D(padding=(1, 1))\n with self.assertRaises(ValueError):\n keras.layers.ZeroPadding3D(padding=None)\n\n\n@test_util.for_all_test_methods(test_util.disable_xla,\n 'align_corners=False not supported by XLA')\n@keras_parameterized.run_all_keras_modes\nclass UpSamplingTest(keras_parameterized.TestCase):\n\n def test_upsampling_1d(self):\n with self.cached_session(use_gpu=True):\n testing_utils.layer_test(\n keras.layers.UpSampling1D, kwargs={'size': 2}, input_shape=(3, 5, 4))\n\n def test_upsampling_2d(self):\n num_samples = 2\n stack_size = 2\n input_num_row = 11\n input_num_col = 12\n\n for data_format in ['channels_first', 'channels_last']:\n if data_format == 'channels_first':\n inputs = np.random.rand(num_samples, stack_size, input_num_row,\n input_num_col)\n else:\n inputs = np.random.rand(num_samples, input_num_row, input_num_col,\n stack_size)\n\n # basic test\n with self.cached_session(use_gpu=True):\n testing_utils.layer_test(\n keras.layers.UpSampling2D,\n kwargs={'size': (2, 2),\n 'data_format': data_format},\n input_shape=inputs.shape)\n\n for length_row in [2]:\n for length_col in [2, 3]:\n layer = keras.layers.UpSampling2D(\n size=(length_row, length_col), data_format=data_format)\n layer.build(inputs.shape)\n output = layer(keras.backend.variable(inputs))\n if context.executing_eagerly():\n np_output = output.numpy()\n else:\n np_output = keras.backend.eval(output)\n if data_format == 'channels_first':\n assert np_output.shape[2] == length_row * input_num_row\n assert np_output.shape[3] == length_col * input_num_col\n else: # tf\n assert np_output.shape[1] == length_row * input_num_row\n assert np_output.shape[2] == length_col * input_num_col\n\n # compare with numpy\n if data_format == 'channels_first':\n expected_out = np.repeat(inputs, length_row, axis=2)\n expected_out = np.repeat(expected_out, length_col, axis=3)\n else: # tf\n expected_out = np.repeat(inputs, length_row, axis=1)\n expected_out = np.repeat(expected_out, length_col, axis=2)\n\n np.testing.assert_allclose(np_output, expected_out)\n\n def test_upsampling_2d_bilinear(self):\n num_samples = 2\n stack_size = 2\n input_num_row = 11\n input_num_col = 12\n for data_format in ['channels_first', 'channels_last']:\n if data_format == 'channels_first':\n inputs = np.random.rand(num_samples, stack_size, input_num_row,\n input_num_col)\n else:\n inputs = np.random.rand(num_samples, input_num_row, input_num_col,\n stack_size)\n\n testing_utils.layer_test(keras.layers.UpSampling2D,\n kwargs={'size': (2, 2),\n 'data_format': data_format,\n 'interpolation': 'bilinear'},\n input_shape=inputs.shape)\n\n if not context.executing_eagerly():\n for length_row in [2]:\n for length_col in [2, 3]:\n layer = keras.layers.UpSampling2D(\n size=(length_row, length_col),\n data_format=data_format)\n layer.build(inputs.shape)\n outputs = layer(keras.backend.variable(inputs))\n np_output = keras.backend.eval(outputs)\n if data_format == 'channels_first':\n self.assertEqual(np_output.shape[2], length_row * input_num_row)\n self.assertEqual(np_output.shape[3], length_col * input_num_col)\n else:\n self.assertEqual(np_output.shape[1], length_row * input_num_row)\n self.assertEqual(np_output.shape[2], length_col * input_num_col)\n\n def test_upsampling_3d(self):\n num_samples = 2\n stack_size = 2\n input_len_dim1 = 10\n input_len_dim2 = 11\n input_len_dim3 = 12\n\n for data_format in ['channels_first', 'channels_last']:\n if data_format == 'channels_first':\n inputs = np.random.rand(num_samples, stack_size, input_len_dim1,\n input_len_dim2, input_len_dim3)\n else:\n inputs = np.random.rand(num_samples, input_len_dim1, input_len_dim2,\n input_len_dim3, stack_size)\n\n # basic test\n with self.cached_session(use_gpu=True):\n testing_utils.layer_test(\n keras.layers.UpSampling3D,\n kwargs={'size': (2, 2, 2),\n 'data_format': data_format},\n input_shape=inputs.shape)\n\n for length_dim1 in [2, 3]:\n for length_dim2 in [2]:\n for length_dim3 in [3]:\n layer = keras.layers.UpSampling3D(\n size=(length_dim1, length_dim2, length_dim3),\n data_format=data_format)\n layer.build(inputs.shape)\n output = layer(keras.backend.variable(inputs))\n if context.executing_eagerly():\n np_output = output.numpy()\n else:\n np_output = keras.backend.eval(output)\n if data_format == 'channels_first':\n assert np_output.shape[2] == length_dim1 * input_len_dim1\n assert np_output.shape[3] == length_dim2 * input_len_dim2\n assert np_output.shape[4] == length_dim3 * input_len_dim3\n else: # tf\n assert np_output.shape[1] == length_dim1 * input_len_dim1\n assert np_output.shape[2] == length_dim2 * input_len_dim2\n assert np_output.shape[3] == length_dim3 * input_len_dim3\n\n # compare with numpy\n if data_format == 'channels_first':\n expected_out = np.repeat(inputs, length_dim1, axis=2)\n expected_out = np.repeat(expected_out, length_dim2, axis=3)\n expected_out = np.repeat(expected_out, length_dim3, axis=4)\n else: # tf\n expected_out = np.repeat(inputs, length_dim1, axis=1)\n expected_out = np.repeat(expected_out, length_dim2, axis=2)\n expected_out = np.repeat(expected_out, length_dim3, axis=3)\n\n np.testing.assert_allclose(np_output, expected_out)\n\n\n@keras_parameterized.run_all_keras_modes\nclass CroppingTest(keras_parameterized.TestCase):\n\n def test_cropping_1d(self):\n num_samples = 2\n time_length = 4\n input_len_dim1 = 2\n inputs = np.random.rand(num_samples, time_length, input_len_dim1)\n\n with self.cached_session(use_gpu=True):\n testing_utils.layer_test(\n keras.layers.Cropping1D,\n kwargs={'cropping': (2, 2)},\n input_shape=inputs.shape)\n\n # test incorrect use\n with self.assertRaises(ValueError):\n keras.layers.Cropping1D(cropping=(1, 1, 1))\n with self.assertRaises(ValueError):\n keras.layers.Cropping1D(cropping=None)\n\n def test_cropping_2d(self):\n num_samples = 2\n stack_size = 2\n input_len_dim1 = 9\n input_len_dim2 = 9\n cropping = ((2, 2), (3, 3))\n\n for data_format in ['channels_first', 'channels_last']:\n if data_format == 'channels_first':\n inputs = np.random.rand(num_samples, stack_size, input_len_dim1,\n input_len_dim2)\n else:\n inputs = np.random.rand(num_samples, input_len_dim1, input_len_dim2,\n stack_size)\n with self.cached_session(use_gpu=True):\n # basic test\n testing_utils.layer_test(\n keras.layers.Cropping2D,\n kwargs={'cropping': cropping,\n 'data_format': data_format},\n input_shape=inputs.shape)\n # correctness test\n layer = keras.layers.Cropping2D(\n cropping=cropping, data_format=data_format)\n layer.build(inputs.shape)\n output = layer(keras.backend.variable(inputs))\n if context.executing_eagerly():\n np_output = output.numpy()\n else:\n np_output = keras.backend.eval(output)\n # compare with numpy\n if data_format == 'channels_first':\n expected_out = inputs[:, :, cropping[0][0]:-cropping[0][1], cropping[\n 1][0]:-cropping[1][1]]\n else:\n expected_out = inputs[:, cropping[0][0]:-cropping[0][1], cropping[1][\n 0]:-cropping[1][1], :]\n np.testing.assert_allclose(np_output, expected_out)\n\n for data_format in ['channels_first', 'channels_last']:\n if data_format == 'channels_first':\n inputs = np.random.rand(num_samples, stack_size, input_len_dim1,\n input_len_dim2)\n else:\n inputs = np.random.rand(num_samples, input_len_dim1, input_len_dim2,\n stack_size)\n # another correctness test (no cropping)\n with self.cached_session(use_gpu=True):\n cropping = ((0, 0), (0, 0))\n layer = keras.layers.Cropping2D(\n cropping=cropping, data_format=data_format)\n layer.build(inputs.shape)\n output = layer(keras.backend.variable(inputs))\n if context.executing_eagerly():\n np_output = output.numpy()\n else:\n np_output = keras.backend.eval(output)\n # compare with input\n np.testing.assert_allclose(np_output, inputs)\n\n # test incorrect use\n with self.assertRaises(ValueError):\n keras.layers.Cropping2D(cropping=(1, 1, 1))\n with self.assertRaises(ValueError):\n keras.layers.Cropping2D(cropping=None)\n\n def test_cropping_3d(self):\n num_samples = 2\n stack_size = 2\n input_len_dim1 = 8\n input_len_dim2 = 8\n input_len_dim3 = 8\n croppings = [((2, 2), (1, 1), (2, 3)), 3, (0, 1, 1)]\n\n for cropping in croppings:\n for data_format in ['channels_last', 'channels_first']:\n if data_format == 'channels_first':\n inputs = np.random.rand(num_samples, stack_size, input_len_dim1,\n input_len_dim2, input_len_dim3)\n else:\n inputs = np.random.rand(num_samples, input_len_dim1, input_len_dim2,\n input_len_dim3, stack_size)\n # basic test\n with self.cached_session(use_gpu=True):\n testing_utils.layer_test(\n keras.layers.Cropping3D,\n kwargs={'cropping': cropping,\n 'data_format': data_format},\n input_shape=inputs.shape)\n\n if len(croppings) == 3 and len(croppings[0]) == 2:\n # correctness test\n with self.cached_session(use_gpu=True):\n layer = keras.layers.Cropping3D(\n cropping=cropping, data_format=data_format)\n layer.build(inputs.shape)\n output = layer(keras.backend.variable(inputs))\n if context.executing_eagerly():\n np_output = output.numpy()\n else:\n np_output = keras.backend.eval(output)\n # compare with numpy\n if data_format == 'channels_first':\n expected_out = inputs[:, :,\n cropping[0][0]:-cropping[0][1],\n cropping[1][0]:-cropping[1][1],\n cropping[2][0]:-cropping[2][1]]\n else:\n expected_out = inputs[:,\n cropping[0][0]:-cropping[0][1],\n cropping[1][0]:-cropping[1][1],\n cropping[2][0]:-cropping[2][1], :]\n np.testing.assert_allclose(np_output, expected_out)\n\n # test incorrect use\n with self.assertRaises(ValueError):\n keras.layers.Cropping3D(cropping=(1, 1))\n with self.assertRaises(ValueError):\n keras.layers.Cropping3D(cropping=None)\n\n\n@keras_parameterized.run_all_keras_modes\nclass DepthwiseConv2DTest(keras_parameterized.TestCase):\n\n def _run_test(self, kwargs):\n num_samples = 2\n stack_size = 3\n num_row = 7\n num_col = 6\n\n with self.cached_session(use_gpu=True):\n testing_utils.layer_test(\n keras.layers.DepthwiseConv2D,\n kwargs=kwargs,\n input_shape=(num_samples, num_row, num_col, stack_size))\n\n @parameterized.named_parameters(\n ('padding_valid', {'padding': 'valid'}),\n ('padding_same', {'padding': 'same'}),\n ('strides', {'strides': (2, 2)}),\n # Only runs on GPU with CUDA, channels_first is not supported on CPU.\n # TODO(b/62340061): Support channels_first on CPU.\n ('data_format', {'data_format': 'channels_first'}),\n ('depth_multiplier_1', {'depth_multiplier': 1}),\n ('depth_multiplier_2', {'depth_multiplier': 2}),\n )\n def test_depthwise_conv2d(self, kwargs):\n kwargs['kernel_size'] = (3, 3)\n if 'data_format' not in kwargs or test.is_gpu_available(cuda_only=True):\n self._run_test(kwargs)\n\n def test_depthwise_conv2d_full(self):\n kwargs = {\n 'kernel_size': 3,\n 'padding': 'valid',\n 'data_format': 'channels_last',\n 'activation': None,\n 'depthwise_regularizer': 'l2',\n 'bias_regularizer': 'l2',\n 'activity_regularizer': 'l2',\n 'depthwise_constraint': 'unit_norm',\n 'use_bias': True,\n 'strides': (2, 2),\n 'depth_multiplier': 1,\n }\n self._run_test(kwargs)\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"`LinearOperator` acting like a Householder transformation.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.linalg import linalg_impl as linalg\nfrom tensorflow.python.ops.linalg import linear_operator\nfrom tensorflow.python.ops.linalg import linear_operator_util\nfrom tensorflow.python.util.tf_export import tf_export\n\n__all__ = [\"LinearOperatorHouseholder\",]\n\n\n@tf_export(\"linalg.LinearOperatorHouseholder\")\nclass LinearOperatorHouseholder(linear_operator.LinearOperator):\n \"\"\"`LinearOperator` acting like a [batch] of Householder transformations.\n\n This operator acts like a [batch] of householder reflections with shape\n `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a\n batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is\n an `N x N` matrix. This matrix `A` is not materialized, but for\n purposes of broadcasting this shape will be relevant.\n\n `LinearOperatorHouseholder` is initialized with a (batch) vector.\n\n A Householder reflection, defined via a vector `v`, which reflects points\n in `R^n` about the hyperplane orthogonal to `v` and through the origin.\n\n ```python\n # Create a 2 x 2 householder transform.\n vec = [1 / np.sqrt(2), 1. / np.sqrt(2)]\n operator = LinearOperatorHouseholder(vec)\n\n operator.to_dense()\n ==> [[0., -1.]\n [-1., -0.]]\n\n operator.shape\n ==> [2, 2]\n\n operator.log_abs_determinant()\n ==> scalar Tensor\n\n x = ... Shape [2, 4] Tensor\n operator.matmul(x)\n ==> Shape [2, 4] Tensor\n\n #### Shape compatibility\n\n This operator acts on [batch] matrix with compatible shape.\n `x` is a batch matrix with compatible shape for `matmul` and `solve` if\n\n ```\n operator.shape = [B1,...,Bb] + [N, N], with b >= 0\n x.shape = [C1,...,Cc] + [N, R],\n and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd]\n ```\n\n #### Matrix property hints\n\n This `LinearOperator` is initialized with boolean flags of the form `is_X`,\n for `X = non_singular, self_adjoint, positive_definite, square`.\n These have the following meaning:\n\n * If `is_X == True`, callers should expect the operator to have the\n property `X`. This is a promise that should be fulfilled, but is *not* a\n runtime assert. For example, finite floating point precision may result\n in these promises being violated.\n * If `is_X == False`, callers should expect the operator to not have `X`.\n * If `is_X == None` (the default), callers should have no expectation either\n way.\n \"\"\"\n\n def __init__(self,\n reflection_axis,\n is_non_singular=None,\n is_self_adjoint=None,\n is_positive_definite=None,\n is_square=None,\n name=\"LinearOperatorHouseholder\"):\n r\"\"\"Initialize a `LinearOperatorHouseholder`.\n\n Args:\n reflection_axis: Shape `[B1,...,Bb, N]` `Tensor` with `b >= 0` `N >= 0`.\n The vector defining the hyperplane to reflect about.\n Allowed dtypes: `float16`, `float32`, `float64`, `complex64`,\n `complex128`.\n is_non_singular: Expect that this operator is non-singular.\n is_self_adjoint: Expect that this operator is equal to its hermitian\n transpose. This is autoset to true\n is_positive_definite: Expect that this operator is positive definite,\n meaning the quadratic form `x^H A x` has positive real part for all\n nonzero `x`. Note that we do not require the operator to be\n self-adjoint to be positive-definite. See:\n https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices\n This is autoset to false.\n is_square: Expect that this operator acts like square [batch] matrices.\n This is autoset to true.\n name: A name for this `LinearOperator`.\n\n Raises:\n ValueError: `is_self_adjoint` is not `True`, `is_positive_definite` is\n not `False` or `is_square` is not `True`.\n \"\"\"\n\n with ops.name_scope(name, values=[reflection_axis]):\n self._reflection_axis = linear_operator_util.convert_nonref_to_tensor(\n reflection_axis, name=\"reflection_axis\")\n self._check_reflection_axis(self._reflection_axis)\n\n # Check and auto-set hints.\n if is_self_adjoint is False: # pylint:disable=g-bool-id-comparison\n raise ValueError(\"A Householder operator is always self adjoint.\")\n else:\n is_self_adjoint = True\n\n if is_positive_definite is True: # pylint:disable=g-bool-id-comparison\n raise ValueError(\n \"A Householder operator is always non-positive definite.\")\n else:\n is_positive_definite = False\n\n if is_square is False: # pylint:disable=g-bool-id-comparison\n raise ValueError(\"A Householder operator is always square.\")\n is_square = True\n\n super(LinearOperatorHouseholder, self).__init__(\n dtype=self._reflection_axis.dtype,\n graph_parents=None,\n is_non_singular=is_non_singular,\n is_self_adjoint=is_self_adjoint,\n is_positive_definite=is_positive_definite,\n is_square=is_square,\n name=name)\n # TODO(b/143910018) Remove graph_parents in V3.\n self._set_graph_parents([self._reflection_axis])\n\n def _check_reflection_axis(self, reflection_axis):\n \"\"\"Static check of reflection_axis.\"\"\"\n if (reflection_axis.shape.ndims is not None and\n reflection_axis.shape.ndims < 1):\n raise ValueError(\n \"Argument reflection_axis must have at least 1 dimension. \"\n \"Found: %s\" % reflection_axis)\n\n def _shape(self):\n # If d_shape = [5, 3], we return [5, 3, 3].\n d_shape = self._reflection_axis.shape\n return d_shape.concatenate(d_shape[-1:])\n\n def _shape_tensor(self):\n d_shape = array_ops.shape(self._reflection_axis)\n k = d_shape[-1]\n return array_ops.concat((d_shape, [k]), 0)\n\n def _assert_non_singular(self):\n return control_flow_ops.no_op(\"assert_non_singular\")\n\n def _assert_positive_definite(self):\n raise errors.InvalidArgumentError(\n node_def=None, op=None, message=\"Householder operators are always \"\n \"non-positive definite.\")\n\n def _assert_self_adjoint(self):\n return control_flow_ops.no_op(\"assert_self_adjoint\")\n\n def _matmul(self, x, adjoint=False, adjoint_arg=False):\n # Given a vector `v`, we would like to reflect `x` about the hyperplane\n # orthogonal to `v` going through the origin. We first project `x` to `v`\n # to get v * dot(v, x) / dot(v, v). After we project, we can reflect the\n # projection about the hyperplane by flipping sign to get\n # -v * dot(v, x) / dot(v, v). Finally, we can add back the component\n # that is orthogonal to v. This is invariant under reflection, since the\n # whole hyperplane is invariant. This component is equal to x - v * dot(v,\n # x) / dot(v, v), giving the formula x - 2 * v * dot(v, x) / dot(v, v)\n # for the reflection.\n\n # Note that because this is a reflection, it lies in O(n) (for real vector\n # spaces) or U(n) (for complex vector spaces), and thus is its own adjoint.\n reflection_axis = ops.convert_to_tensor(self.reflection_axis)\n x = linalg.adjoint(x) if adjoint_arg else x\n normalized_axis = reflection_axis / linalg.norm(\n reflection_axis, axis=-1, keepdims=True)\n mat = normalized_axis[..., array_ops.newaxis]\n x_dot_normalized_v = math_ops.matmul(mat, x, adjoint_a=True)\n\n return x - 2 * mat * x_dot_normalized_v\n\n def _trace(self):\n # We have (n - 1) +1 eigenvalues and a single -1 eigenvalue.\n shape = self.shape_tensor()\n return math_ops.cast(\n self._domain_dimension_tensor(shape=shape) - 2,\n self.dtype) * array_ops.ones(\n shape=self._batch_shape_tensor(shape=shape), dtype=self.dtype)\n\n def _determinant(self):\n # For householder transformations, the determinant is -1.\n return -array_ops.ones(shape=self.batch_shape_tensor(), dtype=self.dtype)\n\n def _log_abs_determinant(self):\n # Orthogonal matrix -> log|Q| = 0.\n return array_ops.zeros(shape=self.batch_shape_tensor(), dtype=self.dtype)\n\n def _solve(self, rhs, adjoint=False, adjoint_arg=False):\n # A householder reflection is a reflection, hence is idempotent. Thus we\n # can just apply a matmul.\n return self._matmul(rhs, adjoint, adjoint_arg)\n\n def _to_dense(self):\n reflection_axis = ops.convert_to_tensor(self.reflection_axis)\n normalized_axis = reflection_axis / linalg.norm(\n reflection_axis, axis=-1, keepdims=True)\n mat = normalized_axis[..., array_ops.newaxis]\n matrix = -2 * math_ops.matmul(mat, mat, adjoint_b=True)\n return array_ops.matrix_set_diag(\n matrix, 1. + array_ops.matrix_diag_part(matrix))\n\n def _diag_part(self):\n reflection_axis = ops.convert_to_tensor(self.reflection_axis)\n normalized_axis = reflection_axis / linalg.norm(\n reflection_axis, axis=-1, keepdims=True)\n return 1. - 2 * normalized_axis * math_ops.conj(normalized_axis)\n\n def _eigvals(self):\n # We have (n - 1) +1 eigenvalues and a single -1 eigenvalue.\n result_shape = array_ops.shape(self.reflection_axis)\n n = result_shape[-1]\n ones_shape = array_ops.concat([result_shape[:-1], [n - 1]], axis=-1)\n neg_shape = array_ops.concat([result_shape[:-1], [1]], axis=-1)\n eigvals = array_ops.ones(shape=ones_shape, dtype=self.dtype)\n eigvals = array_ops.concat(\n [-array_ops.ones(shape=neg_shape, dtype=self.dtype), eigvals], axis=-1)\n return eigvals\n\n @property\n def reflection_axis(self):\n return self._reflection_axis\n", "# Copyright 2016 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\"\"\"Tests for layer graphs construction & handling.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras import keras_parameterized\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.keras.engine import base_layer\nfrom tensorflow.python.keras.engine import input_layer as input_layer_lib\nfrom tensorflow.python.keras.engine import network as network_lib\nfrom tensorflow.python.keras.engine import training\nfrom tensorflow.python.keras.utils import layer_utils\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training.tracking.util import Checkpoint\n\ntry:\n import yaml # pylint:disable=g-import-not-at-top\nexcept ImportError:\n yaml = None\n\n\nclass NetworkConstructionTest(keras_parameterized.TestCase):\n\n @test_util.run_deprecated_v1\n def test_get_updates(self):\n\n class MyLayer(keras.layers.Layer):\n\n def build(self, input_shape):\n self.a = self.add_variable('a',\n (1, 1),\n 'float32',\n trainable=False)\n self.b = self.add_variable('b',\n (1, 1),\n 'float32',\n trainable=False)\n self.add_update(state_ops.assign_add(self.a, [[1.]],\n name='unconditional_update'))\n self.built = True\n\n def call(self, inputs):\n self.add_update(state_ops.assign_add(self.b, inputs,\n name='conditional_update'),\n inputs=True)\n return inputs + 1\n\n x1 = input_layer_lib.Input(shape=(1,))\n layer = MyLayer()\n _ = layer(x1)\n\n self.assertEqual(len(layer.updates), 2)\n self.assertEqual(len(layer.get_updates_for(x1)), 1)\n self.assertEqual(len(layer.get_updates_for(None)), 1)\n\n x2 = input_layer_lib.Input(shape=(1,))\n y2 = layer(x2)\n\n self.assertEqual(len(layer.updates), 3)\n self.assertEqual(len(layer.get_updates_for(x1)), 1)\n self.assertEqual(len(layer.get_updates_for(x2)), 1)\n self.assertEqual(len(layer.get_updates_for(None)), 1)\n\n network = network_lib.Network(x2, y2)\n self.assertEqual(len(network.updates), 3)\n self.assertEqual(len(network.get_updates_for(x2)), 1)\n self.assertEqual(len(network.get_updates_for(None)), 1)\n\n x3 = input_layer_lib.Input(shape=(1,))\n _ = layer(x3)\n self.assertEqual(len(network.updates), 4)\n\n x4 = input_layer_lib.Input(shape=(1,))\n _ = network(x4)\n self.assertEqual(len(network.updates), 5)\n self.assertEqual(len(network.get_updates_for(x2)), 1)\n self.assertEqual(len(network.get_updates_for(x4)), 1)\n self.assertEqual(len(network.get_updates_for(None)), 1)\n\n network.add_update(state_ops.assign_add(layer.a, [[1]]))\n self.assertEqual(len(network.updates), 6)\n self.assertEqual(len(network.get_updates_for(None)), 2)\n\n network.add_update(state_ops.assign_add(layer.b, x4), inputs=True)\n self.assertEqual(len(network.updates), 7)\n self.assertEqual(len(network.get_updates_for(x4)), 2)\n\n @test_util.run_in_graph_and_eager_modes()\n def test_get_updates_bn(self):\n x1 = input_layer_lib.Input(shape=(1,))\n layer = keras.layers.BatchNormalization()\n _ = layer(x1)\n\n self.assertEqual(len(layer.updates), 2)\n self.assertEqual(len(layer.get_updates_for(x1)), 2)\n self.assertEqual(len(layer.get_updates_for(None)), 0)\n\n @test_util.run_deprecated_v1\n def test_get_losses(self):\n\n class MyLayer(keras.layers.Layer):\n\n def build(self, input_shape):\n self.a = self.add_variable('a',\n (1, 1),\n 'float32',\n trainable=False)\n self.b = self.add_variable('b',\n (1, 1),\n 'float32',\n trainable=False)\n self.add_loss(math_ops.reduce_sum(self.a))\n self.built = True\n\n def call(self, inputs):\n self.add_loss(math_ops.reduce_sum(inputs),\n inputs=True)\n return inputs + 1\n\n x1 = input_layer_lib.Input(shape=(1,))\n layer = MyLayer()\n _ = layer(x1)\n\n self.assertEqual(len(layer.losses), 2)\n self.assertEqual(len(layer.get_losses_for(x1)), 1)\n self.assertEqual(len(layer.get_losses_for(None)), 1)\n\n x2 = input_layer_lib.Input(shape=(1,))\n y2 = layer(x2)\n\n self.assertEqual(len(layer.losses), 3)\n self.assertEqual(len(layer.get_losses_for(x1)), 1)\n self.assertEqual(len(layer.get_losses_for(x2)), 1)\n self.assertEqual(len(layer.get_losses_for(None)), 1)\n\n network = network_lib.Network(x2, y2)\n self.assertEqual(len(network.losses), 3)\n self.assertEqual(len(network.get_losses_for(x1)), 1)\n self.assertEqual(len(network.get_losses_for(x2)), 1)\n self.assertEqual(len(network.get_losses_for(None)), 1)\n\n x3 = input_layer_lib.Input(shape=(1,))\n _ = layer(x3)\n self.assertEqual(len(network.losses), 4)\n\n x4 = input_layer_lib.Input(shape=(1,))\n _ = network(x4)\n self.assertEqual(len(network.losses), 5)\n self.assertEqual(len(network.get_losses_for(x2)), 1)\n self.assertEqual(len(network.get_losses_for(x4)), 1)\n self.assertEqual(len(network.get_losses_for(None)), 1)\n\n @test_util.run_in_graph_and_eager_modes()\n def testTopologicalAttributes(self):\n # test layer attributes / methods related to cross-layer connectivity.\n a = input_layer_lib.Input(shape=(32,), name='input_a')\n b = input_layer_lib.Input(shape=(32,), name='input_b')\n\n # test input, output, input_shape, output_shape\n test_layer = keras.layers.Dense(16, name='test_layer')\n a_test = test_layer(a)\n self.assertIs(test_layer.input, a)\n self.assertIs(test_layer.output, a_test)\n self.assertEqual(test_layer.input_shape, (None, 32))\n self.assertEqual(test_layer.output_shape, (None, 16))\n\n # test `get_*_at` methods\n dense = keras.layers.Dense(16, name='dense_1')\n a_2 = dense(a)\n b_2 = dense(b)\n\n self.assertIs(dense.get_input_at(0), a)\n self.assertIs(dense.get_input_at(1), b)\n self.assertIs(dense.get_output_at(0), a_2)\n self.assertIs(dense.get_output_at(1), b_2)\n self.assertEqual(dense.get_input_shape_at(0), (None, 32))\n self.assertEqual(dense.get_input_shape_at(1), (None, 32))\n self.assertEqual(dense.get_output_shape_at(0), (None, 16))\n self.assertEqual(dense.get_output_shape_at(1), (None, 16))\n\n # Test invalid value for attribute retrieval.\n with self.assertRaises(ValueError):\n dense.get_input_at(2)\n with self.assertRaises(AttributeError):\n new_dense = keras.layers.Dense(16)\n _ = new_dense.input\n with self.assertRaises(AttributeError):\n new_dense = keras.layers.Dense(16)\n _ = new_dense.output\n with self.assertRaises(AttributeError):\n new_dense = keras.layers.Dense(16)\n _ = new_dense.output_shape\n with self.assertRaises(AttributeError):\n new_dense = keras.layers.Dense(16)\n _ = new_dense.input_shape\n with self.assertRaises(AttributeError):\n new_dense = keras.layers.Dense(16)\n a = input_layer_lib.Input(shape=(3, 32))\n a = input_layer_lib.Input(shape=(5, 32))\n a_2 = dense(a)\n b_2 = dense(b)\n _ = new_dense.input_shape\n with self.assertRaises(AttributeError):\n new_dense = keras.layers.Dense(16)\n a = input_layer_lib.Input(shape=(3, 32))\n a = input_layer_lib.Input(shape=(5, 32))\n a_2 = dense(a)\n b_2 = dense(b)\n _ = new_dense.output_shape\n\n def _assertAllIs(self, a, b):\n self.assertTrue(all(x is y for x, y in zip(a, b)))\n\n @test_util.run_in_graph_and_eager_modes()\n def testTopologicalAttributesMultiOutputLayer(self):\n\n class PowersLayer(keras.layers.Layer):\n\n def call(self, inputs):\n return [inputs**2, inputs**3]\n\n x = input_layer_lib.Input(shape=(32,))\n test_layer = PowersLayer()\n p1, p2 = test_layer(x) # pylint: disable=not-callable\n\n self.assertIs(test_layer.input, x)\n self._assertAllIs(test_layer.output, [p1, p2])\n self.assertEqual(test_layer.input_shape, (None, 32))\n self.assertEqual(test_layer.output_shape, [(None, 32), (None, 32)])\n\n @test_util.run_in_graph_and_eager_modes()\n def testTopologicalAttributesMultiInputLayer(self):\n\n class AddLayer(keras.layers.Layer):\n\n def call(self, inputs):\n assert len(inputs) == 2\n return inputs[0] + inputs[1]\n\n a = input_layer_lib.Input(shape=(32,))\n b = input_layer_lib.Input(shape=(32,))\n test_layer = AddLayer()\n y = test_layer([a, b]) # pylint: disable=not-callable\n\n self._assertAllIs(test_layer.input, [a, b])\n self.assertIs(test_layer.output, y)\n self.assertEqual(test_layer.input_shape, [(None, 32), (None, 32)])\n self.assertEqual(test_layer.output_shape, (None, 32))\n\n @test_util.run_deprecated_v1\n def testBasicNetwork(self):\n # minimum viable network\n x = input_layer_lib.Input(shape=(32,))\n dense = keras.layers.Dense(2)\n y = dense(x)\n network = network_lib.Network(x, y, name='dense_network')\n\n # test basic attributes\n self.assertEqual(network.name, 'dense_network')\n self.assertEqual(len(network.layers), 2) # InputLayer + Dense\n self.assertEqual(network.layers[1], dense)\n self._assertAllIs(network.weights, dense.weights)\n self._assertAllIs(network.trainable_weights, dense.trainable_weights)\n self._assertAllIs(network.non_trainable_weights,\n dense.non_trainable_weights)\n\n # test callability on Input\n x_2 = input_layer_lib.Input(shape=(32,))\n y_2 = network(x_2)\n self.assertEqual(y_2.shape.as_list(), [None, 2])\n\n # test callability on regular tensor\n x_2 = array_ops.placeholder(dtype='float32', shape=(None, 32))\n y_2 = network(x_2)\n self.assertEqual(y_2.shape.as_list(), [None, 2])\n\n # test network `trainable` attribute\n network.trainable = False\n self._assertAllIs(network.weights, dense.weights)\n self.assertEqual(network.trainable_weights, [])\n self._assertAllIs(network.non_trainable_weights,\n dense.trainable_weights + dense.non_trainable_weights)\n\n @test_util.run_in_graph_and_eager_modes\n def test_trainable_weights(self):\n a = keras.layers.Input(shape=(2,))\n b = keras.layers.Dense(1)(a)\n model = keras.models.Model(a, b)\n\n weights = model.weights\n self._assertAllIs(model.trainable_weights, weights)\n self.assertListEqual(model.non_trainable_weights, [])\n\n model.trainable = False\n self.assertListEqual(model.trainable_weights, [])\n self._assertAllIs(model.non_trainable_weights, weights)\n\n model.trainable = True\n self._assertAllIs(model.trainable_weights, weights)\n self.assertListEqual(model.non_trainable_weights, [])\n\n model.layers[1].trainable = False\n self.assertListEqual(model.trainable_weights, [])\n self._assertAllIs(model.non_trainable_weights, weights)\n\n # sequential model\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(1, input_dim=2))\n weights = model.weights\n\n self._assertAllIs(model.trainable_weights, weights)\n self.assertListEqual(model.non_trainable_weights, [])\n\n model.trainable = False\n self.assertListEqual(model.trainable_weights, [])\n self._assertAllIs(model.non_trainable_weights, weights)\n\n model.trainable = True\n self._assertAllIs(model.trainable_weights, weights)\n self.assertListEqual(model.non_trainable_weights, [])\n\n model.layers[0].trainable = False\n self.assertListEqual(model.trainable_weights, [])\n self._assertAllIs(model.non_trainable_weights, weights)\n\n @test_util.run_deprecated_v1\n def test_layer_call_arguments(self):\n # Test the ability to pass and serialize arguments to `call`.\n inp = keras.layers.Input(shape=(2,))\n x = keras.layers.Dense(3)(inp)\n x = keras.layers.Dropout(0.5)(x, training=True)\n model = keras.models.Model(inp, x)\n # Would be `dropout/cond/Merge` by default\n self.assertTrue(model.output.op.name.endswith('dropout/mul_1'))\n\n # Test that argument is kept when applying the model\n inp2 = keras.layers.Input(shape=(2,))\n out2 = model(inp2)\n self.assertTrue(out2.op.name.endswith('dropout/mul_1'))\n\n # Test that argument is kept after loading a model\n config = model.get_config()\n model = keras.models.Model.from_config(config)\n self.assertTrue(model.output.op.name.endswith('dropout/mul_1'))\n\n def test_node_construction(self):\n # test basics\n a = keras.layers.Input(shape=(32,), name='input_a')\n b = keras.layers.Input(shape=(32,), name='input_b')\n\n with self.assertRaises(ValueError):\n _ = keras.layers.Input(shape=(32,), batch_shape=(10, 32))\n with self.assertRaises(ValueError):\n _ = keras.layers.Input(shape=(32,), unknown_kwarg=None)\n\n self.assertListEqual(a.shape.as_list(), [None, 32])\n a_layer, a_node_index, a_tensor_index = a._keras_history\n b_layer, _, _ = b._keras_history\n self.assertEqual(len(a_layer._inbound_nodes), 1)\n self.assertEqual(a_tensor_index, 0)\n node = a_layer._inbound_nodes[a_node_index]\n self.assertEqual(node.outbound_layer, a_layer)\n\n self.assertListEqual(node.inbound_layers, [])\n self.assertListEqual(node.input_tensors, [a])\n self.assertListEqual(node.input_shapes, [(None, 32)])\n self.assertListEqual(node.output_tensors, [a])\n self.assertListEqual(node.output_shapes, [(None, 32)])\n\n dense = keras.layers.Dense(16, name='dense_1')\n a_2 = dense(a)\n b_2 = dense(b)\n\n self.assertEqual(len(dense._inbound_nodes), 2)\n self.assertEqual(len(dense._outbound_nodes), 0)\n self.assertEqual(dense._inbound_nodes[0].inbound_layers, a_layer)\n self.assertEqual(dense._inbound_nodes[0].outbound_layer, dense)\n self.assertEqual(dense._inbound_nodes[1].inbound_layers, b_layer)\n self.assertEqual(dense._inbound_nodes[1].outbound_layer, dense)\n self.assertIs(dense._inbound_nodes[0].input_tensors, a)\n self.assertIs(dense._inbound_nodes[1].input_tensors, b)\n\n # test layer properties\n test_layer = keras.layers.Dense(16, name='test_layer')\n a_test = test_layer(a)\n self.assertListEqual(test_layer.kernel.shape.as_list(), [32, 16])\n self.assertIs(test_layer.input, a)\n self.assertIs(test_layer.output, a_test)\n self.assertEqual(test_layer.input_shape, (None, 32))\n self.assertEqual(test_layer.output_shape, (None, 16))\n\n self.assertIs(dense.get_input_at(0), a)\n self.assertIs(dense.get_input_at(1), b)\n self.assertIs(dense.get_output_at(0), a_2)\n self.assertIs(dense.get_output_at(1), b_2)\n self.assertEqual(dense.get_input_shape_at(0), (None, 32))\n self.assertEqual(dense.get_input_shape_at(1), (None, 32))\n self.assertEqual(dense.get_output_shape_at(0), (None, 16))\n self.assertEqual(dense.get_output_shape_at(1), (None, 16))\n self.assertEqual(dense.get_input_mask_at(0), None)\n self.assertEqual(dense.get_input_mask_at(1), None)\n self.assertEqual(dense.get_output_mask_at(0), None)\n self.assertEqual(dense.get_output_mask_at(1), None)\n\n @test_util.run_in_graph_and_eager_modes()\n def test_multi_input_layer(self):\n with self.cached_session():\n # test multi-input layer\n a = keras.layers.Input(shape=(32,), name='input_a')\n b = keras.layers.Input(shape=(32,), name='input_b')\n\n dense = keras.layers.Dense(16, name='dense_1')\n a_2 = dense(a)\n b_2 = dense(b)\n\n merged = keras.layers.concatenate([a_2, b_2], name='merge')\n self.assertListEqual(merged.shape.as_list(), [None, 16 * 2])\n merge_layer, merge_node_index, merge_tensor_index = merged._keras_history\n\n self.assertEqual(merge_node_index, 0)\n self.assertEqual(merge_tensor_index, 0)\n\n self.assertEqual(len(merge_layer._inbound_nodes), 1)\n self.assertEqual(len(merge_layer._outbound_nodes), 0)\n\n self.assertEqual(len(merge_layer._inbound_nodes[0].input_tensors), 2)\n self.assertEqual(len(merge_layer._inbound_nodes[0].inbound_layers), 2)\n\n c = keras.layers.Dense(64, name='dense_2')(merged)\n d = keras.layers.Dense(5, name='dense_3')(c)\n\n model = keras.models.Model(inputs=[a, b], outputs=[c, d], name='model')\n self.assertEqual(len(model.layers), 6)\n output_shapes = model.compute_output_shape([(None, 32), (None, 32)])\n self.assertListEqual(output_shapes[0].as_list(), [None, 64])\n self.assertListEqual(output_shapes[1].as_list(), [None, 5])\n self.assertListEqual(\n model.compute_mask([a, b], [None, None]), [None, None])\n\n # we don't check names of first 2 layers (inputs) because\n # ordering of same-level layers is not fixed\n self.assertListEqual([l.name for l in model.layers][2:],\n ['dense_1', 'merge', 'dense_2', 'dense_3'])\n self.assertListEqual([l.name for l in model._input_layers],\n ['input_a', 'input_b'])\n self.assertListEqual([l.name for l in model._output_layers],\n ['dense_2', 'dense_3'])\n\n # actually run model\n fn = keras.backend.function(model.inputs, model.outputs)\n input_a_np = np.random.random((10, 32))\n input_b_np = np.random.random((10, 32))\n fn_outputs = fn([input_a_np, input_b_np])\n self.assertListEqual([x.shape for x in fn_outputs], [(10, 64), (10, 5)])\n\n # test get_source_inputs\n self._assertAllIs(layer_utils.get_source_inputs(c), [a, b])\n\n # serialization / deserialization\n json_config = model.to_json()\n recreated_model = keras.models.model_from_json(json_config)\n recreated_model.compile('rmsprop', 'mse')\n\n self.assertListEqual([l.name for l in recreated_model.layers][2:],\n ['dense_1', 'merge', 'dense_2', 'dense_3'])\n self.assertListEqual([l.name for l in recreated_model._input_layers],\n ['input_a', 'input_b'])\n self.assertListEqual([l.name for l in recreated_model._output_layers],\n ['dense_2', 'dense_3'])\n\n fn = keras.backend.function(recreated_model.inputs,\n recreated_model.outputs)\n input_a_np = np.random.random((10, 32))\n input_b_np = np.random.random((10, 32))\n fn_outputs = fn([input_a_np, input_b_np])\n self.assertListEqual([x.shape for x in fn_outputs], [(10, 64), (10, 5)])\n\n def test_multi_output_layer_output_names(self):\n inp = keras.layers.Input(name='inp', shape=(None,), dtype=dtypes.float32)\n\n class _MultiOutput(keras.layers.Layer):\n\n def call(self, x):\n return x + 1., x + 2.\n\n out = _MultiOutput(name='out')(inp)\n model = keras.models.Model(inp, out)\n self.assertEqual(['out', 'out_1'], model.output_names)\n self.assertAllClose([2., 3.], model(1.))\n\n @test_util.run_deprecated_v1\n def test_recursion(self):\n with self.cached_session():\n a = keras.layers.Input(shape=(32,), name='input_a')\n b = keras.layers.Input(shape=(32,), name='input_b')\n\n dense = keras.layers.Dense(16, name='dense_1')\n a_2 = dense(a)\n b_2 = dense(b)\n merged = keras.layers.concatenate([a_2, b_2], name='merge')\n c = keras.layers.Dense(64, name='dense_2')(merged)\n d = keras.layers.Dense(5, name='dense_3')(c)\n\n model = keras.models.Model(inputs=[a, b], outputs=[c, d], name='model')\n\n e = keras.layers.Input(shape=(32,), name='input_e')\n f = keras.layers.Input(shape=(32,), name='input_f')\n self.assertEqual(len(model.inputs), 2)\n g, h = model([e, f])\n self.assertEqual(len(model.inputs), 2)\n self.assertEqual(g.name, 'model/dense_2/BiasAdd:0')\n\n self.assertListEqual(g.shape.as_list(), c.shape.as_list())\n self.assertListEqual(h.shape.as_list(), d.shape.as_list())\n\n # test separate manipulation of different layer outputs\n i = keras.layers.Dense(7, name='dense_4')(h)\n\n final_model = keras.models.Model(\n inputs=[e, f], outputs=[i, g], name='final')\n self.assertEqual(len(final_model.inputs), 2)\n self.assertEqual(len(final_model.outputs), 2)\n self.assertEqual(len(final_model.layers), 4)\n\n # we don't check names of first 2 layers (inputs) because\n # ordering of same-level layers is not fixed\n self.assertListEqual([layer.name for layer in final_model.layers][2:],\n ['model', 'dense_4'])\n self.assertListEqual(\n model.compute_mask([e, f], [None, None]), [None, None])\n self.assertListEqual(\n final_model.compute_output_shape([(10, 32), (10, 32)]), [(10, 7),\n (10, 64)])\n\n # run recursive model\n fn = keras.backend.function(final_model.inputs, final_model.outputs)\n input_a_np = np.random.random((10, 32))\n input_b_np = np.random.random((10, 32))\n fn_outputs = fn([input_a_np, input_b_np])\n self.assertListEqual([x.shape for x in fn_outputs], [(10, 7), (10, 64)])\n\n # test serialization\n model_config = final_model.get_config()\n recreated_model = keras.models.Model.from_config(model_config)\n\n fn = keras.backend.function(recreated_model.inputs,\n recreated_model.outputs)\n input_a_np = np.random.random((10, 32))\n input_b_np = np.random.random((10, 32))\n fn_outputs = fn([input_a_np, input_b_np])\n self.assertListEqual([x.shape for x in fn_outputs], [(10, 7), (10, 64)])\n\n @test_util.run_in_graph_and_eager_modes()\n def test_multi_input_multi_output_recursion(self):\n with self.cached_session():\n # test multi-input multi-output\n a = keras.layers.Input(shape=(32,), name='input_a')\n b = keras.layers.Input(shape=(32,), name='input_b')\n\n dense = keras.layers.Dense(16, name='dense_1')\n a_2 = dense(a)\n b_2 = dense(b)\n merged = keras.layers.concatenate([a_2, b_2], name='merge')\n c = keras.layers.Dense(64, name='dense_2')(merged)\n d = keras.layers.Dense(5, name='dense_3')(c)\n\n model = keras.models.Model(inputs=[a, b], outputs=[c, d], name='model')\n\n j = keras.layers.Input(shape=(32,), name='input_j')\n k = keras.layers.Input(shape=(32,), name='input_k')\n _, n = model([j, k])\n\n o = keras.layers.Input(shape=(32,), name='input_o')\n p = keras.layers.Input(shape=(32,), name='input_p')\n q, _ = model([o, p])\n\n self.assertListEqual(n.shape.as_list(), [None, 5])\n self.assertListEqual(q.shape.as_list(), [None, 64])\n s = keras.layers.concatenate([n, q], name='merge_nq')\n self.assertListEqual(s.shape.as_list(), [None, 64 + 5])\n\n # test with single output as 1-elem list\n multi_io_model = keras.models.Model([j, k, o, p], [s])\n\n fn = keras.backend.function(multi_io_model.inputs, multi_io_model.outputs)\n fn_outputs = fn([\n np.random.random((10, 32)), np.random.random((10, 32)),\n np.random.random((10, 32)), np.random.random((10, 32))\n ])\n self.assertListEqual([x.shape for x in fn_outputs], [(10, 69)])\n\n # test with single output as tensor\n multi_io_model = keras.models.Model([j, k, o, p], s)\n\n fn = keras.backend.function(multi_io_model.inputs, multi_io_model.outputs)\n fn_outputs = fn([\n np.random.random((10, 32)), np.random.random((10, 32)),\n np.random.random((10, 32)), np.random.random((10, 32))\n ])\n # note that the output of the function will still be a 1-elem list\n self.assertListEqual([x.shape for x in fn_outputs], [(10, 69)])\n\n # test serialization\n model_config = multi_io_model.get_config()\n recreated_model = keras.models.Model.from_config(model_config)\n\n fn = keras.backend.function(recreated_model.inputs,\n recreated_model.outputs)\n fn_outputs = fn([\n np.random.random((10, 32)), np.random.random((10, 32)),\n np.random.random((10, 32)), np.random.random((10, 32))\n ])\n # note that the output of the function will still be a 1-elem list\n self.assertListEqual([x.shape for x in fn_outputs], [(10, 69)])\n\n config = model.get_config()\n keras.models.Model.from_config(config)\n\n model.summary()\n json_str = model.to_json()\n keras.models.model_from_json(json_str)\n\n if yaml is not None:\n yaml_str = model.to_yaml()\n keras.models.model_from_yaml(yaml_str)\n\n @test_util.run_in_graph_and_eager_modes()\n def test_invalid_graphs(self):\n a = keras.layers.Input(shape=(32,), name='input_a')\n b = keras.layers.Input(shape=(32,), name='input_b')\n\n dense = keras.layers.Dense(16, name='dense_1')\n a_2 = dense(a)\n b_2 = dense(b)\n merged = keras.layers.concatenate([a_2, b_2], name='merge')\n c = keras.layers.Dense(64, name='dense_2')(merged)\n d = keras.layers.Dense(5, name='dense_3')(c)\n\n model = keras.models.Model(inputs=[a, b], outputs=[c, d], name='model')\n\n # input is not an Input tensor\n j = keras.layers.Input(shape=(32,), name='input_j')\n j = keras.layers.Dense(32)(j)\n k = keras.layers.Input(shape=(32,), name='input_k')\n m, n = model([j, k])\n\n with self.assertRaises(Exception):\n keras.models.Model([j, k], [m, n])\n\n # disconnected graph\n j = keras.layers.Input(shape=(32,), name='input_j')\n k = keras.layers.Input(shape=(32,), name='input_k')\n m, n = model([j, k])\n with self.assertRaises(Exception):\n keras.models.Model([j], [m, n])\n\n # redundant outputs\n j = keras.layers.Input(shape=(32,), name='input_j')\n k = keras.layers.Input(shape=(32,), name='input_k')\n m, n = model([j, k])\n\n keras.models.Model([j, k], [m, n, n])\n\n # redundant inputs\n j = keras.layers.Input(shape=(32,), name='input_j')\n k = keras.layers.Input(shape=(32,), name='input_k')\n m, n = model([j, k])\n with self.assertRaises(Exception):\n keras.models.Model([j, k, j], [m, n])\n\n # i have not idea what I'm doing: garbage as inputs/outputs\n j = keras.layers.Input(shape=(32,), name='input_j')\n k = keras.layers.Input(shape=(32,), name='input_k')\n m, n = model([j, k])\n with self.assertRaises(Exception):\n keras.models.Model([j, k], [m, n, 0])\n\n @test_util.run_deprecated_v1\n def test_raw_tf_compatibility(self):\n # test calling layers/models on TF tensors\n a = keras.layers.Input(shape=(32,), name='input_a')\n b = keras.layers.Input(shape=(32,), name='input_b')\n\n dense = keras.layers.Dense(16, name='dense_1')\n a_2 = dense(a)\n b_2 = dense(b)\n merged = keras.layers.concatenate([a_2, b_2], name='merge')\n c = keras.layers.Dense(64, name='dense_2')(merged)\n d = keras.layers.Dense(5, name='dense_3')(c)\n\n model = keras.models.Model(inputs=[a, b], outputs=[c, d], name='model')\n\n j = keras.layers.Input(shape=(32,), name='input_j')\n k = keras.layers.Input(shape=(32,), name='input_k')\n self.assertEqual(len(model.inputs), 2)\n m, n = model([j, k])\n self.assertEqual(len(model.inputs), 2)\n tf_model = keras.models.Model([j, k], [m, n])\n\n j_tf = array_ops.placeholder(dtype=dtypes.float32, shape=(None, 32))\n k_tf = array_ops.placeholder(dtype=dtypes.float32, shape=(None, 32))\n m_tf, n_tf = tf_model([j_tf, k_tf])\n self.assertListEqual(m_tf.shape.as_list(), [None, 64])\n self.assertListEqual(n_tf.shape.as_list(), [None, 5])\n\n # test merge\n keras.layers.concatenate([j_tf, k_tf], axis=1)\n keras.layers.add([j_tf, k_tf])\n\n # test tensor input\n x = array_ops.placeholder(shape=(None, 2), dtype=dtypes.float32)\n keras.layers.InputLayer(input_tensor=x)\n\n x = keras.layers.Input(tensor=x)\n keras.layers.Dense(2)(x)\n\n @test_util.run_in_graph_and_eager_modes()\n def test_basic_masking(self):\n a = keras.layers.Input(shape=(10, 32), name='input_a')\n b = keras.layers.Masking()(a)\n model = keras.models.Model(a, b)\n self.assertEqual(model.output_mask.shape.as_list(), [None, 10])\n\n @test_util.run_deprecated_v1\n def testMaskingSingleInput(self):\n\n class MaskedLayer(keras.layers.Layer):\n\n def call(self, inputs, mask=None):\n if mask is not None:\n return inputs * mask\n return inputs\n\n def compute_mask(self, inputs, mask=None):\n return array_ops.ones_like(inputs)\n\n if context.executing_eagerly():\n a = constant_op.constant([2] * 32)\n mask = constant_op.constant([0, 1] * 16)\n a._keras_mask = mask\n b = MaskedLayer().apply(a)\n self.assertTrue(hasattr(b, '_keras_mask'))\n self.assertAllEqual(\n self.evaluate(array_ops.ones_like(mask)),\n self.evaluate(getattr(b, '_keras_mask')))\n self.assertAllEqual(self.evaluate(a * mask), self.evaluate(b))\n else:\n x = input_layer_lib.Input(shape=(32,))\n y = MaskedLayer()(x) # pylint: disable=not-callable\n network = network_lib.Network(x, y)\n\n # test callability on Input\n x_2 = input_layer_lib.Input(shape=(32,))\n y_2 = network(x_2)\n self.assertEqual(y_2.shape.as_list(), [None, 32])\n\n # test callability on regular tensor\n x_2 = array_ops.placeholder(dtype='float32', shape=(None, 32))\n y_2 = network(x_2)\n self.assertEqual(y_2.shape.as_list(), [None, 32])\n\n @test_util.run_deprecated_v1\n def test_activity_regularization_with_model_composition(self):\n\n def reg(x):\n return math_ops.reduce_sum(x)\n\n net_a_input = input_layer_lib.Input((2,))\n net_a = net_a_input\n net_a = keras.layers.Dense(2, kernel_initializer='ones',\n use_bias=False,\n activity_regularizer=reg)(net_a)\n model_a = keras.Model([net_a_input], [net_a])\n\n net_b_input = input_layer_lib.Input((2,))\n net_b = model_a(net_b_input)\n model_b = keras.Model([net_b_input], [net_b])\n\n model_b.compile(optimizer='sgd', loss=None)\n x = np.ones((1, 2))\n loss = model_b.evaluate(x)\n self.assertEqual(loss, 4.)\n\n @keras_parameterized.run_all_keras_modes\n def test_layer_sharing_at_heterogenous_depth(self):\n x_val = np.random.random((10, 5))\n\n x = input_layer_lib.Input(shape=(5,))\n a = keras.layers.Dense(5, name='A')\n b = keras.layers.Dense(5, name='B')\n output = a(b(a(b(x))))\n m = keras.models.Model(x, output)\n m.run_eagerly = testing_utils.should_run_eagerly()\n m._experimental_run_tf_function = testing_utils.should_run_tf_function()\n\n output_val = m.predict(x_val)\n\n config = m.get_config()\n weights = m.get_weights()\n\n m2 = keras.models.Model.from_config(config)\n m2.set_weights(weights)\n\n output_val_2 = m2.predict(x_val)\n self.assertAllClose(output_val, output_val_2, atol=1e-6)\n\n @keras_parameterized.run_all_keras_modes\n def test_layer_sharing_at_heterogenous_depth_with_concat(self):\n input_shape = (16, 9, 3)\n input_layer = input_layer_lib.Input(shape=input_shape)\n\n a = keras.layers.Dense(3, name='dense_A')\n b = keras.layers.Dense(3, name='dense_B')\n c = keras.layers.Dense(3, name='dense_C')\n\n x1 = b(a(input_layer))\n x2 = a(c(input_layer))\n output = keras.layers.concatenate([x1, x2])\n\n m = keras.models.Model(inputs=input_layer, outputs=output)\n m.run_eagerly = testing_utils.should_run_eagerly()\n m._experimental_run_tf_function = testing_utils.should_run_tf_function()\n\n x_val = np.random.random((10, 16, 9, 3))\n output_val = m.predict(x_val)\n\n config = m.get_config()\n weights = m.get_weights()\n\n m2 = keras.models.Model.from_config(config)\n m2.set_weights(weights)\n\n output_val_2 = m2.predict(x_val)\n self.assertAllClose(output_val, output_val_2, atol=1e-6)\n\n @keras_parameterized.run_all_keras_modes\n def test_explicit_training_argument(self):\n a = keras.layers.Input(shape=(2,))\n b = keras.layers.Dropout(0.5)(a)\n base_model = keras.models.Model(a, b)\n\n a = keras.layers.Input(shape=(2,))\n b = base_model(a, training=False)\n model = keras.models.Model(a, b)\n\n x = np.ones((100, 2))\n y = np.ones((100, 2))\n model.compile(\n optimizer='sgd',\n loss='mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n loss = model.train_on_batch(x, y)\n self.assertEqual(loss, 0) # In inference mode, output is equal to input.\n\n a = keras.layers.Input(shape=(2,))\n b = base_model(a, training=True)\n model = keras.models.Model(a, b)\n preds = model.predict(x)\n self.assertEqual(np.min(preds), 0.) # At least one unit was dropped.\n\n @keras_parameterized.run_all_keras_modes\n def test_mask_derived_from_keras_layer(self):\n inputs = keras.Input((5, 10))\n mask = keras.Input((5,))\n outputs = keras.layers.RNN(keras.layers.LSTMCell(100))(inputs, mask=mask)\n model = keras.Model([inputs, mask], outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n history = model.fit(\n x=[np.ones((10, 5, 10)), np.zeros((10, 5))],\n y=np.zeros((10, 100)),\n batch_size=2)\n # All data is masked, returned values are 0's.\n self.assertEqual(history.history['loss'][0], 0.0)\n history = model.fit(\n x=[np.ones((10, 5, 10)), np.ones((10, 5))],\n y=np.zeros((10, 100)),\n batch_size=2)\n # Data is not masked, returned values are random.\n self.assertGreater(history.history['loss'][0], 0.0)\n\n model = keras.Model.from_config(model.get_config())\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n history = model.fit(\n x=[np.ones((10, 5, 10)), np.zeros((10, 5))],\n y=np.zeros((10, 100)),\n batch_size=2)\n # All data is masked, returned values are 0's.\n self.assertEqual(history.history['loss'][0], 0.0)\n history = model.fit(\n x=[np.ones((10, 5, 10)), np.ones((10, 5))],\n y=np.zeros((10, 100)),\n batch_size=2)\n # Data is not masked, returned values are random.\n self.assertGreater(history.history['loss'][0], 0.0)\n\n @keras_parameterized.run_all_keras_modes\n def test_call_arg_derived_from_keras_layer(self):\n\n class MyAdd(keras.layers.Layer):\n\n def call(self, x1, x2):\n return x1 + x2\n\n input1 = keras.Input(10)\n input2 = keras.Input(10)\n outputs = MyAdd()(input1, input2)\n model = keras.Model([input1, input2], outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n history = model.fit(\n x=[3 * np.ones((10, 10)), 7 * np.ones((10, 10))],\n y=10 * np.ones((10, 10)),\n batch_size=2)\n # Check that second input was correctly added to first.\n self.assertEqual(history.history['loss'][0], 0.0)\n\n # Check serialization.\n model = keras.Model.from_config(\n model.get_config(), custom_objects={'MyAdd': MyAdd})\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n history = model.fit(\n x=[3 * np.ones((10, 10)), 7 * np.ones((10, 10))],\n y=10 * np.ones((10, 10)),\n batch_size=2)\n # Check that second input was correctly added to first.\n self.assertEqual(history.history['loss'][0], 0.0)\n\n @keras_parameterized.run_all_keras_modes\n def test_call_kwarg_derived_from_keras_layer(self):\n\n class MaybeAdd(keras.layers.Layer):\n\n def call(self, x1, x2=None):\n if x2 is not None:\n return x1 + x2\n return x1\n\n input1 = keras.Input(10)\n input2 = keras.Input(10)\n outputs = MaybeAdd()(input1, x2=input2)\n model = keras.Model([input1, input2], outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n history = model.fit(\n x=[3 * np.ones((10, 10)), 7 * np.ones((10, 10))],\n y=10 * np.ones((10, 10)),\n batch_size=2)\n # Check that second input was correctly added to first.\n self.assertEqual(history.history['loss'][0], 0.0)\n\n model = keras.Model.from_config(\n model.get_config(), custom_objects={'MaybeAdd': MaybeAdd})\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n history = model.fit(\n x=[3 * np.ones((10, 10)), 7 * np.ones((10, 10))],\n y=10 * np.ones((10, 10)),\n batch_size=2)\n # Check that second input was correctly added to first.\n self.assertEqual(history.history['loss'][0], 0.0)\n\n @keras_parameterized.run_all_keras_modes\n def test_call_nested_arg_derived_from_keras_layer(self):\n\n class AddAll(keras.layers.Layer):\n\n def call(self, x1, x2, x3=None):\n out = x1 + x2\n if x3 is not None:\n for t in x3.values():\n out += t\n return out\n\n input1 = keras.Input(10)\n input2 = keras.Input(10)\n input3 = keras.Input(10)\n outputs = AddAll()(\n input1,\n 4 * array_ops.ones((1, 10)),\n x3={\n 'a': input2,\n 'b': input3,\n 'c': 5 * array_ops.ones((1, 10))\n })\n model = keras.Model([input1, input2, input3], outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n history = model.fit(\n x=[np.ones((10, 10)), 2 * np.ones((10, 10)), 3 * np.ones((10, 10))],\n y=15 * np.ones((10, 10)),\n batch_size=2)\n # Check that all inputs were correctly added.\n self.assertEqual(history.history['loss'][0], 0.0)\n\n model = keras.Model.from_config(\n model.get_config(), custom_objects={'AddAll': AddAll})\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n history = model.fit(\n x=[np.ones((10, 10)), 2 * np.ones((10, 10)), 3 * np.ones((10, 10))],\n y=15 * np.ones((10, 10)),\n batch_size=2)\n # Check that all inputs were correctly added.\n self.assertEqual(history.history['loss'][0], 0.0)\n\n @keras_parameterized.run_all_keras_modes\n def test_multi_output_model_with_none_masking(self):\n def func(x):\n return [x * 0.2, x * 0.3]\n\n def output_shape(input_shape):\n return [input_shape, input_shape]\n\n i = keras.layers.Input(shape=(3, 2, 1))\n o = keras.layers.Lambda(function=func, output_shape=output_shape)(i)\n\n self.assertEqual(keras.backend.int_shape(o[0]), (None, 3, 2, 1))\n self.assertEqual(keras.backend.int_shape(o[1]), (None, 3, 2, 1))\n\n o = keras.layers.add(o)\n model = keras.Model(i, o)\n model.run_eagerly = testing_utils.should_run_eagerly()\n model._experimental_run_tf_function = testing_utils.should_run_tf_function()\n\n i2 = keras.layers.Input(shape=(3, 2, 1))\n o2 = model(i2)\n model2 = keras.Model(i2, o2)\n model2.run_eagerly = testing_utils.should_run_eagerly()\n model2._experimental_run_tf_function = testing_utils.should_run_tf_function(\n )\n\n x = np.random.random((4, 3, 2, 1))\n out = model2.predict(x)\n assert out.shape == (4, 3, 2, 1)\n self.assertAllClose(out, x * 0.2 + x * 0.3, atol=1e-4)\n\n @keras_parameterized.run_all_keras_modes\n def test_constant_initializer_with_numpy(self):\n initializer = keras.initializers.Constant(np.ones((3, 2)))\n model = keras.models.Sequential()\n model.add(\n keras.layers.Dense(2, input_shape=(3,), kernel_initializer=initializer))\n model.add(keras.layers.Dense(3))\n model.compile(\n loss='mse',\n optimizer='sgd',\n metrics=['acc'],\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n\n json_str = model.to_json()\n keras.models.model_from_json(json_str)\n\n if yaml is not None:\n yaml_str = model.to_yaml()\n keras.models.model_from_yaml(yaml_str)\n\n def test_subclassed_error_if_init_not_called(self):\n\n class MyNetwork(network_lib.Network):\n\n def __init__(self):\n self._foo = [keras.layers.Dense(10), keras.layers.Dense(10)]\n\n with self.assertRaisesRegexp(RuntimeError, 'forgot to call'):\n MyNetwork()\n\n @test_util.run_in_graph_and_eager_modes()\n def test_int_input_shape(self):\n inputs = keras.Input(10)\n self.assertEqual([None, 10], inputs.shape.as_list())\n\n inputs_with_batch = keras.Input(batch_size=20, shape=5)\n self.assertEqual([20, 5], inputs_with_batch.shape.as_list())\n\n @test_util.run_in_graph_and_eager_modes()\n def test_model_initialization(self):\n # Functional model\n inputs = input_layer_lib.Input(shape=(32,))\n outputs = keras.layers.Dense(4)(inputs)\n\n with self.assertRaisesRegexp(TypeError, 'unexpected argument'):\n model = training.Model(inputs, outputs, name='m', trainable=False,\n dtype='int64')\n with self.assertRaisesRegexp(TypeError, 'unexpected argument'):\n model = training.Model(inputs, outputs, name='m', trainable=False,\n dynamic=False)\n\n model = training.Model(inputs, outputs, name='m', trainable=False)\n self.assertEqual('m', model.name)\n self.assertFalse(model.trainable)\n self.assertFalse(model.dynamic)\n\n # Subclassed model\n model = training.Model(name='subclassed', trainable=True, dtype='int64',\n dynamic=True)\n self.assertEqual('subclassed', model.name)\n self.assertTrue(model.dynamic)\n self.assertTrue(model.trainable)\n w = model.add_weight('w', [], initializer=keras.initializers.Constant(1))\n self.assertEqual(dtypes.int64, w.dtype)\n\n def test_disconnected_inputs(self):\n input_tensor1 = input_layer_lib.Input(shape=[200], name='a')\n input_tensor2 = input_layer_lib.Input(shape=[10], name='b')\n output_tensor1 = keras.layers.Dense(units=10)(input_tensor1)\n\n net = keras.engine.network.Network(\n inputs=[input_tensor1, input_tensor2], outputs=[output_tensor1])\n net2 = keras.engine.network.Network.from_config(net.get_config())\n self.assertLen(net2.inputs, 2)\n self.assertEqual('a', net2.layers[0].name)\n self.assertEqual('b', net2.layers[1].name)\n\n @keras_parameterized.run_with_all_model_types\n def test_dependency_tracking(self):\n model = testing_utils.get_small_mlp(1, 4, input_dim=3)\n model.trackable = Checkpoint()\n self.assertIn('trackable', model._unconditional_dependency_names)\n self.assertEqual(model.trackable, model._lookup_dependency('trackable'))\n\n\nclass DeferredModeTest(test.TestCase):\n\n @test_util.run_in_graph_and_eager_modes()\n def testSimpleNetworkBuilding(self):\n inputs = input_layer_lib.Input(shape=(32,))\n if context.executing_eagerly():\n self.assertEqual(inputs.dtype.name, 'float32')\n self.assertEqual(inputs.shape.as_list(), [None, 32])\n\n x = keras.layers.Dense(2)(inputs)\n if context.executing_eagerly():\n self.assertEqual(x.dtype.name, 'float32')\n self.assertEqual(x.shape.as_list(), [None, 2])\n\n outputs = keras.layers.Dense(4)(x)\n network = network_lib.Network(inputs, outputs)\n self.assertIsInstance(network, network_lib.Network)\n\n if context.executing_eagerly():\n # It should be possible to call such a network on EagerTensors.\n inputs = constant_op.constant(\n np.random.random((10, 32)).astype('float32'))\n outputs = network(inputs)\n self.assertEqual(outputs.shape.as_list(), [10, 4])\n\n @test_util.run_in_graph_and_eager_modes()\n def testMultiIONetworkBuilding(self):\n input_a = input_layer_lib.Input(shape=(32,))\n input_b = input_layer_lib.Input(shape=(16,))\n a = keras.layers.Dense(16)(input_a)\n\n class AddLayer(keras.layers.Layer):\n\n def call(self, inputs):\n return inputs[0] + inputs[1]\n\n c = AddLayer()([a, input_b]) # pylint: disable=not-callable\n c = keras.layers.Dense(2)(c)\n\n network = network_lib.Network([input_a, input_b], [a, c])\n if context.executing_eagerly():\n a_val = constant_op.constant(\n np.random.random((10, 32)).astype('float32'))\n b_val = constant_op.constant(\n np.random.random((10, 16)).astype('float32'))\n outputs = network([a_val, b_val])\n self.assertEqual(len(outputs), 2)\n self.assertEqual(outputs[0].shape.as_list(), [10, 16])\n self.assertEqual(outputs[1].shape.as_list(), [10, 2])\n\n\nclass DefaultShapeInferenceBehaviorTest(keras_parameterized.TestCase):\n\n def _testShapeInference(self, model, input_shape, expected_output_shape):\n input_value = np.random.random(input_shape)\n output_value = model.predict(input_value)\n self.assertEqual(output_value.shape, expected_output_shape)\n\n @test_util.run_in_graph_and_eager_modes()\n def testSingleInputCase(self):\n\n class LayerWithOneInput(keras.layers.Layer):\n\n def build(self, input_shape):\n self.w = array_ops.ones(shape=(3, 4))\n\n def call(self, inputs):\n return keras.backend.dot(inputs, self.w)\n\n inputs = input_layer_lib.Input(shape=(3,))\n layer = LayerWithOneInput()\n\n if context.executing_eagerly():\n self.assertEqual(\n layer.compute_output_shape((None, 3)).as_list(), [None, 4])\n # As a side-effect, compute_output_shape builds the layer.\n self.assertTrue(layer.built)\n # We can still query the layer's compute_output_shape with compatible\n # input shapes.\n self.assertEqual(\n layer.compute_output_shape((6, 3)).as_list(), [6, 4])\n\n outputs = layer(inputs)\n model = keras.Model(inputs, outputs)\n self._testShapeInference(model, (2, 3), (2, 4))\n\n @test_util.run_in_graph_and_eager_modes()\n def testMultiInputOutputCase(self):\n\n class MultiInputOutputLayer(keras.layers.Layer):\n\n def build(self, input_shape):\n self.w = array_ops.ones(shape=(3, 4))\n\n def call(self, inputs):\n a = keras.backend.dot(inputs[0], self.w)\n b = a + inputs[1]\n return [a, b]\n\n input_a = input_layer_lib.Input(shape=(3,))\n input_b = input_layer_lib.Input(shape=(4,))\n output_a, output_b = MultiInputOutputLayer()([input_a, input_b])\n model = keras.Model([input_a, input_b], [output_a, output_b])\n output_a_val, output_b_val = model.predict(\n [np.random.random((2, 3)), np.random.random((2, 4))])\n self.assertEqual(output_a_val.shape, (2, 4))\n self.assertEqual(output_b_val.shape, (2, 4))\n\n @test_util.run_in_graph_and_eager_modes()\n def testTrainingArgument(self):\n\n class LayerWithTrainingArg(keras.layers.Layer):\n\n def build(self, input_shape):\n self.w = array_ops.ones(shape=(3, 4))\n\n def call(self, inputs, training):\n return keras.backend.dot(inputs, self.w)\n\n inputs = input_layer_lib.Input(shape=(3,))\n outputs = LayerWithTrainingArg()(inputs, training=False)\n model = keras.Model(inputs, outputs)\n self._testShapeInference(model, (2, 3), (2, 4))\n\n @test_util.run_in_graph_and_eager_modes()\n def testNoneInShape(self):\n\n class Model(keras.Model):\n\n def __init__(self):\n super(Model, self).__init__()\n self.conv1 = keras.layers.Conv2D(8, 3)\n self.pool = keras.layers.GlobalAveragePooling2D()\n self.fc = keras.layers.Dense(3)\n\n def call(self, x):\n x = self.conv1(x)\n x = self.pool(x)\n x = self.fc(x)\n return x\n\n model = Model()\n model.build(tensor_shape.TensorShape((None, None, None, 1)))\n self.assertTrue(model.built, 'Model should be built')\n self.assertTrue(model.weights,\n 'Model should have its weights created as it '\n 'has been built')\n sample_input = array_ops.ones((1, 10, 10, 1))\n output = model(sample_input)\n self.assertEqual(output.shape, (1, 3))\n\n @test_util.run_in_graph_and_eager_modes()\n def testNoneInShapeWithCompoundModel(self):\n\n class BasicBlock(keras.Model):\n\n def __init__(self):\n super(BasicBlock, self).__init__()\n self.conv1 = keras.layers.Conv2D(8, 3)\n self.pool = keras.layers.GlobalAveragePooling2D()\n self.dense = keras.layers.Dense(3)\n\n def call(self, x):\n x = self.conv1(x)\n x = self.pool(x)\n x = self.dense(x)\n return x\n\n class CompoundModel(keras.Model):\n\n def __init__(self):\n super(CompoundModel, self).__init__()\n self.block = BasicBlock()\n\n def call(self, x):\n x = self.block(x) # pylint: disable=not-callable\n return x\n\n model = CompoundModel()\n model.build(tensor_shape.TensorShape((None, None, None, 1)))\n self.assertTrue(model.built, 'Model should be built')\n self.assertTrue(model.weights,\n 'Model should have its weights created as it '\n 'has been built')\n sample_input = array_ops.ones((1, 10, 10, 1))\n output = model(sample_input) # pylint: disable=not-callable\n self.assertEqual(output.shape, (1, 3))\n\n @test_util.run_in_graph_and_eager_modes()\n def testNoneInShapeWithFunctinalAPI(self):\n\n class BasicBlock(keras.Model):\n # Inherting from keras.layers.Layer since we are calling this layer\n # inside a model created using functional API.\n\n def __init__(self):\n super(BasicBlock, self).__init__()\n self.conv1 = keras.layers.Conv2D(8, 3)\n\n def call(self, x):\n x = self.conv1(x)\n return x\n\n input_layer = keras.layers.Input(shape=(None, None, 1))\n x = BasicBlock()(input_layer)\n x = keras.layers.GlobalAveragePooling2D()(x)\n output_layer = keras.layers.Dense(3)(x)\n\n model = keras.Model(inputs=input_layer, outputs=output_layer)\n\n model.build(tensor_shape.TensorShape((None, None, None, 1)))\n self.assertTrue(model.built, 'Model should be built')\n self.assertTrue(model.weights,\n 'Model should have its weights created as it '\n 'has been built')\n sample_input = array_ops.ones((1, 10, 10, 1))\n output = model(sample_input)\n self.assertEqual(output.shape, (1, 3))\n\n @keras_parameterized.run_all_keras_modes\n def test_sequential_as_downstream_of_masking_layer(self):\n inputs = keras.layers.Input(shape=(3, 4))\n x = keras.layers.Masking(mask_value=0., input_shape=(3, 4))(inputs)\n\n s = keras.Sequential()\n s.add(keras.layers.Dense(5, input_shape=(4,)))\n\n x = keras.layers.wrappers.TimeDistributed(s)(x)\n model = keras.Model(inputs=inputs, outputs=x)\n model.compile(\n optimizer='rmsprop',\n loss='mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n\n model_input = np.random.randint(\n low=1, high=5, size=(10, 3, 4)).astype('float32')\n for i in range(4):\n model_input[i, i:, :] = 0.\n model.fit(model_input,\n np.random.random((10, 3, 5)), epochs=1, batch_size=6)\n\n if not context.executing_eagerly():\n # Note: this doesn't work in eager due to DeferredTensor/ops compatibility\n # issue.\n mask_outputs = [model.layers[1].compute_mask(model.layers[1].input)]\n mask_outputs += [model.layers[2].compute_mask(\n model.layers[2].input, mask_outputs[-1])]\n func = keras.backend.function([model.input], mask_outputs)\n mask_outputs_val = func([model_input])\n self.assertAllClose(mask_outputs_val[0], np.any(model_input, axis=-1))\n self.assertAllClose(mask_outputs_val[1], np.any(model_input, axis=-1))\n\n @test_util.run_in_graph_and_eager_modes()\n def test_external_keras_serialization_compat_input_layers(self):\n inputs = keras.Input(shape=(10,))\n outputs = keras.layers.Dense(1)(inputs)\n model = keras.Model(inputs, outputs)\n config = model.get_config()\n # Checks that single inputs and outputs are still saved as 1-element lists.\n # Saving as 1-element lists or not is equivalent in TF Keras, but only the\n # 1-element list format is supported in TF.js and keras-team/Keras.\n self.assertLen(config['input_layers'], 1)\n self.assertLen(config['output_layers'], 1)\n\n @test_util.run_in_graph_and_eager_modes()\n def test_external_keras_serialization_compat_inbound_nodes(self):\n # Check single Tensor input.\n inputs = keras.Input(shape=(10,), name='in')\n outputs = keras.layers.Dense(1)(inputs)\n model = keras.Model(inputs, outputs)\n config = model.get_config()\n self.assertEqual(config['layers'][1]['inbound_nodes'], [[['in', 0, 0, {}]]])\n\n # Check multiple Tensor input.\n inputs1 = keras.Input(shape=(10,), name='in1')\n inputs2 = keras.Input(shape=(10,), name='in2')\n outputs = keras.layers.Add()([inputs1, inputs2])\n model = keras.Model([inputs1, inputs2], outputs)\n config = model.get_config()\n self.assertEqual(config['layers'][2]['inbound_nodes'],\n [[['in1', 0, 0, {}], ['in2', 0, 0, {}]]])\n\n\nclass GraphUtilsTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testGetReachableFromInputs(self):\n\n with self.cached_session():\n pl_1 = array_ops.placeholder(shape=None, dtype='float32')\n pl_2 = array_ops.placeholder(shape=None, dtype='float32')\n pl_3 = array_ops.placeholder(shape=None, dtype='float32')\n x_1 = pl_1 + pl_2\n x_2 = pl_2 * 2\n x_3 = pl_3 + 1\n x_4 = x_1 + x_2\n x_5 = x_3 * pl_1\n\n self.assertEqual(\n keras.utils.tf_utils.get_reachable_from_inputs([pl_1]),\n {pl_1, x_1, x_4, x_5, x_1.op, x_4.op, x_5.op})\n self.assertEqual(\n keras.utils.tf_utils.get_reachable_from_inputs([pl_1, pl_2]),\n {pl_1, pl_2, x_1, x_2, x_4, x_5, x_1.op, x_2.op, x_4.op, x_5.op})\n self.assertEqual(\n keras.utils.tf_utils.get_reachable_from_inputs([pl_3]),\n {pl_3, x_3, x_5, x_3.op, x_5.op})\n self.assertEqual(\n keras.utils.tf_utils.get_reachable_from_inputs([x_3]),\n {x_3, x_5, x_5.op})\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass NestedNetworkTest(test.TestCase):\n\n def test_nested_inputs_network(self):\n inputs = {'x1': keras.Input(shape=(1,)), 'x2': keras.Input(shape=(1,))}\n outputs = keras.layers.Add()([inputs['x1'], inputs['x2']])\n network = keras.engine.network.Network(inputs, outputs)\n\n network = keras.engine.network.Network.from_config(network.get_config())\n\n result_tensor = network({\n 'x': array_ops.ones((1, 1), 'float32'),\n 'y': array_ops.ones((1, 1), 'float32')\n })\n result = self.evaluate(result_tensor)\n self.assertAllEqual(result, [[2.]])\n\n # TODO(b/122726584): Investigate why concrete batch is flaky in some builds.\n output_shape = network.compute_output_shape({\n 'x1': (None, 1),\n 'x2': (None, 1)\n })\n self.assertListEqual(output_shape.as_list(), [None, 1])\n\n def test_nested_outputs_network(self):\n inputs = keras.Input(shape=(1,))\n outputs = {\n 'x+x': keras.layers.Add()([inputs, inputs]),\n 'x*x': keras.layers.Multiply()([inputs, inputs])\n }\n\n network = keras.engine.network.Network(inputs, outputs)\n\n network = keras.engine.network.Network.from_config(network.get_config())\n\n result_tensor = network(array_ops.ones((1, 1), 'float32'))\n result = self.evaluate(result_tensor)\n self.assertAllEqual(result['x+x'], [[2.]])\n self.assertAllEqual(result['x*x'], [[1.]])\n\n output_shape = network.compute_output_shape((None, 1))\n self.assertListEqual(output_shape['x+x'].as_list(), [None, 1])\n self.assertListEqual(output_shape['x*x'].as_list(), [None, 1])\n\n def test_nested_network_inside_network(self):\n inner_inputs = {\n 'x1': keras.Input(shape=(1,)),\n 'x2': keras.Input(shape=(1,))\n }\n inner_outputs = {\n 'x1+x2':\n keras.layers.Add()([inner_inputs['x1'], inner_inputs['x2']]),\n 'x1*x2':\n keras.layers.Multiply()([inner_inputs['x1'], inner_inputs['x2']])\n }\n inner_network = keras.engine.network.Network(inner_inputs, inner_outputs)\n\n inputs = [keras.Input(shape=(1,)), keras.Input(shape=(1,))]\n middle = inner_network({'x1': inputs[0], 'x2': inputs[1]})\n outputs = keras.layers.Add()([middle['x1+x2'], middle['x1*x2']])\n network = keras.engine.network.Network(inputs, outputs)\n\n network = keras.engine.network.Network.from_config(network.get_config())\n\n # Computes: `(x1+x2) + (x1*x2)`\n result_tensor = network(\n [array_ops.ones((1, 1), 'float32'),\n array_ops.ones((1, 1), 'float32')])\n result = self.evaluate(result_tensor)\n self.assertAllEqual(result, [[3.]])\n\n output_shape = network.compute_output_shape([(None, 1), (None, 1)])\n self.assertListEqual(output_shape.as_list(), [None, 1])\n\n @test_util.run_in_graph_and_eager_modes\n def test_updates_with_direct_call(self):\n inputs = keras.Input(shape=(10,))\n x = keras.layers.BatchNormalization()(inputs)\n x = keras.layers.Dense(10)(x)\n model = keras.Model(inputs, x)\n\n ph = keras.backend.placeholder(shape=(10, 10))\n model(ph)\n\n self.assertLen(model.get_updates_for(ph), 2)\n self.assertLen(model.get_updates_for(None), 0)\n\n def test_dict_mapping_input(self):\n\n class ReturnFirst(keras.layers.Layer):\n\n def call(self, inputs):\n b, _ = inputs\n return b\n\n # Checks that inputs are put in same order as the\n # Model was constructed with.\n b = keras.Input(shape=(10,), name='b')\n a = keras.Input(shape=(10,), name='a')\n outputs = ReturnFirst()([b, a])\n\n b_val = array_ops.ones((10, 10))\n a_val = array_ops.zeros((10, 10))\n\n model = keras.Model([b, a], outputs)\n res = model({'a': a_val, 'b': b_val})\n self.assertAllClose(self.evaluate(res), self.evaluate(b_val))\n\n reversed_model = keras.Model([a, b], outputs)\n res = reversed_model({'a': a_val, 'b': b_val})\n self.assertAllClose(self.evaluate(res), self.evaluate(b_val))\n\n\n@keras_parameterized.run_all_keras_modes\nclass AddLossTest(keras_parameterized.TestCase):\n\n def test_add_loss_outside_call_only_loss(self):\n inputs = keras.Input((10,))\n mid = keras.layers.Dense(10)(inputs)\n outputs = keras.layers.Dense(1)(mid)\n model = keras.Model(inputs, outputs)\n model.add_loss(math_ops.reduce_mean(outputs))\n self.assertLen(model.losses, 1)\n\n initial_weights = model.get_weights()\n\n x = np.ones((10, 10))\n model.compile(\n 'sgd',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n model.fit(x, batch_size=2, epochs=1)\n\n model2 = model.from_config(model.get_config())\n model2.compile(\n 'sgd',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n model2.set_weights(initial_weights)\n model2.fit(x, batch_size=2, epochs=1)\n\n # The TFOpLayer and the AddLoss layer are serialized.\n self.assertLen(model2.layers, 5)\n self.assertAllClose(model.get_weights(), model2.get_weights())\n\n def test_add_loss_outside_call_multiple_losses(self):\n inputs = keras.Input((10,))\n x1 = keras.layers.Dense(10)(inputs)\n x2 = keras.layers.Dense(10)(x1)\n outputs = keras.layers.Dense(1)(x2)\n model = keras.Model(inputs, outputs)\n model.add_loss(math_ops.reduce_sum(x1 * x2))\n model.add_loss(math_ops.reduce_mean(outputs))\n self.assertLen(model.losses, 2)\n\n initial_weights = model.get_weights()\n\n x, y = np.ones((10, 10)), np.ones((10, 1))\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n model.fit(x, y, batch_size=2, epochs=1)\n\n model2 = model.from_config(model.get_config())\n model2.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n model2.set_weights(initial_weights)\n model2.fit(x, y, batch_size=2, epochs=1)\n\n self.assertAllClose(model.get_weights(), model2.get_weights())\n\n\n@keras_parameterized.run_all_keras_modes\nclass WeightAccessTest(keras_parameterized.TestCase):\n\n def test_functional_model(self):\n inputs = keras.Input((10,))\n x1 = keras.layers.Dense(10)(inputs)\n x2 = keras.layers.Dense(10)(x1)\n outputs = keras.layers.Dense(1)(x2)\n model = keras.Model(inputs, outputs)\n\n self.assertEqual(len(model.weights), 6)\n\n def test_sequential_model_with_input_shape(self):\n x1 = keras.layers.Dense(10, input_shape=(10,))\n x2 = keras.layers.Dense(10)\n x3 = keras.layers.Dense(1)\n model = keras.models.Sequential([x1, x2, x3])\n\n self.assertEqual(len(model.weights), 6)\n\n def test_sequential_model_without_input_shape(self):\n x1 = keras.layers.Dense(10)\n x2 = keras.layers.Dense(10)\n x3 = keras.layers.Dense(1)\n model = keras.models.Sequential([x1, x2, x3])\n\n with self.assertRaisesRegexp(\n ValueError, 'Weights for model .* have not yet been created'):\n _ = model.weights\n\n def test_subclass_model_with_build_method(self):\n class SubclassModel(keras.models.Model):\n\n def build(self, input_shape):\n self.w = self.add_weight(shape=input_shape[-1], initializer='ones')\n\n def call(self, inputs):\n return inputs * self.w\n\n model = SubclassModel()\n\n with self.assertRaisesRegexp(\n ValueError, 'Weights for model .* have not yet been created'):\n _ = model.weights\n\n model(keras.Input((10,)))\n self.assertEqual(len(model.weights), 1)\n\n def test_subclass_model_without_build_method(self):\n class SubclassModel(keras.models.Model):\n\n def __init__(self):\n super(SubclassModel, self).__init__()\n self.w = self.add_weight(shape=(), initializer='ones')\n\n def call(self, inputs):\n return inputs * self.w\n\n model = SubclassModel()\n self.assertEqual(len(model.weights), 1)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass DTypeTest(keras_parameterized.TestCase):\n\n @testing_utils.enable_v2_dtype_behavior\n def test_graph_network_dtype(self):\n inputs = keras.Input((10,))\n outputs = keras.layers.Dense(10)(inputs)\n network = network_lib.Network(inputs, outputs)\n self.assertEqual(network.dtype, 'float32')\n\n @testing_utils.enable_v2_dtype_behavior\n def test_subclassed_network_dtype(self):\n\n class IdentityNetwork(network_lib.Network):\n\n def call(self, inputs):\n return inputs\n\n network = IdentityNetwork()\n self.assertEqual(network.dtype, 'float32')\n self.assertEqual(network(array_ops.constant(1, 'float64')).dtype, 'float32')\n\n network = IdentityNetwork(dtype='float16')\n self.assertEqual(network.dtype, 'float16')\n self.assertEqual(network(array_ops.constant(1, 'float64')).dtype, 'float16')\n\n network = IdentityNetwork(autocast=False)\n self.assertEqual(network.dtype, 'float32')\n self.assertEqual(network(array_ops.constant(1, 'float64')).dtype, 'float64')\n\n\nclass AttrTrackingLayer(base_layer.Layer):\n \"\"\"Count how many times `dynamic` and `stateful` are called.\n\n These counts are used to test that the attribute cache behaves as expected.\n \"\"\"\n def __init__(self, *args, **kwargs):\n self.stateful_count = 0\n self.dynamic_count = 0\n super(AttrTrackingLayer, self).__init__(*args, **kwargs)\n\n @base_layer.Layer.stateful.getter\n def stateful(self):\n self.stateful_count += 1\n return super(AttrTrackingLayer, self).stateful\n\n @property\n def dynamic(self):\n self.dynamic_count += 1\n return super(AttrTrackingLayer, self).dynamic\n\n\nclass CacheCorrectnessTest(keras_parameterized.TestCase):\n def layer_and_network_test(self):\n # Top level layer\n network = network_lib.Network()\n\n layer_0 = AttrTrackingLayer()\n\n sub_network = network_lib.Network()\n layer_1 = AttrTrackingLayer(dynamic=True)\n layer_2 = AttrTrackingLayer()\n sub_network.sub_layers = [layer_1, layer_2]\n\n network.sub_layer = layer_0\n\n for _ in range(2):\n self.assertEqual(network.dynamic, False)\n self.assertEqual(network.stateful, False)\n\n # The second pass should be a cache hit.\n self.assertEqual(layer_0.dynamic_count, 1)\n self.assertEqual(layer_0.stateful_count, 1)\n\n # Mutations of the sub-layer should force recalculation of the network's\n # stateful attribute. (mutations bubble up.)\n layer_0.stateful = True\n self.assertEqual(network.stateful, True)\n self.assertEqual(layer_0.stateful_count, 2)\n\n layer_0.stateful = False\n self.assertEqual(network.stateful, False)\n self.assertEqual(layer_0.stateful_count, 3)\n\n # But changing stateful should not affect dynamic.\n self.assertEqual(network.dynamic, False)\n self.assertEqual(layer_0.dynamic_count, 1)\n\n network.sub_network = sub_network\n\n # Adding to the topology should invalidate the cache and reflect in the top\n # level network.\n self.assertEqual(network.dynamic, True)\n self.assertEqual(layer_0.dynamic_count, 2)\n self.assertEqual(layer_1.dynamic_count, 1)\n\n # Still dynamic, but we need to recompute.\n sub_network.sub_layers.pop()\n self.assertEqual(network.dynamic, True)\n self.assertEqual(layer_0.dynamic_count, 3)\n self.assertEqual(layer_1.dynamic_count, 2)\n\n # Now that we've removed the dynamic layer deep in the layer hierarchy, we\n # need to make sure that that bubbles up through all the levels.\n sub_network.sub_layers.pop()\n self.assertEqual(network.dynamic, False)\n self.assertEqual(layer_0.dynamic_count, 4)\n self.assertEqual(layer_1.dynamic_count, 2)\n\n # Now check with a tracked dict.\n sub_network.sub_layers = {\n \"layer_1\": layer_1,\n \"layer_2\": layer_2,\n }\n\n self.assertEqual(network.dynamic, True)\n self.assertEqual(layer_0.dynamic_count, 5)\n self.assertEqual(layer_1.dynamic_count, 3)\n\n # In-place assignment should still invalidate the cache.\n sub_network.sub_layers[\"layer_1\"] = layer_1\n self.assertEqual(network.dynamic, True)\n self.assertEqual(layer_0.dynamic_count, 6)\n self.assertEqual(layer_1.dynamic_count, 4)\n\n sub_network.sub_layers[\"layer_1\"] = None\n for _ in range(2):\n self.assertEqual(network.dynamic, False)\n self.assertEqual(layer_0.dynamic_count, 7)\n self.assertEqual(layer_1.dynamic_count, 4)\n\n layer_3 = AttrTrackingLayer()\n layer_3.stateful = True\n\n sub_network.sub_layers = None\n self.assertEqual(network.dynamic, False)\n self.assertEqual(network.stateful, False)\n\n # Test duplicate layers.\n sub_network.sub_layers = [layer_1, layer_1, layer_1, layer_3]\n self.assertEqual(network.dynamic, True)\n self.assertEqual(network.stateful, True)\n\n for _ in range(3):\n sub_network.sub_layers.pop()\n self.assertEqual(network.dynamic, True)\n self.assertEqual(network.stateful, False)\n\n sub_network.sub_layers.pop()\n self.assertEqual(network.dynamic, False)\n self.assertEqual(network.stateful, False)\n\n\n\nif __name__ == '__main__':\n test.main()\n" ]
[ [ "tensorflow.python.data.util.nest.map_structure_up_to", "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.framework.ops.add_to_collection", "tensorflow.python.ops.gen_dataset_ops.serialize_iterator", "tensorflow.python.framework.ops.device", "tensorflow.python.eager.context.context", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.data.util.structure.get_flat_tensor_types", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.data.util.structure.from_compatible_tensor_list", "tensorflow.python.eager.context.execution_mode", "tensorflow.python.ops.gen_dataset_ops.make_iterator", "tensorflow.python.eager.context.graph_mode", "tensorflow.python.util.deprecation.deprecated", "tensorflow.python.ops.gen_dataset_ops.deserialize_iterator", "tensorflow.python.eager.context.eager_mode", "tensorflow.python.data.util.structure.from_tensor_list", "tensorflow.python.data.util.structure.get_flat_tensor_shapes", "tensorflow.python.data.util.nest.assert_same_structure", "tensorflow.python.framework.ops.colocate_with", "tensorflow.python.training.saver.BaseSaverBuilder.SaveSpec", "tensorflow.python.ops.gen_dataset_ops.delete_iterator", "tensorflow.python.data.util.structure.convert_legacy_structure", "tensorflow.python.data.util.nest.map_structure", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.data.util.nest.flatten", "tensorflow.python.ops.gen_dataset_ops.iterator_get_next_sync", "tensorflow.python.ops.gen_dataset_ops.iterator_to_string_handle", "tensorflow.python.framework.tensor_spec.TensorSpec", "tensorflow.python.ops.gen_dataset_ops.iterator_get_next", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.gen_dataset_ops.anonymous_iterator_v2" ], [ "tensorflow.python.keras.backend.variable", "tensorflow.python.keras.layers.ZeroPadding3D", "tensorflow.python.keras.layers.Conv2D", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.keras.layers.UpSampling2D", "tensorflow.python.platform.test.main", "tensorflow.python.keras.layers.Cropping2D", "numpy.repeat", "numpy.zeros", "tensorflow.python.platform.test.is_gpu_available", "tensorflow.python.keras.testing_utils.layer_test", "tensorflow.python.keras.layers.UpSampling3D", "numpy.random.rand", "tensorflow.python.keras.layers.Conv1D", "numpy.testing.assert_allclose", "numpy.random.random", "tensorflow.python.keras.layers.ZeroPadding2D", "tensorflow.python.keras.backend.eval", "tensorflow.python.keras.layers.ZeroPadding1D", "tensorflow.python.keras.layers.Cropping3D", "numpy.ones", "tensorflow.python.keras.layers.Cropping1D", "tensorflow.python.framework.test_util.for_all_test_methods", "tensorflow.python.keras.layers.Conv3D" ], [ "tensorflow.python.ops.linalg.linalg_impl.adjoint", "tensorflow.python.ops.linalg.linalg_impl.norm", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.linalg.linear_operator_util.convert_nonref_to_tensor", "tensorflow.python.ops.array_ops.matrix_diag_part", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.ops.math_ops.conj", "tensorflow.python.framework.errors.InvalidArgumentError" ], [ "tensorflow.python.keras.layers.Lambda", "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.framework.test_util.run_in_graph_and_eager_modes", "tensorflow.python.ops.array_ops.constant", "tensorflow.python.keras.layers.Dense", "tensorflow.python.ops.state_ops.assign_add", "tensorflow.python.keras.backend.placeholder", "tensorflow.python.keras.backend.int_shape", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.keras.backend.function", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.keras.backend.dot", "tensorflow.python.keras.layers.Conv2D", "numpy.any", "tensorflow.python.keras.layers.GlobalAveragePooling2D", "tensorflow.python.keras.layers.Multiply", "tensorflow.python.eager.context.executing_eagerly", "numpy.random.randint", "tensorflow.python.keras.layers.BatchNormalization", "tensorflow.python.keras.layers.concatenate", "tensorflow.python.keras.testing_utils.get_small_mlp", "tensorflow.python.keras.layers.add", "tensorflow.python.platform.test.main", "tensorflow.python.keras.models.Model.from_config", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.keras.Sequential", "numpy.zeros", "tensorflow.python.keras.layers.Add", "numpy.min", "tensorflow.python.keras.utils.tf_utils.get_reachable_from_inputs", "tensorflow.python.keras.Model", "tensorflow.python.keras.testing_utils.should_run_tf_function", "tensorflow.python.keras.layers.Masking", "tensorflow.python.keras.engine.input_layer.Input", "tensorflow.python.keras.utils.layer_utils.get_source_inputs", "tensorflow.python.keras.models.Sequential", "tensorflow.python.keras.models.model_from_yaml", "tensorflow.python.ops.math_ops.reduce_mean", "tensorflow.python.keras.layers.Dropout", "tensorflow.python.keras.layers.Input", "tensorflow.python.keras.layers.InputLayer", "tensorflow.python.keras.testing_utils.should_run_eagerly", "tensorflow.python.keras.layers.wrappers.TimeDistributed", "tensorflow.python.keras.models.model_from_json", "tensorflow.python.ops.array_ops.ones_like", "numpy.random.random", "tensorflow.python.keras.engine.network.Network", "tensorflow.python.keras.Input", "tensorflow.python.keras.layers.LSTMCell", "numpy.ones", "tensorflow.python.keras.initializers.Constant", "tensorflow.python.keras.models.Model", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.training.tracking.util.Checkpoint", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.keras.engine.training.Model" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2" ] } ]
ycwu1030/CosmoTransitions
[ "dabf3fe02c05d13458571e84398a148aad5aec4c" ]
[ "cosmoTransitions/tunneling1D.py" ]
[ "\"\"\"\nThis module (along with a few functions in :mod:`.helper_functions`) contains\neverything that is needed to calculate instantons in one field dimension.\nThe primary class is :class:`SingleFieldInstanton`, which can calculate the\ninstanton solution in any number of spatial dimensions using the overshoot /\nundershoot method. Additional classes inherit common functionality from this\none, and can be used to calculate the bubble wall profile with constant\nfriction (:class:`WallWithConstFriction`) instead of radius-dependent friction,\nor to calculate the instanton in the presence of gravity (*not yet\nimplemented*).\n\n.. todo::\n Create and document a *CDL_Instanton* class for tunneling with gravity.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom scipy import optimize, integrate, special, interpolate\nfrom collections import namedtuple\n\nfrom . import helper_functions\nfrom .helper_functions import rkqs, IntegrationError, clampVal\nfrom .helper_functions import cubicInterpFunction\n\nimport sys\nif sys.version_info >= (3,0):\n xrange = range\n\n\nclass PotentialError(Exception):\n \"\"\"\n Used when the potential does not have the expected characteristics.\n\n The error messages should be tuples, with the second item being one of\n ``(\"no barrier\", \"stable, not metastable\")``.\n \"\"\"\n pass\n\n\nclass SingleFieldInstanton:\n \"\"\"\n This class will calculate properties of an instanton with a single scalar\n Field without gravity using the overshoot/undershoot method.\n\n Most users will probably be primarily interested in the functions\n :func:`findProfile` and :func:`findAction`.\n\n Note\n ----\n When the bubble is thin-walled (due to nearly degenerate minima), an\n approximate solution is found to the equations of motion and integration\n starts close to the wall itself (instead of always starting at the center\n of the bubble). This way the overshoot/undershoot method runs just as fast\n for extremely thin-walled bubbles as it does for thick-walled bubbles.\n\n Parameters\n ----------\n phi_absMin : float\n The field value at the stable vacuum to which the instanton\n tunnels. Nowhere in the code is it *required* that there actually be a\n minimum at `phi_absMin`, but the :func:`findProfile` function will only\n use initial conditions between `phi_absMin` and `phi_metaMin`, and the\n code is optimized for thin-walled bubbles when the center of the\n instanton is close to `phi_absMin`.\n phi_metaMin : float\n The field value in the metastable vacuum.\n V : callable\n The potential function. It should take as its single parameter the field\n value `phi`.\n dV, d2V : callable, optional\n The potential's first and second derivatives. If not None, these\n override the methods :func:`dV` and :func:`d2V`.\n phi_eps : float, optional\n A small value used to calculate derivatives (if not overriden by\n the user) and in the function :func:`dV_from_absMin`. The input should\n be unitless; it is later rescaled by ``abs(phi_absMin - phi_metaMin)``.\n alpha : int or float, optional\n The coefficient for the friction term in the ODE. This is also\n the number of spacetime dimensions minus 1.\n phi_bar : float, optional\n The field value at the edge of the barrier. If `None`, it is found by\n :func:`findBarrierLocation`.\n rscale : float, optional\n The approximate radial scale of the instanton. If `None` it is found by\n :func:`findRScale`.\n\n Raises\n ------\n PotentialError\n when the barrier is non-existent or when the presumably stable minimum\n has a higher energy that the metastable minimum.\n\n Examples\n --------\n Thick and thin-walled bubbles:\n\n .. plot::\n :include-source:\n\n from cosmoTransitions.tunneling1D import SingleFieldInstanton\n import matplotlib.pyplot as plt\n\n # Thin-walled\n def V1(phi): return 0.25*phi**4 - 0.49*phi**3 + 0.235 * phi**2\n def dV1(phi): return phi*(phi-.47)*(phi-1)\n profile = SingleFieldInstanton(1.0, 0.0, V1, dV1).findProfile()\n plt.plot(profile.R, profile.Phi)\n\n # Thick-walled\n def V2(phi): return 0.25*phi**4 - 0.4*phi**3 + 0.1 * phi**2\n def dV2(phi): return phi*(phi-.2)*(phi-1)\n profile = SingleFieldInstanton(1.0, 0.0, V2, dV2).findProfile()\n plt.plot(profile.R, profile.Phi)\n\n plt.xlabel(r\"Radius $r$\")\n plt.ylabel(r\"Field $\\phi$\")\n plt.show()\n \"\"\"\n def __init__(self, phi_absMin, phi_metaMin, V,\n dV=None, d2V=None, phi_eps=1e-3, alpha=2,\n phi_bar=None, rscale=None):\n self.phi_absMin, self.phi_metaMin = phi_absMin, phi_metaMin\n self.V = V\n if V(phi_metaMin) <= V(phi_absMin):\n raise PotentialError(\"V(phi_metaMin) <= V(phi_absMin); \"\n \"tunneling cannot occur.\", \"stable, not metastable\")\n if dV is not None:\n self.dV = dV\n if d2V is not None:\n self.d2V = d2V\n if phi_bar is None:\n self.phi_bar = self.findBarrierLocation()\n else:\n self.phi_bar = phi_bar\n if rscale is None:\n self.rscale = self.findRScale()\n else:\n self.rscale = rscale\n self.alpha = alpha\n self.phi_eps = phi_eps * abs(phi_absMin - phi_metaMin)\n\n def dV(self, phi):\n R\"\"\"\n Calculates `dV/dphi` using finite differences.\n\n The finite difference is given by `self.phi_eps`, and the derivative\n is calculated to fourth order.\n \"\"\"\n eps = self.phi_eps\n V = self.V\n return (V(phi-2*eps) - 8*V(phi-eps) + 8*V(phi+eps) - V(phi+2*eps)\n ) / (12.*eps)\n\n def dV_from_absMin(self, delta_phi):\n R\"\"\"\n Calculates `dV/dphi` at ``phi = phi_absMin + delta_phi``.\n\n It is sometimes helpful to find `dV/dphi` extremely close to the\n minimum. In this case, floating-point error can be significant. To get\n increased accuracy, this function expands about the minimum in\n a Taylor series and uses that for nearby values. That is,\n :math:`V'(\\phi) \\approx V''(\\phi_{\\rm absMin})(\\phi-\\phi_{\\rm absMin})`.\n For values that are farther away, it instead uses :func:`dV`.\n It blends the two methods so that there are no numerical\n discontinuities.\n\n This uses `self.phi_eps` to determine whether the field is considered\n nearby or not.\n \"\"\"\n phi = self.phi_absMin + delta_phi\n dV = self.dV(phi)\n # If phi is very close to phi_absMin, it should be safer to assume\n # that dV is zero exactly at phi_absMin and instead calculate dV from\n # d2V.\n if self.phi_eps > 0:\n dV_ = self.d2V(phi) * delta_phi\n # blend the two together so that there are no discontinuites\n blend_factor = np.exp(-(delta_phi/self.phi_eps)**2)\n dV = dV_*blend_factor + dV*(1-blend_factor)\n return dV\n\n def d2V(self, phi):\n R\"\"\"\n Calculates `d^2V/dphi^2` using finite differences.\n\n The finite difference is given by `self.phi_eps`, and the derivative\n is calculated to fourth order.\n \"\"\"\n eps = self.phi_eps\n V = self.V\n return (-V(phi-2*eps) + 16*V(phi-eps) - 30*V(phi)\n + 16*V(phi+eps) - V(phi+2*eps)) / (12.*eps*eps)\n\n def findBarrierLocation(self):\n R\"\"\"\n Find edge of the potential barrier.\n\n Returns\n -------\n phi_barrier : float\n The value such that `V(phi_barrier) = V(phi_metaMin)`\n \"\"\"\n phi_tol = abs(self.phi_metaMin - self.phi_absMin) * 1e-12\n V_phimeta = self.V(self.phi_metaMin)\n phi1 = self.phi_metaMin\n phi2 = self.phi_absMin\n phi0 = 0.5 * (phi1+phi2)\n\n # Do a very simple binary search to narrow down on the right answer.\n while abs(phi1-phi2) > phi_tol:\n V0 = self.V(phi0)\n if V0 > V_phimeta:\n phi1 = phi0\n else:\n phi2 = phi0\n phi0 = 0.5 * (phi1+phi2)\n return phi0\n\n def findRScale(self):\n R\"\"\"\n Find the characteristic length scale for tunneling over the potential\n barrier.\n\n The characteristic length scale should formally be given by the period\n of oscillations about the top of the potential barrier. However, it is\n perfectly acceptable for the potential barrier to have a flat top, in\n which case a naive calculation of the length scale would be infinite.\n Instead, this function finds the top of the barrier along with a cubic\n function that has a maximum at the barrier top and a minimum at the\n metastable minimum. The returned length scale is then the period of\n oscillations about this cubic maximum.\n\n Raises\n ------\n PotentialError\n when the barrier is non-existent.\n \"\"\"\n \"\"\"\n NOT USED:\n We could also do a sanity check in case the barrier goes to zero.\n A second way of finding the scale is to see how long it would take\n the field to roll from one minimum to the other if the potential were\n purely linear and there were no friction.\n\n Parameters\n ----------\n second_check : float\n If bigger than zero, do the sanity check. Return value is then the\n larger of the first scale and the second scale times\n `second_check`.\n \"\"\"\n phi_tol = abs(self.phi_bar - self.phi_metaMin) * 1e-6\n x1 = min(self.phi_bar, self.phi_metaMin)\n x2 = max(self.phi_bar, self.phi_metaMin)\n phi_bar_top = optimize.fminbound(\n lambda x: -self.V(x), x1, x2, xtol=phi_tol)\n if phi_bar_top + phi_tol > x2 or phi_bar_top - phi_tol < x1:\n raise PotentialError(\n \"Minimization is placing the top of the \"\n \"potential barrier outside of the interval defined by \"\n \"phi_bar and phi_metaMin. Assume that the barrier does not exist.\",\n \"no barrier\")\n\n Vtop = self.V(phi_bar_top) - self.V(self.phi_metaMin)\n xtop = phi_bar_top - self.phi_metaMin\n # Cubic function given by (ignoring linear and constant terms):\n # f(x) = C [(-1/3)x^3 + (1/2)x^2 xtop]\n # C = 6 Vtop / xtop^3\n # f''(xtop) = - C xtop\n # d2V = -6*Vtop / xtop**2\n # rscale = 1 / sqrt(d2V)\n if Vtop <= 0:\n raise PotentialError(\"Barrier height is not positive, \"\n \"does not exist.\", \"no barrier\")\n rscale1 = abs(xtop) / np.sqrt(abs(6*Vtop))\n return rscale1\n # The following would calculate it a separate way, but this goes\n # to infinity when delta_V goes to zero, so it's a bad way of doing it\n delta_phi = abs(self.phi_absMin - self.phi_metaMin)\n delta_V = abs(self.V(self.phi_absMin) - self.V(self.phi_metaMin))\n rscale2 = np.sqrt(2*delta_phi**2 / (delta_V+1e-100))\n return max(rscale1, rscale2)\n\n _exactSolution_rval = namedtuple(\"exactSolution_rval\", \"phi dphi\")\n def exactSolution(self, r, phi0, dV, d2V):\n R\"\"\"\n Find `phi(r)` given `phi(r=0)`, assuming a quadratic potential.\n\n Parameters\n ----------\n r : float\n The radius at which the solution should be calculated.\n phi0 : float\n The field at `r=0`.\n dV, d2V : float\n The potential's first and second derivatives evaluated at `phi0`.\n\n Returns\n -------\n phi, dphi : float\n The field and its derivative evaluated at `r`.\n\n Notes\n -----\n\n If the potential at the point :math:`\\phi_0` is a simple quadratic, the\n solution to the instanton equation of motion can be determined exactly.\n The non-singular solution to\n\n .. math::\n \\frac{d^2\\phi}{dr^2} + \\frac{\\alpha}{r}\\frac{d\\phi}{dr} =\n V'(\\phi_0) + V''(\\phi_0) (\\phi-\\phi_0)\n\n is\n\n .. math::\n \\phi(r)-\\phi_0 = \\frac{V'}{V''}\\left[\n \\Gamma(\\nu+1)\\left(\\frac{\\beta r}{2}\\right)^{-\\nu} I_\\nu(\\beta r) - 1\n \\right]\n\n where :math:`\\nu = \\frac{\\alpha-1}{2}`, :math:`I_\\nu` is the modified\n Bessel function, and :math:`\\beta^2 = V''(\\phi_0) > 0`. If instead\n :math:`-\\beta^2 = V''(\\phi_0) < 0`, the solution is the same but with\n :math:`I_\\nu \\rightarrow J_\\nu`.\n\n \"\"\"\n beta = np.sqrt(abs(d2V))\n beta_r = beta*r\n nu = 0.5 * (self.alpha - 1)\n gamma = special.gamma # Gamma function\n iv, jv = special.iv, special.jv # (modified) Bessel function\n if beta_r < 1e-2:\n # Use a small-r approximation for the Bessel function.\n s = +1 if d2V > 0 else -1\n phi = 0.0\n dphi = 0.0\n for k in xrange(1,4):\n _ = (0.5*beta_r)**(2*k-2) * s**k / (gamma(k+1)*gamma(k+1+nu))\n phi += _\n dphi += _ * (2*k)\n phi *= 0.25 * gamma(nu+1) * r**2 * dV * s\n dphi *= 0.25 * gamma(nu+1) * r * dV * s\n phi += phi0\n elif d2V > 0:\n import warnings\n # If beta_r is very large, this will throw off overflow and divide\n # by zero errors in iv(). It will return np.inf though, which is\n # what we want. Just ignore the warnings.\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n phi = (gamma(nu+1)*(0.5*beta_r)**-nu * iv(nu, beta_r)-1) * dV/d2V\n dphi = -nu*((0.5*beta_r)**-nu / r) * iv(nu, beta_r)\n dphi += (0.5*beta_r)**-nu * 0.5*beta \\\n * (iv(nu-1, beta_r)+iv(nu+1, beta_r))\n dphi *= gamma(nu+1) * dV/d2V\n phi += phi0\n else:\n phi = (gamma(nu+1)*(0.5*beta_r)**-nu * jv(nu, beta_r) - 1) * dV/d2V\n dphi = -nu*((0.5*beta_r)**-nu / r) * jv(nu, beta_r)\n dphi += (0.5*beta_r)**-nu * 0.5*beta \\\n * (jv(nu-1, beta_r)-jv(nu+1, beta_r))\n dphi *= gamma(nu+1) * dV/d2V\n phi += phi0\n return self._exactSolution_rval(phi, dphi)\n\n _initialConditions_rval = namedtuple(\n \"initialConditions_rval\", \"r0 phi dphi\")\n def initialConditions(self, delta_phi0, rmin, delta_phi_cutoff):\n R\"\"\"\n Finds the initial conditions for integration.\n\n The instanton equations of motion are singular at `r=0`, so we\n need to start the integration at some larger radius. This\n function finds the value `r0` such that `phi(r0) = phi_cutoff`.\n If there is no such value, it returns the intial conditions at `rmin`.\n\n Parameters\n ----------\n delta_phi0 : float\n `delta_phi0 = phi(r=0) - phi_absMin`\n rmin : float\n The smallest acceptable radius at which to start integration.\n delta_phi_cutoff : float\n The desired value for `phi(r0)`.\n `delta_phi_cutoff = phi(r0) - phi_absMin`.\n\n Returns\n -------\n r0, phi, dphi : float\n The initial radius and the field and its derivative at that radius.\n\n Notes\n -----\n The field values are calculated using :func:`exactSolution`.\n \"\"\"\n phi0 = self.phi_absMin + delta_phi0\n dV = self.dV_from_absMin(delta_phi0)\n d2V = self.d2V(phi0)\n phi_r0, dphi_r0 = self.exactSolution(rmin, phi0, dV, d2V)\n if abs(phi_r0 - self.phi_absMin) > abs(delta_phi_cutoff):\n # The initial conditions at rmin work. Stop here.\n return self._initialConditions_rval(rmin, phi_r0, dphi_r0)\n if np.sign(dphi_r0) != np.sign(delta_phi0):\n # The field is evolving in the wrong direction.\n # Increasing r0 won't increase |delta_phi_r0|/\n return rmin, phi_r0, dphi_r0\n\n # Find the smallest r0 such that delta_phi_r0 > delta_phi_cutoff\n r = rmin\n while np.isfinite(r):\n rlast = r\n r *= 10\n phi, dphi = self.exactSolution(r, phi0, dV, d2V)\n if abs(phi - self.phi_absMin) > abs(delta_phi_cutoff):\n break\n\n # Now find where phi - self.phi_absMin = delta_phi_cutoff exactly\n\n def deltaPhiDiff(r_):\n p = self.exactSolution(r_, phi0, dV, d2V)[0]\n return abs(p - self.phi_absMin) - abs(delta_phi_cutoff)\n\n r0 = optimize.brentq(deltaPhiDiff, rlast, r, disp=False)\n phi_r0, dphi_r0 = self.exactSolution(r0, phi0, dV, d2V)\n return self._initialConditions_rval(r0, phi_r0, dphi_r0)\n\n def equationOfMotion(self, y, r):\n \"\"\"\n Used to integrate the bubble wall.\n \"\"\"\n return np.array([y[1], self.dV(y[0])-self.alpha*y[1]/r])\n\n _integrateProfile_rval = namedtuple(\n \"integrateProfile_rval\", \"r y convergence_type\")\n def integrateProfile(self, r0, y0, dr0,\n epsfrac, epsabs, drmin, rmax, *eqn_args):\n R\"\"\"\n Integrate the bubble wall equation:\n\n .. math::\n \\frac{d^2\\phi}{dr^2} + \\frac{\\alpha}{r}\\frac{d\\phi}{dr} =\n \\frac{dV}{d\\phi}.\n\n The integration will stop when it either overshoots or undershoots\n the false vacuum minimum, or when it converges upon the false vacuum\n minimum.\n\n Parameters\n ----------\n r0 : float\n The starting radius for the integration.\n y0 : array_like\n The starting values [phi(r0), dphi(r0)].\n dr0 : float\n The starting integration stepsize.\n epsfrac, epsabs : float\n The error tolerances used for integration. This is fed into\n :func:`helper_functions.rkqs` and is used to test for convergence.\n drmin : float\n The minimum allowed value of `dr` before raising an error.\n rmax : float\n The maximum allowed value of `r-r0` before raising an error.\n eqn_args : tuple\n Extra arguments to pass to :func:`equationOfMotion`. Useful for\n subclasses.\n\n Returns\n -------\n r : float\n The final radius.\n y : array_like\n The final field values [phi, dphi]\n convergence_type : str\n Either 'overshoot', 'undershoot', or 'converged'.\n\n Raises\n ------\n helper_functions.IntegrationError\n \"\"\"\n dr = dr0\n # dY is the ODE that we use\n def dY(y,r,args=eqn_args):\n return self.equationOfMotion(y,r,*args)\n dydr0 = dY(y0, r0)\n ysign = np.sign(y0[0]-self.phi_metaMin)\n # positive means we're heading down, negative means heading up.\n rmax += r0\n\n convergence_type = None\n while True:\n dy, dr, drnext = rkqs(y0, dydr0, r0, dY, dr, epsfrac, epsabs)\n r1 = r0 + dr\n y1 = y0 + dy\n dydr1 = dY(y1,r1)\n\n # Check for completion\n if (r1 > rmax):\n raise IntegrationError(\"r > rmax\")\n elif (dr < drmin):\n raise IntegrationError(\"dr < drmin\")\n elif (abs(y1 - np.array([self.phi_metaMin,0])) < 3*epsabs).all():\n r,y = r1,y1\n convergence_type = \"converged\"\n break\n\n elif y1[1]*ysign > 0 or (y1[0]-self.phi_metaMin)*ysign < 0:\n f = cubicInterpFunction(y0, dr*dydr0, y1, dr*dydr1)\n if(y1[1]*ysign > 0):\n # Extrapolate to where dphi(r) = 0\n x = optimize.brentq(lambda x: f(x)[1], 0, 1)\n convergence_type = \"undershoot\"\n else:\n # Extrapolate to where phi(r) = phi_metaMin\n x = optimize.brentq(lambda x: f(x)[0]-self.phi_metaMin, 0,1)\n convergence_type = \"overshoot\"\n r = r0 + dr*x\n y = f(x)\n break\n # Advance the integration variables\n r0,y0,dydr0 = r1,y1,dydr1\n dr = drnext\n # Check convergence for a second time.\n # The extrapolation in overshoot/undershoot might have gotten us within\n # the acceptable error.\n if (abs(y - np.array([self.phi_metaMin,0])) < 3*epsabs).all():\n convergence_type = \"converged\"\n return self._integrateProfile_rval(r, y, convergence_type)\n\n profile_rval = namedtuple(\"Profile1D\", \"R Phi dPhi Rerr\")\n def integrateAndSaveProfile(self, R, y0, dr,\n epsfrac, epsabs,drmin, *eqn_args):\n \"\"\"\n Integrate the bubble profile, saving the output in an array.\n\n Parameters\n ----------\n R: array_like\n The array of points at which we want to save the profile.\n y0 : float\n The starting values [phi(r0), dphi(r0)].\n dr : float\n Starting stepsize.\n epsfrac, epsabs : float\n The error tolerances used for integration. This\n is fed into :func:`helper_functions.rkqs`.\n drmin : float\n The smallest allowed stepsize.\n eqn_args : tuple\n Extra arguments to pass to :func:`equationOfMotion`. Useful for\n subclasses.\n\n Returns\n -------\n R, Phi, dPhi : array_like\n Radii and field values which make up the bubble profile.\n Rerr : float or None\n The first value of `r` at which ``dr < drmin``, or `None` if\n ``dr >= drmin`` always.\n\n Notes\n -----\n Subclasses can use this function without overriding it even if the\n subclass uses more fields/values in its equation of motion (i.e.,\n ``len(y0) > 2``). This is accomplished by setting the class variable\n `profile_rval` to a different named tuple type with more than four\n inputs. The first three should always be *R, Phi, dPhi*, and the last\n one should be *Rerr*, but additional values can be stuck in between.\n \"\"\"\n N = len(R)\n R, r0 = np.array(R), R[0]\n Yout = np.zeros((N,len(y0)))\n Yout[0] = y0\n # dY is the ODE that we use\n def dY(y,r,args=eqn_args):\n return self.equationOfMotion(y,r,*args)\n dydr0 = dY(y0, r0)\n Rerr = None\n\n i = 1\n while i < N:\n dy, dr, drnext = rkqs(y0, dydr0, r0, dY, dr, epsfrac, epsabs)\n if (dr >= drmin):\n r1 = r0 + dr\n y1 = y0 + dy\n else:\n y1 = y0 + dy*drmin/dr\n dr = drnext = drmin\n r1 = r0 + dr\n if Rerr is not None: Rerr = r1\n dydr1 = dY(y1,r1)\n # Fill the arrays, if necessary\n if (r0 < R[i] <= r1):\n f = cubicInterpFunction(y0, dr*dydr0, y1, dr*dydr1)\n while (i < N and r0 < R[i] <= r1):\n x = (R[i]-r0)/dr\n Yout[i] = f(x)\n i += 1\n\n # Advance the integration variables\n r0,y0,dydr0 = r1,y1,dydr1\n dr = drnext\n\n rval = (R,)+tuple(Yout.T)+eqn_args+(Rerr,)\n return self.profile_rval(*rval)\n\n def findProfile(self, xguess=None, xtol=1e-4, phitol=1e-4,\n thinCutoff=.01, npoints=500, rmin=1e-4, rmax=1e4,\n max_interior_pts=None):\n R\"\"\"\n Calculate the bubble profile by iteratively over/undershooting.\n\n This will call :func:`integrateProfile` many times, trying to find\n the correct initial condition `phi(r=0)` such that the field ends up\n in the metastable vacuum at infinity. Once the correct initial\n condition is found, it calls :func:`integrateAndSaveProfile` to find\n the profile along the length of the wall.\n\n Parameters\n ----------\n xguess : float, optional\n The initial guess for `x`. If `None`, `xguess` is set such\n that ``phi_guess = self.phi_bar``.\n xtol : float, optional\n Target accuracy in `x`.\n phitol : float, optional\n Fractional error tolerance in integration.\n thinCutoff : float, optional\n Equal to `delta_phi_cutoff / (phi_metaMin - phi_absMin)`, where\n `delta_phi_cutoff` is used in :func:`initialConditions`.\n npoints : int\n Number of points to return in the profile.\n rmin : float\n Relative to ``self.rscale``. Sets the smallest starting\n radius, the starting stepsize, and the smallest allowed stepsize\n (``0.01*rmin``).\n rmax : float\n Relative ``self.rscale``. Sets the maximum allowed integration\n distance.\n max_interior_pts : int\n Maximum number of points to place between ``r=0`` and the start of\n integration. If None, ``max_interior_pts=npoints/2``. If zero, no\n points are added to the bubble interior.\n\n Returns\n -------\n R, Phi, dPhi : array_like\n Radii and field values which make up the bubble profile. Note that\n `R[0]` can be much bigger than zero for thin-walled bubbles.\n Rerr : float or None\n The first value of `r` at which ``dr < drmin``, or `None` if\n ``dr >= drmin`` always.\n\n Notes\n -----\n For very thin-walled bubbles, the initially value of `phi` can be\n extremely close to the stable minimum and small variations in `phi`\n can cause large variations in the integration. Rather than varying\n `phi(r=0)` directly, it is easier to vary a parameter `x` defined by\n\n .. math::\n \\phi(r=0) = \\phi_{\\rm absMin}\n + e^{-x}(\\phi_{\\rm metaMin}-\\phi_{\\rm absMin})\n\n This way, `phi = phi_metaMin` when `x` is zero and\n `phi = phi_absMin` when `x` is infinity.\n \"\"\"\n # Set x parameters\n xmin = xtol*10\n xmax = np.inf\n if xguess is not None:\n x = xguess\n else:\n x = -np.log(abs((self.phi_bar-self.phi_absMin) /\n (self.phi_metaMin-self.phi_absMin)))\n xincrease = 5.0\n # The relative amount to increase x by if there is no upper bound.\n # --\n # Set r parameters\n rmin *= self.rscale\n dr0 = rmin\n drmin = 0.01*rmin\n rmax *= self.rscale\n # --\n # Set the phi parameters\n delta_phi = self.phi_metaMin - self.phi_absMin\n epsabs = abs(np.array([delta_phi, delta_phi/self.rscale])*phitol)\n epsfrac = np.array([1,1]) * phitol\n delta_phi_cutoff = thinCutoff * delta_phi\n # The sign for delta_phi_cutoff doesn't matter\n # --\n integration_args = (dr0, epsfrac, epsabs, drmin, rmax)\n rf = None\n while True:\n delta_phi0 = np.exp(-x)*delta_phi\n # r0, phi0, dphi0 = self.initialConditions(x, rmin, thinCutoff)\n r0_, phi0, dphi0 = self.initialConditions(\n delta_phi0, rmin, delta_phi_cutoff)\n if not np.isfinite(r0_) or not np.isfinite(x):\n # Use the last finite values instead\n # (assuming there are such values)\n assert rf is not None, \"Failed to retrieve initial \"\\\n \"conditions on the first try.\"\n break\n r0 = r0_\n y0 = np.array([phi0, dphi0])\n rf, yf, ctype = self.integrateProfile(r0, y0, *integration_args)\n # Check for overshoot, undershoot\n if ctype == \"converged\":\n break\n elif ctype == \"undershoot\": # x is too low\n xmin = x\n x = x*xincrease if xmax == np.inf else .5*(xmin+xmax)\n elif ctype == \"overshoot\": # x is too high\n xmax = x\n x = .5*(xmin+xmax)\n # Check if we've reached xtol\n if (xmax-xmin) < xtol:\n break\n\n # Integrate a second time, this time getting the points along the way\n R = np.linspace(r0, rf, npoints)\n profile = self.integrateAndSaveProfile(R, y0, dr0,\n epsfrac, epsabs, drmin)\n # Make points interior to the bubble.\n if max_interior_pts is None:\n max_interior_pts = len(R) // 2\n if max_interior_pts > 0:\n dx0 = R[1]-R[0]\n if R[0] / dx0 <= max_interior_pts:\n n = np.ceil(R[0]/dx0)\n R_int = np.linspace(0, R[0], n+1)[:-1]\n else:\n n = max_interior_pts\n # R[0] = dx0 * (n + a*n*(n+1)/2)\n a = (R[0]/dx0 - n) * 2/(n*(n+1))\n N = np.arange(1,n+1)[::-1]\n R_int = R[0] - dx0*(N + 0.5*a*N*(N+1))\n R_int[0] = 0.0 # enforce this exactly\n Phi_int = np.empty_like(R_int)\n dPhi_int = np.empty_like(R_int)\n Phi_int[0] = self.phi_absMin + delta_phi0\n dPhi_int[0] = 0.0\n dV = self.dV_from_absMin(delta_phi0)\n d2V = self.d2V(Phi_int[0])\n for i in xrange(1,len(R_int)):\n Phi_int[i], dPhi_int[i] = self.exactSolution(\n R_int[i], Phi_int[0], dV, d2V)\n R = np.append(R_int, profile.R)\n Phi = np.append(Phi_int, profile.Phi)\n dPhi = np.append(dPhi_int, profile.dPhi)\n profile = self.profile_rval(R,Phi,dPhi, profile.Rerr)\n return profile\n\n def findAction(self, profile):\n R\"\"\"\n Calculate the Euclidean action for the instanton:\n\n .. math::\n S = \\int [(d\\phi/dr)^2 + V(\\phi)] r^\\alpha dr d\\Omega_\\alpha\n\n Arguments\n ---------\n profile\n Output from :func:`findProfile()`.\n\n Returns\n -------\n float\n The Euclidean action.\n \"\"\"\n r, phi, dphi = profile.R, profile.Phi, profile.dPhi\n # Find the area of an n-sphere (alpha=n):\n d = self.alpha+1 # Number of dimensions in the integration\n area = r**self.alpha * 2*np.pi**(d*.5)/special.gamma(d*.5)\n # And integrate the profile\n integrand = 0.5 * dphi**2 + self.V(phi) - self.V(self.phi_metaMin)\n integrand *= area\n S = integrate.simps(integrand, r)\n # Find the bulk term in the bubble interior\n volume = r[0]**d * np.pi**(d*.5)/special.gamma(d*.5 + 1)\n S += volume * (self.V(phi[0]) - self.V(self.phi_metaMin))\n return S\n\n def evenlySpacedPhi(self, phi, dphi, npoints=100, k=1, fixAbs=True):\n \"\"\"\n This method takes `phi` and `dphi` as input, which will probably\n come from the output of :func:`findProfile`, and returns a different\n set of arrays `phi2` and `dphi2` such that `phi2` is linearly spaced\n (instead of `r`).\n\n Parameters\n ----------\n phi, dphi : array_like\n npoints : int\n The number of points to output.\n k : int\n The degree of spline fitting. ``k=1`` means linear interpolation.\n fixAbs : bool\n If true, make phi go all the way to `phi_absMin`.\n \"\"\"\n if fixAbs is True:\n phi = np.append(self.phi_absMin, np.append(phi, self.phi_metaMin))\n dphi = np.append(0.0, np.append(dphi, 0.0))\n else:\n phi = np.append(phi, self.phi_metaMin)\n dphi = np.append(dphi, 0.0)\n # Make sure that phi is increasing everywhere\n # (this is uglier than it ought to be)\n i = helper_functions.monotonicIndices(phi)\n # Now do the interpolation\n tck = interpolate.splrep(phi[i], dphi[i], k=k)\n if fixAbs:\n p = np.linspace(self.phi_absMin, self.phi_metaMin, npoints)\n else:\n p = np.linspace(phi[i][0], self.phi_metaMin, npoints)\n dp = interpolate.splev(p, tck)\n return p, dp\n\n\nclass WallWithConstFriction(SingleFieldInstanton):\n \"\"\"\n This class solves a modified version of the instanton equations of motion\n with a *constant* friction term.\n\n This may be useful if one wants to estimate the shape of a bubble wall\n moving through a plasma. It will, however, be a rough estimate since a real\n friction force would most likely be field-dependent.\n \"\"\"\n def findRScale(self):\n R\"\"\"\n Find the characteristic length scale for tunneling over the potential\n barrier.\n\n Since for this class the tunneling solution always goes between the two\n minima, we want to take the overall shape between the two (not just\n at the top of the barrier) to set the radial scale. This finds the scale\n by fitting a simple quadratic to the potential.\n\n Raises\n ------\n PotentialError\n when the barrier is non-existent.\n \"\"\"\n pA = self.phi_absMin\n pB = 0.5 * (self.phi_bar + self.phi_metaMin)\n pC = self.phi_metaMin\n yA = self.V(pA)\n yB = self.V(pB)\n yC = self.V(pC)\n # Let lmda be the quadratic coefficient that will fit these 3 points\n lmda = 2*((yA-yB)/(pA-pB) - (yB-yC)/(pB-pC)) / (pC-pA)\n if lmda <= 0.0:\n raise PotentialError(\"Cannot fit the potential to a negative \"\n \"quadratic.\", \"no barrier\")\n omega = np.sqrt(lmda) # frequency of oscillations\n return np.pi / omega\n\n def initialConditions(self, F, phi0_rel=1e-3):\n R\"\"\"\n Get the initial conditions for integration.\n\n Parameters\n ----------\n F : float\n Magnitude of the friction term.\n phi0_rel : float\n The initial value for the field, relative to the two minima\n with 0.0 being at `phi_absMin` and 1.0 being at `phi_metaMin`\n (should be close to 0.0).\n\n Returns\n -------\n r0, phi, dphi : float\n The initial radius and the field and its derivative at that radius.\n\n Notes\n -----\n Approximate the equation of motion near the minimum as\n\n .. math::\n\n \\phi'' + F \\phi' = (\\phi-\\phi_{absMin}) \\frac{d^2V}{d\\phi^2}\n\n which has solution\n\n .. math::\n\n \\phi(r) = (\\phi_0-\\phi_{absMin}) e^{kr} + \\phi_{absMin}\n\n where :math:`k = (\\sqrt{F^2 + 4 V''} - F) / 2`.\n \"\"\"\n k = 0.5 * (np.sqrt(F*F+4*self.d2V(self.phi_absMin)) - F)\n r0 = 0.0\n phi0 = self.phi_absMin + phi0_rel * (self.phi_metaMin-self.phi_absMin)\n dphi0 = k * (phi0 - self.phi_absMin)\n return self._initialConditions_rval(r0, phi0, dphi0)\n\n def equationOfMotion(self, y, r, F):\n \"\"\"\n Used to integrate the bubble wall.\n \"\"\"\n return np.array([y[1], self.dV(y[0])-F*y[1]])\n\n profile_rval = namedtuple(\"Profile1D\", \"R Phi dPhi F Rerr\")\n\n def findProfile(self, Fguess=None, Ftol=1e-4, phitol=1e-4,\n npoints=500, rmin=1e-4, rmax=1e4, phi0_rel=1e-3):\n R\"\"\"\n Calculate the bubble profile by iteratively over/undershooting.\n\n Parameters\n ----------\n Fguess : float, optional\n The initial guess for `F`. If `None`, `Fguess` is calculated from\n `self.rscale`.\n Ftol : float, optional\n Target accuracy in `F`, relative to `Fguess`.\n phitol : float, optional\n Fractional error tolerance in integration.\n npoints : int\n Number of points to return in the profile.\n rmin : float\n Relative to ``self.rscale``. Sets the smallest starting\n radius, the starting stepsize, and the smallest allowed stepsize\n (``0.01*rmin``).\n rmax : float\n Relative ``self.rscale``. Sets the maximum allowed integration\n distance.\n phi0_rel : float\n Passed to :func:`initialConditions`.\n\n Returns\n -------\n R, Phi, dPhi : array_like\n Radii and field values which make up the bubble profile. Note that\n `R[0]` can be much bigger than zero for thin-walled bubbles.\n Rerr : float or None\n The first value of `r` at which ``dr < drmin``, or `None` if\n ``dr >= drmin`` always.\n \"\"\"\n # Set r parameters\n rmin *= self.rscale\n dr0 = rmin\n drmin = 0.01*rmin\n rmax *= self.rscale\n # --\n # Set the phi parameters\n delta_phi = self.phi_metaMin - self.phi_absMin\n epsabs = abs(np.array([delta_phi, delta_phi/self.rscale])*phitol)\n epsfrac = np.array([1,1]) * phitol\n # --\n # Set F parameters\n Fmin = 0.0\n Fmax = np.inf\n if Fguess is not None:\n F = Fguess\n else:\n # Find F from conservation of energy\n # (total work done to slow down the field)\n Delta_V = self.V(self.phi_metaMin) - self.V(self.phi_absMin)\n F = Delta_V * self.rscale / delta_phi**2\n Ftol *= F\n Fincrease = 5.0\n # The relative amount to increase F by if there is no upper bound.\n # --\n integration_args = [dr0, epsfrac, epsabs, drmin, rmax, F]\n rf = None\n while True:\n r0, phi0, dphi0 = self.initialConditions(F, phi0_rel)\n y0 = np.array([phi0, dphi0])\n integration_args[-1] = F\n rf, yf, ctype = self.integrateProfile(r0, y0, *integration_args)\n # Check for overshoot, undershoot\n if ctype == \"converged\":\n break\n elif ctype == \"undershoot\": # F is too high\n Fmax = F\n F = F/Fincrease if Fmin == 0.0 else .5*(Fmin+Fmax)\n elif ctype == \"overshoot\": # F is too low\n Fmin = F\n F = F*Fincrease if Fmax == np.inf else .5*(Fmin+Fmax)\n # Check if we've reached xtol\n if (Fmax-Fmin) < Ftol:\n break\n\n # Integrate a second time, this time getting the points along the way\n R = np.linspace(r0, rf, npoints)\n profile = self.integrateAndSaveProfile(R, y0, dr0,\n epsfrac, epsabs, drmin, F)\n return profile\n\n def findAction(self, profile):\n \"\"\"\n Always returns `np.inf`.\n \"\"\"\n return np.inf\n" ]
[ [ "scipy.interpolate.splrep", "scipy.special.gamma", "numpy.sqrt", "numpy.isfinite", "numpy.linspace", "numpy.empty_like", "numpy.arange", "scipy.interpolate.splev", "numpy.sign", "numpy.exp", "numpy.append", "numpy.ceil", "scipy.integrate.simps", "numpy.array", "scipy.optimize.brentq" ] ]
[ { "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": [] } ]
Business-Wizard/01_capstone
[ "2985c664546d6503ef071a5afe1d0220a2c079be" ]
[ "src/EDA.py" ]
[ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport EDA_functions as eda\n\nsample_10m = 'data/10m_sample_common_passwords/10m_standard_complete3.csv'\npwned_path = '../data/have_i_been_pwned_v4/been_pwned_v4_hash_plain.txt'\nlinkedin_path = '../data/linkedin_leak/linkedin_hash_plain.txt'\nlinkedin_test_file = '../data/linkedin_leak/test_write.txt'\nrockyou_path = '../data/rockyou_leak/rockyou_copy.txt'\n\n\nif __name__ == '__main__':\n \n '''10m_sample'''\n df_10msample = pd.read_csv(sample_10m)\\\n .sample(frac=0.0001) \n #! most exploration can be done with very smaller sample fractions\n \n # null_bool = df_10msample.password.isnull()\n # print(null_bool.describe() )\n # df_10msample.dropna(axis=0, inplace=True)\n # print( df_10msample[ null_bool].count() )\n # df_10msample.to_csv('data/10m_sample_common_passwords/10m_standard_complete3.csv',index=None)\n # eda.explore_df(df_10msample)\n # pd.plotting.scatter_matrix(frame=df_10msample.loc[:,\n # ['score','upper','lower','number','symbol'] ])\n # plt.show()\n\n '''show chart 1 Length'''\n # eda.plot_hist_length(df_10msample)\n # plt.show()\n\n # plt.savefig('images/lengths.png')\n\n '''show chart 2 Strength'''\n # eda.plot_hist_strength(df_10msample)\n # plt.show()\n\n # plt.savefig('images/strengths.png')\n\n '''show chart 3 password chars- loop used for giph animations'''\n # for strength in range(0,23,2):\n # eda.plot_hist_chars(df_10msample, strength)\n # plt.show()\n\n # plt.savefig(fname=f\"images/{strength}_strength.png\")\n\n '''show chart 4 - guess v. length'''\n # eda.plot_guess_length(df_10msample)\n # plt.show()\n\n # plt.savefig('images/guess_by_length.png')\n\n\n '''passwords table'''\n # length_10 = df_10msample.length==10\n # length_20 = df_10msample.length==20\n # strength_7 = df_10msample.guesses_log<7\n # strength_10 = df_10msample.guesses_log==10\n # strength_20 = df_10msample.guesses_log==20\n # print(\n # df_10msample[(df_10msample.length==10)&(df_10msample.guesses_log<7)].head(5),\n # '\\n',\n # df_10msample[(df_10msample.length==10)&(df_10msample.guesses_log==10)].head(5),\n # '\\n',\n # df_10msample[(df_10msample.length==20)&(df_10msample.guesses_log<7)].head(5),\n # '\\n',\n # df_10msample[(df_10msample.length==20)&(df_10msample.guesses_log==20)].head(5)\n # )\n\n print(\"completed\")\n\n\n '''rockyou EDA'''\n #TODO Awaiting pipeline optimization for multi-core libraries\n #TODO Identify bug of parsing double-quotes in sequences \"\"\n \n '''linkedin EDA'''\n #TODO Awaiting pipeline optimization for multi-core libraries\n\n '''pwned EDA'''\n #TODO Awaiting pipeline optimization for multi-core libraries\n \n \n \n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
michaelkazman/random-chart-generator
[ "bf53666ab18e47b3d3882611ea88b30f5ce84161", "bf53666ab18e47b3d3882611ea88b30f5ce84161" ]
[ "creators/bubble.py", "generators/histogram.py" ]
[ "import numpy as np\nimport pandas as pd\nimport altair as alt\nimport plotnine as p9\nfrom bokeh.plotting import figure\nfrom bokeh.models import ColumnDataSource\nfrom utils.creators import unpack_graph_object\n\ndef create_bokeh_graph(graph_object):\n # format data\n (X, y, bubble_size, *_), styles = unpack_graph_object(graph_object)\n\n # create dataframe \n df = ColumnDataSource({\n 'X': X,\n 'y': y,\n 'bubble_size': bubble_size,\n })\n \n # plot data points\n p = figure(\n width=styles.get('width'),\n height=styles.get('height'),\n x_axis_label='X',\n y_axis_label='y',\n toolbar_location=None,\n )\n p.scatter(\n x='X',\n y='y',\n size='bubble_size',\n fill_alpha=styles.get('opacity'),\n fill_color=styles.get('fill'),\n line_color=styles.get('stroke_color'),\n line_width=styles.get('stroke_width'),\n source=df,\n )\n \n return p\n\ndef create_altair_graph(graph_object):\n # format data\n (X, y, bubble_size, *_), styles = unpack_graph_object(graph_object)\n df = pd.DataFrame({\n 'X': X,\n 'y': y,\n 'size': bubble_size,\n })\n\n # create chart\n p = alt.Chart(df).mark_point().encode(\n x=alt.X('X', scale=alt.Scale(domain=calculate_axis_range(X, bubble_size))),\n y=alt.Y('y', scale=alt.Scale(domain=calculate_axis_range(y, bubble_size))),\n size=alt.Size('size', legend=None),\n ).properties(\n width=styles.get('width'),\n height=styles.get('height'),\n ).configure_mark(\n opacity=styles.get('opacity'),\n fill=styles.get('fill'),\n stroke=styles.get('stroke_color'),\n strokeWidth=styles.get('stroke_width'),\n filled=True,\n )\n\n return p\n\ndef create_plotnine_graph(graph_object):\n # format data\n (X, y, bubble_size, *_), styles = unpack_graph_object(graph_object)\n df = pd.DataFrame({\n 'x': X,\n 'y': y,\n 'size': bubble_size,\n })\n\n # create plot\n p = (\n p9.ggplot(data=df, mapping=p9.aes(x='X', y='y', size='size'))\n + p9.geom_point(\n show_legend='None',\n fill=styles.get('fill'),\n color=styles.get('stroke_color'),\n stroke=styles.get('stroke_width'),\n alpha=styles.get('opacity'),\n )\n + p9.labels.xlab('X')\n + p9.labels.ylab('y')\n + p9.theme(figure_size=(styles.get('width'), styles.get('height')))\n )\n \n return p\n\ndef calculate_axis_range(X, bubble_size):\n percent_offset = np.amax(X) * (np.amax(bubble_size)/100)\n\n height_range = (\n np.amin(X) - percent_offset,\n np.amax(X) + percent_offset,\n )\n return height_range", "import numpy as np\n\nparameters = {\n 'size_range': (300, 1000),\n 'bins_range': (7, 100),\n 'mu_range': (0, 4),\n 'sigma_range': (0.01, 0.5),\n 'k_range': (1, 10),\n 'lambda_range': (0.5, 1.5),\n 'theta_range': (0.5, 2),\n 'low_range': (0.2, 1),\n 'high_range': (1, 2),\n}\n\ndef generate_data():\n # select a distribution type\n data_distributions = {\n 'normal': generate_random_normal_distribution,\n 'log-normal': generate_random_lognormal_distribution,\n 'gamma': generate_random_gamma_distribution,\n 'weibull': generate_random_weibull_distribution,\n 'uniform': generate_random_uniform_distribution,\n }\n distribution = np.random.choice(list(data_distributions.keys()))\n\n # generate parameters\n size = np.random.randint(*parameters.get('size_range', ()))\n bins = np.random.randint(*parameters.get('bins_range', ()))\n \n # get data distribution (and ensure no negative y values)\n y, X = data_distributions[distribution](size, bins)\n y = y.clip(0)\n\n return {\n 'X': X,\n 'y': y,\n 'distribution': distribution,\n }\n\n'''\nTitle: histogram.py\nAuthor: Bokeh\nDate: 2021\nCode version: N/A\nAvailability: https://docs.bokeh.org/en/latest/docs/gallery/histogram.html\n\nThe basis for the following generation functions was taken from the above\n'''\n\n# generates a normal distribution (with random mu, sigma, and size)\ndef generate_random_normal_distribution(size, bins):\n mu = np.random.uniform(*parameters.get('mu_range', ()))\n sigma = np.random.uniform(*parameters.get('sigma_range', ()))\n measured = np.random.normal(mu, sigma, size)\n y, X = np.histogram(measured, density=False, bins=bins)\n return y, X\n\n# generates a logistic normal distribution (with random mu, sigma, and size)\ndef generate_random_lognormal_distribution(size, bins):\n mu = np.random.uniform(*parameters.get('mu_range', ()))\n sigma = np.random.uniform(*parameters.get('sigma_range', ()))\n measured = np.random.lognormal(mu, sigma, size)\n y, X = np.histogram(measured, density=True, bins=bins)\n return y, X\n\n# generates a gamma distribution (with random k, theta, and size)\ndef generate_random_gamma_distribution(size, bins):\n k = np.random.uniform(*parameters.get('k_range', ()))\n theta = np.random.uniform(*parameters.get('theta_range', ()))\n measured = np.random.gamma(k, theta, size)\n y, X = np.histogram(measured, density=True, bins=bins)\n return y, X\n\n# generates a weibull distribution (with random lambda, k, and size)\ndef generate_random_weibull_distribution(size, bins):\n lam = np.random.uniform(*parameters.get('lambda_range', ()))\n k = np.random.uniform(*parameters.get('k_range', ()))\n measured = lam*(-np.log(np.random.uniform(0, 1, size)))**(1/k)\n y, X = np.histogram(measured, density=True, bins=bins)\n return y, X\n\n# generates a uniform distribution (with random range and size)\ndef generate_random_uniform_distribution(size, bins):\n low = np.random.uniform(*parameters.get('low_range', ()))\n high = np.random.uniform(*parameters.get('high_range', ()))\n measured = np.random.uniform(low, high, size)\n y, X = np.histogram(measured, density=True, bins=bins)\n return y, X" ]
[ [ "numpy.amin", "numpy.amax", "pandas.DataFrame" ], [ "numpy.random.lognormal", "numpy.random.normal", "numpy.random.gamma", "numpy.random.uniform", "numpy.histogram" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
repagh/python-control
[ "9f27293483c54ab7f90b34a100baba7587e9d36d" ]
[ "control/tests/rlocus_test.py" ]
[ "\"\"\"rlocus_test.py - unit test for root locus diagrams\n\nRMM, 1 Jul 2011\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.testing import assert_array_almost_equal\nimport pytest\n\nimport control as ct\nfrom control.rlocus import root_locus, _RLClickDispatcher\nfrom control.xferfcn import TransferFunction\nfrom control.statesp import StateSpace\nfrom control.bdalg import feedback\n\n\nclass TestRootLocus:\n \"\"\"These are tests for the feedback function in rlocus.py.\"\"\"\n\n @pytest.fixture(params=[(TransferFunction, ([1, 2], [1, 2, 3])),\n (StateSpace, ([[1., 4.], [3., 2.]],\n [[1.], [-4.]],\n [[1., 0.]], [[0.]]))],\n ids=[\"tf\", \"ss\"])\n def sys(self, request):\n \"\"\"Return some simple LTI system for testing\"\"\"\n # avoid construction during collection time: prevent unfiltered\n # deprecation warning\n sysfn, args = request.param\n return sysfn(*args)\n\n def check_cl_poles(self, sys, pole_list, k_list):\n for k, poles in zip(k_list, pole_list):\n poles_expected = np.sort(feedback(sys, k).pole())\n poles = np.sort(poles)\n np.testing.assert_array_almost_equal(poles, poles_expected)\n\n def testRootLocus(self, sys):\n \"\"\"Basic root locus plot\"\"\"\n klist = [-1, 0, 1]\n\n roots, k_out = root_locus(sys, klist, plot=False)\n np.testing.assert_equal(len(roots), len(klist))\n np.testing.assert_allclose(klist, k_out)\n self.check_cl_poles(sys, roots, klist)\n\n def test_without_gains(self, sys):\n roots, kvect = root_locus(sys, plot=False)\n self.check_cl_poles(sys, roots, kvect)\n\n def test_root_locus_zoom(self):\n \"\"\"Check the zooming functionality of the Root locus plot\"\"\"\n system = TransferFunction([1000], [1, 25, 100, 0])\n plt.figure()\n root_locus(system)\n fig = plt.gcf()\n ax_rlocus = fig.axes[0]\n\n event = type('test', (object,), {'xdata': 14.7607954359,\n 'ydata': -35.6171379864,\n 'inaxes': ax_rlocus.axes})()\n ax_rlocus.set_xlim((-10.813628105112421, 14.760795435937652))\n ax_rlocus.set_ylim((-35.61713798641108, 33.879716621220311))\n plt.get_current_fig_manager().toolbar.mode = 'zoom rect'\n _RLClickDispatcher(event, system, fig, ax_rlocus, '-')\n\n zoom_x = ax_rlocus.lines[-2].get_data()[0][0:5]\n zoom_y = ax_rlocus.lines[-2].get_data()[1][0:5]\n zoom_y = [abs(y) for y in zoom_y]\n\n zoom_x_valid = [\n -5., - 4.61281263, - 4.16689986, - 4.04122642, - 3.90736502]\n zoom_y_valid = [0., 0., 0., 0., 0.]\n\n assert_array_almost_equal(zoom_x, zoom_x_valid)\n assert_array_almost_equal(zoom_y, zoom_y_valid)\n\n @pytest.mark.timeout(2)\n def test_rlocus_default_wn(self):\n \"\"\"Check that default wn calculation works properly\"\"\"\n #\n # System that triggers use of y-axis as basis for wn (for coverage)\n #\n # This system generates a root locus plot that used to cause the\n # creation (and subsequent deletion) of a large number of natural\n # frequency contours within the `_default_wn` function in `rlocus.py`.\n # This unit test makes sure that is fixed by generating a test case\n # that will take a long time to do the calculation (minutes).\n #\n import scipy as sp\n import signal\n\n # Define a system that exhibits this behavior\n sys = ct.tf(*sp.signal.zpk2tf(\n [-1e-2, 1-1e7j, 1+1e7j], [0, -1e7j, 1e7j], 1))\n\n ct.root_locus(sys)\n\n" ]
[ [ "numpy.testing.assert_array_almost_equal", "numpy.sort", "matplotlib.pyplot.gcf", "matplotlib.pyplot.get_current_fig_manager", "numpy.testing.assert_allclose", "scipy.signal.zpk2tf", "matplotlib.pyplot.figure" ] ]
[ { "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": [] } ]
tadorfer/ProtClass
[ "da1a01ea9abd3c367b3389dfed683c6a9dfa6afd", "da1a01ea9abd3c367b3389dfed683c6a9dfa6afd" ]
[ "protlearn/dimreduction/tests/test_univariate_filter.py", "protlearn/features/tests/test_cksaap.py" ]
[ "import pytest\nimport numpy as np\nfrom ..univariate_filter import univariate_filter\n\nimport pkg_resources\n\nPATH = pkg_resources.resource_filename(__name__, 'test_data/')\n\ndef test_univariate_filter():\n \"Test filter-based dimensionality reduction\"\n \n # load data\n X = np.load(PATH+'features_largeN.npy')\n y = np.load(PATH+'features_largeN_labels.npy')\n\n # compute filter-based feature importances\n X_f = univariate_filter(X, y, top=10)\n X_chi2 = univariate_filter(X, y, method='chi2', top=10)\n X_mi = univariate_filter(X, y, method='mutual_info', top=10)\n\n # test f_test\n np.testing.assert_almost_equal(X_f[0,:], np.array([\n 0. , 0.71888889, -0.32333333, 4.33666667, -1.198 ,\n 13.93111111, -0.13444444, 1.07 , -0.07111111, 4.43333333]), decimal=3)\n\n np.testing.assert_almost_equal(X_f[300,:], np.array([\n 0.11111111, 0.76333333, -0.44888889, 4.61333333, -1.13922222,\n 13.48111111, 0.02666667, 1.37888889, -0.16033333, 4.58888889]), decimal=3)\n\n np.testing.assert_almost_equal(X_f[-1,:], np.array([\n 0.00000000e+00, 7.42222222e-01, 4.44444444e-03, 6.01000000e+00,\n -1.21611111e+00, 1.43533333e+01, 1.11111111e-03, 2.09777778e+00,\n 4.03333333e-02, 6.12222222e+00]), decimal=3)\n \n # test chi2\n np.testing.assert_almost_equal(X_chi2[0,:], np.array([\n 0. , 0. , 0. , 0. , 0.19548082,\n 0.49728261, 0.1206297 , 0.23030149, 0.10641248, 0.44082605]), decimal=3)\n\n np.testing.assert_almost_equal(X_chi2[300,:], np.array([\n 0. , 0. , 0.16666667, 0. , 0.21650026,\n 0.61277174, 0.17247985, 0.02685584, 0.15840555, 0.52223987]), decimal=3)\n\n np.testing.assert_almost_equal(X_chi2[-1,:], np.array([\n 0.5 , 0.2 , 0. , 0. , 0.20651603,\n 0.57540761, 0.43422943, 0.48441855, 0.36048527, 0.1457506]), decimal=3)\n\n # test array shape\n X_f.shape == (700, 10)\n X_chi2.shape == (700, 10)\n X_mi.shape == (700, 10)", "import pytest\nimport numpy as np\nfrom ..cksaap import cksaap\nimport pkg_resources\n\nPATH = pkg_resources.resource_filename(__name__, 'test_data/')\n\ndef test_cksaap():\n \"Test k-spaced amino acid pair composition\"\n \n # load data\n X_list = open(PATH+'multiple.txt').read().splitlines()\n X_err = 'AGT2HT9'\n \n # get cksaap \n cksaap_list, desc = cksaap(X_list, k=3, remove_zero_cols=True)\n \n # test cksaap\n assert np.array_equal(cksaap_list, np.array([\n [0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0],\n [1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1]]))\n\n # test ValueError\n with pytest.raises(ValueError):\n cksaap_error, desc = cksaap(X_err)" ]
[ [ "numpy.load", "numpy.array" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Vernacular-ai/slu-service
[ "c61af67ead471e47202036779eeda124e57d9850" ]
[ "slu/slu/utils/config.py" ]
[ "\"\"\"\n[summary]\n\"\"\"\nimport abc\nimport os\nimport re\nimport pickle\nimport shutil\nfrom typing import Any, Dict, List, Optional, Union\n\nimport attr\nimport requests\nimport semver\nimport torch\nimport yaml\nfrom requests.adapters import HTTPAdapter\nfrom simpletransformers.classification import ClassificationModel # type: ignore\nfrom simpletransformers.ner import NERModel\nfrom urllib3.util import Retry\n\nfrom slu import constants as const\nfrom slu.dev.io.reader.csv import (\n read_ner_dataset_csv,\n save_classification_report,\n save_ner_report,\n)\nfrom slu.dev.prepare import prepare\nfrom slu.utils.logger import log\nfrom slu.utils.decorators import task_guard\nfrom slu.utils.error import MissingArtifact\nfrom slu.utils.s3 import get_csvs\nfrom slu.utils.nfs_minio import download_directory_from_minio\n\n\[email protected]\nclass Task:\n use = attr.ib(type=bool, kw_only=True, validator=attr.validators.instance_of(bool))\n threshold = attr.ib(\n type=float, kw_only=True, validator=attr.validators.instance_of(float)\n )\n model_args = attr.ib(\n type=dict, kw_only=True, validator=attr.validators.instance_of(dict)\n )\n alias = attr.ib(\n factory=dict, kw_only=True, validator=attr.validators.instance_of(dict)\n )\n format = attr.ib(\n factory=str,\n kw_only=True,\n validator=attr.validators.optional(attr.validators.instance_of(str)),\n )\n\n\[email protected]\nclass Tasks:\n classification = attr.ib(\n type=Task, kw_only=True, validator=attr.validators.instance_of(dict)\n )\n ner = attr.ib(type=Task, kw_only=True, validator=attr.validators.instance_of(dict))\n\n def __attrs_post_init__(self) -> None:\n self.classification = Task(**self.classification) # type: ignore\n self.ner = Task(**self.ner) # type: ignore\n\n\[email protected]\nclass Parser:\n params = attr.ib(type=dict, validator=attr.validators.instance_of(dict))\n plugin = attr.ib(type=str, default=None)\n lambda_ = attr.ib(type=str, default=None)\n\n def __attrs_post_init__(self) -> None:\n error_message = \"A Parser should define either a plugin or lambda_ endpoint.\"\n if isinstance(self.plugin, str) and isinstance(self.lambda_, str):\n raise TypeError(error_message)\n\n if self.plugin is None and self.lambda_ is None:\n raise TypeError(error_message)\n\n\[email protected]\nclass Config:\n \"\"\"\n An instance of config handles `config/config.yaml` configurations. This includes reading other related files, models, datasets, etc.\n\n An instance can:\n\n - Read config.yaml\n - Modify config.yaml\n - Load models and their configurations\n - Save pickled objects.\n \"\"\"\n\n model_name = attr.ib(\n type=str, kw_only=True, validator=attr.validators.instance_of(str)\n )\n version = attr.ib(\n type=str,\n kw_only=True,\n default=\"0.0.0\",\n validator=attr.validators.instance_of(str),\n )\n tasks = attr.ib(type=Tasks, kw_only=True)\n languages = attr.ib(type=List[str], kw_only=True)\n slots: Dict[str, Dict[str, Any]] = attr.ib(factory=dict, kw_only=True)\n preprocess: List[Dict[str, Any]] = attr.ib(factory=list, kw_only=True)\n postprocess: List[Dict[str, Any]] = attr.ib(factory=list, kw_only=True)\n\n def __attrs_post_init__(self) -> None:\n \"\"\"\n Update default values of attributes from `conifg.yaml`.\n \"\"\"\n self.tasks = Tasks(**self.tasks) # type: ignore\n semver.VersionInfo.parse(self.version)\n\n def task_by_name(self, task_name: str) -> Task:\n return getattr(self.tasks, task_name)\n\n @task_guard\n def get_data_dir(self, task_name: str) -> str:\n return os.path.join(const.DATA, self.version, task_name)\n\n @task_guard\n def get_metrics_dir(self, task_name: str) -> str:\n return os.path.join(self.get_data_dir(task_name), const.METRICS)\n\n @task_guard\n def get_model_dir(self, task_name: str, purpose: str) -> str:\n if purpose == const.TRAIN:\n model_dir = os.path.join(self.get_data_dir(task_name), const.MODELS)\n else:\n model_dir = self.task_by_name(task_name).model_args[purpose][\n const.S_OUTPUT_DIR\n ]\n if not isinstance(model_dir, str):\n raise TypeError(\n f\"Expected model directory for task={task_name}[{purpose}]\"\n f\" to be a string but {type(model_dir)} was found.\"\n )\n return model_dir\n\n def set_model_dir(self, task: str, purpose: str):\n\n if purpose == const.TRAIN:\n\n if task == const.CLASSIFICATION:\n classification_model_dir = self.get_model_dir(\n const.CLASSIFICATION, const.TRAIN\n )\n\n for next_purpose in [const.TEST, const.PRODUCTION.lower()]:\n\n self.tasks.classification.model_args[next_purpose][\n const.S_OUTPUT_DIR\n ] = classification_model_dir\n self.tasks.classification.model_args[next_purpose][\n const.S_BEST_MODEL\n ] = classification_model_dir\n\n elif task == const.NER:\n ner_model_dir = self.get_model_dir(const.NER, const.TRAIN)\n\n for next_purpose in [const.TEST, const.PRODUCTION.lower()]:\n\n self.tasks.ner.model_args[next_purpose][\n const.S_OUTPUT_DIR\n ] = ner_model_dir\n self.tasks.ner.model_args[next_purpose][\n const.S_BEST_MODEL\n ] = ner_model_dir\n\n @task_guard\n def get_dataset(\n self, task_name: str, purpose: str, file_format=const.CSV, custom_file=None\n ) -> Any:\n data_dir = self.get_data_dir(task_name)\n dataset_dir = os.path.join(data_dir, const.DATASETS)\n dataset_file = custom_file or os.path.join(\n dataset_dir, f\"{purpose}.{file_format}\"\n )\n alias = self.task_by_name(task_name).alias\n try:\n if task_name == const.CLASSIFICATION:\n data, _ = prepare(dataset_file, alias, file_format=file_format)\n elif task_name == const.NER:\n data, _ = read_ner_dataset_csv(dataset_file)\n except FileNotFoundError as file_missing_error:\n raise ValueError(\n f\"{dataset_file} not found! Are you sure {const.TASKS}.{task_name}.use = true?\"\n ) from file_missing_error\n\n return data\n\n @task_guard\n def get_model_args(self, task_name: str, purpose: str) -> Dict[str, Any]:\n model_args = self.task_by_name(task_name).model_args[purpose]\n if not model_args[const.S_OUTPUT_DIR]:\n model_args[const.S_OUTPUT_DIR] = self.get_model_dir(task_name, purpose)\n\n if not model_args[const.S_BEST_MODEL]:\n model_args[const.S_BEST_MODEL] = self.get_model_dir(task_name, purpose)\n\n n_epochs = model_args.get(const.S_NUM_TRAIN_EPOCHS)\n\n eval_batch_size = model_args.get(const.S_EVAL_BATCH_SIZE)\n\n if purpose == const.TRAIN and not isinstance(n_epochs, int):\n raise TypeError(\"n_epochs should be an int.\")\n\n if purpose == const.TRAIN and not isinstance(eval_batch_size, int):\n raise TypeError(\"Number of eval_batch_size should be an int.\")\n\n if n_epochs and purpose == const.TRAIN:\n model_args[const.S_EVAL_DURING_TRAINING_STEPS] = (\n n_epochs * eval_batch_size + const.k\n )\n\n return model_args\n\n def get_classification_model(\n self, purpose: str, labels: List[str]\n ) -> ClassificationModel:\n if not self.tasks.classification.use:\n log.warning(\n \"You have set `classification.use = false` within `config.yaml`. Model will not be loaded.\"\n )\n return None\n\n model_args = self.get_model_args(const.CLASSIFICATION, purpose)\n kwargs = {\n \"use_cuda\": (\n (purpose != const.PRODUCTION.lower())\n and (torch.cuda.device_count() > 0)\n ),\n \"args\": model_args,\n }\n\n if purpose == const.TRAIN:\n kwargs[\"num_labels\"] = len(labels)\n\n try:\n return ClassificationModel(\n const.S_XLMR,\n (\n const.S_XLMRB\n if purpose == const.TRAIN\n else model_args[const.S_BEST_MODEL]\n ),\n **kwargs,\n )\n except OSError as os_err:\n raise ValueError(\n f\"config/config.yaml has {const.TASKS}.{purpose}.use = True, \"\n f\"but no model found in {model_args[const.S_OUTPUT_DIR]}\"\n ) from os_err\n\n def get_ner_model(self, purpose: str, labels: List[str]) -> NERModel:\n if not self.tasks.ner.use:\n log.warning(\n \"You have set `ner.use = false` within `config.yaml`. Model will not be loaded.\"\n )\n return None\n\n model_args = self.get_model_args(const.NER, purpose)\n\n kwargs = {\n \"use_cuda\": (\n (purpose != const.PRODUCTION.lower())\n and (torch.cuda.device_count() > 0)\n ),\n \"args\": model_args,\n }\n\n if purpose == const.TRAIN:\n kwargs[const.LABELS] = labels\n\n try:\n return NERModel(\n const.S_XLMR,\n (\n const.S_XLMRB\n if purpose == const.TRAIN\n else model_args[const.S_OUTPUT_DIR]\n ),\n **kwargs,\n )\n except OSError as os_err:\n raise ValueError(\n f\"config/config.yaml has {const.TASKS}.{purpose}.use = True, \"\n f\"but no model found in {model_args[const.S_OUTPUT_DIR]}\"\n ) from os_err\n\n @task_guard\n def get_model(\n self, task_name: str, purpose: str\n ) -> Union[ClassificationModel, NERModel]:\n labels = self.get_labels(task_name, purpose)\n if task_name == const.NER:\n return self.get_ner_model(purpose, labels)\n return self.get_classification_model(purpose, labels)\n\n @task_guard\n def get_labels(self, task_name: str, purpose: str) -> List[str]:\n if task_name == const.NER:\n return self.load_pickle(const.NER, purpose, const.S_ENTITY_LABELS)\n\n try:\n encoder = self.load_pickle(\n const.CLASSIFICATION, purpose, const.S_INTENT_LABEL_ENCODER\n )\n except TypeError:\n model_dir = self.get_model_dir(task_name, purpose)\n raise MissingArtifact(\n const.S_INTENT_LABEL_ENCODER,\n os.path.join(model_dir, const.S_INTENT_LABEL_ENCODER),\n )\n return encoder.classes_\n\n @task_guard\n def set_labels(self, task_name: str, purpose: str, labels: List[str]) -> None:\n namespace = (\n const.S_ENTITY_LABELS\n if task_name == const.NER\n else const.S_INTENT_LABEL_ENCODER\n )\n self.save_pickle(task_name, purpose, namespace, labels)\n\n @task_guard\n def save_pickle(\n self, task_name: str, purpose: str, prop: str, value: Any\n ) -> \"Config\":\n model_dir = self.get_model_dir(task_name, purpose)\n with open(os.path.join(model_dir, prop), \"wb\") as handle:\n pickle.dump(value, handle)\n return self\n\n @task_guard\n def load_pickle(self, task_name: str, purpose: str, prop: str):\n model_dir = self.get_model_dir(task_name, purpose)\n with open(os.path.join(model_dir, prop), \"rb\") as handle:\n return pickle.load(handle)\n\n @task_guard\n def get_alias(self, task_name: str) -> Dict[str, str]:\n return self.task_by_name(task_name).alias\n\n def save_classification_errors(self, df):\n df.to_csv(\n os.path.join(self.get_metrics_dir(const.CLASSIFICATION), const.S_ERRORS),\n index=False,\n )\n\n def save(self) -> \"Config\":\n with open(const.S_CONFIG_PATH, \"w\") as handle:\n yaml.dump(attr.asdict(self), handle, sort_keys=False)\n return self\n\n @task_guard\n def save_report(self, task, results) -> \"Config\":\n if task == const.CLASSIFICATION:\n save_classification_report(\n results[0], results[1], self.get_metrics_dir(task)\n )\n return self\n elif task == const.NER:\n save_ner_report(results, self.get_metrics_dir(task))\n return self\n else:\n raise ValueError(\n f\"Expected task to be {const.CLASSIFICATION} or {const.NER} instead, {task} was found\"\n )\n\n @task_guard\n def remove_checkpoints(self, task, purpose) -> None:\n model_dir = self.get_model_dir(task, purpose)\n items = os.listdir(model_dir)\n for item in items:\n subdir = os.path.join(model_dir, item)\n if os.path.isdir(subdir):\n shutil.rmtree(subdir)\n\n def get_supported_languages(self) -> List[str]:\n return self.languages\n\n def make_slot_rules(self):\n slot_rules = {}\n for intent_name, slot_dict in self.slots.items():\n slot_rules[intent_name] = {}\n for slot_name, entities in slot_dict.items():\n for entity in entities:\n if slot_name in slot_rules[intent_name]:\n slot_rules[intent_name][slot_name].append(entity[const.NAME])\n else:\n slot_rules[intent_name][slot_name] = [entity[const.NAME]]\n return slot_rules\n\n def make_candidates(self):\n urls = set()\n candidates = {}\n pattern_delim = re.compile(r\",\\s*\")\n\n for slot_dict in self.slots.values():\n for entities in slot_dict.values():\n for entity in entities:\n if entity[const.PARSER] in (const.DUCKLING_PLUGIN, const.DUCKLING):\n continue\n candidates[entity[const.NAME]] = {}\n if (\n entity[const.PARSER] == const.LIST_ENTITY_PLUGIN\n and const.URL in entity[const.PARAMS]\n ):\n urls.add(entity[const.PARAMS][const.URL])\n else:\n for language in self.languages:\n pattern_map = entity[const.PARAMS].get(language, {})\n if not pattern_map:\n log.error(\n f\"entity={entity} doesn't have patterns for language={language}.\"\n )\n for parse_value, patterns in pattern_map.items():\n if isinstance(patterns, str):\n candidates[entity[const.NAME]].update(\n {parse_value: pattern_delim.split(patterns)}\n )\n elif isinstance(patterns, list):\n candidates[entity[const.NAME]].update(\n {parse_value: patterns}\n )\n else:\n raise TypeError(\n \"Patterns are expected to be comma separated strings or list of strings.\"\n )\n\n if urls:\n dataframe = get_csvs(urls)\n columns = dataframe.columns\n reference_column = columns[\n 1\n ] # The entity value corresponding to a set of patterns.\n value_column = columns[0] # A set of patterns.\n references = dataframe[reference_column].unique()\n candidates[entity[const.NAME]] = {\n reference: dataframe[dataframe[reference_column] == reference][\n value_column\n ].to_list()\n for reference in references\n }\n return candidates\n\n def plugin_parameterize(self, plugin_name):\n if plugin_name == const.RULE_BASED_SLOT_FILLER_PLUGIN:\n return {const.RULES: self.make_slot_rules()}\n if plugin_name == const.LIST_ENTITY_PLUGIN:\n return {const.CANDIDATES: self.make_candidates()}\n\n def json(self) -> Dict[str, Any]:\n \"\"\"\n Represent the class as json\n\n :return: The class instance as json\n :rtype: Dict[str, Any]\n \"\"\"\n return attr.asdict(self)\n\n\nclass ConfigDataProviderInterface(metaclass=abc.ABCMeta):\n @abc.abstractmethod\n def generate(self):\n ...\n\n\nclass HTTPConfig(ConfigDataProviderInterface):\n def __init__(self) -> None:\n self.client_configs: Dict[str, Any] = {}\n self.root_level_keys = [const.MODEL_NAME, const.LANGUAGES, const.SLOTS]\n\n def _parse_json(self, configs: List[Dict[str, Any]]):\n # if project_configs_response is of List[Dict]\n for config_dict in configs:\n model_name = config_dict.get(const.MODEL_NAME)\n if model_name:\n alias = config_dict[const.ALIAS]\n metadata = config_dict[const.METADATA]\n root_level_config = {\n key: value\n for key, value in config_dict.items()\n if key in self.root_level_keys\n }\n if not metadata:\n raise ValueError(f\"You need to set metadata for {model_name}.\")\n\n root_level_config.update(metadata)\n root_level_config[const.TASKS][const.CLASSIFICATION][\n const.ALIAS\n ] = alias\n config = Config(**root_level_config)\n plugins = config.preprocess + config.postprocess\n\n for plugin_dict in plugins:\n plugin_name = plugin_dict[const.PLUGIN]\n params = config.plugin_parameterize(plugin_name=plugin_name)\n if params:\n plugin_dict[const.PARAMS].update(params)\n\n self.client_configs[model_name] = config\n\n def _get_config(self):\n BUILDER_BACKEND_URL = os.getenv(\"BUILDER_BACKEND_URL\")\n if BUILDER_BACKEND_URL is None:\n raise ValueError(\n f\"missing BUILDER_BACKEND_URL env variable, please set it appropriately.\"\n )\n\n url = BUILDER_BACKEND_URL + const.CLIENTS_CONFIGS_ROUTE\n\n session = requests.Session()\n\n retry = Retry(\n total=const.REQUEST_MAX_RETRIES,\n connect=const.REQUEST_MAX_RETRIES,\n read=const.REQUEST_MAX_RETRIES,\n backoff_factor=0.3,\n status_forcelist=(500, 502, 504),\n )\n\n http_adapter = HTTPAdapter(max_retries=retry)\n session.mount(\"http://\", http_adapter)\n session.mount(\"https://\", http_adapter)\n\n response = session.get(url, timeout=10)\n\n if response.ok:\n return response.json()\n\n raise RuntimeError(\n f\"couldn't establish connection with {url} while trying to collect configs\"\n )\n\n def generate(self) -> Dict[str, Config]:\n if not self.client_configs:\n configs_response = self._get_config()\n self._parse_json(configs_response)\n\n return self.client_configs\n\n\nclass YAMLLocalConfig(ConfigDataProviderInterface):\n def __init__(self, config_path: Optional[str] = None) -> None:\n self.config_path = (\n config_path if config_path else os.path.join(\"config\", \"config.yaml\")\n )\n\n def generate(self) -> Dict[str, Config]:\n with open(self.config_path, \"r\") as handle:\n config_dict = yaml.safe_load(handle)\n\n config = Config(**config_dict)\n plugins = config.preprocess + config.postprocess\n\n for plugin_dict in plugins:\n plugin_name = plugin_dict[const.PLUGIN]\n params = config.plugin_parameterize(plugin_name=plugin_name)\n if params:\n plugin_dict[const.PARAMS].update(params)\n\n return {config_dict[const.MODEL_NAME]: config}\n\n\nclass JSONAPIConfig(ConfigDataProviderInterface):\n def __init__(self, config_dict: Optional[Dict] = None) -> None:\n super().__init__()\n self.config = config_dict\n self._setup_model_dir()\n\n def _fix_model_output_dirs(self, nfs_minio_task_path, task):\n\n dest_path = \"/\".join(nfs_minio_task_path.split(\"/\")[1:])\n\n purposes = [const.TRAIN, const.TEST, const.PRODUCTION.lower()]\n\n for purpose in purposes:\n self.config[const.TASKS][task][const.S_MODEL_ARGS][purpose][\n const.S_OUTPUT_DIR\n ] = dest_path\n self.config[const.TASKS][task][const.S_MODEL_ARGS][purpose][\n const.S_BEST_MODEL\n ] = dest_path\n\n def _setup_model_dir(self):\n\n setup_done = False\n\n minio_classification_path = self.config[const.TASKS][const.CLASSIFICATION][\n const.S_MODEL_ARGS\n ][const.PRODUCTION.lower()][const.S_OUTPUT_DIR]\n\n minio_ner_path = self.config[const.TASKS][const.NER][const.S_MODEL_ARGS][\n const.PRODUCTION.lower()\n ][const.S_OUTPUT_DIR]\n\n if minio_classification_path is None and minio_ner_path is None:\n raise ValueError(\"model paths are missing in the given Config...\")\n\n if minio_classification_path:\n actual_minio_path = \"/\".join(minio_classification_path.split(\"/\")[:-2])\n download_directory_from_minio(actual_minio_path)\n setup_done = True\n if not setup_done and minio_ner_path:\n actual_minio_path = \"/\".join(minio_ner_path.split(\"/\")[:-2])\n download_directory_from_minio(actual_minio_path)\n\n if minio_classification_path:\n self._fix_model_output_dirs(minio_classification_path, const.CLASSIFICATION)\n \n if minio_ner_path:\n self._fix_model_output_dirs(minio_ner_path, const.NER)\n\n def generate(self) -> Dict:\n\n config = Config(**self.config)\n log.debug(\"Loaded models from the JSON ...\")\n plugins = config.preprocess + config.postprocess\n\n for plugin_dict in plugins:\n plugin_name = plugin_dict[const.PLUGIN]\n params = config.plugin_parameterize(plugin_name=plugin_name)\n if params:\n plugin_dict[const.PARAMS].update(params)\n\n return config\n" ]
[ [ "torch.cuda.device_count" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
A-Waterman/udacity-dog-project
[ "f5035fd12ebc7bafb10aa7ccd03384a5eab1f648" ]
[ "keras_tests.py" ]
[ "from sklearn.datasets import load_files\nfrom keras.utils import np_utils\nimport numpy as np\nfrom glob import glob\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.layers import Activation, BatchNormalization\nfrom keras.layers import Dropout, Flatten, Dense\nfrom keras.initializers import lecun_normal\nfrom keras.optimizers import RMSprop\nimport cv2\nimport matplotlib.pyplot as plt\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom time import time\nimport random\nfrom keras.preprocessing import image\nfrom tqdm import tqdm\nfrom PIL import ImageFile\nfrom keras_tqdm import TQDMCallback\n#\n# Load Dataset\n#\n\n\ndef load_dataset(path):\n data = load_files(path)\n dog_files = np.array(data['filenames'])\n dog_targets = np_utils.to_categorical(np.array(data['target']), 133)\n return dog_files, dog_targets\n\n\ndef fast_load_dataset(path):\n dog_files = np.load(path + '/files.npy')\n dog_targets = np.load(path + '/targets.npy')\n return dog_files, dog_targets\n\n\ndef load_and_save(path):\n dog_files, dog_targets = load_dataset(path)\n print('saving files...')\n np.save(path + '/files.npy', dog_files)\n np.save(path + '/targets.npy', dog_targets)\n print('files saved!')\n\n\ndef test_load_save():\n for path in ['dogImages/train', 'dogImages/valid', 'dogImages/test']:\n load_and_save(path)\n\n\n#\n# Supplied methods and helpers to load tensors\n#\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\ndef path_to_tensor(img_path):\n # loads RGB image as PIL.Image.Image type\n img = image.load_img(img_path, target_size=(224, 224))\n # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)\n x = image.img_to_array(img)\n # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor\n return np.expand_dims(x, axis=0)\n\n\ndef paths_to_tensor(img_paths):\n list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]\n return np.vstack(list_of_tensors)\n\n\ndef load_tensors_supplied(paths):\n tensors = paths_to_tensor(paths).astype('float32') / 255\n return tensors\n\n\n#\n# Own methods and helpers to load tensors\n#\n\ndef load_tensors(file_path):\n # NOTE: file_path should be one of ['dogImages/train', 'dogImages/valid', 'dogImages/test']\n tensors = np.load(file_path + '/tensors.npy')\n return tensors\n\n\ndef test_save_tensors():\n print(\"saving tensors...\")\n paths = ['dogImages/train', 'dogImages/valid', 'dogImages/test']\n for path in paths:\n files, targets = fast_load_dataset(path)\n tensors = load_tensors_supplied(files)\n tensors_path = path + '/tensors.npy'\n np.save(tensors_path, tensors)\n print(\"saved all tensors\")\n\n#\n# Own methods and helpers to load tensors (npz)\n#\n\n\ndef load_tensors_targets(file_path):\n # NOTE: file_path should be one of ['dogImages/train', 'dogImages/valid', 'dogImages/test']\n tensors = np.load(file_path + '/tensors_targets.npz')['tensors']\n targets = np.load(file_path + '/tensors_targets.npz')['targets']\n return tensors, targets\n\n\ndef test_load_tensors_targets():\n paths = ['dogImages/train', 'dogImages/valid', 'dogImages/test']\n for path in paths:\n tensors_targets = np.load(path + '/tensors_targets.npz')\n print(tensors_targets.files)\n\n\ndef test_save_tensors_targets():\n print(\"saving tensors and targets...\")\n paths = ['dogImages/train', 'dogImages/valid', 'dogImages/test']\n for path in ['dogImages/valid', 'dogImages/test']:\n files, targets = fast_load_dataset(path)\n tensors = load_tensors_supplied(files)\n np.savez(path + '/tensors_targets.npz', tensors=tensors, targets=targets)\n print(path, \"successfully saved!\")\n print(\"All tensors and targets saved!\")\n\n\ndef dumb_save_tensors():\n print(\"saving tensors...\")\n for path in ['dogImages/train', 'dogImages/valid', 'dogImages/test']:\n files, targets = fast_load_dataset(path)\n tensors = paths_to_tensor(files)\n np.savez(path+'/tensors.npz', tensors=tensors)\n print(\"All tensors saved!\")\n\n\ndef dumb_load_tensors():\n print(\"loading tensors...\")\n for path in ['dogImages/train', 'dogImages/valid', 'dogImages/test']:\n tensors = np.load(path + '/tensors.npz')['tensors']\n print(tensors.shape)\n print(\"All tensors loaded!\")\n\n#\n# preprocess methods\n#\n\n\ndef test_dumb_preprocess():\n # initalize Contrast-limited adaptive histogram equalization\n # clip limit governs ...\n # tileGridSize needs to be larger than first layer(s) kernel size\n clahe = cv2.createCLAHE(clipLimit=3, tileGridSize=(8, 8))\n\n valid_files, valid_targets = fast_load_dataset('dogImages/valid')\n x = preprocess_img_to_tensor(valid_files[20], clahe)\n print(x.shape)\n\n\nedge_flag = False\n\n\ndef preprocess_img_to_tensor(img_path, clahe):\n # loads RGB image as cv2 image\n rgb_img = cv2.imread(img_path)\n # converts RGB image to CIE L*a*b* color space\n lab_img = cv2.cvtColor(rgb_img, cv2.COLOR_RGB2Lab)\n # split the CIE L*a*b* image into channels\n luminance, a_star, b_star = cv2.split(lab_img)\n # apply CLAHE to Luminance channel\n equalized_luminance = clahe.apply(luminance)\n # merge the channels back together\n merge = cv2.merge((equalized_luminance, a_star, b_star))\n # convert the CIE L*a*b* color space back into RGB\n equalized_img = cv2.cvtColor(merge, cv2.COLOR_Lab2BGR)\n # resize the image to (224, 224)\n resized_img = cv2.resize(equalized_img, (224, 224))\n\n if edge_flag:\n # extract the edges\n edges = cv2.Canny(resized_img, 100, 200)\n # convert rgb edge image to grayscale\n # gray_edges = cv2.cvtColor(edges, cv2.COLOR_RGB2GRAY)\n # merge edge channel into main image\n dumb_img = cv2.merge((resized_img, edges))\n # convert the image to 3D tensor with shape (224, 224, 4)\n x = image.img_to_array(dumb_img)\n else:\n # convert the image to 3D tensor with shape (224, 224, 3)\n x = image.img_to_array(resized_img)\n # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor\n return np.expand_dims(x, axis=0)\n\n\ndef preprocess_path(img_paths):\n # initalize Contrast-limited adaptive histogram equalization\n # clip limit governs ...\n # tileGridSize needs to be larger than first layer(s) kernel size\n clahe = cv2.createCLAHE(clipLimit=3, tileGridSize=(8, 8))\n\n list_of_tensors = [preprocess_img_to_tensor(img_path, clahe) for img_path in tqdm(img_paths)]\n return np.vstack(list_of_tensors)\n\n\ndef preprocess_tensors(paths):\n tensors = preprocess_path(paths).astype('float32') / 255\n return tensors\n\n#\n# keras model definitions\n#\n\n\ndef hint_model_1(number_of_labels, first_filters=16, input_shape=(224, 224, 3)):\n model = Sequential()\n\n # first layer\n model.add(Conv2D(filters=first_filters, input_shape=input_shape,\n kernel_size=2, strides=1, activation='relu',\n kernel_initializer=lecun_normal()))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n # second layer\n model.add(Conv2D(filters=first_filters * 2,\n kernel_size=2, strides=1, activation='relu',\n kernel_initializer=lecun_normal()))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n # third layer\n model.add(Conv2D(filters=first_filters * 4,\n kernel_size=2, strides=1, activation='relu',\n kernel_initializer=lecun_normal()))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n #\n model.add(GlobalAveragePooling2D())\n\n model.add(Dense(units=number_of_labels, activation='softmax',\n kernel_initializer=lecun_normal()))\n\n # set the filepath for saving the model's weights\n save_filepath = \"saved_models/weights.best.hint_model_1.hdf5\"\n return model, save_filepath\n\n\ndef hint_model_2(number_of_labels, first_filters=16, input_shape=(224, 224, 3)):\n ks = 2 # kernel + stride example ks=2 means (2,2) kernel and stride of 2\n model = Sequential()\n\n model.add(Conv2D(filters=first_filters, kernel_size=ks, strides=ks,\n activation='relu', kernel_initializer=lecun_normal(),\n input_shape=input_shape))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(Conv2D(filters=first_filters*2, kernel_size=ks, strides=ks,\n activation='relu', kernel_initializer=lecun_normal()))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(Conv2D(filters=first_filters*4, kernel_size=ks, strides=ks,\n activation='relu', kernel_initializer=lecun_normal()))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(GlobalAveragePooling2D())\n\n model.add(Dense(units=number_of_labels, activation='softmax', kernel_initializer=lecun_normal()))\n\n filepath = \"saved_models/weights.best.hint_model_2.hdf5\"\n return model, filepath\n\n\ndef hint_model_2_bn(number_of_labels, first_filters=16, input_shape=(224, 224, 3)):\n ks = 2 # kernel + stride example ks=2 means (2,2) kernel and stride of 2\n model = Sequential()\n\n model.add(Conv2D(filters=first_filters, kernel_size=ks, strides=ks,\n kernel_initializer=lecun_normal(),\n input_shape=input_shape))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(Conv2D(filters=first_filters*2, kernel_size=ks, strides=ks,\n kernel_initializer=lecun_normal()))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(Conv2D(filters=first_filters*4, kernel_size=ks, strides=ks,\n kernel_initializer=lecun_normal()))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(GlobalAveragePooling2D())\n\n model.add(Dense(units=number_of_labels, activation='softmax', kernel_initializer=lecun_normal()))\n\n filepath = \"saved_models/weights.best.hint_model_2_bn.hdf5\"\n return model, filepath\n\n\ndef hint_model_2_nin(number_of_labels, first_filters=16, input_shape=(224, 224, 3)):\n ks = 2 # kernel + stride example ks=2 means (2,2) kernel and stride of 2\n model = Sequential()\n\n model.add(Conv2D(filters=first_filters, kernel_size=1, strides=1,\n kernel_initializer=lecun_normal(), input_shape=input_shape))\n model.add(Conv2D(filters=first_filters, kernel_size=ks, strides=ks,\n activation='relu', kernel_initializer=lecun_normal()))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(Conv2D(filters=first_filters*2, kernel_size=1, strides=1,\n kernel_initializer=lecun_normal()))\n model.add(Conv2D(filters=first_filters*2, kernel_size=ks, strides=ks,\n activation='relu', kernel_initializer=lecun_normal()))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(Conv2D(filters=first_filters*4, kernel_size=1, strides=1,\n kernel_initializer=lecun_normal()))\n model.add(Conv2D(filters=first_filters*4, kernel_size=ks, strides=ks,\n activation='relu', kernel_initializer=lecun_normal()))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(GlobalAveragePooling2D())\n\n model.add(Dense(units=number_of_labels, activation='softmax', kernel_initializer=lecun_normal()))\n\n filepath = \"saved_models/weights.best.hint_model_2_nin.hdf5\"\n return model, filepath\n\n\ndef hint_model_2_nin_bn(number_of_labels, first_filters=16, input_shape=(224, 224, 3)):\n ks = 2 # kernel + stride example ks=2 means (2,2) kernel and stride of 2\n model = Sequential()\n\n model.add(Conv2D(filters=first_filters, kernel_size=1, strides=1,\n kernel_initializer=lecun_normal(), input_shape=input_shape))\n model.add(Conv2D(filters=first_filters, kernel_size=ks, strides=ks,\n kernel_initializer=lecun_normal()))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(Conv2D(filters=first_filters*2, kernel_size=1, strides=1,\n kernel_initializer=lecun_normal()))\n model.add(Conv2D(filters=first_filters*2, kernel_size=ks, strides=ks,\n kernel_initializer=lecun_normal()))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(Conv2D(filters=first_filters*4, kernel_size=1, strides=1,\n kernel_initializer=lecun_normal()))\n model.add(Conv2D(filters=first_filters*4, kernel_size=ks, strides=ks,\n kernel_initializer=lecun_normal()))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=2, strides=2))\n\n model.add(GlobalAveragePooling2D())\n\n model.add(Dense(units=number_of_labels, activation='softmax', kernel_initializer=lecun_normal()))\n\n filepath = \"saved_models/weights.best.hint_model_2_nin_bn.hdf5\"\n return model, filepath\n\n\ndef model_from_scratch(number_of_labels, first_filters=16, input_shape=(224, 224, 3)):\n model = Sequential()\n\n # first layer\n model.add(Conv2D(filters=first_filters, input_shape=input_shape, kernel_size=2, strides=2))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=2))\n\n # second layer\n model.add(Conv2D(filters=first_filters*2, kernel_size=2, strides=2))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=2))\n\n # third layer\n model.add(Conv2D(filters=first_filters*4, kernel_size=2, strides=2))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=2))\n\n model.add(GlobalAveragePooling2D())\n model.add(Dense(units=number_of_labels))\n # model.add(BatchNormalization())\n model.add(Activation('softmax'))\n\n # set the filepath for saving the model's weights\n save_filepath = \"saved_models/weights.best.from_scratch.hdf5\"\n return model, save_filepath\n\n\n#\n#\n#\n\ndef test_savez_targets():\n print(\"saving targets...\")\n # load targets\n train = np.load('dogImages/train/targets.npy')\n test = np.load('dogImages/test/targets.npy')\n valid = np.load('dogImages/valid/targets.npy')\n # save targets\n np.savez('dogImages/targets.npz', train=train, test=test, valid=valid)\n print(\"all targets successfully saved!\")\n\n\ndef test_savez_tensors():\n # load files\n train_files = np.load('dogImages/train/files.npy')\n test_files = np.load('dogImages/test/files.npy')\n valid_files = np.load('dogImages/valid/files.npy')\n # load tensors\n train = paths_to_tensor(train_files).astype('float32') / 255\n test = paths_to_tensor(test_files).astype('float32') / 255\n valid = paths_to_tensor(valid_files).astype('float32') / 255\n # save tensors\n print(\"saving tensors...\")\n np.savez('dogImages/tensors.npz', train=train, test=test, valid=valid)\n print(\"all tensors successfully saved!\")\n\n\ndef test_savez_tt():\n test_savez_targets()\n test_savez_tensors()\n\n\ndef test_load_tt():\n targets = np.load('dogImages/targets.npz')\n tensors = np.load('dogImages/tensors.npz')\n\n print(targets.files)\n print(tensors.files)\n\n#\n# helper functions\n#\n\n\ndef load_data():\n # pre-process the data for Keras\n print('loading tensor and target data for keras...')\n start = time()\n raw_targets = np.load('dogImages/targets.npz')\n raw_tensors = np.load('dogImages/tensors.npz')\n stop = time()\n loading_time = round(stop - start, 0)\n print('targets and tensors loaded in %d seconds.\\n' % loading_time)\n\n print('unpacking tensor and target data...')\n start = time()\n tensors = {'train': raw_tensors['train'],\n 'test': raw_tensors['test'],\n 'valid': raw_tensors['valid']}\n targets = {'train': raw_targets['train'],\n 'test': raw_targets['test'],\n 'valid': raw_targets['valid']}\n stop = time()\n unpacking_time = round(stop - start, 0)\n print('targets and tensors unpacked in %d seconds.\\n' % unpacking_time)\n return tensors, targets\n\n\ndef train_model(model, save_path, tensors, targets, epochs=5, batch_size=20, resume=False):\n print(\"summarizing model...\")\n model.summary()\n\n if resume:\n print(\"loading saved weights...\")\n model.load_weights(save_path)\n\n start = time()\n model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n stop = time()\n compilation_time = round(stop - start, 0)\n print('model compiled in %d seconds.\\n' % compilation_time)\n\n print(\"unpacking tensors...\")\n train_tensors, train_targets = tensors['train'], targets['train']\n valid_tensors, valid_targets = tensors['valid'], targets['valid']\n print(\"tensors unpacked!\")\n\n checkpointer = ModelCheckpoint(filepath=save_path,\n verbose=1, save_best_only=True)\n start = time()\n model.fit(train_tensors, train_targets,\n validation_data=(valid_tensors, valid_targets),\n epochs=epochs, batch_size=batch_size,\n callbacks=[checkpointer, TQDMCallback()], verbose=0)\n stop = time()\n fit_time = round(stop - start, 0)\n print('model fitted in 5 epochs over %d seconds.\\n' % fit_time)\n\n\ndef test_model(model, save_path, test_tensors, test_targets):\n model.load_weights(save_path)\n\n # get index of predicted dog breed for each image in test set\n print('start preditions...')\n start = time()\n predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]\n stop = time()\n predict_time = round(stop - start, 0)\n print('predictions made in %d seconds.\\n' % predict_time)\n\n # report test accuracy\n test_accuracy = 100 * np.sum(np.array(predictions) == np.argmax(test_targets, axis=1)) / len(predictions)\n print('Test accuracy: %.4f%%\\n' % test_accuracy)\n\n#\n# main test loop\n#\n\n\ndef summarize_model(model_func):\n model, save = model_func(133)\n model.summary()\n print(save)\n\n\ndef main_test(model_func=hint_model_2, epochs=5, batch_size=20, resume=False):\n # set random seed\n random.seed(8675309)\n\n # load list of dog names\n dog_names = [item[20:-1] for item in sorted(glob(\"dogImages/train/*/\"))]\n\n # define model and save path\n model, save_path = model_func(len(dog_names))\n\n tensors, targets = load_data()\n\n train_model(model, save_path, tensors, targets, epochs, batch_size, resume)\n\n test_model(model, save_path, tensors['test'], targets['test'])\n\n\ndef test_VGG16_bottleneck_features(epochs=5, batch_size=20):\n print('testing VGG16 bottleneck features')\n print('loading bottleneck features...')\n start = time()\n bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')\n train_files, train_targets = fast_load_dataset('dogImages/train')\n valid_files, valid_targets = fast_load_dataset('dogImages/valid')\n test_files, test_targets = fast_load_dataset('dogImages/test')\n stop = time()\n loading_time = round(stop - start, 0)\n print('bottleneck features loaded in %d seconds.\\n' % loading_time)\n\n print('extracting bottleneck tensors...')\n start = time()\n train_VGG16 = bottleneck_features['train']\n valid_VGG16 = bottleneck_features['valid']\n test_VGG16 = bottleneck_features['test']\n stop = time()\n extraction_time = round(stop - start, 0)\n print('bottleneck tensors extracted in %d seconds.\\n' % extraction_time)\n\n print('defining model...')\n VGG16_model = Sequential()\n # VGG16_model.add(Dense(128, activation='relu', input_shape=train_VGG16.shape[1:], kernel_initializer=lecun_normal()))\n # VGG16_model.add(Dense(128, activation='relu', kernel_initializer=lecun_normal()))\n # VGG16_model.add(GlobalAveragePooling2D())\n VGG16_model.add(Flatten(input_shape=train_VGG16.shape[1:]))\n VGG16_model.add(Dense(133, activation='softmax', kernel_initializer=lecun_normal()))\n\n VGG16_model.summary()\n\n print('compiling model...')\n start = time()\n VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n stop = time()\n compiling_time = round(stop - start, 0)\n print('model compiled in %d seconds.\\n' % compiling_time)\n\n print('training model...')\n start = time()\n checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5',\n verbose=1, save_best_only=True)\n\n VGG16_model.fit(train_VGG16, train_targets,\n validation_data=(valid_VGG16, valid_targets),\n epochs=epochs, batch_size=batch_size,\n callbacks=[checkpointer, TQDMCallback()], verbose=0)\n stop = time()\n training_time = round(stop - start, 0)\n print('model trained in %d seconds.\\n' % training_time)\n\n VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')\n\n # get index of predicted dog breed for each image in test set\n VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]\n\n # report test accuracy\n test_accuracy = 100 * np.sum(np.array(VGG16_predictions) == np.argmax(test_targets, axis=1)) / len(\n VGG16_predictions)\n print('Test accuracy: %.4f%%' % test_accuracy)\n\n\ndef test_VGG19_bottleneck_features(epochs=5, batch_size=20):\n print('testing VGG19 bottleneck features')\n print('loading bottleneck features...')\n start = time()\n bottleneck_features = np.load('bottleneck_features/DogVGG19Data.npz')\n train_files, train_targets = fast_load_dataset('dogImages/train')\n valid_files, valid_targets = fast_load_dataset('dogImages/valid')\n test_files, test_targets = fast_load_dataset('dogImages/test')\n stop = time()\n loading_time = round(stop - start, 0)\n print('bottleneck features loaded in %d seconds.\\n' % loading_time)\n\n print('extracting bottleneck tensors...')\n start = time()\n train_VGG19 = bottleneck_features['train']\n valid_VGG19 = bottleneck_features['valid']\n test_VGG19 = bottleneck_features['test']\n stop = time()\n extraction_time = round(stop - start, 0)\n print('bottleneck tensors extracted in %d seconds.\\n' % extraction_time)\n\n print('defining model...')\n VGG19_model = Sequential()\n VGG19_model.add(Dense(128, activation='relu',\n input_shape=train_VGG19.shape[1:],\n kernel_initializer=lecun_normal()))\n VGG19_model.add(Dense(128, activation='relu',\n kernel_initializer=lecun_normal()))\n VGG19_model.add(GlobalAveragePooling2D())\n VGG19_model.add(Dense(133, activation='softmax',\n kernel_initializer=lecun_normal()))\n VGG19_model.summary()\n\n print('compiling model...')\n start = time()\n VGG19_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n stop = time()\n compiling_time = round(stop - start, 0)\n print('model compiled in %d seconds.\\n' % compiling_time)\n\n print('training model...')\n start = time()\n checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5',\n verbose=1, save_best_only=True)\n\n VGG19_model.fit(train_VGG19, train_targets,\n validation_data=(valid_VGG19, valid_targets),\n epochs=epochs, batch_size=batch_size,\n callbacks=[checkpointer, TQDMCallback()], verbose=0)\n stop = time()\n training_time = round(stop - start, 0)\n print('model trained in %d seconds.\\n' % training_time)\n\n VGG19_model.load_weights('saved_models/weights.best.VGG19.hdf5')\n\n # get index of predicted dog breed for each image in test set\n VGG19_predictions = [np.argmax(VGG19_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG19]\n\n # report test accuracy\n test_accuracy = 100 * np.sum(np.array(VGG19_predictions) == np.argmax(test_targets, axis=1)) / len(\n VGG19_predictions)\n print('Test accuracy: %.4f%%' % test_accuracy)\n\n\ndef test_resnet50_bottleneck_features(epochs=5, batch_size=20, augment_data=False):\n print('testing Resnet50 bottleneck features')\n print('loading bottleneck features...')\n start = time()\n bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')\n train_files, train_targets = fast_load_dataset('dogImages/train')\n valid_files, valid_targets = fast_load_dataset('dogImages/valid')\n test_files, test_targets = fast_load_dataset('dogImages/test')\n stop = time()\n loading_time = round(stop - start, 0)\n print('bottleneck features loaded in %d seconds.\\n' % loading_time)\n\n print('extracting bottleneck tensors...')\n start = time()\n train_resnet50 = bottleneck_features['train']\n valid_resnet50 = bottleneck_features['valid']\n test_resnet50 = bottleneck_features['test']\n stop = time()\n extraction_time = round(stop - start, 0)\n print('bottleneck tensors extracted in %d seconds.\\n' % extraction_time)\n\n print('defining model...')\n resnet50_model = Sequential()\n resnet50_model.add(Flatten(input_shape=train_resnet50.shape[1:], name='extracted_features'))\n resnet50_model.add(Dense(133, name='labels'))\n resnet50_model.add(Activation('softmax', name='softmax'))\n\n resnet50_model.summary()\n\n print('compiling model...')\n start = time()\n resnet50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n stop = time()\n compiling_time = round(stop - start, 0)\n print('model compiled in %d seconds.\\n' % compiling_time)\n\n print('training model...')\n start = time()\n checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5',\n verbose=1, save_best_only=True)\n\n if augment_data:\n pass\n datagen = ImageDataGenerator(rotation_range=45,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n fill_mode='nearest',\n horizontal_flip=True,\n data_format='channels_last')\n\n train_generator = datagen.flow(train_resnet50, train_targets, batch_size=batch_size)\n validation_generator = datagen.flow(valid_resnet50, valid_targets, batch_size=batch_size)\n\n resnet50_model.fit_generator(generator=train_generator,\n steps_per_epoch=100,\n epochs=epochs,\n verbose=1,\n callbacks=[checkpointer],\n validation_data=validation_generator,\n validation_steps=100)\n else:\n resnet50_model.fit(train_resnet50, train_targets,\n validation_data=(valid_resnet50, valid_targets),\n epochs=epochs, batch_size=batch_size,\n callbacks=[checkpointer, TQDMCallback()], verbose=0)\n stop = time()\n training_time = round(stop - start, 0)\n print('model trained in %d seconds.\\n' % training_time)\n\n resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')\n\n # get index of predicted dog breed for each image in test set\n predictions = [np.argmax(resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_resnet50]\n\n # report test accuracy\n test_accuracy = 100 * np.sum(np.array(predictions) == np.argmax(test_targets, axis=1)) / len(predictions)\n print('Test accuracy: %.4f%%' % test_accuracy)\n\n\ndef test_InceptionV3_bottleneck_features(epochs=5, batch_size=20):\n print('testing InceptionV3 bottleneck features')\n print('loading bottleneck features...')\n start = time()\n bottleneck_features = np.load('bottleneck_features/DogInceptionV3Data.npz')\n train_files, train_targets = fast_load_dataset('dogImages/train')\n valid_files, valid_targets = fast_load_dataset('dogImages/valid')\n test_files, test_targets = fast_load_dataset('dogImages/test')\n stop = time()\n loading_time = round(stop - start, 0)\n print('bottleneck features loaded in %d seconds.\\n' % loading_time)\n\n print('extracting bottleneck tensors...')\n start = time()\n train_InceptionV3 = bottleneck_features['train']\n valid_InceptionV3 = bottleneck_features['valid']\n test_InceptionV3 = bottleneck_features['test']\n stop = time()\n extraction_time = round(stop - start, 0)\n print('bottleneck tensors extracted in %d seconds.\\n' % extraction_time)\n\n print('defining model...')\n InceptionV3_model = Sequential()\n InceptionV3_model.add(Dense(128, activation='relu',\n input_shape=train_InceptionV3.shape[1:],\n kernel_initializer=lecun_normal()))\n InceptionV3_model.add(Dense(128, activation='relu',\n kernel_initializer=lecun_normal()))\n InceptionV3_model.add(GlobalAveragePooling2D())\n InceptionV3_model.add(Dense(133, activation='softmax', kernel_initializer=lecun_normal()))\n\n InceptionV3_model.summary()\n\n print('compiling model...')\n start = time()\n InceptionV3_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n stop = time()\n compiling_time = round(stop - start, 0)\n print('model compiled in %d seconds.\\n' % compiling_time)\n\n print('training model...')\n start = time()\n checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.InceptionV3.hdf5',\n verbose=1, save_best_only=True)\n\n InceptionV3_model.fit(train_InceptionV3, train_targets,\n validation_data=(valid_InceptionV3, valid_targets),\n epochs=epochs, batch_size=batch_size,\n callbacks=[checkpointer, TQDMCallback()], verbose=0)\n stop = time()\n training_time = round(stop - start, 0)\n print('model trained in %d seconds.\\n' % training_time)\n\n InceptionV3_model.load_weights('saved_models/weights.best.InceptionV3.hdf5')\n\n # get index of predicted dog breed for each image in test set\n predictions = [np.argmax(InceptionV3_model.predict(np.expand_dims(feature, axis=0))) for feature in test_InceptionV3]\n\n # report test accuracy\n test_accuracy = 100 * np.sum(np.array(predictions) == np.argmax(test_targets, axis=1)) / len(predictions)\n print('Test accuracy: %.4f%%' % test_accuracy)\n\n#\n# Resnet50\n#\n\n\ndef test_save_resnet50():\n print(\"downloading weights...\")\n model = ResNet50(include_top=False, weights='imagenet')\n print(\"weights downloaded!\")\n model.save_weights(filepath='model_weights/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5')\n print(\"weights saved!\")\n\n\ndef test_load_resnet50():\n print(\"loading weights...\")\n model = ResNet50(include_top=False, weights='model_weights/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5')\n print(\"weights loaded!\")\n\n#\n# main method\n#\n\n\ndef main():\n print(\"START\")\n start = time()\n # summarize_model(model_from_scratch)\n main_test(model_from_scratch, epochs=1, batch_size=20, resume=True)\n # test_VGG16_bottleneck_features()\n # test_VGG19_bottleneck_features()\n # test_resnet50_bottleneck_features()\n # test_InceptionV3_bottleneck_features()\n stop = time()\n total_time = round(stop - start, 0)\n print(\"total runtime was %d seconds\\n\" % total_time)\n print(\"END\")\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.expand_dims", "numpy.savez", "numpy.save", "sklearn.datasets.load_files", "numpy.argmax", "numpy.load", "numpy.array", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tylerhuntington222/yellowbrick
[ "4db12724d10d4abe6cf97374380d11ac9025ac3e", "4db12724d10d4abe6cf97374380d11ac9025ac3e" ]
[ "yellowbrick/model_selection/validation_curve.py", "docs/gallery.py" ]
[ "# yellowbrick.model_selection.validation_curve\n# Implements a visual validation curve for a hyperparameter.\n#\n# Author: Benjamin Bengfort\n# Created: Sat Mar 31 06:27:28 2018 -0400\n#\n# Copyright (C) 2018 The scikit-yb developers\n# For license information, see LICENSE.txt\n#\n# ID: validation_curve.py [c5355ee] [email protected] $\n\n\"\"\"\nImplements a visual validation curve for a hyperparameter.\n\"\"\"\n\n##########################################################################\n# Imports\n##########################################################################\n\nimport numpy as np\n\nfrom yellowbrick.base import ModelVisualizer\nfrom yellowbrick.style import resolve_colors\nfrom yellowbrick.exceptions import YellowbrickValueError\n\nfrom sklearn.model_selection import validation_curve as sk_validation_curve\n\n\n##########################################################################\n# ValidationCurve visualizer\n##########################################################################\n\n\nclass ValidationCurve(ModelVisualizer):\n \"\"\"\n Visualizes the validation curve for both test and training data for a\n range of values for a single hyperparameter of the model. Adjusting the\n value of a hyperparameter adjusts the complexity of a model. Less complex\n models suffer from increased error due to bias, while more complex models\n suffer from increased error due to variance. By inspecting the training\n and cross-validated test score error, it is possible to estimate a good\n value for a hyperparameter that balances the bias/variance trade-off.\n\n The visualizer evaluates cross-validated training and test scores for the\n different hyperparameters supplied. The curve is plotted so that the\n x-axis is the value of the hyperparameter and the y-axis is the model\n score. This is similar to a grid search with a single hyperparameter.\n\n The cross-validation generator splits the dataset k times, and scores are\n averaged over all k runs for the training and test subsets. The curve\n plots the mean score, and the filled in area suggests the variability of\n cross-validation by plotting one standard deviation above and below the\n mean for each split.\n\n Parameters\n ----------\n model : a scikit-learn estimator\n An object that implements ``fit`` and ``predict``, can be a\n classifier, regressor, or clusterer so long as there is also a valid\n associated scoring metric.\n\n Note that the object is cloned for each validation.\n\n param_name : string\n Name of the parameter that will be varied.\n\n param_range : array-like, shape (n_values,)\n The values of the parameter that will be evaluated.\n\n ax : matplotlib.Axes object, optional\n The axes object to plot the figure on.\n\n logx : boolean, optional\n If True, plots the x-axis with a logarithmic scale.\n\n groups : array-like, with shape (n_samples,)\n Optional group labels for the samples used while splitting the dataset\n into train/test sets.\n\n cv : int, cross-validation generator or an iterable, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n - None, to use the default 3-fold cross-validation,\n - integer, to specify the number of folds.\n - An object to be used as a cross-validation generator.\n - An iterable yielding train/test splits.\n\n see the scikit-learn\n `cross-validation guide <https://bit.ly/2MMQAI7>`_\n for more information on the possible strategies that can be used here.\n\n scoring : string, callable or None, optional, default: None\n A string or scorer callable object / function with signature\n ``scorer(estimator, X, y)``. See scikit-learn model evaluation\n documentation for names of possible metrics.\n\n n_jobs : integer, optional\n Number of jobs to run in parallel (default 1).\n\n pre_dispatch : integer or string, optional\n Number of predispatched jobs for parallel execution (default is\n all). The option can reduce the allocated memory. The string can\n be an expression like '2*n_jobs'.\n\n kwargs : dict\n Keyword arguments that are passed to the base class and may influence\n the visualization as defined in other Visualizers.\n\n Attributes\n ----------\n train_scores_ : array, shape (n_ticks, n_cv_folds)\n Scores on training sets.\n\n train_scores_mean_ : array, shape (n_ticks,)\n Mean training data scores for each training split\n\n train_scores_std_ : array, shape (n_ticks,)\n Standard deviation of training data scores for each training split\n\n test_scores_ : array, shape (n_ticks, n_cv_folds)\n Scores on test set.\n\n test_scores_mean_ : array, shape (n_ticks,)\n Mean test data scores for each test split\n\n test_scores_std_ : array, shape (n_ticks,)\n Standard deviation of test data scores for each test split\n\n Examples\n --------\n\n >>> import numpy as np\n >>> from yellowbrick.model_selection import ValidationCurve\n >>> from sklearn.svm import SVC\n >>> pr = np.logspace(-6,-1,5)\n >>> model = ValidationCurve(SVC(), param_name=\"gamma\", param_range=pr)\n >>> model.fit(X, y)\n >>> model.poof()\n\n Notes\n -----\n This visualizer is essentially a wrapper for the\n ``sklearn.model_selection.learning_curve utility``, discussed in the\n `validation curves <https://bit.ly/2KlumeB>`__\n documentation.\n\n .. seealso:: The documentation for the\n `learning_curve <https://bit.ly/2Yz9sBB>`__\n function, which this visualizer wraps.\n \"\"\"\n\n def __init__(\n self,\n model,\n param_name,\n param_range,\n ax=None,\n logx=False,\n groups=None,\n cv=None,\n scoring=None,\n n_jobs=1,\n pre_dispatch=\"all\",\n **kwargs\n ):\n\n # Initialize the model visualizer\n super(ValidationCurve, self).__init__(model, ax=ax, **kwargs)\n\n # Validate the param_range\n param_range = np.asarray(param_range)\n if param_range.ndim != 1:\n raise YellowbrickValueError(\n \"must specify array of param values, '{}' is not valid\".format(\n repr(param_range)\n )\n )\n\n # Set the visual and validation curve parameters on the estimator\n self.set_params(\n param_name=param_name,\n param_range=param_range,\n logx=logx,\n groups=groups,\n cv=cv,\n scoring=scoring,\n n_jobs=n_jobs,\n pre_dispatch=pre_dispatch,\n )\n\n def fit(self, X, y=None):\n \"\"\"\n Fits the validation curve with the wrapped estimator and parameter\n array to the specified data. Draws training and test score curves and\n saves the scores to the visualizer.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to X for classification or regression;\n None for unsupervised learning.\n\n Returns\n -------\n self : instance\n Returns the instance of the validation curve visualizer for use in\n pipelines and other sequential transformers.\n \"\"\"\n # arguments to pass to sk_validation_curve\n skvc_kwargs = {\n key: self.get_params()[key]\n for key in (\n \"param_name\",\n \"param_range\",\n \"groups\",\n \"cv\",\n \"scoring\",\n \"n_jobs\",\n \"pre_dispatch\",\n )\n }\n\n # compute the validation curve and store scores\n curve = sk_validation_curve(self.estimator, X, y, **skvc_kwargs)\n self.train_scores_, self.test_scores_ = curve\n\n # compute the mean and standard deviation of the training data\n self.train_scores_mean_ = np.mean(self.train_scores_, axis=1)\n self.train_scores_std_ = np.std(self.train_scores_, axis=1)\n\n # compute the mean and standard deviation of the test data\n self.test_scores_mean_ = np.mean(self.test_scores_, axis=1)\n self.test_scores_std_ = np.std(self.test_scores_, axis=1)\n\n # draw the curves on the current axes\n self.draw()\n return self\n\n def draw(self, **kwargs):\n \"\"\"\n Renders the training and test curves.\n \"\"\"\n # Specify the curves to draw and their labels\n labels = (\"Training Score\", \"Cross Validation Score\")\n curves = (\n (self.train_scores_mean_, self.train_scores_std_),\n (self.test_scores_mean_, self.test_scores_std_),\n )\n\n # Get the colors for the train and test curves\n colors = resolve_colors(n_colors=2)\n\n # Plot the fill betweens first so they are behind the curves.\n for idx, (mean, std) in enumerate(curves):\n # Plot one standard deviation above and below the mean\n self.ax.fill_between(\n self.param_range, mean - std, mean + std, alpha=0.25, color=colors[idx]\n )\n\n # Plot the mean curves so they are in front of the variance fill\n for idx, (mean, _) in enumerate(curves):\n self.ax.plot(\n self.param_range, mean, \"d-\", color=colors[idx], label=labels[idx]\n )\n\n if self.logx:\n self.ax.set_xscale(\"log\")\n\n return self.ax\n\n def finalize(self, **kwargs):\n \"\"\"\n Add the title, legend, and other visual final touches to the plot.\n \"\"\"\n # Set the title of the figure\n self.set_title(\"Validation Curve for {}\".format(self.name))\n\n # Add the legend\n self.ax.legend(frameon=True, loc=\"best\")\n\n # Set the axis labels\n self.ax.set_xlabel(self.param_name)\n self.ax.set_ylabel(\"score\")\n\n\n##########################################################################\n# Quick Method\n##########################################################################\n\n\ndef validation_curve(\n model,\n X,\n y,\n param_name,\n param_range,\n ax=None,\n logx=False,\n groups=None,\n cv=None,\n scoring=None,\n n_jobs=1,\n pre_dispatch=\"all\",\n **kwargs\n):\n \"\"\"\n Displays a validation curve for the specified param and values, plotting\n both the train and cross-validated test scores. The validation curve is a\n visual, single-parameter grid search used to tune a model to find the best\n balance between error due to bias and error due to variance.\n\n This helper function is a wrapper to use the ValidationCurve in a fast,\n visual analysis.\n\n Parameters\n ----------\n model : a scikit-learn estimator\n An object that implements ``fit`` and ``predict``, can be a\n classifier, regressor, or clusterer so long as there is also a valid\n associated scoring metric.\n\n Note that the object is cloned for each validation.\n\n X : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to X for classification or regression;\n None for unsupervised learning.\n\n param_name : string\n Name of the parameter that will be varied.\n\n param_range : array-like, shape (n_values,)\n The values of the parameter that will be evaluated.\n\n ax : matplotlib.Axes object, optional\n The axes object to plot the figure on.\n\n logx : boolean, optional\n If True, plots the x-axis with a logarithmic scale.\n\n groups : array-like, with shape (n_samples,)\n Optional group labels for the samples used while splitting the dataset\n into train/test sets.\n\n cv : int, cross-validation generator or an iterable, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n - None, to use the default 3-fold cross-validation,\n - integer, to specify the number of folds.\n - An object to be used as a cross-validation generator.\n - An iterable yielding train/test splits.\n\n see the scikit-learn\n `cross-validation guide <https://bit.ly/2MMQAI7>`_\n for more information on the possible strategies that can be used here.\n\n scoring : string, callable or None, optional, default: None\n A string or scorer callable object / function with signature\n ``scorer(estimator, X, y)``. See scikit-learn model evaluation\n documentation for names of possible metrics.\n\n n_jobs : integer, optional\n Number of jobs to run in parallel (default 1).\n\n pre_dispatch : integer or string, optional\n Number of predispatched jobs for parallel execution (default is\n all). The option can reduce the allocated memory. The string can\n be an expression like '2*n_jobs'.\n\n kwargs : dict\n Keyword arguments that are passed to the base class and may influence\n the visualization as defined in other Visualizers. These arguments are\n also passed to the `poof()` method, e.g. can pass a path to save the\n figure to.\n\n Returns\n -------\n visualizer : ValidationCurve\n The fitted visualizer\n \"\"\"\n\n # Initialize the visualizer\n oz = ValidationCurve(\n model,\n param_name,\n param_range,\n ax=ax,\n logx=logx,\n groups=groups,\n cv=cv,\n scoring=scoring,\n n_jobs=n_jobs,\n pre_dispatch=pre_dispatch,\n )\n\n # Fit and poof the visualizer\n oz.fit(X, y)\n oz.poof(**kwargs)\n return oz\n", "#!/usr/bin/env python3\n# Generates images for the gallery\n\nimport os\nimport argparse\nimport numpy as np\nimport os.path as path\nimport matplotlib.pyplot as plt\n\nfrom yellowbrick.datasets import load_occupancy, load_credit, load_concrete\nfrom yellowbrick.datasets import load_spam, load_game, load_energy, load_hobbies\n\nfrom yellowbrick.model_selection import RFECV, FeatureImportances\n\nfrom yellowbrick.features import PCA, Manifold, JointPlot\nfrom yellowbrick.features import RadViz, Rank1D, Rank2D, ParallelCoordinates\n\nfrom yellowbrick.contrib.scatter import ScatterVisualizer\n\nfrom yellowbrick.regressor import ResidualsPlot, PredictionError, AlphaSelection\n\nfrom yellowbrick.classifier import DiscriminationThreshold\nfrom yellowbrick.classifier import ClassificationReport, ConfusionMatrix\nfrom yellowbrick.classifier import ROCAUC, PRCurve, ClassPredictionError\n\nfrom yellowbrick.cluster import KElbowVisualizer, SilhouetteVisualizer\nfrom yellowbrick.cluster import InterclusterDistance\n\nfrom yellowbrick.model_selection import ValidationCurve, LearningCurve, CVScores\nfrom yellowbrick.contrib.classifier import DecisionViz\n\nfrom yellowbrick.text import (\n FreqDistVisualizer,\n TSNEVisualizer,\n DispersionPlot,\n PosTagVisualizer,\n)\n\nfrom yellowbrick.target import (\n BalancedBinningReference,\n ClassBalance,\n FeatureCorrelation,\n)\n\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import RidgeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.naive_bayes import GaussianNB, MultinomialNB\nfrom sklearn.model_selection import train_test_split as tts\nfrom sklearn.preprocessing import OrdinalEncoder, LabelEncoder\nfrom sklearn.linear_model import Ridge, Lasso, LassoCV, RidgeCV\nfrom sklearn.datasets import load_iris, load_digits, load_diabetes\nfrom sklearn.datasets import make_classification, make_blobs, make_moons\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n\n\nGALLERY = path.join(path.dirname(__file__), \"images\", \"gallery\")\n\n\n##########################################################################\n## Helper Methods\n##########################################################################\n\n\ndef newfig():\n \"\"\"\n Helper function to create an axes object of the gallery dimensions.\n \"\"\"\n # NOTE: this figsize generates a better thumbnail\n _, ax = plt.subplots(figsize=(8, 4))\n return ax\n\n\ndef savefig(viz, name, gallery=GALLERY):\n \"\"\"\n Saves the figure to the gallery directory\n \"\"\"\n if not path.exists(gallery):\n os.makedirs(gallery)\n\n # Must save as png\n if len(name.split(\".\")) > 1:\n raise ValueError(\"name should not specify extension\")\n\n outpath = path.join(gallery, name + \".png\")\n viz.poof(outpath=outpath)\n print(\"created {}\".format(outpath))\n\n\n##########################################################################\n## Feature Analysis\n##########################################################################\n\n\ndef radviz():\n X, y = load_occupancy()\n oz = RadViz(ax=newfig())\n oz.fit_transform(X, y)\n savefig(oz, \"radviz\")\n\n\ndef rank1d():\n X, y = load_credit()\n oz = Rank1D(algorithm=\"shapiro\", ax=newfig())\n oz.fit_transform(X, y)\n savefig(oz, \"rank1d_shapiro\")\n\n\ndef rank2d():\n X, y = load_credit()\n oz = Rank2D(algorithm=\"covariance\", ax=newfig())\n oz.fit_transform(X, y)\n savefig(oz, \"rank2d_covariance\")\n\n\ndef pcoords():\n X, y = load_occupancy()\n oz = ParallelCoordinates(sample=0.05, shuffle=True, ax=newfig())\n oz.fit_transform(X, y)\n savefig(oz, \"parallel_coordinates\")\n\n\ndef pca():\n X, y = load_credit()\n colors = np.array([\"r\" if yi else \"b\" for yi in y])\n oz = PCA(scale=True, color=colors, proj_dim=3)\n oz.fit_transform(X, y)\n savefig(oz, \"pca_projection_3d\")\n\n\ndef manifold(dataset, manifold):\n if dataset == \"concrete\":\n X, y = load_concrete()\n elif dataset == \"occupancy\":\n X, y = load_occupancy()\n else:\n raise ValueError(\"unknown dataset\")\n\n oz = Manifold(manifold=manifold, ax=newfig())\n oz.fit_transform(X, y)\n savefig(oz, \"{}_{}_manifold\".format(dataset, manifold))\n\n\ndef scatter():\n X, y = load_occupancy()\n oz = ScatterVisualizer(x=\"light\", y=\"CO2\", ax=newfig())\n oz.fit_transform(X, y)\n savefig(oz, \"scatter\")\n\n\ndef jointplot():\n X, y = load_concrete()\n oz = JointPlot(columns=[\"cement\", \"splast\"], ax=newfig())\n oz.fit_transform(X, y)\n savefig(oz, \"jointplot\")\n\n\n##########################################################################\n## Regression\n##########################################################################\n\n\ndef residuals():\n X, y = load_concrete()\n X_train, X_test, y_train, y_test = tts(X, y, test_size=0.2)\n oz = ResidualsPlot(Ridge(), ax=newfig())\n oz.fit(X_train, y_train)\n oz.score(X_test, y_test)\n savefig(oz, \"residuals\")\n\n\ndef peplot():\n X, y = load_concrete()\n X_train, X_test, y_train, y_test = tts(X, y, test_size=0.2)\n oz = PredictionError(Lasso(), ax=newfig())\n oz.fit(X_train, y_train)\n oz.score(X_test, y_test)\n savefig(oz, \"prediction_error\")\n\n\ndef alphas():\n X, y = load_concrete()\n alphas = np.logspace(-10, 1, 400)\n oz = AlphaSelection(LassoCV(alphas=alphas), ax=newfig())\n oz.fit(X, y)\n savefig(oz, \"alpha_selection\")\n\n\n##########################################################################\n## Classification\n##########################################################################\n\n\ndef classreport():\n X, y = load_occupancy()\n X_train, X_test, y_train, y_test = tts(X, y, test_size=0.2)\n oz = ClassificationReport(GaussianNB(), support=True, ax=newfig())\n oz.fit(X_train, y_train)\n oz.score(X_test, y_test)\n savefig(oz, \"classification_report\")\n\n\ndef confusion(dataset):\n if dataset == \"iris\":\n data = load_iris()\n elif dataset == \"digits\":\n data = load_digits()\n else:\n raise ValueError(\"uknown dataset\")\n\n X_train, X_test, y_train, y_test = tts(data.data, data.target, test_size=0.2)\n oz = ConfusionMatrix(LogisticRegression(), ax=newfig())\n oz.fit(X_train, y_train)\n oz.score(X_test, y_test)\n savefig(oz, \"confusion_matrix_{}\".format(dataset))\n\n\ndef rocauc(dataset):\n if dataset == \"binary\":\n X, y = load_occupancy()\n model = GaussianNB()\n elif dataset == \"multiclass\":\n X, y = load_game()\n X = OrdinalEncoder().fit_transform(X)\n model = RidgeClassifier()\n else:\n raise ValueError(\"uknown dataset\")\n\n X_train, X_test, y_train, y_test = tts(X, y, test_size=0.2)\n oz = ROCAUC(model, ax=newfig())\n oz.fit(X_train, y_train)\n oz.score(X_test, y_test)\n savefig(oz, \"rocauc_{}\".format(dataset))\n\n\ndef prcurve(dataset):\n if dataset == \"binary\":\n X, y = load_spam()\n model = RidgeClassifier()\n kws = {}\n elif dataset == \"multiclass\":\n X, y = load_game()\n X = OrdinalEncoder().fit_transform(X)\n y = LabelEncoder().fit_transform(y)\n model = MultinomialNB()\n kws = {\n \"per_class\": True,\n \"iso_f1_curves\": True,\n \"fill_area\": False,\n \"micro\": False,\n }\n else:\n raise ValueError(\"uknown dataset\")\n\n X_train, X_test, y_train, y_test = tts(X, y, test_size=0.2, shuffle=True)\n oz = PRCurve(model, ax=newfig(), **kws)\n oz.fit(X_train, y_train)\n oz.score(X_test, y_test)\n savefig(oz, \"precision_recall_{}\".format(dataset))\n\n\ndef classprede():\n X, y = make_classification(\n n_samples=1000, n_classes=5, n_informative=3, n_clusters_per_class=1\n )\n\n classes = [\"apple\", \"kiwi\", \"pear\", \"banana\", \"orange\"]\n\n # Perform 80/20 training/test split\n X_train, X_test, y_train, y_test = tts(X, y, test_size=0.20)\n oz = ClassPredictionError(RandomForestClassifier(), classes=classes, ax=newfig())\n oz.fit(X_train, y_train)\n oz.score(X_test, y_test)\n savefig(oz, \"class_prediction_error\")\n\n\ndef discrimination():\n X, y = load_spam()\n oz = DiscriminationThreshold(LogisticRegression(solver=\"lbfgs\"), ax=newfig())\n oz.fit(X, y)\n savefig(oz, \"discrimination_threshold\")\n\n\n##########################################################################\n## Clustering\n##########################################################################\n\n\ndef elbow():\n X, _ = make_blobs(centers=8, n_features=12, shuffle=True)\n oz = KElbowVisualizer(KMeans(), k=(4, 12), ax=newfig())\n oz.fit(X)\n savefig(oz, \"elbow\")\n\n\ndef silhouette():\n X, _ = make_blobs(centers=8)\n oz = SilhouetteVisualizer(MiniBatchKMeans(6), ax=newfig())\n oz.fit(X)\n savefig(oz, \"silhouette\")\n\n\ndef icdm():\n X, _ = make_blobs(centers=12, n_samples=1000, n_features=16, shuffle=True)\n oz = InterclusterDistance(KMeans(9), ax=newfig())\n oz.fit(X)\n savefig(oz, \"icdm\")\n\n\n##########################################################################\n## Model Selection\n##########################################################################\n\n\ndef validation():\n X, y = load_energy()\n oz = ValidationCurve(\n DecisionTreeRegressor(),\n param_name=\"max_depth\",\n param_range=np.arange(1, 11),\n cv=10,\n scoring=\"r2\",\n ax=newfig(),\n )\n oz.fit(X, y)\n savefig(oz, \"validation_curve\")\n\n\ndef learning():\n X, y = load_energy()\n sizes = np.linspace(0.3, 1.0, 10)\n oz = LearningCurve(RidgeCV(), train_sizes=sizes, scoring=\"r2\", ax=newfig())\n oz.fit(X, y)\n savefig(oz, \"learning_curve\")\n\n\ndef cvscores():\n X, y = load_energy()\n oz = CVScores(Ridge(), scoring=\"r2\", cv=10, ax=newfig())\n oz.fit(X, y)\n savefig(oz, \"cv_scores\")\n\n\ndef decision():\n X, y = make_moons(noise=0.3)\n X = StandardScaler().fit_transform(X)\n X_train, X_test, y_train, y_test = tts(X, y, test_size=0.20)\n\n oz = DecisionViz(KNeighborsClassifier(3), ax=newfig())\n oz.fit(X_train, y_train)\n oz.draw(X_test, y_test)\n savefig(oz, \"decision_boundaries\")\n\n\ndef importances():\n X, y = load_occupancy()\n oz = FeatureImportances(RandomForestClassifier(), ax=newfig())\n oz.fit(X, y)\n savefig(oz, \"feature_importances\")\n\n\ndef rfecv():\n X, y = load_credit()\n model = RandomForestClassifier(n_estimators=10)\n oz = RFECV(model, cv=3, scoring=\"f1_weighted\", ax=newfig())\n oz.fit(X, y)\n savefig(oz, \"rfecv_sklearn_example\")\n\n\n##########################################################################\n## Text Model Diagnostics\n##########################################################################\n\n\ndef freqdist():\n corpus = load_hobbies()\n vecs = CountVectorizer()\n docs = vecs.fit_transform(corpus.data)\n\n oz = FreqDistVisualizer(features=vecs.get_feature_names(), ax=newfig())\n oz.fit(docs)\n savefig(oz, \"freqdist\")\n\n\ndef tsne():\n corpus = load_hobbies()\n docs = TfidfVectorizer().fit_transform(corpus.data)\n\n oz = TSNEVisualizer(ax=newfig())\n oz.fit(docs, corpus.target)\n savefig(oz, \"corpus_tsne\")\n\n\ndef dispersion():\n corpus = load_hobbies()\n target_words = [\"Game\", \"player\", \"score\", \"oil\", \"Man\"]\n\n oz = DispersionPlot(target_words, ax=newfig())\n oz.fit([doc.split() for doc in corpus.data])\n savefig(oz, \"dispersion\")\n\n\ndef postag():\n tagged_stanzas = [\n [\n [\n (\"Whose\", \"JJ\"),\n (\"woods\", \"NNS\"),\n (\"these\", \"DT\"),\n (\"are\", \"VBP\"),\n (\"I\", \"PRP\"),\n (\"think\", \"VBP\"),\n (\"I\", \"PRP\"),\n (\"know\", \"VBP\"),\n (\".\", \".\"),\n ],\n [\n (\"His\", \"PRP$\"),\n (\"house\", \"NN\"),\n (\"is\", \"VBZ\"),\n (\"in\", \"IN\"),\n (\"the\", \"DT\"),\n (\"village\", \"NN\"),\n (\"though\", \"IN\"),\n (\";\", \":\"),\n (\"He\", \"PRP\"),\n (\"will\", \"MD\"),\n (\"not\", \"RB\"),\n (\"see\", \"VB\"),\n (\"me\", \"PRP\"),\n (\"stopping\", \"VBG\"),\n (\"here\", \"RB\"),\n (\"To\", \"TO\"),\n (\"watch\", \"VB\"),\n (\"his\", \"PRP$\"),\n (\"woods\", \"NNS\"),\n (\"fill\", \"VB\"),\n (\"up\", \"RP\"),\n (\"with\", \"IN\"),\n (\"snow\", \"NNS\"),\n (\".\", \".\"),\n ],\n ],\n [\n [\n (\"My\", \"PRP$\"),\n (\"little\", \"JJ\"),\n (\"horse\", \"NN\"),\n (\"must\", \"MD\"),\n (\"think\", \"VB\"),\n (\"it\", \"PRP\"),\n (\"queer\", \"JJR\"),\n (\"To\", \"TO\"),\n (\"stop\", \"VB\"),\n (\"without\", \"IN\"),\n (\"a\", \"DT\"),\n (\"farmhouse\", \"NN\"),\n (\"near\", \"IN\"),\n (\"Between\", \"NNP\"),\n (\"the\", \"DT\"),\n (\"woods\", \"NNS\"),\n (\"and\", \"CC\"),\n (\"frozen\", \"JJ\"),\n (\"lake\", \"VB\"),\n (\"The\", \"DT\"),\n (\"darkest\", \"JJS\"),\n (\"evening\", \"NN\"),\n (\"of\", \"IN\"),\n (\"the\", \"DT\"),\n (\"year\", \"NN\"),\n (\".\", \".\"),\n ]\n ],\n [\n [\n (\"He\", \"PRP\"),\n (\"gives\", \"VBZ\"),\n (\"his\", \"PRP$\"),\n (\"harness\", \"NN\"),\n (\"bells\", \"VBZ\"),\n (\"a\", \"DT\"),\n (\"shake\", \"NN\"),\n (\"To\", \"TO\"),\n (\"ask\", \"VB\"),\n (\"if\", \"IN\"),\n (\"there\", \"EX\"),\n (\"is\", \"VBZ\"),\n (\"some\", \"DT\"),\n (\"mistake\", \"NN\"),\n (\".\", \".\"),\n ],\n [\n (\"The\", \"DT\"),\n (\"only\", \"JJ\"),\n (\"other\", \"JJ\"),\n (\"sound\", \"NN\"),\n (\"’\", \"NNP\"),\n (\"s\", \"VBZ\"),\n (\"the\", \"DT\"),\n (\"sweep\", \"NN\"),\n (\"Of\", \"IN\"),\n (\"easy\", \"JJ\"),\n (\"wind\", \"NN\"),\n (\"and\", \"CC\"),\n (\"downy\", \"JJ\"),\n (\"flake\", \"NN\"),\n (\".\", \".\"),\n ],\n ],\n [\n [\n (\"The\", \"DT\"),\n (\"woods\", \"NNS\"),\n (\"are\", \"VBP\"),\n (\"lovely\", \"RB\"),\n (\",\", \",\"),\n (\"dark\", \"JJ\"),\n (\"and\", \"CC\"),\n (\"deep\", \"JJ\"),\n (\",\", \",\"),\n (\"But\", \"CC\"),\n (\"I\", \"PRP\"),\n (\"have\", \"VBP\"),\n (\"promises\", \"NNS\"),\n (\"to\", \"TO\"),\n (\"keep\", \"VB\"),\n (\",\", \",\"),\n (\"And\", \"CC\"),\n (\"miles\", \"NNS\"),\n (\"to\", \"TO\"),\n (\"go\", \"VB\"),\n (\"before\", \"IN\"),\n (\"I\", \"PRP\"),\n (\"sleep\", \"VBP\"),\n (\",\", \",\"),\n (\"And\", \"CC\"),\n (\"miles\", \"NNS\"),\n (\"to\", \"TO\"),\n (\"go\", \"VB\"),\n (\"before\", \"IN\"),\n (\"I\", \"PRP\"),\n (\"sleep\", \"VBP\"),\n (\".\", \".\"),\n ]\n ],\n ]\n oz = PosTagVisualizer(ax=newfig())\n oz.fit(tagged_stanzas)\n savefig(oz, \"postag\")\n\n\n##########################################################################\n## Target Visualizations\n##########################################################################\n\n\ndef binning():\n _, y = load_concrete()\n oz = BalancedBinningReference(ax=newfig())\n oz.fit(y)\n savefig(oz, \"balanced_binning_reference\")\n\n\ndef balance():\n X, y = load_occupancy()\n _, _, y_train, y_test = tts(X, y, test_size=0.2)\n\n oz = ClassBalance(ax=newfig(), labels=[\"unoccupied\", \"occupied\"])\n oz.fit(y_train, y_test)\n savefig(oz, \"class_balance\")\n\n\ndef featcorr():\n data = load_diabetes()\n\n oz = FeatureCorrelation(ax=newfig())\n oz.fit(data.data, data.target)\n savefig(oz, \"feature_correlation\")\n\n\n##########################################################################\n## Main Method\n##########################################################################\n\nif __name__ == \"__main__\":\n plots = {\n \"all\": None,\n \"radviz\": radviz,\n \"rank1d\": rank1d,\n \"rank2d\": rank2d,\n \"pcoords\": pcoords,\n \"pca\": pca,\n \"concrete_tsne\": lambda: manifold(\"concrete\", \"tsne\"),\n \"occupancy_tsne\": lambda: manifold(\"occupancy\", \"tsne\"),\n \"concrete_isomap\": lambda: manifold(\"concrete\", \"isomap\"),\n \"importances\": importances,\n \"rfecv\": rfecv,\n \"scatter\": scatter,\n \"jointplot\": jointplot,\n \"residuals\": residuals,\n \"peplot\": peplot,\n \"alphas\": alphas,\n \"classreport\": classreport,\n \"confusion_digits\": lambda: confusion(\"digits\"),\n \"confusion_iris\": lambda: confusion(\"iris\"),\n \"rocauc_binary\": lambda: rocauc(\"binary\"),\n \"rocauc_multi\": lambda: rocauc(\"multiclass\"),\n \"prcurve_binary\": lambda: prcurve(\"binary\"),\n \"prcurve_multi\": lambda: prcurve(\"multiclass\"),\n \"classprede\": classprede,\n \"discrimination\": discrimination,\n \"elbow\": elbow,\n \"silhouette\": silhouette,\n \"icdm\": icdm,\n \"validation\": validation,\n \"learning\": learning,\n \"cvscores\": cvscores,\n \"freqdist\": freqdist,\n \"tsne\": tsne,\n \"dispersion\": dispersion,\n \"postag\": postag,\n \"decision\": decision,\n \"binning\": binning,\n \"balance\": balance,\n \"featcorr\": featcorr,\n }\n\n parser = argparse.ArgumentParser(description=\"gallery image generator\")\n parser.add_argument(\n \"plots\",\n nargs=\"+\",\n choices=plots.keys(),\n metavar=\"plot\",\n help=\"names of images to generate\",\n )\n args = parser.parse_args()\n\n queue = frozenset(args.plots)\n if \"all\" in queue:\n queue = frozenset(plots.keys())\n\n for item in queue:\n method = plots[item]\n if method is not None:\n method()\n" ]
[ [ "numpy.asarray", "numpy.std", "numpy.mean", "sklearn.model_selection.validation_curve" ], [ "sklearn.datasets.make_classification", "numpy.linspace", "sklearn.cluster.KMeans", "sklearn.datasets.load_diabetes", "sklearn.preprocessing.LabelEncoder", "sklearn.datasets.make_blobs", "sklearn.ensemble.RandomForestClassifier", "numpy.arange", "sklearn.linear_model.Lasso", "sklearn.neighbors.KNeighborsClassifier", "sklearn.feature_extraction.text.CountVectorizer", "sklearn.linear_model.RidgeCV", "sklearn.feature_extraction.text.TfidfVectorizer", "sklearn.naive_bayes.GaussianNB", "numpy.logspace", "sklearn.naive_bayes.MultinomialNB", "sklearn.datasets.load_iris", "sklearn.model_selection.train_test_split", "sklearn.linear_model.Ridge", "sklearn.preprocessing.StandardScaler", "sklearn.linear_model.LassoCV", "numpy.array", "sklearn.linear_model.RidgeClassifier", "sklearn.tree.DecisionTreeRegressor", "sklearn.linear_model.LogisticRegression", "sklearn.datasets.make_moons", "matplotlib.pyplot.subplots", "sklearn.datasets.load_digits", "sklearn.preprocessing.OrdinalEncoder", "sklearn.cluster.MiniBatchKMeans" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JintuZheng/zisan
[ "84b30d1ee91754d4351841a2077c78146028adfc" ]
[ "zisan/Seg/Interface.py" ]
[ "#################################################################\n### @author:郑晋图 JintuZheng\n### Email: [email protected]\n### Remarks: Please respect my labor achievements, and contact me to modify the source code\n### Date:2020-01-23\n################################################################\n\nimport numpy as np\nimport os\nimport cv2\nfrom .model import model\nfrom .utils import load_frames,overlay_bin,overlay_fade\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nnp.set_printoptions(threshold=np.inf)\n\nclass ImgSeg(object):\n def __init__(self,weight_path):\n self.Inetmodel = model(weight_path) #load the model init need more time\n\n def Preview(self,img,mask):\n img[:,:,(0,1,2)]=img[:,:,(2,1,0)]#通道转换\n cv2.imshow(\"Preview_Jintu\",img)\n cv2.imshow(\"Preview_mask_Jintu\",mask)\n cv2.waitKey(0)\n \n def rawProcess(self,frame_list,object_mark,is_showPreview): \n frames = np.stack(frame_list, axis=0)\n self.Inetmodel.loadframes(frames) # reset all frames\n _, height, width = frames.shape[:3]\n self.Inetmodel.Run_interaction(object_mark)\n current_mask = np.zeros((1, height, width), dtype=np.uint8)\n current_mask=self.Inetmodel.Get_mask_index(0)\n result=overlay_bin(frames[0],current_mask)\n if is_showPreview :\n self.Preview(overlay_fade(frames[0],current_mask),result)\n return result,overlay_fade(frames[0],current_mask)\n\n def ImgSeg_SingleObj_FromFile(self,img_path,object_mark,is_showPreview=False):\n frame_list=[]\n frame_list.append(np.array(Image.open(img_path).convert('RGB'), dtype=np.uint8))\n return self.rawProcess(frame_list,object_mark,is_showPreview)\n\n def ImgSeg_SingleObj(self,img_RGB,object_mark,is_showPreview=False): #Image.open(img_path).convert('RGB')\n frame_list=[]\n frame_list.append(np.array(img_RGB, dtype=np.uint8))\n return self.rawProcess(frame_list,object_mark,is_showPreview)\n \n\nclass markTools(object):\n def __init__(self,height,width):\n self.canvas=np.zeros((height,width), np.uint8) #create a new canvas\n self.height=height\n self.width=width\n self.thickness=7\n self.lineType=4\n self.color=255\n self.pen=[[5,1],[6,2],[7,3],[8,4],[9,5],[10,5],[15,5]] # [thickness point_size]\n\n def pointStrength(self,level=4): #max level is 7\n thickness,point_size=self.pen[level-1]\n return thickness,point_size\n \n def checkColor(self,flag):\n if flag==False:\n self.color=100\n else: \n self.color=255\n\n def curveDraw(self,points=[(0,0)],thickness=10,is_Pos=True):\n self.checkColor(is_Pos)\n if len(points)<2:\n return\n ptStart=points[0]\n ptEnd=points[1]\n for index in range(1,len(points)):\n ptEnd=points[index]\n self.canvas=cv2.line(self.canvas, ptStart, ptEnd, self.color, thickness, self.lineType)\n ptStart=ptEnd\n\n def pointDraw(self,points=[(0,0)],point_sizeLevel=4,is_Pos=True):\n self.checkColor(is_Pos)\n tk,psz=self.pointStrength(point_sizeLevel)\n for cur_point in points:\n cv2.circle(self.canvas,cur_point,psz,self.color,tk)\n \n def getMark_result(self,is_showPreview=False):\n if is_showPreview:\n cv2.imshow('markPreview',self.canvas)\n cv2.waitKey(0)\n #处理顺序的逻辑不能错\n self.canvas[self.canvas==255]=1 #Pos\n self.canvas[self.canvas==0]=-1 #background\n self.canvas[self.canvas==100]=0 # Na\n return self.canvas\n def getMark_result_from_gray(img_gray2):\n img_gray=img_gray2.copy()\n img_gray[img_gray==255]=1 #Pos\n img_gray[img_gray==0]=-1 #background\n img_gray[img_gray==100]=0 # Na\n return img_gray\n\n def mergeMask_fade_from_gray(image,mask_gray):\n from scipy.ndimage.morphology import binary_erosion, binary_dilation\n mask_gray[np.where(mask_gray==255)]=1\n mask=mask_gray\n im_overlay = image.copy()\n # Overlay color on binary mask\n binary_mask = mask == 1\n not_mask = mask != 1\n # Compose image\n im_overlay[not_mask] = 0.4 * im_overlay[not_mask]\n countours = binary_dilation(binary_mask) ^ binary_mask\n im_overlay[countours,0] = 0\n im_overlay[countours,1] = 255\n im_overlay[countours,2] = 255\n return im_overlay.astype(image.dtype)\n\n" ]
[ [ "scipy.ndimage.morphology.binary_dilation", "numpy.set_printoptions", "numpy.stack", "numpy.array", "numpy.zeros", "numpy.where" ] ]
[ { "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": [] } ]
aflaxman/milk
[ "252806fd081dc1b3c7fe34b14f9e7a4b646e0b49", "252806fd081dc1b3c7fe34b14f9e7a4b646e0b49", "252806fd081dc1b3c7fe34b14f9e7a4b646e0b49" ]
[ "milk/tests/test_tree.py", "milk/measures/curves.py", "milk/supervised/lasso.py" ]
[ "import milk.supervised.tree\nimport milk.supervised._tree\nfrom milk.supervised._tree import set_entropy\nfrom milk.supervised.tree import information_gain, stump_learner\nimport numpy as np\n\ndef test_tree():\n from milksets import wine\n features, labels = wine.load()\n selected = (labels < 2)\n features = features[selected]\n labels = labels[selected]\n C = milk.supervised.tree.tree_classifier()\n model = C.train(features,labels)\n assert (np.array([model.apply(f) for f in features]) == labels).mean() > .5\n\n\ndef test_split_subsample():\n import random\n from milksets import wine\n features, labels = wine.load()\n labels = labels.astype(np.int)\n\n seen = set()\n for i in xrange(20):\n random.seed(2)\n i,s = milk.supervised.tree._split(features[::10], labels[::10], None, milk.supervised.tree.information_gain, 2, random)\n seen.add(i)\n assert len(seen) <= 2\n\n\ndef test_set_entropy():\n labels = np.arange(101)%3\n counts = np.zeros(3)\n entropy = milk.supervised._tree.set_entropy(labels, counts)\n slow_counts = np.array([(labels == i).sum() for i in xrange(3)])\n assert np.all(counts == slow_counts)\n px = slow_counts.astype(float)/ slow_counts.sum()\n slow_entropy = - np.sum(px * np.log(px))\n assert np.abs(slow_entropy - entropy) < 1.e-8\n\n\ndef slow_information_gain(labels0, labels1):\n H = 0.\n N = len(labels0) + len(labels1)\n nlabels = 1+max(labels0.max(), labels1.max())\n counts = np.empty(nlabels, np.double)\n for arg in (labels0, labels1):\n H -= len(arg)/float(N) * set_entropy(arg, counts)\n return H\n\ndef test_information_gain():\n np.random.seed(22)\n for i in xrange(8):\n labels0 = (np.random.randn(20) > .2).astype(int)\n labels1 = (np.random.randn(33) > .8).astype(int)\n fast = information_gain(labels0, labels1)\n slow = slow_information_gain(labels0, labels1)\n assert np.abs(fast - slow) < 1.e-8\n\n\ndef test_information_gain_small():\n labels1 = np.array([0])\n labels0 = np.array([0, 1])\n assert information_gain(labels0, labels1) < 0.\n\n\ndef test_z1_loss():\n from milk.supervised.tree import z1_loss\n L0 = np.zeros(10)\n L1 = np.ones(10)\n L1[3] = 0\n W0 = np.ones(10)\n W1 = np.ones(10)\n assert z1_loss(L0, L1) == z1_loss(L0, L1, W0, W1)\n assert z1_loss(L0, L1) != z1_loss(L0, L1, W0, .8*W1)\n assert z1_loss(L0, L1) > 0\n\n\ndef test_stump_learner():\n learner = stump_learner()\n np.random.seed(111)\n for i in xrange(8):\n features = np.random.random_sample((40,2))\n features[:20,0] += .5\n labels = np.repeat((0,1),20)\n model = learner.train(features, labels, normalisedlabels=True)\n assert not model.apply([0.01,.5])\n assert model.apply(np.random.random_sample(2)+.8)\n assert model.idx == 0\n\n", "# -*- coding: utf-8 -*-\n# Copyright (C) 2011, Luis Pedro Coelho <[email protected]>\n# vim: set ts=4 sts=4 sw=4 expandtab smartindent:\n# License: MIT. See COPYING.MIT file in the milk distribution\n\nfrom __future__ import division\nimport numpy as np\n\ndef precision_recall(values, labels, mode='all', nr_steps=100):\n '''\n precision, recall = precision_recall(values, labels, mode='all', nr_steps=100)\n\n Compute a precision-recall curve.\n\n For a given threshold ``T``, consider that the positions where ``values >=\n T`` are classified as True. Precision is defined as ``TP/(TP+FP)``, while\n recall is defined as ``TP/(TP+FN)``.\n\n Parameters\n ----------\n values : sequence of numbers\n labels : boolean sequence\n mode : str, optional\n Which thresholds to consider. Either 'all' (i.e., use all values of\n `values` as possible thresholds), or 'step' (using `nr_steps`\n equidistant points from ``min(values)`` to ``max(values)``)\n nr_steps : integer, optional\n How many steps to use. Only meaningfule if ``mode == 'steps'``\n\n Returns\n -------\n precision : a sequence of floats\n recall : a sequence of floats\n\n Actually, ``2 x P`` array is returned.\n '''\n\n values = np.asanyarray(values)\n labels = np.asanyarray(labels)\n if len(values) != len(labels):\n raise ValueError('milk.measures.precision_recall: `values` must be of same length as `labels`')\n if mode == 'all':\n points = list(set(values))\n points.sort()\n elif mode == 'steps':\n points = np.linspace(values.min(), values.max(), nr_steps)\n else:\n raise ValueError('milk.measures.precision_recall: cannot handle mode: `%s`' % mode)\n true_pos = float(np.sum(labels))\n precision_recall = np.empty((len(points),2), np.float)\n\n for i,p in enumerate(points):\n selected = (values >= p)\n selected = labels[selected]\n precision_recall[i] = (np.mean(selected), np.sum(selected)/true_pos)\n return precision_recall.T\n\n", "# -*- coding: utf-8 -*- \nimport numpy as np\nimport _lasso\nfrom .base import supervised_model\nfrom milk.unsupervised import center\n\ndef lasso(X, Y, B=None, lam=1., max_iter=None, tol=None):\n '''\n B = lasso(X, Y, B={np.zeros()}, lam=1. max_iter={1024}, tol={1e-5})\n\n Solve LASSO Optimisation\n\n B* = arg min_B ½/n || Y - BX ||₂² + λ||B||₁\n\n where $n$ is the number of samples.\n\n Milk uses coordinate descent, looping through the coordinates in order\n (with an active set strategy to update only non-zero βs, if possible). The\n problem is convex and the solution is guaranteed to be optimal (within\n floating point accuracy).\n\n Parameters\n ----------\n X : ndarray\n Design matrix\n Y : ndarray\n Matrix of outputs\n B : ndarray, optional\n Starting values for approximation. This can be used for a warm start if\n you have an estimate of where the solution should be. If used, the\n solution might be written in-place (if the array has the right format).\n lam : float, optional\n λ (default: 1.0)\n max_iter : int, optional\n Maximum nr of iterations (default: 1024)\n tol : float, optional\n Tolerance. Whenever a parameter is to be updated by a value smaller\n than ``tolerance``, that is considered a null update. Be careful that\n if the value is too small, performance will degrade horribly.\n (default: 1e-5)\n\n Returns\n -------\n B : ndarray\n '''\n X = np.ascontiguousarray(X, dtype=np.float32)\n Y = np.ascontiguousarray(Y, dtype=np.float32)\n if B is None:\n B = np.zeros((Y.shape[0],X.shape[0]), np.float32)\n else:\n B = np.ascontiguousarray(B, dtype=np.float32)\n if max_iter is None:\n max_iter = 1024\n if tol is None:\n tol = 1e-5\n if X.shape[0] != B.shape[1] or \\\n Y.shape[0] != B.shape[0] or \\\n X.shape[1] != Y.shape[1]:\n raise ValueError('milk.supervised.lasso: Dimensions do not match')\n if np.any(np.isnan(X)) or np.any(np.isnan(B)):\n raise ValueError('milk.supervised.lasso: NaNs are only supported in the ``Y`` matrix')\n W = np.ascontiguousarray(~np.isnan(Y), dtype=np.float32)\n Y = np.nan_to_num(Y)\n n = Y.size\n _lasso.lasso(X, Y, W, B, max_iter, float(2*n*lam), float(tol))\n return B\n\ndef lasso_walk(X, Y, B=None, nr_steps=None, start=None, step=None, tol=None, return_lams=False):\n '''\n Bs = lasso_walk(X, Y, B={np.zeros()}, nr_steps={64}, start={automatically inferred}, step={.9}, tol=None, return_lams=False)\n Bs,lams = lasso_walk(X, Y, B={np.zeros()}, nr_steps={64}, start={automatically inferred}, step={.9}, tol=None, return_lams=True)\n\n Repeatedly solve LASSO Optimisation\n\n B* = arg min_B ½/n || Y - BX ||₂² + λ||B||₁\n\n for different values of λ.\n\n Parameters\n ----------\n X : ndarray\n Design matrix\n Y : ndarray\n Matrix of outputs\n B : ndarray, optional\n Starting values for approximation. This can be used for a warm start if\n you have an estimate of where the solution should be.\n start : float, optional\n first λ to use (default is ``np.abs(Y).max()``)\n nr_steps : int, optional\n How many steps in the path (default is 64)\n step : float, optional\n Multiplicative step to take (default is 0.9)\n tol : float, optional\n This is the tolerance parameter. It is passed to the lasso function\n unmodified.\n return_lams : bool, optional\n Whether to return the values of λ used (default: False)\n\n Returns\n -------\n Bs : ndarray\n '''\n if nr_steps is None:\n nr_steps = 64\n if step is None:\n step = .9\n if start is None:\n n = Y.size\n start = 0.5/n*np.nanmax(np.abs(Y))*np.abs(X).max()\n\n\n lam = start\n lams = []\n Bs = []\n for i in xrange(nr_steps):\n # The central idea is that each iteration is already \"warm\" and this\n # should be faster than starting from zero each time\n B = lasso(X, Y, B, lam=lam, tol=tol)\n lams.append(lam)\n Bs.append(B.copy())\n lam *= step\n if return_lams:\n return np.array(Bs), np.array(lams)\n return np.array(Bs)\n\ndef _dict_subset(mapping, keys):\n return dict(\n [(k,mapping[k]) for k in keys])\n\nclass lasso_model(supervised_model):\n def __init__(self, betas, mean):\n self.betas = betas\n self.mean = mean\n\n def retrain(self, features, labels, lam, **kwargs):\n features, mean = center(features) \n betas = lasso(features, labels, self.betas.copy(), lam=lam, **_dict_subset(kwargs, ['tol', 'max_iter']))\n return lasso_model(betas, mean)\n \n def apply(self, features):\n return np.dot(self.betas, features) + self.mean\n\n\nclass lasso_learner(object):\n def __init__(self, lam=1.0):\n self.lam = lam\n\n def train(self, features, labels, betas=None, **kwargs):\n labels, mean = center(labels, axis=1) \n betas = lasso(features, labels, betas, lam=self.lam)\n return lasso_model(betas, mean)\n\ndef lasso_model_walk(X, Y, B=None, nr_steps=64, start=None, step=.9, tol=None, return_lams=False):\n Y, mean = center(Y, axis=1)\n Bs,lams = lasso_walk(X,Y, B, nr_steps, start, step, tol, return_lams=True)\n models = [lasso_model(B, mean) for B in Bs]\n if return_lams:\n return models, lams\n return models\n\n" ]
[ [ "numpy.log", "numpy.abs", "numpy.random.seed", "numpy.arange", "numpy.random.random_sample", "numpy.ones", "numpy.all", "numpy.random.randn", "numpy.repeat", "numpy.array", "numpy.zeros", "numpy.empty" ], [ "numpy.asanyarray", "numpy.mean", "numpy.sum" ], [ "numpy.dot", "numpy.abs", "numpy.ascontiguousarray", "numpy.isnan", "numpy.nan_to_num", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
matinraayai/pytorch_connectomics
[ "b11a2f7e71a8d1442fb05f7a6edfaaaa7b0d9205" ]
[ "connectomics/model/utils/criterion.py" ]
[ "import numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom ..loss import *\n\nclass Criterion(object):\n def __init__(self, device=0, target_opt=['1'], loss_opt=[['WeightedBCE']], loss_weight=[[1.]], regu_opt=[], regu_weight=[]):\n self.device = device\n self.target_opt = target_opt\n self.loss_opt = loss_opt\n self.loss_weight = loss_weight\n self.num_target = len(target_opt)\n self.num_regu = len(regu_opt)\n\n self.loss = self.get_loss()\n self.loss_w = loss_weight\n self.regu = self.get_regu(regu_opt)\n self.regu_w = regu_weight\n\n def get_regu(self, regu_opt=[]):\n regu = None\n if len(regu_opt)>0:\n regu = [None]*len(regu_opt)\n for i in range(len(regu_opt)):\n if regu_opt[i] == 0:\n regu[i] = nn.L1Loss()\n elif regu_opt[i] == 'BinaryReg':\n regu[i] = BinaryReg()\n return regu\n\n def get_loss(self):\n out = [None]*self.num_target\n for i in range(self.num_target):\n out[i] = [None]*len(self.loss_opt[i])\n for j,lopt in enumerate(self.loss_opt[i]):\n if lopt == 'WeightedMSE':\n out[i][j] = WeightedMSE()\n elif lopt == 'WeightedBCE':\n out[i][j] = WeightedBCE()\n elif lopt == 'JaccardLoss':\n out[i][j] = JaccardLoss()\n elif lopt == 'DiceLoss':\n out[i][j] = DiceLoss()\n elif lopt == 'WeightedCE':\n out[i][j] = WeightedCE()\n else:\n print('Unknown loss option {}'.format(lopt))\n return out\n\n def to_torch(self, data):\n return torch.from_numpy(data).to(self.device)\n\n def eval(self, pred, target, weight):\n # target, weight: numpy\n # pred: torch\n # compute loss\n loss = 0\n cid = 0 # channel index for prediction\n for i in range(self.num_target):\n # for each target\n numC = self.get_num_channel(i, target)\n target_t = self.to_torch(target[i])\n for j in range(len(self.loss[i])):\n if weight[i][j].shape[-1] == 1: # placeholder for no weight\n loss += self.loss_weight[i][j]*self.loss_w[i][j]*self.loss[i][j](pred[:,cid:cid+numC], target_t)\n else:\n loss += self.loss_weight[i][j]*self.loss_w[i][j]*self.loss[i][j](pred[:,cid:cid+numC], target_t, self.to_torch(weight[i][j]))\n cid += numC\n for i in range(self.num_regu):\n loss += self.regu[i](pred)*self.regu_w[i]\n return loss\n\n def get_num_channel(self, i, target):\n topt = self.target_opt[i]\n if topt[0] == '9': # generic segmantic segmentation\n numC = topt.split('-')[1]\n numC = int(numC)\n else:\n numC = target[i].shape[1]\n return numC\n" ]
[ [ "torch.from_numpy", "torch.nn.L1Loss" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cminusQAQ/graph4nlp
[ "d980e897131f1b9d3766750c06316d94749904fa", "d980e897131f1b9d3766750c06316d94749904fa", "d980e897131f1b9d3766750c06316d94749904fa", "d980e897131f1b9d3766750c06316d94749904fa" ]
[ "graph4nlp/pytorch/datasets/cnn.py", "graph4nlp/pytorch/modules/graph_construction/utils.py", "graph4nlp/pytorch/modules/prediction/classification/graph_classification/max_pooling.py", "examples/pytorch/name_entity_recognition/main.py" ]
[ "import json\nimport torch\nfrom nltk.tokenize import word_tokenize\n\nfrom graph4nlp.pytorch.data.dataset import Text2TextDataItem, Text2TextDataset\nfrom graph4nlp.pytorch.modules.utils.padding_utils import pad_2d_vals, pad_2d_vals_no_size\n\n\nclass CNNDataset(Text2TextDataset):\n def __init__(\n self,\n root_dir,\n topology_subdir,\n graph_name,\n static_or_dynamic=\"static\",\n tokenizer=word_tokenize,\n lower_case=True,\n pretrained_word_emb_name=\"840B\",\n pretrained_word_emb_url=None,\n target_pretrained_word_emb_name=None,\n target_pretrained_word_emb_url=None,\n pretrained_word_emb_cache_dir=\".vector_cache/\",\n use_val_for_vocab=False,\n seed=1234,\n thread_number=4,\n port=9000,\n timeout=15000,\n edge_strategy=None,\n share_vocab=True,\n word_emb_size=300,\n dynamic_init_graph_name=None,\n dynamic_init_topology_builder=None,\n dynamic_init_topology_aux_args=None,\n for_inference=False,\n reused_vocab_model=None,\n **kwargs\n ):\n super(CNNDataset, self).__init__(\n root_dir=root_dir,\n topology_subdir=topology_subdir,\n graph_name=graph_name,\n static_or_dynamic=static_or_dynamic,\n tokenizer=tokenizer,\n lower_case=lower_case,\n pretrained_word_emb_name=pretrained_word_emb_name,\n pretrained_word_emb_url=pretrained_word_emb_url,\n target_pretrained_word_emb_name=target_pretrained_word_emb_name,\n target_pretrained_word_emb_url=target_pretrained_word_emb_url,\n pretrained_word_emb_cache_dir=pretrained_word_emb_cache_dir,\n use_val_for_vocab=use_val_for_vocab,\n seed=seed,\n thread_number=thread_number,\n port=port,\n timeout=timeout,\n edge_strategy=edge_strategy,\n share_vocab=share_vocab,\n word_emb_size=word_emb_size,\n dynamic_init_graph_name=dynamic_init_graph_name,\n dynamic_init_topology_builder=dynamic_init_topology_builder,\n dynamic_init_topology_aux_args=dynamic_init_topology_aux_args,\n for_inference=for_inference,\n reused_vocab_model=reused_vocab_model,\n **kwargs\n )\n\n @property\n def raw_file_names(self):\n \"\"\"\n 3 reserved keys: 'train', 'val' (optional), 'test'.\n Represent the split of dataset.\n \"\"\"\n return {\"train\": \"train_3w.json\", \"val\": \"val.json\", \"test\": \"test.json\"}\n\n @property\n def processed_file_names(self):\n \"\"\"At least 2 reserved keys should be fiiled: 'vocab' and 'data'.\"\"\"\n return {\"vocab\": \"vocab.pt\", \"data\": \"data.pt\"}\n\n def download(self):\n return\n\n def parse_file(self, file_path):\n \"\"\"\n Read and parse the file specified by `file_path`. The file format is\n specified by each individual task-specific base class. Returns all\n the indices of data items in this file w.r.t. the whole dataset.\n For Text2TextDataset, the format of the input file should contain\n lines of input, each line representing one record of data. The input\n and output is separated by a tab(\\t).\n\n Parameters\n ----------\n file_path: str\n The path of the input file.\n Returns\n -------\n list\n The indices of data items in the file w.r.t. the whole dataset.\n \"\"\"\n data = []\n with open(file_path, \"r\") as f:\n examples = json.load(f)\n for example_dict in examples:\n input = \" \".join(\" \".join(example_dict[\"article\"]).split()[:400]).lower()\n output = \" \".join(\n \" \".join(\n [\"<t> \" + sent[0] + \" . </t>\" for sent in example_dict[\"highlight\"]]\n ).split()[:99]\n ).lower()\n if input == \"\" or output == \"\":\n continue\n data_item = Text2TextDataItem(\n input_text=input,\n output_text=output,\n tokenizer=self.tokenizer,\n share_vocab=self.share_vocab,\n )\n data.append(data_item)\n return data\n\n @staticmethod\n def collate_fn(data_list: [Text2TextDataItem]):\n graph_data = [item.graph for item in data_list]\n max_node_len = 0\n for graph_item in graph_data:\n max_node_len = max(max_node_len, graph_item.node_features[\"token_id\"].size()[1])\n for graph_item in graph_data:\n token_id_numpy = graph_item.node_features[\"token_id\"].numpy()\n token_id_pad = pad_2d_vals(token_id_numpy, token_id_numpy.shape[0], max_node_len)\n graph_item.node_features[\"token_id\"] = torch.from_numpy(token_id_pad).long()\n\n from graph4nlp.pytorch.data.data import to_batch\n\n big_graph = to_batch(graph_data)\n\n output_numpy = [item.output_np for item in data_list]\n output_str = [item.output_text.lower().strip() for item in data_list]\n output_pad = pad_2d_vals_no_size(output_numpy)\n tgt_seq = torch.from_numpy(output_pad).long()\n\n return {\"graph_data\": big_graph, \"tgt_seq\": tgt_seq, \"output_str\": output_str}\n", "import torch\n\nCORENLP_TIMEOUT_SIGNATURE = \"CoreNLP request timed out. Your document may be too long.\"\n\n\ndef convert_adj_to_graph(graph, adj, reverse_adj, mask_off_val):\n slides = (adj != mask_off_val).nonzero(as_tuple=False)\n\n batch_nodes_tensor = torch.Tensor([0] + graph._batch_num_nodes).to(slides.device)\n batch_prefix = batch_nodes_tensor.view(-1, 1).expand(-1, batch_nodes_tensor.shape[0])\n\n batch_prefix = batch_prefix.triu().long().sum(0)\n\n src = slides[:, 1] + batch_prefix.index_select(dim=0, index=slides[:, 0])\n tgt = slides[:, 2] + batch_prefix.index_select(dim=0, index=slides[:, 0])\n\n graph_data = graph\n graph_data.remove_all_edges() # remove all existing edges\n graph_data.add_edges(src.detach().cpu().numpy().tolist(), tgt.detach().cpu().numpy().tolist())\n\n value = adj[slides[:, 0], slides[:, 1], slides[:, 2]]\n reverse_value = reverse_adj[slides[:, 0], slides[:, 1], slides[:, 2]]\n graph_data.edge_features[\"edge_weight\"] = value\n graph_data.edge_features[\"reverse_edge_weight\"] = reverse_value\n\n return graph_data\n", "import torch\nimport torch.nn as nn\n\nfrom .....data.data import from_batch\nfrom ..base import PoolingBase\n\n\nclass MaxPooling(PoolingBase):\n r\"\"\"Apply max pooling over the nodes in the graph.\n\n .. math::\n r^{(i)} = \\max_{k=1}^{N_i}\\left( x^{(i)}_k \\right)\n \"\"\"\n\n def __init__(self, dim=None, use_linear_proj=False):\n super(MaxPooling, self).__init__()\n if use_linear_proj:\n assert dim is not None, \"dim should be specified when use_linear_proj is set to True\"\n self.linear = nn.Linear(dim, dim, bias=False)\n else:\n self.linear = None\n\n def forward(self, graph, feat):\n r\"\"\"Compute max pooling.\n\n Parameters\n ----------\n graph : GraphData\n The graph data.\n feat : str\n The feature field name.\n\n Returns\n -------\n torch.Tensor\n The output feature.\n \"\"\"\n graph_list = from_batch(graph)\n output_feat = []\n for g in graph_list:\n feat_tensor = g.node_features[feat]\n if self.linear is not None:\n feat_tensor = self.linear(feat_tensor)\n\n output_feat.append(torch.max(feat_tensor, dim=0)[0])\n\n output_feat = torch.stack(output_feat, 0)\n\n return output_feat\n", "import argparse\nimport os\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.multiprocessing\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nfrom graph4nlp.pytorch.data.data import from_batch\nfrom graph4nlp.pytorch.modules.evaluation.accuracy import Accuracy\nfrom graph4nlp.pytorch.modules.graph_construction import NodeEmbeddingBasedRefinedGraphConstruction\nfrom graph4nlp.pytorch.modules.graph_construction.node_embedding_based_graph_construction import (\n NodeEmbeddingBasedGraphConstruction,\n)\nfrom graph4nlp.pytorch.modules.utils.generic_utils import to_cuda\n\nfrom conll import ConllDataset\nfrom conlleval import evaluate\nfrom dependency_graph_construction_without_tokenize import (\n DependencyBasedGraphConstruction_without_tokenizer,\n)\nfrom line_graph_construction import LineBasedGraphConstruction\nfrom model import Word2tag\n\ntorch.multiprocessing.set_sharing_strategy(\"file_system\")\ncudnn.benchmark = False\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\n# from torchcrf import CRF\n\n\ndef all_to_cuda(data, device=None):\n if isinstance(data, torch.Tensor):\n data = to_cuda(data, device)\n elif isinstance(data, (list, dict)):\n keys = range(len(data)) if isinstance(data, list) else data.keys()\n for k in keys:\n if isinstance(data[k], torch.Tensor):\n data[k] = to_cuda(data[k], device)\n\n return data\n\n\ndef conll_score(preds, tgts, tag_types):\n # preds is a list and each elements is the list of tags of a sentence\n # tgts is a lits and each elements is the tensor of tags of a text\n pred_list = []\n tgt_list = []\n\n for idx in range(len(preds)):\n pred_list.append(preds[idx].cpu().clone().numpy())\n for idx in range(len(tgts)):\n tgt_list.extend(tgts[idx].cpu().clone().numpy().tolist())\n pred_tags = [tag_types[int(pred)] for pred in pred_list]\n tgt_tags = [tag_types[int(tgt)] for tgt in tgt_list]\n prec, rec, f1 = evaluate(tgt_tags, pred_tags, verbose=False)\n return prec, rec, f1\n\n\ndef write_file(tokens_collect, pred_collect, tag_collect, file_name, tag_types):\n num_sent = len(tokens_collect)\n f = open(file_name, \"w\")\n for idx in range(num_sent):\n sent_token = tokens_collect[idx]\n sent_pred = pred_collect[idx].cpu().clone().numpy()\n sent_tag = tag_collect[idx].cpu().clone().numpy()\n # f.write('%s\\n' % ('-X- SENTENCE START'))\n for word_idx in range(len(sent_token)):\n w = sent_token[word_idx]\n tgt = tag_types[sent_tag[word_idx].item()]\n pred = tag_types[sent_pred[word_idx].item()]\n f.write(\"%d %s %s %s\\n\" % (word_idx + 1, w, tgt, pred))\n\n f.close()\n\n\ndef get_tokens(g_list):\n tokens = []\n for g in g_list:\n sent_token = []\n dic = g.node_attributes\n for node in dic:\n sent_token.append(node[\"token\"])\n if \"ROOT\" in sent_token:\n sent_token.remove(\"ROOT\")\n tokens.append(sent_token)\n return tokens\n\n\nclass Conll:\n def __init__(self):\n super(Conll, self).__init__()\n self.tag_types = [\"I-PER\", \"O\", \"B-ORG\", \"B-LOC\", \"I-ORG\", \"I-MISC\", \"I-LOC\", \"B-MISC\"]\n if args.gpu > -1:\n self.device = torch.device(\"cuda\")\n else:\n self.device = torch.device(\"cpu\")\n self.checkpoint_path = \"./checkpoints/\"\n if not os.path.exists(self.checkpoint_path):\n os.mkdir(self.checkpoint_path)\n self._build_dataloader()\n print(\"finish dataloading\")\n self._build_model()\n print(\"finish building model\")\n self._build_optimizer()\n self._build_evaluation()\n\n def _build_dataloader(self):\n print(\"starting build the dataset\")\n\n if args.graph_name == \"line_graph\":\n dataset = ConllDataset(\n root_dir=\"examples/pytorch/name_entity_recognition/conll\",\n topology_builder=LineBasedGraphConstruction,\n graph_name=args.graph_name,\n static_or_dynamic=args.static_or_dynamic,\n pretrained_word_emb_cache_dir=args.pre_word_emb_file,\n topology_subdir=\"LineGraph\",\n tag_types=self.tag_types,\n )\n elif args.graph_name == \"dependency_graph\":\n dataset = ConllDataset(\n root_dir=\"examples/pytorch/name_entity_recognition/conll\",\n topology_builder=DependencyBasedGraphConstruction_without_tokenizer,\n graph_name=args.graph_name,\n static_or_dynamic=\"static\",\n pretrained_word_emb_cache_dir=args.pre_word_emb_file,\n topology_subdir=\"DependencyGraph\",\n tag_types=self.tag_types,\n )\n elif args.graph_name == \"node_emb\":\n dataset = ConllDataset(\n root_dir=\"examples/pytorch/name_entity_recognition/conll\",\n topology_builder=NodeEmbeddingBasedGraphConstruction,\n graph_name=args.graph_name,\n static_or_dynamic=\"static\",\n pretrained_word_emb_cache_dir=args.pre_word_emb_file,\n topology_subdir=\"DynamicGraph_node_emb\",\n tag_types=self.tag_types,\n merge_strategy=None,\n )\n elif args.graph_type == \"node_emb_refined\":\n if args.init_graph_name == \"line\":\n dynamic_init_topology_builder = LineBasedGraphConstruction\n elif args.init_graph_name == \"dependency\":\n dynamic_init_topology_builder = DependencyBasedGraphConstruction_without_tokenizer\n else:\n # init_topology_builder\n raise RuntimeError(\"Define your own init_topology_builder\")\n dataset = ConllDataset(\n root_dir=\"examples/pytorch/name_entity_recognition/conll\",\n topology_builder=NodeEmbeddingBasedRefinedGraphConstruction,\n graph_name=args.graph_name,\n static_or_dynamic=\"dynamic\",\n pretrained_word_emb_cache_dir=args.pre_word_emb_file,\n topology_subdir=\"DynamicGraph_node_emb_refined\",\n tag_types=self.tag_types,\n dynamic_init_topology_builder=dynamic_init_topology_builder,\n dynamic_init_topology_aux_args={\"dummy_param\": 0},\n )\n\n print(len(dataset.train))\n print(\"strating loading the training data\")\n self.train_dataloader = DataLoader(\n dataset.train,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=1,\n collate_fn=dataset.collate_fn,\n )\n print(\"strating loading the validating data\")\n self.val_dataloader = DataLoader(\n dataset.val, batch_size=100, shuffle=True, num_workers=1, collate_fn=dataset.collate_fn\n )\n print(\"strating loading the testing data\")\n self.test_dataloader = DataLoader(\n dataset.test, batch_size=100, shuffle=True, num_workers=1, collate_fn=dataset.collate_fn\n )\n print(\"strating loading the vocab\")\n self.vocab = dataset.vocab_model\n\n def _build_model(self):\n self.model = Word2tag(self.vocab, args, device=self.device).to(self.device)\n\n def _build_optimizer(self):\n parameters = [p for p in self.model.parameters() if p.requires_grad]\n self.optimizer = optim.Adam(parameters, lr=args.lr, weight_decay=args.weight_decay)\n\n def _build_evaluation(self):\n self.metrics = Accuracy([\"F1\", \"precision\", \"recall\"])\n\n def train(self):\n max_score = -1\n max_idx = 0\n for epoch in range(args.epochs):\n self.model.train()\n print(\"Epoch: {}\".format(epoch))\n pred_collect = []\n gt_collect = []\n for data in self.train_dataloader:\n graph, tgt = data[\"graph_data\"], data[\"tgt_tag\"]\n tgt_l = [tgt_.to(self.device) for tgt_ in tgt]\n graph = graph.to(self.device)\n pred_tags, loss = self.model(graph, tgt_l, require_loss=True)\n pred_collect.extend(pred_tags) # pred: list of batch_sentence pred tensor\n gt_collect.extend(tgt) # tgt:list of sentence token tensor\n # num_tokens=len(torch.cat(pred_tags).view(-1))\n print(\"Epoch: {}\".format(epoch) + \" loss:\" + str(loss.cpu().item()))\n self.optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1)\n self.optimizer.step()\n\n if epoch % 1 == 0:\n score = self.evaluate(epoch)\n if score > max_score:\n self.model.save_checkpoint(self.checkpoint_path, \"best.pt\")\n max_idx = epoch\n max_score = max(max_score, score)\n return max_score, max_idx\n\n def evaluate(self, epoch):\n self.model.eval()\n pred_collect = []\n gt_collect = []\n tokens_collect = []\n with torch.no_grad():\n for data in self.val_dataloader:\n graph, tgt = data[\"graph_data\"], data[\"tgt_tag\"]\n graph = graph.to(self.device)\n tgt_l = [tgt_.to(self.device) for tgt_ in tgt]\n pred, loss = self.model(graph, tgt_l, require_loss=True)\n pred_collect.extend(pred) # pred: list of batch_sentence pred tensor\n gt_collect.extend(tgt) # tgt:list of sentence token tensor\n tokens_collect.extend(get_tokens(from_batch(graph)))\n\n prec, rec, f1 = conll_score(pred_collect, gt_collect, self.tag_types)\n print(\"Testing results: precision is %5.2f, rec is %5.2f, f1 is %5.2f\" % (prec, rec, f1))\n print(\"Epoch: {}\".format(epoch) + \" loss:\" + str(loss.cpu().item()))\n\n return f1\n\n @torch.no_grad()\n def test(self):\n self.model.eval()\n pred_collect = []\n tokens_collect = []\n tgt_collect = []\n with torch.no_grad():\n for data in self.test_dataloader:\n graph, tgt = data[\"graph_data\"], data[\"tgt_tag\"]\n graph = graph.to(self.device)\n tgt_l = [tgt_.to(self.device) for tgt_ in tgt]\n pred, loss = self.model(graph, tgt_l, require_loss=True)\n # pred = logits2tag(g)\n pred_collect.extend(pred)\n tgt_collect.extend(tgt)\n tokens_collect.extend(get_tokens(from_batch(graph)))\n prec, rec, f1 = conll_score(pred_collect, tgt_collect, self.tag_types)\n print(\"Testing results: precision is %5.2f, rec is %5.2f, f1 is %5.2f\" % (prec, rec, f1))\n return f1\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"NER\")\n parser.add_argument(\"--gpu\", type=int, default=-1, help=\"which GPU to use.\")\n parser.add_argument(\"--epochs\", type=int, default=5, help=\"number of training epochs\")\n parser.add_argument(\n \"--direction_option\",\n type=str,\n default=\"bi_fuse\",\n help=\"direction type (`undirected`, `bi_fuse`, `bi_sep`)\",\n )\n parser.add_argument(\n \"--lstm_num_layers\", type=int, default=1, help=\"number of hidden layers in lstm\"\n )\n parser.add_argument(\n \"--gnn_num_layers\", type=int, default=1, help=\"number of hidden layers in gnn\"\n )\n parser.add_argument(\"--init_hidden_size\", type=int, default=300, help=\"initial_emb_hidden_size\")\n parser.add_argument(\"--hidden_size\", type=int, default=128, help=\"initial_emb_hidden_size\")\n parser.add_argument(\"--lstm_hidden_size\", type=int, default=80, help=\"initial_emb_hidden_size\")\n parser.add_argument(\"--num_class\", type=int, default=8, help=\"num_class\")\n parser.add_argument(\n \"--residual\", action=\"store_true\", default=False, help=\"use residual connection\"\n )\n parser.add_argument(\"--word_dropout\", type=float, default=0.5, help=\"input feature dropout\")\n parser.add_argument(\"--tag_dropout\", type=float, default=0.5, help=\"input feature dropout\")\n parser.add_argument(\n \"--rnn_dropout\", type=list, default=0.33, help=\"dropout for rnn in word_emb\"\n )\n parser.add_argument(\"--lr\", type=float, default=0.01, help=\"learning rate\")\n parser.add_argument(\"--weight-decay\", type=float, default=5e-5, help=\"weight decay\")\n parser.add_argument(\n \"--aggregate_type\",\n type=str,\n default=\"mean\",\n help=\"aggregate type: 'mean','gcn','pool','lstm'\",\n )\n parser.add_argument(\n \"--gnn_type\", type=str, default=\"graphsage\", help=\"ingnn type: 'gat','graphsage','ggnn'\"\n )\n parser.add_argument(\"--use_gnn\", type=bool, default=True, help=\"whether to use gnn\")\n parser.add_argument(\"--batch_size\", type=int, default=100, help=\"batch size for training\")\n parser.add_argument(\n \"--graph_name\",\n type=str,\n default=\"line_graph\",\n help=\"graph_type:line_graph, dependency_graph, dynamic_graph\",\n )\n parser.add_argument(\n \"--init_graph_name\",\n type=str,\n default=\"dependency\",\n help=\"initial graph construction type ('line', 'dependency', 'constituency', 'ie')\",\n )\n parser.add_argument(\n \"--static_or_dynamic\",\n type=str,\n default=\"static\",\n help=\"static or dynamic\",\n )\n parser.add_argument(\n \"--pre_word_emb_file\", type=str, default=None, help=\"path of pretrained_word_emb_file\"\n )\n parser.add_argument(\n \"--gl_num_heads\", type=int, default=1, help=\"num of heads for dynamic graph construction\"\n )\n parser.add_argument(\n \"--gl_epsilon\", type=int, default=0.5, help=\"epsilon for graph sparsification\"\n )\n parser.add_argument(\"--gl_top_k\", type=int, default=None, help=\"top k for graph sparsification\")\n parser.add_argument(\n \"--gl_smoothness_ratio\",\n type=float,\n default=None,\n help=\"smoothness ratio for graph regularization loss\",\n )\n parser.add_argument(\n \"--gl_sparsity_ratio\",\n type=float,\n default=None,\n help=\"sparsity ratio for graph regularization loss\",\n )\n parser.add_argument(\n \"--gl_connectivity_ratio\",\n type=float,\n default=None,\n help=\"connectivity ratio for graph regularization loss\",\n )\n parser.add_argument(\n \"--init_adj_alpha\",\n type=float,\n default=0.8,\n help=\"alpha ratio for combining initial graph adjacency matrix\",\n )\n parser.add_argument(\n \"--gl_metric_type\",\n type=str,\n default=\"weighted_cosine\",\n help=\"similarity metric type for dynamic graph construction ('weighted_cosine', 'attention', \\\n 'rbf_kernel', 'cosine')\",\n )\n parser.add_argument(\n \"--no_fix_word_emb\",\n type=bool,\n default=False,\n help=\"Not fix pretrained word embeddings (default: false)\",\n )\n parser.add_argument(\n \"--no_fix_bert_emb\",\n type=bool,\n default=False,\n help=\"Not fix pretrained word embeddings (default: false)\",\n )\n\n import datetime\n\n starttime = datetime.datetime.now()\n # long running\n # do something other\n\n args = parser.parse_args()\n runner = Conll()\n max_score, max_idx = runner.train()\n print(\"Train finish, best score: {:.3f}\".format(max_score))\n print(max_idx)\n score = runner.test()\n endtime = datetime.datetime.now()\n print((endtime - starttime).seconds)\n" ]
[ [ "torch.from_numpy" ], [ "torch.Tensor" ], [ "torch.stack", "torch.nn.Linear", "torch.max" ], [ "torch.optim.Adam", "torch.utils.data.DataLoader", "torch.no_grad", "torch.device", "torch.multiprocessing.set_sharing_strategy" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jusch196/chameleon-apps
[ "b63a6b20a62c450565403b0768551cca9c288156" ]
[ "tools/tool_load_prediction/python_utils/cham_toollogs_evaluate_loss.py" ]
[ "from sklearn.metrics import mean_squared_error\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport sys\nimport os\nimport csv\n\n\n\n\"\"\"Read cham-tool-logs with predicted-load values\n\nEach rank holds an array of real-load and predicted load. For example,\n real_load_data=[R0_dat, R1_dat, ...]\n R0_dat = [] ...\n pred_load_data=[R0_dat, R1_dat, ...]\n R0_dat = [] ...\n\"\"\"\ndef parse_predicted_results(filename):\n\n # open the logfile\n file = open(filename, 'r')\n\n # for storing runtime/iter\n ret_data = []\n line_counter = 0\n for line in file:\n line_counter += 1\n # just get runtime per iteration\n if line_counter >= 20801:\n tmp = line.split(\"\\t\")\n real_load = float(tmp[0])\n pred_load = float(tmp[1])\n real_pred_tuple = [real_load, pred_load]\n ret_data.append(real_pred_tuple)\n\n # return the result\n return ret_data\n\n\n\"\"\"Gather results of all cham-tool-log files in a folder.\n\nNumber of log-files depends on # ranks to run the application,\nhence we process file-by-file, and storing results could be in a list.\n\"\"\"\ndef gather_Results(folder, num_nodes):\n\n # create a list for storing\n num_ranks = num_nodes * 2\n results_per_rank = []\n for i in range(num_ranks):\n results_per_rank.append([])\n\n # loop for all files in the folder\n for f in os.listdir(folder):\n\n # get rank id\n filename = f.split(\"_\")\n rank_id = int((filename[-1].split(\".\"))[0])\n\n # read log-file\n filepath = os.path.join(folder,f)\n data = parse_predicted_results(filepath)\n results_per_rank[rank_id] = data\n\n return results_per_rank\n\n\n\"\"\"Calculate MSE errors between real and pred load values.\n\nInput is the array of real_ and pred_load per rank, MSE values are\ncalculated indepently for each iteration, but skip the previous iters\nbecause of training phase.\n\"\"\"\ndef calculate_MSE(chamtool_data, num_ranks):\n\n ret_arr = []\n for i in range(num_ranks):\n ret_arr.append([])\n\n for i in range(num_ranks):\n\n # get the data of rank i\n load_arr = chamtool_data[i]\n num_iters = len(load_arr)\n\n # array for storing mse_errors\n mse_loss = []\n for j in range(20, num_iters):\n real_load = (load_arr[j])[0]\n pred_load = (load_arr[j])[1]\n mse = np.square(np.subtract(real_load, pred_load))\n mse_loss.append(mse)\n\n # add to the parent arr\n ret_arr[i] = mse_loss \n \n return ret_arr\n\n\n\"\"\"Plot runtime-by-iters\n\nInput is a list of runtime-data per rank. Use them to plot\na stacked-bar chart for easily to compare the load imbalance.\n\"\"\"\ndef plot_pred_data_boxplot(avg_loss_arr, out_folder):\n\n # boxplot\n fig, ax = plt.subplots()\n ax.boxplot(avg_loss_arr)\n ax.set_xlabel(\"Scale (# nodes)\")\n ax.set_ylabel(\"Loss (MSE)\")\n ax.set_xticklabels(['2', '4', '8', '16'])\n\n plt.yscale('log')\n plt.grid(True)\n # plt.show()\n\n # save the figure\n fig_filename = \"boxplot_avg_mse_loss\" + \".pdf\"\n plt.savefig(os.path.join(out_folder, fig_filename), bbox_inches='tight')\n\n\n\n\"\"\"The main function\n\nThere are 3 mains phases in the boday of this source,\nthat could be reading-logs, visualizing, and prediction.\n\"\"\"\nif __name__ == \"__main__\":\n\n # array for storing avg_loss of all cases\n num_cases = 0\n avg_loss_arr = []\n\n # get folder-path of log-files\n folder = sys.argv[1]\n dirs = os.listdir(folder)\n for d in dirs:\n # count num of the case traversed\n num_cases = num_cases + 1\n\n # get path to each directory\n path_to_dir = folder + \"/\" + d\n print(path_to_dir)\n\n # extract the folder name\n tokens = path_to_dir.split(\"/\")\n sub_token = tokens[len(tokens)-1].split(\"_\")\n num_nodes = int(sub_token[0])\n\n # gather results in the folder of logs\n real_pred_load_data = gather_Results(path_to_dir, num_nodes)\n \n # calculate loss_errors per rank\n num_ranks = num_nodes * 2\n mse_loss_arr = calculate_MSE(real_pred_load_data, num_ranks)\n print(\"Case: {} nodes, len(mse_loss_arr)={}\".format(num_nodes, len(mse_loss_arr)))\n\n # get avg_mse_arr for each case\n num_iters = len(mse_loss_arr[0])\n avg_mse_loss_arr = []\n for i in range(num_iters):\n tmp_arr = []\n for r in range(num_ranks):\n loss = mse_loss_arr[r][i]\n tmp_arr.append(loss)\n\n # get avg loss per iter of all ranks\n # print(\"\\t Iter {}: {}\".format(i, tmp_arr))\n avg_loss = np.average(tmp_arr) / len(tmp_arr)\n \n # store values to the par_array\n avg_mse_loss_arr.append(avg_loss)\n \n # append to the total array of loss\n avg_loss_arr.append(avg_mse_loss_arr) \n\n # plot box-plot\n plot_pred_data_boxplot(avg_loss_arr, folder)\n \n" ]
[ [ "numpy.subtract", "matplotlib.pyplot.yscale", "matplotlib.pyplot.subplots", "matplotlib.pyplot.grid", "numpy.average" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
closest-git/QuantumFold
[ "2dc6afa96cdee91b58f66543b440a2d7a8d32a8a" ]
[ "cnn/attention_net.py" ]
[ "'''\n@Author: Yingshi Chen\n\n@Date: 2020-04-27 18:30:01\n@\n# Description: \n'''\nfrom torch import nn\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom operations import *\nfrom sparse_max import sparsemax, sparsemoid, entmoid15, entmax15\nfrom genotypes import Genotype\nimport time\nfrom MixedOp import *\nfrom torch.autograd import Variable\nimport seaborn as sns; sns.set()\nimport matplotlib.pyplot as plt\n\nclass BasicConv(nn.Module):\n def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True, bias=False):\n super(BasicConv, self).__init__()\n self.out_channels = out_planes\n self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)\n self.bn = nn.BatchNorm2d(out_planes,eps=1e-5, momentum=0.01, affine=True) if bn else None\n self.relu = nn.ReLU() if relu else None\n\n def forward(self, x):\n x = self.conv(x)\n if self.bn is not None:\n x = self.bn(x)\n if self.relu is not None:\n x = self.relu(x)\n return x\n\nclass Flatten(nn.Module):\n def forward(self, x):\n return x.view(x.size(0), -1)\n\nclass ChannelGate(nn.Module):\n def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max']):\n super(ChannelGate, self).__init__()\n self.gate_channels = gate_channels\n self.mlp = nn.Sequential(\n Flatten(),\n nn.Linear(gate_channels, gate_channels // reduction_ratio),\n nn.ReLU(),\n nn.Linear(gate_channels // reduction_ratio, gate_channels)\n )\n self.pool_types = pool_types\n def forward(self, x):\n channel_att_sum = None\n for pool_type in self.pool_types:\n if pool_type=='avg':\n avg_pool = F.avg_pool2d( x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))\n channel_att_raw = self.mlp( avg_pool )\n elif pool_type=='max':\n max_pool = F.max_pool2d( x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))\n channel_att_raw = self.mlp( max_pool )\n elif pool_type=='lp':\n lp_pool = F.lp_pool2d( x, 2, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))\n channel_att_raw = self.mlp( lp_pool )\n elif pool_type=='lse':\n # LSE pool only\n lse_pool = logsumexp_2d(x)\n channel_att_raw = self.mlp( lse_pool )\n\n if channel_att_sum is None:\n channel_att_sum = channel_att_raw\n else:\n channel_att_sum = channel_att_sum + channel_att_raw\n\n scale = F.sigmoid( channel_att_sum ).unsqueeze(2).unsqueeze(3).expand_as(x)\n return x * scale\n\ndef logsumexp_2d(tensor):\n tensor_flatten = tensor.view(tensor.size(0), tensor.size(1), -1)\n s, _ = torch.max(tensor_flatten, dim=2, keepdim=True)\n outputs = s + (tensor_flatten - s).exp().sum(dim=2, keepdim=True).log()\n return outputs\n\nclass ChannelPool(nn.Module):\n def forward(self, x):\n return torch.cat( (torch.max(x,1)[0].unsqueeze(1), torch.mean(x,1).unsqueeze(1)), dim=1 )\n\nclass SpatialGate(nn.Module):\n def __init__(self):\n super(SpatialGate, self).__init__()\n kernel_size = 7\n self.compress = ChannelPool()\n self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=(kernel_size-1) // 2, relu=False)\n def forward(self, x):\n x_compress = self.compress(x)\n x_out = self.spatial(x_compress)\n scale = F.sigmoid(x_out) # broadcasting\n return x * scale\n\nclass CBAM(nn.Module):\n def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max'], no_spatial=False):\n super(CBAM, self).__init__()\n self.ChannelGate = ChannelGate(gate_channels, reduction_ratio, pool_types)\n self.no_spatial=no_spatial\n if not no_spatial:\n self.SpatialGate = SpatialGate()\n def forward(self, x):\n x_out = self.ChannelGate(x)\n if not self.no_spatial:\n x_out = self.SpatialGate(x_out)\n return x_out\n\nclass se_channels(nn.Module):\n def __init__(self, channel, reduction=16):\n super(se_channels, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.fc = nn.Sequential(\n nn.Linear(channel, channel // reduction, bias=False),\n nn.ReLU(inplace=True),\n nn.Linear(channel // reduction, channel, bias=False),\n nn.Sigmoid()\n )\n\n #einsum is more elegant than code at https://github.com/moskomule/senet.pytorch/blob/master/senet/se_module.py\n def forward_verify(self, x,out_0):\n b, c, _, _ = x.size()\n y = self.avg_pool(x).view(b, c)\n y = self.fc(y)\n out = torch.einsum('bcxy,bc->bcxy', x,y) \n dist = torch.dist(out,out_0,2)\n assert dist==0\n return \n\n #elegant code from https://github.com/moskomule/senet.pytorch/blob/master/senet/se_module.py\n def forward(self, x):\n b, c, _, _ = x.size()\n y = self.avg_pool(x).view(b, c)\n y = self.fc(y).view(b, c, 1, 1)\n out = x * y.expand_as(x)\n self.forward_verify(x,out) \n return out\n\nclass eca_channel(nn.Module):\n def __init__(self, channel, k_size=3):\n super(eca_channel, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.conv = nn.Conv1d(1, 1, kernel_size=k_size, padding=(k_size - 1) // 2, bias=False) \n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n b, c, h, w = x.size()\n y = self.avg_pool(x)\n # Two different branches of ECA module\n y0 = y.squeeze(-1).transpose(-1, -2)\n y = self.conv(y.squeeze(-1).transpose(-1, -2)).transpose(-1, -2).unsqueeze(-1)\n\n # Multi-scale information fusion\n y = self.sigmoid(y)\n\n return x * y.expand_as(x)\n\nclass se_operate(nn.Module):\n def __init__(self, nOP, reduction=2):\n super(se_operate, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1) #The number of output features is equal to the number of input planes.\n self.nOP,reduction = nOP,2\n self.fc = nn.Sequential(\n nn.Linear(nOP, nOP // reduction, bias=False), \n nn.ReLU(inplace=True),\n nn.Linear(nOP // reduction, nOP, bias=False),\n #nn.Sigmoid()\n nn.Softmax()\n ) \n self.desc=f\"se_operate_{reduction}\"\n self.nStep = 0\n #self.cur_alpha = torch.zeros(self.nOP).cuda()\n self.alpha_sum = torch.zeros(self.nOP)\n \n def __repr__(self):\n return self.desc\n\n # def InitAlpha(self):\n # self.nStep = 0\n # self.alpha = torch.zeros(self.nOP)\n \n def UpdateAlpha(self):\n if self.nStep==0:\n print(f\"\\tnStep=0\")\n self.alpha=self.alpha_sum*1\n return\n self.alpha=self.alpha_sum/self.nStep\n #print(f\"\\tnStep={self.nStep}\",end=\"\")\n a = torch.sum(self.alpha).item()\n self.alpha_sum.fill_(0)\n self.nStep = 0\n \n assert np.isclose(a, 1) \n\n #elegant code from https://github.com/moskomule/senet.pytorch/blob/master/senet/se_module.py\n def forward(self, listOPX):\n assert len(listOPX)==self.nOP\n y_list=[]\n for i,opx in enumerate(listOPX):\n y = torch.mean(self.avg_pool(opx).squeeze(),dim=1)\n y_list.append(y)\n y = torch.stack( y_list ,dim=1) \n w = self.fc(y)\n m_ = torch.mean(w,dim=0).detach() \n #assert np.isclose(torch.sum(m_).item(), 1) \n\n self.alpha_sum += m_.cpu()\n self.nStep = self.nStep+1 \n if False: #似乎都可以,真奇怪 \n out = 0\n for i,opx in enumerate(listOPX):\n w_i = w[:,i:i+1].squeeze()\n out = out+torch.einsum('bcxy,b->bcxy',opx,w_i) \n else:\n out = sum(w * opx for w, opx in zip(m_, listOPX)) \n \n return out\n\n#多个cell之间可共用alpha parameters!!!\nclass Alpha4Cell(object):\n def __init__(self,config, nOP,topo,isReduce=False):\n super(Alpha4Cell, self).__init__()\n self.config = config\n self.nets = None\n self.topo = topo\n self.isReduce = isReduce\n self.hasBeta = self.config.op_struc == \"PCC\" or self.config.op_struc == \"pair\"\n if self.config.topo_edges == \"2\":\n self.hasBeta = True\n #k = sum(1 for i in range(self.nNode) for n in range(2+i)) \n k = self.topo.hGraph[-1]\n self.desc = f\"W[edges={k},nOP={nOP}]\"\n if self.config.op_struc==\"se\": \n pass\n else:\n self.alphas_ = Variable(1e-3*torch.randn((k,nOP)).cuda(), requires_grad=True)\n if self.hasBeta:\n self.betas_ = Variable(1e-3*torch.randn(k).cuda(), requires_grad=True) \n\n if self.hasBeta: self.desc+=\"\\tbeta\"\n if self.isReduce: self.desc+=\"\\treduce\"\n\n def __repr__(self):\n return self.desc\n\n # def BeforeEpoch(self):\n # pass\n\n # def AfterEpoch(self):\n # pass\n\n def step(self):\n pass\n\n def get_weight(self,purpose=\"get_gene\"):\n if not hasattr(self,\"alphas_\"):\n # assert False\n return [None,None]\n\n w_a,w_b = F.softmax(self.alphas_, dim=-1),None\n if self.hasBeta:\n if False: \n n = 3\n start = 2\n weights2 = F.softmax(self.betas_[0:2], dim=-1)\n for i in range(self.nNode-1):\n end = start + n\n tw2 = F.softmax(self.betas_[start:end], dim=-1)\n start = end\n n += 1\n weights2 = torch.cat([weights2,tw2],dim=0)\n assert end==len(self.betas_)\n else:\n I_I = self.topo.I_I\n weights2 = torch.cat( [F.softmax(self.betas_[I_I(id)], dim=-1) for id in range(self.topo.nNode)] ,dim=0) \n w_b = weights2 \n \n return [w_a,w_b]\n \n def get_gene(self,plot_path=\"\"):\n [weights,weights2] = self.get_weight()\n if weights is None:\n return \"\"\n weights = weights.detach().cpu().numpy()\n if weights2 is not None:\n weights2 = weights2.detach().cpu().numpy()\n \n nNode = self.topo.nNode\n nEdges = self.topo.nMostEdge()\n PRIMITIVES_pool = self.config.PRIMITIVES_pool\n \n gene = []\n\n none_index = PRIMITIVES_pool.index('none')\n \n for i in range(nNode):\n II = self.topo.I_I(i)\n start = self.topo.hGraph[i] #类似于单刚和总刚\n nEdge = len(II)\n #W = weights[II].copy()\n if weights2 is not None:\n #W2 = weights2[II].copy()\n for j in II:\n weights[j, :] = weights[j, :]*weights2[j]\n edges,cur_gene = [],[]\n for edge in II: \n W_edge = weights[edge].copy() #print(W_edge)\n cur_nz = len(weights[edge])\n k_sort = sorted(range(cur_nz), key=lambda k:W_edge[k])\n k_sort.remove(none_index)\n k_best = k_sort[cur_nz-2]\n cur_min, cur_max = W_edge[k_sort[0]], W_edge[k_best]\n edges.append(-cur_max)\n cur_gene.append((PRIMITIVES_pool[k_best], edge-start))\n edges = sorted(range(nEdge), key=lambda k:edges[k]) #Default is ascending\n gene.extend([cur_gene[edges[0]], cur_gene[edges[1]]]) \n\n if plot_path is not None: #已考虑weights2的影响\n sns.set(font_scale=1)\n fig, ax = plt.subplots(figsize=(8,3))\n g = sns.heatmap(weights.T,square=True, cmap='coolwarm', ax=ax) #, annot=True\n g.set_yticklabels(PRIMITIVES_pool, rotation=0)\n g.set_xticklabels([i+1 for i in range(nEdges)],rotation=0) #rotation=45\n fig.savefig(plot_path, bbox_inches='tight', pad_inches=0)\n #plt.show()\n plt.close(\"all\") \n return gene\n \n def get_param(self):\n param_list = []\n if self.nets is not None:\n for net in self.nets:\n for name, param in net.named_parameters():\n param_list.append(param) \n if self.hasBeta:\n param_list.append(self.betas_) \n return param_list \n if self.hasBeta:\n return [self.alphas_,self.betas_]\n else:\n return [self.alphas_]\n\nclass Alpha_se(Alpha4Cell):\n def __init__(self,config, nOP,topo,isReduce=False):\n super(Alpha_se, self).__init__(config, nOP,topo,isReduce)\n self.nets = [se_operate(nOP) for i in range(self.topo.nMostEdge())]\n self.nets = nn.ModuleList(self.nets)\n self.desc+=f\"\\t\\\"{self.nets[0]}\\\"x{len(self.nets)}\"\n\n def __repr__(self):\n return self.desc\n\n # def BeforeEpoch(self):\n # for net in self.nets:\n # net.BeforeEpoch()\n\n def step(self):\n list_alpha=[] \n nNet = len(self.nets) \n for i,net in enumerate(self.nets):\n net.UpdateAlpha()\n list_alpha.append(net.alpha)\n self.alphas_ = torch.stack(list_alpha,dim=0)\n #print(\"\")\n # for net in self.nets: #重置\n # net.InitAlpha()\n\n\n def get_weight(self):\n if not hasattr(self,\"alphas_\"):\n # assert False\n return [None,None]\n\n return [self.alphas_,None]\n \n " ]
[ [ "torch.nn.Softmax", "torch.nn.functional.softmax", "torch.nn.ModuleList", "torch.nn.Conv2d", "matplotlib.pyplot.subplots", "torch.nn.Sigmoid", "torch.nn.functional.sigmoid", "torch.nn.Linear", "torch.nn.AdaptiveAvgPool2d", "torch.nn.BatchNorm2d", "torch.nn.Conv1d", "matplotlib.pyplot.close", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
csvance/machine-learning-connect-four
[ "faec52280a82183f7dfd8ed6d9253af9093811eb", "faec52280a82183f7dfd8ed6d9253af9093811eb" ]
[ "c4_model.py", "c4.py" ]
[ "import numpy as np\nimport tensorflow as tf\nfrom keras.backend import set_session\nfrom keras.layers import Dense, Flatten, Input, concatenate, SeparableConv2D\nfrom keras.models import Model\nfrom keras.optimizers import Adam\n\nfrom c4_game import C4Action, C4Experience, C4State, C4MoveResult\n\n\nclass Ramp(object):\n def __init__(self, start: float, end: float, steps: int, delay: int = 0):\n self.value = start\n self.start = start\n self.end = end\n self.steps = steps\n self.delay = delay\n\n if steps == 0:\n self.value = end\n\n self._steps_processed = 0\n\n def step(self, steps: int) -> float:\n self._steps_processed += steps\n\n if self._steps_processed < self.delay:\n return self.value\n\n ramp_vertical = self.end - self.start\n ramp_horizontal = self.steps\n\n try:\n m = ramp_vertical / ramp_horizontal\n except ZeroDivisionError:\n self.value = self.end\n return self.end\n\n x = (self._steps_processed - self.delay)\n b = self.start\n y = m * x + b\n\n if self.start < self.end:\n self.value = min(self.end, y)\n elif self.start > self.end:\n self.value = max(self.end, y)\n\n return self.value\n\n\nclass C4Model(object):\n def __init__(self, use_gpu=True, epsilon_start: float = 1., epsilon_steps: int = 1000000, epsilon_end=0.05,\n gamma=0.9, learning_rate=0.0001):\n\n self.epsilon = Ramp(start=epsilon_start, end=epsilon_end, steps=epsilon_steps)\n self.gamma = gamma\n\n self.reward_memory = []\n\n self.steps = 0\n\n input_board = Input(shape=(6, 7, 2))\n input_heights = Input(shape=(7,))\n input_scores = Input(shape=(7, 8, 2))\n\n x_1 = input_board\n x_1 = SeparableConv2D(64, 4, activation='relu')(x_1)\n x_1 = SeparableConv2D(64, 1, activation='relu')(x_1)\n x_1 = Flatten()(x_1)\n\n x_2 = input_scores\n x_2 = Dense(64, activation='relu')(x_2)\n x_2 = Dense(64, activation='relu')(x_2)\n x_2 = Flatten()(x_2)\n\n x_3 = input_heights\n\n x = concatenate([x_1, x_2, x_3])\n x = Dense(256, activation='relu')(x)\n\n output = Dense(len(C4Action), activation='linear')(x)\n\n model = Model(inputs=[input_board, input_scores, input_heights], outputs=output)\n model.compile(optimizer=Adam(lr=learning_rate), loss='mse', metrics=['mae'])\n model.summary()\n self._model = model\n\n if use_gpu:\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n set_session(tf.Session(config=config))\n\n # Data is the game state, labels are the action taken\n def train(self, experience: C4Experience):\n\n if not experience.terminal:\n new_state = experience.new_state.copy()\n\n # Invert state perspective to match the enemy agent\n new_state.invert_perspective()\n\n # We don't care about the enemy reward, just the most likely action\n prediction = self._model.predict(new_state.state_representation())[0]\n action = C4Action(np.argmax(prediction))\n\n # Apply the enemy action to advance the state, invert the perspective to match friendly agent\n move_result = new_state.move(action)\n if move_result != C4MoveResult.VICTORY:\n new_state.invert_perspective()\n\n # Here is where our discounted future reward comes from (next friendly state in our perspective)\n prediction = self._model.predict(new_state.state_representation())[0]\n\n # Calculate discounted future reward\n target = experience.reward + self.gamma * np.amax(prediction)\n elif C4MoveResult.VICTORY:\n target = -1.\n else:\n target = 0.\n else:\n target = experience.reward\n\n # Clip reward\n if target > 1.:\n target = 1.\n elif target < -1.:\n target = -1.\n\n self.reward_memory.append(target)\n\n target_f = self._model.predict(experience.old_state.state_representation())\n target_f[0][experience.action.value] = target\n\n history = self._model.fit(experience.old_state.state_representation(), target_f, epochs=1, verbose=0)\n\n self.epsilon.step(1)\n\n self.steps += 1\n\n return history\n\n def print_suggest(self, state: C4State):\n predictions = self._model.predict(state.state_representation())[0]\n\n p_list = []\n for i in range(0, len(predictions)):\n p_list.append([i + 1, predictions[i]])\n\n p_list.sort(key=lambda x: x[1], reverse=True)\n\n for p in p_list:\n print(\"%d: %f\" % (p[0], p[1]))\n\n def predict(self, state: C4State, valid_moves: np.ndarray, epsilon: float = None) -> C4Action:\n\n if epsilon is None:\n e = self.epsilon.value\n else:\n e = epsilon\n\n if np.random.rand() <= e:\n potential_moves = []\n for idx in range(0, len(valid_moves)):\n if valid_moves[idx] == 1:\n potential_moves.append(C4Action(idx))\n return np.random.choice(potential_moves)\n\n predictions = self._model.predict(state.state_representation())[0]\n\n # We only want valid moves\n np.place(valid_moves, valid_moves == 0., [-999999.])\n np.place(valid_moves, valid_moves == 1., 0.)\n\n predictions = predictions + valid_moves\n\n return C4Action(np.argmax(predictions))\n\n def stats(self):\n rewards = np.array(self.reward_memory)\n self.reward_memory = []\n\n min = np.min(rewards)\n max = np.max(rewards)\n avg = np.average(rewards)\n stdev = np.std(rewards)\n med = np.median(rewards)\n return min, max, avg, stdev, med, self.steps\n\n def save(self, path='weights.h5'):\n self._model.save_weights(filepath=path)\n\n def load(self, path='weights.h5'):\n self._model.load_weights(filepath=path)\n", "import argparse\nimport csv\nimport os\n\nimport numpy as np\n\nfrom c4_game import C4Game, C4MoveResult, C4Team, C4Action\nfrom c4_model import C4Model\n\n\ndef human_vs_human(weights_file: str):\n c4 = C4Game()\n c4ai = C4Model(epsilon_start=0., epsilon_end=0.)\n c4ai.load(weights_file)\n\n print(c4.display())\n\n while True:\n current_team = c4.current_turn()\n valid_moves = c4.state.valid_moves()\n\n c4ai.print_suggest(c4.state)\n\n if current_team == C4Team.BLACK:\n move = input(\"Move(%s): \" % current_team)\n if move == 'q':\n return\n move = C4Action(int(move) - 1)\n elif current_team == C4Team.RED:\n move = input(\"Move(%s): \" % current_team)\n if move == 'q':\n return\n move = C4Action(int(move) - 1)\n\n result = c4.action(move)\n\n print(c4.display())\n print(\"Result: %s\" % result)\n\n if result == C4MoveResult.VICTORY:\n c4.reset()\n print(c4.display())\n continue\n elif result == C4MoveResult.TIE:\n c4.reset()\n print(c4.display())\n continue\n elif result == C4MoveResult.INVALID:\n print(c4.display())\n continue\n\n\ndef human_vs_ai(weights_file: str):\n c4 = C4Game()\n c4ai = C4Model(epsilon_start=0., epsilon_end=0.)\n c4ai.load(weights_file)\n\n print(c4.display())\n\n while True:\n current_team = c4.current_turn()\n valid_moves = c4.state.valid_moves()\n\n c4ai.print_suggest(c4.state)\n\n if current_team == C4Team.BLACK:\n move = input(\"Move(%s): \" % current_team)\n if move == 'q':\n return\n move = C4Action(int(move) - 1)\n elif current_team == C4Team.RED:\n move = c4ai.predict(c4.state, valid_moves=valid_moves)\n\n result = c4.action(move)\n\n print(c4.display())\n print(\"Result: %s\" % result)\n\n if result == C4MoveResult.VICTORY:\n c4.reset()\n print(c4.display())\n continue\n elif result == C4MoveResult.TIE:\n c4.reset()\n print(c4.display())\n continue\n elif result == C4MoveResult.INVALID:\n print(c4.display())\n continue\n\n\ndef ai_vs_best(c4: C4Game, c4ai: C4Model, games: int = 100):\n best_wins = 0\n ai_wins = 0\n\n ai_scores = []\n best_scores = []\n\n c4.reset()\n while True:\n\n if best_wins + ai_wins >= games:\n return best_wins, ai_wins, np.sum(best_scores) / games, np.sum(ai_scores) / games\n\n current_team = c4.current_turn()\n valid_moves = c4.state.valid_moves()\n\n if current_team == C4Team.BLACK:\n move = c4.best_action(valid_moves=valid_moves)\n elif current_team == C4Team.RED:\n move = c4ai.predict(c4.state, valid_moves=valid_moves, epsilon=0.05)\n\n result = c4.action(move)\n\n if result == C4MoveResult.VICTORY:\n if c4.current_turn() == C4Team.RED:\n ai_wins += 1\n elif c4.current_turn() == C4Team.BLACK:\n best_wins += 1\n ai_scores.append(c4.red_score)\n best_scores.append(c4.black_score)\n print(c4.display())\n c4.reset()\n continue\n elif result == C4MoveResult.TIE:\n print(c4.display())\n c4.reset()\n continue\n elif result == C4MoveResult.INVALID:\n continue\n\n\ndef ai_vs_ai(weights_file: str, epsilon_start: float, epsilon_steps: int, epsilon_end: float, training_steps: int,\n gamma: float):\n game_no = 0\n red_wins = 0\n black_wins = 0\n\n stats_headers = ['red_wins', 'black_wins', 'epsilon', 'game_length', 'loss', 'mae', 'avg', 'med', 'std']\n stats_log_file = open('stats_log.csv', 'w')\n stats_log_writer = csv.DictWriter(stats_log_file, fieldnames=stats_headers)\n stats_log_writer.writeheader()\n\n perf_headers = ['ai_win_rate']\n perf_log_file = open('perf_log.csv', 'w')\n perf_log_writer = csv.DictWriter(perf_log_file, fieldnames=perf_headers)\n perf_log_writer.writeheader()\n\n c4 = C4Game()\n c4ai = C4Model(epsilon_start=epsilon_start, epsilon_steps=epsilon_steps, epsilon_end=epsilon_end,\n gamma=gamma)\n try:\n if weights_file is not None:\n c4ai.load(weights_file)\n c4.load()\n except OSError:\n print(\"Warning: could not load weights file!\")\n pass\n\n while True:\n current_team = c4.current_turn()\n valid_moves = c4.state.valid_moves()\n\n if current_team == C4Team.BLACK:\n move = c4ai.predict(c4.state, valid_moves=valid_moves)\n elif current_team == C4Team.RED:\n move = c4ai.predict(c4.state, valid_moves=valid_moves)\n\n result = c4.action(move)\n\n if result == C4MoveResult.VICTORY:\n # Update stats\n if current_team == C4Team.RED:\n red_wins += 1\n elif current_team == C4Team.BLACK:\n black_wins += 1\n\n # Train\n if not c4.duplicate:\n training_data = c4.sample()\n else:\n print(\"Duplicate.\")\n training_data = None\n\n if training_data is not None:\n\n step_count = 0\n loss_sum = 0.\n mae_sum = 0.\n for state in training_data:\n history = c4ai.train(state)\n loss_sum += history.history['loss'][0]\n mae_sum += history.history['mean_absolute_error'][0]\n step_count += 1\n\n min, max, avg, stdev, med, steps = c4ai.stats()\n\n stats = {}\n stats['red_wins'] = red_wins\n stats['black_wins'] = black_wins\n stats['epsilon'] = c4ai.epsilon.value\n stats['game_length'] = (c4.turn + 1) / 42.\n stats['loss'] = loss_sum / step_count\n stats['mae'] = mae_sum / step_count\n stats['avg'] = avg\n stats['med'] = med\n stats['std'] = stdev\n stats_log_writer.writerow(stats)\n\n print(\"Red: %d Black %d Steps: %d\" % (red_wins, black_wins, steps))\n print(\"Epsilon: %f Gamma: %f Loss: %f mae: %f\" % (\n c4ai.epsilon.value, c4ai.gamma, loss_sum / step_count, mae_sum / step_count))\n print(\"Avg: %f Med: %f Std: %f\\nRange: [%f, %f]\" % (avg, med, stdev, min, max))\n print(c4.display())\n print(\"\")\n\n if (game_no != 0 and game_no % 100 == 0) or c4ai.steps >= training_steps:\n print(\"Saving...\")\n stats_log_file.flush()\n c4ai.save(weights_file)\n\n best_wins, ai_wins, best_score, ai_score = ai_vs_best(c4, c4ai)\n ai_win_rate = ai_wins / (best_wins + ai_wins)\n perf_log_writer.writerow(\n {'ai_win_rate': ai_win_rate})\n perf_log_file.flush()\n print(\"AI won %f%% of games\" % ai_win_rate)\n\n if c4ai.steps >= training_steps:\n print(\"Ran %d steps.\" % steps)\n c4.save()\n return\n print(\"Done.\")\n\n game_no += 1\n\n # Reset\n c4.reset()\n\n elif result == C4MoveResult.TIE:\n print(\"Tie.\")\n\n # Reset\n c4.reset()\n\n\nif __name__ == '__main__':\n np.seterr(all='raise')\n\n parser = argparse.ArgumentParser()\n parser.add_argument('mode')\n parser.add_argument('--weights-file', type=str, default=\"weights.h5\")\n parser.add_argument('--epsilon-start', type=float, default=1.)\n parser.add_argument('--epsilon-steps', type=int, default=100000)\n parser.add_argument('--epsilon-end', type=float, default=0.05)\n parser.add_argument('--training-steps', type=int, default=2000000)\n parser.add_argument('--gamma', type=float, default=0.9)\n parser.add_argument('--verbose', action='store_true')\n args = parser.parse_args()\n\n if not args.verbose:\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n if args.mode == 'ava':\n ai_vs_ai(weights_file=args.weights_file, epsilon_start=args.epsilon_start, epsilon_steps=args.epsilon_steps,\n epsilon_end=args.epsilon_end, training_steps=args.training_steps, gamma=args.gamma)\n elif args.mode == 'hva':\n human_vs_ai(args.weights_file)\n elif args.mode == 'hvh':\n human_vs_human(args.weights_file)\n else:\n print(\"Valid modes are: \")\n print(\"hvh - Human vs Human\")\n print(\"hva - Huamn vs AI\")\n print(\"ava - AI vs AI (Training)\")\n" ]
[ [ "numpy.amax", "numpy.min", "numpy.random.choice", "numpy.median", "tensorflow.ConfigProto", "numpy.max", "numpy.std", "numpy.argmax", "numpy.random.rand", "tensorflow.Session", "numpy.average", "numpy.array", "numpy.place" ], [ "numpy.seterr", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pnnl/ProxyTSPRD
[ "6e60c65768d9ff124802a66526be0923665f0e17", "6e60c65768d9ff124802a66526be0923665f0e17" ]
[ "proxy_apps/apps/timeseries_prediction/proxyDeepDMDMGPU.py", "examples/test_data_pipeline.py" ]
[ "import time\nimport logging\nimport tensorflow as tf\n# from tensorflow.keras.utils import Progbar\n# from tensorflow.python.keras import callbacks as callbacks_module\n# import nvtx.plugins.tf as nvtx_tf\n\nlogger = tf.get_logger()\n\n# Neural Network\nclass TFOptimizedModelTrainer():\n def __init__(self, hp, model, mixed_precision=False):\n self.encoder = model\n\n # other parameters\n self.rf = hp.rf\n self.data_type = hp.data_type\n self.mixed_precision = mixed_precision\n\n # @tf.function(experimental_compile=True)\n def fit(self, training_dataset, n_epochs, batch_size, steps_per_epoch):\n all_loss = []\n epoch_time = []\n avg_batch_time = []\n for epoch in range(n_epochs):\n # logger.info(\"\\nepoch {}/{}\".format(epoch+1, n_epochs))\n # self.pb_i = Progbar(steps_per_epoch+1, stateful_metrics=['loss'])\n epoch_start_time = time.time()\n total_loss, num_batches = self.distributed_train_epoch(training_dataset, batch_size, steps_per_epoch)\n loss_value = total_loss / (self.encoder.distribute_strategy.num_replicas_in_sync * num_batches)\n epoch_stop_time = time.time()\n \n # logger.info(\"Loss value: {}\".format(tf.keras.backend.get_value(loss_value)))\n all_loss.append(tf.keras.backend.get_value(loss_value))\n epoch_time.append(epoch_stop_time-epoch_start_time)\n avg_batch_time.append((epoch_stop_time-epoch_start_time)/num_batches)\n \n return all_loss, epoch_time, avg_batch_time\n\n @tf.function#(experimental_compile=True)\n def distributed_train_epoch(self, training_dataset, batch_size, steps_per_epoch):\n total_loss = tf.cast(0.0, self.data_type)\n num_batches = tf.cast(0, self.data_type)\n\n # Iterate over the batches of the dataset.\n for inp_data in training_dataset:\n total_loss += self.distributed_train_step(inp_data)\n num_batches += tf.cast(1, self.data_type)\n\n return total_loss, num_batches\n\n @tf.function#(experimental_compile=True) # (input_signature=(tf.TensorSpec(shape=[None], dtype=tf.float64),))\n def train_step(self, inputs):\n X, Y = inputs\n with tf.GradientTape() as tape:\n Psi_X = self.encoder(X, training=True)\n Psi_Y = self.encoder(Y, training=False)\n\n PSI_X = tf.concat([X, tf.cast(Psi_X, self.data_type)], 1)\n PSI_Y = tf.concat([Y, tf.cast(Psi_Y, self.data_type)], 1)\n\n # 1-time step evolution on observable space:\n K_PSI_X = tf.matmul(PSI_X, self.encoder.KO)\n\n # 1-step Koopman loss on observable space:\n K_loss = tf.norm(PSI_Y - K_PSI_X, axis=[0, 1], ord='fro')\n\n # Regularization loss on Koopman operator:\n Reg_loss = tf.math.scalar_mul(self.rf, tf.norm(self.encoder.KO, axis=[0, 1], ord='fro'))\n\n # Total loss:\n loss = K_loss + Reg_loss\n loss += sum(self.encoder.losses)\n if self.mixed_precision: scaled_loss = self.encoder.optimizer.get_scaled_loss(loss)\n # tf.print(\"K Loss: \", K_loss, \"Reg Loss: \", Reg_loss, \"Total Loss: \", loss, \"Scaled Loss: \", scaled_loss)\n\n # Compute gradients\n trainable_vars = self.encoder.trainable_variables\n if self.mixed_precision:\n scaled_gradients = tape.gradient(scaled_loss, trainable_vars)\n gradients = self.encoder.optimizer.get_unscaled_gradients(scaled_gradients)\n else:\n gradients = tape.gradient(loss, trainable_vars)\n\n # Update weights\n self.encoder.optimizer.apply_gradients(zip(gradients, trainable_vars))\n\n # Return a dict mapping metric names to current value.\n # Note that it will include the loss (tracked in self.metrics).\n return loss\n\n @tf.function#(experimental_compile=True)\n def distributed_train_step(self, dist_inputs):\n per_replica_losses = self.encoder.distribute_strategy.run(self.train_step, args=(dist_inputs,))\n return self.encoder.distribute_strategy.reduce(tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)\n\n @tf.function(experimental_compile=True)\n def predict(self, test_dataset):\n for inp_data in test_dataset: total_loss += self.distributed_test_step(inp_data)\n\n @tf.function(experimental_compile=True)\n def distributed_test_step(self, dist_inputs):\n return self.encoder.distribute_strategy.run(self.test_step, args=(dist_inputs,))\n\n @tf.function(experimental_compile=True)\n def test_step(self, inputs): \n X, Y = inputs\n\n Psi_X = self.encoder(X, training=False)\n Psi_Y = self.encoder(Y, training=False) \n\n PSI_X = tf.concat([X, tf.cast(Psi_X, self.data_type)], 1)\n PSI_Y = tf.concat([Y, tf.cast(Psi_Y, self.data_type)], 1)\n \n # 1-time step evolution on observable space:\n K_PSI_X = tf.matmul(PSI_X, self.encoder.KO) \n\n # 1-step Koopman loss on observable space: \n K_loss = tf.norm(PSI_Y - K_PSI_X, axis = [0,1], ord = 'fro')\n\n # Regularization loss on Koopman operator:\n Reg_loss= tf.math.scalar_mul(self.rf, tf.norm(self.encoder.KO, axis = [0,1], ord = 'fro')) \n\n # Total loss:\n loss = K_loss + Reg_loss\n loss += sum(self.encoder.losses)\n \n # Return a dict mapping metric names to current value.\n # Note that it will include the loss (tracked in self.metrics).\n return Psi_X, PSI_X, Psi_Y, PSI_Y, K_loss\n \n @tf.function(experimental_compile=True)\n def predict_step(self, inputs): \n X, Y = inputs\n\n Psi_X = self.encoder(X, training=False)\n Psi_Y = self.encoder(Y, training=False) \n\n PSI_X = tf.concat([X, tf.cast(Psi_X, self.data_type)], 1)\n PSI_Y = tf.concat([Y, tf.cast(Psi_Y, self.data_type)], 1)\n\n # 1-time step evolution on observable space:\n K_PSI_X = tf.matmul(PSI_X, self.encoder.KO) \n\n # 1-step Koopman loss on observable space: \n K_loss = tf.norm(PSI_Y - K_PSI_X, axis = [0,1], ord = 'fro')\n \n # Regularization loss on Koopman operator:\n Reg_loss= tf.math.scalar_mul(self.rf, tf.norm(self.encoder.KO, axis = [0,1], ord = 'fro')) \n\n return Psi_X, PSI_X, Psi_Y, PSI_Y, K_loss\n\nclass TFOptimizedEncoder(tf.keras.Model):\n def __init__(self, hps):\n super(TFOptimizedEncoder, self).__init__(name = 'Encoder')\n # Define and randomly initialize the Koopman operator\n self.KO = tf.Variable(tf.random.normal(shape = (hps.ld+hps.od, hps.ld+hps.od),\n dtype=hps.data_type,\n mean=0.0, stddev=0.05,\n seed=123321, name='KoopmanOperator'), trainable=True)\n\n self.input_layer = DenseLayer(hps.h1, 0.0, 0.0, hps.data_type)\n self.hidden_layer1 = DenseLayer(hps.h2, hps.wr, hps.br, hps.data_type)\n self.dropout_laye1 = tf.keras.layers.Dropout(hps.dr)\n self.hidden_layer2 = DenseLayer(hps.h3, hps.wr, hps.br, hps.data_type)\n self.dropout_laye2 = tf.keras.layers.Dropout(hps.dr)\n self.hidden_layer3 = DenseLayer(hps.h4, hps.wr, hps.br, hps.data_type)\n self.dropout_laye3 = tf.keras.layers.Dropout(hps.dr)\n self.output_layer = LinearLayer(hps.ld, hps.wr, hps.br, hps.data_type)\n\n def call(self, input_data, training):\n fx = self.input_layer(input_data)\n fx = self.hidden_layer1(fx)\n fx = self.dropout_laye1(fx, training=training)\n fx = self.hidden_layer2(fx)\n fx = self.dropout_laye2(fx, training=training)\n fx = self.hidden_layer3(fx)\n fx = self.dropout_laye3(fx, training=training)\n return self.output_layer(fx)\n\nclass LinearLayer(tf.keras.layers.Layer):\n def __init__(self, units, weights_regularizer, bias_regularizer, d_type):\n super(LinearLayer, self).__init__()\n self.units = units\n self.weights_regularizer = weights_regularizer\n self.bias_regularizer = bias_regularizer\n self.d_type = d_type\n \n def build(self, input_shape):\n input_dim = input_shape[-1]\n self.w = self.add_weight(name='w_linear',\n shape=(input_dim, self.units),\n initializer=tf.keras.initializers.RandomUniform(\n minval=-tf.cast(tf.math.sqrt(6/(input_dim+self.units)), dtype=self.d_type),\n maxval=tf.cast(tf.math.sqrt(6/(input_dim+self.units)), dtype=self.d_type),\n seed=16751),\n trainable=True)\n self.b = self.add_weight(name='b_linear',\n shape=(self.units,),\n initializer=tf.zeros_initializer(),\n regularizer=tf.keras.regularizers.l1(self.bias_regularizer),\n trainable=True)\n\n def call(self, inputs):\n return tf.matmul(inputs, self.w) + self.b\n\nclass DenseLayer(tf.keras.layers.Layer):\n\n def __init__(self, units, weights_regularizer, bias_regularizer, d_type):\n super(DenseLayer, self).__init__()\n self.units = units\n self.weights_regularizer = weights_regularizer\n self.bias_regularizer = bias_regularizer\n self.d_type = d_type\n self.alpha = 1\n \n def build(self, input_shape):\n input_dim = input_shape[-1]\n self.w = self.add_weight(name='w_dense',\n shape=(input_dim, self.units),\n initializer=tf.keras.initializers.RandomUniform(\n minval=-tf.cast(tf.math.sqrt(6.0/(input_dim+self.units)), dtype=self.d_type),\n maxval=tf.cast(tf.math.sqrt(6.0/(input_dim+self.units)), dtype=self.d_type),\n seed=16751),\n regularizer=tf.keras.regularizers.l1(self.weights_regularizer),\n trainable=True)\n self.b = self.add_weight(name='b_dense',\n shape=(self.units,),\n initializer=tf.zeros_initializer(),\n regularizer=tf.keras.regularizers.l1(self.bias_regularizer),\n trainable=True)\n\n def call(self, inputs):\n x = tf.matmul(inputs, self.w) + self.b\n cond = tf.keras.backend.greater(x, 0)\n return tf.keras.backend.switch(cond, x, tf.keras.backend.exp(tf.keras.backend.minimum(x, 0.)) - 1)", "import os\nimport numpy as np\nimport pandas as pd\nimport torch\nimport tensorflow as tf\n\n# Custom Library\nimport sys\nsys.path.append('../')\n\nfrom proxy_apps import ProxyTSPRD\nfrom proxy_apps.utils import file_reader, path_handler\n\nclass ProcessDataFile(tf.data.Dataset):\n def _generator(file_name, n_rows, n_cols, n_repeat, x_indexer, y_indexer, norm, scale_factor):\n # Opening the file\n dataset = TransientDataset(file_name.decode('utf-8'))\n raw_data = np.repeat(np.concatenate([dataset.F, dataset.Vm], axis=1), n_repeat, axis=1)[:n_rows, :]\n \n split_index = (n_cols * n_repeat) // 2\n flat_X_data = raw_data[x_indexer]\n flat_Y_data = raw_data[y_indexer]\n \n if norm:\n # normalization specific to grid strategy only\n flat_X_data[:, :, :split_index] = scale_factor*(flat_X_data[:, :, :split_index] - 60)\n flat_X_data[:, :, split_index:] = 10*(flat_X_data[:, :, split_index:] - 1)\n \n flat_Y_data[:, :, :split_index] = scale_factor*(flat_Y_data[:, :, :split_index] - 60)\n flat_Y_data[:, :, split_index:] = 10*(flat_Y_data[:, :, split_index:] - 1)\n \n yield (flat_X_data, flat_Y_data)\n\n def __new__(cls, file_name, n_rows, flat_n_rows, n_cols, n_repeat, x_indexer, y_indexer, d_type, norm=True, scale_factor=2*np.pi):\n # print(\"Enter\")\n return tf.data.Dataset.from_generator(\n cls._generator,\n output_signature = (tf.TensorSpec(shape=(x_indexer.shape[0], x_indexer.shape[1], n_cols*n_repeat), dtype=d_type),\n tf.TensorSpec(shape=(y_indexer.shape[0], y_indexer.shape[1], n_cols*n_repeat), dtype=d_type)),\n args=(file_name, n_rows, n_cols, n_repeat, x_indexer, y_indexer, norm, scale_factor,)\n )\n\nclass GridNetworkWindowDataGenerator():\n def __init__(self, dir_list, handler_params, dtype):#scenario_dir, n_rows, n_cols, dtype, repeat_cols=1):\n self.dir_list = dir_list\n self.n_rows = handler_params[\"n_rows\"]\n self.n_cols = handler_params[\"n_cols\"]\n self.repeat_cols = handler_params[\"repeat_cols\"]\n self.look_back = handler_params[\"look_back\"]\n self.look_forward = handler_params[\"look_forward\"]\n self.shift_size = handler_params[\"shift_size\"]\n self.stride = handler_params[\"stride\"]\n self.n_signals = handler_params[\"n_signals\"]\n self.data_type = dtype\n\n # @tf.function(experimental_compile=True)\n def get_training_data(self, x_indexer, y_indexer, deterministic=False):\n # load data and print list of files\n # print('[INFO]: Loading the datasets from the directory:', self.scenario_dir)\n # self.dir_list = [self.scenario_dir + \"/\" + f + \"/\" for f in os.listdir(self.scenario_dir)[:self.n_scenarios]]\n \n list_files = tf.data.Dataset.from_tensor_slices(self.dir_list)\n trimmed_scenarios = list_files.interleave(lambda x: ProcessDataFile(x, self.n_rows, \n x_indexer.shape[0] * x_indexer.shape[1], \n self.n_cols, self.repeat_cols, \n x_indexer, y_indexer,\n self.data_type\n ).prefetch(tf.data.AUTOTUNE),\n num_parallel_calls=tf.data.AUTOTUNE,\n #cycle_length=len(self.dir_list), \n #block_length=1,\n deterministic=deterministic\n )\n \n flat_data = trimmed_scenarios.flat_map(lambda x, y: tf.data.Dataset.from_tensor_slices((x, y)))\n \n return flat_data\n\nclass GridNetworkSequentialDataGenerator_TF(tf.keras.utils.Sequence):\n 'Characterizes a dataset for TensorFlow'\n def __init__(self, dir_list, handler_params, dtype, scale_factor=2*np.pi, norm=True):#, n_rows, n_cols, n_repeat, x_indexer, y_indexer, scale_factor=2, norm=True, d_type=\"float64\"):\n 'Initialization'\n self.list_of_directories = dir_list\n self.n_rows = handler_params[\"n_rows\"]\n self.n_cols = handler_params[\"n_cols\"]\n self.repeat_cols = handler_params[\"repeat_cols\"]\n self.scale_factor = scale_factor # handler_params[\"scale_factor\"]\n self.norm = norm # handler_params[\"norm\"]\n self.look_back = handler_params[\"look_back\"]\n self.look_forward = handler_params[\"look_forward\"]\n self.shift_size = handler_params[\"shift_size\"]\n self.stride = handler_params[\"stride\"]\n self.n_signals = handler_params[\"n_signals\"]\n self.d_type = dtype\n \n def get_training_data(self, x_indexer, y_indexer):\n self.x_indexer = x_indexer\n self.y_indexer = y_indexer\n \n complete_data = list(map(functools.partial(self.get_data), self.list_of_directories))\n self.X = np.vstack([arr[0] for arr in complete_data]) # stacked_array[0, :, :]\n self.y = np.vstack([arr[1] for arr in complete_data]) # stacked_array[1, :, :]\n \n assert self.X.shape[0]==self.y.shape[0]\n \n def get_data(self, dir_path): # , n_rows, n_cols, n_repeat, x_indexer, y_indexer, scale_factor, norm, d_type\n dataset = TransientDataset(dir_path)\n raw_data = np.repeat(np.concatenate([dataset.F, dataset.Vm], axis=1), self.repeat_cols, axis=1)[:self.n_rows, :].astype(self.d_type)\n\n split_index = (self.n_cols * self.repeat_cols) // 2\n flat_X_data = raw_data[self.x_indexer]#.reshape(-1, self.n_cols*self.n_repeat)\n flat_Y_data = raw_data[self.y_indexer]#.reshape(-1, self.n_cols*self.n_repeat)\n # print(flat_X_data.shape, flat_Y_data.shape)\n\n if self.norm:\n flat_X_data[:, :, :split_index] = self.scale_factor*(flat_X_data[:, :, :split_index] - 60)\n flat_X_data[:, :, split_index:] = 10*(flat_X_data[:, :, split_index:] - 1)\n\n flat_Y_data[:, :, :split_index] = self.scale_factor*(flat_Y_data[:, :, :split_index] - 60)\n flat_Y_data[:, :, split_index:] = 10*(flat_Y_data[:, :, split_index:] - 1)\n\n return flat_X_data, flat_Y_data\n\n def __len__(self):\n 'Denotes the total number of samples'\n return self.X.shape[0]\n \n def __getitem__(self, index):\n 'Generates one sample of data'\n # print(self.X[index, :].shape, self.y[index, :].shape)\n return self.X[index, :], self.y[index, :]\n \n def __call__(self):\n for i in range(self.X.shape[0]):\n yield self.__getitem__(i)\n \nclass GridNetworkSequentialDataGenerator_PT(torch.utils.data.Dataset):\n 'Characterizes a dataset for PyTorch'\n def __init__(self, dir_list, handler_params, dtype, scale_factor=2*np.pi, norm=True):#, n_rows, n_cols, n_repeat, x_indexer, y_indexer, scale_factor=2, norm=True, d_type=\"float64\"):\n 'Initialization'\n self.list_of_directories = dir_list\n self.n_rows = handler_params[\"n_rows\"]\n self.n_cols = handler_params[\"n_cols\"]\n self.repeat_cols = handler_params[\"repeat_cols\"]\n self.scale_factor = scale_factor # handler_params[\"scale_factor\"]\n self.norm = norm # handler_params[\"norm\"]\n self.look_back = handler_params[\"look_back\"]\n self.look_forward = handler_params[\"look_forward\"]\n self.shift_size = handler_params[\"shift_size\"]\n self.stride = handler_params[\"stride\"]\n self.n_signals = handler_params[\"n_signals\"]\n self.d_type = dtype\n \n def get_training_data(self, x_indexer, y_indexer):\n self.x_indexer = x_indexer\n self.y_indexer = y_indexer\n \n complete_data = list(map(functools.partial(self.get_data), self.list_of_directories))\n self.X = np.vstack([arr[0] for arr in complete_data]) # stacked_array[0, :, :]\n self.y = np.vstack([arr[1] for arr in complete_data]) # stacked_array[1, :, :]\n \n assert self.X.shape[0]==self.y.shape[0]\n \n def get_data(self, dir_path): # , n_rows, n_cols, n_repeat, x_indexer, y_indexer, scale_factor, norm, d_type\n dataset = TransientDataset(dir_path)\n raw_data = np.repeat(np.concatenate([dataset.F, dataset.Vm], axis=1), self.repeat_cols, axis=1)[:self.n_rows, :].astype(self.d_type)\n\n split_index = (self.n_cols * self.repeat_cols) // 2\n flat_X_data = raw_data[self.x_indexer]#.reshape(-1, self.n_cols*self.n_repeat)\n flat_Y_data = raw_data[self.y_indexer]#.reshape(-1, self.n_cols*self.n_repeat)\n # print(flat_X_data.shape, flat_Y_data.shape)\n\n if self.norm:\n flat_X_data[:, :, :split_index] = self.scale_factor*(flat_X_data[:, :, :split_index] - 60)\n flat_X_data[:, :, split_index:] = 10*(flat_X_data[:, :, split_index:] - 1)\n\n flat_Y_data[:, :, :split_index] = self.scale_factor*(flat_Y_data[:, :, :split_index] - 60)\n flat_Y_data[:, :, split_index:] = 10*(flat_Y_data[:, :, split_index:] - 1)\n\n return flat_X_data, flat_Y_data\n\n def __len__(self):\n 'Denotes the total number of samples'\n return self.X.shape[0]\n \n def __getitem__(self, index):\n 'Generates one sample of data'\n return self.X[index, :], self.y[index, :]\n \nif __name__==\"__main__\":\n ## ProxyTSPRD\n # get configuration file\n _REF_DIR = \"./\"\n _CONFIG_FILE = \"./configs/config_lstm.json\"\n config = file_reader.read_config(_REF_DIR + _CONFIG_FILE)\n \n data_params = config[\"data_params\"]\n \n # training data\n data_params[\"training_data_dir\"] = path_handler.get_absolute_path(_REF_DIR, data_params[\"training_data_dir\"])\n print(\"[INFO] Training Data Directory:\", data_params[\"training_data_dir\"])\n\n # validation data - if any\n if \"val_data_dir\" in data_params:\n data_params[\"val_data_dir\"] = path_handler.get_absolute_path(_REF_DIR, data_params[\"val_data_dir\"])\n print(\"[INFO] Validation Data Directory:\", data_params[\"val_data_dir\"])\n\n dir_list = [data_params[\"training_data_dir\"] + \"/\" + f + \"/\" for f in os.listdir(data_params[\"training_data_dir\"])]\n n_files = len(dir_list)\n\n # subset files\n if data_params[\"n_scenarios\"]:\n n_files = data_params[\"n_scenarios\"]\n dir_list = dir_list[:n_files]\n\n import horovod.tensorflow.keras as hvd\n\n # Initialize Horovod\n hvd.init()\n\n # Pin GPU to be used to process local rank (one GPU per process)\n gpus = tf.config.experimental.list_physical_devices('GPU')\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n if gpus:\n tf.config.experimental.set_visible_devices(gpus[hvd.local_rank()], 'GPU')\n\n # if self._MGPU_STRATEGY == \"HVD\":\n print(\"[INFO] Sharding data files for Horovod\")\n splitter = n_files // hvd.size()\n print(n_files, splitter, splitter*hvd.rank(), splitter*(hvd.rank()+1))\n dir_list = dir_list[splitter*hvd.rank():splitter*(hvd.rank()+1)]\n n_files = len(dir_list)\n\n print(\"[INFO] Number of files (per GPU):\", n_files)\n\n# data_handler = GridNetworkWindowDataGenerator(dir_list, config['data_params'], 'float64')\n# x_indexer = self.get_indexer(self.data_handler.n_rows,\n# self.data_handler.window_size,\n# self.data_handler.shift_size,\n# 0,\n# self.data_handler.n_signals\n# )\n# y_indexer = self.get_indexer(self.data_handler.n_rows,\n# self.data_handler.window_size,\n# self.data_handler.shift_size,\n# 1,\n# 0\n# )\n\n# scenario_data = data_handler.get_training_data(x_indexer, y_indexer)\n\n" ]
[ [ "tensorflow.matmul", "tensorflow.norm", "tensorflow.math.sqrt", "tensorflow.keras.regularizers.l1", "tensorflow.keras.backend.greater", "tensorflow.keras.backend.get_value", "tensorflow.cast", "tensorflow.zeros_initializer", "tensorflow.get_logger", "tensorflow.function", "tensorflow.keras.backend.minimum", "tensorflow.keras.layers.Dropout", "tensorflow.random.normal", "tensorflow.GradientTape" ], [ "tensorflow.config.experimental.set_memory_growth", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.config.experimental.list_physical_devices", "numpy.concatenate", "tensorflow.TensorSpec", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "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" ] } ]
allenbai01/ProxQuant
[ "1a9240e2afd1f49257ab5527b0f61862481a0e9d" ]
[ "models/binarized_modules.py" ]
[ "import torch\nimport pdb\nimport torch.nn as nn\nimport math\nfrom torch.autograd import Variable\nfrom torch.autograd import Function\n\nimport numpy as np\n\n\ndef Binarize(tensor,quant_mode='det'):\n if quant_mode=='det':\n return tensor.sign()\n else:\n return tensor.add_(1).div_(2).add_(torch.rand(tensor.size()).add(-0.5)).clamp_(0,1).round().mul_(2).add_(-1)\n\n\n\n\nclass HingeLoss(nn.Module):\n def __init__(self):\n super(HingeLoss,self).__init__()\n self.margin=1.0\n\n def hinge_loss(self,input,target):\n #import pdb; pdb.set_trace()\n output=self.margin-input.mul(target)\n output[output.le(0)]=0\n return output.mean()\n\n def forward(self, input, target):\n return self.hinge_loss(input,target)\n\nclass SqrtHingeLossFunction(Function):\n def __init__(self):\n super(SqrtHingeLossFunction,self).__init__()\n self.margin=1.0\n\n def forward(self, input, target):\n output=self.margin-input.mul(target)\n output[output.le(0)]=0\n self.save_for_backward(input, target)\n loss=output.mul(output).sum(0).sum(1).div(target.numel())\n return loss\n\n def backward(self,grad_output):\n input, target = self.saved_tensors\n output=self.margin-input.mul(target)\n output[output.le(0)]=0\n import pdb; pdb.set_trace()\n grad_output.resize_as_(input).copy_(target).mul_(-2).mul_(output)\n grad_output.mul_(output.ne(0).float())\n grad_output.div_(input.numel())\n return grad_output,grad_output\n\ndef Quantize(tensor,quant_mode='det', params=None, numBits=8):\n tensor.clamp_(-2**(numBits-1),2**(numBits-1))\n if quant_mode=='det':\n tensor=tensor.mul(2**(numBits-1)).round().div(2**(numBits-1))\n else:\n tensor=tensor.mul(2**(numBits-1)).round().add(torch.rand(tensor.size()).add(-0.5)).div(2**(numBits-1))\n quant_fixed(tensor, params)\n return tensor\n\nimport torch.nn._functions as tnnf\n\n\nclass BinarizeLinear(nn.Linear):\n\n def __init__(self, *kargs, **kwargs):\n super(BinarizeLinear, self).__init__(*kargs, **kwargs)\n\n def forward(self, input):\n\n if input.size(1) != 784:\n input.data=Binarize(input.data)\n if not hasattr(self.weight,'org'):\n self.weight.org=self.weight.data.clone()\n self.weight.data=Binarize(self.weight.org)\n out = nn.functional.linear(input, self.weight)\n if not self.bias is None:\n self.bias.org=self.bias.data.clone()\n out += self.bias.view(1, -1).expand_as(out)\n\n return out\n\nclass BinarizeConv2d(nn.Conv2d):\n\n def __init__(self, *kargs, **kwargs):\n super(BinarizeConv2d, self).__init__(*kargs, **kwargs)\n\n\n def forward(self, input):\n if input.size(1) != 3:\n input.data = Binarize(input.data)\n if not hasattr(self.weight,'org'):\n self.weight.org=self.weight.data.clone()\n self.weight.data=Binarize(self.weight.org)\n\n out = nn.functional.conv2d(input, self.weight, None, self.stride,\n self.padding, self.dilation, self.groups)\n\n if not self.bias is None:\n self.bias.org=self.bias.data.clone()\n out += self.bias.view(1, -1, 1, 1).expand_as(out)\n\n return out\n" ]
[ [ "torch.nn.functional.conv2d", "torch.nn.functional.linear" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zhoubin-me/agent0
[ "1184827077e43dfa63e1f24a004fcc6c3e3d5130", "1184827077e43dfa63e1f24a004fcc6c3e3d5130" ]
[ "agent0/ddpg/model.py", "agent0/deepq/trainer.py" ]
[ "from itertools import chain\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.distributions import Normal\n\n\ndef init(m, gain=1.0):\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n nn.init.orthogonal_(m.weight.data, gain)\n nn.init.zeros_(m.bias.data)\n\n\nclass DDPGMLP(nn.Module):\n def __init__(self, num_inputs, action_dim, max_action, hidden_size=256):\n super(DDPGMLP, self).__init__()\n\n self.max_action = max_action\n self.v = nn.Sequential(\n nn.Linear(num_inputs + action_dim, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, 1)\n )\n\n self.p = nn.Sequential(\n nn.Linear(num_inputs, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, action_dim), nn.Tanh()\n )\n\n self.apply(lambda m: init(m, np.sqrt(2)))\n\n def act(self, x):\n return self.p(x) * self.max_action\n\n def action_value(self, state, action):\n return self.v(torch.cat([state, action], dim=1))\n\n def get_policy_params(self):\n return self.p.parameters()\n\n def get_value_params(self):\n return self.v.parameters()\n\n\nclass SACMLP(nn.Module):\n LOG_STD_MAX = 2\n LOG_STD_MIN = -20\n eps = 1e-6\n\n def __init__(self, num_inputs, action_dim, max_action, hidden_size=256):\n super(SACMLP, self).__init__()\n self.max_action = max_action\n self.v = nn.Sequential(\n nn.Linear(num_inputs + action_dim, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, 1)\n )\n\n self.v2 = nn.Sequential(\n nn.Linear(num_inputs + action_dim, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, 1)\n )\n\n self.p = nn.Sequential(\n nn.Linear(num_inputs, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, action_dim * 2)\n )\n\n self.apply(lambda m: init(m, np.sqrt(2)))\n\n def act(self, x):\n action_mean, action_log_std = torch.chunk(self.p(x), 2, dim=-1)\n action_log_std = action_log_std.clamp(self.LOG_STD_MIN, self.LOG_STD_MAX)\n dist = Normal(action_mean, action_log_std.exp())\n\n xs = dist.rsample()\n action = xs.tanh() * self.max_action\n\n action_log_prob = dist.log_prob(xs) - torch.log(1 - action.pow(2) + self.eps)\n entropy = action_log_prob.sum(-1, keepdim=True).neg()\n\n return action, entropy, action_mean.tanh() * self.max_action\n\n def action_value(self, state, action):\n x = torch.cat([state, action], dim=1)\n return self.v(x), self.v2(x)\n\n def get_policy_params(self):\n return self.p.parameters()\n\n def get_value_params(self):\n return chain(self.v.parameters(), self.v2.parameters())\n\n\nclass TD3MLP(nn.Module):\n def __init__(self, num_inputs, action_dim, max_action, hidden_size=256):\n super(TD3MLP, self).__init__()\n self.max_action = max_action\n self.v = nn.Sequential(\n nn.Linear(num_inputs + action_dim, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, 1)\n )\n\n self.v2 = nn.Sequential(\n nn.Linear(num_inputs + action_dim, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, 1)\n )\n\n self.p = nn.Sequential(\n nn.Linear(num_inputs, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, hidden_size), nn.Tanh(),\n nn.Linear(hidden_size, action_dim), nn.Tanh()\n )\n\n self.apply(lambda m: init(m, np.sqrt(2)))\n\n def act(self, x):\n return self.p(x) * self.max_action\n\n def action_value(self, state, action):\n x = torch.cat([state, action], dim=1)\n return self.v(x), self.v2(x)\n\n def get_policy_params(self):\n return self.p.parameters()\n\n def get_value_params(self):\n return chain(self.v.parameters(), self.v2.parameters())\n", "import json\nimport os\nimport time\nfrom abc import ABC\n\nimport numpy as np\nimport ray\nimport torch\nfrom agent0.common.utils import LinearSchedule, set_random_seed\nfrom agent0.deepq.actor import Actor\nfrom agent0.deepq.agent import Agent\nfrom agent0.deepq.config import Config\nfrom ray import tune\nfrom ray.tune.trial import ExportFormat\n\n\nclass Trainer(tune.Trainable, ABC):\n def __init__(self, config=None, logger_creator=None):\n\n self.Rs, self.Qs, self.TRs, self.Ls, self.ITRs, self.velocity = [], [], [], [], [], []\n self.cfg = None\n self.agent = None\n self.epsilon = None\n self.epsilon_schedule = None\n self.actors = None\n self.frame_count = None\n self.Rs, self.Qs, self.TRs, self.Ls, self.ITRs = [], [], [], [], []\n self.best = float('-inf')\n self.sample_ops = None\n super(Trainer, self).__init__(config, logger_creator)\n\n def setup(self, config):\n self.cfg = Config(**config)\n self.cfg.update_atoms()\n set_random_seed(self.cfg.random_seed)\n print(\"input args:\\n\", json.dumps(vars(self.cfg), indent=4, separators=(\",\", \":\")))\n\n self.agent = Agent(**config)\n self.epsilon_schedule = LinearSchedule(1.0, self.cfg.min_eps, self.cfg.exploration_steps)\n self.actors = [ray.remote(Actor).options(num_gpus=0.1 * self.cfg.gpu_mult).remote(rank=rank, **config)\n for rank in range(self.cfg.num_actors)]\n\n self.frame_count = 0\n self.best = float('-inf')\n self.epsilon = 1.0\n\n self.sample_ops = [a.sample.remote(self.cfg.actor_steps, 1.0, self.agent.model.state_dict()) for a in\n self.actors]\n\n def step(self):\n fraction_loss = None\n ce_loss = None\n tic = time.time()\n done_id, self.sample_ops = ray.wait(self.sample_ops)\n data = ray.get(done_id)\n transitions, rs, qs, rank, fps, best_ep = data[0]\n # Actors\n if len(transitions) > 0:\n self.agent.replay.extend(transitions)\n if len(best_ep) > 0:\n self.agent.replay.extend_ep_best(best_ep)\n\n self.epsilon = self.epsilon_schedule(self.cfg.actor_steps * self.cfg.num_envs)\n self.frame_count += self.cfg.actor_steps * self.cfg.num_envs\n\n self.sample_ops.append(\n self.actors[rank].sample.remote(self.cfg.actor_steps, self.epsilon, self.agent.model.state_dict()))\n self.Rs += rs\n self.Qs += qs\n # Start training at\n if len(self.agent.replay) > self.cfg.start_training_step:\n data = [self.agent.train_step() for _ in range(self.cfg.agent_train_steps)]\n if self.cfg.algo in ['fqf']:\n fraction_loss = torch.stack([x['fraction_loss'] for x in data]).mean().item()\n if self.cfg.best_ep:\n ce_loss = torch.stack([x['ce_loss'] for x in data]).mean().item()\n\n loss = [x['loss'] for x in data]\n loss = torch.stack(loss)\n self.Ls += loss.tolist()\n toc = time.time()\n self.velocity.append(self.cfg.actor_steps * self.cfg.num_envs / (toc - tic))\n\n result = dict(\n game=self.cfg.game,\n time_past=self._time_total,\n epsilon=self.epsilon,\n adam_lr=self.cfg.adam_lr,\n frames=self.frame_count,\n fraction_loss=fraction_loss if fraction_loss is not None else 0,\n ce_loss=ce_loss if ce_loss is not None else 0,\n velocity=np.mean(self.velocity[-20:]) if len(self.velocity) > 0 else 0,\n speed=self.frame_count / (self._time_total + 1),\n time_remain=(self.cfg.total_steps - self.frame_count) / ((self.frame_count + 1) / (self._time_total + 1)),\n loss=np.mean(self.Ls[-20:]) if len(self.Ls) > 0 else 0,\n ep_reward_test=np.mean(self.ITRs) if len(self.ITRs) > 0 else 0,\n ep_reward_train=np.mean(self.Rs[-20:]) if len(self.Rs) > 0 else 0,\n ep_reward_train_max=np.max(self.Rs) if len(self.Rs) > 0 else 0,\n ep_reward_test_max=np.max(self.TRs) if len(self.TRs) > 0 else 0,\n qmax=np.mean(self.Qs[-100:]) if len(self.Qs) > 0 else 0\n )\n return result\n\n def save_checkpoint(self, checkpoint_dir):\n print(f\"Iteration {self.training_iteration} testing started\")\n output = ray.get([a.sample.remote(self.cfg.actor_steps,\n self.cfg.test_eps,\n self.agent.model.state_dict(),\n testing=True,\n test_episodes=self.cfg.test_episode_per_actor) for a in self.actors])\n\n ckpt_rs = []\n for _, rs, qs, rank, fps, _ in output:\n ckpt_rs += rs\n\n self.ITRs = ckpt_rs\n self.TRs += ckpt_rs\n print(f\"Iteration {self.training_iteration} test Result(mean|std|max|min|len):\"\n f\" {np.mean(ckpt_rs)}\\t{np.std(ckpt_rs)}\\t{np.max(ckpt_rs)}\\t{np.min(ckpt_rs)}\\t{len(ckpt_rs)}\")\n\n data_to_save = {\n 'model': self.agent.model.state_dict(),\n 'optim': self.agent.optimizer.state_dict(),\n 'model_target': self.agent.model_target.state_dict(),\n 'Ls': self.Ls,\n 'Rs': self.Rs,\n 'Qs': self.Qs,\n 'TRs': self.TRs,\n 'frame_count': self.frame_count,\n 'ITRs': ckpt_rs,\n 'best': self.best,\n }\n\n if np.mean(ckpt_rs) > self.best:\n self.best = np.mean(ckpt_rs)\n torch.save(data_to_save, f'./itr_{self.training_iteration}.pth')\n torch.save(data_to_save, f'./best.pth')\n\n return dict()\n\n def load_checkpoint(self, checkpoint):\n self.agent.model.load_state_dict(checkpoint['model'])\n self.agent.model_target.load_state_dict(checkpoint['model_target'])\n self.agent.optimizer.load_state_dict(checkpoint['optim'])\n self.Ls = checkpoint['Ls']\n self.Qs = checkpoint['Qs']\n self.Rs = checkpoint['Rs']\n self.TRs = checkpoint['TRs']\n self.frame_count = checkpoint['frame_count']\n self.best = checkpoint['best']\n self.epsilon_schedule(self.frame_count)\n\n def _export_model(self, export_formats, export_dir):\n if export_formats == [ExportFormat.MODEL]:\n path = os.path.join(export_dir, \"exported_models\")\n torch.save({\n \"model\": self.agent.model.state_dict(),\n \"optim\": self.agent.optimizer.state_dict()\n }, path)\n return {ExportFormat.MODEL: path}\n else:\n raise ValueError(\"unexpected formats: \" + str(export_formats))\n\n def reset_config(self, new_config):\n if \"adam_lr\" in new_config:\n self.cfg.adam_lr = new_config['adam_lr']\n for param_group in self.agent.optimizer.param_groups:\n param_group['lr'] = new_config['adam_lr']\n\n self.config = new_config\n return True\n\n def cleanup(self):\n ray.get([a.close_envs.remote() for a in self.actors])\n" ]
[ [ "numpy.sqrt", "torch.cat", "torch.nn.Tanh", "torch.nn.Linear", "torch.nn.init.orthogonal_", "torch.nn.init.zeros_" ], [ "numpy.min", "numpy.max", "numpy.std", "numpy.mean", "torch.stack", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hideyukiinada/ml
[ "2618e2d694edb40b4b01e584f63a3c0ade7e4652" ]
[ "project/neuralnetwork.py" ]
[ "#!/usr/bin/env python\n\"\"\"\nNeural Network implementation.\n\nCredit\n------\nI primarily learned the neural network algorithm from below sources:\n[ICL] Imperial College London, Mathematics for Machine Learning Specialization, https://www.coursera.org/specializations/mathematics-machine-learning\n[DA] deeplearning.ai, Deep Learning Specialization, https://www.coursera.org/specializations/deep-learning\n[IG] Ian Goodfellow, Yoshua Bengio and Aaron Courville, Deep Learning, MIT Press, 2016\nbibtex entry for the [IG] above:\n@book{Goodfellow-et-al-2016,\n title={Deep Learning},\n author={Ian Goodfellow and Yoshua Bengio and Aaron Courville},\n publisher={MIT Press},\n note={\\\\url={http://www.deeplearningbook.org}},\n year={2016}\n}\n\nAdam optimization code is based on the below paper:\n[DK] Diederik P. Kingma and Jimmy Lei Ba, ADAM: A METHOD FOR STOCHASTIC OPTIMIZATION, https://arxiv.org/abs/1412.6980, 2015\n\nI crafted the code from scratch based on the algorithm that I learned, so please email me if you see an error\nin this code\n\n* Model class was inspired by the Keras SequenceModel and Keras layer.\n\n__author__ = \"Hide Inada\"\n__copyright__ = \"Copyright 2018, Hide Inada\"\n__license__ = \"The MIT License\"\n__email__ = \"[email protected]\"\n\"\"\"\n\nimport sys\nimport os\nimport logging\n\nfrom numba import jit\nimport math\nimport numpy as np\n\nfrom .activationfunction import ActivationFunction as af\nfrom .costfunction import CostFunction as cf\nfrom .optimizer import Optimizer as opt\nfrom .weightpersistence import WeightPersistence as wp\nfrom .weightparameter import WeightParameter as wparam\nfrom .convolve import Convolve as conv\nfrom .convolve import _calculate_target_matrix_dimension\n\nlog = logging.getLogger(__name__)\nlogging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\")) # Change the 2nd arg to INFO to suppress debug logging\n\n\n@jit(nopython=True)\ndef forward_prop_affine_transform(a_prev, weight, bias):\n \"\"\"\n Apply affine transformation for forward prop\n\n Parameters\n ----------\n a_prev: ndarray\n Previous layer's activation\n weight: ndarray\n Weight\n bias: ndarray\n Bias\n\n Returns\n -------\n z: ndarray\n Affine transform\n \"\"\"\n\n return a_prev.dot(weight) + bias\n\n\nclass LayerType():\n \"\"\"\n Type of layers for neural network\n \"\"\"\n DENSE = 0\n CONV = 1\n\n\nclass Layer():\n \"\"\"\n Holds meta-information of a single layer of neural network\n \"\"\"\n\n def __init__(self, num_units, activation=af.RELU, dropout=1.0):\n self.num_units = num_units # number of units on the layer.\n self.activation = activation # the activation function for the layer.\n self.layer_type = LayerType.DENSE # type of the layer\n self.dropout = dropout # Dropout. For now, this is valid for dense layer only.\n\nclass ConvLayer(Layer):\n def __init__(self, kernel_shape, channels, strides=(1, 1), use_padding=True, activation=af.RELU, flatten=False,\n layer_dim=None):\n \"\"\"\n Initialize kernel parameters.\n\n Parameters\n ----------\n kernel_shape: tuple\n Shape of kernel specified with a tuple (height, row, number of channels)\n strides: tuple\n Step size in each axis\n use_padding: bool\n True if m should be zero-padded before convolution. This is to keep the output matrix the same size.\n False if no padding should be applied before convolution.\n flatten: bool\n Output a flattened layer.\n layer_dim: tuple\n Dimension of the layer. This is specified only for the input layer which is the pseudo conv layer.\n For other layers, this is calculated from other parameters during init.\n \"\"\"\n self.kernel_shape = kernel_shape\n self.channels = channels\n self.strides = strides\n self.use_padding = use_padding\n self.activation = activation\n self.layer_type = LayerType.CONV\n self.flatten = flatten\n self.layer_dim = layer_dim\n\n\nclass Model():\n \"\"\"\n Container for holding information for multiple layers\n \"\"\"\n\n def __init__(self, num_input=0, layer_dim=None):\n \"\"\"\n Initialize the model.\n\n Parameters\n ----------\n num_input: int\n Number of elements in each sample\n input_shape: tuple\n Shape of each sample, e.g. (64, 64, 3) for RGB.\n if both num_input and input_shape are specified, input_shape takes precedence.\n \"\"\"\n\n self.layers = list()\n\n if layer_dim is not None:\n self.layers.append(\n ConvLayer(layer_dim=layer_dim, kernel_shape=None, channels=layer_dim[2], activation=af.NONE))\n else:\n self.layers.append(Layer(num_units=num_input, activation=af.NONE))\n\n def add(self, layer):\n \"\"\"\n Add a single layer to the model.\n\n Parameters\n ----------\n layer: Layer\n A single layer of the network\n \"\"\"\n self.layers.append(layer)\n\n\nclass NeuralNetwork():\n \"\"\"\n Neural Network\n\n Variables used in the class\n ---------------------------\n weight: matrix\n Weight stored in matrix associated with each layer.\n Size of the matrix is unit count of the previous layer multiplied by the unit count of the current layer\n bias: vector\n Bias stored in matrix associated with each layer.\n Size of the vector is unit unit count of the current layer\n z: matrix\n Affine transformation applied to previous layer's activation\n z = a.T w. In this code, a is a matrix with each row holding all parameters for a single point.\n Therefore, z = a w is used.\n a: matrix\n Output of an activation function with z as an input. Activation functions include sigmoid and ReLU.\n\n Notes\n -----\n Layer number starts with 0 with 0 being the input. However, input is not counted as a layer following a convention.\n Weight and bias only exist for layers 1 and above.\n \"\"\"\n\n MODE_FIT = 0\n MODE_PREDICT = 1\n\n def _init_weight_forward_prop_data_list(self):\n \"\"\"\n Allocate list for weight, bias, z, a, gradient of weight, gradient of bias.\n Allocate matrix and vector as weight and bias for each layer.\n\n Notes\n -----\n With the exception of a[0] which is used to access input, all others have valid values only with indices\n greater than or equal to 1.\n \"\"\"\n\n def list_with_n_elements(n):\n \"\"\"\n Helper function to generate a list with n elements.\n The primary use for this is to instantiate a list with one item as our neural network uses\n 1-based index for all except for accessing the input as layer 0 activation.\n\n\n Parameters\n ----------\n n: int\n Number of elements\n\n Returns\n -------\n out: list\n list with n elements. All elements are set to None\n \"\"\"\n return [None] * n\n\n self.weight = list_with_n_elements(1)\n self.gradient_weight = list_with_n_elements(1)\n self.bias = list_with_n_elements(1)\n self.gradient_bias = list_with_n_elements(1)\n self.z = list_with_n_elements(self.num_layers + 1)\n self.a = list_with_n_elements(self.num_layers + 1)\n self.dropout_vector = list_with_n_elements(self.num_layers + 1)\n self.kernel_parameter = list_with_n_elements(self.num_layers + 1)\n self.layer_locked = [False] * (self.num_layers + 1)\n\n # Create a list for holding references to moment vectors for ADAM\n if self.optimizer == opt.ADAM:\n self.mt_weight = list_with_n_elements(1) # First moment vector for weight\n self.mt_bias = list_with_n_elements(1) # First moment vector for bias\n self.vt_weight = list_with_n_elements(1) # Second moment vector for weight\n self.vt_bias = list_with_n_elements(1) # Second moment vector for bias\n\n # Allocate weight and bias for each layer\n for i in range(self.num_layers):\n w = None # to suppress a wrong IDE warning\n b = None\n\n this_layer = self.model.layers[i + 1]\n prev_layer = self.model.layers[i]\n\n if self.model.layers[i + 1].layer_type == LayerType.DENSE:\n\n num_units_this_layer = this_layer.num_units\n num_units_prev_layer = prev_layer.num_units\n\n self.dropout_vector[i] = np.ones((num_units_prev_layer))\n\n # w initialization below is following the recommendation on http://cs231n.github.io/neural-networks-2/\n # min 100 to ensure that weights are small when the number of units is a few.\n\n if self.weight_parameter is None:\n w = np.random.randn(num_units_prev_layer, num_units_this_layer) * 0.1\n else:\n if self.weight_parameter.init_type == wparam.NORMAL:\n w = np.random.normal(self.weight_parameter.mean, self.weight_parameter.stddev,\n (num_units_prev_layer,\n num_units_this_layer)) * self.weight_parameter.multiplier\n elif self.weight_parameter.init_type == wparam.UNIFORM:\n w = np.random.uniform(self.weight_parameter.mean, self.weight_parameter.stddev,\n (num_units_prev_layer,\n num_units_this_layer)) * self.weight_parameter.multiplier\n elif self.weight_parameter.init_type == wparam.ZERO:\n w = np.zeros((num_units_prev_layer, num_units_this_layer))\n elif self.weight_parameter.init_type == wparam.LAYER_UNIT_COUNT_PROPORTIONAL:\n w = np.random.randn(num_units_prev_layer, num_units_this_layer) * math.sqrt(\n 1.0 / num_units_prev_layer) * self.weight_parameter.multiplier\n elif self.weight_parameter.init_type == wparam.LAYER_UNIT_COUNT_PROPORTIONAL2:\n w = np.random.randn(num_units_prev_layer, num_units_this_layer) * math.sqrt(\n 2.0 / num_units_prev_layer) * self.weight_parameter.multiplier\n\n # Bias\n if self.bias_parameter is None:\n b = np.zeros((1, num_units_this_layer))\n else:\n if self.bias_parameter.init_type == wparam.NORMAL:\n b = np.random.normal(self.bias_parameter.mean, self.bias_parameter.stddev,\n (1, num_units_this_layer)) * self.bias_parameter.multiplier\n elif self.bias_parameter.init_type == wparam.UNIFORM:\n b = np.random.uniform(self.bias_parameter.mean, self.bias_parameter.stddev,\n (1, num_units_this_layer)) * self.bias_parameter.multiplier\n elif self.bias_parameter.init_type == wparam.ZERO:\n b = np.zeros((1, num_units_this_layer))\n\n else: # if current layer is conv\n if prev_layer.layer_dim is None:\n log.error(\"Fatal error. Dimension of the previous layer is set to None.\")\n raise ValueError(\"Fatal error. Dimension of the previous layer is set to None.\")\n\n prev_channels = prev_layer.channels\n prev_layer_height = prev_layer.layer_dim[0]\n prev_layer_width = prev_layer.layer_dim[1]\n\n kernel_shape = this_layer.kernel_shape # 0:height, 1:width\n channels = this_layer.channels\n strides = this_layer.strides\n use_padding = this_layer.use_padding\n kernel_height = kernel_shape[0]\n kernel_width = kernel_shape[1]\n padding_height = (kernel_shape[0] // 2) * 2\n padding_width = (kernel_shape[1] // 2) * 2\n\n target_height = (prev_layer_height + padding_height - kernel_height) // strides[0] + 1\n target_width = (prev_layer_width + padding_width - kernel_width) // strides[1] + 1\n\n this_layer.layer_dim = (target_height, target_width, channels)\n this_layer.num_units = target_height * target_width * channels\n\n if self.weight_parameter is None:\n w = np.random.randn(kernel_shape[0], kernel_shape[1], prev_channels, channels) * 0.01\n else:\n if self.weight_parameter.init_type == wparam.NORMAL:\n w = np.random.normal(self.weight_parameter.mean, self.weight_parameter.stddev,\n (kernel_shape[0], kernel_shape[1], prev_channels,\n channels)) * self.weight_parameter.multiplier\n elif self.weight_parameter.init_type == wparam.UNIFORM:\n w = np.random.uniform(self.weight_parameter.mean, self.weight_parameter.stddev,\n (kernel_shape[0], kernel_shape[1], prev_channels,\n channels)) * self.weight_parameter.multiplier\n elif self.weight_parameter.init_type == wparam.ZERO:\n w = np.zeros((kernel_shape[0], kernel_shape[1], prev_channels, channels))\n\n # Bias\n if self.bias_parameter is None:\n b = np.zeros((channels))\n else:\n if self.bias_parameter.init_type == wparam.NORMAL:\n b = np.random.normal(self.bias_parameter.mean, self.bias_parameter.stddev,\n (channels)) * self.bias_parameter.multiplier\n elif self.bias_parameter.init_type == wparam.UNIFORM:\n b = np.random.uniform(self.bias_parameter.mean, self.bias_parameter.stddev,\n (channels)) * self.bias_parameter.multiplier\n elif self.bias_parameter.init_type == wparam.ZERO:\n b = np.zeros((channels))\n\n self.weight.append(w)\n self.gradient_weight.append(np.zeros(w.shape))\n\n self.bias.append(b)\n self.gradient_bias.append(np.zeros(b.shape))\n\n if self.optimizer == opt.ADAM:\n self.mt_weight.append(np.zeros(w.shape))\n self.mt_bias.append(np.zeros(b.shape))\n self.vt_weight.append(np.zeros(w.shape))\n self.vt_bias.append(np.zeros(b.shape))\n\n def __init__(self, model, cost_function=cf.MEAN_SQUARED_ERROR, learning_rate=0.001, optimizer=opt.BATCH,\n optimizer_settings=None, batch_size=1, use_layer_from=None, weight_parameter=None,\n bias_parameter=None):\n \"\"\"\n Initialize the class.\n\n Parameters\n ----------\n num_units_per_layer: list\n Number of units for each layer including input\n learning_rate: float\n Controls the speed of gradient descent. At the end of each each epoch,\n gradient is multiplied with the learning rate before subtracted from weight.\n optimizer: int\n Optimizer type\n Optimizer settings: Optimizer parameters object\n Optimizer parameters\n batch_size: int\n Size of the batch\n use_layer_from: list\n Dictionary containing a list of objects to share one or more layers with in the read-only mode.\n Namely, during the backprop of this object, weights on those layers will not be updated.\n\n Example:\n use_layer_from=[{\"model\": nn_discriminator,\n \"layer_map\": [{\"from\": 3, \"to\": 1},\n {\"from\": 4, \"to\": 2}]}],\n\n Use nn_discriminator object's 3rd and 4th layers as the 1st and 2nd layer of this model.\n weight_parameter: WeightParameter\n Contains parameters to initialize layer weights\n bias_parameter: WeightParameter\n Contains parameters to initialize layer biases\n \"\"\"\n self.mode = NeuralNetwork.MODE_FIT\n self.model = model\n self.optimizer = optimizer\n self.optimizer_settings = optimizer_settings\n self.cost_function = cost_function\n self.learning_rate = learning_rate\n self._dataset_size = 0 # Dataset size: Size of samples fed to fit(). Dataset size to be initialized in fit()\n self.batch_size = batch_size\n self.use_layer_from = use_layer_from\n self.weight_parameter = weight_parameter\n self.bias_parameter = bias_parameter\n\n self.num_layers = len(model.layers) - 1 # To exclude the input layer\n self._init_weight_forward_prop_data_list()\n\n def _forward_prop(self, x, output_layer_index=-1):\n \"\"\"\n Forward propagation\n\n Parameters\n ----------\n x: ndarray\n Input data\n output_layer_index: int\n 1-based layer index to output. If set to -1, forward prop proceeds to the last layer.\n This is used to output the activation of an intermediate layer.\n\n Returns\n -------\n out: ndarray\n Predicted values\n \"\"\"\n a = x # For the first layer, assign input as the activation\n self.a[0] = a\n\n if output_layer_index != -1:\n loop_count = output_layer_index\n else:\n loop_count = self.num_layers\n\n for i in range(loop_count):\n a = self._forward_prop_one_layer(a, i + 1)\n\n return (a)\n\n # forward prop\n def _forward_prop_one_layer(self, a_prev, current_layer_index):\n \"\"\"\n Forward propagate one layer by applying affine transformation and activation\n\n Parameters\n ----------\n a_prev: ndarray\n Previous layer's activation\n current_layer_index: int\n Index of current layer. Index 0 is input.\n activation: str\n Activation function\n \"\"\"\n\n this_layer = self.model.layers[current_layer_index]\n prev_layer = self.model.layers[current_layer_index-1]\n\n if this_layer.layer_type == LayerType.CONV:\n kernel = self.weight[current_layer_index]\n bias = self.bias[current_layer_index]\n strides = this_layer.strides\n use_padding = this_layer.use_padding\n z = conv.convolve_tensor_dataset_2(a_prev, kernel, bias, strides=strides, use_padding=use_padding)\n\n else: # Dense layer\n # Affine transformation\n # z = a_prev.dot(self.weight[current_layer_index]) + self.bias[current_layer_index]\n\n if prev_layer.dropout != 1.0:\n if self.mode == NeuralNetwork.MODE_FIT:\n num_activation_prev = self.dropout_vector[current_layer_index-1].shape[0]\n dropout = prev_layer.dropout\n num_units_to_drop = int(num_activation_prev * (1-dropout))\n index_of_units_to_drop = np.random.choice(num_activation_prev, num_units_to_drop)\n dropout_vector = np.ones((num_activation_prev)) # reset to 1 first\n dropout_vector[index_of_units_to_drop] = 0\n self.dropout_vector[current_layer_index - 1] = dropout_vector\n a_prev_tilda = a_prev * self.dropout_vector[current_layer_index - 1]\n else: # if predict, use all nodes but multiply by the dropout\n a_prev_tilda = a_prev * prev_layer.dropout\n else:\n a_prev_tilda = a_prev\n\n z = forward_prop_affine_transform(a_prev_tilda, self.weight[current_layer_index], self.bias[current_layer_index])\n\n self.z[current_layer_index] = z\n\n # Activation\n if this_layer.activation == af.SIGMOID:\n a = af.sigmoid(z)\n elif this_layer.activation == af.RELU:\n a = af.relu(z)\n elif this_layer.activation == af.LEAKY_RELU:\n a = af.leaky_relu(z)\n else:\n a = af.none(z)\n\n if this_layer.layer_type == LayerType.CONV and this_layer.flatten == True:\n a_shape = a.shape\n a = a.reshape((a_shape[0], a_shape[1] * a_shape[2] * a_shape[3]))\n\n self.a[current_layer_index] = a\n\n return (a)\n\n def predict(self, x):\n \"\"\"\n Predict based on the input x\n\n Parameters\n ----------\n x: ndarray\n Input data\n\n Returns\n -------\n out: ndarray\n Predicted values\n \"\"\"\n self.mode = NeuralNetwork.MODE_PREDICT\n return self._forward_prop(x)\n\n def predict_intermediate(self, x, output_layer_index):\n \"\"\"\n Feedforward up to the layer specified.\n\n Parameters\n ----------\n x: ndarray\n Input data\n output_layer_index: int\n 1-based layer index to output. If set to -1, forward prop proceeds to the last layer.\n This is used to output the activation of an intermediate layer.\n\n Returns\n -------\n out: ndarray\n Predicted values\n \"\"\"\n return self._forward_prop(x, output_layer_index)\n\n def _backprop(self, x, y, y_hat):\n \"\"\"\n Backpropagation\n\n x: ndarray\n Input\n y: ndarray\n Ground-truth\n y_hat: ndarray\n Predicted values\n\n Notes\n -----\n Gradient is calculated using the multivariable chain rule.\n A variable 'derivative_cumulative' carries this over from the last layer all the way to the first layer.\n \"\"\"\n\n dj_wrt_a = self.derivative_j_wrt_a(y, y_hat, cost_function=self.cost_function)\n derivative_cumulative = dj_wrt_a\n\n for i in range(self.num_layers):\n derivative_cumulative = self._backprop_one_layer(derivative_cumulative, self.num_layers - i)\n\n self._update_weight()\n\n def _backprop_one_layer(self, derivative_cumulative, layer_index):\n \"\"\"\n Backpropagate one layer\n\n derivative_cumulative: ndarray\n Accumulated derivative from the last layer in the network.\n At the entry point of this method, the shape of the array\n is the same as the shape of the layer (dataset size by the number of units for the layer).\n layer_index: int\n Current layer index\n\n Returns\n -------\n derivative_cumulative: ndarray\n Updated accumulated derivative from the last layer\n\n \"\"\"\n\n current_batch_size = derivative_cumulative.shape[0]\n\n log.debug(\"Backprop: Layer index: %d\" % (layer_index))\n\n if layer_index <= self.num_layers - 1: # for a 3 layer network, if index <= 2\n above_layer = self.model.layers[layer_index + 1]\n else:\n above_layer = None\n\n this_layer = self.model.layers[layer_index]\n prev_layer = self.model.layers[layer_index-1]\n\n if this_layer.layer_type == LayerType.CONV:\n if above_layer is None:\n raise ValueError(\"Unexpected value for above layer. Value is None.\")\n\n if above_layer.layer_type == LayerType.DENSE:\n derivative_cumulative = derivative_cumulative.reshape(\n (derivative_cumulative.shape[0], this_layer.layer_dim[0],\n this_layer.layer_dim[1],\n this_layer.layer_dim[2]\n ))\n\n # Derivative of a with respect to z\n if this_layer.activation == af.SIGMOID:\n pa_pz = self.sigmoid_derivative_with_z(layer_index)\n elif this_layer.activation == af.RELU:\n pa_pz = self.relu_derivative_with_z(layer_index)\n elif this_layer.activation == af.LEAKY_RELU:\n pa_pz = self.leaky_relu_derivative_with_z(layer_index)\n else:\n pa_pz = self.none_derivative_with_z(layer_index)\n\n cumulative_derivative_to_z = derivative_cumulative * pa_pz\n # Note that the shape is still the same as current layer.\n\n # Derivative of z with respect to weight\n if this_layer.layer_type == LayerType.DENSE:\n pz_pw = self.partial_z_wrt_partial_w(layer_index)\n cumulative_derivative_to_w = pz_pw.T.dot(cumulative_derivative_to_z)\n\n # At this point, shape of cumulative_derivative_to_w is the same as the weight of this layer\n cumulative_derivative_to_w /= current_batch_size\n self.gradient_weight[layer_index] = cumulative_derivative_to_w\n\n # Derivative of z with respect to bias\n pz_pb = self.partial_z_wrt_partial_b(layer_index)\n cumulative_derivative_to_b = np.sum(cumulative_derivative_to_z * pz_pb, axis=0)\n # At this point, shape of cumulative_derivative_to_b is the same as the bias of this layer\n\n cumulative_derivative_to_b /= current_batch_size\n self.gradient_bias[layer_index] = cumulative_derivative_to_b\n\n # Derivative of z with respect to previous layer's activation\n pz_pa_prev = self.partial_z_wrt_partial_a_prev(layer_index)\n\n cumulative_derivative_to_a_prev = cumulative_derivative_to_z.dot(pz_pa_prev.T)\n\n if prev_layer.dropout != 1.0:\n dropout_vector = self.dropout_vector[layer_index - 1]\n cumulative_derivative_to_a_prev *= dropout_vector\n\n else: # if Conv\n \"\"\"\n See refer to my documentation to see how these calculations are derived: \n https://hideyukiinada.github.io/cnn_backprop_strides2.html\n \"\"\"\n\n # Calculate ∂L/∂a_prev\n # Step 1. Interweave ∂L/∂z with zeros\n # Determine the number of output channels\n channels = cumulative_derivative_to_z.shape[3]\n # dataset_size = cumulative_derivative_to_z.shape[0]\n h = cumulative_derivative_to_z.shape[1]\n w = cumulative_derivative_to_z.shape[2]\n strides = this_layer.strides[0] # FIXME for non-square matrix\n if strides > 1:\n # l1 = list()\n # for i in range(dataset_size):\n # l2 = list()\n # for c in range(channels): # shape = (dataset_size, h, w)\n # padded = conv.zero_interweave(cumulative_derivative_to_z[i, :, :, c], strides - 1)\n # l2.append(padded)\n #\n # l2np = np.array(l2)\n # l2combined = np.concatenate((l2np), axis=2)\n # l2stacked = l2combined.reshape((h * 2, w * 2, channels))\n # l1.append(l2stacked)\n #\n # l1np = np.array(l1)\n # l1combined = np.concatenate((l1np),axis=0)\n # partial_l_partial_z_interweaved = l1combined.reshape((dataset_size, h * 2, w * 2, channels))\n\n partial_l_partial_z_interweaved = conv.zero_interweave_dataset(cumulative_derivative_to_z, strides - 1)\n\n else: # if strides == 1\n partial_l_partial_z_interweaved = cumulative_derivative_to_z\n\n # Step 2. Zeropad\n # This step is done in convolve_tensor_dataset_back_2()\n\n # Step 3. Flip W vertically and horizontally\n weights = self.weight[layer_index]\n weights_flipped = conv.flip_weight(weights)\n\n # Convolute partial_l_partial_z_padded * weights_flipped\n cumulative_derivative_to_a_prev = conv.convolve_tensor_dataset_back_2(partial_l_partial_z_interweaved,\n weights_flipped, use_padding=True)\n\n # Calculate Calculate ∂L/∂W\n # Step 1. Interweave ∂L/∂z with zeros\n # Reuse partial_l_partial_z_interweaved\n\n # Step 2. Zero-pad a_prev\n a_prev = self.a[layer_index - 1]\n kernel_width = self.gradient_weight[layer_index].shape[0]\n kernel_height = self.gradient_weight[layer_index].shape[0]\n pad_h = kernel_height // 2\n pad_w = kernel_width // 2\n\n # Step 3. Convolve two matrices\n cumulative_derivative_to_w = conv.convolve_two_datasets_calc_mean(a_prev,\n partial_l_partial_z_interweaved,\n use_padding=True, padding=(pad_h, pad_w))\n self.gradient_weight[layer_index] = cumulative_derivative_to_w\n\n # Calculate Calculate ∂L/∂bias\n pz_pb = 1.0\n cumulative_derivative_to_b = np.sum(cumulative_derivative_to_z * pz_pb)\n cumulative_derivative_to_b /= current_batch_size\n self.gradient_bias[layer_index] = cumulative_derivative_to_b\n\n return cumulative_derivative_to_a_prev # Shape is the same as the previous layer's activation.\n\n def _update_weight(self):\n \"\"\"\n Update weight and bias of the network by subtracting the gradient of weight and bias multiplied by the learning\n rate.\n \"\"\"\n for i in range(self.num_layers):\n\n layer_index = self.num_layers - i\n\n if self.optimizer == opt.ADAM:\n beta1 = self.optimizer_settings.beta1\n beta2 = self.optimizer_settings.beta2\n beta1_to_t = self.optimizer_settings.beta1_to_t\n beta2_to_t = self.optimizer_settings.beta2_to_t\n epsilon = self.optimizer_settings.epsilon\n\n self.mt_weight[layer_index] = beta1 * self.mt_weight[layer_index] + \\\n (1 - beta1) * self.gradient_weight[layer_index]\n\n self.vt_weight[layer_index] = beta2 * self.vt_weight[layer_index] + \\\n (1 - beta2) * self.gradient_weight[layer_index] ** 2\n\n self.mt_bias[layer_index] = beta1 * self.mt_bias[layer_index] + \\\n (1 - beta1) * self.gradient_bias[layer_index]\n\n self.vt_bias[layer_index] = beta2 * self.vt_bias[layer_index] + \\\n (1 - beta2) * self.gradient_bias[layer_index] ** 2\n\n mt_weight_hat = self.mt_weight[layer_index] / (1.0 - beta1_to_t)\n vt_weight_hat = self.vt_weight[layer_index] / (1.0 - beta2_to_t)\n\n mt_bias_hat = self.mt_bias[layer_index] / (1.0 - beta1_to_t)\n vt_bias_hat = self.vt_bias[layer_index] / (1.0 - beta2_to_t)\n\n if self.layer_locked[layer_index] is False: # Do not update if the layer is borrowed from other model.\n self.weight[layer_index] -= self.learning_rate * mt_weight_hat / (\n np.sqrt(vt_weight_hat) + epsilon)\n self.bias[layer_index] -= self.learning_rate * mt_bias_hat / (\n np.sqrt(vt_bias_hat) + epsilon)\n\n else:\n if self.layer_locked[layer_index] is False:\n self.weight[layer_index] -= self.learning_rate * self.gradient_weight[layer_index]\n self.bias[layer_index] -= self.learning_rate * self.gradient_bias[layer_index]\n\n if self.optimizer == opt.ADAM:\n self.optimizer_settings.beta1_to_t *= self.optimizer_settings.beta1\n self.optimizer_settings.beta2_to_t *= self.optimizer_settings.beta2\n\n def fit(self, x, y, epochs, verbose=True, interval=1):\n \"\"\"\n Train the model\n\n Parameters\n ----------\n x: ndarray\n Input\n y: ndarray\n Ground-truth\n epochs: int\n Number of epochs to iterate\n verbose: bool\n Show the cost for each epoch\n interval: int\n Number of epochs to show the cost if verbose is set to true\n \"\"\"\n\n def process_verbose(y, y_hat, batch_index, batch_loop_count, epoch_index, epoch_size, current_batch_size):\n \"\"\"\n Helper function to output cost at regular intervals\n\n Parameters\n ----------\n y: ndarray\n Ground-truth\n y_hat: ndarray\n Predicted values\n batch_index: int\n 0-based batch index within the current epoch\n batch_loop_count: int\n Total number of batch loops within a epoch\n epoch_index: int\n 0-based epoch index\n epoch_size: int\n Number of epochs\n current_batch_size : int\n Dataset size in this batch\n \"\"\"\n cost = -1\n if self.cost_function == cf.CROSS_ENTROPY:\n cost = cf.mean_cross_entropy(y, y_hat)\n elif self.cost_function == cf.MEAN_SQUARED_ERROR:\n cost = cf.mean_squared_error(y, y_hat)\n\n if (self.batch_size >= 32):\n print(\"[Epoch %d/%d - Batch %d/%d] Cost: %.07f. Batch size: %d\" %\n (epoch_index + 1, epoch_size, batch_index + 1, batch_loop_count, cost, current_batch_size ))\n else:\n if (batch_index % 100 == 0):\n print(\"[Epoch %d/%d - Batch %d/%d] Cost: %.07f. Batch size: %d\" %\n (epoch_index + 1, epoch_size, batch_index + 1, batch_loop_count, cost, current_batch_size ))\n\n\n self._dataset_size = x.shape[0]\n self.mode = NeuralNetwork.MODE_FIT\n\n # check to see if we should use layers from other object\n if self.use_layer_from is not None:\n for other_object in self.use_layer_from:\n other_model = other_object[\"model\"]\n\n mappings = other_object[\"layer_map\"]\n\n for mapping in mappings:\n source = mapping[\"from\"]\n target = mapping[\"to\"]\n\n # print(\"Using layer %d from other model as this model's layer %d\" % (source, target))\n\n self.weight[target] = other_model.weight[source]\n self.bias[target] = other_model.bias[source]\n self.layer_locked[target] = True\n\n if self.optimizer in [opt.SGD, opt.ADAM]:\n\n if self.optimizer == opt.ADAM:\n self.optimizer_settings.beta1_to_t = self.optimizer_settings.beta1\n self.optimizer_settings.beta2_to_t = self.optimizer_settings.beta2\n\n for i in range(epochs):\n\n next_k = 0\n loop_count = int(self._dataset_size / self.batch_size) # for m = 5, batch_size = 2, this results in [0, 1]\n current_batch_size = 0\n for j in range(loop_count):\n\n current_batch_size = self.batch_size\n k = j * current_batch_size\n next_k = k + current_batch_size\n x_sub = x[k:next_k]\n y_sub = y[k:next_k]\n y_hat = self._forward_prop(x_sub)\n\n if verbose:\n process_verbose(y_sub, y_hat, j, loop_count, i, epochs, current_batch_size )\n\n self._backprop(x_sub, y_sub, y_hat)\n\n # remainder\n last_batch_size = x.shape[0] - next_k\n if last_batch_size > 0:\n k = next_k\n x_sub = x[k:k + last_batch_size ]\n y_sub = y[k:k + last_batch_size ]\n y_hat = self._forward_prop(x_sub)\n\n if verbose:\n process_verbose(y_sub, y_hat, j + 1, loop_count + 1, i, epochs, last_batch_size )\n\n self._backprop(x_sub, y_sub, y_hat)\n\n else: # Batch gradient\n current_batch_size = x.shape[0]\n\n for i in range(epochs):\n y_hat = self._forward_prop(x)\n\n if verbose:\n if self.cost_function == cf.CROSS_ENTROPY:\n cost = cf.mean_cross_entropy(y, y_hat)\n elif self.cost_function == cf.MEAN_SQUARED_ERROR:\n cost = cf.mean_squared_error(y, y_hat)\n\n if ((i + 1) % interval == 0):\n print(\"[%d/%d epochs] Cost: %.07f\" % (i + 1, epochs, cost))\n\n self._backprop(x, y, y_hat)\n\n # Partial derivatives\n def derivative_j_wrt_a(self, y, y_hat, cost_function):\n \"\"\"\n Calculate the derivative of cost with respect to y hat (or the activation of the last layer).\n\n Parameters\n ----------\n y: ndarray\n Ground-truth\n y_hat: ndarray\n Predicted values\n\n Returns\n -------\n out: ndarray\n The partial derivative of cost with respect to y hat\n\n Raises\n ------\n ValueError\n If unsupported cost function is specified\n \"\"\"\n if cost_function == cf.CROSS_ENTROPY:\n d = cf.d_cross_entropy(y, y_hat)\n elif cost_function == cf.MEAN_SQUARED_ERROR:\n d = cf.d_squared_error(y, y_hat)\n else:\n raise ValueError(\"Unsupported cost function\")\n\n return (d) # we will multiply by 1/m later\n\n def sigmoid_derivative_with_z(self, layer_index):\n \"\"\"\n Calculate the derivative of activation using the value of z used in forward prop.\n\n Parameters\n ----------\n layer_index: int\n Layer index to be used in retrieving the value of z\n\n Returns\n -------\n out: ndarray\n Partial derivative of a with respect to z\n \"\"\"\n return af.d_sigmoid(self.z[layer_index])\n\n def relu_derivative_with_z(self, layer_index):\n \"\"\"\n Calculate the derivative of activation using the value of z used in forward prop.\n\n Parameters\n ----------\n layer_index: int\n Layer index to be used in retrieving the value of z\n\n Returns\n -------\n out: ndarray\n Partial derivative of a with respect to z\n \"\"\"\n return af.d_relu(self.z[layer_index])\n\n def leaky_relu_derivative_with_z(self, layer_index):\n \"\"\"\n Calculate the derivative of activation using the value of z used in forward prop.\n\n Parameters\n ----------\n layer_index: int\n Layer index to be used in retrieving the value of z\n\n Returns\n -------\n out: ndarray\n Partial derivative of a with respect to z\n \"\"\"\n return af.d_leaky_relu(self.z[layer_index])\n\n def none_derivative_with_z(self, layer_index):\n \"\"\"\n Dummy derivative function to return 1.\n\n Parameters\n ----------\n layer_index: int\n Layer index to be used in retrieving the value of z\n\n Returns\n -------\n out: ndarray\n Partial derivative of a with respect to z\n \"\"\"\n return af.d_none(self.z[layer_index])\n\n def partial_z_wrt_partial_w(self, current_layer_index):\n \"\"\"\n Calculate the partial derivative of z with respect to weight.\n\n Parameters\n ----------\n layer_index: int\n Layer index to be used in retrieving the value of z\n\n Returns\n -------\n out: ndarray\n Partial derivative of z with respect to weight\n\n Notes\n -----\n Since z = w a_prev + b, the partial derivative is a_prev.\n \"\"\"\n a_prev = self.a[current_layer_index - 1]\n return a_prev\n\n def partial_z_wrt_partial_a_prev(self, current_layer_index):\n \"\"\"\n Calculate the partial derivative of z with respect to activation of the last layer.\n\n Parameters\n ----------\n layer_index: int\n Layer index to be used in retrieving the value of z\n\n Returns\n -------\n out: ndarray\n Partial derivative of z with respect to activation of the last layer\n\n Notes\n -----\n Since z = w a_prev + b, the partial derivative is z.\n \"\"\"\n w = self.weight[current_layer_index]\n return w\n\n def partial_z_wrt_partial_b(self, current_layer_index):\n \"\"\"\n Calculate the partial derivative of z with respect to bias.\n\n Parameters\n ----------\n layer_index: int\n Layer index. Not currently used.\n\n Returns\n -------\n out: ndarray\n Partial derivative of z with respect to bias\n\n Notes\n -----\n Since z = w a_prev + b, the partial derivative is 1.\n \"\"\"\n return 1\n\n # Loading and saving weights\n def load(self, file_path):\n \"\"\"\n Load the matrix weight from a file specified with file_path.\n\n Parameters\n ---------\n file_path: Pathlib.path\n Path to save the weights\n\n Returns\n -------\n Weights of the model\n\n Raises\n ------\n File not found\n \"\"\"\n weight, bias = wp.load(file_path)\n\n self.weight = weight\n self.bias = bias\n\n def save(self, file_path):\n \"\"\"\n Save the matrix weight in a file specified by file_path.\n\n Parameters\n ----------\n file_path: Pathlib.path\n Path to save the weights\n \"\"\"\n\n # index corresponds to a layer. layer 0 does not have weight, but wp is aware of this.\n wp.save(file_path,\n {\n \"weight\": self.weight,\n \"bias\": self.bias\n }\n )\n" ]
[ [ "numpy.sqrt", "numpy.random.choice", "numpy.ones", "numpy.random.normal", "numpy.random.randn", "numpy.random.uniform", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ualsbombe/mne-python
[ "d02ac81019cec662dd8245c167f6657e57ec44a3", "d02ac81019cec662dd8245c167f6657e57ec44a3" ]
[ "mne/preprocessing/ica.py", "mne/connectivity/spectral.py" ]
[ "# -*- coding: utf-8 -*-\n#\n# Authors: Denis A. Engemann <[email protected]>\n# Alexandre Gramfort <[email protected]>\n# Juergen Dammers <[email protected]>\n#\n# License: BSD (3-clause)\n\nfrom inspect import isfunction\nfrom collections import namedtuple\nfrom copy import deepcopy\nfrom numbers import Integral\nfrom time import time\n\nimport math\nimport os\nimport json\n\nimport numpy as np\n\nfrom .ecg import (qrs_detector, _get_ecg_channel_index, _make_ecg,\n create_ecg_epochs)\nfrom .eog import _find_eog_events, _get_eog_channel_index\nfrom .infomax_ import infomax\n\nfrom ..cov import compute_whitener\nfrom .. import Covariance, Evoked\nfrom ..io.pick import (pick_types, pick_channels, pick_info,\n _picks_to_idx, _get_channel_types, _DATA_CH_TYPES_SPLIT)\nfrom ..io.proj import make_projector\nfrom ..io.write import (write_double_matrix, write_string,\n write_name_list, write_int, start_block,\n end_block)\nfrom ..io.tree import dir_tree_find\nfrom ..io.open import fiff_open\nfrom ..io.tag import read_tag\nfrom ..io.meas_info import write_meas_info, read_meas_info\nfrom ..io.constants import FIFF\nfrom ..io.base import BaseRaw\nfrom ..io.eeglab.eeglab import _get_info, _check_load_mat\n\nfrom ..epochs import BaseEpochs\nfrom ..viz import (plot_ica_components, plot_ica_scores,\n plot_ica_sources, plot_ica_overlay)\nfrom ..viz.ica import plot_ica_properties\nfrom ..viz.topomap import _plot_corrmap\n\nfrom ..channels.channels import _contains_ch_type, ContainsMixin\nfrom ..io.write import start_file, end_file, write_id\nfrom ..utils import (check_version, logger, check_fname, verbose,\n _reject_data_segments, check_random_state, _validate_type,\n compute_corr, _get_inst_data, _ensure_int,\n copy_function_doc_to_method_doc, _pl, warn, Bunch,\n _check_preload, _check_compensation_grade, fill_doc,\n _check_option, _PCA, int_like,\n _check_all_same_channel_names)\n\nfrom ..fixes import _get_args, _safe_svd\nfrom ..filter import filter_data\nfrom .bads import _find_outliers\nfrom .ctps_ import ctps\nfrom ..io.pick import pick_channels_regexp\n\n__all__ = ('ICA', 'ica_find_ecg_events', 'ica_find_eog_events',\n 'get_score_funcs', 'read_ica', 'read_ica_eeglab')\n\n\ndef _make_xy_sfunc(func, ndim_output=False):\n \"\"\"Aux function.\"\"\"\n if ndim_output:\n def sfunc(x, y):\n return np.array([func(a, y.ravel()) for a in x])[:, 0]\n else:\n def sfunc(x, y):\n return np.array([func(a, y.ravel()) for a in x])\n sfunc.__name__ = '.'.join(['score_func', func.__module__, func.__name__])\n sfunc.__doc__ = func.__doc__\n return sfunc\n\n\n# Violate our assumption that the output is 1D so can't be used.\n# Could eventually be added but probably not worth the effort unless someone\n# requests it.\n_BLOCKLIST = {'somersd'}\n\n\n# makes score funcs attr accessible for users\ndef get_score_funcs():\n \"\"\"Get the score functions.\n\n Returns\n -------\n score_funcs : dict\n The score functions.\n \"\"\"\n from scipy import stats\n from scipy.spatial import distance\n score_funcs = Bunch()\n xy_arg_dist_funcs = [(n, f) for n, f in vars(distance).items()\n if isfunction(f) and not n.startswith('_') and\n n not in _BLOCKLIST]\n xy_arg_stats_funcs = [(n, f) for n, f in vars(stats).items()\n if isfunction(f) and not n.startswith('_') and\n n not in _BLOCKLIST]\n score_funcs.update({n: _make_xy_sfunc(f)\n for n, f in xy_arg_dist_funcs\n if _get_args(f) == ['u', 'v']})\n score_funcs.update({n: _make_xy_sfunc(f, ndim_output=True)\n for n, f in xy_arg_stats_funcs\n if _get_args(f) == ['x', 'y']})\n return score_funcs\n\n\ndef _check_for_unsupported_ica_channels(picks, info, allow_ref_meg=False):\n \"\"\"Check for channels in picks that are not considered valid channels.\n\n Accepted channels are the data channels\n ('seeg', 'dbs', 'ecog', 'eeg', 'hbo', 'hbr', 'mag', and 'grad'), 'eog'\n and 'ref_meg'.\n This prevents the program from crashing without\n feedback when a bad channel is provided to ICA whitening.\n \"\"\"\n types = _DATA_CH_TYPES_SPLIT + ('eog',)\n types += ('ref_meg',) if allow_ref_meg else ()\n chs = _get_channel_types(info, picks, unique=True, only_data_chs=False)\n check = all([ch in types for ch in chs])\n if not check:\n raise ValueError('Invalid channel type%s passed for ICA: %s.'\n 'Only the following types are supported: %s'\n % (_pl(chs), chs, types))\n\n\n_KNOWN_ICA_METHODS = ('fastica', 'infomax', 'picard')\n\n\n@fill_doc\nclass ICA(ContainsMixin):\n u\"\"\"Data decomposition using Independent Component Analysis (ICA).\n\n This object estimates independent components from :class:`mne.io.Raw`,\n :class:`mne.Epochs`, or :class:`mne.Evoked` objects. Components can\n optionally be removed (for artifact repair) prior to signal reconstruction.\n\n .. warning:: ICA is sensitive to low-frequency drifts and therefore\n requires the data to be high-pass filtered prior to fitting.\n Typically, a cutoff frequency of 1 Hz is recommended.\n\n Parameters\n ----------\n n_components : int | float | None\n Number of principal components (from the pre-whitening PCA step) that\n are passed to the ICA algorithm during fitting:\n\n - :class:`int`\n Must be greater than 1 and less than or equal to the number of\n channels.\n - :class:`float` between 0 and 1 (exclusive)\n Will select the smallest number of components required to explain\n the cumulative variance of the data greater than ``n_components``.\n Consider this hypothetical example: we have 3 components, the first\n explaining 70%%, the second 20%%, and the third the remaining 10%%\n of the variance. Passing 0.8 here (corresponding to 80%% of\n explained variance) would yield the first two components,\n explaining 90%% of the variance: only by using both components the\n requested threshold of 80%% explained variance can be exceeded. The\n third component, on the other hand, would be excluded.\n - ``None``\n ``0.999999`` will be used. This is done to avoid numerical\n stability problems when whitening, particularly when working with\n rank-deficient data.\n\n Defaults to ``None``. The actual number used when executing the\n :meth:`ICA.fit` method will be stored in the attribute\n ``n_components_`` (note the trailing underscore).\n\n .. versionchanged:: 0.22\n For a :class:`python:float`, the number of components will account\n for *greater than* the given variance level instead of *less than or\n equal to* it. The default (None) will also take into account the\n rank deficiency of the data.\n noise_cov : None | instance of Covariance\n Noise covariance used for pre-whitening. If None (default), channels\n are scaled to unit variance (\"z-standardized\") as a group by channel\n type prior to the whitening by PCA.\n %(random_state)s\n As estimation can be non-deterministic it can be useful to fix the\n random state to have reproducible results.\n method : {'fastica', 'infomax', 'picard'}\n The ICA method to use in the fit method. Use the fit_params argument to\n set additional parameters. Specifically, if you want Extended Infomax,\n set method='infomax' and fit_params=dict(extended=True) (this also\n works for method='picard'). Defaults to 'fastica'. For reference, see\n :footcite:`Hyvarinen1999,BellSejnowski1995,LeeEtAl1999,AblinEtAl2018`.\n fit_params : dict | None\n Additional parameters passed to the ICA estimator as specified by\n ``method``.\n max_iter : int\n Maximum number of iterations during fit. Defaults to 200. The actual\n number of iterations it took :meth:`ICA.fit` to complete will be stored\n in the ``n_iter_`` attribute.\n allow_ref_meg : bool\n Allow ICA on MEG reference channels. Defaults to False.\n\n .. versionadded:: 0.18\n %(verbose)s\n\n Attributes\n ----------\n current_fit : str\n Flag informing about which data type (raw or epochs) was used for the\n fit.\n ch_names : list-like\n Channel names resulting from initial picking.\n n_components_ : int\n If fit, the actual number of PCA components used for ICA decomposition.\n pre_whitener_ : ndarray, shape (n_channels, 1) or (n_channels, n_channels)\n If fit, array used to pre-whiten the data prior to PCA.\n pca_components_ : ndarray, shape ``(n_channels, n_channels)``\n If fit, the PCA components.\n pca_mean_ : ndarray, shape (n_channels,)\n If fit, the mean vector used to center the data before doing the PCA.\n pca_explained_variance_ : ndarray, shape ``(n_channels,)``\n If fit, the variance explained by each PCA component.\n mixing_matrix_ : ndarray, shape ``(n_components_, n_components_)``\n If fit, the whitened mixing matrix to go back from ICA space to PCA\n space.\n It is, in combination with the ``pca_components_``, used by\n :meth:`ICA.apply` and :meth:`ICA.get_components` to re-mix/project\n a subset of the ICA components into the observed channel space.\n The former method also removes the pre-whitening (z-scaling) and the\n de-meaning.\n unmixing_matrix_ : ndarray, shape ``(n_components_, n_components_)``\n If fit, the whitened matrix to go from PCA space to ICA space.\n Used, in combination with the ``pca_components_``, by the methods\n :meth:`ICA.get_sources` and :meth:`ICA.apply` to unmix the observed\n data.\n exclude : array-like of int\n List or np.array of sources indices to exclude when re-mixing the data\n in the :meth:`ICA.apply` method, i.e. artifactual ICA components.\n The components identified manually and by the various automatic\n artifact detection methods should be (manually) appended\n (e.g. ``ica.exclude.extend(eog_inds)``).\n (There is also an ``exclude`` parameter in the :meth:`ICA.apply`\n method.) To scrap all marked components, set this attribute to an empty\n list.\n info : None | instance of Info\n The measurement info copied from the object fitted.\n n_samples_ : int\n The number of samples used on fit.\n labels_ : dict\n A dictionary of independent component indices, grouped by types of\n independent components. This attribute is set by some of the artifact\n detection functions.\n n_iter_ : int\n If fit, the number of iterations required to complete ICA.\n\n Notes\n -----\n A trailing ``_`` in an attribute name signifies that the attribute was\n added to the object during fitting, consistent with standard scikit-learn\n practice.\n\n ICA :meth:`fit` in MNE proceeds in two steps:\n\n 1. :term:`Whitening <whitening>` the data by means of a pre-whitening step\n (using ``noise_cov`` if provided, or the standard deviation of each\n channel type) and then principal component analysis (PCA).\n 2. Passing the ``n_components`` largest-variance components to the ICA\n algorithm to obtain the unmixing matrix (and by pseudoinversion, the\n mixing matrix).\n\n ICA :meth:`apply` then:\n\n 1. Unmixes the data with the ``unmixing_matrix_``.\n 2. Includes ICA components based on ``ica.include`` and ``ica.exclude``.\n 3. Re-mixes the data with ``mixing_matrix_``.\n 4. Restores any data not passed to the ICA algorithm, i.e., the PCA\n components between ``n_components`` and ``n_pca_components``.\n\n ``n_pca_components`` determines how many PCA components will be kept when\n reconstructing the data when calling :meth:`apply`. This parameter can be\n used for dimensionality reduction of the data, or dealing with low-rank\n data (such as those with projections, or MEG data processed by SSS). It is\n important to remove any numerically-zero-variance components in the data,\n otherwise numerical instability causes problems when computing the mixing\n matrix. Alternatively, using ``n_components`` as a float will also avoid\n numerical stability problems.\n\n The ``n_components`` parameter determines how many components out of\n the ``n_channels`` PCA components the ICA algorithm will actually fit.\n This is not typically used for EEG data, but for MEG data, it's common to\n use ``n_components < n_channels``. For example, full-rank\n 306-channel MEG data might use ``n_components=40`` to find (and\n later exclude) only large, dominating artifacts in the data, but still\n reconstruct the data using all 306 PCA components. Setting\n ``n_pca_components=40``, on the other hand, would actually reduce the\n rank of the reconstructed data to 40, which is typically undesirable.\n\n If you are migrating from EEGLAB and intend to reduce dimensionality via\n PCA, similarly to EEGLAB's ``runica(..., 'pca', n)`` functionality,\n pass ``n_components=n`` during initialization and then\n ``n_pca_components=n`` during :meth:`apply`. The resulting reconstructed\n data after :meth:`apply` will have rank ``n``.\n\n .. note:: Commonly used for reasons of i) computational efficiency and\n ii) additional noise reduction, it is a matter of current debate\n whether pre-ICA dimensionality reduction could decrease the\n reliability and stability of the ICA, at least for EEG data and\n especially during preprocessing :footcite:`ArtoniEtAl2018`.\n (But see also :footcite:`Montoya-MartinezEtAl2017` for a\n possibly confounding effect of the different whitening/sphering\n methods used in this paper (ZCA vs. PCA).)\n On the other hand, for rank-deficient data such as EEG data after\n average reference or interpolation, it is recommended to reduce\n the dimensionality (by 1 for average reference and 1 for each\n interpolated channel) for optimal ICA performance (see the\n `EEGLAB wiki <eeglab_wiki_>`_).\n\n Caveat! If supplying a noise covariance, keep track of the projections\n available in the cov or in the raw object. For example, if you are\n interested in EOG or ECG artifacts, EOG and ECG projections should be\n temporally removed before fitting ICA, for example::\n\n >> projs, raw.info['projs'] = raw.info['projs'], []\n >> ica.fit(raw)\n >> raw.info['projs'] = projs\n\n Methods currently implemented are FastICA (default), Infomax, and Picard.\n Standard Infomax can be quite sensitive to differences in floating point\n arithmetic. Extended Infomax seems to be more stable in this respect,\n enhancing reproducibility and stability of results; use Extended Infomax\n via ``method='infomax', fit_params=dict(extended=True)``. Allowed entries\n in ``fit_params`` are determined by the various algorithm implementations:\n see :class:`~sklearn.decomposition.FastICA`, :func:`~picard.picard`,\n :func:`~mne.preprocessing.infomax`.\n\n .. note:: Picard can be used to solve the same problems as FastICA,\n Infomax, and extended Infomax, but typically converges faster\n than either of those methods. To make use of Picard's speed while\n still obtaining the same solution as with other algorithms, you\n need to specify ``method='picard'`` and ``fit_params`` as a\n dictionary with the following combination of keys:\n\n - ``dict(ortho=False, extended=False)`` for Infomax\n - ``dict(ortho=False, extended=True)`` for extended Infomax\n - ``dict(ortho=True, extended=True)`` for FastICA\n\n Reducing the tolerance (set in ``fit_params``) speeds up estimation at the\n cost of consistency of the obtained results. It is difficult to directly\n compare tolerance levels between Infomax and Picard, but for Picard and\n FastICA a good rule of thumb is ``tol_fastica == tol_picard ** 2``.\n\n .. _eeglab_wiki: https://sccn.ucsd.edu/wiki/Chapter_09:_Decomposing_Data_Using_ICA#Issue:_ICA_returns_near-identical_components_with_opposite_polarities\n\n References\n ----------\n .. footbibliography::\n \"\"\" # noqa: E501\n\n @verbose\n def __init__(self, n_components=None, *, noise_cov=None,\n random_state=None, method='fastica', fit_params=None,\n max_iter=200, allow_ref_meg=False,\n verbose=None): # noqa: D102\n _validate_type(method, str, 'method')\n _validate_type(n_components, (float, 'int-like', None))\n\n if method != 'imported_eeglab': # internal use only\n _check_option('method', method, _KNOWN_ICA_METHODS)\n if method == 'fastica' and not check_version('sklearn'):\n raise ImportError(\n 'The scikit-learn package is required for method=\"fastica\".')\n if method == 'picard' and not check_version('picard'):\n raise ImportError(\n 'The python-picard package is required for method=\"picard\".')\n\n self.noise_cov = noise_cov\n\n for (kind, val) in [('n_components', n_components)]:\n if isinstance(val, float) and not 0 < val < 1:\n raise ValueError('Selecting ICA components by explained '\n 'variance needs values between 0.0 and 1.0 '\n f'(exclusive), got {kind}={val}')\n if isinstance(val, int_like) and val == 1:\n raise ValueError(\n f'Selecting one component with {kind}={val} is not '\n 'supported')\n\n self.current_fit = 'unfitted'\n self.verbose = verbose\n self.n_components = n_components\n # In newer ICAs this should always be None, but keep it for\n # backward compat with older versions of MNE that used it\n self._max_pca_components = None\n self.n_pca_components = None\n self.ch_names = None\n self.random_state = random_state\n\n if fit_params is None:\n fit_params = {}\n fit_params = deepcopy(fit_params) # avoid side effects\n\n if method == 'fastica':\n update = {'algorithm': 'parallel', 'fun': 'logcosh',\n 'fun_args': None}\n fit_params.update({k: v for k, v in update.items() if k\n not in fit_params})\n elif method == 'infomax':\n # extended=True is default in underlying function, but we want\n # default False here unless user specified True:\n fit_params.setdefault('extended', False)\n fit_params.setdefault('max_iter', max_iter)\n self.max_iter = max_iter\n self.fit_params = fit_params\n\n self.exclude = []\n self.info = None\n self.method = method\n self.labels_ = dict()\n self.allow_ref_meg = allow_ref_meg\n\n def __repr__(self):\n \"\"\"ICA fit information.\"\"\"\n if self.current_fit == 'unfitted':\n s = 'no'\n elif self.current_fit == 'raw':\n s = 'raw data'\n else:\n s = 'epochs'\n s += ' decomposition, '\n s += 'fit (%s): %s samples, ' % (self.method,\n str(getattr(self, 'n_samples_', '')))\n s += ('%s components' % str(self.n_components_) if\n hasattr(self, 'n_components_') else\n 'no dimension reduction')\n if self.info is not None:\n ch_fit = ['\"%s\"' % c for c in _DATA_CH_TYPES_SPLIT if c in self]\n s += ', channels used: {}'.format('; '.join(ch_fit))\n if self.exclude:\n s += ', %i sources marked for exclusion' % len(self.exclude)\n\n return '<ICA | %s>' % s\n\n @verbose\n def fit(self, inst, picks=None, start=None, stop=None, decim=None,\n reject=None, flat=None, tstep=2.0, reject_by_annotation=True,\n verbose=None):\n \"\"\"Run the ICA decomposition on raw data.\n\n Caveat! If supplying a noise covariance keep track of the projections\n available in the cov, the raw or the epochs object. For example,\n if you are interested in EOG or ECG artifacts, EOG and ECG projections\n should be temporally removed before fitting the ICA.\n\n Parameters\n ----------\n inst : instance of Raw or Epochs\n Raw measurements to be decomposed.\n %(picks_good_data_noref)s\n This selection remains throughout the initialized ICA solution.\n start : int | float | None\n First sample to include. If float, data will be interpreted as\n time in seconds. If None, data will be used from the first sample.\n stop : int | float | None\n Last sample to not include. If float, data will be interpreted as\n time in seconds. If None, data will be used to the last sample.\n decim : int | None\n Increment for selecting each nth time slice. If None, all samples\n within ``start`` and ``stop`` are used.\n reject : dict | None\n Rejection parameters based on peak-to-peak amplitude.\n Valid keys are 'grad', 'mag', 'eeg', 'seeg', 'dbs', 'ecog', 'eog',\n 'ecg', 'hbo', 'hbr'.\n If reject is None then no rejection is done. Example::\n\n reject = dict(grad=4000e-13, # T / m (gradiometers)\n mag=4e-12, # T (magnetometers)\n eeg=40e-6, # V (EEG channels)\n eog=250e-6 # V (EOG channels)\n )\n\n It only applies if ``inst`` is of type Raw.\n flat : dict | None\n Rejection parameters based on flatness of signal.\n Valid keys are 'grad', 'mag', 'eeg', 'seeg', 'dbs', 'ecog', 'eog',\n 'ecg', 'hbo', 'hbr'.\n Values are floats that set the minimum acceptable peak-to-peak\n amplitude. If flat is None then no rejection is done.\n It only applies if ``inst`` is of type Raw.\n tstep : float\n Length of data chunks for artifact rejection in seconds.\n It only applies if ``inst`` is of type Raw.\n %(reject_by_annotation_raw)s\n\n .. versionadded:: 0.14.0\n %(verbose_meth)s\n\n Returns\n -------\n self : instance of ICA\n Returns the modified instance.\n \"\"\"\n _validate_type(inst, (BaseRaw, BaseEpochs), 'inst', 'Raw or Epochs')\n picks = _picks_to_idx(inst.info, picks, allow_empty=False,\n with_ref_meg=self.allow_ref_meg)\n _check_for_unsupported_ica_channels(\n picks, inst.info, allow_ref_meg=self.allow_ref_meg)\n\n # Actually start fitting\n t_start = time()\n if self.current_fit != 'unfitted':\n self._reset()\n\n logger.info('Fitting ICA to data using %i channels '\n '(please be patient, this may take a while)' % len(picks))\n\n # n_components could be float 0 < x < 1, but that's okay here\n if self.n_components is not None and self.n_components > len(picks):\n raise ValueError(\n f'ica.n_components ({self.n_components}) cannot '\n f'be greater than len(picks) ({len(picks)})')\n\n # filter out all the channels the raw wouldn't have initialized\n self.info = pick_info(inst.info, picks)\n\n if self.info['comps']:\n self.info['comps'] = []\n self.ch_names = self.info['ch_names']\n\n if isinstance(inst, BaseRaw):\n self._fit_raw(inst, picks, start, stop, decim, reject, flat,\n tstep, reject_by_annotation, verbose)\n else:\n assert isinstance(inst, BaseEpochs)\n self._fit_epochs(inst, picks, decim, verbose)\n\n # sort ICA components by explained variance\n var = _ica_explained_variance(self, inst)\n var_ord = var.argsort()[::-1]\n _sort_components(self, var_ord, copy=False)\n t_stop = time()\n logger.info(\"Fitting ICA took {:.1f}s.\".format(t_stop - t_start))\n return self\n\n def _reset(self):\n \"\"\"Aux method.\"\"\"\n for key in ('pre_whitener_', 'unmixing_matrix_', 'mixing_matrix_',\n 'n_components_', 'n_samples_', 'pca_components_',\n 'pca_explained_variance_',\n 'pca_mean_', 'n_iter_', 'drop_inds_', 'reject_'):\n if hasattr(self, key):\n delattr(self, key)\n\n def _fit_raw(self, raw, picks, start, stop, decim, reject, flat, tstep,\n reject_by_annotation, verbose):\n \"\"\"Aux method.\"\"\"\n start, stop = _check_start_stop(raw, start, stop)\n\n reject_by_annotation = 'omit' if reject_by_annotation else None\n # this will be a copy\n data = raw.get_data(picks, start, stop, reject_by_annotation)\n\n # this will be a view\n if decim is not None:\n data = data[:, ::decim]\n\n # this will make a copy\n if (reject is not None) or (flat is not None):\n self.reject_ = reject\n data, self.drop_inds_ = _reject_data_segments(data, reject, flat,\n decim, self.info,\n tstep)\n\n self.n_samples_ = data.shape[1]\n self._fit(data, 'raw')\n\n return self\n\n def _fit_epochs(self, epochs, picks, decim, verbose):\n \"\"\"Aux method.\"\"\"\n if epochs.events.size == 0:\n raise RuntimeError('Tried to fit ICA with epochs, but none were '\n 'found: epochs.events is \"{}\".'\n .format(epochs.events))\n\n # this should be a copy (picks a list of int)\n data = epochs.get_data()[:, picks]\n # this will be a view\n if decim is not None:\n data = data[:, :, ::decim]\n\n self.n_samples_ = data.shape[0] * data.shape[2]\n\n # This will make at least one copy (one from hstack, maybe one\n # more from _pre_whiten)\n data = np.hstack(data)\n self._fit(data, 'epochs')\n\n return self\n\n def _compute_pre_whitener(self, data):\n \"\"\"Aux function.\"\"\"\n data = self._do_proj(data, log_suffix='(pre-whitener computation)')\n\n if self.noise_cov is None:\n # use standardization as whitener\n # Scale (z-score) the data by channel type\n info = self.info\n pre_whitener = np.empty([len(data), 1])\n for ch_type in _DATA_CH_TYPES_SPLIT + ('eog', \"ref_meg\"):\n if _contains_ch_type(info, ch_type):\n if ch_type == 'seeg':\n this_picks = pick_types(info, meg=False, seeg=True)\n elif ch_type == 'dbs':\n this_picks = pick_types(info, meg=False, dbs=True)\n elif ch_type == 'ecog':\n this_picks = pick_types(info, meg=False, ecog=True)\n elif ch_type == 'eeg':\n this_picks = pick_types(info, meg=False, eeg=True)\n elif ch_type in ('mag', 'grad'):\n this_picks = pick_types(info, meg=ch_type)\n elif ch_type == 'eog':\n this_picks = pick_types(info, meg=False, eog=True)\n elif ch_type in ('hbo', 'hbr'):\n this_picks = pick_types(info, meg=False, fnirs=ch_type)\n elif ch_type == 'ref_meg':\n this_picks = pick_types(info, meg=False, ref_meg=True)\n else:\n raise RuntimeError('Should not be reached.'\n 'Unsupported channel {}'\n .format(ch_type))\n pre_whitener[this_picks] = np.std(data[this_picks])\n else:\n pre_whitener, _ = compute_whitener(self.noise_cov, self.info)\n assert data.shape[0] == pre_whitener.shape[1]\n self.pre_whitener_ = pre_whitener\n\n def _do_proj(self, data, log_suffix=''):\n if self.info is not None and self.info['projs']:\n proj, nproj, _ = make_projector(\n [p for p in self.info['projs'] if p['active']],\n self.info['ch_names'], include_active=True)\n if nproj:\n logger.info(\n f' Applying projection operator with {nproj} '\n f'vector{_pl(nproj)}'\n f'{\" \" if log_suffix else \"\"}{log_suffix}')\n if self.noise_cov is None: # otherwise it's in pre_whitener_\n data = proj @ data\n return data\n\n def _pre_whiten(self, data):\n data = self._do_proj(data, log_suffix='(pre-whitener application)')\n if self.noise_cov is None:\n data /= self.pre_whitener_\n else:\n data = self.pre_whitener_ @ data\n return data\n\n def _fit(self, data, fit_type):\n \"\"\"Aux function.\"\"\"\n random_state = check_random_state(self.random_state)\n n_channels, n_samples = data.shape\n self._compute_pre_whitener(data)\n data = self._pre_whiten(data)\n\n pca = _PCA(n_components=self._max_pca_components, whiten=True)\n data = pca.fit_transform(data.T)\n use_ev = pca.explained_variance_ratio_\n n_pca = self.n_pca_components\n if isinstance(n_pca, float):\n n_pca = int(_exp_var_ncomp(use_ev, n_pca)[0])\n elif n_pca is None:\n n_pca = len(use_ev)\n assert isinstance(n_pca, (int, np.int_))\n\n # If user passed a float, select the PCA components explaining the\n # given cumulative variance. This information will later be used to\n # only submit the corresponding parts of the data to ICA.\n if self.n_components is None:\n # None case: check if n_pca_components or 0.999999 yields smaller\n msg = 'Selecting by non-zero PCA components'\n self.n_components_ = min(\n n_pca, _exp_var_ncomp(use_ev, 0.999999)[0])\n elif isinstance(self.n_components, float):\n self.n_components_, ev = _exp_var_ncomp(use_ev, self.n_components)\n if self.n_components_ == 1:\n raise RuntimeError(\n 'One PCA component captures most of the '\n f'explained variance ({100 * ev}%), your threshold '\n 'results in 1 component. You should select '\n 'a higher value.')\n msg = 'Selecting by explained variance'\n else:\n msg = 'Selecting by number'\n self.n_components_ = _ensure_int(self.n_components)\n # check to make sure something okay happened\n if self.n_components_ > n_pca:\n ev = np.cumsum(use_ev)\n ev /= ev[-1]\n evs = 100 * ev[[self.n_components_ - 1, n_pca - 1]]\n raise RuntimeError(\n f'n_components={self.n_components} requires '\n f'{self.n_components_} PCA values (EV={evs[0]:0.1f}%) but '\n f'n_pca_components ({self.n_pca_components}) results in '\n f'only {n_pca} components (EV={evs[1]:0.1f}%)')\n logger.info('%s: %s components' % (msg, self.n_components_))\n\n # the things to store for PCA\n self.pca_mean_ = pca.mean_\n self.pca_components_ = pca.components_\n self.pca_explained_variance_ = pca.explained_variance_\n del pca\n # update number of components\n self._update_ica_names()\n if self.n_pca_components is not None and \\\n self.n_pca_components > len(self.pca_components_):\n raise ValueError(\n f'n_pca_components ({self.n_pca_components}) is greater than '\n f'the number of PCA components ({len(self.pca_components_)})')\n\n # take care of ICA\n sel = slice(0, self.n_components_)\n if self.method == 'fastica':\n from sklearn.decomposition import FastICA\n ica = FastICA(\n whiten=False, random_state=random_state, **self.fit_params)\n ica.fit(data[:, sel])\n self.unmixing_matrix_ = ica.components_\n self.n_iter_ = ica.n_iter_\n elif self.method in ('infomax', 'extended-infomax'):\n unmixing_matrix, n_iter = infomax(\n data[:, sel], random_state=random_state, return_n_iter=True,\n **self.fit_params)\n self.unmixing_matrix_ = unmixing_matrix\n self.n_iter_ = n_iter\n del unmixing_matrix, n_iter\n elif self.method == 'picard':\n from picard import picard\n _, W, _, n_iter = picard(\n data[:, sel].T, whiten=False, return_n_iter=True,\n random_state=random_state, **self.fit_params)\n self.unmixing_matrix_ = W\n self.n_iter_ = n_iter + 1 # picard() starts counting at 0\n del _, n_iter\n assert self.unmixing_matrix_.shape == (self.n_components_,) * 2\n norms = self.pca_explained_variance_\n stable = norms / norms[0] > 1e-6 # to be stable during pinv\n norms = norms[:self.n_components_]\n if not stable[self.n_components_ - 1]:\n max_int = np.where(stable)[0][-1] + 1\n warn(f'Using n_components={self.n_components} (resulting in '\n f'n_components_={self.n_components_}) may lead to an '\n f'unstable mixing matrix estimation because the ratio '\n f'between the largest ({norms[0]:0.2g}) and smallest '\n f'({norms[-1]:0.2g}) variances is too large (> 1e6); '\n f'consider setting n_components=0.999999 or an '\n f'integer <= {max_int}')\n norms = np.sqrt(norms)\n norms[norms == 0] = 1.\n self.unmixing_matrix_ /= norms # whitening\n self._update_mixing_matrix()\n self.current_fit = fit_type\n\n def _update_mixing_matrix(self):\n from scipy import linalg\n self.mixing_matrix_ = linalg.pinv(self.unmixing_matrix_)\n\n def _update_ica_names(self):\n \"\"\"Update ICA names when n_components_ is set.\"\"\"\n self._ica_names = ['ICA%03d' % ii for ii in range(self.n_components_)]\n\n def _transform(self, data):\n \"\"\"Compute sources from data (operates inplace).\"\"\"\n data = self._pre_whiten(data)\n if self.pca_mean_ is not None:\n data -= self.pca_mean_[:, None]\n\n # Apply first PCA\n pca_data = np.dot(self.pca_components_[:self.n_components_], data)\n # Apply unmixing to low dimension PCA\n sources = np.dot(self.unmixing_matrix_, pca_data)\n return sources\n\n def _transform_raw(self, raw, start, stop, reject_by_annotation=False):\n \"\"\"Transform raw data.\"\"\"\n if not hasattr(self, 'mixing_matrix_'):\n raise RuntimeError('No fit available. Please fit ICA.')\n start, stop = _check_start_stop(raw, start, stop)\n\n picks = pick_types(raw.info, include=self.ch_names, exclude='bads',\n meg=False, ref_meg=False)\n if len(picks) != len(self.ch_names):\n raise RuntimeError('Raw doesn\\'t match fitted data: %i channels '\n 'fitted but %i channels supplied. \\nPlease '\n 'provide Raw compatible with '\n 'ica.ch_names' % (len(self.ch_names),\n len(picks)))\n\n reject = 'omit' if reject_by_annotation else None\n data = raw.get_data(picks, start, stop, reject)\n return self._transform(data)\n\n def _transform_epochs(self, epochs, concatenate):\n \"\"\"Aux method.\"\"\"\n if not hasattr(self, 'mixing_matrix_'):\n raise RuntimeError('No fit available. Please fit ICA.')\n\n picks = pick_types(epochs.info, include=self.ch_names, exclude='bads',\n meg=False, ref_meg=False)\n # special case where epochs come picked but fit was 'unpicked'.\n if len(picks) != len(self.ch_names):\n raise RuntimeError('Epochs don\\'t match fitted data: %i channels '\n 'fitted but %i channels supplied. \\nPlease '\n 'provide Epochs compatible with '\n 'ica.ch_names' % (len(self.ch_names),\n len(picks)))\n\n data = np.hstack(epochs.get_data()[:, picks])\n sources = self._transform(data)\n\n if not concatenate:\n # Put the data back in 3D\n sources = np.array(np.split(sources, len(epochs.events), 1))\n\n return sources\n\n def _transform_evoked(self, evoked):\n \"\"\"Aux method.\"\"\"\n if not hasattr(self, 'mixing_matrix_'):\n raise RuntimeError('No fit available. Please fit ICA.')\n\n picks = pick_types(evoked.info, include=self.ch_names, exclude='bads',\n meg=False, ref_meg=False)\n\n if len(picks) != len(self.ch_names):\n raise RuntimeError('Evoked doesn\\'t match fitted data: %i channels'\n ' fitted but %i channels supplied. \\nPlease '\n 'provide Evoked compatible with '\n 'ica.ch_names' % (len(self.ch_names),\n len(picks)))\n\n sources = self._transform(evoked.data[picks])\n\n return sources\n\n def get_components(self):\n \"\"\"Get ICA topomap for components as numpy arrays.\n\n Returns\n -------\n components : array, shape (n_channels, n_components)\n The ICA components (maps).\n \"\"\"\n return np.dot(self.mixing_matrix_[:, :self.n_components_].T,\n self.pca_components_[:self.n_components_]).T\n\n def get_sources(self, inst, add_channels=None, start=None, stop=None):\n \"\"\"Estimate sources given the unmixing matrix.\n\n This method will return the sources in the container format passed.\n Typical usecases:\n\n 1. pass Raw object to use `raw.plot <mne.io.Raw.plot>` for ICA sources\n 2. pass Epochs object to compute trial-based statistics in ICA space\n 3. pass Evoked object to investigate time-locking in ICA space\n\n Parameters\n ----------\n inst : instance of Raw, Epochs or Evoked\n Object to compute sources from and to represent sources in.\n add_channels : None | list of str\n Additional channels to be added. Useful to e.g. compare sources\n with some reference. Defaults to None.\n start : int | float | None\n First sample to include. If float, data will be interpreted as\n time in seconds. If None, the entire data will be used.\n stop : int | float | None\n Last sample to not include. If float, data will be interpreted as\n time in seconds. If None, the entire data will be used.\n\n Returns\n -------\n sources : instance of Raw, Epochs or Evoked\n The ICA sources time series.\n \"\"\"\n if isinstance(inst, BaseRaw):\n _check_compensation_grade(self.info, inst.info, 'ICA', 'Raw',\n ch_names=self.ch_names)\n sources = self._sources_as_raw(inst, add_channels, start, stop)\n elif isinstance(inst, BaseEpochs):\n _check_compensation_grade(self.info, inst.info, 'ICA', 'Epochs',\n ch_names=self.ch_names)\n sources = self._sources_as_epochs(inst, add_channels, False)\n elif isinstance(inst, Evoked):\n _check_compensation_grade(self.info, inst.info, 'ICA', 'Evoked',\n ch_names=self.ch_names)\n sources = self._sources_as_evoked(inst, add_channels)\n else:\n raise ValueError('Data input must be of Raw, Epochs or Evoked '\n 'type')\n return sources\n\n def _sources_as_raw(self, raw, add_channels, start, stop):\n \"\"\"Aux method.\"\"\"\n # merge copied instance and picked data with sources\n start, stop = _check_start_stop(raw, start, stop)\n data_ = self._transform_raw(raw, start=start, stop=stop)\n assert data_.shape[1] == stop - start\n if raw.preload: # get data and temporarily delete\n data = raw._data\n del raw._data\n\n out = raw.copy() # copy and reappend\n if raw.preload:\n raw._data = data\n\n # populate copied raw.\n if add_channels is not None and len(add_channels):\n picks = pick_channels(raw.ch_names, add_channels)\n data_ = np.concatenate([\n data_, raw.get_data(picks, start=start, stop=stop)])\n out._data = data_\n out._filenames = [None]\n out.preload = True\n out._first_samps[:] = [out.first_samp + start]\n out._last_samps[:] = [out.first_samp + data_.shape[1] - 1]\n out._projector = None\n self._export_info(out.info, raw, add_channels)\n\n return out\n\n def _sources_as_epochs(self, epochs, add_channels, concatenate):\n \"\"\"Aux method.\"\"\"\n out = epochs.copy()\n sources = self._transform_epochs(epochs, concatenate)\n if add_channels is not None:\n picks = [epochs.ch_names.index(k) for k in add_channels]\n else:\n picks = []\n out._data = np.concatenate([sources, epochs.get_data()[:, picks]],\n axis=1) if len(picks) > 0 else sources\n\n self._export_info(out.info, epochs, add_channels)\n out.preload = True\n out._raw = None\n out._projector = None\n\n return out\n\n def _sources_as_evoked(self, evoked, add_channels):\n \"\"\"Aux method.\"\"\"\n if add_channels is not None:\n picks = [evoked.ch_names.index(k) for k in add_channels]\n else:\n picks = []\n\n sources = self._transform_evoked(evoked)\n if len(picks) > 1:\n data = np.r_[sources, evoked.data[picks]]\n else:\n data = sources\n out = evoked.copy()\n out.data = data\n self._export_info(out.info, evoked, add_channels)\n\n return out\n\n def _export_info(self, info, container, add_channels):\n \"\"\"Aux method.\"\"\"\n # set channel names and info\n ch_names = []\n ch_info = info['chs'] = []\n for ii, name in enumerate(self._ica_names):\n ch_names.append(name)\n ch_info.append(dict(\n ch_name=name, cal=1, logno=ii + 1,\n coil_type=FIFF.FIFFV_COIL_NONE, kind=FIFF.FIFFV_MISC_CH,\n coord_frame=FIFF.FIFFV_COORD_UNKNOWN, unit=FIFF.FIFF_UNIT_NONE,\n loc=np.zeros(12, dtype='f4'),\n range=1.0, scanno=ii + 1, unit_mul=0))\n\n if add_channels is not None:\n # re-append additionally picked ch_names\n ch_names += add_channels\n # re-append additionally picked ch_info\n ch_info += [k for k in container.info['chs'] if k['ch_name'] in\n add_channels]\n info['bads'] = [ch_names[k] for k in self.exclude]\n info['projs'] = [] # make sure projections are removed.\n info._update_redundant()\n info._check_consistency()\n\n @verbose\n def score_sources(self, inst, target=None, score_func='pearsonr',\n start=None, stop=None, l_freq=None, h_freq=None,\n reject_by_annotation=True, verbose=None):\n \"\"\"Assign score to components based on statistic or metric.\n\n Parameters\n ----------\n inst : instance of Raw, Epochs or Evoked\n The object to reconstruct the sources from.\n target : array-like | str | None\n Signal to which the sources shall be compared. It has to be of\n the same shape as the sources. If str, a routine will try to find\n a matching channel name. If None, a score\n function expecting only one input-array argument must be used,\n for instance, scipy.stats.skew (default).\n score_func : callable | str\n Callable taking as arguments either two input arrays\n (e.g. Pearson correlation) or one input\n array (e. g. skewness) and returns a float. For convenience the\n most common score_funcs are available via string labels:\n Currently, all distance metrics from scipy.spatial and All\n functions from scipy.stats taking compatible input arguments are\n supported. These function have been modified to support iteration\n over the rows of a 2D array.\n start : int | float | None\n First sample to include. If float, data will be interpreted as\n time in seconds. If None, data will be used from the first sample.\n stop : int | float | None\n Last sample to not include. If float, data will be interpreted as\n time in seconds. If None, data will be used to the last sample.\n l_freq : float\n Low pass frequency.\n h_freq : float\n High pass frequency.\n %(reject_by_annotation_all)s\n\n .. versionadded:: 0.14.0\n %(verbose_meth)s\n\n Returns\n -------\n scores : ndarray\n Scores for each source as returned from score_func.\n \"\"\"\n if isinstance(inst, BaseRaw):\n _check_compensation_grade(self.info, inst.info, 'ICA', 'Raw',\n ch_names=self.ch_names)\n sources = self._transform_raw(inst, start, stop,\n reject_by_annotation)\n elif isinstance(inst, BaseEpochs):\n _check_compensation_grade(self.info, inst.info, 'ICA', 'Epochs',\n ch_names=self.ch_names)\n sources = self._transform_epochs(inst, concatenate=True)\n elif isinstance(inst, Evoked):\n _check_compensation_grade(self.info, inst.info, 'ICA', 'Evoked',\n ch_names=self.ch_names)\n sources = self._transform_evoked(inst)\n else:\n raise ValueError('Data input must be of Raw, Epochs or Evoked '\n 'type')\n\n if target is not None: # we can have univariate metrics without target\n target = self._check_target(target, inst, start, stop,\n reject_by_annotation)\n\n if sources.shape[-1] != target.shape[-1]:\n raise ValueError('Sources and target do not have the same '\n 'number of time slices.')\n # auto target selection\n if isinstance(inst, BaseRaw):\n # We pass inst, not self, because the sfreq of the data we\n # use for scoring components can be different:\n sources, target = _band_pass_filter(inst, sources, target,\n l_freq, h_freq)\n\n scores = _find_sources(sources, target, score_func)\n\n return scores\n\n def _check_target(self, target, inst, start, stop,\n reject_by_annotation=False):\n \"\"\"Aux Method.\"\"\"\n if isinstance(inst, BaseRaw):\n reject_by_annotation = 'omit' if reject_by_annotation else None\n start, stop = _check_start_stop(inst, start, stop)\n if hasattr(target, 'ndim'):\n if target.ndim < 2:\n target = target.reshape(1, target.shape[-1])\n if isinstance(target, str):\n pick = _get_target_ch(inst, target)\n target = inst.get_data(pick, start, stop, reject_by_annotation)\n\n elif isinstance(inst, BaseEpochs):\n if isinstance(target, str):\n pick = _get_target_ch(inst, target)\n target = inst.get_data()[:, pick]\n\n if hasattr(target, 'ndim'):\n if target.ndim == 3 and min(target.shape) == 1:\n target = target.ravel()\n\n elif isinstance(inst, Evoked):\n if isinstance(target, str):\n pick = _get_target_ch(inst, target)\n target = inst.data[pick]\n\n return target\n\n def _find_bads_ch(self, inst, chs, threshold=3.0, start=None,\n stop=None, l_freq=None, h_freq=None,\n reject_by_annotation=True, prefix='chs',\n measure='zscore'):\n \"\"\"Compute ExG/ref components.\n\n See find_bads_ecg, find_bads_eog, and find_bads_ref for details.\n \"\"\"\n scores, idx = [], []\n # some magic we need inevitably ...\n # get targets before equalizing\n targets = [self._check_target(\n ch, inst, start, stop, reject_by_annotation) for ch in chs]\n # assign names, if targets are arrays instead of strings\n target_names = []\n for ch in chs:\n if not isinstance(ch, str):\n if prefix == \"ecg\":\n target_names.append('ECG-MAG')\n else:\n target_names.append(prefix)\n else:\n target_names.append(ch)\n\n for ii, (ch, target) in enumerate(zip(target_names, targets)):\n scores += [self.score_sources(\n inst, target=target, score_func='pearsonr', start=start,\n stop=stop, l_freq=l_freq, h_freq=h_freq,\n reject_by_annotation=reject_by_annotation)]\n # pick last scores\n if measure == \"zscore\":\n this_idx = _find_outliers(scores[-1], threshold=threshold)\n elif measure == \"correlation\":\n this_idx = np.where(abs(scores[-1]) > threshold)[0]\n else:\n raise ValueError(\"Unknown measure {}\".format(measure))\n idx += [this_idx]\n self.labels_['%s/%i/' % (prefix, ii) + ch] = list(this_idx)\n\n # remove duplicates but keep order by score, even across multiple\n # ref channels\n scores_ = np.concatenate([scores[ii][inds]\n for ii, inds in enumerate(idx)])\n idx_ = np.concatenate(idx)[np.abs(scores_).argsort()[::-1]]\n\n idx_unique = list(np.unique(idx_))\n idx = []\n for i in idx_:\n if i in idx_unique:\n idx.append(i)\n idx_unique.remove(i)\n if len(scores) == 1:\n scores = scores[0]\n labels = list(idx)\n\n return labels, scores\n\n def _get_ctps_threshold(self, pk_threshold=20):\n \"\"\"Automatically decide the threshold of Kuiper index for CTPS method.\n\n This function finds the threshold of Kuiper index based on the\n threshold of pk. Kuiper statistic that minimizes the difference between\n pk and the pk threshold (defaults to 20 [1]) is returned. It is assumed\n that the data are appropriately filtered and bad data are rejected at\n least based on peak-to-peak amplitude when/before running the ICA\n decomposition on data.\n\n References\n ----------\n [1] Dammers, J., Schiek, M., Boers, F., Silex, C., Zvyagintsev,\n M., Pietrzyk, U., Mathiak, K., 2008. Integration of amplitude\n and phase statistics for complete artifact removal in independent\n components of neuromagnetic recordings. Biomedical\n Engineering, IEEE Transactions on 55 (10), pp.2356.\n \"\"\"\n N = self.info['sfreq']\n Vs = np.arange(1, 100) / 100\n C = math.sqrt(N) + 0.155 + 0.24 / math.sqrt(N)\n # in formula (13), when k gets large, only k=1 matters for the\n # summation. k*V*C thus becomes V*C\n Pks = 2 * (4 * (Vs * C)**2 - 1) * (np.exp(-2 * (Vs * C)**2))\n # NOTE: the threshold of pk is transformed to Pk for comparison\n # pk = -log10(Pk)\n return Vs[np.argmin(np.abs(Pks - 10**(-pk_threshold)))]\n\n @verbose\n def find_bads_ecg(self, inst, ch_name=None, threshold='auto', start=None,\n stop=None, l_freq=8, h_freq=16, method='ctps',\n reject_by_annotation=True, measure='zscore',\n verbose=None):\n \"\"\"Detect ECG related components.\n\n Cross-trial phase statistics (default) or Pearson correlation can be\n used for detection.\n\n .. note:: If no ECG channel is available, routine attempts to create\n an artificial ECG based on cross-channel averaging.\n\n Parameters\n ----------\n inst : instance of Raw, Epochs or Evoked\n Object to compute sources from.\n ch_name : str\n The name of the channel to use for ECG peak detection.\n The argument is mandatory if the dataset contains no ECG\n channels.\n threshold : float | str\n The value above which a feature is classified as outlier. If 'auto'\n and method is 'ctps', automatically compute the threshold. If\n 'auto' and method is 'correlation', defaults to 3.0. The default\n translates to 0.25 for 'ctps' and 3.0 for 'correlation' in version\n 0.21 but will change to 'auto' in version 0.22.\n\n .. versionchanged:: 0.21\n start : int | float | None\n First sample to include. If float, data will be interpreted as\n time in seconds. If None, data will be used from the first sample.\n stop : int | float | None\n Last sample to not include. If float, data will be interpreted as\n time in seconds. If None, data will be used to the last sample.\n l_freq : float\n Low pass frequency.\n h_freq : float\n High pass frequency.\n method : {'ctps', 'correlation'}\n The method used for detection. If 'ctps', cross-trial phase\n statistics [1] are used to detect ECG related components.\n Thresholding is then based on the significance value of a Kuiper\n statistic.\n If 'correlation', detection is based on Pearson correlation\n between the filtered data and the filtered ECG channel.\n Thresholding is based on iterative z-scoring. The above\n threshold components will be masked and the z-score will\n be recomputed until no supra-threshold component remains.\n Defaults to 'ctps'.\n %(reject_by_annotation_all)s\n\n .. versionadded:: 0.14.0\n measure : 'zscore' | 'correlation'\n Which method to use for finding outliers. ``'zscore'`` (default) is\n the iterated Z-scoring method, and ``'correlation'`` is an absolute\n raw correlation threshold with a range of 0 to 1.\n\n .. versionadded:: 0.21\n %(verbose_meth)s\n\n Returns\n -------\n ecg_idx : list of int\n The indices of ECG-related components.\n scores : np.ndarray of float, shape (``n_components_``)\n If method is 'ctps', the normalized Kuiper index scores. If method\n is 'correlation', the correlation scores.\n\n See Also\n --------\n find_bads_eog, find_bads_ref\n\n References\n ----------\n [1] Dammers, J., Schiek, M., Boers, F., Silex, C., Zvyagintsev,\n M., Pietrzyk, U., Mathiak, K., 2008. Integration of amplitude\n and phase statistics for complete artifact removal in independent\n components of neuromagnetic recordings. Biomedical\n Engineering, IEEE Transactions on 55 (10), 2353-2362.\n \"\"\"\n idx_ecg = _get_ecg_channel_index(ch_name, inst)\n\n if idx_ecg is None:\n ecg, times = _make_ecg(inst, start, stop,\n reject_by_annotation=reject_by_annotation)\n else:\n ecg = inst.ch_names[idx_ecg]\n\n _validate_type(threshold, (str, 'numeric'), 'threshold')\n if isinstance(threshold, str):\n _check_option('threshold', threshold, ('auto',), extra='when str')\n if method == 'ctps':\n if threshold == 'auto':\n threshold = self._get_ctps_threshold()\n logger.info('Using threshold: %.2f for CTPS ECG detection'\n % threshold)\n if isinstance(inst, BaseRaw):\n sources = self.get_sources(create_ecg_epochs(\n inst, ch_name, l_freq=l_freq, h_freq=h_freq,\n keep_ecg=False,\n reject_by_annotation=reject_by_annotation)).get_data()\n\n if sources.shape[0] == 0:\n warn('No ECG activity detected. Consider changing '\n 'the input parameters.')\n elif isinstance(inst, BaseEpochs):\n sources = self.get_sources(inst).get_data()\n else:\n raise ValueError('With `ctps` only Raw and Epochs input is '\n 'supported')\n _, p_vals, _ = ctps(sources)\n scores = p_vals.max(-1)\n ecg_idx = np.where(scores >= threshold)[0]\n # sort indices by scores\n ecg_idx = ecg_idx[np.abs(scores[ecg_idx]).argsort()[::-1]]\n\n self.labels_['ecg'] = list(ecg_idx)\n if ch_name is None:\n ch_name = 'ECG-MAG'\n self.labels_['ecg/%s' % ch_name] = list(ecg_idx)\n elif method == 'correlation':\n if threshold == 'auto':\n threshold = 3.0\n self.labels_['ecg'], scores = self._find_bads_ch(\n inst, [ecg], threshold=threshold, start=start, stop=stop,\n l_freq=l_freq, h_freq=h_freq, prefix=\"ecg\",\n reject_by_annotation=reject_by_annotation, measure=measure)\n else:\n raise ValueError('Method \"%s\" not supported.' % method)\n return self.labels_['ecg'], scores\n\n @verbose\n def find_bads_ref(self, inst, ch_name=None, threshold=3.0, start=None,\n stop=None, l_freq=None, h_freq=None,\n reject_by_annotation=True, method='together',\n measure=\"zscore\", verbose=None):\n \"\"\"Detect MEG reference related components using correlation.\n\n Parameters\n ----------\n inst : instance of Raw, Epochs or Evoked\n Object to compute sources from. Should contain at least one channel\n i.e. component derived from MEG reference channels.\n ch_name : list of str\n Which MEG reference components to use. If None, then all channels\n that begin with REF_ICA.\n threshold : int | float\n The value above which a feature is classified as outlier.\n start : int | float | None\n First sample to include. If float, data will be interpreted as\n time in seconds. If None, data will be used from the first sample.\n stop : int | float | None\n Last sample to not include. If float, data will be interpreted as\n time in seconds. If None, data will be used to the last sample.\n l_freq : float\n Low pass frequency.\n h_freq : float\n High pass frequency.\n %(reject_by_annotation_all)s\n method : 'together' | 'separate'\n Method to use to identify reference channel related components.\n Defaults to ``'together'``. See notes.\n\n .. versionadded:: 0.21\n measure : 'zscore' | 'correlation'\n Which method to use for finding outliers. ``'zscore'`` (default) is\n the iterated Z-scoring method, and ``'correlation'`` is an absolute\n raw correlation threshold with a range of 0 to 1.\n\n .. versionadded:: 0.21\n %(verbose_meth)s\n\n Returns\n -------\n ref_idx : list of int\n The indices of MEG reference related components, sorted by score.\n scores : np.ndarray of float, shape (``n_components_``) | list of array\n The correlation scores.\n\n See Also\n --------\n find_bads_ecg, find_bads_eog\n\n Notes\n -----\n ICA decomposition on MEG reference channels is used to assess external\n magnetic noise and remove it from the MEG. Two methods are supported:\n\n With the \"together\" method, only one ICA fit is used, which\n encompasses both MEG and reference channels together. Components which\n have particularly strong weights on the reference channels may be\n thresholded and marked for removal.\n\n With \"separate,\" selected components from a separate ICA decomposition\n on the reference channels are used as a ground truth for identifying\n bad components in an ICA fit done on MEG channels only. The logic here\n is similar to an EOG/ECG, with reference components replacing the\n EOG/ECG channels. Recommended procedure is to perform ICA separately\n on reference channels, extract them using .get_sources(), and then\n append them to the inst using :meth:`~mne.io.Raw.add_channels`,\n preferably with the prefix ``REF_ICA`` so that they can be\n automatically detected.\n\n Thresholding in both cases is based on adaptive z-scoring:\n The above-threshold components will be masked and the z-score will be\n recomputed until no supra-threshold component remains.\n\n Validation and further documentation for this technique can be found\n in :footcite:`HannaEtAl2020`.\n\n .. versionadded:: 0.18\n\n References\n ----------\n .. footbibliography::\n \"\"\"\n if method == \"separate\":\n if not ch_name:\n inds = pick_channels_regexp(inst.ch_names, 'REF_ICA*')\n else:\n inds = pick_channels(inst.ch_names, ch_name)\n # regexp returns list, pick_channels returns numpy\n inds = list(inds)\n if not inds:\n raise ValueError('No valid channels available.')\n ref_chs = [inst.ch_names[k] for k in inds]\n\n self.labels_['ref_meg'], scores = self._find_bads_ch(\n inst, ref_chs, threshold=threshold, start=start, stop=stop,\n l_freq=l_freq, h_freq=h_freq, prefix='ref_meg',\n reject_by_annotation=reject_by_annotation,\n measure=measure)\n elif method == 'together':\n meg_picks = pick_types(self.info, meg=True, ref_meg=False)\n ref_picks = pick_types(self.info, meg=False, ref_meg=True)\n if not any(meg_picks) or not any(ref_picks):\n raise ValueError('ICA solution must contain both reference and\\\n MEG channels.')\n weights = self.get_components()\n # take norm of component weights on reference channels for each\n # component, divide them by the norm on the standard channels,\n # log transform to approximate normal distribution\n normrats = np.linalg.norm(weights[ref_picks],\n axis=0) / np.linalg.norm(weights[meg_picks], # noqa\n axis=0)\n scores = np.log(normrats)\n self.labels_['ref_meg'] = list(_find_outliers(scores,\n threshold=threshold,\n tail=1))\n else:\n raise ValueError('Method \"%s\" not supported.' % method)\n\n return self.labels_['ref_meg'], scores\n\n @verbose\n def find_bads_eog(self, inst, ch_name=None, threshold=3.0, start=None,\n stop=None, l_freq=1, h_freq=10,\n reject_by_annotation=True, measure='zscore',\n verbose=None):\n \"\"\"Detect EOG related components using correlation.\n\n Detection is based on Pearson correlation between the\n filtered data and the filtered EOG channel.\n Thresholding is based on adaptive z-scoring. The above threshold\n components will be masked and the z-score will be recomputed\n until no supra-threshold component remains.\n\n Parameters\n ----------\n inst : instance of Raw, Epochs or Evoked\n Object to compute sources from.\n ch_name : str\n The name of the channel to use for EOG peak detection.\n The argument is mandatory if the dataset contains no EOG\n channels.\n threshold : int | float\n The value above which a feature is classified as outlier.\n start : int | float | None\n First sample to include. If float, data will be interpreted as\n time in seconds. If None, data will be used from the first sample.\n stop : int | float | None\n Last sample to not include. If float, data will be interpreted as\n time in seconds. If None, data will be used to the last sample.\n l_freq : float\n Low pass frequency.\n h_freq : float\n High pass frequency.\n %(reject_by_annotation_all)s\n\n .. versionadded:: 0.14.0\n measure : 'zscore' | 'correlation'\n Which method to use for finding outliers. ``'zscore'`` (default) is\n the iterated Z-scoring method, and ``'correlation'`` is an absolute\n raw correlation threshold with a range of 0 to 1.\n\n .. versionadded:: 0.21\n %(verbose_meth)s\n\n Returns\n -------\n eog_idx : list of int\n The indices of EOG related components, sorted by score.\n scores : np.ndarray of float, shape (``n_components_``) | list of array\n The correlation scores.\n\n See Also\n --------\n find_bads_ecg, find_bads_ref\n \"\"\"\n eog_inds = _get_eog_channel_index(ch_name, inst)\n eog_chs = [inst.ch_names[k] for k in eog_inds]\n\n self.labels_['eog'], scores = self._find_bads_ch(\n inst, eog_chs, threshold=threshold, start=start, stop=stop,\n l_freq=l_freq, h_freq=h_freq, prefix=\"eog\",\n reject_by_annotation=reject_by_annotation, measure=measure)\n return self.labels_['eog'], scores\n\n @verbose\n def apply(self, inst, include=None, exclude=None, n_pca_components=None,\n start=None, stop=None, verbose=None):\n \"\"\"Remove selected components from the signal.\n\n Given the unmixing matrix, transform data,\n zero out components, and inverse transform the data.\n This procedure will reconstruct M/EEG signals from which\n the dynamics described by the excluded components is subtracted.\n The data is processed in place.\n\n Parameters\n ----------\n inst : instance of Raw, Epochs or Evoked\n The data to be processed. The instance is modified inplace.\n include : array_like of int\n The indices referring to columns in the ummixing matrix. The\n components to be kept.\n exclude : array_like of int\n The indices referring to columns in the ummixing matrix. The\n components to be zeroed out.\n %(n_pca_components_apply)s\n start : int | float | None\n First sample to include. If float, data will be interpreted as\n time in seconds. If None, data will be used from the first sample.\n stop : int | float | None\n Last sample to not include. If float, data will be interpreted as\n time in seconds. If None, data will be used to the last sample.\n %(verbose_meth)s\n\n Returns\n -------\n out : instance of Raw, Epochs or Evoked\n The processed data.\n \"\"\"\n _validate_type(inst, (BaseRaw, BaseEpochs, Evoked), 'inst',\n 'Raw, Epochs, or Evoked')\n kwargs = dict(include=include, exclude=exclude,\n n_pca_components=n_pca_components)\n if isinstance(inst, BaseRaw):\n kind, meth = 'Raw', self._apply_raw\n kwargs.update(raw=inst, start=start, stop=stop)\n elif isinstance(inst, BaseEpochs):\n kind, meth = 'Epochs', self._apply_epochs\n kwargs.update(epochs=inst)\n else: # isinstance(inst, Evoked):\n kind, meth = 'Evoked', self._apply_evoked\n kwargs.update(evoked=inst)\n _check_compensation_grade(self.info, inst.info, 'ICA', kind,\n ch_names=self.ch_names)\n logger.info(f'Applying ICA to {kind} instance')\n return meth(**kwargs)\n\n def _check_exclude(self, exclude):\n if exclude is None:\n return list(set(self.exclude))\n else:\n # Allow both self.exclude and exclude to be array-like:\n return list(set(self.exclude).union(set(exclude)))\n\n def _apply_raw(self, raw, include, exclude, n_pca_components, start, stop):\n \"\"\"Aux method.\"\"\"\n _check_preload(raw, \"ica.apply\")\n\n start, stop = _check_start_stop(raw, start, stop)\n\n picks = pick_types(raw.info, meg=False, include=self.ch_names,\n exclude='bads', ref_meg=False)\n\n data = raw[picks, start:stop][0]\n data = self._pick_sources(data, include, exclude, n_pca_components)\n\n raw[picks, start:stop] = data\n return raw\n\n def _apply_epochs(self, epochs, include, exclude, n_pca_components):\n \"\"\"Aux method.\"\"\"\n _check_preload(epochs, \"ica.apply\")\n\n picks = pick_types(epochs.info, meg=False, ref_meg=False,\n include=self.ch_names,\n exclude='bads')\n\n # special case where epochs come picked but fit was 'unpicked'.\n if len(picks) != len(self.ch_names):\n raise RuntimeError('Epochs don\\'t match fitted data: %i channels '\n 'fitted but %i channels supplied. \\nPlease '\n 'provide Epochs compatible with '\n 'ica.ch_names' % (len(self.ch_names),\n len(picks)))\n\n data = np.hstack(epochs.get_data(picks))\n data = self._pick_sources(data, include, exclude, n_pca_components)\n\n # restore epochs, channels, tsl order\n epochs._data[:, picks] = np.array(\n np.split(data, len(epochs.events), 1))\n epochs.preload = True\n\n return epochs\n\n def _apply_evoked(self, evoked, include, exclude, n_pca_components):\n \"\"\"Aux method.\"\"\"\n picks = pick_types(evoked.info, meg=False, ref_meg=False,\n include=self.ch_names,\n exclude='bads')\n\n # special case where evoked come picked but fit was 'unpicked'.\n if len(picks) != len(self.ch_names):\n raise RuntimeError('Evoked does not match fitted data: %i channels'\n ' fitted but %i channels supplied. \\nPlease '\n 'provide an Evoked object that\\'s compatible '\n 'with ica.ch_names' % (len(self.ch_names),\n len(picks)))\n\n data = evoked.data[picks]\n data = self._pick_sources(data, include, exclude, n_pca_components)\n\n # restore evoked\n evoked.data[picks] = data\n\n return evoked\n\n def _pick_sources(self, data, include, exclude, n_pca_components):\n \"\"\"Aux function.\"\"\"\n if n_pca_components is None:\n n_pca_components = self.n_pca_components\n data = self._pre_whiten(data)\n exclude = self._check_exclude(exclude)\n _n_pca_comp = self._check_n_pca_components(n_pca_components)\n n_ch, _ = data.shape\n\n max_pca_components = self.pca_components_.shape[0]\n if not self.n_components_ <= _n_pca_comp <= max_pca_components:\n raise ValueError(\n f'n_pca_components ({_n_pca_comp}) must be >= '\n f'n_components_ ({self.n_components_}) and <= '\n 'the total number of PCA components '\n f'({max_pca_components}).')\n\n logger.info(f' Transforming to ICA space ({self.n_components_} '\n f'component{_pl(self.n_components_)})')\n\n # Apply first PCA\n if self.pca_mean_ is not None:\n data -= self.pca_mean_[:, None]\n\n sel_keep = np.arange(self.n_components_)\n if include not in (None, []):\n sel_keep = np.unique(include)\n elif exclude not in (None, []):\n sel_keep = np.setdiff1d(np.arange(self.n_components_), exclude)\n\n n_zero = self.n_components_ - len(sel_keep)\n logger.info(f' Zeroing out {n_zero} ICA component{_pl(n_zero)}')\n\n # Mixing and unmixing should both be shape (self.n_components_, 2),\n # and we need to put these into the upper left part of larger mixing\n # and unmixing matrices of shape (n_ch, _n_pca_comp)\n pca_components = self.pca_components_[:_n_pca_comp]\n assert pca_components.shape == (_n_pca_comp, n_ch)\n assert self.unmixing_matrix_.shape == \\\n self.mixing_matrix_.shape == \\\n (self.n_components_,) * 2\n unmixing = np.eye(_n_pca_comp)\n unmixing[:self.n_components_, :self.n_components_] = \\\n self.unmixing_matrix_\n unmixing = np.dot(unmixing, pca_components)\n\n logger.info(f' Projecting back using {_n_pca_comp} '\n f'PCA component{_pl(_n_pca_comp)}')\n mixing = np.eye(_n_pca_comp)\n mixing[:self.n_components_, :self.n_components_] = \\\n self.mixing_matrix_\n mixing = pca_components.T @ mixing\n assert mixing.shape == unmixing.shape[::-1] == (n_ch, _n_pca_comp)\n\n # keep requested components plus residuals (if any)\n sel_keep = np.concatenate(\n (sel_keep, np.arange(self.n_components_, _n_pca_comp)))\n proj_mat = np.dot(mixing[:, sel_keep], unmixing[sel_keep, :])\n data = np.dot(proj_mat, data)\n assert proj_mat.shape == (n_ch,) * 2\n\n if self.pca_mean_ is not None:\n data += self.pca_mean_[:, None]\n\n # restore scaling\n if self.noise_cov is None: # revert standardization\n data *= self.pre_whitener_\n else:\n data = np.linalg.pinv(self.pre_whitener_, rcond=1e-14) @ data\n\n return data\n\n @verbose\n def save(self, fname, verbose=None):\n \"\"\"Store ICA solution into a fiff file.\n\n Parameters\n ----------\n fname : str\n The absolute path of the file name to save the ICA solution into.\n The file name should end with -ica.fif or -ica.fif.gz.\n %(verbose_meth)s\n\n Returns\n -------\n ica : instance of ICA\n The object.\n\n See Also\n --------\n read_ica\n \"\"\"\n if self.current_fit == 'unfitted':\n raise RuntimeError('No fit available. Please first fit ICA')\n\n check_fname(fname, 'ICA', ('-ica.fif', '-ica.fif.gz',\n '_ica.fif', '_ica.fif.gz'))\n\n logger.info('Writing ICA solution to %s...' % fname)\n fid = start_file(fname)\n\n try:\n _write_ica(fid, self)\n end_file(fid)\n except Exception:\n end_file(fid)\n os.remove(fname)\n raise\n\n return self\n\n def copy(self):\n \"\"\"Copy the ICA object.\n\n Returns\n -------\n ica : instance of ICA\n The copied object.\n \"\"\"\n return deepcopy(self)\n\n @copy_function_doc_to_method_doc(plot_ica_components)\n def plot_components(self, picks=None, ch_type=None, res=64,\n vmin=None, vmax=None, cmap='RdBu_r', sensors=True,\n colorbar=False, title=None, show=True, outlines='head',\n contours=6, image_interp='bilinear',\n inst=None, plot_std=True, topomap_args=None,\n image_args=None, psd_args=None, reject='auto',\n sphere=None, verbose=None):\n return plot_ica_components(self, picks=picks, ch_type=ch_type,\n res=res, vmin=vmin,\n vmax=vmax, cmap=cmap, sensors=sensors,\n colorbar=colorbar, title=title, show=show,\n outlines=outlines, contours=contours,\n image_interp=image_interp,\n inst=inst, plot_std=plot_std,\n topomap_args=topomap_args,\n image_args=image_args, psd_args=psd_args,\n reject=reject, sphere=sphere,\n verbose=verbose)\n\n @copy_function_doc_to_method_doc(plot_ica_properties)\n def plot_properties(self, inst, picks=None, axes=None, dB=True,\n plot_std=True, topomap_args=None, image_args=None,\n psd_args=None, figsize=None, show=True, reject='auto',\n reject_by_annotation=True, *, verbose=None):\n return plot_ica_properties(self, inst, picks=picks, axes=axes,\n dB=dB, plot_std=plot_std,\n topomap_args=topomap_args,\n image_args=image_args, psd_args=psd_args,\n figsize=figsize, show=show, reject=reject,\n reject_by_annotation=reject_by_annotation,\n verbose=verbose)\n\n @copy_function_doc_to_method_doc(plot_ica_sources)\n def plot_sources(self, inst, picks=None, start=None,\n stop=None, title=None, show=True, block=False,\n show_first_samp=False, show_scrollbars=True):\n return plot_ica_sources(self, inst=inst, picks=picks,\n start=start, stop=stop, title=title, show=show,\n block=block, show_first_samp=show_first_samp,\n show_scrollbars=show_scrollbars)\n\n @copy_function_doc_to_method_doc(plot_ica_scores)\n def plot_scores(self, scores, exclude=None, labels=None, axhline=None,\n title='ICA component scores', figsize=None, n_cols=None,\n show=True):\n return plot_ica_scores(\n ica=self, scores=scores, exclude=exclude, labels=labels,\n axhline=axhline, title=title, figsize=figsize, n_cols=n_cols,\n show=show)\n\n @copy_function_doc_to_method_doc(plot_ica_overlay)\n def plot_overlay(self, inst, exclude=None, picks=None, start=None,\n stop=None, title=None, show=True, n_pca_components=None):\n return plot_ica_overlay(self, inst=inst, exclude=exclude, picks=picks,\n start=start, stop=stop, title=title, show=show,\n n_pca_components=n_pca_components)\n\n def detect_artifacts(self, raw, start_find=None, stop_find=None,\n ecg_ch=None, ecg_score_func='pearsonr',\n ecg_criterion=0.1, eog_ch=None,\n eog_score_func='pearsonr',\n eog_criterion=0.1, skew_criterion=0,\n kurt_criterion=0, var_criterion=-1,\n add_nodes=None):\n \"\"\"Run ICA artifacts detection workflow.\n\n Note. This is still experimental and will most likely change over\n the next releases. For maximum control use the workflow exposed in\n the examples.\n\n Hints and caveats:\n - It is highly recommended to bandpass filter ECG and EOG\n data and pass them instead of the channel names as ecg_ch and eog_ch\n arguments.\n - please check your results. Detection by kurtosis and variance\n may be powerful but misclassification of brain signals as\n noise cannot be precluded.\n - Consider using shorter times for start_find and stop_find than\n for start and stop. It can save you much time.\n\n Example invocation (taking advantage of the defaults)::\n\n ica.detect_artifacts(ecg_channel='MEG 1531', eog_channel='EOG 061')\n\n Parameters\n ----------\n raw : instance of Raw\n Raw object to draw sources from. No components are actually removed\n here, i.e. ica is not applied to raw in this function. Use\n `ica.apply() <ICA.apply>` for this after inspection of the\n identified components.\n start_find : int | float | None\n First sample to include for artifact search. If float, data will be\n interpreted as time in seconds. If None, data will be used from the\n first sample.\n stop_find : int | float | None\n Last sample to not include for artifact search. If float, data will\n be interpreted as time in seconds. If None, data will be used to\n the last sample.\n ecg_ch : str | ndarray | None\n The ``target`` argument passed to ica.find_sources_raw. Either the\n name of the ECG channel or the ECG time series. If None, this step\n will be skipped.\n ecg_score_func : str | callable\n The ``score_func`` argument passed to ica.find_sources_raw. Either\n the name of function supported by ICA or a custom function.\n ecg_criterion : float | int | list-like | slice\n The indices of the sorted ecg scores. If float, sources with\n absolute scores greater than the criterion will be dropped. Else,\n the absolute scores sorted in descending order will be indexed\n accordingly. E.g. range(2) would return the two sources with the\n highest absolute score. If None, this step will be skipped.\n eog_ch : list | str | ndarray | None\n The ``target`` argument or the list of target arguments\n subsequently passed to ica.find_sources_raw. Either the name of the\n vertical EOG channel or the corresponding EOG time series. If None,\n this step will be skipped.\n eog_score_func : str | callable\n The ``score_func`` argument passed to ica.find_sources_raw. Either\n the name of function supported by ICA or a custom function.\n eog_criterion : float | int | list-like | slice\n The indices of the sorted eog scores. If float, sources with\n absolute scores greater than the criterion will be dropped. Else,\n the absolute scores sorted in descending order will be indexed\n accordingly. E.g. range(2) would return the two sources with the\n highest absolute score. If None, this step will be skipped.\n skew_criterion : float | int | list-like | slice\n The indices of the sorted skewness scores. If float, sources with\n absolute scores greater than the criterion will be dropped. Else,\n the absolute scores sorted in descending order will be indexed\n accordingly. E.g. range(2) would return the two sources with the\n highest absolute score. If None, this step will be skipped.\n kurt_criterion : float | int | list-like | slice\n The indices of the sorted kurtosis scores. If float, sources with\n absolute scores greater than the criterion will be dropped. Else,\n the absolute scores sorted in descending order will be indexed\n accordingly. E.g. range(2) would return the two sources with the\n highest absolute score. If None, this step will be skipped.\n var_criterion : float | int | list-like | slice\n The indices of the sorted variance scores. If float, sources with\n absolute scores greater than the criterion will be dropped. Else,\n the absolute scores sorted in descending order will be indexed\n accordingly. E.g. range(2) would return the two sources with the\n highest absolute score. If None, this step will be skipped.\n add_nodes : list of tuple\n Additional list if tuples carrying the following parameters\n of ica nodes:\n (name : str, target : str | array, score_func : callable,\n criterion : float | int | list-like | slice). This parameter is a\n generalization of the artifact specific parameters above and has\n the same structure. Example::\n\n add_nodes=('ECG phase lock', ECG 01',\n my_phase_lock_function, 0.5)\n\n Returns\n -------\n self : instance of ICA\n The ICA object with the detected artifact indices marked for\n exclusion.\n \"\"\"\n logger.info(' Searching for artifacts...')\n _detect_artifacts(self, raw=raw, start_find=start_find,\n stop_find=stop_find, ecg_ch=ecg_ch,\n ecg_score_func=ecg_score_func,\n ecg_criterion=ecg_criterion,\n eog_ch=eog_ch, eog_score_func=eog_score_func,\n eog_criterion=eog_criterion,\n skew_criterion=skew_criterion,\n kurt_criterion=kurt_criterion,\n var_criterion=var_criterion,\n add_nodes=add_nodes)\n\n return self\n\n @verbose\n def _check_n_pca_components(self, _n_pca_comp, verbose=None):\n \"\"\"Aux function.\"\"\"\n if isinstance(_n_pca_comp, float):\n n, ev = _exp_var_ncomp(\n self.pca_explained_variance_, _n_pca_comp)\n logger.info(f' Selected {n} PCA components by explained '\n f'variance ({100 * ev}≥{100 * _n_pca_comp}%)')\n _n_pca_comp = n\n elif _n_pca_comp is None:\n _n_pca_comp = self._max_pca_components\n if _n_pca_comp is None:\n _n_pca_comp = self.pca_components_.shape[0]\n elif _n_pca_comp < self.n_components_:\n _n_pca_comp = self.n_components_\n\n return _n_pca_comp\n\n\ndef _exp_var_ncomp(var, n):\n cvar = np.asarray(var, dtype=np.float64)\n cvar = cvar.cumsum()\n cvar /= cvar[-1]\n # We allow 1., which would give us N+1\n n = min((cvar <= n).sum() + 1, len(cvar))\n return n, cvar[n - 1]\n\n\ndef _check_start_stop(raw, start, stop):\n \"\"\"Aux function.\"\"\"\n out = list()\n for st, none_ in ((start, 0), (stop, raw.n_times)):\n if st is None:\n out.append(none_)\n else:\n try:\n out.append(_ensure_int(st))\n except TypeError: # not int-like\n out.append(raw.time_as_index(st)[0])\n return out\n\n\n@verbose\ndef ica_find_ecg_events(raw, ecg_source, event_id=999,\n tstart=0.0, l_freq=5, h_freq=35, qrs_threshold='auto',\n verbose=None):\n \"\"\"Find ECG peaks from one selected ICA source.\n\n Parameters\n ----------\n raw : instance of Raw\n Raw object to draw sources from.\n ecg_source : ndarray\n ICA source resembling ECG to find peaks from.\n event_id : int\n The index to assign to found events.\n tstart : float\n Start detection after tstart seconds. Useful when beginning\n of run is noisy.\n l_freq : float\n Low pass frequency.\n h_freq : float\n High pass frequency.\n qrs_threshold : float | str\n Between 0 and 1. qrs detection threshold. Can also be \"auto\" to\n automatically choose the threshold that generates a reasonable\n number of heartbeats (40-160 beats / min).\n %(verbose)s\n\n Returns\n -------\n ecg_events : array\n Events.\n ch_ECG : string\n Name of channel used.\n average_pulse : float.\n Estimated average pulse.\n \"\"\"\n logger.info('Using ICA source to identify heart beats')\n\n # detecting QRS and generating event file\n ecg_events = qrs_detector(raw.info['sfreq'], ecg_source.ravel(),\n tstart=tstart, thresh_value=qrs_threshold,\n l_freq=l_freq, h_freq=h_freq)\n\n n_events = len(ecg_events)\n\n ecg_events = np.c_[ecg_events + raw.first_samp, np.zeros(n_events),\n event_id * np.ones(n_events)]\n\n return ecg_events\n\n\n@verbose\ndef ica_find_eog_events(raw, eog_source=None, event_id=998, l_freq=1,\n h_freq=10, verbose=None):\n \"\"\"Locate EOG artifacts from one selected ICA source.\n\n Parameters\n ----------\n raw : instance of Raw\n The raw data.\n eog_source : ndarray\n ICA source resembling EOG to find peaks from.\n event_id : int\n The index to assign to found events.\n l_freq : float\n Low cut-off frequency in Hz.\n h_freq : float\n High cut-off frequency in Hz.\n %(verbose)s\n\n Returns\n -------\n eog_events : array\n Events.\n \"\"\"\n eog_events = _find_eog_events(eog_source[np.newaxis], event_id=event_id,\n l_freq=l_freq, h_freq=h_freq,\n sampling_rate=raw.info['sfreq'],\n first_samp=raw.first_samp)\n return eog_events\n\n\ndef _get_target_ch(container, target):\n \"\"\"Aux function.\"\"\"\n # auto target selection\n picks = pick_channels(container.ch_names, include=[target])\n ref_picks = pick_types(container.info, meg=False, eeg=False, ref_meg=True)\n if len(ref_picks) > 0:\n picks = list(set(picks) - set(ref_picks))\n\n if len(picks) == 0:\n raise ValueError('%s not in channel list (%s)' %\n (target, container.ch_names))\n return picks\n\n\ndef _find_sources(sources, target, score_func):\n \"\"\"Aux function.\"\"\"\n if isinstance(score_func, str):\n score_func = get_score_funcs().get(score_func, score_func)\n\n if not callable(score_func):\n raise ValueError('%s is not a valid score_func.' % score_func)\n\n scores = (score_func(sources, target) if target is not None\n else score_func(sources, 1))\n\n return scores\n\n\ndef _ica_explained_variance(ica, inst, normalize=False):\n \"\"\"Check variance accounted for by each component in supplied data.\n\n Parameters\n ----------\n ica : ICA\n Instance of `mne.preprocessing.ICA`.\n inst : Raw | Epochs | Evoked\n Data to explain with ICA. Instance of Raw, Epochs or Evoked.\n normalize : bool\n Whether to normalize the variance.\n\n Returns\n -------\n var : array\n Variance explained by each component.\n \"\"\"\n # check if ica is ICA and whether inst is Raw or Epochs\n if not isinstance(ica, ICA):\n raise TypeError('first argument must be an instance of ICA.')\n if not isinstance(inst, (BaseRaw, BaseEpochs, Evoked)):\n raise TypeError('second argument must an instance of either Raw, '\n 'Epochs or Evoked.')\n\n source_data = _get_inst_data(ica.get_sources(inst))\n\n # if epochs - reshape to channels x timesamples\n if isinstance(inst, BaseEpochs):\n n_epochs, n_chan, n_samp = source_data.shape\n source_data = source_data.transpose(1, 0, 2).reshape(\n (n_chan, n_epochs * n_samp))\n\n n_chan, n_samp = source_data.shape\n var = np.sum(ica.mixing_matrix_ ** 2, axis=0) * np.sum(\n source_data ** 2, axis=1) / (n_chan * n_samp - 1)\n if normalize:\n var /= var.sum()\n return var\n\n\ndef _sort_components(ica, order, copy=True):\n \"\"\"Change the order of components in ica solution.\"\"\"\n assert ica.n_components_ == len(order)\n if copy:\n ica = ica.copy()\n\n # reorder components\n ica.mixing_matrix_ = ica.mixing_matrix_[:, order]\n ica.unmixing_matrix_ = ica.unmixing_matrix_[order, :]\n\n # reorder labels, excludes etc.\n if isinstance(order, np.ndarray):\n order = list(order)\n if ica.exclude:\n ica.exclude = [order.index(ic) for ic in ica.exclude]\n for k in ica.labels_.keys():\n ica.labels_[k] = [order.index(ic) for ic in ica.labels_[k]]\n\n return ica\n\n\ndef _serialize(dict_, outer_sep=';', inner_sep=':'):\n \"\"\"Aux function.\"\"\"\n s = []\n for key, value in dict_.items():\n if callable(value):\n value = value.__name__\n elif isinstance(value, Integral):\n value = int(value)\n elif isinstance(value, dict):\n # py35 json does not support numpy int64\n for subkey, subvalue in value.items():\n if isinstance(subvalue, list):\n if len(subvalue) > 0:\n if isinstance(subvalue[0], (int, np.integer)):\n value[subkey] = [int(i) for i in subvalue]\n\n for cls in (np.random.RandomState, Covariance):\n if isinstance(value, cls):\n value = cls.__name__\n\n s.append(key + inner_sep + json.dumps(value))\n\n return outer_sep.join(s)\n\n\ndef _deserialize(str_, outer_sep=';', inner_sep=':'):\n \"\"\"Aux Function.\"\"\"\n out = {}\n for mapping in str_.split(outer_sep):\n k, v = mapping.split(inner_sep, 1)\n out[k] = json.loads(v)\n return out\n\n\ndef _write_ica(fid, ica):\n \"\"\"Write an ICA object.\n\n Parameters\n ----------\n fid: file\n The file descriptor\n ica:\n The instance of ICA to write\n \"\"\"\n ica_init = dict(noise_cov=ica.noise_cov,\n n_components=ica.n_components,\n n_pca_components=ica.n_pca_components,\n max_pca_components=ica._max_pca_components,\n current_fit=ica.current_fit,\n allow_ref_meg=ica.allow_ref_meg)\n\n if ica.info is not None:\n start_block(fid, FIFF.FIFFB_MEAS)\n write_id(fid, FIFF.FIFF_BLOCK_ID)\n if ica.info['meas_id'] is not None:\n write_id(fid, FIFF.FIFF_PARENT_BLOCK_ID, ica.info['meas_id'])\n\n # Write measurement info\n write_meas_info(fid, ica.info)\n end_block(fid, FIFF.FIFFB_MEAS)\n\n start_block(fid, FIFF.FIFFB_MNE_ICA)\n\n # ICA interface params\n write_string(fid, FIFF.FIFF_MNE_ICA_INTERFACE_PARAMS,\n _serialize(ica_init))\n\n # Channel names\n if ica.ch_names is not None:\n write_name_list(fid, FIFF.FIFF_MNE_ROW_NAMES, ica.ch_names)\n\n # samples on fit\n n_samples = getattr(ica, 'n_samples_', None)\n ica_misc = {'n_samples_': (None if n_samples is None else int(n_samples)),\n 'labels_': getattr(ica, 'labels_', None),\n 'method': getattr(ica, 'method', None),\n 'n_iter_': getattr(ica, 'n_iter_', None),\n 'fit_params': getattr(ica, 'fit_params', None)}\n\n # ICA misc params\n write_string(fid, FIFF.FIFF_MNE_ICA_MISC_PARAMS,\n _serialize(ica_misc))\n\n # Whitener\n write_double_matrix(fid, FIFF.FIFF_MNE_ICA_WHITENER, ica.pre_whitener_)\n\n # PCA components_\n write_double_matrix(fid, FIFF.FIFF_MNE_ICA_PCA_COMPONENTS,\n ica.pca_components_)\n\n # PCA mean_\n write_double_matrix(fid, FIFF.FIFF_MNE_ICA_PCA_MEAN, ica.pca_mean_)\n\n # PCA explained_variance_\n write_double_matrix(fid, FIFF.FIFF_MNE_ICA_PCA_EXPLAINED_VAR,\n ica.pca_explained_variance_)\n\n # ICA unmixing\n write_double_matrix(fid, FIFF.FIFF_MNE_ICA_MATRIX, ica.unmixing_matrix_)\n\n # Write bad components\n write_int(fid, FIFF.FIFF_MNE_ICA_BADS, list(ica.exclude))\n\n # Done!\n end_block(fid, FIFF.FIFFB_MNE_ICA)\n\n\n@verbose\ndef read_ica(fname, verbose=None):\n \"\"\"Restore ICA solution from fif file.\n\n Parameters\n ----------\n fname : str\n Absolute path to fif file containing ICA matrices.\n The file name should end with -ica.fif or -ica.fif.gz.\n %(verbose)s\n\n Returns\n -------\n ica : instance of ICA\n The ICA estimator.\n \"\"\"\n check_fname(fname, 'ICA', ('-ica.fif', '-ica.fif.gz',\n '_ica.fif', '_ica.fif.gz'))\n\n logger.info('Reading %s ...' % fname)\n fid, tree, _ = fiff_open(fname)\n\n try:\n # we used to store bads that weren't part of the info...\n info, _ = read_meas_info(fid, tree, clean_bads=True)\n except ValueError:\n logger.info('Could not find the measurement info. \\n'\n 'Functionality requiring the info won\\'t be'\n ' available.')\n info = None\n\n ica_data = dir_tree_find(tree, FIFF.FIFFB_MNE_ICA)\n if len(ica_data) == 0:\n ica_data = dir_tree_find(tree, 123) # Constant 123 Used before v 0.11\n if len(ica_data) == 0:\n fid.close()\n raise ValueError('Could not find ICA data')\n\n my_ica_data = ica_data[0]\n for d in my_ica_data['directory']:\n kind = d.kind\n pos = d.pos\n if kind == FIFF.FIFF_MNE_ICA_INTERFACE_PARAMS:\n tag = read_tag(fid, pos)\n ica_init = tag.data\n elif kind == FIFF.FIFF_MNE_ROW_NAMES:\n tag = read_tag(fid, pos)\n ch_names = tag.data\n elif kind == FIFF.FIFF_MNE_ICA_WHITENER:\n tag = read_tag(fid, pos)\n pre_whitener = tag.data\n elif kind == FIFF.FIFF_MNE_ICA_PCA_COMPONENTS:\n tag = read_tag(fid, pos)\n pca_components = tag.data\n elif kind == FIFF.FIFF_MNE_ICA_PCA_EXPLAINED_VAR:\n tag = read_tag(fid, pos)\n pca_explained_variance = tag.data\n elif kind == FIFF.FIFF_MNE_ICA_PCA_MEAN:\n tag = read_tag(fid, pos)\n pca_mean = tag.data\n elif kind == FIFF.FIFF_MNE_ICA_MATRIX:\n tag = read_tag(fid, pos)\n unmixing_matrix = tag.data\n elif kind == FIFF.FIFF_MNE_ICA_BADS:\n tag = read_tag(fid, pos)\n exclude = tag.data\n elif kind == FIFF.FIFF_MNE_ICA_MISC_PARAMS:\n tag = read_tag(fid, pos)\n ica_misc = tag.data\n\n fid.close()\n\n ica_init, ica_misc = [_deserialize(k) for k in (ica_init, ica_misc)]\n n_pca_components = ica_init.pop('n_pca_components')\n current_fit = ica_init.pop('current_fit')\n max_pca_components = ica_init.pop('max_pca_components')\n method = ica_misc.get('method', 'fastica')\n if method in _KNOWN_ICA_METHODS:\n ica_init['method'] = method\n if ica_init['noise_cov'] == Covariance.__name__:\n logger.info('Reading whitener drawn from noise covariance ...')\n\n logger.info('Now restoring ICA solution ...')\n\n # make sure dtypes are np.float64 to satisfy fast_dot\n def f(x):\n return x.astype(np.float64)\n\n ica_init = {k: v for k, v in ica_init.items()\n if k in _get_args(ICA.__init__)}\n ica = ICA(**ica_init)\n ica.current_fit = current_fit\n ica.ch_names = ch_names.split(':')\n if n_pca_components is not None and \\\n not isinstance(n_pca_components, int_like):\n n_pca_components = np.float64(n_pca_components)\n ica.n_pca_components = n_pca_components\n ica.pre_whitener_ = f(pre_whitener)\n ica.pca_mean_ = f(pca_mean)\n ica.pca_components_ = f(pca_components)\n ica.n_components_ = unmixing_matrix.shape[0]\n ica._max_pca_components = max_pca_components\n ica._update_ica_names()\n ica.pca_explained_variance_ = f(pca_explained_variance)\n ica.unmixing_matrix_ = f(unmixing_matrix)\n ica._update_mixing_matrix()\n ica.exclude = [] if exclude is None else list(exclude)\n ica.info = info\n if 'n_samples_' in ica_misc:\n ica.n_samples_ = ica_misc['n_samples_']\n if 'labels_' in ica_misc:\n labels_ = ica_misc['labels_']\n if labels_ is not None:\n ica.labels_ = labels_\n if 'method' in ica_misc:\n ica.method = ica_misc['method']\n if 'n_iter_' in ica_misc:\n ica.n_iter_ = ica_misc['n_iter_']\n if 'fit_params' in ica_misc:\n ica.fit_params = ica_misc['fit_params']\n\n logger.info('Ready.')\n\n return ica\n\n\n_ica_node = namedtuple('Node', 'name target score_func criterion')\n\n\ndef _detect_artifacts(ica, raw, start_find, stop_find, ecg_ch, ecg_score_func,\n ecg_criterion, eog_ch, eog_score_func, eog_criterion,\n skew_criterion, kurt_criterion, var_criterion,\n add_nodes):\n \"\"\"Aux Function.\"\"\"\n from scipy import stats\n\n nodes = []\n if ecg_ch is not None:\n nodes += [_ica_node('ECG', ecg_ch, ecg_score_func, ecg_criterion)]\n\n if eog_ch not in [None, []]:\n if not isinstance(eog_ch, list):\n eog_ch = [eog_ch]\n for idx, ch in enumerate(eog_ch):\n nodes += [_ica_node('EOG %02d' % idx, ch, eog_score_func,\n eog_criterion)]\n\n if skew_criterion is not None:\n nodes += [_ica_node('skewness', None, stats.skew, skew_criterion)]\n\n if kurt_criterion is not None:\n nodes += [_ica_node('kurtosis', None, stats.kurtosis, kurt_criterion)]\n\n if var_criterion is not None:\n nodes += [_ica_node('variance', None, np.var, var_criterion)]\n\n if add_nodes is not None:\n nodes.extend(add_nodes)\n\n for node in nodes:\n scores = ica.score_sources(raw, start=start_find, stop=stop_find,\n target=node.target,\n score_func=node.score_func)\n if isinstance(node.criterion, float):\n found = list(np.where(np.abs(scores) > node.criterion)[0])\n else:\n # Sort in descending order; use (-abs()), rather than [::-1] to\n # keep any NaN values in the end (and also keep the order of same\n # values):\n found = list(np.atleast_1d((-np.abs(scores)).argsort()\n [node.criterion]))\n\n case = (len(found), _pl(found), node.name)\n logger.info(' found %s artifact%s by %s' % case)\n ica.exclude = list(ica.exclude) + found\n\n logger.info('Artifact indices found:\\n ' + str(ica.exclude).strip('[]'))\n if len(set(ica.exclude)) != len(ica.exclude):\n logger.info(' Removing duplicate indices...')\n ica.exclude = list(set(ica.exclude))\n\n logger.info('Ready.')\n\n\n@verbose\ndef _band_pass_filter(inst, sources, target, l_freq, h_freq, verbose=None):\n \"\"\"Optionally band-pass filter the data.\"\"\"\n if l_freq is not None and h_freq is not None:\n logger.info('... filtering ICA sources')\n # use FIR here, steeper is better\n kw = dict(phase='zero-double', filter_length='10s', fir_window='hann',\n l_trans_bandwidth=0.5, h_trans_bandwidth=0.5,\n fir_design='firwin2')\n sources = filter_data(sources, inst.info['sfreq'], l_freq, h_freq,\n **kw)\n logger.info('... filtering target')\n target = filter_data(target, inst.info['sfreq'], l_freq, h_freq, **kw)\n elif l_freq is not None or h_freq is not None:\n raise ValueError('Must specify both pass bands')\n return sources, target\n\n\n# #############################################################################\n# CORRMAP\n\ndef _find_max_corrs(all_maps, target, threshold):\n \"\"\"Compute correlations between template and target components.\"\"\"\n all_corrs = [compute_corr(target, subj.T) for subj in all_maps]\n abs_corrs = [np.abs(a) for a in all_corrs]\n corr_polarities = [np.sign(a) for a in all_corrs]\n\n if threshold <= 1:\n max_corrs = [list(np.nonzero(s_corr > threshold)[0])\n for s_corr in abs_corrs]\n else:\n max_corrs = [list(_find_outliers(s_corr, threshold=threshold))\n for s_corr in abs_corrs]\n\n am = [l_[i] for l_, i_s in zip(abs_corrs, max_corrs)\n for i in i_s]\n median_corr_with_target = np.median(am) if len(am) > 0 else 0\n\n polarities = [l_[i] for l_, i_s in zip(corr_polarities, max_corrs)\n for i in i_s]\n\n maxmaps = [l_[i] for l_, i_s in zip(all_maps, max_corrs)\n for i in i_s]\n\n if len(maxmaps) == 0:\n return [], 0, 0, []\n newtarget = np.zeros(maxmaps[0].size)\n std_of_maps = np.std(np.asarray(maxmaps))\n mean_of_maps = np.std(np.asarray(maxmaps))\n for maxmap, polarity in zip(maxmaps, polarities):\n newtarget += (maxmap / std_of_maps - mean_of_maps) * polarity\n\n newtarget /= len(maxmaps)\n newtarget *= std_of_maps\n\n sim_i_o = np.abs(np.corrcoef(target, newtarget)[1, 0])\n\n return newtarget, median_corr_with_target, sim_i_o, max_corrs\n\n\n@verbose\ndef corrmap(icas, template, threshold=\"auto\", label=None, ch_type=\"eeg\",\n plot=True, show=True, outlines='head',\n sensors=True, contours=6, cmap=None, sphere=None, verbose=None):\n \"\"\"Find similar Independent Components across subjects by map similarity.\n\n Corrmap (Viola et al. 2009 Clin Neurophysiol) identifies the best group\n match to a supplied template. Typically, feed it a list of fitted ICAs and\n a template IC, for example, the blink for the first subject, to identify\n specific ICs across subjects.\n\n The specific procedure consists of two iterations. In a first step, the\n maps best correlating with the template are identified. In the next step,\n the analysis is repeated with the mean of the maps identified in the first\n stage.\n\n Run with ``plot`` and ``show`` set to ``True`` and ``label=False`` to find\n good parameters. Then, run with labelling enabled to apply the\n labelling in the IC objects. (Running with both ``plot`` and ``labels``\n off does nothing.)\n\n Outputs a list of fitted ICAs with the indices of the marked ICs in a\n specified field.\n\n The original Corrmap website: www.debener.de/corrmap/corrmapplugin1.html\n\n Parameters\n ----------\n icas : list of mne.preprocessing.ICA\n A list of fitted ICA objects.\n template : tuple | np.ndarray, shape (n_components,)\n Either a tuple with two elements (int, int) representing the list\n indices of the set from which the template should be chosen, and the\n template. E.g., if template=(1, 0), the first IC of the 2nd ICA object\n is used.\n Or a numpy array whose size corresponds to each IC map from the\n supplied maps, in which case this map is chosen as the template.\n threshold : \"auto\" | list of float | float\n Correlation threshold for identifying ICs\n If \"auto\", search for the best map by trying all correlations between\n 0.6 and 0.95. In the original proposal, lower values are considered,\n but this is not yet implemented.\n If list of floats, search for the best map in the specified range of\n correlation strengths. As correlation values, must be between 0 and 1\n If float > 0, select ICs correlating better than this.\n If float > 1, use z-scoring to identify ICs within subjects (not in\n original Corrmap)\n Defaults to \"auto\".\n label : None | str\n If not None, categorised ICs are stored in a dictionary ``labels_``\n under the given name. Preexisting entries will be appended to\n (excluding repeats), not overwritten. If None, a dry run is performed\n and the supplied ICs are not changed.\n ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg'\n The channel type to plot. Defaults to 'eeg'.\n plot : bool\n Should constructed template and selected maps be plotted? Defaults\n to True.\n show : bool\n Show figures if True.\n %(topomap_outlines)s\n sensors : bool | str\n Add markers for sensor locations to the plot. Accepts matplotlib plot\n format string (e.g., 'r+' for red plusses). If True, a circle will be\n used (via .add_artist). Defaults to True.\n contours : int | array of float\n The number of contour lines to draw. If 0, no contours will be drawn.\n When an integer, matplotlib ticker locator is used to find suitable\n values for the contour thresholds (may sometimes be inaccurate, use\n array for accuracy). If an array, the values represent the levels for\n the contours. Defaults to 6.\n cmap : None | matplotlib colormap\n Colormap for the plot. If ``None``, defaults to 'Reds_r' for norm data,\n otherwise to 'RdBu_r'.\n %(topomap_sphere_auto)s\n %(verbose)s\n\n Returns\n -------\n template_fig : Figure\n Figure showing the template.\n labelled_ics : Figure\n Figure showing the labelled ICs in all ICA decompositions.\n \"\"\"\n if not isinstance(plot, bool):\n raise ValueError(\"`plot` must be of type `bool`\")\n\n same_chans = _check_all_same_channel_names(icas)\n if same_chans is False:\n raise ValueError(\"Not all ICA instances have the same channel names. \"\n \"Corrmap requires all instances to have the same \"\n \"montage. Consider interpolating bad channels before \"\n \"running ICA.\")\n\n threshold_extra = ''\n if threshold == 'auto':\n threshold = np.arange(60, 95, dtype=np.float64) / 100.\n threshold_extra = ' (\"auto\")'\n\n all_maps = [ica.get_components().T for ica in icas]\n\n # check if template is an index to one IC in one ICA object, or an array\n if len(template) == 2:\n target = all_maps[template[0]][template[1]]\n is_subject = True\n elif template.ndim == 1 and len(template) == all_maps[0].shape[1]:\n target = template\n is_subject = False\n else:\n raise ValueError(\"`template` must be a length-2 tuple or an array the \"\n \"size of the ICA maps.\")\n\n template_fig, labelled_ics = None, None\n if plot is True:\n if is_subject: # plotting from an ICA object\n ttl = 'Template from subj. {}'.format(str(template[0]))\n template_fig = icas[template[0]].plot_components(\n picks=template[1], ch_type=ch_type, title=ttl,\n outlines=outlines, cmap=cmap, contours=contours,\n show=show, topomap_args=dict(sphere=sphere))\n else: # plotting an array\n template_fig = _plot_corrmap([template], [0], [0], ch_type,\n icas[0].copy(), \"Template\",\n outlines=outlines, cmap=cmap,\n contours=contours,\n show=show, template=True,\n sphere=sphere)\n template_fig.subplots_adjust(top=0.8)\n template_fig.canvas.draw()\n\n # first run: use user-selected map\n threshold = np.atleast_1d(np.array(threshold, float)).ravel()\n threshold_err = ('No component detected using when z-scoring '\n 'threshold%s %s, consider using a more lenient '\n 'threshold' % (threshold_extra, threshold))\n if len(all_maps) == 0:\n raise RuntimeError(threshold_err)\n paths = [_find_max_corrs(all_maps, target, t) for t in threshold]\n # find iteration with highest avg correlation with target\n new_target, _, _, _ = paths[np.argmax([path[2] for path in paths])]\n\n # second run: use output from first run\n if len(all_maps) == 0 or len(new_target) == 0:\n raise RuntimeError(threshold_err)\n paths = [_find_max_corrs(all_maps, new_target, t) for t in threshold]\n del new_target\n # find iteration with highest avg correlation with target\n _, median_corr, _, max_corrs = paths[\n np.argmax([path[1] for path in paths])]\n\n allmaps, indices, subjs, nones = [list() for _ in range(4)]\n logger.info('Median correlation with constructed map: %0.3f' % median_corr)\n del median_corr\n if plot is True:\n logger.info('Displaying selected ICs per subject.')\n\n for ii, (ica, max_corr) in enumerate(zip(icas, max_corrs)):\n if len(max_corr) > 0:\n if isinstance(max_corr[0], np.ndarray):\n max_corr = max_corr[0]\n if label is not None:\n ica.labels_[label] = list(set(list(max_corr) +\n ica.labels_.get(label, list())))\n if plot is True:\n allmaps.extend(ica.get_components()[:, max_corr].T)\n subjs.extend([ii] * len(max_corr))\n indices.extend(max_corr)\n else:\n if (label is not None) and (label not in ica.labels_):\n ica.labels_[label] = list()\n nones.append(ii)\n\n if len(nones) == 0:\n logger.info('At least 1 IC detected for each subject.')\n else:\n logger.info('No maps selected for subject%s %s, '\n 'consider a more liberal threshold.'\n % (_pl(nones), nones))\n\n if plot is True:\n labelled_ics = _plot_corrmap(allmaps, subjs, indices, ch_type, ica,\n label, outlines=outlines, cmap=cmap,\n contours=contours,\n show=show, sphere=sphere)\n return template_fig, labelled_ics\n else:\n return None\n\n\n@verbose\ndef read_ica_eeglab(fname, *, verbose=None):\n \"\"\"Load ICA information saved in an EEGLAB .set file.\n\n Parameters\n ----------\n fname : str\n Complete path to a .set EEGLAB file that contains an ICA object.\n %(verbose)s\n\n Returns\n -------\n ica : instance of ICA\n An ICA object based on the information contained in the input file.\n \"\"\"\n from scipy import linalg\n eeg = _check_load_mat(fname, None)\n info, eeg_montage, _ = _get_info(eeg)\n info.set_montage(eeg_montage)\n pick_info(info, np.round(eeg['icachansind']).astype(int) - 1, copy=False)\n\n rank = eeg.icasphere.shape[0]\n n_components = eeg.icaweights.shape[0]\n\n ica = ICA(method='imported_eeglab', n_components=n_components)\n\n ica.current_fit = \"eeglab\"\n ica.ch_names = info[\"ch_names\"]\n ica.n_pca_components = None\n ica.n_components_ = n_components\n\n n_ch = len(ica.ch_names)\n assert len(eeg.icachansind) == n_ch\n\n ica.pre_whitener_ = np.ones((n_ch, 1))\n ica.pca_mean_ = np.zeros(n_ch)\n\n assert eeg.icasphere.shape[1] == n_ch\n assert eeg.icaweights.shape == (n_components, rank)\n\n # When PCA reduction is used in EEGLAB, runica returns\n # weights= weights*sphere*eigenvectors(:,1:ncomps)';\n # sphere = eye(urchans). When PCA reduction is not used, we have:\n #\n # eeg.icawinv == pinv(eeg.icaweights @ eeg.icasphere)\n #\n # So in either case, we can use SVD to get our square whitened\n # weights matrix (u * s) and our PCA vectors (v) back:\n use = eeg.icaweights @ eeg.icasphere\n use_check = linalg.pinv(eeg.icawinv)\n if not np.allclose(use, use_check, rtol=1e-6):\n warn('Mismatch between icawinv and icaweights @ icasphere from EEGLAB '\n 'possibly due to ICA component removal, assuming icawinv is '\n 'correct')\n use = use_check\n u, s, v = _safe_svd(use, full_matrices=False)\n ica.unmixing_matrix_ = u * s\n ica.pca_components_ = v\n ica.pca_explained_variance_ = s * s\n ica.info = info\n ica._update_mixing_matrix()\n ica._update_ica_names()\n return ica\n", "# Authors: Martin Luessi <[email protected]>\n# Denis A. Engemann <[email protected]>\n#\n# License: BSD (3-clause)\n\nfrom functools import partial\nfrom inspect import getmembers\n\nimport numpy as np\n\nfrom .utils import check_indices\nfrom ..utils import _check_option\nfrom ..fixes import _get_args, _import_fft\nfrom ..parallel import parallel_func\nfrom ..source_estimate import _BaseSourceEstimate\nfrom ..epochs import BaseEpochs\nfrom ..time_frequency.multitaper import (_mt_spectra, _compute_mt_params,\n _psd_from_mt, _csd_from_mt,\n _psd_from_mt_adaptive)\nfrom ..time_frequency.tfr import morlet, cwt\nfrom ..utils import logger, verbose, _time_mask, warn, _arange_div\n\n########################################################################\n# Various connectivity estimators\n\n\nclass _AbstractConEstBase(object):\n \"\"\"ABC for connectivity estimators.\"\"\"\n\n def start_epoch(self):\n raise NotImplementedError('start_epoch method not implemented')\n\n def accumulate(self, con_idx, csd_xy):\n raise NotImplementedError('accumulate method not implemented')\n\n def combine(self, other):\n raise NotImplementedError('combine method not implemented')\n\n def compute_con(self, con_idx, n_epochs):\n raise NotImplementedError('compute_con method not implemented')\n\n\nclass _EpochMeanConEstBase(_AbstractConEstBase):\n \"\"\"Base class for methods that estimate connectivity as mean epoch-wise.\"\"\"\n\n def __init__(self, n_cons, n_freqs, n_times):\n self.n_cons = n_cons\n self.n_freqs = n_freqs\n self.n_times = n_times\n\n if n_times == 0:\n self.csd_shape = (n_cons, n_freqs)\n else:\n self.csd_shape = (n_cons, n_freqs, n_times)\n\n self.con_scores = None\n\n def start_epoch(self): # noqa: D401\n \"\"\"Called at the start of each epoch.\"\"\"\n pass # for this type of con. method we don't do anything\n\n def combine(self, other):\n \"\"\"Include con. accumated for some epochs in this estimate.\"\"\"\n self._acc += other._acc\n\n\nclass _CohEstBase(_EpochMeanConEstBase):\n \"\"\"Base Estimator for Coherence, Coherency, Imag. Coherence.\"\"\"\n\n def __init__(self, n_cons, n_freqs, n_times):\n super(_CohEstBase, self).__init__(n_cons, n_freqs, n_times)\n\n # allocate space for accumulation of CSD\n self._acc = np.zeros(self.csd_shape, dtype=np.complex128)\n\n def accumulate(self, con_idx, csd_xy):\n \"\"\"Accumulate CSD for some connections.\"\"\"\n self._acc[con_idx] += csd_xy\n\n\nclass _CohEst(_CohEstBase):\n \"\"\"Coherence Estimator.\"\"\"\n\n name = 'Coherence'\n\n def compute_con(self, con_idx, n_epochs, psd_xx, psd_yy): # lgtm\n \"\"\"Compute final con. score for some connections.\"\"\"\n if self.con_scores is None:\n self.con_scores = np.zeros(self.csd_shape)\n csd_mean = self._acc[con_idx] / n_epochs\n self.con_scores[con_idx] = np.abs(csd_mean) / np.sqrt(psd_xx * psd_yy)\n\n\nclass _CohyEst(_CohEstBase):\n \"\"\"Coherency Estimator.\"\"\"\n\n name = 'Coherency'\n\n def compute_con(self, con_idx, n_epochs, psd_xx, psd_yy): # lgtm\n \"\"\"Compute final con. score for some connections.\"\"\"\n if self.con_scores is None:\n self.con_scores = np.zeros(self.csd_shape,\n dtype=np.complex128)\n csd_mean = self._acc[con_idx] / n_epochs\n self.con_scores[con_idx] = csd_mean / np.sqrt(psd_xx * psd_yy)\n\n\nclass _ImCohEst(_CohEstBase):\n \"\"\"Imaginary Coherence Estimator.\"\"\"\n\n name = 'Imaginary Coherence'\n\n def compute_con(self, con_idx, n_epochs, psd_xx, psd_yy): # lgtm\n \"\"\"Compute final con. score for some connections.\"\"\"\n if self.con_scores is None:\n self.con_scores = np.zeros(self.csd_shape)\n csd_mean = self._acc[con_idx] / n_epochs\n self.con_scores[con_idx] = np.imag(csd_mean) / np.sqrt(psd_xx * psd_yy)\n\n\nclass _PLVEst(_EpochMeanConEstBase):\n \"\"\"PLV Estimator.\"\"\"\n\n name = 'PLV'\n\n def __init__(self, n_cons, n_freqs, n_times):\n super(_PLVEst, self).__init__(n_cons, n_freqs, n_times)\n\n # allocate accumulator\n self._acc = np.zeros(self.csd_shape, dtype=np.complex128)\n\n def accumulate(self, con_idx, csd_xy):\n \"\"\"Accumulate some connections.\"\"\"\n self._acc[con_idx] += csd_xy / np.abs(csd_xy)\n\n def compute_con(self, con_idx, n_epochs):\n \"\"\"Compute final con. score for some connections.\"\"\"\n if self.con_scores is None:\n self.con_scores = np.zeros(self.csd_shape)\n plv = np.abs(self._acc / n_epochs)\n self.con_scores[con_idx] = plv\n\n\nclass _ciPLVEst(_EpochMeanConEstBase):\n \"\"\"corrected imaginary PLV Estimator.\"\"\"\n\n name = 'ciPLV'\n\n def __init__(self, n_cons, n_freqs, n_times):\n super(_ciPLVEst, self).__init__(n_cons, n_freqs, n_times)\n\n # allocate accumulator\n self._acc = np.zeros(self.csd_shape, dtype=np.complex128)\n\n def accumulate(self, con_idx, csd_xy):\n \"\"\"Accumulate some connections.\"\"\"\n self._acc[con_idx] += csd_xy / np.abs(csd_xy)\n\n def compute_con(self, con_idx, n_epochs):\n \"\"\"Compute final con. score for some connections.\"\"\"\n if self.con_scores is None:\n self.con_scores = np.zeros(self.csd_shape)\n imag_plv = np.abs(np.imag(self._acc)) / n_epochs\n real_plv = np.real(self._acc) / n_epochs\n real_plv = np.clip(real_plv, -1, 1) # bounded from -1 to 1\n mask = (np.abs(real_plv) == 1) # avoid division by 0\n real_plv[mask] = 0\n corrected_imag_plv = imag_plv / np.sqrt(1 - real_plv ** 2)\n self.con_scores[con_idx] = corrected_imag_plv\n\n\nclass _PLIEst(_EpochMeanConEstBase):\n \"\"\"PLI Estimator.\"\"\"\n\n name = 'PLI'\n\n def __init__(self, n_cons, n_freqs, n_times):\n super(_PLIEst, self).__init__(n_cons, n_freqs, n_times)\n\n # allocate accumulator\n self._acc = np.zeros(self.csd_shape)\n\n def accumulate(self, con_idx, csd_xy):\n \"\"\"Accumulate some connections.\"\"\"\n self._acc[con_idx] += np.sign(np.imag(csd_xy))\n\n def compute_con(self, con_idx, n_epochs):\n \"\"\"Compute final con. score for some connections.\"\"\"\n if self.con_scores is None:\n self.con_scores = np.zeros(self.csd_shape)\n pli_mean = self._acc[con_idx] / n_epochs\n self.con_scores[con_idx] = np.abs(pli_mean)\n\n\nclass _PLIUnbiasedEst(_PLIEst):\n \"\"\"Unbiased PLI Square Estimator.\"\"\"\n\n name = 'Unbiased PLI Square'\n\n def compute_con(self, con_idx, n_epochs):\n \"\"\"Compute final con. score for some connections.\"\"\"\n if self.con_scores is None:\n self.con_scores = np.zeros(self.csd_shape)\n pli_mean = self._acc[con_idx] / n_epochs\n\n # See Vinck paper Eq. (30)\n con = (n_epochs * pli_mean ** 2 - 1) / (n_epochs - 1)\n\n self.con_scores[con_idx] = con\n\n\nclass _WPLIEst(_EpochMeanConEstBase):\n \"\"\"WPLI Estimator.\"\"\"\n\n name = 'WPLI'\n\n def __init__(self, n_cons, n_freqs, n_times):\n super(_WPLIEst, self).__init__(n_cons, n_freqs, n_times)\n\n # store both imag(csd) and abs(imag(csd))\n acc_shape = (2,) + self.csd_shape\n self._acc = np.zeros(acc_shape)\n\n def accumulate(self, con_idx, csd_xy):\n \"\"\"Accumulate some connections.\"\"\"\n im_csd = np.imag(csd_xy)\n self._acc[0, con_idx] += im_csd\n self._acc[1, con_idx] += np.abs(im_csd)\n\n def compute_con(self, con_idx, n_epochs):\n \"\"\"Compute final con. score for some connections.\"\"\"\n if self.con_scores is None:\n self.con_scores = np.zeros(self.csd_shape)\n\n num = np.abs(self._acc[0, con_idx])\n denom = self._acc[1, con_idx]\n\n # handle zeros in denominator\n z_denom = np.where(denom == 0.)\n denom[z_denom] = 1.\n\n con = num / denom\n\n # where we had zeros in denominator, we set con to zero\n con[z_denom] = 0.\n\n self.con_scores[con_idx] = con\n\n\nclass _WPLIDebiasedEst(_EpochMeanConEstBase):\n \"\"\"Debiased WPLI Square Estimator.\"\"\"\n\n name = 'Debiased WPLI Square'\n\n def __init__(self, n_cons, n_freqs, n_times):\n super(_WPLIDebiasedEst, self).__init__(n_cons, n_freqs, n_times)\n # store imag(csd), abs(imag(csd)), imag(csd)^2\n acc_shape = (3,) + self.csd_shape\n self._acc = np.zeros(acc_shape)\n\n def accumulate(self, con_idx, csd_xy):\n \"\"\"Accumulate some connections.\"\"\"\n im_csd = np.imag(csd_xy)\n self._acc[0, con_idx] += im_csd\n self._acc[1, con_idx] += np.abs(im_csd)\n self._acc[2, con_idx] += im_csd ** 2\n\n def compute_con(self, con_idx, n_epochs):\n \"\"\"Compute final con. score for some connections.\"\"\"\n if self.con_scores is None:\n self.con_scores = np.zeros(self.csd_shape)\n\n # note: we use the trick from fieldtrip to compute the\n # the estimate over all pairwise epoch combinations\n sum_im_csd = self._acc[0, con_idx]\n sum_abs_im_csd = self._acc[1, con_idx]\n sum_sq_im_csd = self._acc[2, con_idx]\n\n denom = sum_abs_im_csd ** 2 - sum_sq_im_csd\n\n # handle zeros in denominator\n z_denom = np.where(denom == 0.)\n denom[z_denom] = 1.\n\n con = (sum_im_csd ** 2 - sum_sq_im_csd) / denom\n\n # where we had zeros in denominator, we set con to zero\n con[z_denom] = 0.\n\n self.con_scores[con_idx] = con\n\n\nclass _PPCEst(_EpochMeanConEstBase):\n \"\"\"Pairwise Phase Consistency (PPC) Estimator.\"\"\"\n\n name = 'PPC'\n\n def __init__(self, n_cons, n_freqs, n_times):\n super(_PPCEst, self).__init__(n_cons, n_freqs, n_times)\n\n # store csd / abs(csd)\n self._acc = np.zeros(self.csd_shape, dtype=np.complex128)\n\n def accumulate(self, con_idx, csd_xy):\n \"\"\"Accumulate some connections.\"\"\"\n denom = np.abs(csd_xy)\n z_denom = np.where(denom == 0.)\n denom[z_denom] = 1.\n this_acc = csd_xy / denom\n this_acc[z_denom] = 0. # handle division by zero\n\n self._acc[con_idx] += this_acc\n\n def compute_con(self, con_idx, n_epochs):\n \"\"\"Compute final con. score for some connections.\"\"\"\n if self.con_scores is None:\n self.con_scores = np.zeros(self.csd_shape)\n\n # note: we use the trick from fieldtrip to compute the\n # the estimate over all pairwise epoch combinations\n con = ((self._acc[con_idx] * np.conj(self._acc[con_idx]) - n_epochs) /\n (n_epochs * (n_epochs - 1.)))\n\n self.con_scores[con_idx] = np.real(con)\n\n\n###############################################################################\ndef _epoch_spectral_connectivity(data, sig_idx, tmin_idx, tmax_idx, sfreq,\n mode, window_fun, eigvals, wavelets,\n freq_mask, mt_adaptive, idx_map, block_size,\n psd, accumulate_psd, con_method_types,\n con_methods, n_signals, n_times,\n accumulate_inplace=True):\n \"\"\"Estimate connectivity for one epoch (see spectral_connectivity).\"\"\"\n n_cons = len(idx_map[0])\n\n if wavelets is not None:\n n_times_spectrum = n_times\n n_freqs = len(wavelets)\n else:\n n_times_spectrum = 0\n n_freqs = np.sum(freq_mask)\n\n if not accumulate_inplace:\n # instantiate methods only for this epoch (used in parallel mode)\n con_methods = [mtype(n_cons, n_freqs, n_times_spectrum)\n for mtype in con_method_types]\n\n _check_option('mode', mode, ('cwt_morlet', 'multitaper', 'fourier'))\n if len(sig_idx) == n_signals:\n # we use all signals: use a slice for faster indexing\n sig_idx = slice(None, None)\n\n # compute tapered spectra\n x_t = list()\n this_psd = list()\n for this_data in data:\n if mode in ('multitaper', 'fourier'):\n if isinstance(this_data, _BaseSourceEstimate):\n _mt_spectra_partial = partial(_mt_spectra, dpss=window_fun,\n sfreq=sfreq)\n this_x_t = this_data.transform_data(\n _mt_spectra_partial, idx=sig_idx, tmin_idx=tmin_idx,\n tmax_idx=tmax_idx)\n else:\n this_x_t, _ = _mt_spectra(\n this_data[sig_idx, tmin_idx:tmax_idx],\n window_fun, sfreq)\n\n if mt_adaptive:\n # compute PSD and adaptive weights\n _this_psd, weights = _psd_from_mt_adaptive(\n this_x_t, eigvals, freq_mask, return_weights=True)\n\n # only keep freqs of interest\n this_x_t = this_x_t[:, :, freq_mask]\n else:\n # do not use adaptive weights\n this_x_t = this_x_t[:, :, freq_mask]\n if mode == 'multitaper':\n weights = np.sqrt(eigvals)[np.newaxis, :, np.newaxis]\n else:\n # hack to so we can sum over axis=-2\n weights = np.array([1.])[:, None, None]\n\n if accumulate_psd:\n _this_psd = _psd_from_mt(this_x_t, weights)\n else: # mode == 'cwt_morlet'\n if isinstance(this_data, _BaseSourceEstimate):\n cwt_partial = partial(cwt, Ws=wavelets, use_fft=True,\n mode='same')\n this_x_t = this_data.transform_data(\n cwt_partial, idx=sig_idx, tmin_idx=tmin_idx,\n tmax_idx=tmax_idx)\n else:\n this_x_t = cwt(this_data[sig_idx, tmin_idx:tmax_idx],\n wavelets, use_fft=True, mode='same')\n _this_psd = (this_x_t * this_x_t.conj()).real\n\n x_t.append(this_x_t)\n if accumulate_psd:\n this_psd.append(_this_psd)\n\n x_t = np.concatenate(x_t, axis=0)\n if accumulate_psd:\n this_psd = np.concatenate(this_psd, axis=0)\n\n # accumulate or return psd\n if accumulate_psd:\n if accumulate_inplace:\n psd += this_psd\n else:\n psd = this_psd\n else:\n psd = None\n\n # tell the methods that a new epoch starts\n for method in con_methods:\n method.start_epoch()\n\n # accumulate connectivity scores\n if mode in ['multitaper', 'fourier']:\n for i in range(0, n_cons, block_size):\n con_idx = slice(i, i + block_size)\n if mt_adaptive:\n csd = _csd_from_mt(x_t[idx_map[0][con_idx]],\n x_t[idx_map[1][con_idx]],\n weights[idx_map[0][con_idx]],\n weights[idx_map[1][con_idx]])\n else:\n csd = _csd_from_mt(x_t[idx_map[0][con_idx]],\n x_t[idx_map[1][con_idx]],\n weights, weights)\n\n for method in con_methods:\n method.accumulate(con_idx, csd)\n else: # mode == 'cwt_morlet' # reminder to add alternative TFR methods\n for i_block, i in enumerate(range(0, n_cons, block_size)):\n con_idx = slice(i, i + block_size)\n # this codes can be very slow\n csd = (x_t[idx_map[0][con_idx]] *\n x_t[idx_map[1][con_idx]].conjugate())\n\n for method in con_methods:\n method.accumulate(con_idx, csd)\n # future estimator types need to be explicitly handled here\n\n return con_methods, psd\n\n\ndef _get_n_epochs(epochs, n):\n \"\"\"Generate lists with at most n epochs.\"\"\"\n epochs_out = list()\n for epoch in epochs:\n if not isinstance(epoch, (list, tuple)):\n epoch = (epoch,)\n epochs_out.append(epoch)\n if len(epochs_out) >= n:\n yield epochs_out\n epochs_out = list()\n if 0 < len(epochs_out) < n:\n yield epochs_out\n\n\ndef _check_method(method):\n \"\"\"Test if a method implements the required interface.\"\"\"\n interface_members = [m[0] for m in getmembers(_AbstractConEstBase)\n if not m[0].startswith('_')]\n method_members = [m[0] for m in getmembers(method)\n if not m[0].startswith('_')]\n\n for member in interface_members:\n if member not in method_members:\n return False, member\n return True, None\n\n\ndef _get_and_verify_data_sizes(data, sfreq, n_signals=None, n_times=None,\n times=None, warn_times=True):\n \"\"\"Get and/or verify the data sizes and time scales.\"\"\"\n if not isinstance(data, (list, tuple)):\n raise ValueError('data has to be a list or tuple')\n n_signals_tot = 0\n # Sometimes data can be (ndarray, SourceEstimate) groups so in the case\n # where ndarray comes first, don't use it for times\n times_inferred = False\n for this_data in data:\n this_n_signals, this_n_times = this_data.shape\n if n_times is not None:\n if this_n_times != n_times:\n raise ValueError('all input time series must have the same '\n 'number of time points')\n else:\n n_times = this_n_times\n n_signals_tot += this_n_signals\n\n if hasattr(this_data, 'times'):\n assert isinstance(this_data, _BaseSourceEstimate)\n this_times = this_data.times\n if times is not None and not times_inferred:\n if warn_times and not np.allclose(times, this_times):\n with np.printoptions(threshold=4, linewidth=120):\n warn('time scales of input time series do not match:\\n'\n f'{this_times}\\n{times}')\n warn_times = False\n else:\n times = this_times\n elif times is None:\n times_inferred = True\n times = _arange_div(n_times, sfreq)\n\n if n_signals is not None:\n if n_signals != n_signals_tot:\n raise ValueError('the number of time series has to be the same in '\n 'each epoch')\n n_signals = n_signals_tot\n\n return n_signals, n_times, times, warn_times\n\n\n# map names to estimator types\n_CON_METHOD_MAP = {'coh': _CohEst, 'cohy': _CohyEst, 'imcoh': _ImCohEst,\n 'plv': _PLVEst, 'ciplv': _ciPLVEst, 'ppc': _PPCEst,\n 'pli': _PLIEst, 'pli2_unbiased': _PLIUnbiasedEst,\n 'wpli': _WPLIEst, 'wpli2_debiased': _WPLIDebiasedEst}\n\n\ndef _check_estimators(method, mode):\n \"\"\"Check construction of connectivity estimators.\"\"\"\n n_methods = len(method)\n con_method_types = list()\n for this_method in method:\n if this_method in _CON_METHOD_MAP:\n con_method_types.append(_CON_METHOD_MAP[this_method])\n elif isinstance(this_method, str):\n raise ValueError('%s is not a valid connectivity method' %\n this_method)\n else:\n # support for custom class\n method_valid, msg = _check_method(this_method)\n if not method_valid:\n raise ValueError('The supplied connectivity method does '\n 'not have the method %s' % msg)\n con_method_types.append(this_method)\n\n # determine how many arguments the compute_con_function needs\n n_comp_args = [len(_get_args(mtype.compute_con))\n for mtype in con_method_types]\n\n # we currently only support 3 arguments\n if any(n not in (3, 5) for n in n_comp_args):\n raise ValueError('The .compute_con method needs to have either '\n '3 or 5 arguments')\n # if none of the comp_con functions needs the PSD, we don't estimate it\n accumulate_psd = any(n == 5 for n in n_comp_args)\n return con_method_types, n_methods, accumulate_psd, n_comp_args\n\n\n@verbose\ndef spectral_connectivity(data, method='coh', indices=None, sfreq=2 * np.pi,\n mode='multitaper', fmin=None, fmax=np.inf,\n fskip=0, faverage=False, tmin=None, tmax=None,\n mt_bandwidth=None, mt_adaptive=False,\n mt_low_bias=True, cwt_freqs=None,\n cwt_n_cycles=7, block_size=1000, n_jobs=1,\n verbose=None):\n \"\"\"Compute frequency- and time-frequency-domain connectivity measures.\n\n The connectivity method(s) are specified using the \"method\" parameter.\n All methods are based on estimates of the cross- and power spectral\n densities (CSD/PSD) Sxy and Sxx, Syy.\n\n Parameters\n ----------\n data : array-like, shape=(n_epochs, n_signals, n_times) | Epochs\n The data from which to compute connectivity. Note that it is also\n possible to combine multiple signals by providing a list of tuples,\n e.g., data = [(arr_0, stc_0), (arr_1, stc_1), (arr_2, stc_2)],\n corresponds to 3 epochs, and arr_* could be an array with the same\n number of time points as stc_*. The array-like object can also\n be a list/generator of array, shape =(n_signals, n_times),\n or a list/generator of SourceEstimate or VolSourceEstimate objects.\n method : str | list of str\n Connectivity measure(s) to compute.\n indices : tuple of array | None\n Two arrays with indices of connections for which to compute\n connectivity. If None, all connections are computed.\n sfreq : float\n The sampling frequency.\n mode : str\n Spectrum estimation mode can be either: 'multitaper', 'fourier', or\n 'cwt_morlet'.\n fmin : float | tuple of float\n The lower frequency of interest. Multiple bands are defined using\n a tuple, e.g., (8., 20.) for two bands with 8Hz and 20Hz lower freq.\n If None the frequency corresponding to an epoch length of 5 cycles\n is used.\n fmax : float | tuple of float\n The upper frequency of interest. Multiple bands are dedined using\n a tuple, e.g. (13., 30.) for two band with 13Hz and 30Hz upper freq.\n fskip : int\n Omit every \"(fskip + 1)-th\" frequency bin to decimate in frequency\n domain.\n faverage : bool\n Average connectivity scores for each frequency band. If True,\n the output freqs will be a list with arrays of the frequencies\n that were averaged.\n tmin : float | None\n Time to start connectivity estimation. Note: when \"data\" is an array,\n the first sample is assumed to be at time 0. For other types\n (Epochs, etc.), the time information contained in the object is used\n to compute the time indices.\n tmax : float | None\n Time to end connectivity estimation. Note: when \"data\" is an array,\n the first sample is assumed to be at time 0. For other types\n (Epochs, etc.), the time information contained in the object is used\n to compute the time indices.\n mt_bandwidth : float | None\n The bandwidth of the multitaper windowing function in Hz.\n Only used in 'multitaper' mode.\n mt_adaptive : bool\n Use adaptive weights to combine the tapered spectra into PSD.\n Only used in 'multitaper' mode.\n mt_low_bias : bool\n Only use tapers with more than 90%% spectral concentration within\n bandwidth. Only used in 'multitaper' mode.\n cwt_freqs : array\n Array of frequencies of interest. Only used in 'cwt_morlet' mode.\n cwt_n_cycles : float | array of float\n Number of cycles. Fixed number or one per frequency. Only used in\n 'cwt_morlet' mode.\n block_size : int\n How many connections to compute at once (higher numbers are faster\n but require more memory).\n n_jobs : int\n How many epochs to process in parallel.\n %(verbose)s\n\n Returns\n -------\n con : array | list of array\n Computed connectivity measure(s). The shape of each array is either\n (n_signals, n_signals, n_freqs) mode: 'multitaper' or 'fourier'\n (n_signals, n_signals, n_freqs, n_times) mode: 'cwt_morlet'\n when \"indices\" is None, or\n (n_con, n_freqs) mode: 'multitaper' or 'fourier'\n (n_con, n_freqs, n_times) mode: 'cwt_morlet'\n when \"indices\" is specified and \"n_con = len(indices[0])\".\n freqs : array\n Frequency points at which the connectivity was computed.\n times : array\n Time points for which the connectivity was computed.\n n_epochs : int\n Number of epochs used for computation.\n n_tapers : int\n The number of DPSS tapers used. Only defined in 'multitaper' mode.\n Otherwise None is returned.\n\n Notes\n -----\n The spectral densities can be estimated using a multitaper method with\n digital prolate spheroidal sequence (DPSS) windows, a discrete Fourier\n transform with Hanning windows, or a continuous wavelet transform using\n Morlet wavelets. The spectral estimation mode is specified using the\n \"mode\" parameter.\n\n By default, the connectivity between all signals is computed (only\n connections corresponding to the lower-triangular part of the\n connectivity matrix). If one is only interested in the connectivity\n between some signals, the \"indices\" parameter can be used. For example,\n to compute the connectivity between the signal with index 0 and signals\n \"2, 3, 4\" (a total of 3 connections) one can use the following::\n\n indices = (np.array([0, 0, 0]), # row indices\n np.array([2, 3, 4])) # col indices\n\n con_flat = spectral_connectivity(data, method='coh',\n indices=indices, ...)\n\n In this case con_flat.shape = (3, n_freqs). The connectivity scores are\n in the same order as defined indices.\n\n **Supported Connectivity Measures**\n\n The connectivity method(s) is specified using the \"method\" parameter. The\n following methods are supported (note: ``E[]`` denotes average over\n epochs). Multiple measures can be computed at once by using a list/tuple,\n e.g., ``['coh', 'pli']`` to compute coherence and PLI.\n\n 'coh' : Coherence given by::\n\n | E[Sxy] |\n C = ---------------------\n sqrt(E[Sxx] * E[Syy])\n\n 'cohy' : Coherency given by::\n\n E[Sxy]\n C = ---------------------\n sqrt(E[Sxx] * E[Syy])\n\n 'imcoh' : Imaginary coherence [1]_ given by::\n\n Im(E[Sxy])\n C = ----------------------\n sqrt(E[Sxx] * E[Syy])\n\n 'plv' : Phase-Locking Value (PLV) [2]_ given by::\n\n PLV = |E[Sxy/|Sxy|]|\n\n 'ciplv' : corrected imaginary PLV (icPLV) [3]_ given by::\n\n |E[Im(Sxy/|Sxy|)]|\n ciPLV = ------------------------------------\n sqrt(1 - |E[real(Sxy/|Sxy|)]| ** 2)\n\n 'ppc' : Pairwise Phase Consistency (PPC), an unbiased estimator\n of squared PLV [4]_.\n\n 'pli' : Phase Lag Index (PLI) [5]_ given by::\n\n PLI = |E[sign(Im(Sxy))]|\n\n 'pli2_unbiased' : Unbiased estimator of squared PLI [6]_.\n\n 'wpli' : Weighted Phase Lag Index (WPLI) [6]_ given by::\n\n |E[Im(Sxy)]|\n WPLI = ------------------\n E[|Im(Sxy)|]\n\n 'wpli2_debiased' : Debiased estimator of squared WPLI [6]_.\n\n References\n ----------\n .. [1] Nolte et al. \"Identifying true brain interaction from EEG data using\n the imaginary part of coherency\" Clinical neurophysiology, vol. 115,\n no. 10, pp. 2292-2307, Oct. 2004.\n .. [2] Lachaux et al. \"Measuring phase synchrony in brain signals\" Human\n brain mapping, vol. 8, no. 4, pp. 194-208, Jan. 1999.\n .. [3] Bruña et al. \"Phase locking value revisited: teaching new tricks to\n an old dog\" Journal of Neural Engineering, vol. 15, no. 5, pp.\n 056011 , Jul. 2018.\n .. [4] Vinck et al. \"The pairwise phase consistency: a bias-free measure of\n rhythmic neuronal synchronization\" NeuroImage, vol. 51, no. 1,\n pp. 112-122, May 2010.\n .. [5] Stam et al. \"Phase lag index: assessment of functional connectivity\n from multi channel EEG and MEG with diminished bias from common\n sources\" Human brain mapping, vol. 28, no. 11, pp. 1178-1193,\n Nov. 2007.\n .. [6] Vinck et al. \"An improved index of phase-synchronization for\n electro-physiological data in the presence of volume-conduction,\n noise and sample-size bias\" NeuroImage, vol. 55, no. 4,\n pp. 1548-1565, Apr. 2011.\n \"\"\"\n if n_jobs != 1:\n parallel, my_epoch_spectral_connectivity, _ = \\\n parallel_func(_epoch_spectral_connectivity, n_jobs,\n verbose=verbose)\n\n # format fmin and fmax and check inputs\n if fmin is None:\n fmin = -np.inf # set it to -inf, so we can adjust it later\n\n fmin = np.array((fmin,), dtype=float).ravel()\n fmax = np.array((fmax,), dtype=float).ravel()\n if len(fmin) != len(fmax):\n raise ValueError('fmin and fmax must have the same length')\n if np.any(fmin > fmax):\n raise ValueError('fmax must be larger than fmin')\n\n n_bands = len(fmin)\n\n # assign names to connectivity methods\n if not isinstance(method, (list, tuple)):\n method = [method] # make it a list so we can iterate over it\n\n # handle connectivity estimators\n (con_method_types, n_methods, accumulate_psd,\n n_comp_args) = _check_estimators(method=method, mode=mode)\n\n if isinstance(data, BaseEpochs):\n times_in = data.times # input times for Epochs input type\n sfreq = data.info['sfreq']\n else:\n times_in = None\n\n # loop over data; it could be a generator that returns\n # (n_signals x n_times) arrays or SourceEstimates\n epoch_idx = 0\n logger.info('Connectivity computation...')\n warn_times = True\n for epoch_block in _get_n_epochs(data, n_jobs):\n if epoch_idx == 0:\n # initialize everything times and frequencies\n (n_cons, times, n_times, times_in, n_times_in, tmin_idx,\n tmax_idx, n_freqs, freq_mask, freqs, freqs_bands, freq_idx_bands,\n n_signals, indices_use, warn_times) = _prepare_connectivity(\n epoch_block=epoch_block, times_in=times_in,\n tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, sfreq=sfreq,\n indices=indices, mode=mode, fskip=fskip, n_bands=n_bands,\n cwt_freqs=cwt_freqs, faverage=faverage)\n\n # get the window function, wavelets, etc for different modes\n (spectral_params, mt_adaptive, n_times_spectrum,\n n_tapers) = _assemble_spectral_params(\n mode=mode, n_times=n_times, mt_adaptive=mt_adaptive,\n mt_bandwidth=mt_bandwidth, sfreq=sfreq,\n mt_low_bias=mt_low_bias, cwt_n_cycles=cwt_n_cycles,\n cwt_freqs=cwt_freqs, freqs=freqs, freq_mask=freq_mask)\n\n # unique signals for which we actually need to compute PSD etc.\n sig_idx = np.unique(np.r_[indices_use[0], indices_use[1]])\n\n # map indices to unique indices\n idx_map = [np.searchsorted(sig_idx, ind) for ind in indices_use]\n\n # allocate space to accumulate PSD\n if accumulate_psd:\n if n_times_spectrum == 0:\n psd_shape = (len(sig_idx), n_freqs)\n else:\n psd_shape = (len(sig_idx), n_freqs, n_times_spectrum)\n psd = np.zeros(psd_shape)\n else:\n psd = None\n\n # create instances of the connectivity estimators\n con_methods = [mtype(n_cons, n_freqs, n_times_spectrum)\n for mtype in con_method_types]\n\n sep = ', '\n metrics_str = sep.join([meth.name for meth in con_methods])\n logger.info(' the following metrics will be computed: %s'\n % metrics_str)\n\n # check dimensions and time scale\n for this_epoch in epoch_block:\n _, _, _, warn_times = _get_and_verify_data_sizes(\n this_epoch, sfreq, n_signals, n_times_in, times_in,\n warn_times=warn_times)\n\n call_params = dict(\n sig_idx=sig_idx, tmin_idx=tmin_idx,\n tmax_idx=tmax_idx, sfreq=sfreq, mode=mode,\n freq_mask=freq_mask, idx_map=idx_map, block_size=block_size,\n psd=psd, accumulate_psd=accumulate_psd,\n mt_adaptive=mt_adaptive,\n con_method_types=con_method_types,\n con_methods=con_methods if n_jobs == 1 else None,\n n_signals=n_signals, n_times=n_times,\n accumulate_inplace=True if n_jobs == 1 else False)\n call_params.update(**spectral_params)\n\n if n_jobs == 1:\n # no parallel processing\n for this_epoch in epoch_block:\n logger.info(' computing connectivity for epoch %d'\n % (epoch_idx + 1))\n # con methods and psd are updated inplace\n _epoch_spectral_connectivity(data=this_epoch, **call_params)\n epoch_idx += 1\n else:\n # process epochs in parallel\n logger.info(' computing connectivity for epochs %d..%d'\n % (epoch_idx + 1, epoch_idx + len(epoch_block)))\n\n out = parallel(my_epoch_spectral_connectivity(\n data=this_epoch, **call_params)\n for this_epoch in epoch_block)\n # do the accumulation\n for this_out in out:\n for method, parallel_method in zip(con_methods, this_out[0]):\n method.combine(parallel_method)\n if accumulate_psd:\n psd += this_out[1]\n\n epoch_idx += len(epoch_block)\n\n # normalize\n n_epochs = epoch_idx\n if accumulate_psd:\n psd /= n_epochs\n\n # compute final connectivity scores\n con = list()\n for method, n_args in zip(con_methods, n_comp_args):\n # future estimators will need to be handled here\n if n_args == 3:\n # compute all scores at once\n method.compute_con(slice(0, n_cons), n_epochs)\n elif n_args == 5:\n # compute scores block-wise to save memory\n for i in range(0, n_cons, block_size):\n con_idx = slice(i, i + block_size)\n psd_xx = psd[idx_map[0][con_idx]]\n psd_yy = psd[idx_map[1][con_idx]]\n method.compute_con(con_idx, n_epochs, psd_xx, psd_yy)\n else:\n raise RuntimeError('This should never happen.')\n\n # get the connectivity scores\n this_con = method.con_scores\n\n if this_con.shape[0] != n_cons:\n raise ValueError('First dimension of connectivity scores must be '\n 'the same as the number of connections')\n if faverage:\n if this_con.shape[1] != n_freqs:\n raise ValueError('2nd dimension of connectivity scores must '\n 'be the same as the number of frequencies')\n con_shape = (n_cons, n_bands) + this_con.shape[2:]\n this_con_bands = np.empty(con_shape, dtype=this_con.dtype)\n for band_idx in range(n_bands):\n this_con_bands[:, band_idx] =\\\n np.mean(this_con[:, freq_idx_bands[band_idx]], axis=1)\n this_con = this_con_bands\n\n con.append(this_con)\n\n if indices is None:\n # return all-to-all connectivity matrices\n logger.info(' assembling connectivity matrix '\n '(filling the upper triangular region of the matrix)')\n con_flat = con\n con = list()\n for this_con_flat in con_flat:\n this_con = np.zeros((n_signals, n_signals) +\n this_con_flat.shape[1:],\n dtype=this_con_flat.dtype)\n this_con[indices_use] = this_con_flat\n con.append(this_con)\n\n logger.info('[Connectivity computation done]')\n\n if n_methods == 1:\n # for a single method return connectivity directly\n con = con[0]\n\n if faverage:\n # for each band we return the frequencies that were averaged\n freqs = freqs_bands\n\n return con, freqs, times, n_epochs, n_tapers\n\n\ndef _prepare_connectivity(epoch_block, times_in, tmin, tmax,\n fmin, fmax, sfreq, indices,\n mode, fskip, n_bands,\n cwt_freqs, faverage):\n \"\"\"Check and precompute dimensions of results data.\"\"\"\n rfftfreq = _import_fft('rfftfreq')\n first_epoch = epoch_block[0]\n\n # get the data size and time scale\n n_signals, n_times_in, times_in, warn_times = _get_and_verify_data_sizes(\n first_epoch, sfreq, times=times_in)\n\n n_times_in = len(times_in)\n\n if tmin is not None and tmin < times_in[0]:\n warn('start time tmin=%0.2f s outside of the time scope of the data '\n '[%0.2f s, %0.2f s]' % (tmin, times_in[0], times_in[-1]))\n if tmax is not None and tmax > times_in[-1]:\n warn('stop time tmax=%0.2f s outside of the time scope of the data '\n '[%0.2f s, %0.2f s]' % (tmax, times_in[0], times_in[-1]))\n\n mask = _time_mask(times_in, tmin, tmax, sfreq=sfreq)\n tmin_idx, tmax_idx = np.where(mask)[0][[0, -1]]\n tmax_idx += 1\n tmin_true = times_in[tmin_idx]\n tmax_true = times_in[tmax_idx - 1] # time of last point used\n\n times = times_in[tmin_idx:tmax_idx]\n n_times = len(times)\n\n if indices is None:\n logger.info('only using indices for lower-triangular matrix')\n # only compute r for lower-triangular region\n indices_use = np.tril_indices(n_signals, -1)\n else:\n indices_use = check_indices(indices)\n\n # number of connectivities to compute\n n_cons = len(indices_use[0])\n\n logger.info(' computing connectivity for %d connections'\n % n_cons)\n logger.info(' using t=%0.3fs..%0.3fs for estimation (%d points)'\n % (tmin_true, tmax_true, n_times))\n\n # get frequencies of interest for the different modes\n if mode in ('multitaper', 'fourier'):\n # fmin fmax etc is only supported for these modes\n # decide which frequencies to keep\n freqs_all = rfftfreq(n_times, 1. / sfreq)\n elif mode == 'cwt_morlet':\n # cwt_morlet mode\n if cwt_freqs is None:\n raise ValueError('define frequencies of interest using '\n 'cwt_freqs')\n else:\n cwt_freqs = cwt_freqs.astype(np.float64)\n if any(cwt_freqs > (sfreq / 2.)):\n raise ValueError('entries in cwt_freqs cannot be '\n 'larger than Nyquist (sfreq / 2)')\n freqs_all = cwt_freqs\n else:\n raise ValueError('mode has an invalid value')\n\n # check that fmin corresponds to at least 5 cycles\n dur = float(n_times) / sfreq\n five_cycle_freq = 5. / dur\n if len(fmin) == 1 and fmin[0] == -np.inf:\n # we use the 5 cycle freq. as default\n fmin = np.array([five_cycle_freq])\n else:\n if np.any(fmin < five_cycle_freq):\n warn('fmin=%0.3f Hz corresponds to %0.3f < 5 cycles '\n 'based on the epoch length %0.3f sec, need at least %0.3f '\n 'sec epochs or fmin=%0.3f. Spectrum estimate will be '\n 'unreliable.' % (np.min(fmin), dur * np.min(fmin), dur,\n 5. / np.min(fmin), five_cycle_freq))\n\n # create a frequency mask for all bands\n freq_mask = np.zeros(len(freqs_all), dtype=bool)\n for f_lower, f_upper in zip(fmin, fmax):\n freq_mask |= ((freqs_all >= f_lower) & (freqs_all <= f_upper))\n\n # possibly skip frequency points\n for pos in range(fskip):\n freq_mask[pos + 1::fskip + 1] = False\n\n # the frequency points where we compute connectivity\n freqs = freqs_all[freq_mask]\n n_freqs = len(freqs)\n\n # get the freq. indices and points for each band\n freq_idx_bands = [np.where((freqs >= fl) & (freqs <= fu))[0]\n for fl, fu in zip(fmin, fmax)]\n freqs_bands = [freqs[freq_idx] for freq_idx in freq_idx_bands]\n\n # make sure we don't have empty bands\n for i, n_f_band in enumerate([len(f) for f in freqs_bands]):\n if n_f_band == 0:\n raise ValueError('There are no frequency points between '\n '%0.1fHz and %0.1fHz. Change the band '\n 'specification (fmin, fmax) or the '\n 'frequency resolution.'\n % (fmin[i], fmax[i]))\n if n_bands == 1:\n logger.info(' frequencies: %0.1fHz..%0.1fHz (%d points)'\n % (freqs_bands[0][0], freqs_bands[0][-1],\n n_freqs))\n else:\n logger.info(' computing connectivity for the bands:')\n for i, bfreqs in enumerate(freqs_bands):\n logger.info(' band %d: %0.1fHz..%0.1fHz '\n '(%d points)' % (i + 1, bfreqs[0],\n bfreqs[-1], len(bfreqs)))\n if faverage:\n logger.info(' connectivity scores will be averaged for '\n 'each band')\n\n return (n_cons, times, n_times, times_in, n_times_in, tmin_idx,\n tmax_idx, n_freqs, freq_mask, freqs, freqs_bands, freq_idx_bands,\n n_signals, indices_use, warn_times)\n\n\ndef _assemble_spectral_params(mode, n_times, mt_adaptive, mt_bandwidth, sfreq,\n mt_low_bias, cwt_n_cycles, cwt_freqs,\n freqs, freq_mask):\n \"\"\"Prepare time-frequency decomposition.\"\"\"\n spectral_params = dict(\n eigvals=None, window_fun=None, wavelets=None)\n n_tapers = None\n n_times_spectrum = 0\n if mode == 'multitaper':\n window_fun, eigvals, mt_adaptive = _compute_mt_params(\n n_times, sfreq, mt_bandwidth, mt_low_bias, mt_adaptive)\n spectral_params.update(window_fun=window_fun, eigvals=eigvals)\n elif mode == 'fourier':\n logger.info(' using FFT with a Hanning window to estimate '\n 'spectra')\n spectral_params.update(window_fun=np.hanning(n_times), eigvals=1.)\n elif mode == 'cwt_morlet':\n logger.info(' using CWT with Morlet wavelets to estimate '\n 'spectra')\n\n # reformat cwt_n_cycles if we have removed some frequencies\n # using fmin, fmax, fskip\n cwt_n_cycles = np.array((cwt_n_cycles,), dtype=float).ravel()\n if len(cwt_n_cycles) > 1:\n if len(cwt_n_cycles) != len(cwt_freqs):\n raise ValueError('cwt_n_cycles must be float or an '\n 'array with the same size as cwt_freqs')\n cwt_n_cycles = cwt_n_cycles[freq_mask]\n\n # get the Morlet wavelets\n spectral_params.update(\n wavelets=morlet(sfreq, freqs,\n n_cycles=cwt_n_cycles, zero_mean=True))\n n_times_spectrum = n_times\n else:\n raise ValueError('mode has an invalid value')\n return spectral_params, mt_adaptive, n_times_spectrum, n_tapers\n" ]
[ [ "numpy.dot", "scipy.linalg.pinv", "numpy.sqrt", "numpy.asarray", "sklearn.decomposition.FastICA", "numpy.cumsum", "numpy.concatenate", "numpy.round", "numpy.exp", "numpy.where", "numpy.hstack", "numpy.allclose", "numpy.unique", "numpy.arange", "numpy.eye", "numpy.std", "numpy.argmax", "numpy.zeros", "numpy.log", "numpy.nonzero", "numpy.median", "numpy.corrcoef", "numpy.array", "numpy.sum", "numpy.abs", "numpy.linalg.norm", "numpy.ones", "numpy.sign", "numpy.linalg.pinv", "numpy.float64" ], [ "numpy.imag", "numpy.sqrt", "numpy.concatenate", "numpy.mean", "numpy.any", "numpy.searchsorted", "numpy.hanning", "numpy.where", "numpy.allclose", "numpy.clip", "numpy.tril_indices", "numpy.unique", "numpy.real", "numpy.zeros", "numpy.min", "numpy.array", "numpy.sum", "numpy.printoptions", "numpy.abs", "numpy.conj", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tuananhle7/hmws
[ "175f77a2b386ce5a9598b61c982e053e7ecff8a2" ]
[ "cmws/examples/timeseries_real/lstm_util.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport cmws.util\n\n\ndef step_lstm(lstm, input_, h_0_c_0=None):\n \"\"\"LSTMCell-like API for LSTM.\n Args:\n lstm: nn.LSTM\n input_: [batch_size, input_size]\n h_0_c_0: None or\n h_0: [num_layers, batch_size, hidden_size]\n c_0: [num_layers, batch_size, hidden_size]\n Returns:\n output: [batch_size, hidden_size]\n h_1_c_1:\n h_1: [num_layers, batch_size, hidden_size]\n c_1: [num_layers, batch_size, hidden_size]\n \"\"\"\n output, h_1_c_1 = lstm(input_[None], h_0_c_0)\n return output[0], h_1_c_1\n\n\ndef get_num_timesteps(eos):\n \"\"\"\n Args\n eos [*shape, max_num_timesteps]\n\n Returns [*shape]\n \"\"\"\n # Extract\n shape = eos.shape[:-1]\n max_num_timesteps = eos.shape[-1]\n num_elements = cmws.util.get_num_elements(shape)\n device = eos.device\n\n # Flatten\n eos_flattened = eos.reshape(-1, max_num_timesteps)\n\n num_timesteps = []\n for element_id in range(num_elements):\n if torch.all(eos_flattened[element_id] == 0):\n num_timesteps.append(max_num_timesteps)\n else:\n num_timesteps.append(\n (eos_flattened[element_id] == 1).nonzero(as_tuple=False)[0].item() + 1\n )\n return torch.tensor(num_timesteps, device=device).view(shape)\n\n\nclass TimeseriesDistribution:\n \"\"\"p(x_{1:T}, eos_{1:T} | embedding) where x_t ∈ Z or R^d\n batch_shape [batch_size]\n or\n []\n and\n event_shape ([max_num_timesteps(, x_dim)], [max_num_timesteps])\n or\n [max_num_timesteps(, x_dim)]\n\n Args\n x_type (str) continuous or discrete\n num_classes_or_dim (int)\n embedding: [batch_size, embedding_dim] or None\n lstm: nn.Module object\n linear: nn.Module mapping from LSTM hidden state to per-timestep distribution params\n lstm_eos: bool; models length if True\n max_num_timesteps (int; default 200)\n Returns distribution with batch_shape [batch_size] and event_shape [num_timesteps]\n where num_timesteps is variable\n \"\"\"\n\n def __init__(\n self, x_type, num_classes_or_dim, embedding, lstm, linear, lstm_eos, max_num_timesteps=200,\n ):\n self.x_type = x_type\n self.num_classes_or_dim = num_classes_or_dim\n if x_type == \"continuous\":\n self.x_dim = num_classes_or_dim\n elif x_type == \"discrete\":\n self.num_classes = num_classes_or_dim\n else:\n raise ValueError()\n self.lstm = lstm\n self.linear = linear\n self.lstm_eos = lstm_eos\n self.max_num_timesteps = max_num_timesteps\n self.embedding = embedding\n if self.embedding is not None:\n self.batch_size = self.embedding.shape[0]\n\n @property\n def device(self):\n return next(iter(self.lstm.parameters())).device\n\n def _sample(self, reparam, sample_shape=torch.Size(), num_timesteps=None, warning_enabled=True):\n \"\"\"\n Args:\n reparam (bool)\n sample_shape:\n num_timesteps: None or [*sample_shape, batch_size]\n NOTE: if provided, will sample for num_timesteps regardless of whether\n lstm_eos is True or not. if not provided, the length will be dicated by\n the end-of-signal indicator.\n Returns:\n x [*sample_shape(, batch_size), max_num_timesteps(, x_dim)]\n\n Optionally\n eos [*sample_shape(, batch_size), max_num_timesteps]\n \"\"\"\n if reparam:\n assert self.x_type == \"continuous\"\n num_samples = cmws.util.get_num_elements(sample_shape)\n if num_timesteps is None: # use EOS to end\n if not self.lstm_eos:\n raise RuntimeError(\n \"num_timesteps is not given and LSTM doesn't support end-of-signal indicator \"\n \"sampling. Don't know how end sampling.\"\n )\n else: # use num_timesteps to end\n if self.lstm_eos and warning_enabled:\n print(\n \"WARNING: num_timesteps is given and LSTM supports end-of-signal indicator.\"\n \" Sampling will ignore EOS and end based on num_timesteps.\"\n )\n\n if self.embedding is not None:\n # [num_samples * batch_size, embedding_dim]\n embedding_expanded = (\n self.embedding[None]\n .expand(num_samples, self.batch_size, -1)\n .contiguous()\n .view(num_samples * self.batch_size, -1)\n )\n\n # will be a list of length max_num_timesteps\n x = []\n if num_timesteps is None: # use EOS to end\n eos = []\n\n if self.embedding is not None:\n # [num_samples * batch_size, num_classes_or_dim + embedding_dim]\n lstm_input = torch.cat(\n [\n torch.zeros(\n (num_samples * self.batch_size, self.num_classes_or_dim),\n device=self.device,\n ),\n embedding_expanded,\n ],\n dim=1,\n )\n else:\n # [num_samples, num_classes_or_dim + embedding_dim]\n lstm_input = torch.zeros((num_samples, self.num_classes_or_dim), device=self.device,)\n hc = None\n for timestep in range(self.max_num_timesteps):\n # [num_samples( * batch_size), lstm_hidden_size], ([...], [...])\n lstm_output, hc = step_lstm(self.lstm, lstm_input, hc)\n\n # [num_samples( * batch_size), num_classes + 1 or num_classes]\n linear_out = self.linear(lstm_output)\n\n if self.x_type == \"discrete\":\n # [num_samples( * batch_size), num_classes]\n x_logits = linear_out[..., : self.num_classes]\n\n # batch_shape [num_samples( * batch_size)], event_shape []\n x_dist = torch.distributions.Categorical(logits=x_logits)\n elif self.x_type == \"continuous\":\n # [num_samples( * batch_size), x_dim]\n x_loc = linear_out[..., : self.x_dim]\n\n # [num_samples( * batch_size), x_dim]\n x_scale = linear_out[..., self.x_dim : 2 * self.x_dim].exp()\n\n # batch_shape [num_samples( * batch_size)], event_shape [x_dim]\n x_dist = torch.distributions.Independent(\n torch.distributions.Normal(loc=x_loc, scale=x_scale),\n reinterpreted_batch_ndims=1,\n )\n\n # sample\n # [num_samples( * batch_size)] or [num_samples( * batch_size), x_dim]\n if reparam:\n x.append(x_dist.rsample())\n else:\n x.append(x_dist.sample())\n\n if num_timesteps is None: # use EOS to end\n eos_logit = linear_out[..., -1]\n # [num_samples( * batch_size)]\n eos.append(torch.distributions.Bernoulli(logits=eos_logit).sample())\n\n # assemble lstm_input\n if self.x_type == \"discrete\":\n if self.embedding is not None:\n # [num_samples * batch_size, num_classes + embedding_dim]\n lstm_input = torch.cat(\n [F.one_hot(x[-1], num_classes=self.num_classes), embedding_expanded], dim=1\n )\n else:\n # [num_samples, num_classes + embedding_dim]\n lstm_input = F.one_hot(x[-1], num_classes=self.num_classes).float()\n elif self.x_type == \"continuous\":\n if self.embedding is not None:\n # [num_samples * batch_size, x_dim + embedding_dim]\n lstm_input = torch.cat([x[-1], embedding_expanded], dim=1)\n else:\n # [num_samples, x_dim + embedding_dim]\n lstm_input = x[-1]\n\n # if num_timesteps is None: # use EOS to end\n # # end early if all eos are 1\n # if (torch.stack(eos).sum(0) > 0).all():\n # # max_num_timesteps = timestep + 1\n # break\n\n if self.embedding is not None:\n if self.x_type == \"discrete\":\n # [max_num_timesteps, num_samples, batch_size]\n x = torch.stack(x).view(self.max_num_timesteps, num_samples, self.batch_size)\n elif self.x_type == \"continuous\":\n # [max_num_timesteps, num_samples, batch_size, x_dim]\n x = torch.stack(x).view(\n self.max_num_timesteps, num_samples, self.batch_size, self.x_dim\n )\n\n if num_timesteps is None: # use EOS to end\n # [max_num_timesteps, num_samples, batch_size]\n eos = torch.stack(eos).view(self.max_num_timesteps, num_samples, self.batch_size)\n\n # thing to be returned\n x_final = []\n eos_final = []\n for sample_id in range(num_samples):\n for batch_id in range(self.batch_size):\n if num_timesteps is None: # use EOS to end\n # [max_num_timesteps]\n eos_single = eos[:, sample_id, batch_id]\n if (eos_single == 0).all():\n num_timesteps_sb = len(eos_single)\n else:\n num_timesteps_sb = (eos_single == 1).nonzero(as_tuple=False)[\n 0\n ].item() + 1\n\n eos_final.append(\n F.one_hot(\n torch.tensor(num_timesteps_sb - 1, device=self.device).long(),\n num_classes=self.max_num_timesteps,\n )\n )\n else: # use num_timesteps to end\n num_timesteps_sb = num_timesteps.view(num_samples, self.batch_size)[\n sample_id, batch_id\n ]\n\n if self.x_type == \"discrete\":\n result = torch.zeros((self.max_num_timesteps,), device=self.device)\n result[:num_timesteps_sb] = x[:num_timesteps_sb, sample_id, batch_id]\n elif self.x_type == \"continuous\":\n result = torch.zeros(\n (self.max_num_timesteps, self.x_dim), device=self.device\n )\n result[:num_timesteps_sb] = x[:num_timesteps_sb, sample_id, batch_id]\n x_final.append(result)\n\n if self.x_type == \"discrete\":\n x_final = (\n torch.stack(x_final)\n .view(*[*sample_shape, self.batch_size, self.max_num_timesteps])\n .long()\n )\n elif self.x_type == \"continuous\":\n x_final = torch.stack(x_final).view(\n *[*sample_shape, self.batch_size, self.max_num_timesteps, self.x_dim]\n )\n if num_timesteps is None:\n eos_final = (\n torch.stack(eos_final).view(*[*sample_shape, self.batch_size, -1]).long()\n )\n return x_final, eos_final\n else:\n return x_final\n else:\n if self.x_type == \"discrete\":\n # [max_num_timesteps, num_samples]\n x = torch.stack(x).view(self.max_num_timesteps, num_samples)\n elif self.x_type == \"continuous\":\n # [max_num_timesteps, num_samples, x_dim]\n x = torch.stack(x).view(self.max_num_timesteps, num_samples, self.x_dim)\n\n if num_timesteps is None: # use EOS to end\n # [max_num_timesteps, num_samples]\n eos = torch.stack(eos).view(self.max_num_timesteps, num_samples)\n\n # thing to be returned\n x_final = []\n eos_final = []\n for sample_id in range(num_samples):\n if num_timesteps is None: # use EOS to end\n # [max_num_timesteps]\n eos_single = eos[:, sample_id]\n if (eos_single == 0).all():\n num_timesteps_sb = len(eos_single)\n else:\n num_timesteps_sb = (eos_single == 1).nonzero(as_tuple=False)[0].item() + 1\n\n eos_final.append(\n F.one_hot(\n torch.tensor(num_timesteps_sb - 1, device=self.device).long(),\n num_classes=self.max_num_timesteps,\n )\n )\n else: # use num_timesteps to end\n num_timesteps_sb = num_timesteps.view(num_samples)[sample_id]\n\n if self.x_type == \"discrete\":\n result = torch.zeros((self.max_num_timesteps,), device=self.device)\n result[:num_timesteps_sb] = x[:num_timesteps_sb, sample_id]\n elif self.x_type == \"continuous\":\n result = torch.zeros((self.max_num_timesteps, self.x_dim), device=self.device)\n result[:num_timesteps_sb] = x[:num_timesteps_sb, sample_id]\n x_final.append(result)\n\n if self.x_type == \"discrete\":\n x_final = torch.stack(x_final).view(*[*sample_shape, self.max_num_timesteps]).long()\n elif self.x_type == \"continuous\":\n x_final = torch.stack(x_final).view(\n *[*sample_shape, self.max_num_timesteps, self.x_dim]\n )\n if num_timesteps is None:\n eos_final = torch.stack(eos_final).view(*[*sample_shape, -1]).long()\n return x_final, eos_final\n else:\n return x_final\n\n def sample(self, sample_shape=torch.Size(), num_timesteps=None, warning_enabled=True):\n \"\"\"NOT reparameterized\n\n Args:\n sample_shape:\n num_timesteps: None or [*sample_shape, batch_size]\n NOTE: if provided, will sample for num_timesteps regardless of whether\n lstm_eos is True or not. if not provided, the length will be dicated by\n the end-of-signal indicator.\n Returns:\n x [*sample_shape(, batch_size), max_num_timesteps(, x_dim)]\n\n Optionally\n eos [*sample_shape(, batch_size), max_num_timesteps]\n \"\"\"\n return self._sample(\n False,\n sample_shape=sample_shape,\n num_timesteps=num_timesteps,\n warning_enabled=warning_enabled,\n )\n\n def rsample(self, sample_shape=torch.Size(), num_timesteps=None, warning_enabled=True):\n \"\"\"Reparameterized\n\n Args:\n sample_shape:\n num_timesteps: None or [*sample_shape, batch_size]\n NOTE: if provided, will sample for num_timesteps regardless of whether\n lstm_eos is True or not. if not provided, the length will be dicated by\n the end-of-signal indicator.\n Returns:\n x [*sample_shape(, batch_size), max_num_timesteps(, x_dim)]\n\n Optionally\n eos [*sample_shape(, batch_size), max_num_timesteps]\n \"\"\"\n return self._sample(\n True,\n sample_shape=sample_shape,\n num_timesteps=num_timesteps,\n warning_enabled=warning_enabled,\n )\n\n def log_prob(self, x, eos=None, num_timesteps=None):\n \"\"\"\n Args:\n x [batch_size, max_num_timesteps(, x_dim)]\n\n Optional\n eos [batch_size, max_num_timesteps]\n num_timesteps [batch_size]\n\n Returns: tensor [batch_size]\n \"\"\"\n batch_size = len(x)\n if self.embedding is not None:\n assert batch_size == self.batch_size\n\n if num_timesteps is None:\n num_timesteps = get_num_timesteps(eos)\n\n # Downsample x\n x_seq = []\n\n # Build LSTM input\n # [batch_size]\n zero_length_x = torch.zeros((batch_size,), device=self.device, dtype=torch.bool)\n lstm_input = []\n for batch_id in range(batch_size):\n num_timesteps_b = num_timesteps[batch_id]\n if num_timesteps_b == 0:\n zero_length_x[batch_id] = True\n if self.x_type == \"discrete\":\n x_b = torch.tensor([0.0], device=self.device)\n elif self.x_type == \"continuous\":\n x_b = torch.zeros((1, self.x_dim), device=self.device)\n num_timesteps_b += 1\n # print(f\"Warning: x[{batch_id}] has length 0. Setting its log_prob to 0.\")\n else:\n x_b = x[batch_id, :num_timesteps_b]\n\n x_seq.append(x_b)\n\n if self.embedding is not None:\n # [num_timesteps_b, embedding_dim]\n embedding_expanded = self.embedding[batch_id][None].expand(num_timesteps_b, -1)\n if self.x_type == \"discrete\":\n # [num_timesteps_b, num_classes]\n shifted_x = torch.cat(\n [\n torch.zeros((1, self.num_classes), device=self.device),\n F.one_hot(x_b[:-1].long(), num_classes=self.num_classes),\n ]\n )\n elif self.x_type == \"continuous\":\n # [num_timesteps_b, x_dim]\n shifted_x = torch.cat([torch.zeros((1, self.x_dim), device=self.device), x_b[:-1]])\n\n if self.embedding is not None:\n # [num_timesteps_b, num_classes_or_dim + embedding_dim]\n lstm_input.append(torch.cat([shifted_x, embedding_expanded], dim=1))\n else:\n # [num_timesteps_b, num_classes_or_dim]\n lstm_input.append(shifted_x)\n lstm_input = nn.utils.rnn.pack_sequence(lstm_input, enforce_sorted=False)\n\n # Run LSTM\n # [*, batch_size, lstm_hidden_size]\n output, _ = self.lstm(lstm_input)\n # [max_num_timesteps, batch_size, lstm_hidden_size]\n padded_output, _ = nn.utils.rnn.pad_packed_sequence(\n output, total_length=self.max_num_timesteps\n )\n\n # Extract distribution params for x_t\n # [max_num_timesteps, batch_size, num_classes or 2*x_dim + 1 or num_classes or 2*x_dim]\n linear_out = self.linear(padded_output.view(self.max_num_timesteps * batch_size, -1)).view(\n self.max_num_timesteps, batch_size, -1\n )\n\n if self.x_type == \"discrete\":\n # [max_num_timesteps, batch_size, num_classes]\n x_logits = linear_out[..., : self.num_classes]\n\n # batch_shape [max_num_timesteps, batch_size], event_shape []\n x_dist = torch.distributions.Categorical(logits=x_logits)\n elif self.x_type == \"continuous\":\n # [max_num_timesteps, batch_size, x_dim]\n x_loc = linear_out[..., : self.x_dim]\n # [max_num_timesteps, batch_size, x_dim]\n x_scale = linear_out[..., self.x_dim : 2 * self.x_dim].exp()\n\n # batch_shape [max_num_timesteps, batch_size], event_shape [x_dim]\n x_dist = torch.distributions.Independent(\n torch.distributions.Normal(loc=x_loc, scale=x_scale), reinterpreted_batch_ndims=1\n )\n\n # Evaluate log prob\n if self.x_type == \"discrete\":\n # [max_num_timesteps, batch_size]\n x_log_prob = x_dist.log_prob(x.T)\n elif self.x_type == \"continuous\":\n # [max_num_timesteps, batch_size]\n x_log_prob = x_dist.log_prob(x.permute(1, 0, 2))\n\n if self.lstm_eos:\n # [max_num_timesteps, batch_size]\n eos_logit = linear_out[..., -1]\n\n # [max_num_timesteps, batch_size]\n eos_log_prob = torch.distributions.Bernoulli(logits=eos_logit).log_prob(eos.T.float())\n\n # this will be a list of length batch_size\n log_prob = []\n for batch_id in range(batch_size):\n num_timesteps_b = num_timesteps[batch_id]\n if self.lstm_eos:\n log_prob_b = (x_log_prob[:, batch_id] + eos_log_prob[:, batch_id])[\n :num_timesteps_b\n ].sum()\n else:\n log_prob_b = x_log_prob[:, batch_id][:num_timesteps_b].sum()\n log_prob.append(log_prob_b)\n return torch.stack(log_prob) * (1 - zero_length_x.float())\n" ]
[ [ "torch.all", "torch.Size", "torch.zeros", "torch.cat", "torch.nn.functional.one_hot", "torch.distributions.Bernoulli", "torch.tensor", "torch.nn.utils.rnn.pad_packed_sequence", "torch.distributions.Categorical", "torch.distributions.Normal", "torch.stack", "torch.nn.utils.rnn.pack_sequence" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
open-data-toronto/operations
[ "db180e655e435338bc57f22a3e706a5bdc40304e" ]
[ "dags/datasets/licensed-child-care-centres.py" ]
[ "import hashlib\nimport json\nimport logging\nimport os\nfrom datetime import datetime\nfrom pathlib import Path\n\nimport pandas as pd\nfrom airflow import DAG\nfrom airflow.models import Variable\nfrom airflow.operators.dummy import DummyOperator\nfrom airflow.operators.python import BranchPythonOperator, PythonOperator\nfrom ckan_operators.datastore_operator import (\n BackupDatastoreResourceOperator, DeleteDatastoreResourceRecordsOperator,\n InsertDatastoreResourceRecordsOperator,\n RestoreDatastoreResourceBackupOperator)\nfrom ckan_operators.package_operator import GetPackageOperator\nfrom ckan_operators.resource_operator import (GetOrCreateResourceOperator,\n ResourceAndFileOperator)\nfrom dateutil import parser\nfrom utils import agol_utils, airflow_utils\nfrom utils_operators.directory_operator import CreateLocalDirectoryOperator\nfrom utils_operators.file_operators import DownloadFileOperator\nfrom utils_operators.slack_operators import task_success_slack_alert, task_failure_slack_alert, GenericSlackOperator\n\n\nSRC_URL = \"http://opendata.toronto.ca/childrens.services/licensed-child-care-centres/child-care.csv\" # noqa: E501\nPACKAGE_NAME = \"licensed-child-care-centres\"\nRESOURCE_NAME = \"Child care centres\"\n\nEXPECTED_COLUMNS = [\n \"LOC_ID\",\n \"LOC_NAME\",\n \"AUSPICE\",\n \"ADDRESS\",\n \"PCODE\",\n \"ward\",\n \"PHONE\",\n \"bldg_type\",\n \"BLDGNAME\",\n \"IGSPACE\",\n \"TGSPACE\",\n \"PGSPACE\",\n \"KGSPACE\",\n \"SGSPACE\",\n \"TOTSPACE\",\n \"subsidy\",\n \"run_date\",\n \"latitude\",\n \"longitude\",\n]\n\n\ndef send_failure_msg():\n airflow_utils.message_slack(\n name=PACKAGE_NAME,\n message_type=\"error\",\n msg=\"Job not finished\",\n active_env=Variable.get(\"active_env\"),\n prod_webhook=Variable.get(\"active_env\") == \"prod\",\n )\n\n\nwith DAG(\n PACKAGE_NAME,\n default_args=airflow_utils.get_default_args(\n {\n \"on_failure_callback\": task_failure_slack_alert,\n \"start_date\": datetime(2020, 11, 24, 13, 35, 0),\n \"retries\": 0,\n # \"retry_delay\": timedelta(minutes=3),\n }\n ),\n description=\"Take data from opendata.toronto.ca (CSV) and put into datastore\",\n schedule_interval=\"0 17 * * *\",\n catchup=False,\n tags=[\"dataset\"],\n) as dag:\n\n def is_resource_new(**kwargs):\n package = kwargs[\"ti\"].xcom_pull(task_ids=\"get_package\")\n logging.info(f\"resources found: {[r['name'] for r in package['resources']]}\")\n is_new = RESOURCE_NAME not in [r[\"name\"] for r in package[\"resources\"]]\n\n if is_new:\n return \"resource_is_new\"\n\n return \"resource_is_not_new\"\n\n def is_data_new(**kwargs):\n ti = kwargs[\"ti\"]\n fields = ti.xcom_pull(task_ids=\"get_fields\")\n if fields is not None:\n return \"data_is_new\"\n\n backups_dir = Path(ti.xcom_pull(task_ids=\"backups_dir\"))\n backup_data = ti.xcom_pull(task_ids=\"backup_data\")\n\n df = pd.read_parquet(backup_data[\"data\"])\n\n if df.shape[0] == 0:\n return \"data_is_new\"\n\n checksum = hashlib.md5()\n checksum.update(df.sort_values(by=\"LOC_ID\").to_csv(index=False).encode(\"utf-8\"))\n checksum = checksum.hexdigest()\n\n for f in os.listdir(backups_dir):\n if not os.path.isfile(backups_dir / f):\n continue\n logging.info(f\"File in backups: {f}\")\n\n if os.path.isfile(backups_dir / f) and checksum in f:\n logging.info(f\"Data has already been loaded, ID: {checksum}\")\n return \"data_is_not_new\"\n\n logging.info(f\"Data has not been loaded, new ID: {checksum}\")\n\n return \"data_is_new\"\n\n def transform_data(**kwargs):\n ti = kwargs.pop(\"ti\")\n tmp_dir = Path(ti.xcom_pull(task_ids=\"tmp_dir\"))\n data_fp = Path(ti.xcom_pull(task_ids=\"get_data\")[\"path\"])\n\n data = pd.read_csv(data_fp)\n\n data[\"geometry\"] = data.apply(\n lambda x: json.dumps(\n {\"type\": \"Point\", \"coordinates\": [x[\"longitude\"], x[\"latitude\"]]}\n )\n if x[\"longitude\"] and x[\"latitude\"]\n else \"\",\n axis=1,\n )\n\n data = agol_utils.remove_geo_columns(data)\n\n filename = \"new_data_transformed\"\n filepath = tmp_dir / f\"{filename}.parquet\"\n\n data.to_parquet(filepath, engine=\"fastparquet\", compression=None)\n\n return filepath\n\n def validate_expected_columns(**kwargs):\n ti = kwargs[\"ti\"]\n data_fp = Path(ti.xcom_pull(task_ids=\"get_data\")[\"path\"])\n\n df = pd.read_csv(data_fp)\n\n for col in df.columns.values:\n assert col in EXPECTED_COLUMNS, f\"{col} not in list of expected columns\"\n\n for col in EXPECTED_COLUMNS:\n assert col in df.columns.values, f\"Expected column {col} not in data file\"\n\n def is_file_new(**kwargs):\n ti = kwargs[\"ti\"]\n data_file_info = ti.xcom_pull(task_ids=\"get_data\")\n resource = ti.xcom_pull(task_ids=\"get_or_create_resource\")\n\n logging.info(f\"resource: {resource} | data_file_info: {data_file_info}\")\n\n last_modified_string = data_file_info[\"last_modified\"]\n file_last_modified = parser.parse(last_modified_string)\n last_modified_attr = resource[\"last_modified\"]\n\n if not last_modified_attr:\n last_modified_attr = resource[\"created\"]\n\n resource_last_modified = parser.parse(last_modified_attr + \" UTC\")\n\n difference_in_seconds = (\n file_last_modified.timestamp() - resource_last_modified.timestamp()\n )\n\n logging.info(\n f\"{difference_in_seconds}secs between file and resource last modified times\"\n )\n\n if difference_in_seconds == 0:\n return \"file_is_not_new\"\n\n return \"file_is_new\"\n\n def build_data_dict(**kwargs):\n data_fp = Path(kwargs[\"ti\"].xcom_pull(task_ids=\"transform_data\"))\n data = pd.read_parquet(Path(data_fp))\n\n fields = []\n\n for field, dtype in data.dtypes.iteritems():\n ckan_type_map = {\"int64\": \"int\", \"object\": \"text\", \"float64\": \"float\"}\n fields.append({\"type\": ckan_type_map[dtype.name], \"id\": field})\n\n return fields\n\n def build_message(**kwargs):\n ti = kwargs[\"id\"]\n records_inserted = ti.xcom_pull(\"records_inserted\")\n\n if records_inserted is None:\n resource = ti.xcom_pull(\"update_resource_last_modified\")\n last_modified = parser.parse(resource[\"last_modified\"]).strftime(\n \"%Y-%m-%d %H:%M\"\n )\n\n return (\n f\"New file, no new data. New last modified timestamp: {last_modified}\"\n )\n\n new_data_fp = Path(ti.xcom_pull(\"transform_data\"))\n new_data = pd.read_parquet(new_data_fp)\n\n return f\"Refreshed: {new_data.shape[0]} records\"\n\n def get_fields(**kwargs):\n ti = kwargs[\"ti\"]\n backup_data = ti.xcom_pull(task_ids=\"backup_data\")\n\n if backup_data is not None:\n with open(Path(backup_data[\"fields_file_path\"]), \"r\") as f:\n fields = json.load(f)\n else:\n fields = ti.xcom_pull(task_ids=\"create_data_dictionary\")\n assert fields is not None, \"No fields\"\n\n return fields\n\n def were_records_loaded(**kwargs):\n inserted_records_count = kwargs[\"ti\"].xcom_pull(task_ids=\"insert_records\")\n\n if inserted_records_count is not None and inserted_records_count > 0:\n return \"new_records_notification\"\n\n return \"no_new_data_notification\"\n\n def send_new_records_notification(**kwargs):\n count = kwargs[\"ti\"].xcom_pull(\"insert_records\")\n\n airflow_utils.message_slack(\n PACKAGE_NAME,\n f\"Refreshed {count} records\",\n \"success\",\n Variable.get(\"active_env\") == \"prod\",\n Variable.get(\"active_env\"),\n )\n\n ckan_creds = Variable.get(\"ckan_credentials_secret\", deserialize_json=True)\n active_env = Variable.get(\"active_env\")\n ckan_address = ckan_creds[active_env][\"address\"]\n ckan_apikey = ckan_creds[active_env][\"apikey\"]\n\n tmp_dir = CreateLocalDirectoryOperator(\n task_id=\"tmp_dir\", path=Path(Variable.get(\"tmp_dir\")) / PACKAGE_NAME,\n )\n\n backups_dir = CreateLocalDirectoryOperator(\n task_id=\"backups_dir\", path=Path(Variable.get(\"backups_dir\")) / PACKAGE_NAME,\n )\n\n src = DownloadFileOperator(\n task_id=\"get_data\",\n file_url=SRC_URL,\n dir =Path(Variable.get(\"tmp_dir\")) / PACKAGE_NAME,\n filename=\"src_data.csv\",\n )\n\n package = GetPackageOperator(\n task_id=\"get_package\",\n address=ckan_address,\n apikey=ckan_apikey,\n package_name_or_id=PACKAGE_NAME,\n )\n\n new_resource_branch = BranchPythonOperator(\n task_id=\"new_resource_branch\", python_callable=is_resource_new,\n )\n\n transformed_data = PythonOperator(\n task_id=\"transform_data\", python_callable=transform_data,\n )\n\n create_data_dictionary = PythonOperator(\n task_id=\"create_data_dictionary\", python_callable=build_data_dict,\n )\n\n get_or_create_resource = GetOrCreateResourceOperator(\n task_id=\"get_or_create_resource\",\n address=ckan_address,\n apikey=ckan_apikey,\n package_name_or_id=PACKAGE_NAME,\n resource_name=RESOURCE_NAME,\n resource_attributes=dict(\n format=\"geojson\",\n is_preview=True,\n url_type=\"datastore\",\n extract_job=f\"Airflow: {PACKAGE_NAME}\",\n ),\n )\n\n backup_data = BackupDatastoreResourceOperator(\n task_id=\"backup_data\",\n address=ckan_address,\n apikey=ckan_apikey,\n resource_task_id=\"get_or_create_resource\",\n dir_task_id=\"backups_dir\",\n sort_columns=[\"LOC_ID\"],\n )\n\n fields = PythonOperator(\n task_id=\"get_fields\", python_callable=get_fields, trigger_rule=\"none_failed\"\n )\n\n file_new_branch = BranchPythonOperator(\n task_id=\"file_new_branch\", python_callable=is_file_new,\n )\n\n new_data_branch = BranchPythonOperator(\n task_id=\"is_data_new\", python_callable=is_data_new,\n )\n\n delete_tmp_data = PythonOperator(\n task_id=\"delete_tmp_data\",\n python_callable=airflow_utils.delete_tmp_data_dir,\n op_kwargs={\"dag_id\": PACKAGE_NAME, \"recursively\": True},\n trigger_rule=\"one_success\",\n )\n\n sync_timestamp = ResourceAndFileOperator(\n task_id=\"sync_timestamp\",\n address=ckan_address,\n apikey=ckan_apikey,\n download_file_task_id=\"get_data\",\n resource_task_id=\"get_or_create_resource\",\n upload_to_ckan=False,\n sync_timestamp=True,\n trigger_rule=\"one_success\",\n )\n\n send_nothing_notification = PythonOperator(\n task_id=\"send_nothing_notification\",\n python_callable=airflow_utils.message_slack,\n op_args=(\n PACKAGE_NAME,\n \"No new data file\",\n \"success\",\n active_env == \"prod\",\n active_env,\n ),\n )\n\n delete_records = DeleteDatastoreResourceRecordsOperator(\n task_id=\"delete_records\",\n address=ckan_address,\n apikey=ckan_apikey,\n backup_task_id=\"backup_data\",\n )\n\n insert_records = InsertDatastoreResourceRecordsOperator(\n task_id=\"insert_records\",\n address=ckan_address,\n apikey=ckan_apikey,\n parquet_filepath_task_id=\"transform_data\",\n resource_task_id=\"get_or_create_resource\",\n )\n\n new_records_notification = PythonOperator(\n task_id=\"new_records_notification\",\n python_callable=send_new_records_notification,\n )\n\n no_new_data_notification = PythonOperator(\n task_id=\"no_new_data_notification\",\n python_callable=airflow_utils.message_slack,\n op_args=(\n PACKAGE_NAME,\n \"Updated resource last_modified time only: new file but no new data\",\n \"success\",\n active_env == \"prod\",\n active_env,\n ),\n )\n\n records_loaded_branch = BranchPythonOperator(\n task_id=\"were_records_loaded\", python_callable=were_records_loaded,\n )\n\n restore_backup = RestoreDatastoreResourceBackupOperator(\n task_id=\"restore_backup\",\n address=ckan_address,\n apikey=ckan_apikey,\n backup_task_id=\"backup_data\",\n trigger_rule=\"all_failed\",\n )\n\n validated_columns = PythonOperator(\n task_id=\"validate_expected_columns\", python_callable=validate_expected_columns,\n )\n\n backups_dir >> backup_data\n\n tmp_dir >> src >> validated_columns >> transformed_data >> file_new_branch\n\n package >> get_or_create_resource >> [file_new_branch, new_resource_branch]\n\n new_resource_branch >> DummyOperator(\n task_id=\"resource_is_new\"\n ) >> create_data_dictionary >> fields\n\n new_resource_branch >> DummyOperator(\n task_id=\"resource_is_not_new\"\n ) >> backup_data >> fields\n\n file_new_branch >> DummyOperator(task_id=\"file_is_new\") >> new_data_branch\n\n file_new_branch >> DummyOperator(\n task_id=\"file_is_not_new\"\n ) >> send_nothing_notification\n\n fields >> new_data_branch\n\n new_data_branch >> DummyOperator(\n task_id=\"data_is_new\"\n ) >> delete_records >> insert_records >> sync_timestamp\n\n new_data_branch >> DummyOperator(task_id=\"data_is_not_new\") >> sync_timestamp\n\n sync_timestamp >> records_loaded_branch\n\n records_loaded_branch >> new_records_notification\n\n records_loaded_branch >> no_new_data_notification\n\n [\n no_new_data_notification,\n new_records_notification,\n send_nothing_notification,\n ] >> delete_tmp_data\n\n [delete_records, insert_records] >> restore_backup\n" ]
[ [ "pandas.read_parquet", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
marinko-peso/python-simple-neural-network
[ "b3a36e6a7a568ed54f691ce15d73ce0f2e77c6de" ]
[ "neuron.py" ]
[ "from numpy import exp # natural exponential\nfrom numpy import array # creates a matrix\nfrom numpy import dot # multiplies matrices\nfrom numpy import random\n\n\nclass NeuralNetwork():\n def __init__(self):\n # Seed the random number generator, so it generates the same numbers\n # every time the program runs.\n random.seed(1)\n\n # We model a single neuron, with 3 input connections and 1 output connection.\n # We assign random weights to a 3 x 1 matrix, with values in the range -1 to 1\n # and mean 0.\n self.synaptic_weights = 2 * random.random((3, 1)) - 1\n\n # The Sigmoid function, which describes an S shaped curve.\n # We pass the weighted sum of the inputs through this function to\n # normalise them between 0 and 1.\n def __sigmoid(self, x):\n return 1 / (1 + exp(-x))\n\n # The derivative of the Sigmoid function.\n # This is the gradient of the Sigmoid curve.\n # It indicates how confident we are about the existing weight.\n def __sigmoid_derivative(self, x):\n return x * (1 - x)\n\n # We train the neural network through a process of trial and error.\n # Adjusting the synaptic weights each time.\n def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations):\n for iteration in range(number_of_training_iterations):\n # Pass the training set through our neural network (a single neuron).\n output = self.think(training_set_inputs)\n\n # Calculate the error (The difference between the desired output\n # and the predicted output).\n error = training_set_outputs - output\n\n # Multiply the error by the input and again by the gradient of the Sigmoid curve.\n # This means less confident weights are adjusted more.\n # This means inputs, which are zero, do not cause changes to the weights.\n adjustment = dot(training_set_inputs.T, error * self.__sigmoid_derivative(output))\n\n # Adjust the weights.\n self.synaptic_weights += adjustment\n\n # The neural network thinks.\n def think(self, inputs):\n # Pass inputs through our neural network (our single neuron).\n return self.__sigmoid(dot(inputs, self.synaptic_weights))\n\n\nif __name__ == '__main__':\n\n # Intialise a single neuron neural network.\n neural_network = NeuralNetwork()\n\n print('Random starting synaptic weights: ')\n print(neural_network.synaptic_weights)\n\n # Training set. We have 4 examples, each consisting of 3 input values and 1 output value.\n training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])\n # .T -> transposes the matrix from horizontal to vertical.\n training_set_outputs = array([[0, 1, 1, 0]]).T\n\n # Train the neural network using a training set.\n # Do it 10,000 times and make small adjustments each time.\n neural_network.train(training_set_inputs, training_set_outputs, 10000)\n\n print('New synaptic weights after training: ')\n print(neural_network.synaptic_weights)\n\n # Test the neural network with a new situation.\n print('Considering new situation [1, 0, 0] -> ?: ')\n print(neural_network.think(array([1, 0, 0])))\n\n print('Considering new situation [0, 1, 1] -> ?: ')\n print(neural_network.think(array([0, 1, 1])))\n\n print('Considering new situation [0, 1, 0] -> ?: ')\n print(neural_network.think(array([0, 1, 0])))\n" ]
[ [ "numpy.dot", "numpy.random.random", "numpy.random.seed", "numpy.array", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
alexitkes/pandas
[ "8305a856c150126ef899544091395104ac6141e2", "8305a856c150126ef899544091395104ac6141e2", "8305a856c150126ef899544091395104ac6141e2" ]
[ "pandas/core/dtypes/missing.py", "pandas/tests/series/indexing/test_indexing.py", "pandas/tests/arrays/categorical/test_indexing.py" ]
[ "\"\"\"\nmissing types & inference\n\"\"\"\nimport numpy as np\n\nfrom pandas._config import get_option\n\nfrom pandas._libs import lib\nimport pandas._libs.missing as libmissing\nfrom pandas._libs.tslibs import NaT, iNaT\nfrom pandas._typing import DtypeObj\n\nfrom pandas.core.dtypes.common import (\n _NS_DTYPE,\n _TD_DTYPE,\n ensure_object,\n is_bool_dtype,\n is_complex_dtype,\n is_datetimelike_v_numeric,\n is_dtype_equal,\n is_extension_array_dtype,\n is_float_dtype,\n is_integer_dtype,\n is_object_dtype,\n is_scalar,\n is_string_dtype,\n is_string_like_dtype,\n needs_i8_conversion,\n pandas_dtype,\n)\nfrom pandas.core.dtypes.generic import (\n ABCDataFrame,\n ABCExtensionArray,\n ABCIndexClass,\n ABCMultiIndex,\n ABCSeries,\n)\nfrom pandas.core.dtypes.inference import is_list_like\n\nisposinf_scalar = libmissing.isposinf_scalar\nisneginf_scalar = libmissing.isneginf_scalar\n\n\ndef isna(obj):\n \"\"\"\n Detect missing values for an array-like object.\n\n This function takes a scalar or array-like object and indicates\n whether values are missing (``NaN`` in numeric arrays, ``None`` or ``NaN``\n in object arrays, ``NaT`` in datetimelike).\n\n Parameters\n ----------\n obj : scalar or array-like\n Object to check for null or missing values.\n\n Returns\n -------\n bool or array-like of bool\n For scalar input, returns a scalar boolean.\n For array input, returns an array of boolean indicating whether each\n corresponding element is missing.\n\n See Also\n --------\n notna : Boolean inverse of pandas.isna.\n Series.isna : Detect missing values in a Series.\n DataFrame.isna : Detect missing values in a DataFrame.\n Index.isna : Detect missing values in an Index.\n\n Examples\n --------\n Scalar arguments (including strings) result in a scalar boolean.\n\n >>> pd.isna('dog')\n False\n\n >>> pd.isna(pd.NA)\n True\n\n >>> pd.isna(np.nan)\n True\n\n ndarrays result in an ndarray of booleans.\n\n >>> array = np.array([[1, np.nan, 3], [4, 5, np.nan]])\n >>> array\n array([[ 1., nan, 3.],\n [ 4., 5., nan]])\n >>> pd.isna(array)\n array([[False, True, False],\n [False, False, True]])\n\n For indexes, an ndarray of booleans is returned.\n\n >>> index = pd.DatetimeIndex([\"2017-07-05\", \"2017-07-06\", None,\n ... \"2017-07-08\"])\n >>> index\n DatetimeIndex(['2017-07-05', '2017-07-06', 'NaT', '2017-07-08'],\n dtype='datetime64[ns]', freq=None)\n >>> pd.isna(index)\n array([False, False, True, False])\n\n For Series and DataFrame, the same type is returned, containing booleans.\n\n >>> df = pd.DataFrame([['ant', 'bee', 'cat'], ['dog', None, 'fly']])\n >>> df\n 0 1 2\n 0 ant bee cat\n 1 dog None fly\n >>> pd.isna(df)\n 0 1 2\n 0 False False False\n 1 False True False\n\n >>> pd.isna(df[1])\n 0 False\n 1 True\n Name: 1, dtype: bool\n \"\"\"\n return _isna(obj)\n\n\nisnull = isna\n\n\ndef _isna_new(obj):\n\n if is_scalar(obj):\n return libmissing.checknull(obj)\n # hack (for now) because MI registers as ndarray\n elif isinstance(obj, ABCMultiIndex):\n raise NotImplementedError(\"isna is not defined for MultiIndex\")\n elif isinstance(obj, type):\n return False\n elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):\n return _isna_ndarraylike(obj)\n elif isinstance(obj, ABCDataFrame):\n return obj.isna()\n elif isinstance(obj, list):\n return _isna_ndarraylike(np.asarray(obj, dtype=object))\n elif hasattr(obj, \"__array__\"):\n return _isna_ndarraylike(np.asarray(obj))\n else:\n return False\n\n\ndef _isna_old(obj):\n \"\"\"\n Detect missing values, treating None, NaN, INF, -INF as null.\n\n Parameters\n ----------\n arr: ndarray or object value\n\n Returns\n -------\n boolean ndarray or boolean\n \"\"\"\n if is_scalar(obj):\n return libmissing.checknull_old(obj)\n # hack (for now) because MI registers as ndarray\n elif isinstance(obj, ABCMultiIndex):\n raise NotImplementedError(\"isna is not defined for MultiIndex\")\n elif isinstance(obj, type):\n return False\n elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):\n return _isna_ndarraylike_old(obj)\n elif isinstance(obj, ABCDataFrame):\n return obj.isna()\n elif isinstance(obj, list):\n return _isna_ndarraylike_old(np.asarray(obj, dtype=object))\n elif hasattr(obj, \"__array__\"):\n return _isna_ndarraylike_old(np.asarray(obj))\n else:\n return False\n\n\n_isna = _isna_new\n\n\ndef _use_inf_as_na(key):\n \"\"\"\n Option change callback for na/inf behaviour.\n\n Choose which replacement for numpy.isnan / -numpy.isfinite is used.\n\n Parameters\n ----------\n flag: bool\n True means treat None, NaN, INF, -INF as null (old way),\n False means None and NaN are null, but INF, -INF are not null\n (new way).\n\n Notes\n -----\n This approach to setting global module values is discussed and\n approved here:\n\n * https://stackoverflow.com/questions/4859217/\n programmatically-creating-variables-in-python/4859312#4859312\n \"\"\"\n flag = get_option(key)\n if flag:\n globals()[\"_isna\"] = _isna_old\n else:\n globals()[\"_isna\"] = _isna_new\n\n\ndef _isna_ndarraylike(obj):\n is_extension = is_extension_array_dtype(obj.dtype)\n values = getattr(obj, \"_values\", obj)\n dtype = values.dtype\n\n if is_extension:\n result = values.isna()\n elif is_string_dtype(dtype):\n result = _isna_string_dtype(values, dtype, old=False)\n\n elif needs_i8_conversion(dtype):\n # this is the NaT pattern\n result = values.view(\"i8\") == iNaT\n else:\n result = np.isnan(values)\n\n # box\n if isinstance(obj, ABCSeries):\n result = obj._constructor(result, index=obj.index, name=obj.name, copy=False)\n\n return result\n\n\ndef _isna_ndarraylike_old(obj):\n values = getattr(obj, \"_values\", obj)\n dtype = values.dtype\n\n if is_string_dtype(dtype):\n result = _isna_string_dtype(values, dtype, old=True)\n\n elif needs_i8_conversion(dtype):\n # this is the NaT pattern\n result = values.view(\"i8\") == iNaT\n else:\n result = ~np.isfinite(values)\n\n # box\n if isinstance(obj, ABCSeries):\n result = obj._constructor(result, index=obj.index, name=obj.name, copy=False)\n\n return result\n\n\ndef _isna_string_dtype(values: np.ndarray, dtype: np.dtype, old: bool) -> np.ndarray:\n # Working around NumPy ticket 1542\n shape = values.shape\n\n if is_string_like_dtype(dtype):\n result = np.zeros(values.shape, dtype=bool)\n else:\n result = np.empty(shape, dtype=bool)\n if old:\n vec = libmissing.isnaobj_old(values.ravel())\n else:\n vec = libmissing.isnaobj(values.ravel())\n\n result[...] = vec.reshape(shape)\n\n return result\n\n\ndef notna(obj):\n \"\"\"\n Detect non-missing values for an array-like object.\n\n This function takes a scalar or array-like object and indicates\n whether values are valid (not missing, which is ``NaN`` in numeric\n arrays, ``None`` or ``NaN`` in object arrays, ``NaT`` in datetimelike).\n\n Parameters\n ----------\n obj : array-like or object value\n Object to check for *not* null or *non*-missing values.\n\n Returns\n -------\n bool or array-like of bool\n For scalar input, returns a scalar boolean.\n For array input, returns an array of boolean indicating whether each\n corresponding element is valid.\n\n See Also\n --------\n isna : Boolean inverse of pandas.notna.\n Series.notna : Detect valid values in a Series.\n DataFrame.notna : Detect valid values in a DataFrame.\n Index.notna : Detect valid values in an Index.\n\n Examples\n --------\n Scalar arguments (including strings) result in a scalar boolean.\n\n >>> pd.notna('dog')\n True\n\n >>> pd.notna(pd.NA)\n False\n\n >>> pd.notna(np.nan)\n False\n\n ndarrays result in an ndarray of booleans.\n\n >>> array = np.array([[1, np.nan, 3], [4, 5, np.nan]])\n >>> array\n array([[ 1., nan, 3.],\n [ 4., 5., nan]])\n >>> pd.notna(array)\n array([[ True, False, True],\n [ True, True, False]])\n\n For indexes, an ndarray of booleans is returned.\n\n >>> index = pd.DatetimeIndex([\"2017-07-05\", \"2017-07-06\", None,\n ... \"2017-07-08\"])\n >>> index\n DatetimeIndex(['2017-07-05', '2017-07-06', 'NaT', '2017-07-08'],\n dtype='datetime64[ns]', freq=None)\n >>> pd.notna(index)\n array([ True, True, False, True])\n\n For Series and DataFrame, the same type is returned, containing booleans.\n\n >>> df = pd.DataFrame([['ant', 'bee', 'cat'], ['dog', None, 'fly']])\n >>> df\n 0 1 2\n 0 ant bee cat\n 1 dog None fly\n >>> pd.notna(df)\n 0 1 2\n 0 True True True\n 1 True False True\n\n >>> pd.notna(df[1])\n 0 True\n 1 False\n Name: 1, dtype: bool\n \"\"\"\n res = isna(obj)\n if is_scalar(res):\n return not res\n return ~res\n\n\nnotnull = notna\n\n\ndef _isna_compat(arr, fill_value=np.nan) -> bool:\n \"\"\"\n Parameters\n ----------\n arr: a numpy array\n fill_value: fill value, default to np.nan\n\n Returns\n -------\n True if we can fill using this fill_value\n \"\"\"\n dtype = arr.dtype\n if isna(fill_value):\n return not (is_bool_dtype(dtype) or is_integer_dtype(dtype))\n return True\n\n\ndef array_equivalent(left, right, strict_nan: bool = False) -> bool:\n \"\"\"\n True if two arrays, left and right, have equal non-NaN elements, and NaNs\n in corresponding locations. False otherwise. It is assumed that left and\n right are NumPy arrays of the same dtype. The behavior of this function\n (particularly with respect to NaNs) is not defined if the dtypes are\n different.\n\n Parameters\n ----------\n left, right : ndarrays\n strict_nan : bool, default False\n If True, consider NaN and None to be different.\n\n Returns\n -------\n b : bool\n Returns True if the arrays are equivalent.\n\n Examples\n --------\n >>> array_equivalent(\n ... np.array([1, 2, np.nan]),\n ... np.array([1, 2, np.nan]))\n True\n >>> array_equivalent(\n ... np.array([1, np.nan, 2]),\n ... np.array([1, 2, np.nan]))\n False\n \"\"\"\n left, right = np.asarray(left), np.asarray(right)\n\n # shape compat\n if left.shape != right.shape:\n return False\n\n # Object arrays can contain None, NaN and NaT.\n # string dtypes must be come to this path for NumPy 1.7.1 compat\n if is_string_dtype(left) or is_string_dtype(right):\n\n if not strict_nan:\n # isna considers NaN and None to be equivalent.\n return lib.array_equivalent_object(\n ensure_object(left.ravel()), ensure_object(right.ravel())\n )\n\n for left_value, right_value in zip(left, right):\n if left_value is NaT and right_value is not NaT:\n return False\n\n elif left_value is libmissing.NA and right_value is not libmissing.NA:\n return False\n\n elif isinstance(left_value, float) and np.isnan(left_value):\n if not isinstance(right_value, float) or not np.isnan(right_value):\n return False\n else:\n try:\n if np.any(np.asarray(left_value != right_value)):\n return False\n except TypeError as err:\n if \"Cannot compare tz-naive\" in str(err):\n # tzawareness compat failure, see GH#28507\n return False\n elif \"boolean value of NA is ambiguous\" in str(err):\n return False\n raise\n return True\n\n # NaNs can occur in float and complex arrays.\n if is_float_dtype(left) or is_complex_dtype(left):\n\n # empty\n if not (np.prod(left.shape) and np.prod(right.shape)):\n return True\n return ((left == right) | (isna(left) & isna(right))).all()\n\n elif is_datetimelike_v_numeric(left, right):\n # GH#29553 avoid numpy deprecation warning\n return False\n\n elif needs_i8_conversion(left) or needs_i8_conversion(right):\n # datetime64, timedelta64, Period\n if not is_dtype_equal(left.dtype, right.dtype):\n return False\n\n left = left.view(\"i8\")\n right = right.view(\"i8\")\n\n # if we have structured dtypes, compare first\n if left.dtype.type is np.void or right.dtype.type is np.void:\n if left.dtype != right.dtype:\n return False\n\n return np.array_equal(left, right)\n\n\ndef _infer_fill_value(val):\n \"\"\"\n infer the fill value for the nan/NaT from the provided\n scalar/ndarray/list-like if we are a NaT, return the correct dtyped\n element to provide proper block construction\n \"\"\"\n if not is_list_like(val):\n val = [val]\n val = np.array(val, copy=False)\n if needs_i8_conversion(val):\n return np.array(\"NaT\", dtype=val.dtype)\n elif is_object_dtype(val.dtype):\n dtype = lib.infer_dtype(ensure_object(val), skipna=False)\n if dtype in [\"datetime\", \"datetime64\"]:\n return np.array(\"NaT\", dtype=_NS_DTYPE)\n elif dtype in [\"timedelta\", \"timedelta64\"]:\n return np.array(\"NaT\", dtype=_TD_DTYPE)\n return np.nan\n\n\ndef _maybe_fill(arr, fill_value=np.nan):\n \"\"\"\n if we have a compatible fill_value and arr dtype, then fill\n \"\"\"\n if _isna_compat(arr, fill_value):\n arr.fill(fill_value)\n return arr\n\n\ndef na_value_for_dtype(dtype, compat: bool = True):\n \"\"\"\n Return a dtype compat na value\n\n Parameters\n ----------\n dtype : string / dtype\n compat : bool, default True\n\n Returns\n -------\n np.dtype or a pandas dtype\n\n Examples\n --------\n >>> na_value_for_dtype(np.dtype('int64'))\n 0\n >>> na_value_for_dtype(np.dtype('int64'), compat=False)\n nan\n >>> na_value_for_dtype(np.dtype('float64'))\n nan\n >>> na_value_for_dtype(np.dtype('bool'))\n False\n >>> na_value_for_dtype(np.dtype('datetime64[ns]'))\n NaT\n \"\"\"\n dtype = pandas_dtype(dtype)\n\n if is_extension_array_dtype(dtype):\n return dtype.na_value\n if needs_i8_conversion(dtype):\n return NaT\n elif is_float_dtype(dtype):\n return np.nan\n elif is_integer_dtype(dtype):\n if compat:\n return 0\n return np.nan\n elif is_bool_dtype(dtype):\n return False\n return np.nan\n\n\ndef remove_na_arraylike(arr):\n \"\"\"\n Return array-like containing only true/non-NaN values, possibly empty.\n \"\"\"\n if is_extension_array_dtype(arr):\n return arr[notna(arr)]\n else:\n return arr[notna(np.asarray(arr))]\n\n\ndef is_valid_nat_for_dtype(obj, dtype: DtypeObj) -> bool:\n \"\"\"\n isna check that excludes incompatible dtypes\n\n Parameters\n ----------\n obj : object\n dtype : np.datetime64, np.timedelta64, DatetimeTZDtype, or PeriodDtype\n\n Returns\n -------\n bool\n \"\"\"\n if not lib.is_scalar(obj) or not isna(obj):\n return False\n if dtype.kind == \"M\":\n return not isinstance(obj, np.timedelta64)\n if dtype.kind == \"m\":\n return not isinstance(obj, np.datetime64)\n\n # must be PeriodDType\n return not isinstance(obj, (np.datetime64, np.timedelta64))\n", "\"\"\" test get/set & misc \"\"\"\n\nfrom datetime import timedelta\n\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.common import is_scalar\n\nimport pandas as pd\nfrom pandas import Categorical, DataFrame, MultiIndex, Series, Timedelta, Timestamp\nimport pandas._testing as tm\n\nfrom pandas.tseries.offsets import BDay\n\n\ndef test_basic_indexing():\n s = Series(np.random.randn(5), index=[\"a\", \"b\", \"a\", \"a\", \"b\"])\n\n msg = \"index 5 is out of bounds for axis 0 with size 5\"\n with pytest.raises(IndexError, match=msg):\n s[5]\n with pytest.raises(IndexError, match=msg):\n s[5] = 0\n\n with pytest.raises(KeyError, match=r\"^'c'$\"):\n s[\"c\"]\n\n s = s.sort_index()\n\n with pytest.raises(IndexError, match=msg):\n s[5]\n msg = r\"index 5 is out of bounds for axis (0|1) with size 5|^5$\"\n with pytest.raises(IndexError, match=msg):\n s[5] = 0\n\n\ndef test_basic_getitem_with_labels(datetime_series):\n indices = datetime_series.index[[5, 10, 15]]\n\n result = datetime_series[indices]\n expected = datetime_series.reindex(indices)\n tm.assert_series_equal(result, expected)\n\n result = datetime_series[indices[0] : indices[2]]\n expected = datetime_series.loc[indices[0] : indices[2]]\n tm.assert_series_equal(result, expected)\n\n # integer indexes, be careful\n s = Series(np.random.randn(10), index=list(range(0, 20, 2)))\n inds = [0, 2, 5, 7, 8]\n arr_inds = np.array([0, 2, 5, 7, 8])\n with pytest.raises(KeyError, match=\"with any missing labels\"):\n s[inds]\n\n with pytest.raises(KeyError, match=\"with any missing labels\"):\n s[arr_inds]\n\n # GH12089\n # with tz for values\n s = Series(\n pd.date_range(\"2011-01-01\", periods=3, tz=\"US/Eastern\"), index=[\"a\", \"b\", \"c\"]\n )\n expected = Timestamp(\"2011-01-01\", tz=\"US/Eastern\")\n result = s.loc[\"a\"]\n assert result == expected\n result = s.iloc[0]\n assert result == expected\n result = s[\"a\"]\n assert result == expected\n\n\ndef test_getitem_setitem_ellipsis():\n s = Series(np.random.randn(10))\n\n np.fix(s)\n\n result = s[...]\n tm.assert_series_equal(result, s)\n\n s[...] = 5\n assert (result == 5).all()\n\n\ndef test_getitem_get(datetime_series, string_series, object_series):\n idx1 = string_series.index[5]\n idx2 = object_series.index[5]\n\n assert string_series[idx1] == string_series.get(idx1)\n assert object_series[idx2] == object_series.get(idx2)\n\n assert string_series[idx1] == string_series[5]\n assert object_series[idx2] == object_series[5]\n\n assert string_series.get(-1) == string_series.get(string_series.index[-1])\n assert string_series[5] == string_series.get(string_series.index[5])\n\n # missing\n d = datetime_series.index[0] - BDay()\n msg = r\"Timestamp\\('1999-12-31 00:00:00', freq='B'\\)\"\n with pytest.raises(KeyError, match=msg):\n datetime_series[d]\n\n # None\n # GH 5652\n s1 = Series(dtype=object)\n s2 = Series(dtype=object, index=list(\"abc\"))\n for s in [s1, s2]:\n result = s.get(None)\n assert result is None\n\n\ndef test_getitem_fancy(string_series, object_series):\n slice1 = string_series[[1, 2, 3]]\n slice2 = object_series[[1, 2, 3]]\n assert string_series.index[2] == slice1.index[1]\n assert object_series.index[2] == slice2.index[1]\n assert string_series[2] == slice1[1]\n assert object_series[2] == slice2[1]\n\n\ndef test_getitem_generator(string_series):\n gen = (x > 0 for x in string_series)\n result = string_series[gen]\n result2 = string_series[iter(string_series > 0)]\n expected = string_series[string_series > 0]\n tm.assert_series_equal(result, expected)\n tm.assert_series_equal(result2, expected)\n\n\ndef test_type_promotion():\n # GH12599\n s = pd.Series(dtype=object)\n s[\"a\"] = pd.Timestamp(\"2016-01-01\")\n s[\"b\"] = 3.0\n s[\"c\"] = \"foo\"\n expected = Series([pd.Timestamp(\"2016-01-01\"), 3.0, \"foo\"], index=[\"a\", \"b\", \"c\"])\n tm.assert_series_equal(s, expected)\n\n\[email protected](\n \"result_1, duplicate_item, expected_1\",\n [\n [\n pd.Series({1: 12, 2: [1, 2, 2, 3]}),\n pd.Series({1: 313}),\n pd.Series({1: 12}, dtype=object),\n ],\n [\n pd.Series({1: [1, 2, 3], 2: [1, 2, 2, 3]}),\n pd.Series({1: [1, 2, 3]}),\n pd.Series({1: [1, 2, 3]}),\n ],\n ],\n)\ndef test_getitem_with_duplicates_indices(result_1, duplicate_item, expected_1):\n # GH 17610\n result = result_1.append(duplicate_item)\n expected = expected_1.append(duplicate_item)\n tm.assert_series_equal(result[1], expected)\n assert result[2] == result_1[2]\n\n\ndef test_getitem_out_of_bounds(datetime_series):\n # don't segfault, GH #495\n msg = r\"index \\d+ is out of bounds for axis 0 with size \\d+\"\n with pytest.raises(IndexError, match=msg):\n datetime_series[len(datetime_series)]\n\n # GH #917\n msg = r\"index -\\d+ is out of bounds for axis 0 with size \\d+\"\n s = Series([], dtype=object)\n with pytest.raises(IndexError, match=msg):\n s[-1]\n\n\ndef test_getitem_setitem_integers():\n # caused bug without test\n s = Series([1, 2, 3], [\"a\", \"b\", \"c\"])\n\n assert s.iloc[0] == s[\"a\"]\n s.iloc[0] = 5\n tm.assert_almost_equal(s[\"a\"], 5)\n\n\ndef test_getitem_box_float64(datetime_series):\n value = datetime_series[5]\n assert isinstance(value, np.float64)\n\n\ndef test_series_box_timestamp():\n rng = pd.date_range(\"20090415\", \"20090519\", freq=\"B\")\n ser = Series(rng)\n\n assert isinstance(ser[5], pd.Timestamp)\n\n rng = pd.date_range(\"20090415\", \"20090519\", freq=\"B\")\n ser = Series(rng, index=rng)\n assert isinstance(ser[5], pd.Timestamp)\n\n assert isinstance(ser.iat[5], pd.Timestamp)\n\n\ndef test_series_box_timedelta():\n rng = pd.timedelta_range(\"1 day 1 s\", periods=5, freq=\"h\")\n ser = pd.Series(rng)\n assert isinstance(ser[0], Timedelta)\n assert isinstance(ser.at[1], Timedelta)\n assert isinstance(ser.iat[2], Timedelta)\n assert isinstance(ser.loc[3], Timedelta)\n assert isinstance(ser.iloc[4], Timedelta)\n\n\ndef test_getitem_ambiguous_keyerror():\n s = Series(range(10), index=list(range(0, 20, 2)))\n with pytest.raises(KeyError, match=r\"^1$\"):\n s[1]\n with pytest.raises(KeyError, match=r\"^1$\"):\n s.loc[1]\n\n\ndef test_getitem_unordered_dup():\n obj = Series(range(5), index=[\"c\", \"a\", \"a\", \"b\", \"b\"])\n assert is_scalar(obj[\"c\"])\n assert obj[\"c\"] == 0\n\n\ndef test_getitem_dups_with_missing():\n # breaks reindex, so need to use .loc internally\n # GH 4246\n s = Series([1, 2, 3, 4], [\"foo\", \"bar\", \"foo\", \"bah\"])\n with pytest.raises(KeyError, match=\"with any missing labels\"):\n s.loc[[\"foo\", \"bar\", \"bah\", \"bam\"]]\n\n with pytest.raises(KeyError, match=\"with any missing labels\"):\n s[[\"foo\", \"bar\", \"bah\", \"bam\"]]\n\n\ndef test_getitem_dups():\n s = Series(range(5), index=[\"A\", \"A\", \"B\", \"C\", \"C\"], dtype=np.int64)\n expected = Series([3, 4], index=[\"C\", \"C\"], dtype=np.int64)\n result = s[\"C\"]\n tm.assert_series_equal(result, expected)\n\n\ndef test_setitem_ambiguous_keyerror():\n s = Series(range(10), index=list(range(0, 20, 2)))\n\n # equivalent of an append\n s2 = s.copy()\n s2[1] = 5\n expected = s.append(Series([5], index=[1]))\n tm.assert_series_equal(s2, expected)\n\n s2 = s.copy()\n s2.loc[1] = 5\n expected = s.append(Series([5], index=[1]))\n tm.assert_series_equal(s2, expected)\n\n\ndef test_getitem_dataframe():\n rng = list(range(10))\n s = pd.Series(10, index=rng)\n df = pd.DataFrame(rng, index=rng)\n msg = (\n \"Indexing a Series with DataFrame is not supported, \"\n \"use the appropriate DataFrame column\"\n )\n with pytest.raises(TypeError, match=msg):\n s[df > 5]\n\n\ndef test_setitem(datetime_series, string_series):\n datetime_series[datetime_series.index[5]] = np.NaN\n datetime_series[[1, 2, 17]] = np.NaN\n datetime_series[6] = np.NaN\n assert np.isnan(datetime_series[6])\n assert np.isnan(datetime_series[2])\n datetime_series[np.isnan(datetime_series)] = 5\n assert not np.isnan(datetime_series[2])\n\n # caught this bug when writing tests\n series = Series(tm.makeIntIndex(20).astype(float), index=tm.makeIntIndex(20))\n\n series[::2] = 0\n assert (series[::2] == 0).all()\n\n # set item that's not contained\n s = string_series.copy()\n s[\"foobar\"] = 1\n\n app = Series([1], index=[\"foobar\"], name=\"series\")\n expected = string_series.append(app)\n tm.assert_series_equal(s, expected)\n\n # Test for issue #10193\n key = pd.Timestamp(\"2012-01-01\")\n series = pd.Series(dtype=object)\n series[key] = 47\n expected = pd.Series(47, [key])\n tm.assert_series_equal(series, expected)\n\n series = pd.Series([], pd.DatetimeIndex([], freq=\"D\"), dtype=object)\n series[key] = 47\n expected = pd.Series(47, pd.DatetimeIndex([key], freq=\"D\"))\n tm.assert_series_equal(series, expected)\n\n\ndef test_setitem_dtypes():\n # change dtypes\n # GH 4463\n expected = Series([np.nan, 2, 3])\n\n s = Series([1, 2, 3])\n s.iloc[0] = np.nan\n tm.assert_series_equal(s, expected)\n\n s = Series([1, 2, 3])\n s.loc[0] = np.nan\n tm.assert_series_equal(s, expected)\n\n s = Series([1, 2, 3])\n s[0] = np.nan\n tm.assert_series_equal(s, expected)\n\n s = Series([False])\n s.loc[0] = np.nan\n tm.assert_series_equal(s, Series([np.nan]))\n\n s = Series([False, True])\n s.loc[0] = np.nan\n tm.assert_series_equal(s, Series([np.nan, 1.0]))\n\n\ndef test_set_value(datetime_series, string_series):\n idx = datetime_series.index[10]\n res = datetime_series._set_value(idx, 0)\n assert res is None\n assert datetime_series[idx] == 0\n\n # equiv\n s = string_series.copy()\n res = s._set_value(\"foobar\", 0)\n assert res is None\n assert s.index[-1] == \"foobar\"\n assert s[\"foobar\"] == 0\n\n s = string_series.copy()\n s.loc[\"foobar\"] = 0\n assert s.index[-1] == \"foobar\"\n assert s[\"foobar\"] == 0\n\n\ndef test_setslice(datetime_series):\n sl = datetime_series[5:20]\n assert len(sl) == len(sl.index)\n assert sl.index.is_unique is True\n\n\ndef test_2d_to_1d_assignment_raises():\n x = np.random.randn(2, 2)\n y = pd.Series(range(2))\n\n msg = (\n r\"shape mismatch: value array of shape \\(2,2\\) could not be \"\n r\"broadcast to indexing result of shape \\(2,\\)\"\n )\n with pytest.raises(ValueError, match=msg):\n y.loc[range(2)] = x\n\n msg = r\"could not broadcast input array from shape \\(2,2\\) into shape \\(2\\)\"\n with pytest.raises(ValueError, match=msg):\n y.loc[:] = x\n\n\n# FutureWarning from NumPy about [slice(None, 5).\[email protected](\"ignore:Using a non-tuple:FutureWarning\")\ndef test_basic_getitem_setitem_corner(datetime_series):\n # invalid tuples, e.g. td.ts[:, None] vs. td.ts[:, 2]\n msg = \"Can only tuple-index with a MultiIndex\"\n with pytest.raises(ValueError, match=msg):\n datetime_series[:, 2]\n with pytest.raises(ValueError, match=msg):\n datetime_series[:, 2] = 2\n\n # weird lists. [slice(0, 5)] will work but not two slices\n with tm.assert_produces_warning(FutureWarning):\n # GH#31299\n result = datetime_series[[slice(None, 5)]]\n expected = datetime_series[:5]\n tm.assert_series_equal(result, expected)\n\n # OK\n msg = r\"unhashable type(: 'slice')?\"\n with pytest.raises(TypeError, match=msg):\n datetime_series[[5, slice(None, None)]]\n with pytest.raises(TypeError, match=msg):\n datetime_series[[5, slice(None, None)]] = 2\n\n\[email protected](\"tz\", [\"US/Eastern\", \"UTC\", \"Asia/Tokyo\"])\ndef test_setitem_with_tz(tz):\n orig = pd.Series(pd.date_range(\"2016-01-01\", freq=\"H\", periods=3, tz=tz))\n assert orig.dtype == f\"datetime64[ns, {tz}]\"\n\n # scalar\n s = orig.copy()\n s[1] = pd.Timestamp(\"2011-01-01\", tz=tz)\n exp = pd.Series(\n [\n pd.Timestamp(\"2016-01-01 00:00\", tz=tz),\n pd.Timestamp(\"2011-01-01 00:00\", tz=tz),\n pd.Timestamp(\"2016-01-01 02:00\", tz=tz),\n ]\n )\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s.loc[1] = pd.Timestamp(\"2011-01-01\", tz=tz)\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s.iloc[1] = pd.Timestamp(\"2011-01-01\", tz=tz)\n tm.assert_series_equal(s, exp)\n\n # vector\n vals = pd.Series(\n [pd.Timestamp(\"2011-01-01\", tz=tz), pd.Timestamp(\"2012-01-01\", tz=tz)],\n index=[1, 2],\n )\n assert vals.dtype == f\"datetime64[ns, {tz}]\"\n\n s[[1, 2]] = vals\n exp = pd.Series(\n [\n pd.Timestamp(\"2016-01-01 00:00\", tz=tz),\n pd.Timestamp(\"2011-01-01 00:00\", tz=tz),\n pd.Timestamp(\"2012-01-01 00:00\", tz=tz),\n ]\n )\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s.loc[[1, 2]] = vals\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s.iloc[[1, 2]] = vals\n tm.assert_series_equal(s, exp)\n\n\ndef test_setitem_with_tz_dst():\n # GH XXX\n tz = \"US/Eastern\"\n orig = pd.Series(pd.date_range(\"2016-11-06\", freq=\"H\", periods=3, tz=tz))\n assert orig.dtype == f\"datetime64[ns, {tz}]\"\n\n # scalar\n s = orig.copy()\n s[1] = pd.Timestamp(\"2011-01-01\", tz=tz)\n exp = pd.Series(\n [\n pd.Timestamp(\"2016-11-06 00:00-04:00\", tz=tz),\n pd.Timestamp(\"2011-01-01 00:00-05:00\", tz=tz),\n pd.Timestamp(\"2016-11-06 01:00-05:00\", tz=tz),\n ]\n )\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s.loc[1] = pd.Timestamp(\"2011-01-01\", tz=tz)\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s.iloc[1] = pd.Timestamp(\"2011-01-01\", tz=tz)\n tm.assert_series_equal(s, exp)\n\n # vector\n vals = pd.Series(\n [pd.Timestamp(\"2011-01-01\", tz=tz), pd.Timestamp(\"2012-01-01\", tz=tz)],\n index=[1, 2],\n )\n assert vals.dtype == f\"datetime64[ns, {tz}]\"\n\n s[[1, 2]] = vals\n exp = pd.Series(\n [\n pd.Timestamp(\"2016-11-06 00:00\", tz=tz),\n pd.Timestamp(\"2011-01-01 00:00\", tz=tz),\n pd.Timestamp(\"2012-01-01 00:00\", tz=tz),\n ]\n )\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s.loc[[1, 2]] = vals\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s.iloc[[1, 2]] = vals\n tm.assert_series_equal(s, exp)\n\n\ndef test_categorical_assigning_ops():\n orig = Series(Categorical([\"b\", \"b\"], categories=[\"a\", \"b\"]))\n s = orig.copy()\n s[:] = \"a\"\n exp = Series(Categorical([\"a\", \"a\"], categories=[\"a\", \"b\"]))\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s[1] = \"a\"\n exp = Series(Categorical([\"b\", \"a\"], categories=[\"a\", \"b\"]))\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s[s.index > 0] = \"a\"\n exp = Series(Categorical([\"b\", \"a\"], categories=[\"a\", \"b\"]))\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s[[False, True]] = \"a\"\n exp = Series(Categorical([\"b\", \"a\"], categories=[\"a\", \"b\"]))\n tm.assert_series_equal(s, exp)\n\n s = orig.copy()\n s.index = [\"x\", \"y\"]\n s[\"y\"] = \"a\"\n exp = Series(Categorical([\"b\", \"a\"], categories=[\"a\", \"b\"]), index=[\"x\", \"y\"])\n tm.assert_series_equal(s, exp)\n\n # ensure that one can set something to np.nan\n s = Series(Categorical([1, 2, 3]))\n exp = Series(Categorical([1, np.nan, 3], categories=[1, 2, 3]))\n s[1] = np.nan\n tm.assert_series_equal(s, exp)\n\n\ndef test_getitem_categorical_str():\n # GH#31765\n ser = pd.Series(range(5), index=pd.Categorical([\"a\", \"b\", \"c\", \"a\", \"b\"]))\n result = ser[\"a\"]\n expected = ser.iloc[[0, 3]]\n tm.assert_series_equal(result, expected)\n\n # Check the intermediate steps work as expected\n result = ser.index.get_value(ser, \"a\")\n tm.assert_series_equal(result, expected)\n\n\ndef test_slice(string_series, object_series):\n numSlice = string_series[10:20]\n numSliceEnd = string_series[-10:]\n objSlice = object_series[10:20]\n\n assert string_series.index[9] not in numSlice.index\n assert object_series.index[9] not in objSlice.index\n\n assert len(numSlice) == len(numSlice.index)\n assert string_series[numSlice.index[0]] == numSlice[numSlice.index[0]]\n\n assert numSlice.index[1] == string_series.index[11]\n assert tm.equalContents(numSliceEnd, np.array(string_series)[-10:])\n\n # Test return view.\n sl = string_series[10:20]\n sl[:] = 0\n\n assert (string_series[10:20] == 0).all()\n\n\ndef test_slice_can_reorder_not_uniquely_indexed():\n s = Series(1, index=[\"a\", \"a\", \"b\", \"b\", \"c\"])\n s[::-1] # it works!\n\n\ndef test_loc_setitem(string_series):\n inds = string_series.index[[3, 4, 7]]\n\n result = string_series.copy()\n result.loc[inds] = 5\n\n expected = string_series.copy()\n expected[[3, 4, 7]] = 5\n tm.assert_series_equal(result, expected)\n\n result.iloc[5:10] = 10\n expected[5:10] = 10\n tm.assert_series_equal(result, expected)\n\n # set slice with indices\n d1, d2 = string_series.index[[5, 15]]\n result.loc[d1:d2] = 6\n expected[5:16] = 6 # because it's inclusive\n tm.assert_series_equal(result, expected)\n\n # set index value\n string_series.loc[d1] = 4\n string_series.loc[d2] = 6\n assert string_series[d1] == 4\n assert string_series[d2] == 6\n\n\ndef test_setitem_na():\n # these induce dtype changes\n expected = Series([np.nan, 3, np.nan, 5, np.nan, 7, np.nan, 9, np.nan])\n s = Series([2, 3, 4, 5, 6, 7, 8, 9, 10])\n s[::2] = np.nan\n tm.assert_series_equal(s, expected)\n\n # gets coerced to float, right?\n expected = Series([np.nan, 1, np.nan, 0])\n s = Series([True, True, False, False])\n s[::2] = np.nan\n tm.assert_series_equal(s, expected)\n\n expected = Series([np.nan, np.nan, np.nan, np.nan, np.nan, 5, 6, 7, 8, 9])\n s = Series(np.arange(10))\n s[:5] = np.nan\n tm.assert_series_equal(s, expected)\n\n\ndef test_timedelta_assignment():\n # GH 8209\n s = Series([], dtype=object)\n s.loc[\"B\"] = timedelta(1)\n tm.assert_series_equal(s, Series(Timedelta(\"1 days\"), index=[\"B\"]))\n\n s = s.reindex(s.index.insert(0, \"A\"))\n tm.assert_series_equal(s, Series([np.nan, Timedelta(\"1 days\")], index=[\"A\", \"B\"]))\n\n s.loc[\"A\"] = timedelta(1)\n expected = Series(Timedelta(\"1 days\"), index=[\"A\", \"B\"])\n tm.assert_series_equal(s, expected)\n\n # GH 14155\n s = Series(10 * [np.timedelta64(10, \"m\")])\n s.loc[[1, 2, 3]] = np.timedelta64(20, \"m\")\n expected = pd.Series(10 * [np.timedelta64(10, \"m\")])\n expected.loc[[1, 2, 3]] = pd.Timedelta(np.timedelta64(20, \"m\"))\n tm.assert_series_equal(s, expected)\n\n\[email protected](\n \"nat_val,should_cast\",\n [\n (pd.NaT, True),\n (np.timedelta64(\"NaT\", \"ns\"), False),\n (np.datetime64(\"NaT\", \"ns\"), True),\n ],\n)\[email protected](\"tz\", [None, \"UTC\"])\ndef test_dt64_series_assign_nat(nat_val, should_cast, tz):\n # some nat-like values should be cast to datetime64 when inserting\n # into a datetime64 series. Others should coerce to object\n # and retain their dtypes.\n dti = pd.date_range(\"2016-01-01\", periods=3, tz=tz)\n base = pd.Series(dti)\n expected = pd.Series([pd.NaT] + list(dti[1:]), dtype=dti.dtype)\n if not should_cast:\n expected = expected.astype(object)\n\n ser = base.copy(deep=True)\n ser[0] = nat_val\n tm.assert_series_equal(ser, expected)\n\n ser = base.copy(deep=True)\n ser.loc[0] = nat_val\n tm.assert_series_equal(ser, expected)\n\n ser = base.copy(deep=True)\n ser.iloc[0] = nat_val\n tm.assert_series_equal(ser, expected)\n\n\[email protected](\n \"nat_val,should_cast\",\n [\n (pd.NaT, True),\n (np.timedelta64(\"NaT\", \"ns\"), True),\n (np.datetime64(\"NaT\", \"ns\"), False),\n ],\n)\ndef test_td64_series_assign_nat(nat_val, should_cast):\n # some nat-like values should be cast to timedelta64 when inserting\n # into a timedelta64 series. Others should coerce to object\n # and retain their dtypes.\n base = pd.Series([0, 1, 2], dtype=\"m8[ns]\")\n expected = pd.Series([pd.NaT, 1, 2], dtype=\"m8[ns]\")\n if not should_cast:\n expected = expected.astype(object)\n\n ser = base.copy(deep=True)\n ser[0] = nat_val\n tm.assert_series_equal(ser, expected)\n\n ser = base.copy(deep=True)\n ser.loc[0] = nat_val\n tm.assert_series_equal(ser, expected)\n\n ser = base.copy(deep=True)\n ser.iloc[0] = nat_val\n tm.assert_series_equal(ser, expected)\n\n\[email protected](\n \"td\",\n [\n pd.Timedelta(\"9 days\"),\n pd.Timedelta(\"9 days\").to_timedelta64(),\n pd.Timedelta(\"9 days\").to_pytimedelta(),\n ],\n)\ndef test_append_timedelta_does_not_cast(td):\n # GH#22717 inserting a Timedelta should _not_ cast to int64\n expected = pd.Series([\"x\", td], index=[0, \"td\"], dtype=object)\n\n ser = pd.Series([\"x\"])\n ser[\"td\"] = td\n tm.assert_series_equal(ser, expected)\n assert isinstance(ser[\"td\"], pd.Timedelta)\n\n ser = pd.Series([\"x\"])\n ser.loc[\"td\"] = pd.Timedelta(\"9 days\")\n tm.assert_series_equal(ser, expected)\n assert isinstance(ser[\"td\"], pd.Timedelta)\n\n\ndef test_underlying_data_conversion():\n # GH 4080\n df = DataFrame({c: [1, 2, 3] for c in [\"a\", \"b\", \"c\"]})\n df.set_index([\"a\", \"b\", \"c\"], inplace=True)\n s = Series([1], index=[(2, 2, 2)])\n df[\"val\"] = 0\n df\n df[\"val\"].update(s)\n\n expected = DataFrame(dict(a=[1, 2, 3], b=[1, 2, 3], c=[1, 2, 3], val=[0, 1, 0]))\n expected.set_index([\"a\", \"b\", \"c\"], inplace=True)\n tm.assert_frame_equal(df, expected)\n\n # GH 3970\n # these are chained assignments as well\n pd.set_option(\"chained_assignment\", None)\n df = DataFrame({\"aa\": range(5), \"bb\": [2.2] * 5})\n df[\"cc\"] = 0.0\n\n ck = [True] * len(df)\n\n df[\"bb\"].iloc[0] = 0.13\n\n # TODO: unused\n df_tmp = df.iloc[ck] # noqa\n\n df[\"bb\"].iloc[0] = 0.15\n assert df[\"bb\"].iloc[0] == 0.15\n pd.set_option(\"chained_assignment\", \"raise\")\n\n # GH 3217\n df = DataFrame(dict(a=[1, 3], b=[np.nan, 2]))\n df[\"c\"] = np.nan\n df[\"c\"].update(pd.Series([\"foo\"], index=[0]))\n\n expected = DataFrame(dict(a=[1, 3], b=[np.nan, 2], c=[\"foo\", np.nan]))\n tm.assert_frame_equal(df, expected)\n\n\ndef test_preserve_refs(datetime_series):\n seq = datetime_series[[5, 10, 15]]\n seq[1] = np.NaN\n assert not np.isnan(datetime_series[10])\n\n\ndef test_cast_on_putmask():\n # GH 2746\n\n # need to upcast\n s = Series([1, 2], index=[1, 2], dtype=\"int64\")\n s[[True, False]] = Series([0], index=[1], dtype=\"int64\")\n expected = Series([0, 2], index=[1, 2], dtype=\"int64\")\n\n tm.assert_series_equal(s, expected)\n\n\ndef test_type_promote_putmask():\n # GH8387: test that changing types does not break alignment\n ts = Series(np.random.randn(100), index=np.arange(100, 0, -1)).round(5)\n left, mask = ts.copy(), ts > 0\n right = ts[mask].copy().map(str)\n left[mask] = right\n tm.assert_series_equal(left, ts.map(lambda t: str(t) if t > 0 else t))\n\n s = Series([0, 1, 2, 0])\n mask = s > 0\n s2 = s[mask].map(str)\n s[mask] = s2\n tm.assert_series_equal(s, Series([0, \"1\", \"2\", 0]))\n\n s = Series([0, \"foo\", \"bar\", 0])\n mask = Series([False, True, True, False])\n s2 = s[mask]\n s[mask] = s2\n tm.assert_series_equal(s, Series([0, \"foo\", \"bar\", 0]))\n\n\ndef test_multilevel_preserve_name():\n index = MultiIndex(\n levels=[[\"foo\", \"bar\", \"baz\", \"qux\"], [\"one\", \"two\", \"three\"]],\n codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],\n names=[\"first\", \"second\"],\n )\n s = Series(np.random.randn(len(index)), index=index, name=\"sth\")\n\n result = s[\"foo\"]\n result2 = s.loc[\"foo\"]\n assert result.name == s.name\n assert result2.name == s.name\n\n\ndef test_setitem_scalar_into_readonly_backing_data():\n # GH14359: test that you cannot mutate a read only buffer\n\n array = np.zeros(5)\n array.flags.writeable = False # make the array immutable\n series = Series(array)\n\n for n in range(len(series)):\n msg = \"assignment destination is read-only\"\n with pytest.raises(ValueError, match=msg):\n series[n] = 1\n\n assert array[n] == 0\n\n\ndef test_setitem_slice_into_readonly_backing_data():\n # GH14359: test that you cannot mutate a read only buffer\n\n array = np.zeros(5)\n array.flags.writeable = False # make the array immutable\n series = Series(array)\n\n msg = \"assignment destination is read-only\"\n with pytest.raises(ValueError, match=msg):\n series[1:3] = 1\n\n assert not array.any()\n\n\n\"\"\"\nmiscellaneous methods\n\"\"\"\n\n\ndef test_pop():\n # GH 6600\n df = DataFrame({\"A\": 0, \"B\": np.arange(5, dtype=\"int64\"), \"C\": 0})\n k = df.iloc[4]\n\n result = k.pop(\"B\")\n assert result == 4\n\n expected = Series([0, 0], index=[\"A\", \"C\"], name=4)\n tm.assert_series_equal(k, expected)\n\n\ndef test_uint_drop(any_int_dtype):\n # see GH18311\n # assigning series.loc[0] = 4 changed series.dtype to int\n series = pd.Series([1, 2, 3], dtype=any_int_dtype)\n series.loc[0] = 4\n expected = pd.Series([4, 2, 3], dtype=any_int_dtype)\n tm.assert_series_equal(series, expected)\n\n\ndef test_getitem_2d_no_warning():\n # https://github.com/pandas-dev/pandas/issues/30867\n # Don't want to support this long-term, but\n # for now ensure that the warning from Index\n # doesn't comes through via Series.__getitem__.\n series = pd.Series([1, 2, 3], index=[1, 2, 3])\n with tm.assert_produces_warning(None):\n series[:, None]\n\n\ndef test_getitem_unrecognized_scalar():\n # GH#32684 a scalar key that is not recognized by lib.is_scalar\n\n # a series that might be produced via `frame.dtypes`\n ser = pd.Series([1, 2], index=[np.dtype(\"O\"), np.dtype(\"i8\")])\n\n key = ser.index[1]\n\n result = ser[key]\n assert result == 2\n", "import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import Categorical, CategoricalIndex, Index, PeriodIndex, Series\nimport pandas._testing as tm\nimport pandas.core.common as com\nfrom pandas.tests.arrays.categorical.common import TestCategorical\n\n\nclass TestCategoricalIndexingWithFactor(TestCategorical):\n def test_getitem(self):\n assert self.factor[0] == \"a\"\n assert self.factor[-1] == \"c\"\n\n subf = self.factor[[0, 1, 2]]\n tm.assert_numpy_array_equal(subf._codes, np.array([0, 1, 1], dtype=np.int8))\n\n subf = self.factor[np.asarray(self.factor) == \"c\"]\n tm.assert_numpy_array_equal(subf._codes, np.array([2, 2, 2], dtype=np.int8))\n\n def test_setitem(self):\n\n # int/positional\n c = self.factor.copy()\n c[0] = \"b\"\n assert c[0] == \"b\"\n c[-1] = \"a\"\n assert c[-1] == \"a\"\n\n # boolean\n c = self.factor.copy()\n indexer = np.zeros(len(c), dtype=\"bool\")\n indexer[0] = True\n indexer[-1] = True\n c[indexer] = \"c\"\n expected = Categorical([\"c\", \"b\", \"b\", \"a\", \"a\", \"c\", \"c\", \"c\"], ordered=True)\n\n tm.assert_categorical_equal(c, expected)\n\n @pytest.mark.parametrize(\n \"other\",\n [pd.Categorical([\"b\", \"a\"]), pd.Categorical([\"b\", \"a\"], categories=[\"b\", \"a\"])],\n )\n def test_setitem_same_but_unordered(self, other):\n # GH-24142\n target = pd.Categorical([\"a\", \"b\"], categories=[\"a\", \"b\"])\n mask = np.array([True, False])\n target[mask] = other[mask]\n expected = pd.Categorical([\"b\", \"b\"], categories=[\"a\", \"b\"])\n tm.assert_categorical_equal(target, expected)\n\n @pytest.mark.parametrize(\n \"other\",\n [\n pd.Categorical([\"b\", \"a\"], categories=[\"b\", \"a\", \"c\"]),\n pd.Categorical([\"b\", \"a\"], categories=[\"a\", \"b\", \"c\"]),\n pd.Categorical([\"a\", \"a\"], categories=[\"a\"]),\n pd.Categorical([\"b\", \"b\"], categories=[\"b\"]),\n ],\n )\n def test_setitem_different_unordered_raises(self, other):\n # GH-24142\n target = pd.Categorical([\"a\", \"b\"], categories=[\"a\", \"b\"])\n mask = np.array([True, False])\n msg = \"Cannot set a Categorical with another, without identical categories\"\n with pytest.raises(ValueError, match=msg):\n target[mask] = other[mask]\n\n @pytest.mark.parametrize(\n \"other\",\n [\n pd.Categorical([\"b\", \"a\"]),\n pd.Categorical([\"b\", \"a\"], categories=[\"b\", \"a\"], ordered=True),\n pd.Categorical([\"b\", \"a\"], categories=[\"a\", \"b\", \"c\"], ordered=True),\n ],\n )\n def test_setitem_same_ordered_rasies(self, other):\n # Gh-24142\n target = pd.Categorical([\"a\", \"b\"], categories=[\"a\", \"b\"], ordered=True)\n mask = np.array([True, False])\n msg = \"Cannot set a Categorical with another, without identical categories\"\n with pytest.raises(ValueError, match=msg):\n target[mask] = other[mask]\n\n\nclass TestCategoricalIndexing:\n def test_getitem_listlike(self):\n\n # GH 9469\n # properly coerce the input indexers\n np.random.seed(1)\n c = Categorical(np.random.randint(0, 5, size=150000).astype(np.int8))\n result = c.codes[np.array([100000]).astype(np.int64)]\n expected = c[np.array([100000]).astype(np.int64)].codes\n tm.assert_numpy_array_equal(result, expected)\n\n def test_periodindex(self):\n idx1 = PeriodIndex(\n [\"2014-01\", \"2014-01\", \"2014-02\", \"2014-02\", \"2014-03\", \"2014-03\"], freq=\"M\"\n )\n\n cat1 = Categorical(idx1)\n str(cat1)\n exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.int8)\n exp_idx = PeriodIndex([\"2014-01\", \"2014-02\", \"2014-03\"], freq=\"M\")\n tm.assert_numpy_array_equal(cat1._codes, exp_arr)\n tm.assert_index_equal(cat1.categories, exp_idx)\n\n idx2 = PeriodIndex(\n [\"2014-03\", \"2014-03\", \"2014-02\", \"2014-01\", \"2014-03\", \"2014-01\"], freq=\"M\"\n )\n cat2 = Categorical(idx2, ordered=True)\n str(cat2)\n exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.int8)\n exp_idx2 = PeriodIndex([\"2014-01\", \"2014-02\", \"2014-03\"], freq=\"M\")\n tm.assert_numpy_array_equal(cat2._codes, exp_arr)\n tm.assert_index_equal(cat2.categories, exp_idx2)\n\n idx3 = PeriodIndex(\n [\n \"2013-12\",\n \"2013-11\",\n \"2013-10\",\n \"2013-09\",\n \"2013-08\",\n \"2013-07\",\n \"2013-05\",\n ],\n freq=\"M\",\n )\n cat3 = Categorical(idx3, ordered=True)\n exp_arr = np.array([6, 5, 4, 3, 2, 1, 0], dtype=np.int8)\n exp_idx = PeriodIndex(\n [\n \"2013-05\",\n \"2013-07\",\n \"2013-08\",\n \"2013-09\",\n \"2013-10\",\n \"2013-11\",\n \"2013-12\",\n ],\n freq=\"M\",\n )\n tm.assert_numpy_array_equal(cat3._codes, exp_arr)\n tm.assert_index_equal(cat3.categories, exp_idx)\n\n def test_categories_assignments(self):\n s = Categorical([\"a\", \"b\", \"c\", \"a\"])\n exp = np.array([1, 2, 3, 1], dtype=np.int64)\n s.categories = [1, 2, 3]\n tm.assert_numpy_array_equal(s.__array__(), exp)\n tm.assert_index_equal(s.categories, Index([1, 2, 3]))\n\n @pytest.mark.parametrize(\"new_categories\", [[1, 2, 3, 4], [1, 2]])\n def test_categories_assignments_wrong_length_raises(self, new_categories):\n cat = Categorical([\"a\", \"b\", \"c\", \"a\"])\n msg = (\n \"new categories need to have the same number of items \"\n \"as the old categories!\"\n )\n with pytest.raises(ValueError, match=msg):\n cat.categories = new_categories\n\n # Combinations of sorted/unique:\n @pytest.mark.parametrize(\n \"idx_values\", [[1, 2, 3, 4], [1, 3, 2, 4], [1, 3, 3, 4], [1, 2, 2, 4]]\n )\n # Combinations of missing/unique\n @pytest.mark.parametrize(\"key_values\", [[1, 2], [1, 5], [1, 1], [5, 5]])\n @pytest.mark.parametrize(\"key_class\", [Categorical, CategoricalIndex])\n def test_get_indexer_non_unique(self, idx_values, key_values, key_class):\n # GH 21448\n key = key_class(key_values, categories=range(1, 5))\n # Test for flat index and CategoricalIndex with same/different cats:\n for dtype in None, \"category\", key.dtype:\n idx = Index(idx_values, dtype=dtype)\n expected, exp_miss = idx.get_indexer_non_unique(key_values)\n result, res_miss = idx.get_indexer_non_unique(key)\n\n tm.assert_numpy_array_equal(expected, result)\n tm.assert_numpy_array_equal(exp_miss, res_miss)\n\n def test_where_unobserved_nan(self):\n ser = pd.Series(pd.Categorical([\"a\", \"b\"]))\n result = ser.where([True, False])\n expected = pd.Series(pd.Categorical([\"a\", None], categories=[\"a\", \"b\"]))\n tm.assert_series_equal(result, expected)\n\n # all NA\n ser = pd.Series(pd.Categorical([\"a\", \"b\"]))\n result = ser.where([False, False])\n expected = pd.Series(pd.Categorical([None, None], categories=[\"a\", \"b\"]))\n tm.assert_series_equal(result, expected)\n\n def test_where_unobserved_categories(self):\n ser = pd.Series(Categorical([\"a\", \"b\", \"c\"], categories=[\"d\", \"c\", \"b\", \"a\"]))\n result = ser.where([True, True, False], other=\"b\")\n expected = pd.Series(\n Categorical([\"a\", \"b\", \"b\"], categories=ser.cat.categories)\n )\n tm.assert_series_equal(result, expected)\n\n def test_where_other_categorical(self):\n ser = pd.Series(Categorical([\"a\", \"b\", \"c\"], categories=[\"d\", \"c\", \"b\", \"a\"]))\n other = Categorical([\"b\", \"c\", \"a\"], categories=[\"a\", \"c\", \"b\", \"d\"])\n result = ser.where([True, False, True], other)\n expected = pd.Series(Categorical([\"a\", \"c\", \"c\"], dtype=ser.dtype))\n tm.assert_series_equal(result, expected)\n\n def test_where_new_category_raises(self):\n ser = pd.Series(Categorical([\"a\", \"b\", \"c\"]))\n msg = \"Cannot setitem on a Categorical with a new category\"\n with pytest.raises(ValueError, match=msg):\n ser.where([True, False, True], \"d\")\n\n def test_where_ordered_differs_rasies(self):\n ser = pd.Series(\n Categorical([\"a\", \"b\", \"c\"], categories=[\"d\", \"c\", \"b\", \"a\"], ordered=True)\n )\n other = Categorical(\n [\"b\", \"c\", \"a\"], categories=[\"a\", \"c\", \"b\", \"d\"], ordered=True\n )\n with pytest.raises(ValueError, match=\"without identical categories\"):\n ser.where([True, False, True], other)\n\n\[email protected](\"index\", [True, False])\ndef test_mask_with_boolean(index):\n s = Series(range(3))\n idx = Categorical([True, False, True])\n if index:\n idx = CategoricalIndex(idx)\n\n assert com.is_bool_indexer(idx)\n result = s[idx]\n expected = s[idx.astype(\"object\")]\n tm.assert_series_equal(result, expected)\n\n\[email protected](\"index\", [True, False])\ndef test_mask_with_boolean_na_treated_as_false(index):\n # https://github.com/pandas-dev/pandas/issues/31503\n s = Series(range(3))\n idx = Categorical([True, False, None])\n if index:\n idx = CategoricalIndex(idx)\n\n result = s[idx]\n expected = s[idx.fillna(False)]\n\n tm.assert_series_equal(result, expected)\n\n\[email protected]\ndef non_coercible_categorical(monkeypatch):\n \"\"\"\n Monkeypatch Categorical.__array__ to ensure no implicit conversion.\n\n Raises\n ------\n ValueError\n When Categorical.__array__ is called.\n \"\"\"\n # TODO(Categorical): identify other places where this may be\n # useful and move to a conftest.py\n def array(self, dtype=None):\n raise ValueError(\"I cannot be converted.\")\n\n with monkeypatch.context() as m:\n m.setattr(Categorical, \"__array__\", array)\n yield\n\n\ndef test_series_at(non_coercible_categorical):\n arr = Categorical([\"a\", \"b\", \"c\"])\n ser = Series(arr)\n result = ser.at[0]\n assert result == \"a\"\n" ]
[ [ "pandas.core.dtypes.common.is_extension_array_dtype", "numpy.asarray", "pandas.core.dtypes.common.is_dtype_equal", "pandas._libs.lib.is_scalar", "pandas._config.get_option", "pandas._libs.missing.checknull_old", "pandas.core.dtypes.common.is_complex_dtype", "pandas.core.dtypes.common.ensure_object", "pandas.core.dtypes.inference.is_list_like", "pandas.core.dtypes.common.is_float_dtype", "pandas.core.dtypes.common.is_string_dtype", "numpy.zeros", "pandas.core.dtypes.common.is_datetimelike_v_numeric", "pandas.core.dtypes.common.is_integer_dtype", "pandas.core.dtypes.common.pandas_dtype", "numpy.isnan", "numpy.array", "pandas.core.dtypes.common.needs_i8_conversion", "pandas._libs.missing.checknull", "pandas.core.dtypes.common.is_string_like_dtype", "pandas.core.dtypes.common.is_bool_dtype", "numpy.array_equal", "numpy.isfinite", "pandas.core.dtypes.common.is_scalar", "pandas.core.dtypes.common.is_object_dtype", "numpy.prod", "numpy.empty" ], [ "pandas._testing.assert_almost_equal", "pandas.Series", "pandas.DataFrame", "numpy.dtype", "numpy.random.randn", "numpy.fix", "pandas._testing.assert_frame_equal", "pandas.tseries.offsets.BDay", "numpy.arange", "pandas.DatetimeIndex", "pandas._testing.assert_series_equal", "pandas.set_option", "numpy.zeros", "pandas._testing.assert_produces_warning", "pandas.MultiIndex", "numpy.isnan", "pandas.Categorical", "pandas.Timedelta", "numpy.timedelta64", "pandas._testing.makeIntIndex", "pandas.date_range", "numpy.array", "pandas.timedelta_range", "pandas.core.dtypes.common.is_scalar", "numpy.datetime64", "pandas.Timestamp" ], [ "pandas.CategoricalIndex", "pandas._testing.assert_numpy_array_equal", "pandas.Series", "numpy.random.seed", "pandas.PeriodIndex", "pandas.core.common.is_bool_indexer", "pandas.Categorical", "numpy.asarray", "pandas.Index", "pandas._testing.assert_categorical_equal", "numpy.random.randint", "pandas._testing.assert_series_equal", "numpy.array", "pandas._testing.assert_index_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
m-beau/phy
[ "755082af4e123dc057b8edca138652f901d0c8b1", "755082af4e123dc057b8edca138652f901d0c8b1" ]
[ "phy/plot/plot.py", "phy/cluster/views/feature.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"Plotting interface.\"\"\"\n\n\n#------------------------------------------------------------------------------\n# Imports\n#------------------------------------------------------------------------------\n\nfrom collections import OrderedDict\nfrom contextlib import contextmanager\nimport hashlib\nimport json\nimport logging\n\nimport numpy as np\n\nfrom phy.io.array import _accumulate, _in_polygon\nfrom phy.utils._types import _as_tuple\nfrom .base import BaseCanvas\nfrom .interact import Grid, Boxed, Stacked\nfrom .panzoom import PanZoom\nfrom .utils import _get_array\nfrom .visuals import (ScatterVisual, PlotVisual, HistogramVisual,\n LineVisual, TextVisual, PolygonVisual,\n UniformScatterVisual, UniformPlotVisual,\n )\n\nlogger = logging.getLogger(__name__)\n\n\n#------------------------------------------------------------------------------\n# Utils\n#------------------------------------------------------------------------------\n\n# NOTE: we ensure that we only create every type *once*, so that\n# View._items has only one key for any class.\n_CLASSES = {}\n\n\ndef _hash(obj):\n s = json.dumps(obj, sort_keys=True, ensure_ascii=True).encode('utf-8')\n return hashlib.sha256(s).hexdigest()[:8]\n\n\ndef _make_class(cls, **kwargs):\n \"\"\"Return a custom Visual class with given parameters.\"\"\"\n kwargs = {k: (v if v is not None else getattr(cls, k, None))\n for k, v in kwargs.items()}\n # The class name contains a hash of the custom parameters.\n name = cls.__name__ + '_' + _hash(kwargs)\n if name not in _CLASSES:\n logger.log(5, \"Create class %s %s.\", name, kwargs)\n cls = type(name, (cls,), kwargs)\n _CLASSES[name] = cls\n return _CLASSES[name]\n\n\n#------------------------------------------------------------------------------\n# Plotting interface\n#------------------------------------------------------------------------------\n\nclass View(BaseCanvas):\n \"\"\"High-level plotting canvas.\"\"\"\n _default_box_index = (0,)\n\n def __init__(self, layout=None, shape=None, n_plots=None, origin=None,\n box_bounds=None, box_pos=None, box_size=None,\n enable_lasso=False,\n **kwargs):\n if not kwargs.get('keys', None):\n kwargs['keys'] = None\n super(View, self).__init__(**kwargs)\n self.layout = layout\n\n if layout == 'grid':\n self._default_box_index = (0, 0)\n self.grid = Grid(shape)\n self.grid.attach(self)\n self.interact = self.grid\n\n elif layout == 'boxed':\n self.n_plots = (len(box_bounds)\n if box_bounds is not None else len(box_pos))\n self.boxed = Boxed(box_bounds=box_bounds,\n box_pos=box_pos,\n box_size=box_size)\n self.boxed.attach(self)\n self.interact = self.boxed\n\n elif layout == 'stacked':\n self.n_plots = n_plots\n self.stacked = Stacked(n_plots, margin=.1, origin=origin)\n self.stacked.attach(self)\n self.interact = self.stacked\n\n else:\n self.interact = None\n\n self.panzoom = PanZoom(aspect=None,\n constrain_bounds=[-2, -2, +2, +2])\n self.panzoom.attach(self)\n\n if enable_lasso:\n self.lasso = Lasso()\n self.lasso.attach(self)\n else:\n self.lasso = None\n\n self.clear()\n\n def clear(self):\n \"\"\"Reset the view.\"\"\"\n self._items = OrderedDict()\n self.visuals = []\n self.update()\n\n def _add_item(self, cls, *args, **kwargs):\n \"\"\"Add a plot item.\"\"\"\n box_index = kwargs.pop('box_index', self._default_box_index)\n\n data = cls.validate(*args, **kwargs)\n n = cls.vertex_count(**data)\n\n if not isinstance(box_index, np.ndarray):\n k = len(self._default_box_index)\n box_index = _get_array(box_index, (n, k))\n data['box_index'] = box_index\n\n if cls not in self._items:\n self._items[cls] = []\n self._items[cls].append(data)\n return data\n\n def uplot(self, *args, **kwargs):\n cls = _make_class(UniformPlotVisual,\n _default_color=kwargs.pop('color', None),\n )\n return self._add_item(cls, *args, **kwargs)\n\n def plot(self, *args, **kwargs):\n \"\"\"Add a line plot.\"\"\"\n return self._add_item(PlotVisual, *args, **kwargs)\n\n def uscatter(self, *args, **kwargs):\n cls = _make_class(UniformScatterVisual,\n _default_marker=kwargs.pop('marker', None),\n _default_marker_size=kwargs.pop('size', None),\n _default_color=kwargs.pop('color', None),\n )\n return self._add_item(cls, *args, **kwargs)\n\n def scatter(self, *args, **kwargs):\n \"\"\"Add a scatter plot.\"\"\"\n cls = _make_class(ScatterVisual,\n _default_marker=kwargs.pop('marker', None),\n )\n return self._add_item(cls, *args, **kwargs)\n\n def hist(self, *args, **kwargs):\n \"\"\"Add some histograms.\"\"\"\n return self._add_item(HistogramVisual, *args, **kwargs)\n\n def text(self, *args, **kwargs):\n \"\"\"Add text.\"\"\"\n return self._add_item(TextVisual, *args, **kwargs)\n\n def lines(self, *args, **kwargs):\n \"\"\"Add some lines.\"\"\"\n return self._add_item(LineVisual, *args, **kwargs)\n\n def __getitem__(self, box_index):\n self._default_box_index = _as_tuple(box_index)\n return self\n\n def build(self):\n \"\"\"Build all added items.\n\n Visuals are created, added, and built. The `set_data()` methods can\n be called afterwards.\n\n \"\"\"\n for cls, data_list in self._items.items():\n # Some variables are not concatenated. They are specified\n # in `allow_list`.\n data = _accumulate(data_list, cls.allow_list)\n box_index = data.pop('box_index')\n visual = cls()\n self.add_visual(visual)\n visual.set_data(**data)\n # NOTE: visual.program.__contains__ is implemented in vispy master\n # so we can replace this with `if 'a_box_index' in visual.program`\n # after the next VisPy release.\n if 'a_box_index' in visual.program._code_variables:\n visual.program['a_box_index'] = box_index.astype(np.float32)\n # TODO: refactor this when there is the possibility to update existing\n # visuals without recreating the whole scene.\n if self.lasso:\n self.lasso.create_visual()\n self.update()\n\n def get_pos_from_mouse(self, pos, box):\n # From window coordinates to NDC (pan & zoom taken into account).\n pos = self.panzoom.get_mouse_pos(pos)\n # From NDC to data coordinates.\n pos = self.interact.imap(pos, box) if self.interact else pos\n return pos\n\n @contextmanager\n def building(self):\n \"\"\"Context manager to specify the plots.\"\"\"\n self.clear()\n yield\n self.build()\n\n\n#------------------------------------------------------------------------------\n# Interactive tools\n#------------------------------------------------------------------------------\n\nclass Lasso(object):\n def __init__(self):\n self._points = []\n self.view = None\n self.visual = None\n self.box = None\n\n def add(self, pos):\n self._points.append(pos)\n self.update_visual()\n\n @property\n def polygon(self):\n l = self._points\n # Close the polygon.\n # l = l + l[0] if len(l) else l\n out = np.array(l, dtype=np.float64)\n out = np.reshape(out, (out.size // 2, 2))\n assert out.ndim == 2\n assert out.shape[1] == 2\n return out\n\n def clear(self):\n self._points = []\n self.box = None\n self.update_visual()\n\n @property\n def count(self):\n return len(self._points)\n\n def in_polygon(self, pos):\n return _in_polygon(pos, self.polygon)\n\n def attach(self, view):\n view.connect(self.on_mouse_press)\n self.view = view\n\n def create_visual(self):\n self.visual = PolygonVisual()\n self.view.add_visual(self.visual)\n self.update_visual()\n\n def update_visual(self):\n if not self.visual:\n return\n # Update the polygon.\n self.visual.set_data(pos=self.polygon)\n # Set the box index for the polygon, depending on the box\n # where the first point was clicked in.\n box = (self.box if self.box is not None\n else self.view._default_box_index)\n k = len(self.view._default_box_index)\n n = self.visual.vertex_count(pos=self.polygon)\n box_index = _get_array(box, (n, k)).astype(np.float32)\n self.visual.program['a_box_index'] = box_index\n self.view.update()\n\n def on_mouse_press(self, e):\n if 'Control' in e.modifiers:\n if e.button == 1:\n # Find the box.\n ndc = self.view.panzoom.get_mouse_pos(e.pos)\n # NOTE: we don't update the box after the second point.\n # In other words, the first point determines the box for the\n # lasso.\n if self.box is None and self.view.interact:\n self.box = self.view.interact.get_closest_box(ndc)\n # Transform from window coordinates to NDC.\n pos = self.view.get_pos_from_mouse(e.pos, self.box)\n self.add(pos)\n else:\n self.clear()\n self.box = None\n", "# -*- coding: utf-8 -*-\n\n\"\"\"Feature view.\"\"\"\n\n\n# -----------------------------------------------------------------------------\n# Imports\n# -----------------------------------------------------------------------------\n\nimport logging\nimport re\n\nimport numpy as np\nfrom six import u\n\nfrom phy.utils import Bunch\nfrom phy.utils._color import _colormap\nfrom phy.plot.transform import Range\nfrom .base import ManualClusteringView\n\nlogger = logging.getLogger(__name__)\n\n\n# -----------------------------------------------------------------------------\n# Feature view\n# -----------------------------------------------------------------------------\n\ndef _get_default_grid():\n \"\"\"In the grid specification, 0 corresponds to the best channel, 1\n to the second best, and so on. A, B, C refer to the PC components.\"\"\"\n s = \"\"\"\n time,0A 1A,0A 0B,0A 1B,0A\n 0A,1A time,1A 0B,1A 1B,1A\n 0A,0B 1A,0B time,0B 1B,0B\n 0A,1B 1A,1B 0B,1B time,1B\n \"\"\".strip()\n dims = [[_ for _ in re.split(' +', line.strip())]\n for line in s.splitlines()]\n return dims\n\n\ndef _get_point_color(clu_idx=None):\n if clu_idx is not None:\n color = tuple(_colormap(clu_idx)) + (.5,)\n else:\n color = (.5,) * 4\n assert len(color) == 4\n return color\n\n\ndef _get_point_size(clu_idx=None):\n return FeatureView._default_marker_size if clu_idx is not None else 1.\n\n\ndef _get_point_masks(masks=None, clu_idx=None):\n masks = masks if masks is not None else 1.\n # NOTE: we add the cluster relative index for the computation\n # of the depth on the GPU.\n return masks * .99999 + (clu_idx or 0)\n\n\ndef _get_masks_max(px, py):\n mx = px.get('masks', None)\n my = py.get('masks', None)\n if mx is None or my is None:\n return None\n return np.maximum(mx, my)\n\n\ndef _uniq(seq):\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]\n\n\nclass FeatureView(ManualClusteringView):\n _callback_delay = 20\n\n _default_marker_size = 5.\n default_shortcuts = {\n 'increase': 'ctrl++',\n 'decrease': 'ctrl+-',\n 'toggle_automatic_channel_selection': 'c',\n }\n\n def __init__(self,\n features=None,\n attributes=None,\n **kwargs):\n self._scaling = None\n\n assert features\n self.features = features\n\n self.n_cols = 4\n self.shape = (self.n_cols, self.n_cols)\n\n self.grid_dim = _get_default_grid() # [i][j] = '..,..'\n\n # If this is True, the channels won't be automatically chosen\n # when new clusters are selected.\n self.fixed_channels = False\n\n # Channels being shown.\n self.channel_ids = None\n\n # Attributes: extra features. This is a dictionary\n # {name: array}\n # where each array is a `(n_spikes,)` array.\n self.attributes = attributes or {}\n\n # Initialize the view.\n super(FeatureView, self).__init__(layout='grid',\n shape=self.shape,\n enable_lasso=True,\n **kwargs)\n\n # Internal methods\n # -------------------------------------------------------------------------\n\n def _iter_subplots(self):\n \"\"\"Yield (i, j, dim).\"\"\"\n for i in range(self.n_cols):\n for j in range(self.n_cols):\n # Skip lower-diagonal subplots.\n if i > j:\n continue\n dim = self.grid_dim[i][j]\n dim_x, dim_y = dim.split(',')\n yield i, j, dim_x, dim_y\n\n def _get_axis_label(self, dim):\n \"\"\"Return the channel id from a dimension, if applicable.\"\"\"\n if u(dim[:-1]).isdecimal():\n n = len(self.channel_ids)\n return str(self.channel_ids[int(dim[:-1]) % n]) + dim[-1]\n else:\n return dim\n\n def _get_axis_data(self, bunch, dim, cluster_id=None, load_all=None):\n \"\"\"Extract the points from the data on a given dimension.\n\n bunch is returned by the features() function.\n dim is the string specifying the dimensions to extract for the data.\n\n \"\"\"\n if dim in self.attributes:\n return self.attributes[dim](cluster_id, load_all=load_all)\n masks = bunch.get('masks', None)\n assert dim not in self.attributes # This is called only on PC data.\n s = 'ABCDEFGHIJ'\n # Channel relative index.\n c_rel = int(dim[:-1])\n # Get the channel_id from the currently-selected channels.\n channel_id = self.channel_ids[c_rel % len(self.channel_ids)]\n # Skup the plot if the channel id is not displayed.\n if channel_id not in bunch.channel_ids: # pragma: no cover\n return None\n # Get the column index of the current channel in data.\n c = list(bunch.channel_ids).index(channel_id)\n # Principal component: A=0, B=1, etc.\n d = s.index(dim[-1])\n if masks is not None:\n masks = masks[:, c]\n return Bunch(data=bunch.data[:, c, d],\n masks=masks,\n )\n\n def _get_axis_bounds(self, dim, bunch):\n \"\"\"Return the min/max of an axis.\"\"\"\n if dim in self.attributes:\n # Attribute: specified lim, or compute the min/max.\n vmin, vmax = bunch['lim']\n assert vmin is not None\n assert vmax is not None\n return vmin, vmax\n # PC dimensions: use the common scaling.\n return (-1. / self.scaling, +1. / self.scaling)\n\n def _plot_points(self, i, j, dim_x, dim_y, bunch, clu_idx=None):\n cluster_id = self.cluster_ids[clu_idx] if clu_idx is not None else None\n px = self._get_axis_data(bunch, dim_x, cluster_id=cluster_id)\n py = self._get_axis_data(bunch, dim_y, cluster_id=cluster_id)\n # Skip empty data.\n if px is None or py is None:\n return\n assert px.data.shape == py.data.shape\n xmin, xmax = self._get_axis_bounds(dim_x, px)\n ymin, ymax = self._get_axis_bounds(dim_y, py)\n masks = _get_masks_max(px, py)\n self[i, j].uscatter(x=px.data, y=py.data,\n color=_get_point_color(clu_idx),\n size=_get_point_size(clu_idx),\n masks=_get_point_masks(clu_idx=clu_idx,\n masks=masks),\n data_bounds=(xmin, ymin, xmax, ymax),\n )\n\n def _plot_labels(self):\n \"\"\"Plot feature labels along left and bottom edge of subplots\"\"\"\n # iterate simultaneously over kth row in left column and\n # kth column in bottom row:\n br = self.n_cols - 1 # bottom row\n for k in range(0, self.n_cols):\n dim_x, _ = self.grid_dim[0][k].split(',')\n _, dim_y = self.grid_dim[k][br].split(',')\n # Get the channel ids corresponding to the relative channel indices\n # specified in the dimensions. Channel 0 corresponds to the first\n # best channel for the selected cluster, and so on.\n dim_x = self._get_axis_label(dim_x)\n dim_y = self._get_axis_label(dim_y)\n # Left edge of left column of subplots.\n self[k, 0].text(pos=[-1., 0.],\n text=dim_y,\n anchor=[-1.03, 0.],\n data_bounds=None,\n )\n # Bottom edge of bottom row of subplots.\n self[br, k].text(pos=[0., -1.],\n text=dim_x,\n anchor=[0., -1.04],\n data_bounds=None,\n )\n\n def _plot_axes(self):\n for i, j, dim_x, dim_y in self._iter_subplots():\n self[i, j].lines(pos=[[-1., 0., +1., 0.],\n [0., -1., 0., +1.]],\n color=(.25, .25, .25, .5),\n data_bounds=None,\n )\n\n # Public methods\n # -------------------------------------------------------------------------\n\n def clear_channels(self):\n \"\"\"Reset the dimensions.\"\"\"\n self.channel_ids = None\n self.on_select()\n\n def on_select(self, cluster_ids=None, **kwargs):\n super(FeatureView, self).on_select(cluster_ids, **kwargs)\n cluster_ids = self.cluster_ids\n n_clusters = len(cluster_ids)\n if n_clusters == 0:\n return\n\n # Determine whether the channels should be fixed or not.\n added = kwargs.get('up', {}).get('added', None)\n # Fix the channels if the view updates after a cluster event\n # and there are new clusters.\n fixed_channels = (self.fixed_channels or\n kwargs.get('fixed_channels', None) or\n added is not None)\n\n # Get the feature data.\n # Specify the channel ids if these are fixed, otherwise\n # choose the first cluster's best channels.\n c = self.channel_ids if fixed_channels else None\n bunchs = [self.features(cluster_id, channel_ids=c)\n for cluster_id in cluster_ids]\n\n # Choose the channels based on the first selected cluster.\n channel_ids = list(bunchs[0].channel_ids)\n assert len(channel_ids)\n\n # Choose the channels automatically unless fixed_channels is set.\n if (not fixed_channels or self.channel_ids is None):\n self.channel_ids = channel_ids\n assert len(self.channel_ids)\n\n # Get the background data.\n background = self.features(channel_ids=self.channel_ids)\n\n # Plot all features.\n with self.building():\n self._plot_axes()\n\n # NOTE: the columns in bunch.data are ordered by decreasing quality\n # of the associated channels. The channels corresponding to each\n # column are given in bunch.channel_ids in the same order.\n\n # Find the initial scaling.\n if self._scaling in (None, np.inf):\n m = np.median(np.abs(background.data))\n m = m if m > 1e-9 else 1.\n self._scaling = .1 / m\n\n for i, j, dim_x, dim_y in self._iter_subplots():\n # Plot the background points.\n self._plot_points(i, j, dim_x, dim_y, background)\n\n # Plot each cluster's data.\n for clu_idx, bunch in enumerate(bunchs):\n self._plot_points(i, j, dim_x, dim_y, bunch,\n clu_idx=clu_idx)\n\n self._plot_labels()\n self.grid.add_boxes(self, self.shape)\n\n def attach(self, gui):\n \"\"\"Attach the view to the GUI.\"\"\"\n super(FeatureView, self).attach(gui)\n self.actions.add(self.increase)\n self.actions.add(self.decrease)\n self.actions.separator()\n self.actions.add(self.clear_channels)\n self.actions.add(self.toggle_automatic_channel_selection)\n\n gui.connect_(self.on_channel_click)\n gui.connect_(self.on_request_split)\n\n @property\n def state(self):\n return Bunch(scaling=self.scaling)\n\n def on_channel_click(self, channel_id=None, key=None, button=None):\n \"\"\"Respond to the click on a channel.\"\"\"\n channels = self.channel_ids\n if channels is None:\n return\n if len(channels) == 1:\n self.on_select()\n return\n assert len(channels) >= 2\n # Get the axis from the pressed button (1, 2, etc.)\n # axis = 'x' if button == 1 else 'y'\n d = 0 if button == 1 else 1\n # Change the first or second best channel.\n old = channels[d]\n # Avoid updating the view if the channel doesn't change.\n if channel_id == old:\n return\n channels[d] = channel_id\n # Ensure that the first two channels are different.\n if channels[1 - d] == channel_id:\n channels[1 - d] = old\n assert channels[0] != channels[1]\n # Remove duplicate channels.\n self.channel_ids = _uniq(channels)\n logger.debug(\"Choose channels %d and %d in feature view.\",\n *channels[:2])\n # Fix the channels temporarily.\n self.on_select(fixed_channels=True)\n\n def on_request_split(self):\n \"\"\"Return the spikes enclosed by the lasso.\"\"\"\n if (self.lasso.count < 3 or\n not len(self.cluster_ids)): # pragma: no cover\n return np.array([], dtype=np.int64)\n assert len(self.channel_ids)\n\n # Get the dimensions of the lassoed subplot.\n i, j = self.lasso.box\n dim = self.grid_dim[i][j]\n dim_x, dim_y = dim.split(',')\n\n # Get all points from all clusters.\n pos = []\n spike_ids = []\n\n for cluster_id in self.cluster_ids:\n # Load all spikes.\n bunch = self.features(cluster_id,\n channel_ids=self.channel_ids,\n load_all=True)\n px = self._get_axis_data(bunch, dim_x, cluster_id=cluster_id,\n load_all=True)\n py = self._get_axis_data(bunch, dim_y, cluster_id=cluster_id,\n load_all=True)\n points = np.c_[px.data, py.data]\n\n # Normalize the points.\n xmin, xmax = self._get_axis_bounds(dim_x, px)\n ymin, ymax = self._get_axis_bounds(dim_y, py)\n r = Range((xmin, ymin, xmax, ymax))\n points = r.apply(points)\n\n pos.append(points)\n spike_ids.append(bunch.spike_ids)\n pos = np.vstack(pos)\n spike_ids = np.concatenate(spike_ids)\n\n # Find lassoed spikes.\n ind = self.lasso.in_polygon(pos)\n self.lasso.clear()\n return np.unique(spike_ids[ind])\n\n def toggle_automatic_channel_selection(self):\n \"\"\"Toggle the automatic selection of channels when the cluster\n selection changes.\"\"\"\n self.fixed_channels = not self.fixed_channels\n\n # Feature scaling\n # -------------------------------------------------------------------------\n\n @property\n def scaling(self):\n return self._scaling or 1.\n\n @scaling.setter\n def scaling(self, value):\n self._scaling = value\n\n def increase(self):\n \"\"\"Increase the scaling of the features.\"\"\"\n self.scaling *= 1.2\n self.on_select(fixed_channels=True)\n\n def decrease(self):\n \"\"\"Decrease the scaling of the features.\"\"\"\n self.scaling /= 1.2\n self.on_select(fixed_channels=True)\n" ]
[ [ "numpy.reshape", "numpy.array" ], [ "numpy.maximum", "numpy.abs", "numpy.unique", "numpy.concatenate", "numpy.array", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jjfeng/CNNC
[ "35de5df0763aa27dd090e27fb9bb73e3a29f92d4" ]
[ "predict_easiernet.py" ]
[ "# Usage: python predict_no_y.py number_of_separation NEPDF_pathway model_pathway\r\n# command line in developer's linux machine :\r\n# python predict_no_y.py 9 /home/yey3/cnn_project/code3/NEPDF_data /home/yey3/cnn_project/code3/trained_model/models/KEGG_keras_cnn_trained_model_shallow2.h5\r\nfrom __future__ import print_function\r\nimport os,sys\r\nimport numpy as np\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import metrics\r\nfrom scipy import interp\r\n###############################\r\n# Jean modifications\r\nimport argparse\r\nimport json\r\nimport logging\r\n\r\nimport torch\r\nfrom scipy.special import logsumexp\r\n\r\nfrom spinn2.network import SierNet, VGGSierNet\r\n\r\nfrom common import get_perf\r\nfrom train_with_labels_wholedatax_easiernet import load_data_TF2\r\n\r\ndef parse_args(args):\r\n \"\"\" parse command line arguments \"\"\"\r\n\r\n parser = argparse.ArgumentParser(description=__doc__)\r\n\r\n parser.add_argument(\r\n \"--seed\",\r\n type=int,\r\n help=\"Random number generator seed for replicability\",\r\n default=12,\r\n )\r\n parser.add_argument(\r\n \"--do-binary\", action=\"store_true\", default=False, help=\"fit binary outcome\"\r\n )\r\n parser.add_argument(\r\n \"--data-path\", type=str\r\n )\r\n parser.add_argument(\r\n \"--model-path\", type=str\r\n )\r\n parser.add_argument(\r\n \"--tf-idx\", type=int, default=1\r\n )\r\n parser.add_argument(\r\n \"--is-vgg\", action=\"store_true\",\r\n )\r\n parser.add_argument(\r\n \"--out-file\", type=str\r\n )\r\n parser.add_argument(\r\n \"--log-file\", type=str\r\n )\r\n args = parser.parse_args()\r\n\r\n return args\r\n\r\ndef load_easier_net(model_file, is_vgg):\r\n meta_state_dict = torch.load(model_file)\r\n models = []\r\n for state_dict in meta_state_dict[\"state_dicts\"]:\r\n if is_vgg:\r\n model = VGGSierNet(\r\n n_inputs=(meta_state_dict[\"n_inputs\"], meta_state_dict[\"n_inputs\"]),\r\n n_out=meta_state_dict[\"n_out\"],\r\n input_filter_layer=meta_state_dict[\"input_filter_layer\"],\r\n )\r\n else:\r\n model = SierNet(\r\n n_layers=meta_state_dict[\"n_layers\"],\r\n n_input=meta_state_dict[\"n_inputs\"],\r\n n_hidden=meta_state_dict[\"n_hidden\"],\r\n n_out=meta_state_dict[\"n_out\"],\r\n input_filter_layer=meta_state_dict[\"input_filter_layer\"],\r\n )\r\n model.load_state_dict(state_dict)\r\n model.eval()\r\n model.get_net_struct()\r\n models.append(model)\r\n return models\r\n\r\ndef main(args=sys.argv[1:]):\r\n args = parse_args(args)\r\n logging.basicConfig(\r\n format=\"%(message)s\", filename=args.log_file, level=logging.DEBUG\r\n )\r\n\r\n test_TF = [args.tf_idx]\r\n (x_test, y_test, count_set) = load_data_TF2(test_TF,args.data_path, binary_outcome=args.do_binary, flatten=not args.is_vgg)\r\n if args.is_vgg:\r\n x_test = x_test.reshape((x_test.shape[0], 1, x_test.shape[1], x_test.shape[2]))\r\n else:\r\n x_test = x_test.reshape((x_test.shape[0],-1))\r\n print(x_test.shape, 'x_test samples')\r\n y_test = y_test.reshape((y_test.size, 1))\r\n ############\r\n\r\n models = load_easier_net(args.model_path, args.is_vgg)\r\n\r\n y_log_prob = logsumexp([model.predict_log_proba(x_test) for model in models], axis=0) - np.log(len(models))\r\n y_predict = np.exp(y_log_prob)\r\n perf_dict = get_perf(y_predict, y_test)\r\n perf_dict['model'] = \"EASIERnet-DNN\" if not args.is_vgg else \"EASIERnet-VGG\"\r\n perf_dict['tf'] = args.tf_idx\r\n print(perf_dict)\r\n with open(args.out_file, 'w') as f:\r\n json.dump(perf_dict, f)\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv[1:])\r\n" ]
[ [ "matplotlib.use", "numpy.exp", "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
qxr04025/facenet
[ "26bdacab531aba31f96bf50befd256b107aa42b6", "fe78f661234fcd7fdfe8d136b6e7711afe154a43" ]
[ "src/validate_on_lfw.py", "src/generative/calculate_dataset_normalization.py" ]
[ "\"\"\"Validate a face recognizer on the \"Labeled Faces in the Wild\" dataset (http://vis-www.cs.umass.edu/lfw/).\nEmbeddings are calculated using the pairs from http://vis-www.cs.umass.edu/lfw/pairs.txt and the ROC curve\nis calculated and plotted. Both the model metagraph and the model parameters need to exist\nin the same directory, and the metagraph should have the extension '.meta'.\n\"\"\"\n# MIT License\n# \n# Copyright (c) 2016 David Sandberg\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nimport facenet\nimport lfw\nimport os\nimport sys\nimport math\nfrom sklearn import metrics\nfrom scipy.optimize import brentq\nfrom scipy import interpolate\n\ndef main(args):\n \n with tf.Graph().as_default():\n os.environ['CUDA_VISIBLE_DEVICES'] = '3'\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)\n tfconfig = tf.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True)\n with tf.Session(config=tfconfig) as sess:\n \n # Read the file containing the pairs used for testing\n pairs = lfw.read_pairs(os.path.expanduser(args.lfw_pairs))\n\n # Get the paths for the corresponding images\n paths, actual_issame = lfw.get_paths(os.path.expanduser(args.lfw_dir), pairs, args.lfw_file_ext)\n\n # Load the model\n facenet.load_model(args.model)\n \n # Get input and output tensors\n images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n \n #image_size = images_placeholder.get_shape()[1] # For some reason this doesn't work for frozen graphs\n image_size = args.image_size\n embedding_size = embeddings.get_shape()[1]\n \n # Run forward pass to calculate embeddings\n print('Runnning forward pass on LFW images')\n batch_size = args.lfw_batch_size\n nrof_images = len(paths)\n nrof_batches = int(math.ceil(1.0*nrof_images / batch_size))\n emb_array = np.zeros((nrof_images, embedding_size))\n for i in range(nrof_batches):\n start_index = i*batch_size\n end_index = min((i+1)*batch_size, nrof_images)\n paths_batch = paths[start_index:end_index]\n images = facenet.load_data(paths_batch, False, False, image_size)\n feed_dict = { images_placeholder:images, phase_train_placeholder:False }\n emb_array[start_index:end_index,:] = sess.run(embeddings, feed_dict=feed_dict)\n \n tpr, fpr, accuracy, val, val_std, far = lfw.evaluate(emb_array, \n actual_issame, nrof_folds=args.lfw_nrof_folds)\n\n print('Accuracy: %1.3f+-%1.3f' % (np.mean(accuracy), np.std(accuracy)))\n print('Validation rate: %2.5f+-%2.5f @ FAR=%2.5f' % (val, val_std, far))\n\n auc = metrics.auc(fpr, tpr)\n print('Area Under Curve (AUC): %1.3f' % auc)\n eer = brentq(lambda x: 1. - x - interpolate.interp1d(fpr, tpr)(x), 0., 1.)\n print('Equal Error Rate (EER): %1.3f' % eer)\n \ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('--lfw_dir', type=str,\n help='Path to the data directory containing aligned LFW face patches.', default='/home/qinxiaoran/project/facenet/data/lfw/lfw-MTCNNcrop_160/')\n parser.add_argument('--lfw_batch_size', type=int,\n help='Number of images to process in a batch in the LFW test set.', default=100)\n parser.add_argument('model', type=str, \n help='Could be either a directory containing the meta_file and ckpt_file or a model protobuf (.pb) file')\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=160)\n parser.add_argument('--lfw_pairs', type=str,\n help='The file containing the pairs to use for validation.', default='data/pairs.txt')\n parser.add_argument('--lfw_file_ext', type=str,\n help='The file extension for the LFW dataset.', default='jpg', choices=['jpg', 'png'])\n parser.add_argument('--lfw_nrof_folds', type=int,\n help='Number of folds to use for cross validation. Mainly used for testing.', default=10)\n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n", "\"\"\"Calculate the mean and standard deviation (per channel) over all images in a dataset\n\"\"\"\n# MIT License\n# \n# Copyright (c) 2017 David Sandberg\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os.path\nimport sys\nimport random\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nimport facenet\n\ndef main(args):\n \n np.random.seed(seed=args.seed)\n random.seed(args.seed)\n train_set = facenet.get_dataset(args.data_dir)\n result_filename = os.path.join(os.path.expanduser(args.data_dir), 'statistics.txt')\n \n with tf.Graph().as_default():\n tf.set_random_seed(args.seed)\n \n # Get a list of image paths and their labels\n image_list, _ = facenet.get_image_paths_and_labels(train_set)\n nrof_images = len(image_list)\n assert nrof_images>0, 'The dataset should not be empty'\n \n input_queue = tf.train.string_input_producer(image_list, num_epochs=None,\n shuffle=False, seed=None, capacity=32)\n \n \n nrof_preprocess_threads = 4\n images = []\n for _ in range(nrof_preprocess_threads):\n filename = input_queue.dequeue()\n file_contents = tf.read_file(filename)\n image = tf.image.decode_image(file_contents)\n image = tf.image.resize_image_with_crop_or_pad(image, 160, 160)\n \n #pylint: disable=no-member\n image.set_shape((args.image_size, args.image_size, 3))\n image = tf.cast(image, tf.float32)\n images.append((image,))\n \n image_batch = tf.train.batch_join(images, batch_size=100, allow_smaller_final_batch=True)\n #mean = tf.reduce_mean(image_batch, reduction_indices=[0,1,2])\n m, v = tf.nn.moments(image_batch, [1,2])\n mean = tf.reduce_mean(m, 0)\n variance = tf.reduce_mean(v, 0)\n \n \n \n # Start running operations on the Graph.\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n sess.run(tf.global_variables_initializer())\n tf.train.start_queue_runners(sess=sess)\n\n with sess.as_default():\n\n # Training and validation loop\n print('Running training')\n nrof_batches = nrof_images // args.batch_size\n #nrof_batches = 20\n means = np.zeros(shape=(nrof_batches, 3), dtype=np.float32)\n variances = np.zeros(shape=(nrof_batches, 3), dtype=np.float32)\n for i in range(nrof_batches):\n means[i,:], variances[i,:] = sess.run([mean, variance])\n if (i+1)%10==0:\n print('Batch: %5d/%5d, Mean: %s, Variance: %s' % (i+1, nrof_batches, np.array_str(np.mean(means[:i,:],axis=0)), np.array_str(np.mean(variances[:i,:],axis=0))))\n dataset_mean = np.mean(means,axis=0)\n dataset_variance = np.mean(variances,axis=0)\n print('Final mean: %s' % np.array_str(dataset_mean))\n print('Final variance: %s' % np.array_str(dataset_variance))\n with open(result_filename, 'w') as text_file:\n print('Writing result to %s' % result_filename)\n text_file.write('Mean: %.5f, %.5f, %.5f\\n' % (dataset_mean[0], dataset_mean[1], dataset_mean[2]))\n text_file.write('Variance: %.5f, %.5f, %.5f\\n' % (dataset_variance[0], dataset_variance[1], dataset_variance[2]))\n \n \n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('--logs_base_dir', type=str, \n help='Directory where to write event logs.', default='~/logs/facenet')\n parser.add_argument('--models_base_dir', type=str,\n help='Directory where to write trained models and checkpoints.', default='~/models/facenet')\n parser.add_argument('--gpu_memory_fraction', type=float,\n help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)\n parser.add_argument('--pretrained_model', type=str,\n help='Load a pretrained model before training starts.')\n parser.add_argument('--data_dir', type=str,\n help='Path to the data directory containing aligned face patches.',\n default='~/datasets/casia/casia_maxpy_mtcnnalign_182_160')\n parser.add_argument('--model_def', type=str,\n help='Model definition. Points to a module containing the definition of the inference graph.', default='models.inception_resnet_v1')\n parser.add_argument('--max_nrof_epochs', type=int,\n help='Number of epochs to run.', default=500)\n parser.add_argument('--batch_size', type=int,\n help='Number of images to process in a batch.', default=90)\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=160)\n parser.add_argument('--epoch_size', type=int,\n help='Number of batches per epoch.', default=1000)\n parser.add_argument('--embedding_size', type=int,\n help='Dimensionality of the embedding.', default=128)\n parser.add_argument('--random_crop', \n help='Performs random cropping of training images. If false, the center image_size pixels from the training images are used. ' +\n 'If the size of the images in the data directory is equal to image_size no cropping is performed', action='store_true')\n parser.add_argument('--random_flip', \n help='Performs random horizontal flipping of training images.', action='store_true')\n parser.add_argument('--random_rotate', \n help='Performs random rotations of training images.', action='store_true')\n parser.add_argument('--keep_probability', type=float,\n help='Keep probability of dropout for the fully connected layer(s).', default=1.0)\n parser.add_argument('--weight_decay', type=float,\n help='L2 weight regularization.', default=0.0)\n parser.add_argument('--decov_loss_factor', type=float,\n help='DeCov loss factor.', default=0.0)\n parser.add_argument('--center_loss_factor', type=float,\n help='Center loss factor.', default=0.0)\n parser.add_argument('--center_loss_alfa', type=float,\n help='Center update rate for center loss.', default=0.95)\n parser.add_argument('--optimizer', type=str, choices=['ADAGRAD', 'ADADELTA', 'ADAM', 'RMSPROP', 'MOM'],\n help='The optimization algorithm to use', default='ADAGRAD')\n parser.add_argument('--learning_rate', type=float,\n help='Initial learning rate. If set to a negative value a learning rate ' +\n 'schedule can be specified in the file \"learning_rate_schedule.txt\"', default=0.1)\n parser.add_argument('--learning_rate_decay_epochs', type=int,\n help='Number of epochs between learning rate decay.', default=100)\n parser.add_argument('--learning_rate_decay_factor', type=float,\n help='Learning rate decay factor.', default=1.0)\n parser.add_argument('--moving_average_decay', type=float,\n help='Exponential decay for tracking of training parameters.', default=0.9999)\n parser.add_argument('--seed', type=int,\n help='Random seed.', default=666)\n parser.add_argument('--nrof_preprocess_threads', type=int,\n help='Number of preprocessing (data loading and augmentation) threads.', default=4)\n parser.add_argument('--log_histograms', \n help='Enables logging of weight/bias histograms in tensorboard.', action='store_true')\n parser.add_argument('--learning_rate_schedule_file', type=str,\n help='File containing the learning rate schedule that is used when learning_rate is set to to -1.', default='data/learning_rate_schedule.txt')\n parser.add_argument('--filter_filename', type=str,\n help='File containing image data used for dataset filtering', default='')\n parser.add_argument('--filter_percentile', type=float,\n help='Keep only the percentile images closed to its class center', default=100.0)\n parser.add_argument('--filter_min_nrof_images_per_class', type=int,\n help='Keep only the classes with this number of examples or more', default=0)\n \n # Parameters for validation on LFW\n parser.add_argument('--lfw_pairs', type=str,\n help='The file containing the pairs to use for validation.', default='data/pairs.txt')\n parser.add_argument('--lfw_file_ext', type=str,\n help='The file extension for the LFW dataset.', default='png', choices=['jpg', 'png'])\n parser.add_argument('--lfw_dir', type=str,\n help='Path to the data directory containing aligned face patches.', default='')\n parser.add_argument('--lfw_batch_size', type=int,\n help='Number of images to process in a batch in the LFW test set.', default=100)\n parser.add_argument('--lfw_nrof_folds', type=int,\n help='Number of folds to use for cross validation. Mainly used for testing.', default=10)\n return parser.parse_args(argv)\n \n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n" ]
[ [ "tensorflow.Graph", "tensorflow.get_default_graph", "tensorflow.ConfigProto", "numpy.std", "scipy.interpolate.interp1d", "tensorflow.GPUOptions", "numpy.mean", "tensorflow.Session", "sklearn.metrics.auc", "numpy.zeros" ], [ "tensorflow.image.resize_image_with_crop_or_pad", "tensorflow.Graph", "numpy.random.seed", "tensorflow.reduce_mean", "tensorflow.read_file", "tensorflow.train.start_queue_runners", "tensorflow.nn.moments", "tensorflow.cast", "tensorflow.train.batch_join", "tensorflow.ConfigProto", "tensorflow.global_variables_initializer", "numpy.array_str", "tensorflow.train.string_input_producer", "tensorflow.GPUOptions", "tensorflow.image.decode_image", "numpy.mean", "tensorflow.set_random_seed", "numpy.zeros" ] ]
[ { "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", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
debjyoti0891/map
[ "abdae67964420d7d36255dcbf83e4240a1ef4295", "abdae67964420d7d36255dcbf83e4240a1ef4295", "abdae67964420d7d36255dcbf83e4240a1ef4295" ]
[ "helios/plato/py/plato/backend/stat_expression.py", "helios/plato/django/server/bpEndpoint.py", "helios/plato/py/tests/heatmap_delta_weight_sum_investigation.py" ]
[ "import numba\nimport numpy as np\n\n\[email protected](nopython=True, nogil=True)\ndef NoTransform(value_in):\n return value_in\n\n\[email protected](nopython=True, nogil=True)\ndef AbsValueTransform(value_in):\n return np.abs(value_in)\n\n\n# Interpret stats, turning any compound stats into individual stats.\n# Takes a list of stat names and a map of all compound stats' stat-names to their stat structure.\n# Returns a list of tuples [ (raw_stat_name1, Transform1), (raw_stat_name2, Transform2), ... ]\ndef interpret_compound_stats(stat_names, compound_stats_map):\n real_stat_cols = []\n for stat_name in stat_names:\n if stat_name not in compound_stats_map:\n real_stat_cols.append((stat_name, NoTransform))\n else:\n stat = compound_stats_map[stat_name]\n\n # Break out the components\n compound = stat['compound']\n xform = AbsValueTransform if compound.get('a_abs', False) else NoTransform\n real_stat_cols.append((compound['a'], xform))\n if compound.get('b', None) is not None:\n assert(compound.get('op', None) is not None), 'Compound stat {} missing op'.format(stat_name, stat)\n xform = AbsValueTransform if compound.get('b_abs', False) else NoTransform\n real_stat_cols.append((compound['b'], xform))\n\n return real_stat_cols\n\n\n# Takes a stat name, and a map of all compound stats' stat-names to their stat structure. Also takes\n# inputs a and b which should be numpy arrays or some other structure which can accept broadcasted component-wise\n# arithmetic operators (e.g. */+-). a and b should have been populated as prescribed by interpret_compound_stats(...).\n# Returns the appropriate combination of a and b.\ndef assemble_compound_stat(stat_name, compound_stats_map, a, b=None):\n if stat_name not in compound_stats_map:\n return a\n\n # Get the compound info\n compound = compound_stats_map[stat_name]['compound']\n\n if compound.get('b', None) is None:\n return a\n\n assert(b is not None), 'compound stat {} requires a and b inputs, but b is None'.format(stat_name)\n\n op_name = compound['op']\n op = {\n '*': np.multiply,\n '/': np.divide,\n '+': np.add,\n '-': np.subtract,\n }[op_name]\n return op(a, b)\n\n\n#{\n#'name': 'abs_weight_change',\n#'type': STAT_TYPE_SUMMABLE,\n#'compound': {\n# 'a': 'd_weight',\n# 'b': None,\n# 'op': None,\n# 'a_abs': True,\n#}", "import asyncio\nfrom collections import OrderedDict\nimport concurrent\nfrom contextlib import contextmanager\nfrom functools import wraps\nimport functools\nimport itertools\nimport json\nimport logging\nimport math\nfrom os import access\nimport os\nfrom os.path import realpath, basename, dirname\nfrom pathlib import Path\nfrom threading import Lock\nimport threading\nimport time\nimport traceback\nfrom uuid import uuid5\nimport uuid\n\nfrom asgiref.sync import async_to_sync\nfrom channels.generic.websocket import AsyncWebsocketConsumer\nfrom django.core.cache import caches\n\nfrom server import settings\nfrom server.beakercache import cache\nimport numpy as np\nfrom plato.backend.adapters.branch_training_trace.adapter import BranchTrainingTraceAdapter\nfrom plato.backend.adapters.pevent_trace.adapter import PeventTraceAdapter\nfrom plato.backend.adapters.sparta_statistics.adapter import SpartaStatisticsAdapter\nfrom plato.backend.common import logtime, synchronized, synchronizedFine, countactive\nfrom plato.backend.datasources.branch_training_trace.datasource import BranchTrainingDatasource\nfrom plato.backend.datasources.pevent_trace.datasource import PeventDataSource\nfrom plato.backend.datasources.sparta_statistics.datasource import SpartaDataSource\nfrom plato.backend.processors.branch_training_heatmap.adapter import BranchTrainingHeatMapAdapter\nfrom plato.backend.processors.branch_training_heatmap.generator import BranchTrainingHeatMapGenerator\nfrom plato.backend.processors.branch_training_line_plot.generator import BranchTrainingLinePlotGenerator\nfrom plato.backend.processors.branch_training_profile.generator import BranchTrainingProfileHtmlGenerator\nfrom plato.backend.processors.branch_training_table.generator import BranchTrainingListHtmlGenerator\nfrom plato.backend.processors.general_line_plot.generator import GeneralTraceLinePlotGenerator\nfrom plato.backend.processors.pevent_trace_generator.generator import PeventTraceGenerator\nfrom plato.backend.processors.sparta_statistics.generator import SpartaStatsGenerator\nfrom plato.backend.units import Units\nfrom .models import DataId, ProcessorId, LongFunctionCall\n\nlogger = logging.getLogger(\"plato.backend.bpEndpoint\")\n\n\nclass bpEndpoint(AsyncWebsocketConsumer):\n '''\n this is the endpoint for most of the data operations that happen in plato\n handles branch prediction, SPARTA data sources, etc.\n '''\n\n # this is the cache that will speed up complex lookups and hold references\n # to useful data structures that are used for doing data processing\n beakerCache = cache.get_cache('branchPredictor', expire = 3600)\n\n def __init__(self, *args, **kwargs):\n '''\n ctor\n '''\n super().__init__(*args, **kwargs)\n self.callback = None\n self.sendLock = Lock()\n self.loop = asyncio.get_event_loop()\n # the thread pool, whenever a request is received via an async function\n # call, it is immediately launched onto a concurrent thread to avoid\n # keeping the async thread busy, when the processing is done then it\n # will come back to the async thread to send the result back to the client\n self.threadPoolExecutor = concurrent.futures.ThreadPoolExecutor(max_workers = settings.WORKER_THREADS,\n thread_name_prefix = \"wsEndpointWorker\")\n\n async def connect(self):\n '''\n look at the call that this wants to use and cache that\n '''\n path = self.scope.get('path', '')\n\n if path == '/ws/getData':\n self.callback = self.getData\n await self.accept()\n elif path == '/ws/sources':\n self.callback = self.sources\n await self.accept()\n else:\n logger.error(f\"error: not recognized: {path}\")\n await self.close()\n\n async def disconnect(self, close_code):\n '''\n when the client disconnects from the websocket\n '''\n await self.close()\n\n async def receive(self, text_data = None, bytes_data = None):\n '''\n capture and route the actual request\n '''\n # go run this on a separate thread\n # TODO ensure that only text_data is received, clients should be sending\n # json as text, not binary\n blockingTask = asyncio.get_event_loop().run_in_executor(self.threadPoolExecutor,\n self.callback,\n text_data)\n\n def sendMessage(self, text_data = None, bytes_data = None, close = False):\n with self.sendLock:\n loop = self.loop\n\n if text_data:\n future = asyncio.run_coroutine_threadsafe(self.send(json.dumps(text_data), None, close), loop)\n future.result()\n if bytes_data is not None:\n future = asyncio.run_coroutine_threadsafe(self.send(None, bytes_data if len(bytes_data) else b'0', close), loop)\n future.result()\n\n @logtime(logger)\n @cache.cache('getSourceInformation', expire = 360)\n def getSourceInformation(self, path):\n '''\n go look at the file type and get info about it, determine what can read\n it and then go cache the reader for it\n '''\n isHdf5File = path.endswith(\"hdf5\")\n\n if isHdf5File:\n if BranchTrainingDatasource.can_read(path):\n return BranchTrainingDatasource.get_source_information(path), \"branch-predictor-training-trace\"\n elif PeventDataSource.can_read(path):\n return PeventDataSource.get_source_information(path), \"pevent-trace\"\n else:\n raise ValueError(\"unknown hdf5 type, pevent and branch training data sources cannot read this\")\n else:\n return SpartaDataSource.get_source_information(path), \"sparta-statistics\"\n\n @logtime(logger)\n def loadFile(self, jsonData, returnValue):\n '''\n load a single file and return data\n '''\n returnValue['waitEstimate'] = 12345\n file = jsonData['file']\n\n if not access(file, os.R_OK):\n raise ValueError(\"cannot read file\")\n\n currentFile = realpath(file)\n # use the django ORM to lookup or create a persistent UUID for this file\n dataIdObj, created = DataId.objects.get_or_create(path = file,\n defaults = {'uuid': str(uuid5(uuid.NAMESPACE_URL,\n file))})\n\n returnValue[\"result\"] = \"complete\"\n logger.debug(f\"{currentFile} created? {created}: {dataIdObj}\")\n\n statVals, typeId = self.getSourceInformation(file)\n\n newDict = {\"name\": str(basename(file)),\n \"directory\": dirname(file),\n \"typeId\": typeId,\n \"dataId\": dataIdObj.uuid}\n\n for key, value in statVals.items():\n newDict[key] = value\n\n returnValue[\"sources\"] = [newDict]\n\n @logtime(logger)\n def getProcessor(self, jsonData, returnValue):\n '''\n get the processor ID for a given processor type + data ID\n this may take a long time so it should be run in a separate thread,\n rather than the main event loop\n '''\n dataId = jsonData['dataId']\n processor = jsonData['processor']\n kwargs = json.dumps(OrderedDict(sorted(jsonData['kwargs'].items(), key = lambda kv: kv[0])))\n\n # TODO need a better UUID?\n processorUuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, name = str(time.time())))\n\n processorIdObj, created = ProcessorId.objects.get_or_create(dataUuid = dataId,\n processor = processor,\n kwargs = kwargs,\n defaults = {'uuid': processorUuid, })\n logger.debug(f\"{dataId} created? {created}: {processorIdObj}\")\n returnValue['processorId'] = processorIdObj.uuid\n\n if processor == \"shp-heatmap-generator\":\n bpEndpoint.getShpHeatmapGenerator(processorIdObj.uuid)\n elif processor == \"shp-line-plot-generator\":\n bpEndpoint.getShpLinePlotGenerator(processorIdObj.uuid)\n elif processor == \"shp-branch-list-generator\":\n bpEndpoint.getShpTableHtmlGenerator(processorIdObj.uuid)\n elif processor == \"simdb-line-plot-generator\":\n bpEndpoint.getSimDbLinePlotGenerator(processorIdObj.uuid)\n elif processor == \"simdb-get-all-data-generator\":\n bpEndpoint.getSimDbStatsGenerator(processorIdObj.uuid)\n elif processor == \"shp-branch-profile-generator\":\n bpEndpoint.getShpBranchProfileHtmlGenerator(processorIdObj.uuid)\n elif processor == \"pevent-trace-generator\":\n bpEndpoint.getPeventTraceGenerator(processorIdObj.uuid)\n else:\n raise ValueError(f\"unknown processor type {processor}\")\n\n returnValue['result'] = 'complete'\n\n @logtime(logger)\n def loadDirectory(self, jsonData, returnValue):\n '''\n go scan a directory and return metadata + generated UUIDs\n '''\n returnValue['waitEstimate'] = 12345\n directory = Path(jsonData['directory']).resolve()\n returnValue['directory'] = str(directory)\n returnValue[\"result\"] = \"in-progress\"\n hdf5GlobPattern = jsonData.get('globPattern', \"*hdf5\")\n dbGlobPattern = jsonData.get('globPattern', \"*db\")\n\n self.sendMessage(returnValue)\n\n # detect errors\n if not directory.is_dir():\n raise ValueError(f\"cannot read directory: {str(directory)}\")\n if not access(directory, os.R_OK):\n raise ValueError(\"cannot access directory\")\n\n returnValue['subDirectories'] = [str(x) for x in Path(directory).iterdir() if x.is_dir()]\n\n dbFiles = list(filter(os.path.isfile, directory.glob(dbGlobPattern)))\n\n hdf5Files = list(filter(os.path.isfile, directory.glob(hdf5GlobPattern)))\n\n returnValue['result'] = 'partial'\n returnValue['sources'] = []\n\n for i, currentFile in enumerate(hdf5Files + dbFiles):\n # need the canonical path of the file to generate a UUID\n relativePath = currentFile.relative_to(directory)\n currentFile = realpath(currentFile)\n\n isHdf5File = currentFile.endswith(\"hdf5\")\n\n if isHdf5File:\n # two options, branch training or p-events\n if BranchTrainingDatasource.can_read(currentFile):\n typeId = \"branch-predictor-training-trace\"\n elif PeventDataSource.can_read(currentFile):\n typeId = \"pevent-trace\"\n else:\n raise ValueError(\"unknown hdf5 type, pevent and branch training data sources cannot read this\")\n else:\n typeId = \"sparta-statistics\"\n\n dataIdObj, created = DataId.objects.get_or_create(path = currentFile,\n defaults = {'uuid': str(uuid5(uuid.NAMESPACE_URL,\n currentFile))})\n\n logger.debug(f\"{currentFile} created? {created}: {dataIdObj}\")\n newDict = {\"name\": str(relativePath),\n \"typeId\": typeId,\n \"dataId\": dataIdObj.uuid}\n\n returnValue['sources'].append(newDict)\n\n if i + 1 != len(hdf5Files + dbFiles):\n self.sendMessage(returnValue)\n\n returnValue['result'] = 'complete'\n\n @logtime(logger)\n def sources(self, value):\n '''\n load sources and return progress\n this may take a while and should be run in its own thread when possible\n '''\n returnValue = {}\n\n try:\n jsonData = json.loads(value)\n command = returnValue[\"command\"] = jsonData['command']\n returnValue[\"result\"] = \"error\"\n returnValue[\"reqSeqNum\"] = jsonData[\"reqSeqNum\"]\n\n if command == 'getProcessor':\n # cache a processor\n self.getProcessor(jsonData, returnValue)\n\n elif command == 'loadFile':\n # populate with just a single file\n self.loadFile(jsonData, returnValue)\n\n elif command == 'loadDirectory':\n # then populate the cache with all files in this directory\n self.loadDirectory(jsonData, returnValue)\n else:\n raise ValueError(f\"unknown command {command}\")\n\n self.sendMessage(returnValue)\n\n except Exception as e:\n logger.exception(\"problem in sources()\")\n returnValue[\"result\"] = \"error\"\n returnValue[\"stackTrace\"] = traceback.format_exc()\n returnValue[\"errorMessage\"] = \"error in sources(): {}\".format(e)\n\n self.sendMessage(returnValue)\n\n @countactive\n @logtime(logger)\n def getData(self, value):\n '''\n get a branch predictor heatmap or line-plot in byte format\n '''\n logger.debug(f\"getData() with request ${json.loads(value)}\")\n start = time.time()\n\n responseValue = {\"reqSeqNum\": -1,\n \"result\": \"error\",\n \"duration\": 0,\n \"processorSpecific\": {}}\n\n try:\n jsonData = json.loads(value)\n first = jsonData['first']\n last = jsonData['last']\n processorId = jsonData['processorId']\n kwargs = jsonData['kwargs']\n responseValue[\"reqSeqNum\"] = jsonData['reqSeqNum']\n\n processor = self.lookupProcessorId(processorId)[0]\n\n if processor.processor == \"shp-heatmap-generator\":\n bphmg = bpEndpoint.getShpHeatmapGenerator(processor.uuid)\n\n logger.debug(f\"calling generate_2d_heatmap_with_profiles() with {[first,last]}, {kwargs}\")\n\n heatMap, tableMeans, rowMeans, tableStds, tableMins, tableMaxs, tableMedians, = \\\n bphmg.generate_2d_heatmap_with_profiles_and_stats(first, last, **kwargs)\n\n responseValue[\"processorSpecific\"][\"numRows\"] = heatMap.shape[0]\n responseValue[\"processorSpecific\"][\"numCols\"] = heatMap.shape[1]\n responseValue[\"processorSpecific\"][\"zMin\"] = int(round(np.nanmin(heatMap)))\n responseValue[\"processorSpecific\"][\"zMax\"] = int(round(np.nanmax(heatMap)))\n responseValue[\"processorSpecific\"][\"zBlobOffset\"] = 0\n resultBin = heatMap.tobytes()\n\n responseValue[\"processorSpecific\"][\"tableMeansBlobOffset\"] = len(resultBin)\n resultBin += tableMeans.tobytes()\n\n responseValue[\"processorSpecific\"][\"rowMeansBlobOffset\"] = len(resultBin)\n resultBin += rowMeans.tobytes()\n\n responseValue[\"processorSpecific\"][\"tableStdsBlobOffset\"] = len(resultBin)\n resultBin += tableStds.tobytes()\n\n responseValue[\"processorSpecific\"][\"tableMinsBlobOffset\"] = len(resultBin)\n resultBin += tableMins.tobytes()\n\n responseValue[\"processorSpecific\"][\"tableMaxsBlobOffset\"] = len(resultBin)\n resultBin += tableMaxs.tobytes()\n\n responseValue[\"processorSpecific\"][\"tableMediansBlobOffset\"] = len(resultBin)\n resultBin += tableMedians.tobytes()\n\n elif processor.processor == \"shp-line-plot-generator\":\n logger.debug(f\"calling generate_lines() with {[first,last]}, {kwargs}\")\n resultBin = self.getShpLinePlot(jsonData, responseValue)\n\n elif processor.processor == \"shp-branch-list-generator\":\n bptg = bpEndpoint.getShpTableHtmlGenerator(processor.uuid)\n logger.debug(f\"calling generate_table() with {[first,last]}, {kwargs}\")\n result = bptg.generate_table(first, last, **kwargs)\n\n responseValue[\"processorSpecific\"] = {\"stringLength\": len(result),\n \"stringBlobOffset\": 0}\n resultBin = result.encode('utf-8')\n\n elif processor.processor == \"shp-branch-profile-generator\":\n sbpg = bpEndpoint.getShpBranchProfileHtmlGenerator(processor.uuid)\n logger.debug(f\"calling generate_table() with {[first,last]}, {kwargs}\")\n\n result = sbpg.generate_table(first, last, **kwargs)\n\n responseValue[\"processorSpecific\"] = {\"stringLength\": len(result),\n \"stringBlobOffset\": 0}\n resultBin = result.encode('utf-8')\n\n elif processor.processor == \"simdb-line-plot-generator\":\n sdblp = bpEndpoint.getSimDbLinePlotGenerator(processor.uuid)\n\n result = sdblp.generate_lines(first, last, **kwargs)\n\n if result.shape[1] == 0:\n yExtents = [-1, 1]\n else:\n yExtents = [np.nanmin(result[1:]), np.nanmax(result[1:])] # Skip the first row (units)\n\n responseValue[\"processorSpecific\"][\"numSeries\"] = result.shape[0]\n responseValue[\"processorSpecific\"][\"pointsPerSeries\"] = result.shape[1]\n responseValue[\"processorSpecific\"][\"seriesBlobOffset\"] = 0\n responseValue[\"processorSpecific\"][\"yExtents\"] = yExtents\n resultBin = result.astype(dtype = 'f4', copy = False).tobytes()\n\n elif processor.processor == \"simdb-get-all-data-generator\":\n resultBin = self.simdbGetAllData(processor.uuid, jsonData, responseValue)\n\n elif processor.processor == \"pevent-trace-generator\":\n peventTraceGenerator = bpEndpoint.getPeventTraceGenerator(processor.uuid)\n\n histograms = peventTraceGenerator.generate_histograms(first, last, **kwargs)\n\n psData = responseValue[\"processorSpecific\"] = {}\n psData[\"numSeries\"] = len(histograms.keys())\n psData[\"series\"] = list(histograms.keys())\n psData[\"histLengths\"] = [len(v[0]) for v in histograms.values()]\n psData[\"edgesLengths\"] = [len(v[1]) for v in histograms.values()]\n\n resultBin = next(itertools.islice(histograms.values(), 0, 1))[1].astype(dtype = 'f4').tobytes()\n for v in histograms.values():\n resultBin += v[0].astype(dtype = 'f4').tobytes()\n\n else:\n raise ValueError(f\"{processorId} isn't in the database, can't do a lookup\")\n\n responseValue[\"result\"] = \"complete\"\n responseValue[\"durationMs\"] = math.ceil((time.time() - start) * 1000)\n\n # send the metadata back in json format\n self.sendMessage(responseValue, resultBin)\n\n except Exception as e:\n # something went wrong, need to let the client know\n logger.exception(f\"problem in getData(), {value}\")\n responseValue[\"stackTrace\"] = traceback.format_exc()\n responseValue[\"errorMessage\"] = str(e)\n responseValue[\"durationMs\"] = math.ceil((time.time() - start) * 1000)\n\n self.sendMessage(responseValue)\n\n def getShpLinePlot(self, jsonData, responseValue):\n '''\n find the shp generator then tell it to generate a line plot\n '''\n processorId = jsonData['processorId']\n\n if True:\n processor = self.lookupProcessorId(processorId)[0]\n else:\n # TODO this will saturate the db connections quickly, need to either\n # find the connection leak or add db connection pooling\n processor = ProcessorId.objects.get(uuid = processorId)\n bplpg = bpEndpoint.getShpLinePlotGenerator(processor.uuid)\n\n first = jsonData['first']\n last = jsonData['last']\n kwargs = jsonData['kwargs']\n result, modalities, downsamplingLevel, yExtents = bplpg.generate_lines_and_more(first, last, **kwargs)\n\n responseValue[\"processorSpecific\"][\"numSeries\"] = result.shape[0]\n responseValue[\"processorSpecific\"][\"pointsPerSeries\"] = result.shape[1]\n responseValue[\"processorSpecific\"][\"downsampling\"] = downsamplingLevel\n responseValue[\"processorSpecific\"][\"seriesBlobOffset\"] = 0\n responseValue[\"processorSpecific\"][\"yExtents\"] = yExtents\n blob = result.astype(dtype = 'f4', copy = False).tobytes()\n\n responseValue[\"processorSpecific\"][\"modalitiesOffset\"] = len(blob)\n blob += modalities.astype(dtype = 'i2', copy = False).tobytes()\n\n if downsamplingLevel <= 1:\n # Get some data that only makes sense at no-downsampling. User can view individual points' data\n otherKwargs = {\"units\": kwargs[\"units\"],\n \"stat_cols\": ['pc', 'tgt', 'trn_idx', 'instructions'],\n \"branch_predictor_filtering\": kwargs.get(\"branch_predictor_filtering\", {}),\n \"point_cache\": kwargs.get(\"point_cache\", True)}\n points = bplpg.generate_simple_int_points(first, last, **otherKwargs)\n pcs = points[0]\n tgts = points[1]\n indices = points[2]\n instructions = points[3]\n\n # Since these arrays are 8B, they must be aligned to 8B for javascript arrays to be happy.\n misalignment = len(blob) % 8\n if misalignment > 0:\n blob += bytes([0] * (8 - misalignment))\n responseValue[\"processorSpecific\"][\"indicesOffset\"] = len(blob)\n blob += indices.tobytes()\n\n misalignment = len(blob) % 8\n if misalignment > 0:\n blob += bytes([0] * (8 - misalignment))\n responseValue[\"processorSpecific\"][\"addressesOffset\"] = len(blob)\n blob += pcs.tobytes()\n\n misalignment = len(blob) % 8\n if misalignment > 0:\n blob += bytes([0] * (8 - misalignment))\n responseValue[\"processorSpecific\"][\"targetsOffset\"] = len(blob)\n blob += tgts.tobytes()\n\n misalignment = len(blob) % 8\n if misalignment > 0:\n blob += bytes([0] * (8 - misalignment))\n responseValue[\"processorSpecific\"][\"instructionNumsOffset\"] = len(blob)\n blob += instructions.tobytes()\n\n return blob\n\n def simdbGetAllData(self, processorUuid, jsonData, responseValue):\n\n first = jsonData['first']\n last = jsonData['last']\n\n statsGen = bpEndpoint.getSimDbStatsGenerator(processorUuid)\n kwargs = jsonData['kwargs']\n whichChanged = kwargs[\"whichChanged\"]\n\n psData = responseValue[\"processorSpecific\"]\n\n if whichChanged:\n del kwargs[\"whichChanged\"]\n # so x or y is updated\n a = self.threadPoolExecutor.submit(functools.partial(statsGen.generate_lines,\n first,\n last,\n **kwargs))\n blockingTasks = [a]\n\n else:\n a = None\n blockingTasks = []\n psData[\"pointsPerSeries\"] = 0\n\n psData[\"stat_cols\"] = kwargs['stat_cols']\n\n # TODO this is redundant, should either be able to pass this to other calls and save them\n # the trouble or get it as a byproduct of others calls calculating this\n b = self.threadPoolExecutor.submit(functools.partial(statsGen.adapter.range_to_rows,\n first,\n last,\n kwargs[\"units\"]))\n c = self.threadPoolExecutor.submit(functools.partial(statsGen.generate_histogram,\n first,\n last,\n kwargs[\"units\"],\n kwargs[\"stat_cols\"][0],\n -1))\n d = self.threadPoolExecutor.submit(functools.partial(statsGen.generate_histogram,\n first,\n last,\n kwargs[\"units\"],\n kwargs[\"stat_cols\"][1],\n -1))\n e = self.threadPoolExecutor.submit(functools.partial(statsGen.generate_regression_line,\n first,\n last,\n **kwargs))\n blockingTasks.extend([b, c, d, e])\n results = []\n for futureTask in blockingTasks:\n result = futureTask.result()\n results.append((futureTask, result))\n\n x = y = indices = None\n\n for futureTask, result in results:\n if futureTask == a:\n indices, x, y = result\n psData[\"xMin\"] = min(x)\n psData[\"xMax\"] = max(x)\n psData[\"yMin\"] = min(y)\n psData[\"yMax\"] = max(y)\n psData[\"pointsPerSeries\"] = len(x)\n\n elif futureTask == b:\n firstRow, lastRow, _ = result\n psData[\"firstRow\"] = firstRow\n psData[\"lastRow\"] = lastRow\n psData[\"first\"] = first\n psData[\"last\"] = last\n\n elif futureTask == c:\n hEdges, hHist = result\n psData[\"hHistLength\"] = len(hHist)\n psData[\"hEdgesLength\"] = len(hEdges)\n\n elif futureTask == d:\n vEdges, vHist = result\n psData[\"vEdgesLength\"] = len(vEdges)\n psData[\"vHistLength\"] = len(vHist)\n\n elif futureTask == e:\n regX, regY = result\n psData[\"regLength\"] = len(regX)\n\n if x is not None:\n return indices.astype(dtype = 'f4').tobytes() + \\\n x.astype(dtype = 'f4').tobytes() + y.astype(dtype = 'f4').tobytes() + \\\n hEdges.tobytes() + hHist.tobytes() + \\\n vEdges.tobytes() + vHist.tobytes() + \\\n regX.tobytes() + regY.tobytes()\n else:\n return hEdges.tobytes() + hHist.tobytes() + \\\n vEdges.tobytes() + vHist.tobytes() + \\\n regX.tobytes() + regY.tobytes()\n\n @staticmethod\n @logtime(logger)\n @cache.cache('lookupProcessorId', expire = 3600)\n def lookupProcessorId(processorId):\n logger.debug(f\"lookup in ProcessorId for {processorId}\")\n procId = ProcessorId.objects.get(uuid = processorId)\n dataUuid = procId.dataUuid\n logger.debug(f\"returned {dataUuid}\")\n path = DataId.objects.filter(uuid = dataUuid)[0].path\n logger.debug(f\"returned {path}\")\n\n return procId, path\n\n endpointLock = Lock()\n endpointLockDict = {}\n\n @staticmethod\n # TODO need to make a mutex per path, or globally\n @synchronized(endpointLock)\n # @synchronizedFine(endpointLockDict, endpointLock)\n @cache.cache('dataSource', expire = 3600)\n @logtime(logger)\n def getDataSource(path):\n logger.debug(f\"open data source: {path}\")\n if path.endswith(\"hdf5\"):\n if BranchTrainingDatasource.can_read(path):\n return BranchTrainingDatasource(path)\n elif PeventDataSource.can_read(path):\n return PeventDataSource(path)\n else:\n raise ValueError(\"unknown type of file, can't choose data source\")\n else:\n return SpartaDataSource(path)\n\n @staticmethod\n @cache.cache('shpHtmlTable', expire = 3600)\n @logtime(logger)\n def getShpTableHtmlGenerator(processorId):\n\n procIdObj, path = bpEndpoint.lookupProcessorId(processorId)\n\n branch_hm_data = bpEndpoint.getDataSource(path)\n\n bptta = BranchTrainingTraceAdapter(branch_hm_data)\n\n bptg = BranchTrainingListHtmlGenerator(bptta, **json.loads(procIdObj.kwargs))\n\n return bptg\n\n @staticmethod\n @cache.cache('shpHtmlTable', expire = 3600)\n @logtime(logger)\n def getShpBranchProfileHtmlGenerator(processorId):\n\n procIdObj, path = bpEndpoint.lookupProcessorId(processorId)\n\n branch_hm_data = bpEndpoint.getDataSource(path)\n\n bptta = BranchTrainingTraceAdapter(branch_hm_data)\n\n bptg = BranchTrainingProfileHtmlGenerator(bptta, **json.loads(procIdObj.kwargs))\n\n return bptg\n\n @staticmethod\n @cache.cache('shpLinePlot', expire = 3600)\n @logtime(logger)\n def getShpLinePlotGenerator(processorId):\n\n logger.info(f\"getShpLinePlotGenerator for pid={processorId}\")\n procIdObj, path = bpEndpoint.lookupProcessorId(processorId)\n\n # load source data\n branchHeatMapDataSource = bpEndpoint.getDataSource(path)\n logger.debug(f'List of stats are: {branchHeatMapDataSource.stats}')\n\n # constructor adapter\n branchTrainingTraceAdapter = BranchTrainingTraceAdapter(branchHeatMapDataSource)\n\n # construct generator\n linePlotGenerator = BranchTrainingLinePlotGenerator(branchTrainingTraceAdapter, **json.loads(procIdObj.kwargs))\n\n return linePlotGenerator\n\n @staticmethod\n @cache.cache('simDbLinePlot', expire = 3600)\n @logtime(logger)\n def getSimDbLinePlotGenerator(processorId):\n\n procIdObj, path = bpEndpoint.lookupProcessorId(processorId)\n\n # load source data\n simDbDataSource = bpEndpoint.getDataSource(path)\n logger.debug(f'List of stats are: {simDbDataSource.stats}')\n\n # constructor adapter\n spartaStatsAdapter = SpartaStatisticsAdapter(simDbDataSource)\n\n # construct generator\n linePlotGenerator = GeneralTraceLinePlotGenerator(spartaStatsAdapter, **json.loads(procIdObj.kwargs))\n\n return linePlotGenerator\n\n @staticmethod\n @cache.cache('peventTraceGenerator', expire = 3600)\n @logtime(logger)\n def getPeventTraceGenerator(processorId):\n\n procIdObj, path = bpEndpoint.lookupProcessorId(processorId)\n\n # load source data\n peventDataSource = bpEndpoint.getDataSource(path)\n\n # construct adapter\n peventTraceAdapter = PeventTraceAdapter(peventDataSource)\n\n # construct generator\n peventTraceGenerator = PeventTraceGenerator(peventTraceAdapter, **json.loads(procIdObj.kwargs))\n\n return peventTraceGenerator\n\n @staticmethod\n @cache.cache('simDbStatsAdapter', expire = 3600)\n @logtime(logger)\n def getSimDbStatsGenerator(processorId):\n\n procIdObj, path = bpEndpoint.lookupProcessorId(processorId)\n\n # load source data\n simDbDataSource = bpEndpoint.getDataSource(path)\n logger.debug(f'List of stats are: {simDbDataSource.stats}')\n\n # constructor adapter\n spartaStatsAdapter = SpartaStatisticsAdapter(simDbDataSource)\n\n # construct generator\n generator = SpartaStatsGenerator(spartaStatsAdapter, **json.loads(procIdObj.kwargs))\n\n return generator\n\n @staticmethod\n @logtime(logger)\n @cache.cache('shpHeatMap', expire = 3600)\n def getShpHeatmapGenerator(processorId):\n\n procIdObj, path = bpEndpoint.lookupProcessorId(processorId)\n\n # load source data\n branchHeatMapDataSource = bpEndpoint.getDataSource(path)\n\n # constructor adapter\n branchTrainingHeatMapAdapter = BranchTrainingHeatMapAdapter(branchHeatMapDataSource)\n\n heatMapGenerator = BranchTrainingHeatMapGenerator(branchTrainingHeatMapAdapter, **json.loads(procIdObj.kwargs))\n\n return heatMapGenerator\n\n", "from matplotlib import pyplot as plt\nfrom os import path\nimport numpy as np\nimport time\n\nimport sys\nsys.path.append(path.split(path.dirname(__file__))[0])\n\nfrom plato.backend.units import Units\n\nfrom plato.backend.datasources.branch_training_trace.datasource import BranchTrainingDatasource\nfrom plato.backend.processors.branch_training_heatmap.adapter import BranchTrainingHeatMapAdapter\nfrom plato.backend.processors.branch_training_heatmap.generator import BranchTrainingHeatMapGenerator\n\n\nif len(sys.argv) == 1:\n filename = path.join(path.dirname(__file__),'test-branch-training-trace.hdf5')\nelse:\n filename = sys.argv[1]\n\n\ndef plot_heatmap(hm):\n plt.figure()\n plt.imshow(hm, cmap='hot', interpolation='nearest', aspect='auto')\n\n# Load source data\nbranch_hm_data = BranchTrainingDatasource(filename)\nprint('\\nstats', branch_hm_data.stats)\nbphma = BranchTrainingHeatMapAdapter(branch_hm_data)\nprint('\\nnum events', bphma.num_events)\n\nbin_size = 200000\n\n\nbphmg = BranchTrainingHeatMapGenerator(bphma, ['thrash_1', 'd_weight'], bin_size)\n\nhm, table_means, row_means = bphmg.generate_2d_heatmap_with_profiles(0, len(branch_hm_data.ddf_branch_training_events)-1, Units.BRANCH_TRAINING_INDEX, 'd_weight')\n\nprint('max {} at {}'.format(hm.max(), hm.argmax()))\nprint('min {} at {}'.format(hm.min(), hm.argmin()))\n\nhm, table_means, row_means = bphmg.generate_2d_heatmap_with_profiles(0, len(branch_hm_data.ddf_branch_training_events)-1, Units.BRANCH_TRAINING_INDEX, 'd_weight', allow_bins=False)\n\nprint('max {} at {}'.format(hm.max(), hm.argmax()))\nprint('min {} at {}'.format(hm.min(), hm.argmin()))\n\nplot_heatmap(hm)\nplt.title('d_weight')\n\n# Show all the images (blocking)\nsys.stdout.flush()\n\nimport os\nplt.show(block=bool(int(os.environ.get('BLOCKING_SHOW', 1))))" ]
[ [ "numpy.abs" ], [ "numpy.nanmax", "numpy.nanmin" ], [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.title", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
frankovici/DemARK
[ "177c09bd387160d06f979c417671b3de18746846", "177c09bd387160d06f979c417671b3de18746846", "177c09bd387160d06f979c417671b3de18746846" ]
[ "notebooks/LifecycleModelExample.py", "notebooks/KinkedRconsumerType.py", "notebooks/PerfForesightCRRA-Approximation.py" ]
[ "# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: collapsed,code_folding\n# formats: ipynb,py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.2'\n# jupytext_version: 1.2.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown]\n#\n# # A Life Cycle Model: Data and Theory\n#\n# National registry data on income and wealth from Scandinavian countries (esp. Norway) have recently become available (with a lot of security) to some (lucky!) researchers. These data offer a uniquely powerful tool for testing (and improving) our models of consumption and saving behavior over the life cycle.\n#\n# This notebook is an example of how to construct a life cycle model with the HARK toolkit that makes predictions that can be compared to the raw data statistics that now are becoming available.\n#\n# For example, existing papers have tabulated information about the **growth rate** of assets at different ages over the life cycle. \n#\n# The default parameters of the HARK life cycle model have not been optmized to match features of the Norwegian data; a first step in a real \"structural\" estimation would be to use Norwegian calibrate the inputs to the model (like the profile of income, and the magnitude of income shocks, over the life cycle), and then to find the values of parameters like the time preference rate that allow the model to fit the data best. (See [SolvingMicroDSOPs](https://econ.jhu.edu/people/ccarroll/SolvingMicroDSOPs) for how this can be done, and search for the corresponding HARK content using [our documentation](https://hark.readthedocs.io)).\n\n# %% {\"code_folding\": []}\n# Initial imports and notebook setup, click arrow to show\n\nimport HARK.ConsumptionSaving.ConsIndShockModel as cShksModl # The consumption-saving micro model\nimport HARK.SolvingMicroDSOPs.Calibration.EstimationParameters as Params # Parameters for the consumer type and the estimation\nfrom HARK.utilities import plotFuncsDer, plotFuncs # Some tools\nimport pandas as pd \n\nimport numpy as np\n\n\n# %% {\"code_folding\": [0]}\n# Set up default values for CRRA, DiscFac, and simulation variables in the dictionary \nParams.init_consumer_objects[\"CRRA\"]= 2.00 # Default coefficient of relative risk aversion (rho)\nParams.init_consumer_objects[\"DiscFac\"]= 0.97 # Default intertemporal discount factor (beta)\nParams.init_consumer_objects[\"PermGroFacAgg\"]= 1.0 # Aggregate permanent income growth factor \nParams.init_consumer_objects[\"aNrmInitMean\"]= -10.0 # Mean of log initial assets \nParams.init_consumer_objects[\"aNrmInitStd\"]= 1.0 # Standard deviation of log initial assets\nParams.init_consumer_objects[\"pLvlInitMean\"]= 0.0 # Mean of log initial permanent income \nParams.init_consumer_objects[\"pLvlInitStd\"]= 0.0 # Standard deviation of log initial permanent income\n\n\n# %%\n# Make an instance of a lifecycle consumer to be used for estimation\nLifeCyclePop = cShksModl.IndShockConsumerType(**Params.init_consumer_objects)\n\n\n# %% {\"code_folding\": [0]}\n# Solve and simulate the model (ignore the \"warning\" message)\nLifeCyclePop.solve() # Obtain consumption rules by age \nLifeCyclePop.unpackcFunc() # Expose the consumption rules\n\n# Which variables do we want to track\nLifeCyclePop.track_vars = ['aNrmNow','pLvlNow','mNrmNow','cNrmNow','TranShkNow']\n\nLifeCyclePop.T_sim = 120 # Nobody lives to be older than 145 years (=25+120)\nLifeCyclePop.initializeSim() # Construct the age-25 distribution of income and assets\nLifeCyclePop.simulate() # Simulate a population behaving according to this model\n\n\n# %% {\"code_folding\": [0]}\n# Plot the consumption functions during working life\n\nprint('Consumption as a function of market resources while working:')\nmMin = min([LifeCyclePop.solution[t].mNrmMin for t in range(LifeCyclePop.T_cycle)])\nplotFuncs(LifeCyclePop.cFunc[:LifeCyclePop.T_retire],mMin,5)\n\n\n# %% {\"code_folding\": [0]}\n# Define the saving rate function\ndef savRteFunc(SomeType, m, t):\n \"\"\"\n Parameters:\n ----------\n SomeType: \n Agent type that has been solved and simulated.\n m:\n normalized market resources of agent\n t:\n age of agent (from starting in the workforce)\n \n \n Returns:\n --------\n savRte: float\n \n \"\"\"\n inc = (SomeType.Rfree -1.)*(m-1.)+1. # Normalized by permanent labor income\n cns = SomeType.solution[t].cFunc(m) # Consumption (normalized)\n sav = inc - cns # Flow of saving this period\n savRte = sav / inc # Saving Rate\n return savRte \n\n\n# %% {\"code_folding\": []}\n# Create a giant matrix gathering useful data:\n# 't_now', 'aNrmNow_hist', 'cNrmNow_hist', employment-status in date t and date t-1,\n# aLvlGro_hist, Saving rate\n\nw, h = 1, LifeCyclePop.T_cycle\ngiant_list = [[0 for x in range(w)] for y in range(h)]\nsavRte_list = []\n\nimport warnings\nwarnings.filterwarnings(\"ignore\") # Suppress some disturbing but harmless warnings\n\nfor t in range(1,LifeCyclePop.T_cycle+1):\n #aLvlGro_hist[0] = 0 # set the first growth rate to 0, since there is no data for period 0\n aLvlGroNow = np.log((LifeCyclePop.aNrmNow_hist[t] *LifeCyclePop.pLvlNow_hist[t])/ \\\n LifeCyclePop.aNrmNow_hist[t-1] *LifeCyclePop.pLvlNow_hist[t-1]) # (10000,)\n\n # Call the saving rate function defined above \n savRte = savRteFunc(LifeCyclePop, LifeCyclePop.mNrmNow_hist[t] , t)\n \n savRte_list.append(savRte) # Add this period's saving rate to the list \n\n # Create elements of matrix list\n matrix_list = [0 for number in range(7)]\n matrix_list[0] = t\n matrix_list[1] = LifeCyclePop.aNrmNow_hist[t]\n matrix_list[2] = LifeCyclePop.cNrmNow_hist[t]\n matrix_list[3] = LifeCyclePop.TranShkNow_hist[t]\n matrix_list[4] = LifeCyclePop.TranShkNow_hist[t-1]\n matrix_list[5] = aLvlGroNow\n matrix_list[6] = savRte\n \n giant_list[t-1] = matrix_list\n\n# %% {\"code_folding\": [0]}\n# Construct the level of assets A from a*p where a is the ratio to permanent income p\n# Remember 41 is \"years after entering workforce\" (=age 25); 66 is the year right after retirement\nLifeCyclePop.aLvlNow_hist = LifeCyclePop.aNrmNow_hist*LifeCyclePop.pLvlNow_hist\naGro41=LifeCyclePop.aLvlNow_hist[41]/LifeCyclePop.aLvlNow_hist[40]\naGro41NoU=aGro41[aGro41[:]>0.2] # Throw out extreme outliers; don't want growth rates relative to 0 income!\n\n\n# %% {\"code_folding\": [0]}\n# Plot the (truncated) distribution of growth rates of wealth between age 65 and 66 (=25 + 41)\nfrom matplotlib import pyplot as plt\nn, bins, patches = plt.hist(aGro41NoU,50,density=True)\n\n\n# %%\n# put your solution here\n\n# %%\n# put your answer here\n\n# %%\n# put your answer here\n\n# %%\n# put your solution here\n\n# %%\n# put your solution here\n\n# %% [markdown]\n# # Saving Rates and Lifetime Income Growth\n#\n# We are interested in how income growth over the lifetime of the agent affects their saving rate and asset ratio $a=A/P$.\n#\n\n# %%\ncumulative_income_first_half = np.sum(LifeCyclePop.pLvlNow_hist[0:20,:]*LifeCyclePop.TranShkNow_hist[0:20,:],0)\ncumulative_income_second_half = np.sum(LifeCyclePop.pLvlNow_hist[20:40,:]*LifeCyclePop.TranShkNow_hist[20:40,:],0)\nlifetime_growth = cumulative_income_second_half/cumulative_income_first_half\n\nt=39\nvigntiles = qcut(lifetime_growth,20,labels=False)\nsavRte = savRteFunc(LifeCyclePop, LifeCyclePop.mNrmNow_hist[t] , t)\nsavRtgueseByVigtile = np.zeros(20)\nassetsByVigtile = np.zeros(20)\nassetsNrmByVigtile = np.zeros(20)\nfor i in range(20):\n savRteByVigtile[i] = np.mean(savRte[vigntiles==i])\n assetsByVigtile[i] = np.mean(LifeCyclePop.aLvlNow_hist[t][vigntiles==i])\n assetsNrmByVigtile[i] = np.mean(LifeCyclePop.aNrmNow_hist[t][vigntiles==i])\nplt.plot(np.array(range(20)), savRteByVigtile)\nplt.title(\"Saving Rate at age 65, by Vigntile of Lifetime Income Growth\")\nplt.xlabel(\"Vigntile of Lifetime Income Growth\")\nplt.ylabel(\"Savings Rate\")\n\nplt.figure()\nplt.plot(np.array(range(20)), assetsByVigtile)\nplt.title(\"Assets at age 65, by Vigntile of Lifetime Income Growth\")\nplt.xlabel(\"Vigntile of Lifetime Income Growth\")\nplt.ylabel(\"Assets\")\n\nplt.figure()\nplt.plot(np.array(range(20)), assetsNrmByVigtile)\nplt.title(\"Normalized Assets at age 65, by Vigntile of Lifetime Income Growth\")\nplt.xlabel(\"Vigntile of Lifetime Income Growth\")\nplt.ylabel(\"Normalized Assets\")\n", "# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: collapsed,code_folding\n# formats: ipynb,py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.2'\n# jupytext_version: 1.2.3\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown]\n# # KinkedRconsumerType: Consumption-saving model with idiosyncratic income shocks and different interest rates on borrowing and saving\n\n# %% {\"code_folding\": [0]}\n# Initial imports and notebook setup, click arrow to show\nfrom HARK.ConsumptionSaving.ConsIndShockModel import KinkedRconsumerType\nfrom HARK.utilities import plotFuncsDer, plotFuncs\nimport matplotlib.pyplot as plt\nimport numpy as np\nmystr = lambda number : \"{:.4f}\".format(number)\n\n# %% [markdown]\n# The module $\\texttt{HARK.ConsumptionSaving.ConsIndShockModel}$ concerns consumption-saving models with idiosyncratic shocks to (non-capital) income. All of the models assume CRRA utility with geometric discounting, no bequest motive, and income shocks are fully transitory or fully permanent.\n#\n# $\\texttt{ConsIndShockModel}$ currently includes three models:\n# 1. A very basic \"perfect foresight\" model with no uncertainty.\n# 2. A model with risk over transitory and permanent income shocks.\n# 3. The model described in (2), with an interest rate for debt that differs from the interest rate for savings.\n#\n# This notebook provides documentation for the third of these models.\n# $\\newcommand{\\CRRA}{\\rho}$\n# $\\newcommand{\\DiePrb}{\\mathsf{D}}$\n# $\\newcommand{\\PermGroFac}{\\Gamma}$\n# $\\newcommand{\\Rfree}{\\mathsf{R}}$\n# $\\newcommand{\\DiscFac}{\\beta}$\n\n# %% [markdown]\n# ## Statement of \"kinked R\" model\n#\n# Consider a small extension to the model faced by $\\texttt{IndShockConsumerType}$s: that the interest rate on borrowing $a_t < 0$ is greater than the interest rate on saving $a_t > 0$. Consumers who face this kind of problem are represented by the $\\texttt{KinkedRconsumerType}$ class.\n#\n# For a full theoretical treatment, this model analyzed in [A Theory of the Consumption Function, With\n# and Without Liquidity Constraints](http://www.econ2.jhu.edu/people/ccarroll/ATheoryv3JEP.pdf)\n# and its [expanded edition](http://www.econ2.jhu.edu/people/ccarroll/ATheoryv3NBER.pdf).\n#\n# Continuing to work with *normalized* variables (e.g. $m_t$ represents the level of market resources divided by permanent income), the \"kinked R\" model can be stated as:\n#\n# \\begin{eqnarray*}\n# v_t(m_t) &=& \\max_{c_t} {~} U(c_t) + \\DiscFac (1-\\DiePrb_{t+1}) \\mathbb{E}_{t} \\left[ (\\PermGroFac_{t+1}\\psi_{t+1})^{1-\\CRRA} v_{t+1}(m_{t+1}) \\right], \\\\\n# a_t &=& m_t - c_t, \\\\\n# a_t &\\geq& \\underline{a}, \\\\\n# m_{t+1} &=& \\Rfree_t/(\\PermGroFac_{t+1} \\psi_{t+1}) a_t + \\theta_{t+1}, \\\\\n# \\Rfree_t &=& \\cases{\\Rfree_{boro} \\texttt{ if } a_t < 0 \\\\\n# \\Rfree_{save} \\texttt{ if } a_t \\geq 0},\\\\\n# \\Rfree_{boro} &>& \\Rfree_{save}, \\\\\n# (\\psi_{t+1},\\theta_{t+1}) &\\sim& F_{t+1}, \\\\\n# \\mathbb{E}[\\psi]=\\mathbb{E}[\\theta] &=& 1.\n# \\end{eqnarray*}\n\n# %% [markdown]\n# ## Solving the \"kinked R\" model\n#\n# The solution method for the \"kinked R\" model is nearly identical to that of the $\\texttt{IndShockConsumerType}$ on which it is based, using the endogenous grid method; see the notebook for that model for more information. The only significant difference is that the interest factor varies by $a_t$ across the exogenously chosen grid of end-of-period assets, with a discontinuity in $\\Rfree$ at $a_t=0$.\n#\n# To correctly handle this, the $\\texttt{solveConsKinkedR}$ function inserts *two* instances of $a_t=0$ into the grid of $a_t$ values: the first corresponding to $\\Rfree_{boro}$ ($a_t = -0$) and the other corresponding to $\\Rfree_{save}$ ($a_t = +0$). The two consumption levels (and corresponding endogenous $m_t$ gridpoints) represent points at which the agent's first order condition is satisfied at *exactly* $a_t=0$ at the two different interest factors. In between these two points, the first order condition *does not hold with equality*: the consumer will end the period with exactly $a_t=0$, consuming $c_t=m_t$, but his marginal utility of consumption exceeds the marginal value of saving and is less than the marginal value of borrowing. This generates a consumption function with *two* kinks: two concave portions (for borrowing and saving) with a linear segment of slope 1 in between.\n\n# %% [markdown]\n# ## Example parameter values to construct an instance of KinkedRconsumerType\n#\n# The parameters required to create an instance of $\\texttt{KinkedRconsumerType}$ are nearly identical to those for $\\texttt{IndShockConsumerType}$. The only difference is that the parameter $\\texttt{Rfree}$ is replaced with $\\texttt{Rboro}$ and $\\texttt{Rsave}$.\n#\n# While the parameter $\\texttt{CubicBool}$ is required to create a valid $\\texttt{KinkedRconsumerType}$ instance, it must be set to $\\texttt{False}$; cubic spline interpolation has not yet been implemented for this model. In the future, this restriction will be lifted.\n#\n# | Parameter | Description | Code | Example value | Time-varying? |\n# | :---: | --- | --- | --- | --- |\n# | $\\DiscFac$ |Intertemporal discount factor | $\\texttt{DiscFac}$ | $0.96$ | |\n# | $\\CRRA $ |Coefficient of relative risk aversion | $\\texttt{CRRA}$ | $2.0$ | |\n# | $\\Rfree_{boro}$ | Risk free interest factor for borrowing | $\\texttt{Rboro}$ | $1.20$ | |\n# | $\\Rfree_{save}$ | Risk free interest factor for saving | $\\texttt{Rsave}$ | $1.01$ | |\n# | $1 - \\DiePrb_{t+1}$ |Survival probability | $\\texttt{LivPrb}$ | $[0.98]$ | $\\surd$ |\n# |$\\PermGroFac_{t+1}$|Permanent income growth factor|$\\texttt{PermGroFac}$| $[1.01]$ | $\\surd$ |\n# | $\\sigma_\\psi $ | Standard deviation of log permanent income shocks | $\\texttt{PermShkStd}$ | $[0.1]$ |$\\surd$ |\n# | $N_\\psi $ | Number of discrete permanent income shocks | $\\texttt{PermShkCount}$ | $7$ | |\n# | $\\sigma_\\theta $ | Standard deviation of log transitory income shocks | $\\texttt{TranShkStd}$ | $[0.2]$ | $\\surd$ |\n# | $N_\\theta $ | Number of discrete transitory income shocks | $\\texttt{TranShkCount}$ | $7$ | |\n# | $\\mho$ | Probability of being unemployed and getting $\\theta=\\underline{\\theta}$ | $\\texttt{UnempPrb}$ | $0.05$ | |\n# | $\\underline{\\theta} $ | Transitory shock when unemployed | $\\texttt{IncUnemp}$ | $0.3$ | |\n# | $\\mho^{Ret}$ | Probability of being \"unemployed\" when retired | $\\texttt{UnempPrb}$ | $0.0005$ | |\n# | $\\underline{\\theta}^{Ret} $ | Transitory shock when \"unemployed\" and retired | $\\texttt{IncUnemp}$ | $0.0$ | |\n# | $(none)$ | Period of the lifecycle model when retirement begins | $\\texttt{T_retire}$ | $0$ | |\n# | $(none)$ | Minimum value in assets-above-minimum grid | $\\texttt{aXtraMin}$ | $0.001$ | |\n# | $(none)$ | Maximum value in assets-above-minimum grid | $\\texttt{aXtraMax}$ | $20.0$ | |\n# | $(none)$ | Number of points in base assets-above-minimum grid | $\\texttt{aXtraCount}$ | $48$ | |\n# | $(none)$ | Exponential nesting factor for base assets-above-minimum grid | $\\texttt{aXtraNestFac}$ | $3$ | |\n# | $(none)$ | Additional values to add to assets-above-minimum grid | $\\texttt{aXtraExtra}$ | $None$ | |\n# | $\\underline{a} $ | Artificial borrowing constraint (normalized) | $\\texttt{BoroCnstArt}$ | $None$ | |\n# | $(none) $ |Indicator for whether $\\texttt{vFunc}$ should be computed | $\\texttt{vFuncBool}$ | $True$ | |\n# | $(none)$ |Indicator for whether $\\texttt{cFunc}$ should use cubic splines | $\\texttt{CubicBool}$ | $False$ | |\n# |$T$| Number of periods in this type's \"cycle\" |$\\texttt{T_cycle}$| $1$ | |\n# |(none)| Number of times the \"cycle\" occurs |$\\texttt{cycles}$| $0$ | |\n#\n# These example parameters are almostidentical to those used for $\\texttt{IndShockExample}$ in the prior notebook, except that the interest rate on borrowing is 20% (like a credit card), and the interest rate on saving is 1%. Moreover, the artificial borrowing constraint has been set to $\\texttt{None}$. The cell below defines a parameter dictionary with these example values.\n\n# %% {\"code_folding\": [0]}\nKinkedRdict={ # Click the arrow to expand this parameter dictionary\n # Parameters shared with the perfect foresight model\n \"CRRA\" : 2.0, # Coefficient of relative risk aversion\n \"DiscFac\": 0.96, # Intertemporal discount factor\n \"LivPrb\" : [0.98], # Survival probability\n \"PermGroFac\" :[1.01], # Permanent income growth factor\n \n # New parameters unique to the \"kinked R\" model\n \"Rboro\" : 1.20, # Interest factor on borrowing (a < 0)\n \"Rsave\" : 1.01, # Interest factor on saving (a > 0)\n \n # Parameters that specify the income distribution over the lifecycle\n \"PermShkStd\" : [0.1], # Standard deviation of log permanent shocks to income\n \"PermShkCount\" : 7, # Number of points in discrete approximation to permanent income shocks\n \"TranShkStd\" : [0.2], # Standard deviation of log transitory shocks to income\n \"TranShkCount\" : 7, # Number of points in discrete approximation to transitory income shocks\n \"UnempPrb\" : 0.05, # Probability of unemployment while working\n \"IncUnemp\" : 0.3, # Unemployment benefits replacement rate\n \"UnempPrbRet\" : 0.0005, # Probability of \"unemployment\" while retired\n \"IncUnempRet\" : 0.0, # \"Unemployment\" benefits when retired\n \"T_retire\" : 0, # Period of retirement (0 --> no retirement)\n \"tax_rate\" : 0.0, # Flat income tax rate (legacy parameter, will be removed in future)\n \n # Parameters for constructing the \"assets above minimum\" grid\n \"aXtraMin\" : 0.001, # Minimum end-of-period \"assets above minimum\" value\n \"aXtraMax\" : 20, # Maximum end-of-period \"assets above minimum\" value\n \"aXtraCount\" : 48, # Number of points in the base grid of \"assets above minimum\"\n \"aXtraNestFac\" : 3, # Exponential nesting factor when constructing \"assets above minimum\" grid\n \"aXtraExtra\" : [None], # Additional values to add to aXtraGrid\n \n # A few other paramaters\n \"BoroCnstArt\" : None, # Artificial borrowing constraint; imposed minimum level of end-of period assets\n \"vFuncBool\" : True, # Whether to calculate the value function during solution \n \"CubicBool\" : False, # Preference shocks currently only compatible with linear cFunc\n \"T_cycle\" : 1, # Number of periods in the cycle for this agent type \n \n # Parameters only used in simulation\n \"AgentCount\" : 10000, # Number of agents of this type\n \"T_sim\" : 500, # Number of periods to simulate\n \"aNrmInitMean\" : -6.0, # Mean of log initial assets\n \"aNrmInitStd\" : 1.0, # Standard deviation of log initial assets\n \"pLvlInitMean\" : 0.0, # Mean of log initial permanent income\n \"pLvlInitStd\" : 0.0, # Standard deviation of log initial permanent income\n \"PermGroFacAgg\" : 1.0, # Aggregate permanent income growth factor\n \"T_age\" : None, # Age after which simulated agents are automatically killed\n}\n\n# %% [markdown]\n# ## Solving and examining the solution of the \"kinked R\" model\n#\n# The cell below creates an infinite horizon instance of $\\texttt{KinkedRconsumerType}$ and solves its model by calling its $\\texttt{solve}$ method.\n\n# %%\nKinkyExample = KinkedRconsumerType(**KinkedRdict)\nKinkyExample.cycles = 0 # Make the example infinite horizon\nKinkyExample.solve()\n\n# %% [markdown]\n# An element of a $\\texttt{KinkedRconsumerType}$'s solution will have all the same attributes as that of a $\\texttt{IndShockConsumerType}$; see that notebook for details.\n#\n# We can plot the consumption function of our \"kinked R\" example, as well as the MPC:\n\n# %%\nprint('Kinked R consumption function:')\nplotFuncs(KinkyExample.solution[0].cFunc,KinkyExample.solution[0].mNrmMin,5)\n\nprint('Kinked R marginal propensity to consume:')\nplotFuncsDer(KinkyExample.solution[0].cFunc,KinkyExample.solution[0].mNrmMin,5)\n\n# %% [markdown]\n# ## Simulating the \"kinked R\" model\n#\n# In order to generate simulated data, an instance of $\\texttt{KinkedRconsumerType}$ needs to know how many agents there are that share these particular parameters (and are thus *ex ante* homogeneous), the distribution of states for newly \"born\" agents, and how many periods to simulated. These simulation parameters are described in the table below, along with example values.\n#\n# | Description | Code | Example value |\n# | :---: | --- | --- |\n# | Number of consumers of this type | $\\texttt{AgentCount}$ | $10000$ |\n# | Number of periods to simulate | $\\texttt{T_sim}$ | $500$ |\n# | Mean of initial log (normalized) assets | $\\texttt{aNrmInitMean}$ | $-6.0$ |\n# | Stdev of initial log (normalized) assets | $\\texttt{aNrmInitStd}$ | $1.0$ |\n# | Mean of initial log permanent income | $\\texttt{pLvlInitMean}$ | $0.0$ |\n# | Stdev of initial log permanent income | $\\texttt{pLvlInitStd}$ | $0.0$ |\n# | Aggregrate productivity growth factor | $\\texttt{PermGroFacAgg}$ | $1.0$ |\n# | Age after which consumers are automatically killed | $\\texttt{T_age}$ | $None$ |\n#\n# Here, we will simulate 10,000 consumers for 500 periods. All newly born agents will start with permanent income of exactly $P_t = 1.0 = \\exp(\\texttt{pLvlInitMean})$, as $\\texttt{pLvlInitStd}$ has been set to zero; they will have essentially zero assets at birth, as $\\texttt{aNrmInitMean}$ is $-6.0$; assets will be less than $1\\%$ of permanent income at birth.\n#\n# These example parameter values were already passed as part of the parameter dictionary that we used to create $\\texttt{KinkyExample}$, so it is ready to simulate. We need to set the $\\texttt{track_vars}$ attribute to indicate the variables for which we want to record a *history*.\n\n# %%\nKinkyExample.track_vars = ['mNrmNow','cNrmNow','pLvlNow']\nKinkyExample.initializeSim()\nKinkyExample.simulate()\n\n# %% [markdown]\n# We can plot the average (normalized) market resources in each simulated period:\n\n# %%\nplt.plot(np.mean(KinkyExample.mNrmNow_hist,axis=1))\nplt.xlabel('Time')\nplt.ylabel('Mean market resources')\nplt.show()\n\n# %% [markdown]\n# Now let's plot the distribution of (normalized) assets $a_t$ for the current population, after simulating for $500$ periods; this should be fairly close to the long run distribution:\n\n# %%\nplt.plot(np.sort(KinkyExample.aNrmNow),np.linspace(0.,1.,KinkyExample.AgentCount))\nplt.xlabel('End-of-period assets')\nplt.ylabel('Cumulative distribution')\nplt.ylim(-0.01,1.01)\nplt.show()\n\n# %% [markdown]\n# We can see there's a significant point mass of consumers with *exactly* $a_t=0$; these are consumers who do not find it worthwhile to give up a bit of consumption to begin saving (because $\\Rfree_{save}$ is too low), and also are not willing to finance additional consumption by borrowing (because $\\Rfree_{boro}$ is too high).\n#\n# The smaller point masses in this distribution are due to $\\texttt{HARK}$ drawing simulated income shocks from the discretized distribution, rather than the \"true\" lognormal distributions of shocks. For consumers who ended $t-1$ with $a_{t-1}=0$ in assets, there are only 8 values the transitory shock $\\theta_{t}$ can take on, and thus only 8 values of $m_t$ thus $a_t$ they can achieve; the value of $\\psi_t$ is immaterial to $m_t$ when $a_{t-1}=0$. You can verify this by changing $\\texttt{TranShkCount}$ to some higher value, like 25, in the dictionary above, then running the subsequent cells; the smaller point masses will not be visible to the naked eye.\n", "# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.2'\n# jupytext_version: 1.2.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown]\n# # Perfect Foresight CRRA Model - Approximation\n\n# %% {\"code_folding\": []}\n# Initial notebook set up\n\n# %matplotlib inline\nimport matplotlib.pyplot as plt\n# The first step is to be able to bring things in from different directories\nimport sys \nimport os\n\nsys.path.insert(0, os.path.abspath('../lib'))\n\nimport numpy as np\nimport HARK \nfrom time import clock\nfrom copy import deepcopy\nmystr = lambda number : \"{:.4f}\".format(number)\nfrom HARK.utilities import plotFuncs\n\n# These last two will make our charts look nice\nplt.style.use('seaborn-darkgrid')\npalette = plt.get_cmap('Dark2')\n\n# %% [markdown]\n# [PerfectForesightCRRA](http://www.econ2.jhu.edu/people/ccarroll/public/lecturenotes/Consumption/PerfForesightCRRA) derives a number of results as approximations; for instance, the exact formula for the consumption function is derived as $$c_t = \\left(\\frac{R - (R\\beta)^{1/\\rho}}{R}\\right)o_t$$\n# and approximated by $$c_t \\approx (r-\\rho^{-1}(r-\\theta))o_t$$.\n#\n# Your task is to make a series of plots that show how the quality of the approximation deteriorates as you change various model parameters. The notebook aims to make this easier by showing that under the baseline parameter values, the percentage amount of the error is pretty much constant across different values of market resources, so you can assume that is generically true.\n#\n# To get you started, we show how to conduct the exercise under particularly simple parameterization (the Deaton/Friedman model where $R = \\frac{1}{\\beta}$, in which the only relevant parameter is the interest rate).\n#\n# Your specific assignment is:\n#\n# 1. Starting with the default parameterization of the model, show how the approximation quality changes with values of other parameters\n# 1. Explain, mathematically, why you get the patterns you do for how the solutions deteriorate as you change the parameter values\n#\n# Hints: \n#\n# 1. [MathFactsList](http://www.econ2.jhu.edu/people/ccarroll/public/lecturenotes/MathFacts/MathFactsList.pdf) describes the conditions under which the approximations will be good; you want to find conditions under which the approximations get bad\n# 2. An interesting question is the extent to which the size of approximation errors is related to the degree of impatience according to alternative metrics\n\n# %%\n# Set up a HARK Perfect Foresight Consumer called PFagent\n\nfrom HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType # Import the consumer type\n\n# Now we need to give our consumer parameter values that allow us to solve the consumer's problem\n\n# We begin by importing a module that can be invoked to cough up default parameter values\nimport HARK.ConsumptionSaving.ConsumerParameters as Params\n\n# Invoke it to create a dictionary called Paramod (Params that we will modify)\nParamod = deepcopy(Params.init_perfect_foresight) # deepcopy prevents later overwriting\n\n# Extract the parameters from the dictionary to make them easy to reference\nCRRA = Paramod['CRRA'] # Coefficient of relative risk aversion\nRfree = Paramod['Rfree'] # Interest factor on assets\nDiscFac = Paramod['DiscFac'] # Intertemporal discount factor\nPermGroFac = Paramod['PermGroFac'] # Permanent income growth factor\nLivPrb = Paramod['LivPrb'] = [1.0] # Survival probability of 100 percent\ncycles = Paramod['cycles'] = 0 # This says that it is an infinite horizon model\n\n# %%\n# Now let's pass our dictionary to our consumer class to create an instance \nPFagent = PerfForesightConsumerType(**Paramod) # Any parameters we did not modify get their default values\n\n# Solve the agent's problem\nPFagent.solve()\n\n# %%\n# Plot the consumption function approximation versus the \"true\" consumption function\n\n# Set out some range of market resources that we want to plot consumption for\nmMin = 0 \nmMax = 10\nnumPoints = 100\nm_range = np.linspace(mMin, mMax, numPoints) # This creates an array of points in the given range\n\nwealthHmn = PFagent.solution[0].hNrm # normalized human wealth is constructed when we .solve()\nwealthMkt = m_range # bank balances plus current income\nwealthTot = wealthHmn+wealthMkt # Total wealth is the sum of human and market \n\n# Feed our range of market resources into our consumption function in order to get consumption at each point\n# (Remember, after doing .solve(), the consumption function is stored as PFagent.solution[0].cFunc)\ncHARK = PFagent.solution[0].cFunc(m_range) # Because the input m_range is an array, the output cHARK is too\ncMax = cHARK[-1]*1.2 # The last point will be the largest; add 20 percent for visual appeal\n\n# Use matplotlib package (imported in first cell) to plot the consumption function\nplt.figure(figsize=(9,6)) # set the figure size\nplt.plot(m_range, cHARK, 'b', label='Consumption Function from HARK') # m on the x axis vs c on the y axis\n# 'b' is for blue\nplt.xlabel('Market resources m') # x axis label\nplt.ylabel('Consumption c') # y axis label\nplt.ylim(0,cMax)\n\n# The plot is named plt and it hangs around like a variable \n# but is not displayed until you do a plt.show()\n\n# Construct the approximate consumption function\n# Also, recall that in the \"true\" consumption function what matters is total wealth, \n# not just market resources so we need to add in human wealth\n\n# Use the values of R, beta, and rho that we used above to construct rates \nrfree=Rfree-1\ndiscRte=(1/DiscFac)-1 # See handout for why this is approximately the time preference rate\ncApprox = wealthTot*(rfree - (1/CRRA)*(rfree-discRte)) \nplt.plot(m_range, cApprox, 'k', label='c function approximated') # Add true consumption function line\nplt.legend() # show the legend\n\nplt.show() # show the plot\n\n# %% [markdown]\n# The size of the error looks pretty stable, which we can show by calculating it in percentage terms\n\n# %%\n# Plot the deviations\napproximationError = 100*(cHARK - cApprox)/cHARK\nplt.figure(figsize=(9,6)) #set the figure size\nplt.plot(m_range, approximationError, label='cHARK - cApprox')\nplt.xlabel('Market resources') # x axis label\nplt.ylabel('Percent deviation of approximation') # y axis label\nplt.legend()\nplt.show()\n\n# %% [markdown]\n# Now we want to calculate how the approximation quality depends on the interest factor. We proceed as follows:\n# 1. Create arrays of R values, such that the return patience factor is increasing as you descend through the array\n# 2. Set up a for loop in which we will:\n# 1. Input the new value of $R$\n# 0. Solve the HARK model for the consumption function\n# 0. Calculate the approximate consumption function\n# 0. Save the average deviation between the two functions\n# 3. Then we can plot average deviation against the $R$ factor\n\n# %%\n# Create array of Rfree values, and calculate the patience factor\nhowMany = 30\nRfree_min = Rfree\nRfree_max = Rfree**20\nRfree_array = np.linspace(Rfree_min, Rfree_max, howMany)\n\nPat_array = (Rfree_array*DiscFac)**(1/CRRA)\nPatR_array = Pat_array/Rfree_array\n\n# %%\n# Set the time preference factor to match the interest factor so that $(R \\beta) = 1$\n\nParamod['DiscFac'] = 1/Rfree\n\n# %%\n# Plot average deviation from true consumption function\nPFagent = PerfForesightConsumerType(**Paramod) # construct a consumer with our previous parameters\n\nplt.figure(figsize=(9,6)) #set the figure size\nmean_dev = np.zeros(30)\n\nfor i in range(len(Rfree_array)):\n PFagent.Rfree = Rfree_array[i]\n \n # Now we just copy the lines of code from above that we want\n PFagent.solve()\n cHARK = PFagent.solution[0].cFunc(m_range)\n wealthHmn = PFagent.solution[0].hNrm\n wealthTot = wealthHmn+m_range\n rfree=Rfree-1\n discRte=(1/DiscFac)-1 \n cApprox = wealthTot*(rfree - (1/CRRA)*(rfree-discRte)) \n deviation = np.mean(np.abs(cApprox/cHARK))\n mean_dev[i] = deviation\n \nplt.plot(Rfree_array,mean_dev)\nplt.xlabel('Return Factor') # x axis label\nplt.ylabel(' Average deviation along consumption function') # y axis label\nplt.show()\n\n# %% [markdown]\n# So, when the return factor gets to roughly 1.4, the error in the approximation is almost 80 percent. It looks like the value for $R$ where the approximation almost exactly matches the truth is about 1.035.\n\n# %%\n" ]
[ [ "numpy.log", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "numpy.mean", "matplotlib.pyplot.hist", "matplotlib.pyplot.xlabel", "numpy.zeros", "numpy.sum", "matplotlib.pyplot.ylabel" ], [ "numpy.linspace", "matplotlib.pyplot.ylim", "numpy.sort", "numpy.mean", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ], [ "matplotlib.pyplot.legend", "numpy.abs", "numpy.linspace", "matplotlib.pyplot.ylim", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.style.use", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
skyhanil1004/openpilot
[ "900f13bda7b41c238cf75f382d3471141affe005" ]
[ "selfdrive/controls.org/lib/pid.py" ]
[ "import numpy as np\nfrom common.numpy_fast import clip, interp\n\ndef apply_deadzone(error, deadzone):\n if error > deadzone:\n error -= deadzone\n elif error < - deadzone:\n error += deadzone\n else:\n error = 0.\n return error\n\nclass PIController():\n def __init__(self, k_p, k_i, k_f=1., pos_limit=None, neg_limit=None, rate=100, sat_limit=0.8, convert=None):\n self._k_p = k_p # proportional gain\n self._k_i = k_i # integral gain\n self.k_f = k_f # feedforward gain\n\n self.pos_limit = pos_limit\n self.neg_limit = neg_limit\n\n self.sat_count_rate = 1.0 / rate\n self.i_unwind_rate = 0.3 / rate\n self.i_rate = 1.0 / rate\n self.sat_limit = sat_limit\n self.convert = convert\n\n self.reset()\n\n @property\n def k_p(self):\n return interp(self.speed, self._k_p[0], self._k_p[1])\n\n @property\n def k_i(self):\n return interp(self.speed, self._k_i[0], self._k_i[1])\n\n def _check_saturation(self, control, check_saturation, error):\n saturated = (control < self.neg_limit) or (control > self.pos_limit)\n\n if saturated and check_saturation and abs(error) > 0.1:\n self.sat_count += self.sat_count_rate\n else:\n self.sat_count -= self.sat_count_rate\n\n self.sat_count = clip(self.sat_count, 0.0, 1.0)\n\n return self.sat_count > self.sat_limit\n\n def reset(self):\n self.p = 0.0\n self.i = 0.0\n self.f = 0.0\n self.sat_count = 0.0\n self.saturated = False\n self.control = 0\n\n def update(self, setpoint, measurement, speed=0.0, check_saturation=True, override=False, feedforward=0., deadzone=0., freeze_integrator=False):\n self.speed = speed\n\n error = float(apply_deadzone(setpoint - measurement, deadzone))\n self.p = error * self.k_p\n self.f = feedforward * self.k_f\n\n if override:\n self.i -= self.i_unwind_rate * float(np.sign(self.i))\n else:\n i = self.i + error * self.k_i * self.i_rate\n control = self.p + self.f + i\n\n if self.convert is not None:\n control = self.convert(control, speed=self.speed)\n\n # Update when changing i will move the control away from the limits\n # or when i will move towards the sign of the error\n if ((error >= 0 and (control <= self.pos_limit or i < 0.0)) or \\\n (error <= 0 and (control >= self.neg_limit or i > 0.0))) and \\\n not freeze_integrator:\n self.i = i\n\n control = self.p + self.f + self.i\n if self.convert is not None:\n control = self.convert(control, speed=self.speed)\n\n self.saturated = False # self._check_saturation(control, check_saturation, error)\n\n self.control = clip(control, self.neg_limit, self.pos_limit)\n return self.control\n" ]
[ [ "numpy.sign" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SubhashishQPIT/strawberryfields
[ "dae6ae8b1b3eb188fc2c874bd6c943bebf697ab9", "298601e409528f22c6717c2d816ab68ae8bda1fa" ]
[ "strawberryfields/backends/fockbackend/backend.py", "tests/frontend/compilers/test_xcov.py" ]
[ "# Copyright 2019 Xanadu Quantum Technologies Inc.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Fock backend simulator\"\"\"\n# pylint: disable=protected-access,too-many-public-methods\n\nimport string\nfrom cmath import phase\nimport numpy as np\n\nfrom strawberryfields.backends import BaseFock, ModeMap\nfrom strawberryfields.backends.states import BaseFockState\n\nfrom .circuit import Circuit\n\nindices = string.ascii_lowercase\n\n\nclass FockBackend(BaseFock):\n r\"\"\"Implements a simulation of quantum optical circuits in a truncated\n Fock basis using NumPy, returning a :class:`~.BaseFock`\n state object.\n\n The primary component of the FockBackend is a\n :attr:`~.FockBackend.circuit` object which is used to simulate a multi-mode quantum optical system. The\n :class:`FockBackend` provides the basic API-compatible interface to the simulator, while the\n :attr:`~.FockBackend.circuit` object actually carries out the mathematical simulation.\n\n The :attr:`~.FockBackend.circuit` simulator maintains an internal tensor representation of the quantum state of a multi-mode quantum optical system\n using a (truncated) Fock basis representation. As its various state manipulation methods are called, the quantum state is updated\n to reflect these changes. The simulator will try to keep the internal state in a pure (vector) representation\n for as long as possible. Unitary gates will not change the type of representation, while state preparations and measurements will.\n\n A number of factors determine the shape and dimensionality of the state tensor:\n\n * the underlying state representation being used (either a ket vector or a density matrix)\n * the number of modes :math:`n` actively being simulated\n * the cutoff dimension :math:`D` for the Fock basis\n\n The state tensor corresponds to a multimode quantum system. If the\n representation is a pure state, the state tensor has shape\n :math:`(\\underbrace{D,...,D}_{n~\\text{times}})`.\n In a mixed state representation, the state tensor has shape\n :math:`(\\underbrace{D,D,...,D,D}_{2n~\\text{times}})`.\n Indices for the same mode appear consecutively. Hence, for a mixed state, the first two indices\n are for the first mode, the second are for the second mode, etc.\n\n ..\n .. currentmodule:: strawberryfields.backends.fockbackend\n .. autosummary::\n :toctree:\n\n ~circuit.Circuit\n ~ops\n \"\"\"\n\n short_name = \"fock\"\n circuit_spec = \"fock\"\n\n def __init__(self):\n \"\"\"Instantiate a FockBackend object.\"\"\"\n super().__init__()\n self._supported[\"mixed_states\"] = True\n self._init_modes = None #: int: initial number of modes in the circuit\n self._modemap = None #: Modemap: maps external mode indices to internal ones\n self.circuit = (\n None #: ~.fockbackend.circuit.Circuit: representation of the simulated quantum state\n )\n\n def _remap_modes(self, modes):\n if isinstance(modes, int):\n modes = [modes]\n was_int = True\n else:\n was_int = False\n map_ = self._modemap.show()\n submap = [map_[m] for m in modes]\n if not self._modemap.valid(modes) or None in submap:\n raise ValueError(\"The specified modes are not valid.\")\n\n remapped_modes = self._modemap.remap(modes)\n if was_int:\n remapped_modes = remapped_modes[0]\n return remapped_modes\n\n def begin_circuit(self, num_subsystems, **kwargs):\n r\"\"\"Instantiate a quantum circuit.\n\n Instantiates a representation of a quantum optical state with ``num_subsystems`` modes.\n The state is initialized to vacuum.\n\n The modes in the circuit are indexed sequentially using integers, starting from zero.\n Once an index is assigned to a mode, it can never be re-assigned to another mode.\n If the mode is deleted its index becomes invalid.\n An operation acting on an invalid or unassigned mode index raises an ``IndexError`` exception.\n\n Args:\n num_subsystems (int): number of modes in the circuit\n\n Keyword Args:\n cutoff_dim (int): Numerical Hilbert space cutoff dimension for the modes.\n For each mode, the simulator can represent the Fock states :math:`\\ket{0}, \\ket{1}, \\ldots, \\ket{\\text{cutoff_dim}-1}`.\n pure (bool): If True (default), use a pure state representation (otherwise will use a mixed state representation).\n \"\"\"\n cutoff_dim = kwargs.get(\"cutoff_dim\", None)\n pure = kwargs.get(\"pure\", True)\n if cutoff_dim is None:\n raise ValueError(\"Argument 'cutoff_dim' must be passed to the Fock backend\")\n if not isinstance(cutoff_dim, int):\n raise ValueError(\"Argument 'cutoff_dim' must be a positive integer\")\n if not isinstance(num_subsystems, int):\n raise ValueError(\"Argument 'num_subsystems' must be a positive integer\")\n if not isinstance(pure, bool):\n raise ValueError(\"Argument 'pure' must be either True or False\")\n\n self._init_modes = num_subsystems\n self.circuit = Circuit(num_subsystems, cutoff_dim, pure)\n self._modemap = ModeMap(num_subsystems)\n\n def add_mode(self, n=1):\n self.circuit.alloc(n)\n self._modemap.add(n)\n\n def del_mode(self, modes):\n remapped_modes = self._remap_modes(modes)\n if isinstance(remapped_modes, int):\n remapped_modes = [remapped_modes]\n self.circuit.dealloc(remapped_modes)\n self._modemap.delete(modes)\n\n def get_modes(self):\n return [i for i, j in enumerate(self._modemap._map) if j is not None]\n\n def reset(self, pure=True, **kwargs):\n cutoff = kwargs.get(\"cutoff_dim\", self.circuit._trunc)\n self._modemap.reset()\n self.circuit.reset(pure, num_subsystems=self._init_modes, cutoff_dim=cutoff)\n\n def prepare_vacuum_state(self, mode):\n self.circuit.prepare_mode_fock(0, self._remap_modes(mode))\n\n def prepare_coherent_state(self, r, phi, mode):\n self.circuit.prepare_mode_coherent(r, phi, self._remap_modes(mode))\n\n def prepare_squeezed_state(self, r, phi, mode):\n self.circuit.prepare_mode_squeezed(r, phi, self._remap_modes(mode))\n\n def prepare_displaced_squeezed_state(self, r_d, phi_d, r_s, phi_s, mode):\n self.circuit.prepare_mode_displaced_squeezed(\n r_d, phi_d, r_s, phi_s, self._remap_modes(mode)\n )\n\n def prepare_thermal_state(self, nbar, mode):\n self.circuit.prepare_mode_thermal(nbar, self._remap_modes(mode))\n\n def rotation(self, phi, mode):\n self.circuit.phase_shift(phi, self._remap_modes(mode))\n\n def displacement(self, r, phi, mode):\n self.circuit.displacement(r, phi, self._remap_modes(mode))\n\n def squeeze(self, r, phi, mode):\n self.circuit.squeeze(r, phi, self._remap_modes(mode))\n\n def two_mode_squeeze(self, r, phi, mode1, mode2):\n self.circuit.two_mode_squeeze(r, phi, self._remap_modes(mode1), self._remap_modes(mode2))\n\n def beamsplitter(self, theta, phi, mode1, mode2):\n self.circuit.beamsplitter(theta, phi, self._remap_modes(mode1), self._remap_modes(mode2))\n\n def mzgate(self, phi_in, phi_ex, mode1, mode2):\n self.circuit.mzgate(phi_in, phi_ex, self._remap_modes(mode1), self._remap_modes(mode2))\n\n def measure_homodyne(self, phi, mode, shots=1, select=None, **kwargs):\n \"\"\"Perform a homodyne measurement on the specified mode.\n\n See :meth:`.BaseBackend.measure_homodyne`.\n\n Keyword Args:\n num_bins (int): Number of equally spaced bins for the probability distribution function\n (pdf) simulating the homodyne measurement (default: 100000).\n max (float): The pdf is discretized onto the 1D grid [-max,max] (default: 10).\n \"\"\"\n if shots != 1:\n raise NotImplementedError(\n \"fock backend currently does not support \" \"shots != 1 for homodyne measurement\"\n )\n return self.circuit.measure_homodyne(phi, self._remap_modes(mode), select=select, **kwargs)\n\n def loss(self, T, mode):\n self.circuit.loss(T, self._remap_modes(mode))\n\n def is_vacuum(self, tol=0.0, **kwargs):\n return self.circuit.is_vacuum(tol)\n\n def get_cutoff_dim(self):\n return self.circuit._trunc\n\n def state(self, modes=None, **kwargs):\n s, pure = self.circuit.get_state()\n\n if modes is None:\n # reduced state is full state\n red_state = s\n num_modes = len(s.shape) if pure else len(s.shape) // 2\n modes = [m for m in range(num_modes)]\n else:\n # convert to mixed state representation\n if pure:\n num_modes = len(s.shape)\n left_str = [indices[i] for i in range(0, 2 * num_modes, 2)]\n right_str = [indices[i] for i in range(1, 2 * num_modes, 2)]\n out_str = [indices[: 2 * num_modes]]\n einstr = \"\".join(left_str + [\",\"] + right_str + [\"->\"] + out_str)\n rho = np.einsum(einstr, s, s.conj())\n else:\n rho = s\n\n # reduce rho down to specified subsystems\n if isinstance(modes, int):\n modes = [modes]\n\n if len(modes) != len(set(modes)):\n raise ValueError(\"The specified modes cannot be duplicated.\")\n\n num_modes = len(rho.shape) // 2\n if len(modes) > num_modes:\n raise ValueError(\n \"The number of specified modes cannot be larger than the number of subsystems.\"\n )\n\n keep_indices = indices[: 2 * len(modes)]\n trace_indices = indices[2 * len(modes) : len(modes) + num_modes]\n ind = [i * 2 for i in trace_indices]\n ctr = 0\n\n for m in range(num_modes):\n if m in modes:\n ind.insert(m, keep_indices[2 * ctr : 2 * (ctr + 1)])\n ctr += 1\n\n indStr = \"\".join(ind) + \"->\" + keep_indices\n red_state = np.einsum(indStr, rho)\n\n # permute indices of returned state to reflect the ordering of modes (we know and hence can assume that red_state is a mixed state)\n if modes != sorted(modes):\n mode_permutation = np.argsort(modes)\n index_permutation = [2 * x + i for x in mode_permutation for i in (0, 1)]\n red_state = np.transpose(red_state, np.argsort(index_permutation))\n\n cutoff = self.circuit._trunc\n mode_names = [\"q[{}]\".format(i) for i in np.array(self.get_modes())[modes]]\n state = BaseFockState(red_state, len(modes), pure, cutoff, mode_names)\n return state\n\n # ==============================================\n # Fock state specific\n # ==============================================\n\n def prepare_fock_state(self, n, mode):\n self.circuit.prepare_mode_fock(n, self._remap_modes(mode))\n\n def prepare_ket_state(self, state, modes):\n self.circuit.prepare_multimode(state, self._remap_modes(modes))\n\n def prepare_dm_state(self, state, modes):\n self.circuit.prepare_multimode(state, self._remap_modes(modes))\n\n def cubic_phase(self, gamma, mode):\n self.circuit.cubic_phase_shift(gamma, self._remap_modes(mode))\n\n def kerr_interaction(self, kappa, mode):\n self.circuit.kerr_interaction(kappa, self._remap_modes(mode))\n\n def cross_kerr_interaction(self, kappa, mode1, mode2):\n self.circuit.cross_kerr_interaction(\n kappa, self._remap_modes(mode1), self._remap_modes(mode2)\n )\n\n def measure_fock(self, modes, shots=1, select=None, **kwargs):\n if shots != 1:\n raise NotImplementedError(\n \"fock backend currently does not support \" \"shots != 1 for Fock measurement\"\n )\n return self.circuit.measure_fock(self._remap_modes(modes), select=select)\n\n def prepare_gkp(\n self, state, epsilon, ampl_cutoff, representation=\"real\", shape=\"square\", mode=None\n ):\n r\"\"\"Prepares the Fock representation of a finite energy GKP state.\n\n GKP states are qubits, with the qubit state defined by:\n\n :math:`\\ket{\\psi}_{gkp} = \\cos\\frac{\\theta}{2}\\ket{0}_{gkp} + e^{-i\\phi}\\sin\\frac{\\theta}{2}\\ket{1}_{gkp}`\n\n where the computational basis states are :math:`\\ket{\\mu}_{gkp} = \\sum_{n} \\ket{(2n+\\mu)\\sqrt{\\pi\\hbar}}_{q}`.\n\n Args:\n state (list): ``[theta,phi]`` for qubit definition above\n epsilon (float): finite energy parameter of the state\n amplcutoff (float): this determines how many terms to keep\n representation (str): ``'real'`` or ``'complex'`` reprsentation\n shape (str): shape of the lattice; default 'square'\n\n Returns:\n tuple: arrays of the weights, means and covariances for the state\n\n Raises:\n NotImplementedError: if the complex representation or a non-square lattice is attempted\n \"\"\"\n\n if representation == \"complex\":\n raise NotImplementedError(\"The complex description of GKP is not implemented\")\n\n if shape != \"square\":\n raise NotImplementedError(\"Only square GKP are implemented for now\")\n\n theta, phi = state[0], state[1]\n self.circuit.prepare_gkp(theta, phi, epsilon, ampl_cutoff, self._remap_modes(mode))\n", "# Copyright 2019-2020 Xanadu Quantum Technologies Inc.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nr\"\"\"Unit tests for the Xcov compiler\"\"\"\nimport textwrap\n\nimport pytest\nimport numpy as np\nimport networkx as nx\n\nimport blackbird\n\nimport strawberryfields as sf\nimport strawberryfields.ops as ops\n\nfrom strawberryfields.parameters import par_evaluate\nfrom strawberryfields.program_utils import CircuitError, list_to_DAG\nfrom strawberryfields.io import to_program\nfrom strawberryfields.utils import random_interferometer\nfrom strawberryfields.compilers import Compiler\n\nfrom thewalrus.symplectic import two_mode_squeezing, expand\n\npytestmark = pytest.mark.frontend\n\nnp.random.seed(42)\n\nSQ_AMPLITUDE = 1\n\"\"\"float: the allowed squeezing amplitude\"\"\"\n\n\ndef program_equivalence(prog1, prog2, compare_params=True, atol=1e-6, rtol=0):\n r\"\"\"Checks if two programs are equivalent.\n\n This function converts the program lists into directed acyclic graphs,\n and runs the NetworkX `is_isomorphic` graph function in order\n to determine if the two programs are equivalent.\n\n Note: when checking for parameter equality between two parameters\n :math:`a` and :math:`b`, we use the following formula:\n\n .. math:: |a - b| \\leq (\\texttt{atol} + \\texttt{rtol}\\times|b|)\n\n Args:\n prog1 (strawberryfields.program.Program): quantum program\n prog2 (strawberryfields.program.Program): quantum program\n compare_params (bool): Set to ``False`` to turn of comparing\n program parameters; equivalency will only take into\n account the operation order.\n atol (float): the absolute tolerance parameter for checking\n quantum operation parameter equality\n rtol (float): the relative tolerance parameter for checking\n quantum operation parameter equality\n\n Returns:\n bool: returns ``True`` if two quantum programs are equivalent\n \"\"\"\n DAG1 = list_to_DAG(prog1.circuit)\n DAG2 = list_to_DAG(prog2.circuit)\n\n circuit = []\n for G in [DAG1, DAG2]:\n # relabel the DAG nodes to integers\n circuit.append(nx.convert_node_labels_to_integers(G))\n\n # add node attributes to store the operation name and parameters\n name_mapping = {i: n.op.__class__.__name__ for i, n in enumerate(G.nodes())}\n parameter_mapping = {i: par_evaluate(n.op.p) for i, n in enumerate(G.nodes())}\n\n # CXgate and BSgate are not symmetric wrt permuting the order of the two\n # modes it acts on; i.e., the order of the wires matter\n wire_mapping = {}\n for i, n in enumerate(G.nodes()):\n if n.op.__class__.__name__ == \"CXgate\":\n if np.allclose(n.op.p[0], 0):\n # if the CXgate parameter is 0, wire order doesn't matter\n wire_mapping[i] = 0\n else:\n # if the CXgate parameter is not 0, order matters\n wire_mapping[i] = [j.ind for j in n.reg]\n\n elif n.op.__class__.__name__ == \"BSgate\":\n if np.allclose([j % np.pi for j in par_evaluate(n.op.p)], [np.pi / 4, np.pi / 2]):\n # if the beamsplitter is *symmetric*, then the order of the\n # wires does not matter.\n wire_mapping[i] = 0\n else:\n # beamsplitter is not symmetric, order matters\n wire_mapping[i] = [j.ind for j in n.reg]\n\n else:\n # not a CXgate or a BSgate, order of wires doesn't matter\n wire_mapping[i] = 0\n\n # TODO: at the moment, we do not check for whether an empty\n # wire will match an operation with trivial parameters.\n # Maybe we can do this in future, but this is a subgraph\n # isomorphism problem and much harder.\n\n nx.set_node_attributes(circuit[-1], name_mapping, name=\"name\")\n nx.set_node_attributes(circuit[-1], parameter_mapping, name=\"p\")\n nx.set_node_attributes(circuit[-1], wire_mapping, name=\"w\")\n\n def node_match(n1, n2):\n \"\"\"Returns True if both nodes have the same name and\n same parameters, within a certain tolerance\"\"\"\n name_match = n1[\"name\"] == n2[\"name\"]\n p_match = np.allclose(n1[\"p\"], n2[\"p\"], atol=atol, rtol=rtol)\n wire_match = n1[\"w\"] == n2[\"w\"]\n\n if compare_params:\n return name_match and p_match and wire_match\n\n return name_match and wire_match\n\n # check if circuits are equivalent\n return nx.is_isomorphic(circuit[0], circuit[1], node_match)\n\n\nclass DummyCircuit(Compiler):\n \"\"\"Dummy circuit used to instantiate\n the abstract base class\"\"\"\n\n modes = 8\n remote = False\n local = True\n interactive = True\n primitives = {\"S2gate\", \"MeasureFock\", \"Rgate\", \"BSgate\", \"MZgate\"}\n decompositions = {\"Interferometer\": {}}\n\n\nX8_CIRCUIT = textwrap.dedent(\n \"\"\"\\\n name template_4x2_X8\n version 1.0\n target X8_01 (shots=1)\n # for n spatial degrees, first n signal modes, then n idler modes, all phases zero\n S2gate({squeezing_amplitude_0}, 0.0) | [0, 4]\n S2gate({squeezing_amplitude_1}, 0.0) | [1, 5]\n S2gate({squeezing_amplitude_2}, 0.0) | [2, 6]\n S2gate({squeezing_amplitude_3}, 0.0) | [3, 7]\n # standard 4x4 interferometer for the signal modes (the lower ones in frequency)\n # even phase indices correspond to internal Mach-Zehnder interferometer phases\n # odd phase indices correspond to external Mach-Zehnder interferometer phases\n MZgate({phase_0}, {phase_1}) | [0, 1]\n MZgate({phase_2}, {phase_3}) | [2, 3]\n MZgate({phase_4}, {phase_5}) | [1, 2]\n MZgate({phase_6}, {phase_7}) | [0, 1]\n MZgate({phase_8}, {phase_9}) | [2, 3]\n MZgate({phase_10}, {phase_11}) | [1, 2]\n # duplicate the interferometer for the idler modes (the higher ones in frequency)\n MZgate({phase_0}, {phase_1}) | [4, 5]\n MZgate({phase_2}, {phase_3}) | [6, 7]\n MZgate({phase_4}, {phase_5}) | [5, 6]\n MZgate({phase_6}, {phase_7}) | [4, 5]\n MZgate({phase_8}, {phase_9}) | [6, 7]\n MZgate({phase_10}, {phase_11}) | [5, 6]\n # add final dummy phases to allow mapping any unitary to this template (these do not\n # affect the photon number measurement)\n Rgate({final_phase_0}) | [0]\n Rgate({final_phase_1}) | [1]\n Rgate({final_phase_2}) | [2]\n Rgate({final_phase_3}) | [3]\n Rgate({final_phase_4}) | [4]\n Rgate({final_phase_5}) | [5]\n Rgate({final_phase_6}) | [6]\n Rgate({final_phase_7}) | [7]\n # measurement in Fock basis\n MeasureFock() | [0, 1, 2, 3, 4, 5, 6, 7]\n \"\"\"\n)\n\n\nclass TestXCompilation:\n \"\"\"Tests for compilation using the X8_01 circuit specification\"\"\"\n\n def test_exact_template(self, tol):\n \"\"\"Test compilation works for the exact circuit\"\"\"\n bb = blackbird.loads(X8_CIRCUIT)\n bb = bb(\n squeezing_amplitude_0=SQ_AMPLITUDE,\n squeezing_amplitude_1=SQ_AMPLITUDE,\n squeezing_amplitude_2=SQ_AMPLITUDE,\n squeezing_amplitude_3=SQ_AMPLITUDE,\n phase_0=0,\n phase_1=1,\n phase_2=2,\n phase_3=3,\n phase_4=4,\n phase_5=5,\n phase_6=6,\n phase_7=7,\n phase_8=8,\n phase_9=9,\n phase_10=10,\n phase_11=11,\n final_phase_0=1.24,\n final_phase_1=-0.54,\n final_phase_2=4.12,\n final_phase_3=0,\n final_phase_4=1.24,\n final_phase_5=-0.54,\n final_phase_6=4.12,\n final_phase_7=0,\n )\n\n expected = to_program(bb)\n res = expected.compile(compiler=\"Xcov\")\n\n assert program_equivalence(res, expected, atol=tol, compare_params=False)\n\n @pytest.mark.parametrize(\"num_pairs\", [4, 5, 6, 7])\n def test_not_all_modes_measured(self, num_pairs):\n \"\"\"Test exceptions raised if not all modes are measured\"\"\"\n prog = sf.Program(2 * num_pairs)\n U = random_interferometer(num_pairs)\n with prog.context as q:\n for i in range(num_pairs):\n ops.S2gate(SQ_AMPLITUDE) | (q[i], q[i + num_pairs])\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs))\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs, 2 * num_pairs))\n ops.MeasureFock() | (q[0], q[num_pairs])\n with pytest.raises(CircuitError, match=\"All modes must be measured\"):\n prog.compile(compiler=\"Xcov\")\n\n @pytest.mark.parametrize(\"num_pairs\", [4, 5, 6, 7])\n def test_no_s2gates(self, num_pairs, tol):\n \"\"\"Test identity S2gates are inserted when no S2gates\n are provided.\"\"\"\n prog = sf.Program(2 * num_pairs)\n U = random_interferometer(num_pairs)\n\n with prog.context as q:\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs))\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs, 2 * num_pairs))\n ops.MeasureFock() | q\n\n expected = sf.Program(2 * num_pairs)\n\n with expected.context as q:\n for i in range(num_pairs):\n ops.S2gate(0) | (q[i], q[i + num_pairs])\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs))\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs, 2 * num_pairs))\n ops.MeasureFock() | q\n\n res = prog.compile(compiler=\"Xcov\")\n expected = expected.compile(compiler=\"Xcov\")\n assert program_equivalence(res, expected, atol=tol)\n\n @pytest.mark.parametrize(\"num_pairs\", [4, 5, 6, 7])\n def test_missing_s2gates(self, num_pairs, tol):\n \"\"\"Test identity S2gates are inserted when some (but not all)\n S2gates are included.\"\"\"\n prog = sf.Program(2 * num_pairs)\n U = random_interferometer(num_pairs)\n assert num_pairs > 3\n with prog.context as q:\n ops.S2gate(SQ_AMPLITUDE) | (q[1], q[num_pairs + 1])\n ops.S2gate(SQ_AMPLITUDE) | (q[3], q[num_pairs + 3])\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs))\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs, 2 * num_pairs))\n ops.MeasureFock() | q\n\n expected = sf.Program(2 * num_pairs)\n\n with expected.context as q:\n ops.S2gate(SQ_AMPLITUDE) | (q[1], q[num_pairs + 1])\n ops.S2gate(0) | (q[0], q[num_pairs + 0])\n ops.S2gate(SQ_AMPLITUDE) | (q[3], q[num_pairs + 3])\n ops.S2gate(0) | (q[2], q[num_pairs + 2])\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs))\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs, 2 * num_pairs))\n ops.MeasureFock() | q\n\n res = prog.compile(compiler=\"Xcov\")\n expected = expected.compile(compiler=\"Xcov\")\n assert program_equivalence(res, expected, atol=tol)\n\n @pytest.mark.parametrize(\"num_pairs\", [4, 5, 6, 7])\n def test_incorrect_s2gate_modes(self, num_pairs):\n \"\"\"Test exceptions raised if S2gates do not appear on correct modes\"\"\"\n prog = sf.Program(2 * num_pairs)\n U = random_interferometer(num_pairs)\n n_modes = 2 * num_pairs\n half_n_modes = n_modes // 2\n with prog.context as q:\n for i in range(num_pairs):\n ops.S2gate(SQ_AMPLITUDE) | (q[2 * i], q[2 * i + 1])\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs))\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs, 2 * num_pairs))\n ops.MeasureFock() | q\n\n with pytest.raises(\n CircuitError,\n match=\"The applied unitary cannot mix between the modes {}-{} and modes {}-{}.\".format(\n 0, half_n_modes - 1, half_n_modes, n_modes - 1\n ),\n ):\n res = prog.compile(compiler=\"Xcov\")\n\n @pytest.mark.parametrize(\"num_pairs\", [4, 5, 6, 7])\n def test_s2gate_repeated_modes_half_squeezing(self, num_pairs):\n \"\"\"Test that squeezing gates are correctly merged\"\"\"\n prog = sf.Program(2 * num_pairs)\n U = random_interferometer(num_pairs)\n\n with prog.context as q:\n\n ops.S2gate(SQ_AMPLITUDE / 2) | (q[0], q[0 + num_pairs])\n for i in range(1, num_pairs):\n ops.S2gate(SQ_AMPLITUDE) | (q[i], q[i + num_pairs])\n ops.S2gate(SQ_AMPLITUDE / 2) | (q[0], q[0 + num_pairs])\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs))\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs, 2 * num_pairs))\n ops.MeasureFock() | q\n\n res = prog.compile(compiler=\"Xcov\")\n assert np.allclose(res.circuit[0].op.p[0], SQ_AMPLITUDE)\n\n def test_gates_compile(self):\n \"\"\"Test that combinations of MZgates, Rgates, and BSgates\n correctly compile.\"\"\"\n prog = sf.Program(8)\n\n def unitary(q):\n ops.MZgate(0.5, 0.1) | (q[0], q[1])\n ops.BSgate(0.1, 0.2) | (q[1], q[2])\n ops.Rgate(0.4) | q[0]\n\n with prog.context as q:\n ops.S2gate(SQ_AMPLITUDE) | (q[0], q[4])\n ops.S2gate(SQ_AMPLITUDE) | (q[1], q[5])\n ops.S2gate(SQ_AMPLITUDE) | (q[2], q[6])\n ops.S2gate(SQ_AMPLITUDE) | (q[3], q[7])\n\n unitary(q[:4])\n unitary(q[4:])\n ops.MeasureFock() | q\n\n prog.compile(compiler=\"Xcov\")\n\n def test_no_unitary(self, tol):\n \"\"\"Test compilation works with no unitary provided\"\"\"\n prog = sf.Program(8)\n\n with prog.context as q:\n ops.S2gate(SQ_AMPLITUDE) | (q[0], q[4])\n ops.S2gate(SQ_AMPLITUDE) | (q[1], q[5])\n ops.S2gate(SQ_AMPLITUDE) | (q[2], q[6])\n ops.S2gate(SQ_AMPLITUDE) | (q[3], q[7])\n ops.MeasureFock() | q\n\n res = prog.compile(compiler=\"Xcov\")\n expected = sf.Program(8)\n\n with expected.context as q:\n ops.S2gate(SQ_AMPLITUDE, 0) | (q[0], q[4])\n ops.S2gate(SQ_AMPLITUDE, 0) | (q[1], q[5])\n ops.S2gate(SQ_AMPLITUDE, 0) | (q[2], q[6])\n ops.S2gate(SQ_AMPLITUDE, 0) | (q[3], q[7])\n\n # corresponds to an identity on modes [0, 1, 2, 3]\n # This can be easily seen from below by noting that:\n # MZ(pi, pi) = R(0) = I\n # MZ(pi, 0) @ MZ(pi, 0) = I\n # [R(pi) \\otimes I] @ MZ(pi, 0) = I\n ops.MZgate(np.pi, 0) | (q[0], q[1])\n ops.MZgate(np.pi, 0) | (q[2], q[3])\n ops.MZgate(np.pi, np.pi) | (q[1], q[2])\n ops.MZgate(np.pi, np.pi) | (q[0], q[1])\n ops.MZgate(np.pi, 0) | (q[2], q[3])\n ops.MZgate(np.pi, np.pi) | (q[1], q[2])\n ops.Rgate(np.pi) | (q[0])\n ops.Rgate(0) | (q[1])\n ops.Rgate(0) | (q[2])\n ops.Rgate(0) | (q[3])\n\n # corresponds to an identity on modes [4, 5, 6, 7]\n ops.MZgate(np.pi, 0) | (q[4], q[5])\n ops.MZgate(np.pi, 0) | (q[6], q[7])\n ops.MZgate(np.pi, np.pi) | (q[5], q[6])\n ops.MZgate(np.pi, np.pi) | (q[4], q[5])\n ops.MZgate(np.pi, 0) | (q[6], q[7])\n ops.MZgate(np.pi, np.pi) | (q[5], q[6])\n ops.Rgate(np.pi) | (q[4])\n ops.Rgate(0) | (q[5])\n ops.Rgate(0) | (q[6])\n ops.Rgate(0) | (q[7])\n\n ops.MeasureFock() | q\n\n assert program_equivalence(res, expected, atol=tol, compare_params=False)\n\n # double check that the applied symplectic is correct\n\n # remove the Fock measurements\n res.circuit = res.circuit[:-1]\n\n # extract the Gaussian symplectic matrix\n O = res.compile(compiler=\"gaussian_unitary\").circuit[0].op.p[0]\n\n # construct the expected symplectic matrix corresponding\n # to just the initial two mode squeeze gates\n S = two_mode_squeezing(SQ_AMPLITUDE, 0)\n num_modes = 8\n expected = np.identity(2 * num_modes)\n for i in range(num_modes // 2):\n expected = expand(S, [i, i + num_modes // 2], num_modes) @ expected\n # Note that the comparison has to be made at the level of covariance matrices\n # Not at the level of symplectic matrices\n assert np.allclose(O @ O.T, expected @ expected.T, atol=tol)\n\n @pytest.mark.parametrize(\"num_pairs\", [4])\n def test_interferometers(self, num_pairs, tol):\n \"\"\"Test that the compilation correctly decomposes the interferometer using\n the rectangular_symmetric mesh\"\"\"\n prog = sf.Program(2 * num_pairs)\n U = random_interferometer(num_pairs)\n\n with prog.context as q:\n for i in range(0, num_pairs):\n ops.S2gate(SQ_AMPLITUDE) | (q[i], q[i + num_pairs])\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs))\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs, 2 * num_pairs))\n ops.MeasureFock() | q\n\n res = prog.compile(compiler=\"Xcov\")\n\n expected = sf.Program(2 * num_pairs)\n\n with expected.context as q:\n for i in range(0, num_pairs):\n ops.S2gate(SQ_AMPLITUDE) | (q[i], q[i + num_pairs])\n ops.Interferometer(U, mesh=\"rectangular_symmetric\", drop_identity=False) | tuple(\n q[i] for i in range(num_pairs)\n )\n ops.Interferometer(U, mesh=\"rectangular_symmetric\", drop_identity=False) | tuple(\n q[i] for i in range(num_pairs, 2 * num_pairs)\n )\n ops.MeasureFock() | q\n\n expected = expected.compile(compiler=DummyCircuit())\n # Note that since DummyCircuit() has a hard coded limit of 8 modes we only check for this number\n assert program_equivalence(res, expected, atol=tol, compare_params=False)\n\n @pytest.mark.parametrize(\"num_pairs\", [4, 5, 6, 7])\n def test_unitaries_do_not_match(self, num_pairs):\n \"\"\"Test exception raised if the unitary applied to modes [0, 1, 2, 3] is\n different to the unitary applied to modes [4, 5, 6, 7]\"\"\"\n prog = sf.Program(2 * num_pairs)\n U = random_interferometer(num_pairs)\n\n with prog.context as q:\n for i in range(0, num_pairs):\n ops.S2gate(SQ_AMPLITUDE) | (q[i], q[i + num_pairs])\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs))\n ops.Interferometer(U) | tuple(q[i] for i in range(num_pairs, 2 * num_pairs))\n ops.BSgate() | (q[2], q[3])\n ops.MeasureFock() | q\n\n with pytest.raises(CircuitError, match=\"The applied unitary on modes\"):\n res = prog.compile(compiler=\"Xcov\")\n\n @pytest.mark.parametrize(\"num_pairs\", [4, 5, 6, 7])\n def test_unitary_too_large(self, num_pairs):\n \"\"\"Test exception raised if the unitary is applied to more\n than just modes [0, 1, 2, 3, ..., num_pairs-1] and [num_pairs, num_pairs+1, ..., 2*num_pairs-1].\"\"\"\n prog = sf.Program(2 * num_pairs)\n U = random_interferometer(2 * num_pairs)\n\n with prog.context as q:\n for i in range(0, num_pairs):\n ops.S2gate(SQ_AMPLITUDE) | (q[i], q[i + num_pairs])\n ops.Interferometer(U) | q\n ops.MeasureFock() | q\n\n with pytest.raises(CircuitError, match=\"The applied unitary cannot mix between the modes\"):\n res = prog.compile(compiler=\"Xcov\")\n\n def test_error_odd_number_modes(self):\n \"\"\"Test that an error is raised if the number of modes provided is odd\"\"\"\n prog = sf.Program(5)\n\n with pytest.raises(\n CircuitError, match=\"only supports programs with an even number of modes\"\n ):\n res = prog.compile(compiler=\"Xcov\")\n\n def test_symplectic_smaller_than_program(self):\n \"\"\"Test that compilation correctly works if the provided gates act only\n on a subset of program modes\"\"\"\n prog = sf.Program(4)\n\n with prog.context as q:\n ops.S2gate(SQ_AMPLITUDE) | (q[0], q[2])\n ops.MeasureFock() | q\n\n res = prog.compile(compiler=\"Xcov\")\n\n # remove the Fock measurements\n res.circuit = res.circuit[:-1]\n\n # extract the Gaussian symplectic matrix\n c = res.compile(compiler=\"gaussian_unitary\").circuit[0]\n assert [i.ind for i in c.reg] == [0, 1, 2, 3]\n assert c.op.p[0].shape == (8, 8)\n\n def test_identity_program(self, tol):\n \"\"\"Test that compilation correctly works if the gate consists only of measurements\"\"\"\n prog = sf.Program(4)\n\n with prog.context as q:\n ops.MeasureFock() | q\n\n res = prog.compile(compiler=\"Xcov\")\n\n # remove the Fock measurements\n res.circuit = res.circuit[:-1]\n\n # extract the Gaussian symplectic matrix\n res = res.compile(compiler=\"gaussian_unitary\")\n assert not res.circuit\n\n def test_nothing_happens_and_nothing_crashes(self):\n \"\"\"Test that even a program that does nothing compiles correctly\"\"\"\n n_modes = 4\n squeezing_amplitudes = [0] * n_modes\n unitary = np.identity(n_modes)\n\n prog = sf.Program(n_modes * 2)\n\n with prog.context as q:\n for i in range(n_modes):\n ops.S2gate(squeezing_amplitudes[i]) | (q[i], q[i + n_modes])\n for qumodes in (q[:n_modes], q[n_modes:]):\n ops.Interferometer(unitary) | qumodes\n ops.MeasureFock() | q\n\n res = prog.compile(compiler=\"Xcov\")\n\n # check that all squeezing is 0\n assert all(cmd.op.p[0] == 0 for cmd in res.circuit if isinstance(cmd.op, ops.S2gate))\n\n # check that all phase shifts are 0\n assert all(cmd.op.p[0] == 0 for cmd in res.circuit if isinstance(cmd.op, ops.Rgate))\n\n # check that all MZgate angles are pi\n assert all(cmd.op.p[0] == np.pi for cmd in res.circuit if isinstance(cmd.op, ops.MZgate))\n" ]
[ [ "numpy.argsort", "numpy.einsum" ], [ "numpy.identity", "numpy.allclose", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shivamshan/MSS
[ "12879e64b1088b1db94b1db0d0919a31e662cd20", "12879e64b1088b1db94b1db0d0919a31e662cd20" ]
[ "mslib/msui/mpl_map.py", "mslib/msui/mpl_pathinteractor.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n\n mslib.msui.mpl_map\n ~~~~~~~~~~~~~~~~~~\n\n Map canvas for the top view.\n As Matplotlib's Basemap is primarily designed to produce static plots,\n we derived a class MapCanvas to allow for a certain degree of\n interactivity. MapCanvas extends Basemap by functionality to, for\n instance, automatically draw a graticule. It also keeps references to\n plotted map elements to allow the user to toggle their visibility, or\n to redraw when map section (zoom/pan) or projection have been changed.\n\n This file is part of mss.\n\n :copyright: Copyright 2008-2014 Deutsches Zentrum fuer Luft- und Raumfahrt e.V.\n :copyright: Copyright 2011-2014 Marc Rautenhaus (mr)\n :copyright: Copyright 2016-2021 by the mss team, see AUTHORS.\n :license: APACHE-2.0, see LICENSE for details.\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 logging\nimport copy\nimport numpy as np\nfrom shapely.geometry import Polygon\nimport matplotlib\nfrom matplotlib.cm import get_cmap\nimport matplotlib.path as mpath\nimport matplotlib.patches as mpatches\nfrom matplotlib.collections import PolyCollection\nimport mpl_toolkits.basemap as basemap\ntry:\n import mpl_toolkits.basemap.pyproj as pyproj\nexcept ImportError:\n logging.debug(\"Failed to pyproj from mpl_toolkits.basemap\")\n import pyproj\n\nfrom mslib.msui import mpl_pathinteractor as mpl_pi\nfrom mslib.utils.airdata import get_airports, get_airspaces\n\n\nOPENAIP_NOTICE = \"Airspace data used comes from openAIP.\\n\" \\\n \"Visit openAIP.net and contribute to better aviation data, free for everyone to use and share.\"\nOURAIRPORTS_NOTICE = \"Airports provided by OurAirports.\"\n\n\nclass MapCanvas(basemap.Basemap):\n \"\"\"\n Derivative of mpl_toolkits.basemap, providing additional methods to\n automatically draw a graticule and to redraw specific map elements.\n \"\"\"\n\n def __init__(self, identifier=None, CRS=None, BBOX_UNITS=None, OPERATION_NAME=None,\n appearance=None, **kwargs):\n \"\"\"\n New constructor automatically adds coastlines, continents, and\n a graticule to the map.\n\n Keyword arguments are the same as for mpl_toolkits.basemap.\n\n Additional arguments:\n CRS -- string describing the coordinate reference system of the map.\n BBOX_UNITS -- string describing the units of the map coordinates.\n OPERATION_NAME -- string with operation name\n\n \"\"\"\n # Coordinate reference system identifier and coordinate system units.\n self.crs = CRS if CRS is not None else self.crs if hasattr(self, \"crs\") else None\n if BBOX_UNITS is not None:\n self.bbox_units = BBOX_UNITS\n else:\n self.bbox_units = getattr(self, \"bbox_units\", None)\n\n self.operation_name = OPERATION_NAME if OPERATION_NAME is not None else self.operation_name \\\n if hasattr(self, \"operation_name\") else None\n\n # Dictionary containing map appearance settings.\n if appearance is not None:\n param_appearance = appearance\n else:\n param_appearance = getattr(self, \"appearance\", {})\n\n default_appearance = {\"draw_graticule\": True,\n \"draw_coastlines\": True,\n \"fill_waterbodies\": True,\n \"fill_continents\": True,\n \"colour_water\": ((153 / 255.), (255 / 255.), (255 / 255.), (255 / 255.)),\n \"colour_land\": ((204 / 255.), (153 / 255.), (102 / 255.), (255 / 255.))}\n default_appearance.update(param_appearance)\n self.appearance = default_appearance\n # Identifier of this map canvas (used to query data structures that\n # are observed by different views).\n if identifier is not None:\n self.identifier = identifier\n else:\n self.identifier = getattr(self, \"identifier\", None)\n\n # Call the Basemap constructor. If a cylindrical projection was used\n # before, Basemap stores an EPSG code that will not be changed if\n # the Basemap constructor is called a second time. Hence, we have to\n # delete the attribute (mr, 08Feb2013).\n if hasattr(self, \"epsg\"):\n del self.epsg\n super().__init__(**kwargs)\n\n self.gc = pyproj.Geod(a=self.rmajor, b=self.rminor)\n\n self.kwargs = kwargs\n\n # Set up the map appearance.\n if self.appearance[\"draw_coastlines\"]:\n if len(self.coastsegs) > 0 and len(self.coastsegs[0]) > 0:\n self.map_coastlines = self.drawcoastlines(zorder=3)\n self.map_countries = self.drawcountries(zorder=3)\n else:\n self.map_coastlines = None\n self.map_countries = None\n if self.appearance[\"fill_waterbodies\"]:\n self.map_boundary = self.drawmapboundary(fill_color=self.appearance[\"colour_water\"])\n else:\n self.map_boundary = None\n\n # zorder = 0 is necessary to paint over the filled continents with\n # scatter() for drawing the flight tracks and trajectories.\n # Curiously, plot() works fine without this setting, but scatter()\n # doesn't.\n if self.appearance[\"fill_continents\"]:\n self.map_continents = self.fillcontinents(\n color=self.appearance[\"colour_land\"], lake_color=self.appearance[\"colour_water\"], zorder=1)\n else:\n self.map_continents = None\n\n self.image = None\n\n # Print project name and CRS identifier into figure.\n crs_text = \"\"\n if self.operation_name is not None:\n crs_text += self.operation_name\n if self.crs is not None:\n if len(crs_text) > 0:\n crs_text += \"\\n\"\n crs_text += self.crs\n if hasattr(self, \"crs_text\"): # update existing textbox\n self.crs_text.set_text(crs_text)\n else:\n self.crs_text = self.ax.figure.text(0, 0, crs_text)\n\n if self.appearance[\"draw_graticule\"]:\n pass\n # self._draw_auto_graticule() ; It's already called in mpl_qtwidget.py in MplTopviewCanvas init_map().\n else:\n self.map_parallels = None\n self.map_meridians = None\n\n # self.warpimage() # disable fillcontinents when loading bluemarble\n self.ax.set_autoscale_on(False)\n if not hasattr(self, \"airports\") or not self.airports:\n self.airports = None\n self.airtext = None\n if not hasattr(self, \"airspaces\") or not self.airspaces:\n self.airspaces = None\n self.airspacetext = None\n\n def set_identifier(self, identifier):\n self.identifier = identifier\n\n def set_axes_limits(self, ax=None):\n \"\"\"\n See Basemap.set_axes_limits() for documentation.\n\n This function is overridden in MapCanvas as a workaround to a problem\n in Basemap.set_axes_limits() that occurs in interactive matplotlib\n mode. If matplotlib.is_interactive() is True, Basemap.set_axes_limits()\n tries to redraw the canvas by accessing the pylab figure manager.\n If the matplotlib object is embedded in a Qt application, this manager\n is not available and an exception is raised. Hence, the interactive\n mode is disabled here before the original Basemap.set_axes_limits()\n method is called. It is restored afterwards.\n \"\"\"\n intact = matplotlib.is_interactive()\n matplotlib.interactive(False)\n super(MapCanvas, self).set_axes_limits(ax=ax)\n matplotlib.interactive(intact)\n\n def _draw_auto_graticule(self, font_size=None):\n \"\"\"\n Draw an automatically spaced graticule on the map.\n \"\"\"\n # Compute some map coordinates that are required below for the automatic\n # determination of which meridians and parallels to draw.\n axis = self.ax.axis()\n upperLeftCornerLon, upperLeftCornerLat = self.__call__(\n axis[0], axis[3], inverse=True)\n lowerRightCornerLon, lowerRightCornerLat = self.__call__(\n axis[1], axis[2], inverse=True)\n middleUpperBoundaryLon, middleUpperBoundaryLat = self.__call__(\n np.mean([axis[0], axis[1]]), axis[3], inverse=True)\n middleLowerBoundaryLon, middleLowerBoundaryLat = self.__call__(\n np.mean([axis[0], axis[1]]), axis[2], inverse=True)\n\n # Determine which parallels and meridians should be drawn.\n # a) determine which are the minimum and maximum visible\n # longitudes and latitudes, respectively. These\n # values depend on the map projection.\n if self.projection in ['npstere', 'spstere', 'stere', 'lcc']:\n # For stereographic projections: Draw meridians from the minimum\n # longitude contained in the map at one of the four corners to the\n # maximum longitude at one of these corner points. If\n # the southern or norther pole is contained in the map, draw all\n # meridians around the globe.\n # Draw parallels from the min latitude contained in the map at\n # one of the four corners OR the middle top or bottom to the\n # maximum latitude at one of these six points.\n # If the map centre in contained in the map, replace either\n # start or end latitude by the centre latitude (whichever is\n # smaller/larger).\n\n # check if centre point of projection is contained in the map,\n # use projection coordinates for this test\n centre_x = self.projparams[\"x_0\"]\n centre_y = self.projparams[\"y_0\"]\n centre_lon, centre_lat = self.__call__(centre_x, centre_y, inverse=True)\n if centre_lat > 0:\n pole_lon, pole_lat = 0, 90\n else:\n pole_lon, pole_lat = 0, -90\n pole_x, pole_y = self.__call__(pole_lon, pole_lat)\n if self.urcrnrx > self.llcrnrx:\n contains_pole = (self.llcrnrx <= pole_x <= self.urcrnrx)\n else:\n contains_pole = (self.llcrnrx >= pole_x >= self.urcrnrx)\n if self.urcrnry > self.llcrnry:\n contains_pole = contains_pole and (self.llcrnry <= pole_y <= self.urcrnry)\n else:\n contains_pole = contains_pole and (self.llcrnry >= pole_y >= self.urcrnry)\n\n # merdidians\n if contains_pole:\n mapLonStart = -180.\n mapLonStop = 180.\n else:\n mapLonStart = min(upperLeftCornerLon, self.llcrnrlon,\n self.urcrnrlon, lowerRightCornerLon)\n mapLonStop = max(upperLeftCornerLon, self.llcrnrlon,\n self.urcrnrlon, lowerRightCornerLon)\n # parallels\n mapLatStart = min(middleLowerBoundaryLat, lowerRightCornerLat,\n self.llcrnrlat,\n middleUpperBoundaryLat, upperLeftCornerLat,\n self.urcrnrlat)\n mapLatStop = max(middleLowerBoundaryLat, lowerRightCornerLat,\n self.llcrnrlat,\n middleUpperBoundaryLat, upperLeftCornerLat,\n self.urcrnrlat)\n if contains_pole:\n centre_lat = self.projparams[\"lat_0\"]\n mapLatStart = min(mapLatStart, centre_lat)\n mapLatStop = max(mapLatStop, centre_lat)\n else:\n # for other projections (preliminary): difference between the\n # lower left and the upper right corner.\n mapLonStart = self.llcrnrlon\n mapLonStop = self.urcrnrlon\n mapLatStart = self.llcrnrlat\n mapLatStop = self.urcrnrlat\n\n # b) parallels and meridians can be drawn with a spacing of\n # >spacingValues< degrees. Determine the appropriate\n # spacing for the lon/lat differences: about 10 lines\n # should be drawn in each direction. (The following lines\n # filter the spacingValues list for all spacing values\n # that are larger than lat/lon difference / 10, then\n # take the first value (first values that's larger)).\n spacingValues = [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30, 40]\n deltaLon = mapLonStop - mapLonStart\n deltaLat = mapLatStop - mapLatStart\n spacingLon = ([i for i in spacingValues if i > (deltaLon / 11.)] + [60])[0]\n spacingLat = ([i for i in spacingValues if i > (deltaLat / 11.)] + [60])[0]\n\n # c) parallels and meridians start at the first value in the\n # spacingLon/Lat grid that's smaller than the lon/lat of the\n # lower left corner; they stop at the first values in the\n # grid that's larger than the lon/lat of the upper right corner.\n lonStart = np.floor((mapLonStart / spacingLon)) * spacingLon\n lonStop = np.ceil((mapLonStop / spacingLon)) * spacingLon\n latStart = np.floor((mapLatStart / spacingLat)) * spacingLat\n latStop = np.ceil((mapLatStop / spacingLat)) * spacingLat\n\n # d) call the basemap methods to draw the lines in the determined\n # range.\n self.map_parallels = self.drawparallels(np.arange(latStart, latStop,\n spacingLat),\n labels=[1, 1, 0, 0], fontsize=font_size, zorder=3)\n self.map_meridians = self.drawmeridians(np.arange(lonStart, lonStop,\n spacingLon),\n labels=[0, 0, 0, 1], fontsize=font_size, zorder=3)\n\n def set_graticule_visible(self, visible=True):\n \"\"\"\n Set the visibily of the graticule.\n\n Removes a currently visible graticule by deleting internally stored\n line and text objects representing graticule lines and labels, then\n redrawing the map canvas.\n\n See http://www.mail-archive.com/[email protected]/msg09349.html\n \"\"\"\n self.appearance[\"draw_graticule\"] = visible\n if visible and self.map_parallels is None and self.map_meridians is None:\n # Draw new graticule if visible is True and no current graticule\n # exists.\n self._draw_auto_graticule()\n # Update the figure canvas.\n self.ax.figure.canvas.draw()\n elif not visible and self.map_parallels is not None and self.map_meridians is not None:\n # If visible if False, remove current graticule if one exists.\n # Every item in self.map_parallels and self.map_meridians is\n # a tuple of a list of lines and a list of text labels.\n for item in self.map_parallels.values():\n for line in item[0]:\n line.remove()\n for text in item[1]:\n text.remove()\n for item in self.map_meridians.values():\n for line in item[0]:\n line.remove()\n for text in item[1]:\n text.remove()\n self.map_parallels = None\n self.map_meridians = None\n # Update the figure canvas.\n self.ax.figure.canvas.draw()\n\n def set_draw_airports(self, value, port_type=[\"small_airport\"], reload=True):\n \"\"\"\n Sets airports to visible or not visible\n \"\"\"\n if (reload or not value or len(port_type) == 0) and self.airports:\n if OURAIRPORTS_NOTICE in self.crs_text.get_text():\n self.crs_text.set_text(self.crs_text.get_text().replace(f\"{OURAIRPORTS_NOTICE}\\n\", \"\"))\n self.airports.remove()\n self.airtext.remove()\n self.airports = None\n self.airtext = None\n self.ax.figure.canvas.mpl_disconnect(self.airports_event)\n if value and len(port_type) > 0:\n self.draw_airports(port_type)\n\n def set_draw_airspaces(self, value, airspaces=[], range_km=None, reload=True):\n \"\"\"\n Sets airspaces to visible or not visible\n \"\"\"\n if (reload or not value or len(airspaces) == 0) and self.airspaces:\n if OPENAIP_NOTICE in self.crs_text.get_text():\n self.crs_text.set_text(self.crs_text.get_text().replace(f\"{OPENAIP_NOTICE}\\n\", \"\"))\n self.airspaces.remove()\n self.airspacetext.remove()\n self.airspaces = None\n self.airspacetext = None\n self.ax.figure.canvas.mpl_disconnect(self.airspace_event)\n if value and len(airspaces) > 0:\n country_codes = [airspace.split(\" \")[-1] for airspace in airspaces]\n self.draw_airspaces(country_codes, range_km)\n\n def draw_airspaces(self, countries=[], range_km=None):\n \"\"\"\n Load and draw airspace data\n \"\"\"\n if not self.airspaces:\n airspaces = copy.deepcopy(get_airspaces(countries))\n if not airspaces:\n logging.error(\"Tried to draw airspaces without asp files.\")\n return\n\n for i, airspace in enumerate(airspaces):\n airspaces[i][\"polygon\"] = list(zip(*self.projtran(*list(zip(*airspace[\"polygon\"])))))\n map_polygon = Polygon([(self.llcrnrx, self.llcrnry), (self.urcrnrx, self.llcrnry),\n (self.urcrnrx, self.urcrnry), (self.llcrnrx, self.urcrnry)])\n airspaces = [airspace for airspace in airspaces if\n (not range_km or range_km[0] <= airspace[\"bottom\"] <= range_km[1]) and\n Polygon(airspace[\"polygon\"]).intersects(map_polygon)]\n if not airspaces:\n return\n\n if OPENAIP_NOTICE not in self.crs_text.get_text():\n self.crs_text.set_text(f\"{OPENAIP_NOTICE}\\n\" + self.crs_text.get_text())\n\n airspaces.sort(key=lambda x: (x[\"bottom\"], x[\"top\"] - x[\"bottom\"]))\n max_height = max(airspaces[-1][\"bottom\"], 0.001)\n cmap = get_cmap(\"Blues\")\n airspace_colors = [cmap(1 - airspaces[i][\"bottom\"] / max_height) for i in range(len(airspaces))]\n\n collection = PolyCollection([airspace[\"polygon\"] for airspace in airspaces], alpha=0.5, edgecolor=\"black\",\n zorder=5, facecolors=airspace_colors)\n collection.set_pickradius(0)\n self.airspaces = self.ax.add_collection(collection)\n self.airspacetext = self.ax.annotate(airspaces[0][\"name\"], xy=airspaces[0][\"polygon\"][0], xycoords=\"data\",\n bbox={\"boxstyle\": \"round\", \"facecolor\": \"w\",\n \"edgecolor\": \"0.5\", \"alpha\": 0.9}, zorder=7)\n self.airspacetext.set_visible(False)\n\n def update_text(index, xydata):\n self.airspacetext.xy = xydata\n self.airspacetext.set_position(xydata)\n self.airspacetext.set_text(\"\\n\".join([f\"{airspaces[i]['name']}, {airspaces[i]['bottom']} - \"\n f\"{airspaces[i]['top']}km\" for i in index[\"ind\"]]))\n highlight_cmap = get_cmap(\"YlGn\")\n for i in index[\"ind\"]:\n airspace_colors[i] = highlight_cmap(1 - airspaces[i][\"bottom\"] / max_height)\n self.airspaces.set_facecolor(airspace_colors)\n for i in index[\"ind\"]:\n airspace_colors[i] = cmap(1 - airspaces[i][\"bottom\"] / max_height)\n\n def on_move(event):\n if self.airspaces and event.inaxes == self.ax:\n cont, ind = self.airspaces.contains(event)\n if cont:\n update_text(ind, (event.xdata, event.ydata))\n self.airspacetext.set_visible(True)\n self.ax.figure.canvas.draw_idle()\n elif self.airspacetext.get_visible():\n self.airspacetext.set_visible(False)\n self.airspaces.set_facecolor(airspace_colors)\n self.ax.figure.canvas.draw_idle()\n\n self.airspace_event = self.ax.figure.canvas.mpl_connect('motion_notify_event', on_move)\n\n def draw_airports(self, port_type):\n \"\"\"\n Load and draw airports and their respective name on hover\n \"\"\"\n if not self.airports:\n airports = get_airports()\n if not airports:\n logging.error(\"Tried to draw airports but none were found. Try redownloading.\")\n return\n\n lons, lats = self.projtran(*zip(*[(float(airport[\"longitude_deg\"]),\n float(airport[\"latitude_deg\"])) for airport in airports]))\n for i, airport in enumerate(airports):\n airports[i][\"longitude_deg\"] = lons[i]\n airports[i][\"latitude_deg\"] = lats[i]\n\n airports = [airport for airport in airports if airport[\"type\"] in port_type and\n self.llcrnrx <= float(airport[\"longitude_deg\"]) <= self.urcrnrx and\n self.llcrnry <= float(airport[\"latitude_deg\"]) <= self.urcrnry]\n lons = [float(airport[\"longitude_deg\"]) for airport in airports]\n lats = [float(airport[\"latitude_deg\"]) for airport in airports]\n annotations = [airport[\"name\"] for airport in airports]\n if not airports:\n return\n\n if OURAIRPORTS_NOTICE not in self.crs_text.get_text():\n self.crs_text.set_text(f\"{OURAIRPORTS_NOTICE}\\n\" + self.crs_text.get_text())\n\n self.airports = self.ax.scatter(lons, lats, marker=\"o\", color=\"r\", linewidth=1, s=9, edgecolor=\"black\",\n zorder=6)\n self.airports.set_pickradius(1)\n self.airtext = self.ax.annotate(annotations[0], xy=(lons[0], lats[0]), xycoords=\"data\",\n bbox={\"boxstyle\": \"round\", \"facecolor\": \"w\",\n \"edgecolor\": \"0.5\", \"alpha\": 0.9}, zorder=8)\n self.airtext.set_visible(False)\n\n def update_text(index):\n pos = self.airports.get_offsets()[index[\"ind\"][0]]\n self.airtext.xy = pos\n self.airtext.set_position(pos)\n self.airtext.set_text(\"\\n\".join([annotations[i] for i in index[\"ind\"]]))\n\n def on_move(event):\n if self.airports and event.inaxes == self.ax:\n cont, ind = self.airports.contains(event)\n if cont:\n update_text(ind)\n self.airtext.set_visible(True)\n self.ax.figure.canvas.draw_idle()\n elif self.airtext.get_visible():\n self.airtext.set_visible(False)\n self.ax.figure.canvas.draw_idle()\n\n self.airports_event = self.ax.figure.canvas.mpl_connect('motion_notify_event', on_move)\n\n def set_fillcontinents_visible(self, visible=True, land_color=None,\n lake_color=None):\n \"\"\"\n Set the visibility of continent fillings.\n \"\"\"\n if land_color is not None:\n self.appearance[\"colour_land\"] = land_color\n if lake_color is not None:\n self.appearance[\"colour_water\"] = lake_color\n self.appearance[\"fill_continents\"] = visible\n\n if visible and self.map_continents is None:\n # zorder = 0 is necessary to paint over the filled continents with\n # scatter() for drawing the flight tracks and trajectories.\n # Curiously, plot() works fine without this setting, but scatter()\n # doesn't.\n self.map_continents = self.fillcontinents(color=self.appearance[\"colour_land\"],\n lake_color=self.appearance[\"colour_water\"],\n zorder=1)\n self.ax.figure.canvas.draw()\n elif not visible and self.map_continents is not None:\n # Remove current fills. They are stored as a list of polygon patches\n # in self.map_continents.\n for patch in self.map_continents:\n patch.remove()\n self.map_continents = None\n self.ax.figure.canvas.draw()\n elif visible and self.map_continents is not None:\n # Colours have changed: Remove the old fill and redraw.\n for patch in self.map_continents:\n patch.remove()\n self.map_continents = self.fillcontinents(color=self.appearance[\"colour_land\"],\n lake_color=self.appearance[\"colour_water\"],\n zorder=1)\n self.ax.figure.canvas.draw()\n\n def set_coastlines_visible(self, visible=True):\n \"\"\"\n Set the visibility of coastlines and country borders.\n \"\"\"\n self.appearance[\"draw_coastlines\"] = visible\n if visible and self.map_coastlines is None and self.map_countries is None:\n self.map_coastlines = self.drawcoastlines(zorder=3)\n self.map_countries = self.drawcountries(zorder=3)\n self.ax.figure.canvas.draw()\n elif not visible and self.map_coastlines is not None and self.map_countries is not None:\n self.map_coastlines.remove()\n self.map_countries.remove()\n del self.cntrysegs\n self.map_coastlines = None\n self.map_countries = None\n self.ax.figure.canvas.draw()\n\n def set_mapboundary_visible(self, visible=True, bg_color='#99ffff'):\n \"\"\"\n \"\"\"\n # TODO: This doesn't work. Removing the map background only makes sense\n # if there's a second image underneath this map. Maybe we should work\n # with alpha values instead.\n self.appearance[\"fill_waterbodies\"] = visible\n self.appearance[\"colour_water\"] = bg_color\n\n if not visible and self.map_boundary is not None:\n try:\n self.map_boundary.remove()\n except NotImplementedError as ex:\n logging.debug(\"%s\", ex)\n self.map_boundary = None\n self.ax.figure.canvas.draw()\n elif visible:\n self.map_boundary = self.drawmapboundary(fill_color=bg_color)\n self.ax.figure.canvas.draw()\n\n def update_with_coordinate_change(self, kwargs_update=None):\n \"\"\"\n Redraws the entire map. This is necessary after zoom/pan operations.\n\n Determines corner coordinates of the current axes, removes all items\n belonging the the current map and draws a new one by calling\n self.__init__().\n\n DRAWBACK of this approach is that the map coordinate system changes, as\n basemap always takes the lower left axis corner as (0,0). This means\n that all other objects on the matplotlib canvas (flight track, markers,\n ..) will be incorrectly placed after a redraw. Their coordinates need\n to be adjusted by 1) transforming their coordinates to lat/lon BEFORE\n the map is redrawn, 2) redrawing the map, 3) transforming the stored\n lat/lon coordinates to the new map coordinates.\n \"\"\"\n # Convert the current axis corners to lat/lon coordinates.\n axis = self.ax.axis()\n self.kwargs['llcrnrlon'], self.kwargs['llcrnrlat'] = \\\n self.__call__(axis[0], axis[2], inverse=True)\n self.kwargs['urcrnrlon'], self.kwargs['urcrnrlat'] = \\\n self.__call__(axis[1], axis[3], inverse=True)\n logging.debug(\"corner coordinates (lat/lon): ll(%.2f,%.2f), ur(%.2f,%.2f)\",\n self.kwargs['llcrnrlat'], self.kwargs['llcrnrlon'],\n self.kwargs['urcrnrlat'], self.kwargs['urcrnrlon'])\n\n if (self.kwargs.get(\"projection\") in [\"cyl\"] or\n self.kwargs.get(\"epsg\") in [\"4326\"]):\n # Latitudes in cylindrical projection need to be within -90..90.\n self.kwargs['llcrnrlat'] = max(self.kwargs['llcrnrlat'], -90)\n self.kwargs['urcrnrlat'] = max(self.kwargs['urcrnrlat'], -89)\n self.kwargs['llcrnrlat'] = min(self.kwargs['llcrnrlat'], 89)\n self.kwargs['urcrnrlat'] = min(self.kwargs['urcrnrlat'], 90)\n # Longitudes in cylindrical projection need to be within -360..540.\n self.kwargs[\"llcrnrlon\"] = max(self.kwargs[\"llcrnrlon\"], -360)\n self.kwargs[\"urcrnrlon\"] = max(self.kwargs[\"urcrnrlon\"], -359)\n self.kwargs[\"llcrnrlon\"] = min(self.kwargs[\"llcrnrlon\"], 539)\n self.kwargs[\"urcrnrlon\"] = min(self.kwargs[\"urcrnrlon\"], 540)\n\n # Remove the current map artists.\n grat_vis = self.appearance[\"draw_graticule\"]\n self.set_graticule_visible(False)\n self.appearance[\"draw_graticule\"] = grat_vis\n if self.map_coastlines is not None and (len(self.coastsegs) > 0 and len(self.coastsegs[0]) > 0):\n self.map_coastlines.remove()\n\n if self.image is not None:\n self.image.remove()\n self.image = None\n\n # Refer to Basemap.drawcountries() on how to remove country borders.\n # In addition to the matplotlib lines, the loaded country segment data\n # needs to be loaded. THE SAME NEEDS TO BE DONE WITH RIVERS ETC.\n if self.map_countries is not None:\n self.map_countries.remove()\n del self.cntrysegs\n\n # map_boundary is None for rectangular projections (basemap simply sets\n # the background colour).\n if self.map_boundary is not None:\n try:\n self.map_boundary.remove()\n except NotImplementedError as ex:\n logging.debug(\"%s\", ex)\n self.map_boundary = None\n\n cont_vis = self.appearance[\"fill_continents\"]\n self.set_fillcontinents_visible(False)\n self.appearance[\"fill_continents\"] = cont_vis\n\n # POSSIBILITY A): Call self.__init__ again with stored keywords.\n # Update kwargs if new parameters such as the map region have been\n # given.\n if kwargs_update:\n proj_keys = [\"epsg\", \"projection\"]\n if any(_x in kwargs_update for _x in proj_keys):\n for key in (_x for _x in proj_keys if _x in self.kwargs):\n del self.kwargs[key]\n self.kwargs.update(kwargs_update)\n self.__init__(**self.kwargs)\n\n # TODO: HOW TO MAKE THIS MORE EFFICIENT.\n # POSSIBILITY B): Only set the Basemap parameters that influence the\n # plot (corner lat/lon, x/y, width/height, ..) and re-define the\n # polygons that represent the coastlines etc. In Basemap, they are\n # defined in __init__(), at the very bottom (the code that comes\n # with the comments\n # >> read in coastline polygons, only keeping those that\n # >> intersect map boundary polygon.\n # ). Basemap only loads the coastline data that is actually displayed.\n # If we only change llcrnrlon etc. here and replot coastlines etc.,\n # the polygons and the map extent will remain the same.\n # However, it should be possible to make a map change WITHOUT changing\n # coordinates.\n #\n\n # self.llcrnrlon = llcrnrlon\n # self.llcrnrlat = llcrnrlat\n # self.urcrnrlon = urcrnrlon\n # self.urcrnrlat = urcrnrlat\n # self.llcrnrx = axis[0]\n # self.llcrnry = axis[2]\n # self.urcrnrx = axis[1]\n # self.urcrnry = axis[3]\n\n def imshow(self, X, **kwargs):\n \"\"\"\n Overloads basemap.imshow(). Deletes any existing image and\n redraws the figure after the new image has been plotted.\n \"\"\"\n if self.image is not None:\n self.image.remove()\n self.image = super(MapCanvas, self).imshow(X, zorder=2, **kwargs)\n self.ax.figure.canvas.draw()\n return self.image\n\n def gcpoints2(self, lon0, lat0, lon1, lat1, del_s=100., map_coords=True):\n \"\"\"\n The same as basemap.gcpoints(), but takes a distance interval del_s\n to space the points instead of a number of points.\n \"\"\"\n # use great circle formula for a perfect sphere.\n _, _, dist = self.gc.inv(lon0, lat0, lon1, lat1)\n npoints = int((dist + 0.5 * 1000. * del_s) / (1000. * del_s))\n lonlats = self.gc.npts(lon0, lat0, lon1, lat1, npoints)\n lons = [lon0]\n lats = [lat0]\n for lon, lat in lonlats:\n lons.append(lon)\n lats.append(lat)\n lons.append(lon1)\n lats.append(lat1)\n if map_coords:\n x, y = self(lons, lats)\n else:\n x, y = (lons, lats)\n return x, y\n\n def gcpoints_path(self, lons, lats, del_s=100., map_coords=True):\n \"\"\"\n Same as gcpoints2, but for an entire path, i.e. multiple\n line segments. lons and lats are lists of waypoint coordinates.\n \"\"\"\n # use great circle formula for a perfect sphere.\n assert len(lons) == len(lats)\n assert len(lons) > 1\n gclons = [lons[0]]\n gclats = [lats[0]]\n for i in range(len(lons) - 1):\n _, _, dist = self.gc.inv(lons[i], lats[i], lons[i + 1], lats[i + 1])\n npoints = int((dist + 0.5 * 1000. * del_s) / (1000. * del_s))\n lonlats = []\n if npoints > 0:\n lonlats = self.gc.npts(lons[i], lats[i], lons[i + 1], lats[i + 1], npoints)\n for lon, lat in lonlats:\n gclons.append(lon)\n gclats.append(lat)\n gclons.append(lons[i + 1])\n gclats.append(lats[i + 1])\n if self.projection == \"cyl\": # hack for wraparound\n lon_min, lon_max = self.llcrnrlon, self.urcrnrlon\n gclons = np.array(gclons)\n gclons[gclons < lon_min] += 360\n gclons[gclons > lon_max] -= 360\n idcs = np.where(abs(np.diff(gclons)) > 300)[0]\n gclons[idcs] = np.nan\n if map_coords:\n x, y = self(gclons, gclats)\n else:\n x, y = (gclons, gclats)\n return x, y\n\n def drawgreatcircle_path(self, lons, lats, del_s=100., **kwargs):\n \"\"\"\n \"\"\"\n x, y = self.gcpoints_path(lons, lats, del_s=del_s)\n return self.plot(x, y, **kwargs)\n\n\nclass SatelliteOverpassPatch(object):\n \"\"\"\n Represents a satellite overpass on the top view map (satellite\n track and, if available, swath).\n \"\"\"\n\n # TODO: Derive this class from some Matplotlib actor class? Or create\n # a new abstract base class for objects that can be drawn on the\n # map -- they all should provide methods remove(), update(),\n # etc. update() should automatically remap the object to new map\n # coordinates.\n def __init__(self, mapcanvas, segment):\n \"\"\"\n \"\"\"\n self.map = mapcanvas\n self.segment = segment\n # Filter those time elements that correspond to masked positions -- this\n # way the indexes in self.utc correspond to those in self.sat.\n # np.ma.getmaskarray is necessary as ..mask only returns a scalar\n # \"False\" if the array contains no masked entries.\n self.utc = segment[\"utc\"][~np.ma.getmaskarray(segment[\"satpos\"])[:, 0]]\n self.sat = np.ma.compress_rows(segment[\"satpos\"])\n self.sw_l = np.ma.compress_rows(segment[\"swath_left\"])\n self.sw_r = np.ma.compress_rows(segment[\"swath_right\"])\n self.trackline = None\n self.patch = None\n self.texts = []\n self.draw()\n\n def draw(self):\n \"\"\"\n Do the actual plotting of the patch.\n \"\"\"\n # Plot satellite track.\n sat = np.copy(self.sat)\n sat[:, 0], sat[:, 1] = self.map(sat[:, 0], sat[:, 1])\n self.trackline = self.map.plot(sat[:, 0], sat[:, 1], zorder=10,\n marker='+', markerfacecolor='g')\n\n # Plot polygon patch that represents the swath of the sensor.\n sw_l = self.sw_l\n sw_r = self.sw_r\n Path = mpath.Path\n pathdata = [(Path.MOVETO, self.map(sw_l[0, 0], sw_l[0, 1]))]\n for point in sw_l[1:]:\n pathdata.append((Path.LINETO, self.map(point[0], point[1])))\n for point in sw_r[::-1]:\n pathdata.append((Path.LINETO, self.map(point[0], point[1])))\n codes, verts = list(zip(*pathdata))\n path = mpl_pi.PathH(verts, codes, map=self.map)\n patch = mpatches.PathPatch(path, facecolor='yellow',\n edgecolor='yellow', alpha=0.4, zorder=10)\n self.patch = patch\n self.map.ax.add_patch(patch)\n\n # Draw text labels.\n self.texts.append(self.map.ax.text(sat[0, 0], sat[0, 1],\n self.utc[0].strftime(\"%H:%M:%S\"),\n zorder=10,\n bbox=dict(facecolor='white',\n alpha=0.5,\n edgecolor='none')))\n self.texts.append(self.map.ax.text(sat[-1, 0], sat[-1, 1],\n self.utc[-1].strftime(\"%H:%M:%S\"),\n zorder=10,\n bbox=dict(facecolor='white',\n alpha=0.5,\n edgecolor='none')))\n\n self.map.ax.figure.canvas.draw()\n\n def update(self):\n \"\"\"\n Removes the current plot of the patch and redraws the patch.\n This is necessary, for instance, when the map projection and/or\n extent has been changed.\n \"\"\"\n self.remove()\n self.draw()\n\n def remove(self):\n \"\"\"\n Remove this satellite patch from the map canvas.\n \"\"\"\n if self.trackline is not None:\n for element in self.trackline:\n element.remove()\n self.trackline = None\n if self.patch is not None:\n self.patch.remove()\n self.patch = None\n for element in self.texts:\n # Removal of text elements sometimes fails. I don't know why,\n # the plots look fine nevertheless.\n try:\n element.remove()\n except Exception as ex:\n logging.error(\"Wildcard exception caught: %s %s\", type(ex), ex)\n", "# -*- coding: utf-8 -*-\n\"\"\"\n\n mslib.msui.mpl_pathinteractor\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Interactive editing of Path objects on a Matplotlib canvas.\n\n This module provides the following classes:\n\n a) WaypointsPath and subclasses PathV, PathH and PathH-GC:\n Derivatives of matplotlib.Path, provide additional methods to\n insert and delete vertices and to find best insertion points for new\n vertices.\n\n b) PathInteractor and subclasses VPathInteractor and HPathInteractor:\n Classes that implement a path editor by binding matplotlib mouse events\n to a WaypointsPath object. Support for moving, inserting and deleting vertices.\n\n The code in this module is inspired by the matplotlib example 'path_editor.py'\n (http://matplotlib.sourceforge.net/examples/event_handling/path_editor.html).\n\n For more information on implementing animated graphics in matplotlib, see\n http://www.scipy.org/Cookbook/Matplotlib/Animations.\n\n\n This file is part of mss.\n\n :copyright: Copyright 2008-2014 Deutsches Zentrum fuer Luft- und Raumfahrt e.V.\n :copyright: Copyright 2011-2014 Marc Rautenhaus (mr)\n :copyright: Copyright 2016-2021 by the mss team, see AUTHORS.\n :license: APACHE-2.0, see LICENSE for details.\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 logging\nimport math\nimport numpy as np\nimport matplotlib.path as mpath\nimport matplotlib.patches as mpatches\nfrom PyQt5 import QtCore, QtWidgets\n\nfrom mslib.utils.coordinate import get_distance, find_location, latlon_points\nfrom mslib.utils.units import units\nfrom mslib.utils.thermolib import pressure2flightlevel\nfrom mslib.msui import flighttrack as ft\n\n\ndef distance_point_linesegment(p, l1, l2):\n \"\"\"Computes the distance between a point p and a line segment given by its\n endpoints l1 and l2.\n\n p, l1, l2 should be numpy arrays of length 2 representing [x,y].\n\n Based on the dot product formulation from\n 'Subject 1.02: How do I find the distance from a point to a line?'\n (from http://www.faqs.org/faqs/graphics/algorithms-faq/).\n\n Special case: The point p projects to an extension of the line segment.\n In this case, the distance between the point and the segment equals\n the distance between the point and the closest segment endpoint.\n \"\"\"\n # Compute the parameter r in the line formulation p* = l1 + r*(l2-l1).\n # p* is the point on the line at which (p-p*) and (l1-l2) form a right\n # angle.\n r = (np.dot(p - l1, l2 - l1) / np.linalg.norm(l2 - l1) ** 2)\n # If 0 < r < 1, we return the distance p-p*. If r > 1, p* is on the\n # forward extension of l1-l2, hence return the distance between\n # p and l2. If r < 0, return the distance p-l1.\n if r > 1:\n return np.linalg.norm(p - l2)\n elif r < 0:\n return np.linalg.norm(p - l1)\n else:\n p_on_line = l1 + r * (l2 - l1)\n return np.linalg.norm(p - p_on_line)\n\n\nclass WaypointsPath(mpath.Path):\n \"\"\"Derivative of matplotlib.Path that provides methods to insert and\n delete vertices.\n \"\"\"\n\n def delete_vertex(self, index):\n \"\"\"Remove the vertex at the given index from the list of vertices.\n \"\"\"\n # TODO: Should codes (MOVETO, LINETO) be modified here? relevant for\n # inserting/deleting first/last point.\n # Emulate pop() for ndarray:\n self.vertices = np.delete(self.vertices, index, axis=0)\n self.codes = np.delete(self.codes, index, axis=0)\n\n def insert_vertex(self, index, vertex, code):\n \"\"\"Insert a new vertex (a tuple x,y) with the given code (see\n matplotlib.Path) at the given index.\n \"\"\"\n self.vertices = np.insert(self.vertices, index,\n np.asarray(vertex, np.float_), axis=0)\n self.codes = np.insert(self.codes, index, code, axis=0)\n\n def index_of_closest_segment(self, x, y, eps=5):\n \"\"\"Find the index of the edge closest to the specified point at x,y.\n\n If the point is not within eps (in the same coordinates as x,y) of\n any edge in the path, the index of the closest end point is returned.\n \"\"\"\n # If only one point is stored in the list the best index to insert a\n # new point is after this point.\n if len(self.vertices) == 1:\n return 1\n\n # Compute the distance between the first point in the path and\n # the given point.\n point = np.array([x, y])\n min_index = 0\n min_distance = np.linalg.norm(point - self.vertices[0])\n\n # Loop over all line segments. If the distance between the given\n # point and the segment is smaller than a specified threshold AND\n # the distance is smaller than the currently smallest distance\n # then remember the current index.\n for i in range(len(self.vertices) - 1):\n l1 = self.vertices[i]\n l2 = self.vertices[i + 1]\n distance = distance_point_linesegment(point, l1, l2)\n if distance < eps and distance < min_distance:\n min_index = i + 1\n min_distance = distance\n\n # Compute the distance between the given point and the end point of\n # the path. Is it smaller than the currently smallest distance?\n distance = np.linalg.norm(point - self.vertices[-1])\n if distance < min_distance:\n min_index = len(self.vertices)\n\n return min_index\n\n def transform_waypoint(self, wps_list, index):\n \"\"\"Transform the waypoint at index <index> of wps_list to plot\n coordinates.\n\n wps_list is a list of <Waypoint> objects (obtained from\n WaypointsTableModel.allWaypointData()).\n\n NEEDS TO BE IMPLEMENTED IN DERIVED CLASSES.\n \"\"\"\n return (0, 0)\n\n def update_from_WaypointsTableModel(self, wps_model):\n \"\"\"\n \"\"\"\n Path = mpath.Path\n wps = wps_model.all_waypoint_data()\n pathdata = []\n # on a expired mscolab server wps is an empty list\n if len(wps) > 0:\n pathdata = [(Path.MOVETO, self.transform_waypoint(wps, 0))]\n for i, _ in enumerate(wps[1:]):\n pathdata.append((Path.LINETO, self.transform_waypoint(wps, i + 1)))\n\n codes, vertices = list(zip(*pathdata))\n self.codes = np.array(codes, dtype=np.uint8)\n self.vertices = np.array(vertices)\n\n\n#\n# CLASS PathV\n#\n\n\nclass PathV(WaypointsPath):\n \"\"\"Class to represent a vertical flight profile path.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"The constructor required the additional keyword 'numintpoints':\n\n numintpoints -- number of intermediate interpolation points. The entire\n flight track will be interpolated to this number of\n points.\n \"\"\"\n self.numintpoints = kwargs.pop(\"numintpoints\")\n super().__init__(*args, **kwargs)\n\n def update_from_WaypointsTableModel(self, wps_model):\n \"\"\"Extended version of the corresponding WaypointsPath method.\n\n The idea is to generate a field 'intermediate_indexes' that stores\n the indexes of the waypoints in the field of the intermediate\n great circle points generated by the flight track model, then\n to use these great circle indexes as x-coordinates for the vertical\n section. This means: If ngc_points are created by\n wps_model.intermediatePoints(), the waypoints are mapped to the\n range 0..ngc_points.\n\n NOTE: If wps_model only contains two equal waypoints,\n intermediate_indexes will NOT span the entire vertical section\n plot (this is intentional, as a flight with two equal\n waypoints makes no sense).\n \"\"\"\n # Compute intermediate points.\n lats, lons, times = wps_model.intermediate_points(\n numpoints=self.numintpoints, connection=\"greatcircle\")\n\n if lats is not None:\n # Determine indices of waypoints in list of intermediate points.\n # Store these indices.\n waypoints = [[wp.lat, wp.lon] for wp in wps_model.all_waypoint_data()]\n intermediate_indexes = []\n ipoint = 0\n for i, (lat, lon) in enumerate(zip(lats, lons)):\n if abs(lat - waypoints[ipoint][0]) < 1E-10 and abs(lon - waypoints[ipoint][1]) < 1E-10:\n intermediate_indexes.append(i)\n ipoint += 1\n if ipoint >= len(waypoints):\n break\n\n self.intermediate_indexes = intermediate_indexes\n self.ilats = lats\n self.ilons = lons\n self.itimes = times\n\n # Call super method.\n super().update_from_WaypointsTableModel(wps_model)\n\n def transform_waypoint(self, wps_list, index):\n \"\"\"Returns the x-index of the waypoint and its pressure.\n \"\"\"\n return (self.intermediate_indexes[index], wps_list[index].pressure)\n\n\n#\n# CLASS PathH, PathH_GC\n#\n\n\nclass PathH(WaypointsPath):\n \"\"\"Class to represent a horizontal flight track path, waypoints connected\n by linear line segments.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"The constructor required the additional keyword 'map' to transform\n vertex cooredinates between lat/lon and projection coordinates.\n \"\"\"\n self.map = kwargs.pop(\"map\")\n super().__init__(*args, **kwargs)\n\n def transform_waypoint(self, wps_list, index):\n \"\"\"Transform lon/lat to projection coordinates.\n \"\"\"\n return self.map(wps_list[index].lon, wps_list[index].lat)\n\n\nclass PathH_GC(PathH):\n \"\"\"Class to represent a horizontal flight track path, waypoints connected\n by great circle segments.\n\n Derives from PathH.\n\n Provides to kinds of vertex data: (1) Waypoint vertices (wp_vertices) and\n (2) intermediate great circle vertices (vertices).\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.wp_codes = np.array([], dtype=np.uint8)\n self.wp_vertices = np.array([])\n\n def update_from_WaypointsTableModel(self, wps_model):\n \"\"\"Get waypoint coordinates from flight track model, get\n intermediate great circle vertices from map instance.\n \"\"\"\n Path = mpath.Path\n\n # Waypoint coordinates.\n wps = wps_model.all_waypoint_data()\n if len(wps) > 0:\n pathdata = [(Path.MOVETO, self.transform_waypoint(wps, 0))]\n for i in range(len(wps[1:])):\n pathdata.append((Path.LINETO, self.transform_waypoint(wps, i + 1)))\n wp_codes, wp_vertices = list(zip(*pathdata))\n self.wp_codes = np.array(wp_codes, dtype=np.uint8)\n self.wp_vertices = np.array(wp_vertices)\n\n # Coordinates of intermediate great circle points.\n lons, lats = list(zip(*[(wp.lon, wp.lat) for wp in wps]))\n x, y = self.map.gcpoints_path(lons, lats)\n\n if len(x) > 0:\n pathdata = [(Path.MOVETO, (x[0], y[0]))]\n for i in range(len(x[1:])):\n pathdata.append((Path.LINETO, (x[i + 1], y[i + 1])))\n codes, vertices = list(zip(*pathdata))\n self.codes = np.array(codes, dtype=np.uint8)\n self.vertices = np.array(vertices)\n\n def index_of_closest_segment(self, x, y, eps=5):\n \"\"\"Find the index of the edge closest to the specified point at x,y.\n\n If the point is not within eps (in the same coordinates as x,y) of\n any edge in the path, the index of the closest end point is returned.\n \"\"\"\n # Determine the index of the great circle vertex that is closest to the\n # given point.\n gcvertex_index = super().index_of_closest_segment(x, y, eps)\n\n # Determine the waypoint index that corresponds to the great circle\n # index. If the best index is to append the waypoint to the end of\n # the flight track, directly return this index.\n if gcvertex_index == len(self.vertices):\n return len(self.wp_vertices)\n # Otherwise iterate through the list of great circle points and remember\n # the index of the last \"real\" waypoint that was encountered in this\n # list.\n i = 0 # index for great circle points\n j = 0 # index for waypoints\n wp_vertex = self.wp_vertices[j]\n while (i < gcvertex_index):\n vertex = self.vertices[i]\n if vertex[0] == wp_vertex[0] and vertex[1] == wp_vertex[1]:\n j += 1\n wp_vertex = self.wp_vertices[j]\n i += 1\n return j\n\n\n#\n# CLASS PathInteractor\n#\n\n\nclass PathInteractor(QtCore.QObject):\n \"\"\"An interactive matplotlib path editor. Allows vertices of a path patch\n to be interactively picked and moved around.\n\n Superclass for the path editors used by the top and side views of the\n Mission Support System.\n \"\"\"\n\n showverts = True # show the vertices of the path patch\n epsilon = 12\n\n # picking points\n\n def __init__(self, ax=None, waypoints=None, mplpath=None,\n facecolor='blue', edgecolor='yellow',\n linecolor='blue', markerfacecolor='red',\n marker='o', label_waypoints=True):\n \"\"\"The constructor initializes the path patches, overlying line\n plot and connects matplotlib signals.\n\n Arguments:\n ax -- matplotlib.Axes object into which the path should be drawn.\n waypoints -- flighttrack.WaypointsModel instance.\n mplpath -- matplotlib.path.Path instance\n facecolor -- facecolor of the patch\n edgecolor -- edgecolor of the patch\n linecolor -- color of the line plotted above the patch edges\n markerfacecolor -- color of the markers that represent the waypoints\n marker -- symbol of the markers that represent the waypoints, see\n matplotlib plot() or scatter() routines for more information.\n label_waypoints -- put labels with the waypoint numbers on the waypoints.\n \"\"\"\n QtCore.QObject.__init__(self)\n self.waypoints_model = None\n self.background = None\n self._ind = None # the active vertex\n\n # Create a PathPatch representing the interactively editable path\n # (vertical profile or horizontal flight track in subclasses).\n path = mplpath\n pathpatch = mpatches.PathPatch(path, facecolor=facecolor,\n edgecolor=edgecolor, alpha=0.15)\n ax.add_patch(pathpatch)\n\n self.ax = ax\n self.path = path\n self.pathpatch = pathpatch\n self.pathpatch.set_animated(True) # ensure correct redrawing\n\n # Draw the line representing flight track or profile (correct\n # vertices handling for the line needs to be ensured in subclasses).\n x, y = list(zip(*self.pathpatch.get_path().vertices))\n self.line, = self.ax.plot(x, y, color=linecolor,\n marker=marker, linewidth=2,\n markerfacecolor=markerfacecolor,\n animated=True)\n\n # List to accomodate waypoint labels.\n self.wp_labels = []\n self.label_waypoints = label_waypoints\n\n # Connect mpl events to handler routines: mouse movements and picks.\n canvas = self.ax.figure.canvas\n canvas.mpl_connect('draw_event', self.draw_callback)\n self.canvas = canvas\n\n # Set the waypoints model, connect to the change() signals of the model\n # and redraw the figure.\n self.set_waypoints_model(waypoints)\n\n def set_waypoints_model(self, waypoints):\n \"\"\"Change the underlying waypoints data structure. Disconnect change()\n signals of an already existing model and connect to the new model.\n Redraw the map.\n \"\"\"\n # If a model exists, disconnect from the old change() signals.\n wpm = self.waypoints_model\n if wpm:\n wpm.dataChanged.disconnect(self.qt_data_changed_listener)\n wpm.rowsInserted.disconnect(self.qt_insert_remove_point_listener)\n wpm.rowsRemoved.disconnect(self.qt_insert_remove_point_listener)\n # Set the new waypoints model.\n self.waypoints_model = waypoints\n # Connect to the new model's signals.\n wpm = self.waypoints_model\n wpm.dataChanged.connect(self.qt_data_changed_listener)\n wpm.rowsInserted.connect(self.qt_insert_remove_point_listener)\n wpm.rowsRemoved.connect(self.qt_insert_remove_point_listener)\n # Redraw.\n self.pathpatch.get_path().update_from_WaypointsTableModel(wpm)\n self.redraw_figure()\n\n def qt_insert_remove_point_listener(self, index, first, last):\n \"\"\"Listens to rowsInserted() and rowsRemoved() signals emitted\n by the flight track data model. The view can thus react to\n data changes induced by another view (table, side view).\n \"\"\"\n self.pathpatch.get_path().update_from_WaypointsTableModel(self.waypoints_model)\n self.redraw_figure()\n\n def qt_data_changed_listener(self, index1, index2):\n \"\"\"Listens to dataChanged() signals emitted by the flight track\n data model. The view can thus react to data changes induced\n by another view (table, top view).\n \"\"\"\n # REIMPLEMENT IN SUBCLASSES.\n pass\n\n def draw_callback(self, event):\n \"\"\"Called when the figure is redrawn. Stores background data (for later\n restoration) and draws artists.\n \"\"\"\n self.background = self.canvas.copy_from_bbox(self.ax.bbox)\n try:\n # TODO review\n self.ax.draw_artist(self.pathpatch)\n except ValueError as ex:\n # When using Matplotlib 1.2, \"ValueError: Invalid codes array.\"\n # occurs. The error occurs in Matplotlib's backend_agg.py/draw_path()\n # function. However, when I print the codes array in that function,\n # it looks fine -- correct length and correct codes. I can't figure\n # out why that error occurs.. (mr, 2013Feb08).\n logging.error(\"%s %s\", ex, type(ex))\n self.ax.draw_artist(self.line)\n for t in self.wp_labels:\n self.ax.draw_artist(t)\n # The blit() method makes problems (distorted figure background). However,\n # I don't see why it is needed -- everything seems to work without this line.\n # (see infos on http://www.scipy.org/Cookbook/Matplotlib/Animations).\n # self.canvas.blit(self.ax.bbox)\n\n def get_ind_under_point(self, event):\n \"\"\"Get the index of the waypoint vertex under the point\n specified by event within epsilon tolerance.\n\n Uses display coordinates.\n If no waypoint vertex is found, None is returned.\n \"\"\"\n xy = np.asarray(self.pathpatch.get_path().vertices)\n xyt = self.pathpatch.get_transform().transform(xy)\n xt, yt = xyt[:, 0], xyt[:, 1]\n d = np.hypot(xt - event.x, yt - event.y)\n ind = d.argmin()\n if d[ind] >= self.epsilon:\n ind = None\n return ind\n\n def button_press_callback(self, event):\n \"\"\"Called whenever a mouse button is pressed. Determines the index of\n the vertex closest to the click, as long as a vertex is within\n epsilon tolerance of the click.\n \"\"\"\n if not self.showverts:\n return\n if event.inaxes is None:\n return\n if event.button != 1:\n return\n self._ind = self.get_ind_under_point(event)\n\n def set_vertices_visible(self, showverts=True):\n \"\"\"Set the visibility of path vertices (the line plot).\n \"\"\"\n self.showverts = showverts\n self.line.set_visible(self.showverts)\n for t in self.wp_labels:\n t.set_visible(showverts and self.label_waypoints)\n if not self.showverts:\n self._ind = None\n self.canvas.draw()\n\n def set_patch_visible(self, showpatch=True):\n \"\"\"Set the visibility of path patch (the area).\n \"\"\"\n self.pathpatch.set_visible(showpatch)\n self.canvas.draw()\n\n def set_labels_visible(self, visible=True):\n \"\"\"Set the visibility of the waypoint labels.\n \"\"\"\n self.label_waypoints = visible\n for t in self.wp_labels:\n t.set_visible(self.showverts and self.label_waypoints)\n self.canvas.draw()\n\n def redraw_path(self, vertices=None):\n \"\"\"Redraw the matplotlib artists that represent the flight track\n (path patch and line).\n\n If vertices are specified, they will be applied to the graphics\n output. Otherwise the vertex array obtained from the path patch\n will be used.\n \"\"\"\n if vertices is None:\n vertices = self.pathpatch.get_path().vertices\n self.line.set_data(list(zip(*vertices)))\n\n # Draw waypoint labels.\n for wp in self.wp_labels:\n wp.remove()\n self.wp_labels = [] # remove doesn't seem to be necessary\n x, y = list(zip(*vertices))\n wpd = self.waypoints_model.all_waypoint_data()\n for i in range(len(wpd)):\n textlabel = f\"{str(i):} \"\n if wpd[i].location != \"\":\n textlabel = f\"{wpd[i].location:} \"\n t = self.ax.text(x[i],\n y[i],\n textlabel,\n bbox=dict(boxstyle=\"round\",\n facecolor=\"white\",\n alpha=0.5,\n edgecolor=\"none\"),\n fontweight=\"bold\",\n zorder=4,\n rotation=90,\n animated=True,\n clip_on=True,\n visible=self.showverts and self.label_waypoints)\n self.wp_labels.append(t)\n\n if self.background:\n self.canvas.restore_region(self.background)\n try:\n self.ax.draw_artist(self.pathpatch)\n except ValueError as error:\n logging.error(\"ValueError Exception %s\", error)\n self.ax.draw_artist(self.line)\n for t in self.wp_labels:\n self.ax.draw_artist(t)\n self.canvas.blit(self.ax.bbox)\n\n redraw_figure = redraw_path\n\n def confirm_delete_waypoint(self, row):\n \"\"\"Open a QMessageBox and ask the user if he really wants to\n delete the waypoint at index <row>.\n\n Returns TRUE if the user confirms the deletion.\n\n If the flight track consists of only two points deleting a waypoint\n is not possible. In this case the user is informed correspondingly.\n \"\"\"\n wps = self.waypoints_model.all_waypoint_data()\n if len(wps) < 3:\n QtWidgets.QMessageBox.warning(\n None, \"Remove waypoint\",\n \"Cannot remove waypoint, the flight track needs to consist \"\n \"of at least two points.\")\n return False\n else:\n wp = wps[row]\n return QtWidgets.QMessageBox.question(\n None, \"Remove waypoint\",\n f\"Remove waypoint no.{row:d} at {wp.lat:.2f}/{wp.lon:.2f}, flightlevel {wp.flightlevel:.2f}?\",\n QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) == QtWidgets.QMessageBox.Yes\n\n def set_path_color(self, line_color=None, marker_facecolor=None,\n patch_facecolor=None):\n \"\"\"Set the color of the path patch elements.\n\n Arguments (options):\n line_color -- color of the path line\n marker_facecolor -- color of the waypoints\n patch_facecolor -- color of the patch covering the path area\n \"\"\"\n if line_color is not None:\n self.line.set_color(line_color)\n if marker_facecolor is not None:\n self.line.set_markerfacecolor(marker_facecolor)\n if patch_facecolor is not None:\n self.pathpatch.set_facecolor(patch_facecolor)\n\n\n#\n# CLASS VPathInteractor\n#\n\n\nclass VPathInteractor(PathInteractor):\n \"\"\"Subclass of PathInteractor that implements an interactively editable\n vertical profile of the flight track.\n \"\"\"\n signal_get_vsec = QtCore.Signal(name=\"get_vsec\")\n\n def __init__(self, ax, waypoints, redraw_xaxis=None, clear_figure=None, numintpoints=101):\n \"\"\"Constructor passes a PathV instance its parent.\n\n Arguments:\n ax -- matplotlib.Axes object into which the path should be drawn.\n waypoints -- flighttrack.WaypointsModel instance.\n numintpoints -- number of intermediate interpolation points. The entire\n flight track will be interpolated to this number of\n points.\n redrawXAxis -- callback function to redraw the x-axis on path changes.\n \"\"\"\n self.numintpoints = numintpoints\n self.redraw_xaxis = redraw_xaxis\n self.clear_figure = clear_figure\n super().__init__(\n ax=ax, waypoints=waypoints, mplpath=PathV([[0, 0]], numintpoints=numintpoints))\n\n def get_num_interpolation_points(self):\n return self.numintpoints\n\n def redraw_figure(self):\n \"\"\"For the side view, changes in the horizontal position of a waypoint\n (including moved waypoints, new or deleted waypoints) make a complete\n redraw of the figure necessary.\n\n Calls the callback function 'redrawXAxis()'.\n \"\"\"\n self.redraw_path()\n # emit signal to redraw map\n self.signal_get_vsec.emit()\n if self.clear_figure() is not None:\n self.clear_figure()\n\n if self.redraw_xaxis is not None:\n try:\n self.redraw_xaxis(self.path.ilats, self.path.ilons, self.path.itimes)\n except AttributeError as err:\n logging.debug(\"%s\" % err)\n self.ax.figure.canvas.draw()\n\n def button_release_delete_callback(self, event):\n \"\"\"Called whenever a mouse button is released.\n \"\"\"\n if not self.showverts or event.button != 1:\n return\n\n if self._ind is not None:\n if self.confirm_delete_waypoint(self._ind):\n # removeRows() will trigger a signal that will redraw the path.\n self.waypoints_model.removeRows(self._ind)\n self._ind = None\n\n def button_release_insert_callback(self, event):\n \"\"\"Called whenever a mouse button is released.\n\n From the click event's coordinates, best_index is calculated as\n the index of a vertex whose x coordinate > clicked x coordinate.\n This is the position where the waypoint is to be inserted.\n\n 'lat' and 'lon' are calculated as an average of each of the first waypoint\n in left and right neighbourhood of inserted waypoint.\n\n The coordinates are checked against \"locations\" defined in mss' config.\n\n A new waypoint with the coordinates, and name is inserted into the waypoints_model.\n \"\"\"\n if not self.showverts or event.button != 1 or event.inaxes is None:\n return\n y = event.ydata\n wpm = self.waypoints_model\n flightlevel = float(pressure2flightlevel(y * units.Pa).magnitude)\n [lat, lon], best_index = self.get_lat_lon(event)\n loc = find_location(lat, lon) # skipped tolerance which uses appropriate_epsilon_km\n if loc is not None:\n (lat, lon), location = loc\n else:\n location = \"\"\n new_wp = ft.Waypoint(lat, lon, flightlevel, location=location)\n wpm.insertRows(best_index, rows=1, waypoints=[new_wp])\n self.redraw_figure()\n\n self._ind = None\n\n def get_lat_lon(self, event):\n x = event.xdata\n wpm = self.waypoints_model\n vertices = self.pathpatch.get_path().vertices\n best_index = 1\n # if x axis has increasing coordinates\n if vertices[-1, 0] > vertices[0, 0]:\n for index, vertex in enumerate(vertices):\n if x >= vertex[0]:\n best_index = index + 1\n # if x axis has decreasing coordinates\n else:\n for index, vertex in enumerate(vertices):\n if x <= vertex[0]:\n best_index = index + 1\n # number of subcoordinates is determined by difference in x coordinates\n number_of_intermediate_points = math.floor(vertices[best_index, 0] - vertices[best_index - 1, 0])\n vert_xs, vert_ys = latlon_points(\n vertices[best_index - 1, 0], vertices[best_index - 1, 1],\n vertices[best_index, 0], vertices[best_index, 1],\n number_of_intermediate_points, connection=\"linear\")\n lats, lons = latlon_points(\n wpm.waypoint_data(best_index - 1).lat, wpm.waypoint_data(best_index - 1).lon,\n wpm.waypoint_data(best_index).lat, wpm.waypoint_data(best_index).lon,\n number_of_intermediate_points, connection=\"greatcircle\")\n\n # best_index1 is the best index among the intermediate coordinates to fit the hovered point\n # if x axis has increasing coordinates\n best_index1 = np.argmin(abs(vert_xs - x))\n # depends if best_index1 or best_index1 - 1 on closeness to left or right neighbourhood\n return (lats[best_index1], lons[best_index1]), best_index\n\n def button_release_move_callback(self, event):\n \"\"\"Called whenever a mouse button is released.\n \"\"\"\n if not self.showverts or event.button != 1:\n return\n\n if self._ind is not None:\n # Submit the new pressure (the only value that can be edited\n # in the side view) to the data model.\n vertices = self.pathpatch.get_path().vertices\n pressure = vertices[self._ind, 1]\n # http://doc.trolltech.com/4.3/qabstractitemmodel.html#createIndex\n qt_index = self.waypoints_model.createIndex(self._ind, ft.PRESSURE)\n # NOTE: QVariant cannot handle numpy.float64 types, hence convert\n # to float().\n self.waypoints_model.setData(qt_index, QtCore.QVariant(float(pressure / 100.)))\n\n self._ind = None\n\n def motion_notify_callback(self, event):\n \"\"\"Called on mouse movement. Redraws the path if a vertex has been\n picked and is being dragged.\n\n In the side view, the horizontal position of a waypoint is locked.\n Hence, points can only be moved in the vertical direction (y position\n in this view).\n \"\"\"\n if not self.showverts or self._ind is None or event.inaxes is None or event.button != 1:\n return\n vertices = self.pathpatch.get_path().vertices\n # Set the new y position of the vertex to event.ydata. Keep the\n # x coordinate.\n vertices[self._ind] = vertices[self._ind, 0], event.ydata\n self.redraw_path(vertices)\n\n def qt_data_changed_listener(self, index1, index2):\n \"\"\"Listens to dataChanged() signals emitted by the flight track\n data model. The side view can thus react to data changes\n induced by another view (table, top view).\n \"\"\"\n # If the altitude of a point has changed, only the plotted flight\n # profile needs to be redrawn (redraw_path()). If the horizontal\n # position of a waypoint has changed, the entire figure needs to be\n # redrawn, as this affects the x-position of all points.\n self.pathpatch.get_path().update_from_WaypointsTableModel(self.waypoints_model)\n if index1.column() in [ft.FLIGHTLEVEL, ft.PRESSURE, ft.LOCATION]:\n self.redraw_path(self.pathpatch.get_path().vertices)\n elif index1.column() in [ft.LAT, ft.LON]:\n self.redraw_figure()\n elif index1.column() in [ft.TIME_UTC]:\n if self.redraw_xaxis is not None:\n self.redraw_xaxis(self.path.ilats, self.path.ilons, self.path.itimes)\n\n\nclass LPathInteractor(PathInteractor):\n \"\"\"\n Subclass of PathInteractor that implements a non interactive linear profile of the flight track.\n \"\"\"\n signal_get_lsec = QtCore.Signal(name=\"get_lsec\")\n\n def __init__(self, ax, waypoints, redraw_xaxis=None, clear_figure=None, numintpoints=101):\n \"\"\"Constructor passes a PathV instance its parent.\n\n Arguments:\n ax -- matplotlib.Axes object into which the path should be drawn.\n waypoints -- flighttrack.WaypointsModel instance.\n numintpoints -- number of intermediate interpolation points. The entire\n flight track will be interpolated to this number of\n points.\n redrawXAxis -- callback function to redraw the x-axis on path changes.\n \"\"\"\n self.numintpoints = numintpoints\n self.clear_figure = clear_figure\n self.redraw_xaxis = redraw_xaxis\n super().__init__(\n ax=ax, waypoints=waypoints, mplpath=PathV([[0, 0]], numintpoints=numintpoints))\n\n def get_num_interpolation_points(self):\n return self.numintpoints\n\n def redraw_figure(self):\n \"\"\"For the linear view, changes in the horizontal or vertical position of a waypoint\n (including moved waypoints, new or deleted waypoints) make a complete\n redraw of the figure necessary.\n \"\"\"\n # emit signal to redraw map\n self.redraw_xaxis()\n self.signal_get_lsec.emit()\n\n def redraw_path(self, vertices=None):\n \"\"\"Skip redrawing paths for LSec\n \"\"\"\n pass\n\n def draw_callback(self, event):\n \"\"\"Skip drawing paths for LSec\n \"\"\"\n pass\n\n def get_lat_lon(self, event):\n x = event.xdata\n wpm = self.waypoints_model\n vertices = self.pathpatch.get_path().vertices\n best_index = 1\n # if x axis has increasing coordinates\n if vertices[-1, 0] > vertices[0, 0]:\n for index, vertex in enumerate(vertices):\n if x >= vertex[0]:\n best_index = index + 1\n # if x axis has decreasing coordinates\n else:\n for index, vertex in enumerate(vertices):\n if x <= vertex[0]:\n best_index = index + 1\n # number of subcoordinates is determined by difference in x coordinates\n number_of_intermediate_points = int(abs(vertices[best_index, 0] - vertices[best_index - 1, 0]))\n vert_xs, vert_ys = latlon_points(\n vertices[best_index - 1, 0], vertices[best_index - 1, 1],\n vertices[best_index, 0], vertices[best_index, 1],\n number_of_intermediate_points, connection=\"linear\")\n lats, lons = latlon_points(\n wpm.waypoint_data(best_index - 1).lat, wpm.waypoint_data(best_index - 1).lon,\n wpm.waypoint_data(best_index).lat, wpm.waypoint_data(best_index).lon,\n number_of_intermediate_points, connection=\"greatcircle\")\n alts = np.linspace(wpm.waypoint_data(best_index - 1).flightlevel,\n wpm.waypoint_data(best_index).flightlevel, number_of_intermediate_points)\n\n best_index1 = np.argmin(abs(vert_xs - x))\n # depends if best_index1 or best_index1 - 1 on closeness to left or right neighbourhood\n return (lats[best_index1], lons[best_index1], alts[best_index1]), best_index\n\n def qt_data_changed_listener(self, index1, index2):\n \"\"\"Listens to dataChanged() signals emitted by the flight track\n data model. The linear view can thus react to data changes\n induced by another view (table, top view, side view).\n \"\"\"\n self.pathpatch.get_path().update_from_WaypointsTableModel(self.waypoints_model)\n self.redraw_figure()\n\n#\n# CLASS HPathInteractor\n#\n\n\nclass HPathInteractor(PathInteractor):\n \"\"\"Subclass of PathInteractor that implements an interactively editable\n horizontal flight track. Waypoints are connected with great circles.\n \"\"\"\n\n def __init__(self, mplmap, waypoints,\n linecolor='blue', markerfacecolor='red', show_marker=True,\n label_waypoints=True):\n \"\"\"Constructor passes a PathH_GC instance its parent (horizontal path\n with waypoints connected with great circles).\n\n Arguments:\n mplmap -- mpl_map.MapCanvas instance into which the path should be drawn.\n waypoints -- flighttrack.WaypointsModel instance.\n \"\"\"\n self.map = mplmap\n self.wp_scatter = None\n self.markerfacecolor = markerfacecolor\n self.tangent_lines = None\n self.show_tangent_points = False\n self.solar_lines = None\n self.show_marker = show_marker\n self.show_solar_angle = None\n self.remote_sensing = None\n super().__init__(\n ax=mplmap.ax, waypoints=waypoints,\n mplpath=PathH_GC([[0, 0]], map=mplmap),\n facecolor='none', edgecolor='none', linecolor=linecolor,\n markerfacecolor=markerfacecolor, marker='',\n label_waypoints=label_waypoints)\n\n def appropriate_epsilon(self, px=5):\n \"\"\"Determine an epsilon value appropriate for the current projection and\n figure size.\n\n The epsilon value gives the distance required in map projection\n coordinates that corresponds to approximately px Pixels in screen\n coordinates. The value can be used to find the line/point that is\n closest to a click while discarding clicks that are too far away\n from any geometry feature.\n \"\"\"\n # (bounds = left, bottom, width, height)\n ax_bounds = self.ax.bbox.bounds\n width = int(round(ax_bounds[2]))\n map_delta_x = np.hypot(self.map.llcrnry - self.map.urcrnry, self.map.llcrnrx - self.map.urcrnrx)\n map_coords_per_px_x = map_delta_x / width\n return map_coords_per_px_x * px\n\n def appropriate_epsilon_km(self, px=5):\n \"\"\"Determine an epsilon value appropriate for the current projection and\n figure size.\n\n The epsilon value gives the distance required in map projection\n coordinates that corresponds to approximately px Pixels in screen\n coordinates. The value can be used to find the line/point that is\n closest to a click while discarding clicks that are too far away\n from any geometry feature.\n \"\"\"\n # (bounds = left, bottom, width, height)\n ax_bounds = self.ax.bbox.bounds\n diagonal = math.hypot(round(ax_bounds[2]), round(ax_bounds[3]))\n map_delta = get_distance(self.map.llcrnrlat, self.map.llcrnrlon, self.map.urcrnrlat, self.map.urcrnrlon)\n km_per_px = map_delta / diagonal\n\n return km_per_px * px\n\n def get_lat_lon(self, event):\n return self.map(event.xdata, event.ydata, inverse=True)[::-1]\n\n def button_release_insert_callback(self, event):\n \"\"\"Called whenever a mouse button is released.\n\n From the click event's coordinates, best_index is calculated if it can be optimally fit\n as a prior waypoint in the path.\n\n A vertex with same coordinates is inserted into the path in canvas.\n\n The coordinates are checked against \"locations\" defined in mss' config.\n\n A new waypoint with the coordinates, and name is inserted into the waypoints_model.\n \"\"\"\n if not self.showverts or event.button != 1 or event.inaxes is None:\n return\n\n # Get position for new vertex.\n x, y = event.xdata, event.ydata\n best_index = self.pathpatch.get_path().index_of_closest_segment(\n x, y, eps=self.appropriate_epsilon())\n logging.debug(\"TopView insert point: clicked at (%f, %f), \"\n \"best index: %d\", x, y, best_index)\n self.pathpatch.get_path().insert_vertex(best_index, [x, y], WaypointsPath.LINETO)\n\n lon, lat = self.map(x, y, inverse=True)\n loc = find_location(lat, lon, tolerance=self.appropriate_epsilon_km(px=15))\n if loc is not None:\n (lat, lon), location = loc\n else:\n location = \"\"\n wpm = self.waypoints_model\n if len(wpm.all_waypoint_data()) > 0 and 0 < best_index <= len(wpm.all_waypoint_data()):\n flightlevel = wpm.waypoint_data(best_index - 1).flightlevel\n elif len(wpm.all_waypoint_data()) > 0 and best_index == 0:\n flightlevel = wpm.waypoint_data(0).flightlevel\n else:\n logging.error(\"Cannot copy flightlevel. best_index: %s, len: %s\",\n best_index, len(wpm.all_waypoint_data()))\n flightlevel = 0\n new_wp = ft.Waypoint(lat, lon, flightlevel, location=location)\n wpm.insertRows(best_index, rows=1, waypoints=[new_wp])\n self.redraw_path()\n\n self._ind = None\n\n def button_release_move_callback(self, event):\n \"\"\"Called whenever a mouse button is released.\n \"\"\"\n if not self.showverts or event.button != 1 or self._ind is None:\n return\n\n # Submit the new position to the data model.\n vertices = self.pathpatch.get_path().wp_vertices\n lon, lat = self.map(vertices[self._ind][0], vertices[self._ind][1],\n inverse=True)\n loc = find_location(lat, lon, tolerance=self.appropriate_epsilon_km(px=15))\n if loc is not None:\n lat, lon = loc[0]\n self.waypoints_model.setData(\n self.waypoints_model.createIndex(self._ind, ft.LAT), QtCore.QVariant(lat), update=False)\n self.waypoints_model.setData(\n self.waypoints_model.createIndex(self._ind, ft.LON), QtCore.QVariant(lon))\n\n self._ind = None\n\n def button_release_delete_callback(self, event):\n \"\"\"Called whenever a mouse button is released.\n \"\"\"\n if not self.showverts or event.button != 1:\n return\n\n if self._ind is not None and self.confirm_delete_waypoint(self._ind):\n # removeRows() will trigger a signal that will redraw the path.\n self.waypoints_model.removeRows(self._ind)\n\n self._ind = None\n\n def motion_notify_callback(self, event):\n \"\"\"Called on mouse movement. Redraws the path if a vertex has been\n picked and dragged.\n \"\"\"\n if not self.showverts:\n return\n if self._ind is None:\n return\n if event.inaxes is None:\n return\n if event.button != 1:\n return\n wp_vertices = self.pathpatch.get_path().wp_vertices\n wp_vertices[self._ind] = event.xdata, event.ydata\n self.redraw_path(wp_vertices)\n\n def qt_data_changed_listener(self, index1, index2):\n \"\"\"Listens to dataChanged() signals emitted by the flight track\n data model. The top view can thus react to data changes\n induced by another view (table, side view).\n \"\"\"\n # Update the top view if the horizontal position of any point has been\n # changed.\n if index1.column() in [ft.LOCATION, ft.LAT, ft.LON, ft.FLIGHTLEVEL]:\n self.update()\n\n def update(self):\n \"\"\"Update the path plot by updating coordinates and intermediate\n great circle points from the path patch, then redrawing.\n \"\"\"\n self.pathpatch.get_path().update_from_WaypointsTableModel(\n self.waypoints_model)\n self.redraw_path()\n\n def redraw_path(self, wp_vertices=None):\n \"\"\"Redraw the matplotlib artists that represent the flight track\n (path patch, line and waypoint scatter).\n\n If waypoint vertices are specified, they will be applied to the\n graphics output. Otherwise the vertex array obtained from the path\n patch will be used.\n \"\"\"\n\n if wp_vertices is None:\n wp_vertices = self.pathpatch.get_path().wp_vertices\n if len(wp_vertices) == 0:\n raise IOError(\"mscolab session expired\")\n vertices = self.pathpatch.get_path().vertices\n else:\n # If waypoints have been provided, compute the intermediate\n # great circle points for the line instance.\n x, y = list(zip(*wp_vertices))\n lons, lats = self.map(x, y, inverse=True)\n x, y = self.map.gcpoints_path(lons, lats)\n vertices = list(zip(x, y))\n\n # Set the line to disply great circle points, remove existing\n # waypoints scatter instance and draw a new one. This is\n # necessary as scatter() does not provide a set_data method.\n self.line.set_data(list(zip(*vertices)))\n\n wp_heights = [(wp.flightlevel * 0.03048) for wp in self.waypoints_model.all_waypoint_data()]\n wp_times = [wp.utc_time for wp in self.waypoints_model.all_waypoint_data()]\n\n if self.tangent_lines is not None:\n self.tangent_lines.remove()\n if self.show_tangent_points:\n assert self.remote_sensing is not None\n self.tangent_lines = self.remote_sensing.compute_tangent_lines(\n self.map, wp_vertices, wp_heights)\n self.ax.add_collection(self.tangent_lines)\n else:\n self.tangent_lines = None\n\n if self.solar_lines is not None:\n self.solar_lines.remove()\n if self.show_solar_angle is not None:\n assert self.remote_sensing is not None\n self.solar_lines = self.remote_sensing.compute_solar_lines(\n self.map, wp_vertices, wp_heights, wp_times, self.show_solar_angle)\n self.ax.add_collection(self.solar_lines)\n else:\n self.solar_lines = None\n\n if self.wp_scatter is not None:\n self.wp_scatter.remove()\n x, y = list(zip(*wp_vertices))\n\n if self.map.projection == \"cyl\": # hack for wraparound\n x = np.array(x)\n x[x < self.map.llcrnrlon] += 360\n x[x > self.map.urcrnrlon] -= 360\n # (animated is important to remove the old scatter points from the map)\n self.wp_scatter = self.ax.scatter(\n x, y, color=self.markerfacecolor, s=20, zorder=3, animated=True, visible=self.show_marker)\n\n # Draw waypoint labels.\n label_offset = self.appropriate_epsilon(px=5)\n for wp_label in self.wp_labels:\n wp_label.remove()\n self.wp_labels = [] # remove doesn't seem to be necessary\n wpd = self.waypoints_model.all_waypoint_data()\n for i in range(len(wpd)):\n textlabel = str(i)\n if wpd[i].location != \"\":\n textlabel = f\"{wpd[i].location:}\"\n t = self.ax.text(\n x[i] + label_offset, y[i] + label_offset, textlabel,\n bbox={\"boxstyle\": \"round\", \"facecolor\": \"white\", \"alpha\": 0.6, \"edgecolor\": \"none\"},\n fontweight=\"bold\", zorder=4, animated=True, clip_on=True,\n visible=self.showverts and self.label_waypoints)\n self.wp_labels.append(t)\n\n # Redraw the artists.\n if self.background:\n self.canvas.restore_region(self.background)\n try:\n self.ax.draw_artist(self.pathpatch)\n except ValueError as error:\n logging.debug(\"ValueError Exception '%s'\", error)\n self.ax.draw_artist(self.line)\n self.ax.draw_artist(self.wp_scatter)\n\n for t in self.wp_labels:\n self.ax.draw_artist(t)\n if self.show_tangent_points:\n self.ax.draw_artist(self.tangent_lines)\n if self.show_solar_angle is not None:\n self.ax.draw_artist(self.solar_lines)\n self.canvas.blit(self.ax.bbox)\n\n # Link redraw_figure() to redraw_path().\n redraw_figure = redraw_path\n\n def draw_callback(self, event):\n \"\"\"Extends PathInteractor.draw_callback() by drawing the scatter\n instance.\n \"\"\"\n PathInteractor.draw_callback(self, event)\n self.ax.draw_artist(self.wp_scatter)\n if self.show_solar_angle:\n self.ax.draw_artist(self.solar_lines)\n if self.show_tangent_points:\n self.ax.draw_artist(self.tangent_lines)\n\n def get_ind_under_point(self, event):\n \"\"\"Get the index of the waypoint vertex under the point\n specified by event within epsilon tolerance.\n\n Uses display coordinates.\n If no waypoint vertex is found, None is returned.\n \"\"\"\n xy = np.asarray(self.pathpatch.get_path().wp_vertices)\n if self.map.projection == \"cyl\": # hack for wraparound\n lon_min, lon_max = self.map.llcrnrlon, self.map.urcrnrlon\n xy[xy[:, 0] < lon_min, 0] += 360\n xy[xy[:, 0] > lon_max, 0] -= 360\n xyt = self.pathpatch.get_transform().transform(xy)\n xt, yt = xyt[:, 0], xyt[:, 1]\n d = np.hypot(xt - event.x, yt - event.y)\n ind = d.argmin()\n if d[ind] >= self.epsilon:\n ind = None\n return ind\n\n def set_path_color(self, line_color=None, marker_facecolor=None,\n patch_facecolor=None):\n \"\"\"Set the color of the path patch elements.\n\n Arguments (options):\n line_color -- color of the path line\n marker_facecolor -- color of the waypoints\n patch_facecolor -- color of the patch covering the path area\n \"\"\"\n PathInteractor.set_path_color(self, line_color, marker_facecolor,\n patch_facecolor)\n if marker_facecolor is not None:\n self.wp_scatter.set_facecolor(marker_facecolor)\n self.wp_scatter.set_edgecolor(marker_facecolor)\n self.markerfacecolor = marker_facecolor\n\n def set_vertices_visible(self, showverts=True):\n \"\"\"Set the visibility of path vertices (the line plot).\n \"\"\"\n self.wp_scatter.set_visible(self.show_marker)\n PathInteractor.set_vertices_visible(self, showverts)\n\n def set_tangent_visible(self, visible):\n self.show_tangent_points = visible\n\n def set_solar_angle_visible(self, visible):\n self.show_solar_angle = visible\n\n def set_remote_sensing(self, ref):\n self.remote_sensing = ref\n" ]
[ [ "matplotlib.is_interactive", "numpy.ma.getmaskarray", "numpy.arange", "numpy.ceil", "numpy.copy", "numpy.ma.compress_rows", "numpy.mean", "numpy.diff", "numpy.floor", "matplotlib.cm.get_cmap", "matplotlib.collections.PolyCollection", "matplotlib.interactive", "numpy.array", "matplotlib.patches.PathPatch" ], [ "numpy.dot", "numpy.asarray", "numpy.linalg.norm", "numpy.hypot", "numpy.delete", "numpy.insert", "numpy.array", "matplotlib.patches.PathPatch" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
csun-comp587-s20/manim
[ "5d0f4859eb0105fea959e79537ab662159479445" ]
[ "test/test_mobject.py" ]
[ "import copy\nimport math\nimport random\n\nimport unittest\nimport numpy as np\n\nfrom manimlib.constants import *\nfrom manimlib.mobject.mobject import Mobject\nimport test.mobject_generator as mob_gen\n\ndef __func__(mob):\n mob.name = \"lambda\"\ndef __dt_func__(mob, dt):\n mob.name = str(dt)\ndef __x_func__(mob):\n mob.set_x(mob.get_x() + 1)\n\nclass MobjectTest(unittest.TestCase):\n def test_to_string(self):\n obj = Mobject()\n self.assertEqual(str(obj), \"Mobject\")\n obj = Mobject(name=\"dummy\")\n self.assertEqual(str(obj), \"dummy\")\n\n # ---------- Edit Submobjects Tests ---------- #\n def test_add_self_fails(self):\n obj = Mobject()\n with self.assertRaises(Exception):\n obj.add(obj)\n\n def test_add_returns_self(self):\n obj = Mobject()\n self.assertEqual(obj, obj.add())\n\n def test_add_submobjects_singly(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n self.assertListEqual([], obj.submobjects)\n obj.add(a)\n self.assertListEqual([a], obj.submobjects)\n obj.add(b)\n self.assertListEqual([a, b], obj.submobjects)\n obj.add(c)\n self.assertListEqual([a, b, c], obj.submobjects)\n\n def test_add_submobjects_multiply(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n self.assertListEqual([], obj.submobjects)\n obj.add(a, b, c)\n self.assertListEqual([a, b, c], obj.submobjects)\n\n def test_add_exsisting_submobjects(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n obj.add(a, b, c)\n obj.add(b)\n self.assertListEqual([a, c, b], obj.submobjects)\n\n def test_add_self_to_back_fails(self):\n obj = Mobject()\n with self.assertRaises(Exception):\n obj.add_to_back(obj)\n\n def test_add_to_back_returns_self(self):\n obj = Mobject()\n self.assertEqual(obj, obj.add_to_back())\n\n # add to back is actually add to front...\n def test_add_to_back_singly(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n self.assertListEqual([], obj.submobjects)\n obj.add_to_back(a)\n self.assertListEqual([a], obj.submobjects)\n obj.add_to_back(b)\n self.assertListEqual([b, a], obj.submobjects)\n obj.add_to_back(c)\n self.assertListEqual([c, b, a], obj.submobjects)\n\n def test_add_to_back_multiply(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n self.assertListEqual([], obj.submobjects)\n obj.add_to_back(a, b, c)\n self.assertListEqual([a, b, c], obj.submobjects)\n\n def test_add_to_back_exsisting_submobject(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n obj.add(a, b, c)\n obj.add_to_back(b)\n self.assertListEqual([b, a, c], obj.submobjects)\n\n def test_remove_returns_self(self):\n obj = Mobject()\n self.assertEqual(obj, obj.remove())\n\n def test_remove_singly(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n obj.add(a, b, c)\n self.assertListEqual([a, b, c], obj.submobjects)\n obj.remove(a)\n self.assertListEqual([b, c], obj.submobjects)\n obj.remove(b)\n self.assertListEqual([c], obj.submobjects)\n obj.remove(c)\n self.assertListEqual([], obj.submobjects)\n\n def test_remove_multiply(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n obj.add(a, b, c)\n self.assertListEqual([a, b, c], obj.submobjects)\n obj.remove(a, b)\n self.assertListEqual([c], obj.submobjects)\n\n def test_remove_not_submobject(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n obj.add(a, b)\n obj.remove(c)\n self.assertListEqual([a, b], obj.submobjects)\n\n def test_get_array_attrs(self):\n obj = Mobject()\n self.assertEqual([\"points\"], obj.get_array_attrs())\n\n # ---------- Drawing Tests ---------- #\n\n # ---------- Update Tests ---------- #\n def test_update_returns_self(self):\n obj = Mobject()\n self.assertEqual(obj, obj.update())\n \n def test_update_suspended(self):\n obj = Mobject(name=\"obj\")\n obj.updating_suspended = True\n obj.add_updater(__func__)\n obj.update()\n self.assertEqual(\"obj\", str(obj))\n\n def test_update_dt(self):\n obj = Mobject()\n obj.add_updater(__dt_func__)\n obj.update(dt=0.1)\n self.assertEqual(\"0.1\", str(obj))\n\n def test_update_no_dt(self):\n obj = Mobject()\n obj.add_updater(__func__)\n obj.update()\n self.assertEqual(\"lambda\", obj.name)\n\n def test_update_children(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n a.add_updater(__func__)\n b.add_updater(__func__)\n c.add_updater(__func__)\n obj.add(a, b, c)\n obj.update()\n for sub in obj.submobjects:\n self.assertEqual(\"lambda\", str(sub))\n\n def test_get_updaters(self):\n obj = Mobject()\n obj.add_updater(__func__)\n obj.add_updater(__func__)\n obj.add_updater(__func__)\n self.assertListEqual([__func__, __func__, __func__], obj.get_updaters())\n\n def test_get_dt_updaters(self):\n obj = Mobject()\n obj.add_updater(__func__)\n obj.add_updater(__dt_func__)\n obj.add_updater(__func__)\n self.assertListEqual([__dt_func__], obj.get_time_based_updaters())\n\n def test_has_dt_updater(self):\n obj = Mobject()\n obj.add_updater(__dt_func__)\n self.assertTrue(obj.has_time_based_updater())\n\n def test_has_no_dt_updater(self):\n obj = Mobject()\n obj.add_updater(__func__)\n self.assertFalse(obj.has_time_based_updater())\n\n def test_get_family_updater(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n obj.add(a, b, c)\n obj.add_updater(__func__)\n a.add_updater(__func__)\n b.add_updater(__func__)\n c.add_updater(__func__)\n self.assertListEqual([__func__, __func__, __func__, __func__], obj.get_family_updaters())\n\n def test_add_updater_returns_self(self):\n obj = Mobject()\n self.assertEqual(obj, obj.add_updater(__func__))\n\n def test_add_updater(self):\n obj = Mobject()\n self.assertListEqual([], obj.updaters)\n obj.add_updater(__func__)\n self.assertListEqual([__func__], obj.updaters)\n obj.add_updater(__dt_func__)\n self.assertListEqual([__func__, __dt_func__], obj.updaters)\n\n def test_add_updater_by_index(self):\n obj = Mobject()\n self.assertListEqual([], obj.updaters)\n obj.add_updater(__func__, 0)\n self.assertListEqual([__func__], obj.updaters)\n obj.add_updater(__dt_func__, 0)\n self.assertListEqual([__dt_func__, __func__], obj.updaters)\n obj.add_updater(__dt_func__, 1)\n self.assertListEqual([__dt_func__, __dt_func__, __func__], obj.updaters)\n\n def test_remove_updater_returns_self(self):\n obj = Mobject()\n self.assertEqual(obj, obj.remove_updater(__func__))\n\n def test_remove_updater(self):\n obj = Mobject()\n obj.add_updater(__func__)\n obj.add_updater(__dt_func__)\n obj.add_updater(__func__)\n self.assertListEqual([__func__, __dt_func__, __func__], obj.updaters)\n obj.remove_updater(__func__)\n self.assertListEqual([__dt_func__], obj.updaters)\n\n def test_remove_no_updater(self):\n obj = Mobject()\n obj.add_updater(__func__)\n self.assertListEqual([__func__], obj.updaters)\n obj.remove_updater(__dt_func__)\n self.assertListEqual([__func__], obj.updaters)\n\n def test_clear_updaters_returns_self(self):\n obj = Mobject()\n self.assertEqual(obj, obj.clear_updaters())\n\n def test_clear_updaters(self):\n obj = Mobject()\n obj.add_updater(__func__)\n obj.add_updater(__dt_func__)\n obj.add_updater(__func__)\n self.assertListEqual([__func__, __dt_func__, __func__], obj.updaters)\n obj.clear_updaters()\n self.assertListEqual([], obj.updaters)\n\n def test_clear_updaters_in_children(self):\n a, b, c, obj = Mobject(), Mobject(), Mobject(), Mobject()\n obj.add(a, b, c)\n obj.add_updater(__func__)\n a.add_updater(__func__)\n b.add_updater(__func__)\n c.add_updater(__func__)\n self.assertListEqual([__func__, __func__, __func__, __func__], obj.get_family_updaters())\n obj.clear_updaters()\n self.assertListEqual([], obj.get_family_updaters())\n\n def test_match_updaters_returns_self(self):\n obj1, obj2 = Mobject(), Mobject()\n self.assertEqual(obj1, obj1.match_updaters(obj2))\n\n def test_match_updater_1(self):\n a, b = Mobject(), Mobject()\n a.add_updater(__func__)\n a.add_updater(__dt_func__)\n self.assertListEqual([__func__, __dt_func__], a.updaters)\n self.assertListEqual([], b.updaters)\n b.match_updaters(a)\n self.assertListEqual([__func__, __dt_func__], a.updaters)\n self.assertListEqual([__func__, __dt_func__], b.updaters)\n\n def test_match_updater_2(self):\n a, b = Mobject(), Mobject()\n a.add_updater(__func__)\n a.add_updater(__dt_func__)\n self.assertListEqual([__func__, __dt_func__], a.updaters)\n self.assertListEqual([], b.updaters)\n a.match_updaters(b)\n self.assertListEqual([], a.updaters)\n self.assertListEqual([], b.updaters)\n\n def test_suspend_update(self):\n a, b, c = Mobject(), Mobject(), Mobject()\n a.add(b)\n a.updating_suspended = True\n b.updating_suspended = True\n c.updating_suspended = False\n a.suspend_updating()\n c.suspend_updating()\n self.assertTrue(a.updating_suspended)\n self.assertTrue(b.updating_suspended)\n self.assertTrue(c.updating_suspended)\n\n def test_resume_update(self):\n a, b, c = Mobject(), Mobject(), Mobject()\n a.add(b)\n a.updating_suspended = True\n b.updating_suspended = True\n c.updating_suspended = False\n a.resume_updating()\n c.resume_updating()\n self.assertFalse(a.updating_suspended)\n self.assertFalse(b.updating_suspended)\n self.assertFalse(c.updating_suspended)\n\n # ---------- Transformation Tests ---------- #\n def test_apply_to_family(self):\n obj = Mobject()\n obj.points = np.zeros((1, 3))\n self.assertEqual(0, obj.get_x())\n self.assertEqual(0, obj.get_y())\n self.assertEqual(0, obj.get_z())\n obj.apply_to_family(__x_func__)\n self.assertEqual(1, obj.get_x())\n self.assertEqual(0, obj.get_y())\n self.assertEqual(0, obj.get_z())\n\n def test_shift_returns_self(self):\n obj = Mobject()\n obj.points = np.array([[0, 0, 0]])\n self.assertEqual(obj, obj.shift(np.array([0, 0, 0])))\n\n def test_shift(self):\n a = random.Random().randint(-1000, 1000)\n b = random.Random().randint(-1000, 1000)\n c = random.Random().randint(-1000, 1000)\n x = random.Random().randint(-1000, 1000)\n y = random.Random().randint(-1000, 1000)\n z = random.Random().randint(-1000, 1000)\n obj = Mobject()\n obj.points = np.array([[x, y, z]])\n obj.shift(np.array([a, b, c]))\n np.testing.assert_array_equal(obj.points,\n np.array([[x + a, y + b, z + c]]))\n\n def test_shift_by_zero_property(self):\n gen = mob_gen.MobjectGenerator(max_depth = 0)\n obj = gen.next()\n og = obj.points\n obj.shift(np.zeros((1, 3)))\n np.testing.assert_array_equal(og, obj.points)\n\n def test_shift_negative_property(self):\n gen = mob_gen.MobjectGenerator(max_depth=0)\n obj = gen.next()\n og = copy.deepcopy(obj)\n obj.shift(np.full((1, 3), random.Random().randrange(-1000, -1)))\n np.testing.assert_array_less(obj.get_all_points(), og.get_all_points())\n\n def test_shift_positive_property(self):\n gen = mob_gen.MobjectGenerator(max_depth=0)\n obj = gen.next()\n og = copy.deepcopy(obj)\n obj.shift(np.full((1, 3), random.Random().randrange(1, 1000)))\n np.testing.assert_array_less(og.get_all_points(), obj.get_all_points())\n\n def test_scale_returns_self(self):\n obj = Mobject()\n obj.points = np.array([0, 0, 0])\n self.assertEqual(obj, obj.scale(1, about_point=np.array([0, 0, 0])))\n\n def test_scale(self):\n s = random.Random().randint(-1000, 1000)\n x = random.Random().randint(-1000, 1000)\n y = random.Random().randint(-1000, 1000)\n z = random.Random().randint(-1000, 1000)\n obj = Mobject()\n obj.points = np. array([[x, y, z]])\n obj.scale(s, about_point=np.array([0, 0, 0]))\n np.testing.assert_array_equal(obj.points,\n np.array([[x * s, y * s, z * s]]))\n\n def test_scale_property(self):\n gen = mob_gen.MobjectGenerator(max_depth=0)\n obj = gen.next()\n og = copy.deepcopy(obj)\n obj.scale(10)\n np.testing.assert_array_less(\n np.absolute(og.get_all_points()),\n np.absolute(obj.get_all_points()))\n\n def test_rotate_returns_self(self):\n a = random.Random().randint(-1000, 1000)\n x = random.Random().randint(-1000, 1000)\n y = random.Random().randint(-1000, 1000)\n z = random.Random().randint(-1000, 1000)\n obj = Mobject()\n obj.points = np.array([x, y, z])\n self.assertEqual(obj, obj.rotate(a, about_point=np.array([0, 0, 0])))\n\n def test_rotate(self):\n a = random.Random().randint(-1000, 1000)\n x = random.Random().randint(-1000, 1000)\n y = random.Random().randint(-1000, 1000)\n z = random.Random().randint(-1000, 1000)\n obj = Mobject()\n obj.points = np.array([[x, y, z]])\n obj.rotate(a, axis=np.array([0, 0, 1]), about_point=np.array([0, 0, 0]))\n np.testing.assert_array_equal(obj.points, np.array([[\n x * math.cos(a) - y * math.sin(a),\n x * math.sin(a) + y * math.cos(a),\n z]]))\n\n def test_stretch_returns_self(self):\n obj = Mobject()\n obj.points = np.zeros((1, 3))\n self.assertEqual(obj, obj.stretch(1, 0))\n\n def test_stretch_factor_1(self):\n obj = Mobject()\n obj.points = np.array([[1.0, 1.0, 1.0]])\n obj.stretch(1, 0)\n obj.stretch(1, 1)\n obj.stretch(1, 2)\n np.testing.assert_array_equal(obj.points, np.array([[1, 1, 1]]))\n \n def test_stretch_origin(self):\n obj = Mobject()\n obj.points = np.array([[0.0, 0.0, 0.0]])\n f = random.Random().randint(-1000, 1000)\n obj.stretch(f, 0)\n obj.stretch(f, 1)\n obj.stretch(f, 2)\n np.testing.assert_array_equal(obj.points, np.zeros((1, 3)))\n \n def test_stretch_factor_random(self):\n obj = Mobject()\n obj.points = np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])\n f = random.Random().randint(-1000, 1000)\n obj.stretch(f, 0)\n obj.stretch(f, 1)\n obj.stretch(f, 2)\n f /= 2\n np.testing.assert_array_almost_equal(obj.points,\n np.array([[-f, -f, -f], [f, f, f]]),\n decimal=0)\n \n # ---------- Positioning Tests ---------- #\n def test_center_returns_self(self):\n obj = Mobject()\n obj.points = np.zeros((1, obj.dim))\n self.assertEqual(obj, obj.center())\n\n def test_center(self):\n x = random.Random().randint(-1000, 1000)\n y = random.Random().randint(-1000, 1000)\n z = random.Random().randint(-1000, 1000)\n obj = Mobject()\n obj.points = np.array([[x, y, z]])\n obj.center()\n np.testing.assert_array_equal(obj.points, np.zeros((1, 3)))\n\n def test_center_negative_bound_object(self):\n gen = mob_gen.MobjectGenerator(upper_bound=-1)\n obj = gen.next()\n og = copy.deepcopy(obj)\n obj.center()\n np.testing.assert_array_less(og.get_all_points(), obj.get_all_points())\n\n def test_center_positive_bound_object(self):\n gen = mob_gen.MobjectGenerator(lower_bound=1)\n obj = gen.next()\n og = copy.deepcopy(obj)\n obj.center()\n np.testing.assert_array_less(obj.get_all_points(), og.get_all_points())\n\n def test_align_on_border_returns_self(self):\n obj = Mobject()\n obj.points = np.zeros((1, 3))\n self.assertEqual(obj, obj.align_on_border(np.zeros(3)))\n\n def test_align_on_border(self):\n obj = Mobject()\n obj.points = np.zeros((1, 3))\n obj.align_on_border(np.array([0, 1, 0]))\n np.testing.assert_array_equal(obj.points, np.array([[\n 0,\n FRAME_Y_RADIUS - DEFAULT_MOBJECT_TO_EDGE_BUFFER,\n 0]]))\n\n obj.align_on_border(np.array([1, 0, 0]))\n np.testing.assert_array_equal(obj.points, np.array([[\n FRAME_X_RADIUS - DEFAULT_MOBJECT_TO_EDGE_BUFFER,\n FRAME_Y_RADIUS - DEFAULT_MOBJECT_TO_EDGE_BUFFER,\n 0]]))\n\n # need more next to tests for branch coverage\n def test_next_to_returns_self(self):\n a, b = Mobject(), Mobject()\n a.points = np.array([[-1, 0, 0]])\n b.points = np.array([[1, 0, 0]])\n self.assertEqual(a, a.next_to(b))\n\n def test_next_to(self):\n a, b = Mobject(), Mobject()\n a.points = np.array([[-1, 0, 0]])\n b.points = np.array([[1, 0, 0]])\n a.next_to(b)\n np.testing.assert_array_equal(a.points,\n b.points + RIGHT * DEFAULT_MOBJECT_TO_MOBJECT_BUFFER)\n\n def test_shift_onto_screen_returns_self(self):\n obj = Mobject()\n obj.points = np.zeros((1, 3))\n self.assertEqual(obj, obj.shift_onto_screen())\n\n def test_shift_onto_screen_one(self):\n obj = Mobject()\n obj.points = np.zeros((1, 3))\n obj.shift_onto_screen()\n np.testing.assert_array_equal(obj.points, np.zeros((1, 3)))\n\n def test_shift_onto_screen_two(self):\n obj = Mobject()\n obj.points = np.array([[FRAME_X_RADIUS*2, 0, 0]])\n obj.shift_onto_screen()\n np.testing.assert_array_equal(obj.points, np.array([[\n FRAME_X_RADIUS - DEFAULT_MOBJECT_TO_EDGE_BUFFER, 0, 0]]))\n\n def test_is_off_screen_false(self):\n obj = Mobject()\n obj.points = np.zeros((1, 3))\n self.assertFalse(obj.is_off_screen())\n\n def test_is_off_screen_right(self):\n obj = Mobject()\n obj.points = np.array([[FRAME_X_RADIUS*2, 0, 0]])\n self.assertTrue(obj.is_off_screen())\n\n def test_is_off_screen_left(self):\n obj = Mobject()\n obj.points = np.array([[-FRAME_X_RADIUS*2, 0, 0]])\n self.assertTrue(obj.is_off_screen())\n\n def test_is_off_screen_up(self):\n obj = Mobject()\n obj.points = np.array([[0, FRAME_Y_RADIUS*2, 0]])\n self.assertTrue(obj.is_off_screen())\n\n def test_is_off_screen_down(self):\n obj = Mobject()\n obj.points = np.array([[0, -FRAME_Y_RADIUS*2, 0]])\n self.assertTrue(obj.is_off_screen())\n\n # ---------- Coloring Tests ---------- #\n # ---------- Mobject Comparision Tests ---------- #\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
egemenzeytinci/ycimpute
[ "b07a52586692800c68f662bff12c08a6fc2de119", "b07a52586692800c68f662bff12c08a6fc2de119", "b07a52586692800c68f662bff12c08a6fc2de119", "b07a52586692800c68f662bff12c08a6fc2de119" ]
[ "ycimpute/datasets/dpath.py", "ycimpute/unsupervised/knn/common.py", "ycimpute/utils/shower/show.py", "ycimpute/unsupervised/knn/optimistic.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport h5py\n\n\n\ndef make_missing(npdata):\n import random\n import numpy as np\n rows, cols = npdata.shape\n random_cols = range(cols)\n for col in random_cols:\n random_rows = random.sample(range(rows - 1), int(0.1 * rows))\n npdata[random_rows, col] = np.nan\n return npdata\n\n\ndef create_data(data):\n import copy\n full_data = copy.copy(data)\n missing_data = make_missing(data)\n\n return missing_data, full_data\n\n\ndef boston():\n from sklearn.datasets import load_boston\n boston = load_boston()\n data = boston.data\n missing_data, full_data = create_data(data)\n h5_file = h5py.File('boston.hdf5','w')\n h5_file['missing'] = missing_data\n h5_file['full'] = full_data\n h5_file.close()\n\n\ndef diabetes():\n \"\"\"\n Pima Indians Diabetes Datase\n :return:\n \"\"\"\n from sklearn.datasets import load_diabetes\n load_diabetes = load_diabetes()\n data = load_diabetes.data\n missing_data, full_data = create_data(data)\n h5_file = h5py.File('diabetes.hdf5', 'w')\n h5_file['missing'] = missing_data\n h5_file['full'] = full_data\n h5_file.close()\n\n\ndef iris():\n from sklearn.datasets import load_iris\n data = load_iris().data\n missing_data, full_data = create_data(data)\n h5_file = h5py.File('iris.hdf5', 'w')\n h5_file['missing'] = missing_data\n h5_file['full'] = full_data\n h5_file.close()\n\ndef wine():\n from sklearn.datasets import load_wine\n data = load_wine().data\n missing_data, full_data = create_data(data)\n h5_file = h5py.File('wine.hdf5', 'w')\n h5_file['missing'] = missing_data\n h5_file['full'] = full_data\n h5_file.close()\n\nif __name__==\"__main__\":\n #boston()\n #diabetes()\n #iris()\n wine()", "\n\nfrom __future__ import absolute_import, print_function, division\n\nimport numpy as np\n\nfrom .normalized_distance import all_pairs_normalized_distances\n\n\ndef knn_initialize(\n X,\n missing_mask,\n min_dist=1e-6,\n max_dist_multiplier=1e6):\n \"\"\"\n Fill X with NaN values if necessary, construct the n_samples x n_samples\n distance matrix and set the self-distance of each row to infinity.\n\n Returns contents of X laid out in row-major, the distance matrix,\n and an \"effective infinity\" which is larger than any entry of the\n distance matrix.\n \"\"\"\n X_row_major = X.copy(\"C\")\n if missing_mask.sum() != np.isnan(X_row_major).sum():\n # if the missing values have already been zero-filled need\n # to put NaN's back in the data matrix for the distances function\n X_row_major[missing_mask] = np.nan\n D = all_pairs_normalized_distances(X_row_major)\n D_finite_flat = D[np.isfinite(D)]\n if len(D_finite_flat) > 0:\n max_dist = max_dist_multiplier * max(1, D_finite_flat.max())\n else:\n max_dist = max_dist_multiplier\n # set diagonal of distance matrix to a large value since we don't want\n # points considering themselves as neighbors\n np.fill_diagonal(D, max_dist)\n D[D < min_dist] = min_dist # prevents 0s\n D[D > max_dist] = max_dist # prevents infinities\n return X_row_major, D, max_dist\n", "\nimport pandas as pd\nimport numpy as np\nimport copy\nimport h5py\n##################################################\n\nfrom ...imputer.mice import MICE\nfrom ...imputer.knnimput import KNN\nfrom ...imputer.iterforest import IterImput\nfrom ...imputer.simple import SimpleFill\nfrom ...imputer import EM\n\nfrom ...utils.tools import Solver\nfrom .. import evaluate\nfrom .. import config\n\nsolver = Solver()\n\ndef analysiser(missing_X, original_X):\n missing_X = np.asarray(missing_X)\n original_X = np.asarray(original_X)\n\n mask_all = solver.masker(missing_X)[config.all]\n missing_index = evaluate.get_missing_index(mask_all)\n original_arr = original_X[missing_index]\n\n ##################################################\n\n mice_X_filled = MICE().complete(copy.copy(missing_X))\n mice_filled_arr = mice_X_filled[missing_index]\n rmse_mice_score = evaluate.RMSE(original_arr, mice_filled_arr)\n\n #########################################################\n iterforest_X_filled = IterImput().complete(copy.copy(missing_X))\n iterforest_filled_arr = iterforest_X_filled[missing_index]\n rmse_iterforest_score = evaluate.RMSE(original_arr, iterforest_filled_arr)\n\n\n ############################################################\n knn_X_filled = KNN(k=3).complete(copy.copy(missing_X))\n knn_filled_arr = knn_X_filled[missing_index]\n rmse_knn_score = evaluate.RMSE(original_arr, knn_filled_arr)\n\n ######################################################\n mean_X_filled = SimpleFill(fill_method='mean').complete(copy.copy(missing_X))\n mean_filled_arr = mean_X_filled[missing_index]\n rmse_mean_score = evaluate.RMSE(original_arr, mean_filled_arr)\n #################################################################\n zero_X_filled = SimpleFill(fill_method='zero').complete(copy.copy(missing_X))\n zero_filled_arr = zero_X_filled[missing_index]\n rmse_zero_score = evaluate.RMSE(original_arr, zero_filled_arr)\n\n ################################################\n median_X_filled = SimpleFill(fill_method='median').complete(copy.copy(missing_X))\n median_filled_arr = median_X_filled[missing_index]\n rmse_median_score = evaluate.RMSE(original_arr, median_filled_arr)\n ##########################################################################\n min_X_filled = SimpleFill(fill_method='min').complete(copy.copy(missing_X))\n min_filled_arr = min_X_filled[missing_index]\n rmse_min_score = evaluate.RMSE(original_arr, min_filled_arr)\n\n #######################################################\n em_X_filled = EM().complete(copy.copy(missing_X))\n em_filled_arr = em_X_filled[missing_index]\n rmse_em_score = evaluate.RMSE(original_arr,em_filled_arr)\n ################################################\n\n return {'rmse_mice_score':rmse_mice_score,\n 'rmse_iterforest_score':rmse_iterforest_score,\n 'rmse_knn_score':rmse_knn_score,\n 'rmse_mean_score':rmse_mean_score,\n 'rmse_zero_score':rmse_zero_score,\n 'rmse_median_score':rmse_median_score,\n 'rmse_min_score':rmse_min_score,\n 'rmse_em_score': rmse_em_score\n }\n\n\ndef example():\n from ...datasets import load_data\n boston_mis, boston_full = load_data.load_boston()\n print(analysiser(boston_mis, boston_full))", "\n\nfrom __future__ import absolute_import, print_function, division\nimport time\n\nfrom six.moves import range\nimport numpy as np\n\nfrom .common import knn_initialize\n\ndef knn_impute_optimistic(\n X,\n missing_mask,\n k,\n verbose=False,\n print_interval=100):\n \"\"\"\n Fill in the given incomplete matrix using k-nearest neighbor imputation.\n\n This version assumes that most of the time the same neighbors will be\n used so first performs the weighted average of a row's k-nearest neighbors\n and checks afterward whether it was valid (due to possible missing values).\n\n Has been observed to be a lot faster for 1/4 missing images matrix\n with 1000 rows and ~9000 columns.\n\n Parameters\n ----------\n X : np.ndarray\n Matrix to fill of shape (n_samples, n_features)\n\n missing_mask : np.ndarray\n Boolean array of same shape as X\n\n k : int\n\n verbose : bool\n\n Modifies X by replacing its missing values with weighted averages of\n similar rows. Returns the modified X.\n \"\"\"\n start_t = time.time()\n n_rows, n_cols = X.shape\n X_row_major, D, _ = knn_initialize(X, missing_mask)\n D_sorted_indices = np.argsort(D, axis=1)\n X_column_major = X_row_major.copy(order=\"F\")\n\n dot = np.dot\n\n # preallocate array to prevent repeated creation in the following loops\n neighbor_weights = np.ones(k, dtype=X.dtype)\n\n missing_mask_column_major = np.asarray(missing_mask, order=\"F\")\n observed_mask_column_major = ~missing_mask_column_major\n\n for i in range(n_rows):\n missing_columns = np.where(missing_mask[i])[0]\n if verbose and i % print_interval == 0:\n print(\n \"Imputing row %d/%d with %d missing, elapsed time: %0.3f\" % (\n i + 1,\n n_rows,\n len(missing_columns),\n time.time() - start_t))\n n_missing_columns = len(missing_columns)\n if n_missing_columns == 0:\n continue\n\n row_distances = D[i, :]\n neighbor_indices = D_sorted_indices[i, :]\n X_missing_columns = X_column_major[:, missing_columns]\n\n # precompute these for the fast path where the k nearest neighbors\n # are not missing the feature value we're currently trying to impute\n k_nearest_indices = neighbor_indices[:k]\n np.divide(1.0, row_distances[k_nearest_indices], out=neighbor_weights)\n # optimistically impute all the columns from the k nearest neighbors\n # we'll have to back-track for some of the columns for which\n # one of the neighbors did not have a value\n X_knn = X_missing_columns[k_nearest_indices, :]\n weighted_average_of_neighboring_rows = dot(\n X_knn.T,\n neighbor_weights)\n sum_weights = neighbor_weights.sum()\n weighted_average_of_neighboring_rows /= sum_weights\n imputed_values = weighted_average_of_neighboring_rows\n\n observed_mask_missing_columns = observed_mask_column_major[:, missing_columns]\n observed_mask_missing_columns_sorted = observed_mask_missing_columns[\n neighbor_indices, :]\n\n # We can determine the maximum number of other rows that must be\n # inspected across all features missing for this row by\n # looking at the column-wise running sums of the observed feature\n # matrix.\n observed_cumulative_sum = observed_mask_missing_columns_sorted.cumsum(axis=0)\n sufficient_rows = (observed_cumulative_sum == k)\n n_rows_needed = sufficient_rows.argmax(axis=0) + 1\n max_rows_needed = n_rows_needed.max()\n\n if max_rows_needed == k:\n # if we never needed more than k rows then we're done after the\n # optimistic averaging above, so go on to the next sample\n X[i, missing_columns] = imputed_values\n continue\n\n # truncate all the sorted arrays to only include the necessary\n # number of rows (should significantly speed up the \"slow\" path)\n necessary_indices = neighbor_indices[:max_rows_needed]\n d_sorted = row_distances[necessary_indices]\n X_missing_columns_sorted = X_missing_columns[necessary_indices, :]\n observed_mask_missing_columns_sorted = observed_mask_missing_columns_sorted[\n :max_rows_needed, :]\n\n for missing_column_idx in range(n_missing_columns):\n # since all the arrays we're looking into have already been\n # sliced out at the missing features, we need to address these\n # features from 0..n_missing using missing_idx rather than j\n if n_rows_needed[missing_column_idx] == k:\n assert np.isfinite(imputed_values[missing_column_idx]), \\\n \"Expected finite imputed value #%d (column #%d for row %d)\" % (\n missing_column_idx,\n missing_columns[missing_column_idx],\n i)\n continue\n row_mask = observed_mask_missing_columns_sorted[:, missing_column_idx]\n sorted_column_values = X_missing_columns_sorted[:, missing_column_idx]\n neighbor_distances = d_sorted[row_mask][:k]\n\n # may not have enough values in a column for all k neighbors\n k_or_less = len(neighbor_distances)\n usable_weights = neighbor_weights[:k_or_less]\n np.divide(\n 1.0,\n neighbor_distances, out=usable_weights)\n neighbor_values = sorted_column_values[row_mask][:k_or_less]\n\n imputed_values[missing_column_idx] = (\n dot(neighbor_values, usable_weights) / usable_weights.sum())\n\n X[i, missing_columns] = imputed_values\n return X\n" ]
[ [ "sklearn.datasets.load_wine", "sklearn.datasets.load_iris", "sklearn.datasets.load_boston" ], [ "numpy.isnan", "numpy.fill_diagonal", "numpy.isfinite" ], [ "numpy.asarray" ], [ "numpy.isfinite", "numpy.asarray", "numpy.ones", "numpy.argsort", "numpy.where", "numpy.divide" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gamazeps/wot
[ "623bcdc78ad1fab43b3e05b467f961648741a7a0" ]
[ "wot/io/read_gct.py" ]
[ "import anndata\n\n\"\"\" Reads in a gct file .\n\nThe main method is parse. parse_into_3 creates the row\nmetadata, column metadata, and data dataframes, while the\nassemble_multi_index_df method in GCToo.py assembles them.\n\n1) Example GCT v1.3:\n ----- start of file ------\n #1.3\n 96 36 9 15\n ---------------------------------------------------\n |id| rhd | cid |\n ---------------------------------------------------\n | | | |\n |c | | |\n |h | (blank) | col_metadata |\n |d | | |\n | | | |\n ---------------------------------------------------\n | | | |\n |r | | |\n |i | row_metadata | data |\n |d | | |\n | | | |\n ---------------------------------------------------\n ----- end of file ------\n\n Notes:\n - line 1 of file (\"#1.3\") refers to the version number\n - line 2 of file (\"96 36 9 15\") refers to the following:\n -96 = number of data rows\n -36 = number of data columns\n -9 = number of row metadata fields (+1 for the 'id' column -- first column)\n -15 = number of col metadata fields (+1 for the 'id' row -- first row)\n - Once read into a DataFrame, col_metadata_df is stored as the transpose of how it looks in the gct file.\n That is, col_metadata_df.shape = (num_cid, num_chd).\n\n2) Example GCT v1.2\n\n ----- start of file ------\n #1.2\n 96 36\n -----------------------------------------------\n |\"NAME\" |\"Description\"| cid |\n -----------------------------------------------\n | r | | |\n | i | | |\n | d |row_metadata | data |\n | | | |\n | | | |\n -----------------------------------------------\n\n ----- end of file ------\n Notes:\n - line 1 of file (\"#1.3\") refers to the version number\n - line 2 of file (\"96 36 9 15\") refers to the following:\n -96 = number of data rows\n -36 = number of data columns\n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\n__author__ = \"Lev Litichevskiy, Oana Enache\"\n__email__ = \"[email protected]\"\n\n\ndef read_gct(file_path):\n \"\"\" The main method.\n\n Args:\n - file_path (string): full path to gct file you want to parse\n\n Returns:\n anndata.AnnData\n\n \"\"\"\n\n # Read version and dimensions\n (version, num_data_rows, num_data_cols,\n num_row_metadata, num_col_metadata) = read_version_and_dims(file_path)\n\n # Read in metadata and data\n (row_metadata, col_metadata, data) = parse_into_3(\n file_path, num_data_rows, num_data_cols,\n num_row_metadata, num_col_metadata)\n\n row_metadata.index.name = None\n col_metadata.index.name = None\n row_metadata.columns.name = None\n col_metadata.columns.name = None\n return anndata.AnnData(data, row_metadata, col_metadata)\n\n\ndef read_version_and_dims(file_path):\n # Open file\n f = open(file_path, \"r\")\n\n # Get version from the first line\n version = f.readline().strip().lstrip(\"#\")\n\n if version not in [\"1.3\", \"1.2\"]:\n err_msg = (\"Only GCT1.2 and 1.3 are supported. The first row of the GCT \" +\n \"file must simply be (without quotes) '#1.3' or '#1.2'\")\n\n raise Exception(err_msg.format(version))\n\n # Convert version to a string\n version_as_string = \"GCT\" + str(version)\n\n # Read dimensions from the second line\n dims = f.readline().strip().split(\"\\t\")\n\n # Close file\n f.close()\n\n # Check that the second row is what we expect\n if version == \"1.2\" and len(dims) != 2:\n error_msg = \"GCT1.2 should have 2 dimension-related entries in row 2. dims: {}\"\n\n raise Exception(error_msg.format(dims))\n elif version == \"1.3\" and len(dims) != 4:\n error_msg = \"GCT1.3 should have 4 dimension-related entries in row 2. dims: {}\"\n\n raise Exception(error_msg.format(dims))\n\n # Explicitly define each dimension\n num_data_rows = int(dims[0])\n num_data_cols = int(dims[1])\n if len(dims) == 4:\n num_row_metadata = int(dims[2])\n num_col_metadata = int(dims[3])\n else:\n num_row_metadata = 1\n num_col_metadata = 0\n\n # Return version and dimensions\n return version_as_string, num_data_rows, num_data_cols, num_row_metadata, num_col_metadata\n\n\ndef parse_into_3(file_path, num_data_rows, num_data_cols, num_row_metadata, num_col_metadata):\n # Read the gct file beginning with line 3\n full_df = pd.read_csv(file_path, sep=\"\\t\", header=None, skiprows=2, dtype=str)\n\n # Check that full_df is the size we expect\n assert full_df.shape == (num_col_metadata + num_data_rows + 1,\n num_row_metadata + num_data_cols + 1), (\n (\"The shape of full_df is not as expected: data is {} x {} \" +\n \"but there are {} row meta fields and {} col fields\").format(\n num_data_rows, num_data_cols, num_row_metadata, num_col_metadata))\n\n # Assemble metadata dataframes\n row_metadata = assemble_row_metadata(full_df, num_col_metadata, num_data_rows, num_row_metadata)\n col_metadata = assemble_col_metadata(full_df, num_col_metadata, num_row_metadata, num_data_cols)\n\n # Assemble data dataframe\n data = assemble_data(full_df, num_col_metadata, num_data_rows, num_row_metadata, num_data_cols)\n\n # Return 3 dataframes\n return row_metadata, col_metadata, data\n\n\ndef assemble_row_metadata(full_df, num_col_metadata, num_data_rows, num_row_metadata):\n # Extract values\n row_metadata_row_inds = range(num_col_metadata + 1, num_col_metadata + num_data_rows + 1)\n row_metadata_col_inds = range(1, num_row_metadata + 1)\n row_metadata = full_df.iloc[row_metadata_row_inds, row_metadata_col_inds]\n\n # Create index from the first column of full_df (after the filler block)\n row_metadata.set_index(full_df.iloc[row_metadata_row_inds, 0], inplace=True)\n # Create columns from the top row of full_df (before cids start)\n row_metadata.columns = full_df.iloc[0, row_metadata_col_inds].values\n\n # Rename the index name and columns name\n # row_metadata.index.name = row_index_name\n # row_metadata.columns.name = row_header_name\n\n # Convert metadata to numeric if possible\n row_metadata = row_metadata.apply(lambda x: pd.to_numeric(x, errors=\"ignore\"))\n\n return row_metadata\n\n\ndef assemble_col_metadata(full_df, num_col_metadata, num_row_metadata, num_data_cols):\n # Extract values\n col_metadata_row_inds = range(1, num_col_metadata + 1)\n col_metadata_col_inds = range(num_row_metadata + 1, num_row_metadata + num_data_cols + 1)\n col_metadata = full_df.iloc[col_metadata_row_inds, col_metadata_col_inds]\n\n # Transpose so that samples are the rows and headers are the columns\n col_metadata = col_metadata.T\n\n # Create index from the top row of full_df (after the filler block)\n col_metadata.set_index(full_df.iloc[0, col_metadata_col_inds], inplace=True)\n\n # Create columns from the first column of full_df (before rids start)\n col_metadata.columns = full_df.iloc[col_metadata_row_inds, 0].values\n\n # # Rename the index name and columns name\n # col_metadata.index.name = 'id'\n # col_metadata.columns.name = 'description'\n\n # Convert metadata to numeric if possible\n col_metadata = col_metadata.apply(lambda x: pd.to_numeric(x, errors=\"ignore\"))\n\n return col_metadata\n\n\ndef assemble_data(full_df, num_col_metadata, num_data_rows, num_row_metadata, num_data_cols):\n # Extract values\n data_row_inds = range(num_col_metadata + 1, num_col_metadata + num_data_rows + 1)\n data_col_inds = range(num_row_metadata + 1, num_row_metadata + num_data_cols + 1)\n data = full_df.iloc[data_row_inds, data_col_inds].values\n return data.astype(np.float64)\n" ]
[ [ "pandas.read_csv", "pandas.to_numeric" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
chanb/rl_sandbox_public
[ "e55f954a29880f83a5b0c3358badda4d900f1564", "e55f954a29880f83a5b0c3358badda4d900f1564", "e55f954a29880f83a5b0c3358badda4d900f1564", "e55f954a29880f83a5b0c3358badda4d900f1564" ]
[ "rl_sandbox/model_architectures/actor_critics/conv_actor_critic.py", "rl_sandbox/examples/pybullet/hopper/sac_fr_lstm_experiment.py", "rl_sandbox/examples/imitation_learning/dac/dac_experiment.py", "rl_sandbox/envs/wrappers/frame_stack.py" ]
[ "import numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom torch.distributions import Normal\n\nfrom rl_sandbox.constants import OBS_RMS, CPU\nfrom rl_sandbox.model_architectures.actor_critics.actor_critic import ActorCritic\nfrom rl_sandbox.model_architectures.shared import Conv2DEncoder, Flatten, Fuse, Split\nfrom rl_sandbox.model_architectures.utils import construct_linear_layers\n\n\nclass EarlyFusionConv2DGaussianAC(ActorCritic):\n def __init__(self,\n img_dim,\n scalar_feature_dim,\n action_dim,\n shared_layers,\n shared_out_dim,\n eps=1e-7,\n device=torch.device(CPU),\n normalize_obs=False,\n normalize_value=False):\n assert len(img_dim) == 4\n super().__init__(obs_dim=scalar_feature_dim,\n norm_dim=(0,),\n device=device,\n normalize_obs=normalize_obs,\n normalize_value=normalize_value)\n self._eps = eps\n self._img_dim = img_dim\n self._scalar_feature_dim = scalar_feature_dim\n self.split = Split([int(np.product(img_dim)), scalar_feature_dim])\n self.fuse = Fuse()\n self.encoder = Conv2DEncoder(*img_dim[1:], shared_out_dim, shared_layers, nn.LayerNorm(50))\n self.action_net = nn.Sequential(nn.Linear(shared_out_dim * self._img_dim[0] + scalar_feature_dim, 256),\n nn.ReLU(),\n nn.Linear(256, action_dim * 2))\n self.value = nn.Sequential(nn.Linear(shared_out_dim * self._img_dim[0] + scalar_feature_dim, 256),\n nn.ReLU(),\n nn.Linear(256, 1))\n self.to(self.device)\n\n def forward(self, x, h, **kwargs):\n batch_size = x.shape[0]\n\n if self._scalar_feature_dim > 0:\n (imgs, scalars) = self.split(x)\n if hasattr(self, OBS_RMS):\n scalars = self.obs_rms.normalize(scalars)\n else:\n imgs = x\n scalars = torch.empty(batch_size, 0, device=self.device)\n\n imgs = imgs.reshape(batch_size * self._img_dim[0], *self._img_dim[1:]).to(self.device)\n z = self.encoder(imgs)\n\n x = self.fuse((z.reshape(batch_size, -1), scalars.to(self.device)))\n a_mean, a_log_std = torch.chunk(self.action_net(x), chunks=2, dim=1)\n a_std = torch.nn.functional.softplus(a_log_std) + self._eps\n dist = Normal(a_mean, a_std)\n\n val = self.value(x)\n\n return dist, val, h\n", "import argparse\nimport numpy as np\nimport torch\n\nimport rl_sandbox.constants as c\nimport rl_sandbox.transforms.general_transforms as gt\n\nfrom rl_sandbox.agents.random_agents import UniformContinuousAgent\nfrom rl_sandbox.buffers.wrappers.torch_buffer import TorchBuffer\nfrom rl_sandbox.envs.wrappers.action_repeat import ActionRepeatWrapper\nfrom rl_sandbox.envs.wrappers.augment_action import AugmentActionWrapper\nfrom rl_sandbox.envs.wrappers.frame_stack import FrameStackWrapper\nfrom rl_sandbox.envs.wrappers.renderer import GymRenderer\nfrom rl_sandbox.train.train_sac import train_sac\nfrom rl_sandbox.model_architectures.actor_critics.fully_connected_soft_actor_critic import LSTMSquashedGaussianSAC\nfrom rl_sandbox.model_architectures.layers_definition import VALUE_BASED_LINEAR_LAYERS\n\n# This is for script run\nparser = argparse.ArgumentParser()\nparser.add_argument('--seed', type=int, required=True, help=\"Random seed\")\nargs = parser.parse_args()\n\nseed = args.seed\n\nobs_dim = 15\naction_dim = 3\nmin_action = -np.ones(action_dim)\nmax_action = np.ones(action_dim)\n\ndevice = torch.device(\"cuda:0\")\n# device = torch.device(c.CPU)\n\naction_repeat = 1\nnum_frames = 1\nhidden_state_dim = 128\n\nmemory_size = 1000000\nmax_total_steps = 1000000\n\nexperiment_setting = {\n # Auxiliary Tasks\n c.AUXILIARY_TASKS: {},\n\n # Buffer\n c.BUFFER_PREPROCESSING: gt.AsType(),\n c.BUFFER_SETTING: {\n c.KWARGS: {\n c.MEMORY_SIZE: memory_size,\n c.OBS_DIM: (obs_dim,),\n c.H_STATE_DIM: (hidden_state_dim * 2,),\n c.ACTION_DIM: (action_dim,),\n c.REWARD_DIM: (1,),\n c.INFOS: {c.MEAN: ((action_dim,), np.float32),\n c.VARIANCE: ((action_dim,), np.float32),\n c.ENTROPY: ((action_dim,), np.float32),\n c.LOG_PROB: ((1,), np.float32),\n c.VALUE: ((1,), np.float32),\n c.DISCOUNTING: ((1,), np.float32)},\n c.BURN_IN_WINDOW: 19,\n c.PADDING_FIRST: True,\n c.CHECKPOINT_INTERVAL: 0,\n c.CHECKPOINT_PATH: None,\n },\n c.STORAGE_TYPE: c.RAM,\n c.BUFFER_WRAPPERS: [\n {\n c.WRAPPER: TorchBuffer,\n c.KWARGS: {},\n },\n ],\n },\n\n # Environment\n c.ACTION_DIM: action_dim,\n c.CLIP_ACTION: True,\n c.ENV_SETTING: {\n c.ENV_BASE: {\n # c.ENV_NAME: \"Hopper-v2\"\n c.ENV_NAME: \"HopperBulletEnv-v0\"\n },\n c.ENV_TYPE: c.GYM,\n c.ENV_WRAPPERS: [\n {\n c.WRAPPER: GymRenderer,\n c.KWARGS: {},\n },\n # {\n # c.WRAPPER: AugmentActionWrapper,\n # c.KWARGS: {\n # c.ACTION_DIM: action_dim,\n # }\n # },\n {\n c.WRAPPER: ActionRepeatWrapper,\n c.KWARGS: {\n c.ACTION_REPEAT: action_repeat,\n c.DISCOUNT_FACTOR: 1.,\n c.ENABLE_DISCOUNTING: False,\n }\n },\n {\n c.WRAPPER: FrameStackWrapper,\n c.KWARGS: {\n c.NUM_FRAMES: num_frames,\n }\n }\n ]\n },\n c.MIN_ACTION: min_action,\n c.MAX_ACTION: max_action,\n c.OBS_DIM: obs_dim,\n\n # Evaluation\n c.EVALUATION_FREQUENCY: 5000,\n c.EVALUATION_RENDER: False,\n c.EVALUATION_RETURNS: [],\n c.NUM_EVALUATION_EPISODES: 5,\n\n # Exploration\n c.EXPLORATION_STEPS: 1000,\n c.EXPLORATION_STRATEGY: UniformContinuousAgent(min_action,\n max_action,\n np.random.RandomState(seed)),\n \n # General\n c.DEVICE: device,\n c.SEED: seed,\n\n # Load\n c.LOAD_MODEL: False,\n\n # Logging\n c.PRINT_INTERVAL: 5000,\n c.SAVE_INTERVAL: 50000,\n c.LOG_INTERVAL: 1,\n\n # Model\n c.MODEL_SETTING: {\n c.MODEL_ARCHITECTURE: LSTMSquashedGaussianSAC,\n c.KWARGS: {\n c.OBS_DIM: obs_dim,\n c.HIDDEN_STATE_DIM: hidden_state_dim,\n c.ACTION_DIM: action_dim,\n c.SHARED_LAYERS: VALUE_BASED_LINEAR_LAYERS(in_dim=obs_dim),\n c.INITIAL_ALPHA: 1.,\n c.DEVICE: device,\n c.NORMALIZE_OBS: False,\n c.NORMALIZE_VALUE: False,\n },\n },\n \n c.OPTIMIZER_SETTING: {\n c.POLICY: {\n c.OPTIMIZER: torch.optim.Adam,\n c.KWARGS: {\n c.LR: 3e-4,\n },\n },\n c.QS: {\n c.OPTIMIZER: torch.optim.Adam,\n c.KWARGS: {\n c.LR: 3e-4,\n },\n },\n c.ALPHA: {\n c.OPTIMIZER: torch.optim.Adam,\n c.KWARGS: {\n c.LR: 3e-4,\n },\n },\n },\n\n c.EVALUATION_PREPROCESSING: gt.Identity(),\n c.TRAIN_PREPROCESSING: gt.Identity(),\n\n # SAC\n c.ACCUM_NUM_GRAD: 1,\n c.ACTOR_UPDATE_INTERVAL: 1,\n c.BATCH_SIZE: 256,\n c.BUFFER_WARMUP: 1000,\n c.GAMMA: 0.99,\n c.LEARN_ALPHA: True,\n c.MAX_GRAD_NORM: 1e10,\n c.NUM_GRADIENT_UPDATES: 1,\n c.NUM_PREFETCH: 1,\n c.REWARD_SCALING: 1.,\n c.STEPS_BETWEEN_UPDATE: 1,\n c.TARGET_ENTROPY: -action_dim,\n c.TARGET_UPDATE_INTERVAL: 5000,\n c.TAU: 1.,\n c.UPDATE_NUM: 0,\n\n # Progress Tracking\n c.CUM_EPISODE_LENGTHS: [0],\n c.CURR_EPISODE: 1,\n c.NUM_UPDATES: 0,\n c.RETURNS: [],\n\n # Save\n c.SAVE_PATH: f\"../results/pybullet/hopper/gt-sac-fr-lstm-reg_q_targ/{seed}\",\n # c.SAVE_PATH: None,\n\n # train parameters\n c.MAX_TOTAL_STEPS: max_total_steps,\n c.TRAIN_RENDER: False,\n}\n\ntrain_sac(experiment_config=experiment_setting)\n", "import numpy as np\nimport torch\n\nimport rl_sandbox.constants as c\nimport rl_sandbox.transforms.general_transforms as gt\n\nfrom rl_sandbox.agents.random_agents import UniformContinuousAgent\nfrom rl_sandbox.buffers.wrappers.torch_buffer import TorchBuffer\nfrom rl_sandbox.envs.wrappers.absorbing_state import AbsorbingStateWrapper\nfrom rl_sandbox.envs.wrappers.action_repeat import ActionRepeatWrapper\nfrom rl_sandbox.envs.wrappers.frame_stack import FrameStackWrapper\nfrom rl_sandbox.train.train_dac_sac import train_dac_sac\nfrom rl_sandbox.model_architectures.actor_critics.fully_connected_soft_actor_critic import FullyConnectedSeparate, FullyConnectedSquashedGaussianSAC\nfrom rl_sandbox.model_architectures.discriminators.fully_connected_discriminators import ActionConditionedFullyConnectedDiscriminator\nfrom rl_sandbox.model_architectures.layers_definition import VALUE_BASED_LINEAR_LAYERS, SAC_DISCRIMINATOR_LINEAR_LAYERS\n\nseed = 1\nobs_dim = 12\naction_dim = 3\nmin_action = -np.ones(action_dim)\nmax_action = np.ones(action_dim)\n\ndevice = torch.device(\"cuda:0\")\n# device = torch.device(c.CPU)\n\naction_repeat = 1\nnum_frames = 1\n\nmemory_size = max_total_steps = 1000000 // action_repeat\n\nexperiment_setting = {\n # Auxiliary Tasks\n c.AUXILIARY_TASKS: {},\n\n # Buffer\n c.BUFFER_PREPROCESSING: gt.AsType(),\n c.BUFFER_SETTING: {\n c.KWARGS: {\n c.MEMORY_SIZE: memory_size,\n c.OBS_DIM: (obs_dim,),\n c.H_STATE_DIM: (1,),\n c.ACTION_DIM: (action_dim,),\n c.REWARD_DIM: (1,),\n c.INFOS: {c.MEAN: ((action_dim,), np.float32),\n c.VARIANCE: ((action_dim,), np.float32),\n c.ENTROPY: ((action_dim,), np.float32),\n c.LOG_PROB: ((1,), np.float32),\n c.VALUE: ((1,), np.float32),\n c.DISCOUNTING: ((1,), np.float32)},\n c.CHECKPOINT_INTERVAL: 0,\n c.CHECKPOINT_PATH: None,\n },\n c.STORAGE_TYPE: c.RAM,\n c.STORE_NEXT_OBSERVATION: True,\n c.BUFFER_WRAPPERS: [\n {\n c.WRAPPER: TorchBuffer,\n c.KWARGS: {},\n },\n ],\n },\n\n # Environment\n c.ACTION_DIM: action_dim,\n c.CLIP_ACTION: True,\n c.ENV_SETTING: {\n c.ENV_BASE: {\n c.ENV_NAME: \"Hopper-v2\"\n },\n c.ENV_TYPE: c.GYM,\n c.ENV_WRAPPERS: [\n {\n c.WRAPPER: AbsorbingStateWrapper,\n c.KWARGS: {\n c.CREATE_ABSORBING_STATE: True,\n c.MAX_EPISODE_LENGTH: 1000,\n }\n },\n {\n c.WRAPPER: ActionRepeatWrapper,\n c.KWARGS: {\n c.ACTION_REPEAT: action_repeat,\n c.DISCOUNT_FACTOR: 1.,\n c.ENABLE_DISCOUNTING: False,\n }\n },\n {\n c.WRAPPER: FrameStackWrapper,\n c.KWARGS: {\n c.NUM_FRAMES: num_frames,\n }\n }\n ]\n },\n c.MIN_ACTION: min_action,\n c.MAX_ACTION: max_action,\n c.OBS_DIM: obs_dim,\n\n # Evaluation\n c.EVALUATION_FREQUENCY: 5000,\n c.EVALUATION_RENDER: False,\n c.EVALUATION_RETURNS: [],\n c.NUM_EVALUATION_EPISODES: 10,\n\n # Exploration\n c.EXPLORATION_STEPS: 1000,\n c.EXPLORATION_STRATEGY: UniformContinuousAgent(min_action,\n max_action,\n np.random.RandomState(seed)),\n \n # General\n c.DEVICE: device,\n c.SEED: seed,\n\n # Load\n c.LOAD_MODEL: False,\n\n # Logging\n c.PRINT_INTERVAL: 5000,\n c.SAVE_INTERVAL: 500000,\n\n # Model\n c.MODEL_SETTING: {\n c.MODEL_ARCHITECTURE: FullyConnectedSeparate,\n c.KWARGS: {\n c.OBS_DIM: obs_dim,\n c.ACTION_DIM: action_dim,\n c.SHARED_LAYERS: VALUE_BASED_LINEAR_LAYERS(in_dim=obs_dim),\n c.INITIAL_ALPHA: 1.,\n c.DEVICE: device,\n c.NORMALIZE_OBS: False,\n c.NORMALIZE_VALUE: False,\n },\n },\n \n c.OPTIMIZER_SETTING: {\n c.POLICY: {\n c.OPTIMIZER: torch.optim.Adam,\n c.KWARGS: {\n c.LR: 1e-5,\n },\n },\n c.QS: {\n c.OPTIMIZER: torch.optim.Adam,\n c.KWARGS: {\n c.LR: 1e-3,\n },\n },\n c.ALPHA: {\n c.OPTIMIZER: torch.optim.Adam,\n c.KWARGS: {\n c.LR: 1e-3,\n },\n },\n c.DISCRIMINATOR: {\n c.OPTIMIZER: torch.optim.Adam,\n c.KWARGS: {\n c.LR: 1e-3,\n },\n },\n },\n\n # DAC\n c.EXPERT_BUFFER: \"./expert_buffers/mujoco/hopper-v2/gt-sac-separate-fix.pkl\",\n c.DISCRIMINATOR_SETTING: {\n c.MODEL_ARCHITECTURE: ActionConditionedFullyConnectedDiscriminator,\n c.KWARGS: {\n c.OBS_DIM: obs_dim,\n c.ACTION_DIM: action_dim,\n c.OUTPUT_DIM: 1,\n c.LAYERS: SAC_DISCRIMINATOR_LINEAR_LAYERS(in_dim=obs_dim + action_dim),\n c.DEVICE: device,\n }\n },\n c.DISCRIMINATOR_BATCH_SIZE: 256,\n c.GRADIENT_PENALTY_LAMBDA: 10.,\n\n # SAC\n c.ACCUM_NUM_GRAD: 1,\n c.BATCH_SIZE: 256,\n c.BUFFER_WARMUP: 1000,\n c.EVALUATION_PREPROCESSING: gt.Identity(),\n c.GAMMA: 0.99,\n c.LEARN_ALPHA: True,\n c.MAX_GRAD_NORM: 10,\n c.NUM_GRADIENT_UPDATES: 1,\n c.NUM_PREFETCH: 1,\n c.REWARD_SCALING: 1.,\n c.STEPS_BETWEEN_UPDATE: 1,\n c.TARGET_ENTROPY: -3.,\n c.TARGET_UPDATE_INTERVAL: 1,\n c.TAU: 0.005,\n c.TRAIN_PREPROCESSING: gt.Identity(),\n c.UPDATE_NUM: 0,\n\n # Progress Tracking\n c.CUM_EPISODE_LENGTHS: [0],\n c.CURR_EPISODE: 1,\n c.NUM_UPDATES: 0,\n c.RETURNS: [],\n\n # Save\n c.SAVE_PATH: \"./results/hopper-v2/dac/gt-sac-separate-next_obs\",\n # c.SAVE_PATH: None,\n\n # train parameters\n c.MAX_TOTAL_STEPS: max_total_steps,\n c.TRAIN_RENDER: False,\n}\n\ntrain_dac_sac(experiment_config=experiment_setting)\n", "import numpy as np\n\nfrom collections import deque\n\nfrom rl_sandbox.envs.wrappers.wrapper import Wrapper\n\n\nclass FrameStackWrapper(Wrapper):\n def __init__(self, env, num_frames):\n assert num_frames > 0\n super().__init__(env)\n self._num_frames = num_frames\n self.frames = deque([], maxlen=num_frames)\n\n def _get_obs(self):\n assert len(self.frames) == self._num_frames\n return np.stack(self.frames)\n\n def reset(self):\n obs = self._env.reset()\n for _ in range(self._num_frames):\n self.frames.append(obs)\n\n return self._get_obs()\n\n def step(self, action):\n obs, reward, done, info = self._env.step(action)\n self.frames.append(obs)\n\n return self._get_obs(), reward, done, info\n\n def render(self, **kwargs):\n self._env.render(**kwargs)\n\n def seed(self, seed):\n self._env.seed(seed)\n" ]
[ [ "numpy.product", "torch.empty", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.distributions.Normal", "torch.device", "torch.nn.ReLU", "torch.nn.functional.softplus" ], [ "torch.device", "numpy.random.RandomState", "numpy.ones" ], [ "torch.device", "numpy.random.RandomState", "numpy.ones" ], [ "numpy.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bdb3m/Norfolk_Groundwater_Model
[ "5336e088ab45b4640095df3bdd40efb61364f6ac" ]
[ "Model/keras_mmps175.py" ]
[ "\"\"\"\r\nThis network uses the last 26 observations of gwl, tide, and rain to predict the next 18\r\nvalues of gwl for well MMPS-175\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nfrom pandas import DataFrame\r\nfrom pandas import concat\r\nfrom pandas import read_csv\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nimport tensorflow as tf\r\nimport keras\r\nimport keras.backend as K\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.layers import LSTM\r\nfrom keras.layers import Dropout\r\nfrom keras.layers import Activation\r\nfrom math import sqrt\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\nimport numpy as np\r\nimport random as rn\r\nimport os\r\nmatplotlib.rcParams.update({'font.size': 8})\r\n\r\n\r\n# convert time series into supervised learning problem\r\ndef series_to_supervised(data, n_in=1, n_out=1, dropnan=True):\r\n n_vars = 1 if type(data) is list else data.shape[1]\r\n df = DataFrame(data)\r\n cols, names = list(), list()\r\n # input sequence (t-n, ... t-1)\r\n for i in range(n_in, 0, -1):\r\n cols.append(df.shift(i))\r\n names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]\r\n # forecast sequence (t, t+1, ... t+n)\r\n for i in range(0, n_out):\r\n cols.append(df.shift(-i))\r\n if i == 0:\r\n names += [('var%d(t)' % (j+1)) for j in range(n_vars)]\r\n else:\r\n names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]\r\n # put it all together\r\n agg = concat(cols, axis=1)\r\n agg.columns = names\r\n # drop rows with NaN values\r\n if dropnan:\r\n agg.dropna(inplace=True)\r\n return agg\r\n\r\n\r\n# def create_weights(train_labels):\r\n# obs_mean = np.mean(train_labels, axis=-1)\r\n# obs_mean = np.reshape(obs_mean, (n_batch, 1))\r\n# obs_mean = np.repeat(obs_mean, n_ahead, axis=1)\r\n# weights = (train_labels + obs_mean) / (2 * obs_mean)\r\n# return weights\r\n#\r\n#\r\n# def sq_err(y_true, y_pred):\r\n# return K.square(y_pred - y_true)\r\n#\r\n#\r\ndef mse(y_true, y_pred):\r\n return K.mean(K.square(y_pred - y_true), axis=-1)\r\n\r\ndef rmse(y_true, y_pred):\r\n return K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1))\r\n\r\n\r\ndef pw_rmse(y_true, y_pred):\r\n # num_rows, num_cols = K.int_shape(y_true)[0], K.int_shape(y_true)[1]\r\n # print(num_rows, num_cols)\r\n act_mean = K.mean(y_true, axis=-1)\r\n # print(\"act_mean 1 is:\", act_mean)\r\n act_mean = K.reshape(act_mean, (n_batch, 1))\r\n # print(\"act_mean is: \", act_mean)\r\n mean_repeat = K.repeat_elements(act_mean, n_ahead, axis=1)\r\n # print(\"mean_repeat is:\", mean_repeat)\r\n weights = (y_true+mean_repeat)/(2*mean_repeat)\r\n return K.sqrt(K.mean((K.square(y_pred - y_true)*weights), axis=-1))\r\n\r\n\r\n# configure network\r\nn_lags = 116\r\nn_ahead = 18\r\nn_features = 3\r\nn_train = 52551\r\nn_test = 8359\r\nn_epochs = 500\r\nn_neurons = 10\r\nn_batch = 52551\r\n\r\n# load dataset\r\ndataset_raw = read_csv(\"C:/Users/Ben Bowes/Documents/HRSD GIS/Site Data/MMPS_175_no_blanks.csv\",\r\n index_col=None, parse_dates=True, infer_datetime_format=True)\r\n# dataset_raw = dataset_raw[0:len(dataset_raw)-1]\r\n\r\n# split datetime column into train and test for plots\r\ntrain_dates = dataset_raw[['Datetime', 'GWL', 'Tide', 'Precip.']].iloc[:n_train]\r\ntest_dates = dataset_raw[['Datetime', 'GWL', 'Tide', 'Precip.']].iloc[n_train:]\r\ntest_dates = test_dates.reset_index(drop=True)\r\ntest_dates['Datetime'] = pd.to_datetime(test_dates['Datetime'])\r\n\r\n# drop columns we don't want to predict\r\ndataset = dataset_raw.drop(dataset_raw.columns[[0]], axis=1)\r\n\r\nvalues = dataset.values\r\nvalues = values.astype('float32')\r\n\r\ngwl = values[:, 0]\r\ngwl = gwl.reshape(gwl.shape[0], 1)\r\n\r\ntide = values[:, 1]\r\ntide = tide.reshape(tide.shape[0], 1)\r\n\r\nrain = values[:, 2]\r\nrain = rain.reshape(rain.shape[0], 1)\r\n\r\n# normalize features with individual scalers\r\ngwl_scaler, tide_scaler, rain_scaler = MinMaxScaler(), MinMaxScaler(), MinMaxScaler()\r\ngwl_scaled = gwl_scaler.fit_transform(gwl)\r\ntide_scaled = tide_scaler.fit_transform(tide)\r\nrain_scaled = rain_scaler.fit_transform(rain)\r\n\r\nscaled = np.concatenate((gwl_scaled, tide_scaled, rain_scaled), axis=1)\r\n\r\n# frame as supervised learning\r\nreframed = series_to_supervised(scaled, n_lags, n_ahead)\r\nvalues = reframed.values\r\n\r\n# split into train and test sets\r\ntrain, test = values[:n_train, :], values[n_train:, :]\r\n# split into input and outputs\r\ninput_cols, label_cols = [], []\r\nfor i in range(values.shape[1]):\r\n if i <= n_lags*n_features-1:\r\n input_cols.append(i)\r\n elif i % 3 != 0:\r\n input_cols.append(i)\r\n elif i % 3 == 0:\r\n label_cols.append(i)\r\ntrain_X, train_y = train[:, input_cols], train[:, label_cols] # [start:stop:increment, (cols to include)]\r\ntest_X, test_y = test[:, input_cols], test[:, label_cols]\r\n# reshape input to be 3D [samples, timesteps, features]\r\ntrain_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))\r\ntest_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))\r\nprint(train_X.shape, train_y.shape, test_X.shape, test_y.shape)\r\n\r\n#create weights for peak weighted rmse loss function\r\n# weights = create_weights(train_y)\r\n\r\n# load model here if needed\r\n# model = keras.models.load_model(\"C:/Users/Ben Bowes/PycharmProjects/Tensorflow/keras_models/mmps175.h5\",\r\n# custom_objects={'pw_rmse':pw_rmse})\r\n\r\n# set random seeds for model reproducibility as suggested in:\r\n# https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development\r\nos.environ['PYTHONHASHSEED'] = '0'\r\nnp.random.seed(42)\r\nrn.seed(12345)\r\nsession_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\r\ntf.set_random_seed(1234)\r\nsess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\r\nK.set_session(sess)\r\n\r\n# define model\r\nmodel = Sequential()\r\nmodel.add(LSTM(units=n_neurons, input_shape=(None, train_X.shape[2])))\r\n# model.add(LSTM(units=n_neurons, return_sequences=True, input_shape=(None, train_X.shape[2])))\r\n# model.add(LSTM(units=n_neurons, return_sequences=True))\r\n# model.add(LSTM(units=n_neurons))\r\nmodel.add(Dropout(.1))\r\nmodel.add(Dense(input_dim=n_neurons, activation='linear', units=n_ahead))\r\n# model.add(Activation('linear'))\r\nmodel.compile(loss=pw_rmse, optimizer='adam')\r\ntbCallBack = keras.callbacks.TensorBoard(log_dir='C:/tmp/tensorflow/keras/logs', histogram_freq=0, write_graph=True,\r\n write_images=False)\r\nearlystop = keras.callbacks.EarlyStopping(monitor='loss', min_delta=0.0001, patience=5, verbose=1, mode='auto')\r\nhistory = model.fit(train_X, train_y, batch_size=n_batch, epochs=n_epochs, verbose=2, shuffle=False,\r\n callbacks=[earlystop, tbCallBack])\r\n\r\n# save model\r\n# model.save(\"C:/Users/Ben Bowes/PycharmProjects/Tensorflow/keras_models/mmps175.h5\")\r\n\r\n# plot model history\r\n# plt.plot(history.history['loss'], label='train')\r\n# # plt.plot(history.history['val_loss'], label='validate')\r\n# # plt.legend()\r\n# # ticks = np.arange(0, n_epochs, 1) # (start,stop,increment)\r\n# # plt.xticks(ticks)\r\n# plt.xlabel(\"Epochs\")\r\n# plt.ylabel(\"Loss\")\r\n# plt.tight_layout()\r\n# plt.show()\r\n\r\n# make predictions\r\ntrainPredict = model.predict(train_X)\r\nyhat = model.predict(test_X)\r\ninv_trainPredict = gwl_scaler.inverse_transform(trainPredict)\r\ninv_yhat = gwl_scaler.inverse_transform(yhat)\r\ninv_y = gwl_scaler.inverse_transform(test_y)\r\ninv_train_y = gwl_scaler.inverse_transform(train_y)\r\n\r\n# save test predictions and observed\r\ninv_yhat_df = DataFrame(inv_yhat)\r\ninv_yhat_df.to_csv(\"C:/Users/Ben Bowes/PycharmProjects/Tensorflow/mmps175_results/predicted.csv\")\r\ninv_y_df = DataFrame(inv_y)\r\ninv_y_df.to_csv(\"C:/Users/Ben Bowes/PycharmProjects/Tensorflow/mmps175_results/observed.csv\")\r\n\r\n# calculate RMSE for whole test series (each forecast step)\r\nRMSE_forecast = []\r\nfor i in np.arange(0, n_ahead, 1):\r\n rmse = sqrt(mean_squared_error(inv_y[:, i], inv_yhat[:, i]))\r\n RMSE_forecast.append(rmse)\r\nRMSE_forecast = DataFrame(RMSE_forecast)\r\nrmse_avg = sqrt(mean_squared_error(inv_y, inv_yhat))\r\nprint('Average Test RMSE: %.3f' % rmse_avg)\r\nRMSE_forecast.to_csv(\"C:/Users/Ben Bowes/PycharmProjects/Tensorflow/mmps175_results/RMSE.csv\")\r\n\r\n# calculate RMSE for each individual time step\r\nRMSE_timestep = []\r\nfor i in np.arange(0, inv_yhat.shape[0], 1):\r\n rmse = sqrt(mean_squared_error(inv_y[i, :], inv_yhat[i, :]))\r\n RMSE_timestep.append(rmse)\r\nRMSE_timestep = DataFrame(RMSE_timestep)\r\n\r\n# plot rmse vs forecast steps\r\nplt.plot(RMSE_forecast, 'ko')\r\nticks = np.arange(0, n_ahead, 1) # (start,stop,increment)\r\nplt.xticks(ticks)\r\nplt.ylabel(\"RMSE (ft)\")\r\nplt.xlabel(\"Forecast Step\")\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n# plot training predictions\r\nplt.plot(inv_train_y[:, 0], label='actual')\r\nplt.plot(inv_trainPredict[:, 0], label='predicted')\r\nplt.xlabel(\"Timestep\")\r\nplt.ylabel(\"GWL (ft)\")\r\nplt.title(\"Training Predictions\")\r\n# ticks = np.arange(0, n_ahead, 1)\r\n# plt.xticks(ticks)\r\nplt.legend()\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n# plot test predictions for Hermine, Julia, and Matthew\r\ndates = DataFrame(test_dates[[\"Datetime\"]][n_lags:-n_ahead+1])\r\ndates = dates.reset_index(inplace=False)\r\ndates = dates.drop(columns=['index'])\r\ndates = dates[5700:8000]\r\ndates = dates.reset_index(inplace=False)\r\ndates = dates.drop(columns=['index'])\r\ndates_9 = DataFrame(test_dates[[\"Datetime\"]][n_lags+8:-n_ahead+9])\r\ndates_9 = dates_9.reset_index(inplace=False)\r\ndates_9 = dates_9.drop(columns=['index'])\r\ndates_9 = dates_9[5700:8000]\r\ndates_9 = dates_9.reset_index(inplace=False)\r\ndates_9 = dates_9.drop(columns=['index'])\r\ndates_18 = DataFrame(test_dates[[\"Datetime\"]][n_lags+17:])\r\ndates_18 = dates_18.reset_index(inplace=False)\r\ndates_18 = dates_18.drop(columns=['index'])\r\ndates_18 = dates_18[5700:8000]\r\ndates_18 = dates_18.reset_index(inplace=False)\r\ndates_18 = dates_18.drop(columns=['index'])\r\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(6.5, 3))\r\nx_ticks = np.arange(0, 2300, 168)\r\nax1.plot(inv_y[5700:8000, 0], 'k-', label='Obs.')\r\nax1.plot(inv_yhat[5700:8000, 0], 'k:', label='Pred.')\r\nax1.set_xticks(x_ticks)\r\nax1.set_xticklabels(dates['Datetime'][x_ticks].dt.strftime('%Y-%m-%d'), rotation='vertical')\r\nax2.plot(inv_y[5700:8000, 8], 'k-', label='Obs.')\r\nax2.plot(inv_yhat[5700:8000, 8], 'k:', label='Pred.')\r\nax2.set_xticks(x_ticks)\r\nax2.set_xticklabels(dates_9['Datetime'][x_ticks].dt.strftime('%Y-%m-%d'), rotation='vertical')\r\nax3.plot(inv_y[5700:8000, 17], 'k-', label='Obs.')\r\nax3.plot(inv_yhat[5700:8000, 17], 'k:', label='Pred.')\r\nax3.set_xticks(x_ticks)\r\nax3.set_xticklabels(dates_18['Datetime'][x_ticks].dt.strftime('%Y-%m-%d'), rotation='vertical')\r\nax1.set(ylabel=\"GWL (ft)\", title='t+1')\r\nax2.set(title='t+9')\r\nax3.set(title='t+18')\r\nplt.legend()\r\nplt.tight_layout()\r\nplt.show()\r\n# fig.savefig('C:/Users/Ben Bowes/Documents/HRSD GIS/Presentation Images/Paper Figures/MMPS175_preds.tif', dpi=300)\r\n\r\n# create dfs of timestamps, obs, and pred data to find peak values and times\r\nobs_t1 = np.reshape(inv_y[5700:8000, 0], (2300, 1))\r\npred_t1 = np.reshape(inv_yhat[5700:8000, 0], (2300,1))\r\ndf_t1 = np.concatenate([obs_t1, pred_t1], axis=1)\r\ndf_t1 = DataFrame(df_t1, index=None, columns=[\"obs\", \"pred\"])\r\ndf_t1 = pd.concat([df_t1, dates], axis=1)\r\ndf_t1 = df_t1.set_index(\"Datetime\")\r\n\r\nobs_t9 = np.reshape(inv_y[5700:8000, 8], (2300, 1))\r\npred_t9 = np.reshape(inv_yhat[5700:8000, 8], (2300,1))\r\ndf_t9 = np.concatenate([obs_t9, pred_t9], axis=1)\r\ndf_t9 = DataFrame(df_t9, index=None, columns=[\"obs\", \"pred\"])\r\ndf_t9 = pd.concat([df_t9, dates_9], axis=1)\r\ndf_t9 = df_t9.set_index(\"Datetime\")\r\n\r\nobs_t18 = np.reshape(inv_y[5700:8000, 17], (2300, 1))\r\npred_t18 = np.reshape(inv_yhat[5700:8000, 17], (2300,1))\r\ndf_t18 = np.concatenate([obs_t18, pred_t18], axis=1)\r\ndf_t18 = DataFrame(df_t18, index=None, columns=[\"obs\", \"pred\"])\r\ndf_t18 = pd.concat([df_t18, dates_18], axis=1)\r\ndf_t18 = df_t18.set_index(\"Datetime\")\r\n\r\nHerminePeak_t1 = df_t1.loc[\"2016-09-02T00:00:00.000000000\":\"2016-09-08T00:00:00.000000000\"].max()\r\nHerminePeak_t1_time = df_t1.loc[\"2016-09-02T00:00:00.000000000\":\"2016-09-08T00:00:00.000000000\"].idxmax()\r\nJuliaPeak_t1 = df_t1.loc[\"2016-09-18T00:00:00.000000000\":\"2016-09-25T00:00:00.000000000\"].max()\r\nJuliaPeak_t1_time = df_t1.loc[\"2016-09-18T00:00:00.000000000\":\"2016-09-25T00:00:00.000000000\"].idxmax()\r\nMatthewPeak_t1 = df_t1.loc[\"2016-10-07T00:00:00.000000000\":\"2016-10-14T00:00:00.000000000\"].max()\r\nMatthewPeak_t1_time = df_t1.loc[\"2016-10-07T00:00:00.000000000\":\"2016-10-14T00:00:00.000000000\"].idxmax()\r\n\r\nHerminePeak_t9 = df_t9.loc[\"2016-09-02T00:00:00.000000000\":\"2016-09-08T00:00:00.000000000\"].max()\r\nHerminePeak_t9_time = df_t9.loc[\"2016-09-02T00:00:00.000000000\":\"2016-09-08T00:00:00.000000000\"].idxmax()\r\nJuliaPeak_t9 = df_t9.loc[\"2016-09-18T00:00:00.000000000\":\"2016-09-25T00:00:00.000000000\"].max()\r\nJuliaPeak_t9_time = df_t9.loc[\"2016-09-18T00:00:00.000000000\":\"2016-09-25T00:00:00.000000000\"].idxmax()\r\nMatthewPeak_t9 = df_t9.loc[\"2016-10-07T00:00:00.000000000\":\"2016-10-14T00:00:00.000000000\"].max()\r\nMatthewPeak_t9_time = df_t9.loc[\"2016-10-07T00:00:00.000000000\":\"2016-10-14T00:00:00.000000000\"].idxmax()\r\n\r\nHerminePeak_t18 = df_t18.loc[\"2016-09-02T00:00:00.000000000\":\"2016-09-08T00:00:00.000000000\"].max()\r\nHerminePeak_t18_time = df_t18.loc[\"2016-09-02T00:00:00.000000000\":\"2016-09-08T00:00:00.000000000\"].idxmax()\r\nJuliaPeak_t18 = df_t18.loc[\"2016-09-18T00:00:00.000000000\":\"2016-09-25T00:00:00.000000000\"].max()\r\nJuliaPeak_t18_time = df_t18.loc[\"2016-09-18T00:00:00.000000000\":\"2016-09-25T00:00:00.000000000\"].idxmax()\r\nMatthewPeak_t18 = df_t18.loc[\"2016-10-07T00:00:00.000000000\":\"2016-10-14T00:00:00.000000000\"].max()\r\nMatthewPeak_t18_time = df_t18.loc[\"2016-10-07T00:00:00.000000000\":\"2016-10-14T00:00:00.000000000\"].idxmax()\r\n\r\npeaks_values = DataFrame([HerminePeak_t1, JuliaPeak_t1, MatthewPeak_t1, HerminePeak_t9, JuliaPeak_t9, MatthewPeak_t9,\r\n HerminePeak_t18, JuliaPeak_t18, MatthewPeak_t18])\r\n\r\npeaks_values = peaks_values.transpose()\r\npeaks_values.columns = ['HerminePeak_t1', 'JuliaPeak_t1', 'MatthewPeak_t1', 'HerminePeak_t9', 'JuliaPeak_t9',\r\n 'MatthewPeak_t9', 'HerminePeak_t18', 'JuliaPeak_t18', 'MatthewPeak_t18']\r\n\r\npeak_times = DataFrame([HerminePeak_t1_time, JuliaPeak_t1_time, MatthewPeak_t1_time, HerminePeak_t9_time,\r\n JuliaPeak_t9_time, MatthewPeak_t9_time, HerminePeak_t18_time, JuliaPeak_t18_time,\r\n MatthewPeak_t18_time])\r\n\r\npeak_times = peak_times.transpose()\r\npeak_times.columns = ['HermineTime_t1', 'JuliaTime_t1', 'MatthewTime_t1', 'HermineTime_t9', 'JuliaTime_t9',\r\n 'MatthewTime_t9', 'HermineTime_t18', 'JuliaTime_t18', 'MatthewTime_t18']\r\n\r\npeaks_df = pd.concat([peaks_values, peak_times], axis=1)\r\ncols = ['HerminePeak_t1', 'HermineTime_t1', 'JuliaPeak_t1', 'JuliaTime_t1', 'MatthewPeak_t1', 'MatthewTime_t1',\r\n 'HerminePeak_t9', 'HermineTime_t9', 'JuliaPeak_t9', 'JuliaTime_t9', 'MatthewPeak_t9', 'MatthewTime_t9',\r\n 'HerminePeak_t18', 'HermineTime_t18', 'JuliaPeak_t18', 'JuliaTime_t18', 'MatthewPeak_t18', 'MatthewTime_t18']\r\npeaks_df = peaks_df[cols]\r\npeaks_df.to_csv(\"C:/Users/Ben Bowes/PycharmProjects/Tensorflow/mmps175_results/peaks.csv\")\r\n\r\n# plot all test predictions\r\nplt.plot(inv_y[5700:8000, 0], label='actual')\r\nplt.plot(inv_yhat[5700:8000, 0], label='predicted')\r\nplt.xlabel(\"Timestep\")\r\nplt.ylabel(\"GWL (ft)\")\r\nplt.title(\"Testing Predictions\")\r\n# ticks = np.arange(0, n_ahead, 1)\r\n# plt.xticks(ticks)\r\nplt.legend()\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n# # plot test predictions, 18 hours from specific period\r\n# plt.plot(inv_y[6275, :], label='actual')\r\n# plt.plot(inv_yhat[6275, :], label='predicted')\r\n# plt.xlabel(\"Timestep\")\r\n# plt.ylabel(\"GWL (ft)\")\r\n# plt.title(\"Testing Predictions\")\r\n# # ticks = np.arange(0, n_ahead, 1)\r\n# # plt.xticks(ticks)\r\n# plt.legend()\r\n# plt.tight_layout()\r\n# plt.show()\r\n\r\n# combine prediction data with observations\r\nstart_date, stop_date = \"2016-09-17 00:00:00\", \"2016-09-25 00:00:00\"\r\nact_cols, pred_cols = [], []\r\nfor i in range(n_ahead):\r\n gwl_name = \"Actual t+{0}\".format(i)\r\n pred_name = 'Predicted t+{0}'.format(i)\r\n act_cols.append(gwl_name)\r\n pred_cols.append(pred_name)\r\ndf_act = DataFrame(inv_y, columns=act_cols)\r\ndf_pred = DataFrame(inv_yhat, columns=pred_cols)\r\ndf_gwl = pd.concat([df_act, df_pred], axis=1)\r\ndf = pd.concat([test_dates, df_gwl], axis=1)\r\ndf = df[:inv_y.shape[0]]\r\ndf = df.set_index('Datetime')\r\nstorm = df.loc[start_date:stop_date]\r\nstorm.reset_index(inplace=True)\r\n\r\n# plot test predictions with observed rain and tide\r\nax = storm[[\"Tide\", \"Actual t+0\", \"Predicted t+0\"]].plot(color=[\"k\"], style=[\":\", '-', '-.'], legend=None)\r\nstart, end = ax.get_xlim()\r\nticks = np.arange(0, end, 24) # (start,stop,increment)\r\nax2 = ax.twinx()\r\n# ax2.set_ylim(ymax=2.5, ymin=0)\r\n# ax.set_ylim(ymax=4, ymin=-1.25)\r\nax2.invert_yaxis()\r\nstorm[\"Precip.\"].plot.bar(ax=ax2, color=\"k\")\r\nax2.set_xticks([])\r\nax.set_xticks(ticks)\r\nax.set_xticklabels(storm.loc[ticks, 'Datetime'].dt.strftime('%Y-%m-%d'), rotation='vertical')\r\nax.set_ylabel(\"Hourly Avg GW/Tide Level (ft)\")\r\nax2.set_ylabel(\"Total Hourly Precip. (in)\")\r\nlines, labels = ax.get_legend_handles_labels()\r\nlines2, labels2 = ax2.get_legend_handles_labels()\r\nax2.legend(lines + lines2, labels + labels2, loc=1) # location: 0=best, 9=top center\r\nplt.tight_layout()\r\nplt.show()\r\n# save plot for publication\r\n# plt.savefig('C:/Users/Ben Bowes/Documents/HRSD GIS/Presentation Images/Plots/Floods_GWL_comparisons/'\r\n# '20160919_bw_averaged.png', dpi=300)\r\n\r\n# calculate NSE for each forecast period\r\nNSE_timestep = []\r\nfor i in np.arange(0, inv_yhat.shape[0], 1):\r\n num_diff = np.subtract(inv_y[i, :], inv_yhat[i, :])\r\n num_sq = np.square(num_diff)\r\n numerator = sum(num_sq)\r\n denom_diff = np.subtract(inv_y[i, :], np.mean(inv_y[i, :]))\r\n denom_sq = np.square(denom_diff)\r\n denominator = sum(denom_sq)\r\n if denominator == 0:\r\n nse = 'NaN'\r\n else:\r\n nse = 1-(numerator/denominator)\r\n NSE_timestep.append(nse)\r\nNSE_timestep_df = DataFrame(NSE_timestep)\r\n\r\n# calculate NSE for each timestep ahead\r\nNSE_forecast = []\r\nfor i in np.arange(0, inv_yhat.shape[1], 1):\r\n num_diff = np.subtract(inv_y[:, i], inv_yhat[:, i])\r\n num_sq = np.square(num_diff)\r\n numerator = sum(num_sq)\r\n denom_diff = np.subtract(inv_y[:, i], np.mean(inv_y[:, i]))\r\n denom_sq = np.square(denom_diff)\r\n denominator = sum(denom_sq)\r\n if denominator == 0:\r\n nse = 'NaN'\r\n else:\r\n nse = 1-(numerator/denominator)\r\n NSE_forecast.append(nse)\r\nNSE_forecast_df = DataFrame(NSE_forecast)\r\nNSE_forecast_df.to_csv(\"C:/Users/Ben Bowes/PycharmProjects/Tensorflow/mmps175_results/NSE.csv\")\r\n\r\n# plot NSE vs forecast steps\r\nplt.plot(NSE_forecast, 'ko')\r\nticks = np.arange(0, n_ahead, 1) # (start,stop,increment)\r\nplt.xticks(ticks)\r\nplt.ylabel(\"NSE\")\r\nplt.xlabel(\"Forecast Step\")\r\nplt.tight_layout()\r\nplt.show()\r\n" ]
[ [ "matplotlib.pyplot.legend", "pandas.to_datetime", "pandas.DataFrame", "sklearn.metrics.mean_squared_error", "numpy.concatenate", "matplotlib.pyplot.plot", "numpy.mean", "tensorflow.get_default_graph", "sklearn.preprocessing.MinMaxScaler", "numpy.square", "pandas.read_csv", "matplotlib.pyplot.tight_layout", "numpy.reshape", "numpy.arange", "numpy.subtract", "tensorflow.ConfigProto", "pandas.concat", "matplotlib.pyplot.title", "matplotlib.rcParams.update", "tensorflow.set_random_seed", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.random.seed", "matplotlib.pyplot.subplots", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
guenthermi/table-embeddings
[ "3ce094483fc5057b18f898d450a7c376d49818fa" ]
[ "deco_classifier/web_table_multi_embedding_model.py" ]
[ "import numpy as np\nimport sys\n\nsys.path.insert(0, 'embedding/')\n\nNORMALIZATION = 'individual' # 'individual', 'once', or 'none'\nEPSILON = 1e-5 # only to prevent division by zero\n\nfrom fasttext_web_table_embeddings import FastTextWebTableModel\n\n\nclass WebTableMultiEmbeddingModel:\n def __init__(self, filenames):\n self.fmodels = []\n for filename in filenames:\n self.fmodels.append(FastTextWebTableModel.load_model(filename))\n\n def get_features(self, text_value):\n header_vectors = []\n data_vectors = []\n for fmodel in self.fmodels:\n header_vectors.append(fmodel.get_header_vector(text_value))\n data_vectors.append(fmodel.get_data_vector(text_value))\n header_vector = np.concatenate(header_vectors)\n data_vector = np.concatenate(data_vectors)\n if NORMALIZATION == 'individual':\n header_vector /= np.linalg.norm(header_vector) + EPSILON\n data_vector /= np.linalg.norm(data_vector) + EPSILON\n return np.concatenate([header_vector, data_vector])\n elif NORMALIZATION == 'once':\n vec = np.concatenate([header_vector, data_vector])\n vec /= np.linalg.norm(vec) + EPSILON\n return vec\n else:\n return np.concatenate([header_vector, data_vector])\n" ]
[ [ "numpy.concatenate", "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
tainacan/data_science
[ "a36c977f3aba6ce8bc45b1433ead673fd3c2674f", "a36c977f3aba6ce8bc45b1433ead673fd3c2674f", "a36c977f3aba6ce8bc45b1433ead673fd3c2674f" ]
[ "omeka_tainacan (BCE_2020)/omeka_itens_csv.py", "FAPESP/coleta_amostral/webScraping_SophiA.py", "FAPESP/coleta_amostral/webScraping_Iphan_SicgInstituicao.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\nimport requests\nfrom collections import defaultdict\nimport pandas as pd\nimport time\n\nendpoint_items = 'http://bdce.unb.br/api/items'\nendpoint_collections = 'http://bdce.unb.br/api/collections'\nresponse = requests.get(endpoint_items, params = {'page':'1'})\nmetadata_dict = defaultdict(list)\nmetadatum_dict = {'Coordenadora do Curso de Comunicação Organizacional':[],'Diretor de Marketing':[],'Diagramador(es)':[],'Repórteres':[],'Editor ou diretor de arte':[],'Coordenadora de Laboratórios':[],'Chefe de Departamento de Comunicação Organizacional':[],'Suporte de informática':[],'Publisher':[],'Projeto de Marketing':[],'Equipe':[],'Secretário de redação':[],'Monitor(es)':[],'Projeto gráfico':[],'Revisão':[],'Chefe de Departamento de Audiovisuais e Publicidade':[],'Editor(es)':[],'Colaborador(es)':[],'Executivo de Marketing':[],'Coordenador(a) de Graduação':[],'Editor(a) de Arte':[],'Localização no CEDOC':[],'Creator':[],'Editor(a) executivo':[],'Colaboradores':[],'Revisor de arte':[],'Coordenadora de Projetos Finais':[],'Dimensões físicas':[],'Secretária de Redação':[],'Professor(es)':[],'Coordenador de Pós-Graduação':[],'Fotógrafo':[],'Secretária de Marketing':[],'Capa':[],'Localização no arquivo':[],'Impressão':[],'Coordenador(a) de Extensão':[],'Subject':[],'Editor(a) chefe':[],'Secretário(a)':[],'Revisor(es)':[],'Chefe de Departamento de Jornalismo':[],'Ilustrador(es)':[],'Title':[],'Notas':[],'Jornalista(s)':[],'Gráfica':[],'Date':[],'Editor de Fotográfia':[]}\nmetadata_dict.update(metadatum_dict)\nitems = response.json()\n\n#Extração dos Metadados\npage = 0\n\nwhile requests.get(endpoint_items, params = {'page':page}).json():\n \n items = requests.get(endpoint_items, params = {'page':page}).json()\n \n page+=1\n \n print(page, end=\", \")\n \n for item in items:\n \n #### COLECAO E ID ####\n \n #Id do Item\n metadata_dict['id'].append(item['id'])\n \n #Coleção do Item\n try:\n metadata_dict['colecao'].append(item['collection']['id'])\n except:\n metadata_dict['colecao'].append('')\n \n \n #### METADADOS ####\n #Dicionário com todos os metadados possíveis dos itens, mapeado previamente.\n metadatum_dict = {'Coordenadora do Curso de Comunicação Organizacional':[],'Diretor de Marketing':[],\n 'Diagramador(es)':[],'Repórteres':[],'Editor ou diretor de arte':[],\n 'Coordenadora de Laboratórios':[],'Chefe de Departamento de Comunicação Organizacional':[],\n 'Suporte de informática':[],'Publisher':[],'Projeto de Marketing':[],'Equipe':[],\n 'Secretário de redação':[],'Monitor(es)':[],'Projeto gráfico':[],'Revisão':[],\n 'Chefe de Departamento de Audiovisuais e Publicidade':[],'Editor(es)':[],'Colaborador(es)':[],\n 'Executivo de Marketing':[],'Coordenador(a) de Graduação':[],'Editor(a) de Arte':[],\n 'Localização no CEDOC':[],'Creator':[],'Editor(a) executivo':[],'Colaboradores':[],\n 'Revisor de arte':[],'Coordenadora de Projetos Finais':[],'Dimensões físicas':[],\n 'Secretária de Redação':[],'Professor(es)':[],'Coordenador de Pós-Graduação':[],'Fotógrafo':[],\n 'Secretária de Marketing':[],'Capa':[],'Localização no arquivo':[],'Impressão':[],\n 'Coordenador(a) de Extensão':[],'Subject':[],'Editor(a) chefe':[],'Secretário(a)':[],\n 'Revisor(es)':[],'Chefe de Departamento de Jornalismo':[],'Ilustrador(es)':[],'Title':[],\n 'Notas':[],'Jornalista(s)':[],'Gráfica':[],'Date':[],'Editor de Fotográfia':[]}\n \n #Faz um dicionário que verifica os valores dos metadados disponíveis no item\n for metadata in item['element_texts']:\n \n for key in metadatum_dict.keys():\n \n if key == metadata['element']['name']:\n metadatum_dict[key].append(metadata['text'])\n \n else:\n metadatum_dict[key].append('')\n \n #Adiciona os valores do dicinário anterior ao dicionário com os valores finais.\n for key in metadatum_dict.keys():\n \n metadatum_dict[key] = list(filter(None, metadatum_dict[key]))\n \n if metadatum_dict[key]:\n metadata_dict[key].append(\"||\".join(set(metadatum_dict[key])))\n \n else:\n metadata_dict[key].append(\"\".join(set(metadatum_dict[key])))\n \n ##### ANEXOS #####\n \n #O json do item direcina par outro json com os links dos arquivos anexados ao item\n lista_att = []\n\n #acessando o endpoint do json dos anexos do item\n files = requests.get(item['files']['url'])\n\n #adiciona a url de cada anexo em uma lista\n for file in files.json():\n lista_att.append(file['file_urls']['original'])\n\n #para documento principal no Tainacan\n if not lista_att:\n document = ''\n attch = ''\n \n else:\n document = lista_att[0]\n\n #para anexos no Tainacan\n if len(lista_att) >1:\n attch = \"||\".join(lista_att[1:])\n else:\n attch = ''\n metadata_dict['document'].append(document)\n metadata_dict['attachment'].append(attch) \n\n #### EXIBIÇÕES ####\n exhibit_dict = defaultdict(list)\n \n exhibit_endpoint = item['extended_resources']['exhibit_pages']['url']\n exhibits = requests.get(exhibit_endpoint).json()\n\n \n if len(exhibits) == 0:\n exhibit_dict['id'].append('')\n exhibit_dict['title'].append('')\n \n elif len(exhibits) == 9:\n exhibit_dict['id'].append(str(exhibits['id']))\n exhibit_dict['title'].append(exhibits['title'])\n \n else:\n for exhibit in exhibits:\n exhibit_dict['id'].append(str(exhibit['id']))\n exhibit_dict['title'].append(exhibit['title'])\n\n metadata_dict['exhibit_id'].append(\"||\".join(set(exhibit_dict['id'])))\n metadata_dict['exhibit_name'].append(\"||\".join(set(exhibit_dict['title'])))\n \n \n #### GEOLOCALIZAÇÕES ####\n if 'geolocations' in item['extended_resources'].keys():\n \n geolocation_endpoint = item['extended_resources']['geolocations']['url']\n geolocation = requests.get(geolocation_endpoint).json()\n \n #Latitude, Longitude, Endereço\n metadata_dict['geo_latitude'].append(geolocation['latitude'])\n metadata_dict['geo_longitude'].append(geolocation['longitude'])\n metadata_dict['geo_adress'].append(geolocation['address'])\n else:\n metadata_dict['geo_latitude'].append('')\n metadata_dict['geo_longitude'].append('')\n metadata_dict['geo_adress'].append('')\n \n \n #### TAGS ####\n lista_tags = []\n \n for tag in item['tags']:\n lista_tags.append(tag['name'])\n \n lista_tags = list(filter(None, lista_tags))\n \n if len(lista_tags)>1:\n metadata_dict['tags'].append(\"||\".join(set(lista_tags)))\n else:\n metadata_dict['tags'].append(\"\".join(set(lista_tags)))\n \n time.sleep(20)\n \nfor key in metadata_dict.keys():\n print(key, len(metadata_dict[key]))\n\nexpt_df = pd.DataFrame(metadata_dict)\nexpt_df.to_csv('itens_omeka_bdce.csv')\n", "from selenium import webdriver\r\nimport pandas as pd\r\nimport random\r\nimport time\r\n\r\n#Configura o webdriver como Firefox\r\n#Link para donwload do geckodriver do Firefox - https://github.com/mozilla/geckodriver/releases\r\n#Necessita do geckodriver salvo em uma pasta identificada nas variáveis de ambiente PATH.\r\n#(Sugiro salvar na pasta do Python ou do Anaconda)\r\n\r\ndef sophia_webScrape(entidade, url, n_items):\r\n \r\n result_df = pd.DataFrame()\r\n firefox = webdriver.Firefox()\r\n not_find = []\r\n \r\n for obj_id in range(100):\r\n \r\n n = random.randint(1,n_items)\r\n result_dict = {}\r\n \r\n print(\"\\nAcessando o objeto de id {}\".format(n))\r\n \r\n #Abre a página da URL selecionada\r\n firefox.get(url + '/index.asp?codigo_sophia={}'.format(n))\r\n \r\n time.sleep(5)\r\n \r\n #Identifica o frame onde os metadados estão\r\n frame = firefox.find_element_by_tag_name(\"frameset\").find_element_by_tag_name(\"frame\")\r\n \r\n #Direciona o drives para dentro do conteúdo do frame onde os metadados estão\r\n firefox.switch_to.frame(frame)\r\n \r\n try:\r\n #Direciona o driver para a div onde a tabela com os metadados está!\r\n firefox.find_element_by_xpath(\"//*[@id='div_conteudo']\")\r\n \r\n except:\r\n print(\"Div de conteudo do objeto {} não encontrada\".format(n))\r\n time.sleep(10)\r\n \r\n #Direciona o driver para a div onde a tabela com os metadados está!\r\n firefox.find_element_by_xpath(\"//*[@id='div_conteudo']\")\r\n \r\n try:\r\n print(\"Identificando metadados\")\r\n #Identifica a tabela com os metadados na tabela com a classe max_width table-ficha-detalhes\r\n #Nesse momento o script dá erro se o numero idnetificador não for encontrado\r\n metadata = firefox.find_element_by_xpath(\"//*[@class='max_width table-ficha-detalhes']\").get_attribute('outerHTML')\r\n \r\n print(\"Transoformando os metadados\")\r\n #Tranforma a tabela em um dataframe\r\n result_table = pd.read_html(metadata)\r\n #read_html resulta em um dataframe de dataframes, e a tabela de interesse se encontra do índice 0\r\n result_table = result_table[0]\r\n \r\n print(\"Gravando metadados\")\r\n #Somente as duas últimas colunas deste dataframe tem os valores de interesse\r\n result_table = result_table[[1,2]]\r\n #É necessário executar uma transposição do dataframe, pois o nome das colunas vem na primeira coluna, e os valores na segunda coluna\r\n result_table_T = result_table.transpose()\r\n result_table_T.columns = result_table_T.iloc[0].values\r\n #Essa função elimina as colunas que retornam valor nulo\r\n result_table_T = result_table_T.drop([1]).dropna(axis='columns',how='all')\r\n \r\n \r\n #Transoforma o dataframe resultante em um dicionário, para posterior inserção dos valores do item em um dataframe\r\n for column in result_table_T.columns:\r\n result_dict[column] = result_table_T[column].values[0]\r\n \r\n result_dict['Link do Item'] = url + '/index.asp?codigo_sophia={}'.format(n)\r\n \r\n result_df = result_df.append(result_dict, ignore_index=True)\r\n \r\n print(\"Intervalo de 5 segundos\")\r\n time.sleep(5)\r\n \r\n except Exception as e:\r\n print(e)\r\n #Caso o item não seja encontrado ele seu código é armazenado em uma lista\r\n print(\"Item {} Não encontrado\".format(n))\r\n not_find.append(n)\r\n time.sleep(5)\r\n \r\n #Csv com dados dos registros coletados\r\n result_df.to_csv(path + entidade + \"_sophia_webSpcrape.csv\", index = False)\r\n \r\n #Txt com os códigos não encontrados\r\n with open(path + entidade + \"_notFindCodes.txt\", \"w\") as not_find_txt:\r\n not_find_txt.write(\", \".join(str(code) for code in not_find))\r\n \r\n firefox.quit()\r\n \r\n#%%\r\nnItens_dict = {\"funarte||http://cedoc.funarte.gov.br/sophia_web/\":125859, \r\n \"bn_digital||http://acervo.bndigital.bn.br/sophia/\":101818, \r\n \"rui||http://acervos.casaruibarbosa.gov.br/\":220911}\r\n\r\n\r\nfor entidade in nItens_dict.keys():\r\n \r\n print(\"\\nColetando 100 itens aleatórios de {}\".format(entidade.split('||')[0]))\r\n sophia_webScrape(entidade.split('||')[0], entidade.split('||')[1], nItens_dict[entidade])\r\n", "import pandas as pd\r\nimport time\r\nimport random\r\nresultado = pd.DataFrame()\r\nnotFind = []\r\n\r\nfor i in range(101):\r\n n = random.randint(1,450)\r\n time.sleep(2)\r\n \r\n if i == 0:\r\n continue\r\n else:\r\n resultDict = {}\r\n url = 'https://sicg.iphan.gov.br/sicg/bemImaterial/instituicao/{}/'.format(n)\r\n \r\n try:\r\n acao_df = pd.read_html(url)\r\n except:\r\n time.sleep(10)\r\n try:\r\n acao_df = pd.read_html(url)\r\n except:\r\n notFind.append(n)\r\n continue\r\n \r\n resultDict['link'] = url\r\n print(\"Coletando o item {}-{}\".format(n, i))\r\n \r\n for table in acao_df[0][0]:\r\n values = table.replace(\": \", \": \").split(\" \")[1:]\r\n \r\n for value in values:\r\n try:\r\n resultDict[value.split(\":\")[0].strip()] = value.split(\":\")[1].strip()\r\n except:\r\n continue\r\n \r\n resultado = resultado.append(resultDict, ignore_index=True)\r\n\r\nresultado.to_csv(\"iphan_SICG_instituicao.csv\", index=False)\r\n" ]
[ [ "pandas.DataFrame" ], [ "pandas.DataFrame", "pandas.read_html" ], [ "pandas.DataFrame", "pandas.read_html" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "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": [] }, { "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": [] } ]
nitish-raj/data-science-on-aws
[ "b760805d28f8375094ce83aee849de8b9d3382a2" ]
[ "wip/ray/archive/pytorch-huggingface.py" ]
[ "#########################\n# Import required modules\n#########################\n\nimport argparse\nimport pprint\nimport json\nimport logging\nimport os\nimport sys\nimport pandas as pd\nimport random\nimport time\nimport glob\nimport numpy as np\nfrom collections import defaultdict\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data\nimport torch.utils.data.distributed\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom transformers import RobertaModel, RobertaConfig\nfrom transformers import RobertaForSequenceClassification\nfrom transformers import AdamW, get_linear_schedule_with_warmup\n\nimport ray\nfrom ray.train import Trainer\n\n#######################\n# Parse input arguments\n#######################\ndef parse_args():\n\n parser = argparse.ArgumentParser()\n \n # CLI args\n \n parser.add_argument('--train_batch_size', \n type=int, \n default=64)\n \n parser.add_argument('--train_steps_per_epoch',\n type=int,\n default=64)\n\n parser.add_argument('--validation_batch_size', \n type=int, \n default=64)\n \n parser.add_argument('--validation_steps_per_epoch',\n type=int,\n default=64)\n\n parser.add_argument('--epochs', \n type=int, \n default=1)\n \n parser.add_argument('--freeze_bert_layer', \n type=eval, \n default=False)\n \n parser.add_argument('--learning_rate', \n type=float, \n default=0.01)\n \n parser.add_argument('--momentum', \n type=float, \n default=0.5)\n \n parser.add_argument('--seed', \n type=int, \n default=42)\n \n parser.add_argument('--log_interval', \n type=int, \n default=100)\n \n parser.add_argument('--backend', \n type=str, \n default='gloo')\n \n parser.add_argument('--max_seq_length', \n type=int, \n default=128)\n \n parser.add_argument('--run_validation', \n type=eval,\n default=False)\n \n # Container environment \n \n# BEFORE RAY \n# parser.add_argument('--hosts', \n# type=list, \n# default='127.0.0.1')\n# BEFORE RAY \n# parser.add_argument('--current_host', \n# type=str, \n# default='127.0.0.1')\n \n parser.add_argument('--model_dir', \n type=str, \n default='./model/')\n\n parser.add_argument('--train_data', \n type=str, \n default='./data/train/')\n \n parser.add_argument('--validation_data', \n type=str, \n default='./data/validation/')\n \n parser.add_argument('--output_dir', \n type=str, \n default='./output')\n \n parser.add_argument('--num_gpus', \n type=int, \n default=0)\n\n # Debugger args\n \n# parser.add_argument(\"--save-frequency\", \n# type=int, \n# default=10, \n# help=\"frequency with which to save steps\")\n \n# parser.add_argument(\"--smdebug_path\",\n# type=str,\n# help=\"output directory to save data in\",\n# default=\"/opt/ml/output/tensors\",)\n \n# parser.add_argument(\"--hook-type\",\n# type=str,\n# choices=[\"saveall\", \"module-input-output\", \"weights-bias-gradients\"],\n# default=\"saveall\",)\n\n return parser.parse_args()\n\n#####################\n# Tools and variables\n#####################\n\n# Model name according to the PyTorch documentation: \n# https://github.com/aws/sagemaker-pytorch-inference-toolkit/blob/6936c08581e26ff3bac26824b1e4946ec68ffc85/src/sagemaker_pytorch_serving_container/torchserve.py#L45\nMODEL_NAME = 'model.pth'\n# Hugging face list of models: https://huggingface.co/models\nPRE_TRAINED_MODEL_NAME = 'roberta-base'\n\ndef create_list_input_files(path):\n print('************* path {}'.format(path))\n input_files = glob.glob('{}/*.tsv'.format(path))\n print(input_files)\n return input_files\n\ndef save_transformer_model(model, model_dir):\n path = '{}/transformer'.format(model_dir)\n os.makedirs(path, exist_ok=True) \n print('Saving Transformer model to {}'.format(path))\n model.save_pretrained(path)\n\ndef save_pytorch_model(model, model_dir):\n os.makedirs(model_dir, exist_ok=True) \n print('Saving PyTorch model to {}'.format(model_dir))\n save_path = os.path.join(model_dir, MODEL_NAME)\n torch.save(model.state_dict(), save_path)\n\n#####################\n# Configure the model\n#####################\ndef configure_model():\n classes = [-1, 0, 1]\n\n config = RobertaConfig.from_pretrained(\n PRE_TRAINED_MODEL_NAME, \n num_labels=len(classes),\n id2label={\n ### BEGIN SOLUTION - DO NOT delete this comment for grading purposes\n 0: -1, # Replace all None\n 1: 0, # Replace all None\n 2: 1, # Replace all None\n ### END SOLUTION - DO NOT delete this comment for grading purposes\n },\n label2id={\n -1: 0,\n 0: 1,\n 1: 2,\n }\n )\n \n config.output_attentions=True\n\n return config\n\n################################\n# PyTorch Dataset and DataLoader\n################################\n\n# PyTorch dataset retrieves the dataset’s features and labels one sample at a time\n# Create a custom Dataset class for the reviews\nclass ReviewDataset(Dataset):\n \n def __init__(self, input_ids_list, label_id_list):\n self.input_ids_list = input_ids_list\n self.label_id_list = label_id_list\n\n def __len__(self):\n return len(self.input_ids_list)\n\n def __getitem__(self, item):\n # convert list of token_ids into an array of PyTorch LongTensors\n input_ids = json.loads(self.input_ids_list[item]) \n label_id = self.label_id_list[item]\n\n input_ids_tensor = torch.LongTensor(input_ids)\n label_id_tensor = torch.tensor(label_id, dtype=torch.long)\n\n return input_ids_tensor, label_id_tensor\n\n# PyTorch DataLoader helps to to organise the input training data in “minibatches” and reshuffle the data at every epoch\n# It takes Dataset as an input\ndef create_data_loader(path, batch_size): \n print(\"Get data loader\")\n\n df = pd.DataFrame(columns=['input_ids', 'label_id'])\n \n input_files = create_list_input_files(path)\n\n for file in input_files:\n df_temp = pd.read_csv(file, \n sep='\\t', \n usecols=['input_ids', 'label_id'])\n df = df.append(df_temp)\n \n ds = ReviewDataset(\n input_ids_list=df.input_ids.to_numpy(),\n label_id_list=df.label_id.to_numpy(),\n )\n \n return DataLoader(\n ds,\n batch_size=batch_size,\n shuffle=True,\n drop_last=True,\n ), df\n\n#############\n# Train model\n#############\n\ndef train_model(config):\n# model,\n# train_data_loader,\n# df_train,\n# val_data_loader, \n# df_val,\n# args):\n \n model = config[\"model\"]\n train_data_loader = config[\"train_data_loader\"]\n df_train = config[\"df_train\"]\n val_data_loader = config[\"val_data_loader\"]\n df_val = config[\"df_val\"]\n args = config[\"args\"]\n \n loss_function = nn.CrossEntropyLoss() \n optimizer = optim.Adam(params=model.parameters(), lr=args.learning_rate)\n \n if args.freeze_bert_layer:\n print('Freezing BERT base layers...')\n for name, param in model.named_parameters():\n if 'classifier' not in name: # classifier layer\n param.requires_grad = False\n print('Set classifier layers to `param.requires_grad=False`.') \n \n train_correct = 0\n train_total = 0\n\n for epoch in range(args.epochs):\n print('EPOCH -- {}'.format(epoch))\n\n for i, (sent, label) in enumerate(train_data_loader):\n if i < args.train_steps_per_epoch:\n model.train()\n optimizer.zero_grad()\n sent = sent.squeeze(0)\n if torch.cuda.is_available():\n sent = sent.cuda()\n label = label.cuda()\n output = model(sent)[0]\n _, predicted = torch.max(output, 1)\n\n loss = loss_function(output, label)\n loss.backward()\n optimizer.step()\n \n if args.run_validation and i % args.validation_steps_per_epoch == 0:\n print('RUNNING VALIDATION:')\n correct = 0\n total = 0\n model.eval()\n\n for sent, label in val_data_loader:\n sent = sent.squeeze(0)\n if torch.cuda.is_available():\n sent = sent.cuda()\n label = label.cuda()\n output = model(sent)[0]\n _, predicted = torch.max(output.data, 1)\n\n total += label.size(0)\n correct += (predicted.cpu() ==label.cpu()).sum()\n\n accuracy = 100.00 * correct.numpy() / total\n print('[epoch/step: {0}/{1}] val_loss: {2:.2f} - val_acc: {3:.2f}%'.format(epoch, i, loss.item(), accuracy))\n else:\n break \n\n print('TRAINING COMPLETED.')\n return model\n\n######\n# Main\n######\n\nif __name__ == '__main__':\n \n # Parse args\n \n args = parse_args()\n print('Loaded arguments:')\n print(args)\n\n # Get environment variables\n \n env_var = os.environ \n print('Environment variables:')\n pprint.pprint(dict(env_var), width = 1) \n \n \n # Check if distributed training\n \n #is_distributed = len(args.hosts) > 1 and args.backend is not None\n # is_distributed = True\n\n #print(\"Distributed training - {}\".format(is_distributed))\n use_cuda = args.num_gpus > 0\n print(\"Number of gpus available - {}\".format(args.num_gpus))\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n\n device = torch.device('cuda' if use_cuda else 'cpu')\n\n # Initialize the distributed environment.\n \n #if is_distributed:\n # BEFORE RAY world_size = len(args.hosts)\n #world_size = num_workers \n #os.environ['WORLD_SIZE'] = str(world_size)\n #host_rank = num_workers\n \n\t# BEFORE RAY host_rank = args.hosts.index(args.current_host)\n #os.environ['RANK'] = str(host_rank)\n #dist.init_process_group(backend=args.backend, rank=host_rank, world_size=world_size)\n #print('Initialized the distributed environment: \\'{}\\' backend on {} nodes. '.format(\n # args.backend, dist.get_world_size()) + 'Current host rank is {}. Number of gpus: {}'.format(\n # dist.get_rank(), args.num_gpus))\n \n # Set the seed for generating random numbers\n \n torch.manual_seed(args.seed)\n if use_cuda:\n torch.cuda.manual_seed(args.seed) \n \n # Instantiate model\n \n config = None\n model = None\n \n successful_download = False\n retries = 0\n \n while (retries < 5 and not successful_download):\n try:\n # Configure model\n config = configure_model()\n model = RobertaForSequenceClassification.from_pretrained(\n 'roberta-base',\n config=config\n )\n\n model.to(device)\n successful_download = True\n print('Sucessfully downloaded after {} retries.'.format(retries))\n \n except:\n retries = retries + 1\n random_sleep = random.randint(1, 30)\n print('Retry #{}. Sleeping for {} seconds'.format(retries, random_sleep))\n time.sleep(random_sleep)\n \n if not model:\n print('Not properly initialized...')\n \n # Create data loaders\n \n train_data_loader, df_train = create_data_loader(args.train_data, args.train_batch_size)\n val_data_loader, df_val = create_data_loader(args.validation_data, args.validation_batch_size)\n \n print(\"Processes {}/{} ({:.0f}%) of train data\".format(\n len(train_data_loader.sampler), len(train_data_loader.dataset),\n 100. * len(train_data_loader.sampler) / len(train_data_loader.dataset)\n ))\n\n print(\"Processes {}/{} ({:.0f}%) of validation data\".format(\n len(val_data_loader.sampler), len(val_data_loader.dataset),\n 100. * len(val_data_loader.sampler) / len(val_data_loader.dataset)\n )) \n \n print('model_dir: {}'.format(args.model_dir)) \n print('model summary: {}'.format(model))\n \n callbacks = []\n initial_epoch_number = 0\n \n # Start training\n\n# model = train_model(\n# model,\n# train_data_loader,\n# df_train,\n# val_data_loader, \n# df_val,\n# args\n# )\n\n ray.init(address=\"auto\")\n trainer = Trainer(\"torch\", num_workers=40, use_gpu=False)\n trainer.start()\n\n config = {\n \"model\": model,\n \"train_data_loader\": train_data_loader,\n \"df_train\": df_train,\n \"val_data_loader\": val_data_loader,\n \"df_val\": df_val,\n \"args\": args\n }\n\n model = trainer.run(train_model, config)\n \n save_transformer_model(model, args.model_dir)\n save_pytorch_model(model, args.model_dir)\n \n # Prepare for inference which will be used in deployment\n # You will need three files for it: inference.py, requirements.txt, config.json\n \n inference_path = os.path.join(args.model_dir, \"code/\")\n os.makedirs(inference_path, exist_ok=True)\n os.system(\"cp inference.py {}\".format(inference_path))\n os.system(\"cp requirements.txt {}\".format(inference_path))\n os.system(\"cp config.json {}\".format(inference_path))\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.LongTensor", "pandas.read_csv", "torch.max", "torch.cuda.manual_seed", "torch.manual_seed", "torch.utils.data.DataLoader", "pandas.DataFrame", "torch.tensor", "torch.cuda.is_available", "torch.device" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
pmjherman/CoralModel
[ "37fe169448052f46c4aec858c6e414070edf14b1" ]
[ "coral_model/utils.py" ]
[ "\"\"\"\ncoral_model - utils\n\n@author: Gijs G. Hendrickx\n@contributor: Peter M.J. Herman\n\"\"\"\nimport os\n# TODO: Restructure all utils-related files, methods, and methods.\nimport numpy as np\nfrom netCDF4 import Dataset\n\n\nclass SpaceTime:\n \"\"\"Spacetime-object, which validates the definition of the spacetime dimensions.\"\"\"\n\n __spacetime = None\n\n def __init__(self, spacetime=None):\n \"\"\"\n :param spacetime: spacetime dimensions, defaults to None\n :type spacetime: None, tuple, optional\n \"\"\"\n if spacetime is not None:\n self.spacetime = spacetime\n \n self.set_coral_only(self.spacetime)\n\n def __repr__(self):\n \"\"\"Development representation.\"\"\"\n return f'SpaceTime({self.__spacetime})'\n\n def __str__(self):\n \"\"\"Print representation.\"\"\"\n return str(self.spacetime)\n\n @property\n def spacetime(self):\n \"\"\"Spacetime dimensions.\n\n :rtype: tuple\n \"\"\"\n if self.__spacetime is None:\n return 1, 1\n return self.__spacetime\n\n @spacetime.setter\n def spacetime(self, space_time):\n \"\"\"\n :param space_time: spacetime dimensions\n :type space_time: tuple, list, numpy.ndarray\n \"\"\"\n if not isinstance(space_time, (tuple, list, np.ndarray)):\n msg = f'spacetime must be of type tuple, {type(space_time)} is given.'\n raise TypeError(msg)\n\n if not len(space_time) == 2:\n msg = f'spacetime must be of size 2, {len(space_time)} is given.'\n raise ValueError(msg)\n\n if not all(isinstance(dim, int) for dim in space_time):\n msg = f'spacetime must consist of integers only, {[type(dim) for dim in space_time]} is given.'\n raise TypeError(msg)\n\n self.__spacetime = tuple(space_time)\n self.set_coral_only(tuple(space_time))\n\n @property\n def space(self):\n \"\"\"Space dimension.\n\n :rtype: int\n \"\"\"\n return self.spacetime[0]\n\n @space.setter\n def space(self, x):\n \"\"\"\n :param x: space dimension\n :type x: int\n \"\"\"\n self.spacetime = (x, self.time)\n\n @property\n def time(self):\n \"\"\"Time dimension.\n\n :rtype: int\n \"\"\"\n return self.spacetime[1]\n\n @time.setter\n def time(self, t):\n \"\"\"\n :param t: time dimension\n :type t: int\n \"\"\"\n self.spacetime = (self.space, t)\n \n # TODO: Refactor to a private method\n def set_coral_only(self, spacetime):\n \"\"\"Automatically set the spacetime dimensions for the CoralOnly-class.\n \n :param spacetime: spacetime dimension\n :type spacetime: tuple\n \"\"\"\n CoralOnly.spacetime = spacetime\n \n\nclass DataReshape(SpaceTime):\n \"\"\"Reshape data to create a spacetime matrix.\"\"\"\n\n def __init__(self, spacetime=None):\n \"\"\"\n :param spacetime: spacetime dimensions, defaults to None\n :type spacetime: None, tuple, optional\n \"\"\"\n super().__init__(spacetime=spacetime)\n \n def variable2matrix(self, variable, dimension):\n \"\"\"Transform variable to matrix.\n \n :param variable: variable to be transformed\n :param dimension: dimension of :param variable:\n \n :type variable: float, int, list, tuple, numpy.ndarray\n :type dimension: str\n\n :return: variable as matrix in space-time\n :rtype: numpy.ndarray\n \"\"\"\n # # input check\n # dimension-type\n dimensions = ('space', 'time')\n if dimension not in dimensions:\n msg = f'{dimension} not in {dimensions}.'\n raise ValueError(msg)\n\n # dimension-value\n variable = self.variable2array(variable)\n self.dimension_value(variable, dimension)\n\n # # transformation\n if dimension == 'space':\n return np.tile(variable, (self.time, 1)).transpose()\n elif dimension == 'time':\n return np.tile(variable, (self.space, 1))\n\n def dimension_value(self, variable, dimension):\n \"\"\"Check consistency between variable's dimensions and the defined spacetime dimensions.\n\n :param variable: variable to be checked\n :param dimension: dimension under consideration\n\n :type variable: list, tuple, numpy.ndarray\n :type dimension: str\n \"\"\"\n try:\n _ = len(variable)\n except TypeError:\n variable = [variable]\n\n if not len(variable) == getattr(self, dimension):\n msg = f'Incorrect variable size, {len(variable)} =/= {getattr(self, dimension)}.'\n raise ValueError(msg)\n\n @staticmethod\n def variable2array(variable):\n \"\"\"\"Transform variable to numpy.array (if float or string).\n \n :param variable: variable to be transformed\n :type variable: float, int, list, numpy.ndarray\n\n :return: variable as array\n :rtype: numpy.ndarray\n \"\"\"\n if isinstance(variable, str):\n msg = f'Variable cannot be of {type(variable)}.'\n raise NotImplementedError(msg)\n elif isinstance(variable, (float, int)):\n return np.array([float(variable)])\n elif isinstance(variable, (list, tuple)):\n return np.array(variable)\n elif isinstance(variable, np.ndarray) and not variable.shape:\n return np.array([variable])\n return variable\n\n def matrix2array(self, matrix, dimension, conversion=None):\n \"\"\"Transform matrix to array.\n\n :param matrix: variable as matrix in spacetime\n :param dimension: dimension to convert matrix to\n :param conversion: how to convert the matrix to an array, defaults to None\n None : take the last value\n 'mean' : take the mean value\n 'max' : take the maximum value\n 'min' : take the minimum value\n 'sum' : take the summation\n\n :type matrix: numpy.ndarray\n :type dimension: str\n :type conversion: None, str, optional\n\n :return: variable as array\n :rtype: numpy.ndarray\n \"\"\"\n # # input check\n # dimension-type\n dimensions = ('space', 'time')\n if dimension not in dimensions:\n msg = f'{dimension} not in {dimensions}.'\n raise ValueError(msg)\n\n # input as numpy.array\n matrix = np.array(matrix)\n\n # dimension-value\n if not matrix.shape == self.spacetime:\n if not matrix.shape[:2] == self.spacetime:\n msg = f'Matrix-shape does not correspond with spacetime-dimensions:' \\\n f'\\n{matrix.shape} =/= {self.spacetime}'\n raise ValueError(msg)\n\n # conversion-strategy\n conversions = (None, 'mean', 'max', 'min', 'sum')\n if conversion not in conversions:\n msg = f'{conversion} not in {conversions}.'\n raise ValueError(msg)\n\n # # transformation\n # last position\n if conversion is None:\n if dimension == 'space':\n return matrix[:, -1]\n elif dimension == 'time':\n return matrix[-1, :]\n\n # conversion\n if dimension == 'space':\n return getattr(matrix, conversion)(axis=1)\n elif dimension == 'time':\n return getattr(matrix, conversion)(axis=0)\n\n\nclass Output:\n \"\"\"Output files based on predefined output content.\"\"\"\n\n _file_name_map = None\n _file_name_his = None\n _outdir = None\n \n _map_output = None\n _his_output = None\n\n _map_data = None\n _his_data = None\n\n _xy_stations = None\n _idx_stations = None\n\n def __init__(self, outdir, xy_coordinates, outpoint, first_date):\n \"\"\"Generate output files of CoralModel simulation. Output files are formatted as NetCDF4-files.\n\n :param outdir: directory to write the output to \n :param xy_coordinates: (x,y)-coordinates\n :param outpoint: boolean indicating per (x,y) point if his output is desired\n :param first_date: first date of simulation\n\n :type outdir: str\n :type xy_coordinates: numpy.ndarray\n :type outpoint: numpy.ndarray\n :type first_date: pandas\n \"\"\"\n self.xy_coordinates = xy_coordinates\n self.outpoint = outpoint\n self.nout_his = len(xy_coordinates[outpoint,0])\n self.set_xy_stations\n self.space = len(xy_coordinates)\n\n self.first_date = first_date\n self.first_year = first_date.year\n \n self._outdir = outdir \n\n def __str__(self):\n \"\"\"String-representation of Output.\"\"\"\n return f'Output exported:\\n\\t{self._map_output}\\n\\t{self._his_output}' if self.defined else f'Output undefined.'\n\n def __repr__(self):\n \"\"\"Representation of Output.\"\"\"\n return f'Output(xy_coordinates={self.xy_coordinates}, first_date={self.first_date})'\n\n @property\n def defined(self):\n \"\"\"Output is defined.\"\"\"\n return False if self._map_output is None and self._his_output is None else True\n\n def define_output(self, output_type, lme=True, fme=True, tme=True, pd=True, ps=True, calc=True, md=True):\n \"\"\"Define output dictionary.\n\n :param output_type: mapping or history output\n :param lme: light micro-environment, defaults to True\n :param fme: flow micro-environment, defaults to True\n :param tme: thermal micro-environment, defaults to True\n :param pd: photosynthetic dependencies, defaults to True\n :param ps: population states, defaults to True\n :param calc: calcification rates, defaults to True\n :param md: morphological development, defaults to True\n\n :type output_type: str\n :type lme: bool, optional\n :type fme: bool, optional\n :type tme: bool, optional\n :type pd: bool, optional\n :type ps: bool, optional\n :type calc: bool, optional\n :type md: bool, optional\n \"\"\"\n types = ('map', 'his')\n if output_type not in types:\n msg = f'{output_type} not in {types}.'\n raise ValueError(msg)\n\n setattr(self, f'_{output_type}_output', locals())\n\n @staticmethod\n def __file_ext(file_name):\n \"\"\"Ensure NetCDF file extension.\n\n :param file_name: file name\n :type file_name: str\n \"\"\"\n if not file_name.endswith('.nc'):\n return f'{file_name}.nc'\n return file_name\n\n @property\n def outdir(self):\n \"\"\"\n :return: output directory\n :rtype: str\n \"\"\"\n return self._outdir.__str__()\n\n @outdir.setter\n def set_outdir(self, output_folder):\n \"\"\"Output folder.\n\n :param output_folder: output folder for output files\n :type output_folder: None, str, list, tuple\n \"\"\"\n self._outdir = output_folder\n\n @property\n def file_name_map(self):\n \"\"\"File name of mapping output.\n\n :rtype: str\n \"\"\"\n if self._file_name_map is None:\n return os.path.join(self.file_dir_map,'CoralModel_map.nc')\n else:\n return self._file_name_map\n\n @file_name_map.setter\n def file_name_map(self, file_name):\n \"\"\"\n :param file_name: file name of mapping output\n :type file_name: None, str\n \"\"\"\n self._file_name_map = self.__file_ext(file_name)\n\n @property\n def file_dir_map(self):\n \"\"\"Full file directory of mapping output.\n\n :rtype: str\n \"\"\"\n return self._outdir\n\n @property\n def file_name_his(self):\n \"\"\"File name of history output.\n\n :rtype: str\n \"\"\"\n if self._file_name_his is None:\n return os.path.join(self.file_dir_his,'CoralModel_his.nc')\n else:\n return self._file_name_his\n\n @file_name_his.setter\n def file_name_his(self, file_name):\n \"\"\"\n :param file_name: file name of history output\n :type file_name: str\n \"\"\"\n self._file_name_his = self.__file_ext(file_name)\n\n @property\n def file_dir_his(self):\n \"\"\"Full file directory of history output.\n\n :rtype: str\n \"\"\"\n return self._outdir\n\n def initiate_map(self, coral):\n \"\"\"Initiate mapping output file in which annual output covering the whole model domain is stored.\n\n :param coral: coral animal\n :type coral: Coral\n \"\"\"\n if self._map_output is not None and any(self._map_output.values()):\n self._map_data = Dataset(self.file_name_map, 'w', format='NETCDF4')\n self._map_data.description = 'Mapped simulation data of the CoralModel.'\n\n # dimensions\n self._map_data.createDimension('time', None)\n self._map_data.createDimension('nmesh2d_face', self.space)\n\n # variables\n t = self._map_data.createVariable('time', int, ('time',))\n t.long_name = 'year'\n t.units = 'years since 0 B.C.'\n\n x = self._map_data.createVariable('nmesh2d_x', 'f8', ('nmesh2d_face',))\n x.long_name = 'x-coordinate'\n x.units = 'm'\n\n y = self._map_data.createVariable('nmesh2d_y', 'f8', ('nmesh2d_face',))\n y.long_name = 'y-coordinate'\n y.units = 'm'\n\n t[:] = self.first_year\n x[:] = self.xy_coordinates[:, 0]\n y[:] = self.xy_coordinates[:, 1]\n\n # initial conditions\n if self._map_output['lme']:\n light_set = self._map_data.createVariable('Iz', 'f8', ('time', 'nmesh2d_face'))\n light_set.long_name = 'annual mean representative light-intensity'\n light_set.units = 'micro-mol photons m-2 s-1'\n light_set[:, :] = 0\n if self._map_output['fme']:\n flow_set = self._map_data.createVariable('ucm', 'f8', ('time', 'nmesh2d_face'))\n flow_set.long_name = 'annual mean in-canopy flow'\n flow_set.units = 'm s-1'\n flow_set[:, :] = 0\n if self._map_output['tme']:\n temp_set = self._map_data.createVariable('Tc', 'f8', ('time', 'nmesh2d_face'))\n temp_set.long_name = 'annual mean coral temperature'\n temp_set.units = 'K'\n temp_set[:, :] = 0\n\n low_temp_set = self._map_data.createVariable('Tlo', 'f8', ('time', 'nmesh2d_face'))\n low_temp_set.long_name = 'annual mean lower thermal limit'\n low_temp_set.units = 'K'\n low_temp_set[:, :] = 0\n\n high_temp_set = self._map_data.createVariable('Thi', 'f8', ('time', 'nmesh2d_face'))\n high_temp_set.long_name = 'annual mean upper thermal limit'\n high_temp_set.units = 'K'\n high_temp_set[:, :] = 0\n if self._map_output['pd']:\n pd_set = self._map_data.createVariable('PD', 'f8', ('time', 'nmesh2d_face'))\n pd_set.long_name = 'annual sum photosynthetic rate'\n pd_set.units = '-'\n pd_set[:, :] = 0\n if self._map_output['ps']:\n pt_set = self._map_data.createVariable('PT', 'f8', ('time', 'nmesh2d_face'))\n pt_set.long_name = 'total living coral population at the end of the year'\n pt_set.units = '-'\n pt_set[:, :] = coral.living_cover\n\n ph_set = self._map_data.createVariable('PH', 'f8', ('time', 'nmesh2d_face'))\n ph_set.long_name = 'healthy coral population at the end of the year'\n ph_set.units = '-'\n ph_set[:, :] = coral.living_cover\n\n pr_set = self._map_data.createVariable('PR', 'f8', ('time', 'nmesh2d_face'))\n pr_set.long_name = 'recovering coral population at the end of the year'\n pr_set.units = '-'\n pr_set[:, :] = 0\n\n pp_set = self._map_data.createVariable('PP', 'f8', ('time', 'nmesh2d_face'))\n pp_set.long_name = 'pale coral population at the end of the year'\n pp_set.units = '-'\n pp_set[:, :] = 0\n\n pb_set = self._map_data.createVariable('PB', 'f8', ('time', 'nmesh2d_face'))\n pb_set.long_name = 'bleached coral population at the end of the year'\n pb_set.units = '-'\n pb_set[:, :] = 0\n if self._map_output['calc']:\n calc_set = self._map_data.createVariable('calc', 'f8', ('time', 'nmesh2d_face'))\n calc_set.long_name = 'annual sum calcification rate'\n calc_set.units = 'kg m-2 yr-1'\n calc_set[:, :] = 0\n if self._map_output['md']:\n dc_set = self._map_data.createVariable('dc', 'f8', ('time', 'nmesh2d_face'))\n dc_set.long_name = 'coral plate diameter'\n dc_set.units = 'm'\n dc_set[0, :] = coral.dc\n\n hc_set = self._map_data.createVariable('hc', 'f8', ('time', 'nmesh2d_face'))\n hc_set.long_name = 'coral height'\n hc_set.units = 'm'\n hc_set[0, :] = coral.hc\n\n bc_set = self._map_data.createVariable('bc', 'f8', ('time', 'nmesh2d_face'))\n bc_set.long_name = 'coral base diameter'\n bc_set.units = 'm'\n bc_set[0, :] = coral.bc\n\n tc_set = self._map_data.createVariable('tc', 'f8', ('time', 'nmesh2d_face'))\n tc_set.long_name = 'coral plate thickness'\n tc_set.units = 'm'\n tc_set[0, :] = coral.tc\n\n ac_set = self._map_data.createVariable('ac', 'f8', ('time', 'nmesh2d_face'))\n ac_set.long_name = 'coral axial distance'\n ac_set.units = 'm'\n ac_set[0, :] = coral.ac\n\n vc_set = self._map_data.createVariable('Vc', 'f8', ('time', 'nmesh2d_face'))\n vc_set.long_name = 'coral volume'\n vc_set.units = 'm3'\n vc_set[0, :] = coral.volume\n self._map_data.close()\n\n def update_map(self, coral, year):\n \"\"\"Write data as annual output covering the whole model domain.\n\n :param coral: coral animal\n :param year: simulation year\n\n :type coral: Coral\n :type year: int\n \"\"\"\n if self._map_output is not None and any(self._map_output.values()):\n self._map_data = Dataset(self.file_name_map, mode='a')\n\n i = int(year - self.first_year)\n self._map_data['time'][i] = year\n if self._map_output['lme']:\n self._map_data['Iz'][-1, :] = coral.light[:, -1]\n if self._map_output['fme']:\n self._map_data['ucm'][-1, :] = coral.ucm\n if self._map_output['tme']:\n self._map_data['Tc'][-1, :] = coral.temp[:, -1]\n self._map_data['Tlo'][-1, :] = coral.Tlo if len(DataReshape.variable2array(coral.Tlo)) > 1 else coral.Tlo * np.ones(self.space)\n self._map_data['Thi'][-1, :] = coral.Thi if len(DataReshape.variable2array(coral.Thi)) > 1 else coral.Thi * np.ones(self.space)\n if self._map_output['pd']:\n self._map_data['PD'][-1, :] = coral.photo_rate.mean(axis=1)\n if self._map_output['ps']:\n self._map_data['PT'][-1, :] = coral.pop_states[:, -1, :].sum(axis=1)\n self._map_data['PH'][-1, :] = coral.pop_states[:, -1, 0]\n self._map_data['PR'][-1, :] = coral.pop_states[:, -1, 1]\n self._map_data['PP'][-1, :] = coral.pop_states[:, -1, 2]\n self._map_data['PB'][-1, :] = coral.pop_states[:, -1, 3]\n if self._map_output['calc']:\n self._map_data['calc'][-1, :] = coral.calc.sum(axis=1)\n if self._map_output['md']:\n self._map_data['dc'][-1, :] = coral.dc\n self._map_data['hc'][-1, :] = coral.hc\n self._map_data['bc'][-1, :] = coral.bc\n self._map_data['tc'][-1, :] = coral.tc\n self._map_data['ac'][-1, :] = coral.ac\n self._map_data['Vc'][-1, :] = coral.volume\n\n self._map_data.close()\n\n @property\n def xy_stations(self):\n \"\"\"(x,y)-coordinates of the stations.\n\n :rtype: numpy.ndarray\n \"\"\"\n if self._xy_stations is None:\n x = self.xy_coordinates[:,0]\n y = self.xy_coordinates[:,1]\n \n x_station = self.xy_coordinates[self.outpoint,0]\n y_station = self.xy_coordinates[self.outpoint,1]\n \n idx = np.zeros(self.nout_his)\n\n for s in range(len(idx)):\n idx[s] = np.argmin((x - x_station[s]) ** 2 + (y - y_station[s]) ** 2)\n\n self._idx_stations = idx.astype(int)\n self._xy_stations = self.xy_coordinates[self._idx_stations,:]\n\n return self._xy_stations\n\n @property\n def idx_stations(self):\n \"\"\"Space indices of stations.\n\n :rtype: numpy.ndarray\n \"\"\"\n return self._idx_stations\n\n @xy_stations.setter\n def set_xy_stations(self):\n \"\"\"Determine space indices based on the (x,y)-coordinates of the stations.\n \"\"\"\n return self.xy_stations\n\n def initiate_his(self):\n \"\"\"Initiate history output file in which daily output at predefined locations within the model is stored.\"\"\"\n if self._his_output is not None and any(self._his_output.values()):\n self._his_data = Dataset(self.file_name_his, 'w', format='NETCDF4')\n self._his_data.description = 'Historic simulation data of the CoralModel'\n\n # dimensions\n self._his_data.createDimension('time', None)\n self._his_data.createDimension('stations', len(self.xy_stations))\n\n # variables\n t = self._his_data.createVariable('time', 'f8', ('time',))\n t.long_name = f'days since {self.first_date}'\n t.units = 'days'\n\n x = self._his_data.createVariable('station_x_coordinate', 'f8', ('stations',))\n y = self._his_data.createVariable('station_y_coordinate', 'f8', ('stations',))\n\n # setup data set\n x[:] = self.xy_stations[:, 0]\n y[:] = self.xy_stations[:, 1]\n\n if self._his_output['lme']:\n light_set = self._his_data.createVariable('Iz', 'f8', ('time', 'stations'))\n light_set.long_name = 'representative light-intensity'\n light_set.units = 'micro-mol photons m-2 s-1'\n if self._his_output['fme']:\n flow_set = self._his_data.createVariable('ucm', 'f8', ('time', 'stations'))\n flow_set.long_name = 'in-canopy flow'\n flow_set.units = 'm s-1'\n if self._his_output['tme']:\n temp_set = self._his_data.createVariable('Tc', 'f8', ('time', 'stations'))\n temp_set.long_name = 'coral temperature'\n temp_set.units = 'K'\n\n low_temp_set = self._his_data.createVariable('Tlo', 'f8', ('time', 'stations'))\n low_temp_set.long_name = 'lower thermal limit'\n low_temp_set.units = 'K'\n\n high_temp_set = self._his_data.createVariable('Thi', 'f8', ('time', 'stations'))\n high_temp_set.long_name = 'upper thermal limit'\n high_temp_set.units = 'K'\n if self._his_output['pd']:\n pd_set = self._his_data.createVariable('PD', 'f8', ('time', 'stations'))\n pd_set.long_name = 'photosynthetic rate'\n pd_set.units = '-'\n if self._his_output['ps']:\n pt_set = self._his_data.createVariable('PT', 'f8', ('time', 'stations'))\n pt_set.long_name = 'total coral population'\n pt_set.units = '-'\n\n ph_set = self._his_data.createVariable('PH', 'f8', ('time', 'stations'))\n ph_set.long_name = 'healthy coral population'\n ph_set.units = '-'\n\n pr_set = self._his_data.createVariable('PR', 'f8', ('time', 'stations'))\n pr_set.long_name = 'recovering coral population'\n pr_set.units = '-'\n\n pp_set = self._his_data.createVariable('PP', 'f8', ('time', 'stations'))\n pp_set.long_name = 'pale coral population'\n pp_set.units = '-'\n\n pb_set = self._his_data.createVariable('PB', 'f8', ('time', 'stations'))\n pb_set.long_name = 'bleached coral population'\n pb_set.units = '-'\n if self._his_output['calc']:\n calc_set = self._his_data.createVariable('G', 'f8', ('time', 'stations'))\n calc_set.long_name = 'calcification'\n calc_set.units = 'kg m-2 d-1'\n if self._his_output['md']:\n dc_set = self._his_data.createVariable('dc', 'f8', ('time', 'stations'))\n dc_set.long_name = 'coral plate diameter'\n dc_set.units = 'm'\n\n hc_set = self._his_data.createVariable('hc', 'f8', ('time', 'stations'))\n hc_set.long_name = 'coral height'\n hc_set.units = 'm'\n\n bc_set = self._his_data.createVariable('bc', 'f8', ('time', 'stations'))\n bc_set.long_name = 'coral base diameter'\n bc_set.units = 'm'\n\n tc_set = self._his_data.createVariable('tc', 'f8', ('time', 'stations'))\n tc_set.long_name = 'coral plate thickness'\n tc_set.units = 'm'\n\n ac_set = self._his_data.createVariable('ac', 'f8', ('time', 'stations'))\n ac_set.long_name = 'coral axial distance'\n ac_set.units = 'm'\n\n vc_set = self._his_data.createVariable('Vc', 'f8', ('time', 'stations'))\n vc_set.long_name = 'coral volume'\n vc_set.units = 'm3'\n self._his_data.close()\n\n def update_his(self, coral, dates):\n \"\"\"Write data as daily output at predefined locations within the model domain.\n\n :param coral: coral animal\n :param dates: dates of simulation year\n\n :type coral: Coral\n :type dates: pandas\n \"\"\"\n if self._his_output is not None and any(self._his_output.values()):\n self._his_data = Dataset(self.file_name_his, mode='a')\n\n y_dates = dates.reset_index(drop=True)\n ti = (y_dates - self.first_date).dt.days.values\n self._his_data['time'][ti] = y_dates.values\n if self._his_output['lme']:\n self._his_data['Iz'][ti, :] = coral.light[self.idx_stations, :].transpose()\n if self._his_output['fme']:\n self._his_data['ucm'][ti, :] = np.tile(coral.ucm, (len(y_dates), 1))[:, self.idx_stations]\n if self._his_output['tme']:\n self._his_data['Tc'][ti, :] = coral.temp[self.idx_stations, :].transpose()\n if len(DataReshape.variable2array(coral.Tlo)) > 1 and len(DataReshape.variable2array(coral.Thi)) > 1:\n self._his_data['Tlo'][ti, :] = np.tile(coral.Tlo, (len(y_dates), 1))[:, self.idx_stations]\n self._his_data['Thi'][ti, :] = np.tile(coral.Thi, (len(y_dates), 1))[:, self.idx_stations]\n else:\n self._his_data['Tlo'][ti, :] = coral.Tlo * np.ones((len(y_dates), len(self.idx_stations)))\n self._his_data['Thi'][ti, :] = coral.Thi * np.ones((len(y_dates), len(self.idx_stations)))\n if self._his_output['pd']:\n self._his_data['PD'][ti, :] = coral.photo_rate[self.idx_stations, :].transpose()\n if self._his_output['ps']:\n self._his_data['PT'][ti, :] = coral.pop_states[self.idx_stations, :, :].sum(axis=2).transpose()\n self._his_data['PH'][ti, :] = coral.pop_states[self.idx_stations, :, 0].transpose()\n self._his_data['PR'][ti, :] = coral.pop_states[self.idx_stations, :, 1].transpose()\n self._his_data['PP'][ti, :] = coral.pop_states[self.idx_stations, :, 2].transpose()\n self._his_data['PB'][ti, :] = coral.pop_states[self.idx_stations, :, 3].transpose()\n if self._his_output['calc']:\n self._his_data['G'][ti, :] = coral.calc[self.idx_stations, :].transpose()\n if self._his_output['md']:\n self._his_data['dc'][ti, :] = np.tile(coral.dc, (len(y_dates), 1))[:, self.idx_stations]\n self._his_data['hc'][ti, :] = np.tile(coral.hc, (len(y_dates), 1))[:, self.idx_stations]\n self._his_data['bc'][ti, :] = np.tile(coral.bc, (len(y_dates), 1))[:, self.idx_stations]\n self._his_data['tc'][ti, :] = np.tile(coral.tc, (len(y_dates), 1))[:, self.idx_stations]\n self._his_data['ac'][ti, :] = np.tile(coral.ac, (len(y_dates), 1))[:, self.idx_stations]\n self._his_data['Vc'][ti, :] = np.tile(coral.volume, (len(y_dates), 1))[:, self.idx_stations]\n\n self._his_data.close()\n \n \nclass CoralOnly:\n \"\"\"Execute functions only in the presence of corals.\"\"\"\n \n spacetime = None\n \n @property\n def space(self):\n \"\"\"Space dimension.\"\"\"\n return None if self.spacetime is None else self.spacetime[0]\n \n @property\n def time(self):\n \"\"\"Time dimension.\"\"\"\n return None if self.spacetime is None else self.spacetime[1]\n\n def in_space(self, coral, function, args, no_cover_value=0):\n \"\"\"Only execute the function when there is coral cover.\n \n :param coral: coral object\n :param function: function to be executed\n :param args: input arguments of the function\n :param no_cover_value: default value in absence of coral cover\n \n :type coral: Coral\n :type args: tuple\n :type no_cover_value: float, optional\n \"\"\" \n args = list(args)\n for i, arg in enumerate(args):\n if isinstance(arg, (float, int)) or (isinstance(arg, np.ndarray) and not arg.shape):\n args[i] = np.repeat(arg, self.space)\n elif not len(arg) == self.space:\n msg = f'Sizes do not match up, {len(arg)} =/= {self.space}.'\n raise ValueError(msg)\n \n output = no_cover_value * np.ones(self.space)\n output[coral.cover > 0] = function(*[\n arg[coral.cover > 0] for arg in args\n ])\n return output\n \n def in_spacetime(self, coral, function, args, no_cover_value=0):\n \"\"\"Only execute the function when there is coral cover.\n \n :param coral: coral object\n :param function: function to be executed\n :param args: input arguments of the function\n :param no_cover_value: default value in absence of coral cover\n \n :type coral: Coral\n :type args: tuple\n :type no_cover_value: float, optional\n \"\"\"\n args = list(args)\n for i, arg in enumerate(args):\n if isinstance(arg, (float, int)) or (isinstance(arg, np.ndarray) and not arg.shape):\n args[i] = arg * np.ones(self.spacetime)\n elif arg.shape == coral.cover.shape:\n args[i] = np.tile(arg, (self.time, 1)).transpose()\n elif not arg.shape == self.spacetime:\n msg = f'Sizes do not match up, {arg.shape} =/= {self.spacetime}.'\n raise ValueError(msg)\n \n output = no_cover_value * np.ones(self.spacetime)\n output[coral.cover > 0] = function(*[\n arg[coral.cover > 0] for arg in args\n ])\n return output\n\n\ndef time_series_year(time_series, year):\n \"\"\"Extract a section of the time-series based on the year.\n\n :param time_series: time-series to be extracted\n :param year: year to be extracted\n\n :type time_series: pandas.DataFrame\n :type year: int\n \"\"\"\n return time_series[time_series.index.year == year].values.transpose()[0]\n" ]
[ [ "numpy.tile", "numpy.ones", "numpy.argmin", "numpy.repeat", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kmike/hdbscan
[ "da032cf2a116ff8adc8f2c96c56cbe44511b7eef" ]
[ "setup.py" ]
[ "import warnings\n\ntry:\n from Cython.Distutils import build_ext\n from setuptools import setup, Extension\n HAVE_CYTHON = True\nexcept ImportError as e:\n warnings.warn(e.message)\n from setuptools import setup, Extension\n from setuptools.command.build_ext import build_ext\n HAVE_CYTHON = False\n\nimport numpy\n\n_hdbscan_tree = Extension('hdbscan._hdbscan_tree',\n sources=['hdbscan/_hdbscan_tree.pyx'],\n include_dirs=[numpy.get_include()])\n_hdbscan_linkage = Extension('hdbscan._hdbscan_linkage',\n sources=['hdbscan/_hdbscan_linkage.pyx'],\n include_dirs=['hdbscan', numpy.get_include()])\n_hdbscan_boruvka = Extension('hdbscan._hdbscan_boruvka',\n sources=['hdbscan/_hdbscan_boruvka.pyx'],\n include_dirs=['hdbscan', numpy.get_include()])\n_hdbscan_reachability = Extension('hdbscan._hdbscan_reachability',\n sources=['hdbscan/_hdbscan_reachability.pyx'],\n include_dirs=[numpy.get_include()])\ndist_metrics = Extension('hdbscan.dist_metrics',\n sources=['hdbscan/dist_metrics.pyx'],\n include_dirs=[numpy.get_include()])\n\ndef readme():\n with open('README.rst') as readme_file:\n return readme_file.read()\n\nconfiguration = {\n 'name' : 'hdbscan',\n 'version' : '0.8.2',\n 'description' : 'Clustering based on density with variable density clusters',\n 'long_description' : readme(),\n 'classifiers' : [\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Science/Research',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved',\n 'Programming Language :: C',\n 'Programming Language :: Python',\n 'Topic :: Software Development',\n 'Topic :: Scientific/Engineering',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX',\n 'Operating System :: Unix',\n 'Operating System :: MacOS',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n ],\n 'keywords' : 'cluster clustering density hierarchical',\n 'url' : 'http://github.com/scikit-learn-contrib/hdbscan',\n 'maintainer' : 'Leland McInnes',\n 'maintainer_email' : '[email protected]',\n 'license' : 'BSD',\n 'packages' : ['hdbscan'],\n 'install_requires' : ['scikit-learn>=0.16',\n 'cython >= 0.17'],\n 'ext_modules' : [_hdbscan_tree,\n _hdbscan_linkage,\n _hdbscan_boruvka,\n _hdbscan_reachability,\n dist_metrics],\n 'cmdclass' : {'build_ext' : build_ext},\n 'test_suite' : 'nose.collector',\n 'tests_require' : ['nose'],\n }\n\nif not HAVE_CYTHON:\n _hdbscan_tree.sources[0] = '_hdbscan_tree.c'\n _hdbscan_linkage.sources[0] = '_hdbscan_linkage.c'\n _hdbscan_boruvka.sources[0] = '_hdbscan_boruvka.c'\n _hdbscan_reachability.sources[0] = '_hdbscan_reachability.c'\n dist_metrics.sources[0] = 'dist_metric.c'\n configuration['install_requires'] = ['scikit-learn>=0.16']\n\nsetup(**configuration)\n \n" ]
[ [ "numpy.get_include" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JuliaSprenger/python-neo
[ "832f1348a3de1d27aea09c1320bdb6609c4008d6" ]
[ "neo/io/proxyobjects.py" ]
[ "\"\"\"\nHere a list of proxy object that can be used when lazy=True at neo.io level.\n\nThis idea is to be able to postpone that real in memory loading\nfor objects that contains big data (AnalogSIgnal, SpikeTrain, Event, Epoch).\n\nThe implementation rely on neo.rawio, so it will available only for neo.io that\nineherits neo.rawio.\n\n\"\"\"\n\nimport numpy as np\nimport quantities as pq\nimport logging\n\nfrom neo.core.baseneo import BaseNeo\n\n\nfrom neo.core import (AnalogSignal,\n Epoch, Event, SpikeTrain)\nfrom neo.core.dataobject import ArrayDict\n\n\nlogger = logging.getLogger(\"Neo\")\n\n\nclass BaseProxy(BaseNeo):\n def __init__(self, array_annotations=None, **annotations):\n # this for py27 str vs py3 str in neo attributes ompatibility\n annotations = check_annotations(annotations)\n if 'file_origin' not in annotations:\n # the str is to make compatible with neo_py27 where attribute\n # used to be str so raw bytes\n annotations['file_origin'] = str(self._rawio.source_name())\n\n # this mock the array annotaions to avoid inherits DataObject\n self.array_annotations = ArrayDict(self.shape[-1])\n if array_annotations is not None:\n self.array_annotations.update(array_annotations)\n\n BaseNeo.__init__(self, **annotations)\n\n def load(self, time_slice=None, **kwargs):\n # should be implemented by subclass\n raise NotImplementedError\n\n def time_slice(self, t_start, t_stop):\n '''\n Load the proxy object within the specified time range. Has the same\n call signature as AnalogSignal.time_slice, Epoch.time_slice, etc.\n '''\n return self.load(time_slice=(t_start, t_stop))\n\n\nclass AnalogSignalProxy(BaseProxy):\n '''\n This object mimic AnalogSignal except that it does not\n have the signals array itself. All attributes and annotations are here.\n\n The goal is to postpone the loading of data into memory\n when reading a file with the new lazy load system based\n on neo.rawio.\n\n This object must not be constructed directly but is given\n neo.io when lazy=True instead of a true AnalogSignal.\n\n The AnalogSignalProxy is able to load:\n * only a slice of time\n * only a subset of channels\n * have an internal raw magnitude identic to the file (int16) with\n a pq.CompoundUnit().\n\n Usage:\n >>> proxy_anasig = AnalogSignalProxy(rawio=self.reader,\n global_channel_indexes=None,\n block_index=0,\n seg_index=0)\n >>> anasig = proxy_anasig.load()\n >>> slice_of_anasig = proxy_anasig.load(time_slice=(1.*pq.s, 2.*pq.s))\n >>> some_channel_of_anasig = proxy_anasig.load(channel_indexes=[0,5,10])\n\n '''\n _single_parent_objects = ('Segment', 'ChannelIndex')\n _necessary_attrs = (('sampling_rate', pq.Quantity, 0),\n ('t_start', pq.Quantity, 0))\n _recommended_attrs = BaseNeo._recommended_attrs\n proxy_for = AnalogSignal\n\n def __init__(self, rawio=None, global_channel_indexes=None, block_index=0, seg_index=0):\n self._rawio = rawio\n self._block_index = block_index\n self._seg_index = seg_index\n if global_channel_indexes is None:\n global_channel_indexes = slice(None)\n total_nb_chan = self._rawio.header['signal_channels'].size\n self._global_channel_indexes = np.arange(total_nb_chan)[global_channel_indexes]\n self._nb_chan = self._global_channel_indexes.size\n\n sig_chans = self._rawio.header['signal_channels'][self._global_channel_indexes]\n\n assert np.unique(sig_chans['units']).size == 1, 'Channel do not have same units'\n assert np.unique(sig_chans['dtype']).size == 1, 'Channel do not have same dtype'\n assert np.unique(sig_chans['sampling_rate']).size == 1, \\\n 'Channel do not have same sampling_rate'\n\n self.units = ensure_signal_units(sig_chans['units'][0])\n self.dtype = sig_chans['dtype'][0]\n self.sampling_rate = sig_chans['sampling_rate'][0] * pq.Hz\n self.sampling_period = 1. / self.sampling_rate\n sigs_size = self._rawio.get_signal_size(block_index=block_index, seg_index=seg_index,\n channel_indexes=self._global_channel_indexes)\n self.shape = (sigs_size, self._nb_chan)\n self.t_start = self._rawio.get_signal_t_start(block_index, seg_index,\n self._global_channel_indexes) * pq.s\n\n # magnitude_mode='raw' is supported only if all offset=0\n # and all gain are the same\n support_raw_magnitude = np.all(sig_chans['gain'] == sig_chans['gain'][0]) and \\\n np.all(sig_chans['offset'] == 0.)\n\n if support_raw_magnitude:\n str_units = ensure_signal_units(sig_chans['units'][0]).units.dimensionality.string\n self._raw_units = pq.CompoundUnit('{}*{}'.format(sig_chans['gain'][0], str_units))\n else:\n self._raw_units = None\n\n # both necessary attr and annotations\n annotations = {}\n annotations['name'] = self._make_name(None)\n if len(sig_chans) == 1:\n # when only one channel raw_annotations are set to standart annotations\n d = self._rawio.raw_annotations['blocks'][block_index]['segments'][seg_index][\n 'signals'][self._global_channel_indexes[0]]\n annotations.update(d)\n\n array_annotations = {\n 'channel_names': np.array(sig_chans['name'], copy=True),\n 'channel_ids': np.array(sig_chans['id'], copy=True),\n }\n # array annotations for signal can be at 2 places\n # global at signal channel level\n d = self._rawio.raw_annotations['signal_channels']\n array_annotations.update(create_analogsignal_array_annotations(\n d, self._global_channel_indexes))\n # or specific to block/segment/signals\n d = self._rawio.raw_annotations['blocks'][block_index]['segments'][seg_index]['signals']\n array_annotations.update(create_analogsignal_array_annotations(\n d, self._global_channel_indexes))\n\n BaseProxy.__init__(self, array_annotations=array_annotations, **annotations)\n\n def _make_name(self, channel_indexes):\n sig_chans = self._rawio.header['signal_channels'][self._global_channel_indexes]\n if channel_indexes is not None:\n sig_chans = sig_chans[channel_indexes]\n if len(sig_chans) == 1:\n name = sig_chans['name'][0]\n else:\n name = 'Channel bundle ({}) '.format(','.join(sig_chans['name']))\n return name\n\n @property\n def duration(self):\n '''Signal duration'''\n return self.shape[0] / self.sampling_rate\n\n @property\n def t_stop(self):\n '''Time when signal ends'''\n return self.t_start + self.duration\n\n def load(self, time_slice=None, strict_slicing=True,\n channel_indexes=None, magnitude_mode='rescaled'):\n '''\n *Args*:\n :time_slice: None or tuple of the time slice expressed with quantities.\n None is the entire signal.\n :channel_indexes: None or list. Channels to load. None is all channels\n Be carefull that channel_indexes represent the local channel index inside\n the AnalogSignal and not the global_channel_indexes like in rawio.\n :magnitude_mode: 'rescaled' or 'raw'.\n For instance if the internal dtype is int16:\n * **rescaled** give [1.,2.,3.]*pq.uV and the dtype is float32\n * **raw** give [10, 20, 30]*pq.CompoundUnit('0.1*uV')\n The CompoundUnit with magnitude_mode='raw' is usefull to\n postpone the scaling when needed and having an internal dtype=int16\n but it less intuitive when you don't know so well quantities.\n :strict_slicing: True by default.\n Control if an error is raise or not when one of time_slice member\n (t_start or t_stop) is outside the real time range of the segment.\n '''\n\n if channel_indexes is None:\n channel_indexes = slice(None)\n\n sr = self.sampling_rate\n\n if time_slice is None:\n i_start, i_stop = None, None\n sig_t_start = self.t_start\n else:\n t_start, t_stop = time_slice\n if t_start is None:\n i_start = None\n sig_t_start = self.t_start\n else:\n t_start = ensure_second(t_start)\n if strict_slicing:\n assert self.t_start <= t_start <= self.t_stop, 't_start is outside'\n else:\n t_start = max(t_start, self.t_start)\n # the i_start is ncessary ceil\n i_start = int(np.ceil((t_start - self.t_start).magnitude * sr.magnitude))\n # this needed to get the real t_start of the first sample\n # because do not necessary match what is demanded\n sig_t_start = self.t_start + i_start / sr\n\n if t_stop is None:\n i_stop = None\n else:\n t_stop = ensure_second(t_stop)\n if strict_slicing:\n assert self.t_start <= t_stop <= self.t_stop, 't_stop is outside'\n else:\n t_stop = min(t_stop, self.t_stop)\n i_stop = int((t_stop - self.t_start).magnitude * sr.magnitude)\n\n raw_signal = self._rawio.get_analogsignal_chunk(block_index=self._block_index,\n seg_index=self._seg_index, i_start=i_start, i_stop=i_stop,\n channel_indexes=self._global_channel_indexes[channel_indexes])\n\n # if slice in channel : change name and array_annotations\n if raw_signal.shape[1] != self._nb_chan:\n name = self._make_name(channel_indexes)\n array_annotations = {k: v[channel_indexes] for k, v in self.array_annotations.items()}\n else:\n name = self.name\n array_annotations = self.array_annotations\n\n if magnitude_mode == 'raw':\n assert self._raw_units is not None,\\\n 'raw magnitude is not support gain are not the same for all channel or offset is not 0'\n sig = raw_signal\n units = self._raw_units\n elif magnitude_mode == 'rescaled':\n # dtype is float32 when internally it is float32 or int16\n if self.dtype == 'float64':\n dtype = 'float64'\n else:\n dtype = 'float32'\n sig = self._rawio.rescale_signal_raw_to_float(raw_signal, dtype=dtype,\n channel_indexes=self._global_channel_indexes[channel_indexes])\n units = self.units\n\n anasig = AnalogSignal(sig, units=units, copy=False, t_start=sig_t_start,\n sampling_rate=self.sampling_rate, name=name,\n file_origin=self.file_origin, description=self.description,\n array_annotations=array_annotations, **self.annotations)\n\n return anasig\n\n\nclass SpikeTrainProxy(BaseProxy):\n '''\n This object mimic SpikeTrain except that it does not\n have the spike time nor waveforms.\n All attributes and annotations are here.\n\n The goal is to postpone the loading of data into memory\n when reading a file with the new lazy load system based\n on neo.rawio.\n\n This object must not be constructed directly but is given\n neo.io when lazy=True instead of a true SpikeTrain.\n\n The SpikeTrainProxy is able to load:\n * only a slice of time\n * load wveforms or not.\n * have an internal raw magnitude identic to the file (generally the ticks\n of clock in int64) or the rescale to seconds.\n\n Usage:\n >>> proxy_sptr = SpikeTrainProxy(rawio=self.reader, unit_channel=0,\n block_index=0, seg_index=0,)\n >>> sptr = proxy_sptr.load()\n >>> slice_of_sptr = proxy_sptr.load(time_slice=(1.*pq.s, 2.*pq.s))\n\n '''\n\n _single_parent_objects = ('Segment', 'Unit')\n _quantity_attr = 'times'\n _necessary_attrs = (('t_start', pq.Quantity, 0),\n ('t_stop', pq.Quantity, 0))\n _recommended_attrs = ()\n proxy_for = SpikeTrain\n\n def __init__(self, rawio=None, unit_index=None, block_index=0, seg_index=0):\n\n self._rawio = rawio\n self._block_index = block_index\n self._seg_index = seg_index\n self._unit_index = unit_index\n\n nb_spike = self._rawio.spike_count(block_index=block_index, seg_index=seg_index,\n unit_index=unit_index)\n self.shape = (nb_spike, )\n\n self.t_start = self._rawio.segment_t_start(block_index, seg_index) * pq.s\n self.t_stop = self._rawio.segment_t_stop(block_index, seg_index) * pq.s\n\n # both necessary attr and annotations\n annotations = {}\n for k in ('name', 'id'):\n annotations[k] = self._rawio.header['unit_channels'][unit_index][k]\n ann = self._rawio.raw_annotations['blocks'][block_index]['segments'][seg_index]['units'][unit_index]\n annotations.update(ann)\n\n h = self._rawio.header['unit_channels'][unit_index]\n wf_sampling_rate = h['wf_sampling_rate']\n if not np.isnan(wf_sampling_rate) and wf_sampling_rate > 0:\n self.sampling_rate = wf_sampling_rate * pq.Hz\n self.left_sweep = (h['wf_left_sweep'] / self.sampling_rate).rescale('s')\n self._wf_units = ensure_signal_units(h['wf_units'])\n else:\n self.sampling_rate = None\n self.left_sweep = None\n\n BaseProxy.__init__(self, **annotations)\n\n def load(self, time_slice=None, strict_slicing=True,\n magnitude_mode='rescaled', load_waveforms=False):\n '''\n *Args*:\n :time_slice: None or tuple of the time slice expressed with quantities.\n None is the entire signal.\n :strict_slicing: True by default.\n Control if an error is raise or not when one of time_slice\n member (t_start or t_stop) is outside the real time range of the segment.\n :magnitude_mode: 'rescaled' or 'raw'.\n :load_waveforms: bool load waveforms or not.\n '''\n\n t_start, t_stop = consolidate_time_slice(time_slice, self.t_start,\n self.t_stop, strict_slicing)\n _t_start, _t_stop = prepare_time_slice(time_slice)\n\n spike_timestamps = self._rawio.get_spike_timestamps(block_index=self._block_index,\n seg_index=self._seg_index, unit_index=self._unit_index, t_start=_t_start,\n t_stop=_t_stop)\n\n if magnitude_mode == 'raw':\n # we must modify a bit the neo.rawio interface to also read the spike_timestamps\n # underlying clock wich is not always same as sigs\n raise(NotImplementedError)\n elif magnitude_mode == 'rescaled':\n dtype = 'float64'\n spike_times = self._rawio.rescale_spike_timestamp(spike_timestamps, dtype=dtype)\n units = 's'\n\n if load_waveforms:\n assert self.sampling_rate is not None, 'Do not have waveforms'\n\n raw_wfs = self._rawio.get_spike_raw_waveforms(block_index=self._block_index,\n seg_index=self._seg_index, unit_index=self._unit_index,\n t_start=_t_start, t_stop=_t_stop)\n if magnitude_mode == 'rescaled':\n float_wfs = self._rawio.rescale_waveforms_to_float(raw_wfs,\n dtype='float32', unit_index=self._unit_index)\n waveforms = pq.Quantity(float_wfs, units=self._wf_units,\n dtype='float32', copy=False)\n elif magnitude_mode == 'raw':\n # could code also CompundUnit here but it is over killed\n # so we used dimentionless\n waveforms = pq.Quantity(raw_wfs, units='',\n dtype=raw_wfs.dtype, copy=False)\n else:\n waveforms = None\n\n sptr = SpikeTrain(spike_times, t_stop, units=units, dtype=dtype,\n t_start=t_start, copy=False, sampling_rate=self.sampling_rate,\n waveforms=waveforms, left_sweep=self.left_sweep, name=self.name,\n file_origin=self.file_origin, description=self.description, **self.annotations)\n\n return sptr\n\n\nclass _EventOrEpoch(BaseProxy):\n _single_parent_objects = ('Segment',)\n _quantity_attr = 'times'\n\n def __init__(self, rawio=None, event_channel_index=None, block_index=0, seg_index=0):\n\n self._rawio = rawio\n self._block_index = block_index\n self._seg_index = seg_index\n self._event_channel_index = event_channel_index\n\n nb_event = self._rawio.event_count(block_index=block_index, seg_index=seg_index,\n event_channel_index=event_channel_index)\n self.shape = (nb_event, )\n\n self.t_start = self._rawio.segment_t_start(block_index, seg_index) * pq.s\n self.t_stop = self._rawio.segment_t_stop(block_index, seg_index) * pq.s\n\n # both necessary attr and annotations\n annotations = {}\n for k in ('name', 'id'):\n annotations[k] = self._rawio.header['event_channels'][event_channel_index][k]\n ann = self._rawio.raw_annotations['blocks'][block_index]['segments'][seg_index]['events'][event_channel_index]\n annotations.update(ann)\n\n BaseProxy.__init__(self, **annotations)\n\n def load(self, time_slice=None, strict_slicing=True):\n '''\n *Args*:\n :time_slice: None or tuple of the time slice expressed with quantities.\n None is the entire signal.\n :strict_slicing: True by default.\n Control if an error is raise or not when one of time_slice member (t_start or t_stop)\n is outside the real time range of the segment.\n '''\n\n t_start, t_stop = consolidate_time_slice(time_slice, self.t_start,\n self.t_stop, strict_slicing)\n _t_start, _t_stop = prepare_time_slice(time_slice)\n\n timestamp, durations, labels = self._rawio.get_event_timestamps(block_index=self._block_index,\n seg_index=self._seg_index, event_channel_index=self._event_channel_index,\n t_start=_t_start, t_stop=_t_stop)\n\n dtype = 'float64'\n times = self._rawio.rescale_event_timestamp(timestamp, dtype=dtype)\n units = 's'\n\n if durations is not None:\n durations = self._rawio.rescale_epoch_duration(durations, dtype=dtype) * pq.s\n\n h = self._rawio.header['event_channels'][self._event_channel_index]\n if h['type'] == b'event':\n ret = Event(times=times, labels=labels, units='s',\n name=self.name, file_origin=self.file_origin,\n description=self.description, **self.annotations)\n elif h['type'] == b'epoch':\n ret = Epoch(times=times, durations=durations, labels=labels,\n units='s',\n name=self.name, file_origin=self.file_origin,\n description=self.description, **self.annotations)\n\n return ret\n\n\nclass EventProxy(_EventOrEpoch):\n '''\n This object mimic Event except that it does not\n have the times nor labels.\n All other attributes and annotations are here.\n\n The goal is to postpone the loading of data into memory\n when reading a file with the new lazy load system based\n on neo.rawio.\n\n This object must not be constructed directly but is given\n neo.io when lazy=True instead of a true Event.\n\n The EventProxy is able to load:\n * only a slice of time\n\n Usage:\n >>> proxy_event = EventProxy(rawio=self.reader, event_channel_index=0,\n block_index=0, seg_index=0,)\n >>> event = proxy_event.load()\n >>> slice_of_event = proxy_event.load(time_slice=(1.*pq.s, 2.*pq.s))\n\n '''\n _necessary_attrs = (('times', pq.Quantity, 1),\n ('labels', np.ndarray, 1, np.dtype('S')))\n proxy_for = Event\n\n\nclass EpochProxy(_EventOrEpoch):\n '''\n This object mimic Epoch except that it does not\n have the times nor labels nor durations.\n All other attributes and annotations are here.\n\n The goal is to postpone the loading of data into memory\n when reading a file with the new lazy load system based\n on neo.rawio.\n\n This object must not be constructed directly but is given\n neo.io when lazy=True instead of a true Epoch.\n\n The EpochProxy is able to load:\n * only a slice of time\n\n Usage:\n >>> proxy_epoch = EpochProxy(rawio=self.reader, event_channel_index=0,\n block_index=0, seg_index=0,)\n >>> epoch = proxy_epoch.load()\n >>> slice_of_epoch = proxy_epoch.load(time_slice=(1.*pq.s, 2.*pq.s))\n\n '''\n _necessary_attrs = (('times', pq.Quantity, 1),\n ('durations', pq.Quantity, 1),\n ('labels', np.ndarray, 1, np.dtype('S')))\n proxy_for = Epoch\n\n\nproxyobjectlist = [AnalogSignalProxy, SpikeTrainProxy, EventProxy,\n EpochProxy]\n\n\nunit_convert = {'Volts': 'V', 'volts': 'V', 'Volt': 'V',\n 'volt': 'V', ' Volt': 'V', 'microV': 'uV',\n # note that \"micro\" and \"mu\" are two different characters in Unicode\n # although they mostly look the same. Here we accept both.\n 'µV': 'uV', 'μV': 'uV'}\n\n\ndef ensure_signal_units(units):\n # test units\n units = units.replace(' ', '')\n if units in unit_convert:\n units = unit_convert[units]\n try:\n units = pq.Quantity(1, units)\n except:\n logger.warning('Units \"{}\" can not be converted to a quantity. Using dimensionless '\n 'instead'.format(units))\n units = ''\n units = pq.Quantity(1, units)\n return units\n\n\ndef check_annotations(annotations):\n # force type to str for some keys\n # imposed for tests\n for k in ('name', 'description', 'file_origin'):\n if k in annotations:\n annotations[k] = str(annotations[k])\n\n if 'coordinates' in annotations:\n # some rawio expose some coordinates in annotations but is not standardized\n # (x, y, z) or polar, at the moment it is more resonable to remove them\n annotations.pop('coordinates')\n\n return annotations\n\n\ndef ensure_second(v):\n if isinstance(v, float):\n return v * pq.s\n elif isinstance(v, pq.Quantity):\n return v.rescale('s')\n elif isinstance(v, int):\n return float(v) * pq.s\n\n\ndef prepare_time_slice(time_slice):\n \"\"\"\n This give clean time slice but keep None\n for calling rawio slice\n \"\"\"\n if time_slice is None:\n t_start, t_stop = None, None\n else:\n t_start, t_stop = time_slice\n\n if t_start is not None:\n t_start = ensure_second(t_start).rescale('s').magnitude\n\n if t_stop is not None:\n t_stop = ensure_second(t_stop).rescale('s').magnitude\n\n return (t_start, t_stop)\n\n\ndef consolidate_time_slice(time_slice, seg_t_start, seg_t_stop, strict_slicing):\n \"\"\"\n This give clean time slice in quantity for t_start/t_stop of object\n None is replace by seg limit.\n \"\"\"\n if time_slice is None:\n t_start, t_stop = None, None\n else:\n t_start, t_stop = time_slice\n\n if t_start is None:\n t_start = seg_t_start\n else:\n if strict_slicing:\n assert seg_t_start <= t_start <= seg_t_stop, 't_start is outside'\n else:\n t_start = max(t_start, seg_t_start)\n t_start = ensure_second(t_start)\n\n if t_stop is None:\n t_stop = seg_t_stop\n else:\n if strict_slicing:\n assert seg_t_start <= t_stop <= seg_t_stop, 't_stop is outside'\n else:\n t_stop = min(t_stop, seg_t_stop)\n t_stop = ensure_second(t_stop)\n\n return (t_start, t_stop)\n\n\ndef create_analogsignal_array_annotations(sig_annotations, global_channel_indexes):\n \"\"\"\n Create array_annotations from raw_annoations.\n Since raw_annotation are not np.array but nested dict, this func\n try to find keys in raw_annotation that are shared by all channel\n and make array_annotation with it.\n \"\"\"\n # intersection of keys across channels\n common_keys = None\n for ind in global_channel_indexes:\n keys = [k for k, v in sig_annotations[ind].items() if not \\\n isinstance(v, (list, tuple, np.ndarray))]\n if common_keys is None:\n common_keys = keys\n else:\n common_keys = [k for k in common_keys if k in keys]\n\n # this is redundant and done with other name\n for k in ['name', 'channel_id']:\n if k in common_keys:\n common_keys.remove(k)\n\n array_annotations = {}\n for k in common_keys:\n values = [sig_annotations[ind][k] for ind in global_channel_indexes]\n array_annotations[k] = np.array(values)\n\n return array_annotations\n" ]
[ [ "numpy.unique", "numpy.isnan", "numpy.arange", "numpy.dtype", "numpy.all", "numpy.ceil", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tianyang-he/HARK
[ "2ebf435623c4fc487bd43709614b0fb1ade853a1", "2ebf435623c4fc487bd43709614b0fb1ade853a1" ]
[ "examples/LifecycleModel/LifecycleModel.py", "HARK/ConsumptionSaving/ConsIndShockModelFast.py" ]
[ "# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: collapsed,code_folding\n# formats: ipynb,py:percent\n# notebook_metadata_filter: all\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.2'\n# jupytext_version: 1.2.3\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# language_info:\n# codemirror_mode:\n# name: ipython\n# version: 3\n# file_extension: .py\n# mimetype: text/x-python\n# name: python\n# nbconvert_exporter: python\n# pygments_lexer: ipython3\n# version: 3.7.6\n# ---\n\n# %% [markdown]\n#\n# # The Distribution of Assets By Age\n#\n# National registry data on income and wealth from Scandinavian countries has recently become available (with a lot of security) to some (lucky!) researchers. These data offer a uniquely powerful tool for testing (and improving) our models of consumption and saving behavior over the life cycle.\n#\n#\n# But as of this writing (in March of 2019), the data are so new that there do not seem to be any published attempts to compare the data to the implications a standard life cycle model with income uncertainty, constraints, and other modern features.\n#\n# This notebook is an example of how one could counstruct a life cycle model with the HARK toolkit that would make predictions about the model analogues of the raw data statistics that are available. \n#\n# For example, the papers have shown information about the growth rate of assets at different ages over the life cycle. Here, we show how (under a given parameterization) we could produce the life cycle model's prediction about the distribution of assets at age 65 and age 66, and the growth rate between 65 and 66. \n#\n# The parameters of the model have not been optmized to match features of the Norwegian data; a first step in \"structural\" estimation would be to calibrate the inputs to the model (like the profile of income over the life cycle, and the magnitude of income shocks), and then to find the values of parameters like the time preference rate that allow the model to fit the data best.\n#\n# An interesting question is whether this exercise will suggest that it is necessary to allow for _ex ante_ heterogeneity in such preference parameters.\n#\n# This seems likely; a paper by [<cite data-cite=\"6202365/7MR8GUVS\"></cite>](http://econ.jhu.edu/people/ccarroll/papers/cstwMPC) (all of whose results were constructed using the HARK toolkit) finds that, if all other parameters (e.g., rates of return on savings) are the same, models of this kind require substantial heterogeneity in preferences to generate the degree of inequality in U.S. data.\n#\n# But in one of the many new and interesting findings from the Norwegian data, <cite data-cite=\"6202365/B9BGV9W3\"></cite> have shown that there is substantial heterogeneity in rates of return, even on wealth held in public markets. \n#\n# [Derin Aksit](https://github.com/econ-ark/REMARK) has shown that the degree of time preference heterogeneity needed to match observed inequality is considerably less when rate-of-return heterogeneity is calibrated to match these data.\n\n# %% {\"code_folding\": [0]}\n# Initial imports and notebook setup, click arrow to show\n\nimport HARK.ConsumptionSaving.ConsIndShockModel as Model # The consumption-saving micro model\nimport EstimationParameters as Params # Parameters for the consumer type and the estimation\nfrom HARK.utilities import plotFuncsDer, plotFuncs # Some tools\n\nimport numpy as np\n\n\n# %% {\"code_folding\": [0]}\n# Set up default values for CRRA, DiscFac, and simulation variables in the dictionary \nParams.init_consumer_objects[\"CRRA\"]= 2.00 # Default coefficient of relative risk aversion (rho)\nParams.init_consumer_objects[\"DiscFac\"]= 0.97 # Default intertemporal discount factor (beta)\nParams.init_consumer_objects[\"PermGroFacAgg\"]= 1.0 # Aggregate permanent income growth factor \nParams.init_consumer_objects[\"aNrmInitMean\"]= -10.0 # Mean of log initial assets \nParams.init_consumer_objects[\"aNrmInitStd\"]= 1.0 # Standard deviation of log initial assets\nParams.init_consumer_objects[\"pLvlInitMean\"]= 0.0 # Mean of log initial permanent income \nParams.init_consumer_objects[\"pLvlInitStd\"]= 0.0 # Standard deviation of log initial permanent income\n\n\n# %%\n# Make a lifecycle consumer to be used for estimation\nLifeCyclePop = Model.IndShockConsumerType(**Params.init_consumer_objects)\n\n\n# %% {\"code_folding\": [0]}\n# Solve and simulate the model (ignore the \"warning\" message)\nLifeCyclePop.solve() # Obtain consumption rules by age \nLifeCyclePop.unpack('cFunc') # Expose the consumption rules\n\n# Which variables do we want to track\nLifeCyclePop.track_vars = ['aNrmNow','pLvlNow','mNrmNow','cNrmNow','TranShkNow']\n\nLifeCyclePop.T_sim = 120 # Nobody lives to be older than 145 years (=25+120)\nLifeCyclePop.initializeSim() # Construct the age-25 distribution of income and assets\nLifeCyclePop.simulate() # Simulate a population behaving according to this model\n\n\n# %% {\"code_folding\": [0]}\n# Plot the consumption functions during working life\n\nprint('Consumption as a function of market resources while working:')\nmMin = min([LifeCyclePop.solution[t].mNrmMin for t in range(LifeCyclePop.T_cycle)])\nplotFuncs(LifeCyclePop.cFunc[:LifeCyclePop.T_retire],mMin,5)\n\n\n# %% {\"code_folding\": [0]}\n# Define the saving rate function\ndef savingRateFunc(SomeType, m):\n \"\"\"\n Parameters:\n ----------\n SomeType: \n Agent type that has been solved and simulated.\n \n \n Returns:\n --------\n SavingRate: float\n \n \"\"\"\n inc = (SomeType.Rfree -1.)*(m-1.)+1.\n cons = SomeType.solution[0].cFunc(m)\n Saving = inc - cons\n SavingRate = Saving / inc\n return SavingRate \n\n\n# %% {\"code_folding\": [0]}\n# Create a Giant matrix gathering useful data:\n# 't_now', 'aNrmNow_hist', 'cNrmNow_hist', employment-status in date t, in date t-1, aLvlGro_hist, Saving rate\n\nw, h = 1, LifeCyclePop.T_cycle\ngiant_list = [[0 for x in range(w)] for y in range(h)]\nSavingRate_list = []\n\nimport warnings\nwarnings.filterwarnings(\"ignore\") # Suppress some disturbing but harmless warnings\n\nfor t in range(1,LifeCyclePop.T_cycle+1):\n #aLvlGro_hist[0] = 0 # set the first growth rate to 0, since there is no data for period 0\n aLvlGroNow = np.log(LifeCyclePop.history['aNrmNow'][t]/LifeCyclePop.history['aNrmNow'][t-1]) # (10000,)\n\n # Call the saving rate function with test value for \n SavingRate = savingRateFunc(LifeCyclePop, LifeCyclePop.history['mNrmNow'][t] )\n \n SavingRate_list.append(SavingRate)\n\n # Create elements of matrix list\n matrix_list = [0 for number in range(7)]\n matrix_list[0] = t\n matrix_list[1] = LifeCyclePop.history['aNrmNow'][t]\n matrix_list[2] = LifeCyclePop.history['cNrmNow'][t]\n matrix_list[3] = LifeCyclePop.history['TranShkNow'][t]\n matrix_list[4] = LifeCyclePop.history['TranShkNow'][t-1]\n matrix_list[5] = aLvlGroNow\n matrix_list[6] = SavingRate\n \n giant_list[t-1] = matrix_list\n \n# Print command disabled to prevent giant print!\n#print giant_list\n\n\n# %% {\"code_folding\": [0]}\n# Construct the level of assets A from a*p where a is the ratio to permanent income p\nLifeCyclePop.history['aLvlNow'] = LifeCyclePop.history['aNrmNow']*LifeCyclePop.history['pLvlNow']\naGro41=LifeCyclePop.history['aLvlNow'][41]/LifeCyclePop.history['aLvlNow'][40]\naGro41NoU=aGro41[aGro41[:]>0.2] # Throw out extreme outliers\n\n\n# %% {\"code_folding\": [0]}\n# Plot the distribution of growth rates of wealth between age 65 and 66 (=25 + 41)\nfrom matplotlib import pyplot as plt\nn, bins, patches = plt.hist(aGro41NoU,50,density=True)\n\n", "\"\"\"\nClasses to solve canonical consumption-savings models with idiosyncratic shocks\nto income. All models here assume CRRA utility with geometric discounting, no\nbequest motive, and income shocks are fully transitory or fully permanent.\n\nIt currently solves three types of models:\n 1) A very basic \"perfect foresight\" consumption-savings model with no uncertainty.\n 2) A consumption-savings model with risk over transitory and permanent income shocks. #todo\n 3) The model described in (2), with an interest rate for debt that differs\n from the interest rate for savings. #todo\n\nSee NARK https://HARK.githhub.io/Documentation/NARK for information on variable naming conventions.\nSee HARK documentation for mathematical descriptions of the models being solved.\n\"\"\"\n\nfrom copy import deepcopy\n\nimport numpy as np\nfrom interpolation import interp\nfrom numba import njit\nfrom quantecon.optimize import newton_secant\n\nfrom HARK import makeOnePeriodOOSolver, HARKobject\nfrom HARK.ConsumptionSaving.ConsIndShockModel import (\n ConsumerSolution,\n ConsPerfForesightSolver,\n PerfForesightConsumerType,\n ValueFunc,\n MargValueFunc,\n MargMargValueFunc,\n)\nfrom HARK.interpolation import LinearInterp\nfrom HARK.utilities import (\n CRRAutility,\n CRRAutilityP,\n CRRAutilityPP,\n CRRAutilityP_inv,\n CRRAutility_invP,\n CRRAutility_inv,\n CRRAutilityP_invP,\n)\n\n__all__ = [\n \"PerfForesightSolution\",\n \"ConsPerfForesightSolverFast\",\n \"PerfForesightConsumerTypeFast\",\n]\n\nutility = CRRAutility\nutilityP = CRRAutilityP\nutilityPP = CRRAutilityPP\nutilityP_inv = CRRAutilityP_inv\nutility_invP = CRRAutility_invP\nutility_inv = CRRAutility_inv\nutilityP_invP = CRRAutilityP_invP\n\n\n# =====================================================================\n# === Classes that help solve consumption-saving models ===\n# =====================================================================\n\n\nclass PerfForesightSolution(HARKobject):\n \"\"\"\n A class representing the solution of a single period of a consumption-saving\n perfect foresight problem.\n\n Here and elsewhere in the code, Nrm indicates that variables are normalized\n by permanent income.\n \"\"\"\n\n distance_criteria = [\"cNrm\", \"mNrm\"]\n\n def __init__(\n self,\n mNrm=np.array([0.0, 1.0]),\n cNrm=np.array([0.0, 1.0]),\n vFuncNvrsSlope=0.0,\n mNrmMin=0.0,\n hNrm=0.0,\n MPCmin=1.0,\n MPCmax=1.0,\n ):\n \"\"\"\n The constructor for a new ConsumerSolution object.\n\n Parameters\n ----------\n mNrm: np.array\n (Normalized) corresponding market resource points for interpolation.\n cNrm : np.array\n (Normalized) consumption points for interpolation.\n vFuncNvrsSlope: float\n Constant slope of inverse value vFuncNvrs\n mNrmMin : float\n The minimum allowable market resources for this period; the consump-\n tion function (etc) are undefined for m < mNrmMin.\n hNrm : float\n Human wealth after receiving income this period: PDV of all future\n income, ignoring mortality.\n MPCmin : float\n Infimum of the marginal propensity to consume this period.\n MPC --> MPCmin as m --> infinity.\n MPCmax : float\n Supremum of the marginal propensity to consume this period.\n MPC --> MPCmax as m --> mNrmMin.\n\n Returns\n -------\n None\n \"\"\"\n self.mNrm = mNrm\n self.cNrm = cNrm\n self.vFuncNvrsSlope = vFuncNvrsSlope\n self.mNrmMin = mNrmMin\n self.hNrm = hNrm\n self.MPCmin = MPCmin\n self.MPCmax = MPCmax\n\n\n# =====================================================================\n# === Classes and functions that solve consumption-saving models ===\n# =====================================================================\n\n\n@njit(cache=True)\ndef _searchSSfunc(m, Rfree, PermGroFac, mNrm, cNrm, ExIncNext):\n # Make a linear function of all combinations of c and m that yield mNext = mNow\n mZeroChange = (1.0 - PermGroFac / Rfree) * m + (PermGroFac / Rfree) * ExIncNext\n\n # Find the steady state level of market resources\n res = interp(mNrm, cNrm, m) - mZeroChange\n # A zero of this is SS market resources\n return res\n\n\n# @njit(cache=True) can't cache because of use of globals, perhaps newton_secant?\n@njit\ndef _addSSmNrmNumba(Rfree, PermGroFac, mNrm, cNrm, mNrmMin, ExIncNext):\n \"\"\"\n Finds steady state (normalized) market resources and adds it to the\n solution. This is the level of market resources such that the expectation\n of market resources in the next period is unchanged. This value doesn't\n necessarily exist.\n \"\"\"\n\n # Minimum market resources plus next income is okay starting guess\n m_init_guess = mNrmMin + ExIncNext\n\n mNrmSS = newton_secant(\n _searchSSfunc,\n m_init_guess,\n args=(Rfree, PermGroFac, mNrm, cNrm, ExIncNext),\n disp=False,\n )\n\n if mNrmSS.converged:\n return mNrmSS.root\n else:\n return None\n\n\n@njit(cache=True)\ndef _solveConsPerfForesightNumba(\n DiscFac,\n LivPrb,\n CRRA,\n Rfree,\n PermGroFac,\n BoroCnstArt,\n MaxKinks,\n mNrmNext,\n cNrmNext,\n hNrmNext,\n MPCminNext,\n):\n \"\"\"\n Makes the (linear) consumption function for this period.\n \"\"\"\n\n DiscFacEff = DiscFac * LivPrb\n\n # Calculate human wealth this period\n hNrmNow = (PermGroFac / Rfree) * (hNrmNext + 1.0)\n\n # Calculate the lower bound of the marginal propensity to consume\n PatFac = ((Rfree * DiscFacEff) ** (1.0 / CRRA)) / Rfree\n MPCmin = 1.0 / (1.0 + PatFac / MPCminNext)\n\n # Extract the discrete kink points in next period's consumption function;\n # don't take the last one, as it only defines the extrapolation and is not a kink.\n mNrmNext = mNrmNext[:-1]\n cNrmNext = cNrmNext[:-1]\n\n # Calculate the end-of-period asset values that would reach those kink points\n # next period, then invert the first order condition to get consumption. Then\n # find the endogenous gridpoint (kink point) today that corresponds to each kink\n aNrmNow = (PermGroFac / Rfree) * (mNrmNext - 1.0)\n cNrmNow = (DiscFacEff * Rfree) ** (-1.0 / CRRA) * (PermGroFac * cNrmNext)\n mNrmNow = aNrmNow + cNrmNow\n\n # Add an additional point to the list of gridpoints for the extrapolation,\n # using the new value of the lower bound of the MPC.\n mNrmNow = np.append(mNrmNow, mNrmNow[-1] + 1.0)\n cNrmNow = np.append(cNrmNow, cNrmNow[-1] + MPCmin)\n\n # If the artificial borrowing constraint binds, combine the constrained and\n # unconstrained consumption functions.\n if BoroCnstArt > mNrmNow[0]:\n # Find the highest index where constraint binds\n cNrmCnst = mNrmNow - BoroCnstArt\n CnstBinds = cNrmCnst < cNrmNow\n idx = np.where(CnstBinds)[0][-1]\n\n if idx < (mNrmNow.size - 1):\n # If it is not the *very last* index, find the the critical level\n # of mNrm where the artificial borrowing contraint begins to bind.\n d0 = cNrmNow[idx] - cNrmCnst[idx]\n d1 = cNrmCnst[idx + 1] - cNrmNow[idx + 1]\n m0 = mNrmNow[idx]\n m1 = mNrmNow[idx + 1]\n alpha = d0 / (d0 + d1)\n mCrit = m0 + alpha * (m1 - m0)\n\n # Adjust the grids of mNrm and cNrm to account for the borrowing constraint.\n cCrit = mCrit - BoroCnstArt\n mNrmNow = np.concatenate(\n (np.array([BoroCnstArt, mCrit]), mNrmNow[(idx + 1) :])\n )\n cNrmNow = np.concatenate((np.array([0.0, cCrit]), cNrmNow[(idx + 1) :]))\n\n else:\n # If it *is* the very last index, then there are only three points\n # that characterize the consumption function: the artificial borrowing\n # constraint, the constraint kink, and the extrapolation point.\n mXtra = cNrmNow[-1] - cNrmCnst[-1] / (1.0 - MPCmin)\n mCrit = mNrmNow[-1] + mXtra\n cCrit = mCrit - BoroCnstArt\n mNrmNow = np.array([BoroCnstArt, mCrit, mCrit + 1.0])\n cNrmNow = np.array([0.0, cCrit, cCrit + MPCmin])\n\n # If the mNrm and cNrm grids have become too large, throw out the last\n # kink point, being sure to adjust the extrapolation.\n if mNrmNow.size > MaxKinks:\n mNrmNow = np.concatenate((mNrmNow[:-2], np.array([mNrmNow[-3] + 1.0])))\n cNrmNow = np.concatenate((cNrmNow[:-2], np.array([cNrmNow[-3] + MPCmin])))\n\n # Calculate the upper bound of the MPC as the slope of the bottom segment.\n MPCmax = (cNrmNow[1] - cNrmNow[0]) / (mNrmNow[1] - mNrmNow[0])\n\n # Add attributes to enable calculation of steady state market resources.\n # Relabeling for compatibility with addSSmNrm\n mNrmMinNow = mNrmNow[0]\n\n # See the PerfForesightConsumerType.ipynb documentation notebook for the derivations\n vFuncNvrsSlope = MPCmin ** (-CRRA / (1.0 - CRRA))\n\n return (\n mNrmNow,\n cNrmNow,\n vFuncNvrsSlope,\n mNrmMinNow,\n hNrmNow,\n MPCmin,\n MPCmax,\n )\n\n\nclass ConsPerfForesightSolverFast(ConsPerfForesightSolver):\n \"\"\"\n A class for solving a one period perfect foresight consumption-saving problem.\n An instance of this class is created by the function solvePerfForesight in each period.\n \"\"\"\n\n def solve(self):\n \"\"\"\n Solves the one period perfect foresight consumption-saving problem.\n\n Parameters\n ----------\n None\n\n Returns\n -------\n solution : PerfForesightSolution\n The solution to this period's problem.\n \"\"\"\n # Use a local value of BoroCnstArt to prevent comparing None and float below.\n if self.BoroCnstArt is None:\n BoroCnstArt = -np.inf\n else:\n BoroCnstArt = self.BoroCnstArt\n\n (\n self.mNrmNow,\n self.cNrmNow,\n self.vFuncNvrsSlope,\n self.mNrmMinNow,\n self.hNrmNow,\n self.MPCmin,\n self.MPCmax,\n ) = _solveConsPerfForesightNumba(\n self.DiscFac,\n self.LivPrb,\n self.CRRA,\n self.Rfree,\n self.PermGroFac,\n BoroCnstArt,\n self.MaxKinks,\n self.solution_next.mNrm,\n self.solution_next.cNrm,\n self.solution_next.hNrm,\n self.solution_next.MPCmin,\n )\n\n solution = PerfForesightSolution(\n self.mNrmNow,\n self.cNrmNow,\n self.vFuncNvrsSlope,\n self.mNrmMinNow,\n self.hNrmNow,\n self.MPCmin,\n self.MPCmax,\n )\n return solution\n\n\n# ============================================================================\n# == Classes for representing types of consumer agents (and things they do) ==\n# ============================================================================\n\n\nclass PerfForesightConsumerTypeFast(PerfForesightConsumerType):\n \"\"\"\n A perfect foresight consumer type who has no uncertainty other than mortality.\n His problem is defined by a coefficient of relative risk aversion, intertemporal\n discount factor, interest factor, an artificial borrowing constraint (maybe)\n and time sequences of the permanent income growth rate and survival probability.\n \"\"\"\n\n # Define some universal values for all consumer types\n solution_terminal_ = PerfForesightSolution()\n\n def __init__(self, **kwargs):\n PerfForesightConsumerType.__init__(self, **kwargs)\n\n self.solveOnePeriod = makeOnePeriodOOSolver(ConsPerfForesightSolverFast)\n\n def updateSolutionTerminal(self):\n \"\"\"\n Update the terminal period solution. This method should be run when a\n new AgentType is created or when CRRA changes.\n \"\"\"\n\n self.solution_terminal_cs = ConsumerSolution(\n cFunc=self.cFunc_terminal_,\n vFunc=ValueFunc(self.cFunc_terminal_, self.CRRA),\n vPfunc=MargValueFunc(self.cFunc_terminal_, self.CRRA),\n vPPfunc=MargMargValueFunc(self.cFunc_terminal_, self.CRRA),\n mNrmMin=0.0,\n hNrm=0.0,\n MPCmin=1.0,\n MPCmax=1.0,\n )\n\n def postSolve(self):\n self.solution_fast = deepcopy(self.solution)\n\n if self.cycles == 0:\n terminal = 1\n else:\n terminal = self.cycles\n self.solution[terminal] = self.solution_terminal_cs\n\n for i in range(terminal):\n solution = self.solution[i]\n\n # Construct the consumption function as a linear interpolation.\n cFunc = LinearInterp(solution.mNrm, solution.cNrm)\n\n \"\"\"\n Defines the value and marginal value functions for this period.\n Uses the fact that for a perfect foresight CRRA utility problem,\n if the MPC in period t is :math:`\\kappa_{t}`, and relative risk\n aversion :math:`\\rho`, then the inverse value vFuncNvrs has a\n constant slope of :math:`\\kappa_{t}^{-\\rho/(1-\\rho)}` and\n vFuncNvrs has value of zero at the lower bound of market resources\n mNrmMin. See PerfForesightConsumerType.ipynb documentation notebook\n for a brief explanation and the links below for a fuller treatment.\n\n https://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA/#vFuncAnalytical\n https://econ.jhu.edu/people/ccarroll/SolvingMicroDSOPs/#vFuncPF\n \"\"\"\n\n vFuncNvrs = LinearInterp(\n np.array([solution.mNrmMin, solution.mNrmMin + 1.0]),\n np.array([0.0, solution.vFuncNvrsSlope]),\n )\n vFunc = ValueFunc(vFuncNvrs, self.CRRA)\n vPfunc = MargValueFunc(cFunc, self.CRRA)\n\n consumer_solution = ConsumerSolution(\n cFunc=cFunc,\n vFunc=vFunc,\n vPfunc=vPfunc,\n mNrmMin=solution.mNrmMin,\n hNrm=solution.hNrm,\n MPCmin=solution.MPCmin,\n MPCmax=solution.MPCmax,\n )\n\n ExIncNext = 1.0 # Perfect foresight income of 1\n\n # Add mNrmSS to the solution and return it\n consumer_solution.mNrmSS = _addSSmNrmNumba(\n self.Rfree,\n self.PermGroFac[i],\n solution.mNrm,\n solution.cNrm,\n solution.mNrmMin,\n ExIncNext,\n )\n\n self.solution[i] = consumer_solution\n" ]
[ [ "numpy.log", "matplotlib.pyplot.hist" ], [ "numpy.append", "numpy.array", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
meta-boy/mapleChan
[ "d06174aeea6f4b52c745d88d1254ebd6f7cc1db5", "d06174aeea6f4b52c745d88d1254ebd6f7cc1db5" ]
[ "tools/quality/prediction_distinctness.py", "cakechat/dialog_model/inference/reranking.py" ]
[ "from __future__ import print_function\nimport os\nimport sys\nimport argparse\n\nfrom six.moves import xrange\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nimport numpy as np\n\nfrom cakechat.utils.env import init_theano_env\n\ninit_theano_env()\n\nfrom cakechat.dialog_model.model import get_nn_model\nfrom cakechat.dialog_model.model_utils import get_model_full_path\nfrom cakechat.dialog_model.quality import calculate_response_ngram_distinctness\nfrom cakechat.utils.dataset_loader import load_datasets, load_questions_set\nfrom cakechat.utils.text_processing import get_index_to_token_path, load_index_to_item, get_index_to_condition_path\nfrom cakechat.utils.logger import get_tools_logger\nfrom cakechat.config import BASE_CORPUS_NAME, PREDICTION_MODES, PREDICTION_MODE_FOR_TESTS\n\n_logger = get_tools_logger(__file__)\n\n\ndef log_distinct_metrics(nn_model, x, condition_ids=None, samples_num=1, ngram_lengths=(1, 2, 3)):\n for ngram_length in ngram_lengths:\n scores = [\n calculate_response_ngram_distinctness(x, nn_model, ngram_len=ngram_length, condition_ids=condition_ids)\n for _ in xrange(samples_num)\n ]\n scores_mean = np.mean(scores)\n scores_std = np.std(scores)\n result = 'distinct {}-gram = {:.5f}'.format(ngram_length, scores_mean)\n if samples_num > 1:\n result += ' (std: {:.5f})'.format(scores_std)\n print(result)\n\n\ndef load_model(model_path=None, tokens_index_path=None, conditions_index_path=None):\n if model_path is None:\n model_path = get_model_full_path()\n if tokens_index_path is None:\n tokens_index_path = get_index_to_token_path(BASE_CORPUS_NAME)\n if conditions_index_path is None:\n conditions_index_path = get_index_to_condition_path(BASE_CORPUS_NAME)\n\n index_to_token = load_index_to_item(tokens_index_path)\n index_to_condition = load_index_to_item(conditions_index_path)\n nn_model, model_exists = get_nn_model(index_to_token, index_to_condition, nn_model_path=model_path)\n\n if not model_exists:\n raise ValueError('Couldn\\'t find model: \"{}\".'.format(model_path))\n\n return nn_model\n\n\ndef evaluate_distinctness(args):\n if args.sample_size > 1 and PREDICTION_MODE_FOR_TESTS == PREDICTION_MODES.beamsearch:\n _logger.waring('Using sample_size > 1 is meaningless with prediction_mode=\\'beamsearch\\' because there\\'s no '\n 'randomness in the prediction. Use sample_size=1 instead.')\n\n nn_model = load_model(args.model, args.tokens_index, args.conditions_index)\n\n if args.validation_only:\n validation = load_questions_set(nn_model.token_to_index)\n validation_set_name = 'context free questions'\n else:\n train, _, validation, train_subset, defined_condition_subset = load_datasets(\n nn_model.token_to_index, nn_model.condition_to_index)\n\n validation_set_name = 'validation set without conditions'\n\n _logger.info('Evaluating distinctness for train subset without conditions')\n log_distinct_metrics(nn_model, train_subset.x, samples_num=args.sample_size)\n\n _logger.info('Evaluating distinctness for train subset with conditions')\n log_distinct_metrics(nn_model, train_subset.x, train_subset.condition_ids, samples_num=args.sample_size)\n\n _logger.info('Evaluating distinctness for defined-conditions-subset without conditions')\n log_distinct_metrics(nn_model, defined_condition_subset.x, samples_num=args.sample_size)\n\n _logger.info('Evaluating distinctness for defined-conditions-subset with conditions')\n log_distinct_metrics(\n nn_model, defined_condition_subset.x, defined_condition_subset.condition_ids, samples_num=args.sample_size)\n\n _logger.info('Evaluating distinctness for {}'.format(validation_set_name))\n log_distinct_metrics(nn_model, validation.x, samples_num=args.sample_size)\n\n\nif __name__ == '__main__':\n argparser = argparse.ArgumentParser()\n\n argparser.add_argument(\n '-m',\n '--model',\n action='store',\n default=None,\n help='Path to the file with your model. '\n 'Be careful, model parameters are inferred from the config, not from the filename')\n\n argparser.add_argument(\n '-t',\n '--tokens_index',\n action='store',\n default=None,\n help='Path to the json file with index_to_token dictionary.')\n\n argparser.add_argument(\n '-c',\n '--conditions_index',\n action='store',\n default=None,\n help='Path to the json file with index_to_condition dictionary.')\n\n argparser.add_argument(\n '-s', '--sample_size', action='store', default=1, type=int, help='Number of samples to average over')\n\n argparser.add_argument(\n '-v',\n '--validation_only',\n action='store_true',\n help='Evaluate on the validation set only (useful if you are impatient)')\n\n args = argparser.parse_args()\n\n evaluate_distinctness(args)\n", "from abc import ABCMeta, abstractmethod\nfrom six.moves import zip_longest\n\nimport numpy as np\nfrom six.moves import xrange\n\nfrom cakechat.dialog_model.inference.service_tokens import ServiceTokensIDs\nfrom cakechat.dialog_model.inference.utils import get_sequence_score_by_thought_vector, get_sequence_score, \\\n get_thought_vectors\nfrom cakechat.dialog_model.model_utils import reverse_nn_input\nfrom cakechat.utils.dataset_loader import Dataset\nfrom cakechat.utils.logger import get_logger\nfrom cakechat.utils.profile import timer\n\n_logger = get_logger(__name__)\n\n\nclass AbstractCandidatesReranker(object):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def rerank_candidates(self, contexts, all_candidates, condition_ids):\n pass\n\n\nclass DummyReranker(AbstractCandidatesReranker):\n def rerank_candidates(self, contexts, all_candidates, condition_ids):\n return all_candidates\n\n\nclass MMIReranker(AbstractCandidatesReranker):\n \"\"\"\n Ranks candidates based on the MMI-score:\n score = (1 - \\lambda) log p(y|x) + \\lambda log p(x|y) - \\beta R_y,\n where\n - x is dialogue context;\n - y is a candidate response;\n - R_y is the number of repeated tokens used in a candidate response\n - \\lambda, \\beta - hyperparameters. \\beta = log(REPETITION_PENALIZE_COEFFICIENT)\n\n Score formula is based on (9) https://arxiv.org/pdf/1510.03055v3.pdf\n \"\"\"\n\n def __init__(self, nn_model, reverse_model, mmi_reverse_model_score_weight, repetition_penalization_coefficient):\n self._nn_model = nn_model\n if mmi_reverse_model_score_weight != 0.0 and reverse_model is None:\n raise ValueError('Reverse model has to be supplied to MMI-reranker. '\n 'If you don\\'t have one, set mmi_reverse_model_score_weight to 0.')\n self._reverse_model_score_weight = mmi_reverse_model_score_weight\n self._reverse_model = reverse_model\n self._service_tokens_ids = ServiceTokensIDs(nn_model.token_to_index)\n self._log_repetition_penalization_coefficient = np.log(repetition_penalization_coefficient)\n\n @timer\n def _compute_likelihood_of_output_given_input(self, thought_vector, candidates, condition_id):\n # Repeat to get same thought vector for each candidate\n thoughts_batch = np.repeat(thought_vector, candidates.shape[0], axis=0)\n return get_sequence_score_by_thought_vector(self._nn_model, thoughts_batch, candidates, condition_id)\n\n @timer\n def _compute_likelihood_of_input_given_output(self, context, candidates, condition_id):\n # Repeat to get same context for each candidate\n repeated_context = np.repeat(context, candidates.shape[0], axis=0)\n reversed_dataset = reverse_nn_input(\n Dataset(x=repeated_context, y=candidates, condition_ids=None), self._service_tokens_ids)\n return get_sequence_score(self._reverse_model, reversed_dataset.x, reversed_dataset.y, condition_id)\n\n @timer\n def _compute_num_repetitions(self, candidates):\n skip_tokens_ids = \\\n self._service_tokens_ids.special_tokens_ids + self._service_tokens_ids.non_penalizable_tokens_ids\n result = []\n for candidate in candidates:\n penalizable_tokens = candidate[~np.in1d(candidate, skip_tokens_ids)] # All tokens not in skip_tokens_ids\n num_repetitions = penalizable_tokens.size - np.unique(penalizable_tokens).size\n result.append(num_repetitions)\n return np.array(result)\n\n @timer\n def _compute_candidates_scores(self, context, candidates, condition_id):\n _logger.info('Reranking {} candidates...'.format(candidates.shape[0]))\n context = context[np.newaxis, :] # from (seq_len,) to (1 x seq_len)\n thought_vector = get_thought_vectors(self._nn_model, context)\n\n candidates_num_repetitions = self._compute_num_repetitions(candidates)\n\n if self._reverse_model_score_weight == 0.0:\n candidates_scores = self._compute_likelihood_of_output_given_input(thought_vector, candidates, condition_id)\n elif self._reverse_model_score_weight == 1.0: # Don't compute the likelihood in this case for performance\n candidates_scores = self._compute_likelihood_of_input_given_output(context, candidates, condition_id)\n else:\n candidates_likelihood = self._compute_likelihood_of_output_given_input(thought_vector, candidates,\n condition_id)\n candidates_reverse_likelihood = self._compute_likelihood_of_input_given_output(\n context, candidates, condition_id)\n candidates_scores = (1 - self._reverse_model_score_weight) * candidates_likelihood + \\\n self._reverse_model_score_weight * candidates_reverse_likelihood\n\n candidates_scores -= self._log_repetition_penalization_coefficient * candidates_num_repetitions\n return candidates_scores\n\n @timer\n def rerank_candidates(self, contexts, all_candidates, condition_ids):\n condition_ids = [] if condition_ids is None else condition_ids # For izip_lingest\n candidates_scores = [\n self._compute_candidates_scores(context, candidates, condition_id)\n for context, candidates, condition_id in zip_longest(contexts, all_candidates, condition_ids)\n ]\n scores_order = [np.argsort(-np.array(scores)) for scores in candidates_scores]\n batch_size = len(contexts)\n # reranked_candidates[i][j] = j-th best response for i-th question\n reranked_candidates = [\n [all_candidates[i][j] for j in scores_order[i]] for i in xrange(batch_size) # yapf: disable\n ]\n return reranked_candidates\n" ]
[ [ "numpy.std", "numpy.mean" ], [ "numpy.log", "numpy.unique", "numpy.in1d", "numpy.repeat", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
1170300521/MCN
[ "4591728a691d43d9030b2fa7152273402f888cc5" ]
[ "callbacks/learning_scheduler.py" ]
[ "from __future__ import absolute_import\r\nfrom __future__ import print_function\r\n\r\nimport os\r\n\r\nimport numpy as np\r\nfrom utils.tensorboard_logging import log_scalar\r\n\r\nfrom tensorflow.keras.callbacks import Callback\r\nimport tensorflow.keras.backend as K\r\n\r\n\r\nclass LearningRateScheduler(Callback):\r\n \"\"\"Learning rate scheduler.\r\n\r\n # Arguments\r\n schedule: a function that takes an epoch index as input\r\n (integer, indexed from 0) and current learning rate\r\n and returns a new learning rate as output (float).\r\n verbose: int. 0: quiet, 1: update messages.\r\n \"\"\"\r\n\r\n def __init__(self, schedule, init_epoch=0,verbose=0):\r\n super(LearningRateScheduler, self).__init__()\r\n self.schedule = schedule\r\n self.verbose = verbose\r\n self.step=0\r\n self.epoch=init_epoch\r\n# self.tensorboard=tensorboard\r\n self.lr=0.\r\n\r\n def on_epoch_begin(self, epoch, logs=None):\r\n self.epoch+=1\r\n self.lr = self.schedule(self.epoch)\r\n K.set_value(self.model.optimizer.lr, self.lr)\r\n if self.verbose > 0:\r\n print('\\nEpoch %05d: LearningRateScheduler setting learning '\r\n 'rate to %.4f' % (self.epoch, self.lr))\r\n\r\n" ]
[ [ "tensorflow.keras.backend.set_value" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] } ]
GuillaumeTh/trains
[ "65a4aa7aa90fc867993cf0d5e36c214e6c044270" ]
[ "trains/automation/optimization.py" ]
[ "import hashlib\nimport json\nfrom copy import copy\nfrom datetime import datetime\nfrom itertools import product\nfrom logging import getLogger\nfrom threading import Thread, Event\nfrom time import time\nfrom typing import Union, Any, Sequence, Optional, Mapping, Callable\n\nfrom .job import TrainsJob\nfrom .parameters import Parameter\nfrom ..task import Task\n\nlogger = getLogger('trains.automation.optimization')\n\n\ntry:\n import pandas as pd\n Task.add_requirements('pandas')\nexcept ImportError:\n pd = None\n logger.warning('Pandas is not installed, summary table reporting will be skipped.')\n\n\nclass Objective(object):\n \"\"\"\n Optimization ``Objective`` class to maximize / minimize over all experiments. This class will sample a specific\n scalar from all experiments, and maximize / minimize over single scalar (i.e., title and series combination).\n\n ``SearchStrategy`` and ``HyperParameterOptimizer`` use ``Objective`` in the strategy search algorithm.\n \"\"\"\n\n def __init__(self, title, series, order='max', extremum=False):\n # type: (str, str, str, bool) -> ()\n \"\"\"\n Construct ``Objective`` object that will return the scalar value for a specific task ID.\n\n :param str title: The scalar graph title to sample from.\n :param str series: The scalar series title to sample from.\n :param str order: The setting for maximizing or minimizing the objective scalar value.\n\n The values are:\n\n - ``max``\n - ``min``\n\n :param bool extremum: Return the global minimum / maximum reported metric value?\n\n The values are:\n\n - ``True`` - Return the global minimum / maximum reported metric value.\n - ``False`` - Return the last value reported for a specific Task. (Default)\n\n \"\"\"\n self.title = title\n self.series = series\n assert order in ('min', 'max',)\n # normalize value so we always look for the highest objective value\n self.sign = -1 if (isinstance(order, str) and order.lower().strip() == 'min') else +1\n self._metric = None\n self.extremum = extremum\n\n def get_objective(self, task_id):\n # type: (Union[str, Task, TrainsJob]) -> Optional[float]\n \"\"\"\n Return a specific task scalar value based on the objective settings (title/series).\n\n :param str task_id: The Task id to retrieve scalar from (or ``TrainsJob`` object).\n\n :return: The scalar value.\n \"\"\"\n # create self._metric\n self._get_last_metrics_encode_field()\n\n if isinstance(task_id, Task):\n task_id = task_id.id\n elif isinstance(task_id, TrainsJob):\n task_id = task_id.task_id()\n\n # noinspection PyBroadException, Py\n try:\n # noinspection PyProtectedMember\n task = Task._query_tasks(\n task_ids=[task_id], only_fields=['last_metrics.{}.{}'.format(self._metric[0], self._metric[1])])[0]\n except Exception:\n return None\n\n metrics = task.last_metrics\n # noinspection PyBroadException\n try:\n values = metrics[self._metric[0]][self._metric[1]]\n if not self.extremum:\n return values['value']\n\n return values['min_value'] if self.sign < 0 else values['max_value']\n except Exception:\n return None\n\n def get_current_raw_objective(self, task):\n # type: (Union[TrainsJob, Task]) -> (int, float)\n \"\"\"\n Return the current raw value (without sign normalization) of the objective.\n\n :param str task: The Task or Job to retrieve scalar from (or ``TrainsJob`` object).\n\n :return: Tuple(iteration, value) if, and only if, the metric exists. None if the metric does not exist.\n\n \"\"\"\n\n if not isinstance(task, Task):\n if hasattr(task, 'task'):\n task = task.task\n if not isinstance(task, Task):\n task = Task.get_task(task_id=str(task))\n if not task:\n raise ValueError(\"Task object could not be found\")\n\n # todo: replace with more efficient code\n scalars = task.get_reported_scalars()\n\n # noinspection PyBroadException\n try:\n return scalars[self.title][self.series]['x'][-1], scalars[self.title][self.series]['y'][-1]\n except Exception:\n return None\n\n def get_objective_sign(self):\n # type: () -> float\n \"\"\"\n Return the sign of the objective.\n\n - ``+1`` - If maximizing\n - ``-1`` - If minimizing\n\n :return: Objective function sign.\n \"\"\"\n return self.sign\n\n def get_objective_metric(self):\n # type: () -> (str, str)\n \"\"\"\n Return the metric title, series pair of the objective.\n\n :return: (title, series)\n \"\"\"\n return self.title, self.series\n\n def get_normalized_objective(self, task_id):\n # type: (Union[str, Task, TrainsJob]) -> Optional[float]\n \"\"\"\n Return a normalized task scalar value based on the objective settings (title/series).\n I.e. objective is always to maximize the returned value\n\n :param str task_id: The Task id to retrieve scalar from.\n\n :return: Normalized scalar value.\n \"\"\"\n objective = self.get_objective(task_id=task_id)\n if objective is None:\n return None\n # normalize value so we always look for the highest objective value\n return self.sign * objective\n\n def _get_last_metrics_encode_field(self):\n # type: () -> str\n \"\"\"\n Return encoded representation of the title/series metric.\n\n :return: The objective title/series.\n \"\"\"\n if not self._metric:\n title = hashlib.md5(str(self.title).encode('utf-8')).hexdigest()\n series = hashlib.md5(str(self.series).encode('utf-8')).hexdigest()\n self._metric = title, series\n return '{}last_metrics.{}.{}.{}'.format(\n '-' if self.sign > 0 else '', self._metric[0], self._metric[1],\n ('min_value' if self.sign < 0 else 'max_value') if self.extremum else 'value')\n\n\nclass Budget(object):\n class Field(object):\n def __init__(self, limit=None):\n # type: (Optional[float]) -> ()\n self.limit = limit\n self.current = {}\n\n def update(self, uid, value):\n # type: (Union[str, int], float) -> ()\n if value is not None:\n try:\n self.current[uid] = float(value)\n except (TypeError, ValueError):\n pass\n\n @property\n def used(self):\n # type: () -> (Optional[float])\n if self.limit is None or not self.current:\n return None\n return sum(self.current.values())/float(self.limit)\n\n def __init__(self, jobs_limit, iterations_limit, compute_time_limit):\n # type: (Optional[int], Optional[int], Optional[float]) -> ()\n self.jobs = self.Field(jobs_limit)\n self.iterations = self.Field(iterations_limit)\n self.compute_time = self.Field(compute_time_limit)\n\n def to_dict(self):\n # type: () -> (Mapping[str, Mapping[str, float]])\n\n # returned dict is Mapping[Union['jobs', 'iterations', 'compute_time'], Mapping[Union['limit', 'used'], float]]\n current_budget = {}\n jobs = self.jobs.used\n if jobs:\n current_budget['jobs'] = {'limit': self.jobs.limit, 'used': jobs}\n iterations = self.iterations.used\n if iterations:\n current_budget['iterations'] = {'limit': self.iterations.limit, 'used': iterations}\n compute_time = self.compute_time.used\n if compute_time:\n current_budget['compute_time'] = {'limit': self.compute_time.limit, 'used': compute_time}\n return current_budget\n\n\nclass SearchStrategy(object):\n \"\"\"\n The base search strategy class. Inherit this class to implement your custom strategy.\n \"\"\"\n _tag = 'optimization'\n _job_class = TrainsJob # type: TrainsJob\n\n def __init__(\n self,\n base_task_id, # type: str\n hyper_parameters, # type: Sequence[Parameter]\n objective_metric, # type: Objective\n execution_queue, # type: str\n num_concurrent_workers, # type: int\n pool_period_min=2., # type: float\n time_limit_per_job=None, # type: Optional[float]\n max_iteration_per_job=None, # type: Optional[int]\n total_max_jobs=None, # type: Optional[int]\n **_ # type: Any\n ):\n # type: (...) -> ()\n \"\"\"\n Initialize a search strategy optimizer.\n\n :param str base_task_id: The Task ID (str)\n :param list hyper_parameters: The list of parameter objects to optimize over.\n :param Objective objective_metric: The Objective metric to maximize / minimize.\n :param str execution_queue: The execution queue to use for launching Tasks (experiments).\n :param int num_concurrent_workers: The maximum number of concurrent running machines.\n :param float pool_period_min: The time between two consecutive pools (minutes).\n :param float time_limit_per_job: The maximum execution time per single job in minutes. When time limit is\n exceeded, the job is aborted. (Optional)\n :param int max_iteration_per_job: The maximum iterations (of the Objective metric) per single job. When maximum\n iterations is exceeded, the job is aborted. (Optional)\n :param int total_max_jobs: The total maximum jobs for the optimization process. The default value is ``None``,\n for unlimited.\n \"\"\"\n super(SearchStrategy, self).__init__()\n self._base_task_id = base_task_id\n self._hyper_parameters = hyper_parameters\n self._objective_metric = objective_metric\n self._execution_queue = execution_queue\n self._num_concurrent_workers = num_concurrent_workers\n self.pool_period_minutes = pool_period_min\n self.time_limit_per_job = time_limit_per_job\n self.max_iteration_per_job = max_iteration_per_job\n self.total_max_jobs = total_max_jobs\n self._stop_event = Event()\n self._current_jobs = []\n self._pending_jobs = []\n self._num_jobs = 0\n self._job_parent_id = None\n self._created_jobs_ids = {}\n self._naming_function = None\n self._job_project = {}\n self.budget = Budget(\n jobs_limit=self.total_max_jobs,\n compute_time_limit=self.total_max_jobs * self.time_limit_per_job if\n self.time_limit_per_job and self.total_max_jobs else None,\n iterations_limit=self.total_max_jobs * self.max_iteration_per_job if\n self.max_iteration_per_job and self.total_max_jobs else None\n )\n self._validate_base_task()\n self._optimizer_task = None\n\n def start(self):\n # type: () -> ()\n \"\"\"\n Start the Optimizer controller function loop(). If the calling process is stopped, the controller will stop\n as well.\n\n .. important::\n This function returns only after the optimization is completed or :meth:`stop` was called.\n\n \"\"\"\n counter = 0\n while True:\n logger.debug('optimization loop #{}'.format(counter))\n if not self.process_step():\n break\n if self._stop_event.wait(timeout=self.pool_period_minutes * 60.):\n break\n counter += 1\n\n def stop(self):\n # type: () -> ()\n \"\"\"\n Stop the current running optimization loop. Called from a different thread than the :meth:`start`.\n \"\"\"\n self._stop_event.set()\n\n def process_step(self):\n # type: () -> bool\n \"\"\"\n Abstract helper function. Implementation is not required. Default use in start default implementation\n Main optimization loop, called from the daemon thread created by :meth:`start`.\n\n - Call monitor job on every ``TrainsJob`` in jobs:\n\n - Check the performance or elapsed time, and then decide whether to kill the jobs.\n\n - Call create_job:\n\n - Check if spare job slots exist, and if they do call create a new job based on previous tested experiments.\n\n :return: True, if continue the optimization. False, if immediately stop.\n\n \"\"\"\n updated_jobs = []\n for job in self._current_jobs:\n if self.monitor_job(job):\n updated_jobs.append(job)\n\n self._current_jobs = updated_jobs\n\n pending_jobs = []\n for job in self._pending_jobs:\n if job.is_pending():\n pending_jobs.append(job)\n else:\n self.budget.jobs.update(job.task_id(), 1)\n\n self._pending_jobs = pending_jobs\n\n free_workers = self._num_concurrent_workers - len(self._current_jobs)\n\n # do not create more jobs if we hit the limit\n if self.total_max_jobs and self._num_jobs >= self.total_max_jobs:\n return bool(self._current_jobs)\n\n # see how many free slots we have and create job\n for i in range(max(0, free_workers)):\n new_job = self.create_job()\n if not new_job:\n break\n self._num_jobs += 1\n new_job.launch(self._execution_queue)\n self._current_jobs.append(new_job)\n self._pending_jobs.append(new_job)\n\n return bool(self._current_jobs)\n\n def create_job(self):\n # type: () -> Optional[TrainsJob]\n \"\"\"\n Abstract helper function. Implementation is not required. Default use in process_step default implementation\n Create a new job if needed. return the newly created job. If no job needs to be created, return ``None``.\n\n :return: A Newly created TrainsJob object, or None if no TrainsJob created.\n \"\"\"\n return None\n\n def monitor_job(self, job):\n # type: (TrainsJob) -> bool\n \"\"\"\n Helper function, Implementation is not required. Default use in process_step default implementation.\n Check if the job needs to be aborted or already completed.\n\n If returns ``False``, the job was aborted / completed, and should be taken off the current job list\n\n If there is a budget limitation, this call should update ``self.budget.compute_time.update`` / ``self.budget.iterations.update``\n\n :param TrainsJob job: A ``TrainsJob`` object to monitor.\n\n :return: False, if the job is no longer relevant.\n \"\"\"\n abort_job = False\n\n if self.time_limit_per_job:\n elapsed = job.elapsed() / 60.\n if elapsed > 0:\n self.budget.compute_time.update(job.task_id(), elapsed)\n if elapsed > self.time_limit_per_job:\n abort_job = True\n\n if self.max_iteration_per_job:\n iterations = self._get_job_iterations(job)\n if iterations > 0:\n self.budget.iterations.update(job.task_id(), iterations)\n if iterations > self.max_iteration_per_job:\n abort_job = True\n\n if abort_job:\n job.abort()\n return False\n\n return not job.is_stopped()\n\n def get_running_jobs(self):\n # type: () -> Sequence[TrainsJob]\n \"\"\"\n Return the current running TrainsJobs.\n\n :return: List of TrainsJob objects.\n \"\"\"\n return self._current_jobs\n\n def get_created_jobs_ids(self):\n # type: () -> Mapping[str, dict]\n \"\"\"\n Return a Task IDs dict created by this optimizer until now, including completed and running jobs.\n The values of the returned dict are the parameters used in the specific job\n\n :return: dict of task IDs (str) as keys, and their parameters dict as values.\n \"\"\"\n return self._created_jobs_ids\n\n def get_top_experiments(self, top_k):\n # type: (int) -> Sequence[Task]\n \"\"\"\n Return a list of Tasks of the top performing experiments, based on the controller ``Objective`` object.\n\n :param int top_k: The number of Tasks (experiments) to return.\n\n :return: A list of Task objects, ordered by performance, where index 0 is the best performing Task.\n \"\"\"\n # noinspection PyProtectedMember\n top_tasks = self._get_child_tasks(\n parent_task_id=self._job_parent_id or self._base_task_id,\n order_by=self._objective_metric._get_last_metrics_encode_field(),\n additional_filters={'page_size': int(top_k), 'page': 0})\n return top_tasks\n\n def get_objective_metric(self):\n # type: () -> (str, str)\n \"\"\"\n Return the metric title, series pair of the objective.\n\n :return: (title, series)\n \"\"\"\n return self._objective_metric.get_objective_metric()\n\n def helper_create_job(\n self,\n base_task_id, # type: str\n parameter_override=None, # type: Optional[Mapping[str, str]]\n task_overrides=None, # type: Optional[Mapping[str, str]]\n tags=None, # type: Optional[Sequence[str]]\n parent=None, # type: Optional[str]\n **kwargs # type: Any\n ):\n # type: (...) -> TrainsJob\n \"\"\"\n Create a Job using the specified arguments, ``TrainsJob`` for details.\n\n :return: A newly created Job instance.\n \"\"\"\n if parameter_override:\n param_str = ['{}={}'.format(k, parameter_override[k]) for k in sorted(parameter_override.keys())]\n if self._naming_function:\n name = self._naming_function(self._base_task_name, parameter_override)\n elif self._naming_function is False:\n name = None\n else:\n name = '{}: {}'.format(self._base_task_name, ' '.join(param_str))\n comment = '\\n'.join(param_str)\n else:\n name = None\n comment = None\n tags = (tags or []) + [self._tag, 'opt' + (': {}'.format(self._job_parent_id) if self._job_parent_id else '')]\n new_job = self._job_class(\n base_task_id=base_task_id, parameter_override=parameter_override,\n task_overrides=task_overrides, tags=tags, parent=parent or self._job_parent_id,\n name=name, comment=comment, project=self._get_task_project(parent or self._job_parent_id), **kwargs)\n self._created_jobs_ids[new_job.task_id()] = parameter_override\n logger.info('Creating new Task: {}'.format(parameter_override))\n return new_job\n\n def set_job_class(self, job_class):\n # type: (TrainsJob) -> ()\n \"\"\"\n Set the class to use for the :meth:`helper_create_job` function.\n\n :param TrainsJob job_class: The Job Class type.\n \"\"\"\n self._job_class = job_class\n\n def set_job_default_parent(self, job_parent_task_id):\n # type: (str) -> ()\n \"\"\"\n Set the default parent for all Jobs created by the :meth:`helper_create_job` method.\n\n :param str job_parent_task_id: The parent Task ID.\n \"\"\"\n self._job_parent_id = job_parent_task_id\n\n def set_job_naming_scheme(self, naming_function):\n # type: (Optional[Callable[[str, dict], str]]) -> ()\n \"\"\"\n Set the function used to name a newly created job.\n\n :param callable naming_function:\n\n .. code-block:: py\n\n naming_functor(base_task_name, argument_dict) -> str\n\n \"\"\"\n self._naming_function = naming_function\n\n def set_optimizer_task(self, task):\n # type: (Task) -> ()\n \"\"\"\n Set the optimizer task object to be used to store/generate reports on the optimization process.\n Usually this is the current task of this process.\n\n :param Task task: The optimizer's current Task.\n \"\"\"\n self._optimizer_task = task\n\n def _validate_base_task(self):\n # type: () -> ()\n \"\"\"\n Check the base task exists and contains the requested Objective metric and hyper parameters.\n \"\"\"\n # check if the task exists\n try:\n task = Task.get_task(task_id=self._base_task_id)\n self._base_task_name = task.name\n except ValueError:\n raise ValueError(\"Could not find base task id {}\".format(self._base_task_id))\n # check if the hyper-parameters exist:\n task_parameters = task.get_parameters_as_dict()\n missing_params = [h.name for h in self._hyper_parameters if h.name not in task_parameters]\n if missing_params:\n logger.warning('Could not find requested hyper-parameters {} on base task {}'.format(\n missing_params, self._base_task_id))\n # check if the objective metric exists (i.e. no typos etc)\n if self._objective_metric.get_objective(self._base_task_id) is None:\n logger.warning('Could not find requested metric {} report on base task {}'.format(\n self._objective_metric.get_objective_metric(), self._base_task_id))\n\n def _get_task_project(self, parent_task_id):\n # type: (str) -> (Optional[str])\n if not parent_task_id:\n return\n if parent_task_id not in self._job_project:\n task = Task.get_task(task_id=parent_task_id)\n self._job_project[parent_task_id] = task.project\n\n return self._job_project.get(parent_task_id)\n\n def _get_job_iterations(self, job):\n # type: (Union[TrainsJob, Task]) -> int\n iteration_value = self._objective_metric.get_current_raw_objective(job)\n return iteration_value[0] if iteration_value else -1\n\n @classmethod\n def _get_child_tasks(\n cls,\n parent_task_id, # type: str\n status=None, # type: Optional[Task.TaskStatusEnum]\n order_by=None, # type: Optional[str]\n additional_filters=None # type: Optional[dict]\n ):\n # type: (...) -> (Sequence[Task])\n \"\"\"\n Helper function. Return a list of tasks tagged automl, with specific ``status``, ordered by ``sort_field``.\n\n :param str parent_task_id: The base Task ID (parent).\n :param status: The current status of requested tasks (for example, ``in_progress`` and ``completed``).\n :param str order_by: The field name to sort results.\n\n Examples:\n\n .. code-block:: py\n\n \"-last_metrics.title.series.min\"\n \"last_metrics.title.series.max\"\n \"last_metrics.title.series.last\"\n \"execution.parameters.name\"\n \"updated\"\n\n :param dict additional_filters: The additional task filters.\n :return: A list of Task objects\n \"\"\"\n task_filter = {'parent': parent_task_id,\n # 'tags': [cls._tag],\n 'system_tags': ['-archived']}\n task_filter.update(additional_filters or {})\n\n if status:\n task_filter['status'] = status\n\n if order_by and (order_by.startswith('last_metrics') or order_by.startswith('-last_metrics')):\n parts = order_by.split('.')\n if parts[-1] in ('min', 'max', 'last'):\n title = hashlib.md5(str(parts[1]).encode('utf-8')).hexdigest()\n series = hashlib.md5(str(parts[2]).encode('utf-8')).hexdigest()\n minmax = 'min_value' if 'min' in parts[3] else ('max_value' if 'max' in parts[3] else 'value')\n order_by = '{}last_metrics.'.join(\n ('-' if order_by and order_by[0] == '-' else '', title, series, minmax))\n\n if order_by:\n task_filter['order_by'] = [order_by]\n\n return Task.get_tasks(task_filter=task_filter)\n\n\nclass GridSearch(SearchStrategy):\n \"\"\"\n Grid search strategy controller. Full grid sampling of every hyper-parameter combination.\n \"\"\"\n\n def __init__(\n self,\n base_task_id, # type: str\n hyper_parameters, # type: Sequence[Parameter]\n objective_metric, # type: Objective\n execution_queue, # type: str\n num_concurrent_workers, # type: int\n pool_period_min=2., # type: float\n time_limit_per_job=None, # type: Optional[float]\n max_iteration_per_job=None, # type: Optional[int]\n total_max_jobs=None, # type: Optional[int]\n **_ # type: Any\n ):\n # type: (...) -> ()\n \"\"\"\n Initialize a grid search optimizer\n\n :param str base_task_id: The Task ID.\n :param list hyper_parameters: The list of parameter objects to optimize over.\n :param Objective objective_metric: The Objective metric to maximize / minimize.\n :param str execution_queue: The execution queue to use for launching Tasks (experiments).\n :param int num_concurrent_workers: The maximum number of concurrent running machines.\n :param float pool_period_min: The time between two consecutive pools (minutes).\n :param float time_limit_per_job: The maximum execution time per single job in minutes. When the time limit is\n exceeded job is aborted. (Optional)\n :param int max_iteration_per_job: The maximum iterations (of the Objective metric)\n per single job, When exceeded, the job is aborted.\n :param int total_max_jobs: The total maximum jobs for the optimization process. The default is ``None``, for\n unlimited.\n \"\"\"\n super(GridSearch, self).__init__(\n base_task_id=base_task_id, hyper_parameters=hyper_parameters, objective_metric=objective_metric,\n execution_queue=execution_queue, num_concurrent_workers=num_concurrent_workers,\n pool_period_min=pool_period_min, time_limit_per_job=time_limit_per_job,\n max_iteration_per_job=max_iteration_per_job, total_max_jobs=total_max_jobs, **_)\n self._param_iterator = None\n\n def create_job(self):\n # type: () -> Optional[TrainsJob]\n \"\"\"\n Create a new job if needed. Return the newly created job. If no job needs to be created, return ``None``.\n\n :return: A newly created TrainsJob object, or None if no TrainsJob is created.\n \"\"\"\n try:\n parameters = self._next_configuration()\n except StopIteration:\n return None\n\n return self.helper_create_job(base_task_id=self._base_task_id, parameter_override=parameters)\n\n def _next_configuration(self):\n # type: () -> Mapping[str, str]\n def param_iterator_fn():\n hyper_params_values = [p.to_list() for p in self._hyper_parameters]\n for state in product(*hyper_params_values):\n yield dict(kv for d in state for kv in d.items())\n\n if not self._param_iterator:\n self._param_iterator = param_iterator_fn()\n return next(self._param_iterator)\n\n\nclass RandomSearch(SearchStrategy):\n \"\"\"\n Random search strategy controller. Random uniform sampling of hyper-parameters.\n \"\"\"\n\n # Number of already chosen random samples before assuming we covered the entire hyper-parameter space\n _hp_space_cover_samples = 42\n\n def __init__(\n self,\n base_task_id, # type: str\n hyper_parameters, # type: Sequence[Parameter]\n objective_metric, # type: Objective\n execution_queue, # type: str\n num_concurrent_workers, # type: int\n pool_period_min=2., # type: float\n time_limit_per_job=None, # type: Optional[float]\n max_iteration_per_job=None, # type: Optional[int]\n total_max_jobs=None, # type: Optional[int]\n **_ # type: Any\n ):\n # type: (...) -> ()\n \"\"\"\n Initialize a random search optimizer.\n\n :param str base_task_id: The Task ID.\n :param list hyper_parameters: The list of Parameter objects to optimize over.\n :param Objective objective_metric: The Objective metric to maximize / minimize.\n :param str execution_queue: The execution queue to use for launching Tasks (experiments).\n :param int num_concurrent_workers: The maximum umber of concurrent running machines.\n :param float pool_period_min: The time between two consecutive pools (minutes).\n :param float time_limit_per_job: The maximum execution time per single job in minutes,\n when time limit is exceeded job is aborted. (Optional)\n :param int max_iteration_per_job: The maximum iterations (of the Objective metric)\n per single job. When exceeded, the job is aborted.\n :param int total_max_jobs: The total maximum jobs for the optimization process. The default is ``None``, for\n unlimited.\n \"\"\"\n super(RandomSearch, self).__init__(\n base_task_id=base_task_id, hyper_parameters=hyper_parameters, objective_metric=objective_metric,\n execution_queue=execution_queue, num_concurrent_workers=num_concurrent_workers,\n pool_period_min=pool_period_min, time_limit_per_job=time_limit_per_job,\n max_iteration_per_job=max_iteration_per_job, total_max_jobs=total_max_jobs, **_)\n self._hyper_parameters_collection = set()\n\n def create_job(self):\n # type: () -> Optional[TrainsJob]\n \"\"\"\n Create a new job if needed. Return the newly created job. If no job needs to be created, return ``None``.\n\n :return: A newly created TrainsJob object, or None if no TrainsJob created\n \"\"\"\n parameters = None\n\n # maximum tries to ge a random set that is not already in the collection\n for i in range(self._hp_space_cover_samples):\n parameters = {}\n for p in self._hyper_parameters:\n parameters.update(p.get_value())\n # hash the parameters dictionary\n param_hash = hash(json.dumps(parameters, sort_keys=True))\n # if this is a new set of parameters, use it.\n if param_hash not in self._hyper_parameters_collection:\n self._hyper_parameters_collection.add(param_hash)\n break\n # try again\n parameters = None\n\n # if we failed to find a random set of parameters, assume we selected all of them\n if not parameters:\n return None\n\n return self.helper_create_job(base_task_id=self._base_task_id, parameter_override=parameters)\n\n\nclass HyperParameterOptimizer(object):\n \"\"\"\n Hyper-parameter search controller. Clones the base experiment, changes arguments and tries to maximize/minimize\n the defined objective.\n \"\"\"\n _tag = 'optimization'\n\n def __init__(\n self,\n base_task_id, # type: str\n hyper_parameters, # type: Sequence[Parameter]\n objective_metric_title, # type: str\n objective_metric_series, # type: str\n objective_metric_sign='min', # type: str\n optimizer_class=RandomSearch, # type: type(SearchStrategy)\n max_number_of_concurrent_tasks=10, # type: int\n execution_queue='default', # type: str\n optimization_time_limit=None, # type: Optional[float]\n auto_connect_task=True, # type: bool\n always_create_task=False, # type: bool\n **optimizer_kwargs # type: Any\n ):\n # type: (...) -> ()\n \"\"\"\n Create a new hyper-parameter controller. The newly created object will launch and monitor the new experiments.\n\n :param str base_task_id: The Task ID to be used as template experiment to optimize.\n :param list hyper_parameters: The list of Parameter objects to optimize over.\n :param str objective_metric_title: The Objective metric title to maximize / minimize (for example,\n ``validation``).\n :param str objective_metric_series: The Objective metric series to maximize / minimize (for example, ``loss``).\n :param str objective_metric_sign: The objective to maximize / minimize.\n\n The values are:\n\n - ``min`` - Minimize the last reported value for the specified title/series scalar.\n - ``max`` - Maximize the last reported value for the specified title/series scalar.\n - ``min_global`` - Minimize the min value of *all* reported values for the specific title/series scalar.\n - ``max_global`` - Maximize the max value of *all* reported values for the specific title/series scalar.\n\n :param class.SearchStrategy optimizer_class: The SearchStrategy optimizer to use for the hyper-parameter search\n :param int max_number_of_concurrent_tasks: The maximum number of concurrent Tasks (experiments) running at the\n same time.\n :param str execution_queue: The execution queue to use for launching Tasks (experiments).\n :param float optimization_time_limit: The maximum time (minutes) for the entire optimization process. The\n default is ``None``, indicating no time limit.\n :param bool auto_connect_task: Store optimization arguments and configuration in the Task?\n\n The values are:\n\n - ``True`` - The optimization argument and configuration will be stored in the Task. All arguments will\n be under the hyper-parameter section as ``opt/<arg>``, and the hyper_parameters will stored in the\n Task ``connect_configuration`` (see artifacts/hyper-parameter).\n\n - ``False`` - Do not store with Task.\n\n :param bool always_create_task: Always create a new Task?\n\n The values are:\n\n - ``True`` - No current Task initialized. Create a new task named ``optimization`` in the ``base_task_id``\n project.\n\n - ``False`` - Use the :py:meth:`task.Task.current_task` (if exists) to report statistics.\n\n :param ** optimizer_kwargs: Arguments passed directly to the optimizer constructor.\n\n Example:\n\n .. code-block:: py\n\n :linenos:\n :caption: Example\n\n from trains import Task\n from trains.automation import UniformParameterRange, DiscreteParameterRange\n from trains.automation import GridSearch, RandomSearch, HyperParameterOptimizer\n\n task = Task.init('examples', 'HyperParameterOptimizer example')\n an_optimizer = HyperParameterOptimizer(\n base_task_id='fa30fa45d95d4927b87c323b5b04dc44',\n hyper_parameters=[\n UniformParameterRange('lr', min_value=0.01, max_value=0.3, step_size=0.05),\n DiscreteParameterRange('network', values=['ResNet18', 'ResNet50', 'ResNet101']),\n ],\n objective_metric_title='title',\n objective_metric_series='series',\n objective_metric_sign='min',\n max_number_of_concurrent_tasks=5,\n optimizer_class=RandomSearch,\n execution_queue='workers', time_limit_per_job=120, pool_period_min=0.2)\n\n # This will automatically create and print the optimizer new task id\n # for later use. if a Task was already created, it will use it.\n an_optimizer.set_time_limit(in_minutes=10.)\n an_optimizer.start()\n # we can create a pooling loop if we like\n while not an_optimizer.reached_time_limit():\n top_exp = an_optimizer.get_top_experiments(top_k=3)\n print(top_exp)\n # wait until optimization completed or timed-out\n an_optimizer.wait()\n # make sure we stop all jobs\n an_optimizer.stop()\n \"\"\"\n\n # create a new Task, if we do not have one already\n self._task = Task.current_task()\n if not self._task and always_create_task:\n base_task = Task.get_task(task_id=self.base_task_id)\n self._task = Task.init(\n project_name=base_task.get_project_name(),\n task_name='Optimizing: {}'.format(base_task.name),\n ) # TODO: add task_type=controller\n\n opts = dict(\n base_task_id=base_task_id,\n objective_metric_title=objective_metric_title,\n objective_metric_series=objective_metric_series,\n objective_metric_sign=objective_metric_sign,\n max_number_of_concurrent_tasks=max_number_of_concurrent_tasks,\n execution_queue=execution_queue,\n optimization_time_limit=optimization_time_limit,\n optimizer_kwargs=optimizer_kwargs)\n # make sure all the created tasks are our children, as we are creating them\n if self._task:\n self._task.add_tags([self._tag])\n if auto_connect_task:\n optimizer_class, hyper_parameters, opts = self._connect_args(\n optimizer_class=optimizer_class, hyper_param_configuration=hyper_parameters, **opts)\n\n self.base_task_id = opts['base_task_id']\n self.hyper_parameters = hyper_parameters\n self.max_number_of_concurrent_tasks = opts['max_number_of_concurrent_tasks']\n self.execution_queue = opts['execution_queue']\n self.objective_metric = Objective(\n title=opts['objective_metric_title'], series=opts['objective_metric_series'],\n order='min' if opts['objective_metric_sign'] in ('min', 'min_global') else 'max',\n extremum=opts['objective_metric_sign'].endswith('_global'))\n # if optimizer_class is an instance, use it as is.\n if type(optimizer_class) != type:\n self.optimizer = optimizer_class\n else:\n self.optimizer = optimizer_class(\n base_task_id=opts['base_task_id'], hyper_parameters=hyper_parameters,\n objective_metric=self.objective_metric, execution_queue=opts['execution_queue'],\n num_concurrent_workers=opts['max_number_of_concurrent_tasks'], **opts.get('optimizer_kwargs', {}))\n self.optimizer.set_optimizer_task(self._task)\n self.optimization_timeout = None\n self.optimization_start_time = None\n self._thread = None\n self._stop_event = None\n self._report_period_min = 5.\n self._thread_reporter = None\n self._experiment_completed_cb = None\n if self._task:\n self.optimizer.set_job_default_parent(self._task.id)\n self.set_time_limit(in_minutes=opts['optimization_time_limit'])\n\n def get_num_active_experiments(self):\n # type: () -> int\n \"\"\"\n Return the number of current active experiments.\n\n :return: The number of active experiments.\n \"\"\"\n if not self.optimizer:\n return 0\n return len(self.optimizer.get_running_jobs())\n\n def get_active_experiments(self):\n # type: () -> Sequence[Task]\n \"\"\"\n Return a list of Tasks of the current active experiments.\n\n :return: A list of Task objects, representing the current active experiments.\n \"\"\"\n if not self.optimizer:\n return []\n return [j.task for j in self.optimizer.get_running_jobs()]\n\n def start(self, job_complete_callback=None):\n # type: (Optional[Callable[[str, float, int, dict, str], None]]) -> bool\n \"\"\"\n Start the HyperParameterOptimizer controller. If the calling process is stopped, then the controller stops\n as well.\n\n :param Callable job_complete_callback: Callback function, called when a job is completed.\n\n .. code-block:: py\n\n def job_complete_callback(\n job_id, # type: str\n objective_value, # type: float\n objective_iteration, # type: int\n job_parameters, # type: dict\n top_performance_job_id # type: str\n ):\n pass\n\n :return: True, if the controller started. False, if the controller did not start.\n\n \"\"\"\n if not self.optimizer:\n return False\n\n if self._thread:\n return True\n\n self.optimization_start_time = time()\n self._experiment_completed_cb = job_complete_callback\n self._stop_event = Event()\n self._thread = Thread(target=self._daemon)\n self._thread.daemon = True\n self._thread.start()\n self._thread_reporter = Thread(target=self._report_daemon)\n self._thread_reporter.daemon = True\n self._thread_reporter.start()\n return True\n\n def stop(self, timeout=None):\n # type: (Optional[float]) -> ()\n \"\"\"\n Stop the HyperParameterOptimizer controller and the optimization thread.\n\n :param float timeout: Wait timeout for the optimization thread to exit (minutes).\n The default is ``None``, indicating do not wait terminate immediately.\n \"\"\"\n if not self._thread or not self._stop_event or not self.optimizer:\n return\n\n _thread = self._thread\n self._stop_event.set()\n self.optimizer.stop()\n\n # wait for optimizer thread\n if timeout is not None:\n _thread.join(timeout=timeout * 60.)\n\n # stop all running tasks:\n for j in self.optimizer.get_running_jobs():\n j.abort()\n\n # clear thread\n self._thread = None\n # wait for reporter to flush\n self._thread_reporter.join()\n\n def is_active(self):\n # type: () -> bool\n \"\"\"\n Is the optimization procedure active (still running)?\n\n The values are:\n\n - ``True`` - The optimization procedure is active (still running).\n - ``False`` - The optimization procedure is not active (not still running).\n\n .. note::\n If the daemon thread has not yet started, ``is_active`` returns ``True``.\n\n :return: A boolean indicating whether the optimization procedure is active (still running) or stopped.\n \"\"\"\n return self._stop_event is None or self._thread is not None\n\n def is_running(self):\n # type: () -> bool\n \"\"\"\n Is the optimization controller is running?\n\n The values are:\n\n - ``True`` - The optimization procedure is running.\n - ``False`` - The optimization procedure is running.\n\n :return: A boolean indicating whether the optimization procedure is active (still running) or stopped.\n \"\"\"\n return self._thread is not None\n\n def wait(self, timeout=None):\n # type: (Optional[float]) -> bool\n \"\"\"\n Wait for the optimizer to finish.\n\n .. note::\n This method does not stop the optimizer. Call :meth:`stop` to terminate the optimizer.\n\n :param float timeout: The timeout to wait for the optimization to complete (minutes).\n If ``None``, then wait until we reached the timeout, or optimization completed.\n\n :return: True, if the optimization finished. False, if the optimization timed out.\n\n \"\"\"\n if not self.is_running():\n return True\n\n if timeout is not None:\n timeout *= 60.\n else:\n timeout = max(0, self.optimization_timeout - self.optimization_start_time) \\\n if self.optimization_timeout else None\n\n _thread = self._thread\n\n _thread.join(timeout=timeout)\n if _thread.is_alive():\n return False\n\n return True\n\n def set_time_limit(self, in_minutes=None, specific_time=None):\n # type: (Optional[float], Optional[datetime]) -> ()\n \"\"\"\n Set a time limit for the HyperParameterOptimizer controller. If we reached the time limit, stop the optimization\n process. If ``specific_time`` is provided, use it; otherwise, use the ``in_minutes``.\n\n :param float in_minutes: The maximum processing time from current time (minutes).\n :param datetime specific_time: The specific date/time limit.\n \"\"\"\n if specific_time:\n self.optimization_timeout = specific_time.timestamp()\n else:\n self.optimization_timeout = (in_minutes * 60.) + time() if in_minutes else None\n\n def get_time_limit(self):\n # type: () -> datetime\n \"\"\"\n Return the controller optimization time limit.\n\n :return: The absolute datetime limit of the controller optimization process.\n \"\"\"\n return datetime.fromtimestamp(self.optimization_timeout)\n\n def elapsed(self):\n # type: () -> float\n \"\"\"\n Return minutes elapsed from controller stating time stamp.\n\n :return: The minutes from controller start time. A negative value means the process has not started yet.\n \"\"\"\n if self.optimization_start_time is None:\n return -1.0\n return (time() - self.optimization_start_time) / 60.\n\n def reached_time_limit(self):\n # type: () -> bool\n \"\"\"\n Did the optimizer reach the time limit?\n\n The values are:\n\n - ``True`` - The time limit passed.\n - ``False`` - The time limit did not pass.\n\n This method returns immediately, it does not wait for the optimizer.\n\n :return: True, if optimizer is running and we passed the time limit, otherwise returns False.\n \"\"\"\n if self.optimization_start_time is None:\n return False\n if not self.is_running():\n return False\n\n return time() > self.optimization_timeout\n\n def get_top_experiments(self, top_k):\n # type: (int) -> Sequence[Task]\n \"\"\"\n Return a list of Tasks of the top performing experiments, based on the controller ``Objective`` object.\n\n :param int top_k: The number of Tasks (experiments) to return.\n\n :return: A list of Task objects, ordered by performance, where index 0 is the best performing Task.\n \"\"\"\n if not self.optimizer:\n return []\n return self.optimizer.get_top_experiments(top_k=top_k)\n\n def get_optimizer(self):\n # type: () -> SearchStrategy\n \"\"\"\n Return the currently used optimizer object.\n\n :return: The SearchStrategy object used.\n \"\"\"\n return self.optimizer\n\n def set_default_job_class(self, job_class):\n # type: (TrainsJob) -> ()\n \"\"\"\n Set the Job class to use when the optimizer spawns new Jobs.\n\n :param TrainsJob job_class: The Job Class type.\n \"\"\"\n self.optimizer.set_job_class(job_class)\n\n def set_report_period(self, report_period_minutes):\n # type: (float) -> ()\n \"\"\"\n Set reporting period for the accumulated objective report (minutes). This report is sent on the Optimizer Task,\n and collects the Objective metric from all running jobs.\n\n :param float report_period_minutes: The reporting period (minutes). The default is once every 10 minutes.\n \"\"\"\n self._report_period_min = float(report_period_minutes)\n\n def _connect_args(self, optimizer_class=None, hyper_param_configuration=None, **kwargs):\n # type: (SearchStrategy, dict, Any) -> (SearchStrategy, list, dict)\n if not self._task:\n logger.warning('Auto Connect turned on but no Task was found, '\n 'hyper-parameter optimization argument logging disabled')\n return optimizer_class, hyper_param_configuration, kwargs\n\n configuration_dict = {'parameter_optimization_space': [c.to_dict() for c in hyper_param_configuration]}\n self._task.connect_configuration(configuration_dict)\n # this is the conversion back magic:\n configuration_dict = {'parameter_optimization_space': [\n Parameter.from_dict(c) for c in configuration_dict['parameter_optimization_space']]}\n\n arguments = {'opt': kwargs}\n if type(optimizer_class) != type:\n logger.warning('Auto Connect optimizer_class disabled, {} is already instantiated'.format(optimizer_class))\n self._task.connect(arguments)\n else:\n arguments['opt']['optimizer_class'] = str(optimizer_class).split('.')[-1][:-2] \\\n if not isinstance(optimizer_class, str) else optimizer_class\n self._task.connect(arguments)\n # this is the conversion back magic:\n original_class = optimizer_class\n optimizer_class = arguments['opt'].pop('optimizer_class', None)\n if optimizer_class == 'RandomSearch':\n optimizer_class = RandomSearch\n elif optimizer_class == 'GridSearch':\n optimizer_class = GridSearch\n elif optimizer_class == 'OptimizerBOHB':\n from .hpbandster import OptimizerBOHB\n optimizer_class = OptimizerBOHB\n elif optimizer_class == 'OptimizerOptuna':\n from .optuna import OptimizerOptuna\n optimizer_class = OptimizerOptuna\n else:\n logger.warning(\"Could not resolve optimizer_class {} reverting to original class {}\".format(\n optimizer_class, original_class))\n optimizer_class = original_class\n\n return optimizer_class, configuration_dict['parameter_optimization_space'], arguments['opt']\n\n def _daemon(self):\n # type: () -> ()\n \"\"\"\n Implement the main pooling thread, calling loop every ``self.pool_period_minutes`` minutes.\n \"\"\"\n self.optimizer.start()\n self._thread = None\n\n def _report_daemon(self):\n # type: () -> ()\n worker_to_series = {}\n title, series = self.objective_metric.get_objective_metric()\n title = '{}/{}'.format(title, series)\n series = 'machine:'\n counter = 0\n completed_jobs = dict()\n best_experiment = float('-inf'), None\n\n while self._thread is not None:\n timeout = self.optimization_timeout - time() if self.optimization_timeout else 0.\n\n if timeout >= 0:\n timeout = min(self._report_period_min * 60., timeout if timeout else self._report_period_min * 60.)\n # make sure that we have the first report fired before we actually go to sleep, wait for 15 sec.\n if counter <= 0:\n timeout = 15\n print('Progress report #{} completed, sleeping for {} minutes'.format(counter, timeout / 60.))\n if self._stop_event.wait(timeout=timeout):\n # wait for one last report\n timeout = -1\n\n counter += 1\n\n # get task to report on.\n if self._task or Task.current_task():\n task_logger = (self._task or Task.current_task()).get_logger()\n\n # do some reporting\n\n # running objective, per machine\n running_job_ids = set()\n for j in self.optimizer.get_running_jobs():\n worker = j.worker()\n running_job_ids.add(j.task_id())\n if worker not in worker_to_series:\n worker_to_series[worker] = len(worker_to_series) + 1\n machine_id = worker_to_series[worker]\n value = self.objective_metric.get_objective(j)\n if value is not None:\n task_logger.report_scalar(\n title=title, series='{}{}'.format(series, machine_id),\n iteration=counter, value=value)\n\n # noinspection PyBroadException\n try:\n budget = self.optimizer.budget.to_dict()\n except Exception:\n budget = {}\n\n # report remaining budget\n for budget_part, value in budget.items():\n task_logger.report_scalar(\n title='remaining budget', series='{} %'.format(budget_part),\n iteration=counter, value=round(100 - value['used'] * 100., ndigits=1))\n if self.optimization_timeout and self.optimization_start_time:\n task_logger.report_scalar(\n title='remaining budget', series='time %',\n iteration=counter,\n value=round(100 - (100. * (time() - self.optimization_start_time) /\n (self.optimization_timeout - self.optimization_start_time)), ndigits=1)\n )\n\n # collect a summary of all the jobs and their final objective values\n cur_completed_jobs = set(self.optimizer.get_created_jobs_ids().keys()) - running_job_ids\n if cur_completed_jobs != set(completed_jobs.keys()):\n pairs = []\n labels = []\n created_jobs = copy(self.optimizer.get_created_jobs_ids())\n for i, (job_id, params) in enumerate(created_jobs.items()):\n if job_id in completed_jobs:\n pairs.append((i, completed_jobs[job_id][0]))\n labels.append(str(completed_jobs[job_id][2])[1:-1])\n else:\n value = self.objective_metric.get_objective(job_id)\n if value is not None:\n pairs.append((i, value))\n labels.append(str(params)[1:-1])\n iteration_value = self.objective_metric.get_current_raw_objective(job_id)\n completed_jobs[job_id] = (\n value, iteration_value[0] if iteration_value else -1, copy(params))\n # callback new experiment completed\n if self._experiment_completed_cb:\n normalized_value = self.objective_metric.get_normalized_objective(job_id)\n if normalized_value is not None and normalized_value > best_experiment[0]:\n best_experiment = normalized_value, job_id\n c = completed_jobs[job_id]\n self._experiment_completed_cb(job_id, c[0], c[1], c[2], best_experiment[1])\n\n if pairs:\n print('Updating job performance summary plot/table')\n\n # update scatter plot\n task_logger.report_scatter2d(\n title='optimization', series=title,\n scatter=pairs, iteration=0, labels=labels,\n mode='markers', xaxis='job #', yaxis='objective')\n\n # update summary table\n if pd:\n index = list(completed_jobs.keys())\n table = {'objective': [completed_jobs[i][0] for i in index],\n 'iteration': [completed_jobs[i][1] for i in index]}\n columns = set([c for k, v in completed_jobs.items() for c in v[2].keys()])\n for c in sorted(columns):\n table.update({c: [completed_jobs[i][2].get(c, '') for i in index]})\n\n df = pd.DataFrame(table, index=index)\n df.sort_values(by='objective', ascending=bool(self.objective_metric.sign < 0), inplace=True)\n df.index.name = 'task id'\n task_logger.report_table(\n \"summary\", \"job\", 0, table_plot=df,\n extra_layout={\"title\": \"objective: {}\".format(title)})\n\n # if we should leave, stop everything now.\n if timeout < 0:\n # we should leave\n self.stop()\n return\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": [] } ]
huxian123/mindspore
[ "55372b41fdfae6d2b88d7078971e06d537f6c558", "55372b41fdfae6d2b88d7078971e06d537f6c558", "c3d1f54c7f6d6f514e5748430d24b16a4f9ee9e5", "c3d1f54c7f6d6f514e5748430d24b16a4f9ee9e5", "ec5ba10c82bbd6eccafe32d3a1149add90105bc8", "ec5ba10c82bbd6eccafe32d3a1149add90105bc8" ]
[ "model_zoo/official/gnn/gcn/train.py", "tests/st/pynative/test_parser_tensor_assign.py", "tests/ut/python/parallel/test_sigmoid_cross_entropy_with_logits.py", "tests/ut/python/parallel/test_auto_parallel_onehot.py", "mindspore/nn/layer/quant.py", "model_zoo/official/cv/googlenet/train.py" ]
[ "# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\n\"\"\"\nGCN training script.\n\"\"\"\n\nimport time\nimport argparse\nimport ast\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\nfrom sklearn import manifold\nfrom mindspore import context\nfrom mindspore.common import set_seed\n\nfrom src.gcn import GCN\nfrom src.metrics import LossAccuracyWrapper, TrainNetWrapper\nfrom src.config import ConfigGCN\nfrom src.dataset import get_adj_features_labels, get_mask\n\n\ndef t_SNE(out_feature, dim):\n t_sne = manifold.TSNE(n_components=dim, init='pca', random_state=0)\n return t_sne.fit_transform(out_feature)\n\n\ndef update_graph(i, data, scat, plot):\n scat.set_offsets(data[i])\n plt.title('t-SNE visualization of Epoch:{0}'.format(i))\n return scat, plot\n\n\ndef train():\n \"\"\"Train model.\"\"\"\n parser = argparse.ArgumentParser(description='GCN')\n parser.add_argument('--data_dir', type=str, default='./data/cora/cora_mr', help='Dataset directory')\n parser.add_argument('--seed', type=int, default=123, help='Random seed')\n parser.add_argument('--train_nodes_num', type=int, default=140, help='Nodes numbers for training')\n parser.add_argument('--eval_nodes_num', type=int, default=500, help='Nodes numbers for evaluation')\n parser.add_argument('--test_nodes_num', type=int, default=1000, help='Nodes numbers for test')\n parser.add_argument('--save_TSNE', type=ast.literal_eval, default=False, help='Whether to save t-SNE graph')\n args_opt = parser.parse_args()\n\n set_seed(args_opt.seed)\n context.set_context(mode=context.GRAPH_MODE,\n device_target=\"Ascend\", save_graphs=False)\n config = ConfigGCN()\n adj, feature, label_onehot, label = get_adj_features_labels(args_opt.data_dir)\n\n nodes_num = label_onehot.shape[0]\n train_mask = get_mask(nodes_num, 0, args_opt.train_nodes_num)\n eval_mask = get_mask(nodes_num, args_opt.train_nodes_num, args_opt.train_nodes_num + args_opt.eval_nodes_num)\n test_mask = get_mask(nodes_num, nodes_num - args_opt.test_nodes_num, nodes_num)\n\n class_num = label_onehot.shape[1]\n gcn_net = GCN(config, adj, feature, class_num)\n gcn_net.add_flags_recursive(fp16=True)\n\n eval_net = LossAccuracyWrapper(gcn_net, label_onehot, eval_mask, config.weight_decay)\n test_net = LossAccuracyWrapper(gcn_net, label_onehot, test_mask, config.weight_decay)\n train_net = TrainNetWrapper(gcn_net, label_onehot, train_mask, config)\n\n loss_list = []\n\n if args_opt.save_TSNE:\n out_feature = gcn_net()\n tsne_result = t_SNE(out_feature.asnumpy(), 2)\n graph_data = []\n graph_data.append(tsne_result)\n fig = plt.figure()\n scat = plt.scatter(tsne_result[:, 0], tsne_result[:, 1], s=2, c=label, cmap='rainbow')\n plt.title('t-SNE visualization of Epoch:0', fontsize='large', fontweight='bold', verticalalignment='center')\n\n for epoch in range(config.epochs):\n t = time.time()\n\n train_net.set_train()\n train_result = train_net()\n train_loss = train_result[0].asnumpy()\n train_accuracy = train_result[1].asnumpy()\n\n eval_net.set_train(False)\n eval_result = eval_net()\n eval_loss = eval_result[0].asnumpy()\n eval_accuracy = eval_result[1].asnumpy()\n\n loss_list.append(eval_loss)\n print(\"Epoch:\", '%04d' % (epoch + 1), \"train_loss=\", \"{:.5f}\".format(train_loss),\n \"train_acc=\", \"{:.5f}\".format(train_accuracy), \"val_loss=\", \"{:.5f}\".format(eval_loss),\n \"val_acc=\", \"{:.5f}\".format(eval_accuracy), \"time=\", \"{:.5f}\".format(time.time() - t))\n\n if args_opt.save_TSNE:\n out_feature = gcn_net()\n tsne_result = t_SNE(out_feature.asnumpy(), 2)\n graph_data.append(tsne_result)\n\n if epoch > config.early_stopping and loss_list[-1] > np.mean(loss_list[-(config.early_stopping+1):-1]):\n print(\"Early stopping...\")\n break\n\n t_test = time.time()\n test_net.set_train(False)\n test_result = test_net()\n test_loss = test_result[0].asnumpy()\n test_accuracy = test_result[1].asnumpy()\n print(\"Test set results:\", \"loss=\", \"{:.5f}\".format(test_loss),\n \"accuracy=\", \"{:.5f}\".format(test_accuracy), \"time=\", \"{:.5f}\".format(time.time() - t_test))\n\n if args_opt.save_TSNE:\n ani = animation.FuncAnimation(fig, update_graph, frames=range(config.epochs + 1), fargs=(graph_data, scat, plt))\n ani.save('t-SNE_visualization.gif', writer='imagemagick')\n\n\nif __name__ == '__main__':\n train()\n", "# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\nimport mindspore as ms\nfrom mindspore.nn import ReLU\nfrom mindspore.nn import Cell\nfrom mindspore.common.tensor import Tensor\nfrom mindspore.ops import operations as P\nimport numpy as np\nimport pytest\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_parser_tensor_assign_slice():\n class Net(Cell):\n def __init__(self, U):\n super(Net, self).__init__()\n self.relu = ReLU()\n self.U = U\n\n def construct(self, x):\n x = self.relu(x)\n x[..., :2] = U\n return x\n\n input_np_x = np.random.rand(4, 4, 4)\n input_me_x = Tensor(input_np_x, ms.float32)\n U = 1.0\n\n net = Net(U)\n out_me = net(input_me_x)\n input_np_x[..., :2] = U\n\n assert np.allclose(out_me.asnumpy(), input_np_x, rtol=0.01, atol=0.01)\n\ndef test_parser_tensor_assign_slice_002():\n class Net(Cell):\n def __init__(self, U):\n super(Net, self).__init__()\n self.relu = ReLU()\n self.U = U\n\n def construct(self, x):\n x = self.relu(x)\n x[::, :, :1] = self.U\n return x\n\n input_np_x = np.random.rand(4, 4, 4)\n input_me_x = Tensor(input_np_x, ms.float32)\n U = 1.0\n\n net = Net(U)\n out_me = net(input_me_x)\n input_np_x[::, :, :1] = U\n\n assert np.allclose(out_me.asnumpy(), input_np_x, rtol=0.01, atol=0.01)\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_onecard\ndef test_parser_tensor_assign_bool():\n class Net(Cell):\n def __init__(self, U):\n super(Net, self).__init__()\n self.relu = ReLU()\n self.U = U\n\n def construct(self, x, tensorB):\n x = self.relu(x)\n x[tensorB] = self.U\n return x\n\n input_np_x = np.random.rand(4, 4, 4)\n input_me_x = Tensor(input_np_x, ms.float32)\n numpy_B = np.random.randn(4, 4, 4) > 0\n tensor_B = Tensor(numpy_B)\n U = np.array([1])\n net = Net(Tensor(U))\n\n out_me = net(input_me_x, tensor_B)\n input_np_x[numpy_B] = U\n\n assert np.allclose(out_me.asnumpy(), input_np_x, rtol=0.01, atol=0.01)\n\ndef test_parser_tensor_assign_bool_002():\n class Net(Cell):\n def __init__(self, U):\n super(Net, self).__init__()\n self.relu = ReLU()\n self.U = U\n self.fill = P.Fill()\n\n def construct(self, x, tensorB):\n x = self.relu(x)\n x[tensorB] = self.U\n return x\n\n input_np_x = np.random.rand(2, 2, 2)\n input_me_x = Tensor(input_np_x, ms.float32)\n numpy_B = np.random.randn(2, 2, 2) > 0\n tensor_B = Tensor(numpy_B)\n U = 1\n\n net = Net(U)\n out_me = net(input_me_x, tensor_B)\n input_np_x[numpy_B] = U\n assert np.allclose(out_me.asnumpy(), input_np_x, rtol=0.01, atol=0.01)\n", "# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nimport mindspore as ms\nfrom mindspore import context, Tensor, Parameter\nfrom mindspore.common.api import _executor\nfrom mindspore.nn import Cell, TrainOneStepCell, Momentum\nfrom mindspore.ops import operations as P\n\n\nclass Net(Cell):\n def __init__(self, mul_weight, strategy1=None, strategy2=None):\n super().__init__()\n self.mul = P.Mul().shard(strategy1)\n self.loss = P.SigmoidCrossEntropyWithLogits().shard(strategy2)\n self.mul_weight = Parameter(mul_weight, \"w1\")\n\n def construct(self, x, b):\n out = self.mul(x, self.mul_weight)\n out = self.loss(out, b)\n return out\n\n\n_x = Tensor(np.ones([128, 64]), dtype=ms.float32)\n_w1 = Tensor(np.ones([128, 64]), dtype=ms.float32)\n_b = Tensor(np.ones([128, 64]), dtype=ms.float32)\n\n\ndef compile_net(net):\n optimizer = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)\n train_net = TrainOneStepCell(net, optimizer)\n train_net.set_auto_parallel()\n _executor.compile(train_net, _x, _b)\n context.reset_auto_parallel_context()\n\n\ndef test_sigmoid_cross_entropy_with_logits_data_parallel():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=16, global_rank=0)\n strategy1 = ((16, 1), (16, 1))\n strategy2 = ((16, 1), (16, 1))\n net = Net(_w1, strategy1, strategy2)\n compile_net(net)\n\n\ndef test_sigmoid_cross_entropy_with_logits_model_parallel():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=16, global_rank=0)\n strategy1 = ((1, 16), (1, 16))\n strategy2 = ((1, 16), (1, 16))\n net = Net(_w1, strategy1, strategy2)\n compile_net(net)\n\n\ndef test_sigmoid_cross_entropy_with_logits_hybrid_parallel():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=16, global_rank=0)\n strategy1 = ((2, 8), (2, 8))\n strategy2 = ((2, 8), (2, 8))\n net = Net(_w1, strategy1, strategy2)\n compile_net(net)\n\n\ndef test_sigmoid_cross_entropy_with_logits_auto_parallel():\n context.set_auto_parallel_context(parallel_mode=\"auto_parallel\", device_num=16, global_rank=0)\n net = Net(_w1)\n compile_net(net)\n\n\ndef test_sigmoid_cross_entropy_with_logits_repeat_calc():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=16, global_rank=0)\n strategy1 = ((2, 8), (2, 8))\n strategy2 = ((2, 2), (2, 2))\n net = Net(_w1, strategy1, strategy2)\n compile_net(net)\n", "# Copyright 2019 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nimport mindspore as ms\nimport mindspore.nn as nn\nfrom mindspore import Tensor\nfrom mindspore import context\nfrom mindspore.common.api import _executor\nfrom mindspore.common.parameter import Parameter\nfrom mindspore.nn.optim.momentum import Momentum\nfrom mindspore.ops import composite as C\nfrom mindspore.ops import operations as P\nfrom mindspore.train import Model\nfrom mindspore.context import ParallelMode\nfrom tests.dataset_mock import MindData\nfrom tests.ut.python.ops.test_math_ops import VirtualLoss\n\ncontext.set_context(mode=context.GRAPH_MODE)\n\n\ngrad_all = C.GradOperation(get_all=True)\n\n\nclass Dataset(MindData):\n def __init__(self, predict, label, length=3):\n super(Dataset, self).__init__(size=length)\n self.predict = predict\n self.label = label\n self.index = 0\n self.length = length\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.index >= self.length:\n raise StopIteration\n self.index += 1\n return self.predict, self.label\n\n def reset(self):\n self.index = 0\n\n\nclass NetWithLoss(nn.Cell):\n def __init__(self, network):\n super(NetWithLoss, self).__init__()\n self.loss = VirtualLoss()\n self.network = network\n\n def construct(self, x, y, b):\n predict = self.network(x, y, b)\n return self.loss(predict)\n\n\nclass GradWrap(nn.Cell):\n def __init__(self, network):\n super(GradWrap, self).__init__()\n self.network = network\n\n def construct(self, x, y, b):\n return grad_all(self.network)(x, y, b)\n\n\ndef test_auto_parallel_arithmetic():\n class Net(nn.Cell):\n def __init__(self):\n super().__init__()\n self.matmul = P.MatMul()\n self.one_hot = P.OneHot()\n self.on_value = Tensor(1.0, ms.float32)\n self.off_value = Tensor(0.0, ms.float32)\n self.matmul2 = P.MatMul()\n\n def construct(self, x, y, b):\n out = self.matmul(x, y)\n out1 = self.one_hot(b, 64, self.on_value, self.off_value)\n out2 = self.matmul2(out, out1)\n return out2\n\n context.set_auto_parallel_context(device_num=8, global_rank=0)\n net = GradWrap(NetWithLoss(Net()))\n context.set_auto_parallel_context(parallel_mode=\"auto_parallel\")\n net.set_auto_parallel()\n\n x = Tensor(np.ones([64, 32]), dtype=ms.float32)\n y = Tensor(np.ones([32, 64]), dtype=ms.float32)\n b = Tensor(np.ones([64]), dtype=ms.int32)\n _executor.compile(net, x, y, b)\n\n\ndef test_auto_parallel_arithmetic_model():\n class NetOneHot(nn.Cell):\n def __init__(self):\n super().__init__()\n self.matmul = P.MatMul()\n self.one_hot = P.OneHot().shard(((1, 8), (), ()))\n self.on_value = Tensor(1.0, ms.float32)\n self.off_value = Tensor(0.0, ms.float32)\n self.matmul2 = P.MatMul()\n self.w = Parameter(Tensor(np.zeros([32, 64]).astype(np.float32)), \"weight\", requires_grad=True)\n\n def construct(self, x, b):\n out = self.matmul(x, self.w)\n out1 = self.one_hot(b, 64, self.on_value, self.off_value)\n out2 = self.matmul2(out, out1)\n return out2\n\n context.reset_auto_parallel_context()\n context.set_auto_parallel_context(device_num=8, global_rank=0, parallel_mode=ParallelMode.AUTO_PARALLEL)\n net = NetOneHot()\n\n x = Tensor(np.ones([8, 32]), dtype=ms.float32)\n b = Tensor(np.ones([8]), dtype=ms.int32)\n dataset = Dataset(x, b, 2)\n\n opt = Momentum(net.trainable_params(), 0.1, 0.9)\n model = Model(net, optimizer=opt)\n\n model.train(2, dataset, dataset_sink_mode=False)\n", "# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Quantization aware training.\"\"\"\n\nfrom functools import partial\nimport numpy as np\n\nfrom mindspore import nn\nimport mindspore.common.dtype as mstype\nfrom mindspore.ops import operations as P\nfrom mindspore.ops import functional as F\nfrom mindspore.common.parameter import Parameter\nfrom mindspore.common.initializer import initializer\nfrom mindspore.common.tensor import Tensor\nfrom mindspore._checkparam import check_int_positive, check_bool, twice\nfrom mindspore._checkparam import Rel\nimport mindspore.context as context\n\nfrom .normalization import BatchNorm2d, BatchNorm1d\nfrom .activation import get_activation, ReLU, LeakyReLU\nfrom ..cell import Cell\nfrom . import conv, basic\nfrom ..._checkparam import ParamValidator as validator\nfrom ...ops.operations import _quant_ops as Q\n\n__all__ = [\n 'Conv2dBnAct',\n 'DenseBnAct',\n 'FakeQuantWithMinMax',\n 'Conv2dBnFoldQuant',\n 'Conv2dBnWithoutFoldQuant',\n 'Conv2dQuant',\n 'DenseQuant',\n 'ActQuant',\n 'LeakyReLUQuant',\n 'HSwishQuant',\n 'HSigmoidQuant',\n 'TensorAddQuant',\n 'MulQuant',\n]\n\n\nclass Conv2dBnAct(Cell):\n r\"\"\"\n A combination of convolution, Batchnorm, activation layer.\n\n This part is a more detailed overview of Conv2d op.\n\n Args:\n in_channels (int): The number of input channel :math:`C_{in}`.\n out_channels (int): The number of output channel :math:`C_{out}`.\n kernel_size (Union[int, tuple]): The data type is int or a tuple of 2 integers. Specifies the height\n and width of the 2D convolution window. Single int means the value is for both height and width of\n the kernel. A tuple of 2 ints means the first value is for the height and the other is for the\n width of the kernel.\n stride (int): Specifies stride for all spatial dimensions with the same value. The value of stride should be\n greater than or equal to 1 and lower than any one of the height and width of the input. Default: 1.\n pad_mode (str): Specifies padding mode. The optional values are \"same\", \"valid\", \"pad\". Default: \"same\".\n padding (int): Implicit paddings on both sides of the input. Default: 0.\n dilation (int): Specifying the dilation rate to use for dilated convolution. If set to be :math:`k > 1`,\n there will be :math:`k - 1` pixels skipped for each sampling location. Its value should be greater than\n or equal to 1 and lower than any one of the height and width of the input. Default: 1.\n group (int): Split filter into groups, `in_ channels` and `out_channels` should be\n divisible by the number of groups. Default: 1.\n has_bias (bool): Specifies whether the layer uses a bias vector. Default: False.\n weight_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the convolution kernel.\n It can be a Tensor, a string, an Initializer or a number. When a string is specified,\n values from 'TruncatedNormal', 'Normal', 'Uniform', 'HeUniform' and 'XavierUniform' distributions as well\n as constant 'One' and 'Zero' distributions are possible. Alias 'xavier_uniform', 'he_uniform', 'ones'\n and 'zeros' are acceptable. Uppercase and lowercase are both acceptable. Refer to the values of\n Initializer for more details. Default: 'normal'.\n bias_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the bias vector. Possible\n Initializer and string are the same as 'weight_init'. Refer to the values of\n Initializer for more details. Default: 'zeros'.\n has_bn (bool): Specifies to used batchnorm or not. Default: False.\n activation (Cell): Specifies activation type. The optional values are as following:\n 'softmax', 'logsoftmax', 'relu', 'relu6', 'tanh', 'gelu', 'sigmoid',\n 'prelu', 'leakyrelu', 'hswish', 'hsigmoid'. Default: None.\n\n Inputs:\n - **input** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.\n\n Outputs:\n Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`.\n\n Examples:\n >>> net = Conv2dBnAct(120, 240, 4, has_bn=True, activation='ReLU')\n >>> input = Tensor(np.ones([1, 120, 1024, 640]), mindspore.float32)\n >>> net(input).shape\n (1, 240, 1024, 640)\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n pad_mode='same',\n padding=0,\n dilation=1,\n group=1,\n has_bias=False,\n weight_init='normal',\n bias_init='zeros',\n has_bn=False,\n momentum=0.9,\n eps=1e-5,\n activation=None,\n alpha=0.2,\n after_fake=True):\n super(Conv2dBnAct, self).__init__()\n\n self.conv = conv.Conv2d(in_channels,\n out_channels,\n kernel_size=kernel_size,\n stride=stride,\n pad_mode=pad_mode,\n padding=padding,\n dilation=dilation,\n group=group,\n has_bias=has_bias,\n weight_init=weight_init,\n bias_init=bias_init)\n self.has_bn = validator.check_bool(\"has_bn\", has_bn)\n self.has_act = activation is not None\n self.after_fake = after_fake\n if has_bn:\n self.batchnorm = BatchNorm2d(out_channels, eps, momentum)\n if activation == \"leakyrelu\":\n self.activation = LeakyReLU(alpha)\n else:\n self.activation = get_activation(activation)\n\n def construct(self, x):\n x = self.conv(x)\n if self.has_bn:\n x = self.batchnorm(x)\n if self.has_act:\n x = self.activation(x)\n return x\n\n\nclass DenseBnAct(Cell):\n r\"\"\"\n A combination of Dense, Batchnorm, and the activation layer.\n\n This part is a more detailed overview of Dense op.\n\n Args:\n in_channels (int): The number of channels in the input space.\n out_channels (int): The number of channels in the output space.\n weight_init (Union[Tensor, str, Initializer, numbers.Number]): The trainable weight_init parameter. The dtype\n is same as input x. The values of str refer to the function `initializer`. Default: 'normal'.\n bias_init (Union[Tensor, str, Initializer, numbers.Number]): The trainable bias_init parameter. The dtype is\n same as input x. The values of str refer to the function `initializer`. Default: 'zeros'.\n has_bias (bool): Specifies whether the layer uses a bias vector. Default: True.\n activation (Cell): The regularization function applied to the output of the layer, eg. 'ReLU'. Default: None.\n has_bn (bool): Specifies to use batchnorm or not. Default: False.\n activation (string): Specifies activation type. The optional values are as following:\n 'Softmax', 'LogSoftmax', 'ReLU', 'ReLU6', 'Tanh', 'GELU', 'Sigmoid',\n 'PReLU', 'LeakyReLU', 'h-Swish', and 'h-Sigmoid'. Default: None.\n\n Inputs:\n - **input** (Tensor) - Tensor of shape :math:`(N, in\\_channels)`.\n\n Outputs:\n Tensor of shape :math:`(N, out\\_channels)`.\n\n Examples:\n >>> net = nn.DenseBnAct(3, 4)\n >>> input = Tensor(np.random.randint(0, 255, [2, 3]), mindspore.float32)\n >>> net(input)\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n weight_init='normal',\n bias_init='zeros',\n has_bias=True,\n has_bn=False,\n activation=None,\n after_fake=True):\n super(DenseBnAct, self).__init__()\n self.dense = basic.Dense(\n in_channels,\n out_channels,\n weight_init,\n bias_init,\n has_bias)\n self.has_bn = validator.check_bool(\"has_bn\", has_bn)\n self.has_act = activation is not None\n self.after_fake = after_fake\n if has_bn:\n self.batchnorm = BatchNorm1d(out_channels)\n self.activation = get_activation(activation)\n\n def construct(self, x):\n x = self.dense(x)\n if self.has_bn:\n x = self.batchnorm(x)\n if self.has_act:\n x = self.activation(x)\n return x\n\n\nclass BatchNormFoldCell(Cell):\n \"\"\"\n Batch normalization folded.\n\n Args:\n momentum (float): Momentum value should be [0, 1]. Default: 0.9.\n epsilon (float): A small float number to avoid dividing by 0. 1e-5 if dtype in\n float32 else 1e-3. Default: 1e-5.\n freeze_bn (int): Delay in steps at which computation switches from regular batch\n norm to frozen mean and std. Default: 0.\n\n Inputs:\n - **x** (Tensor) - Tensor of shape :math:`(N, C, H, W)`.\n - **mean** (Tensor) - Tensor of shape :math:`(C,)`.\n - **variance** (Tensor) - Tensor of shape :math:`(C,)`.\n - **global_step** (Tensor) - Tensor to record current global step.\n\n Outputs:\n Tuple of 4 Tensor, the normalized input and the updated parameters.\n\n - **batch_mean** (Tensor) - Tensor of shape :math:`(C,)`.\n - **batch_std** (Tensor) - Tensor of shape :math:`(C,)`.\n - **running_mean** (Tensor) - Tensor of shape :math:`(C,)`.\n - **running_std** (Tensor) - Tensor of shape :math:`(C,)`.\n\n \"\"\"\n\n def __init__(self, momentum=0.9, epsilon=1e-5, freeze_bn=0):\n \"\"\"init batch norm fold layer\"\"\"\n super(BatchNormFoldCell, self).__init__()\n self.epsilon = epsilon\n self.is_gpu = context.get_context('device_target') == \"GPU\"\n if self.is_gpu:\n self.bn_train = Q.BatchNormFold(momentum, epsilon, is_training=True, freeze_bn=freeze_bn)\n self.bn_infer = Q.BatchNormFold(momentum, epsilon, is_training=False, freeze_bn=freeze_bn)\n else:\n self.bn_reduce = P.BNTrainingReduce()\n self.bn_update = Q.BatchNormFoldD(momentum, epsilon, is_training=True, freeze_bn=freeze_bn)\n\n def construct(self, x, mean, variance, global_step):\n if self.is_gpu:\n if self.training:\n batch_mean, batch_std, running_mean, running_std = self.bn_train(x, mean, variance, global_step)\n else:\n batch_mean, batch_std, running_mean, running_std = self.bn_infer(x, mean, variance, global_step)\n else:\n if self.training:\n x_sum, x_square_sum = self.bn_reduce(x)\n _, batch_mean, batch_std, running_mean, running_std, mean_updated, variance_updated = \\\n self.bn_update(x, x_sum, x_square_sum, mean, variance)\n P.Assign()(mean, mean_updated)\n P.Assign()(variance, variance_updated)\n else:\n batch_mean = P.ZerosLike()(variance)\n batch_std = P.OnesLike()(variance)\n running_mean = P.TensorAdd()(mean, 0.)\n running_std = P.Sqrt()(P.TensorAdd()(variance, self.epsilon))\n return batch_mean, batch_std, running_mean, running_std\n\n\nclass FakeQuantWithMinMax(Cell):\n r\"\"\"\n Quantization aware op. This OP provides the fake quantization observer function on data with min and max.\n\n Args:\n min_init (int, float): The dimension of channel or 1(layer). Default: -6.\n max_init (int, float): The dimension of channel or 1(layer). Default: 6.\n ema (bool): The exponential Moving Average algorithm updates min and max. Default: False.\n ema_decay (float): Exponential Moving Average algorithm parameter. Default: 0.999.\n per_channel (bool): Quantization granularity based on layer or on channel. Default: False.\n channel_axis (int): Quantization by channel axis. Default: 1.\n num_channels (int): declarate the min and max channel size, Default: 1.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): Whether the quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): Whether the quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): Quantization delay parameters according to the global step. Default: 0.\n\n Inputs:\n - **x** (Tensor) - The input of FakeQuantWithMinMax.\n\n Outputs:\n Tensor, with the same type and shape as the `x`.\n\n Examples:\n >>> fake_quant = FakeQuantWithMinMax()\n >>> input_x = Tensor(np.array([[1, 2, 1], [-2, 0, -1]]), mindspore.float32)\n >>> result = fake_quant(input_x)\n \"\"\"\n\n def __init__(self,\n min_init=-6,\n max_init=6,\n ema=False,\n ema_decay=0.999,\n per_channel=False,\n channel_axis=1,\n num_channels=1,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0):\n \"\"\"init FakeQuantWithMinMax layer\"\"\"\n super(FakeQuantWithMinMax, self).__init__()\n validator.check_type(\"min_init\", min_init, [int, float])\n validator.check_type(\"max_init\", max_init, [int, float])\n validator.check(\"min_init\", min_init, \"max_init\", max_init, rel=Rel.LT)\n validator.check_integer('quant_delay', quant_delay, 0, Rel.GE)\n self.min_init = min_init\n self.max_init = max_init\n self.num_bits = num_bits\n self.ema = ema\n self.ema_decay = ema_decay\n self.per_channel = per_channel\n self.num_channels = num_channels\n self.channel_axis = channel_axis\n self.quant_delay = quant_delay\n self.symmetric = symmetric\n self.narrow_range = narrow_range\n self.is_ascend = context.get_context('device_target') == \"Ascend\"\n\n # init tensor min and max for fake quant op\n if self.per_channel:\n min_array = np.array([self.min_init] * self.num_channels).astype(np.float32)\n max_array = np.array([self.max_init] * self.num_channels).astype(np.float32)\n else:\n min_array = np.array([self.min_init]).astype(np.float32)\n max_array = np.array([self.max_init]).astype(np.float32)\n self.minq = Parameter(Tensor(min_array), name='quant_min', requires_grad=False)\n self.maxq = Parameter(Tensor(max_array), name='quant_max', requires_grad=False)\n\n # init fake quant relative op\n if self.per_channel:\n quant_fun = partial(Q.FakeQuantPerChannel, channel_axis=self.channel_axis)\n ema_fun = partial(Q.MinMaxUpdatePerChannel, channel_axis=self.channel_axis)\n else:\n quant_fun = Q.FakeQuantPerLayer\n ema_fun = Q.MinMaxUpdatePerLayer\n\n self.ema_update = ema_fun(ema=self.ema, ema_decay=self.ema_decay)\n if self.is_ascend:\n self.fake_quant_train = quant_fun(num_bits=self.num_bits,\n symmetric=self.symmetric,\n narrow_range=self.narrow_range,\n quant_delay=self.quant_delay)\n self.fake_quant_infer = self.fake_quant_train\n else:\n quant_fun = partial(quant_fun,\n ema=self.ema,\n ema_decay=ema_decay,\n num_bits=self.num_bits,\n symmetric=self.symmetric,\n narrow_range=self.narrow_range,\n quant_delay=self.quant_delay)\n self.fake_quant_train = quant_fun(training=True)\n self.fake_quant_infer = quant_fun(training=False)\n\n def extend_repr(self):\n s = 'num_bits={}, symmetric={}, narrow_range={}, ema={}({}), per_channel={}({}, {}), ' \\\n 'quant_delay={}, min_init={}, max_init={}'.format(self.num_bits, self.symmetric, self.narrow_range,\n self.ema, self.ema_decay, self.per_channel,\n self.channel_axis, self.num_channels, self.quant_delay,\n self.min_init, self.max_init)\n return s\n\n def construct(self, x):\n if self.training:\n min_up, max_up = self.ema_update(x, self.minq, self.maxq)\n P.Assign()(self.minq, min_up)\n P.Assign()(self.maxq, max_up)\n out = self.fake_quant_train(x, self.minq, self.maxq)\n else:\n out = self.fake_quant_infer(x, self.minq, self.maxq)\n return out\n\n\nclass Conv2dBnFoldQuant(Cell):\n r\"\"\"\n 2D convolution with BatchNormal op folded construct.\n\n This part is a more detailed overview of Conv2d op.\n\n Args:\n in_channels (int): The number of input channel :math:`C_{in}`.\n out_channels (int): The number of output channel :math:`C_{out}`.\n kernel_size (Union[int, tuple]): Specifies the height and width of the 2D convolution window.\n stride (int): Specifies stride for all spatial dimensions with the same value.\n pad_mode (str): Specifies padding mode. The optional values are \"same\", \"valid\", \"pad\". Default: \"same\".\n padding (int): Implicit paddings on both sides of the input. Default: 0.\n eps (float): Parameters for BatchNormal. Default: 1e-5.\n momentum (float): Parameters for BatchNormal op. Default: 0.997.\n has_bias (bool): Specifies whether the layer uses a bias vector. Default: False.\n weight_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the\n convolution kernel. Default: 'normal'.\n bias_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the\n bias vector. Default: 'zeros'.\n beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the\n beta vector. Default: 'zeros'.\n gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the\n gamma vector. Default: 'ones'.\n mean_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the\n mean vector. Default: 'zeros'.\n var_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the\n variance vector. Default: 'ones'.\n fake (bool): Whether Conv2dBnFoldQuant Cell adds FakeQuantWithMinMax op. Default: True.\n per_channel (bool): FakeQuantWithMinMax Parameters. Default: False.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): The quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): The quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): The Quantization delay parameters according to the global step. Default: 0.\n freeze_bn (int): The quantization freeze BatchNormal op is according to the global step. Default: 100000.\n\n Inputs:\n - **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.\n\n Outputs:\n Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`.\n\n Examples:\n >>> conv2d_bn = nn.Conv2dBnFoldQuant(1, 6, kernel_size=(2, 2), stride=(1, 1), pad_mode=\"valid\")\n >>> x = Tensor(np.random.randint(-2, 2, (2, 1, 1, 3)), mindspore.float32)\n >>> y = conv2d_bn(x)\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n pad_mode='same',\n padding=0,\n dilation=1,\n group=1,\n eps=1e-5,\n momentum=0.997,\n has_bias=False,\n weight_init='normal',\n bias_init='zeros',\n beta_init='zeros',\n gamma_init='ones',\n mean_init='zeros',\n var_init='ones',\n fake=True,\n per_channel=False,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0,\n freeze_bn=100000):\n \"\"\"init Conv2dBnFoldQuant layer\"\"\"\n super(Conv2dBnFoldQuant, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = twice(kernel_size)\n self.stride = twice(stride)\n self.pad_mode = pad_mode\n self.padding = padding\n self.dilation = twice(dilation)\n self.group = group\n self.eps = eps\n self.momentum = momentum\n self.has_bias = has_bias\n self.quant_delay = quant_delay\n self.freeze_bn = freeze_bn\n self.fake = fake\n self.num_bits = num_bits\n self.per_channel = per_channel\n self.symmetric = symmetric\n self.narrow_range = narrow_range\n self.is_gpu = context.get_context('device_target') == \"GPU\"\n\n # initialize convolution op and Parameter\n if context.get_context('device_target') == \"Ascend\" and group > 1:\n validator.check_integer('group', group, in_channels, Rel.EQ)\n validator.check_integer('group', group, out_channels, Rel.EQ)\n self.conv = P.DepthwiseConv2dNative(channel_multiplier=1,\n kernel_size=self.kernel_size,\n pad_mode=pad_mode,\n pad=padding,\n stride=self.stride,\n dilation=self.dilation)\n weight_shape = [1, in_channels, *self.kernel_size]\n channel_axis = 1\n else:\n self.conv = P.Conv2D(out_channel=out_channels,\n kernel_size=self.kernel_size,\n pad_mode=pad_mode,\n pad=padding,\n stride=self.stride,\n dilation=self.dilation,\n group=group)\n weight_shape = [out_channels, in_channels // group, *self.kernel_size]\n channel_axis = 0\n self.weight = Parameter(initializer(weight_init, weight_shape), name='weight')\n self.bias_add = P.BiasAdd()\n if check_bool(has_bias):\n self.bias = Parameter(initializer(bias_init, [out_channels]), name='bias')\n else:\n self.bias = None\n\n # initialize BatchNorm Parameter\n self.gamma = Parameter(initializer(gamma_init, [out_channels]), name='gamma')\n self.beta = Parameter(initializer(beta_init, [out_channels]), name='beta')\n self.moving_mean = Parameter(initializer(mean_init, [out_channels]), name='moving_mean', requires_grad=False)\n self.moving_variance = Parameter(initializer(var_init, [out_channels]), name='moving_variance',\n requires_grad=False)\n\n # initialize fake ops\n self.fake_quant_weight = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=False,\n per_channel=per_channel,\n channel_axis=channel_axis,\n num_channels=out_channels,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n self.batchnorm_fold = BatchNormFoldCell(epsilon=eps, momentum=momentum, freeze_bn=freeze_bn)\n self.correct_mul = Q.CorrectionMul(channel_axis)\n if context.get_context('device_target') == \"Ascend\":\n self.batchnorm_fold2_train = Q.BatchNormFold2_D(freeze_bn=freeze_bn)\n self.batchnorm_fold2_infer = Q.BatchNormFold2_D(freeze_bn=0)\n elif context.get_context('device_target') == \"GPU\":\n self.batchnorm_fold2_train = Q.BatchNormFold2(freeze_bn=freeze_bn)\n self.batchnorm_fold2_infer = Q.BatchNormFold2(freeze_bn=0)\n else:\n raise ValueError(\"Unsupported platform: {}\".format(context.get_context('device_target')))\n self.step = Parameter(initializer('normal', [1], dtype=mstype.int32), name='step', requires_grad=False)\n self.one = Tensor(1, mstype.int32)\n self.assignadd = P.AssignAdd()\n\n def extend_repr(self):\n s = 'in_channels={}, out_channels={}, kernel_size={}, stride={}, ' \\\n 'pad_mode={}, padding={}, dilation={}, group={}, ' \\\n 'fake={}, freeze_bn={}, momentum={}, quant_delay={}'.format(self.in_channels, self.out_channels,\n self.kernel_size, self.stride,\n self.pad_mode, self.padding, self.dilation,\n self.group,\n self.fake, self.freeze_bn, self.momentum,\n self.quant_delay)\n return s\n\n def construct(self, x):\n out_conv = self.conv(x, self.weight)\n if self.has_bias:\n out_conv = self.bias_add(out_conv, self.bias)\n # BN fold1\n batch_mean, batch_std, running_mean, running_std = self.batchnorm_fold(out_conv,\n self.moving_mean,\n self.moving_variance,\n self.step)\n # fake weight\n weight = self.correct_mul(self.weight, self.gamma, running_std)\n if self.fake:\n weight = self.fake_quant_weight(weight)\n out = self.conv(x, weight)\n if self.has_bias:\n out = self.bias_add(out, self.bias)\n # BN fold2\n if self.is_gpu:\n if self.training:\n out = self.batchnorm_fold2_train(out, self.beta, self.gamma,\n batch_std, batch_mean, running_std, running_mean, self.step)\n F.control_depend(out, self.assignadd(self.step, self.one))\n else:\n out = self.batchnorm_fold2_infer(out, self.beta, self.gamma,\n batch_std, batch_mean, running_std, running_mean, self.step)\n else:\n if self.training:\n out = self.batchnorm_fold2_train(out, self.beta, self.gamma, batch_std, batch_mean, running_std)\n F.control_depend(out, self.assignadd(self.step, self.one))\n else:\n out = self.batchnorm_fold2_infer(out, self.beta, self.gamma, running_std, running_mean, running_std)\n return out\n\n\nclass Conv2dBnWithoutFoldQuant(Cell):\n r\"\"\"\n 2D convolution + batchnorm without fold with fake quant construct.\n\n This part is a more detailed overview of Conv2d op.\n\n Args:\n in_channels (int): The number of input channel :math:`C_{in}`.\n out_channels (int): The number of output channel :math:`C_{out}`.\n kernel_size (Union[int, tuple]): Specifies the height and width of the 2D convolution window.\n stride (int): Specifies stride for all spatial dimensions with the same value. Default: 1.\n pad_mode (str): Specifies padding mode. The optional values are \"same\", \"valid\", \"pad\". Default: \"same\".\n padding (int): Implicit paddings on both sides of the input. Default: 0.\n dilation (int): Specifying the dilation rate to use for dilated convolution. Default: 1.\n group (int): Split filter into groups, `in_ channels` and `out_channels` should be\n divisible by the number of groups. Default: 1.\n has_bias (bool): Specifies whether the layer uses a bias vector. Default: False.\n eps (float): Parameters for BatchNormal. Default: 1e-5.\n momentum (float): Parameters for BatchNormal op. Default: 0.997.\n weight_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the convolution kernel.\n Default: 'normal'.\n bias_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the bias vector. Default: 'zeros'.\n per_channel (bool): FakeQuantWithMinMax Parameters. Default: False.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): The quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): The quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): Quantization delay parameters according to the global step. Default: 0.\n\n Inputs:\n - **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.\n\n Outputs:\n Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`.\n\n Examples:\n >>> conv2d_quant = nn.Conv2dBnWithoutFoldQuant(1, 6, kernel_size=(2, 2), stride=(1, 1), pad_mode=\"valid\")\n >>> x = Tensor(np.random.randint(-2, 2, (2, 1, 1, 3)), mstype.float32)\n >>> y = conv2d_quant(x)\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n pad_mode='same',\n padding=0,\n dilation=1,\n group=1,\n has_bias=False,\n eps=1e-5,\n momentum=0.997,\n weight_init='normal',\n bias_init='zeros',\n per_channel=False,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0):\n super(Conv2dBnWithoutFoldQuant, self).__init__()\n if isinstance(kernel_size, int):\n self.kernel_size = (kernel_size, kernel_size)\n else:\n self.kernel_size = kernel_size\n self.in_channels = check_int_positive(in_channels)\n self.out_channels = check_int_positive(out_channels)\n self.has_bias = has_bias\n self.stride = twice(stride)\n self.dilation = twice(dilation)\n self.pad_mode = pad_mode\n self.padding = padding\n self.group = group\n self.quant_delay = quant_delay\n\n self.bias_add = P.BiasAdd()\n if check_bool(has_bias):\n self.bias = Parameter(initializer(bias_init, [out_channels]), name='bias')\n else:\n self.bias = None\n # initialize convolution op and Parameter\n if context.get_context('device_target') == \"Ascend\" and group > 1:\n validator.check_integer('group', group, in_channels, Rel.EQ)\n validator.check_integer('group', group, out_channels, Rel.EQ)\n self.conv = P.DepthwiseConv2dNative(channel_multiplier=1,\n kernel_size=self.kernel_size,\n pad_mode=pad_mode,\n pad=padding,\n stride=self.stride,\n dilation=self.dilation)\n weight_shape = [1, in_channels, *self.kernel_size]\n channel_axis = 1\n else:\n self.conv = P.Conv2D(out_channel=self.out_channels,\n kernel_size=self.kernel_size,\n mode=1,\n pad_mode=self.pad_mode,\n pad=self.padding,\n stride=self.stride,\n dilation=self.dilation,\n group=self.group)\n weight_shape = [out_channels, in_channels // group, *self.kernel_size]\n channel_axis = 0\n self.weight = Parameter(initializer(weight_init, weight_shape), name='weight')\n self.fake_quant_weight = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=False,\n per_channel=per_channel,\n channel_axis=channel_axis,\n num_channels=out_channels,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n self.batchnorm = BatchNorm2d(out_channels, eps=eps, momentum=momentum)\n\n def construct(self, x):\n weight = self.fake_quant_weight(self.weight)\n out = self.conv(x, weight)\n if self.has_bias:\n out = self.bias_add(out, self.bias)\n out = self.batchnorm(out)\n return out\n\n def extend_repr(self):\n s = 'in_channels={}, out_channels={}, kernel_size={}, stride={}, ' \\\n 'pad_mode={}, padding={}, dilation={}, group={}, ' \\\n 'has_bias={}, quant_delay={}'.format(self.in_channels, self.out_channels, self.kernel_size, self.stride,\n self.pad_mode, self.padding, self.dilation, self.group,\n self.has_bias, self.quant_delay)\n return s\n\n\nclass Conv2dQuant(Cell):\n r\"\"\"\n 2D convolution with fake quant op layer.\n\n This part is a more detailed overview of Conv2d op.\n\n Args:\n in_channels (int): The number of input channel :math:`C_{in}`.\n out_channels (int): The number of output channel :math:`C_{out}`.\n kernel_size (Union[int, tuple]): Specifies the height and width of the 2D convolution window.\n stride (int): Specifies stride for all spatial dimensions with the same value. Default: 1.\n pad_mode (str): Specifies padding mode. The optional values are \"same\", \"valid\", \"pad\". Default: \"same\".\n padding (int): Implicit paddings on both sides of the input. Default: 0.\n dilation (int): Specifying the dilation rate to use for dilated convolution. Default: 1.\n group (int): Split filter into groups, `in_ channels` and `out_channels` should be\n divisible by the number of groups. Default: 1.\n has_bias (bool): Specifies whether the layer uses a bias vector. Default: False.\n weight_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the convolution kernel.\n Default: 'normal'.\n bias_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the bias vector. Default: 'zeros'.\n per_channel (bool): FakeQuantWithMinMax Parameters. Default: False.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): The quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): The quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): Quantization delay parameters according to the global step. Default: 0.\n\n Inputs:\n - **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.\n\n Outputs:\n Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`.\n\n Examples:\n >>> conv2d_quant = nn.Conv2dQuant(1, 6, kernel_size= (2, 2), stride=(1, 1), pad_mode=\"valid\")\n >>> x = Tensor(np.random.randint(-2, 2, (2, 1, 1, 3)), mindspore.float32)\n >>> y = conv2d_quant(x)\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n pad_mode='same',\n padding=0,\n dilation=1,\n group=1,\n has_bias=False,\n weight_init='normal',\n bias_init='zeros',\n per_channel=False,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0):\n super(Conv2dQuant, self).__init__()\n if isinstance(kernel_size, int):\n self.kernel_size = (kernel_size, kernel_size)\n else:\n self.kernel_size = kernel_size\n self.in_channels = check_int_positive(in_channels)\n self.out_channels = check_int_positive(out_channels)\n self.has_bias = has_bias\n self.stride = twice(stride)\n self.dilation = twice(dilation)\n self.pad_mode = pad_mode\n self.padding = padding\n self.group = group\n self.quant_delay = quant_delay\n\n weight_shape = [out_channels, in_channels // group, *self.kernel_size]\n self.weight = Parameter(initializer(weight_init, weight_shape), name='weight')\n\n self.bias_add = P.BiasAdd()\n if check_bool(has_bias):\n self.bias = Parameter(initializer(bias_init, [out_channels]), name='bias')\n else:\n self.bias = None\n\n self.conv = P.Conv2D(out_channel=self.out_channels,\n kernel_size=self.kernel_size,\n mode=1,\n pad_mode=self.pad_mode,\n pad=self.padding,\n stride=self.stride,\n dilation=self.dilation,\n group=self.group)\n self.fake_quant_weight = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=False,\n per_channel=per_channel,\n channel_axis=0,\n num_channels=out_channels,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n\n def construct(self, x):\n weight = self.fake_quant_weight(self.weight)\n out = self.conv(x, weight)\n if self.has_bias:\n return self.bias_add(out, self.bias)\n return out\n\n def extend_repr(self):\n s = 'in_channels={}, out_channels={}, kernel_size={}, stride={}, ' \\\n 'pad_mode={}, padding={}, dilation={}, group={}, ' \\\n 'has_bias={}, quant_delay={}'.format(self.in_channels, self.out_channels, self.kernel_size, self.stride,\n self.pad_mode, self.padding, self.dilation, self.group,\n self.has_bias, self.quant_delay)\n return s\n\n\nclass DenseQuant(Cell):\n r\"\"\"\n The fully connected layer with fake quant op.\n\n This part is a more detailed overview of Dense op.\n\n Args:\n in_channels (int): The dimension of the input space.\n out_channels (int): The dimension of the output space.\n weight_init (Union[Tensor, str, Initializer, numbers.Number]): The trainable weight_init parameter. The dtype\n is same as input x. The values of str refer to the function `initializer`. Default: 'normal'.\n bias_init (Union[Tensor, str, Initializer, numbers.Number]): The trainable bias_init parameter. The dtype is\n same as input x. The values of str refer to the function `initializer`. Default: 'zeros'.\n has_bias (bool): Specifies whether the layer uses a bias vector. Default: True.\n activation (str): The regularization function applied to the output of the layer, eg. 'relu'. Default: None.\n per_channel (bool): FakeQuantWithMinMax Parameters. Default: False.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): The quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): The quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): Quantization delay parameters according to the global step. Default: 0.\n\n Inputs:\n - **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.\n\n Outputs:\n Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`.\n\n Examples:\n >>> dense_quant = nn.DenseQuant(3, 6)\n >>> input_x = Tensor(np.random.randint(-2, 2, (2, 3)), mindspore.float32)\n >>> result = dense_quant(input_x)\n \"\"\"\n\n def __init__(\n self,\n in_channels,\n out_channels,\n weight_init='normal',\n bias_init='zeros',\n has_bias=True,\n activation=None,\n per_channel=False,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0):\n super(DenseQuant, self).__init__()\n self.in_channels = check_int_positive(in_channels)\n self.out_channels = check_int_positive(out_channels)\n self.has_bias = check_bool(has_bias)\n\n if isinstance(weight_init, Tensor):\n if weight_init.dim() != 2 or weight_init.shape[0] != out_channels or \\\n weight_init.shape[1] != in_channels:\n raise ValueError(\"weight_init shape error\")\n\n self.weight = Parameter(initializer(\n weight_init, [out_channels, in_channels]), name=\"weight\")\n\n if self.has_bias:\n if isinstance(bias_init, Tensor):\n if bias_init.dim() != 1 or bias_init.shape[0] != out_channels:\n raise ValueError(\"bias_init shape error\")\n\n self.bias = Parameter(initializer(\n bias_init, [out_channels]), name=\"bias\")\n\n self.matmul = P.MatMul(transpose_b=True)\n self.bias_add = P.BiasAdd()\n\n self.activation = get_activation(activation)\n self.activation_flag = self.activation is not None\n self.fake_quant_weight = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=False,\n per_channel=per_channel,\n channel_axis=0,\n num_channels=out_channels,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n\n def construct(self, x):\n \"\"\"Use operators to construct the Dense layer.\"\"\"\n output = self.fake_quant_weight(self.weight)\n output = self.matmul(x, output)\n if self.has_bias:\n output = self.bias_add(output, self.bias)\n if self.activation_flag:\n return self.activation(output)\n return output\n\n def extend_repr(self):\n \"\"\"A pretty print for Dense layer.\"\"\"\n str_info = 'in_channels={}, out_channels={}, weight={}, has_bias={}'.format(\n self.in_channels, self.out_channels, self.weight, self.has_bias)\n if self.has_bias:\n str_info = str_info + ', bias={}'.format(self.bias)\n if self.activation_flag:\n str_info = str_info + ', activation={}'.format(self.activation)\n\n return str_info\n\n\nclass _QuantActivation(Cell):\n r\"\"\"\n Base class for quantization aware training activation function. Add Fake Quant OP after activation OP.\n \"\"\"\n\n def get_origin(self):\n raise NotImplementedError\n\n\nclass ActQuant(_QuantActivation):\n r\"\"\"\n Quantization aware training activation function.\n\n Add the fake quant op to the end of activation op, by which the output of activation op will be truncated.\n Please check `FakeQuantWithMinMax` for more details.\n\n Args:\n activation (Cell): Activation cell class.\n ema_decay (float): Exponential Moving Average algorithm parameter. Default: 0.999.\n per_channel (bool): Quantization granularity based on layer or on channel. Default: False.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): The quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): The quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): Quantization delay parameters according to the global steps. Default: 0.\n\n Inputs:\n - **x** (Tensor) - The input of ReLU6Quant.\n\n Outputs:\n Tensor, with the same type and shape as the `x`.\n\n Examples:\n >>> act_quant = nn.ActQuant(nn.ReLU())\n >>> input_x = Tensor(np.array([[1, 2, -1], [-2, 0, -1]]), mindspore.float32)\n >>> result = act_quant(input_x)\n \"\"\"\n\n def __init__(self,\n activation,\n ema_decay=0.999,\n per_channel=False,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0):\n super(ActQuant, self).__init__()\n self.fake_quant_act = FakeQuantWithMinMax(min_init=0,\n max_init=6,\n ema=True,\n ema_decay=ema_decay,\n per_channel=per_channel,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n self.act = activation\n\n def construct(self, x):\n x = self.act(x)\n x = self.fake_quant_act(x)\n return x\n\n def get_origin(self):\n return self.act\n\n\nclass LeakyReLUQuant(_QuantActivation):\n r\"\"\"\n LeakyReLUQuant activation function. Add Fake Quant OP after HSwish OP.\n\n This part is a more detailed overview of HSwish op.\n\n Args:\n activation (Cell): Activation cell class.\n ema_decay (float): Exponential Moving Average algorithm parameter. Default: 0.999.\n per_channel (bool): Quantization granularity based on layer or on channel. Default: False.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): The quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): The quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): Quantization delay parameters according to the global step. Default: 0.\n\n Inputs:\n - **x** (Tensor) - The input of LeakyReLUQuant.\n\n Outputs:\n Tensor, with the same type and shape as the `x`.\n\n Examples:\n >>> activation = nn.LeakyReLUQuant(nn.LeakyReLU())\n >>> input = Tensor(np.array([[1, 2, 1], [-2, 0, -1]]), mindspore.float32)\n >>> result = activation(input)\n \"\"\"\n\n def __init__(self,\n activation,\n ema_decay=0.999,\n per_channel=False,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0):\n super(LeakyReLUQuant, self).__init__()\n self.fake_quant_act_before = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=True,\n ema_decay=ema_decay,\n per_channel=per_channel,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n self.fake_quant_act_after = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=True,\n ema_decay=ema_decay,\n per_channel=per_channel,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n if issubclass(activation.__class__, nn.LeakyReLU):\n self.act = activation\n else:\n raise ValueError(\"Activation should be `nn.LeakyReLU`\")\n\n def construct(self, x):\n x = self.fake_quant_act_before(x)\n x = self.act(x)\n x = self.fake_quant_act_after(x)\n return x\n\n def get_origin(self):\n return self.act\n\n\nclass HSwishQuant(_QuantActivation):\n r\"\"\"\n HSwishQuant activation function. Add Fake Quant OP after HSwish OP.\n\n This part is a more detailed overview of HSwish op.\n\n Args:\n activation (Cell): Activation cell class.\n ema_decay (float): Exponential Moving Average algorithm parameter. Default: 0.999.\n per_channel (bool): Quantization granularity based on layer or on channel. Default: False.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): Whether the quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): Whether the quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): Quantization delay parameters according to the global step. Default: 0.\n\n Inputs:\n - **x** (Tensor) - The input of HSwishQuant.\n\n Outputs:\n Tensor, with the same type and shape as the `x`.\n\n Examples:\n >>> activation = nn.HSwishQuant(nn.HSwish())\n >>> input = Tensor(np.array([[1, 2, 1], [-2, 0, -1]]), mindspore.float32)\n >>> result = activation(input)\n \"\"\"\n\n def __init__(self,\n activation,\n ema_decay=0.999,\n per_channel=False,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0):\n super(HSwishQuant, self).__init__()\n self.fake_quant_act_before = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=True,\n ema_decay=ema_decay,\n per_channel=per_channel,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n self.fake_quant_act_after = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=True,\n ema_decay=ema_decay,\n per_channel=per_channel,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n if issubclass(activation.__class__, nn.HSwish):\n self.act = activation\n else:\n raise ValueError(\"Activation should be `nn.HSwish`\")\n\n def construct(self, x):\n x = self.fake_quant_act_before(x)\n x = self.act(x)\n x = self.fake_quant_act_after(x)\n return x\n\n def get_origin(self):\n return self.act\n\n\nclass HSigmoidQuant(_QuantActivation):\n r\"\"\"\n HSigmoidQuant activation function. Add Fake Quant OP before and after HSigmoid OP.\n\n This part is a more detailed overview of HSigmoid op.\n\n Args:\n activation (Cell): Activation cell class.\n ema_decay (float): Exponential Moving Average algorithm parameter. Default: 0.999.\n per_channel (bool): Quantization granularity based on layer or on channel. Default: False.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): Whether the quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): Whether the quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): Quantization delay parameters according to the global step. Default: 0.\n\n Inputs:\n - **x** (Tensor) - The input of HSigmoidQuant.\n\n Outputs:\n Tensor, with the same type and shape as the `x`.\n\n Examples:\n >>> activation = nn.HSigmoidQuant(nn.HSigmoid())\n >>> input = Tensor(np.array([[1, 2, 1], [-2, 0, -1]]), mindspore.float32)\n >>> result = activation(input)\n \"\"\"\n\n def __init__(self,\n activation,\n ema_decay=0.999,\n per_channel=False,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0):\n super(HSigmoidQuant, self).__init__()\n self.fake_quant_act_before = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=True,\n ema_decay=ema_decay,\n per_channel=per_channel,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n self.fake_quant_act_after = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=True,\n ema_decay=ema_decay,\n per_channel=per_channel,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n if issubclass(activation.__class__, nn.HSigmoid):\n self.act = activation\n else:\n raise ValueError(\"Activation should be `nn.HSigmoid`\")\n\n def construct(self, x):\n x = self.fake_quant_act_before(x)\n x = self.act(x)\n x = self.fake_quant_act_after(x)\n return x\n\n def get_origin(self):\n return self.act\n\n\nclass TensorAddQuant(Cell):\n r\"\"\"\n Add Fake Quant OP after TensorAdd OP.\n\n This part is a more detailed overview of TensorAdd op.\n\n Args:\n ema_decay (float): Exponential Moving Average algorithm parameter. Default: 0.999.\n per_channel (bool): Quantization granularity based on layer or on channel. Default: False.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): The quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): The quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): Quantization delay parameters according to the global step. Default: 0.\n\n Inputs:\n - **x** (Tensor) - The input of TensorAddQuant.\n\n Outputs:\n Tensor, with the same type and shape as the `x`.\n\n Examples:\n >>> add_quant = nn.TensorAddQuant()\n >>> input_x = Tensor(np.array([[1, 2, 1], [-2, 0, -1]]), mindspore.float32)\n >>> input_y = Tensor(np.random.randint(-2, 2, (2, 3)), mindspore.float32)\n >>> result = add_quant(input_x, input_y)\n \"\"\"\n\n def __init__(self,\n ema_decay=0.999,\n per_channel=False,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0):\n super(TensorAddQuant, self).__init__()\n self.fake_quant_act = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=True,\n ema_decay=ema_decay,\n per_channel=per_channel,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n self.add = P.TensorAdd()\n\n def construct(self, x1, x2):\n x = self.add(x1, x2)\n x = self.fake_quant_act(x)\n return x\n\n\nclass MulQuant(Cell):\n r\"\"\"\n Add Fake Quant OP after Mul OP.\n\n This part is a more detailed overview of Mul op.\n\n Args:\n ema_decay (float): Exponential Moving Average algorithm parameter. Default: 0.999.\n per_channel (bool): Quantization granularity based on layer or on channel. Default: False.\n num_bits (int): The bit number of quantization, supporting 4 and 8bits. Default: 8.\n symmetric (bool): The quantization algorithm is symmetric or not. Default: False.\n narrow_range (bool): The quantization algorithm uses narrow range or not. Default: False.\n quant_delay (int): Quantization delay parameters according to the global step. Default: 0.\n\n Inputs:\n - **x** (Tensor) - The input of MulQuant.\n\n Outputs:\n Tensor, with the same type and shape as the `x`.\n\n \"\"\"\n\n def __init__(self,\n ema_decay=0.999,\n per_channel=False,\n num_bits=8,\n symmetric=False,\n narrow_range=False,\n quant_delay=0):\n super(MulQuant, self).__init__()\n self.fake_quant_act = FakeQuantWithMinMax(min_init=-6,\n max_init=6,\n ema=True,\n ema_decay=ema_decay,\n per_channel=per_channel,\n num_bits=num_bits,\n symmetric=symmetric,\n narrow_range=narrow_range,\n quant_delay=quant_delay)\n self.mul = P.Mul()\n\n def construct(self, x1, x2):\n x = self.mul(x1, x2)\n x = self.fake_quant_act(x)\n return x\n\n\nclass QuantBlock(Cell):\n r\"\"\"\n A quant block of Conv/Dense, activation layer for Ascend deploy.\n\n Calculate Conv or Dense in Int8, with Quant and DeQuant.\n\n Notes:\n This block is only for deploy, and not trainable.\n\n Args:\n in_channels (int): The number of channels in the input space.\n out_channels (int): The number of channels in the output space.\n weight_init (Union[Tensor, str, Initializer, numbers.Number]): The trainable weight_init parameter. The dtype\n is same as input x. The values of str refer to the function `initializer`. Default: 'normal'.\n bias_init (Union[Tensor, str, Initializer, numbers.Number]): The trainable bias_init parameter. The dtype is\n same as input x. The values of str refer to the function `initializer`. Default: 'zeros'.\n has_bias (bool): Specifies whether the layer uses a bias vector. Default: True.\n activation (str): The regularization function applied to the output of the layer, eg. 'relu'. Default: None.\n batchnorm (bool): Specifies to used batchnorm or not. Default: None.\n activation (string): Specifies activation type. The optional values are as following:\n 'softmax', 'logsoftmax', 'relu', 'relu6', 'tanh', 'gelu', 'sigmoid',\n 'prelu', 'leakyrelu', 'hswish', 'hsigmoid'. Default: None.\n\n Inputs:\n - **input** (Tensor) - Tensor of shape :math:`(N, in\\_channels)`.\n\n Outputs:\n Tensor of shape :math:`(N, out\\_channels)`.\n\n Examples:\n >>> net = nn.Dense(3, 4)\n >>> input = Tensor(np.random.randint(0, 255, [2, 3]), mindspore.float32)\n >>> net(input)\n \"\"\"\n\n def __init__(self,\n core_op,\n weight,\n quant_op,\n dequant_op,\n dequant_scale,\n bias=None,\n activation=None):\n super(QuantBlock, self).__init__()\n self.core_op = core_op\n self.weight = weight\n self.quant = quant_op\n self.dequant = dequant_op\n self.dequant_scale = dequant_scale\n self.bias = bias\n self.has_bias = bias is not None\n self.activation = activation\n self.has_act = activation is not None\n if isinstance(activation, ReLU):\n self.activation = None\n self.has_act = False\n self.dequant.add_prim_attr(\"relu_flag\", True)\n self.bias_add = P.BiasAdd()\n\n def construct(self, x):\n x = self.quant(x)\n if self.has_bias:\n x = self.core_op(x, self.weight, self.bias)\n else:\n x = self.core_op(x, self.weight)\n if self.has_act:\n x = self.activation(x)\n x = self.dequant(x, self.dequant_scale)\n return x\n\n def extend_repr(self):\n str_info = f'quant={self.quant}, core_op={type(self.core_op)}, weight=shape[{self.weight.shape}]'\n if self.has_bias:\n str_info = str_info + f', bias=shape[{self.bias.shape}]'\n if self.has_act:\n str_info = str_info + f', activation={self.activation}'\n str_info = str_info + f', dequant={self.dequant}'\n return str_info\n", "# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"\n#################train googlent example on cifar10########################\npython train.py\n\"\"\"\nimport argparse\nimport os\n\nimport numpy as np\n\nimport mindspore.nn as nn\nfrom mindspore import Tensor\nfrom mindspore import context\nfrom mindspore.communication.management import init, get_rank\nfrom mindspore.nn.optim.momentum import Momentum\nfrom mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor\nfrom mindspore.train.loss_scale_manager import DynamicLossScaleManager, FixedLossScaleManager\nfrom mindspore.train.model import Model\nfrom mindspore.context import ParallelMode\nfrom mindspore.train.serialization import load_checkpoint, load_param_into_net\nfrom mindspore.common import set_seed\n\nfrom src.config import cifar_cfg, imagenet_cfg\nfrom src.dataset import create_dataset_cifar10, create_dataset_imagenet\nfrom src.googlenet import GoogleNet\nfrom src.CrossEntropySmooth import CrossEntropySmooth\n\nset_seed(1)\n\ndef lr_steps_cifar10(global_step, lr_max=None, total_epochs=None, steps_per_epoch=None):\n \"\"\"Set learning rate.\"\"\"\n lr_each_step = []\n total_steps = steps_per_epoch * total_epochs\n decay_epoch_index = [0.3 * total_steps, 0.6 * total_steps, 0.8 * total_steps]\n for i in range(total_steps):\n if i < decay_epoch_index[0]:\n lr_each_step.append(lr_max)\n elif i < decay_epoch_index[1]:\n lr_each_step.append(lr_max * 0.1)\n elif i < decay_epoch_index[2]:\n lr_each_step.append(lr_max * 0.01)\n else:\n lr_each_step.append(lr_max * 0.001)\n current_step = global_step\n lr_each_step = np.array(lr_each_step).astype(np.float32)\n learning_rate = lr_each_step[current_step:]\n\n return learning_rate\n\n\ndef lr_steps_imagenet(_cfg, steps_per_epoch):\n \"\"\"lr step for imagenet\"\"\"\n from src.lr_scheduler.warmup_step_lr import warmup_step_lr\n from src.lr_scheduler.warmup_cosine_annealing_lr import warmup_cosine_annealing_lr\n if _cfg.lr_scheduler == 'exponential':\n _lr = warmup_step_lr(_cfg.lr_init,\n _cfg.lr_epochs,\n steps_per_epoch,\n _cfg.warmup_epochs,\n _cfg.epoch_size,\n gamma=_cfg.lr_gamma,\n )\n elif _cfg.lr_scheduler == 'cosine_annealing':\n _lr = warmup_cosine_annealing_lr(_cfg.lr_init,\n steps_per_epoch,\n _cfg.warmup_epochs,\n _cfg.epoch_size,\n _cfg.T_max,\n _cfg.eta_min)\n else:\n raise NotImplementedError(_cfg.lr_scheduler)\n\n return _lr\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Classification')\n parser.add_argument('--dataset_name', type=str, default='cifar10', choices=['imagenet', 'cifar10'],\n help='dataset name.')\n parser.add_argument('--device_id', type=int, default=None, help='device id of GPU or Ascend. (Default: None)')\n args_opt = parser.parse_args()\n\n if args_opt.dataset_name == \"cifar10\":\n cfg = cifar_cfg\n elif args_opt.dataset_name == \"imagenet\":\n cfg = imagenet_cfg\n else:\n raise ValueError(\"Unsupport dataset.\")\n\n # set context\n device_target = cfg.device_target\n\n context.set_context(mode=context.GRAPH_MODE, device_target=cfg.device_target)\n device_num = int(os.environ.get(\"DEVICE_NUM\", 1))\n\n if device_target == \"Ascend\":\n if args_opt.device_id is not None:\n context.set_context(device_id=args_opt.device_id)\n else:\n context.set_context(device_id=cfg.device_id)\n\n if device_num > 1:\n context.reset_auto_parallel_context()\n context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,\n gradients_mean=True)\n init()\n elif device_target == \"GPU\":\n init()\n\n if device_num > 1:\n context.reset_auto_parallel_context()\n context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,\n gradients_mean=True)\n else:\n raise ValueError(\"Unsupported platform.\")\n\n if args_opt.dataset_name == \"cifar10\":\n dataset = create_dataset_cifar10(cfg.data_path, 1)\n elif args_opt.dataset_name == \"imagenet\":\n dataset = create_dataset_imagenet(cfg.data_path, 1)\n else:\n raise ValueError(\"Unsupport dataset.\")\n\n batch_num = dataset.get_dataset_size()\n\n net = GoogleNet(num_classes=cfg.num_classes)\n # Continue training if set pre_trained to be True\n if cfg.pre_trained:\n param_dict = load_checkpoint(cfg.checkpoint_path)\n load_param_into_net(net, param_dict)\n\n loss_scale_manager = None\n if args_opt.dataset_name == 'cifar10':\n lr = lr_steps_cifar10(0, lr_max=cfg.lr_init, total_epochs=cfg.epoch_size, steps_per_epoch=batch_num)\n opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()),\n learning_rate=Tensor(lr),\n momentum=cfg.momentum,\n weight_decay=cfg.weight_decay)\n loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')\n\n elif args_opt.dataset_name == 'imagenet':\n lr = lr_steps_imagenet(cfg, batch_num)\n\n\n def get_param_groups(network):\n \"\"\" get param groups \"\"\"\n decay_params = []\n no_decay_params = []\n for x in network.trainable_params():\n parameter_name = x.name\n if parameter_name.endswith('.bias'):\n # all bias not using weight decay\n # print('no decay:{}'.format(parameter_name))\n no_decay_params.append(x)\n elif parameter_name.endswith('.gamma'):\n # bn weight bias not using weight decay, be carefully for now x not include BN\n # print('no decay:{}'.format(parameter_name))\n no_decay_params.append(x)\n elif parameter_name.endswith('.beta'):\n # bn weight bias not using weight decay, be carefully for now x not include BN\n # print('no decay:{}'.format(parameter_name))\n no_decay_params.append(x)\n else:\n decay_params.append(x)\n\n return [{'params': no_decay_params, 'weight_decay': 0.0}, {'params': decay_params}]\n\n\n if cfg.is_dynamic_loss_scale:\n cfg.loss_scale = 1\n\n opt = Momentum(params=get_param_groups(net),\n learning_rate=Tensor(lr),\n momentum=cfg.momentum,\n weight_decay=cfg.weight_decay,\n loss_scale=cfg.loss_scale)\n if not cfg.use_label_smooth:\n cfg.label_smooth_factor = 0.0\n loss = CrossEntropySmooth(sparse=True, reduction=\"mean\",\n smooth_factor=cfg.label_smooth_factor, num_classes=cfg.num_classes)\n\n if cfg.is_dynamic_loss_scale == 1:\n loss_scale_manager = DynamicLossScaleManager(init_loss_scale=65536, scale_factor=2, scale_window=2000)\n else:\n loss_scale_manager = FixedLossScaleManager(cfg.loss_scale, drop_overflow_update=False)\n\n if device_target == \"Ascend\":\n model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc'},\n amp_level=\"O2\", keep_batchnorm_fp32=False, loss_scale_manager=loss_scale_manager)\n ckpt_save_dir = \"./\"\n else: # GPU\n model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc'},\n amp_level=\"O2\", keep_batchnorm_fp32=True, loss_scale_manager=loss_scale_manager)\n ckpt_save_dir = \"./ckpt_\" + str(get_rank()) + \"/\"\n\n config_ck = CheckpointConfig(save_checkpoint_steps=batch_num * 5, keep_checkpoint_max=cfg.keep_checkpoint_max)\n time_cb = TimeMonitor(data_size=batch_num)\n ckpoint_cb = ModelCheckpoint(prefix=\"train_googlenet_\" + args_opt.dataset_name, directory=ckpt_save_dir,\n config=config_ck)\n loss_cb = LossMonitor()\n model.train(cfg.epoch_size, dataset, callbacks=[time_cb, ckpoint_cb, loss_cb])\n print(\"train success\")\n" ]
[ [ "matplotlib.pyplot.title", "matplotlib.pyplot.scatter", "sklearn.manifold.TSNE", "numpy.mean", "matplotlib.pyplot.figure" ], [ "numpy.array", "numpy.random.randn", "numpy.random.rand" ], [ "numpy.ones" ], [ "numpy.zeros", "numpy.ones" ], [ "numpy.array" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
khasbilegt/coin-detector
[ "23dcd76e60aa9320a7b3252fcf5b9fa58b4d48af" ]
[ "coins.py" ]
[ "import math\n\nimport cv2 as cv\nimport matplotlib.pyplot as plt\n\n\ncircleAreas = []\ncircleCenters = []\ncircles = {}\ncoins = {\"500\": 0, \"100\": 0, \"50\": 0, \"10\": 0, \"5\": 0, \"1\": 0}\n\noriginal = cv.imread(\"coins.jpg\")\nimg = original.copy()\nimg = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\nimg = cv.medianBlur(img, 5)\n\nret, thresh = cv.threshold(img, 50, 255, cv.THRESH_BINARY_INV)\ncontours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\nsorted_ctrs = sorted(contours, key=lambda ctr: cv.boundingRect(ctr)[0])\n\nfor i, ctr in enumerate(sorted_ctrs):\n epsilon = 0.001 * cv.arcLength(ctr, True)\n approx = cv.approxPolyDP(ctr, epsilon, True)\n\n if len(approx) > 80:\n cv.drawContours(original, approx, -1, (0, 0, 255), 3)\n (x, y), radius = cv.minEnclosingCircle(ctr)\n if thresh[int(y)][int(x)] != 0:\n area = int(math.pi * (radius ** 2))\n circles[radius] = (int(x), int(y))\n fontColor = (0, 0, 0)\n imgcenter = (int(x - 15), int(y - 10))\n font = cv.FONT_HERSHEY_SIMPLEX\n\n if area > 7500:\n coins[\"500\"] += 1\n text = \"500\"\n fontColor = (255, 255, 255)\n elif 7500 > area >= 6300:\n coins[\"100\"] += 1\n text = \"100\"\n fontColor = (0, 0, 255)\n elif 6300 > area >= 5500:\n coins[\"10\"] += 1\n text = \"10\"\n fontColor = (255, 255, 88)\n elif 5500 > area >= 5000:\n coins[\"50\"] += 1\n text = \"50\"\n fontColor = (255, 0, 120)\n elif 5000 > area >= 3800:\n coins[\"5\"] += 1\n text = \"5\"\n fontColor = (0, 255, 0)\n elif area < 3800:\n coins[\"1\"] += 1\n text = \"1\"\n fontColor = (88, 255, 255)\n# cv.putText(original, str(text), imgcenter, font, 0.6, fontColor, 2)\n# cv.putText(original, str(\"{}: {}\".format(text, int(radius))), imgcenter, font, 0.6, fontColor, 2)\n# cv.circle(original, (int(x), int(y)), int(radius), fontColor, 2)\n# cv.rectangle(original, (int(x), int(y)), (int(x)+5,int(y)+5), fontColor, 5)\n\nplt.title(\n \"Detected coins | 500: {0}, 100: {1}, 50: {2}, 10: {3}, 1: {4}\".format(\n coins[\"500\"], coins[\"100\"], coins[\"50\"], coins[\"10\"], coins[\"1\"]\n )\n)\nplt.imshow(cv.cvtColor(original, cv.COLOR_BGR2RGB))\nplt.show()\n" ]
[ [ "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]