repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
osin-vladimir/kaggle-hpa-image-classification
[ "8a6da80f875b7eb8d017667d76191f31cf2afeae" ]
[ "protein_get_data.py" ]
[ "import xml.etree.ElementTree as etree\nimport pandas as pd\nfrom collections import defaultdict\nfrom tqdm import tqdm\n\nPROTEINATLAS_XML_PATH = \"../../../../kaggle_protein_atlas/input_data/proteinatlas.xml\"\nTRAIN_EXTRA_PATH = \"../../../../kaggle_protein_atlas/input_data/hpa_website_set.csv\"\n\ncounter = 0\ndata = []\nother_labels = defaultdict(int)\n\nname_to_label_dict = {\n 'nucleoplasm' : 0,\n 'nuclear membrane' : 1,\n 'nucleoli' : 2,\n 'nucleoli fibrillar center' : 3,\n 'nuclear speckles' : 4,\n 'nuclear bodies' : 5,\n 'endoplasmic reticulum' : 6,\n 'golgi apparatus' : 7,\n 'peroxisomes' : 8,\n 'endosomes' : 9,\n 'lysosomes' : 10,\n 'intermediate filaments' : 11,\n 'actin filaments' : 12,\n 'focal adhesion sites' : 13,\n 'microtubules' : 14,\n 'microtubule ends' : 15,\n 'cytokinetic bridge' : 16,\n 'mitotic spindle' : 17,\n 'microtubule organizing center' : 18,\n 'centrosome' : 19,\n 'lipid droplets' : 20,\n 'plasma membrane' : 21,\n 'cell junctions' : 22,\n 'mitochondria' : 23,\n 'aggresome' : 24,\n 'cytosol' : 25,\n 'cytoplasmic bodies' : 26,\n 'rods & rings' : 27,\n 'vesicles' : 28,\n 'nucleus' : 29,\n 'midbody' : 30,\n 'midbody ring' : 31,\n 'cleavage furrow' : 32\n }\n\n# Iterate over the XML file (since parsing it in one run might blow up the memory)\nfor event, elem in tqdm(etree.iterparse(PROTEINATLAS_XML_PATH, events=('start', 'end', 'start-ns', 'end-ns'))):\n if event == 'start':\n if elem.tag == \"data\" and len({\"location\", \"assayImage\"} - set([c.tag for c in elem.getchildren()])) == 0:\n labels = []\n assay_image = None\n for c in elem.getchildren():\n if c.tag == 'assayImage':\n assay_image = c\n if c.tag == 'location':\n if c.text in name_to_label_dict:\n label = name_to_label_dict[c.text]\n if type(label) is int:\n labels.append(label)\n else:\n for l in label:\n labels.append(l)\n else:\n other_labels[c.text] += 1\n\n if not labels:\n # Let's ignore images that do not have labels\n continue\n\n for image in assay_image.getchildren():\n if len(image.getchildren()) < 4 or image.getchildren()[-1].text is None:\n continue\n image_url = image.getchildren()[-1].text\n\n assert \"blue_red_green\" in image_url\n\n for channel, color, object_ in zip(image.getchildren()[:-1], [\"blue\", \"red\", \"green\"],\n [\"nucleus\", \"microtubules\", \"antibody\"]):\n assert channel.text == object_\n assert channel.attrib[\"color\"] == color\n\n # \"https://v18.proteinatlas.org/images/4109/24_H11_1_blue_red_green_yellow.jpg\" -> \"4109/24_H11_1\"\n data.append([\"/\".join(image_url.split(\"/\")[-2:]).replace(\"_blue_red_green.jpg\", \"\"),\n \" \".join(str(x) for x in sorted(labels, reverse=True))])\n counter += 1\n\n # This is necessary to free up memory\n elem.clear()\n\n\nprint(counter)\nprint(other_labels)\n\ndf = pd.DataFrame(data=data, columns=[\"Id\", \"Target\"])\ndf.to_csv(TRAIN_EXTRA_PATH, index=False)" ]
[ [ "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": [] } ]
zhawhjw/yolact-interpret
[ "c9cc6d2eca0c6920f7465a4dc585e8da226f5fa8" ]
[ "data/__init__.py" ]
[ "from .config import *\nfrom .coco import COCODetection, COCOAnnotationTransform, get_label_map\n\nimport torch\nimport cv2\nimport numpy as np\n\n\ndef detection_collate(batch):\n \"\"\"Custom collate fn for dealing with batches of images that have a different\n number of associated object annotations (bounding boxes).\n\n Arguments:\n batch: (tuple) A tuple of tensor images and (lists of annotations, masks)\n\n Return:\n A tuple containing:\n 1) (tensor) batch of images stacked on their 0 dim\n 2) (list<tensor>, list<tensor>, list<int>) annotations for a given image are stacked\n on 0 dim. The output gt is a tuple of annotations and masks.\n \"\"\"\n targets = []\n imgs = []\n masks = []\n num_crowds = []\n names = []\n flags = []\n\n for sample in batch:\n\n imgs.append(sample[0])\n targets.append(torch.FloatTensor(sample[1][0]))\n masks.append(torch.FloatTensor(sample[1][1]))\n\n # if sample[0] is None:\n # pass\n # else:\n # imgs = torch.stack(imgs, 0)\n #\n # if sample[1][0] is None:\n # targets.append(None)\n # else:\n # targets.append(torch.FloatTensor(sample[1][0]))\n #\n # if sample[1][1] is None:\n # masks.append(None)\n # else:\n # masks.append(torch.FloatTensor(sample[1][1]))\n\n num_crowds.append(sample[1][2])\n names.append(sample[1][3])\n flags.append(sample[1][4])\n\n return torch.stack(imgs, 0), (targets, masks, num_crowds, names, flags)\n" ]
[ [ "torch.stack", "torch.FloatTensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SushritPasupuleti/Braggi-A-Python-Based-Contextual-Chatbot-Framework
[ "c81fa4bb0551d2d32fedc5c5d5fbf17940f5d2b1" ]
[ "Text_Processing_Engine.py" ]
[ "#%%\nimport nltk\nfrom nltk.stem.lancaster import LancasterStemmer\nimport json\nimport numpy as np\nimport random\n\nstemmer = LancasterStemmer()\n\ndef intents_loader():\n '''Imports the Main \"intents.json\" File.'''\n with open('./Intent_Models/intents.json') as json_data:\n intents = json.load(json_data)\n return intents\n\ndef intents_parser(intents):\n '''Preprocess the \"intents.json\" file to prepare the dataset for training and analysis.'''\n words = []\n intent_classes = []\n sentences_corpus = []\n ignore_words = ['?','!']\n\n # loop through each sentence in our intents' patterns\n for intent in intents['intents']:\n for pattern in intent['patterns']:\n # tokenize the sentences\n word = nltk.word_tokenize(pattern)\n words.extend(word)\n sentences_corpus.append((word, intent['tag']))\n\n if intent['tag'] not in intent_classes:\n intent_classes.append(intent['tag'])\n\n # stem and lower each word from the word list \n # remove duplicates\n words = [stemmer.stem(word.lower()) for word in words if word not in ignore_words]\n words = sorted(list(set(words)))\n intent_classes = sorted(list(set(intent_classes)))\n\n return words, intent_classes, sentences_corpus\n\ndef stem_sentence(sentence_corpus):\n '''Toeknize and Stem all the sentences'''\n sentence_words = nltk.word_tokenize(sentence_corpus)\n sentence_words = [stemmer.stem(word.lower()) for word in sentence_words]\n return sentence_words\n\ndef bag_of_words(sentence_corpus, words, debug=False):\n '''Create the bag of words. A one hot coded input matrix.'''\n sentence_words = stem_sentence(sentence_corpus)\n bag = [0]*len(words)\n\n for s in sentence_words:\n for i,w in enumerate(words):\n if w==s:\n bag[i] = 1\n if debug:\n print(\"found\",w)\n\n return(np.array(bag))\n\ndef init_training_data(words, intent_classes, sentence_corpus):\n '''Initialize the training data for the Deep Neural Network'''\n training = []\n output = []\n output_empty = [0] * len(intent_classes)\n\n for doc in sentence_corpus:\n bag = []\n pattern_words = doc[0]\n pattern_words = [stemmer.stem(word.lower()) for word in pattern_words]\n for word in words:\n bag.append(1) if word in pattern_words else bag.append(0)\n\n output_row = list(output_empty)\n output_row[intent_classes.index(doc[1])] = 1\n \n training.append([bag, output_row])\n\n random.shuffle(training)\n training = np.array(training)\n\n train_x = list(training[:,0])\n train_y = list(training[:,1])\n return train_x, train_y\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
claforte/nevergrad
[ "a06ae7ccf312392a7de4e90f93084834a5a978f0" ]
[ "nevergrad/optimization/test_base.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport warnings\nfrom unittest import TestCase\nfrom typing import List, Tuple\nimport genty\nimport numpy as np\nfrom ..common import testing\nfrom .base import OptimizationPrinter\nfrom . import optimizerlib\n\n\nclass CounterFunction:\n\n def __init__(self) -> None:\n self.count = 0\n\n def __call__(self, value: optimizerlib.base.ArrayLike) -> float:\n assert len(value) == 1\n self.count += 1\n return (value[0] - 1)**2\n\n\nclass LoggingOptimizer(optimizerlib.base.Optimizer):\n\n def __init__(self, num_workers: int = 1) -> None:\n super().__init__(dimension=1, budget=5, num_workers=num_workers)\n self.logs: List[str] = []\n\n def _internal_ask(self) -> optimizerlib.base.ArrayLike:\n self.logs.append(f\"s{self._num_suggestions}\") # s for suggest\n return np.array((self._num_suggestions,))\n\n def _internal_tell(self, x: optimizerlib.base.ArrayLike, value: float) -> None:\n self.logs.append(f\"u{x[0]}\") # u for update\n\n\[email protected]\nclass OptimizationTests(TestCase):\n\n @genty.genty_dataset( # type: ignore\n w1_batch=(1, True, ['s0', 'u0', 's1', 'u1', 's2', 'u2', 's3', 'u3', 's4', 'u4']),\n w1_steady=(1, False, ['s0', 'u0', 's1', 'u1', 's2', 'u2', 's3', 'u3', 's4', 'u4']), # no difference (normal, since worker=1)\n w3_batch=(3, True, ['s0', 's1', 's2', 'u0', 'u1', 'u2', 's3', 's4', 'u3', 'u4']),\n w3_steady=(3, False, ['s0', 's1', 's2', 'u0', 'u1', 'u2', 's3', 's4', 'u3', 'u4']), # not really steady TODO change this behavior\n # w3_steady=(3, False, ['s0', 's1', 's2', 'u0', 's3', 'u1', 's4', 'u2', 'u3', 'u4']), # This is what we would like\n )\n def test_batch_and_steady_optimization(self, num_workers: int, batch_mode: bool, expected: List[Tuple[str, float]]) -> None:\n # tests the suggestion (s) and update (u) patterns\n # the w3_steady is unexpected. It is designed to be efficient with a non-sequential executor, but because\n # of it, it is acting like batch mode when sequential...\n optim = LoggingOptimizer(num_workers=num_workers)\n func = CounterFunction()\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n optim.optimize(func, verbosity=2, batch_mode=batch_mode)\n testing.printed_assert_equal(optim.logs, expected)\n\n\ndef test_base_optimizer() -> None:\n zeroptim = optimizerlib.Zero(dimension=2, budget=4, num_workers=1)\n representation = repr(zeroptim)\n assert \"dimension=2\" in representation, f\"Unexpected representation: {representation}\"\n np.testing.assert_equal(zeroptim.ask(), [0, 0])\n zeroptim.tell([0, 0], 0)\n zeroptim.tell([1, 1], 1)\n np.testing.assert_equal(zeroptim.provide_recommendation(), [0, 0])\n # check that the best value is updated if a second evaluation is not as good\n zeroptim.tell([0, 0], 10)\n zeroptim.tell([1, 1], 1)\n np.testing.assert_equal(zeroptim.provide_recommendation(), [1, 1])\n np.testing.assert_equal(zeroptim._num_suggestions, 1)\n\n\ndef test_optimize() -> None:\n optimizer = optimizerlib.OnePlusOne(dimension=1, budget=100, num_workers=5)\n optimizer.register_callback(\"tell\", OptimizationPrinter(num_eval=10, num_sec=.1))\n func = CounterFunction()\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n result = optimizer.optimize(func, verbosity=2)\n np.testing.assert_almost_equal(result[0], 1, decimal=2)\n np.testing.assert_equal(func.count, 100)\n # check compatibility\n x = optimizer.suggest_exploration()\n optimizer.update_with_fitness_value(x, 12)\n" ]
[ [ "numpy.testing.assert_equal", "numpy.array", "numpy.testing.assert_almost_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lsst-camera-dh/EO-utilities
[ "28418284fdaf2b2fb0afbeccd4324f7ad3e676c8" ]
[ "python/lsst/eo_utils/flat/flat_oscan.py" ]
[ "\"\"\"Class to analyze the FFT of the bias frames\"\"\"\n\nimport numpy as np\n\n#from lsst.eotest.sensor.overscan_fit import OverscanFit\n\nfrom lsst.eo_utils.base.config_utils import EOUtilOptions\n\nfrom lsst.eo_utils.base.data_utils import TableDict\n\nfrom lsst.eo_utils.base.butler_utils import make_file_dict\n\nfrom lsst.eo_utils.base.iter_utils import AnalysisBySlot\n\nfrom lsst.eo_utils.base.factory import EO_TASK_FACTORY\n\nfrom .analysis import FlatAnalysisConfig, FlatAnalysisTask\n\nclass FlatOverscanConfig(FlatAnalysisConfig):\n \"\"\"Configuration for FlatFlatOverscanTask\"\"\"\n filekey = EOUtilOptions.clone_param('filekey', default='flat-oscan')\n num_oscan_pixels = EOUtilOptions.clone_param('num_oscan_pixels')\n minflux = EOUtilOptions.clone_param('minflux')\n maxflux = EOUtilOptions.clone_param('maxflux')\n\n\nclass FlatOverscanTask(FlatAnalysisTask):\n \"\"\"Estimate the deffered charge by analyzing the overscan in flat frames\"\"\"\n\n ConfigClass = FlatOverscanConfig\n _DefaultName = \"FlatOverscanTask\"\n iteratorClass = AnalysisBySlot\n\n maxflux = 150000.\n xmax = 512\n\n plot_names = ['eper', 'overscan1', 'overscan2', 'summed', 'cti', 'noise']\n\n def extract(self, butler, data, **kwargs):\n \"\"\"Extract the data from the overscan region\n to estimate the deffered charge\n\n Parameters\n ----------\n butler : `Butler`\n The data butler\n data : `dict`\n Dictionary (or other structure) contain the input data\n kwargs\n Used to override default configuration\n\n Returns\n -------\n dtables : `TableDict`\n The resulting data\n \"\"\"\n self.safe_update(**kwargs)\n\n if butler is not None:\n raise ValueError(\"FlatOverscanTask not implemented for Butlerized data\")\n\n flat_files = data['FLAT1']\n\n mask_files = self.get_mask_files()\n superbias_frame = self.get_superbias_frame(mask_files)\n\n self.log_info_slot_msg(self.config, \"%i files\" % len(flat_files))\n\n #fitter = OverscanFit(num_oscan_pixels=self.config.num_oscan_pixels,\n # minflux=self.config.minflux, maxflux=self.config.maxflux)\n\n gains = self.get_gains()\n if gains is None:\n gains = np.ones((17))\n\n # Analysis goes here, you should fill data_dict with data extracted\n # by the analysis\n\n for ifile, flat_id in enumerate(flat_files):\n\n if ifile % 10 == 0:\n self.log_progress(\" %i\" % ifile)\n\n flat = self.get_ccd(butler, flat_id, mask_files, bias_frame=superbias_frame)\n fitter.process_image(flat, gains)\n\n self.xmax = fitter.xmax_val\n\n self.log_progress(\"Done!\")\n\n data_dict = fitter.build_output_dict()\n\n primary = fitter.output[0]\n primary.header['NAMPS'] = 16\n\n dtables = TableDict(primary=primary)\n for key, val in data_dict.items():\n dtables.make_datatable(key.lower(), val)\n dtables.make_datatable('files', make_file_dict(butler, flat_files))\n\n return dtables\n\n\n def plot(self, dtables, figs, **kwargs):\n \"\"\"Make plots of the overscan data to study\n the deffered charge\n\n Parameters\n ----------\n dtables : `TableDict`\n The data produced by this task\n figs : `FigureDict`\n The resulting figures\n kwargs\n Used to override default configuration\n \"\"\"\n self.safe_update(**kwargs)\n\n self.epr_plot(dtables, figs)\n self.overscan1_plot(dtables, figs)\n self.overscan2_plot(dtables, figs)\n self.summedoverscan_plot(dtables, figs)\n self.cti_plot(dtables, figs)\n self.noise_plot(dtables, figs)\n\n\n def epr_plot(self, dtables, figs):\n \"\"\"Plot the data showing the signal levels\n\n Parameters\n ----------\n dtables : `TableDict`\n The data produced by this task\n figs : `FigureDict`\n The resulting figures\n \"\"\"\n figs.setup_amp_plots_grid('eper', title='Mean Overscans',\n xlabel=\"Overscan Pixel Number\", ylabel=\"Signal [e-]\",\n ymin=-2, ymax=300.)\n\n target_flux_levels = [100, 1000, 10000, 25000, 50000, 75000, 100000]\n\n for i, amp in enumerate(range(1, 17)):\n\n target_flux_index = 0\n data = dtables['amp{0:02d}'.format(amp)]\n\n sorted_indices = np.argsort(data['FLUX'])\n\n axs = figs.get_amp_axes('eper', i)\n\n for row in sorted_indices:\n\n flux = data['FLUX'][row]\n\n if flux <= target_flux_levels[target_flux_index]:\n continue\n\n meanrow = data['MEANROW'][row, :]\n offset = np.mean(meanrow[-20:])\n overscan = meanrow[self.xmax:] - offset\n columns = np.arange(self.xmax, meanrow.shape[0])\n\n axs.plot(columns, overscan, label='{0:d} e-'.format(int(round(flux, -2))))\n axs.set_yscale('symlog', linthreshy=1.0)\n axs.set_yticklabels([r'$-1$', '0', '1', r'$10^{1}$', r'$10^{2}$'])\n axs.grid(True, which='major', axis='both')\n axs.tick_params(axis='both', which='minor')\n\n leg_h, leg_l = axs.get_legend_handles_labels()\n\n target_flux_index += 1\n if target_flux_index == len(target_flux_levels):\n break\n\n fig = figs.get_figure('eper')\n\n fig.subplots_adjust(bottom=0.13)\n fig.legend(leg_h, leg_l, loc='lower center', ncol=len(target_flux_levels))\n\n\n def overscan1_plot(self, dtables, figs):\n \"\"\"Plot the data showing the signal in the first overscan pixel\n\n Parameters\n ----------\n dtables : `TableDict`\n The data produced by this task\n figs : `FigureDict`\n The resulting figures\n \"\"\"\n f_dict = figs.setup_figure('overscan1',\n xlabel='Flux [e-]',\n ylabel='First Overscan [e-]')\n\n axs = f_dict['axes']\n\n for i, amp in enumerate(range(1, 17)):\n\n if i >= 10:\n marker = 's'\n else:\n marker = '^'\n\n data = dtables['amp{0:02d}'.format(amp)]\n\n sorted_indices = np.argsort(data['FLUX'])\n\n offset = np.mean(data['MEANROW'][sorted_indices, -20:], axis=1)\n overscan1 = data['MEANROW'][sorted_indices, self.xmax] - offset\n flux = data['FLUX'][sorted_indices] - offset\n\n axs.plot(flux[flux <= self.maxflux], overscan1[flux <= self.maxflux],\n label=\"amp {0}\".format(i+1), marker=marker)\n\n axs.set_ylim(bottom=-1.0)\n axs.set_xlim(left=50)\n axs.set_yscale('symlog', threshold=1.0)\n axs.set_xscale('log')\n axs.grid(True, which='major', axis='both')\n\n leg_h, leg_l = axs.get_legend_handles_labels()\n axs.legend(leg_h, leg_l, loc='upper left', ncol=4, fontsize=12)\n\n\n def overscan2_plot(self, dtables, figs):\n \"\"\"Plot the data showing the signal in the second overscan pixel\n\n Parameters\n ----------\n dtables : `TableDict`\n The data produced by this task\n figs : `FigureDict`\n The resulting figures\n \"\"\"\n f_dict = figs.setup_figure('overscan2',\n xlabel='Flux [e-]',\n ylabel='Second Overscan [e-]')\n\n axs = f_dict['axes']\n axs.grid(True, which='major', axis='both')\n\n for i, amp in enumerate(range(1, 17)):\n\n if i >= 10:\n marker = 's'\n else:\n marker = '^'\n\n data = dtables['amp{0:02d}'.format(amp)]\n\n sorted_indices = np.argsort(data['FLUX'])\n\n offset = np.mean(data['MEANROW'][sorted_indices, -20:], axis=1)\n overscan2 = data['MEANROW'][sorted_indices, self.xmax+1] - offset\n flux = data['FLUX'][sorted_indices] - offset\n\n axs.plot(flux[flux <= self.maxflux], overscan2[flux <= self.maxflux],\n label=\"Amp {0}\".format(i+1), marker=marker)\n\n axs.set_yscale('symlog', threshold=1.0)\n axs.set_xscale('log')\n axs.set_ylim(bottom=-1.0)\n axs.set_xlim(left=50)\n\n leg_h, leg_l = axs.get_legend_handles_labels()\n axs.legend(leg_h, leg_l, loc='upper left', ncol=4, fontsize=12)\n\n\n def summedoverscan_plot(self, dtables, figs):\n \"\"\"Plot the data showing summed signal in the overscan region\n\n Parameters\n ----------\n dtables : `TableDict`\n The data produced by this task\n figs : `FigureDict`\n The resulting figures\n \"\"\"\n f_dict = figs.setup_figure('summed',\n title='Summed Overscan [8:18]',\n xlabel='Flux [e-]',\n ylabel='Summed Overscan [e-]')\n\n axs = f_dict['axes']\n\n for i, amp in enumerate(range(1, 17)):\n\n if i >= 10:\n marker = 's'\n else:\n marker = '^'\n\n data = dtables['amp{0:02d}'.format(amp)]\n\n sorted_indices = np.argsort(data['FLUX'])\n\n offset = np.mean(data['MEANROW'][sorted_indices, -20:], axis=1)\n summedoverscan = np.sum(data['MEANROW'][sorted_indices, self.xmax+8:self.xmax+18],\n axis=1) - offset\n flux = data['FLUX'][sorted_indices] - offset\n\n axs.plot(flux[flux <= self.maxflux], summedoverscan[flux <= self.maxflux],\n label=\"Amp {0}\".format(i+1), marker=marker)\n\n axs.set_yscale('symlog', threshold=1.0)\n axs.set_xscale('log')\n axs.set_ylim(bottom=-1.0)\n axs.set_xlim(left=50)\n axs.grid(True, which='major', axis='both')\n leg_h, leg_l = axs.get_legend_handles_labels()\n axs.legend(leg_h, leg_l, loc='upper left', ncol=4, fontsize=12)\n\n\n def cti_plot(self, dtables, figs):\n \"\"\"Plot the data showing the charge transfer inefficiency\n\n Parameters\n ----------\n dtables : `TableDict`\n The data produced by this task\n figs : `FigureDict`\n The resulting figures\n \"\"\"\n f_dict = figs.setup_figure('cti',\n title='CTI from EPER',\n xlabel='Flux [e-]',\n ylabel='Summed Overscan [e-]')\n\n axs = f_dict['axes']\n\n for i, amp in enumerate(range(1, 17)):\n\n if i >= 10:\n marker = 's'\n else:\n marker = '^'\n\n data = dtables['amp{0:02d}'.format(amp)]\n sorted_indices = np.argsort(data['FLUX'])\n\n offset = np.mean(data['MEANROW'][sorted_indices, -20:], axis=1)\n overscan1 = data['MEANROW'][sorted_indices, self.xmax] - offset\n overscan2 = data['MEANROW'][sorted_indices, self.xmax + 1] - offset\n lastpixel = data['MEANROW'][sorted_indices, self.xmax - 1] - offset\n cti = (overscan1 + overscan2)/(self.xmax * lastpixel)\n flux = data['FLUX'][sorted_indices] - offset\n\n axs.loglog(lastpixel[flux <= self.maxflux], cti[flux <= self.maxflux],\n label=\"Amp {0}\".format(i+1), marker=marker)\n\n axs.axhline(y=0.000005, color='black', linestyle='--')\n axs.set_ylim(bottom=5E-8, top=2E-4)\n axs.set_xlim(left=50.0)\n axs.grid(True, which='major', axis='both')\n\n leg_h, leg_l = axs.get_legend_handles_labels()\n axs.legend(leg_h, leg_l, loc='upper left', ncol=4, fontsize=12)\n\n\n def noise_plot(self, dtables, figs):\n \"\"\"Plot the data showing the overscan noise\n\n Parameters\n ----------\n dtables : `TableDict`\n The data produced by this task\n figs : `FigureDict`\n The resulting figures\n \"\"\"\n f_dict = figs.setup_figure('noise',\n title='Overscan Noise vs. Flux',\n xlabel='Flux [e-]',\n ylabel='Overscan Noise [e-]')\n axs = f_dict['axes']\n\n for i, amp in enumerate(range(1, 17)):\n\n if i >= 10:\n marker = 's'\n else:\n marker = '^'\n\n data = dtables['amp{0:02d}'.format(amp)]\n sorted_indices = np.argsort(data['FLUX'])\n\n noise = data['NOISE'][sorted_indices]\n flux = data['FLUX'][sorted_indices]\n\n axs.semilogx(flux[flux <= self.maxflux], noise[flux <= self.maxflux],\n label=\"Amp {0}\".format(i+1), marker=marker)\n\n axs.set_ylim(0.0, 10.0)\n axs.grid(True, which='major', axis='both')\n\n leg_h, leg_l = axs.get_legend_handles_labels()\n axs.legend(leg_h, leg_l, loc='lower right', ncol=4, fontsize=12)\n\n\n\nEO_TASK_FACTORY.add_task_class('FlatOverscan', FlatOverscanTask)\n" ]
[ [ "numpy.arange", "numpy.ones", "numpy.mean", "numpy.argsort", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nateagr/ml-hadoop-experiment
[ "a821199f5321019d6e2bcfb9c4979b66d2d14324" ]
[ "tests/tensorflow/test_numpy_to_sparse_tensors.py" ]
[ "import pytest\nimport numpy as np\n\nfrom ml_hadoop_experiment.tensorflow import (\n numpy_to_sparse_tensors\n)\n\n\[email protected](\"sizes,expected\", [\n ([2, 3], [0, 1, 0, 1, 2]),\n ([2, 0, 3], [0, 1, 0, 1, 2]),\n ([2, 1, 0], [0, 1, 0]),\n ([0, 0, 0], [])\n])\ndef test_generate_increments(sizes, expected):\n result = numpy_to_sparse_tensors._generate_increments(np.array(sizes))\n assert (np.array_equal(result, expected))\n\n\[email protected](\"features,expected_indices,expected_values,expected_shape\", [\n ([[7, 8], [10, 11, 12]], [[0, 0], [0, 1], [1, 0], [1, 1], [1, 2]], [7, 8, 10, 11, 12], [2, 3]),\n ([[], []], np.empty((0, 2), dtype=np.int64), [], [2, 0])\n])\ndef test_create_sparse_np_stacked_int(features, expected_indices, expected_values, expected_shape):\n indices, values, shape = numpy_to_sparse_tensors.create_sparse_np_stacked(features, np.int64)\n assert (np.array_equal(indices, expected_indices))\n assert (np.array_equal(values, expected_values))\n assert (np.array_equal(shape, expected_shape))\n\n\[email protected](\"features,expected_indices,expected_values,expected_shape\", [\n ([['a', 'b'], ['c', 'd', 'e']], [[0, 0], [0, 1], [1, 0], [1, 1], [1, 2]],\n ['a', 'b', 'c', 'd', 'e'], [2, 3]),\n ([[], []], np.empty((0, 2), dtype=np.int64), np.array([], dtype=np.str), [2, 0])\n])\ndef test_create_sparse_np_stacked_str(features, expected_indices, expected_values, expected_shape):\n indices, values, shape = numpy_to_sparse_tensors.create_sparse_np_stacked(features, np.str)\n assert (np.array_equal(indices, expected_indices))\n assert (np.array_equal(values, expected_values))\n assert (np.array_equal(shape, expected_shape))\n" ]
[ [ "numpy.empty", "numpy.array", "numpy.array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
suranakritika/CarND-Capstone
[ "bed82dac5622f20ea00dd510afc6824b71ee7c0a" ]
[ "ros/src/tl_detector/tl_detector.py" ]
[ "#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import Int32\nfrom geometry_msgs.msg import PoseStamped, Pose\nfrom styx_msgs.msg import TrafficLightArray, TrafficLight\nfrom styx_msgs.msg import Lane\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge\nfrom light_classification.tl_classifier import TLClassifier\nimport tf\nimport cv2\nimport yaml\nfrom scipy.spatial import KDTree\n\nSTATE_COUNT_THRESHOLD = 3\n\nclass TLDetector(object):\n def __init__(self):\n rospy.init_node('tl_detector')\n\n self.pose = None\n self.waypoints = None\n self.camera_image = None\n self.lights = []\n self.base_waypoints = None\n self.waypoints_2d = None\n self.waypoint_tree = None\n\n sub1 = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)\n sub2 = rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)\n\n '''\n /vehicle/traffic_lights provides you with the location of the traffic light in 3D map space and\n helps you acquire an accurate ground truth data source for the traffic light\n classifier by sending the current color state of all traffic lights in the\n simulator. When testing on the vehicle, the color state will not be available. You'll need to\n rely on the position of the light and the camera image to predict it.\n '''\n sub3 = rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb)\n sub6 = rospy.Subscriber('/image_color', Image, self.image_cb)\n\n config_string = rospy.get_param(\"/traffic_light_config\")\n self.config = yaml.load(config_string)\n\n self.upcoming_red_light_pub = rospy.Publisher('/traffic_waypoint', Int32, queue_size=1)\n\n self.bridge = CvBridge()\n self.light_classifier = TLClassifier()\n self.listener = tf.TransformListener()\n\n self.state = TrafficLight.UNKNOWN\n self.last_state = TrafficLight.UNKNOWN\n self.last_wp = -1\n self.state_count = 0\n self.process_count = 0\n rospy.spin()\n\n def pose_cb(self, msg):\n self.pose = msg\n\n def waypoints_cb(self, waypoints):\n self.base_waypoints = waypoints\n if not self.waypoints_2d:\n self.waypoints_2d = [[waypoint.pose.pose.position.x, waypoint.pose.pose.position.y] for waypoint in waypoints.waypoints]\n self.waypoint_tree = KDTree(self.waypoints_2d)\n\n def traffic_cb(self, msg):\n self.lights = msg.lights\n\n def image_cb(self, msg):\n \"\"\"Identifies red lights in the incoming camera image and publishes the index\n of the waypoint closest to the red light's stop line to /traffic_waypoint\n Args:\n msg (Image): image from car-mounted camera\n \"\"\"\n self.has_image = True\n self.camera_image = msg\n light_wp, state = self.process_traffic_lights()\n\n '''\n Publish upcoming red lights at camera frequency.\n Each predicted state has to occur `STATE_COUNT_THRESHOLD` number\n of times till we start using it. Otherwise the previous stable state is\n used.\n '''\n if self.state != state:\n self.state_count = 0\n self.state = state\n elif self.state_count >= STATE_COUNT_THRESHOLD:\n self.last_state = self.state\n light_wp = light_wp if state == TrafficLight.RED else -1\n self.last_wp = light_wp\n self.upcoming_red_light_pub.publish(Int32(light_wp))\n else:\n self.upcoming_red_light_pub.publish(Int32(self.last_wp))\n self.state_count += 1\n\n def get_closest_waypoint(self, x, y):\n \"\"\"Identifies the closest path waypoint to the given position\n https://en.wikipedia.org/wiki/Closest_pair_of_points_problem\n Args:\n pose (Pose): position to match a waypoint to\n Returns:\n int: index of the closest waypoint in self.waypoints\n \"\"\"\n #TODO implement\n closest_idx = self.waypoint_tree.query([x, y], 1)[1]\n return closest_idx\n\n def get_light_state(self, light):\n \"\"\"Determines the current color of the traffic light\n Args:\n light (TrafficLight): light to classify\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n \"\"\"\n # if(not self.has_image):\n # self.prev_light_loc = None\n # return False\n\n # cv_image = self.bridge.imgmsg_to_cv2(self.camera_image, \"bgr8\")\n\n #Get classification\n # return self.light_classifier.get_classification(cv_image)\n return light.state\n\n def process_traffic_lights(self):\n \"\"\"Finds closest visible traffic light, if one exists, and determines its\n location and color\n Returns:\n int: index of waypoint closes to the upcoming stop line for a traffic light (-1 if none exists)\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n \"\"\"\n closest_light = None\n line_wp_idx = None\n\n # List of positions that correspond to the line to stop in front of for a given intersection\n stop_line_positions = self.config['stop_line_positions']\n if(self.pose):\n car_wp_idx = self.get_closest_waypoint(self.pose.pose.position.x, self.pose.pose.position.y)\n\n #TODO find the closest visible traffic light (if one exists)\n diff = len(self.base_waypoints.waypoints)\n for i, light in enumerate(self.lights):\n # Get stop line waypoint index\n line = stop_line_positions[i]\n temp_wp_idx = self.get_closest_waypoint(line[0], line[1])\n # Find closest stop line waypoint index\n d = temp_wp_idx - car_wp_idx\n if(d >= 0 and d < diff):\n diff = d\n closest_light = light\n line_wp_idx = temp_wp_idx\n\n if closest_light:\n self.process_count += 1\n state = self.get_light_state(closest_light)\n if (self.process_count % 5) == 0:\n rospy.logwarn(\"DETECT: line_wp_idx={}, state={}\".format(line_wp_idx, state))\n # self.waypoints = None\n return -1, TrafficLight.UNKNOWN\n\n def to_string(self, state):\n out = \"unknown\"\n if state == TrafficLight.GREEN:\n out = \"green\"\n elif state == TrafficLight.YELLOW:\n out = \"yellow\"\n elif state == TrafficLight.RED:\n out = \"red\"\n return out\n\nif __name__ == '__main__':\n try:\n TLDetector()\n except rospy.ROSInterruptException:\n rospy.logerr('Could not start traffic node.')\n#tl-detector\n" ]
[ [ "scipy.spatial.KDTree" ] ]
[ { "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": [] } ]
STNet-cvpr2022/STNet
[ "b6fb9db95af61c53e12fdb97883e8b9bc301d8e2" ]
[ "videoanalyst/model/backbone/backbone_impl/snn3.py" ]
[ "# -*- coding: utf-8 -*\n\nimport torch.nn as nn\nimport torch\n\nfrom videoanalyst.model.backbone.backbone_base import (TRACK_BACKBONES,\n VOS_BACKBONES)\nfrom videoanalyst.model.common_opr.common_block import conv_bn_relu\nfrom videoanalyst.model.module_base import ModuleBase\n\nthresh_bais = 0.3\n# thresh = 0.3 # neuronal threshold\nlens = 0.5 # hyper-parameters of approximate function\ndecay = 0.2 # decay constants\nglobal thresh\n\nclass SpatialGroupEnhance(nn.Module):\n def __init__(self):\n super(SpatialGroupEnhance, self).__init__()\n # self.groups = groups\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.weight = nn.Parameter(torch.zeros(1, 1, 1, 1))\n self.bias = nn.Parameter(torch.ones(1, 1, 1, 1))\n self.sig = nn.Sigmoid()\n\n def forward(self, x): # (b, c, h, w)\n b, c, h, w = x.size()\n # x = x.view(b * self.groups, -1, h, w) # (b*32, c', h, w)\n xn = x * self.avg_pool(x)\n xn = xn.mean(dim=1, keepdim=True) # (b*32, 1, h, w)\n entro = torch.mean(xn, dim=0).squeeze()\n h,w = entro.size()\n entro = entro.view(-1)\n max = torch.max(entro)\n min = torch.min(entro)\n entro = (entro - min) / (max-min) * 255\n his = torch.histc(entro, bins=256, min=0, max=255) / (h*w)\n entro_final = torch.sum(his * -torch.log(his + 0.00000001))\n # print(entro_final / torch.count_nonzero(his))\n entro_final = entro_final / torch.count_nonzero(his)\n x = self.sig(xn)\n x = torch.mean(x)\n return x + entro_final*10\n\nclass ActFun(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input):\n # print('threshold.............', thresh)\n ctx.save_for_backward(input)\n return input.gt(thresh).float()\n\n @staticmethod\n def backward(ctx, grad_output):\n input, = ctx.saved_tensors\n grad_input = grad_output.clone()\n temp = abs(input - thresh) < lens\n return grad_input * temp.float()\n\nact_fun = ActFun.apply\n\n\n# membrane potential update\ndef mem_update(ops, x, mem, spike):\n mem = mem * decay * (1. - spike) + ops(x)\n spike = act_fun(mem) # act_fun : approximation firing function\n return mem, spike\n\ncfg_cnn = [(6, 64, 2, 0, 11),\n (64, 128, 2, 0, 9),\n (128, 256, 2, 0, 5),\n (64, 128, 1, 1, 3),\n (128, 256, 1, 1, 3)]\n# kernel size\ncfg_kernel = [147, 70, 33, 31, 31]\ncfg_kernel_first = [59, 26, 11, 15, 15]\n# fc layer\ncfg_fc = [128, 10]\n\n@VOS_BACKBONES.register\n@TRACK_BACKBONES.register\n\n\nclass SNN3(ModuleBase):\n r\"\"\"\n SNN\n\n Hyper-parameters\n ----------------\n pretrain_model_path: string\n Path to pretrained backbone parameter file,\n Parameter to be loaded in _update_params_\n \"\"\"\n default_hyper_params = {\"pretrain_model_path\": \"\"}\n\n def __init__(self):\n super(SNN3, self).__init__()\n\n cfg_cnn = [(3, 64, 2, 0, 11),\n (64, 128, 2, 0, 9),\n (128, 256, 2, 0, 5),\n (64, 128, 1, 1, 3),\n (128, 256, 1, 1, 3)]\n # kernel size\n cfg_kernel = [147, 70, 33, 31, 31]\n cfg_kernel_first = [59, 26, 11, 15, 15]\n\n in_planes, out_planes, stride, padding, kernel_size = cfg_cnn[0]\n self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding)\n in_planes, out_planes, stride, padding, kernel_size = cfg_cnn[1]\n self.conv2 = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding)\n in_planes, out_planes, stride, padding, kernel_size = cfg_cnn[2]\n self.conv3 = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding)\n self.bn_tem = nn.BatchNorm2d(256)\n self.relu_tem = nn.ReLU()\n\n self.fuse_snn_transfor = nn.Conv2d(out_planes*2, out_planes, kernel_size=1, stride=1, padding=0)\n self.thre_w = SpatialGroupEnhance()\n self.conv33_11 = nn.Conv2d(256, 256, kernel_size=13, stride=2, padding=0)\n self.bn_spa = nn.BatchNorm2d(256)\n self.relu_spa = nn.ReLU()\n\n def forward(self, input_pos, input_neg, trans_snn, transformer_sig, transformer_fea, first_seq):\n # batch_size = input.shape[0]\n global thresh\n if transformer_fea is None:\n thresh = 0.3\n else:\n thresh = self.thre_w(transformer_fea) * thresh_bais\n # print('before forward threshold...', thresh)\n if first_seq:\n time_window = len(input_pos)\n tem_c3m = 0\n for step in range(time_window):\n x_pos = input_pos[step]\n x_neg = input_neg[step]\n # x = torch.cat([x_pos, x_neg], dim=1)\n x = torch.where(x_pos > x_neg, x_pos, x_neg)\n\n c1_mem, c1_spike = mem_update(self.conv1, x.float(), trans_snn[0], trans_snn[1])\n c2_mem, c2_spike = mem_update(self.conv2, c1_spike, trans_snn[2], trans_snn[3])\n c3_mem, c3_spike = mem_update(self.conv3, c2_spike, trans_snn[4], trans_snn[5])\n trans_snn = [c1_mem, c1_spike, c2_mem, c2_spike, c3_mem, c3_spike]\n tem_c3m = tem_c3m + c3_mem\n tem_fea = tem_c3m / time_window\n tem_fea = self.relu_tem(self.bn_tem(tem_fea))\n spa_fea = self.relu_spa(self.bn_spa(self.conv33_11(transformer_fea)))\n # output = self.fuse_snn_transfor(torch.cat([tem_fea, spa_fea], dim=1))\n return tem_fea, spa_fea, trans_snn\n # return output, trans_snn\n else:\n time_window = len(input_pos)\n tem_c3m = 0\n for step in range(time_window):\n x_pos = input_pos[step]\n x_neg = input_neg[step]\n # x = torch.cat([x_pos, x_neg], dim=1)\n x = torch.where(x_pos > x_neg, x_pos, x_neg)\n c1_mem, c1_spike = mem_update(self.conv1, x.float(), trans_snn[0], trans_snn[1])\n c2_mem, c2_spike = mem_update(self.conv2, c1_spike, trans_snn[2], trans_snn[3])\n c3_mem, c3_spike = mem_update(self.conv3, c2_spike, trans_snn[4], trans_snn[5])\n trans_snn = [c1_mem, c1_spike, c2_mem, c2_spike, c3_mem, c3_spike]\n # if step >= time_window - 10:\n tem_c3m = tem_c3m + c3_mem\n tem_fea = tem_c3m / time_window\n tem_fea = self.relu_tem(self.bn_tem(tem_fea))\n spa_fea = transformer_fea\n # output = self.fuse_snn_transfor(torch.cat([tem_fea, spa_fea], dim=1))\n return tem_fea, spa_fea, trans_snn\n # return output, trans_snn\n" ]
[ [ "torch.mean", "torch.ones", "torch.max", "torch.histc", "torch.zeros", "torch.min", "torch.nn.Conv2d", "torch.nn.Sigmoid", "torch.nn.AdaptiveAvgPool2d", "torch.log", "torch.where", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.count_nonzero" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sweigart/pygama
[ "3c5fe4c69230814933b2de879b9a305ff0d4ad5e", "3c5fe4c69230814933b2de879b9a305ff0d4ad5e" ]
[ "experiments/hades/HADES_AoE.py", "experiments/hades_test/setup.py" ]
[ "## kinda preliminary version which summarises the results in a pdf in ./output/low_cut_results.pdf\n## doesn't overwrite if the folder already exists, instead makes a new folder\n\nimport pygama\nimport os, time, json\nimport numpy as np\nimport pandas as pd\nfrom pprint import pprint\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\nfrom matplotlib.colors import LogNorm\nfrom scipy.integrate import quad\nimport tinydb as db\nimport argparse\nfrom statsmodels.stats import proportion\nimport json\nfrom scipy.optimize import curve_fit\nimport math\nfrom scipy.special import erf\nfrom scipy.signal import savgol_filter\nimport os\n\nfrom pygama import DataSet\nfrom pygama.analysis.calibration import *\nfrom pygama.analysis.histograms import *\nimport pygama.utils as pgu\nfrom matplotlib.lines import Line2D\nfrom pygama.utils import set_plot_style\nimport h5py\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n\ndef main():\n\n\t## took that from original script because why not\n\tpar = argparse.ArgumentParser(description=\"A/E cut for HADES\")\n\targ, st, sf = par.add_argument, \"store_true\", \"store_false\"\n\t#arg(\"-ds\", nargs='*', action=\"store\", help=\"load runs for a DS\")\n\t#arg(\"-r\", default=1, help=\"select a run\")\n\t#arg(\"-db\", \"--writeDB\", action=st, default=False, help=\"store results in DB\")\n\targ(\"-v\", default=0, help=\"verbosity level, 0: Just do it, 1: Tell me when you start a new step, 2: Tell me everything\")\n\targ(\"-o\", action=st, default=False, help=\"stores every plot generated in ./output\")\n\targ(\"-md\", help=\"select runDB to process entire dataset\")\n\t#arg(\"-c\", help=\"calibration json file\")\n\n\n\n\targs = vars(par.parse_args())\n\tprint(args)\n\n # -- declare the DataSet --\n\tif args[\"md\"]:\n\t\t#find_cut_using_md(args[\"md\"], int(args[\"r\"]), int(args[\"v\"]), args[\"writeDB\"], args[\"o\"])\n\t\t#find_cut_using_md(args[\"md\"], int(args[\"v\"]), args[\"writeDB\"], args[\"o\"], args[\"c\"])\n\t\tfind_cut_using_md(args[\"md\"], int(args[\"v\"]), args[\"o\"])\n\telse:\n\t\tprint(\"No metadata given, script will terminate\")\n\texit()\n\n'''\n if args[\"ds\"]:\n ds_lo = int(args[\"ds\"][0])\n try:\n ds_hi = int(args[\"ds\"][1])\n except:\n ds_hi = None\n ds = DataSet(ds_lo, ds_hi,\n md=run_db, cal = cal_db) #,tier_dir=tier_dir)\n find_cut(ds, ds_lo, args[\"writeDB\"])\n\n if args[\"run\"]:\n ds = DataSet(run=int(args[\"run\"][0]),\n md=run_db, cal=cal_db)\n find_cut(ds, ds_lo, args[\"writeDB\"])\n'''\n\n\n#Code to find and record the optimal A/E cut\n#def find_cut_using_md(md, r=1, v=0, write_db=False, o=False):\n#def find_cut_using_md(md, v=0, write_db=False, o=False, calDB = None):\ndef find_cut_using_md(md, v=0, o=False, calDB = None):\n\n\tif o:\n\t\t\n\t\tif os.path.isdir(\"output\"):\n\t\t\toutput_dir = input(\"Directory output already exists, enter different name:\\n\")\n\t\telse:\n\t\t\toutput_dir = \"output\"\n\t\tos.mkdir(output_dir)\n\t\toutput_name = output_dir + \"/low_cut_results.pdf\"\n\t\tpdf = PdfPages(output_name)\n\t\tprint(\"Output will be saved to ./{}\".format(output_name))\n\n\tif v > 0:\n\t\tprint(\"Starting to read subfiles\")\n\n\n\tcurrents = np.array([])\n\taoe = np.array([])\n\tcal_energies = np.array([])\n\ta_over_e = np.array([])\n\ta_over_e_sigma = np.array([])\n\n\tfile_count = 0\n\n\twith open(md, \"r\") as md_file:\n\t\tmd_dict = json.load(md_file)\n\tt2_path = md_dict[\"tier2_dir\"]\n\tfor key in md_dict[\"ds\"].keys():\n\t\ttry:\n\t\t\tr = int(key)\n\t\texcept:\n\t\t\tcontinue\n\t\tnew_uncal_energies = np.array([])\n\t\tnew_currents = np.array([])\n\t\tnew_aoe = np.array([])\n\t\tfor f in os.listdir(t2_path):\n\t\t\t\t\t\t## make run number 4 digits\n\t\t\tif (\"run\" + f'{r:04}' in f) and (\".lh5\" in f):\n\t\t\t\tdata = h5py.File(t2_path + \"/\" + f, \"r\")\n\t\t\t\tnew_uncal_energies = np.append(new_uncal_energies, data[\"data\"][\"trapE\"])\n\t\t\t\tnew_currents = np.append(new_currents, data[\"data\"][\"A_10\"])\n\t\t\t\t#aoe = np.append(new_aoe, data[\"data\"][\"AoE\"])\n\n\t\t\t\tfile_count += 1\n\n\n\t\t## calibration\n\t\tif calDB:\n\t\t\tnew_cal_energies = apply_calibration(new_uncal_energies, calDB, r)\n\t\telse:\n\t\t\tnew_cal_energies = do_calibration(new_uncal_energies, md, v=v, output=pdf, run=r)\n\n\t\tuncal_a_over_e = new_currents / new_cal_energies\n\n\t\tnew_a_over_e, new_a_over_e_sigma = aoe_correction(new_cal_energies, uncal_a_over_e, output=pdf, run=r)\n\n\t\tcal_energies = np.append(cal_energies, new_cal_energies)\n\t\ta_over_e = np.append(a_over_e, new_a_over_e)\n\t\ta_over_e_sigma = np.append(a_over_e_sigma, new_a_over_e_sigma)\n\t\t\n\tprint(\"Found {} output files\".format(file_count))\n\n\t#e_over_unc = cal_energies / uncal_energies #Needed to normalize or something, idk\n\n\tplt.figure(figsize=(14,7))\n\t_h = plt.hist(cal_energies, range=(0,3000), bins=3000)\n\tplt.xlabel(\"Energy in keV\")\n\tplt.ylabel(\"Counts\")\n\tplt.title(\"Calibrated energy spectrum\", fontsize=25)\n\tpdf.savefig()\n\tplt.close()\n\n\t#uncal_a_over_e = currents / cal_energies\n\n\t#a_over_e, a_over_e_sigma = aoe_correction(cal_energies, uncal_a_over_e, output_dir=output_dir)\n\n\tplt.figure(figsize=(14,7))\n\t_h = plt.hist2d(cal_energies, a_over_e, range=((0,3000), (0.9,1.05)), bins=(150,150), cmap=\"jet\", norm=mcolors.PowerNorm(0.3))\n\tplt.colorbar()\n\tplt.xlabel(\"Energy in keV\")\n\tplt.ylabel(\"A/E in a.u.\")\n\tplt.title(\"Corrected A/E\", fontsize=25)\n\tpdf.savefig()\n\tplt.close()\n\n\tclassifier = calc_classifier(cal_energies, a_over_e, a_over_e_sigma, v=0,)\n\n\tfind_low_cut_value(cal_energies, classifier, n=4.5, output=pdf)\n\n\n\tpdf.close()\n\n\t#find_low_cut(cal_energies, a_over_e, v=v, output_dir=output_dir)\n\n\n\texit()\n\n\ndef apply_calibration(uncal_energies, calDB, r):\n\twith open(calDB, \"r\") as cal_file:\n\t\tcal_dict = json.load(cal_file)\n\tparameters = cal_dict[\"cal_pass3\"][\"{}\".format(r)]\n\n\tcal_energies = uncal_energies * parameters[\"slope\"] + parameters[\"offset\"]\n\treturn cal_energies\n\n\n\ndef aoe_correction(cal_energies, uncal_a_over_e, v=0, output=None, run=1):\n\n\tif v > 0:\n\t\tprint(\"Starting A/E correction\")\n\tpdf = output\n\n\t## take intervalls along compton edge\n\tinterval_centers = np.linspace(1000,2000,25)\n\t## add some gamma lines\n\tinterval_centers = np.append(np.array([238.6, 583.2, ]), interval_centers)\n\taoe_means = []\n\taoe_sigmas = []\n\t\n\tfor center in interval_centers:\n\t\tmean, sigma = fit_aoe_histogram(cal_energies, uncal_a_over_e, center, v=v, output_pdf=pdf)\n\t\taoe_means += [mean]\n\t\taoe_sigmas += [sigma]\n\n\taoe_corr_par, aoe_corr_cov = curve_fit(aoe_root, interval_centers, aoe_means, maxfev=1000000)\n\tplot_xs = np.linspace(200, 3000, 2800)\n\tplt.figure(figsize=(14,7))\n\tplt.plot(interval_centers, aoe_means, \"bx\")\n\tplt.plot(plot_xs, aoe_root(plot_xs, *aoe_corr_par), \"red\")\n\tplt.title(\"Fit for A/E correction\", fontsize=25)\n\tplt.xlabel(\"Energy in keV\", fontsize=15)\n\tplt.ylabel(\"Mean of A/E distribution in a.u.\", fontsize=15)\n\tpdf.savefig()\n\tplt.close()\n\n\taoe_sigma_par, aoe_sigma_cov = curve_fit(aoe_sigma_root, interval_centers, aoe_sigmas, maxfev=1000000, method=\"lm\")\n\n\ta_over_e = uncal_a_over_e / aoe_root(cal_energies, *aoe_corr_par)\n\ta_over_e_sigma = aoe_sigma_root(cal_energies, *aoe_sigma_par)/aoe_root(cal_energies, *aoe_corr_par)\n\n\treturn a_over_e, a_over_e_sigma\n\ndef calc_classifier(cal_energies, a_over_e, a_over_e_sigma, v=0):\n\n\tif v > 0:\n\t\tprint(\"Starting classifier calculation\")\n\n\tclassifier = (a_over_e - 1)/a_over_e_sigma\n\n\t#plt.hist2d(cal_energies, classifier, range=((0,3000),(-20,20)), bins=(150,40))\n\t#plt.show()\n\n\treturn classifier\n\ndef find_low_cut_value(cal_energies, classifier, n=4.5, v=0, output=None):\n\n\tif v > 0:\n\t\tprint(\"Starting calibration\")\n\tpdf = output\n\n\tdep_range = 1592.5 - 20, 1592.5 + 20\n\tfep_range = 2614.5 - 20, 2614.5 + 20\n\tbins=400\n\n\t\n\tdep_class_range = -50, 50\n\tdep_class_bins = 1000\n\n\tfep_class_range = -200, 50\n\tfep_class_bins = 2500\n\n\tdep_range = 1592.5 - 20, 1592.5 + 20\n\tbins=400\n\tdep_energies = cal_energies[np.where((cal_energies > dep_range[0]) & (cal_energies < dep_range[1]))]\n\tdep_energy_counts, dep_energy_edges = np.histogram(dep_energies, range=dep_range, bins=bins)\n\tdep_energy_centers = (dep_energy_edges[1:] + dep_energy_edges[:-1])/2\n\tp0 = guess_parameters(dep_energy_centers, dep_energy_counts)\n\tdep_energy_mean, dep_energy_sigma = curve_fit(gauss_tail_step, dep_energy_centers, dep_energy_counts, p0=p0, maxfev=1000000, method=\"trf\")[0][1:3] \n\tdep_class_centers, dep_class_counts = select_classifier_values(cal_energies, classifier, dep_energy_mean, dep_energy_sigma, bins=dep_class_bins, range=dep_class_range)\n\n\tinit_dep_counts = np.sum(dep_class_counts)\n\tinit_dep_class_counts = dep_class_counts\n\n\tcut_value = -5\n\twhile np.sum(dep_class_counts) / init_dep_counts > 0.9:\n\n\t\tcut_value += 0.1\n\t\tdep_class_centers, dep_class_counts = select_classifier_values(cal_energies[np.where(classifier > cut_value)], classifier[np.where(classifier > cut_value)], dep_energy_mean, dep_energy_sigma, bins=dep_class_bins, range=dep_class_range)\n\tif pdf :\n\t\tplt.figure(figsize=(14,7))\n\t\tplt.plot(dep_class_centers, init_dep_class_counts)\n\t\tplt.plot(dep_class_centers, dep_class_counts)\n\t\t#plt.vlines(cut_value, 0, 1.2*np.amax(init_dep_class_counts), \"red\")\n\t\tplt.xlabel(\"Classifier in a.u.\")\n\t\tplt.ylabel(\"Counts\")\n\t\tplt.title(\"Low cut for DEP\")\n\t\tplt.text(-45, 0.95*np.amax(init_dep_class_counts), \"Low cut value: {} \\n Survival fraction: {}\".format(cut_value, np.sum(dep_class_counts) / init_dep_counts))\n\t\tpdf.savefig()\n\t\tplt.close()\n\n\tfep_energies = cal_energies[np.where((cal_energies > fep_range[0]) & (cal_energies < fep_range[1]))]\n\tfep_energy_counts, fep_energy_edges = np.histogram(fep_energies, range=fep_range, bins=bins)\n\tfep_energy_centers = (fep_energy_edges[1:] + fep_energy_edges[:-1])/2\n\tp0 = guess_parameters(fep_energy_centers, fep_energy_counts\t)\n\tfep_energy_mean, fep_energy_sigma = curve_fit(gauss_tail_step, fep_energy_centers, fep_energy_counts, p0=p0, maxfev=1000000, method=\"trf\")[0][1:3]\n\n\tfep_class_centers, init_fep_class_counts = select_classifier_values(cal_energies, classifier, fep_energy_mean, fep_energy_sigma, bins=fep_class_bins, range=fep_class_range)\n\tinit_fep_counts = np.sum(init_fep_class_counts)\n\n\tfep_class_centers, fep_class_counts = select_classifier_values(cal_energies[np.where(classifier > cut_value)], classifier[np.where(classifier > cut_value)], fep_energy_mean, fep_energy_sigma, bins=fep_class_bins, range=fep_class_range)\n\n\tfep_counts = np.sum(fep_class_counts)\n\n\tprint(fep_counts/init_fep_counts)\n\tprint(cut_value)\n\n\tif pdf :\n\t\tplt.figure(figsize=(14,7))\n\t\tplt.plot(fep_class_centers, init_fep_class_counts)\n\t\tplt.plot(fep_class_centers, fep_class_counts)\n\t\t#plt.vlines(cut_value, 0, 1.2*np.amax(init_fep_class_counts), \"red\")\n\t\tplt.title(\"Low cut for FEP\")\n\t\tplt.xlabel(\"Classifier in a.u.\")\n\t\tplt.ylabel(\"Counts\")\n\t\t#plt.text(-175, 0.95*np.amax(init_fep_class_counts), \"Low cut value: {} \\n Survival fraction: {}\".format(cut_value, fep_counts/init_fep_counts))\n\t\tpdf.savefig()\n\t\tplt.close()\n\ndef select_classifier_values(cal_energies, classifier, mean, sigma, n=4.5, bins=500, range=(-25,25),):\n\t## selecting classifier values satisfying given cut around given mean using given sigma (* n) and subtracting background\n\tline_classifier = classifier[np.where((cal_energies > mean - n*sigma)&(cal_energies < mean + n*sigma))]\n\tclassifier_bkg_1 = classifier[np.where((cal_energies > mean - 2*n*sigma)&(cal_energies < mean - n*sigma))]\n\tclassifier_bkg_2 = classifier[np.where((cal_energies > mean + n*sigma)&(cal_energies < mean + 2*n*sigma))]\n\tbin_centers = (np.histogram(classifier, range=range, bins=bins)[1][1:] + np.histogram(classifier, range=range, bins=bins)[1][:-1])/2\n\n\tif mean < 2000 : ## 3 bkg regions if DEP\n\t\tclassifier_bkg_3 = classifier[np.where((cal_energies > mean + 2*n*sigma)&(cal_energies < mean + 3*n*sigma))]\n\t\tsubtracted_classifier = np.histogram(line_classifier, range=range, bins=bins)[0] - np.histogram(classifier_bkg_1, range=range, bins=bins)[0] - 2* np.histogram(classifier_bkg_2, range=range, bins=bins)[0] + np.histogram(classifier_bkg_3, range=range, bins=bins)[0]\n\t\treturn bin_centers, subtracted_classifier\n\telse: ## only 2 regions if fep\n\t\tsubtracted_classifier = np.histogram(line_classifier, range=range, bins=bins)[0] - np.histogram(classifier_bkg_1, range=range, bins=bins)[0] - np.histogram(classifier_bkg_2, range=range, bins=bins)[0]\n\t\treturn bin_centers, subtracted_classifier\n\t\t\n\t\n\ndef aoe_dep_mean_correction(cal_energies, a_over_e, n=4.5, v=0, output_dir=None):\n\n\tbins = 1500\n\trange = 0, 1.5\n\n\n\tif v > 0:\n\t\tprint(\"Starting normalization on DEP mean\")\n\n\tif output_dir:\n\t\taoe_dep_norm_output_dir = output_dir + \"/aoe_dep_normalization\"\n\t\tos.mkdir(aoe_dep_norm_output_dir)\n\telse :\n\t\taoe_dep_norm_output_dir = None\n\n\tdep_energies = cal_energies[np.where((dep_energies > 1592.5-20) & (dep_energies < 1592.5+20))]\n\n\tdep_energy_mean, dep_energy_sigma = fit_energy_histogram(dep_energies, 1592.5, v=v)\n\n\t## DEP region\n\tdep_aoe = a_over_e[np.where( (energies > dep_energy_mean - n * dep_energy_sigma) & (energies < dep_energy_mean + n * dep_energy_sigma) )]\n\t### background region I\n\tdep_aoe_bkg_1 = a_over_e[np.where( (energies > dep_energy_mean - 2*n*dep_energy_sigma) & (energies < dep_energy_mean - n*dep_energy_sigma) )]\n\t## background region II\n\tdep_aoe_bkg_2 = a_over_e[np.where( (energies > dep_energy_mean + n * dep_energy_sigma) & (energies < dep_energy_mean + 2 * n * dep_energy_sigma) )]\t\n\t### background region III\n\tdep_aoe_bkg_3 = a_over_e[np.where( (energies > dep_energy_mean + 2 * n * dep_energy_sigma) & (energies < dep_energy_mean + 3 * n * dep_energy_sigma) )]\n\n\tdep_sub_aoe = np.histogram(init_dep_aoe, bins=bins, range=range)[0] - np.histogram(init_dep_aoe_bkg_1, bins=bins, range=range)[0] - 2*np.histogram(init_dep_aoe_bkg_2, bins=bins, range=range)[0] + np.histogram(init_dep_aoe_bkg_3, bins=bins, range=range)[0]\n\tedges = np.histogram(init_dep_aoe, bins=bins, range=range)[1]\n\tcenters = (edges[1:] + edges[:-1])/2\n\n\tdep_aoe_mean = curve_fit(aoe_fit_line, centers, dep_sub_aoe, p0=p0, maxfev=10000, method=\"lm\")[0][1]\n\n\tnorm_a_over_e = a_over_e / dep_aoe_mean\n\treturn norm_a_over_e\n\n\n\ndef fit_aoe_histogram(cal_energies, uncal_a_over_e, interval_center, v=0, output_pdf=None):\n\n\t## select only A/E values for given peak\n\taoe = uncal_a_over_e[np.where((cal_energies > (interval_center-20)) & (cal_energies < (interval_center + 20)))]\n\n ## trying to figure out sensible binning\n\tcounts, edges = np.histogram(aoe, bins=3000)\n\tcenters = (edges[:-1] + edges[1:]) / 2\n\tmean = centers[np.where(np.amax(counts)==counts)][0]\n\t## make hist +/- 1% of mean\n\tcounts, edges = np.histogram(aoe, bins=3000, range=(0.99*mean, 1.01*mean))\n\tcenters = (edges[:-1] + edges[1:]) / 2\n\t## try to get FWHM from that\n\tfwhm = centers[np.where(counts>np.amax(counts/2))][-1] - centers[np.where(counts>np.amax(counts/2))][0]\n\t## set range to +/-5 FWHM\n\trange = mean-5*fwhm, mean+5*fwhm\n\t## fill into histogram\n\tcounts, edges = np.histogram(aoe, bins=250, range=range)\n\tcenters = (edges[:-1] + edges[1:]) / 2\n\t#plt.plot(centers, hist, drawstyle=\"steps-mid\")\n\n\tp0 = guess_aoe_parameters(centers, counts)\n\taoe_fit_par, aoe_fit_cov = curve_fit(aoe_fit_line, centers, counts, p0=p0, maxfev=100000000, method=\"lm\")\n\n\n\tif output_pdf:\n\t\tplt.figure(figsize=(14,7))\n\t\tplt.plot(centers, counts, drawstyle=\"steps-mid\")\n\t\tplt.plot(centers, aoe_fit_line(centers, *aoe_fit_par), \"red\")\n\t\tplt.title(\"A/E line fit for +/- 20 keV intervall around {} keV\".format(interval_center), fontsize=25)\n\t\tplt.xlabel(\"A/E in a.u.\", fontsize=15)\n\t\tplt.ylabel(\"Counts\", fontsize=15)\n\t\toutput_pdf.savefig()\n\t\tplt.close()\n\n\n\t#results = {\"line\" : interval_center,\n\t#\t\t\t\"values\" : {\"mean\" : aoe_fit_par[1], \"sigma\" : aoe_fit_par[2]},\n\t#\t\t\t\"errors\" : {\"mean\" : math.sqrt(aoe_fit_cov[1,1]),\"sigma\" : math.sqrt(aoe_fit_cov[2,2])}}\n\n\tresults = aoe_fit_par[1], aoe_fit_par[2]\n\n\tif v == 2:\n\t\tprint(\"Results of fitting:\")\n\t\tpprint(results)\n\n\n\treturn results\n\n\n\n\ndef do_calibration(energies, md, v=0, output=None, run=1):\n\t\n\tif v > 0:\n\t\tprint(\"Starting calibration\")\n\tpdf = output\n\n\n\t## see if peaks for calibration set, otherwise use some standard peaks\n\t#try:\n\t#\tcal_peaks = md[\"cal_peaks\"]\n\t#except:\n\tcal_peaks = np.array([238.6, 583.2, 1592.5, 2614.5])\n\t#cal_peaks = np.array([583.2, 2614.5])\n\n\t## coarse method to estimate uncal peak positions\n\tuncal_counts, uncal_edges = np.histogram(energies, bins=500)\n\t\t\t\t\t\t\t\t\t\t\t\t\t## max in last third of histogram probably 208Tl\n\testimated_uncal_peaks = uncal_edges[np.where(uncal_counts == np.amax(uncal_counts[int(1/3 * len(uncal_counts)):]))]*cal_peaks/2614.5\n\n\tuncal_peaks = []\n\tfor idx, uncal_peak in enumerate(estimated_uncal_peaks):\n\t\t#uncal_peaks += [fit_energy_histogram(energies, uncal_peak, cal_peaks[idx], v=0, output_dir=cal_output_dir)[\"values\"][\"mean\"]]\n\t\tuncal_peaks += [fit_energy_histogram(energies, uncal_peak, cal_peaks[idx], v=0, output_pdf=pdf)[0]]\n\n\tcalibration_par, calibration_cov = curve_fit(square, uncal_peaks, cal_peaks)\n\tif v == 2:\n\t\tprint(\"Calibration function is {} x**2 + {} x + {}\".format(*calibration_par))\n\tcal_energies = square(energies, *calibration_par)\n\n\n\treturn cal_energies\n\n\n\ndef fit_energy_histogram(energies, est_uncal_line, cal_line=None, v=0, output_pdf=None):\n\n\tif not cal_line:\n\t\tcal_line = est_uncal_line\n\n\t## trying to figure out sensible binning\n\tcounts, edges = np.histogram(energies, bins=3000, range=(est_uncal_line-100, est_uncal_line+100))\n\tcenters = (edges[:-1] + edges[1:]) / 2\n\tmean = centers[np.where(np.amax(counts)==counts)][0]\n \n\t## make hist +/- 1% of mean\n\tcounts, edges = np.histogram(energies, bins=3000, range=(0.99*mean, 1.01*mean))\n\tcenters = (edges[:-1] + edges[1:]) / 2\n\t## try to get FWHM from that\n\tfwhm = centers[np.where(counts>np.amax(counts/2))][-1] - centers[np.where(counts>np.amax(counts/2))][0]\n\t## set range to +/-2 FWHM\n\trange=mean-2*fwhm, mean+2*fwhm\n\tbins=int((range[1] - range[0]))\n\tcounts, edges = np.histogram(energies, bins=bins, range=range)\n\tcenters = (edges[1:] + edges[:-1])/2\n\n\t## guess starting values\n\tp0 = guess_parameters(centers,counts)\n\n\t## finally do some fitting\n\tuncal_line_par, uncal_line_cov = curve_fit(gauss_tail_step, centers, counts, p0=p0, maxfev=500000, method=\"lm\")\n\n\tif output_pdf:\n\t\tplt.figure(figsize=(14,7))\n\t\tplt.plot(centers, counts, drawstyle=\"steps-mid\")\n\t\tplt.plot(centers, gauss_tail_step(centers, *uncal_line_par), \"red\")\n\t\tplt.title(\"Energy line fit for {} keV line\".format(cal_line), fontsize=25)\n\t\tplt.xlabel(\"Energy in a.u.\", fontsize=15)\n\t\tplt.ylabel(\"Counts\", fontsize=15)\n\t\toutput_pdf.savefig()\n\t\tplt.close()\n \n\t#results = {\"line\" : cal_line,\n\t#\t\t\t\"values\" : {\"integral\" : uncal_line_par[0], \"mean\" : uncal_line_par[1], \"sigma\" : uncal_line_par[2]},\n\t#\t\t\t\"errors\" : {\"integral\" : math.sqrt(uncal_line_cov[1,1]), \"mean\" : math.sqrt(uncal_line_cov[1,1]),\"sigma\" : math.sqrt(uncal_line_cov[2,2])}}\n\n\tresults = uncal_line_par[1], uncal_line_par[2]\n\n\tif v == 2:\n\t\tprint(\"Results of fitting:\")\n\t\tpprint(results)\n\n\treturn results\n\n #plt.bar(centers, b, width=0.04*line/bins)\n #plt.plot(centers,LineFit(centers,*uncal_line_popt), \"red\")\n #plt.xlabel(\"Uncalibrated energy values / a.u.\")\n #plt.ylabel(\"Counts\")\n #plt.show()\n #plt.clf()\n\n# gamma line fit as in HADES GSTR\n\ndef gaussian(xs, amp, mean, sigma):\n return amp/((2*math.pi)**0.5*sigma) * np.exp(-(xs-mean)**2/(2*sigma**2))\n\ndef tail(xs, mean, S_t, beta, gamma):\n return S_t/(2*beta) * np.exp((xs-mean)/beta + gamma**2/(2*beta**2))*erf((xs-mean)/(2**0.5*gamma) + gamma/(2**0.5*beta))\n\ndef step(xs, mean, sigma, A, B):\n return A/2 * erf((xs-mean)/(2**0.5*sigma))\n\ndef gauss_tail_step(xs, amp, mean, sigma, S_t, beta, gamma, A, B):\n return gaussian(xs, amp, mean, sigma) + tail(xs, mean, S_t, beta, gamma) + step(xs, mean, sigma, A, B)\n\n# other functions for fitting\n\ndef linear(xs, a, b):\n return np.array([a*x + b for x in xs])\n\ndef square(xs, a, b, c):\n return a*xs*xs + b*xs + c\n\ndef aoe_tail(xs, m, l, f, d, t):\n return m*(np.exp(f*(xs-l))+d)/(np.exp((xs-l)*t) + l)\n\ndef aoe_fit_line(xs, amp, mean, sigma, m, l, f, d, t):\n return gaussian(xs, amp, mean, sigma) + aoe_tail(xs, m, l, f, d, t)\n\n\ndef guess_parameters(xs, ys):\n ys = savgol_filter(ys, 11, 2)\n ## find height of peak\n raw_height = np.amax(ys)\n ## determin position of max\n mean = xs[np.where(ys == raw_height)][0]\n ## get FWHM\n sigma = (xs[np.where(ys > raw_height/2**0.5)][-1] - xs[np.where(ys > raw_height/2**0.5)][0])/2\n ## take into account normalization\n height = raw_height * (2**0.5 * sigma)\n ## subtract gaussian from spectrum to get handle on the rest of the peak\n rest_ys = ys - height/(2**0.5*sigma) * np.exp(-(xs-mean)**2/(2*sigma**2))\n \n \n ## value of constant so that step goes to 0 on other end of spectrum, in the recent guess just 0\n const_height = ys[-1]\n ## try to find step far away from mean, so tail doesn't interfere, subtract constant at other end of spectrum\n step_height = ys[0] - const_height\n ## subtract infinitely sharp step and constant, only a coarse guess\n rest_ys = rest_ys - step_height*np.heaviside(mean-xs, 0.5) - const_height\n \n ##only tail leftover\n raw_tail_height = np.amax(rest_ys)\n if raw_tail_height < 20:\n \treturn [height, mean, sigma, 0, 1, 1, step_height, const_height]\n ## beta something like a decay length to the lower end, so try something like this\n beta = mean - xs[np.where(rest_ys > raw_tail_height/math.e)][0]\n ## correct tail_height with estimated beta\n tail_height = raw_tail_height * 2 * beta\n ## gamma more or less some kind of sigma, but only to the higher end\n gamma = xs[np.where(rest_ys > raw_tail_height/math.e)][-1] - mean\n \n return [height, mean, sigma, tail_height, beta, gamma, step_height, const_height]\n\n\ndef guess_aoe_parameters(centers, counts):\n counts = savgol_filter(counts, 31, 2)\n\n ## height without normalization, only for mean and sigma guessing\n raw_height = np.amax(counts)\n ## mean as center of bin with highest count\n mean = centers[np.where(counts == raw_height)][0]\n ## sigma as half of FWHM\n sigma = (centers[np.where(counts>raw_height/2)][-1] - centers[np.where(counts>raw_height/2)][0]) / 2.3548#(2*(2*math.log(2))**0.5)\n ## normalize height the way it occurs in function\n height = (2*math.pi)**0.5 * sigma * raw_height\n\n ## subtract gauss, really low level\n remaining_counts = counts - gaussian(centers, height, mean, sigma)\n #plt.plot(centers, remaining_counts)\n #plt.plot(centers, counts)\n #plt.show()\n \n ## just like for the gauss\n tail_center = centers[np.where(np.amax(remaining_counts) == remaining_counts)][0]\n tail_height = np.amax(remaining_counts)\n \n ## interpret other values as kind of decay lengths\n tail_right = .05/(centers[np.where(remaining_counts > tail_height/math.e)][-1] - tail_center)\n tail_left = 10/(tail_center - centers[np.where(remaining_counts > tail_height/math.e)][0])\n\n\n #return [height, mean, sigma, tail_height, tail_center, tail_right, 0, tail_left]\n return [height, mean, sigma, tail_height, tail_center+5*sigma, tail_right, 0, tail_left]\n\ndef aoe_root(xs, a, b, c):\n return a + b / np.sqrt(xs - c)\n\ndef aoe_sigma_root(xs, a, b, c):\n\treturn np.sqrt(a + b/(xs-c))\n\n\ndef find_cut(ds, ds_lo, write_db=False):\n\n #Make tier2 dataframe\n t2 = ds.get_t2df()\n t2 = t2.reset_index(drop=True)\n\n #Get e_ftp and pass1 calibration constant TODO: need pass2 constants at some point\n calDB = ds.calDB\n query = db.Query()\n table = calDB.table(\"cal_pass1\")\n vals = table.all()\n df_cal = pd.DataFrame(vals) # <<---- omg awesome\n df_cal = df_cal.loc[df_cal.ds==ds_lo]\n p1cal = df_cal.iloc[0][\"p1cal\"]\n cal = p1cal * np.asarray(t2[\"e_ftp\"])\n\n #Make A/E array\n current = \"current_max\"\n e_over_unc = cal / np.asarray(t2[\"e_ftp\"]) #Needed to normalize or something, idk\n y0 = np.asarray(t2[current])\n a_over_e = y0 * e_over_unc / cal\n\n y = linear_correction(cal, a_over_e) # Linear correct slight downward trend\n\n test_code(y, cal, ds)\n exit()\n\n # Two separate functions, one for Ac contaminated peak(Th232), one for Th228\n ans = input('Are you running A/E on Th232? \\n y/n -->')\n if ans == 'y':\n line = th_232(cal, y, ds)\n else:\n line = regular_cut(cal, y, ds)\n\n # Write cut to the calDB.json file\n if write_db:\n table = calDB.table(\"A/E_cut\")\n for dset in ds.ds_list:\n row = {\"ds\":dset, \"line\":line}\n table.upsert(row, query.ds == dset)\n\n\n\n\n\n\nif __name__==\"__main__\":\n main()", "#!/usr/bin/env python3\nimport os, sys\nimport argparse\nimport pandas as pd\nimport numpy as np\nfrom pprint import pprint\n\nfrom pygama import DataGroup\nfrom pygama.io.orcadaq import parse_header\nimport pygama.io.lh5 as lh5\n\nimport warnings\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n from tqdm import tqdm\n tqdm.pandas() # suppress annoying FutureWarning\n\ndef main():\n doc=\"\"\"\n Create and maintain the 'fileDB' needed by DataGroup.\n Provides options for first-time setup, and updating an existing fileDB.\n \"\"\"\n rthf = argparse.RawTextHelpFormatter\n par = argparse.ArgumentParser(description=doc, formatter_class=rthf)\n arg, st, sf = par.add_argument, 'store_true', 'store_false'\n\n # initial setup\n arg('--mkdirs', action=st, help='run first-time directory setup')\n arg('--init', action=st, help='run first-time DAQ directory scan')\n\n # update mode (normal)\n arg('-u', '--update', action=st, help='rescan DAQ dir, update existing fileDB')\n arg('--orca', action=st, help='scan ORCA XML headers of DAQ files')\n arg('--rt', action=st, help='get runtimes (requires dsp file)')\n\n # options\n arg('-b', '--batch', action=st, help='batch mode, do not ask for user y/n')\n arg('--show', action=st, help='show current on-disk fileDB')\n arg('-o', '--over', action=st, help='overwrite existing fileDB')\n arg('--lh5_user', action=st, help='use $CAGE_LH5_USER over $CAGE_LH5')\n\n args = par.parse_args()\n\n # declare main DataGroup\n dg = DataGroup('hades.json')\n\n # -- run routines --\n if args.mkdirs: dg.lh5_dir_setup(args.lh5_user)\n if args.show: show_fileDB(dg)\n if args.init: init(dg)\n if args.update: update(dg, args.batch)\n \n # not for flashcam\n # if args.orca: scan_orca_headers(dg, args.over, args.batch)\n \n # need some other way to do this\n # if args.rt: get_runtimes(dg, args.over, args.batch)\n\n\ndef show_fileDB(dg):\n \"\"\"\n $ ./setup.py --show\n Show current on-disk fileDB.\n\n Columns:\n - Added by get_cyc_info: 'YYYY', 'cycle', 'daq_dir', 'daq_file', 'dd', 'mm',\n 'run', 'runtype', 'unique_key'\n - Added by get_lh5_cols: 'raw_file', 'raw_path', 'dsp_file', 'dsp_path',\n 'hit_file', 'hit_path'\n - Added by scan_orca_headers: 'startTime', 'threshold',\n - Added by get_runtime: 'stopTime', 'runtime'\n \"\"\"\n dg.load_df()\n\n dbg_cols = ['run', 'cycle', 'unique_key']\n\n if 'startTime' in dg.fileDB.columns:\n dbg_cols += ['startTime']\n\n if 'runtime' in dg.fileDB.columns:\n dbg_cols += ['runtime']\n\n print(dg.fileDB[dbg_cols])\n print(dg.fileDB.columns)\n\n\ndef init(dg):\n \"\"\"\n ./setup.py --init\n Run first scan of the fileDB over the DAQ directory ($CAGE_DAQ)\n \"\"\"\n print('Initializing fileDB...')\n \n # scan over DAQ directory, then organize by cycle (ORCA run number)\n dg.scan_daq_dir()\n dg.fileDB.sort_values(['cycle'], inplace=True)\n dg.fileDB.reset_index(drop=True, inplace=True)\n dg.fileDB = dg.fileDB.apply(get_cyc_info, args=[dg], axis=1)\n\n # compute lh5 column names (uses $CAGE_LH5, don't use $CAGE_LH5_USER here)\n dg.get_lh5_cols()\n\n # attempt to convert to integer (will fail if nan's are present)\n for col in ['run', 'cycle']:\n dg.fileDB[col] = pd.to_numeric(dg.fileDB[col])\n\n print(dg.fileDB[['run', 'cycle', 'daq_file', 'runtype', 'skip']].to_string())\n\n print('Ready to save. This will overwrite any existing fileDB.')\n ans = input('Continue? (y/n) ')\n if ans.lower() == 'y':\n dg.save_df(dg.config['fileDB'])\n print('Wrote fileDB:', dg.config['fileDB'])\n\n\ndef update(dg, batch_mode=False):\n \"\"\"\n ./setup.py -u\n After taking new data, run this function to add rows to fileDB.\n New rows will not have all columns yet.\n TODO: look for nan's to identify cycles not covered in runDB\n \"\"\"\n print('Updating fileDB ...')\n \n dbg_cols = ['unique_key', 'run', 'cycle', 'daq_file']\n\n # load existing file keys\n dg.load_df()\n # print(dg.fileDB[dbg_cols])\n\n # scan daq dir for new file keys\n dg_new = DataGroup('cage.json')\n dg_new.scan_daq_dir()\n dg_new.file_keys.sort_values(['cycle'], inplace=True)\n dg_new.file_keys.reset_index(drop=True, inplace=True)\n dg_new.file_keys = dg_new.file_keys.apply(get_cyc_info, args=[dg_new], axis=1)\n dg_new.get_lh5_cols()\n for col in ['run', 'cycle']:\n dg_new.file_keys[col] = pd.to_numeric(dg_new.file_keys[col])\n # print(dg_new.file_keys[dbg_cols])\n\n # identify new keys, save new indexes\n df1 = dg.fileDB['unique_key']\n df2 = dg_new.file_keys['unique_key']\n new_keys = pd.concat([df1, df2]).drop_duplicates(keep=False)\n new_idx = new_keys.index\n\n if len(new_keys) > 0:\n print('Found new files:')\n print(new_keys)\n\n print('Merging with existing fileDB:')\n df_upd = pd.concat([dg.fileDB, dg_new.file_keys.loc[new_idx]])\n print(df_upd[dbg_cols])\n\n if not batch_mode:\n print(\"RunDB Check -- did you update runDB.json? Are there any NaN's in filenames/paths above?\")\n ans = input('Save updated fileDB? (y/n):')\n if ans.lower() == 'y':\n dg.fileDB = df_upd\n dg.save_df(dg.config['fileDB'])\n print('fileDB updated.')\n else:\n dg.fileDB = df_upd\n dg.save_df(dg.config['fileDB'])\n print('fileDB updated.')\n else:\n print('No new files found! current fileDB:')\n print(dg.fileDB[dbg_cols])\n\n\ndef get_cyc_info(row, dg):\n \"\"\"\n using the runDB, map cycle numbers to physics runs, identify detector,\n physics run type, etc.\n \"\"\"\n # loop over the runDB and add columns to each row of dg.fileDB\n cyc = row['cycle']\n for run, cycles in dg.runDB.items():\n tmp = cycles[0].split(',')\n for rng in tmp:\n if '-' in rng:\n clo, chi = [int(x) for x in rng.split('-')]\n if clo <= cyc <= chi:\n row['run'] = run\n row['runtype'] = cycles[1]\n break\n else:\n clo = int(rng)\n if cyc == clo:\n row['run'] = run\n row['runtype'] = cycles[1]\n break\n\n # label the detector\n if 0 < cyc <= 124:\n row['detector'] = 'oppi_v1'\n elif 125 <= cyc <= 136:\n row['detector'] = 'icpc_v1'\n elif 137 <= cyc <= 9999:\n row['detector'] = 'oppi_v2'\n \n # apply file selection\n skips = dg.runSelectionDB['daq_junk_cycles']\n row['skip'] = cyc in skips\n \n return row\n\n\ndef scan_orca_headers(dg, overwrite=False, batch_mode=False):\n \"\"\"\n $ ./setup.py --orca\n Add unix start time, threshold, and anything else in the ORCA XML header\n for the fileDB.\n \"\"\"\n print('Scanning ORCA headers ...')\n \n # load existing fileDB\n dg.load_df()\n\n # first-time setup\n if 'startTime' not in dg.fileDB.columns or overwrite:\n df_keys = dg.fileDB.copy()\n update_existing = False\n print('Re-scanning entire fileDB')\n\n elif 'startTime' in dg.fileDB.columns:\n # look for any rows with nans to update\n idx = dg.fileDB.loc[pd.isna(dg.fileDB['startTime']), :].index\n if len(idx) > 0:\n df_keys = dg.fileDB.loc[idx].copy()\n print(f'Found {len(df_keys)} new files without startTime:')\n print(df_keys)\n update_existing = True\n else:\n print('No empty startTime values found.')\n df_keys = pd.DataFrame()\n\n if len(df_keys) == 0:\n print('No files to update. Exiting...')\n exit()\n\n # clear new colums if they exist\n new_cols = ['startTime', 'threshold', 'daq_gb']\n for col in new_cols:\n if col in df_keys.columns:\n df_keys.drop(col, axis=1, inplace=True)\n\n def scan_orca_header(df_row):\n f_daq = dg.daq_dir + df_row['daq_dir'] + '/' + df_row['daq_file']\n daq_gb = os.path.getsize(f_daq) / 1e9\n\n if not os.path.exists(f_daq) and not df_row.skip:\n print(f\"Error, file doesn't exist:\\n {f_daq}\")\n exit()\n if df_row['skip']==True:\n print(f\"Skipping cycle: {df_row['cycle']}\")\n return pd.Series({'startTime':np.nan, 'threshold':np.nan, \n 'daq_gb':daq_gb})\n else:\n _,_, header_dict = parse_header(f_daq)\n # pprint(header_dict)\n info = header_dict['ObjectInfo']\n t_start = info['DataChain'][0]['Run Control']['startTime']\n thresh = info['Crates'][0]['Cards'][1]['thresholds'][2]\n return pd.Series({'startTime':t_start, 'threshold':thresh,\n 'daq_gb':daq_gb})\n\n df_tmp = df_keys.progress_apply(scan_orca_header, axis=1)\n df_keys[new_cols] = df_tmp\n\n if update_existing:\n idx = dg.fileDB.loc[pd.isna(dg.fileDB['startTime']), :].index\n dg.fileDB.loc[idx] = df_keys\n else:\n dg.fileDB = df_keys\n\n dbg_cols = ['run', 'cycle', 'daq_file', 'startTime', 'daq_gb']\n print(dg.fileDB[dbg_cols])\n\n print('Ready to save. This will overwrite any existing fileDB.')\n if not batch_mode:\n ans = input('Save updated fileDB? (y/n):')\n if ans.lower() == 'y':\n dg.save_df(dg.config['fileDB'])\n print('fileDB updated.')\n else:\n dg.save_df(dg.config['fileDB'])\n print('fileDB updated.')\n\n\ndef get_runtimes(dg, overwrite=False, batch_mode=False):\n \"\"\"\n $ ./setup.py --rt\n \n Compute runtime (# minutes in run) and stopTime (unix timestamp) using\n the timestamps in the DSP file.\n \n NOTE: Could change this to use the raw file timestamps instead of dsp file, \n but that still makes this function dependent on a processing step.\n NOTE: CAGE uses struck channel 2 (0-indexed)\n \"\"\"\n print('Scanning DSP files for runtimes ...')\n \n # load existing fileDB\n dg.load_df()\n\n # first-time setup\n if 'runtime' not in dg.fileDB.columns or overwrite:\n df_keys = dg.fileDB.copy()\n update_existing = False\n print('Re-scanning entire fileDB')\n\n elif 'runtime' in dg.fileDB.columns:\n # look for any rows with nans to update\n idx = dg.fileDB.loc[pd.isna(dg.fileDB['runtime']), :].index\n if len(idx) > 0:\n df_keys = dg.fileDB.loc[idx].copy()\n print(f'Found {len(df_keys)} new files without runtime:')\n print(df_keys)\n update_existing = True\n else:\n print('No empty runtime values found.')\n\n if len(df_keys) == 0:\n print('No files to update. Exiting...')\n exit()\n\n # clear new colums if they exist\n new_cols = ['stopTime', 'runtime']\n for col in new_cols:\n if col in df_keys.columns:\n df_keys.drop(col, axis=1, inplace=True)\n\n sto = lh5.Store()\n def get_runtime(df_row):\n\n # load timestamps from dsp file\n f_dsp = dg.lh5_dir + df_row['dsp_path'] + '/' + df_row['dsp_file']\n\n if not os.path.exists(f_dsp) and not df_row.skip:\n print(f\"Error, file doesn't exist:\\n {f_dsp}\")\n exit()\n elif df_row.skip:\n print(f'Skipping cycle file:\\n {f_dsp}')\n return pd.Series({'stopTime':0, 'runtime':0})\n\n data, n_rows = sto.read_object('ORSIS3302DecoderForEnergy/dsp', f_dsp)\n\n # correct for timestamp rollover\n clock = 100e6 # 100 MHz\n UINT_MAX = 4294967295 # (0xffffffff)\n t_max = UINT_MAX / clock\n \n \n # ts = data['timestamp'].nda.astype(np.int64) # must be signed for np.diff\n ts = data['timestamp'].nda / clock # converts to float\n \n tdiff = np.diff(ts)\n tdiff = np.insert(tdiff, 0 , 0)\n iwrap = np.where(tdiff < 0)\n iloop = np.append(iwrap[0], len(ts))\n \n ts_new, t_roll = [], 0\n for i, idx in enumerate(iloop):\n ilo = 0 if i==0 else iwrap[0][i-1]\n ihi = idx\n ts_block = ts[ilo:ihi]\n t_last = ts[ilo-1]\n t_diff = t_max - t_last\n ts_new.append(ts_block + t_roll)\n t_roll += t_last + t_diff \n ts_corr = np.concatenate(ts_new)\n \n # calculate runtime and unix stopTime\n rt = ts_corr[-1] / 60 # minutes\n st = int(np.ceil(df_row['startTime'] + rt * 60))\n \n return pd.Series({'stopTime':st, 'runtime':rt})\n\n df_tmp = df_keys.progress_apply(get_runtime, axis=1)\n df_keys[new_cols] = df_tmp\n\n if update_existing:\n idx = dg.fileDB.loc[pd.isna(dg.fileDB['runtime']), :].index\n dg.fileDB.loc[idx] = df_keys\n else:\n dg.fileDB = df_keys\n\n dbg_cols = ['run', 'cycle', 'unique_key', 'startTime', 'runtime']\n print(dg.fileDB[dbg_cols])\n\n print('Ready to save. This will overwrite any existing fileDB.')\n if not batch_mode:\n ans = input('Save updated fileDB? (y/n):')\n if ans.lower() == 'y':\n dg.fileDB = df_keys\n dg.save_df(dg.config['fileDB'])\n print('fileDB updated.')\n else:\n dg.fileDB = df_keys\n dg.save_df(dg.config['fileDB'])\n print('fileDB updated.')\n\n\nif __name__=='__main__':\n main()\n" ]
[ [ "numpy.amax", "numpy.sqrt", "numpy.linspace", "numpy.asarray", "pandas.DataFrame", "matplotlib.pyplot.plot", "numpy.exp", "numpy.histogram", "scipy.signal.savgol_filter", "scipy.optimize.curve_fit", "numpy.where", "matplotlib.backends.backend_pdf.PdfPages", "matplotlib.colors.PowerNorm", "matplotlib.pyplot.close", "scipy.special.erf", "matplotlib.pyplot.figure", "numpy.heaviside", "matplotlib.pyplot.title", "numpy.append", "numpy.array", "numpy.sum", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.xlabel" ], [ "pandas.concat", "pandas.to_numeric", "pandas.Series", "pandas.DataFrame", "numpy.concatenate", "numpy.ceil", "numpy.diff", "numpy.insert", "pandas.isna", "numpy.where" ] ]
[ { "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", "1.1", "1.5", "0.24", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
valentinp72/espresso
[ "84c0ce6e9f47dae9fcb3b731089d27f4aad5161d" ]
[ "fairseq/dataclass/configs.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport sys\nfrom dataclasses import _MISSING_TYPE, dataclass, field\nfrom typing import Any, List, Optional\n\nimport torch\n\nfrom fairseq.dataclass.constants import (\n DATASET_IMPL_CHOICES,\n DDP_BACKEND_CHOICES,\n GENERATION_CONSTRAINTS_CHOICES,\n GENERATION_DECODING_FORMAT_CHOICES,\n LOG_FORMAT_CHOICES,\n PIPELINE_CHECKPOINT_CHOICES,\n PRINT_ALIGNMENT_CHOICES,\n ZERO_SHARDING_CHOICES,\n)\n\nfrom omegaconf import II, MISSING\n\n\n@dataclass\nclass FairseqDataclass:\n \"\"\"fairseq base dataclass that supported fetching attributes and metas\"\"\"\n\n _name: Optional[str] = None\n\n @staticmethod\n def name():\n return None\n\n def _get_all_attributes(self) -> List[str]:\n return [k for k in self.__dataclass_fields__.keys()]\n\n def _get_meta(\n self, attribute_name: str, meta: str, default: Optional[Any] = None\n ) -> Any:\n return self.__dataclass_fields__[attribute_name].metadata.get(meta, default)\n\n def _get_name(self, attribute_name: str) -> str:\n return self.__dataclass_fields__[attribute_name].name\n\n def _get_default(self, attribute_name: str) -> Any:\n if hasattr(self, attribute_name):\n if str(getattr(self, attribute_name)).startswith(\"${\"):\n return str(getattr(self, attribute_name))\n elif str(self.__dataclass_fields__[attribute_name].default).startswith(\n \"${\"\n ):\n return str(self.__dataclass_fields__[attribute_name].default)\n elif (\n getattr(self, attribute_name)\n != self.__dataclass_fields__[attribute_name].default\n ):\n return getattr(self, attribute_name)\n\n f = self.__dataclass_fields__[attribute_name]\n if not isinstance(f.default_factory, _MISSING_TYPE):\n return f.default_factory()\n return f.default\n\n def _get_type(self, attribute_name: str) -> Any:\n return self.__dataclass_fields__[attribute_name].type\n\n def _get_help(self, attribute_name: str) -> Any:\n return self._get_meta(attribute_name, \"help\")\n\n def _get_argparse_const(self, attribute_name: str) -> Any:\n return self._get_meta(attribute_name, \"argparse_const\")\n\n def _get_argparse_alias(self, attribute_name: str) -> Any:\n return self._get_meta(attribute_name, \"argparse_alias\")\n\n def _get_choices(self, attribute_name: str) -> Any:\n return self._get_meta(attribute_name, \"choices\")\n\n\n@dataclass\nclass CommonConfig(FairseqDataclass):\n # This is the core dataclass including common parameters shared by all different jobs. Please append your params to other dataclasses if they were\n # used for a particular purpose or task, such as those dedicated for `distributed training`, `optimization`, etc.\n no_progress_bar: bool = field(\n default=False, metadata={\"help\": \"disable progress bar\"}\n )\n log_interval: int = field(\n default=100,\n metadata={\n \"help\": \"log progress every N batches (when progress bar is disabled)\"\n },\n )\n log_format: Optional[LOG_FORMAT_CHOICES] = field(\n default=None, metadata={\"help\": \"log format to use\"}\n )\n log_file: Optional[str] = field(\n default=None, metadata={\"help\": \"log file to copy metrics to.\"}\n )\n tensorboard_logdir: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"path to save logs for tensorboard, should match --logdir \"\n \"of running tensorboard (default: no tensorboard logging)\"\n },\n )\n wandb_project: Optional[str] = field(\n default=None,\n metadata={\"help\": \"Weights and Biases project name to use for logging\"},\n )\n azureml_logging: Optional[bool] = field(\n default=False, metadata={\"help\": \"Log scalars to AzureML context\"},\n )\n seed: int = field(\n default=1, metadata={\"help\": \"pseudo random number generator seed\"}\n )\n cpu: bool = field(default=False, metadata={\"help\": \"use CPU instead of CUDA\"})\n tpu: bool = field(default=False, metadata={\"help\": \"use TPU instead of CUDA\"})\n bf16: bool = field(default=False, metadata={\"help\": \"use bfloat16; implies --tpu\"})\n memory_efficient_bf16: bool = field(\n default=False,\n metadata={\n \"help\": \"use a memory-efficient version of BF16 training; implies --bf16\"\n },\n )\n fp16: bool = field(default=False, metadata={\"help\": \"use FP16\"})\n memory_efficient_fp16: bool = field(\n default=False,\n metadata={\n \"help\": \"use a memory-efficient version of FP16 training; implies --fp16\"\n },\n )\n fp16_no_flatten_grads: bool = field(\n default=False, metadata={\"help\": \"don't flatten FP16 grads tensor\"}\n )\n fp16_init_scale: int = field(\n default=2 ** 7, metadata={\"help\": \"default FP16 loss scale\"}\n )\n fp16_scale_window: Optional[int] = field(\n default=None,\n metadata={\"help\": \"number of updates before increasing loss scale\"},\n )\n fp16_scale_tolerance: float = field(\n default=0.0,\n metadata={\n \"help\": \"pct of updates that can overflow before decreasing the loss scale\"\n },\n )\n min_loss_scale: float = field(\n default=1e-4,\n metadata={\"help\": \"minimum FP16 loss scale, after which training is stopped\"},\n )\n threshold_loss_scale: Optional[float] = field(\n default=None, metadata={\"help\": \"threshold FP16 loss scale from below\"}\n )\n user_dir: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"path to a python module containing custom extensions (tasks and/or architectures)\"\n },\n )\n empty_cache_freq: int = field(\n default=0,\n metadata={\"help\": \"how often to clear the PyTorch CUDA cache (0 to disable)\"},\n )\n all_gather_list_size: int = field(\n default=16384,\n metadata={\"help\": \"number of bytes reserved for gathering stats from workers\"},\n )\n model_parallel_size: int = field(\n default=1, metadata={\"help\": \"total number of GPUs to parallelize model over\"}\n )\n quantization_config_path: Optional[str] = field(\n default=None, metadata={\"help\": \"path to quantization config file\"}\n )\n profile: bool = field(\n default=False, metadata={\"help\": \"enable autograd profiler emit_nvtx\"}\n )\n reset_logging: bool = field(\n default=False,\n metadata={\n \"help\": \"when using Hydra, reset the logging at the beginning of training\"\n },\n )\n suppress_crashes: bool = field(\n default=False,\n metadata={\n \"help\": \"suppress crashes when training with the hydra_train entry point so that the \"\n \"main method can return a value (useful for sweeps)\"\n },\n )\n use_plasma_view: bool = field(\n default=False, metadata={\"help\": \"Store indices and sizes in shared memory\"}\n )\n plasma_path: Optional[str] = field(\n default=\"/tmp/plasma\",\n metadata={\n \"help\": \"path to run plasma_store, defaults to /tmp/plasma. Paths outside /tmp tend to fail.\"\n },\n )\n\n\n@dataclass\nclass DistributedTrainingConfig(FairseqDataclass):\n distributed_world_size: int = field(\n default=max(1, torch.cuda.device_count()),\n metadata={\n \"help\": \"total number of GPUs across all nodes (default: all visible GPUs)\"\n },\n )\n distributed_rank: Optional[int] = field(\n default=0, metadata={\"help\": \"rank of the current worker\"}\n )\n distributed_backend: str = field(\n default=\"nccl\", metadata={\"help\": \"distributed backend\"}\n )\n distributed_init_method: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"typically tcp://hostname:port that will be used to \"\n \"establish initial connetion\"\n },\n )\n distributed_port: int = field(\n default=-1,\n metadata={\n \"help\": \"port number (not required if using --distributed-init-method)\"\n },\n )\n device_id: int = field(\n default=0,\n metadata={\n \"help\": \"which GPU to use (usually configured automatically)\",\n \"argparse_alias\": \"--local_rank\",\n },\n )\n distributed_no_spawn: bool = field(\n default=False,\n metadata={\n \"help\": \"do not spawn multiple processes even if multiple GPUs are visible\"\n },\n )\n ddp_backend: DDP_BACKEND_CHOICES = field(\n default=\"pytorch_ddp\", metadata={\"help\": \"DistributedDataParallel backend\"}\n )\n bucket_cap_mb: int = field(\n default=25, metadata={\"help\": \"bucket size for reduction\"}\n )\n fix_batches_to_gpus: bool = field(\n default=False,\n metadata={\n \"help\": \"don't shuffle batches between GPUs; this reduces overall \"\n \"randomness and may affect precision but avoids the cost of re-reading the data\"\n },\n )\n find_unused_parameters: bool = field(\n default=False,\n metadata={\n \"help\": \"disable unused parameter detection (not applicable to \"\n \"--ddp-backend=legacy_ddp)\"\n },\n )\n fast_stat_sync: bool = field(\n default=False,\n metadata={\"help\": \"[deprecated] this is now defined per Criterion\"},\n )\n heartbeat_timeout: int = field(\n default=-1,\n metadata={\n \"help\": \"kill the job if no progress is made in N seconds; \"\n \"set to -1 to disable\"\n },\n )\n broadcast_buffers: bool = field(\n default=False,\n metadata={\n \"help\": \"Copy non-trainable parameters between GPUs, such as \"\n \"batchnorm population statistics\"\n },\n )\n slowmo_momentum: Optional[float] = field(\n default=None,\n metadata={\n \"help\": \"SlowMo momentum term; by default use 0.0 for 16 GPUs, \"\n \"0.2 for 32 GPUs; 0.5 for 64 GPUs, 0.6 for > 64 GPUs\"\n },\n )\n slowmo_algorithm: str = field(\n default=\"LocalSGD\", metadata={\"help\": \"whether to use LocalSGD or SGP\"}\n )\n localsgd_frequency: int = field(\n default=3, metadata={\"help\": \"Local SGD allreduce frequency\"}\n )\n nprocs_per_node: int = field(\n default=max(1, torch.cuda.device_count()),\n metadata={\n \"help\": \"number of GPUs in each node. An allreduce operation across GPUs in \"\n \"a node is very fast. Hence, we do allreduce across GPUs in a node, \"\n \"and gossip across different nodes\"\n },\n )\n pipeline_model_parallel: bool = field(\n default=False,\n metadata={\"help\": \"if set, use pipeline model parallelism across GPUs\"},\n )\n pipeline_balance: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"partition the model into N_K pieces, where each piece \"\n \"contains N_i layers. The sum(args.pipeline_balance) \"\n \"should equal the total number of layers in the model\"\n },\n )\n pipeline_devices: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"a list of device indices indicating which device to place \"\n \"each of the N_K partitions. The length of this list should \"\n \"equal the length of the --pipeline-balance argument\"\n },\n )\n pipeline_chunks: Optional[int] = field(\n default=0, metadata={\"help\": \"microbatch count for pipeline model parallelism\"}\n )\n pipeline_encoder_balance: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"partition the pipeline parallel encoder into N_K pieces, where each piece \"\n \"contains N_i layers. The sum(args.pipeline_encoder_balance) \"\n \"should equal the total number of encoder layers in the model\"\n },\n )\n pipeline_encoder_devices: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"a list of device indices indicating which device to place \"\n \"each of the N_K partitions. The length of this list should \"\n \"equal the length of the --pipeline-encoder-balance argument\"\n },\n )\n pipeline_decoder_balance: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"partition the pipeline parallel decoder into N_K pieces, where each piece \"\n \"contains N_i layers. The sum(args.pipeline_decoder_balance) \"\n \"should equal the total number of decoder layers in the model\"\n },\n )\n pipeline_decoder_devices: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"a list of device indices indicating which device to place \"\n \"each of the N_K partitions. The length of this list should \"\n \"equal the length of the --pipeline-decoder-balance argument\"\n },\n )\n pipeline_checkpoint: PIPELINE_CHECKPOINT_CHOICES = field(\n default=\"never\",\n metadata={\"help\": \"checkpointing mode for pipeline model parallelism\"},\n )\n zero_sharding: ZERO_SHARDING_CHOICES = field(\n default=\"none\", metadata={\"help\": \"ZeRO sharding\"}\n )\n fp16: bool = II(\"common.fp16\")\n memory_efficient_fp16: bool = II(\"common.memory_efficient_fp16\")\n tpu: bool = II(\"common.tpu\")\n # configuration for --ddp-backend=fully_sharded\n no_reshard_after_forward: bool = field(\n default=False, metadata={\"help\": \"don't reshard parameters after forward pass\"},\n )\n fp32_reduce_scatter: bool = field(\n default=False, metadata={\"help\": \"reduce-scatter grads in FP32\"},\n )\n cpu_offload: bool = field(\n default=False, metadata={\"help\": \"offload FP32 params to CPU\"}\n )\n\n\n@dataclass\nclass DatasetConfig(FairseqDataclass):\n num_workers: int = field(\n default=1, metadata={\"help\": \"how many subprocesses to use for data loading\"}\n )\n skip_invalid_size_inputs_valid_test: bool = field(\n default=False,\n metadata={\"help\": \"ignore too long or too short lines in valid and test set\"},\n )\n max_tokens: Optional[int] = field(\n default=None, metadata={\"help\": \"maximum number of tokens in a batch\"}\n )\n batch_size: Optional[int] = field(\n default=None,\n metadata={\n \"help\": \"number of examples in a batch\",\n \"argparse_alias\": \"--max-sentences\",\n },\n )\n required_batch_size_multiple: int = field(\n default=8, metadata={\"help\": \"batch size will be a multiplier of this value\"}\n )\n required_seq_len_multiple: int = field(\n default=1,\n metadata={\n \"help\": \"maximum sequence length in batch will be a multiplier of this value\"\n },\n )\n dataset_impl: Optional[DATASET_IMPL_CHOICES] = field(\n default=None, metadata={\"help\": \"output dataset implementation\"}\n )\n data_buffer_size: int = field(\n default=10, metadata={\"help\": \"Number of batches to preload\"}\n )\n train_subset: str = field(\n default=\"train\",\n metadata={\"help\": \"data subset to use for training (e.g. train, valid, test)\"},\n )\n valid_subset: str = field(\n default=\"valid\",\n metadata={\n \"help\": \"comma separated list of data subsets to use for validation\"\n \" (e.g. train, valid, test)\"\n },\n )\n validate_interval: int = field(\n default=1, metadata={\"help\": \"validate every N epochs\"}\n )\n validate_interval_updates: int = field(\n default=0, metadata={\"help\": \"validate every N updates\"}\n )\n validate_after_updates: int = field(\n default=0, metadata={\"help\": \"dont validate until reaching this many updates\"}\n )\n fixed_validation_seed: Optional[int] = field(\n default=None, metadata={\"help\": \"specified random seed for validation\"}\n )\n disable_validation: bool = field(\n default=False, metadata={\"help\": \"disable validation\"}\n )\n max_tokens_valid: Optional[int] = field(\n default=II(\"dataset.max_tokens\"),\n metadata={\n \"help\": \"maximum number of tokens in a validation batch\"\n \" (defaults to --max-tokens)\"\n },\n )\n batch_size_valid: Optional[int] = field(\n default=II(\"dataset.batch_size\"),\n metadata={\n \"help\": \"batch size of the validation batch (defaults to --batch-size)\",\n \"argparse_alias\": \"--max-sentences-valid\",\n },\n )\n max_valid_steps: Optional[int] = field(default=None, metadata={'help': 'How many batches to evaluate',\n \"argparse_alias\": \"--nval\"})\n curriculum: int = field(\n default=0, metadata={\"help\": \"don't shuffle batches for first N epochs\"}\n )\n gen_subset: str = field(\n default=\"test\",\n metadata={\"help\": \"data subset to generate (train, valid, test)\"},\n )\n num_shards: int = field(\n default=1, metadata={\"help\": \"shard generation over N shards\"}\n )\n shard_id: int = field(\n default=0, metadata={\"help\": \"id of the shard to generate (id < num_shards)\"}\n )\n\n\n@dataclass\nclass OptimizationConfig(FairseqDataclass):\n max_epoch: int = field(\n default=0, metadata={\"help\": \"force stop training at specified epoch\"}\n )\n max_update: int = field(\n default=0, metadata={\"help\": \"force stop training at specified update\"}\n )\n stop_time_hours: float = field(\n default=0,\n metadata={\n \"help\": \"force stop training after specified cumulative time (if >0)\"\n },\n )\n clip_norm: float = field(\n default=0.0, metadata={\"help\": \"clip threshold of gradients\"}\n )\n sentence_avg: bool = field(\n default=False,\n metadata={\n \"help\": \"normalize gradients by the number of sentences in a batch\"\n \" (default is to normalize by number of tokens)\"\n },\n )\n update_freq: List[int] = field(\n default_factory=lambda: [1],\n metadata={\"help\": \"update parameters every N_i batches, when in epoch i\"},\n )\n lr: List[float] = field(\n default_factory=lambda: [0.25],\n metadata={\n \"help\": \"learning rate for the first N epochs; all epochs >N using LR_N\"\n \" (note: this may be interpreted differently depending on --lr-scheduler)\"\n },\n )\n stop_min_lr: float = field(\n default=-1.0,\n metadata={\"help\": \"stop training when the learning rate reaches this minimum\"},\n )\n use_bmuf: bool = field(\n default=False,\n metadata={\n \"help\": \"specify global optimizer for syncing models on different GPUs/shards\"\n },\n )\n\n\n@dataclass\nclass CheckpointConfig(FairseqDataclass):\n save_dir: str = field(\n default=\"checkpoints\", metadata={\"help\": \"path to save checkpoints\"}\n )\n restore_file: str = field(\n default=\"checkpoint_last.pt\",\n metadata={\n \"help\": \"filename from which to load checkpoint \"\n \"(default: <save-dir>/checkpoint_last.pt\"\n },\n )\n finetune_from_model: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"finetune from a pretrained model; note that meters and lr scheduler will be reset\"\n },\n )\n reset_dataloader: bool = field(\n default=False,\n metadata={\n \"help\": \"if set, does not reload dataloader state from the checkpoint\"\n },\n )\n reset_lr_scheduler: bool = field(\n default=False,\n metadata={\n \"help\": \"if set, does not load lr scheduler state from the checkpoint\"\n },\n )\n reset_meters: bool = field(\n default=False,\n metadata={\"help\": \"if set, does not load meters from the checkpoint\"},\n )\n reset_optimizer: bool = field(\n default=False,\n metadata={\"help\": \"if set, does not load optimizer state from the checkpoint\"},\n )\n optimizer_overrides: str = field(\n default=\"{}\",\n metadata={\n \"help\": \"a dictionary used to override optimizer args when loading a checkpoint\"\n },\n )\n save_interval: int = field(\n default=1, metadata={\"help\": \"save a checkpoint every N epochs\"}\n )\n save_interval_updates: int = field(\n default=0, metadata={\"help\": \"save a checkpoint (and validate) every N updates\"}\n )\n keep_interval_updates: int = field(\n default=-1,\n metadata={\n \"help\": \"keep the last N checkpoints saved with --save-interval-updates\"\n },\n )\n keep_interval_updates_pattern: int = field(\n default=-1,\n metadata={\n \"help\": \"when used with --keep-interval-updates, skips deleting \"\n \"any checkpoints with update X where \"\n \"X % keep_interval_updates_pattern == 0\"\n },\n )\n keep_last_epochs: int = field(\n default=-1, metadata={\"help\": \"keep last N epoch checkpoints\"}\n )\n keep_best_checkpoints: int = field(\n default=-1, metadata={\"help\": \"keep best N checkpoints based on scores\"}\n )\n no_save: bool = field(\n default=False, metadata={\"help\": \"don't save models or checkpoints\"}\n )\n no_epoch_checkpoints: bool = field(\n default=False, metadata={\"help\": \"only store last and best checkpoints\"}\n )\n no_last_checkpoints: bool = field(\n default=False, metadata={\"help\": \"don't store last checkpoints\"}\n )\n no_save_optimizer_state: bool = field(\n default=False,\n metadata={\"help\": \"don't save optimizer-state as part of checkpoint\"},\n )\n best_checkpoint_metric: str = field(\n default=\"loss\", metadata={\"help\": 'metric to use for saving \"best\" checkpoints'}\n )\n maximize_best_checkpoint_metric: bool = field(\n default=False,\n metadata={\n \"help\": 'select the largest metric value for saving \"best\" checkpoints'\n },\n )\n patience: int = field(\n default=-1,\n metadata={\n \"help\": (\n \"early stop training if valid performance doesn't \"\n \"improve for N consecutive validation runs; note \"\n \"that this is influenced by --validate-interval\"\n )\n },\n )\n checkpoint_suffix: str = field(\n default=\"\", metadata={\"help\": \"suffix to add to the checkpoint file name\"}\n )\n checkpoint_shard_count: int = field(\n default=1,\n metadata={\n \"help\": \"Number of shards containing the checkpoint - \"\n \"if the checkpoint is over 300GB, it is preferable \"\n \"to split it into shards to prevent OOM on CPU while loading \"\n \"the checkpoint\"\n },\n )\n load_checkpoint_on_all_dp_ranks: bool = field(\n default=False,\n metadata={\n \"help\": \"load checkpoints on all data parallel devices \"\n \"(default: only load on rank 0 and broadcast to other devices)\"\n },\n )\n write_checkpoints_asynchronously: bool = field(\n default=False,\n metadata={\n \"help\": (\n \"Write checkpoints asynchronously in a separate \"\n \"thread. NOTE: This feature is currently being tested.\"\n ),\n \"argparse_alias\": \"--save-async\",\n },\n )\n model_parallel_size: int = II(\"common.model_parallel_size\")\n\n\n@dataclass\nclass FairseqBMUFConfig(FairseqDataclass):\n block_lr: float = field(\n default=1, metadata={\"help\": \"block learning rate for bmuf\"}\n )\n block_momentum: float = field(\n default=0.875, metadata={\"help\": \"block momentum for bmuf\"}\n )\n global_sync_iter: int = field(\n default=50, metadata={\"help\": \"Iteration for syncing global model\"}\n )\n warmup_iterations: int = field(\n default=500, metadata={\"help\": \"warmup iterations for model to broadcast\"}\n )\n use_nbm: bool = field(\n default=False,\n metadata={\"help\": \"Specify whether you want to use classical BM / Nesterov BM\"},\n )\n average_sync: bool = field(\n default=False,\n metadata={\n \"help\": \"Specify whether you want to average the local momentum after each sync\"\n },\n )\n distributed_world_size: int = II(\"distributed_training.distributed_world_size\")\n\n\n@dataclass\nclass GenerationConfig(FairseqDataclass):\n beam: int = field(\n default=5, metadata={\"help\": \"beam size\"},\n )\n nbest: int = field(\n default=1, metadata={\"help\": \"number of hypotheses to output\"},\n )\n max_len_a: float = field(\n default=0,\n metadata={\n \"help\": \"generate sequences of maximum length ax + b, where x is the source length\"\n },\n )\n max_len_b: int = field(\n default=200,\n metadata={\n \"help\": \"generate sequences of maximum length ax + b, where x is the source length\"\n },\n )\n min_len: int = field(\n default=1, metadata={\"help\": \"minimum generation length\"},\n )\n match_source_len: bool = field(\n default=False, metadata={\"help\": \"generations should match the source length\"},\n )\n unnormalized: bool = field(\n default=False, metadata={\"help\": \"compare unnormalized hypothesis scores\"},\n )\n no_early_stop: bool = field(\n default=False, metadata={\"help\": \"deprecated\"},\n )\n no_beamable_mm: bool = field(\n default=False, metadata={\"help\": \"don't use BeamableMM in attention layers\"},\n )\n lenpen: float = field(\n default=1,\n metadata={\n \"help\": \"length penalty: <1.0 favors shorter, >1.0 favors longer sentences\"\n },\n )\n unkpen: float = field(\n default=0,\n metadata={\n \"help\": \"unknown word penalty: <0 produces more unks, >0 produces fewer\"\n },\n )\n replace_unk: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"perform unknown replacement (optionally with alignment dictionary)\",\n \"argparse_const\": \"@@ \",\n },\n )\n sacrebleu: bool = field(\n default=False, metadata={\"help\": \"score with sacrebleu\"},\n )\n score_reference: bool = field(\n default=False, metadata={\"help\": \"just score the reference translation\"},\n )\n prefix_size: int = field(\n default=0,\n metadata={\"help\": \"initialize generation by target prefix of given length\"},\n )\n no_repeat_ngram_size: int = field(\n default=0,\n metadata={\n \"help\": \"ngram blocking such that this size ngram cannot be repeated in the generation\"\n },\n )\n sampling: bool = field(\n default=False,\n metadata={\"help\": \"sample hypotheses instead of using beam search\"},\n )\n sampling_topk: int = field(\n default=-1,\n metadata={\"help\": \"sample from top K likely next words instead of all words\"},\n )\n sampling_topp: float = field(\n default=-1.0,\n metadata={\n \"help\": \"sample from the smallest set whose cumulative probability mass exceeds p for next words\"\n },\n )\n constraints: Optional[GENERATION_CONSTRAINTS_CHOICES] = field(\n default=None,\n metadata={\n \"help\": \"enables lexically constrained decoding\",\n \"argparse_const\": \"ordered\",\n },\n )\n temperature: float = field(\n default=1.0, metadata={\"help\": \"temperature for generation\"},\n )\n diverse_beam_groups: int = field(\n default=-1, metadata={\"help\": \"number of groups for Diverse Beam Search\"},\n )\n diverse_beam_strength: float = field(\n default=0.5,\n metadata={\"help\": \"strength of diversity penalty for Diverse Beam Search\"},\n )\n diversity_rate: float = field(\n default=-1.0,\n metadata={\"help\": \"strength of diversity penalty for Diverse Siblings Search\"},\n )\n print_alignment: Optional[PRINT_ALIGNMENT_CHOICES] = field(\n default=None,\n metadata={\n \"help\": \"if set, uses attention feedback to compute and print alignment to source tokens \"\n \"(valid options are: hard, soft, otherwise treated as hard alignment)\",\n \"argparse_const\": \"hard\",\n },\n )\n print_step: bool = field(\n default=False, metadata={\"help\": \"print steps\"},\n )\n lm_path: Optional[str] = field(\n default=None, metadata={\"help\": \"path to lm checkpoint for lm fusion\"},\n )\n lm_weight: float = field(\n default=0.0, metadata={\"help\": \"weight for lm probs for lm fusion\"},\n )\n\n # arguments for iterative refinement generator\n iter_decode_eos_penalty: float = field(\n default=0.0,\n metadata={\"help\": \"if > 0.0, it penalized early-stopping in decoding.\"},\n )\n iter_decode_max_iter: int = field(\n default=10, metadata={\"help\": \"maximum iterations for iterative refinement.\"},\n )\n iter_decode_force_max_iter: bool = field(\n default=False,\n metadata={\n \"help\": \"if set, run exact the maximum number of iterations without early stop\"\n },\n )\n iter_decode_with_beam: int = field(\n default=1,\n metadata={\n \"help\": \"if > 1, model will generate translations varying by the lengths.\"\n },\n )\n iter_decode_with_external_reranker: bool = field(\n default=False,\n metadata={\n \"help\": \"if set, the last checkpoint are assumed to be a reranker to rescore the translations\"\n },\n )\n retain_iter_history: bool = field(\n default=False,\n metadata={\n \"help\": \"if set, decoding returns the whole history of iterative refinement\"\n },\n )\n retain_dropout: bool = field(\n default=False, metadata={\"help\": \"Use dropout at inference time\"},\n )\n # temporarily set to Any until https://github.com/facebookresearch/hydra/issues/1117 is fixed\n # retain_dropout_modules: Optional[List[str]] = field(\n retain_dropout_modules: Any = field(\n default=None,\n metadata={\n \"help\": \"if set, only retain dropout for the specified modules; \"\n \"if not set, then dropout will be retained for all modules\"\n },\n )\n # special decoding format for advanced decoding.\n decoding_format: Optional[GENERATION_DECODING_FORMAT_CHOICES] = field(\n default=None,\n metadata={\"help\": \"special decoding format for advanced decoding.\"},\n )\n no_seed_provided: bool = field(\n default=False,\n metadata={\"help\": \"if set, dont use seed for initializing random generators\"},\n )\n # for espresso.speech_recognize.py\n eos_factor: Optional[float] = field(\n default=None,\n metadata={\n \"help\": \"only consider emitting EOS if its score is no less than \"\n \"the specified factor of the best candidate score\"\n },\n )\n subwordlm_weight: Optional[float] = field(\n default=0.8,\n metadata={\n \"help\": \"subword LM weight relative to word LM. Only relevant to \"\n \"MultiLevelLanguageModel as an external LM\"\n },\n )\n oov_penalty: Optional[float] = field(\n default=1e-4,\n metadata={\"help\": \"oov penalty with the pretrained external LM\"},\n )\n disable_open_vocab: Optional[bool] = field(\n default=False,\n metadata={\n \"help\": \"whether open vocabulary mode is enabled with the \"\n \"pretrained external LM\"\n },\n )\n # for espresso.dump_posteriors.py\n apply_log_softmax: Optional[bool] = field(\n default=False,\n metadata={\n \"help\": \"apply log-softmax to the neural network outputs for Xent \"\n \"hybrid systems; otherwise use the raw outputs\"\n },\n )\n state_prior_file: Optional[str] = field(\n default=None,\n metadata={\n \"help\": \"state prior file. If provided, use this file instead of \"\n \"that from the checkpoint\"\n },\n )\n\n\n@dataclass\nclass CommonEvalConfig(FairseqDataclass):\n path: Optional[str] = field(\n default=None, metadata={\"help\": \"path(s) to model file(s), colon separated\"},\n )\n post_process: Optional[str] = field(\n default=None,\n metadata={\n \"help\": (\n \"post-process text by removing BPE, letter segmentation, etc. \"\n \"Valid options can be found in fairseq.data.utils.post_process.\"\n ),\n \"argparse_const\": \"subword_nmt\",\n \"argparse_alias\": \"--remove-bpe\",\n },\n )\n quiet: bool = field(default=False, metadata={\"help\": \"only print final scores\"})\n model_overrides: str = field(\n default=\"{}\",\n metadata={\n \"help\": \"a dictionary used to override model args at generation that were used during model training\"\n },\n )\n results_path: Optional[str] = field(\n default=None, metadata={\"help\": \"path to save eval results (optional)\"}\n )\n\n\n@dataclass\nclass EvalLMConfig(FairseqDataclass):\n output_word_probs: bool = field(\n default=False,\n metadata={\n \"help\": \"if set, outputs words and their predicted log probabilities to standard output\"\n },\n )\n output_word_stats: bool = field(\n default=False,\n metadata={\n \"help\": \"if set, outputs word statistics such as word count, average probability, etc\"\n },\n )\n context_window: int = field(\n default=0,\n metadata={\n \"help\": \"ensures that every evaluated token has access to a context of at least this size, if possible\"\n },\n )\n softmax_batch: int = field(\n default=sys.maxsize,\n metadata={\n \"help\": \"if BxT is more than this, will batch the softmax over vocab to this amount of tokens, in order to fit into GPU memory\"\n },\n )\n\n\n@dataclass\nclass InteractiveConfig(FairseqDataclass):\n buffer_size: int = field(\n default=0,\n metadata={\n \"help\": \"read this many sentences into a buffer before processing them\"\n },\n )\n input: str = field(\n default=\"-\", metadata={\"help\": \"file to read from; use - for stdin\"},\n )\n\n\n@dataclass\nclass FairseqConfig(FairseqDataclass):\n common: CommonConfig = CommonConfig()\n common_eval: CommonEvalConfig = CommonEvalConfig()\n distributed_training: DistributedTrainingConfig = DistributedTrainingConfig()\n dataset: DatasetConfig = DatasetConfig()\n optimization: OptimizationConfig = OptimizationConfig()\n checkpoint: CheckpointConfig = CheckpointConfig()\n bmuf: FairseqBMUFConfig = FairseqBMUFConfig()\n generation: GenerationConfig = GenerationConfig()\n eval_lm: EvalLMConfig = EvalLMConfig()\n interactive: InteractiveConfig = InteractiveConfig()\n model: Any = MISSING\n task: Any = None\n criterion: Any = None\n optimizer: Any = None\n lr_scheduler: Any = None\n scoring: Any = None\n bpe: Any = None\n tokenizer: Any = None\n" ]
[ [ "torch.cuda.device_count" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rlowrance/mlpack
[ "4a09987fd5efb9736284c94d90aa51b34d4bce7f" ]
[ "module_linear_n.py" ]
[ "'''linear mode with 1 or more outputs'''\nimport numpy as np\nimport unittest\nimport pdb\n\n\ndef linear_n(num_inputs, num_outputs):\n assert num_inputs >= 1\n assert num_outputs >= 1\n\n def split(theta):\n '''bias vector and weight matrix'''\n b = theta[:num_outputs]\n w = theta[num_outputs:].reshape(num_outputs, num_inputs)\n return b, w\n\n def output(theta, x):\n '''vector size num_outputs'''\n assert x.ndim == 1 # however, code works for x.ndim == 2\n b, w = split(theta)\n r = (b + np.dot(x, w.T))\n return r\n\n def gradient(x):\n '''matrix size(num_outputs, num_inputs)'''\n # NOTE: only include arguments actually used\n # NOTE: always return 2d result\n r1 = np.tile(np.hstack((1, x)), num_outputs)\n return r1.reshape(num_outputs, num_inputs + 1)\n\n return gradient, output\n\n\nclass Test(unittest.TestCase):\n def test_1_output(self):\n num_inputs = 2\n num_outputs = 1\n _, output = linear_n(num_inputs, num_outputs)\n theta = np.array([-1, 2, -3])\n x = np.array([4, -5])\n actual = output(theta, x)\n expected = np.array([-1 + 2 * 4 - 3 * -5])\n self.assertEqual(actual.ndim, 1)\n self.assertEqual(actual.shape, (num_outputs,))\n diff = np.linalg.norm(actual - expected)\n self.assertLess(diff, 1e-3)\n\n def test_1_gradient(self):\n num_inputs = 2\n num_outputs = 1\n gradient, _ = linear_n(num_inputs, num_outputs)\n x = np.array([4, -5])\n actual = gradient(x)\n expected = np.hstack((1, x))\n self.assertEqual(actual.ndim, 2)\n self.assertEqual(actual.shape, (num_outputs, num_inputs + 1))\n diff = np.linalg.norm(actual - expected)\n self.assertLess(diff, 1e-3)\n\n def test_3_output(self):\n num_inputs = 2\n num_outputs = 3\n _, output = linear_n(num_inputs, num_outputs)\n theta = np.array([-1, 2, -3, 4, -5, 6, -7, 8, -9])\n x = np.array([4, -5])\n actual = output(theta, x)\n expected = np.array([-1 + 4 * 4 - 5 * -5,\n 2 + 6 * 4 - 7 * -5,\n -3 + 8 * 4 - 9 * -5])\n self.assertEqual(actual.ndim, 1)\n self.assertEqual(actual.shape, (num_outputs,))\n diff = np.linalg.norm(actual - expected)\n self.assertLess(diff, 1e-3)\n\n def test_3_gradient(self):\n num_inputs = 2\n num_outputs = 3\n gradient, _ = linear_n(num_inputs, num_outputs)\n x = np.array([4, -5])\n actual = gradient(x)\n row = np.hstack((1, x))\n expected = np.array([row, row, row])\n self.assertEqual(actual.ndim, 2)\n self.assertEqual(actual.shape, (num_outputs, num_inputs + 1))\n diff = np.linalg.norm(actual - expected)\n self.assertLess(diff, 1e-3)\n\n\nif __name__ == '__main__':\n if False:\n pdb.set_trace()\n unittest.main()\n" ]
[ [ "numpy.hstack", "numpy.dot", "numpy.array", "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": [] } ]
matthiasdusch/phoeton
[ "9cff26121dc15e9455fbf514f60cc0123280f337" ]
[ "tests/test_tsplots.py" ]
[ "import pytest\nfrom unittest.mock import patch\nimport os\nimport pandas as pd\nfrom copy import deepcopy\nimport matplotlib.pyplot as plt\n\nfrom foehnix.analysis_plots import tsplot, TSControl, image\n\n\ndef test_tsplot_api_control(caplog, tyr_mod1):\n # Test some wrong inputs to the plot API\n with pytest.raises(AttributeError) as e:\n tsplot('foo')\n assert e.match('First Attribute must be a foehnix mixture model')\n\n # test control userdict and kwargs\n _tsc = TSControl(tyr_mod1, userdict={'foo': ['bar', 'r', 'foobar']})\n assert ('Key \"foo\" not valid. Default values will' in\n caplog.records[-1].message)\n _tsc = TSControl(tyr_mod1, foo='bar')\n assert ('Kwarg \"foo\" not valid. Default values will' in\n caplog.records[-1].message)\n\n # change variables to wrong names\n _tsc = TSControl(tyr_mod1, t='temp')\n assert ('Variable >> temp << not found in the data.' in\n caplog.records[-1].message)\n _tsc = TSControl(tyr_mod1, userdict={'ff': ['windsp', 0, 0],\n 'ffx': ['gust', 0, 0],\n 'dd': ['winddir', 0, 0],\n 'rh': ['relhum', 0, 0],\n 'diff_t': ['temp differ', 0, 0]})\n assert ('Variable >> relhum << not' in caplog.records[-5].message)\n assert ('Variable >> temp differ << not' in caplog.records[-4].message)\n assert ('Variable >> winddir << not' in caplog.records[-3].message)\n assert ('Variable >> windsp << not' in caplog.records[-2].message)\n assert ('Variable >> gust << not' in caplog.records[-1].message)\n\n\ndef test_tsplot_start_end(caplog, tyr_mod1):\n # test a out of bounds start date\n tyr_mod1.plot('timeseries', start='1. Feber 2005', end='2006-01-09',\n showplot=False)\n assert ('Could not convert start value to Datetime.' in\n caplog.records[-1].message)\n\n # test a out of bounds end date\n tyr_mod1.plot('timeseries', start='2018-12-24', end='20022-02-22',\n showplot=False)\n assert ('Could not convert end value to Datetime.' in\n caplog.records[-1].message)\n\n\n@patch('matplotlib.pyplot.show')\ndef test_tsplot_show(_mock_show, caplog, tyr_mod1):\n # make 3 plots and show them without saving\n tyr_mod1.plot('timeseries', start='2011-10-01', end='2011-10-25', ndays=10,\n showplot=True, saveplot=False, show_n_plots=1)\n # this should be the last figure\n assert ('Foehn Diagnosis 2011-10-21 to 2011-10-31' in\n plt.gcf().texts[0].get_text())\n\n\ndef test_tsplot_plot_and_save(tmp_path, caplog, tyr_mod1):\n # temporary file to store plots\n path = tmp_path / 'plots'\n path.mkdir()\n\n # make exactly 5 plots and save them\n tyr_mod1.plot('timeseries', start='2010-01-01', end='2010-01-22', ndays=5,\n showplot=False, saveplot=True,\n savedir=path.as_posix())\n assert os.path.exists(os.path.join(path.as_posix(),\n 'foehnix_timeseries_04.png'))\n assert os.path.exists(os.path.join(path.as_posix(),\n 'foehnix_timeseries_05.png')) is False\n\n # make 1 pdf plot\n tyr_mod1.plot('timeseries', start='2010-01-01', end='2010-01-02', ndays=3,\n showplot=False, saveplot=True,\n savedir=path.as_posix(), savefilename='tsplot.pdf')\n assert os.path.exists(os.path.join(path.as_posix(), 'tsplot_00.pdf'))\n\n\ndef test_image_api(tyr_mod1):\n # Test some wrong inputs to the plot API\n with pytest.raises(AttributeError) as e:\n image('foo')\n assert e.match('First Attribute must be a foehnix mixture model')\n # wrong function\n with pytest.raises(ValueError) as e:\n tyr_mod1.plot('image', fun='foo')\n assert e.match('Aggregation function `fun` must either be one')\n\n # modify the index to make it non monotonic\n fakemod = deepcopy(tyr_mod1)\n idx = fakemod.prob.prob.index.tolist()\n idx[1] = idx[3]\n fakemod.prob.prob.index = idx\n with pytest.raises(RuntimeError) as e:\n fakemod.plot('image')\n assert e.match('DataFrame index is not monotonic increasing!')\n\n # modify the index to make it non regular\n idx[1] = idx[2] - pd.to_timedelta('1S')\n fakemod.prob.prob.index = idx\n with pytest.raises(RuntimeError) as e:\n fakemod.plot('image')\n assert e.match('DataFrame index is not strictly regular')\n\n # give a wrong delta t\n with pytest.raises(ValueError) as e:\n tyr_mod1.plot('image', deltat=1000)\n assert e.match('`deltat` must be a fraction of 86400 seconds')\n\n # give a wrong delta d\n with pytest.raises(ValueError) as e:\n tyr_mod1.plot('image', deltad=400)\n assert e.match('must be a integer within')\n\n\ndef test_image_plot_and_save(tmp_path, caplog, tyr_mod1):\n # temporary file to store plots\n path = tmp_path / 'plots'\n path.mkdir()\n\n # basic hovmoeller plot, but a too small delta t should log a warning\n tyr_mod1.plot('image', deltat=1800, showplot=False, saveplot=True,\n savedir=path.as_posix())\n # check for the upsampling message\n assert ('Upsampling is not allowed:' in caplog.records[-1].message)\n # check if plot got saved correctly\n assert os.path.exists(os.path.join(path.as_posix(),\n 'foehnix_hovmoeller.png'))\n # test some labels\n assert 'Hovmoeller Diagram' in plt.gcf().axes[0].get_title()\n assert 'time of the year' in plt.gcf().axes[0].get_xlabel()\n assert 'time of the day' in plt.gcf().axes[0].get_ylabel()\n\n # advanced plot with custom title and pdf\n tyr_mod1.plot('image', fun='occ', deltat=3600, title='Test title',\n xlabel='Test xlabel', ylabel='Test ylabel',\n showplot=False, saveplot=True, savedir=path.as_posix(),\n savefilename='foehnix_hov.pdf')\n # check if plot got saved correctly\n assert os.path.exists(os.path.join(path.as_posix(),\n 'foehnix_hov.pdf'))\n assert 'Test title' in plt.gcf().axes[0].get_title()\n assert 'Test xlabel' in plt.gcf().axes[0].get_xlabel()\n assert 'Test ylabel' in plt.gcf().axes[0].get_ylabel()\n" ]
[ [ "pandas.to_timedelta", "matplotlib.pyplot.gcf" ] ]
[ { "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": [] } ]
RWTH-EBC/X-HD
[ "55b9066e8fc1107f70c0a9cf49aa5ff4d812823c" ]
[ "HSM-Design/Functions_GUI/Functions.py" ]
[ "import json\nimport numpy as np\nimport os\nimport sys\nfrom teaser.project import Project\nimport DyMat\nfrom scipy.io import savemat, loadmat\nimport openpyxl as xl\nfrom pathlib import Path\n\n# paths\n# TODO: ask for paths in app once\nPATH_DYMOLA = r\"C:\\Program Files\\Dymola 2021\"\ncomp_path = r\"C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Auxiliary\\Build\"\n\nres_path = os.path.join(Path(__file__).parents[1], 'Results')\nAixlib_path = os.path.join(Path(__file__).parents[1], 'Modelica', 'AixLib', 'Aixlib')\nOutput_path = os.path.join(Path(__file__).parents[1], 'Results', 'Teaser_Output')\nWPSmodel_path = os.path.join(Path(__file__).parents[2], 'VCLib', 'HeatPumpFlowSheets', 'HPS_model') # path to HPS model\n\nif not os.path.exists(res_path):\n os.mkdir(res_path)\n print(\"Directory \", res_path, \" Created \")\n os.mkdir(res_path + \"/DIN\")\n os.mkdir(res_path + \"/VDI\")\n os.mkdir(res_path + \"/Teaser_Output\")\n\nif not os.path.exists(os.path.join(PATH_DYMOLA, \"Modelica\", \"Library\", \"python_interface\")):\n sys.exit(\"[ERROR] Python Interface was not found in given folder. Program will be aborted!\")\nsys.path.insert(0, os.path.join(PATH_DYMOLA, r'Modelica\\Library\\python_interface\\dymola.egg'))\nfrom dymola.dymola_interface import DymolaInterface\n\n\ndef jahressim(model_path, model_name, result_path, initial_values,\n stoptime=32400000):\n \"\"\"Simulates a simple heat pump system to get performance data over a year. model_path is the path to the\n corresponding modelica model. model_name is the name of the model in Dymola. result_path is the path in which\n the result file is stored. initial_values is a list with the design of the WPS in the order: [q_flow_hp_biv,\n q_flow_hr, v_buffer_sto, v_dhw_sto]. stoptime describes the simulation time. default is one year plus ten days\n for initialization. Returns the path to the result file.\"\"\"\n dymola = DymolaInterface(dymolapath=os.path.join(PATH_DYMOLA, 'bin64', 'Dymola.exe'),\n showwindow=False)\n try:\n\n dymola.openModel(path=os.path.join(Aixlib_path, 'package.mo'))\n dymola.openModel(model_path)\n dymola.SetDymolaCompiler(\"vs\", [\"CCompiler=MSVC\", \"MSVCDir=\" + comp_path])\n dymola.experimentSetupOutput(events=False)\n # Parameters to change\n initial_names = ['Q_flow_hp_biv', 'Q_flow_hr', 'v_buffer_sto',\n 'v_dhw_sto', 'filename_T_amb', 'filename_Qdem', 'filename_DHW']\n initial_values = initial_values + ['Functions_GUI/matFiles/ambTemp.mat', 'Functions_GUI/matFiles/DHW.mat',\n 'Functions_GUI/matFiles/heat.mat']\n dymola.simulateExtendedModel(\n problem=model_name,\n startTime=0.0,\n stopTime=stoptime,\n outputInterval=3600,\n tolerance=0.001,\n resultFile=os.path.join(result_path, 'result'),\n initialNames=initial_names,\n initialValues=initial_values\n )\n except ValueError:\n print(\"[ERROR with Dymola. Please check model]\")\n dymola.close()\n return os.path.join(result_path, 'result.mat')\n\n\ndef teasersim(config_name, weatherdatakreis=None, create_heat_mat=False):\n \"\"\"Simulates Teaser model based on building inputs stored in the config, which path is given in config_name.\n weatherdatakreis is an optional argument to use a individual .mos file for the simulation. The default is the\n .mos file specified in the config file. create_heat_mat is Boolean, if it is set to true, a mat file with the\n heat demand over time is stored in the mat_files folder. Default is false. Returns a list with the heat demand\n averaged over one year and averaged over a cold month (january + febraury). The first is used to calculate the\n bivalent temperature with an edited .mos file for one year with the ambient temperature set constant to the\n bivalent temperature. The second is used for the normative temperature with the corresponding ambient temperature\n set constant over january and february. \"\"\"\n data = open_config(config_name)\n\n if weatherdatakreis is None:\n weatherdatakreis = data['wetterdaten']\n\n # model/project name\n name_project = str(data['kreis'])\n name_model = str(data['Gebaeudeart']) + '_' + str(data['Baujahr'])\n\n w_path = os.getcwd()\n dymola_path = PATH_DYMOLA\n model_path = Output_path\n weatherdata = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Wetterdaten\\\\cop_app_mos')\n\n # start teaser\n prj = Project(load_data=True)\n prj.name = name_project\n if data['residential']:\n prj.add_residential(\n method='tabula_de',\n usage=data['Gebaeudeart'],\n name=name_model,\n year_of_construction=data['Baujahr'],\n number_of_floors=data['Geschosszahl'],\n height_of_floors=data['Deckenhoehe'],\n net_leased_area=data['Nutzflaeche'],\n with_ahu=data['luefter'],\n construction_type=data['Modernisiert']\n )\n else:\n prj.add_non_residential(\n method='bmvbs',\n usage=data['Gebaeudeart'],\n name=name_model,\n year_of_construction=data['Baujahr'],\n number_of_floors=data['Geschosszahl'],\n height_of_floors=data['Deckenhoehe'],\n net_leased_area=data['Nutzflaeche'],\n with_ahu=data['luefter'],\n construction_type=data['Modernisiert']\n )\n\n # exports model\n prj.used_library_calc = 'AixLib'\n prj.number_of_elements_calc = 2\n prj.weather_file_path = os.path.join(weatherdata, weatherdatakreis)\n prj.calc_all_buildings()\n prj.export_aixlib(\n # internal_id=None,\n path=Output_path)\n\n dymola = DymolaInterface(dymolapath=os.path.join(dymola_path, 'bin64', 'Dymola.exe'),\n showwindow=False)\n try:\n dymola.openModel(path=os.path.join(Aixlib_path, 'package.mo'))\n dymola.experimentSetupOutput(events=False)\n\n # simulate with Dymola\n dymola.openModel(path=os.path.join(model_path, name_project, 'package.mo'))\n dymola.SetDymolaCompiler(\"vs\", [\"CCompiler=MSVC\",\n \"MSVCDir=\" + comp_path])\n dymola.simulateModel(\n problem=name_project + '.' + name_model + '.' + name_model,\n startTime=0.0,\n stopTime=32400000, # 1 year plus 10 days\n outputInterval=3600,\n method=\"Cvode\",\n tolerance=0.001,\n resultFile=os.path.join(model_path, name_project, name_model, 'result'),\n )\n except ValueError:\n print(\"[ERROR]\")\n\n # evaluation and analysis\n finally:\n dymola.close()\n\n os.chdir(w_path)\n jahr_auswertung = 240 # 2 days of initialization\n januar_auswertung = 240 # 2 days of initialization\n sum_jahr = 0 # counter for heat demand over 1 year\n sum_januar = 0 # counter for heat demand over 1 year (at normative ambient temperature)\n dmf = DyMat.DyMatFile(os.path.join(model_path, name_project, name_model, 'result'))\n dmf_d = dmf.data('multizone.PHeater[1]') # variable for heat demand\n if create_heat_mat:\n mat_list = []\n time_list = np.arange(0, len(dmf_d) * 3600, 3600)\n for i in range(0, len(time_list)):\n mat_list.append([time_list[i], dmf_d[i]])\n mat = np.array(mat_list)\n path_heat = os.path.join(os.path.dirname(os.path.abspath(__file__)), r'matFiles\\heat.mat')\n savemat(path_heat, {'Q_dem': mat})\n while jahr_auswertung < dmf.size('multizone.PHeater[1]'):\n sum_jahr += dmf_d[jahr_auswertung]\n jahr_auswertung += 1\n while januar_auswertung < (744 + 240):\n sum_januar += dmf_d[januar_auswertung]\n januar_auswertung += 1\n heizlast = [sum_jahr / (8713 * 1000),\n sum_januar / (744 * 1000)]\n # print('The heat demand of the building is ' + str(heizlast))\n return heizlast\n\n\ndef write_mos(wetterdaten, temperature):\n \"\"\"updates the TRY .mos file (path given as String in wetterdaten) and replaces the ambient temperature with the\n value given to the temperature (float) variable. Returns relative path to the new .mos file, which can be used for\n the weatherdatakreis argument from teasersim.\"\"\"\n with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Wetterdaten\\\\cop_app_mos\\\\', wetterdaten),\n 'r') as file:\n mos_list = file.readlines()\n\n header_list = mos_list[0:39]\n wetter_list = mos_list[39:]\n\n neuwetter_list = []\n for i in range(len(wetter_list)):\n neuwetter_list.append(wetter_list[i].split())\n neuwetter_list[i][1] = temperature\n neuwetter_list[i] = '\\t'.join(map(str, neuwetter_list[i]))\n final_list = header_list + neuwetter_list\n\n with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'Wetterdaten\\\\cop_app_mos\\\\erzeugt\\\\', wetterdaten), 'w') as f:\n for item in final_list[0:39]:\n f.write(\"%s\" % item)\n for item in final_list[39:]:\n f.write(\"%s\\n\" % item)\n\n return 'erzeugt\\\\' + wetterdaten\n\n\ndef path_mat(config_name, ambtemp=True, dhw=True, heat=True, ind=False):\n \"\"\"creates time series .mat files for the ambient temperature, heat demand and domestic hot water necessary for\n the HPS simulation and stores these at specific paths. ambtemp, dhw and heat are Boolean. If one of those is set\n to False, the corresponding .mat file is not created. Default for all is True. If ind (individual value for heat\n demand)is true, no teaser simulation is started\"\"\"\n data = open_config(config_name)\n # ambient temperature\n if ambtemp:\n with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'Wetterdaten\\\\cop_app_mos\\\\', data['wetterdaten']), 'r') as file:\n mos_list = file.readlines()\n wetter_list = mos_list[39:]\n temp = [] * (len(wetter_list))\n time_list = np.arange(0, len(wetter_list) * 3600, 3600)\n ambtemp_list = []\n mat_list = []\n for i in range(0, len(wetter_list)):\n temp.append(wetter_list[i].split())\n ambtemp_list.append(float(temp[i][1]) + 273.15) # TRY in °C, Simulation needs K\n for i in range(0, len(time_list)):\n mat_list.append([time_list[i], ambtemp_list[i]])\n mat = np.array(mat_list)\n path_temp = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'matFiles\\\\ambTemp.mat')\n savemat(path_temp, {'T_amb': mat})\n # DHW\n if dhw:\n if data['profil'] == 'einzelperson':\n x = loadmat(os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'matFiles\\\\profilesDHW\\\\Einzelperson.mat'))['DHW']\n savemat(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'matFiles\\\\DHW.mat'), {'DHW': x})\n if data['profil'] == 'familie_duschen':\n x = loadmat(os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'matFiles\\\\profilesDHW\\\\Familie mit Duschen.mat'))['DHW']\n savemat(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'matFiles\\\\DHW.mat'), {'DHW': x})\n if data['profil'] == 'familie_duschen_baden':\n x = loadmat(os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'matFiles\\\\profilesDHW\\\\Familie mit Duschen und Baden.mat'))['DHW']\n savemat(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'matFiles\\\\DHW.mat'), {'DHW': x})\n # heat demand\n if heat and not ind:\n dummy = teasersim(config_name, data['wetterdaten'], create_heat_mat=True)[1]\n\n\ndef open_config(config_name):\n \"\"\"opens the given config file (path as string) and returns the data (dictionary) stored in it\"\"\"\n with open(config_name, 'r') as configfile:\n data = json.load(configfile)\n configfile.close()\n return data\n\n\ndef write_config(data, config_name):\n \"\"\"writes data to the given config file (path as string). Data as dictionary.\"\"\"\n with open(config_name, 'w') as configfile:\n json.dump(data, configfile)\n configfile.close()\n\n\ndef calc_heizlast(config_name, temperature=None):\n \"\"\"uses Teaser to calculate the heat demand of the building over a year. A specific ambient temperature can be\n set to be present for the whole year. The default temperature is None, with which the temperature from the TRY is\n chosen.\"\"\"\n data = open_config(config_name)\n if temperature is None:\n wetterdata = data['wetterdaten']\n else:\n wetterdata = write_mos(data['wetterdaten'], temperature)\n q_heiz = teasersim(config_name, wetterdata)[0]\n dict_heiz = {'gemittelte Heizlast über ein Jahr in kW': q_heiz}\n return dict_heiz\n\n\ndef calc_normbiv(config_name):\n \"\"\"calculates the heat demand at the bivalent temperature using the normative method and returns a list with the\n heat demands at bivalent temperature and normative ambient temperature [q_hw_biv, q_hw_na]\"\"\"\n data = open_config(config_name)\n q_hw_na = data['Q_ind']\n q_hw_biv = 0\n if data['bivalent']:\n q_hw_biv = q_hw_na * (data['T_HG'] - data['T_biv']) / (data['T_HG'] - data['T_NA'])\n return [q_hw_biv, q_hw_na]\n\n\ndef calc_din(config_name, q_hw_biv, q_hw_na):\n \"\"\"calculates the HPS design based on DIN 15450. q_hw_biv and q_hw_na are the heat demands at bivalent and norm\n temperature, which are returned by functions calc_norm_biv or teasersim. Returns a dictionary with the design\"\"\"\n data = open_config(config_name)\n\n # power of hp at normative ambient temperature\n q_wp_na = 0.46 * q_hw_na\n # volume dhw\n v_tww = data[data['profil']]['daily_vol']\n\n # heat demand at design point\n if data['bivalent']:\n q_hw_ap = q_hw_biv\n else:\n q_hw_ap = q_hw_na\n # storage dhw\n v_sp_tww = v_tww * (60 - data['T_kW']) / (data['T_TWW_set'] - data['T_kW'])\n # energy buffer storage\n q_s = data['c_w'] * (data['T_TWW_set'] - data['T_kW']) * v_tww\n # power dhw\n q_tww = (data[data['profil']][\"Q_crit_DIN\"] - q_s * (\n (data['T_TWW_set'] - 40) / (data['T_TWW_set'] - data['T_kW']))) / data[data['profil']][\n \"t_crit_DIN\"] + data[data['profil']][\"Q_loss_crit\"] / data[data['profil']][\"t_crit_DIN\"]\n # power of hp at designpoint\n if data['bivalent']:\n q_wp_ap = data['f_HW'] * q_hw_ap + data['f_TWW'] * q_tww\n q_hs_ap = q_hw_na - q_wp_na\n else:\n q_wp_ap = data['f_HW'] * q_hw_na + data['f_TWW'] * q_tww\n # power heating rod\n q_hs_ap = 0\n # buffer storage\n v_sp_ww_min = data['v_Sp_WW_min'] * q_wp_ap\n v_sp_ww_max = data['v_Sp_WW_max'] * q_wp_ap\n v_sp_ww = data['v_Sp_WW'] * q_wp_ap\n # output dict\n dict_din = {'V_Sp_TWW': v_sp_tww,\n 'V_Sp_WW': v_sp_ww,\n 'V_Sp_WW_min': v_sp_ww_min,\n 'V_Sp_WW_max': v_sp_ww_max,\n 'Q_WP_AP': q_wp_ap,\n 'Q_HS_AP': q_hs_ap,\n 'Q_HW_NA': q_hw_na}\n return dict_din\n\n\ndef calc_vdi(config_name, q_hw_biv, q_hw_na):\n \"\"\"calculates the HPS design based on DIN 4645. q_hw_biv and q_hw_na are the heat demands at bivalent and norm\n temperature, which are returned by functions calc_norm_biv or teasersim. Returns a dictionary with the design\"\"\"\n data = open_config(config_name)\n\n # storage dhw\n v_zirk = data['Q_zirk'] / (data['c_w'] * (data['T_TWW_set'] - data['T_zirkRL']))\n q_dpb = data['n_E'] * data[data['profil']][\"Q_crit_VDI\"]\n v_dpb = q_dpb / (data['c_w'] * (data['T_TWW_set'] - data['T_kW']))\n v_sp_tww = (v_dpb + v_zirk) * data['f_TWE']\n # power dhw at design point\n q_tww_ap = data[data['profil']]['Q_crit_VDI'] / data[data['profil']]['t_crit_VDI']\n # power hp\n if data['bivalent']:\n q_wp_ap = (24 * q_hw_biv + data[data['profil']][\"daily_Q\"] + data['Q_sonst']) / (24 - data['t_SD'])\n q_hs_ap = q_hw_na + q_tww_ap - q_wp_ap\n else:\n q_wp_ap = (24 * q_hw_na + data[data['profil']][\"daily_Q\"] + data['Q_sonst']) / (24 - data['t_SD'])\n q_hs_ap = 0\n # buffer storage\n if data['bivalent']:\n v_sp_ww = 20 * q_wp_ap\n else:\n v_sp_ww = 35 * data['t_SD'] * q_wp_ap\n\n # output dict\n dict_vdi = {'V_Sp_TWW': v_sp_tww,\n 'V_Sp_WW': v_sp_ww,\n 'Q_WP_AP': q_wp_ap,\n 'Q_HS_AP': q_hs_ap,\n 'Q_HW_NA': q_hw_na}\n return dict_vdi\n\n\ndef calc_points(config_name, dict_norm, name, ind=False):\n \"\"\"calculates different operation points of the HPS to determine the SCOP based on the normative method.\n dict_norm is a dict containing the dimensions of the HPS as it is returned by the functions calc_din and\n calc_vdi. name contains a string with the name of the result file of the simulation (recommended are either 'DIN'\n or 'VDI'). Returns a dict with the structure needed for the function scop_norm stored in SCOP_NORM.\"\"\"\n data = open_config(config_name)\n tol = -15 # °C value of ambient temperature underneath which power is zero\n temperature = [tol, -10, -7, 2, 7, 12, data['T_biv']] # °C\n temperature = sorted(temperature)\n\n # The WPS simulation requires a mat file for the heat demand, the DHW and the ambient temperature for all points,\n # that are required for the normative calculation of the SCOP\n cop_list = []\n maxheat_list = []\n # mat file for domestic hot water\n path_mat(config_name, ambtemp=False, heat=False, ind=ind)\n for i in temperature:\n # mat file for heat demand\n wetterdaten = write_mos(data['wetterdaten'], i)\n dummy = teasersim(config_name, wetterdaten, create_heat_mat=True)[1]\n\n # mat file for ambient temperature\n x = loadmat(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'matFiles\\\\ambTemp.mat'))['T_amb']\n x[:, 1] = i + 273.15\n savemat(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'matFiles\\\\ambTemp.mat'), {'T_amb': x})\n savemat(os.path.join(Path(__file__).parents[1], 'Models', 'HPS_model', 'Components', 'new', 'Data',\n 'ambTemp.mat'), {'T_amb': x})\n\n # simulation with beforehand calculated input data\n v_dhw_sto = dict_norm['V_Sp_TWW'] / 1000 # transformation of units\n v_buffer_sto = dict_norm['V_Sp_WW'] / 1000\n q_flow_hp_biv = dict_norm['Q_WP_AP'] * 1000\n q_flow_hr = dict_norm['Q_HS_AP'] * 1000\n\n # simulation of WPS\n initial_values = [q_flow_hp_biv, q_flow_hr, v_buffer_sto, v_dhw_sto] # parameters changed in Simulation\n model_name = 'VCLib.HeatPumpFlowSheets.HPS_model.System_MapOneHeatpump'\n result_path = os.path.join(res_path, name)\n os.makedirs(result_path, exist_ok=True)\n sim_res_path = jahressim(WPSmodel_path, model_name, result_path, initial_values, stoptime=32400000)\n\n # evaluation of points\n res_points = DyMat.DyMatFile(sim_res_path)\n cop = res_points.data('generationCase.heatPump.division.u2')[240:]\n cop = np.mean(cop)\n print('der COP beträgt für ' + str(i) + '°C: ' + str(cop))\n cop_list.append(cop)\n heatpower_wp = res_points.data('generationCase.heatPump.SwitchHeatFlowCondenser.y')[240:]\n heatpower_wp = np.mean(heatpower_wp) / 1000\n maxheat_list.append(heatpower_wp)\n print('Die maximale Heizleistung der Wärmepumpe bei ' + str(i) + '°C beträgt: ' + str(heatpower_wp))\n punkt_list = ['Punkt_a', 'Punkt_b', 'Punkt_c', 'Punkt_d', 'Punkt_e', 'Punkt_f', 'Punkt_g']\n test = []\n for i in range(len(temperature)):\n if i == tol:\n test.append({'h_l': 0, 'cop': 0, 't': temperature[i]})\n else:\n test.append({'h_l': maxheat_list[i], 'cop': cop_list[i], 't': temperature[i]})\n punkte = dict(zip(punkt_list, test))\n return punkte\n\n\ndef calc_js(config_name, dict_norm, name, ind=False):\n \"\"\"calculates the performance of a simple HPS system based on normative design. dict_norm is the dictionary\n containing the dimensions of the normative Designs, returned by calc_din and calc_vdi. name represents the name\n of the result .mat file of the HPS simulation (recommended are either 'DIN' or 'VDI').\"\"\"\n\n v_dhw_sto = dict_norm['V_Sp_TWW'] / 1000 # see modelica model and units\n v_buffer_sto = dict_norm['V_Sp_WW'] / 1000\n q_flow_hp_biv = dict_norm['Q_WP_AP'] * 1000\n q_flow_hr = dict_norm['Q_HS_AP'] * 1000\n path_mat(config_name, ind=ind) # paths changed in Simulation\n initial_values = [q_flow_hp_biv, q_flow_hr, v_buffer_sto, v_dhw_sto] # parameters changed in Simulation\n model_name = 'VCLib.HeatPumpFlowSheets.HPS_model.System_MapOneHeatpump'\n result_path = os.path.join(res_path, name)\n os.makedirs(result_path, exist_ok=True)\n sim_res_path = jahressim(WPSmodel_path, model_name, result_path, initial_values, stoptime=32400000)\n return sim_res_path\n\n\ndef scop_norm(config_name, points):\n data = open_config(config_name)\n # determines the ambient temperature and its variation throughout the year\n klima_moeglich = [\"C\", \"A\", \"W\"]\n klima = \"W\"\n if klima == \"A\":\n t_design = -10\n elif klima == \"W\":\n t_design = 2\n else:\n t_design = -22\n\n tol = -15 # °C value of ambient temperature underneath which power is zero\n c_dh = 0.9 # value that determines the influence of partial load on overall performance\n # assumed values from the example in NORM\n p_off = 0.0057 # kw power demand while turned off\n p_to = 0.0056 # kw power demand while temperature controll of\n p_sb = 0.0051 # kw power demand while standby\n p_ck = 0.0052 # kW power demand while crankcase heater turned on\n\n wetterdata_na = write_mos(data['wetterdaten'], data['T_NA'])\n p_designh = teasersim(\"Functions_GUI\\\\config\\\\config.json\", wetterdata_na)[1]\n # Imports data from the norm saved in a excle file\n # Mainly the number of hours per year a specific ambient temperature is present\n # also number of hours per year the heat pump is in standby mode, on mode and so on\n wb = xl.load_workbook(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"data_SCOPnorm\\\\AnhangDIN_EN_14825\"\n \".xlsx\"))\n seite1 = wb[\"Tabelle1\"]\n anhang = {}\n for zeile in range(3, seite1.max_row + 1):\n topkey = seite1.cell(zeile, 1)\n anhang[topkey.value] = {}\n for spalte in range(2, 5):\n key = seite1.cell(2, spalte)\n wert = seite1.cell(zeile, spalte)\n anhang[topkey.value][key.value] = wert.value\n zustandszeiten = {}\n for zeile in range(3, 8):\n topkey = seite1.cell(zeile, 6)\n zustandszeiten[topkey.value] = {}\n for spalte in range(7, 10):\n key = seite1.cell(2, spalte)\n wert = seite1.cell(zeile, spalte)\n zustandszeiten[topkey.value][key.value] = wert.value\n\n # calculates the heat demand for one Year based on the selected klima\n h_he = zustandszeiten[\"H_HE\"][klima]\n q_h = p_designh * h_he\n\n # calculatesCR und COP_bin for data points\n # CR is the relation between heat demand and supply\n for x in points:\n pl = (points[x][\"t\"] - 16) / (t_design - 16)\n dc = points[x][\"h_l\"]\n cr = pl * p_designh / dc\n if cr > 1:\n cr = 1\n\n # Cop bin is the efficency including partial load losses\n cop_bin = points[x][\"cop\"] * cr / (c_dh * cr + (1 - c_dh))\n points[x][\"Cop_Bin\"] = cop_bin\n # sorting the performance points based on temperature for later interpolation\n sort = points.copy()\n reihenfolge = []\n temperatur = []\n z = 0\n i = len(sort)\n while i > 0:\n y = -300000\n for x in sort:\n if sort[x][\"t\"] > y:\n z = x\n y = sort[x][\"t\"]\n reihenfolge.append(z)\n temperatur.append(y)\n i -= 1\n del (sort[z])\n reihenfolge.reverse()\n temperatur.reverse()\n # Calculation of SCOP on and SCOP Net\n punkt_v = -1\n summe_nenner_scop_on = 0\n summe_zaehler_scop_on = 0\n summe_nenner_scop_net = 0\n summe_zaehler_scop_net = 0\n for i in range(-30, 16): # looping throug all possible temperatures in the Norm\n h_j = anhang[i][klima]\n p_h = (i - 16) / (t_design - 16) * p_designh\n if i in temperatur:\n stelle = temperatur.index(i)\n q = points[reihenfolge[stelle]][\"h_l\"]\n cop_bin = points[reihenfolge[stelle]][\"Cop_Bin\"]\n punkt_v += 1\n else: # interpolation\n if punkt_v >= 0:\n punkt = punkt_v\n else:\n punkt = 0\n if punkt >= len(reihenfolge) - 1:\n punkt = len(reihenfolge) - 2\n q_davor = points[reihenfolge[punkt]][\"h_l\"]\n q_danach = points[reihenfolge[punkt + 1]][\"h_l\"]\n\n t_davor = points[reihenfolge[punkt]][\"t\"]\n t_danach = points[reihenfolge[punkt + 1]][\"t\"]\n cop_bin_davor = points[reihenfolge[punkt]][\"Cop_Bin\"]\n cop_bin_danach = points[reihenfolge[punkt + 1]][\"Cop_Bin\"]\n if i < tol:\n q = 0\n cop_bin = 1\n else:\n q = ((q_danach - q_davor) / (t_danach - t_davor)) * (i - t_davor) + q_davor\n cop_bin = ((cop_bin_danach - cop_bin_davor) / (t_danach - t_davor)) * (i - t_davor) + cop_bin_davor\n if q > p_h:\n q = p_h\n if p_h > q:\n elbu = p_h - q\n else:\n elbu = 0\n\n nenner_scop_on = (((p_h - elbu) / cop_bin) + elbu) * h_j\n zaehler_scop_on = p_h * h_j\n zaehler_scop_net = h_j * (p_h - elbu)\n nenner_scop_net = ((p_h - elbu) / cop_bin) * h_j\n summe_nenner_scop_on += nenner_scop_on\n summe_zaehler_scop_on += zaehler_scop_on\n summe_zaehler_scop_net += zaehler_scop_net\n summe_nenner_scop_net += nenner_scop_net\n scop_on = summe_zaehler_scop_on / summe_nenner_scop_on\n scop_net = summe_zaehler_scop_net / summe_nenner_scop_net\n q_he = q_h / scop_on + zustandszeiten[\"H_TO\"][klima] * p_to + zustandszeiten[\"H_SB\"][klima] * p_sb + \\\n zustandszeiten[\"H_CK\"][klima] * p_ck + zustandszeiten[\"H_OFF\"][klima] * p_off\n scop = q_h / q_he\n print(\"SCOP:\", scop)\n return scop\n" ]
[ [ "numpy.array", "numpy.mean", "scipy.io.savemat" ] ]
[ { "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": [] } ]
klayveR/python-poe-timeless-jewel
[ "5c766d83b3d8772ce507eda6a0b3bc2d93e87556" ]
[ "scripts/ocr.py" ]
[ "import cv2\nimport numpy as np\ntry:\n from PIL import Image\nexcept ImportError:\n import Image\nimport pytesseract\n\nclass OCR:\n @staticmethod\n def clahe(img, clip_limit = 2.0, grid_size = (8,8)):\n clahe = cv2.createCLAHE(clipLimit = clip_limit, tileGridSize = grid_size)\n return clahe.apply(img)\n\n @staticmethod\n def getFilteredImage(imgPath):\n src = cv2.imread(imgPath)\n srcH, srcW = src.shape[:2]\n src = cv2.resize(src, (int(srcW * 1.5), int(srcH * 1.5)))\n\n # HSV thresholding to get rid of as much background as possible\n hsv = cv2.cvtColor(src.copy(), cv2.COLOR_BGR2HSV)\n lower_blue = np.array([0, 0, 180])\n upper_blue = np.array([180, 38, 255])\n mask = cv2.inRange(hsv, lower_blue, upper_blue)\n result = cv2.bitwise_and(src, src, mask = mask)\n b, g, r = cv2.split(result)\n g = OCR.clahe(g, 5, (5, 5))\n inverse = cv2.bitwise_not(g)\n\n return inverse\n\n @staticmethod\n def imageToStringArray(img):\n t = pytesseract.image_to_string(img, lang='eng', \\\n config='--oem 3 --psm 12 poe')\n t = t.replace(\"\\n\\n\", \"\\n\")\n lines = t.split(\"\\n\")\n\n return lines\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jackzhu727/deep-probability-estimation
[ "459deff626fd84ad253ded8ef40790dd0f513b98" ]
[ "datasets/simulated_face.py" ]
[ "import torch\nimport h5py\nfrom scipy.special import expit\nimport numpy as np\n\n\nclass FaceDataset(torch.utils.data.Dataset):\n def __init__(self, root, prob_type, mode='train'):\n with h5py.File(root + mode + '_im.h5', 'r') as f:\n self.keys = list(f.keys())\n self.prob_type = prob_type\n self.root = root\n self.mode = mode\n self.proposed_probs = None\n if not hasattr(self, 'img_data'):\n self.open_data()\n\n def open_data(self):\n self.img_data = h5py.File(self.root + self.mode + '_im.h5', 'r')\n self.target = h5py.File(self.root + \"labels_\" + self.prob_type + '_' + self.mode + '.h5', 'r')\n self.demo = h5py.File(self.root + self.mode + '_label.h5', 'r')\n\n # call different scenarios\n if self.prob_type == 'unif':\n self.prob_sim_func = lambda x: x\n elif self.prob_type == 'sig':\n self.prob_sim_func = lambda x: 1.0 - expit((x - 0.29) * 25)\n elif self.prob_type == 'scaled':\n self.prob_sim_func = lambda x: x / 2.5\n elif self.prob_type == 'mid':\n self.prob_sim_func = lambda x: x / 3.0 + 0.35\n elif self.prob_type == 'step':\n self.prob_sim_func = lambda x: (x < 0.2) * 0.1 + ((x >= 0.2) & (x < 0.4)) * 0.3 + \\\n ((x >= 0.4) & (x < 0.6)) * 0.5 + ((x >= 0.6) & (x < 0.8)) * 0.7 + (x >= 0.8) * 0.9\n else:\n raise NotImplementedError\n\n def __getitem__(self, index):\n data = (torch.tensor(self.img_data[self.keys[index]]).clone().permute(2, 0, 1)) / 255\n target = torch.tensor(np.array(self.target[self.keys[index]])).clone()\n age = torch.tensor(self.demo[self.keys[index]][0, 0])\n target_prob = self.prob_sim_func(torch.minimum(age / 100.0, torch.tensor(1.)))\n if self.proposed_probs is not None:\n probs = self.proposed_probs[index]\n else:\n probs = 0\n return data, target, probs, index, target_prob\n\n def __len__(self):\n return len(self.keys)\n" ]
[ [ "numpy.array", "scipy.special.expit", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
PradeepKadubandi/fairo
[ "9bbe6254a7f49a6eedcccfd9c655e4bb2be4fd53" ]
[ "droidlet/lowlevel/minecraft/pyworld/physical_interfaces.py" ]
[ "import numpy as np\nimport logging\nfrom droidlet.perception.craftassist.rotation import look_vec\nfrom droidlet.shared_data_structs import TICKS_PER_SEC, Time\n\nHEAD_HEIGHT = 2\n# how many internal, non-world-interacting steps agent takes before world steps:\nWORLD_STEP = 10\nWORLD_STEPS_PER_DAY = 480\n\n\n\nclass FakeMCTime(Time):\n def __init__(self, world):\n self.world = world\n\n def get_world_hour(self):\n return (self.world.count % WORLD_STEPS_PER_DAY) / WORLD_STEPS_PER_DAY\n\n # converts from \"seconds\" to internal tick\n def round_time(self, t):\n return int(TICKS_PER_SEC * t)\n\n def get_time(self):\n return self.world.count * TICKS_PER_SEC\n\n def add_tick(self, ticks=1):\n for i in range(ticks):\n self.world.step()\n\n\nclass FakeCPPAction:\n NAME = \"NULL\"\n\n def __init__(self, agent):\n self.agent = agent\n\n def action(self, *args):\n self.agent.world_interaction_occurred = True\n\n def __call__(self, *args):\n if hasattr(self.agent, \"recorder\"):\n self.agent.recorder.record_action({\"name\": self.NAME, \"args\": list(args)})\n return self.action(*args)\n\n\nclass Dig(FakeCPPAction):\n NAME = \"dig\"\n\n def action(self, x, y, z):\n self.agent.world_interaction_occurred = True\n dug = self.agent.world.dig((x, y, z))\n if dug:\n self.agent._changed_blocks.append(((x, y, z), (0, 0)))\n return True\n else:\n return False\n\n\nclass SendChat(FakeCPPAction):\n NAME = \"send_chat\"\n\n def action(self, chat):\n self.agent.world_interaction_occurred = True\n logging.info(\"FakeAgent.send_chat: {}\".format(chat))\n self.agent._outgoing_chats.append(chat)\n\n\nclass SetHeldItem(FakeCPPAction):\n NAME = \"set_held_item\"\n\n def action(self, arg):\n self.agent.world_interaction_occurred = True\n try:\n d, m = arg\n self.agent._held_item = (d, m)\n except TypeError:\n self.agent._held_item = (arg, 0)\n\n\nclass StepPosX(FakeCPPAction):\n NAME = \"step_pos_x\"\n\n def action(self):\n self.agent.world_interaction_occurred = True\n self.agent.pos += (1, 0, 0)\n\n\nclass StepNegX(FakeCPPAction):\n NAME = \"step_neg_x\"\n\n def action(self):\n self.agent.world_interaction_occurred = True\n self.agent.pos += (-1, 0, 0)\n\n\nclass StepPosZ(FakeCPPAction):\n NAME = \"step_pos_z\"\n\n def action(self):\n self.agent.world_interaction_occurred = True\n self.agent.pos += (0, 0, 1)\n\n\nclass StepNegZ(FakeCPPAction):\n NAME = \"step_neg_z\"\n\n def action(self):\n self.agent.world_interaction_occurred = True\n self.agent.pos += (0, 0, -1)\n\n\nclass StepPosY(FakeCPPAction):\n NAME = \"step_pos_y\"\n\n def action(self):\n self.agent.world_interaction_occurred = True\n self.agent.pos += (0, 1, 0)\n\n\nclass StepNegY(FakeCPPAction):\n NAME = \"step_neg_y\"\n\n def action(self):\n self.agent.world_interaction_occurred = True\n self.agent.pos += (0, -1, 0)\n\n\nclass StepForward(FakeCPPAction):\n NAME = \"step_forward\"\n\n def action(self):\n self.agent.world_interaction_occurred = True\n dx, dy, dz = self.agent._look_vec\n self.agent.pos += (dx, 0, dz)\n\n\nclass TurnAngle(FakeCPPAction):\n NAME = \"turn_angle\"\n\n def action(self, angle):\n self.agent.world_interaction_occurred = True\n if angle == 90:\n self.agent.turn_left()\n elif angle == -90:\n self.agent.turn_right()\n else:\n raise ValueError(\"bad angle={}\".format(angle))\n\n\n# FIXME!\nclass TurnLeft(FakeCPPAction):\n NAME = \"turn_left\"\n\n def action(self):\n self.agent.world_interaction_occurred = True\n old_l = (self.agent._look_vec[0], self.agent._look_vec[1])\n idx = self.agent.CCW_LOOK_VECS.index(old_l)\n new_l = self.agent.CCW_LOOK_VECS[(idx + 1) % len(self.agent.CCW_LOOK_VECS)]\n self.agent._look_vec[0] = new_l[0]\n self.agent._look_vec[2] = new_l[2]\n\n\n# FIXME!\nclass TurnRight(FakeCPPAction):\n NAME = \"turn_right\"\n\n def action(self):\n self.agent.world_interaction_occurred = True\n old_l = (self.agent._look_vec[0], self.agent._look_vec[1])\n idx = self.agent.CCW_LOOK_VECS.index(old_l)\n new_l = self.agent.CCW_LOOK_VECS[(idx - 1) % len(self.agent.CCW_LOOK_VECS)]\n self.agent._look_vec[0] = new_l[0]\n self.agent._look_vec[2] = new_l[2]\n\n\nclass PlaceBlock(FakeCPPAction):\n NAME = \"place_block\"\n\n def action(self, x, y, z):\n self.agent.world_interaction_occurred = True\n block = ((x, y, z), self.agent._held_item)\n self.agent.world.place_block(block)\n self.agent._changed_blocks.append(block)\n return True\n\n\nclass LookAt(FakeCPPAction):\n NAME = \"look_at\"\n\n def action(self, x, y, z):\n self.agent.world_interaction_occurred = True\n look_vec = np.array(\n [x - self.agent.pos[0], y - self.agent.pos[1] - HEAD_HEIGHT, z - self.agent.pos[2]]\n )\n self.agent.set_look_vec(*look_vec.tolist())\n\n\nclass SetLook(FakeCPPAction):\n NAME = \"set_look\"\n\n def action(self, yaw, pitch):\n self.agent.world_interaction_occurred = True\n a = look_vec(yaw, pitch)\n self.agent.set_look_vec(a[0], a[1], a[2])\n\n\nclass Craft(FakeCPPAction):\n NAME = \"craft\"\n\n def action(self):\n raise NotImplementedError()\n\n\ndef init_agent_interfaces(agent):\n agent.dig = Dig(agent)\n agent.send_chat = SendChat(agent)\n agent.set_held_item = SetHeldItem(agent)\n agent.step_pos_x = StepPosX(agent)\n agent.step_neg_x = StepNegX(agent)\n agent.step_pos_z = StepPosZ(agent)\n agent.step_neg_z = StepNegZ(agent)\n agent.step_pos_y = StepPosY(agent)\n agent.step_neg_y = StepNegY(agent)\n agent.step_forward = StepForward(agent)\n agent.turn_angle = TurnAngle(agent)\n agent.turn_left = TurnLeft(agent)\n agent.turn_right = TurnRight(agent)\n agent.set_look = SetLook(agent)\n agent.look_at = LookAt(agent)\n agent.place_block = PlaceBlock(agent)\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lev1khachatryan/ASDS_DL
[ "ca00ce7b4cfb722f9bce545820cdb661ff8b643e" ]
[ "DL_FromScratch/unsupervised_learning/generative_adversarial_network.py" ]
[ "from __future__ import print_function, division\nfrom sklearn import datasets\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport progressbar\n\nfrom sklearn.datasets import fetch_mldata\n\nfrom deep_learning.optimizers import Adam\nfrom deep_learning.loss_functions import CrossEntropy\nfrom deep_learning.layers import Dense, Dropout, Flatten, Activation, Reshape, BatchNormalization\nfrom deep_learning import NeuralNetwork\n\n\nclass GAN():\n \"\"\"A Generative Adversarial Network with deep fully-connected neural nets as\n Generator and Discriminator.\n\n Training Data: MNIST Handwritten Digits (28x28 images)\n \"\"\"\n def __init__(self):\n self.img_rows = 28 \n self.img_cols = 28\n self.img_dim = self.img_rows * self.img_cols\n self.latent_dim = 100\n\n optimizer = Adam(learning_rate=0.0002, b1=0.5)\n loss_function = CrossEntropy\n\n # Build the discriminator\n self.discriminator = self.build_discriminator(optimizer, loss_function)\n\n # Build the generator\n self.generator = self.build_generator(optimizer, loss_function)\n\n # Build the combined model\n self.combined = NeuralNetwork(optimizer=optimizer, loss=loss_function)\n self.combined.layers.extend(self.generator.layers)\n self.combined.layers.extend(self.discriminator.layers)\n\n print ()\n self.generator.summary(name=\"Generator\")\n self.discriminator.summary(name=\"Discriminator\")\n\n def build_generator(self, optimizer, loss_function):\n \n model = NeuralNetwork(optimizer=optimizer, loss=loss_function)\n\n model.add(Dense(256, input_shape=(self.latent_dim,)))\n model.add(Activation('leaky_relu'))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(512))\n model.add(Activation('leaky_relu'))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(1024))\n model.add(Activation('leaky_relu'))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(self.img_dim))\n model.add(Activation('tanh'))\n\n return model\n\n def build_discriminator(self, optimizer, loss_function):\n \n model = NeuralNetwork(optimizer=optimizer, loss=loss_function)\n\n model.add(Dense(512, input_shape=(self.img_dim,)))\n model.add(Activation('leaky_relu'))\n model.add(Dropout(0.5))\n model.add(Dense(256))\n model.add(Activation('leaky_relu'))\n model.add(Dropout(0.5))\n model.add(Dense(2))\n model.add(Activation('softmax'))\n\n return model\n\n def train(self, n_epochs, batch_size=128, save_interval=50):\n\n mnist = fetch_mldata('MNIST original')\n\n X = mnist.data\n y = mnist.target\n\n # Rescale [-1, 1]\n X = (X.astype(np.float32) - 127.5) / 127.5\n\n half_batch = int(batch_size / 2)\n\n for epoch in range(n_epochs):\n\n # ---------------------\n # Train Discriminator\n # ---------------------\n\n self.discriminator.set_trainable(True)\n\n # Select a random half batch of images\n idx = np.random.randint(0, X.shape[0], half_batch)\n imgs = X[idx]\n\n # Sample noise to use as generator input\n noise = np.random.normal(0, 1, (half_batch, self.latent_dim))\n\n # Generate a half batch of images\n gen_imgs = self.generator.predict(noise)\n\n # Valid = [1, 0], Fake = [0, 1]\n valid = np.concatenate((np.ones((half_batch, 1)), np.zeros((half_batch, 1))), axis=1)\n fake = np.concatenate((np.zeros((half_batch, 1)), np.ones((half_batch, 1))), axis=1)\n\n # Train the discriminator\n d_loss_real, d_acc_real = self.discriminator.train_on_batch(imgs, valid)\n d_loss_fake, d_acc_fake = self.discriminator.train_on_batch(gen_imgs, fake)\n d_loss = 0.5 * (d_loss_real + d_loss_fake)\n d_acc = 0.5 * (d_acc_real + d_acc_fake)\n\n\n # ---------------------\n # Train Generator\n # ---------------------\n\n # We only want to train the generator for the combined model\n self.discriminator.set_trainable(False)\n\n # Sample noise and use as generator input\n noise = np.random.normal(0, 1, (batch_size, self.latent_dim))\n\n # The generator wants the discriminator to label the generated samples as valid\n valid = np.concatenate((np.ones((batch_size, 1)), np.zeros((batch_size, 1))), axis=1)\n\n # Train the generator\n g_loss, g_acc = self.combined.train_on_batch(noise, valid)\n\n # Display the progress\n print (\"%d [D loss: %f, acc: %.2f%%] [G loss: %f, acc: %.2f%%]\" % (epoch, d_loss, 100*d_acc, g_loss, 100*g_acc))\n\n # If at save interval => save generated image samples\n if epoch % save_interval == 0:\n self.save_imgs(epoch)\n\n def save_imgs(self, epoch):\n r, c = 5, 5 # Grid size\n noise = np.random.normal(0, 1, (r * c, self.latent_dim))\n # Generate images and reshape to image shape\n gen_imgs = self.generator.predict(noise).reshape((-1, self.img_rows, self.img_cols))\n\n # Rescale images 0 - 1\n gen_imgs = 0.5 * gen_imgs + 0.5\n\n fig, axs = plt.subplots(r, c)\n plt.suptitle(\"Generative Adversarial Network\")\n cnt = 0\n for i in range(r):\n for j in range(c):\n axs[i,j].imshow(gen_imgs[cnt,:,:], cmap='gray')\n axs[i,j].axis('off')\n cnt += 1\n fig.savefig(\"mnist_%d.png\" % epoch)\n plt.close()\n\n\nif __name__ == '__main__':\n gan = GAN()\n gan.train(n_epochs=200000, batch_size=64, save_interval=400)\n\n\n" ]
[ [ "matplotlib.pyplot.subplots", "numpy.ones", "numpy.random.normal", "sklearn.datasets.fetch_mldata", "matplotlib.pyplot.close", "matplotlib.pyplot.suptitle", "numpy.zeros", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AtousaTorabi/Theano_old
[ "ba2d2f74406243112e813df31429721c791a889a" ]
[ "theano/sandbox/cuda/tests/test_fftconv.py" ]
[ "import unittest\nimport numpy\n\nimport theano\nfrom theano.tests import unittest_tools as utt\n\n# Skip tests if cuda_ndarray is not available.\nfrom nose.plugins.skip import SkipTest\nimport theano.sandbox.cuda as cuda_ndarray\nif not cuda_ndarray.cuda_available:\n raise SkipTest('Optional package cuda not available')\nfrom theano.misc.pycuda_init import pycuda_available\nif not pycuda_available:\n raise SkipTest('Optional package pycuda not available')\nfrom theano.sandbox.cuda.fftconv import scikits_cuda_available\nif not scikits_cuda_available:\n raise SkipTest('Optional package scikits.cuda not available')\n\nfrom theano.sandbox.cuda import float32_shared_constructor as shared\nimport theano.sandbox.cuda.fftconv\n\nif theano.config.mode == 'FAST_COMPILE':\n mode_with_gpu = theano.compile.mode.get_mode('FAST_RUN').including('gpu')\nelse:\n mode_with_gpu = theano.compile.mode.get_default_mode().including('gpu')\n\n\nclass TestConv2dFFT(unittest.TestCase):\n def run_conv(self, inputs_shape, filters_shape, pad=False, **other_args):\n inputs_val = numpy.random.random(inputs_shape).astype('float32')\n filters_val = numpy.random.random(filters_shape).astype('float32')\n\n inputs = shared(inputs_val)\n filters = shared(filters_val)\n\n conv_ref = theano.tensor.nnet.conv.conv2d(inputs, filters,\n **other_args)\n conv_fft = theano.sandbox.cuda.fftconv.conv2d_fft(inputs, filters,\n pad_last_dim=pad,\n **other_args)\n\n f_ref = theano.function([], conv_ref)\n f_fft = theano.function([], conv_fft, mode=mode_with_gpu)\n\n res_ref = f_ref()\n res_fft = f_fft()\n\n utt.assert_allclose(res_ref, res_fft)\n\n def test_valid(self):\n self.run_conv(inputs_shape=(5, 3, 7, 6),\n filters_shape=(2, 3, 3, 3),\n border_mode='valid')\n self.run_conv(inputs_shape=(5, 3, 7, 7),\n filters_shape=(2, 3, 3, 3),\n border_mode='valid', pad=True)\n\n def test_full(self):\n self.run_conv(inputs_shape=(5, 3, 7, 6),\n filters_shape=(2, 3, 3, 3),\n border_mode='full')\n self.run_conv(inputs_shape=(5, 3, 7, 7),\n filters_shape=(2, 3, 3, 3),\n border_mode='full', pad=True)\n\n def test_opt_valid(self):\n inputs_shape = (5, 3, 7, 6)\n filters_shape = (2, 3, 3, 3)\n\n inputs_val = numpy.random.random(inputs_shape).astype('float32')\n filters_val = numpy.random.random(filters_shape).astype('float32')\n\n inputs = shared(inputs_val)\n filters = shared(filters_val)\n\n conv = theano.tensor.nnet.conv.conv2d(inputs, filters)\n\n mode = mode_with_gpu.including('conv_fft_valid')\n\n f_ref = theano.function([], conv)\n f_fft = theano.function([], conv, mode=mode)\n\n # make sure we inserted the fft trickery\n topo = f_fft.maker.fgraph.toposort()\n assert sum(isinstance(n.op, theano.sandbox.cuda.fftconv.CuFFTOp)\n for n in topo) == 2\n\n\n res_ref = f_ref()\n res_fft = f_fft()\n\n utt.assert_allclose(res_ref, res_fft)\n\n def test_opt_full(self):\n inputs_shape = (5, 3, 7, 6)\n filters_shape = (2, 3, 3, 3)\n\n inputs_val = numpy.random.random(inputs_shape).astype('float32')\n filters_val = numpy.random.random(filters_shape).astype('float32')\n\n inputs = shared(inputs_val)\n filters = shared(filters_val)\n\n conv = theano.tensor.nnet.conv.conv2d(inputs, filters,\n border_mode='full')\n\n mode = mode_with_gpu.including('conv_fft_full')\n\n f_ref = theano.function([], conv)\n f_fft = theano.function([], conv, mode=mode)\n\n # make sure we inserted the fft trickery\n topo = f_fft.maker.fgraph.toposort()\n assert sum(isinstance(n.op, theano.sandbox.cuda.fftconv.CuFFTOp)\n for n in topo) == 2\n\n res_ref = f_ref()\n res_fft = f_fft()\n\n utt.assert_allclose(res_ref, res_fft)\n\n def test_opt_nofft_valid(self):\n inputs_shape = (5, 3, 7, 6)\n filters_shape = (2, 3, 3, 3)\n\n inputs_val = numpy.random.random(inputs_shape).astype('float32')\n filters_val = numpy.random.random(filters_shape).astype('float32')\n\n inputs = shared(inputs_val)\n filters = shared(filters_val)\n\n conv = theano.tensor.nnet.conv.conv2d(inputs, filters, version='no_fft')\n\n mode = mode_with_gpu.including('conv_fft_valid')\n\n f_ref = theano.function([], conv)\n f_fft = theano.function([], conv, mode=mode)\n\n # make sure we that no CuFFTOp has been inserted\n topo = f_fft.maker.fgraph.toposort()\n assert sum(isinstance(n.op, theano.sandbox.cuda.fftconv.CuFFTOp)\n for n in topo) == 0\n\n def test_opt_nofft_full(self):\n inputs_shape = (5, 3, 7, 6)\n filters_shape = (2, 3, 3, 3)\n\n inputs_val = numpy.random.random(inputs_shape).astype('float32')\n filters_val = numpy.random.random(filters_shape).astype('float32')\n\n inputs = shared(inputs_val)\n filters = shared(filters_val)\n\n conv = theano.tensor.nnet.conv.conv2d(inputs, filters,\n border_mode='full',\n version='no_fft')\n\n mode = mode_with_gpu.including('conv_fft_full')\n\n f_ref = theano.function([], conv)\n f_fft = theano.function([], conv, mode=mode)\n\n # make sure we that no CuFFTOp has been inserted\n topo = f_fft.maker.fgraph.toposort()\n assert sum(isinstance(n.op, theano.sandbox.cuda.fftconv.CuFFTOp)\n for n in topo) == 0\n\n\nclass TestConv3dFFT(unittest.TestCase):\n\n def run_conv_valid(self, inputs_shape, filters_shape, pad=False):\n inputs_val = numpy.random.random(inputs_shape).astype('float32')\n filters_val = numpy.random.random(filters_shape).astype('float32')\n\n inputs = shared(inputs_val)\n filters = shared(filters_val)\n bias = shared(numpy.zeros(filters_shape[0]).astype('float32'))\n\n # Flip filter as conv3D compute correlation\n filters_flip = filters[:,::-1,::-1,::-1,:]\n #filters_flip = filters\n conv_ref = theano.tensor.nnet.conv3D(V=inputs, W=filters_flip,\n b=bias, d=(1,1,1))\n\n conv_fft = theano.sandbox.cuda.fftconv.conv3d_fft(inputs.dimshuffle(0, 4, 1, 2, 3),\n filters.dimshuffle(0, 4, 1, 2, 3),\n border_mode = \"valid\",\n pad_last_dim = pad)\n conv_fft = conv_fft.dimshuffle(0, 2, 3, 4, 1)\n\n f_ref = theano.function([], conv_ref)\n f_fft = theano.function([], conv_fft, mode=mode_with_gpu)\n\n res_ref = f_ref()\n res_fft = f_fft()\n utt.assert_allclose(res_ref, res_fft, rtol=1e-05, atol=1e-05)\n\n\n\n def run_conv_full(self, inputs_shape, filters_shape, pad=False):\n inputs_val = numpy.random.random(inputs_shape).astype('float32')\n filters_val = numpy.random.random(filters_shape).astype('float32')\n\n inputs = shared(inputs_val)\n filters = shared(filters_val)\n bias = shared(numpy.zeros(filters_shape[4]).astype('float32'))\n\n conv_ref = theano.tensor.nnet.convTransp3D(W=filters, b=bias, d=(1,1,1),\n H=inputs)\n\n filters = filters.dimshuffle(4, 0, 1, 2, 3)\n inputs = inputs.dimshuffle(0, 4, 1, 2, 3)\n conv_fft = theano.sandbox.cuda.fftconv.conv3d_fft(inputs, filters,\n border_mode = \"full\",\n pad_last_dim = pad)\n conv_fft = conv_fft.dimshuffle(0, 2, 3, 4, 1)\n\n f_ref = theano.function([], conv_ref)\n f_fft = theano.function([], conv_fft, mode=mode_with_gpu)\n\n res_ref = f_ref()\n res_fft = f_fft()\n utt.assert_allclose(res_ref, res_fft, rtol=1e-04, atol=1e-04)\n\n\n def test_valid(self):\n self.run_conv_valid(inputs_shape=(16, 20, 32, 16, 1),\n filters_shape=(10, 6, 12, 4, 1),\n pad=True)\n self.run_conv_valid(inputs_shape=(16, 20, 32, 15, 1),\n filters_shape=(10, 6, 12, 4, 1),\n pad=True)\n def test_full(self):\n self.run_conv_full(inputs_shape=(16, 15, 21, 16, 10),\n filters_shape=(10, 6, 12, 4, 1),\n pad=True)\n self.run_conv_full(inputs_shape=(16, 15, 21, 12, 10),\n filters_shape=(10, 6, 12, 4, 1),\n pad=True)\n\n def test_opt_conv3d_fft(self):\n inputs_shape = (16, 20, 32, 16, 1)\n filters_shape = (10, 6, 12, 4, 1)\n\n inputs_val = numpy.random.random(inputs_shape).astype('float32')\n filters_val = numpy.random.random(filters_shape).astype('float32')\n\n inputs = shared(inputs_val)\n filters = shared(filters_val)\n bias = shared(numpy.zeros(filters_shape[0]).astype('float32'))\n\n conv = theano.tensor.nnet.conv3D(V=inputs, W=filters,\n b=bias, d=(1,1,1))\n mode = mode_with_gpu.including('conv3d_fft')\n\n f_ref = theano.function([], conv)\n f_fft = theano.function([], conv, mode=mode)\n\n # make sure we inserted the fft trickery\n topo = f_fft.maker.fgraph.toposort()\n assert sum(isinstance(n.op, theano.sandbox.cuda.fftconv.CuFFTOp)\n for n in topo) == 2\n\n\n res_ref = f_ref()\n res_fft = f_fft()\n\n utt.assert_allclose(res_ref, res_fft)\n\n def test_opt_convgrad3d_fft(self):\n inputs_shape = (16, 20, 32, 16, 1)\n filters_shape = (10, 6, 12, 4, 1)\n dCdH_shape = (16, 15, 21, 13, 10)\n\n inputs_val = numpy.random.random(inputs_shape).astype('float32')\n dCdH_val = numpy.random.random(dCdH_shape).astype('float32')\n\n inputs = shared(inputs_val)\n dCdH = shared(dCdH_val)\n\n conv = theano.tensor.nnet.convGrad3D(V=inputs, dCdH=dCdH,\n WShape=filters_shape,\n d=(1,1,1))\n mode = mode_with_gpu.including('convgrad3d_fft')\n\n f_ref = theano.function([], conv)\n f_fft = theano.function([], conv, mode=mode)\n\n # make sure we inserted the fft trickery\n topo = f_fft.maker.fgraph.toposort()\n assert sum(isinstance(n.op, theano.sandbox.cuda.fftconv.CuFFTOp)\n for n in topo) == 2\n\n\n res_ref = f_ref()\n res_fft = f_fft()\n\n utt.assert_allclose(res_ref, res_fft, rtol=1e-04, atol=1e-04)\n\n\n def test_opt_convtransp3d_fft(self):\n inputs_shape = (16, 15, 21, 12, 10)\n filters_shape = (10, 6, 12, 4, 1)\n\n inputs_val = numpy.random.random(inputs_shape).astype('float32')\n filters_val = numpy.random.random(filters_shape).astype('float32')\n bias = shared(numpy.zeros(filters_shape[4]).astype('float32'))\n\n inputs = shared(inputs_val)\n filters = shared(filters_val)\n\n conv = theano.tensor.nnet.convTransp3D(W=filters, b=bias, d=(1,1,1),\n H=inputs)\n mode = mode_with_gpu.including('convtransp3d_fft')\n\n f_ref = theano.function([], conv)\n f_fft = theano.function([], conv, mode=mode)\n\n # make sure we inserted the fft trickery\n topo = f_fft.maker.fgraph.toposort()\n assert sum(isinstance(n.op, theano.sandbox.cuda.fftconv.CuFFTOp)\n for n in topo) == 2\n\n\n res_ref = f_ref()\n res_fft = f_fft()\n\n utt.assert_allclose(res_ref, res_fft, rtol=1e-04, atol=1e-04)\n\n" ]
[ [ "numpy.random.random", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Sandsten/pixicasso
[ "b60343342c13fd2150fa4a364b51ff71b6f6329f" ]
[ "read_list.py" ]
[ "import numpy as np\nstyle_name_list = [\"kandinsky\", \"shipwreck\", \"the_scream\",\"seated-nude\", \"starry-night\", \"woman-with-hat-matisse\"]\nloss_types = ['total_loss', 'content_loss', 'style_loss', 'cross_loss']\nfor loss in loss_types:\n values = []\n for name in style_name_list:\n data = np.load(\"results_1_faster_decay/data_list_\"+name+\".npz\")['arr_0'].item()\n values.append((name, data[loss][-1]))\n # values.append((name, np.sum(data[loss])/1000))\n values.sort(key=lambda tup: tup[1])\n print(loss)\n print(*values, sep=\"\\n\")\n" ]
[ [ "numpy.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cxqj/34-wtalc
[ "812c777f951966cee1a1f6bfe4e1855a5763faec" ]
[ "classificationMAP.py" ]
[ "import numpy as np\n\ndef getAP(conf,labels):\n assert len(conf)==len(labels)\n sortind = np.argsort(-conf)\n tp = labels[sortind]==1; fp = labels[sortind]!=1\n npos = np.sum(labels);\n\n fp = np.cumsum(fp).astype('float32'); tp = np.cumsum(tp).astype('float32')\n rec=tp/npos; prec=tp/(fp+tp)\n tmp = (labels[sortind]==1).astype('float32')\n\n return np.sum(tmp*prec)/npos\n\ndef getClassificationMAP(confidence,labels):\n ''' confidence and labels are of dimension n_samples x n_label '''\n\n AP = []\n for i in range(np.shape(labels)[1]):\n AP.append(getAP(confidence[:,i], labels[:,i]))\n return 100*sum(AP)/len(AP)\n" ]
[ [ "numpy.argsort", "numpy.cumsum", "numpy.shape", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
susanbao/m3ddpg
[ "1a44a58b7a2ec56468ed34c69a11f0562be191d1" ]
[ "experiments/train_with_perturbed_network.py" ]
[ "import argparse\nimport numpy as np\nimport tensorflow as tf\nimport time\nimport pickle\nimport sys\nimport os\nimport re\n\nsys.path.append('../')\nsys.path.append('../../')\nsys.path.append('../../../')\n\nimport maddpg.common.tf_util as U\nfrom maddpg.trainer.m3ddpg import M3DDPGAgentTrainer\nfrom maddpg.trainer.m3ddpg_with_perturbed_networks import PNM3DDPGAgentTrainer\nfrom maddpg.trainer.maddpg_perturbed_state import MADDPGPerturbedAgentTrainer\nimport tensorflow.contrib.layers as layers\n\ndef parse_args():\n parser = argparse.ArgumentParser(\"Reinforcement Learning experiments for multiagent environments\")\n # Environment\n parser.add_argument(\"--scenario\", type=str, default=\"simple\", help=\"name of the scenario script\")\n parser.add_argument(\"--max-episode-len\", type=int, default=25, help=\"maximum episode length\")\n parser.add_argument(\"--num-episodes\", type=int, default=100000, help=\"number of episodes\")\n parser.add_argument(\"--num-adversaries\", type=int, default=0, help=\"number of adversaries\")\n parser.add_argument(\"--good-policy\", type=str, default=\"mmmaddpg\", help=\"policy for good agents\")\n parser.add_argument(\"--bad-policy\", type=str, default=\"mmmaddpg\", help=\"policy of adversaries\")\n # Core training parameters\n parser.add_argument(\"--lr\", type=float, default=1e-2, help=\"learning rate for Adam optimizer\")\n parser.add_argument(\"--gamma\", type=float, default=0.95, help=\"discount factor\")\n parser.add_argument(\"--batch-size\", type=int, default=1024, help=\"number of episodes to optimize at the same time\")\n parser.add_argument(\"--num-units\", type=int, default=64, help=\"number of units in the mlp\")\n parser.add_argument(\"--adv-eps\", type=float, default=1e-3, help=\"adversarial training rate\")\n parser.add_argument(\"--adv-eps-s\", type=float, default=1e-5, help=\"small adversarial training rate\")\n parser.add_argument(\"--gpu-frac\", type=float, default=0.3, help=\"Fraction of GPU memory usage.\")\n # Checkpointing\n parser.add_argument(\"--exp-name\", type=str, default=None, help=\"name of the experiment\")\n parser.add_argument(\"--save-dir\", type=str, default=\"/tmp/policy/\", help=\"directory in which training state and model should be saved\")\n parser.add_argument(\"--save-rate\", type=int, default=1000, help=\"save model once every time this many episodes are completed\")\n parser.add_argument(\"--load-name\", type=str, default=\"\", help=\"name of which training state and model are loaded, leave blank to load seperately\")\n parser.add_argument(\"--load-good\", type=str, default=\"\", help=\"which good policy to load\")\n parser.add_argument(\"--load-bad\", type=str, default=\"\", help=\"which bad policy to load\")\n parser.add_argument(\"--load-dir\", type=str, default=\"\", help=\"directory in which training state and model are loaded\")\n # Evaluation\n parser.add_argument(\"--test\", action=\"store_true\", default=False)\n parser.add_argument(\"--restore\", action=\"store_true\", default=False)\n parser.add_argument(\"--display\", action=\"store_true\", default=False)\n parser.add_argument(\"--benchmark\", action=\"store_true\", default=False)\n parser.add_argument(\"--benchmark-iters\", type=int, default=100000, help=\"number of iterations run for benchmarking\")\n parser.add_argument(\"--benchmark-dir\", type=str, default=\"./benchmark_files/\", help=\"directory where benchmark data is saved\")\n parser.add_argument(\"--plots-dir\", type=str, default=\"./learning_curves/\", help=\"directory where plot data is saved\")\n # Add Noise for observation \n parser.add_argument(\"--noise-type\", type=int, default=0, help=\"type can be: 0-none, 1-truncated normal distribution, 2-normal distribution\")\n parser.add_argument('--noise-std', type=float, default=1.0, help='{0.0, 1.0, 2.0, 3.0, ...}, noise standard deviation')\n parser.add_argument(\"--d-value\", type=float, default=1.0, help=\"a radius denoting how large the perturbation set is\")\n return parser.parse_args()\n\ndef mlp_model(input, num_outputs, scope, reuse=False, num_units=64, rnn_cell=None):\n # This model takes as input an observation and returns values of all actions\n with tf.variable_scope(scope, reuse=reuse):\n out = input\n out = layers.fully_connected(out, num_outputs=num_units, activation_fn=tf.nn.relu)\n out = layers.fully_connected(out, num_outputs=num_units, activation_fn=tf.nn.relu)\n out = layers.fully_connected(out, num_outputs=num_outputs, activation_fn=None)\n return out\n\ndef make_env(scenario_name, arglist, benchmark=False):\n from multiagent.environment import MultiAgentEnv\n import multiagent.scenarios as scenarios\n\n # load scenario from script\n scenario = scenarios.load(scenario_name + \".py\").Scenario()\n # create world\n world = scenario.make_world()\n # create multiagent environment\n if benchmark:\n env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation, scenario.benchmark_data)\n else:\n env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation)\n return env\n\ndef get_perturbed_trainers(env, num_adversaries, obs_shape_n, arglist):\n trainers = []\n model = mlp_model\n trainer = MADDPGPerturbedAgentTrainer\n policy = \"pmaddpg\"\n for i in range(num_adversaries):\n trainers.append(trainer(\n policy + \"_agent_%d\" % i, model, obs_shape_n, env.observation_space, env.action_space, i, arglist,\n local_q_func=(policy=='ddpg')))\n for i in range(num_adversaries, env.n):\n trainers.append(trainer(\n policy + \"_agent_%d\" % i, model, obs_shape_n, env.observation_space, env.action_space, i, arglist,\n local_q_func=(policy=='ddpg')))\n return trainers\n\ndef get_trainers(env, num_adversaries, obs_shape_n, arglist, perturbed_trainers):\n trainers = []\n model = mlp_model\n trainer = PNM3DDPGAgentTrainer\n for i in range(num_adversaries):\n print(\"{} bad agents\".format(i))\n policy_name = arglist.bad_policy\n trainers.append(trainer(\n policy_name + \"agent_%d\" % i, model, obs_shape_n, env.observation_space, env.action_space, i, arglist, perturbed_trainers,\n policy_name == 'ddpg', policy_name, policy_name == 'mmmaddpg'))\n for i in range(num_adversaries, env.n):\n print(\"{} good agents\".format(i))\n policy_name = arglist.good_policy\n trainers.append(trainer(\n policy_name + \"agent_%d\" % i, model, obs_shape_n, env.observation_space, env.action_space, i, arglist, perturbed_trainers,\n policy_name == 'ddpg', policy_name, policy_name == 'mmmaddpg'))\n return trainers\n\n\ndef train(arglist):\n if arglist.test:\n np.random.seed(71)\n with U.single_threaded_session(arglist.gpu_frac):\n # Create environment\n env = make_env(arglist.scenario, arglist, arglist.benchmark)\n # Create agent trainers\n obs_shape_n = [env.observation_space[i].shape for i in range(env.n)]\n num_adversaries = min(env.n, arglist.num_adversaries)\n perturbed_trainers = get_perturbed_trainers(env, num_adversaries, obs_shape_n, arglist)\n trainers = get_trainers(env, num_adversaries, obs_shape_n, arglist, perturbed_trainers)\n print('Using good policy {} and bad policy {} with {} adversaries'.format(arglist.good_policy, arglist.bad_policy, num_adversaries))\n\n # Initialize\n U.initialize()\n # Load previous results, if necessary\n variables = tf.contrib.framework.get_variables_to_restore()\n variables_to_restore = [v for v in variables if re.match(r'pmaddpg*', v.name.split('/')[0]) != None]\n #variables_name = [v.name for v in variables if re.match(r'pmaddpg*', v.name.split('/')[0]) != None]\n saver = tf.train.Saver(variables_to_restore)\n saver.restore(U.get_session(), arglist.load_dir)\n\n episode_rewards = [0.0] # sum of rewards for all agents\n agent_rewards = [[0.0] for _ in range(env.n)] # individual agent reward\n final_ep_rewards = [] # sum of rewards for training curve\n final_ep_ag_rewards = [] # agent rewards for training curve\n agent_info = [[[]]] # placeholder for benchmarking info\n saver = tf.train.Saver()\n obs_n = env.reset()\n episode_step = 0\n train_step = 0\n t_start = time.time()\n\n print('Starting iterations...')\n while True:\n # get action\n action_n = [agent.action(obs) for agent, obs in zip(trainers,obs_n)]\n # environment step\n new_obs_n, rew_n, done_n, info_n = env.step(action_n)\n episode_step += 1\n done = all(done_n)\n terminal = (episode_step >= arglist.max_episode_len)\n # collect experience\n for i, agent in enumerate(trainers):\n agent.experience(obs_n[i], action_n[i], rew_n[i], new_obs_n[i], done_n[i], terminal)\n obs_n = new_obs_n\n\n for i, rew in enumerate(rew_n):\n episode_rewards[-1] += rew\n agent_rewards[i][-1] += rew\n\n if done or terminal:\n obs_n = env.reset()\n episode_step = 0\n episode_rewards.append(0)\n for a in agent_rewards:\n a.append(0)\n agent_info.append([[]])\n\n # increment global step counter\n train_step += 1\n\n # for benchmarking learned policies\n if arglist.benchmark:\n for i, info in enumerate(info_n):\n agent_info[-1][i].append(info_n['n'])\n if train_step > arglist.benchmark_iters and (done or terminal):\n file_name = arglist.benchmark_dir + arglist.exp_name + '.pkl'\n print('Finished benchmarking, now saving...')\n with open(file_name, 'wb') as fp:\n pickle.dump(agent_info[:-1], fp)\n break\n continue\n\n # for displaying learned policies\n if arglist.display:\n time.sleep(0.1)\n env.render()\n continue\n\n # update all trainers, if not in display or benchmark mode\n if not arglist.test:\n loss = None\n for agent in trainers:\n agent.preupdate()\n for agent in trainers:\n loss = agent.update(trainers, train_step)\n\n # save model, display training output\n if terminal and (len(episode_rewards) % arglist.save_rate == 0):\n U.save_state(arglist.save_dir, global_step = len(episode_rewards), saver=saver)\n # print statement depends on whether or not there are adversaries\n if num_adversaries == 0:\n print(\"steps: {}, episodes: {}, mean episode reward: {}, time: {}\".format(\n train_step, len(episode_rewards), np.mean(episode_rewards[-arglist.save_rate:]), round(time.time()-t_start, 3)))\n else:\n print(\"{} vs {} steps: {}, episodes: {}, mean episode reward: {}, agent episode reward: {}, time: {}\".format(arglist.bad_policy, arglist.good_policy,\n train_step, len(episode_rewards), np.mean(episode_rewards[-arglist.save_rate:]),\n [np.mean(rew[-arglist.save_rate:]) for rew in agent_rewards], round(time.time()-t_start, 3)))\n t_start = time.time()\n # Keep track of final episode reward\n final_ep_rewards.append(np.mean(episode_rewards[-arglist.save_rate:]))\n for rew in agent_rewards:\n final_ep_ag_rewards.append(np.mean(rew[-arglist.save_rate:]))\n\n # saves final episode reward for plotting training curve later\n if len(episode_rewards) > arglist.num_episodes:\n suffix = '_test.pkl' if arglist.test else '.pkl'\n rew_file_name = arglist.plots_dir + arglist.exp_name + '_rewards' + suffix\n agrew_file_name = arglist.plots_dir + arglist.exp_name + '_agrewards' + suffix\n\n if not os.path.exists(os.path.dirname(rew_file_name)):\n try:\n os.makedirs(os.path.dirname(rew_file_name))\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise\n\n with open(rew_file_name, 'wb') as fp:\n pickle.dump(final_ep_rewards, fp)\n with open(agrew_file_name, 'wb') as fp:\n pickle.dump(final_ep_ag_rewards, fp)\n print('...Finished total of {} episodes.'.format(len(episode_rewards)))\n break\n\nif __name__ == '__main__':\n arglist = parse_args()\n train(arglist)\n" ]
[ [ "numpy.random.seed", "tensorflow.contrib.layers.fully_connected", "numpy.mean", "tensorflow.variable_scope", "tensorflow.train.Saver", "tensorflow.contrib.framework.get_variables_to_restore" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
NartayXD/scikit-learn
[ "86c62cff7121b218f7bd7007bd6880e206561019", "86c62cff7121b218f7bd7007bd6880e206561019" ]
[ "sklearn/utils/metaestimators.py", "sklearn/feature_selection/_from_model.py" ]
[ "\"\"\"Utilities for meta-estimators\"\"\"\n# Author: Joel Nothman\n# Andreas Mueller\n# License: BSD\nfrom typing import List, Any\nimport warnings\n\nfrom abc import ABCMeta, abstractmethod\nfrom operator import attrgetter\nfrom functools import update_wrapper\nimport numpy as np\nfrom contextlib import suppress\n\nfrom ..utils import _safe_indexing\nfrom ..utils._tags import _safe_tags\nfrom ..base import BaseEstimator\n\n__all__ = [\"available_if\", \"if_delegate_has_method\"]\n\n\nclass _BaseComposition(BaseEstimator, metaclass=ABCMeta):\n \"\"\"Handles parameter management for classifiers composed of named estimators.\"\"\"\n\n steps: List[Any]\n\n @abstractmethod\n def __init__(self):\n pass\n\n def _get_params(self, attr, deep=True):\n out = super().get_params(deep=deep)\n if not deep:\n return out\n\n estimators = getattr(self, attr)\n try:\n out.update(estimators)\n except (TypeError, ValueError):\n # Ignore TypeError for cases where estimators is not a list of\n # (name, estimator) and ignore ValueError when the list is not\n # formatted correctly. This is to prevent errors when calling\n # `set_params`. `BaseEstimator.set_params` calls `get_params` which\n # can error for invalid values for `estimators`.\n return out\n\n for name, estimator in estimators:\n if hasattr(estimator, \"get_params\"):\n for key, value in estimator.get_params(deep=True).items():\n out[\"%s__%s\" % (name, key)] = value\n return out\n\n def _set_params(self, attr, **params):\n # Ensure strict ordering of parameter setting:\n # 1. All steps\n if attr in params:\n setattr(self, attr, params.pop(attr))\n # 2. Replace items with estimators in params\n items = getattr(self, attr)\n if isinstance(items, list) and items:\n # Get item names used to identify valid names in params\n # `zip` raises a TypeError when `items` does not contains\n # elements of length 2\n with suppress(TypeError):\n item_names, _ = zip(*items)\n for name in list(params.keys()):\n if \"__\" not in name and name in item_names:\n self._replace_estimator(attr, name, params.pop(name))\n\n # 3. Step parameters and other initialisation arguments\n super().set_params(**params)\n return self\n\n def _replace_estimator(self, attr, name, new_val):\n # assumes `name` is a valid estimator name\n new_estimators = list(getattr(self, attr))\n for i, (estimator_name, _) in enumerate(new_estimators):\n if estimator_name == name:\n new_estimators[i] = (name, new_val)\n break\n setattr(self, attr, new_estimators)\n\n def _validate_names(self, names):\n if len(set(names)) != len(names):\n raise ValueError(\"Names provided are not unique: {0!r}\".format(list(names)))\n invalid_names = set(names).intersection(self.get_params(deep=False))\n if invalid_names:\n raise ValueError(\n \"Estimator names conflict with constructor arguments: {0!r}\".format(\n sorted(invalid_names)\n )\n )\n invalid_names = [name for name in names if \"__\" in name]\n if invalid_names:\n raise ValueError(\n \"Estimator names must not contain __: got {0!r}\".format(invalid_names)\n )\n\n\nclass _AvailableIfDescriptor:\n \"\"\"Implements a conditional property using the descriptor protocol.\n\n Using this class to create a decorator will raise an ``AttributeError``\n if check(self) returns a falsey value. Note that if check raises an error\n this will also result in hasattr returning false.\n\n See https://docs.python.org/3/howto/descriptor.html for an explanation of\n descriptors.\n \"\"\"\n\n def __init__(self, fn, check, attribute_name):\n self.fn = fn\n self.check = check\n self.attribute_name = attribute_name\n\n # update the docstring of the descriptor\n update_wrapper(self, fn)\n\n def __get__(self, obj, owner=None):\n attr_err = AttributeError(\n f\"This {repr(owner.__name__)} has no attribute {repr(self.attribute_name)}\"\n )\n if obj is not None:\n # delegate only on instances, not the classes.\n # this is to allow access to the docstrings.\n if not self.check(obj):\n raise attr_err\n\n # lambda, but not partial, allows help() to work with update_wrapper\n out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs) # noqa\n else:\n\n def fn(*args, **kwargs):\n if not self.check(args[0]):\n raise attr_err\n return self.fn(*args, **kwargs)\n\n # This makes it possible to use the decorated method as an unbound method,\n # for instance when monkeypatching.\n out = lambda *args, **kwargs: fn(*args, **kwargs) # noqa\n # update the docstring of the returned function\n update_wrapper(out, self.fn)\n return out\n\n\ndef available_if(check):\n \"\"\"An attribute that is available only if check returns a truthy value\n\n Parameters\n ----------\n check : callable\n When passed the object with the decorated method, this should return\n a truthy value if the attribute is available, and either return False\n or raise an AttributeError if not available.\n\n Examples\n --------\n >>> from sklearn.utils.metaestimators import available_if\n >>> class HelloIfEven:\n ... def __init__(self, x):\n ... self.x = x\n ...\n ... def _x_is_even(self):\n ... return self.x % 2 == 0\n ...\n ... @available_if(_x_is_even)\n ... def say_hello(self):\n ... print(\"Hello\")\n ...\n >>> obj = HelloIfEven(1)\n >>> hasattr(obj, \"say_hello\")\n False\n >>> obj.x = 2\n >>> hasattr(obj, \"say_hello\")\n True\n >>> obj.say_hello()\n Hello\n \"\"\"\n return lambda fn: _AvailableIfDescriptor(fn, check, attribute_name=fn.__name__)\n\n\n# TODO(1.3) remove\nclass _IffHasAttrDescriptor(_AvailableIfDescriptor):\n \"\"\"Implements a conditional property using the descriptor protocol.\n\n Using this class to create a decorator will raise an ``AttributeError``\n if none of the delegates (specified in ``delegate_names``) is an attribute\n of the base object or the first found delegate does not have an attribute\n ``attribute_name``.\n\n This allows ducktyping of the decorated method based on\n ``delegate.attribute_name``. Here ``delegate`` is the first item in\n ``delegate_names`` for which ``hasattr(object, delegate) is True``.\n\n See https://docs.python.org/3/howto/descriptor.html for an explanation of\n descriptors.\n \"\"\"\n\n def __init__(self, fn, delegate_names, attribute_name):\n super().__init__(fn, self._check, attribute_name)\n self.delegate_names = delegate_names\n\n def _check(self, obj):\n warnings.warn(\n \"if_delegate_has_method was deprecated in version 1.1 and will be \"\n \"removed in version 1.3. Use if_available instead.\",\n FutureWarning,\n )\n\n delegate = None\n for delegate_name in self.delegate_names:\n try:\n delegate = attrgetter(delegate_name)(obj)\n break\n except AttributeError:\n continue\n\n if delegate is None:\n return False\n # raise original AttributeError\n getattr(delegate, self.attribute_name)\n\n return True\n\n\n# TODO(1.3) remove\ndef if_delegate_has_method(delegate):\n \"\"\"Create a decorator for methods that are delegated to a sub-estimator\n\n This enables ducktyping by hasattr returning True according to the\n sub-estimator.\n\n .. deprecated:: 1.3\n `if_delegate_has_method` is deprecated in version 1.1 and will be removed in\n version 1.3. Use `available_if` instead.\n\n Parameters\n ----------\n delegate : str, list of str or tuple of str\n Name of the sub-estimator that can be accessed as an attribute of the\n base object. If a list or a tuple of names are provided, the first\n sub-estimator that is an attribute of the base object will be used.\n\n \"\"\"\n if isinstance(delegate, list):\n delegate = tuple(delegate)\n if not isinstance(delegate, tuple):\n delegate = (delegate,)\n\n return lambda fn: _IffHasAttrDescriptor(fn, delegate, attribute_name=fn.__name__)\n\n\ndef _safe_split(estimator, X, y, indices, train_indices=None):\n \"\"\"Create subset of dataset and properly handle kernels.\n\n Slice X, y according to indices for cross-validation, but take care of\n precomputed kernel-matrices or pairwise affinities / distances.\n\n If ``estimator._pairwise is True``, X needs to be square and\n we slice rows and columns. If ``train_indices`` is not None,\n we slice rows using ``indices`` (assumed the test set) and columns\n using ``train_indices``, indicating the training set.\n\n Labels y will always be indexed only along the first axis.\n\n Parameters\n ----------\n estimator : object\n Estimator to determine whether we should slice only rows or rows and\n columns.\n\n X : array-like, sparse matrix or iterable\n Data to be indexed. If ``estimator._pairwise is True``,\n this needs to be a square array-like or sparse matrix.\n\n y : array-like, sparse matrix or iterable\n Targets to be indexed.\n\n indices : array of int\n Rows to select from X and y.\n If ``estimator._pairwise is True`` and ``train_indices is None``\n then ``indices`` will also be used to slice columns.\n\n train_indices : array of int or None, default=None\n If ``estimator._pairwise is True`` and ``train_indices is not None``,\n then ``train_indices`` will be use to slice the columns of X.\n\n Returns\n -------\n X_subset : array-like, sparse matrix or list\n Indexed data.\n\n y_subset : array-like, sparse matrix or list\n Indexed targets.\n\n \"\"\"\n if _safe_tags(estimator, key=\"pairwise\"):\n if not hasattr(X, \"shape\"):\n raise ValueError(\n \"Precomputed kernels or affinity matrices have \"\n \"to be passed as arrays or sparse matrices.\"\n )\n # X is a precomputed square kernel matrix\n if X.shape[0] != X.shape[1]:\n raise ValueError(\"X should be a square kernel matrix\")\n if train_indices is None:\n X_subset = X[np.ix_(indices, indices)]\n else:\n X_subset = X[np.ix_(indices, train_indices)]\n else:\n X_subset = _safe_indexing(X, indices)\n\n if y is not None:\n y_subset = _safe_indexing(y, indices)\n else:\n y_subset = None\n\n return X_subset, y_subset\n", "# Authors: Gilles Louppe, Mathieu Blondel, Maheshakya Wijewardena\n# License: BSD 3 clause\n\nimport numpy as np\nimport numbers\n\nfrom ._base import SelectorMixin\nfrom ._base import _get_feature_importances\nfrom ..base import BaseEstimator, clone, MetaEstimatorMixin\nfrom ..utils._tags import _safe_tags\nfrom ..utils.validation import check_is_fitted\n\nfrom ..exceptions import NotFittedError\nfrom ..utils.metaestimators import available_if\nfrom ..utils.validation import check_scalar\n\n\ndef _calculate_threshold(estimator, importances, threshold):\n \"\"\"Interpret the threshold value\"\"\"\n\n if threshold is None:\n # determine default from estimator\n est_name = estimator.__class__.__name__\n if (\n hasattr(estimator, \"penalty\") and estimator.penalty == \"l1\"\n ) or \"Lasso\" in est_name:\n # the natural default threshold is 0 when l1 penalty was used\n threshold = 1e-5\n else:\n threshold = \"mean\"\n\n if isinstance(threshold, str):\n if \"*\" in threshold:\n scale, reference = threshold.split(\"*\")\n scale = float(scale.strip())\n reference = reference.strip()\n\n if reference == \"median\":\n reference = np.median(importances)\n elif reference == \"mean\":\n reference = np.mean(importances)\n else:\n raise ValueError(\"Unknown reference: \" + reference)\n\n threshold = scale * reference\n\n elif threshold == \"median\":\n threshold = np.median(importances)\n\n elif threshold == \"mean\":\n threshold = np.mean(importances)\n\n else:\n raise ValueError(\n \"Expected threshold='mean' or threshold='median' got %s\" % threshold\n )\n\n else:\n threshold = float(threshold)\n\n return threshold\n\n\ndef _estimator_has(attr):\n \"\"\"Check if we can delegate a method to the underlying estimator.\n\n First, we check the fitted estimator if available, otherwise we\n check the unfitted estimator.\n \"\"\"\n return lambda self: (\n hasattr(self.estimator_, attr)\n if hasattr(self, \"estimator_\")\n else hasattr(self.estimator, attr)\n )\n\n\nclass SelectFromModel(MetaEstimatorMixin, SelectorMixin, BaseEstimator):\n \"\"\"Meta-transformer for selecting features based on importance weights.\n\n .. versionadded:: 0.17\n\n Read more in the :ref:`User Guide <select_from_model>`.\n\n Parameters\n ----------\n estimator : object\n The base estimator from which the transformer is built.\n This can be both a fitted (if ``prefit`` is set to True)\n or a non-fitted estimator. The estimator should have a\n ``feature_importances_`` or ``coef_`` attribute after fitting.\n Otherwise, the ``importance_getter`` parameter should be used.\n\n threshold : str or float, default=None\n The threshold value to use for feature selection. Features whose\n importance is greater or equal are kept while the others are\n discarded. If \"median\" (resp. \"mean\"), then the ``threshold`` value is\n the median (resp. the mean) of the feature importances. A scaling\n factor (e.g., \"1.25*mean\") may also be used. If None and if the\n estimator has a parameter penalty set to l1, either explicitly\n or implicitly (e.g, Lasso), the threshold used is 1e-5.\n Otherwise, \"mean\" is used by default.\n\n prefit : bool, default=False\n Whether a prefit model is expected to be passed into the constructor\n directly or not. If True, ``transform`` must be called directly\n and SelectFromModel cannot be used with ``cross_val_score``,\n ``GridSearchCV`` and similar utilities that clone the estimator.\n Otherwise train the model using ``fit`` and then ``transform`` to do\n feature selection.\n\n norm_order : non-zero int, inf, -inf, default=1\n Order of the norm used to filter the vectors of coefficients below\n ``threshold`` in the case where the ``coef_`` attribute of the\n estimator is of dimension 2.\n\n max_features : int, callable, default=None\n The maximum number of features to select.\n\n - If an integer, then it specifies the maximum number of features to\n allow.\n - If a callable, then it specifies how to calculate the maximum number of\n features allowed by using the output of `max_feaures(X)`.\n\n To only select based on ``max_features``, set ``threshold=-np.inf``.\n\n .. versionadded:: 0.20\n\n importance_getter : str or callable, default='auto'\n If 'auto', uses the feature importance either through a ``coef_``\n attribute or ``feature_importances_`` attribute of estimator.\n\n Also accepts a string that specifies an attribute name/path\n for extracting feature importance (implemented with `attrgetter`).\n For example, give `regressor_.coef_` in case of\n :class:`~sklearn.compose.TransformedTargetRegressor` or\n `named_steps.clf.feature_importances_` in case of\n :class:`~sklearn.pipeline.Pipeline` with its last step named `clf`.\n\n If `callable`, overrides the default feature importance getter.\n The callable is passed with the fitted estimator and it should\n return importance for each feature.\n\n .. versionadded:: 0.24\n\n Attributes\n ----------\n estimator_ : an estimator\n The base estimator from which the transformer is built.\n This is stored only when a non-fitted estimator is passed to the\n ``SelectFromModel``, i.e when prefit is False.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`. Only defined if the\n underlying estimator exposes such an attribute when fit.\n\n .. versionadded:: 0.24\n\n max_features_ : int\n Maximum number of features calculated during :term:`fit`. Only defined\n if the ``max_features`` is not `None`.\n\n - If `max_features` is an int, then `max_features_ = max_features`.\n - If `max_features` is a callable, then `max_features_ = max_features(X)`.\n\n .. versionadded:: 1.1\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Defined only when `X`\n has feature names that are all strings.\n\n .. versionadded:: 1.0\n\n threshold_ : float\n The threshold value used for feature selection.\n\n See Also\n --------\n RFE : Recursive feature elimination based on importance weights.\n RFECV : Recursive feature elimination with built-in cross-validated\n selection of the best number of features.\n SequentialFeatureSelector : Sequential cross-validation based feature\n selection. Does not rely on importance weights.\n\n Notes\n -----\n Allows NaN/Inf in the input if the underlying estimator does as well.\n\n Examples\n --------\n >>> from sklearn.feature_selection import SelectFromModel\n >>> from sklearn.linear_model import LogisticRegression\n >>> X = [[ 0.87, -1.34, 0.31 ],\n ... [-2.79, -0.02, -0.85 ],\n ... [-1.34, -0.48, -2.55 ],\n ... [ 1.92, 1.48, 0.65 ]]\n >>> y = [0, 1, 0, 1]\n >>> selector = SelectFromModel(estimator=LogisticRegression()).fit(X, y)\n >>> selector.estimator_.coef_\n array([[-0.3252302 , 0.83462377, 0.49750423]])\n >>> selector.threshold_\n 0.55245...\n >>> selector.get_support()\n array([False, True, False])\n >>> selector.transform(X)\n array([[-1.34],\n [-0.02],\n [-0.48],\n [ 1.48]])\n\n Using a callable to create a selector that can use no more than half\n of the input features.\n\n >>> def half_callable(X):\n ... return round(len(X[0]) / 2)\n >>> half_selector = SelectFromModel(estimator=LogisticRegression(),\n ... max_features=half_callable)\n >>> _ = half_selector.fit(X, y)\n >>> half_selector.max_features_\n 2\n \"\"\"\n\n def __init__(\n self,\n estimator,\n *,\n threshold=None,\n prefit=False,\n norm_order=1,\n max_features=None,\n importance_getter=\"auto\",\n ):\n self.estimator = estimator\n self.threshold = threshold\n self.prefit = prefit\n self.importance_getter = importance_getter\n self.norm_order = norm_order\n self.max_features = max_features\n\n def _get_support_mask(self):\n # SelectFromModel can directly call on transform.\n if self.prefit:\n estimator = self.estimator\n elif hasattr(self, \"estimator_\"):\n estimator = self.estimator_\n else:\n raise ValueError(\n \"Either fit the model before transform or set\"\n ' \"prefit=True\" while passing the fitted'\n \" estimator to the constructor.\"\n )\n scores = _get_feature_importances(\n estimator=estimator,\n getter=self.importance_getter,\n transform_func=\"norm\",\n norm_order=self.norm_order,\n )\n threshold = _calculate_threshold(estimator, scores, self.threshold)\n if self.max_features is not None:\n mask = np.zeros_like(scores, dtype=bool)\n candidate_indices = np.argsort(-scores, kind=\"mergesort\")[\n : self.max_features_\n ]\n mask[candidate_indices] = True\n else:\n mask = np.ones_like(scores, dtype=bool)\n mask[scores < threshold] = False\n return mask\n\n def fit(self, X, y=None, **fit_params):\n \"\"\"Fit the SelectFromModel meta-transformer.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n The training input samples.\n\n y : array-like of shape (n_samples,), default=None\n The target values (integers that correspond to classes in\n classification, real numbers in regression).\n\n **fit_params : dict\n Other estimator specific parameters.\n\n Returns\n -------\n self : object\n Fitted estimator.\n \"\"\"\n if self.max_features is not None:\n if isinstance(self.max_features, numbers.Integral):\n check_scalar(\n self.max_features,\n \"max_features\",\n numbers.Integral,\n min_val=0,\n max_val=len(X[0]),\n )\n self.max_features_ = self.max_features\n elif callable(self.max_features):\n max_features = self.max_features(X)\n check_scalar(\n max_features,\n \"max_features(X)\",\n numbers.Integral,\n min_val=0,\n max_val=len(X[0]),\n )\n self.max_features_ = max_features\n else:\n raise TypeError(\n \"'max_features' must be either an int or a callable that takes\"\n f\" 'X' as input. Got {self.max_features} instead.\"\n )\n\n if self.prefit:\n raise NotFittedError(\"Since 'prefit=True', call transform directly\")\n self.estimator_ = clone(self.estimator)\n self.estimator_.fit(X, y, **fit_params)\n\n if hasattr(self.estimator_, \"feature_names_in_\"):\n self.feature_names_in_ = self.estimator_.feature_names_in_\n else:\n self._check_feature_names(X, reset=True)\n\n return self\n\n @property\n def threshold_(self):\n \"\"\"Threshold value used for feature selection.\"\"\"\n scores = _get_feature_importances(\n estimator=self.estimator_,\n getter=self.importance_getter,\n transform_func=\"norm\",\n norm_order=self.norm_order,\n )\n return _calculate_threshold(self.estimator, scores, self.threshold)\n\n @available_if(_estimator_has(\"partial_fit\"))\n def partial_fit(self, X, y=None, **fit_params):\n \"\"\"Fit the SelectFromModel meta-transformer only once.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n The training input samples.\n\n y : array-like of shape (n_samples,), default=None\n The target values (integers that correspond to classes in\n classification, real numbers in regression).\n\n **fit_params : dict\n Other estimator specific parameters.\n\n Returns\n -------\n self : object\n Fitted estimator.\n \"\"\"\n if self.prefit:\n raise NotFittedError(\"Since 'prefit=True', call transform directly\")\n if not hasattr(self, \"estimator_\"):\n self.estimator_ = clone(self.estimator)\n self.estimator_.partial_fit(X, y, **fit_params)\n return self\n\n @property\n def n_features_in_(self):\n \"\"\"Number of features seen during `fit`.\"\"\"\n # For consistency with other estimators we raise a AttributeError so\n # that hasattr() fails if the estimator isn't fitted.\n try:\n check_is_fitted(self)\n except NotFittedError as nfe:\n raise AttributeError(\n \"{} object has no n_features_in_ attribute.\".format(\n self.__class__.__name__\n )\n ) from nfe\n\n return self.estimator_.n_features_in_\n\n def _more_tags(self):\n return {\"allow_nan\": _safe_tags(self.estimator, key=\"allow_nan\")}\n" ]
[ [ "numpy.ix_" ], [ "numpy.ones_like", "numpy.median", "numpy.mean", "numpy.zeros_like", "numpy.argsort" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
CodyJohnsonCHL/dfm_models
[ "50cd5e876d545f9aa677fcceee902687be2a97ee" ]
[ "dfm_models/utils/analysis.py" ]
[ "\"\"\"Analysis tools for comparing model results to observations\n\[email protected]\n\n\"\"\"\n\nimport pandas as pd\nimport pytide\nfrom numpy import abs, angle\n\nfrom dfm_models._internal import validate_harcon\n\n\ndef compute_harcon_error(Observations, Results):\n \"\"\"Calculate statistics between COOPs and FM model harmonic constiuents\"\"\"\n\n amplitude_error = {}\n phase_error = {}\n\n validate_harcon(Observations)\n validate_harcon(Results.his_output)\n\n common_stations = get_common_stations(\n Observations.harcons, Results.his_output.harcons\n )\n\n for station in common_stations:\n\n amplitude_error[station] = (\n (Results.his_output.harcons[station] - Observations.harcons[station])[\n \"amplitude\"\n ]\n .dropna()\n .sort_values(ascending=False)\n )\n\n phase_results = Results.his_output.harcons[station][\"phase\"]\n phase_obs = Observations.harcons[station][\"phase\"]\n common_comps = get_common_components(phase_results, phase_obs)\n\n errors = []\n\n for comp in common_comps:\n\n res = phase_results.loc[comp]\n obs = phase_obs.loc[comp]\n\n e = compute_phase_error(res, obs)\n errors.append(e)\n\n errors = pd.Series(errors, index=common_comps)\n errors.name = \"phase\"\n phase_error[station] = errors\n\n return amplitude_error, phase_error\n\n\ndef compute_phase_error(res, obs):\n \"\"\"compute error in phase between 0 and 360\"\"\"\n\n if res < 0:\n res += 360\n\n if obs < 0:\n obs += 360\n\n if res >= obs:\n mu = res - obs\n return mu\n\n else:\n mu = res - obs\n mu += 360\n return mu\n\n\n##########################\n# tidal harmonic #\n##########################\ndef harmonic_analysis(\n waterlevel,\n time,\n consts=[\n \"K1\",\n \"O1\",\n \"P1\",\n \"M2\",\n \"Q1\",\n \"S2\",\n \"S1\",\n \"Mf\",\n \"N2\",\n \"K2\",\n \"J1\",\n \"Mm\",\n \"M4\",\n \"Sa\",\n \"Ssa\",\n ],\n):\n wt = pytide.WaveTable(consts)\n h = waterlevel.values\n f, vu = wt.compute_nodal_modulations(time)\n w = wt.harmonic_analysis(h, f, vu)\n hp = wt.tide_from_tide_series(time, w)\n return w, (h, hp, time), consts\n\n\ndef get_modulus_angle(w):\n modulus = abs(w)\n ang = angle(w, deg=True)\n return modulus, ang\n\n\n##########################\n# getters #\n##########################\ndef get_common_stations(obs_harcons, res_harcons):\n \"\"\"Get intersection of stations for the observations and results\n\n :function: TODO\n :returns: TODO\n\n \"\"\"\n\n obs_stations = obs_harcons.keys()\n res_stations = res_harcons.keys()\n\n common_stations = list(set(obs_stations) & set(res_stations))\n\n if len(common_stations) == 0:\n print(\"There are no common stations between observations and results.\")\n return None\n\n else:\n\n return common_stations\n\n\ndef get_common_components(results, obs):\n \"\"\"get intersectin of constituents\"\"\"\n\n # cast to set for intersection operator\n res_comps = set(results.index)\n obs_comps = set(obs.index)\n\n common_comps = list(res_comps & obs_comps)\n return common_comps\n" ]
[ [ "numpy.angle", "numpy.abs", "pandas.Series" ] ]
[ { "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": [] } ]
TimeEscaper/rl_data_association
[ "fd7f7fb9d5d7aebfbb9729ddaf13b6287a8c11f6" ]
[ "tools/plot.py" ]
[ "\"\"\"\nSudhanva Sreesha\[email protected]\n24-Mar-2018\n\nGonzalo Ferrer\[email protected]\n26-Nov-2018\n\nThis file contains all utilities for plotting data.\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.linalg import cholesky\n\n\ndef plot2dcov(mu, Sigma, color, nSigma=1, legend=None):\n \"\"\"\n Plots a 2D covariance ellipse given the Gaussian distribution parameters.\n The function expects the mean and covariance matrix to ignore the theta parameter.\n\n :param mu: The mean of the distribution: 2x1 vector.\n :param Sigma: The covariance of the distribution: 2x2 matrix.\n :param color: The border color of the ellipse and of the major and minor axes.\n :param nSigma: The radius of the ellipse in terms of the number of standard deviations (default: 1).\n :param legend: If not None, a legend label to the ellipse will be added to the plot as an attribute.\n \"\"\"\n\n mu = np.array(mu)\n assert mu.shape == (2,)\n Sigma = np.array(Sigma)\n assert Sigma.shape == (2, 2)\n\n n_points = 50\n\n A = cholesky(Sigma, lower=True)\n\n angles = np.linspace(0, 2 * np.pi, n_points)\n x_old = nSigma * np.cos(angles)\n y_old = nSigma * np.sin(angles)\n\n x_y_old = np.stack((x_old, y_old), 1)\n x_y_new = np.matmul(x_y_old, np.transpose(A)) + mu.reshape(1, 2) # (A*x)T = xT * AT\n\n plt.plot(x_y_new[:, 0], x_y_new[:, 1], color=color, label=legend)\n plt.scatter(mu[0], mu[1], color=color)\n\n\ndef plot_robot(state, radius=15.):\n \"\"\"\n Plots a circle at the center of the robot and a line to depict the yaw.\n\n :param state: numpy.ndarray([x, y, theta]).\n :param radius: The radius of the circle representing the robot.\n \"\"\"\n\n assert isinstance(state, np.ndarray)\n assert state.shape == (3,)\n\n robot = plt.Circle(state[:-1], radius, edgecolor='black', facecolor='cyan', alpha=0.25)\n orientation_line = np.array([[state[0], state[0] + (np.cos(state[2]) * (radius * 1.5))],\n [state[1], state[1] + (np.sin(state[2]) * (radius * 1.5))]])\n\n plt.gcf().gca().add_artist(robot)\n plt.plot(orientation_line[0], orientation_line[1], 'black')\n\n\n\n\ndef get_plots_figure(should_show_plots, should_write_movie):\n \"\"\"\n :param should_show_plots: Indicates whether the animation of SLAM should be plotted, in real time.\n :param should_write_movie: Indicates whether the animation of SLAM should be written to a movie file.\n :return: A figure if the plots should be shown or a movie file should be written, else None.\n \"\"\"\n\n fig = None\n if should_show_plots or should_write_movie:\n fig = plt.figure(1)\n if should_show_plots:\n plt.ion()\n\n return fig\n\n\ndef plot_field(field_map, detected_landmarks):\n \"\"\"\n Plots the field and highlights the currently detected marker.\n\n :param field_map: The FieldMap object to plot.\n :param detected_landmarks: 1d np.array with landmark indexes of all the detected landmarks at the current time step.\n \"\"\"\n\n margin = 200\n\n plt.axis((-margin, field_map.complete_size_x + margin, -margin, field_map.complete_size_y + margin))\n plt.xlabel('X')\n plt.ylabel('Y')\n\n for k in range(field_map.num_landmarks):\n center = [field_map.landmarks_poses_x[k], field_map.landmarks_poses_y[k]]\n\n if k in detected_landmarks:\n landmark = plt.Circle(center, 15, edgecolor='black', facecolor='gray')\n else:\n landmark = plt.Circle(center, 15, edgecolor='black', facecolor='none')\n\n plt.gcf().gca().add_artist(landmark)\n plt.text(center[0] - 2, center[1], str(k))\n\n\ndef plot_observations(pose, noise_free_observations, noisy_observations):\n \"\"\"\n Plot two lines corresponding to the noisy and noise free observations from the robot to respective landmarks.\n\n :param pose: The current robot pose: x, y, theta.\n :param noise_free_observations: A 2-d np.ndarray of noise free observations (size: Mx3) of all detected landmarks.\n :param noisy_observations: A 2-d np.ndarray of noisy observations (size: Mx3) of all the detected landmarks.\n \"\"\"\n\n assert isinstance(noise_free_observations, np.ndarray)\n assert isinstance(noisy_observations, np.ndarray)\n\n assert noise_free_observations.shape == noisy_observations.shape\n\n M = noise_free_observations.shape[0]\n for k in range(M):\n noisy_range, noisy_bearing, _ = noisy_observations[k]\n nf_range, nf_bearing, _ = noise_free_observations[k]\n\n # Plot the line to indicate observed landmarks (a.k.a. noisy observations).\n plt.plot([pose[0], pose[0] + noisy_range * np.cos(pose[2] + noisy_bearing)],\n [pose[1], pose[1] + noisy_range * np.sin(pose[2] + noisy_bearing)],\n 'brown')\n\n # Plot the line to indicate the true observations to landmarks (a.k.a. noise free observations).\n plt.plot([pose[0], pose[0] + nf_range * np.cos(pose[2] + nf_bearing)],\n [pose[1], pose[1] + nf_range * np.sin(pose[2] + nf_bearing)],\n 'cyan')\n" ]
[ [ "numpy.linspace", "matplotlib.pyplot.scatter", "matplotlib.pyplot.figure", "numpy.cos", "numpy.stack", "numpy.sin", "matplotlib.pyplot.plot", "matplotlib.pyplot.Circle", "numpy.transpose", "scipy.linalg.cholesky", "matplotlib.pyplot.gcf", "matplotlib.pyplot.axis", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.ion", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] } ]
zhuzilin/PatrickStar
[ "72daf8dbded07e03d911db6369b075c9bfcd5245" ]
[ "setup.py" ]
[ "# BSD 3-Clause License\n#\n# Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the psutil authors nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom setuptools import setup, find_packages\nfrom torch.utils.cpp_extension import BuildExtension\nfrom patrickstar.ops.op_builder import CPUAdamBuilder\n\n\ndef fetch_requirements(path):\n with open(path, \"r\") as fd:\n return [r.strip() for r in fd.readlines()]\n\n\nrequire_list = fetch_requirements(\"requirements.txt\")\n\nsetup(\n name=\"patrickstar\",\n version=\"0.4.3\",\n description=\"PatrickStart library\",\n long_description=\"PatrickStar: Parallel Training of Large Language Models via a Chunk-based Parameter Server\",\n long_description_content_type=\"text/markdown\",\n author=\"Tencent PatrickStar Team\",\n author_email=\"[email protected]\",\n url=\"https://fangjiarui.github.io/\",\n install_requires=require_list,\n setup_requires=require_list,\n packages=find_packages(),\n include_package_data=True,\n classifiers=[\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n ],\n license=\"BSD\",\n ext_modules=[CPUAdamBuilder().builder()],\n cmdclass={\"build_ext\": BuildExtension.with_options(use_ninja=False)},\n)\n" ]
[ [ "torch.utils.cpp_extension.BuildExtension.with_options" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nowireless/opencv
[ "1fcc4c74fefee4f845c0d57799163a1cbf36f654" ]
[ "modules/dnn/test/pascal_semsegm_test_fcn.py" ]
[ "from __future__ import print_function\nfrom abc import ABCMeta, abstractmethod\nimport numpy as np\nimport sys\nimport argparse\nimport time\n\nfrom imagenet_cls_test_alexnet import CaffeModel, DnnCaffeModel\ntry:\n import cv2 as cv\nexcept ImportError:\n raise ImportError('Can\\'t find OpenCV Python module. If you\\'ve built it from sources without installation, '\n 'configure environment variable PYTHONPATH to \"opencv_build_dir/lib\" directory (with \"python3\" subdirectory if required)')\n\n\ndef get_metrics(conf_mat):\n pix_accuracy = np.trace(conf_mat) / np.sum(conf_mat)\n t = np.sum(conf_mat, 1)\n num_cl = np.count_nonzero(t)\n assert num_cl\n mean_accuracy = np.sum(np.nan_to_num(np.divide(np.diagonal(conf_mat), t))) / num_cl\n col_sum = np.sum(conf_mat, 0)\n mean_iou = np.sum(\n np.nan_to_num(np.divide(np.diagonal(conf_mat), (t + col_sum - np.diagonal(conf_mat))))) / num_cl\n return pix_accuracy, mean_accuracy, mean_iou\n\n\ndef eval_segm_result(net_out):\n assert type(net_out) is np.ndarray\n assert len(net_out.shape) == 4\n\n channels_dim = 1\n y_dim = channels_dim + 1\n x_dim = y_dim + 1\n res = np.zeros(net_out.shape).astype(np.int)\n for i in range(net_out.shape[y_dim]):\n for j in range(net_out.shape[x_dim]):\n max_ch = np.argmax(net_out[..., i, j])\n res[0, max_ch, i, j] = 1\n return res\n\n\ndef get_conf_mat(gt, prob):\n assert type(gt) is np.ndarray\n assert type(prob) is np.ndarray\n\n conf_mat = np.zeros((gt.shape[0], gt.shape[0]))\n for ch_gt in range(conf_mat.shape[0]):\n gt_channel = gt[ch_gt, ...]\n for ch_pr in range(conf_mat.shape[1]):\n prob_channel = prob[ch_pr, ...]\n conf_mat[ch_gt][ch_pr] = np.count_nonzero(np.multiply(gt_channel, prob_channel))\n return conf_mat\n\n\nclass MeanChannelsPreproc:\n def __init__(self):\n pass\n\n @staticmethod\n def process(img):\n image_data = np.array(img).transpose(2, 0, 1).astype(np.float32)\n mean = np.ones(image_data.shape)\n mean[0] *= 104\n mean[1] *= 117\n mean[2] *= 123\n image_data -= mean\n image_data = np.expand_dims(image_data, 0)\n return image_data\n\n\nclass DatasetImageFetch(object):\n __metaclass__ = ABCMeta\n data_prepoc = object\n\n @abstractmethod\n def __iter__(self):\n pass\n\n @abstractmethod\n def next(self):\n pass\n\n @staticmethod\n def pix_to_c(pix):\n return pix[0] * 256 * 256 + pix[1] * 256 + pix[2]\n\n @staticmethod\n def color_to_gt(color_img, colors):\n num_classes = len(colors)\n gt = np.zeros((num_classes, color_img.shape[0], color_img.shape[1])).astype(np.int)\n for img_y in range(color_img.shape[0]):\n for img_x in range(color_img.shape[1]):\n c = DatasetImageFetch.pix_to_c(color_img[img_y][img_x])\n if c in colors:\n cls = colors.index(c)\n gt[cls][img_y][img_x] = 1\n return gt\n\n\nclass PASCALDataFetch(DatasetImageFetch):\n img_dir = ''\n segm_dir = ''\n names = []\n colors = []\n i = 0\n\n def __init__(self, img_dir, segm_dir, names_file, segm_cls_colors_file, preproc):\n self.img_dir = img_dir\n self.segm_dir = segm_dir\n self.colors = self.read_colors(segm_cls_colors_file)\n self.data_prepoc = preproc\n self.i = 0\n\n with open(names_file) as f:\n for l in f.readlines():\n self.names.append(l.rstrip())\n\n @staticmethod\n def read_colors(img_classes_file):\n result = []\n with open(img_classes_file) as f:\n for l in f.readlines():\n color = np.array(map(int, l.split()[1:]))\n result.append(DatasetImageFetch.pix_to_c(color))\n return result\n\n def __iter__(self):\n return self\n\n def next(self):\n if self.i < len(self.names):\n name = self.names[self.i]\n self.i += 1\n segm_file = self.segm_dir + name + \".png\"\n img_file = self.img_dir + name + \".jpg\"\n gt = self.color_to_gt(cv.imread(segm_file, cv.IMREAD_COLOR)[:, :, ::-1], self.colors)\n img = self.data_prepoc.process(cv.imread(img_file, cv.IMREAD_COLOR)[:, :, ::-1])\n return img, gt\n else:\n self.i = 0\n raise StopIteration\n\n def get_num_classes(self):\n return len(self.colors)\n\n\nclass SemSegmEvaluation:\n log = sys.stdout\n\n def __init__(self, log_path,):\n self.log = open(log_path, 'w')\n\n def process(self, frameworks, data_fetcher):\n samples_handled = 0\n\n conf_mats = [np.zeros((data_fetcher.get_num_classes(), data_fetcher.get_num_classes())) for i in range(len(frameworks))]\n blobs_l1_diff = [0] * len(frameworks)\n blobs_l1_diff_count = [0] * len(frameworks)\n blobs_l_inf_diff = [sys.float_info.min] * len(frameworks)\n inference_time = [0.0] * len(frameworks)\n\n for in_blob, gt in data_fetcher:\n frameworks_out = []\n samples_handled += 1\n for i in range(len(frameworks)):\n start = time.time()\n out = frameworks[i].get_output(in_blob)\n end = time.time()\n segm = eval_segm_result(out)\n conf_mats[i] += get_conf_mat(gt, segm[0])\n frameworks_out.append(out)\n inference_time[i] += end - start\n\n pix_acc, mean_acc, miou = get_metrics(conf_mats[i])\n\n name = frameworks[i].get_name()\n print(samples_handled, 'Pixel accuracy, %s:' % name, 100 * pix_acc, file=self.log)\n print(samples_handled, 'Mean accuracy, %s:' % name, 100 * mean_acc, file=self.log)\n print(samples_handled, 'Mean IOU, %s:' % name, 100 * miou, file=self.log)\n print(\"Inference time, ms \", \\\n frameworks[i].get_name(), inference_time[i] / samples_handled * 1000, file=self.log)\n\n for i in range(1, len(frameworks)):\n log_str = frameworks[0].get_name() + \" vs \" + frameworks[i].get_name() + ':'\n diff = np.abs(frameworks_out[0] - frameworks_out[i])\n l1_diff = np.sum(diff) / diff.size\n print(samples_handled, \"L1 difference\", log_str, l1_diff, file=self.log)\n blobs_l1_diff[i] += l1_diff\n blobs_l1_diff_count[i] += 1\n if np.max(diff) > blobs_l_inf_diff[i]:\n blobs_l_inf_diff[i] = np.max(diff)\n print(samples_handled, \"L_INF difference\", log_str, blobs_l_inf_diff[i], file=self.log)\n\n self.log.flush()\n\n for i in range(1, len(blobs_l1_diff)):\n log_str = frameworks[0].get_name() + \" vs \" + frameworks[i].get_name() + ':'\n print('Final l1 diff', log_str, blobs_l1_diff[i] / blobs_l1_diff_count[i], file=self.log)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--imgs_dir\", help=\"path to PASCAL VOC 2012 images dir, data/VOC2012/JPEGImages\")\n parser.add_argument(\"--segm_dir\", help=\"path to PASCAL VOC 2012 segmentation dir, data/VOC2012/SegmentationClass/\")\n parser.add_argument(\"--val_names\", help=\"path to file with validation set image names, download it here: \"\n \"https://github.com/shelhamer/fcn.berkeleyvision.org/blob/master/data/pascal/seg11valid.txt\")\n parser.add_argument(\"--cls_file\", help=\"path to file with colors for classes, download it here: \"\n \"https://github.com/opencv/opencv/blob/4.x/samples/data/dnn/pascal-classes.txt\")\n parser.add_argument(\"--prototxt\", help=\"path to caffe prototxt, download it here: \"\n \"https://github.com/opencv/opencv/blob/4.x/samples/data/dnn/fcn8s-heavy-pascal.prototxt\")\n parser.add_argument(\"--caffemodel\", help=\"path to caffemodel file, download it here: \"\n \"http://dl.caffe.berkeleyvision.org/fcn8s-heavy-pascal.caffemodel\")\n parser.add_argument(\"--log\", help=\"path to logging file\")\n parser.add_argument(\"--in_blob\", help=\"name for input blob\", default='data')\n parser.add_argument(\"--out_blob\", help=\"name for output blob\", default='score')\n args = parser.parse_args()\n\n prep = MeanChannelsPreproc()\n df = PASCALDataFetch(args.imgs_dir, args.segm_dir, args.val_names, args.cls_file, prep)\n\n fw = [CaffeModel(args.prototxt, args.caffemodel, args.in_blob, args.out_blob, True),\n DnnCaffeModel(args.prototxt, args.caffemodel, '', args.out_blob)]\n\n segm_eval = SemSegmEvaluation(args.log)\n segm_eval.process(fw, df)\n" ]
[ [ "numpy.expand_dims", "numpy.sum", "numpy.abs", "numpy.multiply", "numpy.diagonal", "numpy.ones", "numpy.max", "numpy.argmax", "numpy.count_nonzero", "numpy.array", "numpy.zeros", "numpy.trace" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
stephanecollot/lofo-importance
[ "ca9599f73c939621b3b247a0ccd38c28d23f9dee" ]
[ "tests/test_lofo_importance.py" ]
[ "from sklearn.linear_model import LogisticRegression\nfrom lofo.lofo_importance import LOFOImportance\nfrom data.test_data import generate_test_data\nfrom lightgbm import LGBMRegressor\nfrom sklearn.model_selection import KFold\n\n\ndef test_lofo_importance():\n df = generate_test_data(1000)\n\n features = [\"A\", \"B\", \"C\", \"D\"]\n\n lgbm = LGBMRegressor(random_state=0, n_jobs=4)\n\n lofo = LOFOImportance(lgbm, df, features, 'binary_target', cv=4, scoring='roc_auc')\n\n importance_df = lofo.get_importance()\n\n assert len(features) == importance_df.shape[0], \"Missing importance value for some features!\"\n assert importance_df[\"feature\"].values[0] == \"B\", \"Most important feature is different than B!\"\n\n\ndef test_multithreading():\n df = generate_test_data(100000)\n\n features = [\"A\", \"B\", \"C\", \"D\"]\n\n lr = LogisticRegression(solver='liblinear')\n cv = KFold(n_splits=4, shuffle=True, random_state=0)\n\n lofo = LOFOImportance(lr, df, features, 'binary_target', cv=cv, scoring='roc_auc', n_jobs=3)\n\n importance_df = lofo.get_importance()\n\n assert len(features) == importance_df.shape[0], \"Missing importance value for some features!\"\n assert importance_df[\"feature\"].values[0] == \"B\", \"Most important feature is different than B!\"\n" ]
[ [ "sklearn.linear_model.LogisticRegression", "sklearn.model_selection.KFold" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
huy-ha/nerf
[ "413cf11dbf469b5cb3281306ed1c86b2a474b031" ]
[ "get_gt.py" ]
[ "import json\nimport imageio\nimport numpy as np\nimport tensorflow as tf\nimport os\n\ntf.compat.v1.enable_eager_execution()\n\n\ndef load_gt_data(basedir, timestep, testskip=1):\n with open(os.path.join(basedir, 'transforms.json'), 'r') as fp:\n meta = json.load(fp)\n\n all_imgs = []\n all_poses = []\n all_timesteps = []\n max_time = float('-inf')\n min_time = float('inf')\n counts = [0]\n imgs = []\n poses = []\n timesteps = []\n\n for frame in meta['frames']:\n if frame['timestep'] == timestep:\n fname = os.path.join(basedir, frame['file_path'] + '.png')\n imgs.append(imageio.imread(fname))\n poses.append(np.array(frame['transform_matrix']))\n timestep = frame['timestep']\n timesteps.append(timestep)\n max_time = max(max_time, timestep)\n min_time = min(min_time, timestep)\n # keep all 4 channels (RGBA)\n imgs = (np.array(imgs) / 255.).astype(np.float32)\n poses = np.array(poses).astype(np.float32)\n counts.append(counts[-1] + imgs.shape[0])\n all_imgs.append(imgs)\n all_poses.append(poses)\n all_timesteps.append(timesteps)\n\n\n i_split = [np.arange(counts[i], counts[i+1]) for i in range(3)]\n\n imgs = np.concatenate(all_imgs, 0)\n poses = np.concatenate(all_poses, 0)\n timesteps = np.concatenate(all_timesteps, 0) # 826\n timesteps = [(t - min_time)/max_time - 0.5 for t in timesteps]\n\n H, W = imgs[0].shape[:2]\n camera_angle_x = float(meta['camera_angle_x'])\n focal = .5 * W / np.tan(.5 * camera_angle_x)\n\n # render_poses = tf.stack([pose_spherical(angle, -30.0, 6.0)\n # for angle in np.linspace(-180, 180, 40+1)[:-1]], 0)\n\n return imgs, poses, [H, W, focal], i_split, timesteps\n\n\nunseen_timesteps = [1, 35]\nfor t in unseen_timesteps:\n # Load data\n images, poses, hwf, i_split, timesteps = \\\n load_gt_data(scene_dir_path='debug/277',\n testskip=1)\n # Cast intrinsics to right types\n # H, W, focal = hwf\n # H, W = int(H), int(W)\n # unseen_t = np.array([t] * (H * W))\n moviebase = os.path.join(\n '/home/sujipark/nerf', 'gt_{}'.format(t))\n imageio.mimwrite(moviebase + 'rgb.mp4',\n images, fps=30, quality=8)" ]
[ [ "numpy.arange", "tensorflow.compat.v1.enable_eager_execution", "numpy.concatenate", "numpy.tan", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DylanScotney/cryptocurrency_backtesting
[ "268931ad24f90df676193b15b8bfaa791de616d8" ]
[ "Lib/data_loading/file_loading_strategies.py" ]
[ "import json\nimport numpy as np\nfrom datetime import datetime\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom pandas.plotting import register_matplotlib_converters\n\nfrom .abstract_data_loading_strategy import dataLoadingStrat\n\n\nclass fileLoadingRaw(dataLoadingStrat):\n \"\"\"\n concrete data loading strategy used for dataLoader class.\n Designed to load raw data stored from CryptoCompare api that as been\n stored in json format\n\n Initialisation / construction:\n - infile: desired json file to load. json file has\n been saved using the related webLoading\n class, that is file is of format:\n { \"asset\": [\n {\n \"time\": 1552147200,\n \"close\": 3937.14,\n \"high\": 3975.25,\n \"low\": 3933.41,\n \"open\": 3956.05,\n \"volumefrom\": 2041.4,\n \"volumeto\": 8097477.69\n },\n ...\n ],\n ...\n }\n - symbols: list of symbols corresponding to data in\n infile.\n - ticksize: interval of datapoints in infile.\n \"minute\", \"hour\" or \"day\".\n - outfile: optional outfile to save df.\n \"\"\"\n\n def __init__(self, infile, symbols, ticksize, outfile=False):\n\n if infile.endswith('.json'):\n self._infile = infile\n else:\n raise ValueError(\"Infile must be json format\")\n\n if all(isinstance(symbol, str) for symbol in symbols):\n self._symbols = symbols\n else:\n raise ValueError(\"Symbols must be list of string types\")\n\n if ticksize == \"hour\":\n self._freq = '1H'\n elif ticksize == \"day\":\n self._freq = '1D'\n elif ticksize == 'minute':\n self._freq = '1T'\n else:\n raise ValueError(\"Incompatible ticksize\")\n\n self._ticksize = ticksize\n\n if outfile and not outfile.endswith('.csv'):\n raise ValueError(\"outfile must be csv type\")\n\n self._outfile = outfile\n\n def get_data(self):\n \"\"\"\n Loads close prices of all assets in self._symbols for ticksize\n self._freq from raw data in self._infile by computing several\n steps:\n 1. First checks all data and get the earliest and latest\n timestamps\n 2. Creates a pandas dataframe which stores a list of datetimes\n as an index from earliest timestamp to latest timestamp in steps\n of self._ticksize.\n 3. Then pulls associated close prices from raw json file and\n stores in dataframe.\n\n Outputs:\n - df: (pandas DataFrame) holds close prices of all\n assets in self._symbols along with\n associated datetimes as index\n\n Notes:\n - If there is no close prices associated with a given date,\n function takes price from associated w/ previous time.\n - This function is reasonably ineffcient as iterates over the\n dataset twice. First to determine times and second to get data\n \"\"\"\n\n with open(self._infile) as json_file:\n raw_data = json.load(json_file)\n\n now = datetime.now()\n earliest_timestamp = (now - datetime(1970, 1, 1)).total_seconds()\n latest_timestamp = 0\n\n # determine the longest series in file to build dataframe\n for symbol in self._symbols:\n asset = raw_data[symbol]\n for i in range(len(asset)):\n if asset[i]['time'] < earliest_timestamp:\n earliest_timestamp = asset[i]['time']\n if asset[i]['time'] > latest_timestamp:\n latest_timestamp = asset[i]['time']\n\n # set up dataframe\n start_date = datetime.fromtimestamp(earliest_timestamp)\n end_date = datetime.fromtimestamp(latest_timestamp)\n times = pd.date_range(start=start_date, end=end_date, freq=self._freq)\n df = pd.DataFrame({'date': times})\n df = df.set_index('date')\n\n for symbol in self._symbols:\n print(symbol)\n df[symbol] = 0.0 # initilise asset row in df\n asset_data = raw_data[symbol]\n close_times = ([datetime.fromtimestamp(item['time'])\n for item in asset_data])\n\n if(self._ticksize == \"day\"):\n close_times = [time.date() for time in close_times]\n close_prices = [item[\"close\"] for item in asset_data]\n\n # Store data in dataframe\n # -----------------------------------------------------------------\n for i in range(df.shape[0]):\n date = df.index[i]\n if self._ticksize == \"day\":\n date = date.date()\n try:\n index = close_times.index(date)\n df[symbol][i] = close_prices[index]\n except ValueError:\n # if no data at date, assume the previous date's data\n if i > 0:\n df[symbol][i] = df[symbol][i-1]\n # -----------------------------------------------------------------\n\n if self._outfile:\n df.to_csv(self._outfile)\n\n return df\n\n\nclass fileLoadingDF(dataLoadingStrat):\n \"\"\"\n Concrete data loading strategy for the data loading class.\n Reads data stored in a pandas DataFrame.\n\n Initialisation: \n - infile: (str) file name of csv file containing data\n \"\"\"\n\n def __init__(self, infile):\n if infile.endswith('.csv'):\n self._infile = infile\n else:\n raise ValueError(\"infile must be csv format\")\n\n def get_data(self): \n df = pd.read_csv(self._infile)\n if 'Unnamed: 0' in df.keys():\n df = df.drop(columns=['Unnamed: 0']) # Drop index column\n return df\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame", "pandas.date_range" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Eren-Corn0712/Eren-Corn0712-EsVit_on_Tumor
[ "ceb1e76a795c3ad2aa3d576233fbf91c6a6399f6" ]
[ "models/vision_transformer.py" ]
[ "# Modified by Chunyuan Li ([email protected])\r\n#\r\n# Copyright (c) Facebook, Inc. and its affiliates.\r\n# \r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n# \r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n# \r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\n\"\"\"\r\nMostly copy-paste from timm library.\r\nhttps://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py\r\n\"\"\"\r\nimport math\r\nfrom functools import partial\r\n\r\nimport torch\r\nimport torch.nn as nn\r\n\r\nfrom utils import trunc_normal_\r\n\r\n\r\ndef drop_path(x, drop_prob: float = 0., training: bool = False):\r\n if drop_prob == 0. or not training:\r\n return x\r\n keep_prob = 1 - drop_prob\r\n shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets\r\n random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)\r\n random_tensor.floor_() # binarize\r\n output = x.div(keep_prob) * random_tensor\r\n return output\r\n\r\n\r\nclass DropPath(nn.Module):\r\n \"\"\"Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).\r\n \"\"\"\r\n\r\n def __init__(self, drop_prob=None):\r\n super(DropPath, self).__init__()\r\n self.drop_prob = drop_prob\r\n\r\n def forward(self, x):\r\n return drop_path(x, self.drop_prob, self.training)\r\n\r\n\r\nclass Mlp(nn.Module):\r\n def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):\r\n super().__init__()\r\n out_features = out_features or in_features\r\n hidden_features = hidden_features or in_features\r\n self.fc1 = nn.Linear(in_features, hidden_features)\r\n self.act = act_layer()\r\n self.fc2 = nn.Linear(hidden_features, out_features)\r\n self.drop = nn.Dropout(drop)\r\n\r\n def forward(self, x):\r\n x = self.fc1(x)\r\n x = self.act(x)\r\n x = self.drop(x)\r\n x = self.fc2(x)\r\n x = self.drop(x)\r\n return x\r\n\r\n\r\nclass Attention(nn.Module):\r\n def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):\r\n super().__init__()\r\n self.num_heads = num_heads\r\n head_dim = dim // num_heads\r\n self.scale = qk_scale or head_dim ** -0.5\r\n\r\n self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\r\n self.attn_drop = nn.Dropout(attn_drop)\r\n self.proj = nn.Linear(dim, dim)\r\n self.proj_drop = nn.Dropout(proj_drop)\r\n\r\n def forward(self, x):\r\n B, N, C = x.shape\r\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\r\n q, k, v = qkv[0], qkv[1], qkv[2]\r\n\r\n attn = (q @ k.transpose(-2, -1)) * self.scale\r\n attn = attn.softmax(dim=-1)\r\n attn = self.attn_drop(attn)\r\n\r\n x = (attn @ v).transpose(1, 2).reshape(B, N, C)\r\n x = self.proj(x)\r\n x = self.proj_drop(x)\r\n return x, attn\r\n\r\n\r\nclass Block(nn.Module):\r\n def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,\r\n drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):\r\n super().__init__()\r\n self.norm1 = norm_layer(dim)\r\n self.attn = Attention(\r\n dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)\r\n self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\r\n self.norm2 = norm_layer(dim)\r\n mlp_hidden_dim = int(dim * mlp_ratio)\r\n self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)\r\n\r\n def forward(self, x, return_attention=False):\r\n y, attn = self.attn(self.norm1(x))\r\n if return_attention:\r\n return attn\r\n x = x + self.drop_path(y)\r\n x = x + self.drop_path(self.mlp(self.norm2(x)))\r\n return x\r\n\r\n def forward_fea_and_attn(self, x):\r\n y, attn = self.attn(self.norm1(x))\r\n x = x + self.drop_path(y)\r\n x = x + self.drop_path(self.mlp(self.norm2(x)))\r\n return x, attn\r\n\r\n\r\nclass PatchEmbed(nn.Module):\r\n \"\"\" Image to Patch Embedding\r\n \"\"\"\r\n\r\n def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):\r\n super().__init__()\r\n num_patches = (img_size // patch_size) * (img_size // patch_size)\r\n self.img_size = img_size\r\n self.patch_size = patch_size\r\n self.num_patches = num_patches\r\n\r\n self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)\r\n\r\n def forward(self, x):\r\n B, C, H, W = x.shape\r\n x = self.proj(x).flatten(2).transpose(1, 2)\r\n return x\r\n\r\n\r\nclass VisionTransformer(nn.Module):\r\n \"\"\" Vision Transformer \"\"\"\r\n\r\n def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12,\r\n num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,\r\n drop_path_rate=0., norm_layer=nn.LayerNorm, use_dense_prediction=False, **kwargs):\r\n super().__init__()\r\n self.num_features = self.embed_dim = embed_dim\r\n\r\n self.patch_embed = PatchEmbed(\r\n img_size=img_size[0], patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)\r\n num_patches = self.patch_embed.num_patches\r\n\r\n self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))\r\n self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))\r\n self.pos_drop = nn.Dropout(p=drop_rate)\r\n\r\n dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule\r\n self.blocks = nn.ModuleList([\r\n Block(\r\n dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,\r\n drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)\r\n for i in range(depth)])\r\n self.norm = norm_layer(embed_dim)\r\n\r\n # Classifier head\r\n self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()\r\n\r\n # Dense prediction head\r\n self.use_dense_prediction = use_dense_prediction\r\n if self.use_dense_prediction: self.head_dense = None\r\n\r\n trunc_normal_(self.pos_embed, std=.02)\r\n trunc_normal_(self.cls_token, std=.02)\r\n self.apply(self._init_weights)\r\n\r\n def _init_weights(self, m):\r\n if isinstance(m, nn.Linear):\r\n trunc_normal_(m.weight, std=.02)\r\n if isinstance(m, nn.Linear) and m.bias is not None:\r\n nn.init.constant_(m.bias, 0)\r\n elif isinstance(m, nn.LayerNorm):\r\n nn.init.constant_(m.bias, 0)\r\n nn.init.constant_(m.weight, 1.0)\r\n\r\n def forward(self, x):\r\n # convert to list\r\n if not isinstance(x, list):\r\n x = [x]\r\n # Perform forward pass separately on each resolution input.\r\n # The inputs corresponding to a single resolution are clubbed and single\r\n # forward is run on the same resolution inputs. Hence we do several\r\n # forward passes = number of different resolutions used. We then\r\n # concatenate all the output features.\r\n idx_crops = torch.cumsum(torch.unique_consecutive(\r\n torch.tensor([inp.shape[-1] for inp in x]),\r\n return_counts=True,\r\n )[1], 0)\r\n\r\n if self.use_dense_prediction:\r\n start_idx = 0\r\n\r\n for end_idx in idx_crops:\r\n _out_cls, _out_fea = self.forward_features(torch.cat(x[start_idx: end_idx]))\r\n B, N, C = _out_fea.shape\r\n\r\n if start_idx == 0:\r\n output_cls = _out_cls\r\n output_fea = _out_fea.reshape(B * N, C)\r\n npatch = [N]\r\n else:\r\n output_cls = torch.cat((output_cls, _out_cls))\r\n output_fea = torch.cat((output_fea, _out_fea.reshape(B * N, C)))\r\n npatch.append(N)\r\n start_idx = end_idx\r\n\r\n return self.head(output_cls), self.head_dense(output_fea), output_fea, npatch\r\n\r\n else:\r\n start_idx = 0\r\n for end_idx in idx_crops:\r\n _out = self.forward_features(torch.cat(x[start_idx: end_idx]))\r\n if start_idx == 0:\r\n output = _out\r\n else:\r\n output = torch.cat((output, _out))\r\n start_idx = end_idx\r\n\r\n # print(f'output[0] {output[0].shape}')\r\n # Run the head forward on the concatenated features.\r\n return self.head(output)\r\n\r\n def forward_features(self, x):\r\n B = x.shape[0]\r\n x = self.patch_embed(x)\r\n\r\n cls_tokens = self.cls_token.expand(B, -1, -1)\r\n x = torch.cat((cls_tokens, x), dim=1)\r\n pos_embed = self.interpolate_pos_encoding(x, self.pos_embed)\r\n x = x + pos_embed\r\n x = self.pos_drop(x)\r\n\r\n for blk in self.blocks:\r\n x = blk(x)\r\n if self.norm is not None:\r\n x = self.norm(x)\r\n\r\n if self.use_dense_prediction:\r\n return x[:, 0], x[:, 1:]\r\n else:\r\n return x[:, 0]\r\n\r\n def forward_feature_maps(self, x):\r\n B = x.shape[0]\r\n x = self.patch_embed(x)\r\n\r\n cls_tokens = self.cls_token.expand(B, -1, -1)\r\n x = torch.cat((cls_tokens, x), dim=1)\r\n pos_embed = self.interpolate_pos_encoding(x, self.pos_embed)\r\n x = x + pos_embed\r\n x = self.pos_drop(x)\r\n\r\n for blk in self.blocks:\r\n x = blk(x)\r\n if self.norm is not None:\r\n x = self.norm(x)\r\n\r\n return x\r\n\r\n def interpolate_pos_encoding(self, x, pos_embed):\r\n npatch = x.shape[1] - 1\r\n N = pos_embed.shape[1] - 1\r\n if npatch == N:\r\n return pos_embed\r\n class_emb = pos_embed[:, 0]\r\n pos_embed = pos_embed[:, 1:]\r\n dim = x.shape[-1]\r\n pos_embed = nn.functional.interpolate(\r\n pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),\r\n scale_factor=math.sqrt(npatch / N),\r\n mode='bicubic',\r\n )\r\n pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)\r\n return torch.cat((class_emb.unsqueeze(0), pos_embed), dim=1)\r\n\r\n def forward_selfattention(self, x, n=1):\r\n # n=1 return the last layer attn map; otherwise return attn maps in all layers\r\n\r\n B, nc, w, h = x.shape\r\n N = self.pos_embed.shape[1] - 1\r\n x = self.patch_embed(x)\r\n\r\n # interpolate patch embeddings\r\n dim = x.shape[-1]\r\n w0 = w // self.patch_embed.patch_size\r\n h0 = h // self.patch_embed.patch_size\r\n class_pos_embed = self.pos_embed[:, 0]\r\n patch_pos_embed = self.pos_embed[:, 1:]\r\n patch_pos_embed = nn.functional.interpolate(\r\n patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),\r\n scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),\r\n mode='bicubic',\r\n )\r\n if w0 != patch_pos_embed.shape[-2]:\r\n helper = torch.zeros(h0)[None, None, None, :].repeat(1, dim, w0 - patch_pos_embed.shape[-2], 1).to(x.device)\r\n patch_pos_embed = torch.cat((patch_pos_embed, helper), dim=-2)\r\n if h0 != patch_pos_embed.shape[-1]:\r\n helper = torch.zeros(w0)[None, None, :, None].repeat(1, dim, 1, h0 - patch_pos_embed.shape[-1]).to(x.device)\r\n pos_embed = torch.cat((patch_pos_embed, helper), dim=-1)\r\n patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)\r\n pos_embed = torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)\r\n\r\n cls_tokens = self.cls_token.expand(B, -1, -1)\r\n x = torch.cat((cls_tokens, x), dim=1)\r\n x = x + pos_embed\r\n x = self.pos_drop(x)\r\n\r\n if n == 1:\r\n return self.forward_last_selfattention(x)\r\n else:\r\n return self.forward_all_selfattention(x)\r\n\r\n def forward_last_selfattention(self, x):\r\n for i, blk in enumerate(self.blocks):\r\n if i < len(self.blocks) - 1:\r\n x = blk(x)\r\n else:\r\n return blk(x, return_attention=True)\r\n\r\n def forward_all_selfattention(self, x):\r\n attn_out = []\r\n for i, blk in enumerate(self.blocks):\r\n x, attn = blk.forward_fea_and_attn(x)\r\n attn_out.append(attn)\r\n\r\n return attn_out\r\n\r\n def forward_return_n_last_blocks(self, x, n=1, return_patch_avgpool=False, depths=[]):\r\n B = x.shape[0]\r\n x = self.patch_embed(x)\r\n\r\n cls_tokens = self.cls_token.expand(B, -1, -1)\r\n x = torch.cat((cls_tokens, x), dim=1)\r\n pos_embed = self.interpolate_pos_encoding(x, self.pos_embed)\r\n x = x + pos_embed\r\n x = self.pos_drop(x)\r\n\r\n # we will return the [CLS] tokens from the `n` last blocks\r\n output = []\r\n for i, blk in enumerate(self.blocks):\r\n x = blk(x)\r\n if len(self.blocks) - i <= n:\r\n output.append(self.norm(x)[:, 0])\r\n if return_patch_avgpool:\r\n x = self.norm(x)\r\n # In addition to the [CLS] tokens from the `n` last blocks, we also return \r\n # the patch tokens from the last block. This is useful for linear eval.\r\n output.append(torch.mean(x[:, 1:], dim=1))\r\n return torch.cat(output, dim=-1)\r\n\r\n\r\ndef deit_tiny(patch_size=16, **kwargs):\r\n model = VisionTransformer(\r\n patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4,\r\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\r\n return model\r\n\r\n\r\ndef deit_small(patch_size=16, **kwargs):\r\n model = VisionTransformer(\r\n patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4,\r\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\r\n return model\r\n\r\n\r\ndef vit_base(patch_size=16, **kwargs):\r\n model = VisionTransformer(\r\n patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4,\r\n qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)\r\n return model\r\n\r\n\r\nclass DINOHead(nn.Module):\r\n def __init__(self, in_dim, out_dim, use_bn=False, norm_last_layer=True, nlayers=3, hidden_dim=2048,\r\n bottleneck_dim=256):\r\n super().__init__()\r\n nlayers = max(nlayers, 1)\r\n if nlayers == 1:\r\n self.mlp = nn.Linear(in_dim, bottleneck_dim)\r\n else:\r\n layers = [nn.Linear(in_dim, hidden_dim)]\r\n if use_bn:\r\n layers.append(nn.BatchNorm1d(hidden_dim))\r\n layers.append(nn.GELU())\r\n for _ in range(nlayers - 2):\r\n layers.append(nn.Linear(hidden_dim, hidden_dim))\r\n if use_bn:\r\n layers.append(nn.BatchNorm1d(hidden_dim))\r\n layers.append(nn.GELU())\r\n layers.append(nn.Linear(hidden_dim, bottleneck_dim))\r\n self.mlp = nn.Sequential(*layers)\r\n self.apply(self._init_weights)\r\n self.last_layer = nn.utils.weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False))\r\n self.last_layer.weight_g.data.fill_(1)\r\n if norm_last_layer:\r\n self.last_layer.weight_g.requires_grad = False\r\n\r\n def _init_weights(self, m):\r\n if isinstance(m, nn.Linear):\r\n trunc_normal_(m.weight, std=.02)\r\n if isinstance(m, nn.Linear) and m.bias is not None:\r\n nn.init.constant_(m.bias, 0)\r\n\r\n def forward(self, x):\r\n x = self.mlp(x)\r\n x = nn.functional.normalize(x, dim=-1, p=2)\r\n x = self.last_layer(x)\r\n return x\r\n" ]
[ [ "torch.nn.functional.normalize", "torch.nn.Sequential", "torch.nn.Dropout", "torch.linspace", "torch.mean", "torch.nn.GELU", "torch.nn.BatchNorm1d", "torch.cat", "torch.zeros", "torch.nn.init.constant_", "torch.nn.Conv2d", "torch.tensor", "torch.nn.Linear", "torch.nn.Identity", "torch.rand" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gurasog/cognigraph
[ "34a0f31376bc2cb1b04e45bb333a3437dd6e560a" ]
[ "bci/classifiers.py" ]
[ "from sklearn.naive_bayes import GaussianNB\nimport numpy as np\n\ndef prepare_data_with_window(data, window_shape):\n index_for_data = len(data) // window_shape\n print(index_for_data)\n cut_data = data[0:index_for_data * window_shape]\n print(len(cut_data))\n new_sample = np.empty(0)\n print(type(new_sample))\n new_data = []\n\n for i in range(index_for_data * window_shape):\n if i % window_shape != window_shape - 1:\n new_sample = np.append(new_sample, data[i])\n # print(i)\n # print(data[i])\n else:\n new_sample = np.append(new_sample, data[i])\n new_data.append(new_sample.flatten())\n new_sample = []\n\n new_data = np.array(new_data)\n\n print(\"prepare_data_with_window was run\")\n return new_data\n\n\n\ndef run_naive_bayes(x, y):\n gnb = GaussianNB()\n gnb.fit(x, y)\n y_predicted = gnb.predict(x)\n\n print(\"run_pca was run\")\n return y_predicted\n\n" ]
[ [ "numpy.append", "numpy.array", "sklearn.naive_bayes.GaussianNB", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Bibbidi-Babbidi-Boo/SDRE-based-Cooperative-UAV-Landing-on-High-speed-targets
[ "515fb38120990cb707521da1a5870721b0ee842a", "515fb38120990cb707521da1a5870721b0ee842a" ]
[ "quadcopter/script/extras/sdre_real.py", "quadcopter/script/extras/kalman_filter_cam.py" ]
[ "#!/usr/bin/env python\nimport rospy\nimport tf\nimport scipy.linalg as la\nimport numpy as np\nfrom math import *\nimport mavros_msgs.srv\nfrom mavros_msgs.msg import AttitudeTarget\nfrom nav_msgs.msg import Odometry\nfrom std_msgs.msg import *\nfrom geometry_msgs.msg import *\nfrom mavros_msgs.msg import *\nfrom quadcopter.msg import *\nimport time\nimport control.matlab as mb\nimport csv\nfrom timeit import default_timer as timer\n\nrospy.init_node('sdre', anonymous=True)\npub = rospy.Publisher(\"/drone/mavros/setpoint_raw/attitude\", AttitudeTarget, queue_size=10)\n\n#posn = open('posn4.csv', 'w')\n\nroll = 0.0\npitch = 0.0\nyaw = 0.0\ndetect = 1\nnow = timer()\n\nmsg = AttitudeTarget()\n\n### Goal in gazebo frame with origin as start, from the start point of drone\ngoal = np.array([0.0, 0.0, 0.0])\n\ngoal_body = np.array([0.0, 0.0, 0.0])\n\nx = 0.0\ny = 0.0\nz = 0.0\nx_r = 0.0\ny_r = 0.0\nv_x = 0.0\nv_y = 0.0\nv_z = 0.0\n\nvel_rover = [0,0,0]\n\nA = np.array([[0, 1, 0, 0, 0, 0]\n ,[0, 0, 0, 0, 0, 0]\n ,[0, 0, 0, 1, 0, 0]\n ,[0, 0, 0, 0, 0, 0]\n ,[0, 0, 0, 0, 0, 1]\n ,[0, 0, 0, 0, 0, 0]])\n\nRot_body_to_inertial = np.array([[cos(yaw)*cos(pitch), -sin(yaw)*cos(roll)+sin(roll)*sin(pitch)*cos(yaw), sin(yaw)*sin(roll)+cos(roll)*cos(yaw)*sin(pitch)]\n ,[sin(yaw)*cos(pitch), cos(yaw)*cos(roll)+sin(roll)*sin(pitch)*sin(yaw), -sin(roll)*cos(yaw)+sin(yaw)*sin(pitch)*cos(roll)]\n ,[-sin(pitch), cos(pitch)*sin(roll), cos(pitch)*cos(roll)]])\nRot_inertial_to_body = Rot_body_to_inertial.transpose()\n\n\ndef sdre():\n while not rospy.is_shutdown():\n now = timer()\n global x_r, y_r, detect, x, y, z, roll, pitch, yaw, vel_rover, goal, goal_body, v_x, v_y, v_z, Rot_body_to_inertial, Rot_inertial_to_body\n #### Global to Body conversion for the goal\n\n #posn.write('%f;' % float(x))\n #posn.write('%f;' % float(z))\n #posn.write('%f;' % float(x_r))\n #posn.write('%f;' % float(now))\n #posn.write('\\n')\n\n goal_body[0] = goal[0] - x\n goal_body[1] = goal[1] - y\n goal_body[2] = goal[2] - z\n\n goal_body = np.dot(Rot_inertial_to_body,goal_body.transpose())\n\n #### Weighting Matrices Q R\n Q = np.array([[((5*goal_body[0])**2)/abs(goal_body[2]+0.0001)+1, 0, 0, 0, 0, 0]\n ,[0, abs(150*(0.5+abs(goal_body[2]))*(vel_rover[0]-v_x)/(0.001+0.1*abs(goal_body[0]))), 0, 0, 0, 0]\n ,[0, 0, ((5*goal_body[1])**2)/abs(goal_body[2]+0.0001)+1, 0, 0, 0]\n ,[0, 0, 0, abs(150*(0.5+abs(goal_body[2]))*(vel_rover[1]-v_y)/(0.001+0.1*abs(goal_body[1]))), 0, 0]\n ,[0, 0, 0, 0, 1+(10*goal_body[2]/sqrt(0.01+0.01*(goal_body[0]**2)+0.01*(goal_body[1]**2)))**2, 0]\n ,[0, 0, 0, 0, 0, 1/abs(goal_body[2]+0.001)]])\n\n R = np.array([[800, 0, 0] #z - accn\n ,[0, 75000, 0] #Pitch\n ,[0, 0, 75000]]) #Roll\n\n #### Calculation for control done in body fixed frame\n ### d2(e_x)/dt2 = 0-d2(x)/dt2 so all signs inverted\n X = np.array([[goal_body[0]],[vel_rover[0]-v_x],[goal_body[1]],[vel_rover[1]-v_y],[goal_body[2]],[vel_rover[2]-v_z]])\n\n\n B = np.array([[0, 0, 0], [0, -9.8, 0], [0, 0, 0], [0, 0, 9.8], [0, 0, 0], [-1, 0, 0]])\n\n P = la.solve_continuous_are(A, B, Q, R)\n\n u = np.dot(-np.linalg.inv(R),B.transpose())\n u = np.dot(u,P)\n u = np.dot(u,X)\n\n u0 = float(u[0])\n u1 = float(u[1])\n u2 = float(u[2])\n\n #### Normalizing the received thrust\n u0 = (u0*1.5 + 14.7)/29.4\n\n #### Restrict rotation angles to 10 deg\n if u0>1:\n u0 = 1\n if u0<0:\n u0 = 0\n\n if u1>10*np.pi/180:\n u1 = 10*np.pi/180\n if u1<-10*np.pi/180:\n u1 = -10*np.pi/180\n\n if u2>10*np.pi/180:\n u2 = 10*np.pi/180\n if u2<-10*np.pi/180:\n u2 = -10*np.pi/180\n \n\n #### Start descending for small errors\n if sqrt(goal_body[0]**2+goal_body[1]**2)<0.8 and abs(goal_body[2])<1:\n rospy.loginfo(\"LAND\")\n u0 = 0.0\n u1 = 0.0\n u2 = 0.0\n\n\n #### Convert to quaternions and publish\n quater = tf.transformations.quaternion_from_euler(u2,u1,yaw) #0\n msg.header = Header()\n msg.type_mask = 0\n msg.orientation.x = quater[0]\n msg.orientation.y = quater[1]\n msg.orientation.z = quater[2]\n msg.orientation.w = quater[3]\n msg.body_rate.x = 0.0\n msg.body_rate.y = 0.0\n msg.body_rate.z = 0.0\n msg.thrust = u0\n\n pub.publish(msg)\n\n rate = rospy.Rate(100) \n rate.sleep\n\n\ndef callback(info):\n ##MUST GET HEADING\n global x, y, z, roll, pitch, yaw, vel_rover, vel_drone_rot, vel_drone_trans, head, error_head_prev, goal, goal_body, v_x, v_y, v_z, Rot_body_to_inertial, Rot_inertial_to_body\n \n ### Positions in global gazebo frame\n x = info.pose.pose.position.x\n y = info.pose.pose.position.y\n z = info.pose.pose.position.z\n\n ### All linear velocities are local \n v_x = info.twist.twist.linear.x\n v_y = info.twist.twist.linear.y\n v_z = info.twist.twist.linear.z\n \n ### Orientations in order of rotation\n a1 = info.pose.pose.orientation.x\n b1 = info.pose.pose.orientation.y\n c1 = info.pose.pose.orientation.z\n d1 = info.pose.pose.orientation.w\n\n roll, pitch, yaw = tf.transformations.euler_from_quaternion([a1,b1,c1,d1])\n\n ### Yaw in gazebo frame\n #yaw = yaw-np.pi/2\n #if yaw<np.pi/2:\n # yaw = yaw+2*np.pi/2\n #if yaw>np.pi/2:\n # yaw = yaw-2*np.pi/2\n\n Rot_body_to_inertial = np.array([[cos(yaw)*cos(pitch), -sin(yaw)*cos(roll)+sin(roll)*sin(pitch)*cos(yaw), sin(yaw)*sin(roll)+cos(roll)*cos(yaw)*sin(pitch)]\n ,[sin(yaw)*cos(pitch), cos(yaw)*cos(roll)+sin(roll)*sin(pitch)*sin(yaw), -sin(roll)*cos(yaw)+sin(yaw)*sin(pitch)*cos(roll)]\n ,[-sin(pitch), cos(pitch)*sin(roll), cos(pitch)*cos(roll)]])\n Rot_inertial_to_body = Rot_body_to_inertial.transpose()\n\n### Add integral error\n### No land if no detect\n\ndef ReceiveTar(info):\n global goal, vel_rover, Rot_inertial_to_body, detect, x, y, v_x, v_y\n\n ## Receive position info\n goal[0] = info.goal.x+x\n goal[1] = info.goal.y+y\n goal[2] = 0.435\n detect = info.detected\n\n ## Receive vel info and convert to body fixed frame\n v1 = info.vel.x\n v2 = info.vel.y\n v = np.array([[v1]\n ,[v2]\n ,[0.0]])\n v = np.dot(Rot_inertial_to_body, v)\n vel_rover[0] = float(v[0])\n vel_rover[1] = float(v[1])\n vel_rover[2] = float(v[2])\n \n\n#def callback2(info):\n# global x_r, y_r\n# x_r = info.pose.pose.position.y\n# y_r = -info.pose.pose.position.x\n\ndef listener():\n #rospy.Subscriber(\"/rover/mavros/local_position/odom\", Odometry, callback2)\n rospy.Subscriber(\"/drone/mavros/local_position/odom\", Odometry, callback)\n rospy.Subscriber('/kalman_filter', kalman, ReceiveTar)\n sdre()\n rospy.spin()\n\nif __name__ == '__main__':\n try:\n listener()\n except rospy.ROSInterruptException:\n posn.close()\n pass", "#!/usr/bin/env python\nimport rospy\nimport tf\nimport scipy.linalg as la\nimport scipy.signal as sig\nimport numpy as np\nfrom math import *\nimport mavros_msgs.srv\nfrom mavros_msgs.msg import AttitudeTarget\nfrom nav_msgs.msg import Odometry\nfrom std_msgs.msg import *\n# from test.msg import *\nfrom geometry_msgs.msg import *\nfrom mavros_msgs.msg import *\nfrom quadcopter.msg import *\nimport time\n# import control.matlab as mb\nfrom timeit import default_timer as timer\nfrom quadcopter.msg import *\nimport timeit\n\nrospy.init_node('kalman_filter', anonymous=True)\npub = rospy.Publisher(\"/kalman_filter\", kalman, queue_size=10)\n\nroll = 0.0\npitch = 0.0\nyaw = 0.0\nv_x = 0.0\nv_y = 0.0\nv_z = 0.0\nz = 0.0\nu1_prev = 0.0\nu2_prev = 0.0\nu3_prev = 0.0\nx1_prev = 0.0\nx2_prev = 0.0\nv_roll = 0.0\nv_pitch = 0.0\nv_yaw = 0.0\nv1_prev = 0.0\nv2_prev = 0.0\ni = 0\nv1 = 0.0\nv2 = 0.0\n\ndetect = 1\n\nnow_cam_p = timer()\nnow_cam = timer()\nnow_kal_p = timer()\nnow_kal = timer()\n\n#### Vert and hor fov\nhori_fov = np.pi/4 #on either side\nvert_fov = 2000*hori_fov/2000\n\nH = np.array([[1, 0, 0, 0]\n ,[0, 1, 0, 0]\n ,[0, 0, 1, 0]\n ,[0, 0, 0, 1]])\n\ngoal_pred = np.array([[0.0]\n ,[0.0]\n ,[0.0]\n ,[0.0]])\n\ngoal_pred_var = np.array([[1, 0, 0, 0]\n ,[0, 1, 0, 0]\n ,[0, 0, 1, 0]\n ,[0, 0, 0, 1]])\n\nRot_body_to_inertial = np.array([[cos(yaw)*cos(pitch), -sin(yaw)*cos(roll)+sin(roll)*sin(pitch)*cos(yaw), sin(yaw)*sin(roll)+cos(roll)*cos(yaw)*sin(pitch)]\n ,[sin(yaw)*cos(pitch), cos(yaw)*cos(roll)+sin(roll)*sin(pitch)*sin(yaw), -sin(roll)*cos(yaw)+sin(yaw)*sin(pitch)*cos(roll)]\n ,[-sin(pitch), cos(pitch)*sin(roll), cos(pitch)*cos(roll)]])\nRot_inertial_to_body = Rot_body_to_inertial.transpose()\n\n\nX = np.array([[0.0]\n ,[0.0]\n ,[0.0]\n ,[0.0]])\n\nP = np.array([[np.random.normal(0, 1), 0, 0, 0]\n ,[0, np.random.normal(0, 0.25), 0, 0]\n ,[0, 0, np.random.normal(0, 1), 0]\n ,[0, 0, 0, np.random.normal(0, 0.25)]])\n\nmsg = kalman()\n\ndef kalman(timer):\n global now_kal, now_kal_p, X, P, v_x, v_y, v_z, z, goal_pred, goal_pred_var, detect\n del_t = 0.01\n if detect == 0:\n #### If not detected assume no noise in kalman filter and inf noise in measurement\n Q = np.array([[np.random.normal(0, 1), 0, 0, 0]\n ,[0, np.random.normal(0, 1), 0, 0]\n ,[0, 0, np.random.normal(0, 1), 0]\n ,[0, 0, 0, np.random.normal(0, 1)]])\n else:\n Q = np.array([[np.random.normal(0, 4), 0, 0, 0]\n ,[0, np.random.normal(0, 1), 0, 0]\n ,[0, 0, np.random.normal(0, 4), 0]\n ,[0, 0, 0, np.random.normal(0, 1)]])\n\n #### Apply kalman filter\n v1 = float(X[1])\n v2 = float(X[3])\n A = np.array([[1, (del_t), 0, 0]\n ,[0, 1, 0, 0]\n ,[0, 0, 1, (del_t)]\n ,[0, 0, 0, 1]])\n\n X_new_pred = np.dot(A, X)\n\n P_k = np.dot(A, P)\n P_k = np.dot(P_k, A.transpose())\n Q = np.array([[np.random.normal(0, 3), 0, 0, 0]\n ,[0, np.random.normal(0, 1), 0, 0]\n ,[0, 0, np.random.normal(0, 3), 0]\n ,[0, 0, 0, np.random.normal(0, 1)]])\n\n P_k = P_k + Q\n\n mu_exp = np.dot(H, X_new_pred)\n std_dev_exp = np.dot(H.transpose(), P_k)\n std_dev_exp = np.dot(std_dev_exp, H)\n\n KG = np.dot(np.dot(std_dev_exp, H.transpose()), np.linalg.inv(std_dev_exp + goal_pred_var))\n\n X_new = X_new_pred + np.dot(KG, (np.dot(H,goal_pred) - np.dot(H,mu_exp)))\n\n X = X_new\n\n P = std_dev_exp - np.dot(KG, std_dev_exp)\n msg.goal.x = float(X[0])\n msg.goal.y = float(X[2])\n msg.goal.z = 0.43582\n msg.vel.x = float(X[1])\n msg.vel.y = float(X[3])\n msg.vel.z = 0.0\n msg.posn.x = 0.0\n msg.posn.y = 0.0\n msg.posn.z = 0.435\n msg.detected = detect\n\n print(msg)\n pub.publish(msg)\n\n\ndef ReceiveTar(data):\n global i, now_cam, now_cam_p, v_x, v_y, v_z, v_roll, v_pitch, v_yaw, z, roll, pitch, yaw, goal_pred, Rot_body_to_inertial, goal_pred_var, detect, v1, v2, x1_prev, x2_prev\n\n R = Rot_body_to_inertial\n vx = v_x\n vy = v_y\n xt_image = data.center.x\n yt_image = data.center.y\n radius = data.radius\n detect = data.detected\n now_cam = data.time\n\n if detect==0:\n rospy.loginfo(detect)\n pass\n else:\n del_t = now_cam-now_cam_p\n if del_t == 0:\n pass\n else:\n x1, x2 = get_position(xt_image, yt_image, R)\n\n x1 = 0.65*x1 + 0.35*x1_prev\n x2 = 0.65*x2 + 0.35*x2_prev\n x1_prev = x1\n x2_prev = x2\n\n goal_pred = np.array([[x1]\n ,[v1]\n ,[x2]\n ,[v2]])\n\n img = np.array([[x1]\n ,[x2]\n ,[0.43582]])\n\n goal_pred_var = np.array([[np.random.normal(0, 0.3*1.1**(float(img[0])*0.25/(z+0.0001))), 0, 0, 0]\n ,[0, np.random.normal(0, 1+12*(abs(v_pitch)+abs(v_roll))+0.5*abs(v_x*v_y)+1/(0.25+abs(z-0.43582))), 0, 0]\n ,[0, 0, np.random.normal(0, 0.3*1.1**(float(img[1])*0.25/(z+0.0001))), 0]\n ,[0, 0, 0, np.random.normal(0, 1+12*(abs(v_pitch)+abs(v_roll))+0.5*abs(v_x*v_y)+1/(0.25+abs(z-0.43582)))]])\n\n now_cam_p = data.time\n i+=1\n\ndef get_position(xt, yt, R):\n global vert_fov, hori_fov, z\n key_points_dir_body = np.array([[cos(np.pi/4-vert_fov)*cos(hori_fov), cos(np.pi/4-vert_fov)*cos(-hori_fov), cos(np.pi/4+vert_fov)*cos(hori_fov), cos(np.pi/4+vert_fov)*cos(-hori_fov), cos(np.pi/4)]\n ,[sin(hori_fov), sin(-hori_fov), sin(hori_fov), sin(-hori_fov), 0]\n ,[-sin(np.pi/4-vert_fov)*cos(hori_fov), -sin(np.pi/4-vert_fov)*cos(-hori_fov), -sin(np.pi/4+vert_fov)*cos(hori_fov), -sin(np.pi/4+vert_fov)*cos(-hori_fov), -sin(np.pi/4)]])\n key_points_dir_global = np.dot(R, key_points_dir_body)\n\n for i in range(len(key_points_dir_global[0])):\n key_points_dir_global[0][i] = float(key_points_dir_global[0][i])*(0.43582-z)/float(key_points_dir_global[2][i])\n key_points_dir_global[1][i] = float(key_points_dir_global[1][i])*(0.43582-z)/float(key_points_dir_global[2][i])\n key_points_dir_global[2][i] = 0.43582\n\n M1 = np.array([[float(key_points_dir_global[0][0]), float(key_points_dir_global[1][0]), 1, 0, 0, 0, 0, 0, 0]\n ,[0, 0, 0, float(key_points_dir_global[0][0]), float(key_points_dir_global[1][0]), 1, 0, 0, 0]\n ,[float(key_points_dir_global[0][1]), float(key_points_dir_global[1][1]), 1, 0, 0, 0, -2000*float(key_points_dir_global[0][1]), -2000*float(key_points_dir_global[1][1]), -2000*1]\n ,[0, 0, 0, float(key_points_dir_global[0][1]), float(key_points_dir_global[1][1]), 1, 0, 0, 0]\n ,[float(key_points_dir_global[0][2]), float(key_points_dir_global[1][2]), 1, 0, 0, 0, 0, 0, 0]\n ,[0, 0, 0, float(key_points_dir_global[0][2]), float(key_points_dir_global[1][2]), 1, -2000*float(key_points_dir_global[0][2]), -2000*float(key_points_dir_global[1][2]), -2000*1]\n ,[float(key_points_dir_global[0][3]), float(key_points_dir_global[1][3]), 1, 0, 0, 0, -2000*float(key_points_dir_global[0][3]), -2000*float(key_points_dir_global[1][3]), -2000*1]\n ,[0, 0, 0, float(key_points_dir_global[0][3]), float(key_points_dir_global[1][3]), 1, -2000*float(key_points_dir_global[0][3]), -2000*float(key_points_dir_global[1][3]), -2000*1]\n ,[float(key_points_dir_global[0][4]), float(key_points_dir_global[1][4]), 1, 0, 0, 0, -1000*float(key_points_dir_global[0][4]), -1000*float(key_points_dir_global[1][4]), -1000*1]])\n\n\n M2 = np.array([[xt]\n ,[yt]\n ,[1]])\n\n U, D, V = np.linalg.svd(M1)\n M = np.reshape(V[len(V)-1], (3,3))\n M = np.linalg.inv(M)\n\n w1 = float(np.dot(M[0], M2)/np.dot(M[2], M2))\n w2 = float(np.dot(M[1], M2)/np.dot(M[2], M2))\n\n return w1, w2\n\ndef get_velocity(event):\n global u1_prev, u2_prev, u3_prev, v1, v2, v1_prev, v2_prev\n\n dt = 0.5\n\n w1 = float(goal_pred[0])\n w2 = float(goal_pred[2])\n v1_n = (w1-u1_prev)/dt\n v2_n = (w2-u2_prev)/dt\n\n v1 = 0.6*v1_n+0.4*v1_prev\n\n v2 = 0.6*v2_n+0.4*v2_prev\n\n v1_prev = v1\n v2_prev = v2\n\n u1_prev = w1\n u2_prev = w2\n\n\ndef callback(info):\n global z, roll, pitch, yaw, Rot_body_to_inertial, Rot_inertial_to_body, v_roll, v_pitch, v_yaw, v_x, v_y, v_z\n\n global z, roll, pitch, yaw, Rot_body_to_inertial, Rot_inertial_to_body, v_roll, v_pitch, v_yaw, v_x, v_y, v_z\n\n z = info.pose.pose.position.z\n\n v_x = info.twist.twist.linear.x\n v_y = info.twist.twist.linear.y\n v_z = info.twist.twist.linear.z\n\n a1 = info.pose.pose.orientation.x\n b1 = info.pose.pose.orientation.y\n c1 = info.pose.pose.orientation.z\n d1 = info.pose.pose.orientation.w\n roll, pitch, yaw = tf.transformations.euler_from_quaternion([a1,b1,c1,d1])\n\n yaw = yaw-np.pi/2\n\n Rot_body_to_inertial = np.array([[cos(yaw)*cos(pitch), -sin(yaw)*cos(roll)+sin(roll)*sin(pitch)*cos(yaw), sin(yaw)*sin(roll)+cos(roll)*cos(yaw)*sin(pitch)]\n ,[sin(yaw)*cos(pitch), cos(yaw)*cos(roll)+sin(roll)*sin(pitch)*sin(yaw), -sin(roll)*cos(yaw)+sin(yaw)*sin(pitch)*cos(roll)]\n ,[-sin(pitch), cos(pitch)*sin(roll), cos(pitch)*cos(roll)]])\n Rot_inertial_to_body = Rot_body_to_inertial.transpose()\n\n v_roll = info.twist.twist.angular.x\n v_pitch = info.twist.twist.angular.y\n v_yaw = info.twist.twist.angular.z\n\n\ndef listener():\n rospy.Subscriber('/landing_target_info_new', TargetInfo,ReceiveTar)\n rospy.Subscriber(\"/drone0/mavros/local_position/odom\", Odometry, callback)\n timer=rospy.Timer(rospy.Duration(10/1000.0),kalman)\n timer2=rospy.Timer(rospy.Duration(500/1000.0),get_velocity)\n rospy.spin()\n\nif __name__ == '__main__':\n try:\n listener()\n except rospy.ROSInterruptException:\n pass\n" ]
[ [ "numpy.linalg.inv", "numpy.dot", "numpy.array", "scipy.linalg.solve_continuous_are" ], [ "numpy.dot", "numpy.linalg.svd", "numpy.linalg.inv", "numpy.random.normal", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
panjiacheng/apollo
[ "d547687f8d1e6b37c97421923aa6f507dd6b9e1c" ]
[ "modules/tools/sensor_calibration/extract_data.py" ]
[ "#!/usr/bin/env python\n\n###############################################################################\n# Copyright 2019 The Apollo 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\"\"\"\nThis is a tool to extract useful information from given record files. It does\nself-check the validity of the uploaded data and able to inform developer's when\nthe data is not qualified, and reduce the size of uploaded data significantly.\n\"\"\"\nimport argparse\nfrom datetime import datetime\nimport numpy as np\nimport os\nimport sys\nimport shutil\nimport six\n\nfrom google.protobuf import text_format\n\nfrom cyber_py.record import RecordReader\nfrom cyber.proto import record_pb2\nfrom configuration_yaml_generator import ConfigYaml\nfrom extract_static_data import get_subfolder_list, select_static_image_pcd\nfrom modules.tools.sensor_calibration.proto import extractor_config_pb2\nfrom sensor_msg_extractor import GpsParser, ImageParser, PointCloudParser, PoseParser, ContiRadarParser\n\n#from scripts.record_bag import SMALL_TOPICS\n\nSMALL_TOPICS = [\n '/apollo/canbus/chassis',\n '/apollo/canbus/chassis_detail',\n '/apollo/control',\n '/apollo/control/pad',\n '/apollo/drive_event',\n '/apollo/guardian',\n '/apollo/hmi/status',\n '/apollo/localization/pose',\n '/apollo/localization/msf_gnss',\n '/apollo/localization/msf_lidar',\n '/apollo/localization/msf_status',\n '/apollo/monitor',\n '/apollo/monitor/system_status',\n '/apollo/navigation',\n '/apollo/perception/obstacles',\n '/apollo/perception/traffic_light',\n '/apollo/planning',\n '/apollo/prediction',\n '/apollo/relative_map',\n '/apollo/routing_request',\n '/apollo/routing_response',\n '/apollo/routing_response_history',\n '/apollo/sensor/conti_radar',\n '/apollo/sensor/delphi_esr',\n '/apollo/sensor/gnss/best_pose',\n '/apollo/sensor/gnss/corrected_imu',\n '/apollo/sensor/gnss/gnss_status',\n '/apollo/sensor/gnss/imu',\n '/apollo/sensor/gnss/ins_stat',\n '/apollo/sensor/gnss/odometry',\n '/apollo/sensor/gnss/raw_data',\n '/apollo/sensor/gnss/rtk_eph',\n '/apollo/sensor/gnss/rtk_obs',\n '/apollo/sensor/gnss/heading',\n '/apollo/sensor/mobileye',\n '/tf',\n '/tf_static',\n]\n\nCYBER_PATH = os.environ['CYBER_PATH']\nCYBER_RECORD_HEADER_LENGTH = 2048\n\ndef process_dir(path, operation):\n \"\"\"Create or remove directory.\"\"\"\n try:\n if operation == 'create':\n if os.path.exists(path):\n print('folder: %s exists' % path)\n else:\n print('create folder: %s' % path)\n os.makedirs(path)\n elif operation == 'remove':\n os.remove(path)\n else:\n print('Error! Unsupported operation %s for directory.' % operation)\n return False\n except OSError as e:\n print('Failed to %s directory: %s. Error: %s' %\n (operation, path, six.text_type(e)))\n return False\n\n return True\n\ndef get_sensor_channel_list(record_file):\n \"\"\"Get the channel list of sensors for calibration.\"\"\"\n record_reader = RecordReader(record_file)\n return set(channel_name for channel_name in record_reader.get_channellist()\n if 'sensor' in channel_name or '/localization/pose' in channel_name)\n\ndef validate_channel_list(channels, dictionary):\n ret = True\n for channel in channels:\n if channel not in dictionary:\n print('ERROR: channel %s does not exist in record sensor channels'\n % channel)\n ret = False\n\n return ret\n\ndef in_range(v, s, e):\n return True if v >= s and v <= e else False\n\ndef build_parser(channel, output_path):\n parser = None\n if channel.endswith(\"/image\"):\n parser = ImageParser(output_path=output_path, instance_saving=True)\n elif channel.endswith(\"/PointCloud2\"):\n parser = PointCloudParser(output_path=output_path, instance_saving=True)\n elif channel.endswith(\"/gnss/odometry\"):\n parser = GpsParser(output_path=output_path, instance_saving=False)\n elif channel.endswith(\"/localization/pose\"):\n parser = PoseParser(output_path=output_path, instance_saving=False)\n elif channel.startswith(\"/apollo/sensor/radar\"):\n parser = ContiRadarParser(output_path=output_path, instance_saving=True)\n else:\n raise ValueError(\"Not Support this channel type: %s\" %channel)\n\n return parser\n\ndef extract_data(record_files, output_path, channels,\n start_timestamp, end_timestamp, extraction_rates):\n \"\"\"\n Extract the desired channel messages if channel_list is specified.\n Otherwise extract all sensor calibration messages according to\n extraction rate, 10% by default.\n \"\"\"\n # all records have identical sensor channels.\n sensor_channels = get_sensor_channel_list(record_files[0])\n\n if (len(channels) > 0 and not validate_channel_list(channels,\n sensor_channels)):\n print('The input channel list is invalid.')\n return False\n\n # Extract all the sensor channels if channel_list is empty(no input arguments).\n print(sensor_channels)\n if len(channels) == 0:\n channels = sensor_channels\n\n # Declare logging variables\n process_channel_success_num = len(channels)\n process_channel_failure_num = 0\n process_msg_failure_num = 0\n\n channel_success = {}\n channel_occur_time = {}\n channel_output_path = {}\n #channel_messages = {}\n channel_parsers = {}\n for channel in channels:\n channel_success[channel] = True\n channel_occur_time[channel] = -1\n topic_name = channel.replace('/', '_')\n channel_output_path[channel] = os.path.join(output_path, topic_name)\n process_dir(channel_output_path[channel], operation='create')\n channel_parsers[channel] =\\\n build_parser(channel, channel_output_path[channel])\n\n # if channel in SMALL_TOPICS:\n # channel_messages[channel] = list()\n\n for record_file in record_files:\n record_reader = RecordReader(record_file)\n for msg in record_reader.read_messages():\n if msg.topic in channels:\n # Only care about messages in certain time intervals\n msg_timestamp_sec = msg.timestamp / 1e9\n if not in_range(msg_timestamp_sec, start_timestamp, end_timestamp):\n continue\n\n channel_occur_time[msg.topic] += 1\n # Extract the topic according to extraction_rate\n if channel_occur_time[msg.topic] % extraction_rates[msg.topic] != 0:\n continue\n\n ret = channel_parsers[msg.topic].parse_sensor_message(msg)\n\n # Calculate parsing statistics\n if not ret:\n process_msg_failure_num += 1\n if channel_success[msg.topic]:\n channel_success[msg.topic] = False\n process_channel_failure_num += 1\n process_channel_success_num -= 1\n print('Failed to extract data from channel: %s in record %s'\n % (msg.topic, record_file))\n\n # traverse the dict, if any channel topic stored as a list\n # then save the list as a summary file, mostly binary file\n for channel, parser in channel_parsers.items():\n save_combined_messages_info(parser, channel)\n\n # Logging statics about channel extraction\n print('Extracted sensor channel number [%d] from record files: %s'\n % (len(channels), ' '.join(record_files)))\n print('Successfully processed [%d] channels, and [%d] was failed.'\n % (process_channel_success_num, process_channel_failure_num))\n if process_msg_failure_num > 0:\n print('Channel extraction failure number is [%d].' % process_msg_failure_num)\n\n return True\n\ndef save_combined_messages_info(parser, channel):\n if not parser.save_messages_to_file():\n raise ValueError(\"cannot save combined messages into single file for : %s \" % channel)\n\n\n if not parser.save_timestamps_to_file():\n raise ValueError(\"cannot save tiemstamp info for %s \" % channel)\n\ndef generate_compressed_file(input_path, input_name,\n output_path, compressed_file='sensor_data'):\n \"\"\"\n Compress data extraction directory as a single tar.gz archive\n \"\"\"\n cwd_path = os.getcwd()\n os.chdir(input_path)\n shutil.make_archive(base_name=os.path.join(output_path, compressed_file),\n format='gztar',\n root_dir=input_path,\n base_dir=input_name)\n os.chdir(cwd_path)\n\ndef generate_extraction_rate_dict(channels, large_topic_extraction_rate,\n small_topic_extraction_rate=1):\n \"\"\"\n Default extraction rate for small topics is 1, which means no sampling\n \"\"\"\n\n # Validate extration_rate, and set it as an integer.\n if large_topic_extraction_rate < 1.0 or small_topic_extraction_rate < 1.0:\n raise ValueError(\"Extraction rate must be a number no less than 1.\")\n\n large_topic_extraction_rate = np.floor(large_topic_extraction_rate)\n small_topic_extraction_rate = np.floor(small_topic_extraction_rate)\n\n rates = {}\n for channel in channels:\n if channel in SMALL_TOPICS:\n rates[channel] = small_topic_extraction_rate\n else:\n rates[channel] = large_topic_extraction_rate\n\n return rates\n\ndef validate_record(record_file):\n \"\"\"Validate the record file.\"\"\"\n # Check the validity of a cyber record file according to header info.\n record_reader = RecordReader(record_file)\n header_msg = record_reader.get_headerstring()\n header = record_pb2.Header()\n header.ParseFromString(header_msg)\n print(\"header is {}\".format(header))\n\n if not header.is_complete:\n print('Record file: %s is not completed.' % record_file)\n return False\n if header.size == 0:\n print('Record file: %s. size is 0.' % record_file)\n return False\n if header.major_version != 1 and header.minor_version != 0:\n print('Record file: %s. version [%d:%d] is wrong.' %\n (record_file, header.major_version, header.minor_version))\n return False\n if header.begin_time >= header.end_time:\n print('Record file: %s. begin time [%s] is equal or larger than '\n 'end time [%s].' %\n (record_file, header.begin_time, header.end_time))\n return False\n\n if header.message_number < 1 or header.channel_number < 1:\n print('Record file: %s. [message:channel] number [%d:%d] is invalid.' %\n (record_file, header.message_number, header.channel_number))\n return False\n\n # There should be at least one sensor channel\n sensor_channels = get_sensor_channel_list(record_file)\n if len(sensor_channels) < 1:\n print('Record file: %s. cannot find sensor channels.' % record_file)\n return False\n\n return True\n\ndef validate_record_files(record_files, kword='.record.'):\n\n # load file list from directory if needs\n file_abs_paths = []\n if not isinstance(record_files, list):\n raise ValueError(\"Record files must be in a list\")\n\n if len(record_files) == 1 and os.path.isdir(record_files[0]):\n print('Load cyber records from: %s' % record_files[0])\n for f in sorted(os.listdir(record_files[0])):\n if kword in f:\n file_abs_path = os.path.join(record_files[0], f)\n if validate_record(file_abs_path):\n file_abs_paths.append(file_abs_path)\n else:\n print('Invalid record file: %s' % file_abs_path)\n else:\n for f in record_files:\n if not os.path.isfile(f):\n raise ValueError(\"Input cyber record does not exist or not a regular file: %s\" % f)\n\n if validate_record(f):\n file_abs_paths.append(f)\n else:\n print('Invalid record file: %s' % f)\n\n if len(file_abs_paths) < 1:\n raise ValueError(\"All the input record files are invalid\")\n\n # Validate all record files have the same sensor topics\n first_record_file = file_abs_paths[0]\n default_sensor_channels = get_sensor_channel_list(first_record_file)\n for i, f in enumerate(file_abs_paths[1:]):\n sensor_channels = get_sensor_channel_list(f)\n if sensor_channels != default_sensor_channels:\n print('Default sensor channel list in %s is: ' % first_record_file)\n print(default_sensor_channels)\n print('but sensor channel list in %s is: ' % file_abs_paths[i])\n print(sensor_channels)\n raise ValueError(\"The record files should contain the same channel list\")\n\n return file_abs_paths\n\ndef parse_channel_config(channels):\n channel_list = set()\n extraction_rate_dict = dict()\n\n for channel in channels:\n if channel.name in channel_list:\n raise ValueError(\"Duplicated channel config for : %s\" % channel.name)\n else:\n channel_list.add(channel.name)\n extraction_rate_dict[channel.name] = channel.extraction_rate\n\n return channel_list, extraction_rate_dict\ndef get_substring(str, prefix, suffix):\n \"\"\"return substring, eclusive prefix or suffix\"\"\"\n str_p = str.rfind(prefix) + len(prefix)\n end_p = str.rfind(suffix)\n return str[str_p:end_p]\n\ndef reorganize_extracted_data(tmp_data_path, task_name, remove_input_data_cache=False):\n root_path = os.path.dirname(os.path.normpath(tmp_data_path))\n\n config_yaml = ConfigYaml()\n if task_name == 'lidar_to_gnss':\n print (get_subfolder_list(tmp_data_path))\n subfolders = [x for x in get_subfolder_list(tmp_data_path)\n if '_apollo_sensor_' in x or '_localization_pose' in x]\n odometry_subfolders = [x for x in subfolders if '_odometry' in x or '_pose' in x]\n lidar_subfolders = [x for x in subfolders if '_PointCloud2' in x]\n print(lidar_subfolders)\n print(odometry_subfolders)\n if len(lidar_subfolders) is 0 or len(odometry_subfolders) is not 1:\n raise ValueError(('one odometry and more than 0 lidar(s)'\n 'sensor are needed for sensor calibration'))\n odometry_subfolder = odometry_subfolders[0]\n for lidar in lidar_subfolders:\n # get the lidar name from folder name string\n lidar_name = get_substring(str=lidar, prefix='_apollo_sensor_', suffix='_PointCloud2')\n gnss_name ='novatel'\n\n # reorganize folder structure: each lidar has its raw data,\n # corresponding odometry and configuration yaml file\n out_path = os.path.join(root_path, lidar_name + '_to_gnss_calibration')\n if not process_dir(out_path, 'create'):\n raise ValueError('Failed to create directory: %s' % out_path)\n lidar_in_path =os.path.join(tmp_data_path, lidar)\n lidar_out_path = os.path.join(out_path, lidar)\n shutil.copytree(lidar_in_path, lidar_out_path)\n odometry_in_path = os.path.join(tmp_data_path, odometry_subfolder)\n odometry_out_path = os.path.join(out_path, odometry_subfolder)\n shutil.copytree(odometry_in_path, odometry_out_path)\n\n generated_config_yaml = os.path.join(out_path, 'sample_config.yaml')\n config_yaml.generate_task_config_yaml(task_name=task_name,\n source_sensor=lidar_name, dest_sensor=gnss_name,\n source_folder=lidar, dest_folder=odometry_subfolder,\n out_config_file=generated_config_yaml)\n print('lidar {} calibration data and configuration'\n 'are generated.'.format(lidar_name))\n elif task_name == 'camera_to_lidar':\n # data selection.\n pair_data_folder_name = 'camera-lidar-pairs'\n cameras, lidar = select_static_image_pcd(path=tmp_data_path,\n min_distance=5, stop_times=4,\n wait_time=3, check_range=50,\n image_static_diff_threshold=0.005,\n output_folder_name=pair_data_folder_name,\n image_suffix='.jpg', pcd_suffix='.pcd')\n lidar_name = get_substring(str=lidar, prefix='_apollo_sensor_', suffix='_PointCloud2')\n for camera in cameras:\n camera_name = get_substring(str=camera, prefix='_apollo_sensor_', suffix='_image')\n out_path = os.path.join(root_path, camera_name + '_to_' + lidar_name + '_calibration')\n if not process_dir(out_path, 'create'):\n raise ValueError('Failed to create directory: %s' % out_path)\n # reorganize folder structure: each camera has its images,\n # corresponding lidar pointclouds, camera initial extrinsics,\n # intrinsics, and configuration yaml file\n\n in_pair_data_path = os.path.join(tmp_data_path, camera, pair_data_folder_name)\n out_pair_data_path = os.path.join(out_path, pair_data_folder_name )\n shutil.copytree(in_pair_data_path, out_pair_data_path )\n\n generated_config_yaml = os.path.join(out_path, 'sample_config.yaml')\n config_yaml.generate_task_config_yaml(task_name=task_name,\n source_sensor=camera_name, dest_sensor=lidar_name,\n source_folder=None, dest_folder=None,\n out_config_file=generated_config_yaml)\n elif task_name == 'radar_to_gnss':\n print('not ready. stay tuned')\n else:\n raise ValueError('Unsupported data extraction task for{}'.format(task_name))\n\n\n if remove_input_data_cache:\n print('removing the cache at {}'.format(tmp_data_path))\n os.system('rm -rf {}'.tmp_data_path)\n\ndef main():\n \"\"\"\n Main function\n \"\"\"\n if CYBER_PATH is None:\n print('Error: environment variable CYBER_PATH was not found, '\n 'set environment first.')\n sys.exit(1)\n\n os.chdir(CYBER_PATH)\n\n parser = argparse.ArgumentParser(\n description='A tool to extract data information for sensor calibration.')\n # parser.add_argument(\"-i\", \"--record_path\", action=\"append\", default=[], required=True,\n # dest='record_list',\n # help=\"Specify the record file to extract data information.\")\n # parser.add_argument(\"-o\", \"--output_path\", action=\"store\", type=str,\n # default=\"./extracted_data\",\n # help=\"The output directory to restore message.\")\n # # parser.add_argument(\"-z\", \"--compressed_file\", action=\"store\", type=str,\n # # default=\"extraction_data\", help=\"The output compressed filename.\")\n # parser.add_argument(\"-t\", \"--task_name\", action=\"store\", type=str, default=\"tmp\",\n # help=\"name of the data extraction task, e.g., Camera_Lidar_Calibration.\")\n # parser.add_argument(\"-c\", \"--channel_name\", dest='channel_list', action=\"append\",\n # default=[], help=\"list of channel_name that needs parsing.\")\n # parser.add_argument(\"-s\", \"--start_timestamp\", action=\"store\", type=float,\n # default=np.finfo(np.float32).min,\n # help=\"Specify the beginning time to extract data information.\")\n # parser.add_argument(\"-e\", \"--end_timestamp\", action=\"store\", type=float,\n # default=np.finfo(np.float32).max,\n # help=\"Specify the ending timestamp to extract data information.\")\n # parser.add_argument(\"-r\", \"--extraction_rate\", action=\"store\", type=int,\n # default=10, help=\"extraction rate for channel with large storage cost.\")\n parser.add_argument(\"--config\", action=\"store\", type=str, required=True, dest=\"config\",\n help=\"protobuf text format configuration file abosolute path\")\n args = parser.parse_args()\n\n config = extractor_config_pb2.DataExtractionConfig()\n with open(args.config, \"r\") as f:\n proto_block = f.read()\n text_format.Merge(proto_block, config)\n\n records = []\n for r in config.records.record_path:\n records.append(str(r))\n\n valid_record_list = validate_record_files(records, kword='.record.')\n\n channels, extraction_rates = parse_channel_config(config.channels.channel)\n print('parsing the following channels: %s' % channels)\n\n start_timestamp = -1\n end_timestamp = -1\n if config.io_config.start_timestamp == \"FLOAT_MIN\":\n start_timestamp = np.finfo(np.float32).min\n else:\n start_timestamp = np.float32(config.io_config.start_timestamp)\n\n if config.io_config.end_timestamp == \"FLOAT_MAX\":\n end_timestamp = np.finfo(np.float32).max\n else:\n end_timestamp = np.float32(config.io_config.end_timestamp)\n\n # Create directory to save the extracted data\n # use time now() as folder name\n output_relative_path = config.io_config.task_name +\\\n datetime.now().strftime(\"-%Y-%m-%d-%H-%M\") + '/tmp/'\n output_abs_path = os.path.join(config.io_config.output_path, output_relative_path)\n\n ret = process_dir(output_abs_path, 'create')\n if not ret:\n raise ValueError('Failed to create extrated data directory: %s' % output_abs_path)\n\n ret = extract_data(valid_record_list, output_abs_path, channels,\n start_timestamp, end_timestamp, extraction_rates)\n # output_abs_path='/apollo/data/extracted_data/CoolHigh-2019-09-20/camera_to_lidar-2019-12-16-16-33/tmp'\n reorganize_extracted_data(tmp_data_path=output_abs_path,\n task_name=config.io_config.task_name)\n # generate_compressed_file(input_path=config.io_config.output_path,\n # input_name=output_relative_path,\n # output_path=config.io_config.output_path,\n # compressed_file=config.io_config.task_name)\n\n print('Data extraction is completed successfully!')\n sys.exit(0)\n\nif __name__ == '__main__':\n # root_path = '/apollo/data/extracted_data/MKZ5-2019-05-15/lidar_to_gnss-2019-11-25-11-02/tmp'\n # task_name = 'lidar_to_gnss'\n # root_path = '/apollo/data/extracted_data/udevl002-2019-06-14/camera_to_lidar-2019-11-26-19-49/tmp'\n # task_name = 'camera_to_lidar'\n # reorganize_extracted_data(tmp_data_path=root_path, task_name=task_name)\n main()\n" ]
[ [ "numpy.float32", "numpy.floor", "numpy.finfo" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bicycle315/Qiskit-Metal
[ "41790052d79de0cad94e8c716e6ca1316164fa02" ]
[ "qiskit_metal/renderers/renderer_ansys/hfss_renderer.py" ]
[ "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Union, Tuple\n\nimport logging\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pyEPR as epr\nfrom pyEPR.ansys import set_property, parse_units\nfrom pyEPR.reports import (plot_convergence_f_vspass, plot_convergence_max_df,\n plot_convergence_maxdf_vs_sol,\n plot_convergence_solved_elem)\nfrom qiskit_metal import Dict\nfrom qiskit_metal.draw.utility import to_vec3D\nfrom qiskit_metal.renderers.renderer_ansys.ansys_renderer import (\n QAnsysRenderer, get_clean_name)\n\n\nclass QHFSSRenderer(QAnsysRenderer):\n \"\"\"Subclass of QAnsysRenderer for running HFSS simulations.\n\n QAnsysRenderer Default Options:\n * Lj: '10nH' -- Lj has units of nanoHenries (nH)\n * Cj: 0 -- Cj *must* be 0 for pyEPR analysis! Cj has units of femtofarads (fF)\n * _Rj: 0 -- _Rj *must* be 0 for pyEPR analysis! _Rj has units of Ohms\n * max_mesh_length_jj: '7um' -- Maximum mesh length for Josephson junction elements\n * project_path: None -- Default project path; if None --> get active\n * project_name: None -- Default project name\n * design_name: None -- Default design name\n * ansys_file_extension: '.aedt' -- Ansys file extension for 2016 version and newer\n * x_buffer_width_mm: 0.2 -- Buffer between max/min x and edge of ground plane, in mm\n * y_buffer_width_mm: 0.2 -- Buffer between max/min y and edge of ground plane, in mm\n \"\"\"\n\n name = 'hfss'\n \"\"\"Name\"\"\"\n\n hfss_options = Dict(\n drivenmodal_setup=Dict(freq_ghz='5',\n name=\"Setup\",\n max_delta_s='0.1',\n max_passes='10',\n min_passes='1',\n min_converged='1',\n pct_refinement='30',\n basis_order='1'),\n eigenmode_setup=Dict(name=\"Setup\",\n min_freq_ghz='1',\n n_modes='1',\n max_delta_f='0.5',\n max_passes='10',\n min_passes='1',\n min_converged='1',\n pct_refinement='30',\n basis_order='-1'),\n port_inductor_gap=\n '10um' # spacing between port and inductor if junction is drawn both ways\n )\n \"\"\"HFSS Options\"\"\"\n\n def __init__(self,\n design: 'QDesign',\n initiate=True,\n render_template: Dict = None,\n render_options: Dict = None):\n \"\"\"Create a QRenderer for HFSS simulations, subclassed from\n QAnsysRenderer.\n\n Args:\n design (QDesign): Use QGeometry within QDesign to obtain elements for Ansys.\n initiate (bool, optional): True to initiate the renderer. Defaults to True.\n render_template (Dict, optional): Typically used by GUI for template options for GDS. Defaults to None.\n render_options (Dict, optional): Used to override all options. Defaults to None.\n \"\"\"\n super().__init__(design=design,\n initiate=initiate,\n render_template=render_template,\n render_options=render_options)\n\n self.chip_subtract_dict = defaultdict(set)\n self.assign_perfE = []\n self.assign_mesh = []\n self.jj_lumped_ports = {}\n self.jj_to_ignore = set()\n\n self.current_sweep = None\n\n QHFSSRenderer.load()\n\n def render_design(self,\n selection: Union[list, None] = None,\n open_pins: Union[list, None] = None,\n port_list: Union[list, None] = None,\n jj_to_port: Union[list, None] = None,\n ignored_jjs: Union[list, None] = None,\n box_plus_buffer: bool = True):\n \"\"\"Initiate rendering of components in design contained in selection,\n assuming they're valid. Components are rendered before the chips they\n reside on, and subtraction of negative shapes is performed at the very\n end. Add the metalize() method here to turn objects in\n self.assign_perfE (see init in QAnsysRenderer class) into perfect\n electrical conductors. Create lumped ports as needed.\n\n First obtain a list of IDs of components to render and a corresponding\n case, denoted by self.qcomp_ids and self.case, respectively. If\n self.case == 1, all components in QDesign are to be rendered. If\n self.case == 0, a strict subset of components in QDesign are to be\n rendered. Otherwise, if self.case == 2, one or more component names in\n selection cannot be found in QDesign.\n\n Among the components selected for export, there may or may not be\n unused (unconnected) pins. The second parameter, open_pins, contains\n tuples of the form (component_name, pin_name) that specify exactly\n which pins should be open rather than shorted during the simulation.\n Both the component and pin name must be specified because the latter\n could be shared by multiple components. All pins in this list are\n rendered with an additional endcap in the form of a rectangular\n cutout, to be subtracted from its respective plane.\n\n In driven modal solutions, the Ansys design must include one or more\n ports. This is done by adding all port designations and their\n respective impedances in Ohms as (qcomp, pin, impedance) to port_list.\n Note that an open endcap must separate the two sides of each pin before\n inserting a lumped port in between, so behind the scenes all pins in\n port_list are also added to open_pins. Practically, however, port_list\n and open_pins are inputted as mutually exclusive lists.\n\n Also in driven modal solutions, one may want to render junctions as\n lumped ports and/or inductors, or omit them altogether. To do so,\n tuples of the form (component_name, element_name, impedance, draw_ind)\n are added to the list jj_to_port. For example,\n ('Q1', 'rect_jj', 70, True) indicates that rect_jj of component Q1 is\n to be rendered as both a lumped port with an impedance of 70 Ohms as\n well as an inductor whose properties are given in default_options.\n Replacing the last entry of this 4-element tuple with False would\n indicate that only the port is to be drawn, not the inductor.\n Alternatively for driven modal solutions, one may want to disregard\n select junctions in the Metal design altogether to simulate the\n capacitive effect while keeping the qubit in an \"off\" state. Such\n junctions are specified in the form (component_name, element_name)\n in the list ignored_jjs.\n\n The final parameter, box_plus_buffer, determines how the chip is drawn.\n When set to True, it takes the minimum rectangular bounding box of all\n rendered components and adds a buffer of x_buffer_width_mm and\n y_buffer_width_mm horizontally and vertically, respectively, to the\n chip size. The center of the chip lies at the midpoint x/y coordinates\n of the minimum rectangular bounding box and may change depending on\n which components are rendered and how they're positioned. If\n box_plus_buffer is False, however, the chip position and dimensions\n are taken from the chip info dictionary found in self.design,\n irrespective of what's being rendered. While this latter option is\n faster because it doesn't require calculating a bounding box, it runs\n the risk of rendered components being too close to the edge of the chip\n or even falling outside its boundaries.\n\n Args:\n selection (Union[list, None], optional): List of components to\n render. Defaults to None.\n open_pins (Union[list, None], optional): List of tuples of pins\n that are open. Defaults to None.\n port_list (Union[list, None], optional): List of tuples of pins to\n be rendered as ports. Defaults to None.\n jj_to_port (Union[list, None], optional): List of tuples of jj's to\n be rendered as ports. Defaults to None.\n ignored_jjs (Union[list, None], optional): List of tuples of jj's\n that shouldn't be rendered.\n Defaults to None.\n box_plus_buffer (bool): Either calculate a bounding box based on\n the location of rendered geometries\n or use chip size from design class.\n \"\"\"\n self.qcomp_ids, self.case = self.get_unique_component_ids(selection)\n\n if self.case == 2:\n self.logger.warning(\n 'Unable to proceed with rendering. Please check selection.')\n return\n\n self.chip_subtract_dict = defaultdict(set)\n self.assign_perfE = []\n self.assign_mesh = []\n self.jj_lumped_ports = {}\n self.jj_to_ignore = set()\n\n if jj_to_port:\n self.jj_lumped_ports = {\n (qcomp, elt): [impedance, draw_ind]\n for qcomp, elt, impedance, draw_ind in jj_to_port\n }\n\n if ignored_jjs:\n self.jj_to_ignore = {(qcomp, qelt) for qcomp, qelt in ignored_jjs}\n\n self.render_tables()\n if port_list:\n self.add_endcaps(open_pins +\n [(qcomp, pin) for qcomp, pin, _ in port_list])\n else:\n self.add_endcaps(open_pins)\n\n self.render_chips(box_plus_buffer=box_plus_buffer)\n self.subtract_from_ground()\n self.add_mesh()\n self.metallize()\n if port_list:\n self.create_ports(port_list)\n\n def create_ports(self, port_list: list):\n \"\"\"Add ports and their respective impedances in Ohms to designated pins\n in port_list. Port_list is formatted as [(qcomp_0, pin_0, impedance_0),\n (qcomp_1, pin_1, impedance_1), ...].\n\n Args:\n port_list (list): List of tuples of pins to be rendered as ports.\n \"\"\"\n for qcomp, pin, impedance in port_list:\n port_name = f'Port_{qcomp}_{pin}'\n pdict = self.design.components[qcomp].pins[pin]\n midpt, gap_size, norm_vec, width = pdict['middle'], pdict['gap'], \\\n pdict['normal'], pdict['width']\n width = parse_units(width)\n endpoints = parse_units([midpt, midpt + gap_size * norm_vec])\n endpoints_3d = to_vec3D(endpoints, 0) # Set z height to 0\n x0, y0 = endpoints_3d[0][:2]\n x1, y1 = endpoints_3d[1][:2]\n if abs(y1 - y0) > abs(x1 - x0):\n # Junction runs vertically up/down\n x_min, x_max = x0 - width / 2, x0 + width / 2\n y_min, y_max = min(y0, y1), max(y0, y1)\n else:\n # Junction runs horizontally left/right\n x_min, x_max = min(x0, x1), max(x0, x1)\n y_min, y_max = y0 - width / 2, y0 + width / 2\n\n # Draw rectangle\n self.logger.debug(f'Drawing a rectangle: {port_name}')\n poly_ansys = self.modeler.draw_rect_corner([x_min, y_min, 0],\n x_max - x_min,\n y_max - y_min, 0,\n **dict(transparency=0.0))\n axis = 'x' if abs(x1 - x0) > abs(y1 - y0) else 'y'\n poly_ansys.make_lumped_port(axis,\n z0=str(impedance) + 'ohm',\n name=f'LumpPort_{qcomp}_{pin}')\n self.modeler.rename_obj(poly_ansys, port_name)\n\n # Draw line\n lump_line = self.modeler.draw_polyline(\n [endpoints_3d[0], endpoints_3d[1]],\n closed=False,\n **dict(color=(128, 0, 128)))\n lump_line = lump_line.rename(f'voltage_line_{port_name}')\n lump_line.show_direction = True\n\n def render_element_junction(self, qgeom: pd.Series):\n \"\"\"\n Render a Josephson junction depending on the solution type.\n\n If in HFSS eigenmode, junctions are rendered as inductors consisting of\n 1. A rectangle of length pad_gap and width inductor_width. Defines lumped element RLC\n boundary condition.\n 2. A line that is later used to calculate the voltage in post-processing analysis.\n\n If in HFSS driven modal, junctions can be inductors, lumped ports, both inductors\n and lumped ports, or omitted altogether. Ports are characterized by an impedance\n value given in the list jj_to_port when render_design() is called.\n\n Args:\n qgeom (pd.Series): GeoSeries of element properties.\n \"\"\"\n qcomp = self.design._components[qgeom['component']].name\n qc_elt = get_clean_name(qgeom['name'])\n\n if (qcomp, qc_elt) not in self.jj_to_ignore:\n qc_shapely = qgeom.geometry\n qc_chip_z = parse_units(self.design.get_chip_z(qgeom.chip))\n qc_width = parse_units(qgeom.width)\n\n endpoints = parse_units(list(qc_shapely.coords))\n endpoints_3d = to_vec3D(endpoints, qc_chip_z)\n x0, y0, z0 = endpoints_3d[0]\n x1, y1, z0 = endpoints_3d[1]\n if abs(y1 - y0) > abs(x1 - x0):\n # Junction runs vertically up/down\n axis = 'y'\n x_min, x_max = x0 - qc_width / 2, x0 + qc_width / 2\n y_min, y_max = min(y0, y1), max(y0, y1)\n else:\n # Junction runs horizontally left/right\n axis = 'x'\n x_min, x_max = min(x0, x1), max(x0, x1)\n y_min, y_max = y0 - qc_width / 2, y0 + qc_width / 2\n\n if (qcomp, qc_elt) in self.jj_lumped_ports:\n if self.jj_lumped_ports[(qcomp, qc_elt)][1]:\n # Draw both port and inductor side by side with small gap in between\n gap = parse_units(self.hfss_options['port_inductor_gap'])\n x_mid, y_mid = (x_min + x_max) / 2, (y_min + y_max) / 2\n if axis == 'x':\n y_mid_hi = y_mid + gap / 2\n y_mid_lo = y_mid - gap / 2\n self.render_junction_port(qgeom, x_min, x_max, y_mid_hi,\n y_max, qc_chip_z, axis)\n self.render_junction_inductor(qgeom, x_min, x_max,\n y_min, y_mid_lo,\n qc_chip_z, axis)\n elif axis == 'y':\n x_mid_lo = x_mid - gap / 2\n x_mid_hi = x_mid + gap / 2\n self.render_junction_port(qgeom, x_mid_hi, x_max, y_min,\n y_max, qc_chip_z, axis)\n self.render_junction_inductor(qgeom, x_min, x_mid_lo,\n y_min, y_max, qc_chip_z,\n axis)\n else:\n # Only draw port\n self.render_junction_port(qgeom, x_min, x_max, y_min, y_max,\n qc_chip_z, axis)\n else:\n # Only draw inductor\n self.render_junction_inductor(qgeom, x_min, x_max, y_min, y_max,\n qc_chip_z, axis)\n\n def render_junction_port(self, qgeom: pd.Series, xmin: float, xmax: float,\n ymin: float, ymax: float, z: float, axis: str):\n \"\"\"Render a junction as a port with a bounding box given by xmin/xmax\n and ymin/ymax, a height z, and a horizontal or vertical axis.\n\n Args:\n qgeom (pd.Series): GeoSeries of element properties.\n xmin (float): Smallest x coordinate\n xmax (float): Largest x coordinate\n ymin (float): Smallest y coordinate\n ymax (float): Largest y coordinate\n z (float): z coordinate\n axis (str): Orientation, either 'x' or 'y'\n \"\"\"\n ansys_options = dict(transparency=0.0)\n qcomp = self.design._components[qgeom['component']].name\n qc_elt = get_clean_name(qgeom['name'])\n port_name = f'Port_{qcomp}_{qc_elt}'\n impedance = self.jj_lumped_ports[(qcomp, qc_elt)][0]\n # Draw rectangle for lumped port.\n self.logger.debug(f'Drawing a rectangle: {port_name}')\n poly_ansys = self.modeler.draw_rect_corner([xmin, ymin, z], xmax - xmin,\n ymax - ymin, z,\n **ansys_options)\n poly_ansys.make_lumped_port(axis,\n z0=str(impedance) + 'ohm',\n name=f'LumpPort_{qcomp}_{qc_elt}')\n self.modeler.rename_obj(poly_ansys, port_name)\n # Draw line for lumped port.\n if axis == 'x':\n ymid = (ymin + ymax) / 2\n start, end = [xmin, ymid, z], [xmax, ymid, z]\n elif axis == 'y':\n xmid = (xmin + xmax) / 2\n start, end = [xmid, ymin, z], [xmid, ymax, z]\n lump_line = self.modeler.draw_polyline([start, end],\n closed=False,\n **dict(color=(128, 0, 128)))\n lump_line = lump_line.rename(f'voltage_line_{port_name}')\n lump_line.show_direction = True\n\n def render_junction_inductor(self, qgeom: pd.Series, xmin: float,\n xmax: float, ymin: float, ymax: float,\n z: float, axis: str):\n \"\"\"Render a junction as an inductor with a bounding box given by\n xmin/xmax and ymin/ymax, a height z, and a horizontal or vertical axis.\n\n Args:\n qgeom (pd.Series): GeoSeries of element properties.\n xmin (float): Smallest x coordinate\n xmax (float): Largest x coordinate\n ymin (float): Smallest y coordinate\n ymax (float): Largest y coordinate\n z (float): z coordinate\n axis (str): Orientation, either 'x' or 'y'\n \"\"\"\n ansys_options = dict(transparency=0.0)\n qcomp = self.design._components[qgeom['component']].name\n qc_elt = get_clean_name(qgeom['name'])\n qc_name = 'Lj_' + qcomp\n inductor_name = f'{qc_name}{QAnsysRenderer.NAME_DELIM}{qc_elt}'\n # Draw rectangle for inductor.\n self.logger.debug(f'Drawing a rectangle: {inductor_name}')\n poly_ansys = self.modeler.draw_rect_corner([xmin, ymin, z], xmax - xmin,\n ymax - ymin, z,\n **ansys_options)\n poly_ansys.make_rlc_boundary(axis,\n l=qgeom['hfss_inductance'],\n c=qgeom['hfss_capacitance'],\n r=qgeom['hfss_resistance'],\n name='Lj_' + inductor_name)\n self.modeler.rename_obj(poly_ansys, 'JJ_rect_' + inductor_name)\n self.assign_mesh.append('JJ_rect_' + inductor_name)\n # Draw line for inductor.\n if axis == 'x':\n ymid = (ymin + ymax) / 2\n start, end = [xmin, ymid, z], [xmax, ymid, z]\n elif axis == 'y':\n xmid = (xmin + xmax) / 2\n start, end = [xmid, ymin, z], [xmid, ymax, z]\n induc_line = self.modeler.draw_polyline([start, end],\n closed=False,\n **dict(color=(128, 0, 128)))\n induc_line = induc_line.rename('JJ_' + inductor_name + '_')\n induc_line.show_direction = True\n\n def metallize(self):\n \"\"\"Assign metallic property to all shapes in self.assign_perfE list.\"\"\"\n self.modeler.assign_perfect_E(self.assign_perfE)\n\n def add_drivenmodal_design(self, name: str, connect: bool = True):\n \"\"\"Add a driven modal design with the given name to the project.\n\n Args:\n name (str): Name of the new driven modal design\n connect (bool, optional): Should we connect this session to this design? Defaults to True\n \"\"\"\n if self.pinfo:\n adesign = self.pinfo.project.new_dm_design(name)\n if connect:\n self.connect_ansys_design(adesign.name)\n return adesign\n else:\n self.logger.info(\"Are you mad?? You have to connect to ansys and a project \" \\\n \"first before creating a new design . Use self.connect_ansys()\")\n\n def activate_drivenmodal_design(self, name: str = \"MetalHFSSDrivenModal\"):\n \"\"\"Add a hfss drivenmodal design with the given name to the project.\n If the design exists, that will be added WITHOUT altering the suffix of\n the design name.\n\n Args:\n name (str): Name of the new q3d design\n\n \"\"\"\n if self.pinfo:\n if self.pinfo.project:\n try:\n names_in_design = self.pinfo.project.get_design_names()\n except AttributeError:\n self.logger.error(\n 'Please install a more recent version of pyEPR (>=0.8.4.5)'\n )\n\n if name in names_in_design:\n self.pinfo.connect_design(name)\n oDesktop = self.pinfo.design.parent.parent._desktop # self.pinfo.design does not work\n oProject = oDesktop.SetActiveProject(\n self.pinfo.project_name)\n oDesign = oProject.SetActiveDesign(name)\n else:\n self.logger.warning(\n f'The name={name} was not in active project. '\n 'A new design will be inserted to the project. '\n f'Names in active project are: \\n{names_in_design}. ')\n adesign = self.add_drivenmodal_design(name=name,\n connect=True)\n\n else:\n self.logger.warning(\n \"Project not available, have you opened a project?\")\n else:\n self.logger.warning(\n \"Have you run connect_ansys()? Cannot find a reference to Ansys in QRenderer.\"\n )\n\n def activate_drivenmodal_setup(self, setup_name_activate: str = None):\n \"\"\"For active design, either get existing setup, make new setup with\n name, or make new setup with default name.\n\n Args:\n setup_name_activate (str, optional): If name exists for setup, then have pinfo\n reference it. If name for setup does not exist, create a new setup with the name.\n If name is None, create a new setup with default name.\n \"\"\"\n if self.pinfo:\n if self.pinfo.project:\n if self.pinfo.design:\n # look for setup name, if not there, then add a new one\n if setup_name_activate:\n all_setup_names = self.pinfo.design.get_setup_names()\n self.pinfo.setup_name = setup_name_activate\n if setup_name_activate in all_setup_names:\n # When name is given and in design. So have pinfo reference existing setup.\n self.pinfo.setup = self.pinfo.get_setup(\n self.pinfo.setup_name)\n else:\n # When name is given, but not in design. So make a new setup with given name.\n self.pinfo.setup = self.add_drivenmodal_setup(\n name=self.pinfo.setup_name)\n else:\n # When name is not given, so use default name for setup.\n # default name is \"Setup\"\n self.pinfo.setup = self.add_drivenmodal_setup()\n self.pinfo.setup_name = self.pinfo.setup.name\n\n else:\n self.logger.warning(\n \" The design within a project is not available, have you opened a design?\"\n )\n else:\n self.logger.warning(\n \"Project not available, have you opened a project?\")\n else:\n self.logger.warning(\n \"Have you run connect_ansys()? Cannot find a reference to Ansys in QRenderer.\"\n )\n\n def add_drivenmodal_setup(self,\n freq_ghz: int = None,\n name: str = None,\n max_delta_s: float = None,\n max_passes: int = None,\n min_passes: int = None,\n min_converged: int = None,\n pct_refinement: int = None,\n basis_order: int = None):\n \"\"\"Create a solution setup in Ansys HFSS Driven Modal. If user does\n not provide arguments, they will be obtained from hfss_options dict.\n\n Args:\n freq_ghz (float, optional): Frequency in GHz. Defaults to 5.\n name (str, optional): Name of driven modal setup. Defaults to \"Setup\".\n max_delta_s (float, optional): Absolute value of maximum\n difference in scattering parameter S. Defaults to 0.1.\n max_passes (int, optional): Maximum number of passes. Defaults to 10.\n min_passes (int, optional): Minimum number of passes. Defaults to 1.\n min_converged (int, optional): Minimum number of converged passes.\n Defaults to 1.\n pct_refinement (int, optional): Percent refinement. Defaults to 30.\n basis_order (int, optional): Basis order. Defaults to 1.\n \"\"\"\n dsu = self.hfss_options.drivenmodal_setup #driven_modal set up.\n\n if not freq_ghz:\n freq_ghz = float(self.parse_value(dsu['freq_ghz']))\n if not name:\n name = self.parse_value(dsu['name'])\n if not max_delta_s:\n max_delta_s = float(self.parse_value(dsu['max_delta_s']))\n if not max_passes:\n max_passes = int(self.parse_value(dsu['max_passes']))\n if not min_passes:\n min_passes = int(self.parse_value(dsu['min_passes']))\n if not min_converged:\n min_converged = int(self.parse_value(dsu['min_converged']))\n if not pct_refinement:\n pct_refinement = int(self.parse_value(dsu['pct_refinement']))\n if not basis_order:\n basis_order = int(self.parse_value(dsu['basis_order']))\n\n if self.pinfo:\n if self.pinfo.design:\n return self.pinfo.design.create_dm_setup(\n freq_ghz=freq_ghz,\n name=name,\n max_delta_s=max_delta_s,\n max_passes=max_passes,\n min_passes=min_passes,\n min_converged=min_converged,\n pct_refinement=pct_refinement,\n basis_order=basis_order)\n\n def add_eigenmode_design(self, name: str, connect: bool = True):\n \"\"\"Add an eigenmode design with the given name to the project.\n\n Args:\n name (str): Name of the new eigenmode design\n connect (bool, optional): Should we connect this session to this design? Defaults to True\n\n Returns(pyEPR.ansys.HfssDesign): A eigenmode within Ansys.\n \"\"\"\n if self.pinfo:\n adesign = self.pinfo.project.new_em_design(name)\n if connect:\n self.connect_ansys_design(adesign.name)\n return adesign\n else:\n self.logger.info(\"Are you mad?? You have to connect to ansys and a project \" \\\n \"first before creating a new design . Use self.connect_ansys()\")\n\n def activate_eigenmode_design(self, name: str = \"MetalHFSSEigenmode\"):\n \"\"\"Add a hfss eigenmode design with the given name to the project. If\n the design exists, that will be added WITHOUT altering the suffix of\n the design name.\n\n Args:\n name (str): Name of the new q3d design\n \"\"\"\n if self.pinfo:\n if self.pinfo.project:\n try:\n names_in_design = self.pinfo.project.get_design_names()\n except AttributeError:\n self.logger.error(\n 'Please install a more recent version of pyEPR (>=0.8.4.5)'\n )\n\n if name in names_in_design:\n self.pinfo.connect_design(name)\n oDesktop = self.pinfo.design.parent.parent._desktop # self.pinfo.design does not work\n oProject = oDesktop.SetActiveProject(\n self.pinfo.project_name)\n oDesign = oProject.SetActiveDesign(name)\n else:\n self.logger.warning(\n f'The name={name} was not in active project. '\n 'A new design will be inserted to the project. '\n f'Names in active project are: \\n{names_in_design}. ')\n adesign = self.add_eigenmode_design(name=name, connect=True)\n\n else:\n self.logger.warning(\n \"Project not available, have you opened a project?\")\n else:\n self.logger.warning(\n \"Have you run connect_ansys()? Cannot find a reference to Ansys in QRenderer.\"\n )\n\n def activate_eigenmode_setup(self, setup_name_activate: str = None):\n \"\"\"For active design, either get existing setup, make new setup with\n name, or make new setup with default name.\n\n Args:\n setup_name_activate (str, optional): If name exists for setup, then have pinfo\n reference it. If name for setup does not exist, create a new setup with the\n name. If name is None, create a new setup with default name.\n \"\"\"\n if self.pinfo:\n if self.pinfo.project:\n if self.pinfo.design:\n # look for setup name, if not there, then add a new one\n if setup_name_activate:\n all_setup_names = self.pinfo.design.get_setup_names()\n self.pinfo.setup_name = setup_name_activate\n if setup_name_activate in all_setup_names:\n # When name is given and in design.\n # So have pinfo reference existing setup.\n self.pinfo.setup = self.pinfo.get_setup(\n self.pinfo.setup_name)\n else:\n # When name is given, but not in design.\n # So make a new setup with given name.\n self.pinfo.setup = self.add_eigenmode_setup(\n name=self.pinfo.setup_name)\n else:\n # When name is not given, so use default name for setup.\n # default name is \"Setup\"\n self.pinfo.setup = self.add_eigenmode_setup()\n self.pinfo.setup_name = self.pinfo.setup.name\n\n else:\n self.logger.warning(\n \" The design within a project is not available, have you opened a design?\"\n )\n else:\n self.logger.warning(\n \"Project not available, have you opened a project?\")\n else:\n self.logger.warning(\n \"Have you run connect_ansys()? Cannot find a reference to Ansys in QRenderer.\"\n )\n\n def add_eigenmode_setup(self,\n name: str = None,\n min_freq_ghz: int = None,\n n_modes: int = None,\n max_delta_f: float = None,\n max_passes: int = None,\n min_passes: int = None,\n min_converged: int = None,\n pct_refinement: int = None,\n basis_order: int = None):\n \"\"\"Create a solution setup in Ansys HFSS Eigenmode. If user does not\n provide arguments, they will be obtained from hfss_options dict.\n\n Args:\n name (str, optional): Name of eigenmode setup. Defaults to \"Setup\".\n min_freq_ghz (int, optional): Minimum frequency in GHz. Defaults to 1.\n n_modes (int, optional): Number of modes. Defaults to 1.\n max_delta_f (float, optional): Maximum difference in freq between consecutive passes. Defaults to 0.5.\n max_passes (int, optional): Maximum number of passes. Defaults to 10.\n min_passes (int, optional): Minimum number of passes. Defaults to 1.\n min_converged (int, optional): Minimum number of converged passes. Defaults to 1.\n pct_refinement (int, optional): Percent refinement. Defaults to 30.\n basis_order (int, optional): Basis order. Defaults to -1.\n \"\"\"\n esu = self.hfss_options.eigenmode_setup\n\n if not name:\n name = self.parse_value(esu['name'])\n if not min_freq_ghz:\n min_freq_ghz = int(self.parse_value(esu['min_freq_ghz']))\n if not n_modes:\n n_modes = int(self.parse_value(esu['n_modes']))\n if not max_delta_f:\n max_delta_f = float(self.parse_value(esu['max_delta_f']))\n if not max_passes:\n max_passes = int(self.parse_value(esu['max_passes']))\n if not min_passes:\n min_passes = int(self.parse_value(esu['min_passes']))\n if not min_converged:\n min_converged = int(self.parse_value(esu['min_converged']))\n if not pct_refinement:\n pct_refinement = int(self.parse_value(esu['pct_refinement']))\n if not basis_order:\n basis_order = int(self.parse_value(esu['basis_order']))\n\n if self.pinfo:\n if self.pinfo.design:\n return self.pinfo.design.create_em_setup(\n name=name,\n min_freq_ghz=min_freq_ghz,\n n_modes=n_modes,\n max_delta_f=max_delta_f,\n max_passes=max_passes,\n min_passes=min_passes,\n min_converged=min_converged,\n pct_refinement=pct_refinement,\n basis_order=basis_order)\n\n def edit_eigenmode_setup(self, setup_args: Dict):\n \"\"\"User can pass key/values to edit the setup for active eigenmode setup.\n\n Args:\n setup_args (Dict): a Dict with possible keys/values.\n\n **setup_args** dict contents:\n * name (str, optional): Name of eigenmode setup. Defaults to \"Setup\".\n * min_freq_ghz (int, optional): Minimum frequency in GHz. Defaults to 1.\n * n_modes (int, optional): Number of modes. Defaults to 1.\n * max_delta_f (float, optional): Maximum difference in freq between consecutive passes. Defaults to 0.5.\n * max_passes (int, optional): Maximum number of passes. Defaults to 10.\n * pct_refinement (int, optional): Percent refinement. Defaults to 30.\n * basis_order (int, optional): Basis order. Defaults to -1.\n\n Note, that these two are currently NOT implemented:\n Ansys API named EditSetup not documented for HFSS, and\n self.pinfo.setup does not have all the property variables used for Setup.\n * min_passes (int, optional): Minimum number of passes. Defaults to 1.\n * min_converged (int, optional): Minimum number of converged passes. Defaults to 1.\n \"\"\"\n\n if self.pinfo:\n if self.pinfo.project:\n if self.pinfo.design:\n if self.pinfo.design.solution_type == 'Eigenmode':\n if self.pinfo.setup_name != setup_args.name:\n self.design.logger.warning(\n f'The name of active setup={self.pinfo.setup_name} does not match'\n f'the name of of setup_args.name={setup_args.name}. '\n f'To use this method, activate the desired Setup before editing it. The '\n f'setup_args was not used to update the active Setup.'\n )\n return\n\n for key, value in setup_args.items():\n if key == \"name\":\n continue #Checked for above.\n if key == \"n_modes\":\n #EditSetup not documented, this is just attempt to use.\n #args_editsetup = [\"NAME:\" + setup_args.name,[\"NumModes:=\", setup_args.n_modes]]\n #self.pinfo.setup._setup_module.EditSetup([setup_args.name, args_editsetup])\n if value < 0 or value > 20 or not isinstance(\n value, int):\n self.logger.warning(\n f'Value of n_modes={value} must be integer from 1 to 20.'\n )\n else:\n self.pinfo.setup.n_modes = value\n continue\n if key == \"min_freq_ghz\":\n if not isinstance(value, int):\n self.logger.warning(\n 'The value for min_freq_ghz should be an int. '\n f'The present value is {value}.')\n else:\n self.pinfo.setup.min_freq = f'{value}GHz'\n continue\n if key == 'max_delta_f':\n if not isinstance(value, float):\n self.logger.warning(\n 'The value for max_delta_f should be float. '\n f'The present value is {value}.')\n else:\n self.pinfo.setup.delta_f = value\n continue\n if key == 'max_passes':\n if not isinstance(value, int):\n self.logger.warning(\n 'The value for max_passes should be an int. '\n f'The present value is {value}.')\n else:\n self.pinfo.setup.passes = value\n continue\n if key == 'pct_refinement':\n if not isinstance(value, int):\n self.logger.warning(\n 'The value for pct_refinement should be an int. '\n f'The present value is {value}.')\n else:\n self.pinfo.setup.pct_refinement = value\n continue\n if key == 'basis_order':\n if not isinstance(value, int):\n self.logger.warning(\n 'The value for basis_order should be an int. '\n f'The present value is {value}.')\n else:\n self.pinfo.setup.basis_order = value\n continue\n\n self.design.logger.warning(\n f'In setup_args, key={key}, value={value} is not in pinfo.setup, '\n 'the key/value pair from setup_args not added to Setup in Ansys.'\n )\n\n else:\n self.logger.warning(\n 'The design does not have solution type as \"Eigenmode\". The Setup not updated.'\n )\n else:\n self.logger.warning(\n 'A design is not in active project. The Setup not updated.'\n )\n else:\n self.logger.warning(\n \"Project not available, have you opened a project? Setup not updated.\"\n )\n else:\n self.logger.warning(\n \"Have you run connect_ansys()? \"\n \"Cannot find a reference to Ansys in QRenderer. Setup not updated. \"\n )\n\n def edit_drivenmodal_setup(self, setup_args: Dict):\n \"\"\"User can pass key/values to edit the setup for active driven modal setup.\n\n Args:\n setup_args (Dict): a Dict with possible keys/values.\n\n **setup_args** dict contents:\n * name (str, optional): Name of eigenmode setup. Defaults to \"Setup\".\n * freq_ghz (int, optional): Minimum frequency in GHz. Defaults to 1.\n * max_passes (int, optional): Maximum number of passes. Defaults to 10.\n * pct_refinement (int, optional): Percent refinement. Defaults to 30.\n * basis_order (int, optional): Basis order. Defaults to -1 (1 is \"Mixed Order\").\n\n Note, that these three are currently NOT implemented:\n Ansys API named EditSetup not documented for HFSS, and\n self.pinfo.setup does not have all the property variables used for Setup.\n * max_delta_s (float, optional): Absolute value of maximum difference in scattering parameter S. Defaults to 0.1.\n * min_passes (int, optional): Minimum number of passes. Defaults to 1.\n * min_converged (int, optional): Minimum number of converged passes. Defaults to 1.\n \"\"\"\n\n if self.pinfo:\n if self.pinfo.project:\n if self.pinfo.design:\n if self.pinfo.design.solution_type == 'DrivenModal':\n if self.pinfo.setup_name != setup_args.name:\n self.design.logger.warning(\n f'The name of active setup={self.pinfo.setup_name} does not match'\n f'the name of of setup_args.name={setup_args.name}. '\n f'To use this method, activate the desired Setup before editing it. The '\n f'setup_args was not used to update the active Setup.'\n )\n return\n\n for key, value in setup_args.items():\n if key == \"name\":\n continue #Checked for above.\n if key == \"freq_ghz\":\n if not isinstance(value, float):\n self.logger.warning(\n 'The value for freq_ghz should be an float. '\n f'The present value is {value}.')\n else:\n self.pinfo.setup.solution_freq = f'{value}GHz'\n continue\n if key == 'max_passes':\n if not isinstance(value, int):\n self.logger.warning(\n 'The value for passes should be an int. '\n f'The present value is {value}.')\n else:\n self.pinfo.setup.passes = value\n continue\n if key == 'pct_refinement':\n if not isinstance(value, int):\n self.logger.warning(\n 'The value for pct_refinement should be an int. '\n f'The present value is {value}.')\n else:\n self.pinfo.setup.pct_refinement = value\n continue\n if key == 'basis_order':\n if not isinstance(value, int):\n self.logger.warning(\n 'The value for basis_order should be an int. '\n f'The present value is {value}.')\n else:\n self.pinfo.setup.basis_order = value\n continue\n\n self.design.logger.warning(\n f'In setup_args, key={key}, value={value} is not in pinfo.setup, '\n 'the key/value pair from setup_args not added to Setup in Ansys.'\n )\n\n else:\n self.logger.warning(\n 'The design does not have solution type as \"Driven Modal\". The Setup not updated.'\n )\n else:\n self.logger.warning(\n 'A design is not in active project. The Setup not updated.'\n )\n else:\n self.logger.warning(\n \"Project not available, have you opened a project? Setup not updated.\"\n )\n else:\n self.logger.warning(\n \"Have you run connect_ansys()? \"\n \"Cannot find a reference to Ansys in QRenderer. Setup not updated. \"\n )\n\n def set_mode(self, mode: int, setup_name: str):\n \"\"\"Set the eigenmode in pyEPR for a design with solution_type set to\n Eigenmode.\n\n Args:\n mode (int): Identify a mode from 1 to n_modes.\n setup_name (str): Select a setup from the active design.\n \"\"\"\n if self.pinfo:\n if self.pinfo.project:\n if self.pinfo.design:\n # self.pinfo.design does not work\n oDesktop = self.pinfo.design.parent.parent._desktop\n oProject = oDesktop.SetActiveProject(\n self.pinfo.project_name)\n oDesign = oProject.GetActiveDesign()\n if oDesign.GetSolutionType() == 'Eigenmode':\n # The set_mode() method is in HfssEMDesignSolutions\n # class in pyEPR.\n # The class HfssEMDesignSolutions is instantiated by\n # get_setup() and create_em_setup().\n setup = self.pinfo.get_setup(setup_name)\n if 0 < int(mode) <= int(setup.n_modes):\n setup_solutions = setup.get_solutions()\n if setup_solutions:\n setup_solutions.set_mode(mode)\n else:\n self.logger.warning(\n 'Not able to get setup_solutions, '\n 'the mode was not set.')\n else:\n self.logger.warning(\n f'The requested mode={mode} is not a valid '\n f'(1 to {setup.n_modes}) selection. '\n 'The mode was not set.')\n else:\n self.logger.warning(\n 'The design does not have solution type as '\n '\"Eigenmode\". The mode was not set.')\n else:\n self.logger.warning('A design is not in active project. '\n 'The mode was not set.')\n else:\n self.logger.warning(\n \"Project not available, have you opened a project? \"\n \"The mode was not set.\")\n else:\n self.logger.warning(\n \"Have you run connect_ansys()? \"\n \"Cannot find a reference to Ansys in QRenderer. \"\n \"The mode was not set.\")\n\n def analyze_setup(self, setup_name: str):\n \"\"\"Run a specific solution setup in Ansys HFSS.\n\n Args:\n setup_name (str): Name of setup.\n \"\"\"\n if self.pinfo:\n setup = self.pinfo.get_setup(setup_name)\n setup.analyze()\n\n def add_sweep(self,\n setup_name=\"Setup\",\n start_ghz=2.0,\n stop_ghz=8.0,\n count=101,\n step_ghz=None,\n name=\"Sweep\",\n type=\"Fast\",\n save_fields=False):\n \"\"\"Add a frequency sweep to a driven modal setup.\n\n Args:\n setup_name (str, optional): Name of driven modal simulation setup.\n Defaults to \"Setup\".\n start_ghz (float, optional): Starting frequency of sweep in GHz.\n Defaults to 2.0.\n stop_ghz (float, optional): Ending frequency of sweep in GHz.\n Defaults to 8.0.\n count (int, optional): Total number of frequencies.\n Defaults to 101.\n step_ghz (float, optional): Difference between adjacent\n frequencies. Defaults to None.\n name (str, optional): Name of sweep. Defaults to \"Sweep\".\n type (str, optional): Type of sweep. Defaults to \"Fast\".\n save_fields (bool, optional): Whether or not to save fields.\n Defaults to False.\n \"\"\"\n if self.pinfo:\n setup = self.pinfo.get_setup(setup_name)\n return setup.insert_sweep(start_ghz=start_ghz,\n stop_ghz=stop_ghz,\n count=count,\n step_ghz=step_ghz,\n name=name,\n type=type,\n save_fields=save_fields)\n\n def analyze_sweep(self, sweep_name: str, setup_name: str):\n \"\"\"Analyze a single sweep within the setup.\n\n Args:\n sweep_name (str): Name of sweep to analyze.\n setup_name (str): Name of setup to analyze.\n \"\"\"\n if self.pinfo:\n setup = self.pinfo.get_setup(setup_name)\n sweep = setup.get_sweep(sweep_name)\n sweep.analyze_sweep()\n self.current_sweep = sweep\n\n def get_params(self, param_name: Union[list, None] = None):\n \"\"\"Get one or more parameters (S, Y, or Z) as a function of frequency.\n\n Args:\n param_name (Union[list, None], optional): Parameters to obtain. Defaults to None.\n \"\"\"\n if self.current_sweep:\n\n freqs, Pcurves = self.current_sweep.get_network_data(param_name)\n Pparams = pd.DataFrame(Pcurves,\n columns=freqs / 1e9,\n index=param_name).transpose()\n return freqs, Pcurves, Pparams\n\n # yapf: disable\n def get_all_Pparms_matrices(self, matrix_size: int) -> Tuple[\n Union[pd.core.frame.DataFrame, None],\n Union[pd.core.frame.DataFrame, None],\n Union[pd.core.frame.DataFrame, None]]:\n #yapf: enable\n '''\n S = scattering matrix, Y = Admittance, Z= impedance.\n\n matrix_size should be 1 or larger.\n This method will get the entire Scattering matrix based on matrix_size.\n\n Example:'S21'\n S matrix: SAB means, excite B, measure A\n '''\n s_param_name = []\n y_param_name = []\n z_param_name = []\n if matrix_size < 1:\n return None, None, None\n for excite in range(1, matrix_size + 1):\n for measure in range(1, matrix_size + 1):\n s_param_name.append(f'S{measure}{excite}')\n y_param_name.append(f'Y{measure}{excite}')\n z_param_name.append(f'Z{measure}{excite}')\n dummy_freqs, dummy_Pcurves, S_Pparams = self.get_params(s_param_name)\n dummy_freqs, dummy_Pcurves, Y_Pparams = self.get_params(y_param_name)\n dummy_freqs, dummy_Pcurves, Z_Pparams = self.get_params(z_param_name)\n\n return S_Pparams, Y_Pparams, Z_Pparams\n\n def plot_params(self, param_name: Union[list, None] = None):\n \"\"\"Plot one or more parameters (S, Y, or Z) as a function of frequency.\n S = scattering matrix, Y = Admittance, Z= impedance.\n\n Args:\n param_name (Union[list, None], optional): Parameters to plot. Defaults to None.\n \"\"\"\n freqs, Pcurves, Pparams = self.get_params(param_name)\n if Pparams is not None:\n fig, axs = plt.subplots(1, 2, figsize=(10, 6))\n Pparams.apply(lambda x: 20 * np.log10(np.abs(x))).plot(ax=axs[0])\n Pparams.apply(lambda x: np.angle(x)).plot(ax=axs[1])\n for ax in axs:\n ax.autoscale()\n return Pparams, fig\n\n def distributed_analysis(self):\n \"\"\"Returns class containing info on Hamiltonian parameters from HFSS\n simulation.\n\n Returns:\n DistributedAnalysis: A class from pyEPR which does DISTRIBUTED ANALYSIS of layout\n and microwave results. It is the main computation class & interface with HFSS.\n This class defines a DistributedAnalysis object which calculates\n and saves Hamiltonian parameters from an HFSS simulation.\n It allows one to calculate dissipation.\n \"\"\"\n if self.pinfo:\n return epr.DistributedAnalysis(self.pinfo)\n\n def get_convergences(self, variation: str = None):\n \"\"\"Get convergence for convergence_t, convergence_f, and text from GUI for solution data.\n\n Args:\n variation (str, optional): Information from pyEPR; variation should be in the form\n variation = \"scale_factor='1.2001'\". Defaults to None.\n\n Returns:\n tuple[pandas.core.frame.DataFrame, pandas.core.frame.DataFrame, str]:\n 1st DataFrame: Convergence_t\n 2nd DataFrame: Convergence_f\n 3rd str: Text from GUI of solution data.\n \"\"\"\n if self.pinfo:\n design = self.pinfo.design\n setup = self.pinfo.setup\n convergence_t, text = setup.get_convergence(variation)\n convergence_f = hfss_report_f_convergence(\n design, setup, self.logger, []) # TODO; Fix variation []\n return convergence_t, convergence_f, text\n\n def plot_convergences(self,\n variation: str = None,\n fig: mpl.figure.Figure = None):\n \"\"\"Plot the convergences in Ansys window.\n\n Args:\n variation (str, optional): Information from pyEPR; variation should be in the form\n variation = \"scale_factor='1.2001'\". Defaults to None.\n fig (matplotlib.figure.Figure, optional): A mpl figure. Defaults to None.\n \"\"\"\n if self.pinfo:\n convergence_t, convergence_f, _ = self.get_convergences(variation)\n hfss_plot_convergences_report(convergence_t,\n convergence_f,\n fig=fig,\n _display=True)\n\n\ndef hfss_plot_convergences_report(convergence_t: pd.core.frame.DataFrame,\n convergence_f: pd.core.frame.DataFrame,\n fig: mpl.figure.Figure = None,\n _display=True):\n \"\"\"Plot convergence frequency vs. pass number if fig is None. Plot delta\n frequency and solved elements vs. pass number. Plot delta frequency vs.\n solved elements.\n\n Args:\n convergence_t (pandas.core.frame.DataFrame): Convergence vs pass number of the eigenemode freqs.\n convergence_f (pandas.core.frame.DataFrame): Convergence vs pass number of the eigenemode freqs.\n fig (matplotlib.figure.Figure, optional): A mpl figure. Defaults to None.\n _display (bool, optional): Display the plot? Defaults to True.\n \"\"\"\n\n if fig is None:\n fig = plt.figure(figsize=(11, 3.))\n\n # Grid spec and axes; height_ratios=[4, 1], wspace=0.5\n gs = mpl.gridspec.GridSpec(1, 3, width_ratios=[1.2, 1.5, 1])\n axs = [fig.add_subplot(gs[i]) for i in range(3)]\n\n ax0t = axs[1].twinx()\n plot_convergence_f_vspass(axs[0], convergence_f)\n plot_convergence_max_df(axs[1], convergence_t.iloc[:, 1])\n plot_convergence_solved_elem(ax0t, convergence_t.iloc[:, 0])\n plot_convergence_maxdf_vs_sol(axs[2], convergence_t.iloc[:, 1],\n convergence_t.iloc[:, 0])\n\n fig.tight_layout(w_pad=0.1) # pad=0.0, w_pad=0.1, h_pad=1.0)\n\n # if _display:\n # from IPython.display import display\n # display(fig)\n\n\ndef hfss_report_f_convergence(oDesign: epr.ansys.HfssDesign,\n setup: epr.ansys.HfssEMSetup,\n logger: logging.Logger,\n variation: str = None,\n save_csv: bool = True):\n \"\"\"Create a report inside HFSS to plot the converge of frequency and style\n it. Saves report to csv file.\n\n .. code-block:: text\n\n re(Mode(1)) [g] re(Mode(2)) [g] re(Mode(3)) [g]\n Pass []\n 1 4.643101 4.944204 5.586289\n 2 5.114490 5.505828 6.242423\n 3 5.278594 5.604426 6.296777\n\n Args:\n oDesign (pyEPR.ansys.HfssDesign): Active design within Ansys.\n setup (pyEPR.ansys.HfssEMSetup): The setup of active project and design within Ansys.\n logger (logging.Logger): To give feedback to user.\n variation ('str', optional): Information from pyEPR; variation should be in the form\n variation = \"scale_factor='1.2001'\". Defaults to None.\n save_csv (bool, optional): Save to file? Defaults to True.\n\n Returns:\n pd.core.frame.DataFrame: Returns a convergence vs pass number of the eigenemode frequencies.\n \"\"\"\n\n if not oDesign.solution_type == 'Eigenmode':\n return None\n\n report = oDesign._reporter # reporter OModule for Ansys\n\n # Create report\n n_modes = int(setup.n_modes)\n ycomp = [f\"re(Mode({i}))\" for i in range(1, 1 + n_modes)]\n\n params = [\"Pass:=\", [\"All\"]] + variation\n report_name = \"Freq. vs. pass\"\n if report_name in report.GetAllReportNames():\n report.DeleteReports([report_name])\n\n solutions = setup.get_solutions()\n solutions.create_report(report_name,\n \"Pass\",\n ycomp,\n params,\n pass_name='AdaptivePass')\n\n # Properties of lines\n curves = [\n f\"{report_name}:re(Mode({i})):Curve1\" for i in range(1, 1 + n_modes)\n ]\n set_property(report, 'Attributes', curves, 'Line Width', 3)\n set_property(report, 'Scaling', f\"{report_name}:AxisY1\", 'Auto Units',\n False)\n set_property(report, 'Scaling', f\"{report_name}:AxisY1\", 'Units', 'g')\n set_property(report, 'Legend', f\"{report_name}:Legend\",\n 'Show Solution Name', False)\n\n if save_csv: # Save\n try:\n path = Path().absolute(\n ) / 'hfss_eig_f_convergence.csv' # TODO: Determine better path\n report.ExportToFile(report_name, path)\n logger.info(f'Saved convergences to {path}')\n return pd.read_csv(path, index_col=0)\n except Exception as e:\n logger.error(f\"Error could not save and export hfss plot to {path}.\\\n Is the plot made in HFSS with the correct name.\\\n Check the HFSS error window. \\t Error = {e}\")\n\n return None\n" ]
[ [ "pandas.read_csv", "numpy.abs", "matplotlib.pyplot.subplots", "pandas.DataFrame", "matplotlib.gridspec.GridSpec", "numpy.angle", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
mattrogers1124/fibonacci
[ "7606c9aa6c9837b6f5b6e936741241fb80659444" ]
[ "example.py" ]
[ "import matplotlib.pyplot as plt\nfrom fibonacci import unitdisk, unitsphere\n\n# Plot 1000 points on the unit disk\nfig1 = plt.figure()\nax1 = fig1.add_subplot()\nx1, y1 = unitdisk(1000).transpose()\nax1.scatter(x1, y1)\nax1.set_aspect(1)\nax1.set_title(\"Sample of 1,000 points from unit disk\")\n\n# Plot 1000 points on the unit sphere\nfig2 = plt.figure()\nax2 = fig2.add_subplot(projection='3d')\nx2, y2, z2 = unitsphere(1000).transpose()\nax2.scatter(x2, y2, z2)\nax2.set_title(\"Sample of 1,000 points from unit sphere\")\n\n# Show plots\nplt.show()\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Sy-Zhang/recurrent-transformer
[ "f66ba49a2c9ec42759d3d00d497b49ffe39e18de" ]
[ "src/rtransformer/recursive_caption_dataset.py" ]
[ "import copy\nimport torch\nimport logging\nimport math\nimport nltk\nimport numpy as np\nimport os\n\nfrom torch.utils.data import Dataset\nfrom torch.utils.data.dataloader import default_collate\nfrom tqdm import tqdm\n\nfrom src.utils import load_json, flat_list_of_lists\n\nlog_format = \"%(asctime)-10s: %(message)s\"\nlogging.basicConfig(level=logging.INFO, format=log_format)\n\n\nclass RecursiveCaptionDataset(Dataset):\n PAD_TOKEN = \"[PAD]\" # padding of the whole sequence, note\n CLS_TOKEN = \"[CLS]\" # leading token of the joint sequence\n SEP_TOKEN = \"[SEP]\" # a separator for video and text\n VID_TOKEN = \"[VID]\" # used as placeholder in the clip+text joint sequence\n BOS_TOKEN = \"[BOS]\" # beginning of the sentence\n EOS_TOKEN = \"[EOS]\" # ending of the sentence\n UNK_TOKEN = \"[UNK]\"\n PAD = 0\n CLS = 1\n SEP = 2\n VID = 3\n BOS = 4\n EOS = 5\n UNK = 6\n IGNORE = -1 # used to calculate loss\n\n \"\"\"\n recurrent: if True, return recurrent data\n \"\"\"\n def __init__(self, dset_name, data_dir, video_feature_dir, duration_file, word2idx_path,\n max_t_len, max_v_len, max_n_sen, mode=\"train\", recurrent=True, untied=False):\n self.dset_name = dset_name\n self.word2idx = load_json(word2idx_path)\n self.idx2word = {int(v): k for k, v in self.word2idx.items()}\n self.data_dir = data_dir # containing training data\n self.video_feature_dir = video_feature_dir # a set of .h5 files\n self.duration_file = duration_file\n self.frame_to_second = self._load_duration()\n self.max_seq_len = max_v_len + max_t_len\n self.max_v_len = max_v_len\n self.max_t_len = max_t_len # sen\n self.max_n_sen = max_n_sen\n\n self.mode = mode\n self.recurrent = recurrent\n self.untied = untied\n assert not (self.recurrent and self.untied), \"untied and recurrent cannot be True for both\"\n\n # data entries\n self.data = None\n self.set_data_mode(mode=mode)\n self.missing_video_names = []\n self.fix_missing()\n\n self.num_sens = None # number of sentence for each video, set in self._load_data()\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, index):\n items, meta = self.convert_example_to_features(self.data[index])\n return items, meta\n\n def set_data_mode(self, mode):\n \"\"\"mode: `train` or `val`\"\"\"\n logging.info(\"Mode {}\".format(mode))\n self.mode = mode\n if self.dset_name == \"anet\":\n if mode == \"train\": # 10000 videos\n data_path = os.path.join(self.data_dir, \"train.json\")\n elif mode == \"val\": # 2500 videos\n data_path = os.path.join(self.data_dir, \"anet_entities_val_1.json\")\n elif mode == \"test\": # 2500 videos\n data_path = os.path.join(self.data_dir, \"anet_entities_test_1.json\")\n else:\n raise ValueError(\"Expecting mode to be one of [`train`, `val`, `test`], got {}\".format(mode))\n elif self.dset_name == \"yc2\":\n if mode == \"train\": # 10000 videos\n data_path = os.path.join(self.data_dir, \"yc2_train_anet_format.json\")\n elif mode == \"val\": # 2500 videos\n data_path = os.path.join(self.data_dir, \"yc2_val_anet_format.json\")\n else:\n raise ValueError(\"Expecting mode to be one of [`train`, `val`, `test`], got {}\".format(mode))\n else:\n raise ValueError\n self._load_data(data_path)\n\n def fix_missing(self):\n \"\"\"filter our videos with no feature file\"\"\"\n for e in tqdm(self.data):\n video_name = e[\"name\"][2:] if self.dset_name == \"anet\" else e[\"name\"]\n cur_path_resnet = os.path.join(self.video_feature_dir, \"{}_resnet.npy\".format(video_name))\n cur_path_bn = os.path.join(self.video_feature_dir, \"{}_bn.npy\".format(video_name))\n for p in [cur_path_bn, cur_path_resnet]:\n if not os.path.exists(p):\n self.missing_video_names.append(video_name)\n print(\"Missing {} features (clips/sentences) from {} videos\".format(\n len(self.missing_video_names), len(set(self.missing_video_names))))\n print(\"Missing {}\".format(set(self.missing_video_names)))\n if self.dset_name == \"anet\":\n self.data = [e for e in self.data if e[\"name\"][2:] not in self.missing_video_names]\n else:\n self.data = [e for e in self.data if e[\"name\"] not in self.missing_video_names]\n\n def _load_duration(self):\n \"\"\"https://github.com/salesforce/densecap/blob/master/data/anet_dataset.py#L120\n Since the features are extracted not at the exact 0.5 secs. To get the real time for each feature,\n use `(idx + 1) * frame_to_second[vid_name] `\n \"\"\"\n frame_to_second = {}\n sampling_sec = 0.5 # hard coded, only support 0.5\n if self.dset_name == \"anet\":\n with open(self.duration_file, \"r\") as f:\n for line in f:\n vid_name, vid_dur, vid_frame = [l.strip() for l in line.split(\",\")]\n frame_to_second[vid_name] = float(vid_dur) * int(\n float(vid_frame) * 1. / int(float(vid_dur)) * sampling_sec) * 1. / float(vid_frame)\n frame_to_second[\"_0CqozZun3U\"] = sampling_sec # a missing video in anet\n elif self.dset_name == \"yc2\":\n with open(self.duration_file, \"r\") as f:\n for line in f:\n vid_name, vid_dur, vid_frame = [l.strip() for l in line.split(\",\")]\n frame_to_second[vid_name] = float(vid_dur) * math.ceil(\n float(vid_frame) * 1. / float(vid_dur) * sampling_sec) * 1. / float(vid_frame) # for yc2\n else:\n raise NotImplementedError(\"Only support anet and yc2, got {}\".format(self.dset_name))\n return frame_to_second\n\n def _load_data(self, data_path):\n logging.info(\"Loading data from {}\".format(data_path))\n raw_data = load_json(data_path)\n data = []\n for k, line in tqdm(raw_data.items()):\n line[\"name\"] = k\n line[\"timestamps\"] = line[\"timestamps\"][:self.max_n_sen]\n line[\"sentences\"] = line[\"sentences\"][:self.max_n_sen]\n data.append(line)\n\n if self.recurrent: # recurrent\n self.data = data\n else: # non-recurrent single sentence\n singel_sentence_data = []\n for d in sorted(data, key=lambda x: x['name']):\n num_sen = min(self.max_n_sen, len(d[\"sentences\"]))\n singel_sentence_data.extend([\n {\n \"duration\": d[\"duration\"],\n \"name\": d[\"name\"],\n \"timestamp\": d[\"timestamps\"][idx],\n \"sentence\": d[\"sentences\"][idx]\n } for idx in range(num_sen)])\n self.data = singel_sentence_data\n\n logging.info(\"Loading complete! {} examples\".format(len(self)))\n\n def convert_example_to_features(self, example):\n \"\"\"example single snetence\n {\"name\": str,\n \"duration\": float,\n \"timestamp\": [st(float), ed(float)],\n \"sentence\": str\n } or\n {\"name\": str,\n \"duration\": float,\n \"timestamps\": list([st(float), ed(float)]),\n \"sentences\": list(str)\n }\n \"\"\"\n name = example[\"name\"]\n video_name = name[2:] if self.dset_name == \"anet\" else name\n feat_path_resnet = os.path.join(self.video_feature_dir, \"{}_resnet.npy\".format(video_name))\n feat_path_bn = os.path.join(self.video_feature_dir, \"{}_bn.npy\".format(video_name))\n video_feature = np.concatenate([np.load(feat_path_resnet), np.load(feat_path_bn)], axis=1)\n if self.recurrent: # recurrent\n num_sen = len(example[\"sentences\"])\n single_video_features = []\n single_video_meta = []\n for clip_idx in range(num_sen):\n cur_data, cur_meta = self.clip_sentence_to_feature(example[\"name\"],\n example[\"timestamps\"][clip_idx],\n example[\"sentences\"][clip_idx],\n video_feature)\n single_video_features.append(cur_data)\n single_video_meta.append(cur_meta)\n return single_video_features, single_video_meta\n else: # single sentence\n clip_dataloader = self.clip_sentence_to_feature_untied \\\n if self.untied else self.clip_sentence_to_feature\n cur_data, cur_meta = clip_dataloader(example[\"name\"],\n example[\"timestamp\"],\n example[\"sentence\"],\n video_feature)\n return cur_data, cur_meta\n\n def clip_sentence_to_feature(self, name, timestamp, sentence, video_feature):\n \"\"\" make features for a single clip-sentence pair.\n [CLS], [VID], ..., [VID], [SEP], [BOS], [WORD], ..., [WORD], [EOS]\n Args:\n name: str,\n timestamp: [float, float]\n sentence: str\n video_feature: np array\n \"\"\"\n frm2sec = self.frame_to_second[name[2:]] if self.dset_name == \"anet\" else self.frame_to_second[name]\n\n # video + text tokens\n feat, video_tokens, video_mask = self._load_indexed_video_feature(video_feature, timestamp, frm2sec)\n text_tokens, text_mask = self._tokenize_pad_sentence(sentence)\n\n input_tokens = video_tokens + text_tokens\n\n input_ids = [self.word2idx.get(t, self.word2idx[self.UNK_TOKEN]) for t in input_tokens]\n # shifted right, `-1` is ignored when calculating CrossEntropy Loss\n input_labels = \\\n [self.IGNORE] * len(video_tokens) + \\\n [self.IGNORE if m == 0 else tid for tid, m in zip(input_ids[-len(text_mask):], text_mask)][1:] + \\\n [self.IGNORE]\n input_mask = video_mask + text_mask\n token_type_ids = [0] * self.max_v_len + [1] * self.max_t_len\n\n data = dict(\n name=name,\n input_tokens=input_tokens,\n # model inputs\n input_ids=np.array(input_ids).astype(np.int64),\n input_labels=np.array(input_labels).astype(np.int64),\n input_mask=np.array(input_mask).astype(np.float32),\n token_type_ids=np.array(token_type_ids).astype(np.int64),\n video_feature=feat.astype(np.float32)\n )\n meta = dict(\n # meta\n name=name,\n timestamp=timestamp,\n sentence=sentence,\n )\n return data, meta\n\n def clip_sentence_to_feature_untied(self, name, timestamp, sentence, raw_video_feature):\n \"\"\" make features for a single clip-sentence pair.\n [CLS], [VID], ..., [VID], [SEP], [BOS], [WORD], ..., [WORD], [EOS]\n Args:\n name: str,\n timestamp: [float, float]\n sentence: str\n raw_video_feature: np array, N x D, for the whole video\n \"\"\"\n frm2sec = self.frame_to_second[name[2:]] if self.dset_name == \"anet\" else self.frame_to_second[name]\n\n # video + text tokens\n video_feature, video_mask = self._load_indexed_video_feature_untied(raw_video_feature, timestamp, frm2sec)\n text_tokens, text_mask = self._tokenize_pad_sentence(sentence)\n\n text_ids = [self.word2idx.get(t, self.word2idx[self.UNK_TOKEN]) for t in text_tokens]\n # shifted right, `-1` is ignored when calculating CrossEntropy Loss\n text_labels = [self.IGNORE if m == 0 else tid for tid, m in zip(text_ids, text_mask)][1:] + [self.IGNORE]\n\n data = dict(\n name=name,\n text_tokens=text_tokens,\n # model inputs\n text_ids=np.array(text_ids).astype(np.int64),\n text_mask=np.array(text_mask).astype(np.float32),\n text_labels=np.array(text_labels).astype(np.int64),\n video_feature=video_feature.astype(np.float32),\n video_mask=np.array(video_mask).astype(np.float32),\n )\n meta = dict(\n # meta\n name=name,\n timestamp=timestamp,\n sentence=sentence,\n )\n return data, meta\n\n @classmethod\n def _convert_to_feat_index_st_ed(cls, feat_len, timestamp, frm2sec):\n \"\"\"convert wall time st_ed to feature index st_ed\"\"\"\n st = int(math.floor(timestamp[0] / frm2sec))\n ed = int(math.ceil(timestamp[1] / frm2sec))\n ed = min(ed, feat_len-1)\n st = min(st, ed-1)\n assert st <= ed <= feat_len, \"st {} <= ed {} <= feat_len {}\".format(st, ed, feat_len)\n return st, ed\n\n def _load_indexed_video_feature(self, raw_feat, timestamp, frm2sec):\n \"\"\" [CLS], [VID], ..., [VID], [SEP], [PAD], ..., [PAD],\n All non-PAD tokens are valid, will have a mask value of 1.\n Returns:\n feat is padded to length of (self.max_v_len + self.max_t_len,)\n video_tokens: self.max_v_len\n mask: self.max_v_len\n \"\"\"\n max_v_l = self.max_v_len - 2\n feat_len = len(raw_feat)\n st, ed = self._convert_to_feat_index_st_ed(feat_len, timestamp, frm2sec)\n indexed_feat_len = ed - st + 1\n\n feat = np.zeros((self.max_v_len + self.max_t_len, raw_feat.shape[1])) # includes [CLS], [SEP]\n if indexed_feat_len > max_v_l:\n downsamlp_indices = np.linspace(st, ed, max_v_l, endpoint=True).astype(np.int).tolist()\n assert max(downsamlp_indices) < feat_len\n feat[1:max_v_l+1] = raw_feat[downsamlp_indices] # truncate, sample???\n\n video_tokens = [self.CLS_TOKEN] + [self.VID_TOKEN] * max_v_l + [self.SEP_TOKEN]\n mask = [1] * (max_v_l + 2)\n else:\n valid_l = ed - st + 1\n feat[1:valid_l+1] = raw_feat[st:ed + 1]\n video_tokens = [self.CLS_TOKEN] + [self.VID_TOKEN] * valid_l + \\\n [self.SEP_TOKEN] + [self.PAD_TOKEN] * (max_v_l - valid_l)\n mask = [1] * (valid_l + 2) + [0] * (max_v_l - valid_l)\n return feat, video_tokens, mask\n\n def _load_indexed_video_feature_untied(self, raw_feat, timestamp, frm2sec):\n \"\"\" Untied version: [VID], ..., [VID], [PAD], ..., [PAD], len == max_v_len\n Returns:\n feat is padded to length of (self.max_v_len,)\n mask: self.max_v_len, with 1 indicates valid bits, 0 indicates padding\n \"\"\"\n max_v_l = self.max_v_len\n feat_len = len(raw_feat)\n st, ed = self._convert_to_feat_index_st_ed(feat_len, timestamp, frm2sec)\n indexed_feat_len = ed - st + 1\n\n if indexed_feat_len > max_v_l:\n downsamlp_indices = np.linspace(st, ed, max_v_l, endpoint=True).astype(np.int).tolist()\n assert max(downsamlp_indices) < feat_len\n feat = raw_feat[downsamlp_indices] # truncate, sample???\n mask = [1] * max_v_l # no padding\n else:\n feat = np.zeros((max_v_l, raw_feat.shape[1])) # only video features and padding\n valid_l = ed - st + 1\n feat[:valid_l] = raw_feat[st:ed + 1]\n mask = [1] * valid_l + [0] * (max_v_l - valid_l)\n return feat, mask\n\n def _tokenize_pad_sentence(self, sentence):\n \"\"\"[BOS], [WORD1], [WORD2], ..., [WORDN], [EOS], [PAD], ..., [PAD], len == max_t_len\n All non-PAD values are valid, with a mask value of 1\n \"\"\"\n max_t_len = self.max_t_len\n sentence_tokens = nltk.tokenize.word_tokenize(sentence.lower())[:max_t_len - 2]\n sentence_tokens = [self.BOS_TOKEN] + sentence_tokens + [self.EOS_TOKEN]\n\n # pad\n valid_l = len(sentence_tokens)\n mask = [1] * valid_l + [0] * (max_t_len - valid_l)\n sentence_tokens += [self.PAD_TOKEN] * (max_t_len - valid_l)\n return sentence_tokens, mask\n\n def convert_ids_to_sentence(self, ids, rm_padding=True, return_sentence_only=True):\n \"\"\"A list of token ids\"\"\"\n rm_padding = True if return_sentence_only else rm_padding\n if rm_padding:\n raw_words = [self.idx2word[wid] for wid in ids if wid not in [self.PAD, self.IGNORE]]\n else:\n raw_words = [self.idx2word[wid] for wid in ids if wid != self.IGNORE]\n\n # get only sentences, the tokens between `[BOS]` and the first `[EOS]`\n if return_sentence_only:\n words = []\n for w in raw_words[1:]: # no [BOS]\n if w != self.EOS_TOKEN:\n words.append(w)\n else:\n break\n else:\n words = raw_words\n return \" \".join(words)\n\n\ndef prepare_batch_inputs(batch, device, non_blocking=False):\n batch_inputs = dict()\n bsz = len(batch[\"name\"])\n for k, v in batch.items():\n assert bsz == len(v), (bsz, k, v)\n if isinstance(v, torch.Tensor):\n batch_inputs[k] = v.to(device, non_blocking=non_blocking)\n else: # all non-tensor values\n batch_inputs[k] = v\n return batch_inputs\n\n\ndef step_collate(padded_batch_step):\n \"\"\"The same step (clip-sentence pair) from each example\"\"\"\n c_batch = dict()\n for key in padded_batch_step[0]:\n value = padded_batch_step[0][key]\n if isinstance(value, list):\n c_batch[key] = [d[key] for d in padded_batch_step]\n else:\n c_batch[key] = default_collate([d[key] for d in padded_batch_step])\n return c_batch\n\n\ndef caption_collate(batch):\n \"\"\"get rid of unexpected list transpose in default_collate\n https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L66\n\n HOW to batch clip-sentence pair?\n 1) directly copy the last sentence, but do not count them in when back-prop OR\n 2) put all -1 to their text token label, treat\n \"\"\"\n # collect meta\n raw_batch_meta = [e[1] for e in batch]\n batch_meta = []\n for e in raw_batch_meta:\n cur_meta = dict(\n name=None,\n timestamp=[],\n gt_sentence=[]\n )\n for d in e:\n cur_meta[\"name\"] = d[\"name\"]\n cur_meta[\"timestamp\"].append(d[\"timestamp\"])\n cur_meta[\"gt_sentence\"].append(d[\"sentence\"])\n batch_meta.append(cur_meta)\n\n batch = [e[0] for e in batch]\n # Step1: pad each example to max_n_sen\n max_n_sen = max([len(e) for e in batch])\n raw_step_sizes = []\n\n padded_batch = []\n padding_clip_sen_data = copy.deepcopy(batch[0][0]) # doesn\"t matter which one is used\n padding_clip_sen_data[\"input_labels\"][:] = RecursiveCaptionDataset.IGNORE\n for ele in batch:\n cur_n_sen = len(ele)\n if cur_n_sen < max_n_sen:\n ele = ele + [padding_clip_sen_data] * (max_n_sen - cur_n_sen)\n raw_step_sizes.append(cur_n_sen)\n padded_batch.append(ele)\n\n # Step2: batching each steps individually in the batches\n collated_step_batch = []\n for step_idx in range(max_n_sen):\n collated_step = step_collate([e[step_idx] for e in padded_batch])\n collated_step_batch.append(collated_step)\n return collated_step_batch, raw_step_sizes, batch_meta\n\n\ndef single_sentence_collate(batch):\n \"\"\"get rid of unexpected list transpose in default_collate\n https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L66\n \"\"\"\n # collect meta\n batch_meta = [{\"name\": e[1][\"name\"],\n \"timestamp\": e[1][\"timestamp\"],\n \"gt_sentence\": e[1][\"sentence\"]\n } for e in batch] # change key\n padded_batch = step_collate([e[0] for e in batch])\n return padded_batch, None, batch_meta\n" ]
[ [ "numpy.linspace", "numpy.load", "numpy.array", "numpy.zeros", "torch.utils.data.dataloader.default_collate" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rcox771/mapgen
[ "036bf3fd42473a3bca58250ae9a6e1cce698c95d" ]
[ "mapgen/noise.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom itertools import product, count\nfrom matplotlib.colors import LinearSegmentedColormap\nimport noise\nfrom .maths import *\n\n\n\ndef fbm(shape, p, lower=-np.inf, upper=np.inf):\n # Fourier-based power law noise with frequency bounds.\n\n freqs = tuple(np.fft.fftfreq(n, d=1.0 / n) for n in shape)\n freq_radial = np.hypot(*np.meshgrid(*freqs))\n envelope = (np.power(freq_radial, p, where=freq_radial != 0) *\n (freq_radial > lower) * (freq_radial < upper))\n envelope[0][0] = 0.0\n phase_noise = np.exp(2j * np.pi * np.random.rand(*shape))\n return normalize(\n np.real(np.fft.ifft2(np.fft.fft2(phase_noise) * envelope)))\n\n\ndef domain_warp(shape=(1024, 1024), offsets=1200):\n shape = (shape[0], ) * 2\n\n values = fbm(shape, -2, lower=2.0)\n offsets = offsets * (\n fbm(shape, -2, lower=1.5) + 1j * fbm(shape, -2, lower=1.5))\n result = sample(values, offsets)\n return result\n\n\ndef perlin_square(scale=100.0,\n octaves=6,\n persistence=0.5,\n lacunarity=2.0,\n shape=(1024, 1024),\n bounds=(0, 1)):\n world = np.zeros(shape)\n for i in range(shape[0]):\n for j in range(shape[1]):\n world[i][j] = noise.pnoise2(\n i / scale,\n j / scale,\n octaves=octaves,\n persistence=persistence,\n lacunarity=lacunarity,\n repeatx=shape[1],\n repeaty=shape[0],\n base=0)\n return normalize(world, bounds)\n\n\ndef white_noise(mapH: int = 512, mapW: int = 512, scale: float = .0001):\n return np.random.random((mapH, mapW)) * scale\n\n" ]
[ [ "numpy.fft.fft2", "numpy.random.random", "numpy.power", "numpy.random.rand", "numpy.fft.fftfreq", "numpy.meshgrid", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gyf135/Hands-On-GPU-Programming-with-Python-and-CUDA
[ "4fbd14d3a9fbc68305ffaa16490221b1ef49a934" ]
[ "Chapter11/dynamic_hello.py" ]
[ "from __future__ import division\nimport numpy as np\nfrom pycuda.compiler import DynamicSourceModule\nimport pycuda.autoinit\n\nDynamicParallelismCode='''\n__global__ void dynamic_hello_ker(int depth)\n{\n printf(\"Hello from thread %d, recursion depth %d!\\\\n\", threadIdx.x, depth);\n if (threadIdx.x == 0 && blockIdx.x == 0 && blockDim.x > 1)\n {\n printf(\"Launching a new kernel from depth %d .\\\\n\", depth);\n printf(\"-----------------------------------------\\\\n\");\n dynamic_hello_ker<<< 1, blockDim.x - 1 >>>(depth + 1);\n }\n}'''\n\ndp_mod = DynamicSourceModule(DynamicParallelismCode)\n\nhello_ker = dp_mod.get_function('dynamic_hello_ker')\n\nhello_ker(np.int32(0), grid=(1,1,1), block=(4,1,1))\n" ]
[ [ "numpy.int32" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mmakai/zeppelin
[ "1ec869f38deb79a9a7f8b10fb0ba2e00b4ac3abf" ]
[ "python/src/main/resources/python/backend_zinline.py" ]
[ "# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, 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# This file provides a static (non-interactive) matplotlib plotting backend\n# for zeppelin notebooks for use with the python/pyspark interpreters\n\nfrom __future__ import print_function\n\nimport sys\nimport uuid\nimport warnings\nimport base64\nfrom io import BytesIO\ntry:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\nimport mpl_config\nimport matplotlib\nfrom matplotlib._pylab_helpers import Gcf\nfrom matplotlib.backends.backend_agg import new_figure_manager, FigureCanvasAgg\nfrom matplotlib.backend_bases import ShowBase, FigureManagerBase\nfrom matplotlib.figure import Figure\n\n########################################################################\n#\n# The following functions and classes are for pylab and implement\n# window/figure managers, etc...\n#\n########################################################################\n\nclass Show(ShowBase):\n \"\"\"\n A callable object that displays the figures to the screen. Valid kwargs\n include figure width and height (in units supported by the div tag), block\n (allows users to override blocking behavior regardless of whether or not\n interactive mode is enabled, currently unused) and close (Implicitly call\n matplotlib.pyplot.close('all') with each call to show()).\n \"\"\"\n def __call__(self, close=None, block=None, **kwargs):\n if close is None:\n close = mpl_config.get('close')\n try:\n managers = Gcf.get_all_fig_managers()\n if not managers:\n return\n\n # Tell zeppelin that the output will be html using the %html magic\n # We want to do this only once to avoid seeing \"%html\" printed\n # directly to the outout when multiple figures are displayed from\n # one paragraph.\n if mpl_config.get('angular'):\n print('%angular')\n else:\n print('%html')\n\n # Show all open figures\n for manager in managers:\n manager.show(**kwargs)\n finally:\n # This closes all the figures if close is set to True.\n if close and Gcf.get_all_fig_managers():\n Gcf.destroy_all()\n\n\nclass FigureCanvasZInline(FigureCanvasAgg):\n \"\"\"\n The canvas the figure renders into. Calls the draw and print fig\n methods, creates the renderers, etc...\n \"\"\"\n def get_bytes(self, **kwargs):\n \"\"\"\n Get the byte representation of the figure.\n Should only be used with jpg/png formats.\n \"\"\"\n # Make sure format is correct\n fmt = kwargs.get('format', mpl_config.get('format'))\n if fmt == 'svg':\n raise ValueError(\"get_bytes() does not support svg, use png or jpg\")\n \n # Express the image as bytes\n buf = BytesIO()\n self.print_figure(buf, **kwargs)\n fmt = fmt.encode()\n if sys.version_info >= (3, 4) and sys.version_info < (3, 5):\n byte_str = bytes(\"data:image/%s;base64,\" %fmt, \"utf-8\")\n else:\n byte_str = b\"data:image/%s;base64,\" %fmt\n byte_str += base64.b64encode(buf.getvalue())\n \n # Python3 forces all strings to default to unicode, but for raster image\n # formats (eg png, jpg), we want to work with bytes. Thus this step is\n # needed to ensure compatability for all python versions.\n byte_str = byte_str.decode('ascii')\n buf.close()\n return byte_str\n\n def get_svg(self, **kwargs):\n \"\"\"\n Get the svg representation of the figure.\n Should only be used with svg format.\n \"\"\"\n # Make sure format is correct\n fmt = kwargs.get('format', mpl_config.get('format'))\n if fmt != 'svg':\n raise ValueError(\"get_svg() does not support png or jpg, use svg\")\n \n # For SVG the data string has to be unicode, not bytes\n buf = StringIO()\n self.print_figure(buf, **kwargs)\n svg_str = buf.getvalue()\n buf.close()\n return svg_str\n \n def draw_idle(self, *args, **kwargs):\n \"\"\"\n Called when the figure gets updated (eg through a plotting command).\n This is overriden to allow open figures to be reshown after they\n are updated when mpl_config.get('close') is False.\n \"\"\"\n if not self._is_idle_drawing:\n with self._idle_draw_cntx():\n self.draw(*args, **kwargs)\n draw_if_interactive()\n \n\nclass FigureManagerZInline(FigureManagerBase):\n \"\"\"\n Wrap everything up into a window for the pylab interface\n \"\"\"\n def __init__(self, canvas, num):\n FigureManagerBase.__init__(self, canvas, num)\n self.fig_id = \"figure_{0}\".format(uuid.uuid4().hex)\n self._shown = False\n\n def angular_bind(self, **kwargs):\n \"\"\"\n Bind figure data to Zeppelin's Angular Object Registry.\n If mpl_config(\"angular\") is True and PY4J is supported, this allows\n for the possibility to interactively update a figure from a separate\n paragraph without having to display it multiple times.\n \"\"\"\n # This doesn't work for SVG so make sure it's not our format\n fmt = kwargs.get('format', mpl_config.get('format'))\n if fmt == 'svg':\n return\n \n # Get the figure data as a byte array\n src = self.canvas.get_bytes(**kwargs)\n \n # Flag to determine whether or not to use\n # zeppelin's angular display system\n angular = mpl_config.get('angular')\n \n # ZeppelinContext instance (requires PY4J)\n context = mpl_config.get('context')\n \n # Finally we must ensure that automatic closing is set to False,\n # as otherwise using the angular display system is pointless\n close = mpl_config.get('close')\n \n # If above conditions are met, bind the figure data to\n # the Angular Object Registry.\n if not close and angular:\n if hasattr(context, 'angularBind'):\n # Binding is performed through figure ID to ensure this works\n # if multiple figures are open\n context.angularBind(self.fig_id, src)\n \n # Zeppelin will automatically replace this value even if it\n # is updated from another pargraph thanks to the {{}} notation\n src = \"{{%s}}\" %self.fig_id\n else:\n warnings.warn(\"Cannot bind figure to Angular Object Registry. \"\n \"Check if PY4J is installed.\")\n return src\n \n def angular_unbind(self):\n \"\"\"\n Unbind figure from angular display system.\n \"\"\"\n context = mpl_config.get('context')\n if hasattr(context, 'angularUnbind'):\n context.angularUnbind(self.fig_id)\n \n def destroy(self):\n \"\"\"\n Called when close=True or implicitly by pyplot.close().\n Overriden to automatically clean up the angular object registry.\n \"\"\"\n self.angular_unbind()\n\n def show(self, **kwargs):\n if not self._shown:\n zdisplay(self.canvas.figure, **kwargs)\n else:\n self.canvas.draw_idle()\n self.angular_bind(**kwargs)\n \n self._shown = True\n\n\ndef draw_if_interactive():\n \"\"\"\n If interactive mode is on, this allows for updating properties of\n the figure when each new plotting command is called.\n \"\"\"\n manager = Gcf.get_active()\n interactive = matplotlib.is_interactive()\n angular = mpl_config.get('angular')\n \n # Don't bother continuing if we aren't in interactive mode\n # or if there are no active figures. Also pointless to continue\n # in angular mode as we don't want to reshow the figure.\n if not interactive or angular or manager is None:\n return\n \n # Allow for figure to be reshown if close is false since\n # this function call implies that it has been updated\n if not mpl_config.get('close'):\n manager._shown = False\n \n\ndef new_figure_manager(num, *args, **kwargs):\n \"\"\"\n Create a new figure manager instance\n \"\"\"\n # if a main-level app must be created, this (and\n # new_figure_manager_given_figure) is the usual place to\n # do it -- see backend_wx, backend_wxagg and backend_tkagg for\n # examples. Not all GUIs require explicit instantiation of a\n # main-level app (egg backend_gtk, backend_gtkagg) for pylab\n FigureClass = kwargs.pop('FigureClass', Figure)\n thisFig = FigureClass(*args, **kwargs)\n return new_figure_manager_given_figure(num, thisFig)\n\n\ndef new_figure_manager_given_figure(num, figure):\n \"\"\"\n Create a new figure manager instance for the given figure.\n \"\"\"\n canvas = FigureCanvasZInline(figure)\n manager = FigureManagerZInline(canvas, num)\n return manager\n\n\n########################################################################\n#\n# Backend specific functions\n#\n########################################################################\n \ndef zdisplay(fig, **kwargs):\n \"\"\"\n Publishes a matplotlib figure to the notebook paragraph output.\n \"\"\"\n # kwargs can be width or height (in units supported by div tag)\n width = kwargs.pop('width', 'auto')\n height = kwargs.pop('height', 'auto')\n fmt = kwargs.get('format', mpl_config.get('format'))\n\n # Check if format is supported\n supported_formats = mpl_config.get('supported_formats')\n if fmt not in supported_formats:\n raise ValueError(\"Unsupported format %s\" %fmt)\n \n # For SVG the data string has to be unicode, not bytes\n if fmt == 'svg':\n img = fig.canvas.get_svg(**kwargs)\n \n # This is needed to ensure the SVG image is the correct size.\n # We should find a better way to do this...\n width = '{}px'.format(mpl_config.get('width'))\n height = '{}px'.format(mpl_config.get('height'))\n else:\n # Express the image as bytes\n src = fig.canvas.manager.angular_bind(**kwargs)\n img = \"<img src={src} style='width={width};height:{height}'>\"\n img = img.format(src=src, width=width, height=height)\n \n # Print the image to the notebook paragraph via the %html magic\n html = \"<div style='width:{width};height:{height}'>{img}<div>\"\n print(html.format(width=width, height=height, img=img))\n\ndef displayhook():\n \"\"\"\n Called post paragraph execution if interactive mode is on\n \"\"\"\n if matplotlib.is_interactive():\n show()\n\n########################################################################\n#\n# Now just provide the standard names that backend.__init__ is expecting\n#\n########################################################################\n\n# Create a reference to the show function we are using. This is what actually\n# gets called by matplotlib.pyplot.show().\nshow = Show()\n\n# Default FigureCanvas and FigureManager classes to use from the backend\nFigureCanvas = FigureCanvasZInline\nFigureManager = FigureManagerZInline\n" ]
[ [ "matplotlib._pylab_helpers.Gcf.get_active", "matplotlib.is_interactive", "matplotlib._pylab_helpers.Gcf.get_all_fig_managers", "matplotlib._pylab_helpers.Gcf.destroy_all", "matplotlib.backend_bases.FigureManagerBase.__init__" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
RezaZeinali91/NUTLIS
[ "a521df21266913d482bad91490f236bc99193351" ]
[ "examples/adaptivity.py" ]
[ "#! /usr/bin/env python3\n#\n# In this script we solve the Laplace problem on a unit square that has the\n# bottom-right quadrant removed (a.k.a. an L-shaped domain) with Dirichlet\n# boundary conditions matching the harmonic function\n#\n# .. math:: \\sqrt[3]{x^2 + y^2} \\cos\\left(\\tfrac23 \\arctan\\frac{y+x}{y-x}\\right),\n#\n# shifted by 0.5 such that the origin coincides with the middle of the unit\n# square. This variation of a well known benchmark problem is known to converge\n# suboptimally under uniform refinement due to a singular gradient in the\n# reentrant corner. This script demonstrates that optimal convergence can be\n# restored by using adaptive refinement.\n\nimport nutils, numpy\n\n# The main function defines the parameter space for the script. Configurable\n# parameters are the element type (square, triangle, or mixed), type of basis\n# function (std or spline, with availability depending on element type),\n# polynomial degree, and the number of refinement steps to perform before\n# quitting (by default the script will run forever).\n\ndef main(etype: 'type of elements (square/triangle/mixed)' = 'square',\n btype: 'type of basis function (h/th-std/spline)' = 'h-std',\n degree: 'polynomial degree' = 2,\n nrefine: 'number of refinement steps (-1 for unlimited)' = -1):\n\n domain, geom = nutils.mesh.unitsquare(2, etype)\n\n x, y = geom - .5\n exact = (x**2 + y**2)**(1/3) * nutils.function.cos(nutils.function.arctan2(y+x, y-x) * (2/3))\n domain = domain.trim(exact-1e-15, maxrefine=0)\n linreg = nutils.util.linear_regressor()\n\n for irefine in nutils.log.count('level'):\n\n ns = nutils.function.Namespace()\n ns.x = geom\n ns.basis = domain.basis(btype, degree=degree)\n ns.u = 'basis_n ?lhs_n'\n ns.du = ns.u - exact\n\n sqr = domain.boundary['trimmed'].integral('u^2 d:x' @ ns, degree=degree*2)\n cons = nutils.solver.optimize('lhs', sqr, droptol=1e-15)\n\n sqr = domain.boundary.integral('du^2 d:x' @ ns, degree=7)\n cons = nutils.solver.optimize('lhs', sqr, droptol=1e-15, constrain=cons)\n\n res = domain.integral('basis_n,k u_,k d:x' @ ns, degree=degree*2)\n lhs = nutils.solver.solve_linear('lhs', res, constrain=cons)\n\n ndofs = len(ns.basis)\n error = domain.integral('<du^2, du_,k du_,k>_i d:x' @ ns, degree=7).eval(lhs=lhs)**.5\n rate, offset = linreg.add(numpy.log(len(ns.basis)), numpy.log(error))\n nutils.log.user('ndofs: {ndofs}, L2 error: {error[0]:.2e} ({rate[0]:.2f}), H1 error: {error[1]:.2e} ({rate[1]:.2f})'.format(ndofs=len(ns.basis), error=error, rate=rate))\n\n bezier = domain.sample('bezier', 9)\n x, u, du = bezier.eval(['x_i', 'u', 'du'] @ ns, lhs=lhs)\n nutils.export.triplot('sol.jpg', x, u, tri=bezier.tri, hull=bezier.hull)\n nutils.export.triplot('err.jpg', x, du, tri=bezier.tri, hull=bezier.hull)\n\n if irefine == nrefine:\n break\n\n refdom = domain.refined\n ns.refbasis = refdom.basis(btype, degree=degree)\n indicator = refdom.integral('refbasis_n,k u_,k d:x' @ ns, degree=degree*2).eval(lhs=lhs)\n indicator -= refdom.boundary.integral('refbasis_n u_,k n_k d:x' @ ns, degree=degree*2).eval(lhs=lhs)\n mask = indicator**2 > numpy.mean(indicator**2)\n\n domain = domain.refined_by(elem.transform[:-1] for elem in domain.refined.supp(ns.refbasis, mask))\n\n return ndofs, error, rate, lhs\n\n# If the script is executed (as opposed to imported), :func:`nutils.cli.run`\n# calls the main function with arguments provided from the command line. For\n# example, to perform four refinement steps with quadratic basis functions\n# starting from a triangle mesh run :sh:`python3 adaptivity.py etype=triangle\n# degree=2 nrefine=4`.\n\nif __name__ == '__main__':\n nutils.cli.run(main)\n\n# Once a simulation is developed and tested, it is good practice to save a few\n# strategicly chosen return values for routine regression testing. Here we use\n# the standard :mod:`unittest` framework, with\n# :func:`nutils.numeric.assert_allclose64` facilitating the embedding of\n# desired results as compressed base64 data.\n\nimport unittest\n\nclass test(unittest.TestCase):\n\n def test_square_quadratic(self):\n ndofs, error, rate, lhs = main(nrefine=2, etype='square', degree=2)\n self.assertEqual(ndofs, 149)\n numpy.testing.assert_almost_equal(error, [0.00065, 0.03461], decimal=5)\n numpy.testing.assert_almost_equal(rate, [-1.066, -0.478], decimal=3)\n nutils.numeric.assert_allclose64(lhs, 'eNo1j6FrQmEUxT8RBi4KllVfMsl3z/nK4zEmLC'\n '6bhsKCw2gSw5IPFsymGbZiWnr+By8Ii7Yhsk3BMtC4Z9sJ223ncs85vzvmM9+Yhix8hDIjtnkd'\n 'HqQSdDDDj1Qajr5qPXN/07MZ2vI4V7UOIvmdO/oEZY45xYDnoR7ikLHAHVpcs2A1TLhChDO+MO'\n 'eWt5xjYzm6fOQrGxxiZPeoMGaf37hCyU72hB0u6PglPcQcKxRI/KUd7AYLvMPpsqGkCTPumzWf'\n '+qV92kKevjK36ozDP/FSnh1iteWiqWuf+oMaKuyKaC1i52rKPokiF2WLA/20bya+ZCPbWKRPpv'\n 'gFaedebw==')\n\n def test_triangle_quadratic(self):\n ndofs, error, rate, lhs = main(nrefine=2, etype='triangle', degree=2)\n self.assertEqual(ndofs, 98)\n numpy.testing.assert_almost_equal(error, [0.00138, 0.05324], decimal=5)\n numpy.testing.assert_almost_equal(rate, [-1.111, -0.548], decimal=3)\n nutils.numeric.assert_allclose64(lhs, 'eNprMV1oesqU2VTO1Nbko6myWbhpq+kckwST90'\n 'avjRgYzptYm+YYMwBBk3GQWavZb1NXs2+mm83um1WYbQbyXYEiQWbKZjNM7wJVzjBlYICoPW8C'\n 'MiXH+LXRR9NwoPkg82xN5IB2MZu2mGabSBnnAbGscYEJj3GVYQAQg/TVGfaA7RI0BsErRjeNeo'\n 'wDgDQPmF9gkmciaJxtArGjzrAKCGWNpYAQAL0kOBE=')\n\n def test_mixed_linear(self):\n ndofs, error, rate, lhs = main(nrefine=2, etype='mixed', degree=1)\n self.assertEqual(ndofs, 34)\n numpy.testing.assert_almost_equal(error, [0.00450, 0.11683], decimal=5)\n numpy.testing.assert_almost_equal(rate, [-1.143, -0.545], decimal=3)\n nutils.numeric.assert_allclose64(lhs, 'eNprMT1u6mQyxUTRzMCUAQhazL6b3jNrMYPxp5'\n 'iA5FtMD+lcMgDxHa4aXzS+6HDV+fKO85cMnC8zMBzSAQDBThbY')\n" ]
[ [ "numpy.testing.assert_almost_equal", "numpy.log", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Aniket1313/ga-learner-dsmp-repo
[ "adc9f5310c8ad083efd2ebb06912ea8be818e373" ]
[ "Lego-toy-price-prediction-using-Linear-Regression-/code.py" ]
[ "# --------------\nimport pandas as pd\nimport numpy as np\nfrom sklearn.cross_validation import train_test_split\n\n# code starts here\n\ndf =pd.read_csv(path)\ndf.head(5)\n\nX = df[[\"ages\",\"num_reviews\",\"piece_count\",\"play_star_rating\",\"review_difficulty\",\"star_rating\",\"theme_name\",\"val_star_rating\",\"country\"]]\ny = df[\"list_price\"]\n\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3,random_state = 6)\n\n# code ends here\n\n\n\n# --------------\nimport matplotlib.pyplot as plt\n\n# code starts here \n\ncols =X_train.columns\n\nfig, axes = plt.subplots(nrows=3, ncols=3)\n\nfor i in range(0,3):\n for j in range(0,3):\n col=cols[ i * 3 + j]\n axes[i,j].scatter(X_train[col],y_train)\n \n \nplt.show()\n# code ends here\n\n\n\n# --------------\n# Code starts here\ncorr=(X_train).corr()\n\nX_train.drop(['play_star_rating', 'val_star_rating'], axis=1,inplace=True)\nX_test.drop(['play_star_rating', 'val_star_rating'], axis=1,inplace=True)\n# Code ends here\n\n\n# --------------\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n# Code starts here\nregressor=LinearRegression()\n\nregressor.fit(X_train,y_train)\n\n\ny_pred =regressor.predict(X_test)\n\nmse=mean_squared_error(y_test,y_pred)\nmse \n\nr2=r2_score(y_test,y_pred)\nr2\n\n\n# Code ends here\n\n\n# --------------\n# Code starts here\n\nresidual = y_test - y_pred\nresidual\n\nax = residual.plot.hist(bins=12, alpha=0.5)\n\n\n# Code ends here\n\n\n" ]
[ [ "sklearn.cross_validation.train_test_split", "pandas.read_csv", "sklearn.metrics.r2_score", "matplotlib.pyplot.subplots", "sklearn.metrics.mean_squared_error", "sklearn.linear_model.LinearRegression", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
JakeColtman/SurPyval
[ "71ab77231ba39eccba165088689282b247c015f2" ]
[ "SurPyval/model/fitmodel.py" ]
[ "from typing import Dict, Any\n\nfrom SurPyval.node import NodeTree\nfrom SurPyval.samplers import EmceeSampler\n\n\nclass FitModel:\n \"\"\"\n A model that has a posterior sampler\n\n Parameters\n ----------\n node_tree: NodeTree\n The graphical structure of the model\n posterior: EmceeSampler\n sampler for draws of the parameters from the posterior distribution\n\n \"\"\"\n\n def __init__(self, node_tree: NodeTree, posterior: EmceeSampler):\n self.node_tree = node_tree\n self.posterior = posterior\n\n def sample_replicate(self):\n posterior_sample_parameters = self.posterior.sample(1)[0]\n return self.node_tree.generate_replicate(posterior_sample_parameters)\n\n def generate_replicates(self, n_replicates: int):\n posterior_samples = self.posterior.sample(n_replicates)[:n_replicates]\n return [self.node_tree.generate_replicate(posterior_sample) for posterior_sample in posterior_samples]\n\n def predict(self, data_dict: Dict[str, Any]):\n fitted_node_tree = NodeTree(self.node_tree.node_dict, data_dict)\n fitted_model = FitModel(fitted_node_tree, self.posterior)\n return fitted_model\n\n def sample_survival(self):\n def plot_survival_function(surv_node):\n start_point = surv_node.distribution.ppf( 0.005, **parsed_n )[0]\n end_point = surv_node.distribution.ppf( 0.995, **parsed_n )[0]\n x_s = np.linspace( start_point, end_point, 1000 )\n vals = [surv_node.distribution.sf( x, **parsed_n )[0] for x in x_s]\n from matplotlib import pyplot as plt\n plt.plot( x_s, vals )" ]
[ [ "matplotlib.pyplot.plot" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
CEfanmin/DataMiningProjects
[ "b6375f542c68c0001ae2971dd7e8046a0b4afc7a" ]
[ "GraphSAGE/graphsage/models.py" ]
[ "from collections import namedtuple\n\nimport tensorflow as tf\nimport math\n\nimport graphsage.layers as layers\nimport graphsage.metrics as metrics\n\nfrom .prediction import BipartiteEdgePredLayer\nfrom .aggregators import MeanAggregator, MaxPoolingAggregator, MeanPoolingAggregator, SeqAggregator, GCNAggregator\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n# DISCLAIMER:\n# Boilerplate parts of this code file were originally forked from\n# https://github.com/tkipf/gcn\n# which itself was very inspired by the keras package\n\nclass Model(object):\n def __init__(self, **kwargs):\n allowed_kwargs = {'name', 'logging', 'model_size'}\n for kwarg in kwargs.keys():\n assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg\n name = kwargs.get('name')\n if not name:\n name = self.__class__.__name__.lower()\n self.name = name\n\n logging = kwargs.get('logging', False)\n self.logging = logging\n\n self.vars = {}\n self.placeholders = {}\n\n self.layers = []\n self.activations = []\n\n self.inputs = None\n self.outputs = None\n\n self.loss = 0\n self.accuracy = 0\n self.optimizer = None\n self.opt_op = None\n\n def _build(self):\n raise NotImplementedError\n\n def build(self):\n \"\"\" Wrapper for _build() \"\"\"\n with tf.variable_scope(self.name):\n self._build()\n\n # Build sequential layer model\n self.activations.append(self.inputs)\n for layer in self.layers:\n hidden = layer(self.activations[-1])\n self.activations.append(hidden)\n self.outputs = self.activations[-1]\n\n # Store model variables for easy access\n variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name)\n self.vars = {var.name: var for var in variables}\n\n # Build metrics\n self._loss()\n self._accuracy()\n\n self.opt_op = self.optimizer.minimize(self.loss)\n\n def predict(self):\n pass\n\n def _loss(self):\n raise NotImplementedError\n\n def _accuracy(self):\n raise NotImplementedError\n\n def save(self, sess=None):\n if not sess:\n raise AttributeError(\"TensorFlow session not provided.\")\n saver = tf.train.Saver(self.vars)\n save_path = saver.save(sess, \"tmp/%s.ckpt\" % self.name)\n print(\"Model saved in file: %s\" % save_path)\n\n def load(self, sess=None):\n if not sess:\n raise AttributeError(\"TensorFlow session not provided.\")\n saver = tf.train.Saver(self.vars)\n save_path = \"tmp/%s.ckpt\" % self.name\n saver.restore(sess, save_path)\n print(\"Model restored from file: %s\" % save_path)\n\n\nclass MLP(Model):\n \"\"\" A standard multi-layer perceptron \"\"\"\n def __init__(self, placeholders, dims, categorical=True, **kwargs):\n super(MLP, self).__init__(**kwargs)\n\n self.dims = dims\n self.input_dim = dims[0]\n self.output_dim = dims[-1]\n self.placeholders = placeholders\n self.categorical = categorical\n\n self.inputs = placeholders['features']\n self.labels = placeholders['labels']\n\n self.optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate)\n\n self.build()\n\n def _loss(self):\n # Weight decay loss\n for var in self.layers[0].vars.values():\n self.loss += FLAGS.weight_decay * tf.nn.l2_loss(var)\n\n # Cross entropy error\n if self.categorical:\n self.loss += metrics.masked_softmax_cross_entropy(self.outputs, self.placeholders['labels'],\n self.placeholders['labels_mask'])\n # L2\n else:\n diff = self.labels - self.outputs\n self.loss += tf.reduce_sum(tf.sqrt(tf.reduce_sum(diff * diff, axis=1)))\n\n def _accuracy(self):\n if self.categorical:\n self.accuracy = metrics.masked_accuracy(self.outputs, self.placeholders['labels'],\n self.placeholders['labels_mask'])\n\n def _build(self):\n self.layers.append(layers.Dense(input_dim=self.input_dim,\n output_dim=self.dims[1],\n act=tf.nn.relu,\n dropout=self.placeholders['dropout'],\n sparse_inputs=False,\n logging=self.logging))\n\n self.layers.append(layers.Dense(input_dim=self.dims[1],\n output_dim=self.output_dim,\n act=lambda x: x,\n dropout=self.placeholders['dropout'],\n logging=self.logging))\n\n def predict(self):\n return tf.nn.softmax(self.outputs)\n\nclass GeneralizedModel(Model):\n \"\"\"\n Base class for models that aren't constructed from traditional, sequential layers.\n Subclasses must set self.outputs in _build method\n\n (Removes the layers idiom from build method of the Model class)\n \"\"\"\n\n def __init__(self, **kwargs):\n super(GeneralizedModel, self).__init__(**kwargs)\n \n\n def build(self):\n \"\"\" Wrapper for _build() \"\"\"\n with tf.variable_scope(self.name):\n self._build()\n\n # Store model variables for easy access\n variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name)\n self.vars = {var.name: var for var in variables}\n\n # Build metrics\n self._loss()\n self._accuracy()\n\n self.opt_op = self.optimizer.minimize(self.loss)\n\n# SAGEInfo is a namedtuple that specifies the parameters \n# of the recursive GraphSAGE layers\nSAGEInfo = namedtuple(\"SAGEInfo\",\n ['layer_name', # name of the layer (to get feature embedding etc.)\n 'neigh_sampler', # callable neigh_sampler constructor\n 'num_samples',\n 'output_dim' # the output (i.e., hidden) dimension\n ])\n\nclass SampleAndAggregate(GeneralizedModel):\n \"\"\"\n Base implementation of unsupervised GraphSAGE\n \"\"\"\n\n def __init__(self, placeholders, features, adj, degrees,\n layer_infos, concat=True, aggregator_type=\"mean\", \n model_size=\"small\", identity_dim=0,\n **kwargs):\n '''\n Args:\n - placeholders: Stanford TensorFlow placeholder object.\n - features: Numpy array with node features. \n NOTE: Pass a None object to train in featureless mode (identity features for nodes)!\n - adj: Numpy array with adjacency lists (padded with random re-samples)\n - degrees: Numpy array with node degrees. \n - layer_infos: List of SAGEInfo namedtuples that describe the parameters of all \n the recursive layers. See SAGEInfo definition above.\n - concat: whether to concatenate during recursive iterations\n - aggregator_type: how to aggregate neighbor information\n - model_size: one of \"small\" and \"big\"\n - identity_dim: Set to positive int to use identity features (slow and cannot generalize, but better accuracy)\n '''\n super(SampleAndAggregate, self).__init__(**kwargs)\n if aggregator_type == \"mean\":\n self.aggregator_cls = MeanAggregator\n elif aggregator_type == \"seq\":\n self.aggregator_cls = SeqAggregator\n elif aggregator_type == \"maxpool\":\n self.aggregator_cls = MaxPoolingAggregator\n elif aggregator_type == \"meanpool\":\n self.aggregator_cls = MeanPoolingAggregator\n elif aggregator_type == \"gcn\":\n self.aggregator_cls = GCNAggregator\n else:\n raise Exception(\"Unknown aggregator: \", self.aggregator_cls)\n\n # get info from placeholders...\n self.inputs1 = placeholders[\"batch1\"]\n self.inputs2 = placeholders[\"batch2\"]\n self.model_size = model_size\n self.adj_info = adj\n if identity_dim > 0:\n self.embeds = tf.get_variable(\"node_embeddings\", [adj.get_shape().as_list()[0], identity_dim])\n else:\n self.embeds = None\n if features is None: \n if identity_dim == 0:\n raise Exception(\"Must have a positive value for identity feature dimension if no input features given.\")\n self.features = self.embeds\n else:\n self.features = tf.Variable(tf.constant(features, dtype=tf.float32), trainable=False)\n if not self.embeds is None:\n self.features = tf.concat([self.embeds, self.features], axis=1)\n self.degrees = degrees\n self.concat = concat\n\n self.dims = [(0 if features is None else features.shape[1]) + identity_dim]\n self.dims.extend([layer_infos[i].output_dim for i in range(len(layer_infos))])\n self.batch_size = placeholders[\"batch_size\"]\n self.placeholders = placeholders\n self.layer_infos = layer_infos\n\n self.optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate)\n\n self.build()\n\n def sample(self, inputs, layer_infos, batch_size=None):\n \"\"\" Sample neighbors to be the supportive fields for multi-layer convolutions.\n\n Args:\n inputs: batch inputs\n batch_size: the number of inputs (different for batch inputs and negative samples).\n \"\"\"\n \n if batch_size is None:\n batch_size = self.batch_size\n samples = [inputs]\n # size of convolution support at each layer per node\n support_size = 1\n support_sizes = [support_size]\n for k in range(len(layer_infos)):\n t = len(layer_infos) - k - 1\n support_size *= layer_infos[t].num_samples\n sampler = layer_infos[t].neigh_sampler\n node = sampler((samples[k], layer_infos[t].num_samples))\n samples.append(tf.reshape(node, [support_size * batch_size,]))\n support_sizes.append(support_size)\n return samples, support_sizes\n\n\n def aggregate(self, samples, input_features, dims, num_samples, support_sizes, batch_size=None,\n aggregators=None, name=None, concat=False, model_size=\"small\"):\n \"\"\" At each layer, aggregate hidden representations of neighbors to compute the hidden representations \n at next layer.\n Args:\n samples: a list of samples of variable hops away for convolving at each layer of the\n network. Length is the number of layers + 1. Each is a vector of node indices.\n input_features: the input features for each sample of various hops away.\n dims: a list of dimensions of the hidden representations from the input layer to the\n final layer. Length is the number of layers + 1.\n num_samples: list of number of samples for each layer.\n support_sizes: the number of nodes to gather information from for each layer.\n batch_size: the number of inputs (different for batch inputs and negative samples).\n Returns:\n The hidden representation at the final layer for all nodes in batch\n \"\"\"\n\n if batch_size is None:\n batch_size = self.batch_size\n\n # length: number of layers + 1\n hidden = [tf.nn.embedding_lookup(input_features, node_samples) for node_samples in samples]\n new_agg = aggregators is None\n if new_agg:\n aggregators = []\n for layer in range(len(num_samples)):\n if new_agg:\n dim_mult = 2 if concat and (layer != 0) else 1\n # aggregator at current layer\n if layer == len(num_samples) - 1:\n aggregator = self.aggregator_cls(dim_mult*dims[layer], dims[layer+1], act=lambda x : x,\n dropout=self.placeholders['dropout'], \n name=name, concat=concat, model_size=model_size)\n else:\n aggregator = self.aggregator_cls(dim_mult*dims[layer], dims[layer+1],\n dropout=self.placeholders['dropout'], \n name=name, concat=concat, model_size=model_size)\n aggregators.append(aggregator)\n else:\n aggregator = aggregators[layer]\n # hidden representation at current layer for all support nodes that are various hops away\n next_hidden = []\n # as layer increases, the number of support nodes needed decreases\n for hop in range(len(num_samples) - layer):\n dim_mult = 2 if concat and (layer != 0) else 1\n neigh_dims = [batch_size * support_sizes[hop], \n num_samples[len(num_samples) - hop - 1], \n dim_mult*dims[layer]]\n h = aggregator((hidden[hop],\n tf.reshape(hidden[hop + 1], neigh_dims)))\n next_hidden.append(h)\n hidden = next_hidden\n return hidden[0], aggregators\n\n def _build(self):\n labels = tf.reshape(\n tf.cast(self.placeholders['batch2'], dtype=tf.int64),\n [self.batch_size, 1])\n self.neg_samples, _, _ = (tf.nn.fixed_unigram_candidate_sampler(\n true_classes=labels,\n num_true=1,\n num_sampled=FLAGS.neg_sample_size,\n unique=False,\n range_max=len(self.degrees),\n distortion=0.75,\n unigrams=self.degrees.tolist()))\n\n \n # perform \"convolution\"\n samples1, support_sizes1 = self.sample(self.inputs1, self.layer_infos)\n samples2, support_sizes2 = self.sample(self.inputs2, self.layer_infos)\n num_samples = [layer_info.num_samples for layer_info in self.layer_infos]\n self.outputs1, self.aggregators = self.aggregate(samples1, [self.features], self.dims, num_samples,\n support_sizes1, concat=self.concat, model_size=self.model_size)\n self.outputs2, _ = self.aggregate(samples2, [self.features], self.dims, num_samples,\n support_sizes2, aggregators=self.aggregators, concat=self.concat,\n model_size=self.model_size)\n\n neg_samples, neg_support_sizes = self.sample(self.neg_samples, self.layer_infos,\n FLAGS.neg_sample_size)\n self.neg_outputs, _ = self.aggregate(neg_samples, [self.features], self.dims, num_samples,\n neg_support_sizes, batch_size=FLAGS.neg_sample_size, aggregators=self.aggregators,\n concat=self.concat, model_size=self.model_size)\n\n dim_mult = 2 if self.concat else 1\n self.link_pred_layer = BipartiteEdgePredLayer(dim_mult*self.dims[-1],\n dim_mult*self.dims[-1], self.placeholders, act=tf.nn.sigmoid, \n bilinear_weights=False,\n name='edge_predict')\n\n self.outputs1 = tf.nn.l2_normalize(self.outputs1, 1)\n self.outputs2 = tf.nn.l2_normalize(self.outputs2, 1)\n self.neg_outputs = tf.nn.l2_normalize(self.neg_outputs, 1)\n\n def build(self):\n self._build()\n\n # TF graph management\n self._loss()\n self._accuracy()\n self.loss = self.loss / tf.cast(self.batch_size, tf.float32)\n grads_and_vars = self.optimizer.compute_gradients(self.loss)\n clipped_grads_and_vars = [(tf.clip_by_value(grad, -5.0, 5.0) if grad is not None else None, var) \n for grad, var in grads_and_vars]\n self.grad, _ = clipped_grads_and_vars[0]\n self.opt_op = self.optimizer.apply_gradients(clipped_grads_and_vars)\n\n def _loss(self):\n for aggregator in self.aggregators:\n for var in aggregator.vars.values():\n self.loss += FLAGS.weight_decay * tf.nn.l2_loss(var)\n\n self.loss += self.link_pred_layer.loss(self.outputs1, self.outputs2, self.neg_outputs) \n tf.summary.scalar('loss', self.loss)\n\n def _accuracy(self):\n # shape: [batch_size]\n aff = self.link_pred_layer.affinity(self.outputs1, self.outputs2)\n # shape : [batch_size x num_neg_samples]\n self.neg_aff = self.link_pred_layer.neg_cost(self.outputs1, self.neg_outputs)\n self.neg_aff = tf.reshape(self.neg_aff, [self.batch_size, FLAGS.neg_sample_size])\n _aff = tf.expand_dims(aff, axis=1)\n self.aff_all = tf.concat(axis=1, values=[self.neg_aff, _aff])\n size = tf.shape(self.aff_all)[1]\n _, indices_of_ranks = tf.nn.top_k(self.aff_all, k=size)\n _, self.ranks = tf.nn.top_k(-indices_of_ranks, k=size)\n self.mrr = tf.reduce_mean(tf.div(1.0, tf.cast(self.ranks[:, -1] + 1, tf.float32)))\n tf.summary.scalar('mrr', self.mrr)\n\n\nclass Node2VecModel(GeneralizedModel):\n def __init__(self, placeholders, dict_size, degrees, name=None,\n nodevec_dim=50, lr=0.001, **kwargs):\n \"\"\" Simple version of Node2Vec/DeepWalk algorithm.\n\n Args:\n dict_size: the total number of nodes.\n degrees: numpy array of node degrees, ordered as in the data's id_map\n nodevec_dim: dimension of the vector representation of node.\n lr: learning rate of optimizer.\n \"\"\"\n\n super(Node2VecModel, self).__init__(**kwargs)\n\n self.placeholders = placeholders\n self.degrees = degrees\n self.inputs1 = placeholders[\"batch1\"]\n self.inputs2 = placeholders[\"batch2\"]\n\n self.batch_size = placeholders['batch_size']\n self.hidden_dim = nodevec_dim\n\n # following the tensorflow word2vec tutorial\n self.target_embeds = tf.Variable(\n tf.random_uniform([dict_size, nodevec_dim], -1, 1),\n name=\"target_embeds\")\n self.context_embeds = tf.Variable(\n tf.truncated_normal([dict_size, nodevec_dim],\n stddev=1.0 / math.sqrt(nodevec_dim)),\n name=\"context_embeds\")\n self.context_bias = tf.Variable(\n tf.zeros([dict_size]),\n name=\"context_bias\")\n\n self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=lr)\n\n self.build()\n\n def _build(self):\n labels = tf.reshape(\n tf.cast(self.placeholders['batch2'], dtype=tf.int64),\n [self.batch_size, 1])\n self.neg_samples, _, _ = (tf.nn.fixed_unigram_candidate_sampler(\n true_classes=labels,\n num_true=1,\n num_sampled=FLAGS.neg_sample_size,\n unique=True,\n range_max=len(self.degrees),\n distortion=0.75,\n unigrams=self.degrees.tolist()))\n\n self.outputs1 = tf.nn.embedding_lookup(self.target_embeds, self.inputs1)\n self.outputs2 = tf.nn.embedding_lookup(self.context_embeds, self.inputs2)\n self.outputs2_bias = tf.nn.embedding_lookup(self.context_bias, self.inputs2)\n self.neg_outputs = tf.nn.embedding_lookup(self.context_embeds, self.neg_samples)\n self.neg_outputs_bias = tf.nn.embedding_lookup(self.context_bias, self.neg_samples)\n\n self.link_pred_layer = BipartiteEdgePredLayer(self.hidden_dim, self.hidden_dim,\n self.placeholders, bilinear_weights=False)\n\n def build(self):\n self._build()\n # TF graph management\n self._loss()\n self._minimize()\n self._accuracy()\n\n def _minimize(self):\n self.opt_op = self.optimizer.minimize(self.loss)\n\n def _loss(self):\n aff = tf.reduce_sum(tf.multiply(self.outputs1, self.outputs2), 1) + self.outputs2_bias\n neg_aff = tf.matmul(self.outputs2, tf.transpose(self.neg_outputs)) + self.neg_outputs_bias\n true_xent = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.ones_like(aff), logits=aff)\n negative_xent = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.zeros_like(neg_aff), logits=neg_aff)\n loss = tf.reduce_sum(true_xent) + tf.reduce_sum(negative_xent)\n self.loss = loss / tf.cast(self.batch_size, tf.float32)\n tf.summary.scalar('loss', self.loss)\n \n def _accuracy(self):\n # shape: [batch_size]\n aff = self.link_pred_layer.affinity(self.outputs1, self.outputs2)\n # shape : [batch_size x num_neg_samples]\n self.neg_aff = self.link_pred_layer.neg_cost(self.outputs1, self.neg_outputs)\n self.neg_aff = tf.reshape(self.neg_aff, [self.batch_size, FLAGS.neg_sample_size])\n _aff = tf.expand_dims(aff, axis=1)\n self.aff_all = tf.concat(axis=1, values=[self.neg_aff, _aff])\n size = tf.shape(self.aff_all)[1]\n _, indices_of_ranks = tf.nn.top_k(self.aff_all, k=size)\n _, self.ranks = tf.nn.top_k(-indices_of_ranks, k=size)\n self.mrr = tf.reduce_mean(tf.div(1.0, tf.cast(self.ranks[:, -1] + 1, tf.float32)))\n tf.summary.scalar('mrr', self.mrr)\n" ]
[ [ "tensorflow.concat", "tensorflow.zeros", "tensorflow.reduce_sum", "tensorflow.cast", "tensorflow.nn.l2_loss", "tensorflow.train.AdamOptimizer", "tensorflow.summary.scalar", "tensorflow.get_collection", "tensorflow.nn.top_k", "tensorflow.train.Saver", "tensorflow.nn.l2_normalize", "tensorflow.shape", "tensorflow.zeros_like", "tensorflow.train.GradientDescentOptimizer", "tensorflow.nn.embedding_lookup", "tensorflow.clip_by_value", "tensorflow.nn.softmax", "tensorflow.constant", "tensorflow.multiply", "tensorflow.transpose", "tensorflow.reshape", "tensorflow.ones_like", "tensorflow.expand_dims", "tensorflow.variable_scope", "tensorflow.random_uniform" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
kristianmeyerr/AMICI
[ "15f14c24b781daf5ceb3606d79edbbf57155a043" ]
[ "python/tests/test_heavisides.py" ]
[ "\"\"\"Tests for SBML events, including piecewise expressions.\"\"\"\nimport numpy as np\nimport pytest\n\n\nfrom util import (\n create_sbml_model,\n create_amici_model,\n check_trajectories_without_sensitivities,\n check_trajectories_with_forward_sensitivities,\n)\n\[email protected](params=[\n 'state_and_parameter_dependent_heavisides',\n 'piecewise_with_boolean_operations',\n 'piecewise_many_conditions',\n])\ndef model(request):\n \"\"\"Returns the requested AMICI model and analytical expressions.\"\"\"\n (\n initial_assignments,\n parameters,\n rate_rules,\n species,\n events,\n timepoints,\n x_pected,\n sx_pected\n ) = get_model_definition(request.param)\n\n # SBML model\n sbml_document, sbml_model = create_sbml_model(\n initial_assignments=initial_assignments,\n parameters=parameters,\n rate_rules=rate_rules,\n species=species,\n events=events,\n # uncomment `to_file` to save SBML model to file for inspection\n # to_file=sbml_test_models / (model_name + '.sbml'),\n )\n\n # AMICI model\n amici_model = create_amici_model(\n sbml_model=sbml_model,\n model_name=request.param,\n )\n amici_model.setTimepoints(timepoints)\n\n return amici_model, parameters, timepoints, x_pected, sx_pected\n\n\ndef test_models(model):\n amici_model, parameters, timepoints, x_pected, sx_pected = model\n\n result_expected_x = np.array([\n x_pected(t, **parameters)\n for t in timepoints\n ])\n result_expected_sx = np.array([\n sx_pected(t, **parameters)\n for t in timepoints\n ])\n\n # Does the AMICI simulation match the analytical solution?\n check_trajectories_without_sensitivities(amici_model,\n result_expected_x)\n check_trajectories_with_forward_sensitivities(amici_model,\n result_expected_x,\n result_expected_sx)\n\n\ndef get_model_definition(model_name):\n if model_name == 'state_and_parameter_dependent_heavisides':\n return model_definition_state_and_parameter_dependent_heavisides()\n elif model_name == 'piecewise_with_boolean_operations':\n return model_definition_piecewise_with_boolean_operations()\n elif model_name == 'piecewise_many_conditions':\n return model_definition_piecewise_many_conditions()\n else:\n raise NotImplementedError(\n f'Model with name {model_name} is not implemented.'\n )\n\n\ndef model_definition_state_and_parameter_dependent_heavisides():\n \"\"\"Test model for state- and parameter-dependent heavisides.\n\n ODEs\n ----\n d/dt x_1:\n - { alpha * x_1, t < x_2\n - { -beta * x_1, t >= x_2\n d/dt x_2:\n - { gamma * x_2, t < delta\n - { eta, t >= delta\n \"\"\"\n # Model components\n species = ['x_1', 'x_2']\n initial_assignments = {\n 'x_1': 'zeta',\n }\n rate_rules = {\n 'x_1': 'piecewise( alpha * x_1, time < x_2, -beta * x_1 )',\n 'x_2': 'piecewise( gamma * x_2, time < delta, eta )',\n }\n parameters = {\n 'alpha': float(np.log(2)),\n 'beta': float(np.log(4)),\n 'gamma': float(np.log(3)),\n 'delta': 1,\n 'eta': 0.5,\n 'zeta': 0.25,\n }\n timepoints = np.linspace(0, 10, 100)\n events = {}\n\n # Analytical solution\n def x_pected(t, alpha, beta, gamma, delta, eta, zeta):\n # get x_1\n tau_1 = (np.exp(gamma * delta) - delta * eta) / (1 - eta)\n if t < tau_1:\n x_1 = zeta * np.exp(alpha * t)\n else:\n x_1 = zeta * np.exp(alpha * tau_1 - beta*(t - tau_1))\n\n # get x_2\n tau_2 = delta\n if t < tau_2:\n x_2 = np.exp(gamma*t)\n else:\n x_2 = np.exp(gamma*delta) + eta*(t-delta)\n\n return (x_1, x_2)\n\n def sx_pected(t, alpha, beta, gamma, delta, eta, zeta):\n # get sx_1, w.r.t. parameters\n tau_1 = (np.exp(gamma * delta) - delta * eta) / (1 - eta)\n if t < tau_1:\n sx_1_alpha = zeta * t * np.exp(alpha * t)\n sx_1_beta = 0\n sx_1_gamma = 0\n sx_1_delta = 0\n sx_1_eta = 0\n sx_1_zeta = np.exp(alpha * t)\n else:\n # Never trust Wolfram Alpha...\n sx_1_alpha = (\n zeta * tau_1 * np.exp(alpha * tau_1 - beta*(t - tau_1))\n )\n sx_1_beta = (\n zeta * (tau_1 - t)\n * np.exp(alpha * tau_1 - beta*(t - tau_1))\n )\n sx_1_gamma = (\n zeta * (alpha + beta) * delta * np.exp(gamma * delta)\n / (1 - eta)\n * np.exp(alpha * tau_1 - beta*(t - tau_1))\n )\n sx_1_delta = (\n zeta * (alpha + beta)\n * np.exp(alpha * tau_1 - beta*(t - tau_1))\n * (gamma * np.exp(gamma * delta) - eta)\n / (1 - eta)\n )\n sx_1_eta = (\n zeta * (alpha + beta)\n * (-delta * (1-eta) + np.exp(gamma * delta) - delta * eta)\n / (1 - eta)**2\n * np.exp(alpha * tau_1 - beta*(t - tau_1))\n )\n sx_1_zeta = np.exp(alpha * tau_1 - beta*(t - tau_1))\n\n # get sx_2, w.r.t. parameters\n tau_2 = delta\n if t < tau_2:\n sx_2_alpha = 0\n sx_2_beta = 0\n sx_2_gamma = t * np.exp(gamma*t)\n sx_2_delta = 0\n sx_2_eta = 0\n sx_2_zeta = 0\n else:\n sx_2_alpha = 0\n sx_2_beta = 0\n sx_2_gamma = delta * np.exp(gamma*delta)\n sx_2_delta = gamma*np.exp(gamma*delta) - eta\n sx_2_eta = t - delta\n sx_2_zeta = 0\n\n sx_1 = (sx_1_alpha, sx_1_beta, sx_1_gamma,\n sx_1_delta, sx_1_eta, sx_1_zeta)\n sx_2 = (sx_2_alpha, sx_2_beta, sx_2_gamma,\n sx_2_delta, sx_2_eta, sx_2_zeta)\n\n return np.array((sx_1, sx_2)).transpose()\n\n return (\n initial_assignments,\n parameters,\n rate_rules,\n species,\n events,\n timepoints,\n x_pected,\n sx_pected\n )\n\n\ndef model_definition_piecewise_with_boolean_operations():\n \"\"\"Test model for boolean operations in a piecewise condition.\n\n ODEs\n ----\n d/dt x_1:\n - { 1, (alpha <= t and t < beta) or (gamma <= t and t < delta)\n - { 0, otherwise\n \"\"\"\n # Model components\n species = ['x_1']\n initial_assignments = {'x_1': 'x_1_0'}\n rate_rules = {\n 'x_1': (\n 'piecewise('\n '1, ' # noqa\n '(alpha <= time && time < beta) || ' # noqa\n '(gamma <= time && time < delta), '\n '0'\n ')'\n ),\n }\n parameters = {\n 'alpha': 1,\n 'beta': 2,\n 'gamma': 3,\n 'delta': 4,\n 'x_1_0': 1,\n }\n timepoints = np.linspace(0, 5, 100)\n events = {}\n\n # Analytical solution\n def x_pected(t, x_1_0, alpha, beta, gamma, delta):\n if t < alpha:\n return (x_1_0,)\n elif alpha <= t < beta:\n return (x_1_0 + (t - alpha),)\n elif beta <= t < gamma:\n return (x_1_0 + (beta - alpha),)\n elif gamma <= t < delta:\n return (x_1_0 + (beta - alpha) + (t - gamma),)\n else:\n return (x_1_0 + (beta - alpha) + (delta - gamma), )\n\n def sx_pected(t, x_1_0, alpha, beta, gamma, delta):\n # x0 is very simple...\n sx_x0 = 1\n sx_alpha = 0\n sx_beta = 0\n sx_gamma = 0\n sx_delta = 0\n\n if t >= alpha:\n sx_alpha = -1\n if t >= beta:\n sx_beta = 1\n if t >= gamma:\n sx_gamma = -1\n if t >= delta:\n sx_delta = 1\n\n sx = (sx_alpha, sx_beta, sx_gamma, sx_delta, sx_x0)\n\n return np.array((sx,)).transpose()\n\n return (\n initial_assignments,\n parameters,\n rate_rules,\n species,\n events,\n timepoints,\n x_pected,\n sx_pected\n )\n\n\ndef model_definition_piecewise_many_conditions():\n \"\"\"Test model for piecewise functions with many pieces.\n\n ODEs\n ----\n d/dt x_1:\n - { 1, floor(t) is odd\n - { 0, otherwise\n \"\"\"\n # Model components\n species = ['x_1']\n initial_assignments = {'x_1': 'x_1_0'}\n t_final = 5\n\n pieces = 'piecewise('\n for t in range(t_final):\n if t > 0:\n pieces += ', '\n if t % 2 == 1:\n pieces += f'1, time < {t + 1}'\n else:\n pieces += f'0, time < {t + 1}'\n pieces += ', 0)'\n rate_rules = {'x_1': pieces, }\n\n parameters = {\n 'x_1_0': 1,\n }\n timepoints = np.linspace(0, t_final, 100)\n events = {}\n\n # Analytical solution\n def x_pected(t, x_1_0):\n if np.floor(t) % 2 == 1:\n return (x_1_0 + (np.floor(t)-1)/2 + (t-np.floor(t)), )\n else:\n return (x_1_0 + np.floor(t)/2, )\n\n def sx_pected(t, x_1_0):\n return np.array([[1, ], ])\n\n return (\n initial_assignments,\n parameters,\n rate_rules,\n species,\n events,\n timepoints,\n x_pected,\n sx_pected\n )\n" ]
[ [ "numpy.log", "numpy.linspace", "numpy.floor", "numpy.array", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yashraj02/incubator-mxnet
[ "91b8e575072b92c5bf1a6ad211249b3a9b528221" ]
[ "tests/python/unittest/test_symbol.py" ]
[ "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport copy\nimport sys\nimport os\nimport logging\nimport re\nimport json\nimport mxnet as mx\nimport numpy as np\nfrom common import assertRaises, models, TemporaryDirectory\nfrom mxnet.base import NotImplementedForSymbol\nfrom mxnet.test_utils import discard_stderr, rand_shape_nd, use_np\nfrom mxnet.util import np_shape\nimport pickle as pkl\n\ndef test_symbol_basic():\n mlist = []\n mlist.append(models.mlp2())\n for m in mlist:\n m.list_arguments()\n m.list_outputs()\n\ndef test_symbol_bool():\n x = mx.symbol.Variable('x')\n assertRaises(NotImplementedForSymbol, bool, x)\n\ndef test_symbol_compose():\n data = mx.symbol.Variable('data')\n net1 = mx.symbol.FullyConnected(data=data, name='fc1', num_hidden=10)\n net1 = mx.symbol.FullyConnected(data=net1, name='fc2', num_hidden=100)\n net1.list_arguments() == ['data',\n 'fc1_weight', 'fc1_bias',\n 'fc2_weight', 'fc2_bias']\n\n net2 = mx.symbol.FullyConnected(name='fc3', num_hidden=10)\n net2 = mx.symbol.Activation(data=net2, act_type='relu')\n net2 = mx.symbol.FullyConnected(data=net2, name='fc4', num_hidden=20)\n\n composed = net2(fc3_data=net1, name='composed')\n multi_out = mx.symbol.Group([composed, net1])\n assert len(multi_out.list_outputs()) == 2\n assert len(multi_out) == 2\n\n\ndef test_symbol_copy():\n data = mx.symbol.Variable('data')\n data_2 = copy.deepcopy(data)\n data_3 = copy.copy(data)\n assert data.tojson() == data_2.tojson()\n assert data.tojson() == data_3.tojson()\n\n\ndef test_symbol_internal():\n data = mx.symbol.Variable('data')\n oldfc = mx.symbol.FullyConnected(data=data, name='fc1', num_hidden=10)\n net1 = mx.symbol.FullyConnected(data=oldfc, name='fc2', num_hidden=100)\n assert net1.list_arguments() == ['data', 'fc1_weight', 'fc1_bias', 'fc2_weight', 'fc2_bias']\n\n internal = net1.get_internals()\n fc1 = internal['fc1_output']\n assert fc1.list_arguments() == oldfc.list_arguments()\n\ndef test_symbol_children():\n data = mx.symbol.Variable('data')\n oldfc = mx.symbol.FullyConnected(data=data, name='fc1', num_hidden=10)\n net1 = mx.symbol.FullyConnected(data=oldfc, name='fc2', num_hidden=100)\n\n assert net1.get_children().list_outputs() == ['fc1_output', 'fc2_weight', 'fc2_bias']\n assert len(net1.get_children()) == 3\n assert net1.get_children().get_children().list_outputs() == ['data', 'fc1_weight', 'fc1_bias']\n assert len(net1.get_children().get_children()) == 3\n assert net1.get_children()['fc2_weight'].list_arguments() == ['fc2_weight']\n assert net1.get_children()['fc2_weight'].get_children() is None\n\n data = mx.sym.Variable('data')\n sliced = mx.sym.SliceChannel(data, num_outputs=3, name='slice')\n concat = mx.sym.Concat(*list(sliced))\n\n assert concat.get_children().list_outputs() == \\\n ['slice_output0', 'slice_output1', 'slice_output2']\n assert sliced.get_children().list_outputs() == ['data']\n\ndef test_symbol_pickle():\n mlist = [models.mlp2()]\n data = pkl.dumps(mlist)\n mlist2 = pkl.loads(data)\n for x, y in zip(mlist, mlist2):\n assert x.tojson() == y.tojson()\n\n\ndef test_symbol_saveload():\n sym = models.mlp2()\n fname = 'tmp_sym.json'\n sym.save(fname)\n data2 = mx.symbol.load(fname)\n # save because of order\n assert sym.tojson() == data2.tojson()\n os.remove(fname)\n\ndef test_symbol_infer_shape():\n num_hidden = 128\n num_dim = 64\n num_sample = 10\n\n data = mx.symbol.Variable('data')\n prev = mx.symbol.Variable('prevstate')\n x2h = mx.symbol.FullyConnected(data=data, name='x2h', num_hidden=num_hidden)\n h2h = mx.symbol.FullyConnected(data=prev, name='h2h', num_hidden=num_hidden)\n\n out = mx.symbol.Activation(data=mx.sym.elemwise_add(x2h, h2h), name='out', act_type='relu')\n\n # shape inference will fail because information is not available for h2h\n ret = out.infer_shape(data=(num_sample, num_dim))\n assert ret == (None, None, None)\n\n arg, out_shapes, aux_shapes = out.infer_shape_partial(data=(num_sample, num_dim))\n arg_shapes = dict(zip(out.list_arguments(), arg))\n assert arg_shapes['data'] == (num_sample, num_dim)\n assert arg_shapes['x2h_weight'] == (num_hidden, num_dim)\n assert arg_shapes['h2h_weight'] == ()\n\n # now we can do full shape inference\n state_shape = out_shapes[0]\n arg, out_shapes, aux_shapes = out.infer_shape(data=(num_sample, num_dim), prevstate=state_shape)\n arg_shapes = dict(zip(out.list_arguments(), arg))\n assert arg_shapes['data'] == (num_sample, num_dim)\n assert arg_shapes['x2h_weight'] == (num_hidden, num_dim)\n assert arg_shapes['h2h_weight'] == (num_hidden, num_hidden)\n\n # Partial shape inference with some unknown dimensions\n data_shape = (1, 0, 0, 0)\n data = mx.sym.Variable('data', shape=data_shape)\n weight = mx.sym.Variable('weight')\n cdata = mx.sym.cast(data, dtype='float16')\n cweight = mx.sym.cast(weight, dtype='float16')\n test = mx.sym.Convolution(data=cdata, weight=cweight, pad=(3, 3), num_filter=64, stride=(2, 2), no_bias=True, kernel=(7, 7))\n\n arg, _, _ = test.infer_shape_partial()\n arg_shapes = dict(zip(test.list_arguments(), arg))\n assert arg_shapes['data'] == data_shape\n assert arg_shapes['weight'] == (64, 0, 7, 7)\n\n\ndef test_symbol_infer_shape_var():\n \"Test specifying shape information when constructing a variable\"\n shape = (2, 3)\n a = mx.symbol.Variable('a', shape=shape)\n b = mx.symbol.Variable('b')\n c = mx.symbol.elemwise_add(a, b)\n arg_shapes, out_shapes, aux_shapes = c.infer_shape()\n assert arg_shapes[0] == shape\n assert arg_shapes[1] == shape\n assert out_shapes[0] == shape\n\n overwrite_shape = (5, 6)\n arg_shapes, out_shapes, aux_shapes = c.infer_shape(a=overwrite_shape)\n assert arg_shapes[0] == overwrite_shape\n assert arg_shapes[1] == overwrite_shape\n assert out_shapes[0] == overwrite_shape\n\n\ndef test_symbol_magic_abs():\n for dim in range(1, 7):\n with mx.name.NameManager():\n data = mx.symbol.Variable('data')\n method = data.abs(name='abs0')\n magic = abs(data)\n regular = mx.symbol.abs(data, name='abs0')\n ctx = {'ctx': mx.context.current_context(), 'data': rand_shape_nd(dim)}\n mx.test_utils.check_consistency(\n [method, magic], ctx_list=[ctx, ctx])\n mx.test_utils.check_consistency(\n [regular, magic], ctx_list=[ctx, ctx])\n\n\ndef test_symbol_fluent():\n has_grad = set(['flatten', 'expand_dims', 'flip', 'tile', 'transpose', 'sum', 'nansum', 'prod',\n 'nanprod', 'mean', 'max', 'min', 'reshape', 'broadcast_to', 'split',\n 'broadcast_axes', 'broadcast_like', 'pad', 'swapaxes', 'slice', 'slice_axis', 'slice_like',\n 'take', 'one_hot', 'pick', 'sort', 'topk', 'argsort', 'argmax', 'argmin',\n 'clip', 'abs', 'sign', 'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan',\n 'degrees', 'radians', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh',\n 'exp', 'expm1', 'log', 'log10', 'log2', 'log1p', 'sqrt', 'rsqrt',\n 'square', 'reciprocal' 'reshape_like', 'cbrt', 'rcbrt', 'relu', 'sigmoid',\n 'softmax', 'log_softmax', 'softmin', 'rint', 'ceil', 'floor', 'trunc', 'fix'])\n\n def check_fluent_regular(func, kwargs, shape=(5, 17, 1), equal_nan=False):\n with mx.name.NameManager():\n data = mx.symbol.Variable('data')\n regular = getattr(mx.symbol, func)(data, name=func+'0', **kwargs)\n fluent = getattr(data, func)(**kwargs)\n check_symbol_consistency(regular, fluent, {'ctx': mx.context.current_context(),\n 'data': shape},\n skip_grad=func not in has_grad,\n equal_nan=equal_nan)\n\n for func in ['flatten', 'norm', 'round', 'rint', 'fix', 'floor', 'ceil', 'trunc', 'zeros_like',\n 'ones_like', 'abs', 'sign', 'sin', 'cos', 'degrees', 'radians', 'exp', 'expm1',\n 'square', 'reciprocal', 'argmax_channel', 'shape_array', 'size_array']:\n check_fluent_regular(func, {})\n\n for func in ['arccosh', 'arcsin', 'arccos', 'arctan', 'tan', 'sinh', 'cosh', 'tanh',\n 'arcsinh', 'arctanh', 'log', 'log10', 'log2', 'log1p', 'sqrt', 'rsqrt',\n 'cbrt', 'rcbrt', 'relu', 'sigmoid', 'softmax', 'log_softmax', 'softmin']:\n check_fluent_regular(func, {}, equal_nan=True)\n\n for func in ['expand_dims', 'flip', 'sort', 'topk', 'argsort', 'argmax', 'argmin']:\n check_fluent_regular(func, {'axis': 1})\n\n check_fluent_regular('one_hot', {'depth': 15})\n check_fluent_regular('tile', {'reps': (1,2)})\n check_fluent_regular('repeat', {'repeats': 3})\n check_fluent_regular('transpose', {'axes': (1,0,2)})\n check_fluent_regular('split', {'axis': 2, 'num_outputs': 3}, shape=(5, 17, 6))\n check_fluent_regular('slice', {'begin': (2, 5, 1), 'end': (4, 7, 6)}, shape=(5, 17, 6))\n check_fluent_regular('slice_axis', {'axis': 1, 'begin': 5, 'end': 7})\n check_fluent_regular('slice_like', {'axes': (0, -2), 'shape_like': mx.sym.zeros((3, 3))})\n check_fluent_regular('clip', {'a_min': 0.25, 'a_max': 0.75})\n check_fluent_regular('broadcast_axes', {'axis': (2,), 'size': (5,)})\n check_fluent_regular('broadcast_like', {'rhs': mx.sym.ones((1, 5)), 'lhs_axes': (0,), 'rhs_axes': (1,)}, shape=(1,9))\n check_fluent_regular('pad', {'mode': 'constant', 'pad_width': (0,0,0,0,3,0,0,4)}, shape=(5, 17, 2, 3))\n check_fluent_regular('reshape_like', {'rhs': mx.sym.ones((30, 17))}, shape=(5, 17, 2, 3))\n\n for func in ['sum', 'nansum', 'prod', 'nanprod', 'mean', 'max', 'min', 'norm']:\n check_fluent_regular(func, {'axis': (1, 2)})\n\n check_fluent_regular('reshape', {'shape': (17, 1, 5)})\n check_fluent_regular('broadcast_to', {'shape': (5, 17, 47)})\n check_fluent_regular('squeeze', {'axis': (1, 3)}, shape=(2, 1, 3, 1, 4))\n check_fluent_regular('squeeze', {}, shape=(2, 1, 3, 1, 4))\n\ndef check_symbol_consistency(sym1, sym2, ctx, skip_grad=False, equal_nan=False):\n assert sym1.list_arguments() == sym2.list_arguments()\n assert sym1.list_auxiliary_states() == sym2.list_auxiliary_states()\n assert sym1.list_outputs() == sym2.list_outputs()\n\n mx.test_utils.check_consistency([sym1, sym2], ctx_list=[ctx, ctx],\n grad_req='null' if skip_grad else 'write',\n equal_nan=equal_nan)\n\ndef test_blockgrad():\n a = mx.sym.Variable('a')\n b = mx.sym.BlockGrad(2*a)\n exe = b._simple_bind(ctx=mx.cpu(), a=(10,10))\n\n\ndef test_zero_prop2():\n x = mx.sym.Variable('x')\n idx = mx.sym.Variable('idx')\n y = mx.sym.batch_take(x, idx)\n z = mx.sym.stop_gradient(y)\n exe = z._simple_bind(ctx=mx.cpu(), x=(10, 10), idx=(10,),\n type_dict={'x': np.float32, 'idx': np.int32})\n exe.forward(is_train=True)\n exe.backward()\n mx.nd.waitall()\n\n\ndef test_simple_bind_incomplete_shape_inference_in_one_forward_pass():\n r\"\"\"This is a special case that results in shape inference\n failure after moving _simple_bind logic from frontend to backend.\n Added here for testing against the network similar to the following one.\n\n Network diagram:\n weight --> abs_op --> sum_op --\n \\ |--> add_op\n data --> fc_op --> sum_op --\n\n Given data's shape, if the shape inference starts from weight node,\n then the node entries of negative_op and sum_op are unknown in the\n forward pass. Therefore, there are several unknown shapes after the\n first forward pass is done. Now the backward inference pass starts with\n the assumption that there are no unknown-shape node entries in the forward\n pass, and consequently, leads to CHECK_EQ failure.\n \"\"\"\n data_shape = (5, 13)\n data = mx.sym.Variable('data')\n fc = mx.sym.FullyConnected(data=data, num_hidden=1, no_bias=True, name='fc')\n modified_weight = mx.sym.abs(fc.get_internals()['fc_weight'])\n net = mx.sym.sum(modified_weight) + mx.sym.sum(fc)\n net._simple_bind(ctx=mx.cpu(), data=data_shape)\n\n\ndef test_simple_bind_gradient_graph_possible_with_cycle():\n \"\"\"This is a special case that results in a cycle in the gradient graph\n before this bug was fixed. With the following symbol, the node entries\n passed into function AggregateGradient(std::vector<nnvm::NodeEntry>&& v)\n are the outputs of the same node. Therefore, adding a node to the\n control_deps of itself must be skipped.\n See GitHub issue:\n https://github.com/apache/incubator-mxnet/issues/8029\n for more details.\"\"\"\n data = mx.symbol.Variable('data')\n res = data + data + data + data + data + data + data + data\n res._simple_bind(ctx=mx.cpu(), data=(1,))\n\ndef test_children_same_name():\n a = mx.sym.Variable('data')\n b = a + a\n for c in b.get_children():\n pass\n\ndef test_transpose_nullop():\n for dim in range(1, 7):\n a = mx.sym.Variable('a')\n b = mx.sym.transpose(a, axes=tuple(np.random.permutation(dim)))\n c = mx.sym.zeros_like(b)\n\n shape = rand_shape_nd(dim)\n nd_a = mx.nd.random.normal(shape=shape)\n c_out = c.eval(ctx=mx.cpu(), a=nd_a)\n b_out = b.eval(ctx=mx.cpu(), a=nd_a)\n\n assert mx.test_utils.same(c_out[0].asnumpy(),\n np.zeros_like(b_out[0].asnumpy()))\n\n\ndef test_gen_atomic_symbol_multiple_outputs():\n data=mx.sym.Variable('data')\n p = mx.sym.Variable('param')\n h0 = mx.sym.Variable('h0')\n h1 = mx.sym.Variable('h1')\n s = mx.sym.RNN(data, p, h0, h1, state_size=10, num_layers=2,\n bidirectional=True, state_outputs=True, mode='lstm')\n atomic_sym = s._gen_atomic_symbol()\n\n\ndef test_eliminate_common_expr():\n if not sys.platform.startswith('linux'):\n logging.info(\"Bypass the CSE test on non-Linux OS as setting env variables during test does not work on Windows\")\n return\n def set_back_env_var(var_name, old_env_var):\n if old_env_var is None:\n os.environ.pop(var_name)\n else:\n os.environ[var_name] = old_env_var\n\n # helper function to test a single model\n def check_cse_on_symbol(sym, expected_savings, check_data, **kwargs):\n inputs = sym.list_inputs()\n shapes = {inp : kwargs[inp].shape for inp in inputs}\n rtol = {'float16' : 1e-2,\n 'float32' : 1.5e-6,\n 'float64' : 1.5e-6,\n }\n atol = {'float16' : 1e-3,\n 'float32' : 1e-7,\n 'float64' : 1e-7,\n }\n env_var_name = 'MXNET_ELIMINATE_COMMON_EXPR'\n old_env_var = os.environ.get(env_var_name, None)\n try:\n for dtype in ['float16', 'float32', 'float64']:\n data = {inp : kwargs[inp].astype(dtype) for inp in inputs}\n for grad_req in ['write', 'add']:\n type_dict = {inp : dtype for inp in inputs}\n os.environ[env_var_name] = '0'\n orig_exec = sym._simple_bind(ctx=mx.cpu(0), grad_req=grad_req,\n type_dict=type_dict, **shapes)\n os.environ[env_var_name] = '1'\n cse_exec = sym._simple_bind(ctx=mx.cpu(0), grad_req=grad_req,\n type_dict=type_dict, **shapes)\n fwd_orig = orig_exec.forward(is_train=True, **data)\n out_grads = [mx.nd.ones_like(arr) for arr in fwd_orig]\n orig_exec.backward(out_grads=out_grads)\n fwd_cse = cse_exec.forward(is_train=True, **data)\n cse_exec.backward(out_grads=out_grads)\n if check_data:\n for orig, cse in zip(fwd_orig, fwd_cse):\n np.testing.assert_allclose(orig.asnumpy(), cse.asnumpy(),\n rtol=rtol[dtype], atol=atol[dtype])\n for orig, cse in zip(orig_exec.grad_arrays, cse_exec.grad_arrays):\n if orig is None and cse is None:\n continue\n assert orig is not None\n assert cse is not None\n np.testing.assert_allclose(orig.asnumpy(), cse.asnumpy(),\n rtol=rtol[dtype], atol=atol[dtype])\n orig_sym_internals = orig_exec.get_optimized_symbol().get_internals()\n cse_sym_internals = cse_exec.get_optimized_symbol().get_internals()\n # test that the graph has been simplified as expected\n assert (len(cse_sym_internals) + expected_savings) == len(orig_sym_internals)\n finally:\n set_back_env_var(env_var_name, old_env_var)\n\n a = mx.sym.Variable('a')\n b = mx.sym.Variable('b')\n c = mx.sym.Variable('c')\n shape = rand_shape_nd(2)\n arr1 = mx.random.uniform(shape=shape)\n arr2 = mx.random.uniform(shape=shape)\n arr3 = mx.random.uniform(shape=shape)\n\n check_cse_on_symbol((a+1) + (a+2), expected_savings=0, check_data=True, a=arr1, b=arr2)\n check_cse_on_symbol((a+b) + (a+b), expected_savings=1, check_data=True, a=arr1, b=arr2)\n check_cse_on_symbol(((a+b)+c) +((a+b)+c), expected_savings=2, check_data=True,\n a=arr1, b=arr2, c=arr3)\n d = a + 1\n\n # a*d node gets eliminated, but then a copy is inserted to isolate the outputs, so no net gain.\n check_cse_on_symbol(mx.sym.Group([a*d, a*d]), expected_savings=0, check_data=True, a=arr1)\n\n # a*d node gets eliminated, then the duplicated add-of-b, but then a copy is added for net of 1.\n check_cse_on_symbol(mx.sym.Group([a*d+b, a*d+b]), expected_savings=1, check_data=True,\n a=arr1, b=arr2)\n\n # dropout uses a resource that precludes any optimization\n check_cse_on_symbol(mx.sym.Dropout(a) +\n mx.sym.Dropout(a), expected_savings=0, check_data=False, a=arr1)\n\ndef test_load_save_symbol():\n batch_size = 10\n num_hdidden = 128\n num_features = 784\n\n def get_net():\n data = mx.sym.var('data')\n weight = mx.sym.var('weight', shape=(num_hdidden, 0))\n return mx.sym.FullyConnected(data, weight, num_hidden=num_hdidden)\n\n for flag1 in [False, True]:\n with np_shape(flag1):\n net_json_str = get_net().tojson()\n net_data = json.loads(net_json_str)\n assert \"attrs\" in net_data\n if flag1:\n assert \"is_np_shape\" in net_data[\"attrs\"]\n else:\n assert \"is_np_shape\" not in net_data[\"attrs\"]\n\n with TemporaryDirectory() as work_dir:\n fname = os.path.join(work_dir, 'test_sym.json')\n with open(fname, 'w') as fp:\n json.dump(net_data, fp)\n\n # test loading 1.5.0 symbol file since 1.6.0\n # w/ or w/o np_shape semantics\n for flag2 in [False, True]:\n if flag1: # Do not need to test this case since 0 indicates zero-size dim\n continue\n with np_shape(flag2):\n net = mx.sym.load(fname)\n arg_shapes, out_shapes, aux_shapes = net.infer_shape(data=(batch_size, num_features))\n assert arg_shapes[0] == (batch_size, num_features) # data\n assert arg_shapes[1] == (num_hdidden, num_features) # weight\n assert arg_shapes[2] == (num_hdidden,) # bias\n assert out_shapes[0] == (batch_size, num_hdidden) # output\n assert len(aux_shapes) == 0\n\ndef test_infershape_happens_for_all_ops_in_graph():\n v = mx.sym.Variable('V')\n s = mx.sym.transpose(v)\n x = mx.sym.Variable('x')\n s2 = x + v\n s3 = s + s2\n with discard_stderr():\n try:\n # This should throw an exception as you cannot add arrays\n # with shapes [2,3] and [3,2]\n e = s3._simple_bind(ctx=mx.cpu(), x=(2,3), grad_req='null')\n except:\n return\n\n assert False\n\n" ]
[ [ "numpy.random.permutation" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shuva10v/airflow
[ "caadbc1618d73e054de99138b0892cea3a9327c4" ]
[ "airflow/contrib/hooks/salesforce_hook.py" ]
[ "# -*- coding: utf-8 -*-\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\"\"\"\nThis module contains a Salesforce Hook which allows you to connect to your Salesforce instance,\nretrieve data from it, and write that data to a file for other uses.\n\n.. note:: this hook also relies on the simple_salesforce package:\n https://github.com/simple-salesforce/simple-salesforce\n\"\"\"\nimport time\n\nimport pandas as pd\nfrom simple_salesforce import Salesforce\n\nfrom airflow.hooks.base_hook import BaseHook\nfrom airflow.utils.log.logging_mixin import LoggingMixin\n\n\nclass SalesforceHook(BaseHook):\n\n def __init__(self, conn_id):\n \"\"\"\n Create new connection to Salesforce and allows you to pull data out of SFDC and save it to a file.\n\n You can then use that file with other Airflow operators to move the data into another data source.\n\n :param conn_id: the name of the connection that has the parameters we need to connect to Salesforce.\n The connection should be type `http` and include a user's security token in the `Extras` field.\n :type conn_id: str\n\n .. note::\n For the HTTP connection type, you can include a\n JSON structure in the `Extras` field.\n We need a user's security token to connect to Salesforce.\n So we define it in the `Extras` field as:\n `{\"security_token\":\"YOUR_SECURITY_TOKEN\"}`\n\n \"\"\"\n super().__init__(conn_id)\n self.conn_id = conn_id\n self.conn = None\n\n def get_conn(self):\n \"\"\"\n Sign into Salesforce, only if we are not already signed in.\n \"\"\"\n if not self.conn:\n connection = self.get_connection(self.conn_id)\n extras = connection.extra_dejson\n self.conn = Salesforce(\n username=connection.login,\n password=connection.password,\n security_token=extras['security_token'],\n instance_url=connection.host,\n sandbox=extras.get('sandbox', False)\n )\n return self.conn\n\n def make_query(self, query):\n \"\"\"\n Make a query to Salesforce.\n\n :param query: The query to make to Salesforce.\n :type query: str\n :return: The query result.\n :rtype: dict\n \"\"\"\n conn = self.get_conn()\n\n self.log.info(\"Querying for all objects\")\n query_results = conn.query_all(query)\n\n self.log.info(\"Received results: Total size: %s; Done: %s\",\n query_results['totalSize'], query_results['done'])\n\n return query_results\n\n def describe_object(self, obj):\n \"\"\"\n Get the description of an object from Salesforce.\n This description is the object's schema and\n some extra metadata that Salesforce stores for each object.\n\n :param obj: The name of the Salesforce object that we are getting a description of.\n :type obj: str\n :return: the description of the Salesforce object.\n :rtype: dict\n \"\"\"\n conn = self.get_conn()\n\n return conn.__getattr__(obj).describe()\n\n def get_available_fields(self, obj):\n \"\"\"\n Get a list of all available fields for an object.\n\n :param obj: The name of the Salesforce object that we are getting a description of.\n :type obj: str\n :return: the names of the fields.\n :rtype: list of str\n \"\"\"\n self.get_conn()\n\n obj_description = self.describe_object(obj)\n\n return [field['name'] for field in obj_description['fields']]\n\n def get_object_from_salesforce(self, obj, fields):\n \"\"\"\n Get all instances of the `object` from Salesforce.\n For each model, only get the fields specified in fields.\n\n All we really do underneath the hood is run:\n SELECT <fields> FROM <obj>;\n\n :param obj: The object name to get from Salesforce.\n :type obj: str\n :param fields: The fields to get from the object.\n :type fields: iterable\n :return: all instances of the object from Salesforce.\n :rtype: dict\n \"\"\"\n query = \"SELECT {} FROM {}\".format(\",\".join(fields), obj)\n\n self.log.info(\"Making query to Salesforce: %s\",\n query if len(query) < 30 else \" ... \".join([query[:15], query[-15:]]))\n\n return self.make_query(query)\n\n @classmethod\n def _to_timestamp(cls, column):\n \"\"\"\n Convert a column of a dataframe to UNIX timestamps if applicable\n\n :param column: A Series object representing a column of a dataframe.\n :type column: pd.Series\n :return: a new series that maintains the same index as the original\n :rtype: pd.Series\n \"\"\"\n # try and convert the column to datetimes\n # the column MUST have a four digit year somewhere in the string\n # there should be a better way to do this,\n # but just letting pandas try and convert every column without a format\n # caused it to convert floats as well\n # For example, a column of integers\n # between 0 and 10 are turned into timestamps\n # if the column cannot be converted,\n # just return the original column untouched\n try:\n column = pd.to_datetime(column)\n except ValueError:\n log = LoggingMixin().log\n log.warning(\"Could not convert field to timestamps: %s\", column.name)\n return column\n\n # now convert the newly created datetimes into timestamps\n # we have to be careful here\n # because NaT cannot be converted to a timestamp\n # so we have to return NaN\n converted = []\n for value in column:\n try:\n converted.append(value.timestamp())\n except (ValueError, AttributeError):\n converted.append(pd.np.NaN)\n\n return pd.Series(converted, index=column.index)\n\n def write_object_to_file(self,\n query_results,\n filename,\n fmt=\"csv\",\n coerce_to_timestamp=False,\n record_time_added=False):\n \"\"\"\n Write query results to file.\n\n Acceptable formats are:\n - csv:\n comma-separated-values file. This is the default format.\n - json:\n JSON array. Each element in the array is a different row.\n - ndjson:\n JSON array but each element is new-line delimited instead of comma delimited like in `json`\n\n This requires a significant amount of cleanup.\n Pandas doesn't handle output to CSV and json in a uniform way.\n This is especially painful for datetime types.\n Pandas wants to write them as strings in CSV, but as millisecond Unix timestamps.\n\n By default, this function will try and leave all values as they are represented in Salesforce.\n You use the `coerce_to_timestamp` flag to force all datetimes to become Unix timestamps (UTC).\n This is can be greatly beneficial as it will make all of your datetime fields look the same,\n and makes it easier to work with in other database environments\n\n :param query_results: the results from a SQL query\n :type query_results: list of dict\n :param filename: the name of the file where the data should be dumped to\n :type filename: str\n :param fmt: the format you want the output in. Default: 'csv'\n :type fmt: str\n :param coerce_to_timestamp: True if you want all datetime fields to be converted into Unix timestamps.\n False if you want them to be left in the same format as they were in Salesforce.\n Leaving the value as False will result in datetimes being strings. Default: False\n :type coerce_to_timestamp: bool\n :param record_time_added: True if you want to add a Unix timestamp field\n to the resulting data that marks when the data was fetched from Salesforce. Default: False\n :type record_time_added: bool\n :return: the dataframe that gets written to the file.\n :rtype: pd.Dataframe\n \"\"\"\n fmt = fmt.lower()\n if fmt not in ['csv', 'json', 'ndjson']:\n raise ValueError(\"Format value is not recognized: {}\".format(fmt))\n\n # this line right here will convert all integers to floats\n # if there are any None/np.nan values in the column\n # that's because None/np.nan cannot exist in an integer column\n # we should write all of our timestamps as FLOATS in our final schema\n df = pd.DataFrame.from_records(query_results, exclude=[\"attributes\"])\n\n df.columns = [column.lower() for column in df.columns]\n\n # convert columns with datetime strings to datetimes\n # not all strings will be datetimes, so we ignore any errors that occur\n # we get the object's definition at this point and only consider\n # features that are DATE or DATETIME\n if coerce_to_timestamp and df.shape[0] > 0:\n # get the object name out of the query results\n # it's stored in the \"attributes\" dictionary\n # for each returned record\n object_name = query_results[0]['attributes']['type']\n\n self.log.info(\"Coercing timestamps for: %s\", object_name)\n\n schema = self.describe_object(object_name)\n\n # possible columns that can be converted to timestamps\n # are the ones that are either date or datetime types\n # strings are too general and we risk unintentional conversion\n possible_timestamp_cols = [\n field['name'].lower()\n for field in schema['fields']\n if field['type'] in [\"date\", \"datetime\"] and field['name'].lower() in df.columns\n ]\n df[possible_timestamp_cols] = df[possible_timestamp_cols].apply(self._to_timestamp)\n\n if record_time_added:\n fetched_time = time.time()\n df[\"time_fetched_from_salesforce\"] = fetched_time\n\n # write the CSV or JSON file depending on the option\n # NOTE:\n # datetimes here are an issue.\n # There is no good way to manage the difference\n # for to_json, the options are an epoch or a ISO string\n # but for to_csv, it will be a string output by datetime\n # For JSON we decided to output the epoch timestamp in seconds\n # (as is fairly standard for JavaScript)\n # And for csv, we do a string\n if fmt == \"csv\":\n # there are also a ton of newline objects that mess up our ability to write to csv\n # we remove these newlines so that the output is a valid CSV format\n self.log.info(\"Cleaning data and writing to CSV\")\n possible_strings = df.columns[df.dtypes == \"object\"]\n df[possible_strings] = df[possible_strings].apply(\n lambda x: x.str.replace(\"\\r\\n\", \"\").str.replace(\"\\n\", \"\")\n )\n # write the dataframe\n df.to_csv(filename, index=False)\n elif fmt == \"json\":\n df.to_json(filename, \"records\", date_unit=\"s\")\n elif fmt == \"ndjson\":\n df.to_json(filename, \"records\", lines=True, date_unit=\"s\")\n\n return df\n" ]
[ [ "pandas.DataFrame.from_records", "pandas.to_datetime", "pandas.Series" ] ]
[ { "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": [] } ]
ch-shin/nlp-tutorial
[ "8b05db81daa98fae519bbe652f4b4e6b8cb8777a" ]
[ "5-1.Transformer/Transformer(Greedy_decoder)-Torch.py" ]
[ "'''\n code by Tae Hwan Jung(Jeff Jung) @graykode, Derek Miller @dmmiller612\n Reference : https://github.com/jadore801120/attention-is-all-you-need-pytorch\n https://github.com/JayParks/transformer\n'''\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\n\ndtype = torch.FloatTensor\n# S: Symbol that shows starting of decoding input\n# E: Symbol that shows starting of decoding output\n# P: Symbol that will fill in blank sequence if current batch data size is short than time steps\nsentences = ['ich mochte ein bier P', 'S i want a beer', 'i want a beer E']\n\n# Transformer Parameters\nsrc_vocab = {w: i for i, w in enumerate(sentences[0].split())}\nsrc_vocab_size = len(src_vocab)\ntgt_vocab = {w: i for i, w in enumerate(set((sentences[1]+' '+sentences[2]).split()))}\nnumber_dict = {i: w for i, w in enumerate(set((sentences[1]+' '+sentences[2]).split()))}\ntgt_vocab_size = len(tgt_vocab)\n\nsrc_len = 5\ntgt_len = 5\n\nd_model = 512 # Embedding Size\nd_ff = 2048 # FeedForward dimension\nd_k = d_v = 64 # dimension of K(=Q), V\nn_layers = 6 # number of Encoder of Decoder Layer\nn_heads = 8 # number of heads in Multi-Head Attention\n\ndef make_batch(sentences):\n input_batch = [[src_vocab[n] for n in sentences[0].split()]]\n output_batch = [[tgt_vocab[n] for n in sentences[1].split()]]\n target_batch = [[tgt_vocab[n] for n in sentences[2].split()]]\n return Variable(torch.LongTensor(input_batch)), Variable(torch.LongTensor(output_batch)), Variable(torch.LongTensor(target_batch))\n\ndef get_sinusoid_encoding_table(n_position, d_model):\n def cal_angle(position, hid_idx):\n return position / np.power(10000, 2 * (hid_idx // 2) / d_model)\n def get_posi_angle_vec(position):\n return [cal_angle(position, hid_j) for hid_j in range(d_model)]\n\n sinusoid_table = np.array([get_posi_angle_vec(pos_i) for pos_i in range(n_position)])\n sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i\n sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1\n return torch.FloatTensor(sinusoid_table)\n\ndef get_attn_pad_mask(seq_q, seq_k):\n batch_size, len_q = seq_q.size()\n batch_size, len_k = seq_k.size()\n pad_attn_mask = seq_k.data.eq(0).unsqueeze(1) # batch_size x 1 x len_k(=len_q)\n return pad_attn_mask.expand(batch_size, len_q, len_k) # batch_size x len_q x len_k\n\nclass ScaledDotProductAttention(nn.Module):\n\n def __init__(self):\n super(ScaledDotProductAttention, self).__init__()\n\n def forward(self, Q, K, V, attn_mask=None):\n scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size x n_heads x len_q(=len_k) x len_k(=len_q)]\n if attn_mask is not None:\n scores.masked_fill_(attn_mask, -1e9)\n attn = nn.Softmax(dim=-1)(scores)\n context = torch.matmul(attn, V)\n return context, attn\n\nclass MultiHeadAttention(nn.Module):\n\n def __init__(self):\n super(MultiHeadAttention, self).__init__()\n self.W_Q = nn.Linear(d_model, d_k * n_heads)\n self.W_K = nn.Linear(d_model, d_k * n_heads)\n self.W_V = nn.Linear(d_model, d_v * n_heads)\n\n def forward(self, Q, K, V, attn_mask=None):\n # q: [batch_size x len_q x d_model], k: [batch_size x len_k x d_model], v: [batch_size x len_k x d_model]\n residual, batch_size = Q, Q.size(0)\n # (B, S, D) -proj-> (B, S, D) -split-> (B, S, H, W) -trans-> (B, H, S, W)\n q_s = self.W_Q(Q).view(batch_size, -1, n_heads, d_k).transpose(1,2) # q_s: [batch_size x n_heads x len_q x d_k]\n k_s = self.W_K(K).view(batch_size, -1, n_heads, d_k).transpose(1,2) # k_s: [batch_size x n_heads x len_k x d_k]\n v_s = self.W_V(V).view(batch_size, -1, n_heads, d_v).transpose(1,2) # v_s: [batch_size x n_heads x len_k x d_v]\n\n if attn_mask is not None: # attn_mask : [batch_size x len_q x len_k]\n attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) # attn_mask : [batch_size x n_heads x len_q x len_k]\n # context: [batch_size x n_heads x len_q x d_v], attn: [batch_size x n_heads x len_q(=len_k) x len_k(=len_q)]\n context, attn = ScaledDotProductAttention()(q_s, k_s, v_s, attn_mask=attn_mask)\n context = context.transpose(1, 2).contiguous().view(batch_size, -1, n_heads * d_v) # context: [batch_size x len_q x n_heads * d_v]\n output = nn.Linear(n_heads * d_v, d_model)(context)\n return nn.LayerNorm(d_model)(output + residual), attn # output: [batch_size x len_q x d_model]\n\nclass PoswiseFeedForwardNet(nn.Module):\n\n def __init__(self):\n super(PoswiseFeedForwardNet, self).__init__()\n self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=1)\n self.conv2 = nn.Conv1d(in_channels=d_ff, out_channels=d_model, kernel_size=1)\n\n def forward(self, inputs):\n residual = inputs # inputs : [batch_size, len_q, d_model]\n output = nn.ReLU()(self.conv1(inputs.transpose(1, 2)))\n output = self.conv2(output).transpose(1, 2)\n return nn.LayerNorm(d_model)(output + residual)\n\nclass EncoderLayer(nn.Module):\n\n def __init__(self):\n super(EncoderLayer, self).__init__()\n self.enc_self_attn = MultiHeadAttention()\n self.pos_ffn = PoswiseFeedForwardNet()\n\n def forward(self, enc_inputs):\n enc_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs) # enc_inputs to same Q,K,V\n enc_outputs = self.pos_ffn(enc_outputs) # enc_outputs: [batch_size x len_q x d_model]\n return enc_outputs, attn\n\nclass DecoderLayer(nn.Module):\n\n def __init__(self):\n super(DecoderLayer, self).__init__()\n self.dec_self_attn = MultiHeadAttention()\n self.dec_enc_attn = MultiHeadAttention()\n self.pos_ffn = PoswiseFeedForwardNet()\n\n def forward(self, dec_inputs, enc_outputs, enc_attn_mask, dec_attn_mask=None):\n dec_outputs, dec_self_attn = self.dec_self_attn(dec_inputs, dec_inputs, dec_inputs, dec_attn_mask)\n dec_outputs, dec_enc_attn = self.dec_enc_attn(dec_outputs, enc_outputs, enc_outputs, enc_attn_mask)\n dec_outputs = self.pos_ffn(dec_outputs)\n return dec_outputs, dec_self_attn, dec_enc_attn\n\nclass Encoder(nn.Module):\n\n def __init__(self):\n super(Encoder, self).__init__()\n self.src_emb = nn.Embedding(src_vocab_size, d_model)\n self.pos_emb = nn.Embedding.from_pretrained(get_sinusoid_encoding_table(src_len+1 , d_model),freeze=True)\n self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)])\n\n def forward(self, enc_inputs): # enc_inputs : [batch_size x source_len]\n enc_outputs = self.src_emb(enc_inputs) + self.pos_emb(torch.LongTensor([[1,2,3,4,5]]))\n enc_self_attns = []\n for layer in self.layers:\n enc_outputs, enc_self_attn = layer(enc_outputs)\n enc_self_attns.append(enc_self_attn)\n return enc_outputs, enc_self_attns\n\nclass Decoder(nn.Module):\n\n def __init__(self):\n super(Decoder, self).__init__()\n self.tgt_emb = nn.Embedding(tgt_vocab_size, d_model)\n self.pos_emb = nn.Embedding.from_pretrained(get_sinusoid_encoding_table(tgt_len+1 , d_model),freeze=True)\n self.layers = nn.ModuleList([DecoderLayer() for _ in range(n_layers)])\n\n def forward(self, dec_inputs, enc_inputs, enc_outputs, dec_attn_mask=None): # dec_inputs : [batch_size x target_len]\n dec_outputs = self.tgt_emb(dec_inputs) + self.pos_emb(torch.LongTensor([[1,2,3,4,5]]))\n dec_enc_attn_pad_mask = get_attn_pad_mask(dec_inputs, enc_inputs)\n\n dec_self_attns, dec_enc_attns = [], []\n for layer in self.layers:\n dec_outputs, dec_self_attn, dec_enc_attn = layer(dec_outputs, enc_outputs,\n enc_attn_mask=dec_enc_attn_pad_mask,\n dec_attn_mask=dec_attn_mask)\n dec_self_attns.append(dec_self_attn)\n dec_enc_attns.append(dec_enc_attn)\n return dec_outputs, dec_self_attns, dec_enc_attns\n\nclass Transformer(nn.Module):\n\n def __init__(self):\n super(Transformer, self).__init__()\n self.encoder = Encoder()\n self.decoder = Decoder()\n self.projection = nn.Linear(d_model, tgt_vocab_size, bias=False)\n\n def forward(self, enc_inputs, dec_inputs, decoder_mask=None):\n enc_outputs, enc_self_attns = self.encoder(enc_inputs)\n dec_outputs, dec_self_attns, dec_enc_attns = self.decoder(dec_inputs, enc_inputs, enc_outputs, decoder_mask)\n dec_logits = self.projection(dec_outputs) # dec_logits : [batch_size x src_vocab_size x tgt_vocab_size]\n return dec_logits.view(-1, dec_logits.size(-1)), enc_self_attns, dec_self_attns, dec_enc_attns\n\ndef greedy_decoder(model, enc_input, start_symbol):\n \"\"\"\n For simplicity, a Greedy Decoder is Beam search when K=1. This is necessary for inference as we don't know the\n target sequence input. Therefore we try to generate the target input word by word, then feed it into the transformer.\n Starting Reference: http://nlp.seas.harvard.edu/2018/04/03/attention.html#greedy-decoding\n :param model: Transformer Model\n :param enc_input: The encoder input\n :param start_symbol: The start symbol. In this example it is 'S' which corresponds to index 4\n :return: The target input\n \"\"\"\n memory, attention = model.encoder(enc_input)\n dec_input = torch.ones(1, 5).fill_(0).type_as(enc_input.data)\n dec_mask = torch.from_numpy(np.triu(np.ones((1, 5, 5)), 1).astype('uint8')) == 0\n next_symbol = start_symbol\n for i in range(0, 5):\n dec_input[0][i] = next_symbol\n out = model.decoder(Variable(dec_input), enc_input, memory, dec_mask)\n projected = model.projection(out[0])\n prob = projected.view(-1, projected.size(-1))\n prob = prob.data.max(1, keepdim=True)[1]\n next_word = prob.data[i]\n next_symbol = next_word[0]\n return dec_input\n\ndef showgraph(attn):\n attn = attn[-1].squeeze(0)[0]\n attn = attn.squeeze(0).data.numpy()\n fig = plt.figure(figsize=(n_heads, n_heads)) # [n_heads, n_heads]\n ax = fig.add_subplot(1, 1, 1)\n ax.matshow(attn, cmap='viridis')\n ax.set_xticklabels(['']+sentences[0].split(), fontdict={'fontsize': 14}, rotation=90)\n ax.set_yticklabels(['']+sentences[2].split(), fontdict={'fontsize': 14})\n plt.show()\n\nmodel = Transformer()\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n\nfor epoch in range(100):\n\toptimizer.zero_grad()\n\tenc_inputs, dec_inputs, target_batch = make_batch(sentences)\n\toutputs, enc_self_attns, dec_self_attns, dec_enc_attns = model(enc_inputs, dec_inputs)\n\tloss = criterion(outputs, target_batch.contiguous().view(-1))\n\tif (epoch + 1) % 20 == 0:\n\t\tprint('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(loss))\n\tloss.backward()\n\toptimizer.step()\n\n# Test\ngreedy_dec_input = greedy_decoder(model, enc_inputs, start_symbol=4)\npredict, _, _, _ = model(enc_inputs, greedy_dec_input)\npredict = predict.data.max(1, keepdim=True)[1]\nprint(sentences[0], '->', [number_dict[n.item()] for n in predict.squeeze()])\n\nprint('first head of last state enc_self_attns')\nshowgraph(enc_self_attns)\n\nprint('first head of last state dec_self_attns')\nshowgraph(dec_self_attns)\n\nprint('first head of last state dec_enc_attns')\nshowgraph(dec_enc_attns)" ]
[ [ "torch.nn.Softmax", "numpy.sqrt", "torch.nn.Embedding", "torch.FloatTensor", "torch.autograd.Variable", "torch.nn.CrossEntropyLoss", "torch.ones", "numpy.sin", "matplotlib.pyplot.figure", "torch.LongTensor", "numpy.power", "torch.nn.Linear", "torch.nn.Conv1d", "matplotlib.pyplot.show", "numpy.cos", "torch.nn.LayerNorm", "numpy.ones", "torch.matmul", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EmanueleGhelfi/tensorflow
[ "d4ddccd3cca4fc837c66ae1dfa190739420ad122" ]
[ "tensorflow/python/distribute/values.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Various classes representing distributed values.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport contextlib\nimport operator\nimport weakref\nimport six\n\nfrom tensorflow.python.data.experimental.ops import batching\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import multi_device_iterator_ops\nfrom tensorflow.python.distribute import device_util\nfrom tensorflow.python.distribute import distribute_lib\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.distribute import input_ops\nfrom tensorflow.python.distribute import reduce_util\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import tape\nfrom tensorflow.python.framework import device as tf_device\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_resource_variable_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.training import saver\nfrom tensorflow.python.training.checkpointable import base as checkpointable\nfrom tensorflow.python.util import nest\n\n\ndef _devices_match(d1, d2):\n return device_util.canonicalize(d1) == device_util.canonicalize(d2)\n\n\nclass DeviceMap(object):\n \"\"\"A mapping of replicas & logical device ids to devices.\"\"\"\n\n @property\n def all_devices(self):\n \"\"\"Returns a tuple of strings with all devices in this DeviceMap.\"\"\"\n raise NotImplementedError(\"Required for DeviceMap implementations.\")\n\n @property\n def devices_by_replica(self):\n \"\"\"Returns a tuple `t` where `t[replica]` is the devices for `replica`.\"\"\"\n raise NotImplementedError(\"Required for DeviceMap implementations.\")\n\n @property\n def num_logical_devices(self):\n \"\"\"Count of the number of devices each replica may be defined across.\"\"\"\n raise NotImplementedError(\"Required for DeviceMap implementations.\")\n\n @property\n def num_replicas_in_graph(self):\n \"\"\"Number of replicas defined in this graph.\"\"\"\n raise NotImplementedError(\"Required for DeviceMap implementations.\")\n\n def logical_device_from_values(self, values):\n \"\"\"Returns the logical device index `values` is on.\"\"\"\n raise NotImplementedError(\"Required for DeviceMap implementations.\")\n\n def logical_to_actual_devices(self, logical_device_id):\n \"\"\"Returns sequence of `num_replicas_in_graph` devices.\"\"\"\n raise NotImplementedError(\"Required for DeviceMap implementations.\")\n\n def select_for_current_replica(self, values, replica_context):\n \"\"\"Select the element of `values` for the current replica.\"\"\"\n raise NotImplementedError(\"Required for DeviceMap implementations.\")\n\n def replica_for_device(self, device):\n \"\"\"Return the replica id containing `device`.\"\"\"\n raise NotImplementedError(\"Required for DeviceMap implementations.\")\n\n def select_for_device(self, values, device):\n \"\"\"Select the element of `values` to access from `device`.\"\"\"\n raise NotImplementedError(\"Required for DeviceMap implementations.\")\n\n def is_device_in_replica(self, device, replica_id):\n \"\"\"Returns whether `device` is a member of replica `replica_id`.\"\"\"\n raise NotImplementedError(\"Required for DeviceMap implementations.\")\n\n\nclass SingleDeviceMap(DeviceMap):\n \"\"\"A device map for 1 non-computation device.\n\n Use `SingleDeviceMap` when the device does not correspond to some replica of\n the computation. For computation devices, use `ReplicaDeviceMap` below (even\n if there is only a single device in the map).\n \"\"\"\n\n def __init__(self, device):\n \"\"\"Initialize a `SingleDeviceMap`.\n\n Args:\n device: A string device.\n \"\"\"\n assert isinstance(device, six.string_types)\n self._device = device_util.canonicalize(device)\n self._devices = (self._device,)\n\n @property\n def all_devices(self):\n return self._devices\n\n @property\n def devices_by_replica(self):\n raise ValueError(\"SingleDeviceMap not indexed by replicas\")\n\n @property\n def num_logical_devices(self):\n return 1\n\n @property\n def num_replicas_in_graph(self):\n return 1\n\n def logical_device_from_values(self, values):\n del values\n return 0\n\n def logical_to_actual_devices(self, logical_device_id):\n assert logical_device_id == 0\n return self._devices\n\n def select_for_current_replica(self, values, replica_context):\n assert len(values) == 1\n del replica_context\n return values[0]\n\n def replica_for_device(self, device):\n raise ValueError(\"SingleDeviceMap not indexed by replicas\")\n\n def select_for_device(self, values, device):\n assert len(values) == 1\n if self._device != device:\n raise ValueError(\"Device %s not found in %s (current device %s)\" %\n (device, self._devices, device_util.current()))\n return values[0]\n\n def is_device_in_replica(self, device, replica_id):\n raise ValueError(\"SingleDeviceMap not indexed by replicas\")\n\n def __repr__(self):\n return \"%s(%r)\" % (self.__class__.__name__, self._device)\n\n\nclass ReplicaDeviceMap(DeviceMap):\n \"\"\"A device map for 1 device per replica.\"\"\"\n\n def __init__(self, devices):\n \"\"\"Initialize a `ReplicaDeviceMap`.\n\n Args:\n devices: `devices[i]` is the string device for replica `i`.\n \"\"\"\n self._devices = tuple(device_util.canonicalize(d) for d in devices)\n if len(set(self._devices)) != len(self._devices):\n raise ValueError(\"Duplicate devices in %s, after canonicalization: %s\" %\n (devices, self._devices))\n self._device_to_replica = {d: r for r, d in enumerate(self._devices)}\n\n @property\n def all_devices(self):\n return self._devices\n\n @property\n def devices_by_replica(self):\n return ((d,) for d in self._devices)\n\n @property\n def num_logical_devices(self):\n return 1\n\n @property\n def num_replicas_in_graph(self):\n return len(self._devices)\n\n def logical_device_from_values(self, values):\n del values\n return 0\n\n def logical_to_actual_devices(self, logical_device_id):\n assert logical_device_id == 0\n return self._devices\n\n def select_for_current_replica(self, values, replica_context):\n assert len(values) == len(self._devices)\n replica_id = replica_context.replica_id_in_sync_group\n if not isinstance(replica_id, int):\n replica_id = tensor_util.constant_value(replica_id)\n return values[replica_id]\n\n def replica_for_device(self, device):\n return self._device_to_replica.get(device)\n\n def select_for_device(self, values, device):\n assert len(values) == len(self._devices)\n replica_id = self._device_to_replica.get(device)\n if replica_id is None:\n raise ValueError(\"Device %s not found in %s (current device %s)\" %\n (device, self._devices, device_util.current()))\n return values[replica_id]\n\n def is_device_in_replica(self, device, replica_id):\n return _devices_match(device, self._devices[replica_id])\n\n def __str__(self):\n return \"[%s]\" % (\", \".join(self._devices))\n\n def __repr__(self):\n return \"%s([%s])\" % (self.__class__.__name__,\n \", \".join(repr(d) for d in self._devices))\n\n\nLogicalDeviceSpec = collections.namedtuple(\n \"LogicalDeviceSpec\", (\"device_map\", \"logical_device\"))\n\n\nclass DistributedValues(object):\n \"\"\"Holds a map from device to values. Either PerReplica or Mirrored.\"\"\"\n\n def __init__(self, device_map, values, logical_device=None):\n assert isinstance(device_map, DeviceMap)\n self._device_map = device_map\n self._values = tuple(values)\n if logical_device is None:\n logical_device = device_map.logical_device_from_values(self._values)\n self._logical_device = logical_device\n\n # TODO(josh11b): Split this into two functions, one with device, one without.\n def get(self, device=None):\n \"\"\"Returns the value for the current device or raises a ValueError.\"\"\"\n if device is None:\n replica_context = distribution_strategy_context.get_replica_context()\n if replica_context:\n return self._device_map.select_for_current_replica(\n self._values, replica_context)\n else:\n device = distribute_lib.get_update_device()\n if device is None:\n return self._get_cross_replica()\n device = device_util.canonicalize(device)\n return self._device_map.select_for_device(self._values, device)\n\n @property\n def primary(self):\n \"\"\"Returns a representative component.\"\"\"\n return self._values[0]\n\n @property\n def devices(self):\n return self._device_map.logical_to_actual_devices(self._logical_device)\n\n @property\n def logical_device(self):\n return self._logical_device\n\n @property\n def device_map(self):\n return self._device_map\n\n # TODO(josh11b): Replace unwrap with this?\n @property\n def values(self):\n return self._values\n\n @property\n def is_tensor_like(self):\n for v in self._values:\n if not tensor_util.is_tensor(v):\n return False\n return True\n\n def __str__(self):\n devices = self.devices\n assert len(self._values) == len(devices)\n debug_str = \",\\n\".join(\" %d %s: %s\" % (i, devices[i], self._values[i])\n for i in range(len(devices)))\n return \"%s:{\\n%s\\n}\" % (self.__class__.__name__, debug_str)\n\n def __repr__(self):\n devices = self.devices\n assert len(self._values) == len(devices)\n debug_repr = \",\\n\".join(\" %d %s: %r\" % (i, devices[i], self._values[i])\n for i in range(len(devices)))\n return \"%s:{\\n%s\\n}\" % (self.__class__.__name__, debug_repr)\n\n\n# NOTE(josh11b,apassos): It would be great if we could inspect the values this was\n# initialized with and use that to generate the overloaded operators here.\n# Unfortunately, Python's rules for special methods don't allow this, see\n# https://docs.python.org/3/reference/datamodel.html#special-method-names\n# \"if a class defines a method named __getitem__(), and x is an instance of\n# this class, then x[i] is roughly equivalent to type(x).__getitem__(x, i).\"\n# In particular, these special methods don't go through __getattr__, and\n# it will only use those methods if they are defined in the class, not the\n# object.\nclass DistributedDelegate(DistributedValues):\n \"\"\"A map from device to values; acts as the same type as the values.\"\"\"\n\n def __getattr__(self, name):\n # TODO(priyag): This needs to be made robust against pitfalls from mix use\n # __getattr__ and @property. See b/120402273.\n return getattr(self.get(), name)\n\n # pylint: disable=multiple-statements\n def __add__(self, o): return self.get() + o\n def __radd__(self, o): return o + self.get()\n def __sub__(self, o): return self.get() - o\n def __rsub__(self, o): return o - self.get()\n def __mul__(self, o): return self.get() * o\n def __rmul__(self, o): return o * self.get()\n def __truediv__(self, o): return self.get() / o\n def __rtruediv__(self, o): return o / self.get()\n def __floordiv__(self, o): return self.get() // o\n def __rfloordiv__(self, o): return o // self.get()\n def __mod__(self, o): return self.get() % o\n def __rmod__(self, o): return o % self.get()\n def __lt__(self, o): return self.get() < o\n def __le__(self, o): return self.get() <= o\n def __gt__(self, o): return self.get() > o\n def __ge__(self, o): return self.get() >= o\n def __and__(self, o): return self.get() & o\n def __rand__(self, o): return o & self.get()\n def __or__(self, o): return self.get() | o\n def __ror__(self, o): return o | self.get()\n def __xor__(self, o): return self.get() ^ o\n def __rxor__(self, o): return o ^ self.get()\n def __getitem__(self, o): return self.get()[o]\n def __pow__(self, o, modulo=None): return pow(self.get(), o, modulo)\n def __rpow__(self, o): return pow(o, self.get())\n def __invert__(self): return ~self.get()\n def __neg__(self): return -self.get()\n def __abs__(self): return abs(self.get())\n\n def __div__(self, o):\n try:\n return self.get().__div__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __rdiv__(self, o):\n try:\n return self.get().__rdiv__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __matmul__(self, o):\n try:\n return self.get().__matmul__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __rmatmul__(self, o):\n try:\n return self.get().__rmatmul__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n # TODO(josh11b): Even more operator overloads.\n\n\nclass PerReplica(DistributedValues):\n \"\"\"Holds a map from device to unsynchronized values.\"\"\"\n pass\n\n\n# Note that unlike PerReplica, Mirrored values inherit from\n# DistributedDelegate and so can be used directly in cross-replica mode.\nclass Mirrored(DistributedDelegate):\n \"\"\"Holds a map from device to values which are kept in sync.\"\"\"\n\n def _get_cross_replica(self):\n device = device_util.canonicalize(device_util.current())\n replica_id = self._device_map.replica_for_device(device)\n if replica_id is None:\n return self.primary\n return self._values[replica_id]\n\n def _as_graph_element(self):\n obj = self.get()\n conv_fn = getattr(obj, \"_as_graph_element\", None)\n if conv_fn and callable(conv_fn):\n return conv_fn()\n return obj\n\n\ndef _assign_on_device(device, variable, tensor):\n with ops.device(device):\n return variable.assign(array_ops.identity(tensor))\n\n\ndef _assert_strategy(strategy):\n if not distribution_strategy_context.has_distribution_strategy():\n raise RuntimeError(\n 'Need to be inside \"with strategy.scope()\" for %s' %\n (strategy,))\n current_strategy = distribution_strategy_context.get_distribution_strategy()\n if current_strategy is not strategy:\n raise RuntimeError(\n \"Mixing different tf.distribute.Strategy objects: %s is not %s\" %\n (current_strategy, strategy))\n\n\nDistributedVarOp = collections.namedtuple(\n \"DistributedVarOp\", [\"name\", \"graph\", \"type\"])\n\n\nclass DistributedVariable(DistributedDelegate):\n \"\"\"Holds a map from device to variables.\"\"\"\n # TODO(josh11b): Support changing the set of variables if e.g. if new\n # devices are joining or a device is to leave.\n\n def __init__(self, strategy, device_map, values, logical_device=None):\n self._distribute_strategy = strategy\n super(DistributedVariable, self).__init__(\n device_map, values, logical_device=logical_device)\n self._common_name = self.primary.name.split(\":\")[0]\n # Use a weakref to make it easy to map from the contained values\n # to the container without introducing a reference cycle.\n for v in values:\n v._distributed_container = weakref.ref(self) # pylint: disable=protected-access\n # tf.keras keeps track of variables initialized using this attribute. When\n # tf.keras gets the default session, it initializes all uninitialized vars.\n # We need to make _keras_initialized a member of DistributedVariable because\n # without this it will use `__getattr__` which will delegate to a component\n # variable.\n self._keras_initialized = False\n # Typically, a `DistributedVariable`'s initializer is composed of the\n # initializers of the components variables. However, in some cases, such as\n # when restoring from a checkpoint, we may set the _initializer_op\n # property on the entire `DistributedVariable`.\n self._initializer_op = None\n\n def is_initialized(self, name=None):\n \"\"\"Identifies if all the component variables are initialized.\n\n Args:\n name: Name of the final `logical_and` op.\n\n Returns:\n The op that evaluates to True or False depending on if all the\n component variables are initialized.\n \"\"\"\n result = self.primary.is_initialized()\n # We iterate through the list of values except the last one to allow us to\n # name the final `logical_and` op the same name that is passed by the user\n # to the `is_initialized` op. For distributed variables, the\n # `is_initialized` op is a `logical_and` op.\n for v in self._values[1:-1]:\n result = math_ops.logical_and(result, v.is_initialized())\n result = math_ops.logical_and(result, self._values[-1].is_initialized(),\n name=name)\n return result\n\n @property\n def initializer(self):\n if self._initializer_op:\n init_op = self._initializer_op\n else:\n # return grouped ops of all the var initializations of component values of\n # the mirrored variable\n init_op = control_flow_ops.group(tuple(\n v.initializer for v in self._values))\n return init_op\n\n def _get_closest(self):\n \"\"\"Return member in the same replica if possible, else the primary.\"\"\"\n replica_context = distribution_strategy_context.get_replica_context()\n if replica_context:\n return self._device_map.select_for_current_replica(\n self._values, replica_context)\n device = distribute_lib.get_update_device()\n if device is None:\n device = device_util.canonicalize(device_util.current())\n replica_id = self._device_map.replica_for_device(device)\n if replica_id is None:\n return self.primary\n return self._values[replica_id]\n\n def initialized_value(self):\n return self._get_closest().initialized_value()\n\n @property\n def initial_value(self):\n return self._get_closest().initial_value\n\n @property\n def graph(self):\n return self.primary.graph\n\n @property\n def _shared_name(self):\n return self._common_name\n\n @property\n def _unique_id(self):\n return self.primary._unique_id # pylint: disable=protected-access\n\n @property\n def name(self):\n return self.primary.name\n\n @property\n def dtype(self):\n return self.primary.dtype\n\n @property\n def shape(self):\n return self.primary.shape\n\n @property\n def distribute_strategy(self):\n return self._distribute_strategy\n\n def get_shape(self):\n return self.primary.get_shape()\n\n def to_proto(self, export_scope=None):\n return self.primary.to_proto(export_scope=export_scope)\n\n @property\n def op(self):\n # We want cross-replica code that does some var.op.X calls\n # to work (even if the current device isn't in self.devices), but\n # other uses of var.op in a cross-replica context to fail.\n if distribution_strategy_context.in_cross_replica_context():\n return DistributedVarOp(self.primary.op.name,\n self.primary.op.graph,\n self.primary.op.type)\n return self.get().op\n\n @property\n def _in_graph_mode(self):\n return self.primary._in_graph_mode # pylint: disable=protected-access\n\n def read_value(self):\n return self._distribute_strategy.extended.read_var(self)\n\n def _should_act_as_resource_variable(self):\n \"\"\"Pass resource_variable_ops.is_resource_variable check.\"\"\"\n pass\n\n\nops.register_dense_tensor_like_type(DistributedVariable)\n\n\ndef _apply_aggregation(strategy, value, aggregation, destinations):\n if aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA:\n return strategy.broadcast(strategy.unwrap(value)[0],\n destinations=destinations)\n reduce_op = reduce_util.ReduceOp.from_variable_aggregation(aggregation)\n return strategy.extended.reduce_to(reduce_op, value, destinations)\n\n\nclass _MirroredSaveable(saver.BaseSaverBuilder.ResourceVariableSaveable):\n \"\"\"Class for defining how to restore a MirroredVariable.\"\"\"\n\n def __init__(self, mirrored_variable, primary_variable, name):\n self._mirrored_variable = mirrored_variable\n super(_MirroredSaveable, self).__init__(primary_variable, \"\", name)\n\n def restore(self, restored_tensors, restored_shapes):\n \"\"\"Restore the same value into all variables.\"\"\"\n tensor, = restored_tensors\n return control_flow_ops.group(tuple(\n _assign_on_device(v.device, v, tensor)\n for v in self._mirrored_variable.values))\n\n\nclass MirroredVariable(DistributedVariable, Mirrored,\n checkpointable.CheckpointableBase):\n \"\"\"Holds a map from device to variables whose values are kept in sync.\"\"\"\n\n def __init__(\n self, strategy, device_map, values, aggregation, logical_device=None):\n super(MirroredVariable, self).__init__(\n strategy, device_map, values, logical_device=logical_device)\n self._aggregation = aggregation\n\n # The arguments to update() are automatically unwrapped so the update()\n # function would normally see regular variables, not MirroredVariables.\n # However, the update function can still operate on wrapped MirroredVariables\n # through object members, captured arguments, etc. This is more likely in an\n # update_non_slot() function (like OptimizerV2._finish), which can\n # update several non-slot variables in one call.\n def _assign_func(self, *args, **kwargs):\n _assert_strategy(self._distribute_strategy)\n f = kwargs.pop(\"f\")\n if distribution_strategy_context.in_cross_replica_context():\n update_device = distribute_lib.get_update_device()\n if update_device is not None:\n # We are calling an assign function on the mirrored variable in an\n # update context.\n v = self.get(device=update_device)\n return f(v, *args, **kwargs)\n\n # We are calling assign on the mirrored variable in cross replica context,\n # use `strategy.update()` to update the variable.\n return self._distribute_strategy.update(self, f, *args, **kwargs)\n else:\n _assert_replica_context(self._distribute_strategy)\n # We are calling an assign function on the mirrored variable in replica\n # context.\n # We reduce the value we want to assign/add/sub. More details about how we\n # handle the different use cases can be found in the _reduce method.\n # We call the function on each of the mirrored variables with the reduced\n # value.\n if self._aggregation == vs.VariableAggregation.NONE:\n raise ValueError(\"You must specify an aggregation method to update a \"\n \"MirroredVariable in Replica Context.\")\n\n def merge_fn(strategy, value, *other_args, **other_kwargs):\n v = _apply_aggregation(strategy, value, self._aggregation, self)\n return strategy.update(self, f, v, *other_args, **other_kwargs)\n\n return distribution_strategy_context.get_replica_context().merge_call(\n merge_fn, args=args, kwargs=kwargs)\n\n def assign_sub(self, *args, **kwargs):\n assign_sub_fn = lambda var, *a, **kw: var.assign_sub(*a, **kw)\n return self._assign_func(f=assign_sub_fn, *args, **kwargs)\n\n def assign_add(self, *args, **kwargs):\n assign_add_fn = lambda var, *a, **kw: var.assign_add(*a, **kw)\n return self._assign_func(f=assign_add_fn, *args, **kwargs)\n\n def assign(self, *args, **kwargs):\n assign_fn = lambda var, *a, **kw: var.assign(*a, **kw)\n return self._assign_func(f=assign_fn, *args, **kwargs)\n\n @property\n def aggregation(self):\n return self._aggregation\n\n def _get_cross_replica(self):\n device = device_util.canonicalize(device_util.current())\n replica_id = self._device_map.replica_for_device(device)\n if replica_id is None:\n return array_ops.identity(self.primary)\n return array_ops.identity(self._values[replica_id])\n\n def _as_graph_element(self):\n # pylint: disable=protected-access\n if distribution_strategy_context.in_cross_replica_context():\n return self.primary._as_graph_element()\n return self.get()._as_graph_element()\n\n def _gather_saveables_for_checkpoint(self):\n \"\"\"Overrides CheckpointableBase method.\n\n This allows both name-based and object-based save and restore of\n MirroredVariables.\n\n Returns:\n A dictionary mapping attribute names to `SaveableObject` factories.\n \"\"\"\n def _saveable_factory(name=self._common_name):\n return _MirroredSaveable(self, self.primary, name)\n return {checkpointable.VARIABLE_VALUE_KEY: _saveable_factory}\n\n\n# Register a conversion function which reads the value of the variable,\n# allowing instances of the class to be used as tensors.\ndef _tensor_conversion_mirrored(var, dtype=None, name=None, as_ref=False):\n # Try to avoid assignments to and other mutations of MirroredVariable\n # state except through a DistributionStrategy.update() call.\n assert not as_ref\n return ops.internal_convert_to_tensor(\n var.get(), dtype=dtype, name=name, as_ref=as_ref)\n\n\nops.register_tensor_conversion_function(MirroredVariable,\n _tensor_conversion_mirrored)\n\n\ndef _enclosing_tpu_context():\n # pylint: disable=protected-access\n tpu_context = ops.get_default_graph()._get_control_flow_context()\n # pylint: enable=protected-access\n while tpu_context is not None and not isinstance(\n tpu_context, control_flow_ops.XLAControlFlowContext):\n tpu_context = tpu_context.outer_context\n return tpu_context\n\n\n# TODO(jhseu): Deduplicate code. We copy code because we don't want to\n# inherit from DistributedDelegate. DistributedDelegate will not work in a\n# tpu.replicate() because it assumes that you're in a device context where you\n# can operate on a single version of the variable, but a tpu.replicate()\n# operates on all variables and is replicated during a rewrite pass.\nclass TPUMirroredVariable(checkpointable.CheckpointableBase):\n \"\"\"Holds a map from device to TPU variables whose values are kept in sync.\"\"\"\n\n def __init__(\n self, strategy, device_map, values, aggregation, logical_device=None):\n assert isinstance(device_map, DeviceMap)\n self._distribute_strategy = strategy\n self._device_map = device_map\n self._values = tuple(values)\n if logical_device is None:\n logical_device = device_map.logical_device_from_values(self._values)\n self._logical_device = logical_device\n\n # Use a weakref to make it easy to map from the contained values\n # to the container without introducing a reference cycle.\n for v in self._values:\n v._mirrored_container = weakref.ref(self) # pylint: disable=protected-access\n self._common_name = self.primary.name.split(\":\")[0]\n self._aggregation = aggregation\n # Needed for GradientTape\n self._trainable = self.primary.trainable\n # Typically like `DistributedVariable`, a `TPUMirroredVariable`'s\n # initializer is composed of the initializers of the components variables.\n # However, in some cases, such as when restoring from a checkpoint, we may\n # set the _initializer_op property on the entire `TPUMirroredVariable`.\n self._initializer_op = None\n\n def _get(self, device=None):\n \"\"\"Returns the value for the current device or raises a ValueError.\"\"\"\n if device is None:\n replica_context = distribution_strategy_context.get_replica_context()\n if replica_context:\n return self._device_map.select_for_current_replica(\n self._values, replica_context)\n else:\n device = distribute_lib.get_update_device()\n if device is None:\n return self._get_cross_replica()\n device = device_util.canonicalize(device)\n return self._device_map.select_for_device(self._values, device)\n\n @property\n def primary(self):\n \"\"\"Returns a representative component.\"\"\"\n return self._values[0]\n\n @property\n def devices(self):\n return self._device_map.logical_to_actual_devices(self._logical_device)\n\n @property\n def logical_device(self):\n return self._logical_device\n\n @property\n def device_map(self):\n return self._device_map\n\n # TODO(josh11b): Replace unwrap with this?\n @property\n def values(self):\n return self._values\n\n @property\n def distribute_strategy(self):\n return self._distribute_strategy\n\n # pylint: disable=multiple-statements\n def __add__(self, o): return self.read_value() + o\n def __radd__(self, o): return o + self.read_value()\n def __sub__(self, o): return self.read_value() - o\n def __rsub__(self, o): return o - self.read_value()\n def __mul__(self, o): return self.read_value() * o\n def __rmul__(self, o): return o * self.read_value()\n def __truediv__(self, o): return self.read_value() / o\n def __rtruediv__(self, o): return o / self.read_value()\n def __floordiv__(self, o): return self.read_value() // o\n def __rfloordiv__(self, o): return o // self.read_value()\n def __mod__(self, o): return self.read_value() % o\n def __rmod__(self, o): return o % self.read_value()\n def __lt__(self, o): return self.read_value() < o\n def __le__(self, o): return self.read_value() <= o\n def __gt__(self, o): return self.read_value() > o\n def __ge__(self, o): return self.read_value() >= o\n def __and__(self, o): return self.read_value() & o\n def __rand__(self, o): return o & self.read_value()\n def __or__(self, o): return self.read_value() | o\n def __ror__(self, o): return o | self.read_value()\n def __xor__(self, o): return self.read_value() ^ o\n def __rxor__(self, o): return o ^ self.read_value()\n def __getitem__(self, o): return self.read_value()[o]\n def __pow__(self, o, modulo=None): return pow(self.read_value(), o, modulo)\n def __rpow__(self, o): return pow(o, self.read_value())\n def __invert__(self): return ~self.read_value()\n def __neg__(self): return -self.read_value()\n def __abs__(self): return abs(self.read_value())\n\n def __div__(self, o):\n try:\n return self.read_value().__div__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __rdiv__(self, o):\n try:\n return self.read_value().__rdiv__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __matmul__(self, o):\n try:\n return self.read_value().__matmul__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __rmatmul__(self, o):\n try:\n return self.read_value().__rmatmul__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __str__(self):\n devices = self.devices\n debug_str = \",\\n\".join(\" %d %s: %s\" % (i, devices[i], self._values[i])\n for i in range(len(devices)))\n return \"%s:{\\n%s\\n}\" % (self.__class__.__name__, debug_str)\n\n def __repr__(self):\n devices = self.devices\n debug_repr = \",\\n\".join(\" %d %s: %r\" % (i, devices[i], self._values[i])\n for i in range(len(devices)))\n return \"%s:{\\n%s\\n}\" % (self.__class__.__name__, debug_repr)\n\n @property\n def handle(self):\n # If we're in a tpu.rewrite(), return the replicated handle.\n tpu_context = _enclosing_tpu_context()\n if tpu_context is not None:\n return tpu_context.get_replicated_var_handle(\n self._common_name, self._values)\n\n device = distribute_lib.get_update_device()\n if device is None:\n return self.primary.handle\n return self._get(device=device).handle\n\n @property\n def device(self):\n return self._get().device\n\n def eval(self, session=None):\n return self.primary.eval(session)\n\n # The arguments to update() are automatically unwrapped so the update()\n # function would normally see regular variables, not MirroredVariables.\n # However, the update function can still operate on wrapped MirroredVariables\n # through object members, captured arguments, etc. This is more likely in an\n # update_non_slot() function (like OptimizerV2._finish), which can\n # update several non-slot variables in one call.\n def _assign_func(self, *args, **kwargs):\n _assert_strategy(self._distribute_strategy)\n f = kwargs.pop(\"f\")\n if distribution_strategy_context.in_cross_replica_context():\n if _enclosing_tpu_context() is not None:\n return self._distribute_strategy.update(self, f, *args, **kwargs)\n\n update_device = distribute_lib.get_update_device()\n # We are calling update on the mirrored variable in cross replica context.\n if update_device is not None:\n # We are calling an assign function on the mirrored variable in cross\n # replica context.\n v = self._get(device=update_device)\n return f(v, *args, **kwargs)\n\n return self._distribute_strategy.update(self, f, *args, **kwargs)\n else:\n _assert_replica_context(self._distribute_strategy)\n # We are calling an assign function on the mirrored variable in replica\n # context.\n # We reduce the value we want to assign/add/sub. More details about how we\n # handle the different use cases can be found in the _reduce method.\n # We call the function on each of the mirrored variables with the reduced\n # value.\n if self._aggregation == vs.VariableAggregation.NONE:\n raise ValueError(\"You must specify an aggregation method to update a \"\n \"TPUMirroredVariable in Replica Context.\")\n\n def merge_fn(strategy, value, *other_args, **other_kwargs):\n v = _apply_aggregation(strategy, value, self._aggregation, self)\n return strategy.update(self, f, v, *other_args, **other_kwargs)\n\n return distribution_strategy_context.get_replica_context().merge_call(\n merge_fn, args=args, kwargs=kwargs)\n\n @contextlib.contextmanager\n def _handle_graph(self, handle):\n # Note: might have an eager tensor but not be executing eagerly when\n # building functions.\n if (context.executing_eagerly() or isinstance(handle, ops.EagerTensor)\n or ops.has_default_graph()):\n yield\n else:\n with handle.graph.as_default():\n yield\n\n @property\n def trainable(self):\n return self._trainable\n\n def _read_variable_op(self, parent_op=None):\n if self.trainable:\n tape.variable_accessed(self)\n if parent_op is not None:\n with ops.control_dependencies([parent_op]):\n return gen_resource_variable_ops.read_variable_op(\n self.handle, self.dtype)\n\n return gen_resource_variable_ops.read_variable_op(\n self.handle, self.dtype)\n\n def read_value(self):\n return self._read_variable_op()\n\n def assign_sub(self, *args, **kwargs):\n def assign_sub_fn(var, delta, **kw):\n name = kw.pop(\"name\", None)\n read_value = kw.pop(\"read_value\", True)\n with self._handle_graph(var.handle):\n op = gen_resource_variable_ops.assign_sub_variable_op(\n var.handle, ops.convert_to_tensor(delta, dtype=self.dtype),\n name=name)\n if read_value:\n return self._read_variable_op(parent_op=op)\n return op\n\n return self._assign_func(f=assign_sub_fn, *args, **kwargs)\n\n def assign_add(self, *args, **kwargs):\n def assign_add_fn(var, delta, **kw):\n name = kw.pop(\"name\", None)\n read_value = kw.pop(\"read_value\", True)\n with self._handle_graph(var.handle):\n op = gen_resource_variable_ops.assign_add_variable_op(\n var.handle, ops.convert_to_tensor(delta, dtype=self.dtype),\n name=name)\n if read_value:\n return self._read_variable_op(parent_op=op)\n return op\n\n return self._assign_func(f=assign_add_fn, *args, **kwargs)\n\n def assign(self, *args, **kwargs):\n def assign_fn(var, value, **kw):\n name = kw.pop(\"name\", None)\n read_value = kw.pop(\"read_value\", True)\n with self._handle_graph(var.handle):\n op = gen_resource_variable_ops.assign_variable_op(\n var.handle, ops.convert_to_tensor(value, dtype=self.dtype),\n name=name)\n if read_value:\n return self._read_variable_op(parent_op=op)\n return op\n\n return self._assign_func(f=assign_fn, *args, **kwargs)\n\n @property\n def aggregation(self):\n return self._aggregation\n\n @property\n def constraint(self):\n return None\n\n @property\n def initializer(self):\n if self._initializer_op:\n init_op = self._initializer_op\n else:\n init_op = control_flow_ops.group(tuple(\n v.initializer for v in self._values))\n return init_op\n\n @property\n def graph(self):\n return self.primary.graph\n\n @property\n def _shared_name(self):\n return self._common_name\n\n @property\n def _unique_id(self):\n return self.primary._unique_id # pylint: disable=protected-access\n\n @property\n def name(self):\n return self.primary.name\n\n @property\n def dtype(self):\n return self.primary.dtype\n\n @property\n def shape(self):\n return self.primary.shape\n\n def get_shape(self):\n return self.primary.get_shape()\n\n def to_proto(self, export_scope=None):\n return self.primary.to_proto(export_scope=export_scope)\n\n def _get_cross_replica(self):\n device = device_util.canonicalize(device_util.current())\n replica = self._device_map.replica_for_device(device)\n if replica is None:\n return self.primary\n return self._values[replica]\n\n def _as_graph_element(self):\n # pylint: disable=protected-access\n if distribution_strategy_context.in_cross_replica_context():\n return self.primary._as_graph_element()\n return self._read_variable_op()\n\n def _gather_saveables_for_checkpoint(self):\n \"\"\"Overrides CheckpointableBase method.\n\n This allows both name-based and object-based save and restore of\n MirroredVariables.\n\n Returns:\n A dictionary mapping attribute names to `SaveableObject` factories.\n \"\"\"\n def _saveable_factory(name=self._common_name):\n return _MirroredSaveable(self, self.primary, name)\n return {checkpointable.VARIABLE_VALUE_KEY: _saveable_factory}\n\n def _should_act_as_resource_variable(self):\n \"\"\"Pass resource_variable_ops.is_resource_variable check.\"\"\"\n pass\n\n # Needed to pass ResourceVariable checks.\n @property\n def op(self):\n return self.primary.op\n\n # pylint: disable=protected-access\n @property\n def _save_slice_info(self):\n return self.primary._save_slice_info\n\n def _get_save_slice_info(self):\n return self.primary._get_save_slice_info()\n\n def _set_save_slice_info(self, save_slice_info):\n return self.primary._set_save_slice_info(save_slice_info)\n # pylint: enable=protected-access\n\n @property\n def _in_graph_mode(self):\n return self.primary._in_graph_mode # pylint: disable=protected-access\n\n def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False):\n \"\"\"Converts a variable to a tensor.\"\"\"\n # pylint: disable=protected-access\n if _enclosing_tpu_context() is None:\n return self._get()._dense_var_to_tensor(dtype, name, as_ref)\n # pylint: enable=protected-access\n if dtype is not None and dtype != self.dtype:\n return math_ops.cast(self.read_value(), dtype)\n if as_ref:\n return self.handle\n else:\n return self.read_value()\n\n def is_initialized(self, name=None):\n \"\"\"Identifies if all the component variables are initialized.\n\n Args:\n name: Name of the final `logical_and` op.\n\n Returns:\n The op that evaluates to True or False depending on if all the\n component variables are initialized.\n \"\"\"\n # TODO(jhseu): Do we need TPU context implementation?\n\n result = self.primary.is_initialized()\n # We iterate through the list of values except the last one to allow us to\n # name the final `logical_and` op the same name that is passed by the user\n # to the `is_initialized` op. For distributed variables, the\n # `is_initialized` op is a `logical_and` op.\n for v in self._values[1:-1]:\n result = math_ops.logical_and(result, v.is_initialized())\n result = math_ops.logical_and(result, self._values[-1].is_initialized(),\n name=name)\n return result\n\n\n# Register a conversion function which reads the value of the variable,\n# allowing instances of the class to be used as tensors.\ndef _tensor_conversion_tpu_mirrored(var, dtype=None, name=None, as_ref=False):\n return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access\n\n\nops.register_tensor_conversion_function(TPUMirroredVariable,\n _tensor_conversion_tpu_mirrored)\nops.register_dense_tensor_like_type(TPUMirroredVariable)\n\n\nclass _ReplicaLocalSaveable(saver.BaseSaverBuilder.SaveableObject):\n \"\"\"Class for defining how to restore a ReplicaLocalVariable.\"\"\"\n\n def __init__(self, replica_local_variable, name):\n self._replica_local_variable = replica_local_variable\n # We use a callable so that we don't have to evaluate this expression\n # in the case where we are trying to restore instead of save.\n def tensor():\n strategy = replica_local_variable.distribute_strategy\n return strategy.extended.read_var(replica_local_variable)\n\n spec = saver.BaseSaverBuilder.SaveSpec(\n tensor=tensor,\n slice_spec=\"\",\n name=name,\n dtype=replica_local_variable.dtype)\n super(_ReplicaLocalSaveable, self).__init__(tensor, [spec], name)\n\n def restore(self, restored_tensors, restored_shapes):\n \"\"\"Restore the same value into all variables.\"\"\"\n tensor, = restored_tensors\n return self._replica_local_variable.assign(tensor)\n\n\ndef _assert_replica_context(strategy):\n replica_context = distribution_strategy_context.get_replica_context()\n if not replica_context:\n raise RuntimeError(\n \"Replica-local variables may only be assigned in a replica context.\")\n if replica_context.strategy is not strategy:\n raise RuntimeError(\n \"Replica-local variables may only be assigned in a replica context.\")\n\n\nclass ReplicaLocalVariable(DistributedVariable, PerReplica,\n checkpointable.CheckpointableBase):\n \"\"\"Holds a map from device to variables whose values are reduced on save.\"\"\"\n\n def __init__(\n self, strategy, device_map, values, aggregation, logical_device=None):\n self._aggregation = aggregation\n super(ReplicaLocalVariable, self).__init__(\n strategy, device_map, values, logical_device=logical_device)\n\n def assign_sub(self, *args, **kwargs):\n _assert_replica_context(self._distribute_strategy)\n return self.get().assign_sub(*args, **kwargs)\n\n def assign_add(self, *args, **kwargs):\n _assert_replica_context(self._distribute_strategy)\n return self.get().assign_add(*args, **kwargs)\n\n def assign(self, *args, **kwargs):\n if distribution_strategy_context.in_cross_replica_context():\n # To preserve the sum across save and restore, we have to divide the\n # total across all devices when restoring a variable that was summed\n # when saving.\n tensor = args[0]\n if self._aggregation == vs.VariableAggregation.SUM:\n tensor *= 1. / len(self.devices)\n return control_flow_ops.group(tuple(\n _assign_on_device(v.device, v, tensor) for v in self._values))\n else:\n _assert_replica_context(self._distribute_strategy)\n return self.get().assign(*args, **kwargs)\n\n @property\n def aggregation(self):\n return self._aggregation\n\n def _get_cross_replica(self):\n if self._aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA:\n return self.primary\n # TODO(josh11b): Use a strategy-specific method.\n total = math_ops.add_n(self._values)\n if self._aggregation == vs.VariableAggregation.MEAN:\n return total * (1./ len(self._values))\n return total\n\n def _as_graph_element(self):\n # pylint: disable=protected-access\n if distribution_strategy_context.in_cross_replica_context():\n return self._get_cross_replica()\n return self.get()._as_graph_element()\n\n def _gather_saveables_for_checkpoint(self):\n \"\"\"Overrides CheckpointableBase method.\n\n This allows both name-based and object-based save and restore of\n ReplicaLocalVariables.\n\n Returns:\n A dictionary mapping attribute names to `SaveableObject` factories.\n \"\"\"\n def _saveable_factory(name=self._common_name):\n return _ReplicaLocalSaveable(self, name)\n return {checkpointable.VARIABLE_VALUE_KEY: _saveable_factory}\n\n\n# Register a conversion function for ReplicaLocalVariable which allows as_ref to\n# be true.\ndef _tensor_conversion_replica_local(var, dtype=None, name=None, as_ref=False):\n return ops.internal_convert_to_tensor(\n var.get(), dtype=dtype, name=name, as_ref=as_ref)\n\n\nops.register_tensor_conversion_function(ReplicaLocalVariable,\n _tensor_conversion_replica_local)\n\n\ndef regroup(device_map, values, wrap_class=PerReplica):\n \"\"\"Makes a nest per-replica into a nest of PerReplica/Mirrored values.\"\"\"\n assert isinstance(device_map, DeviceMap)\n assert len(values) == device_map.num_replicas_in_graph\n v0 = values[0]\n\n if isinstance(v0, list):\n for v in values[1:]:\n assert isinstance(v, list)\n assert len(v) == len(v0), (\"len(v) == %d, len(v0) == %d, v: %s, v0: %s\" %\n (len(v), len(v0), v, v0))\n return [regroup(device_map, tuple(v[i] for v in values), wrap_class)\n for i in range(len(v0))]\n\n if isinstance(v0, tuple):\n for v in values[1:]:\n assert isinstance(v, tuple)\n assert len(v) == len(v0)\n regrouped_tuple = tuple(\n regroup(device_map, tuple(v[i] for v in values), wrap_class)\n for i in range(len(v0)))\n if hasattr(v0, \"_fields\"):\n # This tuple is in fact a namedtuple! Create a new namedtuple instance\n # and initialize it with the regrouped values:\n assert hasattr(type(v0), \"_make\")\n return type(v0)._make(regrouped_tuple)\n else:\n return regrouped_tuple\n\n if isinstance(v0, dict):\n v0keys = set(v0.keys())\n for v in values[1:]:\n assert isinstance(v, dict), (\"v[0]: %r v[i]: %r\" % (v0, v))\n assert set(v.keys()) == v0keys, (\"v[0].keys: %s v[i].keys: %s\" %\n (v0keys, set(v.keys())))\n return {key: regroup(device_map, tuple(v[key] for v in values), wrap_class)\n for key in v0keys}\n\n # If exactly the same object across all devices, return it unwrapped.\n same_id = True\n for v in values[1:]:\n if v is not v0:\n same_id = False\n break\n # Consider three cases where same_id is true:\n # * If v0 is a DistributedVariable (a MirroredVariable or\n # ReplicaLocalVariable, and same_id means it is the same across all\n # devices), we want to return it. We check DistributedVariable\n # specifically since it can look like it has a\n # _distributed_container member since its members do.\n # * If v0 is a member of a distributed variable, in which case\n # hasattr(v0, \"_distributed_container\") is true, we want to\n # return the DistributedVariable that contains it using the\n # _distributed_container logic below. This case can trigger\n # same_id when there is only one device.\n # * In any other situation, same_id means we return v0.\n if same_id and (isinstance(v0, DistributedVariable) or\n not hasattr(v0, \"_distributed_container\")):\n return v0\n\n # Detect the case where each device has a parallel component of the\n # same MirroredVariable (or ReplicaLocalVariable). In this case we\n # want to return the containing MirroredVariable, after a bunch of\n # sanity checking. In particular, each component should have the\n # same container, and the devices of the variables should match the\n # keys of the per-replica dictionary.\n if hasattr(v0, \"_distributed_container\"):\n # pylint: disable=protected-access\n assert not isinstance(v0, MirroredVariable), (\n \"ids = %s, values = %s\" % ([id(v) for v in values], values))\n assert device_map.is_device_in_replica(v0.device, 0), (\n \"v0.device = %s, device_map = %s\" % (v0.device, device_map))\n distributed_container = v0._distributed_container()\n assert distributed_container is not None\n for r, v in enumerate(values[1:]):\n assert device_map.is_device_in_replica(v.device, r + 1), (\n \"v.device = %s, r = %d, device_map = %s\" %\n (v.device, r + 1, device_map))\n assert distributed_container is v._distributed_container()\n return distributed_container\n # pylint: enable=protected-access\n\n return wrap_class(device_map, values)\n\n\ndef select_replica(replica_id, structured):\n \"\"\"Specialize a nest of regular & per-replica values for one replica.\"\"\"\n def _get(x):\n return x.values[replica_id] if isinstance(x, DistributedValues) else x\n\n return nest.map_structure(_get, structured)\n\n\ndef select_device_mirrored(device, structured):\n \"\"\"Specialize a nest of regular & mirrored values for one device.\"\"\"\n def _get_mirrored(x):\n if isinstance(x, DistributedValues):\n if not isinstance(x, Mirrored):\n raise TypeError(\n \"Expected value to be mirrored across replicas: %s in %s.\" %\n (x, structured))\n return x.get(device)\n else:\n return x\n\n return nest.map_structure(_get_mirrored, structured)\n\n\ndef update_regroup(extended, device_map, updates, group):\n \"\"\"Regroup for an update, with dependencies to ensure all updates execute.\"\"\"\n # TODO(josh11b): Replace \"Mirrored\" here with a function that does the following\n # so we can avoid all these nest operations.\n regrouped = regroup(device_map, updates, Mirrored)\n if not group:\n return nest.map_structure(extended._unwrap, regrouped) # pylint: disable=protected-access\n grouped_flat = []\n for u in nest.flatten(regrouped):\n if isinstance(u, DistributedValues):\n g = extended._group(u) # pylint: disable=protected-access\n if u.is_tensor_like:\n # Make sure we run all updates. Without this, something like\n # session.run(extended.update(...)) may only update one replica.\n values = []\n for d in u.devices:\n with ops.device(d), ops.control_dependencies([g]):\n values.append(array_ops.identity(u.get(d)))\n g = Mirrored(u.device_map, values)\n else:\n g = u\n grouped_flat.append(g)\n return nest.pack_sequence_as(regrouped, grouped_flat)\n\n\nclass InputWorkers(object):\n \"\"\"A 1-to-many mapping from input worker devices to compute devices.\"\"\"\n\n def __init__(self, device_map, worker_device_pairs=None, logical_device=0):\n \"\"\"Initialize an `InputWorkers` object.\n\n Args:\n device_map: A `DeviceMap` with the computation devices fed by the\n input workers.\n worker_device_pairs: A sequence of pairs:\n `(input device, a tuple of compute devices fed by that input device)`.\n logical_device: The logical device of `device_map` to feed.\n \"\"\"\n self._device_map = device_map\n self._logical_device = logical_device\n if worker_device_pairs is None:\n worker_device_pairs = ((\n device_util.canonicalize(\"/device:CPU:0\"),\n device_map.logical_to_actual_devices(logical_device)),)\n self._input_worker_devices = tuple(d for d, _ in worker_device_pairs)\n self._fed_devices = tuple(tuple(device_util.canonicalize(d) for d in f)\n for _, f in worker_device_pairs)\n flattened = tuple(d for l in self._fed_devices for d in l)\n assert (flattened ==\n device_map.logical_to_actual_devices(logical_device)), (\n \"flattened: %s logical device %d: %s\" %\n (flattened, logical_device,\n device_map.logical_to_actual_devices(logical_device)))\n\n @property\n def device_map(self):\n return self._device_map\n\n @property\n def logical_device(self):\n return self._logical_device\n\n @property\n def num_workers(self):\n return len(self._input_worker_devices)\n\n @property\n def worker_devices(self):\n return self._input_worker_devices\n\n def compute_devices_for_worker(self, worker_index):\n return self._fed_devices[worker_index]\n\n def __repr__(self):\n devices = self.worker_devices\n debug_repr = \",\\n\".join(\" %d %s: %s\" %\n (i, devices[i], self._fed_devices[i])\n for i in range(len(devices)))\n return \"%s:{\\n%s\\n device_map: %s}\" % (\n self.__class__.__name__, debug_repr, self._device_map)\n\n\nclass PerReplicaDataIterator(object):\n \"\"\"An iterator (like `tf.data.Iterator`) into a `PerReplicaDataset`.\"\"\"\n\n def __init__(self, iterator, input_workers, worker_index, prefetch_on_device):\n assert isinstance(input_workers, InputWorkers)\n self._iterator = iterator\n self._input_workers = input_workers\n self._worker_index = worker_index\n self._prefetch_on_device = prefetch_on_device\n\n @property\n def initializer(self):\n return self._iterator.initializer\n\n def get_next_as_list(self, name=None):\n \"\"\"Scatter the input across devices.\"\"\"\n if self._prefetch_on_device:\n data_list = self._iterator.get_next()\n else:\n batch = self._iterator.get_next(name=name)\n data_list = []\n def get_ith(i):\n return lambda x: x[i]\n\n devices = self._input_workers.compute_devices_for_worker(\n self._worker_index)\n for i, d in enumerate(devices):\n v = nest.map_structure(get_ith(i), batch)\n if context.executing_eagerly():\n with ops.device(d):\n v = nest.map_structure(array_ops.identity, v)\n data_list.append(v)\n\n return data_list\n\n def get_next(self, name=None):\n assert self._input_workers.num_workers == 1\n data_list = self.get_next_as_list(name)\n return regroup(self._input_workers.device_map, data_list)\n\n @property\n def output_classes(self):\n return self._iterator.output_classes\n\n @property\n def output_shapes(self):\n return self._iterator.output_shapes\n\n @property\n def output_types(self):\n return self._iterator.output_types\n\n\nclass PerReplicaDataset(object):\n \"\"\"Like `tf.data.Dataset` split devices, producing `PerReplica` data.\"\"\"\n\n def __init__(self, dataset, input_workers, worker_index,\n prefetch_on_device=None):\n assert isinstance(input_workers, InputWorkers)\n assert worker_index is not None\n assert worker_index is not True\n assert worker_index is not False\n self._input_workers = input_workers\n self._worker_index = worker_index\n\n # Default to using prefetching in graph mode, unless specified.\n # TODO(rohanj): Enable prefetching in eager mode.\n self._prefetch_on_device = prefetch_on_device\n if self._prefetch_on_device is None:\n self._prefetch_on_device = not context.executing_eagerly()\n assert not (self._prefetch_on_device and context.executing_eagerly()), (\n \"Prefetching is only supported in graph mode currently\")\n\n self._dataset = dataset\n if not self._prefetch_on_device:\n # TODO(priyag): If dropping remainder is not appropriate, find another\n # approach to distributing the dataset when not possible to divide evenly.\n # Possibly not an issue when we start using PartitionedDataset.\n num_replicas = len(input_workers.compute_devices_for_worker(worker_index))\n self._dataset = dataset.batch(num_replicas, drop_remainder=True)\n\n def make_one_shot_iterator(self):\n \"\"\"Get a one time use iterator for the distributed PerReplicaDataset.\"\"\"\n # Graph mode with one shot iterator is disabled.\n if not context.executing_eagerly():\n raise ValueError(\"Cannot create a one shot iterator. Please use \"\n \"`make_initializable_iterator()` instead.\")\n # Eager mode prefetching would error out in constructor. Only remaining\n # case is non-prefetching in eager mode. We delegate to\n # PerReplicaDataIterator to handle that case.\n dataset_iterator = dataset_ops.make_one_shot_iterator(self._dataset)\n return PerReplicaDataIterator(\n dataset_iterator, self._input_workers, self._worker_index,\n prefetch_on_device=False)\n\n def make_initializable_iterator(self):\n \"\"\"Get an initializable iterator for the distributed PerReplicaDataset.\"\"\"\n # Eager mode generates already initialized iterators. Hence we cannot create\n # an initializable iterator.\n if context.executing_eagerly():\n raise ValueError(\"Cannot create initializable iterator in Eager mode. \"\n \"Please use `make_one_shot_iterator` instead.\")\n if self._prefetch_on_device:\n replica_devices = self._input_workers.compute_devices_for_worker(\n self._worker_index)\n dataset_iterator = multi_device_iterator_ops.MultiDeviceIterator(\n self._dataset, replica_devices)\n else:\n dataset_iterator = dataset_ops.make_initializable_iterator(self._dataset)\n return PerReplicaDataIterator(\n dataset_iterator, self._input_workers, self._worker_index,\n prefetch_on_device=self._prefetch_on_device)\n\n\nclass MultiWorkerDataIterator(object):\n \"\"\"An iterator (like `tf.data.Iterator`) into a `MultiWorkerDataset`.\"\"\"\n\n def __init__(self, iterators, input_workers):\n \"\"\"Initialize the `MultiWorkerDataIterator` object.\n\n Args:\n iterators: a list of worker, iterator pairs.\n input_workers: an `InputWorkers` object.\n\n Raises:\n ValueError: if iterators and input_workers are not compatible.\n \"\"\"\n assert isinstance(input_workers, InputWorkers)\n workers = tuple(d for d, _ in iterators)\n if workers != input_workers.worker_devices:\n raise ValueError(\"iterators and input_workers are not compatible. \"\n \"iterator workers: %r input_workers devices: %r\" %\n (workers, input_workers.worker_devices))\n self._iterators = tuple(i for _, i in iterators)\n self._input_workers = input_workers\n\n @property\n def initializer(self):\n return control_flow_ops.group(\n tuple(iterator.initializer for iterator in self._iterators))\n\n def get_iterator(self, worker):\n for i, w in enumerate(self._input_workers.worker_devices):\n if worker == w:\n return self._iterators[i]\n return None\n\n @property\n def output_shapes(self):\n return self._iterators[0].output_shapes\n\n @property\n def output_types(self):\n return self._iterators[0].output_types\n\n def get_next(self, name=None):\n \"\"\"Scatter the input across hosts and devices.\"\"\"\n replicas = []\n for worker, iterator in zip(self._input_workers.worker_devices,\n self._iterators):\n if name is not None:\n d = tf_device.DeviceSpec.from_string(worker)\n new_name = \"%s_%s_%d\" % (name, d.job, d.task)\n else:\n new_name = None\n with ops.device(worker):\n data_per_worker = iterator.get_next_as_list(name=new_name)\n # Append to replicas to get a flat list of values indexed by replica.\n replicas.extend(data_per_worker)\n\n return regroup(self._input_workers.device_map, replicas)\n\n\nclass MultiWorkerDataset(object):\n \"\"\"Like a `tf.data.Dataset` that distributes data to different workers.\n\n Each worker gets one shard of the input dataset. This currently does not work\n in eager mode.\n \"\"\"\n\n def __init__(self, dataset_fn, input_workers, prefetch_on_device=None,\n auto_shard=False):\n \"\"\"Initialize the MultiWorkerDataset object.\n\n Args:\n dataset_fn: a function or a list of functions that returns a\n `tf.data.Dataset`.\n input_workers: an `InputWorkers` object.\n prefetch_on_device: whether to prefetch to devices.\n auto_shard: whether to auto-shard the dataset.\n \"\"\"\n assert isinstance(input_workers, InputWorkers)\n if isinstance(dataset_fn, (list, tuple)):\n if len(dataset_fn) != input_workers.num_workers:\n raise ValueError(\"If `dataset_fn` is a list, it must have one entry \"\n \"per worker\")\n # TODO(rohanj): b/120673685 to track re-enabling auto sharding.\n if auto_shard:\n raise ValueError(\"Currently autosharding is not supported.\")\n self._input_workers = input_workers\n self._datasets = []\n # TODO(yuefengz, priyag): support different set of jobs for input\n # processing.\n for i, worker in enumerate(input_workers.worker_devices):\n with ops.device(worker):\n if isinstance(dataset_fn, (list, tuple)):\n worker_input = dataset_fn[i]()\n else:\n worker_input = dataset_fn()\n dataset = PerReplicaDataset(worker_input, input_workers, i,\n prefetch_on_device=prefetch_on_device)\n self._datasets.append((worker, dataset))\n\n def make_one_shot_iterator(self):\n iterators = []\n for worker, dataset in self._datasets:\n with ops.device(worker):\n iterators.append((worker, dataset_ops.make_one_shot_iterator(dataset)))\n return MultiWorkerDataIterator(iterators, self._input_workers)\n\n def make_initializable_iterator(self):\n iterators = []\n for worker, dataset in self._datasets:\n with ops.device(worker):\n iterators.append(\n (worker, dataset_ops.make_initializable_iterator(dataset)))\n return MultiWorkerDataIterator(iterators, self._input_workers)\n\n\nclass InputIterator(object):\n \"\"\"An input iterator, intended to be passed to `DistributionStrategy.run`.\"\"\"\n\n def get_next(self):\n \"\"\"Returns the next inputs for all replicas.\"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n def initialize(self):\n \"\"\"Initialize the underlying input dataset, when applicable.\n\n In eager mode, this will create a new iterator and return it.\n In graph mode, this will initialize the same underlying iterator(s).\n\n Users are required to call this if\n - This iterator was returned from a call to `make_input_fn_iterator` with an\n input function that returns a dataset.\n - Or this iterator was returned from a call to `make_dataset_iterator`.\n\n Returns:\n A list of initialization ops to be executed.\n \"\"\"\n raise NotImplementedError(\"must be implemented in descendants\")\n\n\nclass InputIteratorImpl(InputIterator):\n \"\"\"Common implementation for all input iterators.\"\"\"\n\n def __init__(self, input_workers, iterators):\n assert isinstance(input_workers, InputWorkers)\n if not input_workers.worker_devices:\n raise ValueError(\"Should have at least one worker for input iterator.\")\n\n self._iterators = iterators\n self._input_workers = input_workers\n self._is_eager = context.executing_eagerly()\n\n def get_next(self, name=None):\n \"\"\"Returns the next input from the iterator for all replicas.\"\"\"\n assert self._is_eager == context.executing_eagerly(), (\n \"Iterator should be created and used in same execution mode.\")\n\n replicas = []\n for i, worker in enumerate(self._input_workers.worker_devices):\n if name is not None:\n d = tf_device.DeviceSpec.from_string(worker)\n new_name = \"%s_%s_%d\" % (name, d.job, d.task)\n else:\n new_name = None\n with ops.device(worker):\n # Make `replicas` a flat list of values across all replicas.\n replicas.extend(self._iterators[i].get_next_as_list(new_name))\n\n return regroup(self._input_workers.device_map, replicas)\n\n def initialize(self):\n \"\"\"Initialze underlying iterators.\n\n Returns:\n A list of any initializer ops that should be run.\n \"\"\"\n assert self._is_eager == context.executing_eagerly(), (\n \"Iterator should be created and used in same execution mode.\")\n\n init_ops = []\n for it in self._iterators:\n init_ops.extend(it.initialize())\n return init_ops\n\n # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.\n @property\n def output_classes(self):\n return self._iterators[0].output_classes\n\n # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.\n @property\n def output_shapes(self):\n return self._iterators[0].output_shapes\n\n # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.\n @property\n def output_types(self):\n return self._iterators[0].output_types\n\n # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.\n def get_iterator(self, worker):\n for i, w in enumerate(self._input_workers.worker_devices):\n if worker == w:\n return self._iterators[i]\n return None\n\n\nclass InputFunctionIterator(InputIteratorImpl):\n \"\"\"Iterator created from input function.\"\"\"\n\n def __init__(self, input_fn, input_workers, input_contexts):\n \"\"\"Make an iterator for input provided via an input function.\n\n Currently implements PER_WORKER mode, in which the `input_fn` is called\n once on each worker.\n\n TODO(priyag): Add other replication modes.\n TODO(priyag): Allow taking input function that returns a callable that\n returns nest of tensors.\n\n Args:\n input_fn: Input function that returns a `tf.data.Dataset` object.\n input_workers: an `InputWorkers` object.\n input_contexts: A list of `InputContext` instances to be passed to call(s)\n to `input_fn`. Length and order should match worker order in\n `worker_device_pairs`.\n \"\"\"\n assert isinstance(input_workers, InputWorkers)\n if input_workers.num_workers != len(input_contexts):\n raise ValueError(\n \"Number of input workers (%d) is not same as number of \"\n \"input_contexts (%d)\" %\n (input_workers.num_workers, len(input_contexts)))\n\n iterators = []\n for i, ctx in enumerate(input_contexts):\n worker = input_workers.worker_devices[i]\n with ops.device(worker):\n result = input_fn(ctx)\n if not isinstance(result, dataset_ops.DatasetV2):\n raise ValueError(\"input_fn must return a tf.data.Dataset.\")\n devices = input_workers.compute_devices_for_worker(i)\n iterator = _SingleWorkerDatasetIterator(result, worker, devices)\n iterators.append(iterator)\n\n super(InputFunctionIterator, self).__init__(input_workers, iterators)\n\n\nclass DatasetIterator(InputIteratorImpl):\n \"\"\"Iterator created from input dataset.\"\"\"\n\n def __init__(self, dataset, input_workers, split_batch_by=None):\n \"\"\"Make an iterator for the dataset on given devices.\n\n If `split_batch_by` is not None, we \"split\" each batch of the\n dataset by `split_batch_by` value. To achieve this, we first unbatch the\n input dataset and then rebatch it with the per replica batch size that is\n calculated using `global_batch_size // split_batch_by`.\n The currently supported datasets are as follows:\n `dataset.batch()` is the last operation on the dataset OR\n `dataset.apply(map_and_batch)` is the last operation on the dataset OR\n `dataset.batch().prefetch()` are the last 2 operations on the dataset OR\n `dataset.apply(map_and_batch).prefetch()` are the last 2 operations.\n\n TODO(priyag): Support multi worker / host cases properly by cloning\n and sharding the dataset on each worker. Current setup will only work in\n some cases, such as in-graph multi worker GPU case. If the input pipeline\n has random shuffling (with a different seed on each worker), each worker\n will see random input from the same overall dataset in each step. Otherwise,\n each worker will see the same input in each step.\n\n Args:\n dataset: `tf.data.Dataset` that will be used as the input source.\n input_workers: an `InputWorkers` object.\n split_batch_by: Optional integer. If present, we \"split\" each batch of the\n dataset by `split_batch_by` value.\n \"\"\"\n assert isinstance(input_workers, InputWorkers)\n if split_batch_by:\n dataset = _split_dataset_batch(dataset, split_batch_by)\n\n iterators = []\n for i, worker in enumerate(input_workers.worker_devices):\n with ops.device(worker):\n worker_devices = input_workers.compute_devices_for_worker(i)\n cloned_dataset = dataset\n if not context.executing_eagerly():\n cloned_dataset = input_ops._clone_dataset(dataset) # pylint: disable=protected-access\n iterator = _SingleWorkerDatasetIterator(cloned_dataset, worker,\n worker_devices)\n iterators.append(iterator)\n\n super(DatasetIterator, self).__init__(input_workers, iterators)\n\n\nclass _SingleWorkerDatasetIterator(object):\n \"\"\"Iterator for a single `tf.data.Dataset`.\"\"\"\n\n def __init__(self, dataset, worker, devices):\n \"\"\"Create iterator for the `dataset` to fetch data to worker's `devices` .\n\n `MultiDeviceIterator` is used to prefetch input to the devices on the\n given worker. `MultiDeviceIterator` doesn't work in eager mode yet.\n\n Args:\n dataset: A `tf.data.Dataset` instance.\n worker: Worker on which ops should be created.\n devices: Distribute data from `dataset` to these devices.\n \"\"\"\n self._dataset = dataset\n self._worker = worker\n self._devices = devices\n self._is_eager = context.executing_eagerly()\n self._make_iterator()\n\n def _make_iterator(self):\n \"\"\"Make appropriate iterator on the dataset.\"\"\"\n with ops.device(self._worker):\n if self._is_eager:\n # TODO(rohanj): Enable prefetching in eager mode.\n # TODO(priyag): Measure the performance of this approach vs calling\n # get_next on the original dataset N times.\n dataset = self._dataset.batch(len(self._devices), drop_remainder=True)\n iterator = dataset_ops.make_one_shot_iterator(dataset)\n else:\n iterator = multi_device_iterator_ops.MultiDeviceIterator(\n self._dataset, self._devices)\n self._iterator = iterator\n\n def get_next_as_list(self, name=None):\n \"\"\"Get next element from the underlying iterator.\"\"\"\n with ops.device(self._worker):\n if self._is_eager:\n # Batched dataset case.\n batch = self._iterator.get_next(name=name)\n data_list = []\n for i, d in enumerate(self._devices):\n v = nest.map_structure(operator.itemgetter(i), batch)\n with ops.device(d):\n v = nest.map_structure(array_ops.identity, v)\n data_list.append(v)\n else:\n # MultiDeviceIterator case.\n data_list = self._iterator.get_next()\n\n return data_list\n\n def initialize(self):\n \"\"\"Initialze underlying iterator.\n\n In eager execution, this simply recreates the underlying iterator.\n In graph execution, it returns the initializer ops for the underlying\n iterator.\n\n Returns:\n A list of any initializer ops that should be run.\n \"\"\"\n if self._is_eager:\n self._make_iterator()\n return []\n else:\n return [self._iterator.initializer]\n\n @property\n def output_classes(self):\n return self._iterator.output_classes\n\n @property\n def output_shapes(self):\n return self._iterator.output_shapes\n\n @property\n def output_types(self):\n return self._iterator.output_types\n\n\ndef _split_dataset_batch(dataset, split_batch_by):\n \"\"\"Divide a batch-ed dataset's batches into smaller batches.\"\"\"\n # TODO(sourabhbajaj): Remove this in lieu of distributed datasets\n # pylint: disable=protected-access\n def _get_batch_dataset(d):\n \"\"\"Get the underlying batch dataset from the dataset object.\"\"\"\n if isinstance(d, dataset_ops.DatasetV1Adapter):\n d = d._dataset\n\n if isinstance(d, (dataset_ops.BatchDataset, batching._MapAndBatchDataset)):\n return d\n elif isinstance(d, dataset_ops.PrefetchDataset):\n return _get_batch_dataset(d._input_dataset)\n raise ValueError(\n \"Unable to get batched dataset from the input dataset. `batch` \"\n \"`map_and_batch` need to be the last operations on the dataset. \"\n \"The batch operations can be followed by a prefetch.\")\n\n batched_dataset = _get_batch_dataset(dataset)\n if isinstance(batched_dataset, dataset_ops.BatchDataset):\n batch_size = batched_dataset._batch_size\n drop_remainder = batched_dataset._drop_remainder\n elif isinstance(batched_dataset, batching._MapAndBatchDataset):\n batch_size = batched_dataset._batch_size_t\n drop_remainder = batched_dataset._drop_remainder_t\n\n prefetch_buffer = None\n if isinstance(dataset, dataset_ops.PrefetchDataset):\n prefetch_buffer = dataset._buffer_size\n # pylint: enable=protected-access\n\n if tensor_util.is_tensor(batch_size):\n batch_size = tensor_util.constant_value(batch_size)\n\n if tensor_util.is_tensor(drop_remainder):\n drop_remainder = tensor_util.constant_value(drop_remainder)\n\n if batch_size % split_batch_by:\n raise ValueError(\n \"Batch size %s cannot be sharded evenly across replicas %s\" % (\n batch_size, split_batch_by))\n new_batch_size = batch_size // split_batch_by\n\n dataset = dataset.apply(batching.unbatch())\n dataset = dataset.batch(new_batch_size, drop_remainder=drop_remainder)\n if prefetch_buffer is not None:\n dataset = dataset.prefetch(prefetch_buffer)\n return dataset\n\n\nclass MultiStepContext(object):\n \"\"\"A context object that can be used to capture things when running steps.\n\n This context object is useful when running multiple steps at a time using the\n `experimental_run_steps_on_iterator` API. For e.g. it allows the user's step\n function to specify which outputs to emit at what frequency. Currently it\n supports capturing output from the last step, as well as capturing non tensor\n outputs. In the future it will be augmented to support other use cases such\n as output each N steps.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize an output context.\n\n Returns:\n A context object.\n \"\"\"\n self._last_step_outputs = {}\n self._last_step_outputs_reduce_ops = {}\n self._non_tensor_outputs = {}\n\n @property\n def last_step_outputs(self):\n \"\"\"A dictionary consisting of outputs to be captured on last step.\n\n Keys in the dictionary are names of tensors to be captured, as specified\n when `set_last_step_output` is called.\n Values in the dictionary are the tensors themselves. If\n `set_last_step_output` was called with a `reduce_op` for this output,\n then the value is the reduced value.\n\n Returns:\n A dictionary with last step outputs.\n \"\"\"\n return self._last_step_outputs\n\n def _set_last_step_outputs(self, outputs):\n \"\"\"Replace the entire dictionary of last step outputs.\"\"\"\n if not isinstance(outputs, dict):\n raise ValueError(\"Need a dictionary to set last_step_outputs.\")\n self._last_step_outputs = outputs\n\n def set_last_step_output(self, name, output, reduce_op=None):\n \"\"\"Set `output` with `name` to be outputted from the last step.\n\n Args:\n name: String, name to identify the output. Doesn't need to match tensor\n name.\n output: The tensors that should be outputted with `name`. See below for\n actual types supported.\n reduce_op: Reduction method to use to reduce outputs from multiple\n replicas. Required if `set_last_step_output` is called in a replica\n context. Optional in cross_replica_context.\n When present, the outputs from all the replicas are reduced using the\n current distribution strategy's `reduce` method. Hence, the type of\n `output` must be what's supported by the corresponding `reduce` method.\n For e.g. if using MirroredStrategy and reduction is set, output\n must be a `PerReplica` value.\n The reduce method is also recorded in a dictionary\n `_last_step_outputs_reduce_ops` for later interpreting of the\n outputs as already reduced or not.\n \"\"\"\n if distribution_strategy_context.in_cross_replica_context():\n self._last_step_outputs_reduce_ops[name] = reduce_op\n if reduce_op is None:\n self._last_step_outputs[name] = output\n else:\n distribution = distribution_strategy_context.get_distribution_strategy()\n self._last_step_outputs[name] = distribution.reduce(reduce_op, output)\n else:\n assert reduce_op is not None\n def merge_fn(distribution, value):\n self._last_step_outputs[name] = distribution.reduce(reduce_op, value)\n # Setting this inside the `merge_fn` because all replicas share the same\n # context object, so it's more robust to set it only once (even if all\n # the replicas are trying to set the same value).\n self._last_step_outputs_reduce_ops[name] = reduce_op\n\n distribution_strategy_context.get_replica_context().merge_call(\n merge_fn, args=(output,))\n\n @property\n def non_tensor_outputs(self):\n \"\"\"A dictionary consisting of any non tensor outputs to be captured.\"\"\"\n return self._non_tensor_outputs\n\n def set_non_tensor_output(self, name, output):\n \"\"\"Set `output` with `name` to be captured as a non tensor output.\"\"\"\n if distribution_strategy_context.in_cross_replica_context():\n self._non_tensor_outputs[name] = output\n else:\n def merge_fn(distribution, value):\n # NOTE(priyag): For non tensor outputs, we simply return all the values\n # in a list as reduction doesn't make sense on non tensors.\n self._non_tensor_outputs[name] = distribution.unwrap(value)\n distribution_strategy_context.get_replica_context().merge_call(\n merge_fn, args=(output,))\n\n\ndef value_container(val):\n \"\"\"Returns the container that this per-replica `value` belongs to.\n\n Args:\n val: A value returned by `call_for_each_replica()` or a variable\n created in `scope()`.\n\n Returns:\n A container that `value` belongs to.\n If value does not belong to any container (including the case of\n container having been destroyed), returns the value itself.\n \"\"\"\n if (hasattr(val, \"_distributed_container\") and\n # DistributedVariable has _distributed_container defined\n # but we don't want to return it.\n not isinstance(val, DistributedVariable)):\n container = val._distributed_container() # pylint: disable=protected-access\n if container is not None:\n return container\n return val\n\n\n# TODO(josh11b): Descend from Variable.\nclass AggregatingVariable(checkpointable.CheckpointableBase):\n \"\"\"A wrapper around a variable that aggregates updates across replicas.\"\"\"\n\n def __init__(self, strategy, v, aggregation):\n self._distribute_strategy = strategy\n self._v = v\n # NOTE: We don't use \"_distributed_container\" here because we don't want\n # to trigger that code path in regroup().\n v._aggregating_container = weakref.ref(self) # pylint: disable=protected-access\n self._aggregation = aggregation\n\n def get(self):\n return self._v\n\n @property\n def distribute_strategy(self):\n return self._distribute_strategy\n\n def __getattr__(self, name):\n return getattr(self._v, name)\n\n def _assign_func(self, *args, **kwargs):\n _assert_strategy(self._distribute_strategy)\n f = kwargs.pop(\"f\")\n if distribution_strategy_context.in_cross_replica_context():\n update_device = distribute_lib.get_update_device()\n if update_device is not None:\n # We are calling an assign function in an update context.\n return f(self._v, *args, **kwargs)\n\n # We are calling an assign function in cross replica context, wrap it in\n # an update call.\n return self._distribute_strategy.update(self, f, *args, **kwargs)\n else:\n replica_context = distribution_strategy_context.get_replica_context()\n assert replica_context\n # We are calling an assign function in replica context.\n # We reduce the value we want to assign/add/sub. More details about how we\n # handle the different use cases can be found in the _reduce method.\n # We call the function with the reduced value.\n if self._aggregation == vs.VariableAggregation.NONE:\n raise ValueError(\"You must specify an aggregation method to update a \"\n \"a variable in replica context.\")\n\n def merge_fn(strategy, value, *other_args, **other_kwargs):\n v = _apply_aggregation(strategy, value, self._aggregation, self)\n return strategy.update(self, f, v, *other_args, **other_kwargs)\n\n return replica_context.merge_call(merge_fn, args=args, kwargs=kwargs)\n\n def assign_sub(self, *args, **kwargs):\n assign_sub_fn = lambda var, *a, **kw: var.assign_sub(*a, **kw)\n return self._assign_func(f=assign_sub_fn, *args, **kwargs)\n\n def assign_add(self, *args, **kwargs):\n assign_add_fn = lambda var, *a, **kw: var.assign_add(*a, **kw)\n return self._assign_func(f=assign_add_fn, *args, **kwargs)\n\n def assign(self, *args, **kwargs):\n assign_fn = lambda var, *a, **kw: var.assign(*a, **kw)\n return self._assign_func(f=assign_fn, *args, **kwargs)\n\n @property\n def aggregation(self):\n return self._aggregation\n\n @property\n def name(self):\n return self._v.name\n\n @property\n def dtype(self):\n return self._v.dtype\n\n # TODO(josh11b): Test saving & restoring.\n def _gather_saveables_for_checkpoint(self):\n return {checkpointable.VARIABLE_VALUE_KEY: self._v}\n\n # pylint: disable=multiple-statements\n def __add__(self, o): return self._v + o\n def __radd__(self, o): return o + self._v\n def __sub__(self, o): return self._v - o\n def __rsub__(self, o): return o - self._v\n def __mul__(self, o): return self._v * o\n def __rmul__(self, o): return o * self._v\n def __truediv__(self, o): return self._v / o\n def __rtruediv__(self, o): return o / self._v\n def __floordiv__(self, o): return self._v // o\n def __rfloordiv__(self, o): return o // self._v\n def __mod__(self, o): return self._v % o\n def __rmod__(self, o): return o % self._v\n def __lt__(self, o): return self._v < o\n def __le__(self, o): return self._v <= o\n def __gt__(self, o): return self._v > o\n def __ge__(self, o): return self._v >= o\n def __and__(self, o): return self._v & o\n def __rand__(self, o): return o & self._v\n def __or__(self, o): return self._v | o\n def __ror__(self, o): return o | self._v\n def __xor__(self, o): return self._v ^ o\n def __rxor__(self, o): return o ^ self._v\n def __getitem__(self, o): return self._v[o]\n def __pow__(self, o, modulo=None): return pow(self._v, o, modulo)\n def __rpow__(self, o): return pow(o, self._v)\n def __invert__(self): return ~self._v\n def __neg__(self): return -self._v\n def __abs__(self): return abs(self._v)\n\n def __div__(self, o):\n try:\n return self._v.__div__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __rdiv__(self, o):\n try:\n return self._v.__rdiv__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __matmul__(self, o):\n try:\n return self._v.__matmul__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __rmatmul__(self, o):\n try:\n return self._v.__rmatmul__(o)\n except AttributeError:\n # See https://docs.python.org/3/library/constants.html#NotImplemented\n return NotImplemented\n\n def __str__(self):\n return str(self._v)\n\n def __repr__(self):\n return repr(self._v)\n\n def _should_act_as_resource_variable(self):\n \"\"\"Pass resource_variable_ops.is_resource_variable check.\"\"\"\n pass\n\n\n# Register a conversion function which reads the value of the variable,\n# allowing instances of the class to be used as tensors.\ndef _tensor_conversion_aggregate(var, dtype=None, name=None, as_ref=False):\n return ops.internal_convert_to_tensor(\n var.get(), dtype=dtype, name=name, as_ref=as_ref)\n\n\nops.register_tensor_conversion_function(\n AggregatingVariable, _tensor_conversion_aggregate)\nops.register_dense_tensor_like_type(AggregatingVariable)\n" ]
[ [ "tensorflow.python.data.experimental.ops.batching.unbatch", "tensorflow.python.distribute.distribution_strategy_context.get_distribution_strategy", "tensorflow.python.data.ops.dataset_ops.make_one_shot_iterator", "tensorflow.python.framework.device.DeviceSpec.from_string", "tensorflow.python.framework.ops.register_dense_tensor_like_type", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.distribute.distribution_strategy_context.has_distribution_strategy", "tensorflow.python.util.nest.map_structure", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.framework.ops.register_tensor_conversion_function", "tensorflow.python.distribute.distribution_strategy_context.in_cross_replica_context", "tensorflow.python.data.ops.dataset_ops.make_initializable_iterator", "tensorflow.python.framework.tensor_util.is_tensor", "tensorflow.python.eager.tape.variable_accessed", "tensorflow.python.training.saver.BaseSaverBuilder.SaveSpec", "tensorflow.python.distribute.device_util.current", "tensorflow.python.framework.ops.has_default_graph", "tensorflow.python.distribute.device_util.canonicalize", "tensorflow.python.data.ops.multi_device_iterator_ops.MultiDeviceIterator", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.util.nest.pack_sequence_as", "tensorflow.python.distribute.distribution_strategy_context.get_replica_context", "tensorflow.python.ops.gen_resource_variable_ops.read_variable_op", "tensorflow.python.ops.math_ops.add_n", "tensorflow.python.distribute.input_ops._clone_dataset", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.distribute.reduce_util.ReduceOp.from_variable_aggregation", "tensorflow.python.util.nest.flatten", "tensorflow.python.distribute.distribute_lib.get_update_device" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sigmaai/behavioral-cloning
[ "3e9c9fa638de78dbb7cf61d80cc53b275aa0d3e6" ]
[ "visualization.py" ]
[ "\n# Dataset visualization tool\n# Original By: Comma.ai and Chris Gundling\n# Revised and used by Neil Nie\n\n\nimport matplotlib.backends.backend_agg as agg\nfrom i3d import Inception3D\nimport pandas as pd\nfrom os import path\nimport numpy as np\nimport cv2\nimport pygame\nimport pylab\nimport helper\nimport configs\n\n\npygame.init()\nsize = (640, 660)\npygame.display.set_caption(\"self driving data viewer\")\nscreen = pygame.display.set_mode(size, pygame.DOUBLEBUF)\nscreen.set_alpha(None)\n\ncamera_surface = pygame.surface.Surface((640, 480),0,24).convert()\nclock = pygame.time.Clock()\n\nPI_RAD = (180 / np.pi)\nred = (255, 0, 0)\nblue = (0, 0, 255)\n\n# ***** get perspective transform for images *****\nfrom skimage import transform as tf\n\nrsrc = \\\n [[43.45456230828867, 118.00743250075844],\n [104.5055617352614, 69.46865203761757],\n [114.86050156739812, 60.83953551083698],\n [129.74572757609468, 50.48459567870026],\n [132.98164627363735, 46.38576532847949],\n [301.0336906326895, 98.16046448916306],\n [238.25686790036065, 62.56535881619311],\n [227.2547443287154, 56.30924933427718],\n [209.13359962247614, 46.817221154818526],\n [203.9561297064078, 43.5813024572758]]\nrdst = \\\n [[10.822125594094452, 1.42189132706374],\n [21.177065426231174, 1.5297552836484982],\n [25.275895776451954, 1.42189132706374],\n [36.062291434927694, 1.6376192402332563],\n [40.376849698318004, 1.42189132706374],\n [11.900765159942026, -2.1376192402332563],\n [22.25570499207874, -2.1376192402332563],\n [26.785991168638553, -2.029755283648498],\n [37.033067044190524, -2.029755283648498],\n [41.67121717733509, -2.029755283648498]]\n\ntform3_img = tf.ProjectiveTransform()\ntform3_img.estimate(np.array(rdst), np.array(rsrc))\n\n\ndef perspective_tform(x, y):\n p1, p2 = tform3_img((x, y))[0]\n return p2, p1\n\n\n# ***** functions to draw lines *****\ndef draw_pt(img, x, y, color, sz=2):\n row, col = perspective_tform(x, y)\n row = row * 2\n col = col * 2\n if row >= 0 and row < img.shape[0] * 2 / 2 and col >= 0 and col < img.shape[1] * 2 / 2:\n img[int(row - sz):int(row + sz), int(col - sz):int(col + sz)] = color\n\n\ndef draw_path(img, path_x, path_y, color):\n for x, y in zip(path_x, path_y):\n draw_pt(img, x, y, color)\n\n\n# ***** functions to draw predicted path *****\n\ndef calc_curvature(v_ego, angle_steers, angle_offset=0):\n slip_fator = 0.0014 # slip factor obtained from real data\n steer_ratio = 15.3 # from http://www.edmunds.com/acura/ilx/2016/road-test-specs/\n wheel_base = 2.67 # from http://www.edmunds.com/acura/ilx/2016/sedan/features-specs/\n\n angle_steers_rad = (angle_steers - angle_offset) # * deg_to_rad\n curvature = angle_steers_rad / (steer_ratio * wheel_base * (1. + slip_fator * v_ego ** 2))\n return curvature\n\ndef calc_lookahead_offset(v_ego, angle_steers, d_lookahead, angle_offset=0):\n # *** this function returns the lateral offset given the steering angle, speed and the lookahead distance\n curvature = calc_curvature(v_ego, angle_steers, angle_offset)\n\n # clip is to avoid arcsin NaNs due to too sharp turns\n y_actual = d_lookahead * np.tan(np.arcsin(np.clip(d_lookahead * curvature, -0.999, 0.999)) / 2.)\n return y_actual, curvature\n\n\ndef draw_path_on(img, speed_ms, angle_steers, color=(0, 0, 255)):\n path_x = np.arange(0, 50.1, 0.5) # 50.1\n path_y, _ = calc_lookahead_offset(speed_ms, angle_steers, path_x)\n draw_path(img, path_x, path_y, color)\n\n\ndef steering_loop(model_path):\n\n # loading models\n model = Inception3D(weights_path=model_path,\n input_shape=(configs.LENGTH, configs.IMG_HEIGHT, configs.IMG_WIDTH, configs.CHANNELS))\n model.summary()\n\n # steerings and images\n steering_labels = path.join(configs.VAL_DIR, 'labels.csv')\n\n # read the steering labels and image path\n df_truth = pd.read_csv(steering_labels, usecols=['frame_id', 'steering_angle'], index_col=None)\n\n # Create second screen with matplotlibs\n fig = pylab.figure(figsize=[6.4, 1.8], dpi=100)\n ax = fig.gca()\n ax.tick_params(axis='x', labelsize=8)\n ax.tick_params(axis='y', labelsize=8)\n line1, = ax.plot([], [], 'b.-', label='Human')\n line2, = ax.plot([], [], 'r.-', label='Model')\n a = []\n b = []\n ax.legend(loc='upper left', fontsize=8)\n\n my_font = pygame.font.SysFont(\"monospace\", 18)\n rand_num_label = my_font.render('Human Steer Angle:', 1, blue)\n rand_num_label2 = my_font.render('Model Steer Angle:', 1, red)\n speed_ms = 5\n\n inputs = []\n\n for i in range(configs.LENGTH):\n file = configs.VAL_DIR + \"center/\" + str(df_truth['frame_id'].loc[i]) + \".jpg\"\n img = helper.load_image(file)\n inputs.append(img)\n\n # Run through all images\n for i in range(configs.LENGTH, len(df_truth)):\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n break\n\n img = helper.load_image(configs.VAL_DIR + \"center/\" + str(df_truth['frame_id'].loc[i]) + \".jpg\", auto_resize=False)\n in_frame = cv2.resize(img, (configs.IMG_WIDTH, configs.IMG_HEIGHT))\n inputs.pop(0)\n inputs.append(in_frame)\n prediction = model.model.predict(np.array([inputs]))[0][0]\n actual_steers = df_truth['steering_angle'].loc[i]\n\n draw_path_on(img, speed_ms, actual_steers / 2) # human is blue\n draw_path_on(img, speed_ms, prediction / 2, (255, 0, 0)) # prediction is red\n\n a.append(actual_steers)\n b.append(prediction)\n line1.set_ydata(a)\n line1.set_xdata(range(len(a)))\n line2.set_ydata(b)\n line2.set_xdata(range(len(b)))\n ax.relim()\n ax.autoscale_view()\n\n canvas = agg.FigureCanvasAgg(fig)\n canvas.draw()\n renderer = canvas.get_renderer()\n raw_data = renderer.tostring_rgb()\n size = canvas.get_width_height()\n surf = pygame.image.fromstring(raw_data, size, \"RGB\")\n screen.blit(surf, (0, 480))\n\n # draw on\n pygame.surfarray.blit_array(camera_surface, img.swapaxes(0, 1))\n screen.blit(camera_surface, (0, 0))\n\n diceDisplay = my_font.render(str(round(actual_steers * PI_RAD, 4)), 1, blue)\n diceDisplay2 = my_font.render(str(round(prediction * PI_RAD, 4)), 1, red)\n screen.blit(rand_num_label, (50, 420))\n screen.blit(rand_num_label2, (400, 420))\n screen.blit(diceDisplay, (50, 450))\n screen.blit(diceDisplay2, (400, 450))\n clock.tick(60)\n pygame.display.flip()\n\n\nif __name__ == \"__main__\":\n\n steering_loop(model_path='i3d_small_v2.h5')" ]
[ [ "pandas.read_csv", "numpy.clip", "matplotlib.backends.backend_agg.FigureCanvasAgg", "numpy.arange", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Animadversio/FloodFillNetwork-Notes
[ "c4d207e53db1c2befc79fbc0ef0451d6f877c868" ]
[ "run_inference_script.py" ]
[ "# Copyright 2017 Google 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# https://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\"\"\"Runs FFN inference\nThis simple script aims at run a less sophisticated inference from several preselected seeds\nand inspect the single seed segmentation result.\n\"\"\"\n\nimport os\nimport time\n\nfrom google.protobuf import text_format\nfrom absl import app\nfrom absl import flags\nimport ast\nfrom tensorflow import gfile\nimport numpy as np\nimport sys\nimport logging\nimport logging.config\n# logging.getLogger().setLevel(logging.INFO)\nlogger = logging.getLogger(__name__)\n# logging.config.fileConfig(json.load(open('configs/logging.json')), disable_existing_loggers=False)\nlogging.config.dictConfig({\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"standard\": {\n \"format\": \"%(asctime)s [%(filename)s: %(funcName)s(): %(lineno)d] %(message)s\"\n },\n },\n \"handlers\": {\n \"default\": {\n \"level\":\"INFO\",\n \"class\":\"logging.StreamHandler\",\n },\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"level\": \"INFO\",\n \"formatter\": \"standard\",\n \"stream\": \"ext://sys.stdout\"\n },\n \"logfile\": {\n \"class\": \"logging.FileHandler\",\n \"level\": \"INFO\",\n \"formatter\": \"standard\",\n \"filename\": \"inference_log_new.log\",\n \"encoding\": \"utf8\"\n }\n },\n \"loggers\": {\n \"\": {\n \"handlers\": [\"console\", \"logfile\"],\n \"level\": \"INFO\",\n \"propagate\": True\n }\n }\n})\nlogging.info(\"Logger prepared! \")\n# handlers = [logging.StreamHandler(sys.stdout),\n# logging.FileHandler('/home/morganlab/PycharmProjects/FloodFillNetwork-Notes/inference_log3.log'), ]\n# logging.basicConfig(level=logging.INFO, handlers=handlers, disable_existing_loggers=False,\n# format=('%(asctime)s [%(filename)s: %(funcName)s(): %(lineno)d] %(message)s'))\n\nfrom ffn.utils import bounding_box_pb2\nfrom ffn.inference import inference\nfrom ffn.inference import inference_pb2\nfrom ffn.inference import storage\nfrom scipy.special import expit, logit\n\ncorner = (0, 0, 0)\ndownsample_factor = 1\n#%%\n# Model on LGN of mice\n# \"models/LR_model_Longtime/model.ckpt-264380\"\nconfig = '''image {\n hdf5: \"/home/morganlab/Downloads/ffn-master/third_party/LGN_DATA/grayscale_maps_LR.h5:raw\"\n}\nimage_mean: 136\nimage_stddev: 55\ncheckpoint_interval: 1200\nseed_policy: \"PolicyPeaks\"\nmodel_checkpoint_path: \"/home/morganlab/Downloads/ffn-master/models/LR_model_Longtime/model.ckpt-1127307\"\nmodel_name: \"convstack_3d.ConvStack3DFFNModel\"\nmodel_args: \"{\\\\\"depth\\\\\": 9, \\\\\"fov_size\\\\\": [55, 37, 17], \\\\\"deltas\\\\\": [9,6,3]}\"\nsegmentation_output_dir: \"/home/morganlab/Downloads/ffn-master/results/LGN/testing_LR_Longtime_point3\"\ninference_options {\n init_activation: 0.95\n pad_value: 0.05\n move_threshold: 0.90\n min_boundary_dist { x: 5 y: 5 z: 1}\n segment_threshold: 0.6\n min_segment_size: 1000\n disco_seed_threshold: 0.005\n}'''\nseed_list = [(1080, 860, 72), (1616, 1872, 43), (612, 1528, 92), (616, 180, 92), (144, 712, 43), (400, 168, 45), (1332, 248, 45), (120, 700,45)] # in xyz order\ndownsample_factor = 2\ncanvas_bbox = [(0, 0, 0), (175, 1058, 1180)]\n\n#%%\nast.literal_eval()\n#%%\nrequest = inference_pb2.InferenceRequest()\n_ = text_format.Parse(config, request)\nif not gfile.Exists(request.segmentation_output_dir):\n gfile.MakeDirs(request.segmentation_output_dir)\nrunner = inference.Runner()\nrunner.start(request)\ncanvas, alignment = runner.make_canvas(canvas_bbox[0], canvas_bbox[1]) # like (0, 0, 0), (175, 1058, 1180)\nfor id, start_point in enumerate(seed_list):\n label = id + 1\n pos = (int(start_point[2]-corner[2]), int((start_point[1]-corner[1])//downsample_factor), int((start_point[0]-corner[0])//downsample_factor))\n canvas.log_info('Starting segmentation at %r (zyx)', pos)\n num_iters = canvas.segment_at(pos,) # zyx\n # dynamic_image=inference.DynamicImage(),\n # vis_update_every=2, vis_fixed_z=True)\n mask = canvas.seed >= request.inference_options.segment_threshold\n\n raw_segmented_voxels = np.sum(mask) # count the number of raw segmented voxels\n # Record existing segment IDs overlapped by the newly added object.\n overlapped_ids, counts = np.unique(canvas.segmentation[mask],\n return_counts=True)\n valid = overlapped_ids > 0 # id < 0 are the background and invalid voxels\n overlapped_ids = overlapped_ids[valid]\n counts = counts[valid]\n if len(counts) > 0:\n print('Overlapping segments (label, size): ', *zip(overlapped_ids, counts), sep=\" \")\n\n mask &= canvas.segmentation <= 0 # get rid of the marked voxels from mask\n actual_segmented_voxels = np.sum(mask) # only count those unmarked voxel in `actual_segmented_voxels`\n canvas.segmentation[mask] = label\n canvas.log_info('Created supervoxel:%d seed(zyx):%s size:%d (raw size %d) iters:%d',\n label, pos, actual_segmented_voxels, raw_segmented_voxels, num_iters)\n\n np.savez(os.path.join(request.segmentation_output_dir, 'seg%03d_%s.npz' % (label, str(start_point))),\n segmentation=mask,\n prob=storage.quantize_probability(\n expit(canvas.seed)))\n\ncounter_path = os.path.join(request.segmentation_output_dir, 'counters.txt')\nif not gfile.Exists(counter_path):\n runner.counters.dump(counter_path)\n#%%\ncorner = (0,0,0)\nseg_path = storage.segmentation_path(\n request.segmentation_output_dir, corner)\nprob_path = storage.object_prob_path(\n request.segmentation_output_dir, corner)\nrunner.save_segmentation(canvas, alignment, seg_path, prob_path)\n\n\n\n\n\n\n\n" ]
[ [ "scipy.special.expit", "numpy.unique", "tensorflow.gfile.Exists", "tensorflow.gfile.MakeDirs", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yanghr/Hoyer_MNIST
[ "2a50da067ba10f2fc783624f448fb5ca91914ff6" ]
[ "mnist/CNN/prun_tune_T.py" ]
[ "import argparse\nimport os\n\nimport numpy as np\nimport scipy.io as sio\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom tqdm import tqdm\n\nfrom net.models import LeNet_5 as LeNet\nimport util\n\nos.makedirs('saves', exist_ok=True)\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch MNIST pruning from deep compression paper')\nparser.add_argument('--batch-size', type=int, default=100, metavar='N',\n help='input batch size for training (default: 100)')\nparser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\nparser.add_argument('--epochs', type=int, default=100, metavar='N',\n help='number of epochs to train (default: 100)')\nparser.add_argument('--lr', type=float, default=0.0001, metavar='LR',\n help='learning rate (default: 0.01)') \nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\nparser.add_argument('--seed', type=int, default=12345678, metavar='S',\n help='random seed (default: 42)')\nparser.add_argument('--log-interval', type=int, default=100, metavar='N',\n help='how many batches to wait before logging training status')\nparser.add_argument('--log', type=str, default='log.txt',\n help='log file name')\nparser.add_argument('--model', type=str, default='saves/initial_model',\n help='path to model pretrained with sparsity-inducing regularizer') \nparser.add_argument('--sensitivity', type=float, default=0.001,\n help=\"pruning threshold set as the sensitivity value\")\nargs = parser.parse_args()\n\n# Control Seed\ntorch.manual_seed(args.seed)\n\n# Select Device\nuse_cuda = not args.no_cuda and torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else 'cpu')\nif use_cuda:\n print(\"Using CUDA!\")\n torch.cuda.manual_seed(args.seed)\nelse:\n print('Not using CUDA!!!')\n\n# Loader\nkwargs = {'num_workers': 5, 'pin_memory': True} if use_cuda else {}\ntrain_loader = torch.utils.data.DataLoader(\n datasets.MNIST('data', train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor()])),\n batch_size=args.batch_size, shuffle=True, **kwargs)\ntest_loader = torch.utils.data.DataLoader(\n datasets.MNIST('data', train=False, transform=transforms.Compose([\n transforms.ToTensor()])),\n batch_size=args.test_batch_size, shuffle=False, **kwargs)\n\n\n# Define which model to use\nmodel = LeNet(mask=False).to(device)\n\n# NOTE : `weight_decay` term denotes L2 regularization loss term\noptimizer = optim.Adam(model.parameters(), lr=args.lr)\ninitial_optimizer_state_dict = optimizer.state_dict()\n\ndef train(epochs):\n model.train()\n pbar = tqdm(range(epochs), total=epochs)\n for epoch in pbar:\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target)\n total_loss = loss\n \n total_loss.backward()\n\n # zero-out all the gradients corresponding to the pruned connections\n for name, p in model.named_parameters():\n if 'mask' in name:\n continue\n tensor = p.data.cpu().numpy()\n grad_tensor = p.grad.data.cpu().numpy()\n grad_tensor = np.where(tensor==0, 0, grad_tensor)\n p.grad.data = torch.from_numpy(grad_tensor).to(device)\n\n optimizer.step()\n \n \n if batch_idx % args.log_interval == 0:\n done = batch_idx * len(data)\n percentage = 100. * batch_idx / len(train_loader)\n pbar.set_description(f'Train Epoch: {epoch} [{done:5}/{len(train_loader.dataset)} ({percentage:3.0f}%)] Loss: {loss.item():.6f} Total: {total_loss.item():.6f}')\n\n\ndef test():\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n pred = output.data.max(1, keepdim=True)[1] # get the index of the max log-probability\n correct += pred.eq(target.data.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n accuracy = 100. * correct / len(test_loader.dataset)\n print(f'Test set: Average loss: {test_loss:.4f}, Accuracy: {correct}/{len(test_loader.dataset)} ({accuracy:.2f}%)')\n return accuracy\n\n\nmodel.load_state_dict(torch.load(args.model+'.pth'))\n# Initial training\nprint(\"--- Pruning ---\")\nfor name, p in model.named_parameters():\n if 'mask' in name:\n continue\n tensor = p.data.cpu().numpy()\n new_mask = np.where(abs(tensor) < args.sensitivity, 0, tensor)\n p.data = torch.from_numpy(new_mask).to(device)\n\naccuracy = test()\nutil.print_nonzeros(model)\n\nprint(\"--- Finetuning ---\")\ntrain(args.epochs)\naccuracy = test()\ntorch.save(model.state_dict(), args.model+'_T_'+str(args.sensitivity)+'.pth')\n\n" ]
[ [ "torch.cuda.manual_seed", "torch.load", "torch.nn.functional.nll_loss", "torch.manual_seed", "torch.from_numpy", "torch.no_grad", "torch.cuda.is_available", "torch.device", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MittalNeha/vision_pytorch
[ "886e4e19d2ddf0d03f5fefdfd001ff6dd67560ac" ]
[ "utils/gradcam.py" ]
[ "import matplotlib.cm as cm\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn.functional as F\r\n\r\n\r\nclass GradCAM():\r\n '''Implementation for Grad-CAM\r\n Steps:\r\n - Load a pre-trained model\r\n - Load an image that can be processed by this model (224x224 for VGG16 why?)\r\n - Infer the image and get the topmost class index\r\n - Take the output of the final convolutional layer\r\n - Compute the gradient of the class output value w.r.t to L feature maps\r\n - Pool the gradients over all the axes leaving out the channel dimension\r\n - Weigh the output feature map with the computed gradients (+ve)\r\n - Average the weighted feature maps along channels\r\n - Normalize the heat map to make the values between 0 and 1\r\n '''\r\n def __init__(self, model_layer):\r\n self.fmap = None\r\n self.grad = None\r\n\r\n #Register the forward and backward hooks\r\n handle_fw = model_layer.register_forward_hook(self.fwd_hook)\r\n handle_bw = model_layer.register_backward_hook(self.bkw_hook)\r\n self.handles = [handle_fw, handle_bw]\r\n \r\n def fwd_hook(self, module, input, output):\r\n print(module)\r\n self.fmap = output.detach()\r\n print('Inside ' + self.__class__.__name__ + ' forward')\r\n # print('')\r\n # print('input: ', type(input))\r\n # print('input[0]: ', type(input[0]))\r\n # print('output: ', type(output))\r\n # print('')\r\n # print('input size:', input[0].size())\r\n # print('output size:', output.data.size())\r\n # print('output norm:', output.data.norm())\r\n\r\n def bkw_hook(self, module, grad_input, grad_output):\r\n self.grad = grad_output[0].detach()\r\n print('Inside ' + self.__class__.__name__ + ' backward')\r\n # print('')\r\n # print('grad_input: ', type(grad_input))\r\n # print('grad_input[0]: ', type(grad_input[0]))\r\n # print('grad_output: ', type(grad_output))\r\n # print('grad_output[0]: ', type(grad_output[0]))\r\n # print('')\r\n # print('grad_input size:', grad_input[0].size())\r\n # print('grad_output size:', grad_output[0].size())\r\n # print('grad_input norm:', grad_input[0].norm())\r\n # print(self.grad.shape)\r\n\r\n def remove_hooks(self):\r\n for handle in self.handles:\r\n handle.remove()\r\n\r\n def generate(self, inputs, input_shape, index):\r\n\r\n grad = self.grad[index].unsqueeze(dim=0)\r\n fmap = self.fmap[index].unsqueeze(dim=0)\r\n\r\n input_image = inputs[index]\r\n # print(input_image.shape)\r\n input_image = input_image.numpy()\r\n input_image = np.transpose(input_image, (1,2,0))\r\n\r\n weights = F.adaptive_avg_pool2d(grad, 1)\r\n # print(weights.shape)\r\n\r\n gcam = torch.mul(fmap, weights).sum(dim=1, keepdim=True)\r\n # print(gcam.shape)\r\n\r\n gcam = F.relu(gcam)\r\n gcam = F.interpolate(\r\n gcam, input_shape, mode=\"bilinear\", align_corners=False\r\n )\r\n\r\n B, C, H, W = gcam.shape\r\n gcam = gcam.view(B, -1)\r\n gcam -= gcam.min(dim=1, keepdim=True)[0]\r\n gcam /= gcam.max(dim=1, keepdim=True)[0]\r\n gcam = gcam.view(B, C, H, W)\r\n\r\n #get the heatmap\r\n gcam = gcam.numpy() \r\n cmap = cm.jet(gcam)[..., :3] #* 255.0\r\n gcam_image = (cmap.astype(np.float) + input_image.astype(np.float)) / 2\r\n\r\n return gcam_image\r\n\r\n\r\n" ]
[ [ "torch.nn.functional.adaptive_avg_pool2d", "torch.nn.functional.relu", "torch.mul", "torch.nn.functional.interpolate", "numpy.transpose", "matplotlib.cm.jet" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
arjunsavel/astroML
[ "d378ca41565d1aa39997191d13d46d09d104ff1d" ]
[ "examples/datasets/plot_sdss_specgals.py" ]
[ "\"\"\"\nSDSS Spectroscopic Galaxy Sample\n--------------------------------\nThis figure shows photometric colors of the SDSS spectroscopic galaxy\nsample.\n\"\"\"\n# Author: Jake VanderPlas <[email protected]>\n# License: BSD\n# The figure is an example from astroML: see http://astroML.github.com\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom astropy.visualization import hist\n\nfrom astroML.datasets import fetch_sdss_specgals\n\ndata = fetch_sdss_specgals()\n\n#------------------------------------------------------------\n# plot the RA/DEC in an area-preserving projection\n\nRA = data['ra']\nDEC = data['dec']\n\n# convert coordinates to degrees\nRA -= 180\nRA *= np.pi / 180\nDEC *= np.pi / 180\n\nax = plt.axes(projection='mollweide')\n\nax.grid()\nplt.scatter(RA, DEC, s=1, lw=0, c=data['z'], cmap=plt.cm.copper,\n vmin=0, vmax=0.4)\n\nplt.title('SDSS DR8 Spectroscopic Galaxies')\ncb = plt.colorbar(cax=plt.axes([0.05, 0.1, 0.9, 0.05]),\n orientation='horizontal',\n ticks=np.linspace(0, 0.4, 9))\ncb.set_label('redshift')\n\n\n#------------------------------------------------------------\n# plot the r vs u-r color-magnitude diagram\nu = data['modelMag_u']\nr = data['modelMag_r']\nrPetro = data['petroMag_r']\n\nplt.figure()\nax = plt.axes()\nplt.scatter(u - r, rPetro, s=1, lw=0, c=data['z'], cmap=plt.cm.copper,\n vmin=0, vmax=0.4)\nplt.colorbar(ticks=np.linspace(0, 0.4, 9)).set_label('redshift')\n\nplt.xlim(0.5, 5.5)\nplt.ylim(18, 12.5)\n\nplt.xlabel('u-r')\nplt.ylabel('rPetrosian')\n\n#------------------------------------------------------------\n# plot a histogram of the redshift\n\nplt.figure()\nhist(data['z'], bins='knuth',\n histtype='stepfilled', ec='k', fc='#F5CCB0')\nplt.xlim(0, 0.4)\nplt.xlabel('z (redshift)')\nplt.ylabel('dN/dz(z)')\n\nplt.show()\n" ]
[ [ "matplotlib.pyplot.title", "matplotlib.pyplot.scatter", "numpy.linspace", "matplotlib.pyplot.ylim", "matplotlib.pyplot.axes", "matplotlib.pyplot.xlim", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mikalst/MFClassifier
[ "f12dd17764817871cab0b34e309124a880475e2d" ]
[ "mfclassifier/utils/saving.py" ]
[ "import json\nimport numpy as np\nimport os\n\n\ndef save_ridge(\n parameters_simulate_ordinal,\n parameters_simulate_mask,\n parameters_algorithm,\n X_ordinal,\n X_float,\n X_masked,\n ridge,\n out\n):\n percentage_nonzero = X_masked.count_nonzero(\n ) / (X_masked.shape[0] * X_masked.shape[1])\n nonzero_rows, nonzero_cols = X_masked.nonzero()\n\n cm_mc = ridge.confusion_matrix()\n cm_ff = ridge.confusion_matrix_forward_fill()\n\n params = {\n 'ord_output_domain': ''.join([str(s) for s in parameters_simulate_ordinal['output_domain']]),\n 'ord_pdf': ''.join([str(s) for s in parameters_simulate_ordinal['original_data_pdf']]),\n 'ord_kernel_parameter': parameters_simulate_ordinal['kernel_parameter'],\n 'ord_truncate_limits': ''.join([str(s) for s in parameters_simulate_ordinal['truncate_limits']]),\n\n 'mask_expectations': ''.join([str(s) for s in parameters_simulate_mask['mask_transition_expectations']]),\n 'mask_variances': ''.join([str(s) for s in parameters_simulate_mask['mask_transition_variances']]),\n 'mask_level': parameters_simulate_mask['mask_level'],\n 'mask_memory_length': parameters_simulate_mask['memory_length'],\n 'mask_prctg_nonzero': percentage_nonzero,\n\n 'alg_lambda0': parameters_algorithm['lambda0'],\n 'alg_lambda1': parameters_algorithm['lambda1'],\n 'alg_lambda2': parameters_algorithm['lambda2'],\n 'alg_lambda3': parameters_algorithm['lambda3'],\n 'alg_k': parameters_algorithm['k'],\n 'alg_total_iterations': parameters_algorithm['total_iterations'],\n\n 'predict_window': parameters_algorithm['predict_window'],\n\n 'result_reconstruct_ordinal': np.mean(np.abs(([email protected] - X_ordinal)[~nonzero_rows, ~nonzero_cols])),\n 'result_reconstruct_mean': np.mean(np.abs(([email protected] - X_float)[~nonzero_rows, ~nonzero_cols])),\n 'result_specificity_mc': (cm_mc[0, 0] / np.sum(cm_mc[:, 0])),\n 'result_sensitivity_mc': (np.sum(cm_mc[1:, 1:]) / np.sum(cm_mc[:, 1:])),\n 'result_specificity_ff': (cm_ff[0, 0] / np.sum(cm_ff[:, 0])),\n 'result_sensitivity_ff': np.sum(cm_ff[1:, 1:]) / np.sum(cm_ff[:, 1:])\n }\n\n params_json = json.dumps(params)\n\n if not os.path.exists('/'.join(out.split('/')[:-1])):\n os.makedirs('/'.join(out.split('/')[:-1]))\n\n out_params = open(out + 'params.json', 'w')\n out_params.write(params_json)\n out_params.close()\n\n np.save(out + 'cm_mc.npy', cm_mc)\n np.save(out + 'cm_ff.npy', cm_ff)\n\n np.save(out + 'V.npy', ridge.V)\n" ]
[ [ "numpy.sum", "numpy.abs", "numpy.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aliciawyy/notebooks
[ "7f9c73f39e86e2178a428de184c88b74d22bcf81" ]
[ "plot_compare_reduction.py" ]
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n=================================================================\nSelecting dimensionality reduction with Pipeline and GridSearchCV\n=================================================================\n\nThis example constructs a pipeline that does dimensionality\nreduction followed by prediction with a support vector\nclassifier. It demonstrates the use of GridSearchCV and\nPipeline to optimize over different classes of estimators in a\nsingle CV run -- unsupervised PCA and NMF dimensionality\nreductions are compared to univariate feature selection during\nthe grid search.\n\"\"\"\n# Authors: Robert McGibbon, Joel Nothman\n\nfrom __future__ import print_function, division\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_digits\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.svm import LinearSVC\nfrom sklearn.decomposition import PCA, NMF\nfrom sklearn.feature_selection import SelectKBest, chi2\n\nprint(__doc__)\n\npipe = Pipeline([\n ('reduce_dim', PCA()),\n ('classify', LinearSVC())\n])\n\nN_FEATURES_OPTIONS = [2, 4, 8]\nC_OPTIONS = [1, 10, 100, 1000]\nparam_grid = [\n {\n 'reduce_dim': [PCA(iterated_power=7), NMF()],\n 'reduce_dim__n_components': N_FEATURES_OPTIONS,\n 'classify__C': C_OPTIONS\n },\n {\n 'reduce_dim': [SelectKBest(chi2)],\n 'reduce_dim__k': N_FEATURES_OPTIONS,\n 'classify__C': C_OPTIONS\n },\n]\nreducer_labels = ['PCA', 'NMF', 'KBest(chi2)']\n\ngrid = GridSearchCV(pipe, cv=3, n_jobs=2, param_grid=param_grid)\ndigits = load_digits()\ngrid.fit(digits.data, digits.target)\n\nmean_scores = np.array(grid.cv_results_['mean_test_score'])\n# scores are in the order of param_grid iteration, which is alphabetical\nmean_scores = mean_scores.reshape(len(C_OPTIONS), -1, len(N_FEATURES_OPTIONS))\n# select score for best C\nmean_scores = mean_scores.max(axis=0)\nbar_offsets = (np.arange(len(N_FEATURES_OPTIONS)) *\n (len(reducer_labels) + 1) + .5)\n\nplt.figure()\nCOLORS = 'bgrcmyk'\nfor i, (label, reducer_scores) in enumerate(zip(reducer_labels, mean_scores)):\n plt.bar(bar_offsets + i, reducer_scores, label=label, color=COLORS[i])\n\nplt.title(\"Comparing feature reduction techniques\")\nplt.xlabel('Reduced number of features')\nplt.xticks(bar_offsets + len(reducer_labels) / 2, N_FEATURES_OPTIONS)\nplt.ylabel('Digit classification accuracy')\nplt.ylim((0, 1))\nplt.legend(loc='upper left')\nplt.show()\n" ]
[ [ "matplotlib.pyplot.legend", "sklearn.model_selection.GridSearchCV", "sklearn.decomposition.NMF", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "sklearn.feature_selection.SelectKBest", "matplotlib.pyplot.ylabel", "sklearn.datasets.load_digits", "matplotlib.pyplot.bar", "sklearn.svm.LinearSVC", "matplotlib.pyplot.xlabel", "numpy.array", "sklearn.decomposition.PCA", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Shengqiang-Zhang/self-attentive-parser
[ "493f74c7acab9824d593f55d231754c5ac7cbb26" ]
[ "src/main.py" ]
[ "import argparse\nimport itertools\nimport os.path\nimport time\n\nimport torch\nimport torch.optim.lr_scheduler\n\nimport numpy as np\n\nimport evaluate\nimport trees\nimport vocabulary\nimport nkutil\nimport parse_nk\n\ntokens = parse_nk\n\n\ndef torch_load(load_path):\n if parse_nk.use_cuda:\n return torch.load(load_path)\n else:\n return torch.load(load_path, map_location=lambda storage, location: storage)\n\n\ndef format_elapsed(start_time):\n elapsed_time = int(time.time() - start_time)\n minutes, seconds = divmod(elapsed_time, 60)\n hours, minutes = divmod(minutes, 60)\n days, hours = divmod(hours, 24)\n elapsed_string = \"{}h{:02}m{:02}s\".format(hours, minutes, seconds)\n if days > 0:\n elapsed_string = \"{}d{}\".format(days, elapsed_string)\n return elapsed_string\n\n\ndef make_hparams():\n return nkutil.HParams(\n max_len_train=0, # no length limit\n max_len_dev=0, # no length limit\n\n sentence_max_len=300,\n\n learning_rate=0.0008,\n learning_rate_warmup_steps=160,\n clip_grad_norm=0., # no clipping\n step_decay=True, # note that disabling step decay is not implemented\n step_decay_factor=0.5,\n step_decay_patience=5,\n max_consecutive_decays=3, # establishes a termination criterion\n\n partitioned=True,\n num_layers_position_only=0,\n\n num_layers=8,\n d_model=1024,\n num_heads=8,\n d_kv=64,\n d_ff=2048,\n d_label_hidden=250,\n d_tag_hidden=250,\n tag_loss_scale=5.0,\n\n attention_dropout=0.2,\n embedding_dropout=0.0,\n relu_dropout=0.1,\n residual_dropout=0.2,\n\n use_tags=False,\n use_words=False,\n use_chars_lstm=False,\n use_elmo=False,\n use_bert=False,\n use_bert_only=False,\n predict_tags=False,\n\n d_char_emb=32, # A larger value may be better for use_chars_lstm\n\n tag_emb_dropout=0.2,\n word_emb_dropout=0.4,\n morpho_emb_dropout=0.2,\n timing_dropout=0.0,\n char_lstm_input_dropout=0.2,\n elmo_dropout=0.5, # Note that this semi-stacks with morpho_emb_dropout!\n\n bert_model=\"bert-base-uncased\",\n bert_do_lower_case=True,\n bert_transliterate=\"\",\n )\n\n\ndef run_train(args, hparams):\n if args.numpy_seed is not None:\n print(\"Setting numpy random seed to {}...\".format(args.numpy_seed))\n np.random.seed(args.numpy_seed)\n\n # Make sure that pytorch is actually being initialized randomly.\n # On my cluster I was getting highly correlated results from multiple\n # runs, but calling reset_parameters() changed that. A brief look at the\n # pytorch source code revealed that pytorch initializes its RNG by\n # calling std::random_device, which according to the C++ spec is allowed\n # to be deterministic.\n seed_from_numpy = np.random.randint(2147483648)\n print(\"Manual seed for pytorch:\", seed_from_numpy)\n torch.manual_seed(seed_from_numpy)\n\n hparams.set_from_args(args)\n print(\"Hyperparameters:\")\n hparams.print()\n\n print(\"Loading training trees from {}...\".format(args.train_path))\n if hparams.predict_tags and args.train_path.endswith('10way.clean'):\n print(\"WARNING: The data distributed with this repository contains \"\n \"predicted part-of-speech tags only (not gold tags!) We do not \"\n \"recommend enabling predict_tags in this configuration.\")\n train_treebank = trees.load_trees(args.train_path)\n if hparams.max_len_train > 0:\n train_treebank = [tree for tree in train_treebank if len(list(tree.leaves())) <= hparams.max_len_train]\n print(\"Loaded {:,} training examples.\".format(len(train_treebank)))\n\n print(\"Loading development trees from {}...\".format(args.dev_path))\n dev_treebank = trees.load_trees(args.dev_path)\n if hparams.max_len_dev > 0:\n dev_treebank = [tree for tree in dev_treebank if len(list(tree.leaves())) <= hparams.max_len_dev]\n print(\"Loaded {:,} development examples.\".format(len(dev_treebank)))\n\n print(\"Processing trees for training...\")\n train_parse = [tree.convert() for tree in train_treebank]\n\n print(\"Constructing vocabularies...\")\n\n tag_vocab = vocabulary.Vocabulary()\n tag_vocab.index(tokens.START)\n tag_vocab.index(tokens.STOP)\n tag_vocab.index(tokens.TAG_UNK)\n\n word_vocab = vocabulary.Vocabulary()\n word_vocab.index(tokens.START)\n word_vocab.index(tokens.STOP)\n word_vocab.index(tokens.UNK)\n\n label_vocab = vocabulary.Vocabulary()\n label_vocab.index(())\n\n char_set = set()\n\n for tree in train_parse:\n nodes = [tree]\n while nodes:\n node = nodes.pop()\n if isinstance(node, trees.InternalParseNode):\n label_vocab.index(node.label)\n nodes.extend(reversed(node.children))\n else:\n tag_vocab.index(node.tag)\n word_vocab.index(node.word)\n char_set |= set(node.word)\n\n char_vocab = vocabulary.Vocabulary()\n\n # If codepoints are small (e.g. Latin alphabet), index by codepoint directly\n highest_codepoint = max(ord(char) for char in char_set)\n if highest_codepoint < 512:\n if highest_codepoint < 256:\n highest_codepoint = 256\n else:\n highest_codepoint = 512\n\n # This also takes care of constants like tokens.CHAR_PAD\n for codepoint in range(highest_codepoint):\n char_index = char_vocab.index(chr(codepoint))\n assert char_index == codepoint\n else:\n char_vocab.index(tokens.CHAR_UNK)\n char_vocab.index(tokens.CHAR_START_SENTENCE)\n char_vocab.index(tokens.CHAR_START_WORD)\n char_vocab.index(tokens.CHAR_STOP_WORD)\n char_vocab.index(tokens.CHAR_STOP_SENTENCE)\n for char in sorted(char_set):\n char_vocab.index(char)\n\n tag_vocab.freeze()\n word_vocab.freeze()\n label_vocab.freeze()\n char_vocab.freeze()\n\n def print_vocabulary(name, vocab):\n special = {tokens.START, tokens.STOP, tokens.UNK}\n print(\"{} ({:,}): {}\".format(\n name, vocab.size,\n sorted(value for value in vocab.values if value in special) +\n sorted(value for value in vocab.values if value not in special)))\n\n if args.print_vocabs:\n print_vocabulary(\"Tag\", tag_vocab)\n print_vocabulary(\"Word\", word_vocab)\n print_vocabulary(\"Label\", label_vocab)\n\n print(\"Initializing model...\")\n\n load_path = None\n if load_path is not None:\n print(f\"Loading parameters from {load_path}\")\n info = torch_load(load_path)\n parser = parse_nk.NKChartParser.from_spec(info['spec'], info['state_dict'])\n else:\n parser = parse_nk.NKChartParser(\n tag_vocab,\n word_vocab,\n label_vocab,\n char_vocab,\n hparams,\n )\n\n print(\"Initializing optimizer...\")\n trainable_parameters = [param for param in parser.parameters() if param.requires_grad]\n trainer = torch.optim.Adam(trainable_parameters, lr=1., betas=(0.9, 0.98), eps=1e-9)\n if load_path is not None:\n trainer.load_state_dict(info['trainer'])\n\n def set_lr(new_lr):\n for param_group in trainer.param_groups:\n param_group['lr'] = new_lr\n\n assert hparams.step_decay, \"Only step_decay schedule is supported\"\n\n warmup_coeff = hparams.learning_rate / hparams.learning_rate_warmup_steps\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n trainer, 'max',\n factor=hparams.step_decay_factor,\n patience=hparams.step_decay_patience,\n verbose=True,\n )\n\n def schedule_lr(iteration):\n iteration = iteration + 1\n if iteration <= hparams.learning_rate_warmup_steps:\n set_lr(iteration * warmup_coeff)\n\n clippable_parameters = trainable_parameters\n grad_clip_threshold = np.inf if hparams.clip_grad_norm == 0 else hparams.clip_grad_norm\n\n print(\"Training...\")\n total_processed = 0\n current_processed = 0\n check_every = len(train_parse) / args.checks_per_epoch\n best_dev_fscore = -np.inf\n best_dev_model_path = None\n best_dev_processed = 0\n\n start_time = time.time()\n\n def check_dev():\n nonlocal best_dev_fscore\n nonlocal best_dev_model_path\n nonlocal best_dev_processed\n\n dev_start_time = time.time()\n\n dev_predicted = []\n for dev_start_index in range(0, len(dev_treebank), args.eval_batch_size):\n subbatch_trees = dev_treebank[dev_start_index:dev_start_index + args.eval_batch_size]\n subbatch_sentences = [[(leaf.tag, leaf.word) for leaf in tree.leaves()] for tree in subbatch_trees]\n predicted, _ = parser.parse_batch(subbatch_sentences)\n del _\n dev_predicted.extend([p.convert() for p in predicted])\n\n dev_fscore = evaluate.evalb(args.evalb_dir, dev_treebank, dev_predicted)\n\n print(\n \"dev-fscore {} \"\n \"dev-elapsed {} \"\n \"total-elapsed {}\".format(\n dev_fscore,\n format_elapsed(dev_start_time),\n format_elapsed(start_time),\n )\n )\n\n if dev_fscore.fscore > best_dev_fscore:\n if best_dev_model_path is not None:\n extensions = [\".pt\"]\n for ext in extensions:\n path = best_dev_model_path + ext\n if os.path.exists(path):\n print(\"Removing previous model file {}...\".format(path))\n os.remove(path)\n\n best_dev_fscore = dev_fscore.fscore\n best_dev_model_path = \"{}_dev={:.2f}\".format(\n args.model_path_base, dev_fscore.fscore)\n best_dev_processed = total_processed\n print(\"Saving new best model to {}...\".format(best_dev_model_path))\n torch.save({\n 'spec': parser.spec,\n 'state_dict': parser.state_dict(),\n 'trainer': trainer.state_dict(),\n }, best_dev_model_path + \".pt\")\n\n for epoch in itertools.count(start=1):\n if args.epochs is not None and epoch > args.epochs:\n break\n\n np.random.shuffle(train_parse)\n epoch_start_time = time.time()\n\n for start_index in range(0, len(train_parse), args.batch_size):\n trainer.zero_grad()\n schedule_lr(total_processed // args.batch_size)\n\n batch_loss_value = 0.0\n batch_trees = train_parse[start_index: start_index + args.batch_size]\n batch_sentences = [[(leaf.tag, leaf.word) for leaf in tree.leaves()] for tree in batch_trees]\n batch_num_tokens = sum(len(sentence) for sentence in batch_sentences)\n\n for subbatch_sentences, subbatch_trees in parser.split_batch(batch_sentences, batch_trees,\n args.subbatch_max_tokens):\n _, loss = parser.parse_batch(subbatch_sentences, subbatch_trees) # _是predicted\n\n if hparams.predict_tags:\n loss = loss[0] / len(batch_trees) + loss[1] / batch_num_tokens\n else:\n loss = loss / len(batch_trees)\n loss_value = float(loss.data.cpu().numpy())\n batch_loss_value += loss_value\n if loss_value > 0:\n loss.backward()\n del loss\n total_processed += len(subbatch_trees)\n current_processed += len(subbatch_trees)\n\n grad_norm = torch.nn.utils.clip_grad_norm_(clippable_parameters, grad_clip_threshold)\n\n trainer.step()\n\n print(\n \"epoch {:,} \"\n \"batch {:,}/{:,} \"\n \"processed {:,} \"\n \"batch-loss {:.4f} \"\n \"grad-norm {:.4f} \"\n \"epoch-elapsed {} \"\n \"total-elapsed {}\".format(\n epoch,\n start_index // args.batch_size + 1,\n int(np.ceil(len(train_parse) / args.batch_size)),\n total_processed,\n batch_loss_value,\n grad_norm,\n format_elapsed(epoch_start_time),\n format_elapsed(start_time),\n )\n )\n\n if current_processed >= check_every:\n current_processed -= check_every\n check_dev()\n\n # adjust learning rate at the end of an epoch\n if (total_processed // args.batch_size + 1) > hparams.learning_rate_warmup_steps:\n scheduler.step(best_dev_fscore)\n if (total_processed - best_dev_processed) > (\n (hparams.step_decay_patience + 1) * hparams.max_consecutive_decays * len(train_parse)):\n print(\"Terminating due to lack of improvement in dev fscore.\")\n break\n\n\ndef run_test(args):\n print(\"Loading test trees from {}...\".format(args.test_path))\n test_treebank = trees.load_trees(args.test_path)\n print(\"Loaded {:,} test examples.\".format(len(test_treebank)))\n\n print(\"Loading model from {}...\".format(args.model_path_base))\n assert args.model_path_base.endswith(\".pt\"), \"Only pytorch savefiles supported\"\n\n info = torch_load(args.model_path_base)\n assert 'hparams' in info['spec'], \"Older savefiles not supported\"\n parser = parse_nk.NKChartParser.from_spec(info['spec'], info['state_dict'])\n\n print(\"Parsing test sentences...\")\n start_time = time.time()\n\n test_predicted = []\n for start_index in range(0, len(test_treebank), args.eval_batch_size):\n subbatch_trees = test_treebank[start_index:start_index + args.eval_batch_size]\n subbatch_sentences = [[(leaf.tag, leaf.word) for leaf in tree.leaves()] for tree in subbatch_trees]\n predicted, _ = parser.parse_batch(subbatch_sentences) # _是loss\n del _\n test_predicted.extend([p.convert() for p in predicted])\n\n # The tree loader does some preprocessing to the trees (e.g. stripping TOP\n # symbols or SPMRL morphological features). We compare with the input file\n # directly to be extra careful about not corrupting the evaluation. We also\n # allow specifying a separate \"raw\" file for the gold trees: the inputs to\n # our parser have traces removed and may have predicted tags substituted,\n # and we may wish to compare against the raw gold trees to make sure we\n # haven't made a mistake. As far as we can tell all of these variations give\n # equivalent results.\n ref_gold_path = args.test_path\n if args.test_path_raw is not None:\n print(\"Comparing with raw trees from\", args.test_path_raw)\n ref_gold_path = args.test_path_raw\n\n test_fscore = evaluate.evalb(args.evalb_dir, test_treebank, test_predicted, ref_gold_path=ref_gold_path)\n\n print(\n \"test-fscore {} \"\n \"test-elapsed {}\".format(\n test_fscore,\n format_elapsed(start_time),\n )\n )\n\n\n# %%\ndef run_ensemble(args):\n print(\"Loading test trees from {}...\".format(args.test_path))\n test_treebank = trees.load_trees(args.test_path)\n print(\"Loaded {:,} test examples.\".format(len(test_treebank)))\n\n parsers = []\n for model_path_base in args.model_path_base:\n print(\"Loading model from {}...\".format(model_path_base))\n assert model_path_base.endswith(\".pt\"), \"Only pytorch savefiles supported\"\n\n info = torch_load(model_path_base)\n assert 'hparams' in info['spec'], \"Older savefiles not supported\"\n parser = parse_nk.NKChartParser.from_spec(info['spec'], info['state_dict'])\n parsers.append(parser)\n\n # Ensure that label scores charts produced by the models can be combined\n # using simple averaging\n ref_label_vocab = parsers[0].label_vocab\n for parser in parsers:\n assert parser.label_vocab.indices == ref_label_vocab.indices\n\n print(\"Parsing test sentences...\")\n start_time = time.time()\n\n test_predicted = []\n # Ensemble by averaging label score charts from different models\n # We did not observe any benefits to doing weighted averaging, probably\n # because all our parsers output label scores of around the same magnitude\n for start_index in range(0, len(test_treebank), args.eval_batch_size):\n subbatch_trees = test_treebank[start_index:start_index + args.eval_batch_size]\n subbatch_sentences = [[(leaf.tag, leaf.word) for leaf in tree.leaves()] for tree in subbatch_trees]\n\n chart_lists = []\n for parser in parsers:\n charts = parser.parse_batch(subbatch_sentences, return_label_scores_charts=True)\n chart_lists.append(charts)\n\n # todo: 对各parser的结果如何做ensemble的?\n subbatch_charts = [np.mean(list(sentence_charts), 0) for sentence_charts in zip(*chart_lists)]\n predicted, _ = parsers[0].decode_from_chart_batch(subbatch_sentences, subbatch_charts)\n del _\n test_predicted.extend([p.convert() for p in predicted])\n\n test_fscore = evaluate.evalb(args.evalb_dir, test_treebank, test_predicted, ref_gold_path=args.test_path)\n\n print(\n \"test-fscore {} \"\n \"test-elapsed {}\".format(\n test_fscore,\n format_elapsed(start_time),\n )\n )\n\n\n# %%\n\ndef run_parse(args):\n if args.output_path != '-' and os.path.exists(args.output_path):\n print(\"Error: output file already exists:\", args.output_path)\n return\n\n print(\"Loading model from {}...\".format(args.model_path_base))\n assert args.model_path_base.endswith(\".pt\"), \"Only pytorch savefiles supported\"\n\n info = torch_load(args.model_path_base)\n assert 'hparams' in info['spec'], \"Older savefiles not supported\"\n parser = parse_nk.NKChartParser.from_spec(info['spec'], info['state_dict'])\n\n print(\"Parsing sentences...\")\n with open(args.input_path) as input_file:\n sentences = input_file.readlines()\n sentences = [sentence.split() for sentence in sentences]\n\n # Tags are not available when parsing from raw text, so use a dummy tag\n if 'UNK' in parser.tag_vocab.indices:\n dummy_tag = 'UNK'\n else:\n dummy_tag = parser.tag_vocab.value(0)\n\n start_time = time.time()\n\n all_predicted = []\n for start_index in range(0, len(sentences), args.eval_batch_size):\n subbatch_sentences = sentences[start_index:start_index + args.eval_batch_size]\n\n subbatch_sentences = [[(dummy_tag, word) for word in sentence] for sentence in subbatch_sentences]\n predicted, _ = parser.parse_batch(subbatch_sentences)\n del _\n if args.output_path == '-':\n for p in predicted:\n print(p.convert().linearize())\n else:\n all_predicted.extend([p.convert() for p in predicted])\n\n if args.output_path != '-':\n with open(args.output_path, 'w') as output_file:\n for tree in all_predicted:\n output_file.write(\"{}\\n\".format(tree.linearize()))\n print(\"Output written to:\", args.output_path)\n\n\n# %%\ndef run_viz(args):\n assert args.model_path_base.endswith(\".pt\"), \"Only pytorch savefiles supported\"\n\n print(\"Loading test trees from {}...\".format(args.viz_path))\n viz_treebank = trees.load_trees(args.viz_path)\n print(\"Loaded {:,} test examples.\".format(len(viz_treebank)))\n\n print(\"Loading model from {}...\".format(args.model_path_base))\n\n info = torch_load(args.model_path_base)\n\n assert 'hparams' in info['spec'], \"Only self-attentive models are supported\"\n parser = parse_nk.NKChartParser.from_spec(info['spec'], info['state_dict'])\n\n from viz import viz_attention\n\n stowed_values = {}\n orig_multihead_forward = parse_nk.MultiHeadAttention.forward\n\n def wrapped_multihead_forward(self, inp, batch_idxs, **kwargs):\n res, attns = orig_multihead_forward(self, inp, batch_idxs, **kwargs)\n stowed_values[f'attns{stowed_values[\"stack\"]}'] = attns.cpu().data.numpy()\n stowed_values['stack'] += 1\n return res, attns\n\n parse_nk.MultiHeadAttention.forward = wrapped_multihead_forward\n\n # Select the sentences we will actually be visualizing\n max_len_viz = 15\n if max_len_viz > 0:\n viz_treebank = [tree for tree in viz_treebank if len(list(tree.leaves())) <= max_len_viz]\n viz_treebank = viz_treebank[:1]\n\n print(\"Parsing viz sentences...\")\n\n for start_index in range(0, len(viz_treebank), args.eval_batch_size):\n subbatch_trees = viz_treebank[start_index:start_index + args.eval_batch_size]\n subbatch_sentences = [[(leaf.tag, leaf.word) for leaf in tree.leaves()] for tree in subbatch_trees]\n stowed_values = dict(stack=0)\n predicted, _ = parser.parse_batch(subbatch_sentences)\n del _\n predicted = [p.convert() for p in predicted]\n stowed_values['predicted'] = predicted\n\n for snum, sentence in enumerate(subbatch_sentences):\n sentence_words = [tokens.START] + [x[1] for x in sentence] + [tokens.STOP]\n\n for stacknum in range(stowed_values['stack']):\n attns_padded = stowed_values[f'attns{stacknum}']\n attns = attns_padded[snum::len(subbatch_sentences), :len(sentence_words), :len(sentence_words)]\n viz_attention(sentence_words, attns)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers()\n\n hparams = make_hparams()\n subparser = subparsers.add_parser(\"train\")\n subparser.set_defaults(callback=lambda args: run_train(args, hparams))\n hparams.populate_arguments(subparser)\n subparser.add_argument(\"--numpy-seed\", type=int)\n subparser.add_argument(\"--model-path-base\", required=True)\n subparser.add_argument(\"--evalb-dir\", default=\"EVALB/\")\n subparser.add_argument(\"--train-path\", default=\"data/02-21.10way.clean\")\n subparser.add_argument(\"--dev-path\", default=\"data/22.auto.clean\")\n subparser.add_argument(\"--batch-size\", type=int, default=250)\n subparser.add_argument(\"--subbatch-max-tokens\", type=int, default=2000)\n subparser.add_argument(\"--eval-batch-size\", type=int, default=100)\n subparser.add_argument(\"--epochs\", type=int)\n subparser.add_argument(\"--checks-per-epoch\", type=int, default=4)\n subparser.add_argument(\"--print-vocabs\", action=\"store_true\")\n\n subparser = subparsers.add_parser(\"test\")\n subparser.set_defaults(callback=run_test)\n subparser.add_argument(\"--model-path-base\", required=True)\n subparser.add_argument(\"--evalb-dir\", default=\"EVALB/\")\n subparser.add_argument(\"--test-path\", default=\"data/23.auto.clean\")\n subparser.add_argument(\"--test-path-raw\", type=str)\n subparser.add_argument(\"--eval-batch-size\", type=int, default=100)\n\n subparser = subparsers.add_parser(\"ensemble\")\n subparser.set_defaults(callback=run_ensemble)\n subparser.add_argument(\"--model-path-base\", nargs='+', required=True)\n subparser.add_argument(\"--evalb-dir\", default=\"EVALB/\")\n subparser.add_argument(\"--test-path\", default=\"data/22.auto.clean\")\n subparser.add_argument(\"--eval-batch-size\", type=int, default=100)\n\n subparser = subparsers.add_parser(\"parse\")\n subparser.set_defaults(callback=run_parse)\n subparser.add_argument(\"--model-path-base\", required=True)\n subparser.add_argument(\"--input-path\", type=str, required=True)\n subparser.add_argument(\"--output-path\", type=str, default=\"-\")\n subparser.add_argument(\"--eval-batch-size\", type=int, default=100)\n\n subparser = subparsers.add_parser(\"viz\")\n subparser.set_defaults(callback=run_viz)\n subparser.add_argument(\"--model-path-base\", required=True)\n subparser.add_argument(\"--evalb-dir\", default=\"EVALB/\")\n subparser.add_argument(\"--viz-path\", default=\"data/22.auto.clean\")\n subparser.add_argument(\"--eval-batch-size\", type=int, default=100)\n\n args = parser.parse_args()\n args.callback(args)\n\n\n# %%\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "torch.optim.Adam", "torch.optim.lr_scheduler.ReduceLROnPlateau", "numpy.random.seed", "torch.load", "torch.manual_seed", "numpy.random.shuffle", "torch.nn.utils.clip_grad_norm_", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
alawami/MARL
[ "bd0b9a1ebf660f4949825c3869b464255ce9d70f" ]
[ "MADDPG/maddpg.py" ]
[ "# main code that contains the neural network setup\n# policy + critic updates\n# see ddpg.py for other details in the network\n\nfrom ddpg import DDPGAgent\nimport torch\nfrom utilities import soft_update, transpose_to_tensor, transpose_list\nfrom utilities import to_tensor\nfrom utilities import print_variable\n\nimport torch.nn.functional as f\n\nimport logging\n\n# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ndevice = 'cpu'\nTAU = 0.02\n\nclass MADDPG:\n \"\"\"Reinforcement agent implementing MADDPG.\"\"\"\n def __init__(self, discount_factor=0.95, tau=0.02):\n \"\"\"Initialize parameters and setup agent\"\"\"\n # critic input = obs_full + actions = 24+24+2+2=52\n# ddpg = DDPGAgent(24, 400, 300, 2, 52, 400, 300, lr_actor=1e-4, lr_critic=1e-3)\n self.maddpg_agent = [DDPGAgent(24, 512, 256, 2, 52, 512, 256, lr_actor=1e-4, lr_critic=1e-3), \n DDPGAgent(24, 512, 256, 2, 52, 512, 256, lr_actor=1e-4, lr_critic=1e-3)]\n # Use same agent for both\n# self.maddpg_agent = [ddpg, ddpg]\n \n self.discount_factor = discount_factor\n self.tau = tau\n self.iter = 0\n\n def get_actors(self):\n \"\"\"get actors of all the agents in the MADDPG object\"\"\"\n actors = [ddpg_agent.actor for ddpg_agent in self.maddpg_agent]\n return actors\n\n def get_target_actors(self):\n \"\"\"get target_actors of all the agents in the MADDPG object\"\"\"\n target_actors = [ddpg_agent.target_actor for ddpg_agent in self.maddpg_agent]\n return target_actors\n\n def act(self, obs_all_agents, noise=0.0):\n \"\"\"get actions from all agents in the MADDPG object\"\"\"\n \n logging.debug('######### MADDPG.PY - ACT ######### PASS OBS TO ACTOR NET')\n for agent, obs in zip(self.maddpg_agent, obs_all_agents):\n logging.debug('Agent observation:')\n print_variable(obs, 'obs')\n logging.debug('#########')\n \n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n \n actions = [agent.act(obs, noise) for agent, obs in zip(self.maddpg_agent, obs_all_agents)]\n actions = [torch.clamp(action, -1, 1) for action in actions]\n \n logging.debug('######### MADDPG.PY - ACT ######### ACTIONS RETURNED')\n print_variable(actions, 'actions')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n return actions\n\n def target_act(self, obs_all_agents, noise=0.0):\n \"\"\"get target network actions from all the agents in the MADDPG object \"\"\"\n target_actions = [ddpg_agent.target_act(obs, noise) for ddpg_agent, obs in zip(self.maddpg_agent, obs_all_agents)]\n\n return target_actions\n\n def update(self, samples, agent_number, logger):\n \"\"\"update the critics and actors of all the agents \"\"\"\n\n # need to transpose each element of the samples\n # to flip obs[parallel_agent][agent_number] to\n # obs[agent_number][parallel_agent]\n \n logging.debug('######### STEP 8 ######### UPDATE Agent: ' + str(agent_number))\n print_variable(samples, 'samples')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n obs, obs_full, action, reward, next_obs, next_obs_full, done = map(transpose_to_tensor, samples)\n \n logging.debug('######### MADDPG.PY - UPDATE ######### UNPACK SAMPLE')\n print_variable(obs, 'obs')\n print_variable(obs_full, 'obs_full')\n print_variable(obs_full[0], 'obs_full[0]')\n print_variable(action, 'action')\n print_variable(reward, 'reward')\n print_variable(next_obs, 'next_obs')\n print_variable(next_obs_full, 'next_obs_full')\n print_variable(done, 'done')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n\n obs_full = torch.stack(obs_full)\n next_obs_full = torch.stack(next_obs_full)\n \n \n logging.debug('######### MADDPG.PY - UPDATE ######### STACKED FULL OBS')\n print_variable(obs_full, 'stacked obs_full')\n print_variable(next_obs_full, 'stacked next_obs_full')\n print_variable(done, 'done')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n logging.debug('# ---------------------------- update critic ---------------------------- #')\n \n agent = self.maddpg_agent[agent_number]\n agent.critic_optimizer.zero_grad()\n\n #critic loss = batch mean of (y- Q(s,a) from target network)^2\n #y = reward of this timestep + discount * Q(st+1,at+1) from target network\n target_actions = self.target_act(next_obs)\n \n \n logging.debug('######### MADDPG.PY - UPDATE ######### TARGET ACTIONS')\n print_variable(target_actions, 'target_actions')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n \n target_actions = torch.cat(target_actions, dim=1)\n \n logging.debug('######### MADDPG.PY - UPDATE ######### TARGET ACTIONS - CONCAT')\n print_variable(target_actions, 'target_actions')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n target_critic_input = torch.cat((torch.squeeze(next_obs_full.t()),target_actions), dim=1).to(device)\n \n logging.debug('######### MADDPG.PY - UPDATE ######### TARGET CRITIC NETWORK - INPUT')\n print_variable(torch.cat((torch.squeeze(next_obs_full.t()),target_actions), dim=1), 'torch.cat((torch.squeeze(next_obs_full.t()),target_actions), dim=1)')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n with torch.no_grad():\n q_next = agent.target_critic(target_critic_input)\n \n logging.debug('######### MADDPG.PY - UPDATE ######### TARGET CRITIC NETWORK - Q Next')\n print_variable(q_next, 'q_next')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n y = reward[agent_number].view(-1, 1) + self.discount_factor * q_next * (1 - done[agent_number].view(-1, 1))\n action = torch.cat(action, dim=1)\n \n logging.debug('######### MADDPG.PY - UPDATE ######### y')\n print_variable(y, 'y')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n logging.debug('######### MADDPG.PY - UPDATE ######### CRITIC INPUT - ACTION')\n print_variable(action, 'action')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n critic_input = torch.cat((torch.squeeze(obs_full.t()), action), dim=1).to(device)\n q = agent.critic(critic_input)\n \n logging.debug('######### MADDPG.PY - UPDATE ######### CRITIC INPUT')\n print_variable(critic_input, 'critic_input')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n\n# huber_loss = torch.nn.SmoothL1Loss()\n# critic_loss = huber_loss(q, y.detach())\n critic_loss = f.mse_loss(q, y.detach())\n critic_loss.backward()\n #torch.nn.utils.clip_grad_norm_(agent.critic.parameters(), 0.5)\n torch.nn.utils.clip_grad_norm_(agent.critic.parameters(), 0.5)\n agent.critic_optimizer.step()\n\n logging.debug('# ---------------------------- update actor ---------------------------- #')\n \n logging.debug('######### MADDPG.PY - UPDATE ######### ACTOR NETWORK - INPUT')\n print_variable(obs, 'obs')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n # update actor network using policy gradient\n agent.actor_optimizer.zero_grad()\n # make input to agent\n # detach the other agents to save computation\n # saves some time for computing derivative\n q_input = [ self.maddpg_agent[i].actor(ob) if i == agent_number \\\n else self.maddpg_agent[i].actor(ob).detach()\n for i, ob in enumerate(obs) ]\n \n logging.debug('######### MADDPG.PY - UPDATE ######### CRITIC NETWORK - INPUT')\n print_variable(q_input, 'q_input')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n q_input = torch.cat(q_input, dim=1)\n # combine all the actions and observations for input to critic\n # many of the obs are redundant, and obs[1] contains all useful information already\n q_input2 = torch.cat((torch.squeeze(obs_full.t()), q_input), dim=1)\n \n \n logging.debug('######### MADDPG.PY - UPDATE ######### CRITIC NETWORK - INPUT FORMATTED')\n print_variable(q_input2, 'q_input2')\n logging.debug('#########')\n logging.debug('#########')\n logging.debug('')\n logging.debug('')\n \n logging.debug('######### MADDPG.PY - UPDATE ######### UPDATE FINISHED')\n \n # get the policy gradient\n actor_loss = -agent.critic(q_input2).mean()\n actor_loss.backward()\n #torch.nn.utils.clip_grad_norm_(agent.actor.parameters(),0.5)\n torch.nn.utils.clip_grad_norm_(agent.actor.parameters(),0.5)\n agent.actor_optimizer.step()\n\n al = actor_loss.cpu().detach().item()\n cl = critic_loss.cpu().detach().item()\n logger.add_scalars('agent%i/losses' % agent_number,\n {'critic loss': cl,\n 'actor_loss': al},\n self.iter)\n\n def update_targets(self):\n \"\"\"soft update targets\"\"\"\n self.iter += 1\n for ddpg_agent in self.maddpg_agent:\n soft_update(ddpg_agent.target_actor, ddpg_agent.actor, self.tau)\n soft_update(ddpg_agent.target_critic, ddpg_agent.critic, self.tau)\n \n \n \n def reset(self):\n \"\"\"reset noise process for each DDPG agent\"\"\"\n for ddpg_agent in self.maddpg_agent:\n ddpg_agent.reset()\n\n\n" ]
[ [ "torch.stack", "torch.clamp", "torch.no_grad", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dschmitz89/simplenlopt
[ "238000f6f799a2275b1b155046b3740ab5f23014" ]
[ "simplenlopt/_Global_Optimization.py" ]
[ "from simplenlopt._Core import set_auto_maxeval, minimize, is_gradient_based, generate_nlopt_objective, setup_optimizer, normalize_bounds, execute_optimization\nimport numpy as np\n\ndef random_initial_point(lower, upper):\n '''\n Pick one random point from hyperrectangle with uniform probability\n '''\n lower_bounds = np.asarray(lower)\n upper_bounds = np.asarray(upper)\n\n x0 = lower_bounds + (upper_bounds - lower_bounds) * np.random.rand(len(lower_bounds))\n\n return x0\n\ndef mlsl(fun, bounds, args=(), jac=None, x0='random', sobol_sampling = True, \n population=4, local_minimizer='auto', ftol_rel=1e-8,\n xtol_rel=1e-6, ftol_abs = 1e-14, xtol_abs = 1e-8, \n maxeval='auto', maxtime = None, local_minimizer_options={}, solver_options={}):\n '''\n Global optimization via MultiLevel Single Linkage (MLSL)\n\n .. note::\n MLSL does not seem to respect the relative and absolute convergence criteria.\n By default, it will always run for the maximal number of iterations.\n\n Parameters\n --------\n fun : callable \n The objective function to be minimized. Must be in the form ``fun(x, *args)``, where ``x`` is the argument in the form of a 1-D array and args is a tuple of any additional fixed parameters needed to completely specify the function\n bounds : tuple of array-like\n Bounds for variables. ``(min, max)`` pairs for each element in ``x``, defining the finite lower and upper bounds for the optimizing argument of ``fun``. It is required to have ``len(bounds) == len(x)``. ``len(bounds)`` is used to determine the number of parameters in ``x``.\n args : list, optional, default ()\n Further arguments to describe the objective function\n jac : {callable, '2-point', '3-point', 'NLOpt', bool}, optional, default None\n If callable, must be in the form ``jac(x, *args)``, where ``x`` is the argument. \n in the form of a 1-D array and args is a tuple of any additional fixed parameters \n needed to completely specify the function.\\n\n If '2-point' will use forward difference to approximate the gradient.\\n\n If '3-point' will use central difference to approximate the gradient.\\n\n If 'NLOpt', must be in the form ``jac(x, grad, *args)``, where ``x`` is the argument \n in the form of a 1-D array, ``grad`` a 1-D array containing the gradient \n and args is a tuple of any additional fixed parameters needed to completely specify the function.\n x0 : {ndarray, 'random'}, optional, default 'random'\n Initial parameter vector guess.\n If ndarray, must be a 1-D array\n if 'random', picks a random initial guess in the feasible region.\n sobol_sampling : bool, optional, default True\n If True, starting points for local minimizations are sampled from a Sobol sequence.\n population : int, optional, default 4\n Number of local searches per iteration. \n local_minimizer : string, optional, default 'auto'\n Local Optimization algorithm to use. If string, Should be one of \n\n - 'lbfgs': Limited-memory Broyden-Fletcher Goldfarb Shanno algorithm\n - 'slsqp': Sequential least squares programming\n - 'mma': Method of moving asymptotes\n - 'ccsaq': conservative convex separable approximation\n - 'tnewton': truncated Newton\n - 'tnewton_restart': truncated Newton with restarting\n - 'tnewton_precond': truncated Newton with preconditioning\n - 'tnewton_precond_restart': truncated Newton with preconditioning and restarting\n - 'var1': Shifted limited-memory variable metric with rank 1-method\n - 'var2': Shifted limited-memory variable metric with rank 2-method\n - 'bobyqa': Bounded optimization by quadratic approximation\n - 'cobyla': Constrained optimization by linear approximation\n - 'neldermead': Nelder-Mead optimization\n - 'sbplx': Subplex algorithm\n - 'praxis': Principal Axis algorithm\n - 'auto'\n\n See `NLopt documentation <https://nlopt.readthedocs.io/en/latest/NLopt_Algorithms/>`_ \n for a detailed description of these methods.\\n\n If 'auto', will default to \"lbfgs\" if ``jac!= None`` and \"bobyqa\" if ``jac=None``\n ftol_rel : float, optional, default 1e-8\n Relative function tolerance to signal convergence \n xtol_rel : float, optional, default 1e-6\n Relative parameter vector tolerance to signal convergence\n ftol_abs : float, optional, default 1e-14\n Absolute function tolerance to signal convergence\n xtol_abs : 1e-8, optional, default 1e-8\n Absolute parameter vector tolerance to signal convergence\n maxeval : {int, 'auto'}, optional, default 'auto'\n Number of maximal function evaluations.\n If 'auto', set to 1.000 * dimensions for gradient based local optimizer,\n and 10.000 * problem dimensional for gradient free local optimizer\n maxtime : float, optional, default None\n maximum absolute time until the optimization is terminated\n local_mimimizer_options : dict\n Further options supplied to the local minimizer\n solver_options : dict\n Further options supplied to the global MLSL minimizer\n\n Returns\n -------\n result : :py:class:`~OptimizeResult`\n The optimization result represented as a :py:class:`~OptimizeResult` object.\n Important attributes are: ``x`` the solution array, ``fun`` the value\n of the function at the solution, and ``message`` which describes the\n cause of the termination.\n See :py:class:`~OptimizeResult` for a description of other attributes.\n\n Notes\n -------\n References:\\n\n A. H. G. Rinnooy Kan and G. T. Timmer, \"Stochastic global optimization methods,\" \n Mathematical Programming, vol. 39, p. 27-78 (1987)\\n\n Sergei Kucherenko and Yury Sytsko, \"Application of deterministic low-discrepancy sequences \n in global optimization,\" Computational Optimization and Applications, vol. 30, p. 297-318 (2005)\n '''\n #if local_minimizer not given, choose automatically\n #depending on gradient availability\n\n if local_minimizer == 'auto':\n if jac:\n local_minimizer = 'lbfgs'\n else:\n local_minimizer = 'bobyqa'\n\n #check if local minimizer is gradient based\n gradient_required = is_gradient_based(local_minimizer)\n\n #choose the right version of MLSL based on gradient requirement\n if gradient_required:\n if sobol_sampling:\n mlsl_algorithm = 'GD_MLSL_LDS'\n else:\n mlsl_algorithm = 'GD_MLSL'\n else:\n if sobol_sampling:\n mlsl_algorithm = 'GN_MLSL_LDS'\n else:\n mlsl_algorithm = 'GN_MLSL'\n \n #extract dimension from bounds\n lower, upper = zip(*normalize_bounds(bounds))\n dim = len(lower)\n\n #set up local optimizer\n local_optimizer = setup_optimizer(local_minimizer, dim)\n\n #set tolerances\n local_optimizer.set_xtol_rel(xtol_rel)\n local_optimizer.set_ftol_rel(ftol_rel)\n local_optimizer.set_ftol_abs(ftol_abs)\n local_optimizer.set_xtol_abs(xtol_abs)\n\n #set additional local optimizer options\n for option, val in local_minimizer_options.items():\n try:\n set_option = getattr(local_optimizer, 'set_{option}'.format(option=option))\n except AttributeError:\n raise ValueError('Parameter {option} could not be '\n 'recognized.'.format(option=option))\n else:\n set_option(val)\n\n #set up global MLSL optimizer\n path = []\n mlsl_optimizer = setup_optimizer(mlsl_algorithm, dim)\n obj_fun = generate_nlopt_objective(fun, jac_required = gradient_required, \n jac=jac, args = args, path = path)\n mlsl_optimizer.set_min_objective(obj_fun)\n\n #set local minimizer\n mlsl_optimizer.set_local_optimizer(local_optimizer)\n\n #set bounds\n mlsl_optimizer.set_lower_bounds(lower)\n mlsl_optimizer.set_upper_bounds(upper)\n\n #set maximal number of function evaluations\n if maxeval == 'auto':\n if jac:\n maxeval=2000 * dim\n else:\n maxeval=10000 * dim\n \n factor = set_auto_maxeval(mlsl_optimizer, gradient_required, jac, maxeval) \n #else:\n # mlsl_optimizer.set_maxeval(maxeval)\n # factor = 1\n\n #set population\n mlsl_optimizer.set_population(population)\n\n #if given, set maxtime\n if maxtime:\n mlsl_optimizer.set_maxtime(maxtime)\n\n #if no initial point given, pick randomly within bounds\n\n if x0 == 'random':\n x0 = random_initial_point(lower, upper)\n\n #set additional mlsl optimizer options\n for option, val in solver_options.items():\n try:\n set_option = getattr(mlsl_optimizer, 'set_{option}'.format(option=option))\n except AttributeError:\n raise ValueError('Parameter {option} could not be '\n 'recognized.'.format(option=option))\n else:\n set_option(val)\n\n result = execute_optimization(mlsl_optimizer, x0, path, factor)\n\n return result\n\ndef stogo(fun, bounds, args=(), jac=None, x0='random', randomize = False, \n ftol_rel = 1e-8, xtol_rel = 1e-6, ftol_abs = 1e-14, xtol_abs = 1e-8, \n maxeval='auto', maxtime = None, solver_options={}):\n '''\n Global optimization via STOchastic Global Optimization (STOGO)\n\n .. note::\n STOGO does not seem to respect the relative and absolute convergence criteria.\n By default, it will always run for the maximal number of iterations.\n\n Parameters\n --------\n fun : callable \n The objective function to be minimized. Must be in the form ``fun(x, *args)``, where ``x`` is the argument in the form of a 1-D array and args is a tuple of any additional fixed parameters needed to completely specify the function\n bounds : tuple of array-like\n Bounds for variables. ``(min, max)`` pairs for each element in ``x``, defining the finite lower and upper bounds for the optimizing argument of ``fun``. It is required to have ``len(bounds) == len(x)``. ``len(bounds)`` is used to determine the number of parameters in ``x``.\n args : list, optional, default ()\n Further arguments to describe the objective function\n jac : {callable, '2-point', '3-point', 'NLOpt', bool}, optional, default None\n If callable, must be in the form ``jac(x, *args)``, where ``x`` is the argument \n in the form of a 1-D array and args is a tuple of any additional fixed parameters \n needed to completely specify the function. \\n\n If '2-point' will use forward difference to approximate the gradient.\\n\n If '3-point' will use central difference to approximate the gradient.\\n\n If 'NLOpt', must be in the form ``jac(x, grad, *args)``, where ``x`` is the argument \n in the form of a 1-D array, ``grad`` a 1-D array containing the gradient\n and args is a tuple of any additional fixed parameters needed to completely specify the function.\n x0 : {ndarray, 'random'}, optional, default 'random'\n Initial parameter vector guess.\\n\n If ndarray, must be a 1-D array.\\n\n If 'random', picks a random initial guess in the feasible region.\n randomize: bool, optional, default False\n If True, randomizes the branching process\n ftol_rel : float, optional, default 1e-8\n Relative function tolerance to signal convergence \n xtol_rel : float, optional, default 1e-6\n Relative parameter vector tolerance to signal convergence\n ftol_abs : float, optional, default 1e-14\n Absolute function tolerance to signal convergence\n xtol_abs : float, optional, default 1e-8\n Absolute parameter vector tolerance to signal convergence\n maxeval : {int, 'auto'}, optional, default 'auto'\n Number of maximal function evaluations.\n If 'auto', set to 1.000 * dimensions\n maxtime : float, optional, default None\n maximum absolute time until the optimization is terminated.\n solver_options: dict, optional, default None\n Dictionary of additional options supplied to the solver.\n\n Returns\n -------\n result : :py:class:`~OptimizeResult`\n The optimization result represented as a :py:class:`~OptimizeResult` object.\n Important attributes are: ``x`` the solution array, ``fun`` the value\n of the function at the solution, and ``message`` which describes the\n cause of the termination.\n See :py:class:`~OptimizeResult` for a description of other attributes.\n\n Notes\n -------\n References:\\n\n S. Zertchaninov and K. Madsen, \"A C++ Programme for Global Optimization,\"\n IMM-REP-1998-04, Department of Mathematical Modelling,\n Technical University of Denmark, DK-2800 Lyngby, Denmark, 1998\\n\n S. Gudmundsson, \"Parallel Global Optimization,\" M.Sc. Thesis, IMM,\n Technical University of Denmark, 1998\n '''\n if randomize:\n method='stogo_rand'\n\n else:\n method='stogo'\n\n if x0 == 'random':\n lower, upper = zip(*normalize_bounds(bounds))\n x0 = random_initial_point(lower, upper)\n\n if maxeval == 'auto':\n dim = len(x0)\n if jac:\n maxeval=2000 * dim\n else:\n maxeval=10000 * dim\n\n res = minimize(fun, x0, args = args, method=method, jac = jac, bounds=bounds,\n ftol_rel = ftol_rel, xtol_rel = xtol_rel, \n ftol_abs = ftol_abs, xtol_abs = xtol_abs, maxeval=maxeval, \n maxtime=maxtime, solver_options=solver_options)\n\n return res\n\ndef isres(fun, bounds, args=(), constraints = [], x0='random', population=None, \n ftol_rel = 1e-8, xtol_rel = 1e-6, ftol_abs = 1e-14, xtol_abs = 1e-8, \n maxeval='auto', maxtime = None, solver_options={}): \n '''\n Global optimization via the Improved Stochastic Ranking Evolution Strategy\n\n .. note::\n ISRES does not seem to respect the relative and absolute convergence criteria.\n By default, it will always run for the maximal number of iterations.\n\n Parameters\n --------\n fun : callable \n The objective function to be minimized. Must be in the form ``fun(x, *args)``, where ``x`` is the argument in the form of a 1-D array and args is a tuple of any additional fixed parameters needed to completely specify the function\n bounds : tuple of array-like\n Bounds for variables. ``(min, max)`` pairs for each element in ``x``, defining the finite lower and upper bounds for the optimizing argument of ``fun``. It is required to have ``len(bounds) == len(x)``. ``len(bounds)`` is used to determine the number of parameters in ``x``.\n args : list, optional, default ()\n Further arguments to describe the objective function\n constraints: list, optional, default ()\n List of constraint functions. Constraints must be of the form ``f(x)`` for a constraint of the form f(x) <= 0.\n x0 : {ndarray, 'random'}, optional, default 'random'\n Initial parameter vector guess.\n If ndarray, must be a 1-D array\n if 'random', picks a random initial guess in the feasible region.\n population : int, optional, default None\n Population size.\n If None, will use NLopt's default population size.\n ftol_rel : float, optional, default 1e-8\n Relative function tolerance to signal convergence \n xtol_rel : float, optional, default 1e-6\n Relative parameter vector tolerance to signal convergence\n ftol_abs : float, optional, default 1e-14\n Absolute function tolerance to signal convergence\n xtol_abs : float, optional, default 1e-8\n Absolute parameter vector tolerance to signal convergence\n maxeval : {int, 'auto'}, optional, default 'auto'\n Number of maximal function evaluations.\n If 'auto', set to 1.000 * dimensions\n maxtime : float, optional, default None\n maximum absolute time until the optimization is terminated.\n solver_options: dict, optional, default None\n Dictionary of additional options supplied to the solver.\n\n Returns\n -------\n result : :py:class:`~OptimizeResult`\n The optimization result represented as a :py:class:`~OptimizeResult` object.\n Important attributes are: ``x`` the solution array, ``fun`` the value\n of the function at the solution, and ``message`` which describes the\n cause of the termination.\n See :py:class:`~OptimizeResult` for a description of other attributes.\n\n Notes\n -------\n References:\\n\n Thomas Philip Runarsson and Xin Yao, \"Search biases in constrained evolutionary optimization,\"\n IEEE Trans. on Systems, Man, and Cybernetics Part C: Applications and Reviews,\n vol. 35 (no. 2), pp. 233-243 (2005)\\n\n Thomas P. Runarsson and Xin Yao, \"Stochastic ranking for constrained evolutionary optimization,\" \n IEEE Trans. Evolutionary Computation, vol. 4 (no. 3), pp. 284-294 (2000)\n '''\n if x0 == 'random':\n lower, upper = zip(*normalize_bounds(bounds))\n x0 = random_initial_point(lower, upper)\n\n if maxeval == 'auto':\n dim = len(x0)\n maxeval = 10000 * dim\n\n if population:\n solver_options['population'] = population\n\n res = minimize(fun, x0, args = args, method='isres', jac = None, bounds=bounds,\n constraints = constraints, ftol_rel = ftol_rel, xtol_rel = xtol_rel, \n ftol_abs = ftol_abs, xtol_abs = xtol_abs, maxeval=maxeval, \n maxtime=maxtime, solver_options=solver_options)\n\n return res\n\ndef esch(fun, bounds, args=(), x0='random', population=None, \n ftol_rel = 1e-8, xtol_rel = 1e-6, ftol_abs = 1e-14, xtol_abs = 1e-8, \n maxeval='auto', maxtime = None, solver_options={}):\n '''\n Global optimization via Differential Evolution variant\n\n .. note::\n ESCH does not seem to respect the relative and absolute convergence criteria.\n By default, it will always run for the maximal number of iterations.\n\n Parameters\n --------\n fun : callable \n The objective function to be minimized. Must be in the form ``fun(x, *args)``, where ``x`` is the argument in the form of a 1-D array and args is a tuple of any additional fixed parameters needed to completely specify the function\n bounds : tuple of array-like\n Bounds for variables. ``(min, max)`` pairs for each element in ``x``, defining the finite lower and upper bounds for the optimizing argument of ``fun``. It is required to have ``len(bounds) == len(x)``. ``len(bounds)`` is used to determine the number of parameters in ``x``.\n args : list, optional, default ()\n Further arguments to describe the objective function\n x0 : {ndarray, 'random'}, optional, default 'random'\n Initial parameter vector guess.\\n\n If ndarray, must be a 1-D array.\\n\n if 'random', picks a random initial guess in the feasible region.\n population : int, optional, default None\n Population size.\n If None, will use NLopt's default population size.\n ftol_rel : float, optional, default 1e-8\n Relative function tolerance to signal convergence \n xtol_rel : float, optional, default 1e-6\n Relative parameter vector tolerance to signal convergence\n ftol_abs : float, optional, default 1e-14\n Absolute function tolerance to signal convergence\n xtol_abs : float, optional, default 1e-8\n Absolute parameter vector tolerance to signal convergence\n maxeval : {int, 'auto'}, optional, default 'auto'\n Number of maximal function evaluations.\n If 'auto', set to 1.000 * dimensions\n maxtime : float, optional, default None\n maximum absolute time until the optimization is terminated.\n solver_options: dict, optional, default None\n Dictionary of additional options supplied to the solver.\n\n Returns\n -------\n result : :py:class:`~OptimizeResult`\n The optimization result represented as a :py:class:`~OptimizeResult` object.\n Important attributes are: ``x`` the solution array, ``fun`` the value\n of the function at the solution, and ``message`` which describes the\n cause of the termination.\n See :py:class:`~OptimizeResult` for a description of other attributes.\n\n Notes\n -------\n Reference: C. H. da Silva Santos, \"Parallel and Bio-Inspired Computing Applied \n to Analyze Microwave and Photonic Metamaterial Strucutures,\" \n Ph.D. thesis, University of Campinas, (2010)\n '''\n if x0 == 'random':\n lower, upper = zip(*normalize_bounds(bounds))\n x0 = random_initial_point(lower, upper)\n\n if maxeval == 'auto':\n dim = len(x0)\n maxeval = 10000 * dim\n\n if population:\n solver_options['population'] = population\n\n res = minimize(fun, x0, args = args, method='esch', jac = None, bounds=bounds,\n ftol_rel = ftol_rel, xtol_rel = xtol_rel, \n ftol_abs = ftol_abs, xtol_abs = xtol_abs, maxeval=maxeval, \n maxtime=maxtime, solver_options=solver_options)\n\n return res\n\ndef crs(fun, bounds, args=(), x0='random', population = None, \n ftol_rel = 1e-8, xtol_rel = 1e-6, ftol_abs = 1e-14, xtol_abs = 1e-8, \n maxeval='auto', maxtime = None, solver_options={}):\n '''\n Global optimization via Controlled Random Search with local mutation\n\n Parameters\n --------\n fun : callable \n The objective function to be minimized. Must be in the form ``fun(x, *args)``, where ``x`` is the argument in the form of a 1-D array and args is a tuple of any additional fixed parameters needed to completely specify the function\n bounds : tuple of array-like\n Bounds for variables. ``(min, max)`` pairs for each element in ``x``, defining the finite lower and upper bounds for the optimizing argument of ``fun``. It is required to have ``len(bounds) == len(x)``. ``len(bounds)`` is used to determine the number of parameters in ``x``.\n args : list, optional, default ()\n Further arguments to describe the objective function\n x0 : {ndarray, 'random'}, optional, default 'random'\n Initial parameter vector guess.\n If ndarray, must be a 1-D array\n if 'random', picks a random initial guess in the feasible region.\n population : int, optional, default None\n Population size.\n If None, will use NLopt's default population size.\n ftol_rel : float, optional, default 1e-8\n Relative function tolerance to signal convergence \n xtol_rel : float, optional, default 1e-6\n Relative parameter vector tolerance to signal convergence\n ftol_abs : float, optional, default 1e-14\n Absolute function tolerance to signal convergence\n xtol_abs : float, optional, default 1e-8\n Absolute parameter vector tolerance to signal convergence\n maxeval : {int, 'auto'}, optional, default 'auto'\n Number of maximal function evaluations.\n If 'auto', set to 1.000 * dimensions\n maxtime : float, optional, default None\n maximum absolute time until the optimization is terminated.\n solver_options: dict, optional, default None\n Dictionary of additional options supplied to the solver.\n\n Returns\n -------\n result : :py:class:`~OptimizeResult`\n The optimization result represented as a :py:class:`~OptimizeResult` object.\n Important attributes are: ``x`` the solution array, ``fun`` the value\n of the function at the solution, and ``message`` which describes the\n cause of the termination.\n See :py:class:`~OptimizeResult` for a description of other attributes.\n\n Notes\n -------\n References:\\n\n P. Kaelo and M. M. Ali, \"Some variants of the controlled random search algorithm\n for global optimization,\" J. Optim. Theory Appl. 130 (2), 253-264 (2006)\\n\n W. L. Price, \"Global optimization by controlled random search,\" \n J. Optim. Theory Appl. 40 (3), p. 333-348 (1983)\\n\n W. L. Price, \"A controlled random search procedure for global optimization,\" \n in Towards Global Optimization 2, p. 71-84 edited by L. C. W. Dixon and G. P. Szego \n (North-Holland Press, Amsterdam, 1978)\n '''\n if x0 == 'random':\n lower, upper = zip(*normalize_bounds(bounds))\n x0 = random_initial_point(lower, upper)\n\n if population:\n solver_options['population'] = population\n\n if maxeval == 'auto':\n maxeval = 10000 * len(x0)\n\n res = minimize(fun, x0, args = args, method='crs2_lm', jac = None, bounds=bounds,\n ftol_rel = ftol_rel, xtol_rel = xtol_rel, \n ftol_abs = ftol_abs, xtol_abs = xtol_abs, maxeval=maxeval, \n maxtime=maxtime, solver_options=solver_options)\n\n return res\n\ndef direct(fun, bounds, args=(), locally_biased = True, scale = True, \n randomize = False, ftol_rel = 1e-8, xtol_rel = 1e-6, \n ftol_abs = 1e-14, xtol_abs = 1e-8, maxeval=None, maxtime=None, solver_options={}):\n '''\n Global optimization via variants of the DIviding RECTangles (DIRECT) algorithm\n\n Parameters\n --------\n fun : callable \n The objective function to be minimized. Must be in the form ``fun(x, *args)``, where ``x`` is the argument in the form of a 1-D array and args is a tuple of any additional fixed parameters needed to completely specify the function\n bounds : tuple of array-like\n Bounds for variables. ``(min, max)`` pairs for each element in ``x``, defining the finite lower and upper bounds for the optimizing argument of ``fun``. It is required to have ``len(bounds) == len(x)``. ``len(bounds)`` is used to determine the number of parameters in ``x``.\n args : list, optional, default ()\n Further arguments to describe the objective function\n locally_biased : boolean, optional, default True\n If True, uses the locally biased variant of DIRECT known as DIRECT_L\n scale : boolean, optional, default True\n If True, scales the parameter space to a hypercube of length 1 in all dimensions\n randomize : boolean, optional, default False\n If True, randomize the algorithm by partly randomizing which side of the hyperrectangle is halved\n ftol_rel : float, optional, default 1e-8\n Relative function tolerance to signal convergence \n xtol_rel : float, optional, default 1e-6\n Relative parameter vector tolerance to signal convergence\n ftol_abs : float, optional, default 1e-14\n Absolute function tolerance to signal convergence\n xtol_abs : float, optional, default 1e-8\n Absolute parameter vector tolerance to signal convergence\n maxeval : {int, 'auto'}, optional, default 'auto'\n Number of maximal function evaluations.\n If 'auto', set to 1.000 * dimensions\n maxtime : float, optional, default None\n maximum absolute time until the optimization is terminated.\n solver_options: dict, optional, default None\n Dictionary of additional options supplied to the solver.\n\n Returns\n -------\n result : :py:class:`~OptimizeResult`\n The optimization result represented as a :py:class:`~OptimizeResult` object.\n Important attributes are: ``x`` the solution array, ``fun`` the value\n of the function at the solution, and ``message`` which describes the\n cause of the termination.\n See :py:class:`~OptimizeResult` for a description of other attributes.\n\n Notes\n -------\n References:\\n\n D. R. Jones, C. D. Perttunen, and B. E. Stuckmann, \"Lipschitzian optimization without \n the lipschitz constant,\" J. Optimization Theory and Applications, vol. 79, p. 157 (1993)\\n\n J. M. Gablonsky and C. T. Kelley, \"A locally-biased form of the DIRECT algorithm,\" \n J. Global Optimization, vol. 21 (1), p. 27-37 (2001)\\n\\n\n By default will use the locally biased variant with NLopt code \"DIRECT_L\". For objective functions\n with many local minima, setting ``locally_biased=False`` which calls the DIRECT algorithm without \n local bias is advisable.\n '''\n\n #pick the desired version of DIRECT\n\n if scale == True:\n if locally_biased == True:\n if randomize == True:\n direct_algorithm = 'GN_DIRECT_L_RAND'\n else:\n direct_algorithm = 'GN_DIRECT_L'\n else:\n direct_algorithm = 'GN_DIRECT'\n\n else:\n if locally_biased:\n if randomize:\n direct_algorithm = 'GN_DIRECT_L_RAND_NOSCAL'\n else:\n direct_algorithm = 'GN_DIRECT_L_NOSCAL'\n else:\n direct_algorithm = 'GN_DIRECT_NOSCAL' \n \n lower, upper = zip(*normalize_bounds(bounds))\n\n if maxeval == None:\n maxeval = 10000 * len(lower)\n \n result = minimize(fun, upper, args=args, method=direct_algorithm, jac = None, bounds=bounds,\n constraints=[], ftol_rel = ftol_rel, xtol_rel = xtol_rel, \n ftol_abs = ftol_abs, xtol_abs = xtol_abs, maxeval=maxeval, \n maxtime=maxtime, solver_options=solver_options)\n\n return result" ]
[ [ "numpy.asarray" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
benwmcdowell/VASP_add_selective_dynamics
[ "bb4dfb5f72de51018e9a57f25a3441a3362a7799" ]
[ "add_seldyn.py" ]
[ "from numpy import array,dot\r\nfrom numpy.linalg import inv,norm\r\nfrom getopt import getopt\r\nimport sys\r\n\r\ndef add_seldyn(mode, ifile, ofile,reverse, **args):\r\n try:\r\n lv, coord, atomtypes, atomnums, seldyn = parse_poscar(ifile)\r\n except ValueError:\r\n lv, coord, atomtypes, atomnums = parse_poscar(ifile)\r\n if 'frozen_axes'in args:\r\n frozen_axes=args['frozen_axes']\r\n if len(frozen_axes) == 0:\r\n frozen_axes=[0,1,2]\r\n else:\r\n frozen_axes=[0,1,2]\r\n if 'direct' in args:\r\n direct=args['direct']\r\n else:\r\n direct=False\r\n if 'ranges' in args:\r\n ranges=args['ranges']\r\n frozen_atoms=[]\r\n \r\n seldyn=['' for i in range(sum(atomnums))]\r\n if mode == 'type':\r\n counter=0\r\n for i in atomtypes:\r\n if i in args['frozen_atoms']:\r\n for j in range(atomnums[atomtypes.index(i)]):\r\n frozen_atoms.append(counter)\r\n counter+=1\r\n else:\r\n counter+=atomnums[atomtypes.index(i)]\r\n elif mode == 'number':\r\n frozen_atoms=args['frozen_atoms']\r\n \r\n elif mode == 'position':\r\n if direct == False:\r\n ref=dot(lv,array(args['reference_position']))\r\n else:\r\n ref=array(args['reference_position'])\r\n for i in range(sum(atomnums)):\r\n if norm(coord[i]-ref)<args['tolerance']:\r\n frozen_atoms.append(i)\r\n \r\n elif mode == 'range':\r\n for i in range(len(coord)):\r\n counter=0\r\n for j in range(3):\r\n if coord[i][j]>ranges[j][0] and coord[i][j]<ranges[j][1]:\r\n counter+=1\r\n if counter==3:\r\n frozen_atoms.append(i)\r\n else:\r\n print('mode not recognized. exiting...')\r\n sys.exit(1)\r\n \r\n #when selective dynamics is applied to atoms, they are reference starting at zero. if reading atom numbers from VESTA, subtract one from each.\r\n for i in range(len(coord)):\r\n if i in frozen_atoms:\r\n for j in range(3):\r\n if j in frozen_axes and not reverse:\r\n seldyn[i]+='F'\r\n elif j in frozen_axes and reverse:\r\n seldyn[i]+='T'\r\n elif reverse:\r\n seldyn[i]+='F'\r\n else:\r\n seldyn[i]+='T'\r\n elif reverse:\r\n seldyn[i]+='FFF'\r\n else:\r\n seldyn[i]='TTT'\r\n \r\n print(str(len(frozen_atoms))+' atoms selected')\r\n if reverse == False:\r\n print('atoms frozen:' + str(frozen_atoms))\r\n else:\r\n print('atoms un-frozen:' + str(frozen_atoms))\r\n \r\n write_poscar(ofile, lv, coord, atomtypes, atomnums, seldyn=seldyn)\r\n \r\ndef parse_poscar(ifile):\r\n with open(ifile, 'r') as file:\r\n lines=file.readlines()\r\n sf=float(lines[1])\r\n latticevectors=[float(lines[i].split()[j])*sf for i in range(2,5) for j in range(3)]\r\n latticevectors=array(latticevectors).reshape(3,3)\r\n atomtypes=lines[5].split()\r\n atomnums=[int(i) for i in lines[6].split()]\r\n if 'Direct' in lines[7] or 'Cartesian' in lines[7]:\r\n start=8\r\n mode=lines[7].split()[0]\r\n else:\r\n mode=lines[8].split()[0]\r\n start=9\r\n seldyn=[''.join(lines[i].split()[-3:]) for i in range(start,sum(atomnums)+start)]\r\n coord=array([[float(lines[i].split()[j]) for j in range(3)] for i in range(start,sum(atomnums)+start)])\r\n if mode!='Cartesian':\r\n for i in range(sum(atomnums)):\r\n for j in range(3):\r\n while coord[i][j]>1.0 or coord[i][j]<0.0:\r\n if coord[i][j]>1.0:\r\n coord[i][j]-=1.0\r\n elif coord[i][j]<0.0:\r\n coord[i][j]+=1.0\r\n coord[i]=dot(coord[i],latticevectors)\r\n \r\n #latticevectors formatted as a 3x3 array\r\n #coord holds the atomic coordinates with shape ()\r\n try:\r\n return latticevectors, coord, atomtypes, atomnums, seldyn\r\n except NameError:\r\n return latticevectors, coord, atomtypes, atomnums\r\n\r\ndef write_poscar(ofile, lv, coord, atomtypes, atomnums, **args):\r\n with open(ofile,'w') as file:\r\n if 'title' in args:\r\n file.write(str(args['title']))\r\n file.write('\\n1.0\\n')\r\n for i in range(3):\r\n for j in range(3):\r\n file.write(str('{:<018f}'.format(lv[i][j])))\r\n if j<2:\r\n file.write(' ')\r\n file.write('\\n')\r\n for i in atomtypes:\r\n file.write(' '+str(i))\r\n file.write('\\n')\r\n for i in atomnums:\r\n file.write(' '+str(i))\r\n file.write('\\n')\r\n if 'seldyn' in args:\r\n file.write('Selective Dynamics\\n')\r\n file.write('Direct\\n')\r\n for i in range(len(coord)):\r\n coord[i]=dot(coord[i],inv(lv))\r\n for i in range(len(coord)):\r\n for j in range(3):\r\n file.write(str('{:<018f}'.format(coord[i][j])))\r\n if j<2:\r\n file.write(' ')\r\n if 'seldyn' in args:\r\n for j in range(3):\r\n file.write(' ')\r\n file.write(args['seldyn'][i][j])\r\n file.write('\\n')\r\n print('new POSCAR written to: '+str(ofile))\r\n \r\nif __name__ == '__main__':\r\n ifile='./POSCAR'\r\n ofile='./POSCAR_seldyn'\r\n reverse=False\r\n direct=False\r\n mode='none'\r\n frozen_axes=[]\r\n short_opts='hi:m:rf:p:t:dw:o:a:'\r\n long_opts=['help','input=','mode=','reverse','frozen_atoms=','reference_position=','tolerance=','direct','range=','output=','axes=']\r\n try:\r\n opts,args=getopt(sys.argv[1:],short_opts,long_opts)\r\n except getopt.GetoptError:\r\n print('error in command line syntax')\r\n sys.exit(2)\r\n for i,j in opts:\r\n if i in ['-h','--help']:\r\n print('''\r\nNote: for options with multiple values, seperate the values with commas\r\n \r\nthese options take a value:\r\n -i, --input specify an input other than ./POSCAR\r\n -m, --mode optional modes are type, range, position, and number\r\n -p, --reference_position specify the reference point for position mode\r\n -t, --tolerance atoms within this distance of the reference point will freeze\r\n -f, --frozen_atoms specify the index of atoms to be frozen or the type\r\n -w, --range for range mode, specify the range of atoms to be selected\r\n form is: x_min,x_max,y_min,y_max,z_min,z_max\r\n values must be Cartesian coordinates\r\n -o, --output speicfy an output other than ./POSCAR_seldyn\r\n -a, --frozen_axes select which axes will be frozen\r\n default is all\r\nthese options take no value:\r\n -d, --direct use this to specify the reference point in Cartesian\r\n -r, --reverse specify un-frozen atoms rather than frozen\r\nhelp options:\r\n -h, --help display this error message\r\n''')\r\n sys.exit()\r\n if i in ['-i','--input']:\r\n ifile=j\r\n if i in ['-o','--output']:\r\n ofile=j\r\n if i in ['-m','--mode']:\r\n mode=str(j)\r\n if i in ['-r','--reverse']:\r\n reverse=True\r\n if i in ['-f','--frozen_atoms']:\r\n frozen_atoms=j.split(',')\r\n try:\r\n frozen_atoms=[int(i) for i in frozen_atoms]\r\n except ValueError:\r\n pass\r\n if i in ['-p','--reference_position']:\r\n reference_position=array([float(k) for k in j.split(',')])\r\n if i in ['-t','--tolerance']:\r\n tolerance=float(j)\r\n if i in ['-d','--direct']:\r\n direct=True\r\n if i in ['-w','--range']:\r\n ranges=j.split(',')\r\n ranges=[[float(ranges[i]),float(ranges[j])] for i,j in zip([0,2,4],[1,3,5])]\r\n if i in ['-a','-axes']:\r\n frozen_axes=j.split(',')\r\n try:\r\n frozen_axes=[int(i) for i in frozen_axes]\r\n except ValueError:\r\n pass\r\n \r\n if mode == 'type':\r\n try:\r\n add_seldyn(mode,ifile,ofile,reverse,frozen_atoms=frozen_atoms,frozen_axes=frozen_axes)\r\n except TypeError:\r\n print('incorrect use of arguments for mode: type')\r\n sys.exit(2)\r\n elif mode == 'number':\r\n try:\r\n add_seldyn(mode,ifile,ofile,reverse,frozen_atoms=frozen_atoms,frozen_axes=frozen_axes)\r\n except TypeError:\r\n print('incorrect use of arguments for mode: number')\r\n sys.exit(2)\r\n elif mode == 'position':\r\n try:\r\n add_seldyn(mode,ifile,ofile,reverse,reference_position=reference_position,tolerance=tolerance,direct=direct,frozen_axes=frozen_axes)\r\n except TypeError:\r\n print('incorrect use of arguments for mode: position')\r\n sys.exit(2)\r\n elif mode == 'range':\r\n try:\r\n add_seldyn(mode,ifile,ofile,reverse,ranges=ranges,frozen_axes=frozen_axes)\r\n except TypeError:\r\n print('incorrect use of arguments for mode: range')\r\n sys.exit(2)\r\n else:\r\n print('no mode specified. exiting...')\r\n sys.exit(1)\r\n" ]
[ [ "numpy.linalg.inv", "numpy.dot", "numpy.array", "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": [] } ]
sushant-tech/ga-learner-dsmp-repo
[ "aa40705fd5ac079c656c7c1cb2853a541f7d0447" ]
[ "Topic-Modelling-with-News-headlines/code.py" ]
[ "# --------------\n# import libraries\nimport numpy as np\nimport pandas as pd\nimport re\n\n# Load data\ndata=pd.read_csv(path,parse_dates=[0],infer_datetime_format=True)\n\n# Sort headlines by date of publish\ndata.sort_values('publish_date',inplace=True)\n\n# Retain only alphabets\ndata['headline_text'].apply(lambda x:re.sub('[^a-zA-Z]',' ',x))\n\n# Look at the shape of data\ndata.shape\n\n# Look at the first first five observations\ndata.head()\n\n\n# --------------\n# import libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport operator\n\n# Initialize CountVectorizer\nvectorizer = CountVectorizer(stop_words='english', max_features=30000)\n\n# Transform headlines\nnews = vectorizer.fit_transform(data['headline_text'])\n\n'''Number of times a feature/word appears over the entire document''' \n\n# initialize empty dictionary\nwords = {}\n\n# initialize with 0\ni = 0\n\n# Number of time every feature appears over the entire document\nsums = np.array(np.sum(news, axis=0)).flatten()\n\n# Loop to map 'sums' to its word\nfor word in vectorizer.get_feature_names():\n words[word] = sums[i]\n i += 1\n \n# Top 20 most occuring words\ntop_20 = sorted(words.items(), key=operator.itemgetter(1), reverse=True)[:20]\ntop_20_words = [i[0] for i in top_20]\ntop_20_values = [i[1] for i in top_20]\n\n# Display top 20 words\nplt.figure(figsize=(20,10))\nsns.barplot(top_20_words, top_20_values)\nplt.show()\n\n\n# --------------\n# import libraries\nfrom sklearn.decomposition import TruncatedSVD, LatentDirichletAllocation\nimport pprint\n\n# number of topics\nn_topics=5\n\n# initialize SVD \n\nlsa_model=TruncatedSVD(n_components=n_topics,random_state=2)\n# fit and transform 'news' \nlsa_topic_matrix=lsa_model.fit_transform(news)\n\n'''We are not interested in knowing every word of a topic.\nInstead, we want to look at the first (lets say) 10 words\nof a topic'''\n\n# empty dictionary to store topic number and top 10 words for every topic \ntopic_lsa={}\n\n# loop over every topic\nfor i,topic in enumerate(lsa_model.components_):\n key='Topic {}'.format(i)\n value=[(vectorizer.get_feature_names()[i]+'*'+str(topic[i]))for i in topic.argsort()[:-11:-1]]\n topic_lsa[key]=\"+\".join(value)\nprint(topic_lsa)\n\n\n \n# pretty print topics\n\n\n\n\n# --------------\n# import libraries\nimport nltk\nimport gensim\nimport gensim.corpora as corpora\nfrom gensim.utils import simple_preprocess\nfrom gensim.models import CoherenceModel\nfrom gensim.models.ldamodel import LdaModel\nfrom gensim.utils import simple_preprocess\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords \nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport string\nimport matplotlib.pyplot as plt\n\n# Function to clean data from stopwords, punctuation marks and lemmatize\ndef clean(doc):\n stop_free = \" \".join([i for i in doc.lower().split() if i not in stop])\n punc_free = ''.join(ch for ch in stop_free if ch not in exclude)\n normalized = \" \".join(lemma.lemmatize(word) for word in punc_free.split())\n return normalized\n\n# Code starts here\n\n# stopwords list\nstop = set(stopwords.words('english'))\n\n# string punctuations \nexclude = set(string.punctuation)\n\n# lemmatizer\nlemma = WordNetLemmatizer()\n\n# convert headlines to list\nheadlines = data['headline_text'].tolist()\n\n# cleaned data\nclean_headlines = [clean(doc).split() for doc in headlines]\n\n# Creating the term dictionary of our courpus, where every unique term is assigned an index\ndictionary = corpora.Dictionary(clean_headlines)\n\n# Converting list of documents (corpus) into Document Term Matrix using dictionary prepared above.\ndoc_term_matrix = [dictionary.doc2bow(doc) for doc in clean_headlines]\n\n# build LDA model\nlda_model = LdaModel(doc_term_matrix, num_topics=5, id2word = dictionary, iterations=10, random_state=2)\n\n# extract topics for headlines\ntopics = lda_model.print_topics(num_topics=5, num_words=10)\n\n# pprint topics\npprint.pprint(topics)\n\n# Code ends here\n\n\n# --------------\n# coherence score\n\ncoherence_model_lda = CoherenceModel(model=lda_model, texts=clean_headlines, dictionary=dictionary, coherence='c_v')\ncoherence_lda = coherence_model_lda.get_coherence()\nprint(coherence_lda)\n\n# Function to calculate coherence values\ndef compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):\n \"\"\"\n Compute c_v coherence for various number of topics\n\n Parameters:\n ----------\n dictionary : Gensim dictionary\n corpus : Gensim corpus\n texts : List of input texts\n limit : Max num of topics\n\n Returns:\n -------\n model_list : List of LDA topic models\n coherence_values : Coherence values corresponding to the LDA model with respective number of topics\n \"\"\"\n coherence_values = []\n model_list = []\n for num_topics in range(start, limit, step):\n model = gensim.models.ldamodel.LdaModel(doc_term_matrix, random_state = 2, num_topics=num_topics, id2word = dictionary, iterations=10)\n model_list.append(model)\n coherencemodel = CoherenceModel(model=model, texts=texts, dictionary=dictionary, coherence='c_v')\n coherence_values.append(coherencemodel.get_coherence())\n\n return model_list, coherence_values\n\n# Can take a long time to run.\nmodel_list, coherence_values = compute_coherence_values( dictionary=dictionary, corpus=doc_term_matrix, texts=clean_headlines, start=2, limit=50, step=6)\nprint([round(i,2) for i in coherence_values])\n\n# Plotting\nlimit=50; start=2; step=6;\nx = range(start, limit, step)\nplt.plot(x, coherence_values)\nplt.xlabel(\"Num Topics\")\nplt.ylabel(\"Coherence score\")\nplt.legend((\"coherence_values\"), loc='best')\nplt.show()\n\n\n" ]
[ [ "sklearn.decomposition.TruncatedSVD", "matplotlib.pyplot.legend", "pandas.read_csv", "matplotlib.pyplot.plot", "sklearn.feature_extraction.text.CountVectorizer", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.sum", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
chinchay/graphene-oxide
[ "6da0cc8eb951415e71e8c169f868ee9141186c2e" ]
[ "mtp_2D_7l/randomsurface/r23.py" ]
[ "import generate as gn\nimport randomSurface as rs\nfrom timeit import default_timer as timer\n\n\nstart = timer()\n\nlistA, listE = rs.getCurvesNotHighlyOrdrd(xlim=[14.0, 20.0], nLines=17, nRepeat=51)\n\nend = timer()\n\n#print(end - start)\nf = open(\"timeittook2\", \"w\")\nf.write( \"time = \" + str( end - start ) )\nf.close()\n\n\n#listA, listE = gn.plotCurvesRibbons(listnlines=[3, 5, 7, 15, 25, 31, 35, 41, 45, 51, 101, 401, 1001, 4001], xlim=[14.0, 20.0])\n# https://machinelearningmastery.com/how-to-save-a-numpy-array-to-file-for-machine-learning/\n# save numpy array as csv file\nfrom numpy import asarray\nfrom numpy import savetxt\n# define data\ndata_listA = asarray(listA)\ndata_listE = asarray(listE)\n# save to csv file\nsavetxt('data_listA33.csv', data_listA, delimiter=',')\nsavetxt('data_listE33.csv', data_listE, delimiter=',')\n\n\n" ]
[ [ "numpy.asarray", "numpy.savetxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
iisadoramacedo/geofem-master
[ "cc5cf4ae660480dd4dc3d805310f7207fb28230e" ]
[ "geofem/emg3d/meshes.py" ]
[ "\"\"\"\n\n:mod:`meshes` -- Discretization\n===============================\n\nEverything related to meshes appropriate for the multigrid solver.\n\n\"\"\"\n# Copyright 2018-2020 The emg3d Developers.\n#\n# This file is part of emg3d.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy\n# of the License at\n#\n# https://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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\n\nimport numpy as np\nfrom copy import deepcopy\nfrom scipy import optimize\n\n__all__ = ['TensorMesh', 'get_hx_h0', 'get_cell_numbers', 'get_stretched_h',\n 'get_domain', 'get_hx']\n\n\nclass TensorMesh:\n \"\"\"Rudimentary mesh for multigrid calculation.\n\n The tensor-mesh :class:`discretize.TensorMesh` is a powerful tool,\n including sophisticated mesh-generation possibilities in 1D, 2D, and 3D,\n plotting routines, and much more. However, in the multigrid solver we have\n to generate a mesh at each level, many times over and over again, and we\n only need a very limited set of attributes. This tensor-mesh class provides\n all required attributes. All attributes here are the same as their\n counterparts in :class:`discretize.TensorMesh` (both in name and value).\n\n .. warning::\n This is a slimmed-down version of :class:`discretize.TensorMesh`, meant\n principally for internal use by the multigrid modeller. It is highly\n recommended to use :class:`discretize.TensorMesh` to create the input\n meshes instead of this class. There are no input-checks carried out\n here, and there is only one accepted input format for `h` and `x0`.\n\n\n Parameters\n ----------\n h : list of three ndarrays\n Cell widths in [x, y, z] directions.\n\n x0 : ndarray of dimension (3, )\n Origin (x, y, z).\n\n \"\"\"\n\n def __init__(self, h, x0):\n \"\"\"Initialize the mesh.\"\"\"\n self.x0 = x0\n\n # Width of cells.\n self.hx = h[0]\n self.hy = h[1]\n self.hz = h[2]\n\n # Cell related properties.\n self.nCx = int(self.hx.size)\n self.nCy = int(self.hy.size)\n self.nCz = int(self.hz.size)\n self.vnC = np.array([self.hx.size, self.hy.size, self.hz.size])\n self.nC = int(self.vnC.prod())\n self.vectorCCx = np.r_[0, self.hx[:-1].cumsum()]+self.hx*0.5+self.x0[0]\n self.vectorCCy = np.r_[0, self.hy[:-1].cumsum()]+self.hy*0.5+self.x0[1]\n self.vectorCCz = np.r_[0, self.hz[:-1].cumsum()]+self.hz*0.5+self.x0[2]\n\n # Node related properties.\n self.nNx = self.nCx + 1\n self.nNy = self.nCy + 1\n self.nNz = self.nCz + 1\n self.vnN = np.array([self.nNx, self.nNy, self.nNz], dtype=int)\n self.nN = int(self.vnN.prod())\n self.vectorNx = np.r_[0., self.hx.cumsum()] + self.x0[0]\n self.vectorNy = np.r_[0., self.hy.cumsum()] + self.x0[1]\n self.vectorNz = np.r_[0., self.hz.cumsum()] + self.x0[2]\n\n # Edge related properties.\n self.vnEx = np.array([self.nCx, self.nNy, self.nNz], dtype=int)\n self.vnEy = np.array([self.nNx, self.nCy, self.nNz], dtype=int)\n self.vnEz = np.array([self.nNx, self.nNy, self.nCz], dtype=int)\n self.nEx = int(self.vnEx.prod())\n self.nEy = int(self.vnEy.prod())\n self.nEz = int(self.vnEz.prod())\n self.vnE = np.array([self.nEx, self.nEy, self.nEz], dtype=int)\n self.nE = int(self.vnE.sum())\n\n def __repr__(self):\n \"\"\"Simple representation.\"\"\"\n return (f\"TensorMesh: {self.nCx} x {self.nCy} x {self.nCz} \"\n f\"({self.nC:,})\")\n\n def copy(self):\n \"\"\"Return a copy of the TensorMesh.\"\"\"\n return TensorMesh.from_dict(self.to_dict(True))\n\n def to_dict(self, copy=False):\n \"\"\"Store the necessary information of the TensorMesh in a dict.\"\"\"\n out = {'hx': self.hx, 'hy': self.hy, 'hz': self.hz, 'x0': self.x0,\n '__class__': self.__class__.__name__}\n if copy:\n return deepcopy(out)\n else:\n return out\n\n @classmethod\n def from_dict(cls, inp):\n \"\"\"Convert dictionary into :class:`TensorMesh` instance.\n\n Parameters\n ----------\n inp : dict\n Dictionary as obtained from :func:`TensorMesh.to_dict`.\n The dictionary needs the keys `hx`, `hy`, `hz`, and `x0`.\n\n Returns\n -------\n obj : :class:`TensorMesh` instance\n\n \"\"\"\n try:\n return cls(h=[inp['hx'], inp['hy'], inp['hz']], x0=inp['x0'])\n except KeyError as e:\n print(f\"* ERROR :: Variable {e} missing in `inp`.\")\n raise\n\n @property\n def vol(self):\n \"\"\"Construct cell volumes of the 3D model as 1D array.\"\"\"\n if getattr(self, '_vol', None) is None:\n self._vol = (self.hx[None, None, :]*self.hy[None, :, None] *\n self.hz[:, None, None]).ravel()\n return self._vol\n\n\ndef get_hx_h0(freq, res, domain, fixed=0., possible_nx=None, min_width=None,\n pps=3, alpha=None, max_domain=100000., raise_error=True, verb=1,\n return_info=False):\n r\"\"\"Return cell widths and origin for given parameters.\n\n Returns cell widths for the provided frequency, resistivity, domain extent,\n and other parameters using a flexible amount of cells. See input parameters\n for more details. A maximum of three hard/fixed boundaries can be provided\n (one of which is the grid center).\n\n The minimum cell width is calculated through :math:`\\delta/\\rm{pps}`, where\n the skin depth is given by :math:`\\delta = 503.3 \\sqrt{\\rho/f}`, and the\n parameter `pps` stands for 'points-per-skindepth'. The minimum cell width\n can be restricted with the parameter `min_width`.\n\n The actual calculation domain adds a buffer zone around the (survey)\n domain. The thickness of the buffer is six times the skin depth. The field\n is basically zero after two wavelengths. A wavelength is\n :math:`2\\pi\\delta`, hence roughly 6 times the skin depth. Taking a factor 6\n gives therefore almost two wavelengths, as the field travels to the\n boundary and back. The actual buffer thickness can be steered with the\n `res` parameter.\n\n One has to take into account that the air is very resistive, which has to\n be considered not just in the vertical direction, but also in the\n horizontal directions, as the airwave will bounce back from the sides\n otherwise. In the marine case this issue reduces with increasing water\n depth.\n\n\n See Also\n --------\n get_stretched_h : Get `hx` for a fixed number `nx` and within a fixed\n domain.\n\n\n Parameters\n ----------\n\n freq : float\n Frequency (Hz) to calculate the skin depth. The skin depth is a concept\n defined in the frequency domain. If a negative frequency is provided,\n it is assumed that the calculation is carried out in the Laplace\n domain. To calculate the skin depth, the value of `freq` is then\n multiplied by :math:`-2\\pi`, to simulate the closest\n frequency-equivalent.\n\n res : float or list\n Resistivity (Ohm m) to calculate the skin depth. The skin depth is\n used to calculate the minimum cell width and the boundary thicknesses.\n Up to three resistivities can be provided:\n\n - float: Same resistivity for everything;\n - [min_width, boundaries];\n - [min_width, left boundary, right boundary].\n\n domain : list\n Contains the survey-domain limits [min, max]. The actual calculation\n domain consists of this domain plus a buffer zone around it, which\n depends on frequency and resistivity.\n\n fixed : list, optional\n Fixed boundaries, one, two, or maximum three values. The grid is\n centered around the first value. Hence it is the center location with\n the smallest cell. Two more fixed boundaries can be added, at most one\n on each side of the first one.\n Default is 0.\n\n possible_nx : list, optional\n List of possible numbers of cells. See :func:`get_cell_numbers`.\n Default is ``get_cell_numbers(500, 5, 3)``, which corresponds to\n [16, 24, 32, 40, 48, 64, 80, 96, 128, 160, 192, 256, 320, 384].\n\n min_width : float, list or None, optional\n Minimum cell width restriction:\n\n - None : No restriction;\n - float : Fixed to this value, ignoring skin depth and `pps`.\n - list [min, max] : Lower and upper bounds.\n\n Default is None.\n\n pps : int, optional\n Points per skindepth; minimum cell width is calculated via\n `dmin = skindepth/pps`.\n Default = 3.\n\n alpha : list, optional\n Maximum alpha and step size to find a good alpha. The first value is\n the maximum alpha of the survey domain, the second value is the maximum\n alpha for the buffer zone, and the third value is the step size.\n Default = [1, 1.5, .01], hence no stretching within the survey domain\n and a maximum stretching of 1.5 in the buffer zone; step size is 0.01.\n\n max_domain : float, optional\n Maximum calculation domain from fixed[0] (usually source position).\n Default is 100,000.\n\n raise_error : bool, optional\n If True, an error is raised if no suitable grid is found. Otherwise it\n just prints a message and returns None's.\n Default is True.\n\n verb : int, optional\n Verbosity, 0 or 1.\n Default = 1.\n\n return_info : bool\n If True, a dictionary is returned with some grid info (min and max\n cell width and alpha).\n\n\n Returns\n -------\n hx : ndarray\n Cell widths of mesh.\n\n x0 : float\n Origin of the mesh.\n\n info : dict\n Dictionary with mesh info; only if ``return_info=True``.\n\n Keys:\n\n - `dmin`: Minimum cell width;\n - `dmax`: Maximum cell width;\n - `amin`: Minimum alpha;\n - `amax`: Maximum alpha.\n\n \"\"\"\n # Get variables with default lists:\n if alpha is None:\n alpha = [1, 1.5, 0.01]\n if possible_nx is None:\n possible_nx = get_cell_numbers(500, 5, 3)\n\n # Cast resistivity value(s).\n res = np.array(res, ndmin=1)\n if res.size == 1:\n res_arr = np.array([res[0], res[0], res[0]])\n elif res.size == 2:\n res_arr = np.array([res[0], res[1], res[1]])\n else:\n res_arr = np.array([res[0], res[1], res[2]])\n\n # Cast and check fixed.\n fixed = np.array(fixed, ndmin=1)\n if fixed.size > 2:\n\n # Check length.\n if fixed.size > 3:\n print(\"\\n* ERROR :: Maximum three fixed boundaries permitted.\\n\"\n f\" Provided: {fixed.size}.\")\n raise ValueError(\"Wrong input for fixed\")\n\n # Sort second and third, so it doesn't matter how it was provided.\n fixed = np.array([fixed[0], max(fixed[1:]), min(fixed[1:])])\n\n # Check side.\n if np.sign(np.diff(fixed[:2])) == np.sign(np.diff(fixed[::2])):\n print(\"\\n* ERROR :: 2nd and 3rd fixed boundaries have to be \"\n \"left and right of the first one.\\n \"\n f\"Provided: [{fixed[0]}, {fixed[1]}, {fixed[2]}]\")\n raise ValueError(\"Wrong input for fixed\")\n\n # Calculate skin depth.\n skind = 503.3*np.sqrt(res_arr/abs(freq))\n if freq < 0: # For Laplace-domain calculations.\n skind /= np.sqrt(2*np.pi)\n\n # Minimum cell width.\n dmin = skind[0]/pps\n if min_width is not None: # Respect user input.\n min_width = np.array(min_width, ndmin=1)\n if min_width.size == 1:\n dmin = min_width\n else:\n dmin = np.clip(dmin, *min_width)\n\n # Survey domain; contains all sources and receivers.\n domain = np.array(domain, dtype=float)\n\n # Calculation domain; big enough to avoid boundary effects.\n # To avoid boundary effects we want the signal to travel two wavelengths\n # from the source to the boundary and back to the receiver.\n # => 2*pi*sd ~ 6.3*sd = one wavelength => signal is ~ 0.2 %.\n # Two wavelengths we can safely assume it is zero.\n #\n # The air does not follow the concept of skin depth, as it is a wave rather\n # than diffusion. For this is the factor `max_domain`, which restricts\n # the domain in each direction to this value from the center.\n\n # (a) Source to edges of domain.\n dist_in_domain = abs(domain - fixed[0])\n\n # (b) Two wavelengths.\n two_lambda = skind[1:]*4*np.pi\n\n # (c) Required buffer, additional to domain.\n dist_buff = np.max([np.zeros(2), (two_lambda - dist_in_domain)/2], axis=0)\n\n # (d) Add buffer to domain.\n calc_domain = np.array([domain[0]-dist_buff[0], domain[1]+dist_buff[1]])\n\n # (e) Restrict total domain to max_domain.\n calc_domain[0] = max(calc_domain[0], fixed[0]-max_domain)\n calc_domain[1] = min(calc_domain[1], fixed[0]+max_domain)\n\n # Initiate flag if terminated.\n finished = False\n\n # Initiate alpha variables for survey and calculation domains.\n sa, ca = 1.0, 1.0\n\n # Loop over possible cell numbers from small to big.\n for nx in np.unique(possible_nx):\n\n # Loop over possible alphas for domain.\n for sa in np.arange(1.0, alpha[0]+alpha[2]/2, alpha[2]):\n\n # Get current stretched grid cell sizes.\n thxl = dmin*sa**np.arange(nx) # Left of origin.\n thxr = dmin*sa**np.arange(nx) # Right of origin.\n\n # 0. Adjust stretching for fixed boundaries.\n if fixed.size > 1: # Move mesh to first fixed boundary.\n t_nx = np.r_[fixed[0], fixed[0]+np.cumsum(thxr)]\n ii = np.argmin(abs(t_nx-fixed[1]))\n thxr *= abs(fixed[1]-fixed[0])/np.sum(thxr[:ii])\n\n if fixed.size > 2: # Move mesh to second fixed boundary.\n t_nx = np.r_[fixed[0], fixed[0]-np.cumsum(thxl)]\n ii = np.argmin(abs(t_nx-fixed[2]))\n thxl *= abs(fixed[2]-fixed[0])/np.sum(thxl[:ii])\n\n # 1. Fill from center to left domain.\n nl = np.sum((fixed[0]-np.cumsum(thxl)) > domain[0])+1\n\n # 2. Fill from center to right domain.\n nr = np.sum((fixed[0]+np.cumsum(thxr)) < domain[1])+1\n\n # 3. Get remaining number of cells and check termination criteria.\n nsdc = nl+nr # Number of domain cells.\n nx_remain = nx-nsdc\n\n # Not good, try next.\n if nx_remain <= 0:\n continue\n\n # Create the current hx-array.\n hx = np.r_[thxl[:nl][::-1], thxr[:nr]]\n hxo = np.r_[thxl[:nl][::-1], thxr[:nr]]\n\n # Get actual domain:\n asurv_domain = [fixed[0]-np.sum(thxl[:nl]),\n fixed[0]+np.sum(thxr[:nr])]\n x0 = float(fixed[0]-np.sum(thxl[:nl]))\n\n # Get actual stretching (differs in case of fixed layers).\n sa_adj = np.max([hx[1:]/hx[:-1], hx[:-1]/hx[1:]])\n\n # Loop over possible alphas for calc_domain.\n for ca in np.arange(sa, alpha[1]+alpha[2]/2, alpha[2]):\n\n # 4. Fill to left calc_domain.\n thxl = hx[0]*ca**np.arange(1, nx_remain+1)\n nl = np.sum((asurv_domain[0]-np.cumsum(thxl)) >\n calc_domain[0])+1\n\n # 5. Fill to right calc_domain.\n thxr = hx[-1]*ca**np.arange(1, nx_remain+1)\n nr = np.sum((asurv_domain[1]+np.cumsum(thxr)) <\n calc_domain[1])+1\n\n # 6. Get remaining number of cells and check termination\n # criteria.\n ncdc = nl+nr # Number of calc_domain cells.\n nx_remain2 = nx-nsdc-ncdc\n\n if nx_remain2 < 0: # Not good, try next.\n continue\n\n # Create hx-array.\n nl += int(np.floor(nx_remain2/2)) # If uneven, add one cell\n nr += int(np.ceil(nx_remain2/2)) # more on the right.\n hx = np.r_[thxl[:nl][::-1], hx, thxr[:nr]]\n\n # Calculate origin.\n x0 = float(asurv_domain[0]-np.sum(thxl[:nl]))\n\n # Mark it as finished and break out of the loop.\n finished = True\n break\n\n if finished:\n break\n\n if finished:\n break\n\n # Check finished and print info about found grid.\n if not finished:\n # Throw message if no solution was found.\n print(\"\\n* ERROR :: No suitable grid found; relax your criteria.\\n\")\n if raise_error:\n raise ArithmeticError(\"No grid found!\")\n else:\n hx, x0 = None, None\n\n elif verb > 0:\n print(f\" Skin depth \", end=\"\")\n if res.size == 1:\n print(f\" [m] : {skind[0]:.0f}\")\n elif res.size == 2:\n print(f\"(m/l-r) [m] : {skind[0]:.0f} / {skind[1]:.0f}\")\n else:\n print(f\"(m/l/r) [m] : {skind[0]:.0f} / {skind[1]:.0f} / \"\n f\"{skind[2]:.0f}\")\n print(f\" Survey domain [m] : {domain[0]:.0f} - \"\n f\"{domain[1]:.0f}\")\n print(f\" Calculation domain [m] : {calc_domain[0]:.0f} - \"\n f\"{calc_domain[1]:.0f}\")\n print(f\" Final extent [m] : {x0:.0f} - \"\n f\"{x0+np.sum(hx):.0f}\")\n extstr = f\" Min/max cell width [m] : {min(hx):.0f} / \"\n alstr = f\" Alpha survey\"\n nrstr = \" Number of cells \"\n if not np.isclose(sa, sa_adj):\n sastr = f\"{sa:.3f} ({sa_adj:.3f})\"\n else:\n sastr = f\"{sa:.3f}\"\n print(extstr+f\"{max(hxo):.0f} / {max(hx):.0f}\")\n print(alstr+f\"/calc : {sastr} / {ca:.3f}\")\n print(nrstr+f\"(s/c/r) : {nx} ({nsdc}/{ncdc}/{nx_remain2})\")\n print()\n\n if return_info:\n if not fixed.size > 1:\n sa_adj = sa\n\n info = {'dmin': dmin,\n 'dmax': np.nanmax(hx),\n 'amin': np.nanmin([ca, sa, sa_adj]),\n 'amax': np.nanmax([ca, sa, sa_adj])}\n\n return hx, x0, info\n else:\n return hx, x0\n\n\ndef get_cell_numbers(max_nr, max_prime=5, min_div=3):\n r\"\"\"Returns 'good' cell numbers for the multigrid method.\n\n 'Good' cell numbers are numbers which can be divided by 2 as many times as\n possible. At the end there will be a low prime number.\n\n The function adds all numbers :math:`p 2^n \\leq M` for :math:`p={2, 3, ...,\n p_\\text{max}}` and :math:`n={n_\\text{min}, n_\\text{min}+1, ..., \\infty}`;\n :math:`M, p_\\text{max}, n_\\text{min}` correspond to `max_nr`, `max_prime`,\n and `min_div`, respectively.\n\n\n Parameters\n ----------\n max_nr : int\n Maximum number of cells.\n\n max_prime : int\n Highest permitted prime number p for p*2^n. {2, 3, 5, 7} are good upper\n limits in order to avoid too big lowest grids in the multigrid method.\n Default is 5.\n\n min_div : int\n Minimum times the number can be divided by two.\n Default is 3.\n\n\n Returns\n -------\n numbers : array\n Array containing all possible cell numbers from lowest to highest.\n\n \"\"\"\n # Primes till 20.\n primes = np.array([2, 3, 5, 7, 11, 13, 17, 19])\n\n # Sanity check; 19 is already ridiculously high.\n if max_prime > primes[-1]:\n print(f\"* ERROR :: Highest prime is {max_prime}, \"\n \"please use a value < 20.\")\n raise ValueError(\"Highest prime too high\")\n\n # Restrict to max_prime.\n primes = primes[primes <= max_prime]\n\n # Get possible values.\n # Currently restricted to prime*2**30 (for prime=2 => 1,073,741,824 cells).\n numbers = primes[:, None]*2**np.arange(min_div, 30)\n\n # Get unique values.\n numbers = np.unique(numbers)\n\n # Restrict to max_nr and return.\n return numbers[numbers <= max_nr]\n\n\ndef get_stretched_h(min_width, domain, nx, x0=0, x1=None, resp_domain=False):\n \"\"\"Return cell widths for a stretched grid within the domain.\n\n Returns `nx` cell widths within `domain`, where the minimum cell width is\n `min_width`. The cells are not stretched within `x0` and `x1`, and outside\n uses a power-law stretching. The actual stretching factor and the number of\n cells left and right of `x0` and `x1` are find in a minimization process.\n\n The domain is not completely respected. The starting point of the domain\n is, but the endpoint of the domain might slightly shift (this is more\n likely the case for small `nx`, for big `nx` the shift should be small).\n The new endpoint can be obtained with ``domain[0]+np.sum(hx)``. If you want\n the domain to be respected absolutely, set ``resp_domain=True``. However,\n be aware that this will introduce one stretch-factor which is different\n from the other stretch factors, to accommodate the restriction. This\n one-off factor is between the left- and right-side of `x0`, or, if `x1` is\n provided, just after `x1`.\n\n\n See Also\n --------\n get_hx_x0 : Get `hx` and `x0` for a flexible number of `nx` with\n given bounds.\n\n\n Parameters\n ----------\n\n min_width : float\n Minimum cell width. If x1 is provided, the actual minimum cell width\n might be smaller than min_width.\n\n domain : list\n [start, end] of model domain.\n\n nx : int\n Number of cells.\n\n x0 : float\n Center of the grid. `x0` is restricted to `domain`.\n Default is 0.\n\n x1 : float\n If provided, then no stretching is applied between `x0` and `x1`. The\n non-stretched part starts at `x0` and stops at the first possible\n location at or after `x1`. `x1` is restricted to `domain`. This will\n min_width so that an integer number of cells fit within x0 and x1.\n\n resp_domain : bool\n If False (default), then the domain-end might shift slightly to assure\n that the same stretching factor is applied throughout. If set to True,\n however, the domain is respected absolutely. This will introduce one\n stretch-factor which is different from the other stretch factors, to\n accommodate the restriction. This one-off factor is between the left-\n and right-side of `x0`, or, if `x1` is provided, just after `x1`.\n\n\n Returns\n -------\n hx : ndarray\n Cell widths of mesh.\n\n \"\"\"\n\n # Cast to arrays\n domain = np.array(domain, dtype=float)\n x0 = np.array(x0, dtype=float)\n x0 = np.clip(x0, *domain) # Restrict to model domain\n min_width = np.array(min_width, dtype=float)\n if x1 is not None:\n x1 = np.array(x1, dtype=float)\n x1 = np.clip(x1, *domain) # Restrict to model domain\n\n # If x1 is provided (a part is not stretched)\n if x1 is not None:\n\n # Store original values\n xlim_orig = domain.copy()\n nx_orig = int(nx)\n x0_orig = x0.copy()\n h_min_orig = min_width.copy()\n\n # Get number of non-stretched cells\n n_nos = int(np.ceil((x1-x0)/min_width))\n\n # Re-calculate min_width to fit with x0-x1-limits:\n min_width = (x1-x0)/n_nos\n\n # Subtract one cell, because the standard scheme provides one\n # min_width-cell.\n n_nos -= 1\n\n # Reset x0, because the first min_width comes from normal scheme\n x0 += min_width\n\n # Reset xmax for normal scheme\n domain[1] -= n_nos*min_width\n\n # Reset nx for normal scheme\n nx -= n_nos\n\n # If there are not enough points reset to standard procedure. The limit\n # of five is arbitrary. However, nx should be much bigger than five\n # anyways, otherwise stretched grid doesn't make sense.\n if nx <= 5:\n print(\"Warning :: Not enough points for non-stretched part,\"\n \"ignoring therefore `x1`.\")\n domain = xlim_orig\n nx = nx_orig\n x0 = x0_orig\n x1 = None\n min_width = h_min_orig\n\n # Get stretching factor (a = 1+alpha).\n if min_width == 0 or min_width > np.diff(domain)/nx:\n # If min_width is bigger than the domain-extent divided by nx, no\n # stretching is required at all.\n alpha = 0\n else:\n\n # Wrap _get_dx into a minimization function to call with fsolve.\n def find_alpha(alpha, min_width, args):\n \"\"\"Find alpha such that min(hx) = min_width.\"\"\"\n return min(get_hx(alpha, *args))/min_width-1\n\n # Search for best alpha, must be at least 0\n args = (domain, nx, x0)\n alpha = max(0, optimize.fsolve(find_alpha, 0.02, (min_width, args)))\n\n # With alpha get actual cell spacing with `resp_domain` to respect the\n # users decision.\n hx = get_hx(alpha, domain, nx, x0, resp_domain)\n\n # Add the non-stretched center if x1 is provided\n if x1 is not None:\n hx = np.r_[hx[: np.argmin(hx)], np.ones(n_nos)*min_width,\n hx[np.argmin(hx):]]\n\n # Print warning min_width could not be respected.\n if abs(hx.min() - min_width) > 0.1:\n print(f\"Warning :: Minimum cell width ({np.round(hx.min(), 2)} m) is \"\n \"below `min_width`, because `nx` is too big for `domain`.\")\n\n return hx\n\n\ndef get_domain(x0=0, freq=1, res=0.3, limits=None, min_width=None,\n fact_min=0.2, fact_neg=5, fact_pos=None):\n r\"\"\"Get domain extent and minimum cell width as a function of skin depth.\n\n Returns the extent of the calculation domain and the minimum cell width as\n a multiple of the skin depth, with possible user restrictions on minimum\n calculation domain and range of possible minimum cell widths.\n\n .. math::\n\n \\delta &= 503.3 \\sqrt{\\frac{\\rho}{f}} , \\\\\n x_\\text{start} &= x_0-k_\\text{neg}\\delta , \\\\\n x_\\text{end} &= x_0+k_\\text{pos}\\delta , \\\\\n h_\\text{min} &= k_\\text{min} \\delta .\n\n\n Parameters\n ----------\n\n x0 : float\n Center of the calculation domain. Normally the source location.\n Default is 0.\n\n freq : float\n Frequency (Hz) to calculate the skin depth. The skin depth is a concept\n defined in the frequency domain. If a negative frequency is provided,\n it is assumed that the calculation is carried out in the Laplace\n domain. To calculate the skin depth, the value of `freq` is then\n multiplied by :math:`-2\\pi`, to simulate the closest\n frequency-equivalent.\n\n Default is 1 Hz.\n\n res : float, optional\n Resistivity (Ohm m) to calculate skin depth.\n Default is 0.3 Ohm m (sea water).\n\n limits : None or list\n [start, end] of model domain. This extent represents the minimum extent\n of the domain. The domain is therefore only adjusted if it has to reach\n outside of [start, end].\n Default is None.\n\n min_width : None, float, or list of two floats\n Minimum cell width is calculated as a function of skin depth:\n fact_min*sd. If `min_width` is a float, this is used. If a list of\n two values [min, max] are provided, they are used to restrain\n min_width. Default is None.\n\n fact_min, fact_neg, fact_pos : floats\n The skin depth is multiplied with these factors to estimate:\n\n - Minimum cell width (`fact_min`, default 0.2)\n - Domain-start (`fact_neg`, default 5), and\n - Domain-end (`fact_pos`, defaults to `fact_neg`).\n\n\n Returns\n -------\n\n h_min : float\n Minimum cell width.\n\n domain : list\n Start- and end-points of calculation domain.\n\n \"\"\"\n\n # Set fact_pos to fact_neg if not provided.\n if fact_pos is None:\n fact_pos = fact_neg\n\n # Calculate the skin depth.\n skind = 503.3*np.sqrt(res/abs(freq))\n if freq < 0: # For Laplace-domain calculations.\n skind /= np.sqrt(2*np.pi)\n\n # Estimate minimum cell width.\n h_min = fact_min*skind\n if min_width is not None: # Respect user input.\n if np.array(min_width).size == 1:\n h_min = min_width\n else:\n h_min = np.clip(h_min, *min_width)\n\n # Estimate calculation domain.\n domain = [x0-fact_neg*skind, x0+fact_pos*skind]\n if limits is not None: # Respect user input.\n domain = [min(limits[0], domain[0]), max(limits[1], domain[1])]\n\n return h_min, domain\n\n\ndef get_hx(alpha, domain, nx, x0, resp_domain=True):\n r\"\"\"Return cell widths for given input.\n\n Find the number of cells left and right of `x0`, `nl` and `nr`\n respectively, for the provided alpha. For this, we solve\n\n .. math:: \\frac{x_\\text{max}-x_0}{x_0-x_\\text{min}} =\n \\frac{a^{nr}-1}{a^{nl}-1}\n\n where :math:`a = 1+\\alpha`.\n\n\n Parameters\n ----------\n\n alpha : float\n Stretching factor `a` is given by ``a=1+alpha``.\n\n domain : list\n [start, end] of model domain.\n\n nx : int\n Number of cells.\n\n x0 : float\n Center of the grid. `x0` is restricted to `domain`.\n\n resp_domain : bool\n If False (default), then the domain-end might shift slightly to assure\n that the same stretching factor is applied throughout. If set to True,\n however, the domain is respected absolutely. This will introduce one\n stretch-factor which is different from the other stretch factors, to\n accommodate the restriction. This one-off factor is between the left-\n and right-side of `x0`, or, if `x1` is provided, just after `x1`.\n\n\n Returns\n -------\n hx : ndarray\n Cell widths of mesh.\n\n \"\"\"\n if alpha <= 0.: # If alpha <= 0: equal spacing (no stretching at all)\n hx = np.ones(nx)*np.diff(np.squeeze(domain))/nx\n\n else: # Get stretched hx\n a = alpha+1\n\n # Get hx depending if x0 is on the domain boundary or not.\n if np.isclose(x0, domain[0]) or np.isclose(x0, domain[1]):\n # Get al a's\n alr = np.diff(domain)*alpha/(a**nx-1)*a**np.arange(nx)\n if x0 == domain[1]:\n alr = alr[::-1]\n\n # Calculate differences\n hx = alr*np.diff(domain)/sum(alr)\n\n else:\n # Find number of elements left and right by solving:\n # (xmax-x0)/(x0-xmin) = a**nr-1/(a**nl-1)\n nr = np.arange(2, nx+1)\n er = (domain[1]-x0)/(x0-domain[0]) - (a**nr[::-1]-1)/(a**nr-1)\n nl = np.argmin(abs(np.floor(er)))+1\n nr = nx-nl\n\n # Get all a's\n al = a**np.arange(nl-1, -1, -1)\n ar = a**np.arange(1, nr+1)\n\n # Calculate differences\n if resp_domain:\n # This version honours domain[0] and domain[1], but to achieve\n # this it introduces one stretch-factor which is different from\n # all the others between al to ar.\n hx = np.r_[al*(x0-domain[0])/sum(al),\n ar*(domain[1]-x0)/sum(ar)]\n else:\n # This version moves domain[1], but each stretch-factor is\n # exactly the same.\n fact = (x0-domain[0])/sum(al) # Take distance from al.\n hx = np.r_[al, ar]*fact\n\n # Note: this hx is equivalent as providing the following h\n # to TensorMesh:\n # h = [(min_width, nl-1, -a), (min_width, n_nos+1),\n # (min_width, nr, a)]\n\n return hx\n" ]
[ [ "numpy.nanmax", "numpy.sqrt", "numpy.squeeze", "numpy.nanmin", "numpy.cumsum", "numpy.max", "numpy.argmin", "numpy.clip", "numpy.unique", "numpy.arange", "numpy.ceil", "numpy.diff", "numpy.zeros", "numpy.isclose", "scipy.optimize.fsolve", "numpy.floor", "numpy.array", "numpy.sum", "numpy.ones" ] ]
[ { "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": [] } ]
jms0923/mmdet_tta
[ "8d4c298d615c07302ae668346c46c6bfd93a11bd" ]
[ "predict_utils.py" ]
[ " \nfrom abc import ABCMeta, abstractmethod\nfrom collections import OrderedDict\nfrom random import randint\n\nimport cv2\nimport mmcv\nimport numpy as np\nimport os\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom mmcv.runner import auto_fp16\nfrom mmcv.utils import print_log\nfrom mmcv.image import imread, imwrite\n\nfrom mmdet.utils import get_root_logger\n\n\nclass PostProcessor():\n def __init__(self,\n classes,\n score_thr=0.3):\n self.classes = classes\n self.num_classes = len(classes)\n if self.num_classes == 10:\n self.box_real_class = [0, 1, 1, 2, 3, 4, 5, 6, 5, 6]\n elif self.num_classes == 12:\n self.box_real_class = [0, 1, 1, 2, 3, 4, 5, 6, 2, 5, 0, 6]\n self.score_thr = score_thr\n self.thickness = 1\n self.font_scale = 0.5\n self.win_name = ''\n self.wait_time = 0\n self.colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0), (255, 255, 0), (0, 255, 255),\n (255, 0, 255), (255, 255, 255), (0, 0, 0), (255, 0, 128), (0, 191, 255),\n (10, 255, 128), (191, 255, 0), (255, 191, 0), (255, 128, 10), (50, 152, 89)]\n self.makeColors()\n self.iitpID = 1\n self.iitpJson = {'annotations':[]}\n\n def makeColors(self):\n if len(self.colors) >= self.num_classes:\n return\n else:\n while len(self.colors) < self.num_classes:\n self.colors.append((randint(20, 230), randint(20, 230), randint(20, 230)))\n return\n\n def saveResult(self,\n img,\n result,\n show=False,\n out_file=None):\n img, bboxes, labels = self.extractInfo(img, result, show=False, out_file=out_file)\n \n # draw bounding boxes\n return self.imshow_det_bboxes(img, bboxes, labels, show=show, out_file=out_file)\n\n def labelChanger(self, labels):\n appliedLabels = []\n if self.num_classes == 10:\n for i in labels:\n if i == 8:\n if 3 in labels or 4 in labels:\n i = 3\n if i == 9:\n if 3 in labels:\n i = 3 \n elif 4 in labels:\n i = 0 \n i = self.box_real_class[i]\n i += 1\n appliedLabels.append(i)\n elif self.num_classes == 12:\n appliedLabels = [self.box_real_class[i]+1 for i in labels]\n else:\n print('Unexpected # class')\n raise ValueError\n\n return appliedLabels\n\n def saveIitp(self, img, imgPath, result):\n _, bboxes, labels = self.extractInfo(img, result, show=False, out_file=None)\n bboxes, labels = self.iitpProcess(bboxes, labels)\n if len(labels) < 1:\n return False\n return self.annoMaker(imgPath, bboxes, labels)\n\n def annoMaker(self, imgPath, bboxes, labels, labelChanger=True):\n anno = {}\n anno['id'] = self.iitpID\n self.iitpID += 1\n if labelChanger:\n labels = self.labelChanger(labels)\n fileName = imgPath.split('/')[-1]\n anno['file_name'] = fileName\n anno['object'] = []\n for box, label in zip(bboxes, labels):\n anno['object'].append({\n 'box': box,\n 'label': 'c'+str(label)\n })\n self.iitpJson['annotations'].append(anno)\n\n return labels\n\n def iitpProcess(self, bboxes, labels):\n assert bboxes.ndim == 2\n assert labels.ndim == 1\n assert bboxes.shape[0] == labels.shape[0]\n assert bboxes.shape[1] == 4 or bboxes.shape[1] == 5\n\n if self.score_thr > 0:\n assert bboxes.shape[1] == 5\n scores = bboxes[:, -1]\n inds = scores > self.score_thr\n bboxes = bboxes[inds, :]\n labels = labels[inds]\n\n processedBoxes = []\n for box in bboxes:\n box = box.tolist()\n box.pop()\n box = list(map(int, box))\n processedBoxes.append(box)\n\n return processedBoxes, labels\n\n def bb_intersection_over_union(self, bboxes, labels, box_scores):\n # determine the (x, y)-coordinates of the intersection rectangle\n best_indexes = []\n\n for i in range(0, len(bboxes) - 1):\n\n best_iou = -1\n best_list = []\n\n for j in range(i + 1 , len(bboxes)):\n xA = max(bboxes[i][0], bboxes[j][0])\n yA = max(bboxes[i][1], bboxes[j][1])\n xB = min(bboxes[i][2], bboxes[j][2])\n yB = min(bboxes[i][3], bboxes[j][3])\n # compute the area of intersection rectangle\n interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)\n # compute the area of both the prediction and ground-truth\n # rectangles\n boxAArea = (bboxes[i][2] - bboxes[i][0] + 1) * (bboxes[i][3] - bboxes[i][1] + 1)\n boxBArea = (bboxes[j][2] - bboxes[j][0] + 1) * (bboxes[j][3] - bboxes[j][1] + 1)\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n iou = interArea / float(boxAArea + boxBArea - interArea)\n if iou > best_iou:\n best_iou = iou\n best_list = [i , j, best_iou]\n\n best_indexes.append(best_list)\n\n index = []\n for best_index in best_indexes:\n if best_index[2] > 0.98: # best_iou\n if box_scores[best_index[0]] > box_scores[best_index[1]]:\n index.append(best_index[1])\n\n else :\n index.append(best_index[0])\n\n index = set(index)\n index = sorted(list(index), reverse=True)\n\n for i in index :\n if box_scores[i] < self.score_thr + 0.05:\n bboxes = np.delete(bboxes, i, axis = 0)\n labels = np.delete(labels, i, axis = 0)\n box_scores = np.delete(box_scores, i, axis = 0)\n\n return bboxes, labels, box_scores\n\n def cropBoxes(self, img, result, out_file=None):\n img, bboxes, labels = self.extractInfo(img, result, show=False, out_file=out_file)\n assert bboxes.ndim == 2\n assert labels.ndim == 1\n assert bboxes.shape[0] == labels.shape[0]\n assert bboxes.shape[1] == 4 or bboxes.shape[1] == 5\n img = imread(img)\n box_scores = []\n\n if self.score_thr > 0:\n assert bboxes.shape[1] == 5\n scores = bboxes[:, -1]\n inds = scores > self.score_thr\n bboxes = bboxes[inds, :]\n labels = labels[inds]\n box_scores = scores[inds]\n\n img = np.ascontiguousarray(img)\n croppedImgs = []\n out_label = []\n\n if len(labels) > 1:\n bboxes, labels, box_scores = self.bb_intersection_over_union(bboxes, labels, box_scores)\n\n # path to save cropped image if save\n # splitPath = out_file.split('/')\n # fileName = splitPath.pop(-1).split('.')[0]\n\n for idx, (bbox, label) in enumerate(zip(bboxes, labels)):\n\n # !!!!!!!!!!! ~ Except class cap(8) or label(9) ~ !!!!!!!!!!!!\n if label != 8 and label != 9:\n \n bbox_int = bbox.astype(np.int32)\n heightRange = (bbox_int[1], bbox_int[3])\n widthRange = (bbox_int[0], bbox_int[2])\n\n dst = img.copy()\n\n center_x = int(int(bbox_int[0]) - int(bbox_int[0])*0.15)\n center_y = int(int(bbox_int[1]) - int(bbox_int[0])*0.15)\n width = int(int(bbox_int[2]) + int(bbox_int[2])*0.15)\n height = int(int(bbox_int[3]) + int(bbox_int[3])*0.15)\n\n dst = dst[center_y:height, center_x:width]\n\n # dst = dst[bbox_int[1]:bbox_int[3], bbox_int[0]:bbox_int[2]]\n\n croppedImgs.append(dst)\n\n out_label.append(label)\n\n # save cropped image \n # out_file = splitPath.copy()\n # out_file.append(fileName+'_'+str(idx)+'.jpg')\n # out_file = '/'.join(out_file)\n # if out_file is not None:\n # imwrite(dst, out_file)\n \n out_label = self.labelChanger(out_label)\n\n return croppedImgs, out_label\n\n def extractInfo(self,\n img,\n result,\n show=False,\n out_file=None):\n\n # batch_size = len(result)\n # print('batch_size : ', batch_size)\n # print('result : ', len(result[0]), result)\n \n img = mmcv.imread(img)\n img = img.copy()\n if isinstance(result, tuple):\n bbox_result, segm_result = result\n if isinstance(segm_result, tuple):\n segm_result = segm_result[0] # ms rcnn\n # print('check msrcnn : ', len(segm_result))\n else:\n bbox_result, segm_result = result, None\n bboxes = np.vstack(bbox_result)\n labels = [\n np.full(bbox.shape[0], i, dtype=np.int32)\n for i, bbox in enumerate(bbox_result)\n ]\n labels = np.concatenate(labels)\n # draw segmentation masks\n if segm_result is not None and len(labels) > 0: # non empty\n # print('check segm_result is not None')\n segms = mmcv.concat_list(segm_result)\n inds = np.where(bboxes[:, -1] > self.score_thr)[0]\n np.random.seed(42)\n color_masks = [\n np.random.randint(0, 256, (1, 3), dtype=np.uint8)\n for _ in range(max(labels) + 1)\n ]\n for i in inds:\n i = int(i)\n color_mask = color_masks[labels[i]]\n mask = segms[i].astype(bool)\n img[mask] = img[mask] * 0.5 + color_mask * 0.5\n # if out_file specified, do not show image in window\n if out_file is not None:\n show = False\n\n # if not (show or out_file):\n # return img\n\n return img, bboxes, labels\n\n def imshow_det_bboxes(self,\n img,\n bboxes,\n labels,\n show=True,\n out_file=None):\n\n assert bboxes.ndim == 2\n assert labels.ndim == 1\n assert bboxes.shape[0] == labels.shape[0]\n assert bboxes.shape[1] == 4 or bboxes.shape[1] == 5\n img = imread(img)\n\n if self.score_thr > 0:\n assert bboxes.shape[1] == 5\n scores = bboxes[:, -1]\n inds = scores > self.score_thr\n bboxes = bboxes[inds, :]\n labels = labels[inds]\n\n img = np.ascontiguousarray(img)\n for bbox, label in zip(bboxes, labels):\n bbox_int = bbox.astype(np.int32)\n left_top = (bbox_int[0], bbox_int[1])\n right_bottom = (bbox_int[2], bbox_int[3])\n cv2.rectangle(\n img, left_top, right_bottom, self.colors[label], thickness=self.thickness)\n label_text = self.classes[\n label] if self.classes is not None else f'cls {label}'\n if len(bbox) > 4:\n label_text += f'|{bbox[-1]:.02f}'\n cv2.putText(img, label_text, (bbox_int[0], bbox_int[1] - (label*2*randint(0, 1))),\n cv2.FONT_HERSHEY_COMPLEX, self.font_scale, self.colors[label])\n\n if show:\n imshow(img, self.win_name, self.wait_time)\n if out_file is not None:\n imwrite(img, out_file)\n return img\n\n\n\n\n\n def get_key_object(self, img, result, out_file=None):\n img, bboxes, labels = self.extractInfo(img, result, show=False, out_file=out_file)\n\n assert bboxes.ndim == 2\n assert labels.ndim == 1\n assert bboxes.shape[0] == labels.shape[0]\n assert bboxes.shape[1] == 4 or bboxes.shape[1] == 5\n box_scores = []\n\n if self.score_thr > 0:\n assert bboxes.shape[1] == 5\n scores = bboxes[:, -1]\n inds = scores > self.score_thr\n bboxes = bboxes[inds, :]\n labels = labels[inds]\n box_scores = scores[inds]\n\n if len(labels) > 1:\n bboxes, labels, box_scores = self.bb_intersection_over_union(bboxes, labels, box_scores)\n p = self.key_object(bboxes, labels)\n\n return labels, p\n\n def key_object(self, bboxes, labels):\n # set debug mode\n debug = False\n\n bbox = []\n if len(labels) > 1:\n for idx_box, ibox in enumerate(bboxes):\n bbox.append([ibox[0],ibox[1],ibox[2],ibox[3],ibox[4],labels[idx_box]])\n elif len(labels) == 1:\n bbox.append([bboxes[0][0],bboxes[0][1],bboxes[0][2],bboxes[0][3],bboxes[0][4],labels[0]])\n\n bounding_box = sorted(bbox, key=lambda k: k[0])\n if debug == True:\n print('sort: ', bounding_box)\n q = []\n p = []\n flag = 0\n for bidx, bi in enumerate(bounding_box):\n if bidx == 0 or len(q)==0:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n else:\n ck = 0\n cj = 1\n flag2 = 0\n for jdx in range(0,len(q)):\n if debug == True:\n print('ck: ',ck)\n print('jdx: ',jdx)\n qsz = len(q)\n if qsz == 1:\n bk = q[0]\n elif ck >= 1:\n bk = q[ck-cj]\n else:\n #bk = q[jdx]\n bk = q[jdx]\n\n if debug == True:\n print('bi: ', bi)\n print('size of LL: ', bk.size())\n print('bk (Q) :', bk.selectNode(0))\n print('size of q',len(q))\n for iddd in q:\n print('now q: ', iddd.selectNode(0))\n\n\n iou = self.get_iou(bk.selectNode(0).data, bi)\n bk_area = (bk.selectNode(0).data[2]-bk.selectNode(0).data[0])*(bk.selectNode(0).data[3]-bk.selectNode(0).data[1])\n bi_area = (bi[2]-bi[0])*(bi[3]-bi[1])\n if debug == True:\n print('iou',iou)\n print('bk_area',bk_area)\n print('bi_area',bi_area)\n\n #print('iou/((bi_area/bk_area)+1e-6)',iou/((bi_area/bk_area)+1e-6))\n\n #print('(bk.selectNode(0).data[1]/(bi[1]+1e-6))',(bk.selectNode(0).data[1]/(bi[1]+1e-6)))\n #print('bk.selectNode(0).data[3]/(bi[3]+1e-6)',bk.selectNode(0).data[3]/(bi[3]+1e-6))\n\n if iou >= 0.99 and iou/((bi_area/bk_area)+1e-6) >= 0.99:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n\n\n #print('bi[1]/(bk.selectNode(0).data[3]+1e-6)',bi[1]/(bk.selectNode(0).data[3]+1e-6))\n\n #if bi_area > bk_area:\n #print('area: ', bk_area/bi_area)\n # case 1\n # bi_xmin >> bk_xmax\n if bi[0] > bk.selectNode(0).data[2]:\n if debug == True:\n print('case 1')\n # delete bk from Q\n p.append(q.pop(0))\n #if ck == 0:\n if jdx == (len(q)) or len(q) == 0:\n if int(bk.selectNode(0).data[5]) == 8 and bk_area < bi_area and 0.98<bk.selectNode(0).data[3]/(bi[1]+1e-6):\n bk.insertFirst([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n break\n else:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n else:\n ck += 1\n if ck >= 2:\n cj += 1\n continue\n\n # case 2\n # bi_xmin ~= bk_xmax\n # bi is side, smaller than bk\n #elif 0.98 < (bi[0]/bk.selectNode(0).data[2]) and ((bk.selectNode(0).data[2]-bk.selectNode(0).data[0])*(bk.selectNode(0).data[3]-bk.selectNode(0).data[1])) > ((bi[2]-bi[0])*(bi[3]-bi[1])) and bk.selectNode(0).data[3] > bi[3]:\n elif 0.98 < (bi[0]/bk.selectNode(0).data[2]) and 1.1 > (bk.selectNode(0).data[2]/bi[0]) and (bk_area) > (bi_area) and bk.selectNode(0).data[3] > bi[3] and bk.selectNode(0).data[0] < bi[0] and bk.selectNode(0).data[1] < bi[1]:\n if debug == True:\n print('case 2')\n if ck != 0:\n ck += 1\n if flag == 0:\n if len(q) > jdx and bi[0] > q[jdx].selectNode(0).data[2]:\n p.append(q.pop(0))\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n elif int(bk.size()) > 2:\n p.append(q.pop(0))\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n else:\n if bi[5] != 8:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n else:\n bk.insertLast([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n break\n elif flag == 1:\n bk.insertFirst([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n flag = 0\n break\n # case 3\n # continue\n elif iou == 0.0:\n if ck != 0:\n ck += 1\n if debug == True:\n print('case 3')\n if jdx == (len(q)-1) or len(q) == 1:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n else:\n continue\n # case 4\n elif iou > 0.0:\n if ck != 0:\n ck += 1\n if debug == True:\n print('case 4')\n # a)\n if bk.selectNode(0).data[0] < bi[0] and bk.selectNode(0).data[1] < bi[1] and bk.selectNode(0).data[2] > bi[2] and bk.selectNode(0).data[3] > bi[3]:\n if debug == True:\n print('1')\n if bi[5] == 8 or bi[5] == 9:\n if bi[4] > 0.6 or flag2 == 1:\n bk.insertLast([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n flag2 = 0\n break\n elif bk.selectNode(0).data[5] == 0 and len(q) > 1: # 종이 일 때 q 안에 물체가 두개 이상일 때,\n flag2 = 1\n continue\n elif bi[5] == 9:\n bk.insertLast([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n flag2 = 0\n break\n else:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n else:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n # insert bi into L(bk)\n #break\n # b-1)\n elif 0.98 < (min(bk.selectNode(0).data[0],bi[0])/(max(bk.selectNode(0).data[0],bi[0])+1e-6)) and 0.98 < (min(bk.selectNode(0).data[3],bi[3])/(max(bk.selectNode(0).data[3],bi[3])+1e-6)):\n if debug == True:\n print('2')\n if (bk_area) > (bi_area):\n if bi[5] == 8 or bi[5] == 9:\n bk.insertLast([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]) # 이번만\n #q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[5]]))\n else:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n else:\n bk.insertFirst([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n break\n # b-2)\n elif 0.98 < (min(bk.selectNode(0).data[2],bi[2])/(max(bk.selectNode(0).data[2],bi[2])+1e-6)) and 0.98 < (min(bk.selectNode(0).data[3],bi[3])/(max(bk.selectNode(0).data[3],bi[3])+1e-6)):\n if debug == True:\n print('3')\n if (bk_area) > (bi_area):\n if int(bk.size()) == 3:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n else:\n bk.insertLast([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n else:\n if int(bk.size()) == 3:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n else:\n bk.insertFirst([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n break\n # b-3)\n elif 0.98 < (min(bk.selectNode(0).data[1],bi[1])/(max(bk.selectNode(0).data[1],bi[1])+1e-6)) and 0.90 < (min(bk.selectNode(0).data[2],bi[2])/(max(bk.selectNode(0).data[2],bi[2])+1e-6)) and 0.95 < (min(bk.selectNode(0).data[0],bi[0])/(max(bk.selectNode(0).data[0],bi[0])+1e-6)): # 0.98 -> 0.90\n if debug == True:\n print('4')\n if (bk_area) > (bi_area):\n if bi[5] == 8 or bi[5] == 9:\n bk.insertLast([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]) #이번만\n #q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[5]]))\n else:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n else:\n if int(bk.selectNode(0).data[5]) == 8 or int(bk.selectNode(0).data[5]) == 9:\n bk.insertFirst([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n else:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n # d) bk is side + bi is bigger than bk\n elif 0.98 < (bk.selectNode(0).data[2]/(bi[0]+1e-6)) and bk.selectNode(0).data[1] > bi[1] and bk.selectNode(0).data[3] > bi[3] and bk.selectNode(0).data[1] < bi[1] and (bk_area) < (bi_area):\n if debug == True:\n print('5')\n bk.insertFirst([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n break\n elif 0.98 < (min(bk.selectNode(0).data[0],bi[0])/(max(bk.selectNode(0).data[0],bi[0])+1e-6)) and bi_area > bk_area and 0.98 < iou/((bk_area/bi_area)+1e-6):\n if debug == True:\n print('6')\n bk.insertFirst([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n break\n elif bi_area > bk_area and bk.selectNode(0).data[1] > bi[1] and bk.selectNode(0).data[3] < bi[3]:\n if debug == True:\n print('7')\n if flag == 0:\n if bidx == len(bounding_box)-1 or len(bounding_box) <= 3:\n if 0.95 < (min(bk.selectNode(0).data[0],bi[0])/(max(bk.selectNode(0).data[0],bi[0])+1e-6)):\n #print('check')\n if int(bk.selectNode(0).data[5]) != 8:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n else:\n bk.insertFirst([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n break\n else:\n #print('check2')\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n else:\n if int(bk.selectNode(0).data[5]) == 8 and bi[5] != 8:\n bk.insertFirst([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n break\n else:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n flag += 1\n break\n elif flag == 1:\n bk.insertFirst([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n flag = 0\n break\n # 아래쪽 side\n elif bi_area < bk_area and 0.98 < (bi[1]/(bk.selectNode(0).data[3]+1e-6)) and bk.selectNode(0).data[0] < bi[0] and bk.selectNode(0).data[2] > bi[2]:\n if debug == True:\n print('8')\n if bi[5] != 8:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n else:\n bk.insertLast([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n break\n # inside 지만, 약간 튀어 나온 inside\n elif bi_area < bk_area and 0.95 < iou/((bi_area/bk_area)+1e-6) and 0.98 < (bk.selectNode(0).data[1]/(bi[1]+1e-6)) and 0.98 < (bk.selectNode(0).data[3]/(bi[3]+1e-6)):\n if debug == True:\n print('9')\n if bi[5] == 8 or bi[5] == 9:\n bk.insertLast([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n else:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n break\n # 위쪽 side\n elif bi_area < bk_area and 0.97 < (bk.selectNode(0).data[1]/(bi[3]+1e-6)) and bi[0] > bk.selectNode(0).data[0] and bi[3] < bk.selectNode(0).data[3]:\n if debug == True:\n print('10')\n if bi[5] == 8:\n bk.insertLast([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]])\n else:\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n else:\n if debug == True:\n print('last')\n if jdx == (len(q)-1):\n q.append(SingleLinkedList([bi[0],bi[1],bi[2],bi[3],bi[4],bi[5]]))\n #cj += 1\n continue\n else:\n continue\n\n for idxy in range(0, len(q)):\n p.append(q.pop(0))\n\n return p\n\n def get_iou(self, a, b, epsilon=1e-5):\n # COORDINATES OF THE INTERSECTION BOX\n x1 = max(a[0], b[0])\n y1 = max(a[1], b[1])\n x2 = min(a[2], b[2])\n y2 = min(a[3], b[3])\n\n # AREA OF OVERLAP - Area where the boxes intersect\n width = (x2 - x1)\n height = (y2 - y1)\n\n # handle case where there is NO overlap\n if (width<0) or (height <0):\n return 0.0\n area_overlap = width * height\n # COMBINED AREA\n area_a = (a[2] - a[0]) * (a[3] - a[1])\n area_b = (b[2] - b[0]) * (b[3] - b[1])\n area_combined = area_a + area_b - area_overlap\n\n # RATIO OF AREA OF OVERLAP OVER COMBINED AREA\n iou = area_overlap / (area_combined+epsilon)\n return iou\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n def __str__(self):\n return str(self.data)\n\nclass SingleLinkedList:\n def __init__(self, data):\n new_node = Node(data)\n self.head = new_node\n self.list_size = 1\n\n def __str__(self):\n print_list = '[ '\n node = self.head\n while True:\n print_list += str(node)\n if node.next == None:\n break\n node = node.next\n print_list += ', '\n print_list += ' ]'\n return print_list\n\n def insertFirst(self, data):\n new_node = Node(data)\n temp_node = self.head\n self.head = new_node\n self.head.next = temp_node\n self.list_size += 1\n\n def insertLast(self, data):\n node = self.head\n while True:\n if node.next == None:\n break\n node = node.next\n\n new_node = Node(data)\n node.next = new_node\n self.list_size += 1\n\n def insertMiddle(self, num, data):\n if self.head.next == None:\n self.insertLast(data)\n return\n node = self.selectNode(num)\n new_node = Node(data)\n temp_next = node.next\n node.next = new_node\n new_node.next = temp_next\n self.list_size += 1\n\n def selectNode(self, num):\n if self.list_size < num:\n print(\"Overflow\")\n return\n node = self.head\n count = 0\n while count < num:\n node = node.next\n count += 1\n return node\n\n def deleteNode(self, num):\n if self.list_size < 1:\n return # Underflow\n elif self.list_size < num:\n return # Overflow\n\n if num == 0:\n self.deleteHead()\n return\n node = self.selectNode(num - 1)\n node.next = node.next.next\n del_node = node.next\n del del_node\n\n def deleteHead(self):\n node = self.head\n self.head = node.next\n del node\n\n def size(self):\n return str(self.list_size)\n\n" ]
[ [ "numpy.random.seed", "numpy.ascontiguousarray", "numpy.full", "numpy.concatenate", "numpy.delete", "numpy.where", "numpy.vstack", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
1069066484/datasci_prj4
[ "8ff02e4b571bb3f166b2e94a7e4477afd8ac935c" ]
[ "HKMM.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 13 22:29:48 2019\n\n@author: 12709\n\n-- Zhixin Ling modified. 2019/5/17. \n Adding example codes to evaluate training and test accuracies and domain adaptation improvement.\n\"\"\"\n\nimport numpy as np\nimport sklearn.metrics\nfrom cvxopt import matrix, solvers\nimport Ldata_helper as data_helper\nimport Lglobal_defs as global_defs\nfrom sklearn import svm\n\ndef kernel(ker, X1, X2, gamma):\n K = None\n if ker == 'linear':\n if X2 is not None:\n K = sklearn.metrics.pairwise.linear_kernel(np.asarray(X1), np.asarray(X2))\n else:\n K = sklearn.metrics.pairwise.linear_kernel(np.asarray(X1))\n elif ker == 'rbf':\n if X2 is not None:\n K = sklearn.metrics.pairwise.rbf_kernel(np.asarray(X1), np.asarray(X2), gamma)\n else:\n K = sklearn.metrics.pairwise.rbf_kernel(np.asarray(X1), None, gamma)\n return K\n\nclass KMM:\n def __init__(self, kernel_type='linear', gamma=1.0, B=1.0, eps=None):\n '''\n Initialization function\n :param kernel_type: 'linear' | 'rbf'\n :param gamma: kernel bandwidth for rbf kernel\n :param B: bound for beta\n :param eps: bound for sigma_beta\n '''\n self.kernel_type = kernel_type\n self.gamma = gamma\n self.B = B\n self.eps = eps\n\n def fit(self, Xs, Xt):\n '''\n Fit source and target using KMM (compute the coefficients)\n :param Xs: ns * dim\n :param Xt: nt * dim\n :return: Coefficients (Pt / Ps) value vector (Beta in the paper)\n '''\n ns = Xs.shape[0]\n nt = Xt.shape[0]\n if self.eps == None:\n self.eps = self.B / np.sqrt(ns)\n K = kernel(self.kernel_type, Xs, None, self.gamma)\n kappa = np.sum(kernel(self.kernel_type, Xs, Xt, self.gamma) * float(ns) / float(nt), axis=1)\n\n K = matrix(K)\n kappa = matrix(kappa)\n G = matrix(np.r_[np.ones((1, ns)), -np.ones((1, ns)), np.eye(ns), -np.eye(ns)])\n h = matrix(np.r_[ns * (1 + self.eps), ns * (self.eps - 1), self.B * np.ones((ns,)), np.zeros((ns,))])\n\n sol = solvers.qp(K, -kappa, G, h)\n beta = np.array(sol['x'])\n return beta\n def fit_predict_svm(self, Xs, Ys, Xt, Yt, beta):\n weight = beta\n clf = svm.SVC(C=1.0, kernel='rbf',gamma = 'scale', decision_function_shape='ovr')\n clf.fit(Xs, Ys.ravel(), weight.ravel())\n y_pred = clf.predict(Xt)\n acc = sklearn.metrics.accuracy_score(Yt, y_pred)\n return acc, y_pred\n def fit_predict_lin_svm(self, Xs, Ys, Xt, Yt, beta):\n weight = beta\n clf = svm.LinearSVC()\n clf.fit(Xs, Ys.ravel(), weight.ravel())\n y_pred = clf.predict(Xt)\n acc = sklearn.metrics.accuracy_score(Yt, y_pred)\n return acc, y_pred\n\n def fit_predict_svm2(self, Xs, Ys, Xt, Yt, beta):\n weight = beta\n clf = svm.SVC(C=1.0, kernel='rbf',gamma = 'scale', decision_function_shape='ovr', max_iter=100)\n clf.fit(Xs, Ys.ravel(), weight.ravel())\n y_pred = clf.predict(Xt)\n acc = sklearn.metrics.accuracy_score(Yt, y_pred)\n return acc, y_pred, clf\n\n\ndef main_example():\n [src_dl, tgt_dl] = data_helper.read_paired_labeled_features(global_defs.DA.P2R)\n src_dl = data_helper.shuffle_labeled_data(src_dl)\n\n # First, test your model without domain adaptation\n clf = svm.LinearSVC()\n clf.fit(src_dl[0], src_dl[1].ravel(), max_iter=100)\n y_pred = clf.predict(tgt_dl[0])\n acc_without_da = sklearn.metrics.accuracy_score(tgt_dl[1], y_pred)\n\n # You need to split the target dataset into training set and test set\n tgt_tr_dl, tgt_te_dl = data_helper.labeled_data_split(tgt_dl, 0.6)\n kmm = KMM(kernel_type='rbf', B=10)\n beta = kmm.fit(Xs, Xt)\n acc_training_with_da, _, clf = kmm.fit_predict_svm2(src_dl[0], src_dl[1], tgt_tr_dl[0], tgt_tr_dl[1], beta)\n y_pred = clf.predict(tgt_te_dl[0])\n acc_test_with_da = sklearn.metrics.accuracy_score(tgt_te_dl[1], y_pred)\n print(\"Accuracy without domain adaptation = \", acc_without_da)\n print(\"Training accuracy with domain adaptation = \", acc_training_with_da)\n print(\"Test accuracy with domain adaptation = \", acc_test_with_da)\n\n\ndef main():\n [src,dst] = data_helper.read_paired_labeled_features(global_defs.DA.P2R)\n Xs = src[0]\n Ys = src[1]\n Xt = dst[0]\n Yt = dst[1]\n kmm = KMM(kernel_type='rbf', B=10)\n beta = kmm.fit(Xs, Xt)\n print(beta)\n print(beta.shape)\n acc2, ypre2 = kmm.fit_predict_svm(Xs, Ys, Xt, Yt, beta)\n print(\"svm_rbf result:\",acc2)\n acc3, ypre3 = kmm.fit_predict_lin_svm(Xs, Ys, Xt, Yt, beta)\n print(\"svm_lin result:\",acc3)\n\n\nif __name__ == '__main__':\n main()" ]
[ [ "numpy.sqrt", "numpy.asarray", "numpy.eye", "numpy.ones", "sklearn.svm.SVC", "sklearn.svm.LinearSVC", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zimmerman-cole/rbm-lai
[ "6bea9187988d99879d53ac3994d2efad1807eef4" ]
[ "src/lai.py" ]
[ "\"\"\"\nLocal ancestry inference.\n\"\"\"\nimport numpy as np\nimport itertools\nfrom collections import namedtuple\n\nimport matplotlib.pyplot as plt\n\ndef compute_window_accuracies(imputations, H_valid, window_size, save_path=None, hooks=list()):\n \"\"\"\n TODO: doc\n \n Args:\n ======================================================\n (dict) imputations: \n * Imputations made by each population-specific RBM on the (validation) data.\n * Entries (key : value) should include:\n * 'AFR' : (np.array) imputes_AFR - array of shape (num_haps, haplotype_len).\n * Same entries for other populations 'EUR', 'EAS', 'AMR'\n * 'model_info': list of strings - containing information (training, etc.) on each\n RBM model.\n * 'H_valid_info': (str) info - information on which rows of the validation data\n correspond to individuals from which population.\n ====================================\n (int) window_size:\n * Number of adjacent positions to consider.\n ====================================\n (np.array) H_valid: \n * An array of shape (num_haps, haplotype_len) containing the target haplotypes.\n \"\"\"\n pops = set(list(imputations.keys()))\n pops = list(pops.difference({'model_info', 'H_valid_info'}))\n\n n, m = imputations[pops[0]].shape\n\n accuracies = {p: np.zeros((n, 0)) for p in pops}\n # For all haplotypes: compute window accuracy for all positions, for all \n # *individual* models\n for col in range(m):\n for p in pops:\n w_b, w_e = max(0, col-window_size), min(m, col+window_size+1)\n w_size = w_e - w_b\n accs = np.where(H_valid[:, w_b:w_e] == imputations[p][:, w_b:w_e], 1, 0).sum(axis=1)\n accs = accs / w_size\n\n accuracies[p] = np.hstack([accuracies[p], accs.reshape(-1, 1)])\n \n for h in hooks:\n h(col, accuracies)\n \n if save_path is not None:\n out = dict()\n out['model_info'] = imputations['model_info']\n out['H_valid_info'] = imputations['H_valid_info']\n out['accuracies'] = accuracies\n try:\n f = open(save_path, 'wb')\n pkl.dump(out, f)\n except:\n print('Saving accuracies failed.')\n finally:\n f.close()\n \n return accuracies\n\n\ndef assign_ancestries(accuracies, hooks=[]):\n \n pops = list(accuracies.keys())\n n, m = list(accuracies.values())[0].shape\n \n out = list()\n\n for i, g_row in enumerate(range(0, n, 2)):\n out.append(list())\n \n for col in range(m):\n p_accs = dict()\n for (p1, p2) in itertools.combinations_with_replacement(pops, 2):\n \n acc1 = accuracies[p1][g_row][col] * accuracies[p2][g_row+1][col]\n acc2 = accuracies[p1][g_row+1][col] * accuracies[p2][g_row][col]\n \n p_accs[frozenset({p1, p2})] = max(acc1, acc2)\n \n best_pair = max(p_accs.items(), key=lambda item: item[1])[0]\n out[i].append(best_pair)\n \n for hook in hooks:\n hook(i, g_row)\n\n return out\n\nif __name__ == '__main__':\n pass" ]
[ [ "numpy.zeros", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jonah-chen/alphazero-guerzhoy
[ "9e45994d8fc687001bb98caefa2f89a7b4707ea1" ]
[ "8x8/ai.py" ]
[ "\"\"\"Constructs the Neural Network described in D. Silver et. al. Mastering the game of Go without human knowldege, Nature 550, 354-359(2017) doi:10.1038/nature24270.\n\nAuthor(s): Jonah Chen, Muhammad Ahsan Kaleem\n\"\"\"\n\nfrom concurrent.futures import ProcessPoolExecutor\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Input, Conv2D, Dense, BatchNormalization, Flatten, ReLU, Add\nfrom tensorflow.keras.losses import mean_squared_error, categorical_crossentropy\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.optimizers import SGD\nfrom random import randint\n\nfrom game import Game\n\nL2_VAL = 1e-4\n\n\ndef residual_block(x):\n \"\"\"Build the residual block described in the paper.\n \"\"\"\n y = Conv2D(256, (3, 3), strides=1, padding='same',\n kernel_regularizer=l2(l=L2_VAL))(x)\n y = BatchNormalization()(y)\n y = ReLU()(y)\n y = Conv2D(256, (3, 3), strides=1, padding='same',\n kernel_regularizer=l2(l=L2_VAL))(y)\n y = BatchNormalization()(y)\n out = Add()([x, y])\n out = ReLU()(out)\n return out\n\n\ndef build_model(input_shape=(8, 8, 2)):\n \"\"\"Build the ResNet with the additional features described in the paper.\n \"\"\"\n # Process input\n inputs = Input(shape=input_shape)\n\n # Create convolutional block\n t = Conv2D(256, (3, 3), strides=1, padding='same',\n kernel_regularizer=l2(l=L2_VAL))(inputs)\n t = BatchNormalization()(t)\n t = ReLU()(t)\n\n # Create 19 residual blocks\n for _ in range(19):\n t = residual_block(t)\n\n # Create policy head\n policy = Conv2D(2, (1, 1), strides=1, kernel_regularizer=l2(l=L2_VAL))(t)\n policy = BatchNormalization()(policy)\n policy = ReLU()(policy)\n policy = Flatten()(policy)\n policy = Dense(64, activation='softmax', kernel_regularizer=l2(\n l=L2_VAL), name=\"policy\")(policy)\n\n # Create value head\n value = Conv2D(1, (1, 1), strides=1, kernel_regularizer=l2(l=L2_VAL))(t)\n value = BatchNormalization()(value)\n value = ReLU()(value)\n value = Flatten()(value)\n value = Dense(256, activation='relu',\n kernel_regularizer=l2(l=L2_VAL))(value)\n\n value = Dense(1, activation='tanh', kernel_regularizer=l2(\n l=L2_VAL), name=\"value\")(value)\n # Build model\n model = Model(inputs=inputs, outputs=[policy, value])\n\n return model\n\n\ndef compile_new_model(loc, lr=1e-2, model=None):\n \"\"\"Compiles a model with the proper parameters. \n If no model is given, a new model will be created. \n The model is saved to the location loc.\n \"\"\"\n test_vector = np.random.randint(0, 2, size=(3, 8, 8, 2,))\n if model is None:\n model = build_model()\n print(model.predict(test_vector))\n model.compile(loss=[categorical_crossentropy, mean_squared_error], optimizer=SGD(\n lr=lr, momentum=0.9), metrics=['accuracy', 'mean_absolute_error'])\n model.summary()\n print(model.predict(test_vector))\n model.save(loc)\n\n\ndef train_model(model, num=None, s=None, pie=None, z=None, log_name=None, epochs=20, batch_size=32, transformations=True, max_history=20):\n \"\"\"Loads the training data to train the model and trains it with the given parameters.\n \"\"\"\n if num is not None:\n pie = np.load(f'selfplay_data/{num}/pie.npy')\n z = np.load(f'selfplay_data/{num}/z.npy')\n s = np.load(f'selfplay_data/{num}/s.npy')\n with ProcessPoolExecutor() as executor:\n for i in range(max(1, num-max_history), num):\n pie = executor.submit(np.append, pie, np.load(\n f'selfplay_data/{i}/pie.npy'), 0).result()\n z = executor.submit(np.append, z, np.load(\n f'selfplay_data/{i}/z.npy'), 0).result()\n s = executor.submit(np.append, s, np.load(\n f'selfplay_data/{i}/s.npy'), 0).result()\n elif s is None or pie is None or z is None:\n raise NotImplementedError(message=\"Did not recieve training data\")\n\n if transformations:\n for i in range(s.shape[0]):\n rotation, reflection = randint(0, 3), randint(0, 1)\n if rotation:\n s[i] = np.rot90(s[i], k=rotation, axes=(0, 1))\n pie[i] = np.rot90(pie[i].reshape(8,8,), k=rotation, axes=(0, 1)).reshape(64)\n if reflection:\n s[i] = np.flip(s[i], axis=0)\n pie[i] = np.flip(pie[i].reshape(8,8), axis=0).reshape(64)\n\n\n if log_name is None:\n model.fit(x=s, y=[pie, z], batch_size=batch_size,\n epochs=epochs, shuffle=True, use_multiprocessing=True)\n else:\n # Create the callbacks\n model_checkpoint = ModelCheckpoint(\n 'checkpoint', monitor='loss', save_best_only=True)\n tensorboard = TensorBoard(\n log_dir=f'LOGS/{log_name}', histogram_freq=1, write_images=True)\n\n model.fit(x=s, y=[pie, z],\n batch_size=batch_size,\n epochs=epochs,\n shuffle=True,\n use_multiprocessing=True,\n callbacks=[tensorboard, model_checkpoint])\n\n # Load the weights from the checkpoint\n model = tf.keras.models.load_model('checkpoint')\n\n\ndef test_model(model, num):\n \"\"\"Evaluates the model on a set of data to find loss and other metrics.\"\"\"\n pie = np.load(f'selfplay_data/{num}/pie.npy')\n z = np.load(f'selfplay_data/{num}/z.npy')\n s = np.load(f'selfplay_data/{num}/s.npy')\n model.evaluate(x=s, y=[pie, z], batch_size=32, use_multiprocessing=True)\n\n\nif __name__ == '__main__':\n # Lmao I gotta recover the models since I made a few mistakes.\n model = tf.keras.models.load_model(\"models/86.h5\")\n for i in range(1, 10):\n train_model(model, num=86, epochs=1, log_name=f\"monkaS{i}\", max_history=25)\n model.save(\"models/86.h5\")\n" ]
[ [ "tensorflow.keras.models.load_model", "tensorflow.keras.callbacks.ModelCheckpoint", "tensorflow.keras.layers.Input", "tensorflow.keras.layers.ReLU", "numpy.rot90", "tensorflow.keras.regularizers.l2", "tensorflow.keras.optimizers.SGD", "tensorflow.keras.Model", "tensorflow.keras.layers.Add", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.callbacks.TensorBoard", "numpy.load", "numpy.flip", "tensorflow.keras.layers.Flatten", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.2" ] } ]
archaeo-pteryx/montepython_public
[ "6fbcaa3266fd3a10a8e3ed4190dc65e6f29f1a37" ]
[ "montepython/likelihoods/Pantheon/__init__.py" ]
[ "\"\"\"\n.. module:: Pantheon\n :synopsis: Pantheon likelihood from Jones et al. 2018 and Scolnic et al. 2018\n\n.. moduleauthor:: Rodrigo von Marttens <[email protected]> and Antonella Cid <[email protected]>\n\nBased on the previous JLA likelihood writted by Benjamin Audren\n\n.. code::\n\n C00 = mag_covmat_file\n \n.. note::\n\n Since there are a lot of file manipulation involved, the \"pandas\" library\n has to be installed -- it is an 8-fold improvement in speed over numpy, and\n a 2-fold improvement over a fast Python implementation. The \"numexpr\"\n library is also needed for doing the fast array manipulations, done with\n blas daxpy function in the original c++ code. Both can be installed with\n pip (Python package manager) easily.\n\n\"\"\"\nimport numpy as np\nimport scipy.linalg as la\nimport montepython.io_mp as io_mp\ntry:\n import numexpr as ne\nexcept ImportError:\n raise io_mp.MissingLibraryError(\n \"This likelihood has intensive array manipulations. You \"\n \"have to install the numexpr Python package. Please type:\\n\"\n \"(sudo) pip install numexpr --user\")\nfrom montepython.likelihood_class import Likelihood_sn\n\n\nclass Pantheon(Likelihood_sn):\n\n def __init__(self, path, data, command_line):\n\n # Unusual construction, since the data files are not distributed\n # alongside Pantheon (size problems)\n try:\n Likelihood_sn.__init__(self, path, data, command_line)\n except IOError:\n raise io_mp.LikelihoodError(\n \"The Pantheon data files were not found. Please check if \"\n \"the following files are in the data/Pantheon directory: \"\n \"\\n-> pantheon.dataset\"\n \"\\n-> lcparam_full_long.txt\"\n \"\\n-> sys_full_long.dat\")\n\n # Load matrices from text files, whose names were read in the\n # configuration file\n self.C00 = self.read_matrix(self.mag_covmat_file)\n \n # Reading light-curve parameters from self.data_file (lcparam_full_long.txt)\n self.light_curve_params = self.read_light_curve_parameters()\n\n def loglkl(self, cosmo, data):\n \"\"\"\n Compute negative log-likelihood (eq.15 Betoule et al. 2014)\n\n \"\"\"\n # Recover the distance moduli from CLASS (a size N vector of double\n # containing the predicted distance modulus for each SN in the JLA\n # sample, given the redshift of the supernova.)\n redshifts = self.light_curve_params.zcmb\n size = redshifts.size\n\n moduli = np.empty((size, ))\n for index, row in self.light_curve_params.iterrows():\n z_cmb = row['zcmb']\n moduli[index] = cosmo.luminosity_distance(z_cmb)\n moduli = 5 * np.log10(moduli) + 25\n\n # Convenience variables: store the nuisance parameters in short named\n # variables\n M = (data.mcmc_parameters['M']['current'] *\n data.mcmc_parameters['M']['scale'])\n\n # Compute the covariance matrix\n # The module numexpr is used for doing quickly the long multiplication\n # of arrays (factor of 3 improvements over numpy). It is used as a\n # replacement of blas routines cblas_dcopy and cblas_daxpy\n # For numexpr to work, we need (seems like a bug, but anyway) to create\n # local variables holding the arrays. This cost no time (it is a simple\n # pointer assignment)\n C00 = self.C00\n cov = ne.evaluate(\"C00\")\n\n # Compute the residuals (estimate of distance moduli - exact moduli)\n residuals = np.empty((size,))\n sn = self.light_curve_params\n # This operation loops over all supernovae!\n # Compute the approximate moduli\n residuals = sn.mb - M\n # Remove from the approximate moduli the one computed from CLASS\n residuals -= moduli\n\n # Update the diagonal terms of the covariance matrix with the\n # statistical error\n cov += np.diag(sn.dmb**2)\n\n # Whiten the residuals, in two steps\n # 1) Compute the Cholesky decomposition of the covariance matrix, in\n # place. This is a time expensive (0.015 seconds) part\n cov = la.cholesky(cov, lower=True, overwrite_a=True)\n\n # 2) Solve the triangular system, also time expensive (0.02 seconds)\n residuals = la.solve_triangular(cov, residuals, lower=True, check_finite=False)\n\n # Finally, compute the chi2 as the sum of the squared residuals\n chi2 = (residuals**2).sum()\n\n return -0.5 * chi2\n" ]
[ [ "numpy.diag", "numpy.log10", "scipy.linalg.cholesky", "scipy.linalg.solve_triangular", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] } ]
haven-ai/optimization-benchmark
[ "7dd7c01b7e39d1ae4bcd365c6f854598d32867da" ]
[ "src/optimizers/__init__.py" ]
[ "import numpy as np\n# from . import sls\nfrom . import others\nfrom . import adaptive_first, adaptive_second\nimport torch\nfrom src.optimizers import sls, sps, ssn, sls_acc, sls_eg\n\n\ndef get_optimizer(opt, params, train_loader, exp_dict):\n \"\"\"\n opt: name or dict\n params: model parameters\n n_batches_per_epoch: b/n\n \"\"\"\n opt_name = opt[\"name\"]\n opt_dict = opt\n\n n_train = len(train_loader.dataset)\n batch_size = train_loader.batch_size\n n_batches_per_epoch = n_train / float(batch_size)\n \n\n if opt_name == \"adaptive_second\":\n opt = adaptive_second.AdaptiveSecond(params,\n c = opt_dict.get('c', None),\n n_batches_per_epoch=n_batches_per_epoch,\n # gv_option=opt_dict.get('gv_option', 'per_param'),\n base_opt=opt_dict.get('base_opt', 'adagrad'),\n accum_gv=opt_dict.get('accum_gv', None),\n lm=opt_dict.get('lm', 0),\n avg_window=opt_dict.get('window', 10),\n pp_norm_method=opt_dict.get('pp_norm_method', 'pp_armijo'),\n momentum=opt_dict.get('momentum', 0),\n beta=opt_dict.get('beta', 0.99),\n gamma=opt_dict.get('gamma', 2),\n # apply_sqrt=opt_dict.get('apply_sqrt', True),\n init_step_size=opt_dict.get('init_step_size', 1),\n adapt_flag=opt_dict.get('adapt_flag', 'constant'), \n step_size_method=opt_dict.get('step_size_method', 'sls'), \n # sls stuff\n beta_b=opt_dict.get('beta_b', .9),\n beta_f=opt_dict.get('beta_f', 2.),\n reset_option=opt_dict.get('reset_option', 1),\n line_search_fn=opt_dict.get('line_search_fn', \"armijo\"), \n )\n \n elif opt_name == \"adaptive_first\":\n\n opt = adaptive_first.AdaptiveFirst(params,\n c = opt_dict['c'],\n n_batches_per_epoch=n_batches_per_epoch,\n gv_option=opt_dict.get('gv_option', 'per_param'),\n base_opt=opt_dict['base_opt'],\n pp_norm_method=opt_dict['pp_norm_method'],\n momentum=opt_dict.get('momentum', 0),\n beta=opt_dict.get('beta', 0.99),\n gamma=opt_dict.get('gamma', 2),\n init_step_size=opt_dict.get('init_step_size', 1),\n adapt_flag=opt_dict.get('adapt_flag', 'constant'), \n step_size_method=opt_dict['step_size_method'], \n # sls stuff\n beta_b=opt_dict.get('beta_b', .9),\n beta_f=opt_dict.get('beta_f', 2.),\n reset_option=opt_dict.get('reset_option', 1),\n line_search_fn=opt_dict.get('line_search_fn', \"armijo\"), \n )\n \n elif opt_name == \"sgd_armijo\":\n # if opt_dict.get(\"infer_c\"):\n # c = (1e-3) * np.sqrt(n_batches_per_epoch)\n if opt_dict['c'] == 'theory':\n c = (n_train - batch_size) / (2 * batch_size * (n_train - 1))\n else:\n c = opt_dict.get(\"c\") or 0.1\n \n opt = sls.Sls(params,\n c = c,\n n_batches_per_epoch=n_batches_per_epoch,\n init_step_size=opt_dict.get(\"init_step_size\", 1),\n line_search_fn=opt_dict.get(\"line_search_fn\", \"armijo\"), \n gamma=opt_dict.get(\"gamma\", 2.0),\n reset_option=opt_dict.get(\"reset_option\", 1),\n eta_max=opt_dict.get(\"eta_max\"))\n\n\n elif opt_name == \"sgd_goldstein\":\n opt = sls.Sls(params, \n c=opt_dict.get(\"c\") or 0.1,\n reset_option=opt_dict.get(\"reset_option\") or 0,\n n_batches_per_epoch=n_batches_per_epoch,\n line_search_fn=\"goldstein\")\n\n elif opt_name == \"sgd_nesterov\":\n opt = sls_acc.SlsAcc(params, \n acceleration_method=\"nesterov\", \n gamma=opt_dict.get(\"gamma\", 2.0))\n\n elif opt_name == \"sgd_polyak\":\n opt = sls_acc.SlsAcc(params, \n c=opt_dict.get(\"c\") or 0.1,\n momentum=opt_dict.get(\"momentum\", 0.6),\n n_batches_per_epoch=n_batches_per_epoch,\n gamma=opt_dict.get(\"gamma\", 2.0),\n acceleration_method=\"polyak\",\n reset_option=opt_dict.get(\"reset\", 0))\n\n elif opt_name == \"seg\":\n opt = sls_eg.SlsEg(params, n_batches_per_epoch=n_batches_per_epoch)\n\n elif opt_name == \"ssn\":\n opt = ssn.Ssn(params, \n n_batches_per_epoch=n_batches_per_epoch, \n init_step_size=opt_dict.get('init_step_size', 1.0), \n lr=None, \n c=opt_dict.get('c',0.1), \n beta=0.9, \n gamma=1.5,\n reset_option=1, \n lm=opt_dict.get(\"lm\", 0))\n\n # ===============================================\n # others\n elif opt_name == \"adam\":\n opt = torch.optim.Adam(params, amsgrad=opt.get('amsgrad'), lr=opt['lr'], betas=opt.get('betas', (0.9,0.99)))\n\n elif opt_name == \"adagrad\":\n opt = torch.optim.Adagrad(params, lr=opt['lr'])\n\n elif opt_name == 'sgd':\n # best_lr = lr if lr else 1e-3\n opt = torch.optim.SGD(params, lr=opt.get('lr', 1e-3), momentum=opt.get('momentum', 0))\n\n elif opt_name == \"sgd-m\":\n best_lr = lr if lr else 1e-3\n opt = torch.optim.SGD(params, lr=best_lr, momentum=0.9)\n\n elif opt_name == 'rmsprop':\n opt = torch.optim.RMSprop(params, lr=opt['lr'])\n\n elif opt_name == 'adabound':\n opt = others.AdaBound(params)\n print('Running AdaBound..')\n\n elif opt_name == 'amsbound':\n opt = others.AdaBound(params, amsbound=True)\n\n elif opt_name == 'sps':\n opt = sps.Sps(params, c=opt_dict[\"c\"], \n n_batches_per_epoch=n_batches_per_epoch, \n adapt_flag=opt_dict.get('adapt_flag', 'basic'),\n fstar_flag=opt_dict.get('fstar_flag'),\n eta_max=opt_dict.get('eta_max'),\n eps=opt_dict.get('eps', 0),\n gamma=opt_dict.get('gamma', 2),\n momentum=opt_dict.get('momentum', 0),\n )\n\n\n elif opt_name == 'lookahead':\n base_opt = torch.optim.Adam(params, lr=1e-3, betas=(0.9, 0.999)) # Any optimizer\n opt = others.Lookahead(base_opt, k=5, alpha=0.5) # Initialize Lookahead\n\n # base_opt = torch.optim.Adam(params)\n # opt = others.Lookahead(base_opt)\n\n elif opt_name == 'radam':\n opt = others.RAdam(params)\n\n elif opt_name == 'plain_radam':\n opt = others.PlainRAdam(params)\n\n\n else:\n raise ValueError(\"opt %s does not exist...\" % opt_name)\n\n return opt\n\n\n\n\n" ]
[ [ "torch.optim.RMSprop", "torch.optim.Adam", "torch.optim.Adagrad", "torch.optim.SGD" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jrcyyzb/yolox-
[ "46d7656874daf4121552a1d1d925c827f27e598a" ]
[ "RoYOLOX/mmdet/datasets/pipelines/loading.py" ]
[ "# Copyright (c) OpenMMLab. All rights reserved.\nimport os.path as osp\n\nimport mmcv\nimport numpy as np\nimport pycocotools.mask as maskUtils\n\nfrom mmdet.core import BitmapMasks, PolygonMasks\nfrom ..builder import PIPELINES\n\ntry:\n from panopticapi.utils import rgb2id\nexcept ImportError:\n rgb2id = None\n\n\[email protected]_module()\nclass LoadImageFromFile:\n \"\"\"Load an image from file.\n\n Required keys are \"img_prefix\" and \"img_info\" (a dict that must contain the\n key \"filename\"). Added or updated keys are \"filename\", \"img\", \"img_shape\",\n \"ori_shape\" (same as `img_shape`), \"pad_shape\" (same as `img_shape`),\n \"scale_factor\" (1.0) and \"img_norm_cfg\" (means=0 and stds=1).\n\n Args:\n to_float32 (bool): Whether to convert the loaded image to a float32\n numpy array. If set to False, the loaded image is an uint8 array.\n Defaults to False.\n color_type (str): The flag argument for :func:`mmcv.imfrombytes`.\n Defaults to 'color'.\n file_client_args (dict): Arguments to instantiate a FileClient.\n See :class:`mmcv.fileio.FileClient` for details.\n Defaults to ``dict(backend='disk')``.\n \"\"\"\n\n def __init__(self,\n to_float32=False,\n color_type='color',\n file_client_args=dict(backend='disk')):\n self.to_float32 = to_float32\n self.color_type = color_type\n self.file_client_args = file_client_args.copy()\n self.file_client = None\n\n def __call__(self, results):\n \"\"\"Call functions to load image and get image meta information.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded image and meta information.\n \"\"\"\n\n if self.file_client is None:\n self.file_client = mmcv.FileClient(**self.file_client_args)\n\n if results['img_prefix'] is not None:\n filename = osp.join(results['img_prefix'],\n results['img_info']['filename'])\n else:\n filename = results['img_info']['filename']\n\n img_bytes = self.file_client.get(filename)\n img = mmcv.imfrombytes(img_bytes, flag=self.color_type)\n if self.to_float32:\n img = img.astype(np.float32)\n\n results['filename'] = filename\n results['ori_filename'] = results['img_info']['filename']\n results['img'] = img\n results['img_shape'] = img.shape\n results['ori_shape'] = img.shape\n results['img_fields'] = ['img']\n return results\n\n def __repr__(self):\n repr_str = (f'{self.__class__.__name__}('\n f'to_float32={self.to_float32}, '\n f\"color_type='{self.color_type}', \"\n f'file_client_args={self.file_client_args})')\n return repr_str\n\n\[email protected]_module()\nclass LoadImageFromWebcam(LoadImageFromFile):\n \"\"\"Load an image from webcam.\n\n Similar with :obj:`LoadImageFromFile`, but the image read from webcam is in\n ``results['img']``.\n \"\"\"\n\n def __call__(self, results):\n \"\"\"Call functions to add image meta information.\n\n Args:\n results (dict): Result dict with Webcam read image in\n ``results['img']``.\n\n Returns:\n dict: The dict contains loaded image and meta information.\n \"\"\"\n\n img = results['img']\n if self.to_float32:\n img = img.astype(np.float32)\n\n results['filename'] = None\n results['ori_filename'] = None\n results['img'] = img\n results['img_shape'] = img.shape\n results['ori_shape'] = img.shape\n results['img_fields'] = ['img']\n return results\n\n\[email protected]_module()\nclass LoadMultiChannelImageFromFiles:\n \"\"\"Load multi-channel images from a list of separate channel files.\n\n Required keys are \"img_prefix\" and \"img_info\" (a dict that must contain the\n key \"filename\", which is expected to be a list of filenames).\n Added or updated keys are \"filename\", \"img\", \"img_shape\",\n \"ori_shape\" (same as `img_shape`), \"pad_shape\" (same as `img_shape`),\n \"scale_factor\" (1.0) and \"img_norm_cfg\" (means=0 and stds=1).\n\n Args:\n to_float32 (bool): Whether to convert the loaded image to a float32\n numpy array. If set to False, the loaded image is an uint8 array.\n Defaults to False.\n color_type (str): The flag argument for :func:`mmcv.imfrombytes`.\n Defaults to 'color'.\n file_client_args (dict): Arguments to instantiate a FileClient.\n See :class:`mmcv.fileio.FileClient` for details.\n Defaults to ``dict(backend='disk')``.\n \"\"\"\n\n def __init__(self,\n to_float32=False,\n color_type='unchanged',\n file_client_args=dict(backend='disk')):\n self.to_float32 = to_float32\n self.color_type = color_type\n self.file_client_args = file_client_args.copy()\n self.file_client = None\n\n def __call__(self, results):\n \"\"\"Call functions to load multiple images and get images meta\n information.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded images and meta information.\n \"\"\"\n\n if self.file_client is None:\n self.file_client = mmcv.FileClient(**self.file_client_args)\n\n if results['img_prefix'] is not None:\n filename = [\n osp.join(results['img_prefix'], fname)\n for fname in results['img_info']['filename']\n ]\n else:\n filename = results['img_info']['filename']\n\n img = []\n for name in filename:\n img_bytes = self.file_client.get(name)\n img.append(mmcv.imfrombytes(img_bytes, flag=self.color_type))\n img = np.stack(img, axis=-1)\n if self.to_float32:\n img = img.astype(np.float32)\n\n results['filename'] = filename\n results['ori_filename'] = results['img_info']['filename']\n results['img'] = img\n results['img_shape'] = img.shape\n results['ori_shape'] = img.shape\n # Set initial values for default meta_keys\n results['pad_shape'] = img.shape\n results['scale_factor'] = 1.0\n num_channels = 1 if len(img.shape) < 3 else img.shape[2]\n results['img_norm_cfg'] = dict(\n mean=np.zeros(num_channels, dtype=np.float32),\n std=np.ones(num_channels, dtype=np.float32),\n to_rgb=False)\n return results\n\n def __repr__(self):\n repr_str = (f'{self.__class__.__name__}('\n f'to_float32={self.to_float32}, '\n f\"color_type='{self.color_type}', \"\n f'file_client_args={self.file_client_args})')\n return repr_str\n\n\[email protected]_module()\nclass LoadAnnotations:\n \"\"\"Load multiple types of annotations.\n\n Args:\n with_bbox (bool): Whether to parse and load the bbox annotation.\n Default: True.\n with_label (bool): Whether to parse and load the label annotation.\n Default: True.\n with_mask (bool): Whether to parse and load the mask annotation.\n Default: False.\n with_seg (bool): Whether to parse and load the semantic segmentation\n annotation. Default: False.\n poly2mask (bool): Whether to convert the instance masks from polygons\n to bitmaps. Default: True.\n file_client_args (dict): Arguments to instantiate a FileClient.\n See :class:`mmcv.fileio.FileClient` for details.\n Defaults to ``dict(backend='disk')``.\n \"\"\"\n\n def __init__(self,\n with_bbox=True,\n with_label=True,\n with_mask=False,\n with_seg=False,\n poly2mask=False,\n file_client_args=dict(backend='disk')):\n self.with_bbox = with_bbox\n # self.with_polygon=with_polygon\n self.with_label = with_label\n self.with_mask = with_mask\n self.with_seg = with_seg\n self.poly2mask = poly2mask\n self.file_client_args = file_client_args.copy()\n self.file_client = None\n\n def _load_bboxes(self, results):\n \"\"\"Private function to load bounding box annotations.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded bounding box annotations.\n \"\"\"\n\n ann_info = results['ann_info']\n results['gt_bboxes'] = ann_info['bboxes'].copy()\n\n gt_bboxes_ignore = ann_info.get('bboxes_ignore', None)\n if gt_bboxes_ignore is not None:\n results['gt_bboxes_ignore'] = gt_bboxes_ignore.copy()\n results['bbox_fields'].append('gt_bboxes_ignore')\n results['bbox_fields'].append('gt_bboxes')\n return results\n\n def _load_labels(self, results):\n \"\"\"Private function to load label annotations.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded label annotations.\n \"\"\"\n\n results['gt_labels'] = results['ann_info']['labels'].copy()\n return results\n\n def _poly2mask(self, mask_ann, img_h, img_w):\n \"\"\"Private function to convert masks represented with polygon to\n bitmaps.\n\n Args:\n mask_ann (list | dict): Polygon mask annotation input.\n img_h (int): The height of output mask.\n img_w (int): The width of output mask.\n\n Returns:\n numpy.ndarray: The decode bitmap mask of shape (img_h, img_w).\n \"\"\"\n\n if isinstance(mask_ann, list):\n # polygon -- a single object might consist of multiple parts\n # we merge all parts into one mask rle code\n rles = maskUtils.frPyObjects(mask_ann, img_h, img_w)\n rle = maskUtils.merge(rles)\n elif isinstance(mask_ann['counts'], list):\n # uncompressed RLE\n rle = maskUtils.frPyObjects(mask_ann, img_h, img_w)\n else:\n # rle\n rle = mask_ann\n mask = maskUtils.decode(rle)\n return mask\n\n def process_polygons(self, polygons):\n \"\"\"Convert polygons to list of ndarray and filter invalid polygons.\n\n Args:\n polygons (list[list]): Polygons of one instance.\n\n Returns:\n list[numpy.ndarray]: Processed polygons.\n \"\"\"\n\n polygons = [np.array(p) for p in polygons]\n valid_polygons = []\n for polygon in polygons:\n if len(polygon) % 2 == 0 and len(polygon) >= 6:\n valid_polygons.append(polygon)\n return valid_polygons\n\n def _load_masks(self, results):\n \"\"\"Private function to load mask annotations.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded mask annotations.\n If ``self.poly2mask`` is set ``True``, `gt_mask` will contain\n :obj:`PolygonMasks`. Otherwise, :obj:`BitmapMasks` is used.\n \"\"\"\n\n h, w = results['img_info']['height'], results['img_info']['width']\n gt_masks = results['ann_info']['masks']\n if self.poly2mask:\n gt_masks = BitmapMasks(\n [self._poly2mask(mask, h, w) for mask in gt_masks], h, w)\n else:\n gt_masks = PolygonMasks(\n [self.process_polygons(polygons) for polygons in gt_masks], h,\n w)\n results['gt_masks'] = gt_masks\n results['mask_fields'].append('gt_masks')\n return results\n\n def _load_semantic_seg(self, results):\n \"\"\"Private function to load semantic segmentation annotations.\n\n Args:\n results (dict): Result dict from :obj:`dataset`.\n\n Returns:\n dict: The dict contains loaded semantic segmentation annotations.\n \"\"\"\n\n if self.file_client is None:\n self.file_client = mmcv.FileClient(**self.file_client_args)\n\n filename = osp.join(results['seg_prefix'],\n results['ann_info']['seg_map'])\n img_bytes = self.file_client.get(filename)\n results['gt_semantic_seg'] = mmcv.imfrombytes(\n img_bytes, flag='unchanged').squeeze()\n results['seg_fields'].append('gt_semantic_seg')\n return results\n\n def __call__(self, results):\n \"\"\"Call function to load multiple types annotations.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded bounding box, label, mask and\n semantic segmentation annotations.\n \"\"\"\n\n if self.with_bbox:\n results = self._load_bboxes(results)\n if results is None:\n return None\n if self.with_label:\n results = self._load_labels(results)\n if self.with_mask:\n results = self._load_masks(results)\n if self.with_seg:\n results = self._load_semantic_seg(results)\n return results\n\n def __repr__(self):\n repr_str = self.__class__.__name__\n repr_str += f'(with_bbox={self.with_bbox}, '\n repr_str += f'with_label={self.with_label}, '\n repr_str += f'with_mask={self.with_mask}, '\n repr_str += f'with_seg={self.with_seg}, '\n repr_str += f'poly2mask={self.poly2mask}, '\n repr_str += f'poly2mask={self.file_client_args})'\n return repr_str\n\n\[email protected]_module()\nclass LoadPanopticAnnotations(LoadAnnotations):\n \"\"\"Load multiple types of panoptic annotations.\n\n Args:\n with_bbox (bool): Whether to parse and load the bbox annotation.\n Default: True.\n with_label (bool): Whether to parse and load the label annotation.\n Default: True.\n with_mask (bool): Whether to parse and load the mask annotation.\n Default: True.\n with_seg (bool): Whether to parse and load the semantic segmentation\n annotation. Default: True.\n file_client_args (dict): Arguments to instantiate a FileClient.\n See :class:`mmcv.fileio.FileClient` for details.\n Defaults to ``dict(backend='disk')``.\n \"\"\"\n\n def __init__(self,\n with_bbox=True,\n with_label=True,\n with_mask=True,\n with_seg=True,\n file_client_args=dict(backend='disk')):\n if rgb2id is None:\n raise RuntimeError(\n 'panopticapi is not installed, please install it by: '\n 'pip install git+https://github.com/cocodataset/'\n 'panopticapi.git.')\n\n super(LoadPanopticAnnotations,\n self).__init__(with_bbox, with_label, with_mask, with_seg, True,\n file_client_args)\n\n def _load_masks_and_semantic_segs(self, results):\n \"\"\"Private function to load mask and semantic segmentation annotations.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded mask and semantic segmentation\n annotations. `BitmapMasks` is used for mask annotations.\n \"\"\"\n\n if self.file_client is None:\n self.file_client = mmcv.FileClient(**self.file_client_args)\n filename = osp.join(results['seg_prefix'],\n results['ann_info']['seg_map'])\n\n img_bytes = self.file_client.get(filename)\n pan_png = mmcv.imfrombytes(\n img_bytes, flag='color', channel_order='rgb').squeeze()\n pan_png = rgb2id(pan_png)\n\n gt_masks = []\n gt_seg = np.zeros_like(pan_png) # 0 as ignore\n\n for mask_info in results['ann_info']['masks']:\n mask = (pan_png == mask_info['id'])\n gt_seg = np.where(mask, mask_info['category'] + 1, gt_seg)\n\n # The legal thing masks\n if mask_info.get('is_thing'):\n gt_masks.append(mask.astype(np.uint8))\n\n if self.with_mask:\n h, w = results['img_info']['height'], results['img_info']['width']\n gt_masks = BitmapMasks(gt_masks, h, w)\n results['gt_masks'] = gt_masks\n results['mask_fields'].append('gt_masks')\n\n if self.with_seg:\n results['gt_semantic_seg'] = gt_seg\n results['seg_fields'].append('gt_semantic_seg')\n return results\n\n def __call__(self, results):\n \"\"\"Call function to load multiple types panoptic annotations.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded bounding box, label, mask and\n semantic segmentation annotations.\n \"\"\"\n\n if self.with_bbox:\n results = self._load_bboxes(results)\n if results is None:\n return None\n if self.with_label:\n results = self._load_labels(results)\n if self.with_mask or self.with_seg:\n # The tasks completed by '_load_masks' and '_load_semantic_segs'\n # in LoadAnnotations are merged to one function.\n results = self._load_masks_and_semantic_segs(results)\n\n return results\n\n\[email protected]_module()\nclass LoadProposals:\n \"\"\"Load proposal pipeline.\n\n Required key is \"proposals\". Updated keys are \"proposals\", \"bbox_fields\".\n\n Args:\n num_max_proposals (int, optional): Maximum number of proposals to load.\n If not specified, all proposals will be loaded.\n \"\"\"\n\n def __init__(self, num_max_proposals=None):\n self.num_max_proposals = num_max_proposals\n\n def __call__(self, results):\n \"\"\"Call function to load proposals from file.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded proposal annotations.\n \"\"\"\n\n proposals = results['proposals']\n if proposals.shape[1] not in (4, 5):\n raise AssertionError(\n 'proposals should have shapes (n, 4) or (n, 5), '\n f'but found {proposals.shape}')\n proposals = proposals[:, :4]\n\n if self.num_max_proposals is not None:\n proposals = proposals[:self.num_max_proposals]\n\n if len(proposals) == 0:\n proposals = np.array([[0, 0, 0, 0]], dtype=np.float32)\n results['proposals'] = proposals\n results['bbox_fields'].append('proposals')\n return results\n\n def __repr__(self):\n return self.__class__.__name__ + \\\n f'(num_max_proposals={self.num_max_proposals})'\n\n\[email protected]_module()\nclass FilterAnnotations:\n \"\"\"Filter invalid annotations.\n\n Args:\n min_gt_bbox_wh (tuple[int]): Minimum width and height of ground truth\n boxes.\n \"\"\"\n\n def __init__(self, min_gt_bbox_wh):\n # TODO: add more filter options\n self.min_gt_bbox_wh = min_gt_bbox_wh\n\n def __call__(self, results):\n assert 'gt_bboxes' in results\n gt_bboxes = results['gt_bboxes']\n w = gt_bboxes[:, 2] - gt_bboxes[:, 0]\n h = gt_bboxes[:, 3] - gt_bboxes[:, 1]\n keep = (w > self.min_gt_bbox_wh[0]) & (h > self.min_gt_bbox_wh[1])\n if not keep.any():\n return None\n else:\n keys = ('gt_bboxes', 'gt_labels', 'gt_masks', 'gt_semantic_seg')\n for key in keys:\n if key in results:\n results[key] = results[key][keep]\n return results\n\[email protected]_module()\nclass LoadPolygonAnnotations:\n '''\n modify by loadannotation\n '''\n def __init__(self,\n with_polygon=True,\n with_label=True,\n file_client_args=dict(backend='disk')):\n self.with_polygon=with_polygon\n self.with_label = with_label\n self.file_client_args = file_client_args.copy()\n self.file_client = None\n\n def _load_polygons(self, results):\n \"\"\"Private function to load ploygons annotations.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded bounding box annotations.\n \"\"\"\n\n ann_info = results['ann_info']\n results['gt_bboxes'] = ann_info['bboxes'].copy()\n # print(results['gt_bboxes'])\n # gt_bboxes_ignore = ann_info.get('bboxes_ignore', None)\n # if gt_bboxes_ignore is not None:\n # results['gt_bboxes_ignore'] = gt_bboxes_ignore.copy()\n # results['bbox_fields'].append('gt_bboxes_ignore')\n results['bbox_fields'].append('gt_bboxes') # its polygon but use this key\n return results\n\n def _load_labels(self, results):\n \"\"\"Private function to load label annotations.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded label annotations.\n \"\"\"\n\n results['gt_labels'] = results['ann_info']['labels'].copy()\n return results\n\n def __call__(self, results):\n \"\"\"Call function to load multiple types annotations.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded bounding box, label, mask and\n semantic segmentation annotations.\n \"\"\"\n if self.with_polygon:\n results = self._load_polygons(results)\n if results is None:\n return None\n if self.with_label:\n results = self._load_labels(results)\n return results\n\n def __repr__(self):\n repr_str = self.__class__.__name__\n repr_str += f'(with_ploygon={self.with_polygon}, '\n repr_str += f'with_label={self.with_label}, '\n return repr_str\n" ]
[ [ "numpy.stack", "numpy.ones", "numpy.zeros_like", "numpy.array", "numpy.zeros", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tqtifnypmb/ML
[ "dfcc6f849b1d5ee2efd0faa0f585091fc7263a6c" ]
[ "rebuild_wheel/MLP/Gradient_Methods.py" ]
[ "import tensorflow as tf\nimport numpy as np\n\nfrom sklearn import datasets\nfrom sklearn import metrics\nfrom sklearn import neural_network\nfrom sklearn import preprocessing\nfrom math import floor, sqrt\n\nclass MLP:\n def __init__(self, \n learning_rate,\n gradient_type, \n relu = None,\n batch_size = 100, \n max_iteration = 200, \n tolerent = 1e-2,\n rigid = 1e-6):\n self.learning_rate_ = learning_rate\n self.batch_size_ = batch_size\n self.max_iteration_ = max_iteration\n self.tolerent_ = tolerent\n self.gradient_type_ = gradient_type\n self.relu_ = relu\n self.best_loss_value_ = 1000000.\n self.no_improvement_num_ = 0\n self.max_no_improvement_num_ = 10\n self.rigid_ = rigid\n\n def _init_weights(self, hidden_shape, output_shape):\n var_w1 = 2 / hidden_shape[0]\n var_w2 = 2 / output_shape[0]\n w1 = tf.random_normal(hidden_shape, stddev=sqrt(var_w1)) * sqrt(2.0 / hidden_shape[0])\n w2 = tf.random_normal(output_shape, stddev=sqrt(var_w2)) * sqrt(2.0 / output_shape[0])\n return w1, w2\n\n def _predifined_optimizer(self, y_pred, y):\n loss = tf.losses.mean_squared_error(y_pred, y)\n optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_)\n optimize_action = optimizer.minimize(loss)\n\n return loss, optimize_action\n\n def _vanilia_gradient_descent(self, loss, w1, w2):\n grad_w1, grad_w2 = tf.gradients(loss, [w1, w2])\n new_w1 = w1.assign(w1 - grad_w1 / self.batch_size_ * self.learning_rate_)\n new_w2 = w2.assign(w2 - grad_w2 / self.batch_size_ * self.learning_rate_)\n\n return loss, tf.group(new_w1, new_w2)\n\n def _momentum_gradient_descent(self, loss, w1, w2):\n grad_w1, grad_w2 = tf.gradients(loss, [w1, w2])\n\n vel_1_shape = (self.n_features_, self.neuron_num_)\n vel_2_shape = (self.neuron_num_, self.n_labels_dim_)\n\n velocity1 = tf.Variable(tf.zeros(vel_1_shape))\n velocity2 = tf.Variable(tf.zeros(vel_2_shape))\n\n gama = 0.9\n\n velocity1 = velocity1.assign(gama * velocity1 + grad_w1 / self.batch_size_ * self.learning_rate_)\n velocity2 = velocity2.assign(gama * velocity2 + grad_w2 / self.batch_size_ * self.learning_rate_)\n new_w1 = w1.assign(w1 - velocity1)\n new_w2 = w2.assign(w2 - velocity2)\n return loss, tf.group(new_w1, new_w2)\n\n def _nesterov_gradient_descent(self, input, label, w1, w2): \n vel_1_shape = (self.n_features_, self.neuron_num_)\n vel_2_shape = (self.neuron_num_, self.n_labels_dim_)\n velocity1 = tf.Variable(tf.zeros(vel_1_shape))\n velocity2 = tf.Variable(tf.zeros(vel_2_shape))\n future_1 = tf.Variable(w1)\n future_2 = tf.Variable(w2)\n gama = 0.9\n\n hidden = self._relu(input, future_1)\n y_pred = tf.matmul(hidden, future_2)\n diff = y_pred - label\n loss = tf.reduce_mean(tf.reduce_sum(diff ** 2, axis=1))\n\n grad_1, grad_2 = tf.gradients(loss, [future_1, future_2])\n velocity1 = velocity1.assign(gama * velocity1 + grad_1 * self.learning_rate_)\n velocity2 = velocity2.assign(gama * velocity2 + grad_2 * self.learning_rate_)\n new_future_1 = future_1.assign(w1 - gama * velocity1)\n new_future_2 = future_2.assign(w2 - gama * velocity2)\n new_w1 = w1.assign(w1 - velocity1)\n new_w2 = w2.assign(w2 - velocity2)\n return loss, tf.group(new_future_1, new_future_2, new_w1, new_w2)\n\n def _handcraft_optimizer(self, input, y_pred, y, w1, w2):\n loss = self._objective_loss(y_pred, y)\n regularization = tf.reduce_sum(self.rigid_ * (w1 * w1)) + tf.reduce_sum(self.rigid_ * (w2 * w2))\n loss_aug = tf.add(loss, 0.5 * regularization)\n\n if self.gradient_type_ == 'vanilia':\n return self._vanilia_gradient_descent(loss_aug, w1, w2)\n elif self.gradient_type_ == 'momentum':\n return self._momentum_gradient_descent(loss_aug, w1, w2) \n elif self.gradient_type_ == 'nesterov':\n return self._nesterov_gradient_descent(input, y, w1, w2)\n else:\n raise ValueError('Not support gradient type')\n\n def _svm_loss(self, y_pred, y):\n row_idx = 0\n score = 0\n for row in y:\n true_col_idx = row[0]\n y_pred_row = y_pred[row_idx]\n true_score = y_pred_row[true_col_idx]\n for col in y_pred_row:\n score += np.max(col - true_score + 1, 0)\n\n return score\n\n def _cross_entropy_loss(self, y_pred, y):\n return tf.losses.softmax_cross_entropy(y, y_pred)\n\n def _objective_loss(self, y_pred, y):\n return self._cross_entropy_loss(y_pred, y)\n #return self._svm_loss(y_pred, y)\n\n def _relu(self, input, hidden_weight):\n if self.relu_ is None:\n return tf.maximum(tf.matmul(input, hidden_weight), 0)\n elif self.relu_ == 'leaky':\n x = tf.matmul(input, hidden_weight)\n hidden = tf.maximum(x, tf.scalar_mul(0.01, x))\n return hidden\n else:\n raise ValueError(\"Not supported relu type\")\n\n def _is_convergent(self, loss):\n if loss > self.best_loss_value_ - self.tolerent_:\n self.no_improvement_num_ += 1\n else:\n self.no_improvement_num_ = 0\n\n if loss < self.best_loss_value_:\n self.best_loss_value_ = loss\n \n return self.no_improvement_num_ >= self.max_no_improvement_num_\n\n def _softmax(self, x):\n trans_x = tf.transpose(x)\n ret = tf.exp(trans_x) / tf.reduce_sum(tf.exp(trans_x), axis=0)\n return tf.transpose(ret)\n\n def _batch_normalization(self, input): \n return input\n\n def _optimize(self, samples, labels):\n n_hidden = max(samples.shape[1] / 2, 8)\n n_hidden = int(floor(n_hidden))\n \n self.neuron_num_ = n_hidden\n self.n_features_ = samples.shape[1]\n self.n_labels_dim_ = labels.shape[1]\n w1, w2 = self._init_weights((samples.shape[1], n_hidden), (n_hidden, labels.shape[1]))\n\n x = tf.placeholder(tf.float32, shape=(self.batch_size_, samples.shape[1]), name=\"X\")\n h = tf.Variable(w1)\n y = tf.Variable(w2)\n\n self.hidden_weight_ = h\n self.output_weight_ = y\n\n label = tf.placeholder(tf.float32, shape=(self.batch_size_, labels.shape[1]), name=\"Y\")\n\n x = self._batch_normalization(x)\n hidden = self._relu(x, h)\n predict = tf.matmul(hidden, y)\n y_pred = self._softmax(predict)#tf.nn.softmax(predict)\n \n loss, optimize_action = None, None\n if self.gradient_type_ is not None:\n loss, optimize_action = self._handcraft_optimizer(x, y_pred, label, h, y)\n else:\n loss, optimize_action = self._predifined_optimizer(y_pred, label)\n \n self.sess_ = tf.Session()\n self.sess_.run(tf.global_variables_initializer())\n\n data = np.hstack((samples, labels)).astype(np.float32)\n n_batch = samples.shape[0] / self.batch_size_\n n_batch = int(floor(n_batch))\n loss_value = 0\n for iter in range(self.max_iteration_):\n # batch stochastic gradient descent\n np.random.shuffle(data)\n batch_idx = 0\n batch_loss = 0\n for _ in range(n_batch):\n batch_data = data[self.batch_size_ * batch_idx: self.batch_size_ * (batch_idx + 1)]\n batch_samples = batch_data[:,:samples.shape[1]]\n batch_labels = batch_data[:,samples.shape[1]:]\n\n batch_samples -= np.mean(batch_samples, axis=0)\n #batch_samples /= np.std(batch_samples, axis=0)\n\n values = {\n x: batch_samples,\n label: batch_labels\n }\n batch_loss_value, _ = self.sess_.run([loss, optimize_action], feed_dict=values)\n batch_loss += batch_loss_value\n batch_loss /= n_batch\n loss_value += batch_loss\n if iter > 0 and iter % 50 == 0:\n loss_value /= iter\n print(loss_value)\n if self._is_convergent(loss_value):\n return\n\n def fit(self, samples, labels):\n n_samples = samples.shape[0]\n if n_samples < self.batch_size_:\n raise ValueError('invalid batch size which is bigger than samples size')\n\n self._optimize(samples, labels)\n\n def predict(self, X):\n samples = X - np.mean(X, axis=0)\n # samples /= np.std(samples, axis=0)\n\n input = tf.placeholder(tf.float32, X.shape)\n hidden = self._relu(input, self.hidden_weight_)\n y_pred = tf.matmul(hidden, self.output_weight_)\n\n value = {\n input: samples\n }\n y_pred_value = self.sess_.run(y_pred, feed_dict=value)\n \n return y_pred_value\n\nif __name__ == '__main__':\n data = datasets.load_iris()\n X = data.data.astype(np.float32)\n y = data.target.reshape(X.shape[0], -1)\n print(X.shape[1])\n\n sk_mlp = neural_network.MLPClassifier(int(X.shape[0] / 3), max_iter=10000)\n sk_mlp.fit(X, y)\n sk_y_pred = sk_mlp.predict(X)\n sk_ac = metrics.accuracy_score(y, sk_y_pred)\n print(sk_ac)\n\n encoded_y = preprocessing.OneHotEncoder().fit_transform(y).toarray()\n \n mlp = MLP(1e-2, None, relu=None, batch_size=80, tolerent=1e-6, rigid=1e-4)\n mlp.fit(X, encoded_y)\n\n y_pred = mlp.predict(X)\n y_pred = np.argmax(y_pred, axis = 1)\n print(y_pred)\n print(y.reshape(1, -1))\n ac = metrics.accuracy_score(y, y_pred)\n print(ac)\n " ]
[ [ "tensorflow.zeros", "tensorflow.reduce_sum", "numpy.max", "numpy.mean", "tensorflow.train.AdamOptimizer", "tensorflow.group", "numpy.hstack", "tensorflow.Variable", "tensorflow.gradients", "tensorflow.losses.softmax_cross_entropy", "numpy.argmax", "tensorflow.add", "tensorflow.Session", "tensorflow.matmul", "tensorflow.scalar_mul", "sklearn.datasets.load_iris", "tensorflow.placeholder", "tensorflow.exp", "tensorflow.global_variables_initializer", "tensorflow.losses.mean_squared_error", "tensorflow.transpose", "sklearn.preprocessing.OneHotEncoder", "numpy.random.shuffle", "sklearn.metrics.accuracy_score" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
Luigii1506/machine-learning-udemy-courses
[ "29ffde26ce1a17e37fe13cbea7ce9909ff4ca682" ]
[ "Classification/Naive-bayes/naive_bayes.py" ]
[ "# Classification template\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Social_Network_Ads.csv')\nX = dataset.iloc[:, [2, 3]].values\ny = dataset.iloc[:, 4].values\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n# Fitting classifier to the Training set\nfrom sklearn.naive_bayes import GaussianNB\nclassifier = GaussianNB()\nclassifier.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\n# Visualising the Training set results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_train, y_train\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Naive bayes (Training set)')\nplt.xlabel('Age')\nplt.ylabel('Estimated Salary')\nplt.legend()\nplt.show()\n\n# Visualising the Test set results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_test, y_test\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Naive bayes (Test set)')\nplt.xlabel('Age')\nplt.ylabel('Estimated Salary')\nplt.legend()\nplt.show()" ]
[ [ "matplotlib.pyplot.legend", "sklearn.cross_validation.train_test_split", "pandas.read_csv", "sklearn.naive_bayes.GaussianNB", "matplotlib.pyplot.title", "numpy.unique", "sklearn.metrics.confusion_matrix", "matplotlib.colors.ListedColormap", "matplotlib.pyplot.xlabel", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
ranOutaNames/pandas
[ "fea6799dba6657393ff34deab21aae05538f4985" ]
[ "pandas/core/window/rolling.py" ]
[ "\"\"\"\nProvide a generic structure to support window functions,\nsimilar to how we have a Groupby object.\n\"\"\"\nfrom __future__ import annotations\n\nimport copy\nfrom datetime import timedelta\nfrom functools import partial\nimport inspect\nfrom textwrap import dedent\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n)\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs.tslibs import (\n BaseOffset,\n to_offset,\n)\nimport pandas._libs.window.aggregations as window_aggregations\nfrom pandas._typing import (\n ArrayLike,\n Axis,\n FrameOrSeries,\n FrameOrSeriesUnion,\n)\nfrom pandas.compat._optional import import_optional_dependency\nfrom pandas.compat.numpy import function as nv\nfrom pandas.util._decorators import doc\n\nfrom pandas.core.dtypes.common import (\n ensure_float64,\n is_bool,\n is_integer,\n is_list_like,\n is_scalar,\n needs_i8_conversion,\n)\nfrom pandas.core.dtypes.generic import (\n ABCDataFrame,\n ABCSeries,\n)\nfrom pandas.core.dtypes.missing import notna\n\nfrom pandas.core.algorithms import factorize\nfrom pandas.core.apply import ResamplerWindowApply\nfrom pandas.core.base import (\n DataError,\n SelectionMixin,\n)\nimport pandas.core.common as com\nfrom pandas.core.indexes.api import (\n DatetimeIndex,\n Index,\n MultiIndex,\n PeriodIndex,\n TimedeltaIndex,\n)\nfrom pandas.core.internals import ArrayManager\nfrom pandas.core.reshape.concat import concat\nfrom pandas.core.util.numba_ import (\n NUMBA_FUNC_CACHE,\n maybe_use_numba,\n)\nfrom pandas.core.window.common import (\n flex_binary_moment,\n zsqrt,\n)\nfrom pandas.core.window.doc import (\n _shared_docs,\n args_compat,\n create_section_header,\n kwargs_compat,\n kwargs_scipy,\n numba_notes,\n template_header,\n template_returns,\n template_see_also,\n window_agg_numba_parameters,\n window_apply_parameters,\n)\nfrom pandas.core.window.indexers import (\n BaseIndexer,\n FixedWindowIndexer,\n GroupbyIndexer,\n VariableWindowIndexer,\n)\nfrom pandas.core.window.numba_ import (\n generate_manual_numpy_nan_agg_with_axis,\n generate_numba_apply_func,\n generate_numba_table_func,\n)\n\nif TYPE_CHECKING:\n from pandas import (\n DataFrame,\n Series,\n )\n from pandas.core.internals import Block # noqa:F401\n\n\nclass BaseWindow(SelectionMixin):\n \"\"\"Provides utilities for performing windowing operations.\"\"\"\n\n _attributes: list[str] = []\n exclusions: set[str] = set()\n\n def __init__(\n self,\n obj: FrameOrSeries,\n window=None,\n min_periods: int | None = None,\n center: bool = False,\n win_type: str | None = None,\n axis: Axis = 0,\n on: str | Index | None = None,\n closed: str | None = None,\n method: str = \"single\",\n ):\n self.obj = obj\n self.on = on\n self.closed = closed\n self.window = window\n self.min_periods = min_periods\n self.center = center\n # TODO: Change this back to self.win_type once deprecation is enforced\n self._win_type = win_type\n self.axis = obj._get_axis_number(axis) if axis is not None else None\n self.method = method\n self._win_freq_i8 = None\n if self.on is None:\n if self.axis == 0:\n self._on = self.obj.index\n else:\n # i.e. self.axis == 1\n self._on = self.obj.columns\n elif isinstance(self.on, Index):\n self._on = self.on\n elif isinstance(self.obj, ABCDataFrame) and self.on in self.obj.columns:\n self._on = Index(self.obj[self.on])\n else:\n raise ValueError(\n f\"invalid on specified as {self.on}, \"\n \"must be a column (of DataFrame), an Index or None\"\n )\n self.validate()\n\n @property\n def win_type(self):\n if self._win_freq_i8 is not None:\n warnings.warn(\n \"win_type will no longer return 'freq' in a future version. \"\n \"Check the type of self.window instead.\",\n FutureWarning,\n stacklevel=2,\n )\n return \"freq\"\n return self._win_type\n\n @property\n def is_datetimelike(self):\n warnings.warn(\n \"is_datetimelike is deprecated and will be removed in a future version.\",\n FutureWarning,\n stacklevel=2,\n )\n return self._win_freq_i8 is not None\n\n def validate(self) -> None:\n if self.center is not None and not is_bool(self.center):\n raise ValueError(\"center must be a boolean\")\n if self.min_periods is not None:\n if not is_integer(self.min_periods):\n raise ValueError(\"min_periods must be an integer\")\n elif self.min_periods < 0:\n raise ValueError(\"min_periods must be >= 0\")\n elif is_integer(self.window) and self.min_periods > self.window:\n raise ValueError(\n f\"min_periods {self.min_periods} must be <= window {self.window}\"\n )\n if self.closed is not None and self.closed not in [\n \"right\",\n \"both\",\n \"left\",\n \"neither\",\n ]:\n raise ValueError(\"closed must be 'right', 'left', 'both' or 'neither'\")\n if not isinstance(self.obj, (ABCSeries, ABCDataFrame)):\n raise TypeError(f\"invalid type: {type(self)}\")\n if isinstance(self.window, BaseIndexer):\n # Validate that the passed BaseIndexer subclass has\n # a get_window_bounds with the correct signature.\n get_window_bounds_signature = inspect.signature(\n self.window.get_window_bounds\n ).parameters.keys()\n expected_signature = inspect.signature(\n BaseIndexer().get_window_bounds\n ).parameters.keys()\n if get_window_bounds_signature != expected_signature:\n raise ValueError(\n f\"{type(self.window).__name__} does not implement \"\n f\"the correct signature for get_window_bounds\"\n )\n if self.method not in [\"table\", \"single\"]:\n raise ValueError(\"method must be 'table' or 'single\")\n\n def _create_data(self, obj: FrameOrSeries) -> FrameOrSeries:\n \"\"\"\n Split data into blocks & return conformed data.\n \"\"\"\n # filter out the on from the object\n if self.on is not None and not isinstance(self.on, Index) and obj.ndim == 2:\n obj = obj.reindex(columns=obj.columns.difference([self.on]), copy=False)\n if self.axis == 1:\n # GH: 20649 in case of mixed dtype and axis=1 we have to convert everything\n # to float to calculate the complete row at once. We exclude all non-numeric\n # dtypes.\n obj = obj.select_dtypes(include=[\"integer\", \"float\"], exclude=[\"timedelta\"])\n obj = obj.astype(\"float64\", copy=False)\n obj._mgr = obj._mgr.consolidate()\n return obj\n\n def _gotitem(self, key, ndim, subset=None):\n \"\"\"\n Sub-classes to define. Return a sliced object.\n\n Parameters\n ----------\n key : str / list of selections\n ndim : {1, 2}\n requested ndim of result\n subset : object, default None\n subset to act on\n \"\"\"\n # create a new object to prevent aliasing\n if subset is None:\n subset = self.obj\n # TODO: Remove once win_type deprecation is enforced\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", \"win_type\", FutureWarning)\n self = type(self)(\n subset, **{attr: getattr(self, attr) for attr in self._attributes}\n )\n if subset.ndim == 2:\n if is_scalar(key) and key in subset or is_list_like(key):\n self._selection = key\n return self\n\n def __getattr__(self, attr: str):\n if attr in self._internal_names_set:\n return object.__getattribute__(self, attr)\n if attr in self.obj:\n return self[attr]\n\n raise AttributeError(\n f\"'{type(self).__name__}' object has no attribute '{attr}'\"\n )\n\n def _dir_additions(self):\n return self.obj._dir_additions()\n\n def __repr__(self) -> str:\n \"\"\"\n Provide a nice str repr of our rolling object.\n \"\"\"\n attrs_list = (\n f\"{attr_name}={getattr(self, attr_name)}\"\n for attr_name in self._attributes\n if getattr(self, attr_name, None) is not None and attr_name[0] != \"_\"\n )\n attrs = \",\".join(attrs_list)\n return f\"{type(self).__name__} [{attrs}]\"\n\n def __iter__(self):\n obj = self._create_data(self._selected_obj)\n indexer = self._get_window_indexer()\n\n start, end = indexer.get_window_bounds(\n num_values=len(obj),\n min_periods=self.min_periods,\n center=self.center,\n closed=self.closed,\n )\n # From get_window_bounds, those two should be equal in length of array\n assert len(start) == len(end)\n\n for s, e in zip(start, end):\n result = obj.iloc[slice(s, e)]\n yield result\n\n def _prep_values(self, values: ArrayLike) -> np.ndarray:\n \"\"\"Convert input to numpy arrays for Cython routines\"\"\"\n if needs_i8_conversion(values.dtype):\n raise NotImplementedError(\n f\"ops for {type(self).__name__} for this \"\n f\"dtype {values.dtype} are not implemented\"\n )\n else:\n # GH #12373 : rolling functions error on float32 data\n # make sure the data is coerced to float64\n try:\n values = ensure_float64(values)\n except (ValueError, TypeError) as err:\n raise TypeError(f\"cannot handle this type -> {values.dtype}\") from err\n\n # Convert inf to nan for C funcs\n inf = np.isinf(values)\n if inf.any():\n values = np.where(inf, np.nan, values)\n\n # error: Incompatible return value type (got \"Optional[ndarray]\",\n # expected \"ndarray\")\n return values # type: ignore[return-value]\n\n def _insert_on_column(self, result: DataFrame, obj: DataFrame):\n # if we have an 'on' column we want to put it back into\n # the results in the same location\n from pandas import Series\n\n if self.on is not None and not self._on.equals(obj.index):\n name = self._on.name\n extra_col = Series(self._on, index=self.obj.index, name=name)\n if name in result.columns:\n # TODO: sure we want to overwrite results?\n result[name] = extra_col\n elif name in result.index.names:\n pass\n elif name in self._selected_obj.columns:\n # insert in the same location as we had in _selected_obj\n old_cols = self._selected_obj.columns\n new_cols = result.columns\n old_loc = old_cols.get_loc(name)\n overlap = new_cols.intersection(old_cols[:old_loc])\n new_loc = len(overlap)\n result.insert(new_loc, name, extra_col)\n else:\n # insert at the end\n result[name] = extra_col\n\n @property\n def _index_array(self):\n # TODO: why do we get here with e.g. MultiIndex?\n if needs_i8_conversion(self._on.dtype):\n return self._on.asi8\n return None\n\n def _resolve_output(self, out: DataFrame, obj: DataFrame) -> DataFrame:\n \"\"\"Validate and finalize result.\"\"\"\n if out.shape[1] == 0 and obj.shape[1] > 0:\n raise DataError(\"No numeric types to aggregate\")\n elif out.shape[1] == 0:\n return obj.astype(\"float64\")\n\n self._insert_on_column(out, obj)\n return out\n\n def _get_window_indexer(self) -> BaseIndexer:\n \"\"\"\n Return an indexer class that will compute the window start and end bounds\n \"\"\"\n if isinstance(self.window, BaseIndexer):\n return self.window\n if self._win_freq_i8 is not None:\n return VariableWindowIndexer(\n index_array=self._index_array,\n window_size=self._win_freq_i8,\n center=self.center,\n )\n return FixedWindowIndexer(window_size=self.window)\n\n def _apply_series(\n self, homogeneous_func: Callable[..., ArrayLike], name: str | None = None\n ) -> Series:\n \"\"\"\n Series version of _apply_blockwise\n \"\"\"\n obj = self._create_data(self._selected_obj)\n\n if name == \"count\":\n # GH 12541: Special case for count where we support date-like types\n obj = notna(obj).astype(int)\n try:\n values = self._prep_values(obj._values)\n except (TypeError, NotImplementedError) as err:\n raise DataError(\"No numeric types to aggregate\") from err\n\n result = homogeneous_func(values)\n return obj._constructor(result, index=obj.index, name=obj.name)\n\n def _apply_blockwise(\n self, homogeneous_func: Callable[..., ArrayLike], name: str | None = None\n ) -> FrameOrSeriesUnion:\n \"\"\"\n Apply the given function to the DataFrame broken down into homogeneous\n sub-frames.\n \"\"\"\n if self._selected_obj.ndim == 1:\n return self._apply_series(homogeneous_func, name)\n\n obj = self._create_data(self._selected_obj)\n if name == \"count\":\n # GH 12541: Special case for count where we support date-like types\n obj = notna(obj).astype(int)\n obj._mgr = obj._mgr.consolidate()\n mgr = obj._mgr\n\n def hfunc(bvalues: ArrayLike) -> ArrayLike:\n # TODO(EA2D): getattr unnecessary with 2D EAs\n values = self._prep_values(getattr(bvalues, \"T\", bvalues))\n res_values = homogeneous_func(values)\n return getattr(res_values, \"T\", res_values)\n\n def hfunc2d(values: ArrayLike) -> ArrayLike:\n values = self._prep_values(values)\n return homogeneous_func(values)\n\n if isinstance(mgr, ArrayManager) and self.axis == 1:\n new_mgr = mgr.apply_2d(hfunc2d, ignore_failures=True)\n else:\n new_mgr = mgr.apply(hfunc, ignore_failures=True)\n out = obj._constructor(new_mgr)\n\n return self._resolve_output(out, obj)\n\n def _apply_tablewise(\n self, homogeneous_func: Callable[..., ArrayLike], name: str | None = None\n ) -> FrameOrSeriesUnion:\n \"\"\"\n Apply the given function to the DataFrame across the entire object\n \"\"\"\n if self._selected_obj.ndim == 1:\n raise ValueError(\"method='table' not applicable for Series objects.\")\n obj = self._create_data(self._selected_obj)\n values = self._prep_values(obj.to_numpy())\n values = values.T if self.axis == 1 else values\n result = homogeneous_func(values)\n result = result.T if self.axis == 1 else result\n out = obj._constructor(result, index=obj.index, columns=obj.columns)\n\n return self._resolve_output(out, obj)\n\n def _apply_pairwise(\n self,\n target: FrameOrSeriesUnion,\n other: FrameOrSeriesUnion | None,\n pairwise: bool | None,\n func: Callable[[FrameOrSeriesUnion, FrameOrSeriesUnion], FrameOrSeriesUnion],\n ) -> FrameOrSeriesUnion:\n \"\"\"\n Apply the given pairwise function given 2 pandas objects (DataFrame/Series)\n \"\"\"\n if other is None:\n other = target\n # only default unset\n pairwise = True if pairwise is None else pairwise\n\n return flex_binary_moment(target, other, func, pairwise=bool(pairwise))\n\n def _apply(\n self,\n func: Callable[..., Any],\n name: str | None = None,\n numba_cache_key: tuple[Callable, str] | None = None,\n **kwargs,\n ):\n \"\"\"\n Rolling statistical measure using supplied function.\n\n Designed to be used with passed-in Cython array-based functions.\n\n Parameters\n ----------\n func : callable function to apply\n name : str,\n numba_cache_key : tuple\n caching key to be used to store a compiled numba func\n **kwargs\n additional arguments for rolling function and window function\n\n Returns\n -------\n y : type of input\n \"\"\"\n window_indexer = self._get_window_indexer()\n min_periods = (\n self.min_periods\n if self.min_periods is not None\n else window_indexer.window_size\n )\n\n def homogeneous_func(values: np.ndarray):\n # calculation function\n\n if values.size == 0:\n return values.copy()\n\n def calc(x):\n start, end = window_indexer.get_window_bounds(\n num_values=len(x),\n min_periods=min_periods,\n center=self.center,\n closed=self.closed,\n )\n return func(x, start, end, min_periods)\n\n with np.errstate(all=\"ignore\"):\n if values.ndim > 1 and self.method == \"single\":\n result = np.apply_along_axis(calc, self.axis, values)\n else:\n result = calc(values)\n\n if numba_cache_key is not None:\n NUMBA_FUNC_CACHE[numba_cache_key] = func\n\n return result\n\n if self.method == \"single\":\n return self._apply_blockwise(homogeneous_func, name)\n else:\n return self._apply_tablewise(homogeneous_func, name)\n\n def aggregate(self, func, *args, **kwargs):\n result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg()\n if result is None:\n return self.apply(func, raw=False, args=args, kwargs=kwargs)\n return result\n\n agg = aggregate\n\n\nclass BaseWindowGroupby(BaseWindow):\n \"\"\"\n Provide the groupby windowing facilities.\n \"\"\"\n\n _attributes = [\"_grouper\"]\n\n def __init__(\n self,\n obj: FrameOrSeries,\n *args,\n _grouper=None,\n _as_index=True,\n **kwargs,\n ):\n if _grouper is None:\n raise ValueError(\"Must pass a Grouper object.\")\n self._grouper = _grouper\n self._as_index = _as_index\n # GH 32262: It's convention to keep the grouping column in\n # groupby.<agg_func>, but unexpected to users in\n # groupby.rolling.<agg_func>\n obj = obj.drop(columns=self._grouper.names, errors=\"ignore\")\n super().__init__(obj, *args, **kwargs)\n\n def _apply(\n self,\n func: Callable[..., Any],\n name: str | None = None,\n numba_cache_key: tuple[Callable, str] | None = None,\n **kwargs,\n ) -> FrameOrSeries:\n result = super()._apply(\n func,\n name,\n numba_cache_key,\n **kwargs,\n )\n # Reconstruct the resulting MultiIndex\n # 1st set of levels = group by labels\n # 2nd set of levels = original DataFrame/Series index\n grouped_object_index = self.obj.index\n grouped_index_name = [*grouped_object_index.names]\n groupby_keys = copy.copy(self._grouper.names)\n result_index_names = groupby_keys + grouped_index_name\n\n drop_columns = [\n key\n for key in self._grouper.names\n if key not in self.obj.index.names or key is None\n ]\n\n if len(drop_columns) != len(groupby_keys):\n # Our result will have still kept the column in the result\n result = result.drop(columns=drop_columns, errors=\"ignore\")\n\n codes = self._grouper.codes\n levels = copy.copy(self._grouper.levels)\n\n group_indices = self._grouper.indices.values()\n if group_indices:\n indexer = np.concatenate(list(group_indices))\n else:\n indexer = np.array([], dtype=np.intp)\n codes = [c.take(indexer) for c in codes]\n\n # if the index of the original dataframe needs to be preserved, append\n # this index (but reordered) to the codes/levels from the groupby\n if grouped_object_index is not None:\n idx = grouped_object_index.take(indexer)\n if not isinstance(idx, MultiIndex):\n idx = MultiIndex.from_arrays([idx])\n codes.extend(list(idx.codes))\n levels.extend(list(idx.levels))\n\n result_index = MultiIndex(\n levels, codes, names=result_index_names, verify_integrity=False\n )\n\n result.index = result_index\n if not self._as_index:\n result = result.reset_index(level=list(range(len(groupby_keys))))\n return result\n\n def _apply_pairwise(\n self,\n target: FrameOrSeriesUnion,\n other: FrameOrSeriesUnion | None,\n pairwise: bool | None,\n func: Callable[[FrameOrSeriesUnion, FrameOrSeriesUnion], FrameOrSeriesUnion],\n ) -> FrameOrSeriesUnion:\n \"\"\"\n Apply the given pairwise function given 2 pandas objects (DataFrame/Series)\n \"\"\"\n # Manually drop the grouping column first\n target = target.drop(columns=self._grouper.names, errors=\"ignore\")\n result = super()._apply_pairwise(target, other, pairwise, func)\n # 1) Determine the levels + codes of the groupby levels\n if other is not None:\n # When we have other, we must reindex (expand) the result\n # from flex_binary_moment to a \"transform\"-like result\n # per groupby combination\n old_result_len = len(result)\n result = concat(\n [\n result.take(gb_indices).reindex(result.index)\n for gb_indices in self._grouper.indices.values()\n ]\n )\n\n gb_pairs = (\n com.maybe_make_list(pair) for pair in self._grouper.indices.keys()\n )\n groupby_codes = []\n groupby_levels = []\n # e.g. [[1, 2], [4, 5]] as [[1, 4], [2, 5]]\n for gb_level_pair in map(list, zip(*gb_pairs)):\n labels = np.repeat(np.array(gb_level_pair), old_result_len)\n codes, levels = factorize(labels)\n groupby_codes.append(codes)\n groupby_levels.append(levels)\n\n else:\n # When we evaluate the pairwise=True result, repeat the groupby\n # labels by the number of columns in the original object\n groupby_codes = self._grouper.codes\n groupby_levels = self._grouper.levels\n\n group_indices = self._grouper.indices.values()\n if group_indices:\n indexer = np.concatenate(list(group_indices))\n else:\n indexer = np.array([], dtype=np.intp)\n\n if target.ndim == 1:\n repeat_by = 1\n else:\n repeat_by = len(target.columns)\n groupby_codes = [\n np.repeat(c.take(indexer), repeat_by) for c in groupby_codes\n ]\n # 2) Determine the levels + codes of the result from super()._apply_pairwise\n if isinstance(result.index, MultiIndex):\n result_codes = list(result.index.codes)\n result_levels = list(result.index.levels)\n result_names = list(result.index.names)\n else:\n idx_codes, idx_levels = factorize(result.index)\n result_codes = [idx_codes]\n result_levels = [idx_levels]\n result_names = [result.index.name]\n\n # 3) Create the resulting index by combining 1) + 2)\n result_codes = groupby_codes + result_codes\n result_levels = groupby_levels + result_levels\n result_names = self._grouper.names + result_names\n\n result_index = MultiIndex(\n result_levels, result_codes, names=result_names, verify_integrity=False\n )\n result.index = result_index\n return result\n\n def _create_data(self, obj: FrameOrSeries) -> FrameOrSeries:\n \"\"\"\n Split data into blocks & return conformed data.\n \"\"\"\n # Ensure the object we're rolling over is monotonically sorted relative\n # to the groups\n # GH 36197\n if not obj.empty:\n groupby_order = np.concatenate(list(self._grouper.indices.values())).astype(\n np.int64\n )\n obj = obj.take(groupby_order)\n return super()._create_data(obj)\n\n def _gotitem(self, key, ndim, subset=None):\n # we are setting the index on the actual object\n # here so our index is carried through to the selected obj\n # when we do the splitting for the groupby\n if self.on is not None:\n self.obj = self.obj.set_index(self._on)\n return super()._gotitem(key, ndim, subset=subset)\n\n def _validate_monotonic(self):\n \"\"\"\n Validate that \"on\" is monotonic; already validated at a higher level.\n \"\"\"\n pass\n\n\nclass Window(BaseWindow):\n \"\"\"\n Provide rolling window calculations.\n\n Parameters\n ----------\n window : int, offset, or BaseIndexer subclass\n Size of the moving window. This is the number of observations used for\n calculating the statistic. Each window will be a fixed size.\n\n If its an offset then this will be the time period of each window. Each\n window will be a variable sized based on the observations included in\n the time-period. This is only valid for datetimelike indexes.\n\n If a BaseIndexer subclass is passed, calculates the window boundaries\n based on the defined ``get_window_bounds`` method. Additional rolling\n keyword arguments, namely `min_periods`, `center`, and\n `closed` will be passed to `get_window_bounds`.\n min_periods : int, default None\n Minimum number of observations in window required to have a value\n (otherwise result is NA). For a window that is specified by an offset,\n `min_periods` will default to 1. Otherwise, `min_periods` will default\n to the size of the window.\n center : bool, default False\n Set the labels at the center of the window.\n win_type : str, default None\n Provide a window type. If ``None``, all points are evenly weighted.\n See the notes below for further information.\n on : str, optional\n For a DataFrame, a datetime-like column or Index level on which\n to calculate the rolling window, rather than the DataFrame's index.\n Provided integer column is ignored and excluded from result since\n an integer index is not used to calculate the rolling window.\n axis : int or str, default 0\n closed : str, default None\n Make the interval closed on the 'right', 'left', 'both' or\n 'neither' endpoints. Defaults to 'right'.\n\n .. versionchanged:: 1.2.0\n\n The closed parameter with fixed windows is now supported.\n method : str {'single', 'table'}, default 'single'\n Execute the rolling operation per single column or row (``'single'``)\n or over the entire object (``'table'``).\n\n This argument is only implemented when specifying ``engine='numba'``\n in the method call.\n\n .. versionadded:: 1.3.0\n\n Returns\n -------\n a Window or Rolling sub-classed for the particular operation\n\n See Also\n --------\n expanding : Provides expanding transformations.\n ewm : Provides exponential weighted functions.\n\n Notes\n -----\n By default, the result is set to the right edge of the window. This can be\n changed to the center of the window by setting ``center=True``.\n\n To learn more about the offsets & frequency strings, please see `this link\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n\n If ``win_type=None``, all points are evenly weighted; otherwise, ``win_type``\n can accept a string of any `scipy.signal window function\n <https://docs.scipy.org/doc/scipy/reference/signal.windows.html#module-scipy.signal.windows>`__.\n\n Certain Scipy window types require additional parameters to be passed\n in the aggregation function. The additional parameters must match\n the keywords specified in the Scipy window type method signature.\n Please see the third example below on how to add the additional parameters.\n\n Examples\n --------\n >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})\n >>> df\n B\n 0 0.0\n 1 1.0\n 2 2.0\n 3 NaN\n 4 4.0\n\n Rolling sum with a window length of 2, using the 'triang'\n window type.\n\n >>> df.rolling(2, win_type='triang').sum()\n B\n 0 NaN\n 1 0.5\n 2 1.5\n 3 NaN\n 4 NaN\n\n Rolling sum with a window length of 2, using the 'gaussian'\n window type (note how we need to specify std).\n\n >>> df.rolling(2, win_type='gaussian').sum(std=3)\n B\n 0 NaN\n 1 0.986207\n 2 2.958621\n 3 NaN\n 4 NaN\n\n Rolling sum with a window length of 2, min_periods defaults\n to the window length.\n\n >>> df.rolling(2).sum()\n B\n 0 NaN\n 1 1.0\n 2 3.0\n 3 NaN\n 4 NaN\n\n Same as above, but explicitly set the min_periods\n\n >>> df.rolling(2, min_periods=1).sum()\n B\n 0 0.0\n 1 1.0\n 2 3.0\n 3 2.0\n 4 4.0\n\n Same as above, but with forward-looking windows\n\n >>> indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2)\n >>> df.rolling(window=indexer, min_periods=1).sum()\n B\n 0 1.0\n 1 3.0\n 2 2.0\n 3 4.0\n 4 4.0\n\n A ragged (meaning not-a-regular frequency), time-indexed DataFrame\n\n >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]},\n ... index = [pd.Timestamp('20130101 09:00:00'),\n ... pd.Timestamp('20130101 09:00:02'),\n ... pd.Timestamp('20130101 09:00:03'),\n ... pd.Timestamp('20130101 09:00:05'),\n ... pd.Timestamp('20130101 09:00:06')])\n\n >>> df\n B\n 2013-01-01 09:00:00 0.0\n 2013-01-01 09:00:02 1.0\n 2013-01-01 09:00:03 2.0\n 2013-01-01 09:00:05 NaN\n 2013-01-01 09:00:06 4.0\n\n Contrasting to an integer rolling window, this will roll a variable\n length window corresponding to the time period.\n The default for min_periods is 1.\n\n >>> df.rolling('2s').sum()\n B\n 2013-01-01 09:00:00 0.0\n 2013-01-01 09:00:02 1.0\n 2013-01-01 09:00:03 3.0\n 2013-01-01 09:00:05 NaN\n 2013-01-01 09:00:06 4.0\n \"\"\"\n\n _attributes = [\n \"window\",\n \"min_periods\",\n \"center\",\n \"win_type\",\n \"axis\",\n \"on\",\n \"closed\",\n \"method\",\n ]\n\n def validate(self):\n super().validate()\n\n if not isinstance(self.win_type, str):\n raise ValueError(f\"Invalid win_type {self.win_type}\")\n signal = import_optional_dependency(\n \"scipy.signal\", extra=\"Scipy is required to generate window weight.\"\n )\n self._scipy_weight_generator = getattr(signal, self.win_type, None)\n if self._scipy_weight_generator is None:\n raise ValueError(f\"Invalid win_type {self.win_type}\")\n\n if isinstance(self.window, BaseIndexer):\n raise NotImplementedError(\n \"BaseIndexer subclasses not implemented with win_types.\"\n )\n elif not is_integer(self.window) or self.window < 0:\n raise ValueError(\"window must be an integer 0 or greater\")\n\n if self.method != \"single\":\n raise NotImplementedError(\"'single' is the only supported method type.\")\n\n def _center_window(self, result: np.ndarray, offset: int) -> np.ndarray:\n \"\"\"\n Center the result in the window for weighted rolling aggregations.\n \"\"\"\n if self.axis > result.ndim - 1:\n raise ValueError(\"Requested axis is larger then no. of argument dimensions\")\n\n if offset > 0:\n lead_indexer = [slice(None)] * result.ndim\n lead_indexer[self.axis] = slice(offset, None)\n result = np.copy(result[tuple(lead_indexer)])\n return result\n\n def _apply(\n self,\n func: Callable[[np.ndarray, int, int], np.ndarray],\n name: str | None = None,\n numba_cache_key: tuple[Callable, str] | None = None,\n **kwargs,\n ):\n \"\"\"\n Rolling with weights statistical measure using supplied function.\n\n Designed to be used with passed-in Cython array-based functions.\n\n Parameters\n ----------\n func : callable function to apply\n name : str,\n use_numba_cache : tuple\n unused\n **kwargs\n additional arguments for scipy windows if necessary\n\n Returns\n -------\n y : type of input\n \"\"\"\n window = self._scipy_weight_generator(self.window, **kwargs)\n offset = (len(window) - 1) // 2 if self.center else 0\n\n def homogeneous_func(values: np.ndarray):\n # calculation function\n\n if values.size == 0:\n return values.copy()\n\n def calc(x):\n additional_nans = np.array([np.nan] * offset)\n x = np.concatenate((x, additional_nans))\n return func(x, window, self.min_periods or len(window))\n\n with np.errstate(all=\"ignore\"):\n if values.ndim > 1:\n result = np.apply_along_axis(calc, self.axis, values)\n else:\n # Our weighted aggregations return memoryviews\n result = np.asarray(calc(values))\n\n if self.center:\n result = self._center_window(result, offset)\n\n return result\n\n return self._apply_blockwise(homogeneous_func, name)\n\n @doc(\n _shared_docs[\"aggregate\"],\n see_also=dedent(\n \"\"\"\n See Also\n --------\n pandas.DataFrame.aggregate : Similar DataFrame method.\n pandas.Series.aggregate : Similar Series method.\n \"\"\"\n ),\n examples=dedent(\n \"\"\"\n Examples\n --------\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6], \"C\": [7, 8, 9]})\n >>> df\n A B C\n 0 1 4 7\n 1 2 5 8\n 2 3 6 9\n\n >>> df.rolling(2, win_type=\"boxcar\").agg(\"mean\")\n A B C\n 0 NaN NaN NaN\n 1 1.5 4.5 7.5\n 2 2.5 5.5 8.5\n \"\"\"\n ),\n klass=\"Series/DataFrame\",\n axis=\"\",\n )\n def aggregate(self, func, *args, **kwargs):\n result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg()\n if result is None:\n\n # these must apply directly\n result = func(self)\n\n return result\n\n agg = aggregate\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n kwargs_scipy,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"rolling\",\n aggregation_description=\"weighted window sum\",\n agg_method=\"sum\",\n )\n def sum(self, *args, **kwargs):\n nv.validate_window_func(\"sum\", args, kwargs)\n window_func = window_aggregations.roll_weighted_sum\n # error: Argument 1 to \"_apply\" of \"Window\" has incompatible type\n # \"Callable[[ndarray, ndarray, int], ndarray]\"; expected\n # \"Callable[[ndarray, int, int], ndarray]\"\n return self._apply(window_func, name=\"sum\", **kwargs) # type: ignore[arg-type]\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n kwargs_scipy,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"rolling\",\n aggregation_description=\"weighted window mean\",\n agg_method=\"mean\",\n )\n def mean(self, *args, **kwargs):\n nv.validate_window_func(\"mean\", args, kwargs)\n window_func = window_aggregations.roll_weighted_mean\n # error: Argument 1 to \"_apply\" of \"Window\" has incompatible type\n # \"Callable[[ndarray, ndarray, int], ndarray]\"; expected\n # \"Callable[[ndarray, int, int], ndarray]\"\n return self._apply(window_func, name=\"mean\", **kwargs) # type: ignore[arg-type]\n\n @doc(\n template_header,\n \".. versionadded:: 1.0.0 \\n\\n\",\n create_section_header(\"Parameters\"),\n kwargs_scipy,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"rolling\",\n aggregation_description=\"weighted window variance\",\n agg_method=\"var\",\n )\n def var(self, ddof: int = 1, *args, **kwargs):\n nv.validate_window_func(\"var\", args, kwargs)\n window_func = partial(window_aggregations.roll_weighted_var, ddof=ddof)\n kwargs.pop(\"name\", None)\n return self._apply(window_func, name=\"var\", **kwargs)\n\n @doc(\n template_header,\n \".. versionadded:: 1.0.0 \\n\\n\",\n create_section_header(\"Parameters\"),\n kwargs_scipy,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"rolling\",\n aggregation_description=\"weighted window standard deviation\",\n agg_method=\"std\",\n )\n def std(self, ddof: int = 1, *args, **kwargs):\n nv.validate_window_func(\"std\", args, kwargs)\n return zsqrt(self.var(ddof=ddof, name=\"std\", **kwargs))\n\n\nclass RollingAndExpandingMixin(BaseWindow):\n def count(self):\n window_func = window_aggregations.roll_sum\n return self._apply(window_func, name=\"count\")\n\n def apply(\n self,\n func: Callable[..., Any],\n raw: bool = False,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n args: tuple[Any, ...] | None = None,\n kwargs: dict[str, Any] | None = None,\n ):\n if args is None:\n args = ()\n if kwargs is None:\n kwargs = {}\n\n if not is_bool(raw):\n raise ValueError(\"raw parameter must be `True` or `False`\")\n\n numba_cache_key = None\n if maybe_use_numba(engine):\n if raw is False:\n raise ValueError(\"raw must be `True` when using the numba engine\")\n caller_name = type(self).__name__\n if self.method == \"single\":\n apply_func = generate_numba_apply_func(\n args, kwargs, func, engine_kwargs, caller_name\n )\n numba_cache_key = (func, f\"{caller_name}_apply_single\")\n else:\n apply_func = generate_numba_table_func(\n args, kwargs, func, engine_kwargs, f\"{caller_name}_apply\"\n )\n numba_cache_key = (func, f\"{caller_name}_apply_table\")\n elif engine in (\"cython\", None):\n if engine_kwargs is not None:\n raise ValueError(\"cython engine does not accept engine_kwargs\")\n apply_func = self._generate_cython_apply_func(args, kwargs, raw, func)\n else:\n raise ValueError(\"engine must be either 'numba' or 'cython'\")\n\n return self._apply(\n apply_func,\n numba_cache_key=numba_cache_key,\n )\n\n def _generate_cython_apply_func(\n self,\n args: tuple[Any, ...],\n kwargs: dict[str, Any],\n raw: bool,\n function: Callable[..., Any],\n ) -> Callable[[np.ndarray, np.ndarray, np.ndarray, int], np.ndarray]:\n from pandas import Series\n\n window_func = partial(\n window_aggregations.roll_apply,\n args=args,\n kwargs=kwargs,\n raw=raw,\n function=function,\n )\n\n def apply_func(values, begin, end, min_periods, raw=raw):\n if not raw:\n values = Series(values, index=self.obj.index)\n return window_func(values, begin, end, min_periods)\n\n return apply_func\n\n def sum(\n self,\n *args,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n **kwargs,\n ):\n nv.validate_window_func(\"sum\", args, kwargs)\n if maybe_use_numba(engine):\n if self.method == \"table\":\n func = generate_manual_numpy_nan_agg_with_axis(np.nansum)\n else:\n func = np.nansum\n\n return self.apply(\n func,\n raw=True,\n engine=engine,\n engine_kwargs=engine_kwargs,\n )\n window_func = window_aggregations.roll_sum\n return self._apply(window_func, name=\"sum\", **kwargs)\n\n def max(\n self,\n *args,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n **kwargs,\n ):\n nv.validate_window_func(\"max\", args, kwargs)\n if maybe_use_numba(engine):\n if self.method == \"table\":\n func = generate_manual_numpy_nan_agg_with_axis(np.nanmax)\n else:\n func = np.nanmax\n\n return self.apply(\n func,\n raw=True,\n engine=engine,\n engine_kwargs=engine_kwargs,\n )\n window_func = window_aggregations.roll_max\n return self._apply(window_func, name=\"max\", **kwargs)\n\n def min(\n self,\n *args,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n **kwargs,\n ):\n nv.validate_window_func(\"min\", args, kwargs)\n if maybe_use_numba(engine):\n if self.method == \"table\":\n func = generate_manual_numpy_nan_agg_with_axis(np.nanmin)\n else:\n func = np.nanmin\n\n return self.apply(\n func,\n raw=True,\n engine=engine,\n engine_kwargs=engine_kwargs,\n )\n window_func = window_aggregations.roll_min\n return self._apply(window_func, name=\"min\", **kwargs)\n\n def mean(\n self,\n *args,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n **kwargs,\n ):\n nv.validate_window_func(\"mean\", args, kwargs)\n if maybe_use_numba(engine):\n if self.method == \"table\":\n func = generate_manual_numpy_nan_agg_with_axis(np.nanmean)\n else:\n func = np.nanmean\n\n return self.apply(\n func,\n raw=True,\n engine=engine,\n engine_kwargs=engine_kwargs,\n )\n window_func = window_aggregations.roll_mean\n return self._apply(window_func, name=\"mean\", **kwargs)\n\n def median(\n self,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n **kwargs,\n ):\n if maybe_use_numba(engine):\n if self.method == \"table\":\n func = generate_manual_numpy_nan_agg_with_axis(np.nanmedian)\n else:\n func = np.nanmedian\n\n return self.apply(\n func,\n raw=True,\n engine=engine,\n engine_kwargs=engine_kwargs,\n )\n window_func = window_aggregations.roll_median_c\n return self._apply(window_func, name=\"median\", **kwargs)\n\n def std(self, ddof: int = 1, *args, **kwargs):\n nv.validate_window_func(\"std\", args, kwargs)\n window_func = window_aggregations.roll_var\n\n def zsqrt_func(values, begin, end, min_periods):\n return zsqrt(window_func(values, begin, end, min_periods, ddof=ddof))\n\n return self._apply(\n zsqrt_func,\n name=\"std\",\n **kwargs,\n )\n\n def var(self, ddof: int = 1, *args, **kwargs):\n nv.validate_window_func(\"var\", args, kwargs)\n window_func = partial(window_aggregations.roll_var, ddof=ddof)\n return self._apply(\n window_func,\n name=\"var\",\n **kwargs,\n )\n\n def skew(self, **kwargs):\n window_func = window_aggregations.roll_skew\n return self._apply(\n window_func,\n name=\"skew\",\n **kwargs,\n )\n\n def sem(self, ddof: int = 1, *args, **kwargs):\n return self.std(*args, **kwargs) / (self.count() - ddof).pow(0.5)\n\n def kurt(self, **kwargs):\n window_func = window_aggregations.roll_kurt\n return self._apply(\n window_func,\n name=\"kurt\",\n **kwargs,\n )\n\n def quantile(self, quantile: float, interpolation: str = \"linear\", **kwargs):\n if quantile == 1.0:\n window_func = window_aggregations.roll_max\n elif quantile == 0.0:\n window_func = window_aggregations.roll_min\n else:\n window_func = partial(\n window_aggregations.roll_quantile,\n quantile=quantile,\n interpolation=interpolation,\n )\n\n return self._apply(window_func, name=\"quantile\", **kwargs)\n\n def cov(\n self,\n other: FrameOrSeriesUnion | None = None,\n pairwise: bool | None = None,\n ddof: int = 1,\n **kwargs,\n ):\n from pandas import Series\n\n def cov_func(x, y):\n x_array = self._prep_values(x)\n y_array = self._prep_values(y)\n window_indexer = self._get_window_indexer()\n min_periods = (\n self.min_periods\n if self.min_periods is not None\n else window_indexer.window_size\n )\n start, end = window_indexer.get_window_bounds(\n num_values=len(x_array),\n min_periods=min_periods,\n center=self.center,\n closed=self.closed,\n )\n with np.errstate(all=\"ignore\"):\n mean_x_y = window_aggregations.roll_mean(\n x_array * y_array, start, end, min_periods\n )\n mean_x = window_aggregations.roll_mean(x_array, start, end, min_periods)\n mean_y = window_aggregations.roll_mean(y_array, start, end, min_periods)\n count_x_y = window_aggregations.roll_sum(\n notna(x_array + y_array).astype(np.float64), start, end, 0\n )\n result = (mean_x_y - mean_x * mean_y) * (count_x_y / (count_x_y - ddof))\n return Series(result, index=x.index, name=x.name)\n\n return self._apply_pairwise(self._selected_obj, other, pairwise, cov_func)\n\n def corr(\n self,\n other: FrameOrSeriesUnion | None = None,\n pairwise: bool | None = None,\n ddof: int = 1,\n **kwargs,\n ):\n\n from pandas import Series\n\n def corr_func(x, y):\n x_array = self._prep_values(x)\n y_array = self._prep_values(y)\n window_indexer = self._get_window_indexer()\n min_periods = (\n self.min_periods\n if self.min_periods is not None\n else window_indexer.window_size\n )\n start, end = window_indexer.get_window_bounds(\n num_values=len(x_array),\n min_periods=min_periods,\n center=self.center,\n closed=self.closed,\n )\n with np.errstate(all=\"ignore\"):\n mean_x_y = window_aggregations.roll_mean(\n x_array * y_array, start, end, min_periods\n )\n mean_x = window_aggregations.roll_mean(x_array, start, end, min_periods)\n mean_y = window_aggregations.roll_mean(y_array, start, end, min_periods)\n count_x_y = window_aggregations.roll_sum(\n notna(x_array + y_array).astype(np.float64), start, end, 0\n )\n x_var = window_aggregations.roll_var(\n x_array, start, end, min_periods, ddof\n )\n y_var = window_aggregations.roll_var(\n y_array, start, end, min_periods, ddof\n )\n numerator = (mean_x_y - mean_x * mean_y) * (\n count_x_y / (count_x_y - ddof)\n )\n denominator = (x_var * y_var) ** 0.5\n result = numerator / denominator\n return Series(result, index=x.index, name=x.name)\n\n return self._apply_pairwise(self._selected_obj, other, pairwise, corr_func)\n\n\nclass Rolling(RollingAndExpandingMixin):\n\n _attributes = [\n \"window\",\n \"min_periods\",\n \"center\",\n \"win_type\",\n \"axis\",\n \"on\",\n \"closed\",\n \"method\",\n ]\n\n def validate(self):\n super().validate()\n\n # we allow rolling on a datetimelike index\n if (\n self.obj.empty\n or isinstance(self._on, (DatetimeIndex, TimedeltaIndex, PeriodIndex))\n ) and isinstance(self.window, (str, BaseOffset, timedelta)):\n\n self._validate_monotonic()\n\n # this will raise ValueError on non-fixed freqs\n try:\n freq = to_offset(self.window)\n except (TypeError, ValueError) as err:\n raise ValueError(\n f\"passed window {self.window} is not \"\n \"compatible with a datetimelike index\"\n ) from err\n if isinstance(self._on, PeriodIndex):\n self._win_freq_i8 = freq.nanos / (self._on.freq.nanos / self._on.freq.n)\n else:\n self._win_freq_i8 = freq.nanos\n\n # min_periods must be an integer\n if self.min_periods is None:\n self.min_periods = 1\n\n elif isinstance(self.window, BaseIndexer):\n # Passed BaseIndexer subclass should handle all other rolling kwargs\n return\n elif not is_integer(self.window) or self.window < 0:\n raise ValueError(\"window must be an integer 0 or greater\")\n\n def _validate_monotonic(self):\n \"\"\"\n Validate monotonic (increasing or decreasing).\n \"\"\"\n if not (self._on.is_monotonic_increasing or self._on.is_monotonic_decreasing):\n self._raise_monotonic_error()\n\n def _raise_monotonic_error(self):\n formatted = self.on\n if self.on is None:\n formatted = \"index\"\n raise ValueError(f\"{formatted} must be monotonic\")\n\n @doc(\n _shared_docs[\"aggregate\"],\n see_also=dedent(\n \"\"\"\n See Also\n --------\n pandas.Series.rolling : Calling object with Series data.\n pandas.DataFrame.rolling : Calling object with DataFrame data.\n \"\"\"\n ),\n examples=dedent(\n \"\"\"\n Examples\n --------\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6], \"C\": [7, 8, 9]})\n >>> df\n A B C\n 0 1 4 7\n 1 2 5 8\n 2 3 6 9\n\n >>> df.rolling(2).sum()\n A B C\n 0 NaN NaN NaN\n 1 3.0 9.0 15.0\n 2 5.0 11.0 17.0\n\n >>> df.rolling(2).agg({\"A\": \"sum\", \"B\": \"min\"})\n A B\n 0 NaN NaN\n 1 3.0 4.0\n 2 5.0 5.0\n \"\"\"\n ),\n klass=\"Series/Dataframe\",\n axis=\"\",\n )\n def aggregate(self, func, *args, **kwargs):\n return super().aggregate(func, *args, **kwargs)\n\n agg = aggregate\n\n @doc(\n template_header,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also,\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n >>> s = pd.Series([2, 3, np.nan, 10])\n >>> s.rolling(2).count()\n 0 1.0\n 1 2.0\n 2 1.0\n 3 1.0\n dtype: float64\n >>> s.rolling(3).count()\n 0 1.0\n 1 2.0\n 2 2.0\n 3 2.0\n dtype: float64\n >>> s.rolling(4).count()\n 0 1.0\n 1 2.0\n 2 2.0\n 3 3.0\n dtype: float64\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"count of non NaN observations\",\n agg_method=\"count\",\n )\n def count(self):\n if self.min_periods is None:\n warnings.warn(\n (\n \"min_periods=None will default to the size of window \"\n \"consistent with other methods in a future version. \"\n \"Specify min_periods=0 instead.\"\n ),\n FutureWarning,\n )\n self.min_periods = 0\n result = super().count()\n self.min_periods = None\n else:\n result = super().count()\n return result\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n window_apply_parameters,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"rolling\",\n aggregation_description=\"custom aggregation function\",\n agg_method=\"apply\",\n )\n def apply(\n self,\n func: Callable[..., Any],\n raw: bool = False,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n args: tuple[Any, ...] | None = None,\n kwargs: dict[str, Any] | None = None,\n ):\n return super().apply(\n func,\n raw=raw,\n engine=engine,\n engine_kwargs=engine_kwargs,\n args=args,\n kwargs=kwargs,\n )\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n args_compat,\n window_agg_numba_parameters,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also,\n create_section_header(\"Notes\"),\n numba_notes,\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n >>> s = pd.Series([1, 2, 3, 4, 5])\n >>> s\n 0 1\n 1 2\n 2 3\n 3 4\n 4 5\n dtype: int64\n\n >>> s.rolling(3).sum()\n 0 NaN\n 1 NaN\n 2 6.0\n 3 9.0\n 4 12.0\n dtype: float64\n\n >>> s.rolling(3, center=True).sum()\n 0 NaN\n 1 6.0\n 2 9.0\n 3 12.0\n 4 NaN\n dtype: float64\n\n For DataFrame, each sum is computed column-wise.\n\n >>> df = pd.DataFrame({{\"A\": s, \"B\": s ** 2}})\n >>> df\n A B\n 0 1 1\n 1 2 4\n 2 3 9\n 3 4 16\n 4 5 25\n\n >>> df.rolling(3).sum()\n A B\n 0 NaN NaN\n 1 NaN NaN\n 2 6.0 14.0\n 3 9.0 29.0\n 4 12.0 50.0\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"sum\",\n agg_method=\"sum\",\n )\n def sum(\n self,\n *args,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n **kwargs,\n ):\n nv.validate_rolling_func(\"sum\", args, kwargs)\n return super().sum(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n args_compat,\n window_agg_numba_parameters,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also,\n create_section_header(\"Notes\"),\n numba_notes[:-1],\n window_method=\"rolling\",\n aggregation_description=\"maximum\",\n agg_method=\"max\",\n )\n def max(\n self,\n *args,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n **kwargs,\n ):\n nv.validate_rolling_func(\"max\", args, kwargs)\n return super().max(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n args_compat,\n window_agg_numba_parameters,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also,\n create_section_header(\"Notes\"),\n numba_notes,\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n Performing a rolling minimum with a window size of 3.\n\n >>> s = pd.Series([4, 3, 5, 2, 6])\n >>> s.rolling(3).min()\n 0 NaN\n 1 NaN\n 2 3.0\n 3 2.0\n 4 2.0\n dtype: float64\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"minimum\",\n agg_method=\"min\",\n )\n def min(\n self,\n *args,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n **kwargs,\n ):\n nv.validate_rolling_func(\"min\", args, kwargs)\n return super().min(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n args_compat,\n window_agg_numba_parameters,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also,\n create_section_header(\"Notes\"),\n numba_notes,\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n The below examples will show rolling mean calculations with window sizes of\n two and three, respectively.\n\n >>> s = pd.Series([1, 2, 3, 4])\n >>> s.rolling(2).mean()\n 0 NaN\n 1 1.5\n 2 2.5\n 3 3.5\n dtype: float64\n\n >>> s.rolling(3).mean()\n 0 NaN\n 1 NaN\n 2 2.0\n 3 3.0\n dtype: float64\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"mean\",\n agg_method=\"mean\",\n )\n def mean(\n self,\n *args,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n **kwargs,\n ):\n nv.validate_rolling_func(\"mean\", args, kwargs)\n return super().mean(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n window_agg_numba_parameters,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also,\n create_section_header(\"Notes\"),\n numba_notes,\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n Compute the rolling median of a series with a window size of 3.\n\n >>> s = pd.Series([0, 1, 2, 3, 4])\n >>> s.rolling(3).median()\n 0 NaN\n 1 NaN\n 2 1.0\n 3 2.0\n 4 3.0\n dtype: float64\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"median\",\n agg_method=\"median\",\n )\n def median(\n self,\n engine: str | None = None,\n engine_kwargs: dict[str, bool] | None = None,\n **kwargs,\n ):\n return super().median(engine=engine, engine_kwargs=engine_kwargs, **kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n dedent(\n \"\"\"\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations\n is ``N - ddof``, where ``N`` represents the number of elements.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n args_compat,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n \"numpy.std : Equivalent method for NumPy array.\\n\",\n template_see_also,\n create_section_header(\"Notes\"),\n dedent(\n \"\"\"\n The default ``ddof`` of 1 used in :meth:`Series.std` is different\n than the default ``ddof`` of 0 in :func:`numpy.std`.\n\n A minimum of one period is required for the rolling calculation.\n\n The implementation is susceptible to floating point imprecision as\n shown in the example below.\\n\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])\n >>> s.rolling(3).std()\n 0 NaN\n 1 NaN\n 2 5.773503e-01\n 3 1.000000e+00\n 4 1.000000e+00\n 5 1.154701e+00\n 6 2.580957e-08\n dtype: float64\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"standard deviation\",\n agg_method=\"std\",\n )\n def std(self, ddof: int = 1, *args, **kwargs):\n nv.validate_rolling_func(\"std\", args, kwargs)\n return super().std(ddof=ddof, **kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n dedent(\n \"\"\"\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations\n is ``N - ddof``, where ``N`` represents the number of elements.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n args_compat,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n \"numpy.var : Equivalent method for NumPy array.\\n\",\n template_see_also,\n create_section_header(\"Notes\"),\n dedent(\n \"\"\"\n The default ``ddof`` of 1 used in :meth:`Series.var` is different\n than the default ``ddof`` of 0 in :func:`numpy.var`.\n\n A minimum of one period is required for the rolling calculation.\n\n The implementation is susceptible to floating point imprecision as\n shown in the example below.\\n\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])\n >>> s.rolling(3).var()\n 0 NaN\n 1 NaN\n 2 3.333333e-01\n 3 1.000000e+00\n 4 1.000000e+00\n 5 1.333333e+00\n 6 6.661338e-16\n dtype: float64\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"variance\",\n agg_method=\"var\",\n )\n def var(self, ddof: int = 1, *args, **kwargs):\n nv.validate_rolling_func(\"var\", args, kwargs)\n return super().var(ddof=ddof, **kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n \"scipy.stats.skew : Third moment of a probability density.\\n\",\n template_see_also,\n create_section_header(\"Notes\"),\n \"A minimum of three periods is required for the rolling calculation.\\n\",\n window_method=\"rolling\",\n aggregation_description=\"unbiased skewness\",\n agg_method=\"skew\",\n )\n def skew(self, **kwargs):\n return super().skew(**kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n dedent(\n \"\"\"\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations\n is ``N - ddof``, where ``N`` represents the number of elements.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n args_compat,\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also,\n create_section_header(\"Notes\"),\n \"A minimum of one period is required for the calculation.\\n\\n\",\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n >>> s = pd.Series([0, 1, 2, 3])\n >>> s.rolling(2, min_periods=1).sem()\n 0 NaN\n 1 0.707107\n 2 0.707107\n 3 0.707107\n dtype: float64\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"standard error of mean\",\n agg_method=\"sem\",\n )\n def sem(self, ddof: int = 1, *args, **kwargs):\n return self.std(*args, **kwargs) / (self.count() - ddof).pow(0.5)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n \"scipy.stats.kurtosis : Reference SciPy method.\\n\",\n template_see_also,\n create_section_header(\"Notes\"),\n \"A minimum of four periods is required for the calculation.\\n\\n\",\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n The example below will show a rolling calculation with a window size of\n four matching the equivalent function call using `scipy.stats`.\n\n >>> arr = [1, 2, 3, 4, 999]\n >>> import scipy.stats\n >>> print(f\"{{scipy.stats.kurtosis(arr[:-1], bias=False):.6f}}\")\n -1.200000\n >>> print(f\"{{scipy.stats.kurtosis(arr[1:], bias=False):.6f}}\")\n 3.999946\n >>> s = pd.Series(arr)\n >>> s.rolling(4).kurt()\n 0 NaN\n 1 NaN\n 2 NaN\n 3 -1.200000\n 4 3.999946\n dtype: float64\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"Fisher's definition of kurtosis without bias\",\n agg_method=\"kurt\",\n )\n def kurt(self, **kwargs):\n return super().kurt(**kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n dedent(\n \"\"\"\n quantile : float\n Quantile to compute. 0 <= quantile <= 1.\n interpolation : {{'linear', 'lower', 'higher', 'midpoint', 'nearest'}}\n This optional parameter specifies the interpolation method to use,\n when the desired quantile lies between two data points `i` and `j`:\n\n * linear: `i + (j - i) * fraction`, where `fraction` is the\n fractional part of the index surrounded by `i` and `j`.\n * lower: `i`.\n * higher: `j`.\n * nearest: `i` or `j` whichever is nearest.\n * midpoint: (`i` + `j`) / 2.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also,\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n >>> s = pd.Series([1, 2, 3, 4])\n >>> s.rolling(2).quantile(.4, interpolation='lower')\n 0 NaN\n 1 1.0\n 2 2.0\n 3 3.0\n dtype: float64\n\n >>> s.rolling(2).quantile(.4, interpolation='midpoint')\n 0 NaN\n 1 1.5\n 2 2.5\n 3 3.5\n dtype: float64\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"quantile\",\n agg_method=\"quantile\",\n )\n def quantile(self, quantile: float, interpolation: str = \"linear\", **kwargs):\n return super().quantile(\n quantile=quantile,\n interpolation=interpolation,\n **kwargs,\n )\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n dedent(\n \"\"\"\n other : Series or DataFrame, optional\n If not supplied then will default to self and produce pairwise\n output.\n pairwise : bool, default None\n If False then only matching columns between self and other will be\n used and the output will be a DataFrame.\n If True then all pairwise combinations will be calculated and the\n output will be a MultiIndexed DataFrame in the case of DataFrame\n inputs. In the case of missing elements, only complete pairwise\n observations will be used.\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations\n is ``N - ddof``, where ``N`` represents the number of elements.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n template_see_also[:-1],\n window_method=\"rolling\",\n aggregation_description=\"sample covariance\",\n agg_method=\"cov\",\n )\n def cov(\n self,\n other: FrameOrSeriesUnion | None = None,\n pairwise: bool | None = None,\n ddof: int = 1,\n **kwargs,\n ):\n return super().cov(other=other, pairwise=pairwise, ddof=ddof, **kwargs)\n\n @doc(\n template_header,\n create_section_header(\"Parameters\"),\n dedent(\n \"\"\"\n other : Series or DataFrame, optional\n If not supplied then will default to self and produce pairwise\n output.\n pairwise : bool, default None\n If False then only matching columns between self and other will be\n used and the output will be a DataFrame.\n If True then all pairwise combinations will be calculated and the\n output will be a MultiIndexed DataFrame in the case of DataFrame\n inputs. In the case of missing elements, only complete pairwise\n observations will be used.\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations\n is ``N - ddof``, where ``N`` represents the number of elements.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n kwargs_compat,\n create_section_header(\"Returns\"),\n template_returns,\n create_section_header(\"See Also\"),\n dedent(\n \"\"\"\n cov : Similar method to calculate covariance.\n numpy.corrcoef : NumPy Pearson's correlation calculation.\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n template_see_also,\n create_section_header(\"Notes\"),\n dedent(\n \"\"\"\n This function uses Pearson's definition of correlation\n (https://en.wikipedia.org/wiki/Pearson_correlation_coefficient).\n\n When `other` is not specified, the output will be self correlation (e.g.\n all 1's), except for :class:`~pandas.DataFrame` inputs with `pairwise`\n set to `True`.\n\n Function will return ``NaN`` for correlations of equal valued sequences;\n this is the result of a 0/0 division error.\n\n When `pairwise` is set to `False`, only matching columns between `self` and\n `other` will be used.\n\n When `pairwise` is set to `True`, the output will be a MultiIndex DataFrame\n with the original index on the first level, and the `other` DataFrame\n columns on the second level.\n\n In the case of missing elements, only complete pairwise observations\n will be used.\\n\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n create_section_header(\"Examples\"),\n dedent(\n \"\"\"\n The below example shows a rolling calculation with a window size of\n four matching the equivalent function call using :meth:`numpy.corrcoef`.\n\n >>> v1 = [3, 3, 3, 5, 8]\n >>> v2 = [3, 4, 4, 4, 8]\n >>> # numpy returns a 2X2 array, the correlation coefficient\n >>> # is the number at entry [0][1]\n >>> print(f\"{{np.corrcoef(v1[:-1], v2[:-1])[0][1]:.6f}}\")\n 0.333333\n >>> print(f\"{{np.corrcoef(v1[1:], v2[1:])[0][1]:.6f}}\")\n 0.916949\n >>> s1 = pd.Series(v1)\n >>> s2 = pd.Series(v2)\n >>> s1.rolling(4).corr(s2)\n 0 NaN\n 1 NaN\n 2 NaN\n 3 0.333333\n 4 0.916949\n dtype: float64\n\n The below example shows a similar rolling calculation on a\n DataFrame using the pairwise option.\n\n >>> matrix = np.array([[51., 35.], [49., 30.], [47., 32.],\\\n [46., 31.], [50., 36.]])\n >>> print(np.corrcoef(matrix[:-1,0], matrix[:-1,1]).round(7))\n [[1. 0.6263001]\n [0.6263001 1. ]]\n >>> print(np.corrcoef(matrix[1:,0], matrix[1:,1]).round(7))\n [[1. 0.5553681]\n [0.5553681 1. ]]\n >>> df = pd.DataFrame(matrix, columns=['X','Y'])\n >>> df\n X Y\n 0 51.0 35.0\n 1 49.0 30.0\n 2 47.0 32.0\n 3 46.0 31.0\n 4 50.0 36.0\n >>> df.rolling(4).corr(pairwise=True)\n X Y\n 0 X NaN NaN\n Y NaN NaN\n 1 X NaN NaN\n Y NaN NaN\n 2 X NaN NaN\n Y NaN NaN\n 3 X 1.000000 0.626300\n Y 0.626300 1.000000\n 4 X 1.000000 0.555368\n Y 0.555368 1.000000\n \"\"\"\n ).replace(\"\\n\", \"\", 1),\n window_method=\"rolling\",\n aggregation_description=\"correlation\",\n agg_method=\"corr\",\n )\n def corr(\n self,\n other: FrameOrSeriesUnion | None = None,\n pairwise: bool | None = None,\n ddof: int = 1,\n **kwargs,\n ):\n return super().corr(other=other, pairwise=pairwise, ddof=ddof, **kwargs)\n\n\nRolling.__doc__ = Window.__doc__\n\n\nclass RollingGroupby(BaseWindowGroupby, Rolling):\n \"\"\"\n Provide a rolling groupby implementation.\n \"\"\"\n\n _attributes = Rolling._attributes + BaseWindowGroupby._attributes\n\n def _get_window_indexer(self) -> GroupbyIndexer:\n \"\"\"\n Return an indexer class that will compute the window start and end bounds\n\n Returns\n -------\n GroupbyIndexer\n \"\"\"\n rolling_indexer: type[BaseIndexer]\n indexer_kwargs: dict[str, Any] | None = None\n index_array = self._index_array\n if isinstance(self.window, BaseIndexer):\n rolling_indexer = type(self.window)\n indexer_kwargs = self.window.__dict__\n assert isinstance(indexer_kwargs, dict) # for mypy\n # We'll be using the index of each group later\n indexer_kwargs.pop(\"index_array\", None)\n window = 0\n elif self._win_freq_i8 is not None:\n rolling_indexer = VariableWindowIndexer\n window = self._win_freq_i8\n else:\n rolling_indexer = FixedWindowIndexer\n window = self.window\n window_indexer = GroupbyIndexer(\n index_array=index_array,\n window_size=window,\n groupby_indicies=self._grouper.indices,\n window_indexer=rolling_indexer,\n indexer_kwargs=indexer_kwargs,\n )\n return window_indexer\n\n def _validate_monotonic(self):\n \"\"\"\n Validate that on is monotonic;\n in this case we have to check only for nans, because\n monotonicity was already validated at a higher level.\n \"\"\"\n if self._on.hasnans:\n self._raise_monotonic_error()\n" ]
[ [ "pandas.Series", "pandas.core.window.numba_.generate_numba_table_func", "pandas.core.window.indexers.FixedWindowIndexer", "pandas.core.dtypes.missing.notna", "numpy.concatenate", "pandas.compat.numpy.function.validate_rolling_func", "pandas.core.apply.ResamplerWindowApply", "pandas._libs.window.aggregations.roll_var", "numpy.where", "pandas.core.dtypes.common.ensure_float64", "pandas._libs.tslibs.to_offset", "pandas.compat.numpy.function.validate_window_func", "pandas.core.indexes.api.MultiIndex.from_arrays", "pandas.compat._optional.import_optional_dependency", "pandas.core.algorithms.factorize", "pandas.core.window.doc.create_section_header", "pandas.core.util.numba_.maybe_use_numba", "numpy.apply_along_axis", "pandas._libs.window.aggregations.roll_mean", "pandas.core.window.indexers.GroupbyIndexer", "pandas.core.dtypes.common.is_list_like", "pandas.core.base.DataError", "pandas.core.window.indexers.BaseIndexer", "pandas.core.window.numba_.generate_numba_apply_func", "pandas.core.indexes.api.Index", "numpy.errstate", "numpy.array", "pandas.core.dtypes.common.needs_i8_conversion", "pandas.core.dtypes.common.is_bool", "pandas.core.common.maybe_make_list", "pandas.core.window.indexers.VariableWindowIndexer", "pandas.core.window.numba_.generate_manual_numpy_nan_agg_with_axis", "pandas.core.dtypes.common.is_scalar", "pandas.core.dtypes.common.is_integer", "pandas.core.indexes.api.MultiIndex", "numpy.isinf" ] ]
[ { "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": [] } ]
pgunn/ffn
[ "8d9e7a34feb3829338561b8875146b7308d3d793" ]
[ "ffn/utils/bounding_box.py" ]
[ "# Copyright 2017 Google 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# https://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\"\"\"BoundingBox built on Numpy, interoperable with bounding_box_pb2.\n\nComposed of Numpy arrays (3-vectors actually) to support natural arithmetic\noperations. Easily instantiable from and convertible to a BoundingBox proto.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom bisect import bisect_right\nimport copy\n\nimport numpy as np\n\nfrom . import bounding_box_pb2\nfrom . import geom_utils\n\n\nclass BoundingBox(object):\n \"\"\"BoundingBox built on Numpy, interoperable with bounding_box_pb2.\"\"\"\n\n def __init__(self, start=None, size=None, end=None):\n \"\"\"Initialize a BoundingBox from an existing BoundingBox or explicit bounds.\n\n If start is not a BoundingBox object or proto, then exactly two of start,\n size, and end must be specified.\n\n Args:\n start: a Vector3j, 3-element sequence specifying the (inclusive) start\n bound, or BoundingBox proto/object, in which case no other arguments\n may be specified.\n size: a Vector3j or 3-element sequence specifying the size.\n end: a Vector3j or 3-element sequence specifying the (exclusive) end\n bound.\n\n Raises:\n ValueError: on bad inputs.\n \"\"\"\n if start is not None:\n if (isinstance(start, bounding_box_pb2.BoundingBox) or\n isinstance(start, BoundingBox)):\n if size is not None or end is not None:\n raise ValueError('a BoundingBox object/proto must be specified alone')\n size = start.size\n start = start.start\n\n if (end is not None) + (start is not None) + (size is not None) != 2:\n raise ValueError('exactly two of start, end, and size must be specified')\n\n if start is not None:\n self.start = geom_utils.ToNumpy3Vector(start)\n if size is not None:\n self.size = geom_utils.ToNumpy3Vector(size)\n if end is not None:\n end = geom_utils.ToNumpy3Vector(end)\n\n if end is not None:\n if size is not None:\n self.start = end - size\n else:\n self.size = end - start\n\n def adjusted_by(self, start=None, end=None):\n \"\"\"Adds an offset to the start and/or end bounds of the bounding box.\n\n Both arguments can be any argument type supported by\n geom_utils.ToNumpy3Vector, i.e. a Vector3j proto, a 3-tuple, or a\n 3-element numpy array.\n\n Args:\n start: vector offset added to the start bound\n end: vector offset added to the end bound\n\n Returns:\n A new BoundingBox with adjusted bounds.\n\n Raises:\n ValueError: on bad inputs.\n \"\"\"\n start_pos = self.start\n end_pos = self.end\n if start is not None:\n # We don't use += because that would modify our self.start in place.\n start_pos = start_pos + geom_utils.ToNumpy3Vector(start) # pylint: disable=g-no-augmented-assignment\n if end is not None:\n end_pos = end_pos + geom_utils.ToNumpy3Vector(end) # pylint: disable=g-no-augmented-assignment\n return BoundingBox(start=start_pos, end=end_pos)\n\n @property\n def end(self):\n \"\"\"Returns the (exclusive) end bound as a 3-element int64 numpy array.\n\n Returns:\n self.start + self.size\n \"\"\"\n return self.start + self.size\n\n def Sub(self, start=None, end=None, size=None):\n \"\"\"Returns a new BoundingBox with the specified bounds relative to self.\n\n Args:\n start: Specifies the new start bound, relative to self.start. If not\n specified, the current start bound is kept, unless end and size are\n both specified, in which case it is inferred.\n end: Specifies the new end bound, relative to self.start. If not\n specified, the current end bound is kept, unless start and size are\n both specified, in which case it is inferred.\n size: In conjunction with start or end (but not both), specifies the new\n size.\n\n Returns:\n A new BoundingBox with adjusted bounds, or self if no arguments are\n specified.\n\n Raises:\n ValueError: if invalid arguments are specified.\n \"\"\"\n if start is None:\n if end is None:\n if size is not None:\n raise ValueError('size must be specified with either end or start')\n return self\n else:\n end = geom_utils.ToNumpy3Vector(end)\n if size is None:\n return BoundingBox(self.start, end)\n else:\n size = geom_utils.ToNumpy3Vector(size)\n start = self.start + end - size\n return BoundingBox(start, size)\n else:\n # start specified.\n start = geom_utils.ToNumpy3Vector(start)\n if end is None:\n if size is None:\n size = self.size - start\n return BoundingBox(self.start + start, size)\n else:\n # end specified.\n if size is not None:\n raise ValueError(\n 'size must not be specified if both start and end are given')\n return BoundingBox(self.start + start, end - start)\n\n def to_proto(self):\n \"\"\"Returns a corresponding BoundingBox proto.\"\"\"\n proto = bounding_box_pb2.BoundingBox()\n proto.start.CopyFrom(geom_utils.ToVector3j(self.start))\n proto.size.CopyFrom(geom_utils.ToVector3j(self.size))\n return proto\n\n def to_slice(self):\n \"\"\"Returns slice in C-order (ZYX).\"\"\"\n return np.index_exp[self.start[2]:self.end[2], #\n self.start[1]:self.end[1], #\n self.start[0]:self.end[0]]\n\n def __repr__(self):\n return 'BoundingBox(start=%s, size=%s)' % (tuple(self.start),\n tuple(self.size))\n\n def __eq__(self, other):\n if isinstance(other, bounding_box_pb2.BoundingBox):\n other = BoundingBox(other)\n elif not isinstance(other, BoundingBox):\n return False\n return (np.all(self.start == other.start) and\n np.all(self.size == other.size))\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash((tuple(self.start), tuple(self.size)))\n\n\ndef intersection(box0, box1):\n \"\"\"Get intersection between two bounding boxes, or None.\"\"\"\n if isinstance(box0, bounding_box_pb2.BoundingBox):\n box0 = BoundingBox(box0.start, box0.size)\n if isinstance(box1, bounding_box_pb2.BoundingBox):\n box1 = BoundingBox(box1.start, box1.size)\n if not isinstance(box0, BoundingBox):\n raise ValueError('box0 must be a BoundingBox')\n if not isinstance(box0, BoundingBox):\n raise ValueError('box1 must be a BoundingBox')\n start = np.maximum(box0.start, box1.start)\n end = np.minimum(box0.end, box1.end)\n if np.any(end <= start): return None\n return BoundingBox(start=start, end=end)\n\n\ndef intersections(boxes0, boxes1):\n \"\"\"Get intersections between two sequences of boxes.\n\n Args:\n boxes0: a sequence of BoundingBoxes\n boxes1: a sequence of BoundingBoxes\n\n Returns:\n list of intersections between the two sequences. Each element of boxes0 is\n intersected with each element of boxes1, and any non-None are added to the\n list.\n \"\"\"\n intersections = []\n for box0 in boxes0:\n current_intersections = [intersection(box0, box1) for box1 in boxes1]\n intersections.extend([i for i in current_intersections if i is not None])\n return intersections\n\n\ndef containing(*boxes):\n \"\"\"Get the minimum bounding box containing all specified boxes.\n\n Args:\n *boxes: one or more bounding boxes\n\n Returns:\n The minimum bounding box that contains all boxes.\n\n Raises:\n ValueError: if invalid arguments are 217specified.\n \"\"\"\n if not boxes:\n raise ValueError('At least one bounding box must be specified')\n boxes_objs = map(BoundingBox, boxes)\n start = boxes_objs[0].start\n end = boxes_objs[0].end\n for box in boxes_objs[1:]:\n start = np.minimum(start, box.start)\n end = np.maximum(end, box.end)\n return BoundingBox(start=start, end=end)\n\n\nclass OrderlyOverlappingCalculator(object):\n \"\"\"Helper for calculating orderly overlapping sub-boxes.\n\n Provides a serial generator as well as num_sub_boxes and index_to_sub_box to\n support parallel dynamic generation.\n \"\"\"\n\n def __init__(self,\n outer_box,\n sub_box_size,\n overlap,\n include_small_sub_boxes=False,\n back_shift_small_sub_boxes=False):\n \"\"\"Helper for calculating orderly overlapping sub-boxes.\n\n Args:\n outer_box: BoundingBox to be broken into sub-boxes.\n sub_box_size: 3-sequence giving desired 3d size of each sub-box. Smaller\n sub-boxes may be included at the back edge of the volume, but not if\n they are smaller than overlap (in that case they are completely included\n in the preceding box) unless include_small_sub_boxes is True. If an\n element is None, the entire range available within outer_box is used for\n that dimension.\n overlap: 3-sequence giving the overlap between neighboring sub-boxes. Must\n be < sub_box_size.\n include_small_sub_boxes: Whether to include small subvolumes at the back\n end which are smaller than overlap\n back_shift_small_sub_boxes: If True, do not produce undersized boxes at\n the back edge of the outer_box. Instead, shift the start of these boxes\n back so that they can maintain sub_box_size. This means that the boxes\n at the back edge will have more overlap than the rest of the boxes.\n\n Raises:\n ValueError: if overlap >= sub_box_size.\n \"\"\"\n # Allow sub_box_size elements to be None, which means use the whole range.\n sub_box_size = list(sub_box_size)\n for i, x in enumerate(sub_box_size):\n if x is None:\n sub_box_size[i] = outer_box.size[i]\n\n overlap = np.array(overlap)\n stride = np.array(sub_box_size) - overlap\n if np.any(stride <= 0):\n raise ValueError('sub_box_size must be greater than overlap: %r versus %r'\n % (sub_box_size, overlap))\n\n if not include_small_sub_boxes:\n # Don't include subvolumes at the back end that are smaller than overlap;\n # these are included completely in the preceding subvolume.\n end = outer_box.end - overlap\n else:\n end = outer_box.end\n\n self.start = outer_box.start\n self.stride = stride\n self.end = end\n self.sub_box_size = sub_box_size\n self.outer_box = outer_box\n\n size = end - self.start\n self.total_sub_boxes_xyz = (size + stride - 1) // stride # ceil_div\n self.back_shift_small_sub_boxes = back_shift_small_sub_boxes\n\n def start_to_box(self, start):\n full_box = BoundingBox(start=start, size=self.sub_box_size)\n if self.back_shift_small_sub_boxes:\n shift = np.maximum(full_box.end - self.outer_box.end, 0)\n if shift.any():\n return BoundingBox(start=full_box.start - shift, size=self.sub_box_size)\n return full_box\n else:\n return intersection(full_box, self.outer_box)\n\n def index_to_sub_box(self, index):\n \"\"\"Translates a linear index to appropriate sub box.\n\n Args:\n index: The linear index in [0, num_sub_boxes)\n\n Returns:\n The corresponding BoundingBox.\n\n The boxes are guaranteed to be generated in Fortran order, i.e. x fastest\n changing. (This means that VolumeStore Subvolumes generated from contiguous\n indices will be near each other in x.)\n \"\"\"\n coords = np.unravel_index(index, self.total_sub_boxes_xyz, order='F')\n return self.start_to_box(coords * self.stride + self.start)\n\n def offset_to_index(self, index, offset):\n \"\"\"Calculate the index of another box at offset w.r.t.\n\n current index.\n\n Args:\n index: the current flat index from which to calculate the offset index.\n offset: the xyz offset from current index at which to calculate the new\n index.\n\n Returns:\n The flat index at offset from current index, or None if the given offset\n goes beyond the range of sub-boxes.\n\n This is usually used to calculate the boxes that neighbor the current box.\n \"\"\"\n coords = np.unravel_index(index, self.total_sub_boxes_xyz, order='F')\n offset_coords = np.array(coords) + offset\n if np.any(offset_coords < 0) or np.any(\n offset_coords >= self.total_sub_boxes_xyz):\n return None\n return np.ravel_multi_index(\n offset_coords, self.total_sub_boxes_xyz, order='F')\n\n def num_sub_boxes(self):\n \"\"\"Total number of sub-boxes.\"\"\"\n prod = self.total_sub_boxes_xyz.astype(object).prod()\n return prod\n\n def generate_sub_boxes(self):\n \"\"\"Generates all sub-boxes in raster order.\"\"\"\n for z in range(self.start[2], self.end[2], self.stride[2]):\n for y in range(self.start[1], self.end[1], self.stride[1]):\n for x in range(self.start[0], self.end[0], self.stride[0]):\n yield _required(self.start_to_box((x, y, z)))\n\n def batched_sub_boxes(self,\n batch_size,\n begin_index=0,\n end_index=None):\n \"\"\"Generates iterators for batches of sub-boxes.\n\n Args:\n batch_size: how many sub-boxes per iterable.\n begin_index: the inclusive beginning numerical index.\n end_index: the exclusive ending numerical index.\n\n Yields:\n An iterable of sub-boxes for each batch.\n \"\"\"\n if end_index is None:\n end_index = self.num_sub_boxes()\n for i_begin in range(begin_index, end_index, batch_size):\n i_end = min(i_begin + batch_size, end_index)\n yield (\n _required(self.index_to_sub_box(i)) for i in range(i_begin, i_end))\n\n def tag_border_locations(self, index):\n \"\"\"Checks whether a box touches the border of the BoundingBox.\n\n Args:\n index: flat index identifying the box to check\n\n Returns:\n 2-tuple of bool 3d ndarrays (dim order: x, y, z).\n True if the box touches the border at the start/end (respectively for the\n 1st and 2nd element of the tuple) of the bbox along the given dimension.\n \"\"\"\n coords_xyz = np.array(\n np.unravel_index(index, self.total_sub_boxes_xyz, order='F'))\n is_start = coords_xyz == 0\n is_end = coords_xyz == self.total_sub_boxes_xyz - 1\n return is_start, is_end\n" ]
[ [ "numpy.maximum", "numpy.minimum", "numpy.all", "numpy.any", "numpy.ravel_multi_index", "numpy.array", "numpy.unravel_index" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
justkj7/capstone
[ "f458b6624b8aa75961a0ab78e9847355022940d3" ]
[ "tapas/run_task_main.py" ]
[ "# coding=utf-8\n# Copyright 2019 The Google AI Language Team 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# Lint as: python3\n\"\"\"Script for creating TF examples, training and evaluation.\"\"\"\n\nimport enum\nimport functools\nimport os\nimport random\nimport time\nfrom typing import Text, Optional\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport dataclasses\nfrom tapas.experiments import prediction_utils as exp_prediction_utils\nfrom tapas.models import tapas_classifier_model\nfrom tapas.models.bert import modeling\nfrom tapas.scripts import calc_metrics_utils\nfrom tapas.scripts import prediction_utils\nfrom tapas.utils import file_utils\nfrom tapas.utils import hparam_utils\nfrom tapas.utils import number_annotation_utils\nfrom tapas.utils import pruning_utils\nfrom tapas.utils import task_utils\nfrom tapas.utils import tasks\nfrom tapas.utils import tf_example_utils\nimport tensorflow.compat.v1 as tf\n\n\ntf.disable_v2_behavior()\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('input_dir', None,\n 'Directory where original shared task data is read from.')\nflags.DEFINE_string('output_dir', None,\n 'Directory where new data is written to.')\nflags.DEFINE_string(\n 'model_dir', None,\n 'Directory where model checkpoints and predictions are written to. '\n 'f\"{output_dir}/model\" will be used if None.')\nflags.DEFINE_string('task', None, 'Task to run for.')\n\nflags.DEFINE_string('bert_vocab_file', None, 'Bert vocab file.')\nflags.DEFINE_string('bert_config_file', None, 'Bert config file.')\nflags.DEFINE_string('init_checkpoint', None, 'Init checkpoint.')\nflags.DEFINE_string('tapas_verbosity', None, 'Logging verbosity.')\n\nflags.DEFINE_bool('use_tpu', False, 'Whether to use TPU or GPU/CPU.')\n\nflags.DEFINE_string(\n 'tpu_name', None,\n 'The Cloud TPU to use for training. This should be either the name used '\n 'when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 url.')\n\nflags.DEFINE_string(\n 'tpu_zone', None,\n '[Optional] GCE zone where the Cloud TPU is located in. If not '\n 'specified, we will attempt to automatically detect the GCE project from '\n 'metadata.')\n\nflags.DEFINE_string(\n 'gcp_project', None,\n '[Optional] Project name for the Cloud TPU-enabled project. If not '\n 'specified, we will attempt to automatically detect the GCE project from '\n 'metadata.')\n\nflags.DEFINE_string('master', None, '[Optional] TensorFlow master URL.')\n\nflags.DEFINE_integer(\n 'num_tpu_cores', 8,\n 'Only used if `use_tpu` is True. Total number of TPU cores to use.')\n\nflags.DEFINE_integer('test_batch_size', 32, 'Test batch size.')\n\nflags.DEFINE_integer(\n 'train_batch_size', None,\n 'Train batch size, if None will use the value from the hparams of the task '\n '(recommended).')\n\nflags.DEFINE_integer('gradient_accumulation_steps', 1,\n 'Accumulate gradients across multiple steps.')\n\nflags.DEFINE_integer('iterations_per_loop', 1000,\n 'How many steps to make in each estimator call.')\n\nflags.DEFINE_bool('test_mode', False,\n 'Cut some corners to test the pipeline end-to-end.')\n\nflags.DEFINE_integer('tf_random_seed', None, 'Random seed for tensorflow.')\n\nflags.DEFINE_integer('max_seq_length', 512, 'Max sequence length of the input.')\n\nflags.DEFINE_string('mode', '', 'See Mode below.')\n\nflags.DEFINE_bool('loop_predict', True,\n 'Loop predictions as new checkpoints appear while training')\n\nflags.DEFINE_string(\n 'compression_type',\n 'GZIP',\n \"Compression to use when reading tfrecords. '' for no compression.\",\n)\n\nflags.DEFINE_bool('reset_position_index_per_cell', False,\n 'If true, reset absolute position index at every cell.')\n\nflags.DEFINE_bool('prune_columns', False,\n 'Use word overlap heuristics to keep most relevant columns.')\n\n_MAX_TABLE_ID = 512\n_MAX_PREDICTIONS_PER_SEQ = 20\n_CELL_CLASSIFICATION_THRESHOLD = 0.5\n\n\nclass Mode(enum.Enum):\n CREATE_DATA = 1\n TRAIN = 2\n PREDICT_AND_EVALUATE = 3\n EVALUATE = 4\n PREDICT = 5\n\n\nclass TestSet(enum.Enum):\n DEV = 1\n TEST = 2\n\n\[email protected]\nclass TpuOptions:\n use_tpu: bool\n tpu_name: Optional[Text]\n tpu_zone: Optional[Text]\n gcp_project: Optional[Text]\n master: Optional[Text]\n num_tpu_cores: int\n iterations_per_loop: int\n\n\ndef _print(msg):\n print(msg)\n logging.info(msg)\n\n\ndef _warn(msg):\n print(f'Warning: {msg}')\n logging.warn(msg)\n\n\ndef _create_all_examples(\n task,\n vocab_file,\n test_mode,\n output_dir,\n test_batch_size,\n):\n \"\"\"Converts interactions to TF examples.\"\"\"\n interaction_dir = task_utils.get_interaction_dir(output_dir)\n example_dir = os.path.join(output_dir, 'tf_examples')\n file_utils.make_directories(example_dir)\n\n _create_examples(\n interaction_dir,\n example_dir,\n vocab_file,\n task_utils.get_train_filename(task),\n batch_size=None,\n test_mode=test_mode)\n _create_examples(interaction_dir, example_dir, vocab_file,\n task_utils.get_dev_filename(task), test_batch_size,\n test_mode)\n _create_examples(interaction_dir, example_dir, vocab_file,\n task_utils.get_test_filename(task), test_batch_size,\n test_mode)\n\n\ndef _to_tf_compression_type(\n compression_type,):\n if not compression_type:\n return tf.io.TFRecordCompressionType.NONE\n if compression_type == 'GZIP':\n return tf.io.TFRecordCompressionType.GZIP\n if compression_type == 'ZLIB':\n return tf.io.TFRecordCompressionType.ZLIB\n raise ValueError(f'Unknown compression type: {compression_type}')\n\n\ndef _create_examples(\n interaction_dir,\n example_dir,\n vocab_file,\n filename,\n batch_size,\n test_mode,\n):\n \"\"\"Creates TF example for a single dataset.\"\"\"\n\n filename = f'{filename}.tfrecord'\n interaction_path = os.path.join(interaction_dir, filename)\n example_path = os.path.join(example_dir, filename)\n\n config = tf_example_utils.ClassifierConversionConfig(\n vocab_file=vocab_file,\n max_seq_length=FLAGS.max_seq_length,\n max_column_id=_MAX_TABLE_ID,\n max_row_id=_MAX_TABLE_ID,\n strip_column_names=False,\n add_aggregation_candidates=False,\n )\n converter = tf_example_utils.ToClassifierTensorflowExample(config)\n\n examples = []\n num_questions = 0\n num_conversion_errors = 0\n for interaction in prediction_utils.iterate_interactions(interaction_path):\n number_annotation_utils.add_numeric_values(interaction)\n for i in range(len(interaction.questions)):\n num_questions += 1\n\n try:\n examples.append(converter.convert(interaction, i))\n except ValueError as e:\n num_conversion_errors += 1\n logging.info(\"Can't convert interaction: %s error: %s\", interaction.id,\n e)\n if test_mode and len(examples) >= 100:\n break\n\n _print(f'Processed: {filename}')\n _print(f'Num questions processed: {num_questions}')\n _print(f'Num examples: {len(examples)}')\n _print(f'Num conversion errors: {num_conversion_errors}')\n\n if batch_size is None:\n random.shuffle(examples)\n else:\n # Make sure the eval sets are divisible by the test batch size since\n # otherwise examples will be dropped on TPU.\n # These examples will later be ignored when writing the predictions.\n originial_num_examples = len(examples)\n while len(examples) % batch_size != 0:\n examples.append(converter.get_empty_example())\n if originial_num_examples != len(examples):\n _print(f'Padded with {len(examples) - originial_num_examples} examples.')\n\n with tf.io.TFRecordWriter(\n example_path,\n options=_to_tf_compression_type(FLAGS.compression_type),\n ) as writer:\n for example in examples:\n writer.write(example.SerializeToString())\n\n\ndef _get_train_examples_file(task, output_dir):\n return os.path.join(output_dir, 'tf_examples',\n f'{task_utils.get_train_filename(task)}.tfrecord')\n\n\ndef _get_test_filename(task, test_set):\n if test_set == TestSet.TEST:\n return task_utils.get_test_filename(task)\n if test_set == TestSet.DEV:\n return task_utils.get_dev_filename(task)\n raise ValueError(f'Unknown test set: {test_set}')\n\n\ndef _get_test_examples_file(\n task,\n output_dir,\n test_set,\n):\n filename = _get_test_filename(task, test_set)\n return os.path.join(output_dir, 'tf_examples', f'{filename}.tfrecord')\n\n\ndef _get_test_interactions_file(\n task,\n output_dir,\n test_set,\n):\n filename = _get_test_filename(task, test_set)\n return os.path.join(output_dir, 'interactions', f'{filename}.tfrecord')\n\n\ndef _get_test_prediction_file(\n task,\n model_dir,\n test_set,\n is_sequence,\n global_step,\n):\n \"\"\"Get prediction filename for different tasks and setups.\"\"\"\n suffix = '' if global_step is None else f'_{global_step}'\n if is_sequence:\n suffix = f'_sequence{suffix}'\n filename = _get_test_filename(task, test_set)\n return os.path.join(model_dir, f'{filename}{suffix}.tsv')\n\n\ndef _get_token_selector():\n if not FLAGS.prune_columns:\n return None\n return pruning_utils.HeuristicExactMatchTokenSelector(\n FLAGS.bert_vocab_file,\n FLAGS.max_seq_length,\n pruning_utils.SelectionType.COLUMN,\n # Only relevant for SQA where questions come in sequence\n use_previous_answer=True,\n use_previous_questions=True,\n )\n\n\ndef _train_and_predict(\n task,\n tpu_options,\n test_batch_size,\n train_batch_size,\n gradient_accumulation_steps,\n bert_config_file,\n init_checkpoint,\n test_mode,\n mode,\n output_dir,\n model_dir,\n loop_predict,\n):\n \"\"\"Trains, produces test predictions and eval metric.\"\"\"\n file_utils.make_directories(model_dir)\n\n if task == tasks.Task.SQA:\n num_aggregation_labels = 0\n num_classification_labels = 0\n use_answer_as_supervision = None\n elif task in [\n tasks.Task.WTQ, tasks.Task.WIKISQL, tasks.Task.WIKISQL_SUPERVISED\n ]:\n num_aggregation_labels = 4\n num_classification_labels = 0\n use_answer_as_supervision = task != tasks.Task.WIKISQL_SUPERVISED\n elif task == tasks.Task.TABFACT:\n num_classification_labels = 2\n num_aggregation_labels = 0\n use_answer_as_supervision = True\n else:\n raise ValueError(f'Unknown task: {task.name}')\n\n do_model_aggregation = num_aggregation_labels > 0\n do_model_classification = num_classification_labels > 0\n\n hparams = hparam_utils.get_hparams(task)\n if test_mode:\n if train_batch_size is None:\n train_batch_size = 1\n test_batch_size = 1\n num_train_steps = 10\n num_warmup_steps = 1\n else:\n if train_batch_size is None:\n train_batch_size = hparams['train_batch_size']\n num_train_examples = hparams['num_train_examples']\n num_train_steps = int(num_train_examples / train_batch_size)\n num_warmup_steps = int(num_train_steps * hparams['warmup_ratio'])\n\n bert_config = modeling.BertConfig.from_json_file(bert_config_file)\n tapas_config = tapas_classifier_model.TapasClassifierConfig(\n bert_config=bert_config,\n init_checkpoint=init_checkpoint,\n learning_rate=hparams['learning_rate'],\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_tpu=tpu_options.use_tpu,\n positive_weight=10.0,\n num_aggregation_labels=num_aggregation_labels,\n num_classification_labels=num_classification_labels,\n aggregation_loss_importance=1.0,\n use_answer_as_supervision=use_answer_as_supervision,\n answer_loss_importance=1.0,\n use_normalized_answer_loss=False,\n huber_loss_delta=hparams.get('huber_loss_delta'),\n temperature=hparams.get('temperature', 1.0),\n agg_temperature=1.0,\n use_gumbel_for_cells=False,\n use_gumbel_for_agg=False,\n average_approximation_function=tapas_classifier_model.\\\n AverageApproximationFunction.RATIO,\n cell_select_pref=hparams.get('cell_select_pref'),\n answer_loss_cutoff=hparams.get('answer_loss_cutoff'),\n grad_clipping=hparams.get('grad_clipping'),\n disabled_features=[],\n max_num_rows=64,\n max_num_columns=32,\n average_logits_per_cell=False,\n init_cell_selection_weights_to_zero=\\\n hparams['init_cell_selection_weights_to_zero'],\n select_one_column=hparams['select_one_column'],\n allow_empty_column_selection=hparams['allow_empty_column_selection'],\n disable_position_embeddings=False,\n reset_position_index_per_cell=FLAGS.reset_position_index_per_cell)\n\n model_fn = tapas_classifier_model.model_fn_builder(tapas_config)\n\n is_per_host = tf.estimator.tpu.InputPipelineConfig.PER_HOST_V2\n\n tpu_cluster_resolver = None\n if tpu_options.use_tpu and tpu_options.tpu_name:\n tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(\n tpu=tpu_options.tpu_name,\n zone=tpu_options.tpu_zone,\n project=tpu_options.gcp_project,\n )\n\n run_config = tf.estimator.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n master=tpu_options.master,\n model_dir=model_dir,\n tf_random_seed=FLAGS.tf_random_seed,\n save_checkpoints_steps=1000,\n keep_checkpoint_max=5,\n keep_checkpoint_every_n_hours=4.0,\n tpu_config=tf.estimator.tpu.TPUConfig(\n iterations_per_loop=tpu_options.iterations_per_loop,\n num_shards=tpu_options.num_tpu_cores,\n per_host_input_for_training=is_per_host))\n\n # If TPU is not available, this will fall back to normal Estimator on CPU/GPU.\n estimator = tf.estimator.tpu.TPUEstimator(\n params={'gradient_accumulation_steps': gradient_accumulation_steps},\n use_tpu=tpu_options.use_tpu,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=train_batch_size // gradient_accumulation_steps,\n eval_batch_size=None,\n predict_batch_size=test_batch_size)\n\n if mode == Mode.TRAIN:\n _print('Training')\n bert_config.to_json_file(os.path.join(model_dir, 'bert_config.json'))\n tapas_config.to_json_file(os.path.join(model_dir, 'tapas_config.json'))\n train_input_fn = functools.partial(\n tapas_classifier_model.input_fn,\n name='train',\n file_patterns=_get_train_examples_file(task, output_dir),\n data_format='tfrecord',\n compression_type=FLAGS.compression_type,\n is_training=True,\n max_seq_length=FLAGS.max_seq_length,\n max_predictions_per_seq=_MAX_PREDICTIONS_PER_SEQ,\n add_aggregation_function_id=do_model_aggregation,\n add_classification_labels=do_model_classification,\n add_answer=use_answer_as_supervision,\n include_id=False,\n )\n estimator.train(\n input_fn=train_input_fn,\n max_steps=tapas_config.num_train_steps,\n )\n\n elif mode == Mode.PREDICT_AND_EVALUATE or mode == Mode.PREDICT:\n\n # Starts a continous eval that starts with the latest checkpoint and runs\n # until a checkpoint with 'num_train_steps' is reached.\n prev_checkpoint = None\n while True:\n checkpoint = estimator.latest_checkpoint()\n\n if not loop_predict and not checkpoint:\n raise ValueError(f'No checkpoint found at {model_dir}.')\n\n if loop_predict and checkpoint == prev_checkpoint:\n _print('Sleeping 5 mins before predicting')\n time.sleep(5 * 60)\n continue\n\n current_step = int(os.path.basename(checkpoint).split('-')[1])\n _predict(\n estimator,\n task,\n output_dir,\n model_dir,\n do_model_aggregation,\n do_model_classification,\n use_answer_as_supervision,\n use_tpu=tapas_config.use_tpu,\n global_step=current_step,\n )\n if mode == Mode.PREDICT_AND_EVALUATE:\n _eval(\n task=task,\n output_dir=output_dir,\n model_dir=model_dir,\n global_step=current_step)\n if not loop_predict or current_step >= tapas_config.num_train_steps:\n _print(f'Evaluation finished after training step {current_step}.')\n break\n\n else:\n raise ValueError(f'Unexpected mode: {mode}.')\n\n\ndef _predict(\n estimator,\n task,\n output_dir,\n model_dir,\n do_model_aggregation,\n do_model_classification,\n use_answer_as_supervision,\n use_tpu,\n global_step,\n):\n \"\"\"Writes predictions for dev and test.\"\"\"\n for test_set in TestSet:\n _predict_for_set(\n estimator,\n do_model_aggregation,\n do_model_classification,\n use_answer_as_supervision,\n example_file=_get_test_examples_file(\n task,\n output_dir,\n test_set,\n ),\n prediction_file=_get_test_prediction_file(\n task,\n model_dir,\n test_set,\n is_sequence=False,\n global_step=global_step,\n ),\n other_prediction_file=_get_test_prediction_file(\n task,\n model_dir,\n test_set,\n is_sequence=False,\n global_step=None,\n ),\n )\n if task == tasks.Task.SQA:\n if use_tpu:\n _warn('Skipping SQA sequence evaluation because eval is running on TPU.')\n else:\n for test_set in TestSet:\n _predict_sequence_for_set(\n estimator,\n do_model_aggregation,\n use_answer_as_supervision,\n example_file=_get_test_examples_file(task, output_dir, test_set),\n prediction_file=_get_test_prediction_file(\n task,\n model_dir,\n test_set,\n is_sequence=True,\n global_step=global_step,\n ),\n other_prediction_file=_get_test_prediction_file(\n task,\n model_dir,\n test_set,\n is_sequence=True,\n global_step=None,\n ),\n )\n\n\ndef _predict_for_set(\n estimator,\n do_model_aggregation,\n do_model_classification,\n use_answer_as_supervision,\n example_file,\n prediction_file,\n other_prediction_file,\n):\n \"\"\"Gets predictions and writes them to TSV file.\"\"\"\n # TODO also predict for dev.\n predict_input_fn = functools.partial(\n tapas_classifier_model.input_fn,\n name='predict',\n file_patterns=example_file,\n data_format='tfrecord',\n compression_type=FLAGS.compression_type,\n is_training=False,\n max_seq_length=FLAGS.max_seq_length,\n max_predictions_per_seq=_MAX_PREDICTIONS_PER_SEQ,\n add_aggregation_function_id=do_model_aggregation,\n add_classification_labels=do_model_classification,\n add_answer=use_answer_as_supervision,\n include_id=False)\n result = estimator.predict(input_fn=predict_input_fn)\n exp_prediction_utils.write_predictions(\n result,\n prediction_file,\n do_model_aggregation=do_model_aggregation,\n do_model_classification=do_model_classification,\n cell_classification_threshold=_CELL_CLASSIFICATION_THRESHOLD)\n tf.io.gfile.copy(prediction_file, other_prediction_file, overwrite=True)\n\n\ndef _predict_sequence_for_set(\n estimator,\n do_model_aggregation,\n use_answer_as_supervision,\n example_file,\n prediction_file,\n other_prediction_file,\n):\n \"\"\"Runs realistic sequence evaluation for SQA.\"\"\"\n examples_by_position = exp_prediction_utils.read_classifier_dataset(\n predict_data=example_file,\n data_format='tfrecord',\n compression_type=FLAGS.compression_type,\n max_seq_length=FLAGS.max_seq_length,\n max_predictions_per_seq=_MAX_PREDICTIONS_PER_SEQ,\n add_aggregation_function_id=do_model_aggregation,\n add_classification_labels=False,\n add_answer=use_answer_as_supervision)\n result = exp_prediction_utils.compute_prediction_sequence(\n estimator=estimator, examples_by_position=examples_by_position)\n exp_prediction_utils.write_predictions(\n result,\n prediction_file,\n do_model_aggregation,\n do_model_classification=False,\n cell_classification_threshold=_CELL_CLASSIFICATION_THRESHOLD,\n )\n tf.io.gfile.copy(prediction_file, other_prediction_file, overwrite=True)\n\n\ndef _eval(\n task,\n output_dir,\n model_dir,\n global_step = None,\n):\n \"\"\"Evaluate dev and test predictions.\"\"\"\n for test_set in TestSet:\n _eval_for_set(\n name=test_set.name.lower(),\n task=task,\n interaction_file=_get_test_interactions_file(\n task,\n output_dir,\n test_set,\n ),\n prediction_file=_get_test_prediction_file(\n task,\n model_dir,\n test_set,\n is_sequence=False,\n global_step=None,\n ),\n global_step=global_step,\n )\n if task == tasks.Task.SQA:\n _eval_for_set(\n name=f'{test_set.name.lower()}_seq',\n task=task,\n interaction_file=_get_test_interactions_file(\n task,\n output_dir,\n test_set,\n ),\n prediction_file=_get_test_prediction_file(\n task,\n model_dir,\n test_set,\n is_sequence=True,\n global_step=None,\n ),\n global_step=global_step,\n )\n\n\ndef _eval_for_set(\n name,\n task,\n interaction_file,\n prediction_file,\n global_step,\n):\n \"\"\"Computes eval metric from predictions.\"\"\"\n if not tf.io.gfile.exists(prediction_file):\n _warn(f\"Can't evaluate for {name} because {prediction_file} doesn't exist.\")\n return\n test_examples = calc_metrics_utils.read_data_examples_from_interactions(\n interaction_file)\n calc_metrics_utils.read_predictions(\n predictions_path=prediction_file,\n examples=test_examples,\n )\n if task in [\n tasks.Task.SQA, tasks.Task.WTQ, tasks.Task.WIKISQL,\n tasks.Task.WIKISQL_SUPERVISED\n ]:\n denotation_accuracy = calc_metrics_utils.calc_denotation_accuracy(\n examples=test_examples,\n denotation_errors_path=None,\n predictions_file_name=None,\n )\n _print(f'{name} denotation accuracy: {denotation_accuracy:0.4f}')\n elif task == tasks.Task.TABFACT:\n accuracy = calc_metrics_utils.calc_classification_accuracy(test_examples)\n _print(f'{name} accuracy: {accuracy:0.4f}')\n else:\n raise ValueError(f'Unknown task: {task.name}')\n\n\ndef _check_options(output_dir, task, mode):\n \"\"\"Checks against some invalid options so we can fail fast.\"\"\"\n\n if mode == Mode.CREATE_DATA:\n return\n\n if mode == Mode.PREDICT_AND_EVALUATE or mode == Mode.EVALUATE:\n interactions = _get_test_interactions_file(\n task,\n output_dir,\n test_set=TestSet.DEV,\n )\n if not tf.io.gfile.exists(interactions):\n raise ValueError(f'No interactions found: {interactions}')\n\n tf_examples = _get_test_examples_file(\n task,\n output_dir,\n test_set=TestSet.DEV,\n )\n if not tf.io.gfile.exists(tf_examples):\n raise ValueError(f'No TF examples found: {tf_examples}')\n\n _print(f'is_built_with_cuda: {tf.test.is_built_with_cuda()}')\n _print(f'is_gpu_available: {tf.test.is_gpu_available()}')\n _print(f'GPUs: {tf.config.experimental.list_physical_devices(\"GPU\")}')\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n if FLAGS.tapas_verbosity:\n tf.get_logger().setLevel(FLAGS.tapas_verbosity)\n\n task = tasks.Task[FLAGS.task]\n output_dir = os.path.join(FLAGS.output_dir, task.name.lower())\n model_dir = FLAGS.model_dir or os.path.join(output_dir, 'model')\n mode = Mode[FLAGS.mode.upper()]\n _check_options(output_dir, task, mode)\n\n if mode == Mode.CREATE_DATA:\n _print('Creating interactions ...')\n token_selector = _get_token_selector()\n task_utils.create_interactions(task, FLAGS.input_dir, output_dir,\n token_selector)\n _print('Creating TF examples ...')\n _create_all_examples(\n task,\n FLAGS.bert_vocab_file,\n FLAGS.test_mode,\n test_batch_size=FLAGS.test_batch_size,\n output_dir=output_dir)\n\n elif mode in (Mode.TRAIN, Mode.PREDICT_AND_EVALUATE, Mode.PREDICT):\n _print('Training or predicting ...')\n tpu_options = TpuOptions(\n use_tpu=FLAGS.use_tpu,\n tpu_name=FLAGS.tpu_name,\n tpu_zone=FLAGS.tpu_zone,\n gcp_project=FLAGS.gcp_project,\n master=FLAGS.master,\n num_tpu_cores=FLAGS.num_tpu_cores,\n iterations_per_loop=FLAGS.iterations_per_loop)\n _train_and_predict(\n task=task,\n tpu_options=tpu_options,\n test_batch_size=FLAGS.test_batch_size,\n train_batch_size=FLAGS.train_batch_size,\n gradient_accumulation_steps=FLAGS.gradient_accumulation_steps,\n bert_config_file=FLAGS.bert_config_file,\n init_checkpoint=FLAGS.init_checkpoint,\n test_mode=FLAGS.test_mode,\n mode=mode,\n output_dir=output_dir,\n model_dir=model_dir,\n loop_predict=FLAGS.loop_predict,\n )\n\n elif mode == Mode.EVALUATE:\n _eval(\n task=task,\n output_dir=output_dir,\n model_dir=model_dir,\n )\n\n else:\n raise ValueError(f'Unknown mode: {mode}')\n\n\nif __name__ == '__main__':\n app.run(main)\n" ]
[ [ "tensorflow.compat.v1.estimator.tpu.TPUEstimator", "tensorflow.compat.v1.io.gfile.exists", "tensorflow.compat.v1.config.experimental.list_physical_devices", "tensorflow.compat.v1.disable_v2_behavior", "tensorflow.compat.v1.test.is_gpu_available", "tensorflow.compat.v1.estimator.tpu.TPUConfig", "tensorflow.compat.v1.test.is_built_with_cuda", "tensorflow.compat.v1.get_logger", "tensorflow.compat.v1.distribute.cluster_resolver.TPUClusterResolver", "tensorflow.compat.v1.io.gfile.copy" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
annierak/odor_tracking_sim
[ "4600a7be942666c3a5a0f366dab6d14838f332a0" ]
[ "odor_tracking_sim/simulation_running_tools.py" ]
[ "import time\nimport scipy\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animate\nimport matplotlib\n# matplotlib.use(\"Agg\")\nimport cPickle as pickle\nimport sys\nimport itertools\n\nimport odor_tracking_sim.wind_models as wind_models\nimport odor_tracking_sim.odor_models as odor_models\nimport odor_tracking_sim.swarm_models as swarm_models\nimport odor_tracking_sim.trap_models as trap_models\nimport odor_tracking_sim.utility as utility\nimport odor_tracking_sim.borrowed_puff_models as puff_models\nimport odor_tracking_sim.borrowed_wind_models as pompy_wind_models\n\n\n\ndef setup_wind_field(wind_angle,wind_data_file,dt,release_delay,traps,plot_scale,\n wind_dt=None,wind_speed=0.5,pompy_wind_model=False,xlim=None,ylim=None):\n if not(wind_data_file==None):\n wind_dct = utility.process_wind_data(wind_data_file,release_delay,wind_dt=wind_dt)\n wind_param = {\n 'speed':wind_dct['wind_speed'],\n 'angle':wind_dct['wind_angle'],\n 'evolving': True,\n 'wind_dt': wind_dct['wind_dt'],\n 'dt': dt\n }\n else:\n wind_angle=wind_angle*scipy.pi/180.0\n wind_param = {\n 'speed': wind_speed,\n 'angle': wind_angle,\n 'evolving': False,\n 'wind_dt': None,\n 'dt': dt\n }\n if pompy_wind_model:\n if traps.num_traps>1:\n #Standard geometry: 6 traps around the center\n plot_size = plot_scale*traps.param['source_radius']\n xlim = (-plot_size, plot_size)\n ylim = (-plot_size, plot_size)\n aspect_ratio= (xlim[1]-xlim[0])/(ylim[1]-ylim[0])\n wind_region = puff_models.Rectangle(xlim[0]*1.2,ylim[0]*1.2,\n xlim[1]*1.2,ylim[1]*1.2)\n wind_speed = scipy.array(wind_dct['wind_speed'])\n wind_angle = scipy.array(wind_dct['wind_angle'])\n wind_vel_x_av = wind_speed*scipy.cos(wind_angle)\n wind_vel_y_av = wind_speed*scipy.sin(wind_angle)\n wind_field = pompy_wind_models.WindModel(wind_region,\n int(15*aspect_ratio),15, wind_vel_x_av, wind_vel_y_av)\n else:\n wind_field = wind_models.WindField(param=wind_param)\n return wind_field\n\ndef setup_traps(number_sources = 6,radius_sources = 1000.0,strength_sources = 10.0,\ntrap_radius = 5.):\n if number_sources>1:\n #Standard geometry: 6 traps around the center\n location_list, strength_list = utility.create_circle_of_sources(\n number_sources,\n radius_sources,\n strength_sources\n )\n else:\n #Toy example with just one trap\n strength_list = [strength_sources]\n location_list = [(radius_sources*scipy.cos(scipy.pi/3),radius_sources*scipy.sin(scipy.pi/3))]\n\n# Set up the trap object (separated from odor object 3/8)\n\n trap_param = {\n 'source_locations' : location_list,\n 'source_strengths' : strength_list,\n 'epsilon' : 0.01,\n 'trap_radius' : trap_radius,\n 'source_radius' : radius_sources\n }\n\n traps = trap_models.TrapModel(trap_param)\n return traps\n\ndef setup_odor_field(wind_field,traps,plot_scale,puff_mol_amount=None,\n puffs=False,xlim=None,ylim=None):\n if traps.num_traps>1:\n #Standard geometry: 6 traps around the center\n plot_size = plot_scale*traps.param['source_radius']\n xlim = (-plot_size, plot_size)\n ylim = (-plot_size, plot_size)\n\n if not(puffs):\n '''This is Will's odor implementation'''\n odor_param = {\n 'wind_field' : wind_field,\n 'diffusion_coeff' : 0.25,\n 'source_locations' : traps.param['source_locations'],\n 'source_strengths' : traps.param['source_strengths'],\n 'epsilon' : 0.01,\n 'trap_radius' : traps.param['trap_radius']\n }\n odor_field = odor_models.FakeDiffusionOdorField(traps,param=odor_param)\n odor_plot_param = {\n 'xlim' : xlim,\n 'ylim' : ylim,\n 'xnum' : 500,\n 'ynum' : 500,\n 'cmap' : 'binary',\n 'fignums' : (1,2)\n }\n plumes=None\n else:\n '''This is the odor puff implementation borrowed/adapted from here: https://github.com/InsectRobotics/pompy'''\n '''Get the odor puff stuff ready'''\n sim_region = puff_models.Rectangle(xlim[0], ylim[0], xlim[1], ylim[1])\n #source_pos = traps.param['source_locations'][4]\n source_pos = scipy.array([scipy.array(tup) for tup in traps.param['source_locations']]).T\n '''*****************'''\n # plumes = puff_models.PlumeModel(sim_region, source_pos, wind_field,\n # puff_release_rate=1.,model_z_disp=False,\n # centre_rel_diff_scale=1.5,\n # puff_init_rad=1.,puff_spread_rate=0.05)\n plumes = puff_models.PlumeModel(sim_region, source_pos, wind_field,\n puff_release_rate=20.,model_z_disp=False,\n centre_rel_diff_scale=1.5,\n puff_init_rad=0.001,puff_spread_rate=0.02)\n\n #Concentration generator object\n grid_size = 1000\n odor_field = puff_models.ConcentrationArrayGenerator(\n sim_region, 0.1, grid_size, grid_size, puff_mol_amount,\n kernel_rad_mult=5)\n #Pompy version---------------------------\n odor_plot_param = {\n 'xlim' : xlim,\n 'ylim' : ylim,\n 'cmap' : 'Purples'}\n return odor_plot_param,odor_field,plumes\n\ndef setup_swarm(swarm_size,wind_field,traps,beta,kappa,start_type,\n upper_prob,t_stop,release_delay=0.,heading_data = None, wind_slippage = (0.,0.),\n upper_threshold=0.002,schmitt_trigger=True, heading_mean=None,\n track_plume_bouts=False,long_casts = False,dt_plot=2.5):\n if wind_field.evolving:\n wind_angle_0 = wind_field.angle[0]\n else:\n wind_angle_0 = wind_field.angle\n release_times = scipy.random.exponential(beta,(swarm_size,)) + release_delay*60.\n if kappa==0:\n dist = scipy.stats.uniform(0.,2*scipy.pi)\n else:\n if heading_mean is None:\n heading_mean = wind_angle_0\n dist= scipy.stats.vonmises(loc=heading_mean,kappa=kappa)\n swarm_param = {\n # 'initial_heading' : scipy.radians(scipy.random.uniform(0.0,360.0,(swarm_size,))),\n 'swarm_size' : swarm_size,\n 'heading_data' : heading_data,\n 'initial_heading_dist': dist,\n 'initial_heading' : scipy.random.vonmises(heading_mean,kappa,(swarm_size,)),\n 'x_start_position' : scipy.zeros((swarm_size,)),\n 'y_start_position' : scipy.zeros((swarm_size,)),\n 'heading_error_std' : scipy.radians(10.0),\n 'flight_speed' : scipy.full((swarm_size,), 0.7),\n #'flight_speed' : scipy.random.uniform(0.3,1.0,(swarm_size,)),\n #'release_time' : scipy.full((swarm_size,), 0.0),\n 'release_time' : release_times,\n 'release_time_constant': beta,\n 'release_delay' : release_delay*60,\n 'cast_interval' : [1.0, 10.0],\n 'wind_slippage' : wind_slippage,\n 'odor_thresholds' : {\n 'lower': 0.002,\n 'upper': upper_threshold\n },\n 'odor_probabilities' : {\n 'lower': 0.9, # detection probability/sec of exposure\n 'upper': upper_prob, # detection probability/sec of exposure\n },\n 'schmitt_trigger':schmitt_trigger,\n 'reset_distribution': scipy.stats.uniform(0,2*scipy.pi),\n 'dt_plot': dt_plot,\n 't_stop':t_stop\n }\n # print(swarm_param['initial_heading_dist'])\n # print(swarm_param['initial_heading_dist'].mean())\n swarm = swarm_models.BasicSwarmOfFlies(wind_field,traps,param=swarm_param,\n start_type=start_type,track_plume_bouts=track_plume_bouts,long_casts = long_casts)\n # time.sleep(10)\n return swarm\n\ndef initial_plot(odor_field,wind_field,plot_param,flies,release_delay,swarm=None,\npompy_wind_model=False,fignum=1,plumes=None,pre_stored=True):\n #Initial odor plots\n plot_dict = {}\n if not(pre_stored):\n plt.ion()\n fig = plt.figure(fignum,dpi=500)\n plot_dict.update({'fig':fig})\n ax = plt.subplot(111)\n plot_dict.update({'ax':ax})\n if isinstance(odor_field,odor_models.FakeDiffusionOdorField):\n #Will's version\n image = odor_field.plot(0.,plot_param=plot_param)\n elif pre_stored:\n image = odor_field.plot(ax,0)\n else:\n #Pompy version\n conc_array = (odor_field.generate_single_array(plumes.puff_array).T[::-1])\n image=odor_field.plot(conc_array,plot_param)\n plot_dict.update({'image':image})\n\n #Sub-dictionary for color codes for the fly modes\n Mode_StartMode = 0\n Mode_FlyUpWind = 1\n Mode_CastForOdor = 2\n Mode_Trapped = 3\n\n color_dict = {Mode_StartMode : 'blue',\n Mode_FlyUpWind : 'red',\n Mode_CastForOdor : 'orange',\n Mode_Trapped : 'black'}\n\n plot_dict.update({'color_dict':color_dict})\n\n #Put the time in the corner\n (xmin,xmax) = ax.get_xlim();(ymin,ymax) = ax.get_ylim()\n text = str(int(release_delay))+' min 0 sec'\n timer= ax.text(xmax,ymax,text,color='r',horizontalalignment='right')\n plot_dict.update({'timer':timer})\n\n plt.figure(fignum)\n plot_dict.update({'fignum':fignum})\n\n if flies:\n fly_colors = [color_dict[mode] for mode in swarm.mode]\n fly_dots = plt.scatter(swarm.x_position, swarm.y_position,color=fly_colors,alpha=0.5)\n plot_dict.update({'fly_dots':fly_dots})\n\n #put an arrow with the wind direction at the top-ish\n arrow_magn = (xmax-xmin)/20\n x_wind,y_wind = wind_field.value(0,0,0)\n wind_arrow = matplotlib.patches.FancyArrowPatch(posA=(\n xmin+(xmax-xmin)/2,ymax-0.2*(ymax-ymin)),posB=\n (xmin+(xmax-xmin)/2+arrow_magn*x_wind,\n ymax-0.2*(ymax-ymin)+arrow_magn*y_wind),\n color='green',mutation_scale=10,arrowstyle='-|>')\n plt.gca().add_patch(wind_arrow)\n plot_dict.update({'wind_arrow':wind_arrow})\n\n if pre_stored:\n x_coords,y_coords = wind_field.get_plotting_points()\n u,v = wind_field.quiver_at_time(0)\n vector_field = ax.quiver(x_coords,y_coords,u,v)\n plot_dict.update({'vector_field':vector_field})\n\n elif pompy_wind_model:\n #To make sure the pompy wind model is space-varying, plot the wind vector field\n velocity_field = wind_field.velocity_field\n u,v = velocity_field[:,:,0],velocity_field[:,:,1]\n x_origins,y_origins = wind_field.x_points,wind_field.y_points\n coords = scipy.array(list(itertools.product(x_origins, y_origins)))\n x_coords,y_coords = coords[:,0],coords[:,1]\n vector_field = ax.quiver(x_coords,y_coords,u,v)\n plot_dict.update({'vector_field':vector_field})\n\n return plot_dict\n" ]
[ [ "matplotlib.pyplot.gca", "scipy.random.vonmises", "matplotlib.pyplot.scatter", "scipy.zeros", "scipy.radians", "scipy.full", "matplotlib.pyplot.subplot", "scipy.stats.uniform", "scipy.cos", "scipy.sin", "scipy.array", "scipy.stats.vonmises", "matplotlib.pyplot.ion", "scipy.random.exponential", "matplotlib.patches.FancyArrowPatch", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
spencer-hong/unilm
[ "4f2b9016789217b565e5a4fd40f2e31dbe83623a" ]
[ "layoutlm/deprecated/layoutlm/modeling/layoutlm.py" ]
[ "import logging\n\nimport torch\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss, MSELoss\nfrom transformers import BertConfig, BertModel, BertPreTrainedModel\n# from transformers.modeling_bert import BertLayerNorm\n\nlogger = logging.getLogger(__name__)\n\nLAYOUTLM_PRETRAINED_MODEL_ARCHIVE_MAP = {}\n\nLAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}\n\n\nclass LayoutlmConfig(BertConfig):\n pretrained_config_archive_map = LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP\n model_type = \"bert\"\n\n def __init__(self, max_2d_position_embeddings=1024, **kwargs):\n super().__init__(**kwargs)\n self.max_2d_position_embeddings = max_2d_position_embeddings\n\n\nclass LayoutlmEmbeddings(nn.Module):\n def __init__(self, config):\n super(LayoutlmEmbeddings, self).__init__()\n self.word_embeddings = nn.Embedding(\n config.vocab_size, config.hidden_size, padding_idx=0\n )\n self.position_embeddings = nn.Embedding(\n config.max_position_embeddings, config.hidden_size\n )\n self.x_position_embeddings = nn.Embedding(\n config.max_2d_position_embeddings, config.hidden_size\n )\n self.y_position_embeddings = nn.Embedding(\n config.max_2d_position_embeddings, config.hidden_size\n )\n self.h_position_embeddings = nn.Embedding(\n config.max_2d_position_embeddings, config.hidden_size\n )\n self.w_position_embeddings = nn.Embedding(\n config.max_2d_position_embeddings, config.hidden_size\n )\n self.token_type_embeddings = nn.Embedding(\n config.type_vocab_size, config.hidden_size\n )\n\n # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load\n # any TensorFlow checkpoint file\n self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(\n self,\n input_ids,\n bbox,\n token_type_ids=None,\n position_ids=None,\n inputs_embeds=None,\n ):\n seq_length = input_ids.size(1)\n if position_ids is None:\n position_ids = torch.arange(\n seq_length, dtype=torch.long, device=input_ids.device\n )\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n words_embeddings = self.word_embeddings(input_ids)\n position_embeddings = self.position_embeddings(position_ids)\n left_position_embeddings = self.x_position_embeddings(bbox[:, :, 0])\n upper_position_embeddings = self.y_position_embeddings(bbox[:, :, 1])\n right_position_embeddings = self.x_position_embeddings(bbox[:, :, 2])\n lower_position_embeddings = self.y_position_embeddings(bbox[:, :, 3])\n h_position_embeddings = self.h_position_embeddings(\n bbox[:, :, 3] - bbox[:, :, 1]\n )\n w_position_embeddings = self.w_position_embeddings(\n bbox[:, :, 2] - bbox[:, :, 0]\n )\n token_type_embeddings = self.token_type_embeddings(token_type_ids)\n\n embeddings = (\n words_embeddings\n + position_embeddings\n + left_position_embeddings\n + upper_position_embeddings\n + right_position_embeddings\n + lower_position_embeddings\n + h_position_embeddings\n + w_position_embeddings\n + token_type_embeddings\n )\n embeddings = self.LayerNorm(embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\n\nclass LayoutlmModel(BertModel):\n\n config_class = LayoutlmConfig\n pretrained_model_archive_map = LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_MAP\n base_model_prefix = \"bert\"\n\n def __init__(self, config):\n super(LayoutlmModel, self).__init__(config)\n self.embeddings = LayoutlmEmbeddings(config)\n self.init_weights()\n\n def forward(\n self,\n input_ids,\n bbox,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n encoder_hidden_states=None,\n encoder_attention_mask=None,\n ):\n if attention_mask is None:\n attention_mask = torch.ones_like(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n extended_attention_mask = extended_attention_mask.to(\n dtype=next(self.parameters()).dtype\n ) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]\n # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]\n if head_mask is not None:\n if head_mask.dim() == 1:\n head_mask = (\n head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)\n )\n head_mask = head_mask.expand(\n self.config.num_hidden_layers, -1, -1, -1, -1\n )\n elif head_mask.dim() == 2:\n head_mask = (\n head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1)\n ) # We can specify head_mask for each layer\n head_mask = head_mask.to(\n dtype=next(self.parameters()).dtype\n ) # switch to fload if need + fp16 compatibility\n else:\n head_mask = [None] * self.config.num_hidden_layers\n\n embedding_output = self.embeddings(\n input_ids, bbox, position_ids=position_ids, token_type_ids=token_type_ids\n )\n encoder_outputs = self.encoder(\n embedding_output, extended_attention_mask, head_mask=head_mask\n )\n sequence_output = encoder_outputs[0]\n pooled_output = self.pooler(sequence_output)\n\n outputs = (sequence_output, pooled_output) + encoder_outputs[\n 1:\n ] # add hidden_states and attentions if they are here\n return outputs # sequence_output, pooled_output, (hidden_states), (attentions)\n\n\nclass LayoutlmForTokenClassification(BertPreTrainedModel):\n config_class = LayoutlmConfig\n pretrained_model_archive_map = LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_MAP\n base_model_prefix = \"bert\"\n\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n self.bert = LayoutlmModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n\n self.init_weights()\n\n def forward(\n self,\n input_ids,\n bbox,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n ):\n\n outputs = self.bert(\n input_ids=input_ids,\n bbox=bbox,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n )\n\n sequence_output = outputs[0]\n\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n outputs = (logits,) + outputs[\n 2:\n ] # add hidden states and attention if they are here\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n # Only keep active parts of the loss\n if attention_mask is not None:\n active_loss = attention_mask.view(-1) == 1\n active_logits = logits.view(-1, self.num_labels)[active_loss]\n active_labels = labels.view(-1)[active_loss]\n loss = loss_fct(active_logits, active_labels)\n else:\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (loss), scores, (hidden_states), (attentions)\n\n\nclass LayoutlmForSequenceClassification(BertPreTrainedModel):\n config_class = LayoutlmConfig\n pretrained_model_archive_map = LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_MAP\n base_model_prefix = \"bert\"\n\n def __init__(self, config):\n super(LayoutlmForSequenceClassification, self).__init__(config)\n self.num_labels = config.num_labels\n\n self.bert = LayoutlmModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)\n\n self.init_weights()\n\n def forward(\n self,\n input_ids,\n bbox,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n ):\n\n outputs = self.bert(\n input_ids=input_ids,\n bbox=bbox,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n )\n\n pooled_output = outputs[1]\n\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n\n outputs = (logits,) + outputs[\n 2:\n ] # add hidden states and attention if they are here\n\n if labels is not None:\n if self.num_labels == 1:\n # We are doing regression\n loss_fct = MSELoss()\n loss = loss_fct(logits.view(-1), labels.view(-1))\n else:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (loss), logits, (hidden_states), (attentions)\n" ]
[ [ "torch.nn.MSELoss", "torch.nn.Dropout", "torch.nn.CrossEntropyLoss", "torch.zeros_like", "torch.nn.Embedding", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.arange", "torch.ones_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
j-Myles/2300-LEED-Project
[ "c8a99c811c4c6e5f2b1b565e5b0d3e9721b70dd1" ]
[ "src/proj/usgbc/table.py" ]
[ "import matplotlib.pyplot as plt\nimport math\n\ndef show(dataframe):\n\n fig = plt.figure(figsize=(10, 5))\n ax = fig.add_subplot(111)\n\n ax.set_title('LEED Buildings by City')\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n\n lbls = ('City', 'Count')\n\n cells = dataframe.values[:10]\n tab = ax.table(cellText=cells, colWidths=[.25, .25],\n colLabels=lbls, loc='center')\n tab.auto_set_font_size(False)\n tab.set_fontsize(8)\n tab.scale(1, 1)\n\n fig.tight_layout()\n plt.show()\n pass\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lanl/PsDNS
[ "2fcb12d52e522906c93d7a28e5397cae81feb376" ]
[ "psdns/tests/test_dns.py" ]
[ "\"\"\"Tests of the DNS solver\n\nDirect-numerical simulation (DNS) of the incompressible Navier-Stokes\nequation is the key capability of PsDNS. This module contains tests\nof the DNS solver.\n\"\"\"\nimport numpy\nfrom numpy import testing as nptest\n\nfrom psdns import *\nfrom psdns.equations.navier_stokes import NavierStokes\n\n#: :meta hide-value:\n#:\n#: Dissipation versus time data from [Brachet1983]_ for code\n#: comparision.\nbrachet_data = numpy.array([\n [0.04939965322977513, 0.007515479870643941],\n [0.18744323150022435, 0.0074550578313179825],\n [0.32539614217164736, 0.0074492781316720935],\n [0.4633274653194921, 0.00745650851290241],\n [0.6011853908871727, 0.00750797316911183],\n [0.7390433164548531, 0.0075594378253212476],\n [0.8768235269376534, 0.0076577387726850105],\n [1.0145562448685834, 0.007784661897976429],\n [1.1522501052570728, 0.007935003168845017],\n [1.2899094256078376, 0.008106160569115537],\n [1.4275428409303093, 0.008292930066437505],\n [1.5651503512244873, 0.00849531166081092],\n [1.702680146433786, 0.008744529546338682],\n [1.8402444816808088, 0.00897293130246451],\n [1.977752689366529, 0.009235159268868476],\n [2.1152522620428185, 0.009502591267622925],\n [2.2527129771766683, 0.009793441411954545],\n [2.390208232348242, 0.010063475426884237],\n [2.5276991700151004, 0.010336111457989168],\n [2.665194425186675, 0.010606145472918858],\n [2.80270695037711, 0.010865771423147583],\n [2.9402367455864082, 0.011114989308675343],\n [3.0777751758051375, 0.01135900316185262],\n [3.2153222410332987, 0.011597812982679413],\n [3.352903846299184, 0.011815806674104277],\n [3.490507039088646, 0.012020790284652935],\n [3.628166359439411, 0.012191947684923455],\n [3.7658472673137533, 0.012350095004317767],\n [3.9035583977211052, 0.012490028210485392],\n [4.032691185946739, 0.012603977234106566],\n [4.165285533578067, 0.012710105817519631],\n [4.303074379070299, 0.012803202732532909],\n [4.440897764600256, 0.01287548351814426],\n [4.578747055158504, 0.012932152206704161],\n [4.716630885754478, 0.012968004765862132],\n [4.840763463831408, 0.012977894729997233],\n [4.992502167059599, 0.012977261495972284],\n [5.130498252778178, 0.01294546163457398],\n [5.268507291010902, 0.012905855724649952],\n [5.4065638217954985, 0.012837627636798271],\n [5.54466352762725, 0.012743379387194177],\n [5.682811788433499, 0.01261986867295962],\n [5.820940654375634, 0.012508046596831643],\n [5.959143980320558, 0.012351349959021755],\n [6.097377528798492, 0.012176439207985178],\n [6.235632664800003, 0.011988518376072396],\n [6.373918023334524, 0.011782383430932925],\n [6.512242239411485, 0.01155283034021628],\n [6.650566455488446, 0.011323277249499636],\n [6.788899306574836, 0.01108852012643251],\n [6.913940708092023, 0.010864076610406464],\n [7.0656211363089225, 0.01058517967002012],\n [7.204031702480193, 0.010303586255798651],\n [7.342420681127888, 0.010035002922453387],\n [7.480723309681271, 0.00981845991261295],\n [7.5915752432531525, 0.009518767518623872],\n [7.695646671297676, 0.009305459789123272],\n [7.840695265340693, 0.009023348244196287],\n [7.979088561493103, 0.008752162894675784],\n [8.117516397683236, 0.008460161415753346],\n [8.255901058826215, 0.008194180098583324],\n [8.394298672483341, 0.007920392732887579],\n [8.532687651131031, 0.007651809399542315],\n [8.671055042255148, 0.0073962361470732586],\n [8.809400845855688, 0.007153672975480408],\n [8.947763919475086, 0.0069007017391865925],\n [9.086096770561479, 0.006665944616119466],\n [9.224429621647872, 0.00643118749305234],\n [9.362771107743693, 0.00619122633763473],\n [9.501086688811224, 0.005966877279268567],\n [9.639397952374036, 0.0057451302370776485],\n [9.77767035839441, 0.005546801340463902],\n [9.902109479306144, 0.005371948156156867], ]).T\n\n\nclass TestDiagnostics(Diagnostic):\n \"\"\"Diagnostics for DNS testing\n\n The normal diagnostics provided in :mod:`~psdns.diagnostics`\n output information to a file. This class saves diagnostics data\n to an internal data structure so it can easily be used for\n assertion tests.\n \"\"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n #: A list of output data. Each element is a tuple containing\n #: the simulation time and dissipation rate.\n self.dumps = []\n\n def diagnostic(self, time, equations, uhat):\n eps = [(1j*uhat.grid.k[i]*uhat[j]).to_physical().norm()\n for i in range(3) for j in range(3)]\n if uhat.grid.comm.rank == 0:\n self.dumps.append((time, equations.nu*sum(eps)))\n\n\nclass TestDNS(tests.TestCase):\n \"\"\"DNS testing by validation against data in the literature.\n \"\"\"\n def test_Brachet_Re100(self):\n \"\"\"Comparision of DNS to Brachet (1983) data, Re=100\n\n Perform a code-to-code comparison to the Taylor-Green vortex\n simulations of [Brachet1983]_. In order to obtain convergence\n at a very low resolution, the Reynolds number 100 case is\n used. This is a low-Reynolds number case run at coarse\n resolution and high tolerance. It is at about the limit of\n the acceptable run time for a unit test (currently about 16\n seconds on a 2.8 GHz Intel i7).\n\n It is worth noting that this test uses 15 spectral modes, an odd\n number, consistent with the discussion in :ref:`Keeping It\n Real`. If 16 modes are used instead, the results are slightly\n worse, but the test will still pass with the current tolerances.\n If :class:`~psdns.bases.SpectralGrid` is created with\n ``aliasing_strategy='mpi4py'``, and an even number of modes,\n then many more modes are needed to acheive convergence.\n\n .. figure:: fig/test_dns.TestDNS.test_Brachet_Re100.png\n\n PsDNS results for a 3-d DNS of the Taylor-Green vortex\n compared to the results reported by [Brachet1983]_.\n \"\"\"\n grid = SpectralGrid(sdims=2**4-1, pdims=3*2**3)\n equations = NavierStokes(Re=100)\n solver = RungeKutta(\n dt=0.01,\n tfinal=10.0,\n equations=equations,\n ic=equations.taylor_green_vortex(\n grid\n ),\n diagnostics=[\n TestDiagnostics(tdump=0.1, grid=grid)\n ]\n )\n solver.run()\n if solver.uhat.grid.comm.rank == 0:\n output = numpy.array(solver.diagnostics_list[0].dumps).T\n with self.subplots() as (fig, ax):\n ax.plot(\n brachet_data[0],\n brachet_data[1],\n label=\"Brachet (1993)\"\n )\n ax.plot(output[0], output[1], label=\"This code\")\n ax.set_title(\"Comparision to published data\")\n ax.set_xlabel(\"Time\")\n ax.set_ylabel(\"Dissiapation Rate\")\n ax.legend()\n nptest.assert_allclose(\n output[1],\n numpy.interp(output[0], brachet_data[0], brachet_data[1]),\n rtol=0.06, atol=0\n )\n" ]
[ [ "numpy.array", "numpy.interp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
VladimirYugay/PIFu
[ "8f80e7ee539098e53c419a518f6f180dbdec97c5" ]
[ "lib/colab_util.py" ]
[ "import io\nimport os\nimport torch\nfrom skimage.io import imread\nimport numpy as np\nimport cv2\nfrom tqdm import tqdm_notebook as tqdm\nimport base64\nfrom IPython.display import HTML\n\n# Util function for loading meshes\nfrom pytorch3d.io import load_objs_as_meshes\n\nfrom IPython.display import HTML\nfrom base64 import b64encode\n\n# Data structures and functions for rendering\nfrom pytorch3d.structures import Meshes\nfrom pytorch3d.renderer import (\n look_at_view_transform,\n OpenGLOrthographicCameras,\n PointLights,\n DirectionalLights,\n Materials,\n RasterizationSettings,\n MeshRenderer,\n MeshRasterizer,\n SoftPhongShader,\n HardPhongShader,\n TexturesVertex\n)\n\n\ndef set_renderer():\n # Setup\n device = torch.device(\"cuda:0\")\n torch.cuda.set_device(device)\n\n # Initialize an OpenGL perspective camera.\n R, T = look_at_view_transform(2.0, 0, 180)\n cameras = OpenGLOrthographicCameras(device=device, R=R, T=T)\n\n raster_settings = RasterizationSettings(\n image_size=512,\n blur_radius=0.0,\n faces_per_pixel=1,\n bin_size=None,\n max_faces_per_bin=None\n )\n\n lights = PointLights(device=device, location=((2.0, 2.0, 2.0),))\n\n renderer = MeshRenderer(\n rasterizer=MeshRasterizer(\n cameras=cameras,\n raster_settings=raster_settings\n ),\n shader=HardPhongShader(\n device=device,\n cameras=cameras,\n lights=lights\n )\n )\n return renderer\n\n\ndef get_verts_rgb_colors(obj_path):\n rgb_colors = []\n\n f = open(obj_path)\n lines = f.readlines()\n for line in lines:\n ls = line.split(' ')\n if len(ls) == 7:\n rgb_colors.append(ls[-3:])\n\n return np.array(rgb_colors, dtype='float32')[None, :, :]\n\n\ndef generate_video_from_obj(obj_path, video_path, renderer):\n # Setup\n device = torch.device(\"cuda:0\")\n torch.cuda.set_device(device)\n\n # Load obj file\n verts_rgb_colors = get_verts_rgb_colors(obj_path)\n verts_rgb_colors = torch.from_numpy(verts_rgb_colors).to(device)\n textures = TexturesVertex(verts_features=verts_rgb_colors)\n wo_textures = TexturesVertex(verts_features=torch.ones_like(verts_rgb_colors) * 0.75)\n\n # Load obj\n mesh = load_objs_as_meshes([obj_path], device=device)\n\n # Set mesh\n vers = mesh._verts_list\n faces = mesh._faces_list\n mesh_w_tex = Meshes(vers, faces, textures)\n mesh_wo_tex = Meshes(vers, faces, wo_textures)\n\n # create VideoWriter\n fourcc = cv2.VideoWriter_fourcc(*'MP4V')\n out = cv2.VideoWriter(video_path, fourcc, 20.0, (1024, 512))\n\n for i in tqdm(range(90)):\n R, T = look_at_view_transform(1.8, 0, i * 4, device=device)\n images_w_tex = renderer(mesh_w_tex, R=R, T=T)\n images_w_tex = np.clip(images_w_tex[0, ..., :3].cpu().numpy(), 0.0, 1.0)[:, :, ::-1] * 255\n images_wo_tex = renderer(mesh_wo_tex, R=R, T=T)\n images_wo_tex = np.clip(images_wo_tex[0, ..., :3].cpu().numpy(), 0.0, 1.0)[:, :, ::-1] * 255\n image = np.concatenate([images_w_tex, images_wo_tex], axis=1)\n out.write(image.astype('uint8'))\n out.release()\n\n\ndef video(path):\n mp4 = open(path, 'rb').read()\n data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n return HTML('<video width=500 controls loop> <source src=\"%s\" type=\"video/mp4\"></video>' % data_url)\n" ]
[ [ "torch.cuda.set_device", "torch.from_numpy", "numpy.concatenate", "torch.device", "numpy.array", "torch.ones_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
alestolfo/jiant
[ "31efcd3b54ec4d84403854b1a4ce321a2792b503" ]
[ "jiant/tasks/evaluate/core.py" ]
[ "import itertools\nimport json\n\nfrom dataclasses import dataclass\n\nimport numpy as np\nimport pandas as pd\nimport seqeval.metrics as seqeval_metrics\nimport torch\n\nfrom scipy.stats import pearsonr\nfrom scipy.stats import spearmanr\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import matthews_corrcoef\nfrom typing import Dict\nfrom typing import List\n\nimport jiant.shared.model_resolution as model_resolution\n\nimport jiant.tasks.lib.bucc2018 as bucc2018_lib\nimport jiant.tasks.lib.mlqa as mlqa_lib\nimport jiant.tasks.lib.tatoeba as tatoeba_lib\nimport jiant.tasks.lib.templates.squad_style.core as squad_style\nimport jiant.tasks.lib.templates.squad_style.utils as squad_style_utils\n\nimport jiant.tasks.retrieval as tasks_retrieval\n\nfrom jiant.tasks.lib.templates import mlm as mlm_template\nfrom jiant.utils.python.datastructures import ExtendedDataClassMixin\nfrom jiant.utils.python.io import read_json\nfrom jiant.utils.string_comparing import exact_match_score\nfrom jiant.utils.string_comparing import string_f1_score\n\n\n@dataclass\nclass Metrics(ExtendedDataClassMixin):\n major: float\n minor: Dict\n\n\nclass BaseEvaluation:\n pass\n\n\nclass BaseAccumulator:\n def update(self, batch_logits, batch_loss, batch, batch_metadata):\n raise NotImplementedError()\n\n def get_guids(self):\n return None\n\n def get_accumulated(self):\n raise NotImplementedError()\n\n\nclass BaseEvaluationScheme:\n def get_accumulator(self) -> BaseAccumulator:\n raise NotImplementedError()\n\n def get_labels_from_cache_and_examples(self, task, cache, examples):\n # Depending on the task, labels may be more easily extracted from\n # a cache or raw examples.\n # Provide the EvaluationScheme with either, but delegate to another function\n # using only one.\n raise NotImplementedError()\n\n def get_preds_from_accumulator(self, task, accumulator):\n raise NotImplementedError()\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: BaseAccumulator, tokenizer, labels\n ) -> Metrics:\n raise NotImplementedError()\n\n\nclass ConcatenateLogitsAccumulator(BaseAccumulator):\n def __init__(self):\n self.logits_list = []\n self.guid_list = []\n\n def update(self, batch_logits, batch_loss, batch, batch_metadata):\n self.logits_list.append(batch_logits)\n batch_guid = batch_metadata.get(\"guid\")\n if batch_guid is not None:\n self.guid_list.append(batch_guid)\n\n def get_guids(self):\n if self.guid_list:\n return np.concatenate(self.guid_list)\n else:\n return None\n\n def get_accumulated(self):\n all_logits = np.concatenate(self.logits_list)\n return all_logits\n\n\nclass ConcatenateLossAccumulator(BaseAccumulator):\n def __init__(self):\n self.loss_list = []\n\n def update(self, batch_logits, batch_loss, batch, batch_metadata):\n self.loss_list.append(batch_loss)\n\n def get_accumulated(self):\n all_loss = np.array(self.loss_list)\n return all_loss\n\n\nclass ConcatenateStringListAccumulator(BaseAccumulator):\n def __init__(self):\n self.str_list = []\n\n def update(self, batch_logits, batch_loss, batch, batch_metadata):\n bs = len(batch_logits)\n span_pred = batch_logits.argmax(axis=1)\n pred_token_start, pred_token_end = span_pred[:, 0], span_pred[:, 1]\n pred_char_start = batch.token_idx_to_char_idx_start.cpu().numpy()[\n range(bs), pred_token_start\n ]\n pred_char_end = batch.token_idx_to_char_idx_end.cpu().numpy()[range(bs), pred_token_end]\n self.str_list.extend(\n [\n s[i1 : i2 + 1]\n for i1, i2, s in zip(pred_char_start, pred_char_end, batch.selection_str)\n ]\n )\n\n def get_accumulated(self):\n return self.str_list\n\n\nclass SpanPredictionF1andEMScheme(BaseEvaluationScheme):\n def get_accumulator(self):\n return ConcatenateStringListAccumulator()\n\n def get_labels_from_cache_and_examples(self, task, cache, examples):\n return [datum[\"data_row\"].gt_span_str for datum in cache.iter_all()]\n\n def get_preds_from_accumulator(self, task, accumulator):\n return accumulator.get_accumulated()\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n em = sum([exact_match_score(s1, s2) for s1, s2 in zip(preds, labels)]) / len(labels)\n f1 = sum([string_f1_score(s1, s2) for s1, s2 in zip(preds, labels)]) / len(labels)\n scores = {\"f1\": f1, \"em\": em, \"avg\": (f1 + em) / 2}\n return Metrics(major=scores[\"avg\"], minor=scores)\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: ConcatenateStringListAccumulator, tokenizer, labels: list\n ) -> Metrics:\n preds = self.get_preds_from_accumulator(task=task, accumulator=accumulator)\n return self.compute_metrics_from_preds_and_labels(preds=preds, labels=labels)\n\n\nclass RecordAccumulator(ConcatenateLogitsAccumulator):\n def __init__(self):\n super().__init__()\n self.entity_strs = []\n self.gold_label_list = []\n\n def update(self, batch_logits, batch_loss, batch, batch_metadata):\n super().update(batch_logits, batch_loss, batch, batch_metadata)\n self.entity_strs.extend(batch.entity_str)\n self.gold_label_list.extend(batch.label_set)\n\n def get_accumulated(self):\n return super().get_accumulated(), self.entity_strs\n\n def get_gold_label_list(self):\n return self.gold_label_list\n\n\nclass MLMPremaskedAccumulator(BaseAccumulator):\n def __init__(self):\n self.loss_list = []\n self.logits_list = []\n\n def update(self, batch_logits, batch_loss, batch, batch_metadata):\n batch_size = len(batch)\n # Select the tokens that we do MLM prediction on\n masked_tokens_selector = (\n batch.masked_lm_labels.cpu().numpy() != mlm_template.NON_MASKED_TOKEN_LABEL_ID\n )\n for i in range(batch_size):\n # noinspection PyUnresolvedReferences\n self.logits_list.append(batch_logits[i][masked_tokens_selector[i]])\n self.loss_list.append(batch_loss)\n\n def get_accumulated(self):\n return self.loss_list, self.logits_list\n\n\nclass TatoebaAccumulator(BaseAccumulator):\n def __init__(self):\n self.embeddings_list = []\n self.is_english_list = []\n\n def update(self, batch_logits, batch_loss, batch, batch_metadata):\n self.embeddings_list.append(batch_logits)\n self.is_english_list.append(batch.is_english.cpu().numpy())\n\n @classmethod\n def get_guids(cls):\n return None\n\n def get_accumulated(self):\n all_embeddings = np.concatenate(self.embeddings_list)\n is_english_arr = np.concatenate(self.is_english_list).astype(bool)\n return all_embeddings, is_english_arr\n\n\nclass Bucc2018Accumulator(BaseAccumulator):\n def __init__(self):\n self.embeddings_list = []\n self.is_english_list = []\n self.text_hash_list = []\n self.guid_list = []\n\n def update(self, batch_logits, batch_loss, batch, batch_metadata):\n self.embeddings_list.append(batch_logits)\n self.is_english_list.append(batch.is_english.cpu().numpy())\n self.text_hash_list += batch.text_hash\n self.guid_list += batch.guid\n\n @classmethod\n def get_guids(cls):\n return None\n\n def get_accumulated(self):\n return {\n \"all_embeddings\": np.concatenate(self.embeddings_list),\n \"is_english_arr\": np.concatenate(self.is_english_list).astype(bool),\n \"text_hash_list\": self.text_hash_list,\n \"guid_list\": self.guid_list,\n }\n\n\nclass BaseLogitsEvaluationScheme(BaseEvaluationScheme):\n def get_accumulator(self):\n return ConcatenateLogitsAccumulator()\n\n def get_labels_from_cache_and_examples(self, task, cache, examples):\n return get_label_ids_from_cache(cache=cache)\n\n def get_preds_from_accumulator(self, task, accumulator):\n raise NotImplementedError()\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: ConcatenateLogitsAccumulator, tokenizer, labels: list\n ) -> Metrics:\n preds = self.get_preds_from_accumulator(task=task, accumulator=accumulator)\n return self.compute_metrics_from_preds_and_labels(preds=preds, labels=labels)\n\n def compute_metrics_from_preds_and_labels(self, preds, labels):\n raise NotImplementedError()\n\n\nclass SimpleAccuracyEvaluationScheme(BaseLogitsEvaluationScheme):\n @classmethod\n def get_preds_from_accumulator(cls, task, accumulator):\n logits = accumulator.get_accumulated()\n return np.argmax(logits, axis=1)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n # noinspection PyUnresolvedReferences\n acc = float((preds == labels).mean())\n return Metrics(major=acc, minor={\"acc\": acc})\n\n\nclass MCTACOEvaluationScheme(BaseLogitsEvaluationScheme):\n @classmethod\n def get_preds_from_accumulator(self, task, accumulator):\n logits = accumulator.get_accumulated()\n pred = np.argmax(logits, axis=1)\n guid = accumulator.get_guids()\n return guid, pred\n\n @classmethod\n def compute_metrics_from_accumulator(self, task, accumulator, tokenizer, labels) -> Metrics:\n guid, pred = self.get_preds_from_accumulator(task=task, accumulator=accumulator)\n em_ls = []\n f1_ls = []\n label_pred_by_question = {}\n\n for one_guid, one_pred, one_label in zip(guid, pred, labels):\n split, question_id, example_id = one_guid.split(\"-\")\n if question_id not in label_pred_by_question:\n label_pred_by_question[question_id] = [], []\n label_pred_by_question[question_id][0].append(one_label)\n label_pred_by_question[question_id][1].append(one_pred)\n\n em_ls = [\n float(group_label == group_pred)\n for group_label, group_pred in label_pred_by_question.values()\n ]\n f1_ls = [\n f1_score(y_true=group_label, y_pred=group_pred)\n for group_label, group_pred in label_pred_by_question.values()\n ]\n\n em = sum(em_ls) / len(em_ls)\n f1 = sum(f1_ls) / len(f1_ls)\n minor = {\n \"em\": em,\n \"f1\": f1,\n \"f1_em\": (f1 + em) / 2,\n }\n metrics = Metrics(major=minor[\"f1_em\"], minor=minor,)\n return metrics\n\n\nclass MultiLabelAccAndF1EvaluationScheme(BaseLogitsEvaluationScheme):\n def get_labels_from_cache_and_examples(self, task, cache, examples):\n return get_multi_label_ids_from_cache(cache=cache)\n\n def get_preds_from_accumulator(self, task, accumulator):\n logits = accumulator.get_accumulated()\n # alessandro: change the 0.5 to 0 as the logits are raw and not passed through a sigmoid\n return (logits > 0).astype(int)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n # noinspection PyUnresolvedReferences\n acc = float((preds == labels).mean())\n labels = np.array(labels)\n #for b in range(len(labels)):\n # print('preds', preds[b])\n # print('labels', labels[b])\n minor = {\n \"acc\": acc,\n \"f1_micro\": f1_score(y_true=labels, y_pred=preds, average=\"micro\"),\n \"acc_and_f1_micro\": (acc + f1_score(y_true=labels, y_pred=preds, average=\"micro\")) / 2,\n }\n #alessandro: use f1_micro as major\n return Metrics(major=minor[\"f1_micro\"], minor=minor)\n\n\nclass AccAndF1EvaluationScheme(BaseLogitsEvaluationScheme):\n def get_preds_from_accumulator(self, task, accumulator):\n logits = accumulator.get_accumulated()\n return np.argmax(logits, axis=1)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n # noinspection PyUnresolvedReferences\n acc = float((preds == labels).mean())\n labels = np.array(labels)\n f1 = f1_score(y_true=labels, y_pred=preds)\n minor = {\n \"acc\": acc,\n \"f1\": f1,\n \"acc_and_f1\": (acc + f1) / 2,\n }\n return Metrics(major=minor[\"acc_and_f1\"], minor=minor)\n\n\nclass MCCEvaluationScheme(BaseLogitsEvaluationScheme):\n def get_preds_from_accumulator(self, task, accumulator):\n logits = accumulator.get_accumulated()\n return np.argmax(logits, axis=1)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n mcc = matthews_corrcoef(labels, preds)\n return Metrics(major=mcc, minor={\"mcc\": mcc})\n\n\nclass PearsonAndSpearmanEvaluationScheme(BaseLogitsEvaluationScheme):\n def get_labels_from_cache_and_examples(self, task, cache, examples):\n return get_label_vals_from_cache(cache=cache)\n\n def get_preds_from_accumulator(self, task, accumulator):\n logits = accumulator.get_accumulated()\n return np.squeeze(logits, axis=-1)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n pearson_corr = float(pearsonr(preds, labels)[0])\n spearman_corr = float(spearmanr(preds, labels)[0])\n minor = {\n \"pearson\": pearson_corr,\n \"spearmanr\": spearman_corr,\n \"corr\": (pearson_corr + spearman_corr) / 2,\n }\n return Metrics(major=minor[\"corr\"], minor=minor)\n\n\nclass MultipleChoiceAccuracyEvaluationScheme(BaseLogitsEvaluationScheme):\n def get_accumulator(self):\n return ConcatenateLogitsAccumulator()\n\n @classmethod\n def get_labels_from_examples(cls, task, examples):\n return get_multiple_choice_label_ids_from_examples(task=task, examples=examples)\n\n def get_labels_from_cache_and_examples(self, task, cache, examples):\n return get_multiple_choice_labels_from_cache(cache=cache)\n\n def get_preds_from_accumulator(self, task, accumulator):\n return SimpleAccuracyEvaluationScheme.get_preds_from_accumulator(\n task=task, accumulator=accumulator,\n )\n\n def compute_metrics_from_preds_and_labels(self, preds, labels):\n return SimpleAccuracyEvaluationScheme.compute_metrics_from_preds_and_labels(\n preds=preds, labels=labels\n )\n\n\nclass CommitmentBankEvaluationScheme(BaseLogitsEvaluationScheme):\n def get_preds_from_accumulator(self, task, accumulator):\n logits = accumulator.get_accumulated()\n return np.argmax(logits, axis=1)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n # noinspection PyUnresolvedReferences\n acc = float((preds == labels).mean())\n labels = np.array(labels)\n f11 = f1_score(y_true=labels == 0, y_pred=preds == 0)\n f12 = f1_score(y_true=labels == 1, y_pred=preds == 1)\n f13 = f1_score(y_true=labels == 2, y_pred=preds == 2)\n avg_f1 = mean(f11, f12, f13)\n return Metrics(\n major=mean(acc, avg_f1),\n minor={\"acc\": acc, \"avg_f1\": avg_f1, \"f11\": f11, \"f12\": f12, \"f13\": f13},\n )\n\n\nclass MultiRCEvaluationScheme(BaseEvaluationScheme):\n def get_accumulator(self):\n return ConcatenateLogitsAccumulator()\n\n @classmethod\n def get_labels_from_examples(cls, task, examples):\n label_values = get_label_ids(examples=examples, task=task)\n question_ids = np.array([example.question_id for example in examples])\n assert len(label_values) == len(question_ids)\n return [\n {\"label_values\": lab, \"question_ids\": qid}\n for lab, qid in zip(label_values, question_ids)\n ]\n\n @classmethod\n def get_labels_from_cache(cls, cache):\n label_values = []\n question_ids = []\n for datum in cache.iter_all():\n label_values.append(datum[\"data_row\"].label_id)\n question_ids.append(datum[\"data_row\"].question_id)\n label_values = np.array(label_values)\n question_ids = np.array(question_ids)\n assert len(label_values) == len(question_ids)\n return [\n {\"label_values\": lab, \"question_ids\": qid}\n for lab, qid in zip(label_values, question_ids)\n ]\n\n def get_labels_from_cache_and_examples(self, task, cache, examples):\n return self.get_labels_from_examples(task=task, examples=examples)\n\n def get_preds_from_accumulator(self, task, accumulator):\n logits = accumulator.get_accumulated()\n return np.argmax(logits, axis=-1)\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: ConcatenateLogitsAccumulator, tokenizer, labels: list\n ) -> Metrics:\n preds = self.get_preds_from_accumulator(task=task, accumulator=accumulator)\n return self.compute_metrics_from_preds_and_labels(preds=preds, labels=labels,)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n df = pd.DataFrame(labels)\n assert \"label_values\" in df.columns\n assert \"question_ids\" in df.columns\n df[\"preds\"] = preds\n # noinspection PyUnresolvedReferences\n exact_match = (\n df.groupby(\"question_ids\")\n .apply(lambda _: (_[\"preds\"] == _[\"label_values\"]).all())\n .mean()\n )\n exact_match = float(exact_match)\n f1 = f1_score(y_true=df[\"label_values\"], y_pred=df[\"preds\"])\n return Metrics(major=mean(exact_match, f1), minor={\"em\": exact_match, \"f1\": f1},)\n\n\n@dataclass\nclass RecordLabelData:\n passage_idx: int\n question_idx: int\n entity_str: str\n answers_dict: Dict[str, str]\n\n\nclass ReCordEvaluationScheme(BaseEvaluationScheme):\n def get_accumulator(self):\n return RecordAccumulator()\n\n @classmethod\n def get_labels_from_examples(cls, examples):\n return [\n RecordLabelData(\n passage_idx=example.passage_idx,\n question_idx=example.question_idx,\n entity_str=example.entity_str,\n answers_dict=example.answers_dict,\n )\n for example in examples\n ]\n\n @classmethod\n def get_labels_from_cache_and_examples(cls, task, cache, examples):\n return cls.get_labels_from_examples(examples=examples)\n\n @classmethod\n def get_preds_from_accumulator(cls, task, accumulator):\n logits, entity_strs = accumulator.get_accumulated()\n guid_list = accumulator.get_guids()\n\n question_ids = []\n for guid in guid_list:\n question_ids.append(guid.split(\"-\")[2])\n\n # group logits by question id then reorder for submission\n # need question id, logit, and entity_str\n # for example, dict of question id to logit and entity_str\n max_logits = {}\n for logit, entity_str, question_id in zip(logits, entity_strs, question_ids):\n if (question_id not in max_logits) or (max_logits[question_id][\"logit\"][1] < logit[1]):\n max_logits[question_id] = {\"logit\": logit, \"entity_str\": entity_str}\n\n # Convert labels of max_logits to prediction format\n preds = []\n for question_idx, logit_entity in max_logits.items():\n preds.append({\"idx\": question_idx, \"label\": logit_entity[\"entity_str\"]})\n\n return preds\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: RecordAccumulator, tokenizer, labels: List\n ) -> Metrics:\n predictions_dict, metrics = self.compute_preds_and_metrics(task, accumulator)\n return metrics\n\n @classmethod\n def compute_preds_and_metrics(cls, task, accumulator):\n f1_ls = []\n em_ls = []\n predictions_dict = {}\n\n preds = cls.get_preds_from_accumulator(task, accumulator)\n guid_list = accumulator.get_guids()\n gold_label_list_of_sets = accumulator.get_gold_label_list()\n\n question_ids = []\n for guid in guid_list:\n question_ids.append(guid.split(\"-\")[2])\n\n # Reduce list of gold label sets to a gold label set per question_id\n gold_labels = {}\n for question_id, gold_label_set in zip(question_ids, gold_label_list_of_sets):\n if question_id in gold_labels:\n assert gold_label_set == gold_labels[question_id]\n else:\n gold_labels[question_id] = gold_label_set\n\n for pred, gold_label_set in zip(preds, gold_labels.values()):\n pred_ans = pred[\"label\"]\n\n # F1\n f1 = cls.metric_max_over_ground_truths(string_f1_score, pred_ans, gold_label_set)\n f1_ls.append(f1)\n\n # EM\n em = cls.metric_max_over_ground_truths(exact_match_score, pred_ans, gold_label_set)\n em_ls.append(em)\n\n em = sum(em_ls) / len(em_ls)\n f1 = sum(f1_ls) / len(f1_ls)\n minor = {\n \"em\": em,\n \"f1\": f1,\n \"f1_em\": (f1 + em) / 2,\n }\n metrics = Metrics(major=minor[\"f1_em\"], minor=minor,)\n return predictions_dict, metrics\n\n @classmethod\n def metric_max_over_ground_truths(cls, metric_fn, prediction, ground_truths):\n \"\"\"Compute max metric between prediction and each ground truth.\n From official ReCoRD eval script\n \"\"\"\n scores_for_ground_truths = []\n for ground_truth in ground_truths:\n score = metric_fn(prediction, ground_truth)\n scores_for_ground_truths.append(score)\n return max(scores_for_ground_truths)\n\n\nclass CCGEvaluationScheme(BaseEvaluationScheme):\n def get_accumulator(self):\n return ConcatenateLogitsAccumulator()\n\n @classmethod\n def get_label_ids_from_cache(cls, cache):\n return [\n {\"label_ids\": datum[\"data_row\"].label_ids, \"label_mask\": datum[\"data_row\"].label_mask}\n for datum in cache.iter_all()\n ]\n\n @classmethod\n def get_labels_from_cache_and_examples(cls, task, cache, examples):\n return cls.get_label_ids_from_cache(cache=cache)\n\n def get_preds_from_accumulator(self, task, accumulator):\n logits = accumulator.get_accumulated()\n return np.argmax(logits, axis=-1)\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: ConcatenateLogitsAccumulator, tokenizer, labels: list\n ) -> Metrics:\n preds = self.get_preds_from_accumulator(task=task, accumulator=accumulator)\n return self.compute_metrics_from_preds_and_labels(preds=preds, labels=labels,)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n label_ids = np.stack([row[\"label_ids\"] for row in labels])\n label_mask = np.stack([row[\"label_mask\"] for row in labels])\n\n # Account for smart-truncate\n assert (label_mask[:, preds.shape[-1] :] == 0).all()\n label_ids = label_ids[:, : preds.shape[-1]]\n label_mask = label_mask[:, : preds.shape[-1]]\n\n bool_mask = label_mask.reshape(-1).astype(bool)\n flat_preds = preds.reshape(-1)[bool_mask]\n flat_labels = label_ids.reshape(-1)[bool_mask]\n return cls.compute_metrics_from_flat_preds_and_labels(\n flat_preds=flat_preds, flat_labels=flat_labels,\n )\n\n @classmethod\n def compute_metrics_from_flat_preds_and_labels(cls, flat_preds, flat_labels):\n return SimpleAccuracyEvaluationScheme.compute_metrics_from_preds_and_labels(\n preds=flat_preds, labels=flat_labels,\n )\n\n\nclass F1TaggingEvaluationScheme(BaseEvaluationScheme):\n def get_accumulator(self):\n return ConcatenateLogitsAccumulator()\n\n @classmethod\n def get_labels_from_cache_and_examples(cls, task, cache, examples):\n labels = []\n for datum in cache.iter_all():\n label_mask = datum[\"data_row\"].label_mask.astype(bool)\n pos_list = [\n task.ID_TO_LABEL[pos_id] for pos_id in datum[\"data_row\"].label_ids[label_mask]\n ]\n label = {\n \"pos_list\": pos_list,\n \"label_mask\": label_mask,\n }\n labels.append(label)\n assert len(pos_list) == label_mask.sum()\n return labels\n\n def get_preds_from_accumulator(self, task, accumulator):\n logits = accumulator.get_accumulated()\n return np.argmax(logits, axis=-1)\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: ConcatenateLogitsAccumulator, tokenizer, labels: list\n ) -> Metrics:\n preds = self.get_preds_from_accumulator(task=task, accumulator=accumulator)\n return self.compute_metrics_from_preds_and_labels(task=task, preds=preds, labels=labels,)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, task, preds, labels):\n label_mask = np.stack([row[\"label_mask\"] for row in labels])\n\n # Account for smart-truncate\n assert (label_mask[:, preds.shape[-1] :] == 0).all()\n label_mask = label_mask[:, : preds.shape[-1]]\n\n labels_for_eval = [label[\"pos_list\"] for label in labels]\n preds_for_eval = []\n assert len(labels) == preds.shape[0]\n for i in range(len(labels)):\n relevant_preds = preds[i][label_mask[i]]\n relevant_preds_pos = [task.ID_TO_LABEL[pos_id] for pos_id in relevant_preds]\n preds_for_eval.append(relevant_preds_pos)\n\n minor = {\n \"precision\": seqeval_metrics.precision_score(labels_for_eval, preds_for_eval),\n \"recall\": seqeval_metrics.recall_score(labels_for_eval, preds_for_eval),\n \"f1\": seqeval_metrics.f1_score(labels_for_eval, preds_for_eval),\n }\n return Metrics(major=minor[\"f1\"], minor=minor,)\n\n\nclass SQuADEvaluationScheme(BaseEvaluationScheme):\n @classmethod\n def get_accumulator(cls) -> BaseAccumulator:\n return ConcatenateLogitsAccumulator()\n\n @classmethod\n def get_labels_from_cache(cls, cache):\n return [cls.get_label_from_data_row(datum[\"data_row\"]) for datum in cache.iter_all()]\n\n @classmethod\n def get_labels_from_cache_and_examples(cls, task, cache, examples):\n return cls.get_labels_from_cache(cache=cache)\n\n def get_preds_from_accumulator(self, task, accumulator):\n raise NotImplementedError(\"Currently can't be done without access to dataset\")\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: BaseAccumulator, tokenizer, labels\n ) -> Metrics:\n logits = accumulator.get_accumulated()\n results, predictions = squad_style.compute_predictions_logits_v3(\n data_rows=labels,\n logits=logits,\n n_best_size=task.n_best_size,\n max_answer_length=task.max_answer_length,\n do_lower_case=model_resolution.resolve_is_lower_case(tokenizer),\n version_2_with_negative=task.version_2_with_negative,\n null_score_diff_threshold=task.null_score_diff_threshold,\n tokenizer=tokenizer,\n )\n if task.version_2_with_negative:\n # Return the score after the best thresholds for answering has been selected\n return Metrics(major=(results[\"best_f1\"] + results[\"best_exact\"]) / 2, minor=results)\n else:\n return Metrics(major=(results[\"f1\"] + results[\"exact\"]) / 2, minor=results)\n\n @classmethod\n def get_label_from_data_row(cls, data_row):\n return squad_style.PartialDataRow.from_data_row(data_row)\n\n\nclass XlingQAEvaluationScheme(BaseEvaluationScheme):\n @classmethod\n def get_accumulator(cls) -> BaseAccumulator:\n return ConcatenateLogitsAccumulator()\n\n @classmethod\n def get_labels_from_cache(cls, cache):\n return [cls.get_label_from_data_row(datum[\"data_row\"]) for datum in cache.iter_all()]\n\n @classmethod\n def get_labels_from_cache_and_examples(cls, task, cache, examples):\n return cls.get_labels_from_cache(cache=cache)\n\n def get_preds_from_accumulator(self, task, accumulator):\n raise NotImplementedError(\"Currently can't be done without access to dataset\")\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: BaseAccumulator, tokenizer, labels\n ) -> Metrics:\n logits = accumulator.get_accumulated()\n assert isinstance(task, (tasks_retrieval.TyDiQATask, tasks_retrieval.XquadTask))\n lang = task.language\n results, predictions = squad_style.compute_predictions_logits_v3(\n data_rows=labels,\n logits=logits,\n n_best_size=task.n_best_size,\n max_answer_length=task.max_answer_length,\n do_lower_case=model_resolution.resolve_is_lower_case(tokenizer),\n version_2_with_negative=task.version_2_with_negative,\n null_score_diff_threshold=task.null_score_diff_threshold,\n skip_get_final_text=(lang == \"zh\"),\n tokenizer=tokenizer,\n )\n return Metrics(major=(results[\"f1\"] + results[\"exact\"]) / 2, minor=results,)\n\n @classmethod\n def get_label_from_data_row(cls, data_row):\n return squad_style.PartialDataRow.from_data_row(data_row)\n\n\nclass MLQAEvaluationScheme(SQuADEvaluationScheme):\n def get_preds_from_accumulator(self, task, accumulator):\n raise NotImplementedError(\"Too hard for now, too much handled in one giant lib\")\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: BaseAccumulator, tokenizer, labels\n ) -> Metrics:\n\n # Todo: Fix val labels cache\n # This is a quick hack\n logits = accumulator.get_accumulated()\n partial_examples = squad_style.data_rows_to_partial_examples(data_rows=labels)\n all_pred_results = squad_style.logits_to_pred_results_list(logits)\n assert task.context_language == task.question_language\n lang = task.context_language\n predictions = squad_style_utils.compute_predictions_logits_v2(\n partial_examples=partial_examples,\n all_results=all_pred_results,\n n_best_size=task.n_best_size,\n max_answer_length=task.max_answer_length,\n do_lower_case=model_resolution.resolve_is_lower_case(tokenizer),\n version_2_with_negative=task.version_2_with_negative,\n null_score_diff_threshold=task.null_score_diff_threshold,\n tokenizer=tokenizer,\n skip_get_final_text=(lang == \"zh\"),\n verbose=True,\n )\n dataset = read_json(task.val_path)[\"data\"]\n results = mlqa_lib.evaluate(dataset=dataset, predictions=predictions, lang=lang,)\n return Metrics(major=(results[\"f1\"] + results[\"exact_match\"]) / 2, minor=results,)\n\n\nclass MLMEvaluationScheme(BaseEvaluationScheme):\n @classmethod\n def get_accumulator(cls) -> BaseAccumulator:\n return ConcatenateLossAccumulator()\n\n def get_labels_from_cache_and_examples(self, task, cache, examples):\n # This is a dummy function. There are no external labels.\n return [None]\n\n def get_preds_from_accumulator(self, task, accumulator):\n raise NotImplementedError(\"Not possible\")\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: BaseAccumulator, tokenizer, labels\n ) -> Metrics:\n loss_list = accumulator.get_accumulated()\n average_loss = mean(loss_list)\n perplexity = np.exp(average_loss)\n return Metrics(\n # Major = negative perplexity\n major=-perplexity,\n minor={\"perplexity\": perplexity},\n )\n\n\nclass MLMPremaskedEvaluationScheme(MLMEvaluationScheme):\n @classmethod\n def get_accumulator(cls) -> BaseAccumulator:\n return MLMPremaskedAccumulator()\n\n @classmethod\n def get_labels_from_cache_and_examples(cls, task, cache, examples):\n labels = []\n for datum in cache.iter_all():\n masked_lm_labels = datum[\"data_row\"].masked_lm_labels\n labels.append(\n masked_lm_labels[masked_lm_labels != mlm_template.NON_MASKED_TOKEN_LABEL_ID]\n )\n return labels\n\n def get_preds_from_accumulator(self, task, accumulator):\n _, preds = accumulator.get_accumulated()\n return preds\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: BaseAccumulator, tokenizer, labels\n ) -> Metrics:\n loss_list, _ = accumulator.get_accumulated()\n average_loss = mean(loss_list)\n perplexity = np.exp(average_loss)\n return Metrics(\n # Major = negative perplexity\n major=-perplexity,\n minor={\"perplexity\": perplexity},\n )\n\n\nclass TatoebaEvaluationScheme(BaseEvaluationScheme):\n def get_accumulator(self):\n return TatoebaAccumulator()\n\n def get_labels_from_cache_and_examples(self, task, cache, examples):\n return task.get_val_labels()\n\n def get_preds_from_accumulator(self, task, accumulator):\n all_embeddings, is_english_arr = accumulator.get_accumulated()\n other_lang_embeddings = all_embeddings[~is_english_arr]\n eng_embeddings = all_embeddings[is_english_arr]\n predictions = tatoeba_lib.similarity_search(\n x=other_lang_embeddings,\n y=eng_embeddings,\n dim=other_lang_embeddings.shape[-1],\n normalize=True,\n ).flatten()\n return predictions\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: ConcatenateLogitsAccumulator, tokenizer, labels: list\n ) -> Metrics:\n preds = self.get_preds_from_accumulator(task=task, accumulator=accumulator)\n return self.compute_metrics_from_preds_and_labels(preds=preds, labels=labels,)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n # noinspection PyUnresolvedReferences\n acc = (preds == labels).mean()\n return Metrics(major=acc, minor={\"acc\": acc})\n\n\nclass Bucc2018EvaluationScheme(BaseEvaluationScheme):\n def get_accumulator(self):\n return Bucc2018Accumulator()\n\n def get_labels_from_cache_and_examples(self, task, cache, examples):\n return task.get_val_labels()\n\n def get_preds_from_accumulator(self, task, accumulator, threshold=0):\n accumulated = accumulator.get_accumulated()\n is_english_arr = accumulated[\"is_english_arr\"]\n all_embeddings = accumulated[\"all_embeddings\"]\n guids = accumulated[\"guid_list\"]\n text_hash_list = accumulated[\"text_hash_list\"]\n other_lang_embeddings = all_embeddings[~is_english_arr]\n eng_embeddings = all_embeddings[is_english_arr]\n english_guids = [x.split(\"-\", 1)[1] for x in np.array(guids)[is_english_arr]]\n other_guids = [x.split(\"-\", 1)[1] for x in np.array(guids)[~is_english_arr]]\n\n n = len(is_english_arr)\n src_inds, _ = bucc2018_lib.get_unique_lines(\n [text_hash_list[i] for i in np.arange(n) if not is_english_arr[i]]\n )\n trg_inds, _ = bucc2018_lib.get_unique_lines(\n [text_hash_list[i] for i in np.arange(n) if is_english_arr[i]]\n )\n src_ids_map = bucc2018_lib.create_ids_map(src_inds, other_guids)\n trg_ids_map = bucc2018_lib.create_ids_map(trg_inds, english_guids)\n\n result = bucc2018_lib.mine_bitext(\n x=other_lang_embeddings,\n y=eng_embeddings,\n src_inds=src_inds,\n trg_inds=trg_inds,\n threshold=threshold,\n use_gpu=torch.cuda.is_available(),\n )\n # Note: Setting thresholds only available in test script\n candidates2score = {}\n for score, src_idx, trg_idx in result:\n for src_key, trg_key in itertools.product(src_ids_map[src_idx], trg_ids_map[trg_idx]):\n candidates2score[src_key, trg_key] = score\n return candidates2score\n\n def compute_metrics_from_accumulator(\n self, task, accumulator: ConcatenateLogitsAccumulator, tokenizer, labels: list\n ) -> Metrics:\n preds = self.get_preds_from_accumulator(task=task, accumulator=accumulator)\n return self.compute_metrics_from_preds_and_labels(preds=preds, labels=labels,)\n\n @classmethod\n def compute_metrics_from_preds_and_labels(cls, preds, labels):\n labels = [tuple(x.split(\"\\t\")) for x in labels]\n result = bucc2018_lib.bucc_eval(preds, gold=labels, threshold=None)\n return Metrics(major=result[\"F1\"], minor=result,)\n\n\ndef get_evaluation_scheme_for_task(task) -> BaseEvaluationScheme:\n # TODO: move logic to task? (issue #1182)\n if isinstance(\n task,\n (\n tasks_retrieval.AdversarialNliTask,\n tasks_retrieval.AbductiveNliTask,\n tasks_retrieval.AcceptabilityDefinitenessTask,\n tasks_retrieval.AcceptabilityCoordTask,\n tasks_retrieval.AcceptabilityEOSTask,\n tasks_retrieval.AcceptabilityWHwordsTask,\n tasks_retrieval.BoolQTask,\n tasks_retrieval.CopaTask,\n tasks_retrieval.FeverNliTask,\n tasks_retrieval.MnliTask,\n tasks_retrieval.PawsXTask,\n tasks_retrieval.QnliTask,\n tasks_retrieval.RaceTask,\n tasks_retrieval.RteTask,\n tasks_retrieval.SciTailTask,\n tasks_retrieval.SentEvalBigramShiftTask,\n tasks_retrieval.SentEvalCoordinationInversionTask,\n tasks_retrieval.SentEvalObjNumberTask,\n tasks_retrieval.SentEvalOddManOutTask,\n tasks_retrieval.SentEvalPastPresentTask,\n tasks_retrieval.SentEvalSentenceLengthTask,\n tasks_retrieval.SentEvalSubjNumberTask,\n tasks_retrieval.SentEvalTopConstituentsTask,\n tasks_retrieval.SentEvalTreeDepthTask,\n tasks_retrieval.SentEvalWordContentTask,\n tasks_retrieval.SnliTask,\n tasks_retrieval.SstTask,\n tasks_retrieval.WiCTask,\n tasks_retrieval.WnliTask,\n tasks_retrieval.WSCTask,\n tasks_retrieval.XnliTask,\n tasks_retrieval.MCScriptTask,\n tasks_retrieval.ArctTask,\n tasks_retrieval.PiqaTask,\n ),\n ):\n return SimpleAccuracyEvaluationScheme()\n elif isinstance(task, tasks_retrieval.MCTACOTask):\n return MCTACOEvaluationScheme()\n elif isinstance(task, tasks_retrieval.CCGTask):\n return CCGEvaluationScheme()\n elif isinstance(task, tasks_retrieval.CommitmentBankTask):\n return CommitmentBankEvaluationScheme()\n elif isinstance(task, tasks_retrieval.ColaTask):\n return MCCEvaluationScheme()\n elif isinstance(\n task,\n (\n tasks_retrieval.ArcEasyTask,\n tasks_retrieval.ArcChallengeTask,\n tasks_retrieval.CommonsenseQATask,\n tasks_retrieval.CosmosQATask,\n tasks_retrieval.SWAGTask,\n tasks_retrieval.HellaSwagTask,\n tasks_retrieval.MutualTask,\n tasks_retrieval.MutualPlusTask,\n tasks_retrieval.QuailTask,\n tasks_retrieval.SocialIQATask,\n tasks_retrieval.WinograndeTask,\n tasks_retrieval.MCTestTask,\n ),\n ):\n return MultipleChoiceAccuracyEvaluationScheme()\n elif isinstance(task, (tasks_retrieval.MrpcTask, tasks_retrieval.QqpTask)):\n return AccAndF1EvaluationScheme()\n elif isinstance(\n task,\n (\n tasks_retrieval.Spr1Task,\n tasks_retrieval.Spr2Task,\n tasks_retrieval.SemevalTask,\n tasks_retrieval.SrlTask,\n tasks_retrieval.NerTask,\n tasks_retrieval.CorefTask,\n tasks_retrieval.DprTask,\n tasks_retrieval.DepTask,\n tasks_retrieval.PosTask,\n tasks_retrieval.NonterminalTask,\n ),\n ):\n return MultiLabelAccAndF1EvaluationScheme()\n elif isinstance(task, tasks_retrieval.ReCoRDTask):\n return ReCordEvaluationScheme()\n elif isinstance(\n task,\n (\n tasks_retrieval.SquadTask,\n tasks_retrieval.RopesTask,\n tasks_retrieval.QuorefTask,\n tasks_retrieval.NewsQATask,\n tasks_retrieval.MrqaNaturalQuestionsTask,\n ),\n ):\n return SQuADEvaluationScheme()\n elif isinstance(task, (tasks_retrieval.TyDiQATask, tasks_retrieval.XquadTask)):\n return XlingQAEvaluationScheme()\n elif isinstance(task, tasks_retrieval.MlqaTask):\n return MLQAEvaluationScheme()\n elif isinstance(task, tasks_retrieval.MultiRCTask):\n return MultiRCEvaluationScheme()\n elif isinstance(task, tasks_retrieval.StsbTask):\n return PearsonAndSpearmanEvaluationScheme()\n elif isinstance(task, tasks_retrieval.MLMSimpleTask):\n return MLMEvaluationScheme()\n elif isinstance(task, (tasks_retrieval.MLMPremaskedTask, tasks_retrieval.MLMPretokenizedTask)):\n return MLMPremaskedEvaluationScheme()\n elif isinstance(task, (tasks_retrieval.QAMRTask, tasks_retrieval.QASRLTask)):\n return SpanPredictionF1andEMScheme()\n elif isinstance(task, (tasks_retrieval.UdposTask, tasks_retrieval.PanxTask)):\n return F1TaggingEvaluationScheme()\n elif isinstance(task, tasks_retrieval.Bucc2018Task):\n return Bucc2018EvaluationScheme()\n elif isinstance(task, tasks_retrieval.TatoebaTask):\n return TatoebaEvaluationScheme()\n else:\n raise KeyError(task)\n\n\ndef get_label_ids(task, examples):\n return np.array([task.LABEL_TO_ID[example.label] for example in examples])\n\n\ndef get_label_ids_from_data_row(data_row):\n return data_row.label_ids\n\n\ndef get_multi_label_ids_from_cache(cache):\n return np.array(\n [get_label_ids_from_data_row(data_row=datum[\"data_row\"]) for datum in cache.iter_all()]\n )\n\n\ndef get_label_id_from_data_row(data_row):\n return data_row.label_id\n\n\ndef get_label_ids_from_cache(cache):\n return np.array(\n [get_label_id_from_data_row(data_row=datum[\"data_row\"]) for datum in cache.iter_all()]\n )\n\n\ndef get_label_vals_from_cache(cache):\n return np.array(\n [get_label_val_from_data_row(data_row=datum[\"data_row\"]) for datum in cache.iter_all()]\n )\n\n\ndef get_label_val_from_data_row(data_row):\n return data_row.label\n\n\ndef get_multiple_choice_label_ids_from_examples(task, examples):\n return np.array([task.CHOICE_BIMAP.a[example.label] for example in examples])\n\n\ndef get_multiple_choice_label_id_from_data_row(data_row):\n return data_row.label_id\n\n\ndef get_multiple_choice_labels_from_cache(cache):\n return np.array(\n [\n get_multiple_choice_label_id_from_data_row(data_row=datum[\"data_row\"])\n for datum in cache.iter_all()\n ]\n )\n\n\ndef mean(*args) -> float:\n return float(np.mean(args))\n\n\ndef write_metrics(results, output_path, verbose=True):\n results_to_write = {}\n if \"loss\" in results:\n results_to_write[\"loss\"] = results[\"loss\"]\n if \"metrics\" in results:\n results_to_write[\"metrics\"] = results[\"metrics\"].to_dict()\n assert results_to_write\n metrics_str = json.dumps(results_to_write, indent=2)\n if verbose:\n print(metrics_str)\n with open(output_path, \"w\") as f:\n f.write(metrics_str)\n" ]
[ [ "numpy.arange", "numpy.squeeze", "sklearn.metrics.matthews_corrcoef", "scipy.stats.pearsonr", "pandas.DataFrame", "numpy.stack", "numpy.concatenate", "numpy.argmax", "numpy.mean", "torch.cuda.is_available", "numpy.exp", "scipy.stats.spearmanr", "sklearn.metrics.f1_score", "numpy.array" ] ]
[ { "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": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] } ]
CODEJIN/PWGAN_for_HiFiSinger
[ "9c7b0b62e8624180897a791db1517676f2012c5d" ]
[ "Train.py" ]
[ "import os\nos.environ['FOR_DISABLE_CONSOLE_CTRL_HANDLER'] = 'T' # This is ot prevent to be called Fortran Ctrl+C crash in Windows.\nimport torch\nimport numpy as np\nimport logging, yaml, sys, argparse, math\nfrom tqdm import tqdm\nfrom collections import defaultdict\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nfrom scipy.io import wavfile\nimport torch.multiprocessing as mp\n\nfrom Modules import Generator, Discriminators, MultiResolutionSTFTLoss\nfrom Datasets import Dataset, Inference_Dataset, Collater, Inference_Collater\nfrom Radam import RAdam\nfrom Noam_Scheduler import Modified_Noam_Scheduler\nfrom Logger import Logger\nfrom Arg_Parser import Recursive_Parse\n\nlogging.basicConfig(\n level=logging.INFO, stream=sys.stdout,\n format= '%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s'\n )\n\ntry:\n from apex import amp\n is_AMP_Exist = True\nexcept:\n logging.info('There is no apex modules in the environment. Mixed precision does not work.')\n is_AMP_Exist = False\n\nclass Trainer:\n def __init__(self, hp_path, steps= 0, gpu_id= 0):\n self.hp_Path = hp_path\n self.gpu_id = gpu_id\n \n self.hp = Recursive_Parse(yaml.load(\n open(self.hp_Path, encoding='utf-8'),\n Loader=yaml.Loader\n ))\n if not is_AMP_Exist:\n self.hp.Use_Mixed_Precision = False\n\n if not torch.cuda.is_available():\n self.device = torch.device('cpu')\n else:\n self.device = torch.device('cuda:{}'.format(gpu_id))\n torch.backends.cudnn.benchmark = True\n torch.cuda.set_device(0)\n\n self.steps = steps\n\n self.Datset_Generate()\n self.Model_Generate()\n\n self.scalar_Dict = {\n 'Train': defaultdict(float),\n 'Evaluation': defaultdict(float),\n }\n\n self.writer_Dict = {\n 'Train': Logger(os.path.join(self.hp.Log_Path, 'Train')),\n 'Evaluation': Logger(os.path.join(self.hp.Log_Path, 'Evaluation')),\n }\n \n self.Load_Checkpoint()\n\n def Datset_Generate(self):\n train_Dataset = Dataset(\n pattern_path= self.hp.Train.Train_Pattern.Path,\n Metadata_file= self.hp.Train.Train_Pattern.Metadata_File,\n accumulated_dataset_epoch= self.hp.Train.Train_Pattern.Accumulated_Dataset_Epoch,\n use_cache = self.hp.Train.Use_Pattern_Cache\n )\n eval_Dataset = Dataset(\n pattern_path= self.hp.Train.Eval_Pattern.Path,\n Metadata_file= self.hp.Train.Eval_Pattern.Metadata_File,\n use_cache = self.hp.Train.Use_Pattern_Cache\n )\n inference_Dataset = Inference_Dataset(\n pattern_paths= 'Inference_Wav_for_Training.txt',\n use_cache= self.hp.Train.Use_Pattern_Cache\n )\n\n if self.gpu_id == 0:\n logging.info('The number of train patterns = {}.'.format(train_Dataset.base_Length))\n logging.info('The number of development patterns = {}.'.format(eval_Dataset.base_Length))\n logging.info('The number of inference patterns = {}.'.format(len(inference_Dataset)))\n\n collater = Collater(\n wav_length= self.hp.Train.Wav_Length,\n frame_shift= self.hp.Sound.Frame_Shift,\n upsample_pad= self.hp.Generator.Upsample.Pad,\n )\n inference_Collater = Inference_Collater(\n wav_length= self.hp.Train.Wav_Length,\n frame_shift= self.hp.Sound.Frame_Shift,\n upsample_pad= self.hp.Generator.Upsample.Pad,\n max_abs_mel= self.hp.Sound.Max_Abs_Mel\n )\n\n self.dataLoader_Dict = {}\n self.dataLoader_Dict['Train'] = torch.utils.data.DataLoader(\n dataset= train_Dataset,\n sampler= torch.utils.data.DistributedSampler(train_Dataset, shuffle= True) \\\n if self.hp.Use_Multi_GPU else \\\n torch.utils.data.RandomSampler(train_Dataset),\n collate_fn= collater,\n batch_size= self.hp.Train.Batch_Size,\n num_workers= self.hp.Train.Num_Workers,\n pin_memory= True\n )\n self.dataLoader_Dict['Eval'] = torch.utils.data.DataLoader(\n dataset= eval_Dataset,\n sampler= torch.utils.data.RandomSampler(eval_Dataset),\n collate_fn= collater,\n batch_size= self.hp.Train.Batch_Size,\n num_workers= self.hp.Train.Num_Workers,\n pin_memory= True\n )\n self.dataLoader_Dict['Inference'] = torch.utils.data.DataLoader(\n dataset= inference_Dataset,\n sampler= torch.utils.data.SequentialSampler(inference_Dataset),\n collate_fn= inference_Collater,\n batch_size= self.hp.Inference_Batch_Size or self.hp.Train.Batch_Size,\n num_workers= self.hp.Train.Num_Workers,\n pin_memory= True\n )\n\n def Model_Generate(self):\n if self.hp.Use_Multi_GPU:\n self.model_Dict = {\n 'Generator': torch.nn.parallel.DistributedDataParallel(\n Generator(self.hp).to(self.device),\n device_ids=[self.gpu_id]\n ),\n 'Discriminator': torch.nn.parallel.DistributedDataParallel(\n Discriminators(self.hp).to(self.device),\n device_ids=[self.gpu_id]\n )\n }\n else:\n self.model_Dict = {\n 'Generator': Generator(self.hp).to(self.device),\n 'Discriminator': Discriminators(self.hp).to(self.device)\n }\n\n self.criterion_Dict = {\n 'STFT': MultiResolutionSTFTLoss(\n fft_sizes= self.hp.STFT_Loss_Resolution.FFT_Sizes,\n shift_lengths= self.hp.STFT_Loss_Resolution.Shfit_Lengths,\n win_lengths= self.hp.STFT_Loss_Resolution.Win_Lengths,\n ).to(self.device),\n 'Mean_Squared_Error': torch.nn.MSELoss().to(self.device)\n }\n self.optimizer_Dict = {\n 'Generator': RAdam(\n params= self.model_Dict['Generator'].parameters(),\n lr= self.hp.Train.Learning_Rate.Generator.Initial,\n betas=(self.hp.Train.ADAM.Beta1, self.hp.Train.ADAM.Beta2),\n eps= self.hp.Train.ADAM.Epsilon,\n weight_decay= self.hp.Train.Weight_Decay\n ),\n 'Discriminator': RAdam(\n params= self.model_Dict['Discriminator'].parameters(),\n lr= self.hp.Train.Learning_Rate.Discriminator.Initial,\n betas=(self.hp.Train.ADAM.Beta1, self.hp.Train.ADAM.Beta2),\n eps= self.hp.Train.ADAM.Epsilon,\n weight_decay= self.hp.Train.Weight_Decay\n )\n }\n \n self.scheduler_Dict = {\n 'Generator': Modified_Noam_Scheduler(\n optimizer= self.optimizer_Dict['Generator'],\n base= self.hp.Train.Learning_Rate.Generator.Base\n ),\n 'Discriminator': Modified_Noam_Scheduler(\n optimizer= self.optimizer_Dict['Discriminator'],\n base= self.hp.Train.Learning_Rate.Discriminator.Base\n )\n }\n \n if self.hp.Use_Mixed_Precision:\n amp_Wrapped = amp.initialize(\n models=[self.model_Dict['Generator'], self.model_Dict['Discriminator']],\n optimizers=[self.optimizer_Dict['Generator'], self.optimizer_Dict['Discriminator']]\n )\n self.model_Dict['Generator'], self.model_Dict['Discriminator'] = amp_Wrapped[0]\n self.optimizer_Dict['Generator'], self.optimizer_Dict['Discriminator'] = amp_Wrapped[1]\n\n if self.gpu_id == 0:\n logging.info('#' * 100)\n logging.info('Generator structure')\n logging.info(self.model_Dict['Generator'])\n logging.info('#' * 100)\n logging.info('Discriminator structure')\n logging.info(self.model_Dict['Discriminator'])\n\n def Train_Step(self, noises, mels, silences, pitches, audios):\n loss_Dict = {}\n\n noises = noises.to(self.device, non_blocking=True)\n mels = mels.to(self.device, non_blocking=True)\n silences = silences.to(self.device, non_blocking=True)\n pitches = pitches.to(self.device, non_blocking=True)\n audios = audios.to(self.device, non_blocking=True)\n\n fakes = self.model_Dict['Generator'](\n x= noises,\n mels= mels,\n silences= silences,\n pitches= pitches\n )\n\n loss_Dict['Spectral_Convergence'], loss_Dict['Magnitude'] = self.criterion_Dict['STFT'](fakes, audios)\n loss_Dict['Generator'] = loss_Dict['Spectral_Convergence'] + loss_Dict['Magnitude']\n\n if self.steps >= self.hp.Train.Discriminator_Delay:\n fake_Discriminations = self.model_Dict['Discriminator'](fakes)\n loss_Dict['Adversarial'] = 0.0\n for discrimination in fake_Discriminations:\n loss_Dict['Adversarial'] += self.criterion_Dict['Mean_Squared_Error'](\n discrimination,\n discrimination.new_ones(discrimination.size())\n )\n loss_Dict['Generator'] += loss_Dict['Adversarial']\n \n self.optimizer_Dict['Generator'].zero_grad()\n if self.hp.Use_Mixed_Precision:\n with amp.scale_loss(loss_Dict['Generator'], self.optimizer_Dict['Generator']) as scaled_loss:\n scaled_loss.backward()\n torch.nn.utils.clip_grad_norm_(\n parameters= amp.master_params(self.optimizer_Dict['Generator']),\n max_norm= self.hp.Train.Gradient_Norm\n )\n else:\n loss_Dict['Generator'].backward()\n torch.nn.utils.clip_grad_norm_(\n parameters= self.model_Dict['Generator'].parameters(),\n max_norm= self.hp.Train.Gradient_Norm\n )\n self.optimizer_Dict['Generator'].step()\n self.scheduler_Dict['Generator'].step()\n\n if self.steps >= self.hp.Train.Discriminator_Delay:\n real_Discriminations = self.model_Dict['Discriminator'](audios)\n fake_Discriminations = self.model_Dict['Discriminator'](fakes.detach())\n\n loss_Dict['Real'] = 0.0\n for discrimination in real_Discriminations:\n loss_Dict['Real'] += self.criterion_Dict['Mean_Squared_Error'](\n discrimination,\n discrimination.new_ones(discrimination.size())\n )\n loss_Dict['Fake'] = 0.0\n for discrimination in fake_Discriminations:\n loss_Dict['Fake'] += discrimination.mean()\n loss_Dict['Discriminator'] = loss_Dict['Real'] + loss_Dict['Fake']\n\n self.optimizer_Dict['Discriminator'].zero_grad()\n if self.hp.Use_Mixed_Precision:\n with amp.scale_loss(loss_Dict['Discriminator'], self.optimizer_Dict['Discriminator']) as scaled_loss:\n scaled_loss.backward()\n torch.nn.utils.clip_grad_norm_(\n parameters= amp.master_params(self.optimizer_Dict['Discriminator']),\n max_norm= self.hp.Train.Gradient_Norm\n )\n else:\n loss_Dict['Discriminator'].backward()\n torch.nn.utils.clip_grad_norm_(\n parameters= self.model_Dict['Discriminator'].parameters(),\n max_norm= self.hp.Train.Gradient_Norm\n )\n self.optimizer_Dict['Discriminator'].step()\n self.scheduler_Dict['Discriminator'].step()\n\n self.steps += 1\n self.tqdm.update(1)\n\n for tag, loss in loss_Dict.items():\n self.scalar_Dict['Train']['Loss/{}'.format(tag)] += loss\n\n def Train_Epoch(self):\n for noises, mels, silences, pitches, audios in self.dataLoader_Dict['Train']:\n self.Train_Step(noises, mels, silences, pitches, audios)\n \n if self.steps % self.hp.Train.Checkpoint_Save_Interval == 0:\n self.Save_Checkpoint()\n\n if self.steps % self.hp.Train.Logging_Interval == 0:\n self.scalar_Dict['Train'] = {\n tag: loss / self.hp.Train.Logging_Interval\n for tag, loss in self.scalar_Dict['Train'].items()\n }\n self.scalar_Dict['Train']['Learning_Rate/Generator'] = self.scheduler_Dict['Generator'].get_last_lr()\n if self.steps >= self.hp.Train.Discriminator_Delay:\n self.scalar_Dict['Train']['Learning_Rate/Discriminator'] = self.scheduler_Dict['Discriminator'].get_last_lr()\n self.writer_Dict['Train'].add_scalar_dict(self.scalar_Dict['Train'], self.steps)\n self.scalar_Dict['Train'] = defaultdict(float)\n\n if self.steps % self.hp.Train.Evaluation_Interval == 0:\n self.Evaluation_Epoch()\n\n if self.steps % self.hp.Train.Inference_Interval == 0:\n self.Inference_Epoch()\n \n if self.steps >= self.hp.Train.Max_Step:\n return\n\n @torch.no_grad()\n def Evaluation_Step(self, noises, mels, silences, pitches, audios):\n loss_Dict = {}\n\n noises = noises.to(self.device, non_blocking=True)\n mels = mels.to(self.device, non_blocking=True)\n silences = silences.to(self.device, non_blocking=True)\n pitches = pitches.to(self.device, non_blocking=True)\n audios = audios.to(self.device, non_blocking=True)\n\n fakes = self.model_Dict['Generator'](\n x= noises,\n mels= mels,\n silences= silences,\n pitches= pitches\n )\n\n loss_Dict['Spectral_Convergence'], loss_Dict['Magnitude'] = self.criterion_Dict['STFT'](fakes, audios)\n loss_Dict['Generator'] = loss_Dict['Spectral_Convergence'] + loss_Dict['Magnitude']\n\n if self.steps >= self.hp.Train.Discriminator_Delay:\n fake_Discriminations = self.model_Dict['Discriminator'](fakes)\n loss_Dict['Adversarial'] = 0.0\n for discrimination in fake_Discriminations:\n loss_Dict['Adversarial'] += self.criterion_Dict['Mean_Squared_Error'](\n discrimination,\n discrimination.new_ones(discrimination.size())\n )\n loss_Dict['Generator'] += loss_Dict['Adversarial']\n \n if self.steps >= self.hp.Train.Discriminator_Delay:\n real_Discriminations = self.model_Dict['Discriminator'](audios)\n fake_Discriminations = self.model_Dict['Discriminator'](fakes.detach())\n\n loss_Dict['Real'] = 0.0\n for discrimination in real_Discriminations:\n loss_Dict['Real'] += self.criterion_Dict['Mean_Squared_Error'](\n discrimination,\n discrimination.new_ones(discrimination.size())\n )\n loss_Dict['Fake'] = 0.0\n for discrimination in fake_Discriminations:\n loss_Dict['Fake'] += discrimination.mean()\n loss_Dict['Discriminator'] = loss_Dict['Real'] + loss_Dict['Fake']\n\n for tag, loss in loss_Dict.items():\n self.scalar_Dict['Evaluation']['Loss/{}'.format(tag)] += loss.cpu()\n\n return fakes\n\n def Evaluation_Epoch(self):\n if self.gpu_id != 0:\n return\n\n logging.info('(Steps: {}) Start evaluation in GPU {}.'.format(self.steps, self.gpu_id))\n\n self.model_Dict['Generator'].eval()\n self.model_Dict['Discriminator'].eval()\n\n for step, (noises, mels, silences, pitches, audios) in tqdm(\n enumerate(self.dataLoader_Dict['Eval'], 1),\n desc='[Evaluation]',\n total= math.ceil(len(self.dataLoader_Dict['Eval'].dataset) / self.hp.Train.Batch_Size)\n ):\n fakes = self.Evaluation_Step(noises, mels, silences, pitches, audios)\n\n self.scalar_Dict['Evaluation'] = {\n tag: loss / step\n for tag, loss in self.scalar_Dict['Evaluation'].items()\n }\n self.writer_Dict['Evaluation'].add_scalar_dict(self.scalar_Dict['Evaluation'], self.steps)\n self.writer_Dict['Evaluation'].add_histogram_model(self.model_Dict['Generator'], self.steps, delete_keywords=['layer_Dict', 'layer', 'module'])\n self.writer_Dict['Evaluation'].add_histogram_model(self.model_Dict['Discriminator'], self.steps, delete_keywords=['layer_Dict', 'layer', 'module'])\n self.scalar_Dict['Evaluation'] = defaultdict(float)\n\n image_Dict = {\n 'Mel': (mels[-1].cpu().numpy(), None),\n 'Silence': (silences[-1].cpu().numpy(), None),\n 'Pitch': (pitches[-1].cpu().numpy(), None),\n 'Audio/Target': (audios[-1].cpu().numpy(), None),\n 'Audio/Prediction': (fakes[-1].cpu().numpy(), None),\n }\n self.writer_Dict['Evaluation'].add_image_dict(image_Dict, self.steps)\n\n self.model_Dict['Generator'].train()\n self.model_Dict['Discriminator'].train()\n\n @torch.no_grad()\n def Inference_Step(self, noises, mels, silences, pitches, labels, start_index= 0, tag_step= False):\n noises = noises.to(self.device, non_blocking=True)\n mels = mels.to(self.device, non_blocking=True)\n silences = silences.to(self.device, non_blocking=True)\n pitches = pitches.to(self.device, non_blocking=True)\n\n fakes = self.model_Dict['Generator'](\n x= noises,\n mels= mels,\n silences= silences,\n pitches= pitches\n )\n \n files = []\n for index, label in enumerate(labels):\n tags = []\n if tag_step: tags.append('Step-{}'.format(self.steps))\n tags.append(label)\n tags.append('IDX_{}'.format(index + start_index))\n files.append('.'.join(tags))\n\n os.makedirs(os.path.join(self.hp.Inference_Path, 'Step-{}'.format(self.steps), 'PNG').replace('\\\\', '/'), exist_ok= True)\n os.makedirs(os.path.join(self.hp.Inference_Path, 'Step-{}'.format(self.steps), 'NPY', 'Mel').replace('\\\\', '/'), exist_ok= True)\n os.makedirs(os.path.join(self.hp.Inference_Path, 'Step-{}'.format(self.steps), 'Wav').replace('\\\\', '/'), exist_ok= True)\n for fake, mel, silence, pitch, label, file in zip(\n fakes.cpu().numpy(),\n mels.cpu().numpy(),\n silences.cpu().numpy(),\n pitches.cpu().numpy(),\n labels,\n files\n ):\n title = 'Label: {}'.format(label)\n new_Figure = plt.figure(figsize=(20, 5 * 4), dpi=100)\n\n plt.subplot2grid((4, 1), (0, 0))\n plt.plot(fake)\n plt.margins(x= 0)\n plt.title('Audio {}'.format(title))\n\n plt.subplot2grid((4, 1), (1, 0))\n plt.imshow(mel, aspect='auto', origin='lower')\n plt.title('Mel {}'.format(title))\n\n plt.subplot2grid((4, 1), (2, 0))\n plt.plot(silence)\n plt.margins(x= 0)\n plt.title('Silence {}'.format(title))\n\n plt.subplot2grid((4, 1), (3, 0))\n plt.plot(pitch)\n plt.margins(x= 0)\n plt.title('Pitch {}'.format(title))\n \n plt.tight_layout()\n plt.savefig(os.path.join(self.hp.Inference_Path, 'Step-{}'.format(self.steps), 'PNG', '{}.png'.format(file)).replace('\\\\', '/'))\n plt.close(new_Figure)\n \n np.save(\n os.path.join(self.hp.Inference_Path, 'Step-{}'.format(self.steps), 'NPY', 'Mel', file).replace('\\\\', '/'),\n mel.T,\n allow_pickle= False\n ) \n \n wavfile.write(\n filename= os.path.join(self.hp.Inference_Path, 'Step-{}'.format(self.steps), 'Wav', '{}.wav'.format(file)).replace('\\\\', '/'),\n data= (np.clip(fake, -1.0 + 1e-7, 1.0 - 1e-7) * 32767.5).astype(np.int16),\n rate= self.hp.Sound.Sample_Rate\n )\n \n def Inference_Epoch(self):\n if self.gpu_id != 0:\n return\n\n logging.info('(Steps: {}) Start inference in GPU {}.'.format(self.steps, self.gpu_id))\n\n self.model_Dict['Generator'].eval()\n\n for step, (noises, mels, silences, pitches, labels) in tqdm(\n enumerate(self.dataLoader_Dict['Inference']),\n desc='[Inference]',\n total= math.ceil(len(self.dataLoader_Dict['Inference'].dataset) / (self.hp.Inference_Batch_Size or self.hp.Train.Batch_Size))\n ):\n self.Inference_Step(noises, mels, silences, pitches, labels, start_index= step * (self.hp.Inference_Batch_Size or self.hp.Train.Batch_Size))\n\n self.model_Dict['Generator'].train()\n\n def Load_Checkpoint(self):\n if self.steps == 0:\n paths = [\n os.path.join(root, file).replace('\\\\', '/')\n for root, _, files in os.walk(self.hp.Checkpoint_Path)\n for file in files\n if os.path.splitext(file)[1] == '.pt'\n ]\n if len(paths) > 0:\n path = max(paths, key = os.path.getctime)\n else:\n return # Initial training\n else:\n path = os.path.join(self.hp.Checkpoint_Path, 'S_{}.pt'.format(self.steps).replace('\\\\', '/'))\n\n state_Dict = torch.load(path, map_location= 'cpu')\n \n if self.hp.Use_Multi_GPU:\n self.model_Dict['Generator'].module.load_state_dict(state_Dict['Generator']['Model'])\n self.model_Dict['Discriminator'].module.load_state_dict(state_Dict['Discriminator']['Model'])\n else:\n self.model_Dict['Generator'].load_state_dict(state_Dict['Generator']['Model'])\n self.model_Dict['Discriminator'].load_state_dict(state_Dict['Discriminator']['Model'])\n\n self.optimizer_Dict['Generator'].load_state_dict(state_Dict['Generator']['Optimizer'])\n self.optimizer_Dict['Discriminator'].load_state_dict(state_Dict['Discriminator']['Optimizer'])\n\n self.scheduler_Dict['Generator'].load_state_dict(state_Dict['Generator']['Scheduler'])\n self.scheduler_Dict['Discriminator'].load_state_dict(state_Dict['Discriminator']['Scheduler'])\n\n self.steps = state_Dict['Steps']\n\n if self.hp.Use_Mixed_Precision:\n if not 'AMP' in state_Dict.keys():\n logging.info('No AMP state dict is in the checkpoint. Model regards this checkpoint is trained without mixed precision.')\n else: \n amp.load_state_dict(state_Dict['AMP'])\n\n logging.info('Checkpoint loaded at {} steps in GPU {}.'.format(self.steps, self.gpu_id))\n\n def Save_Checkpoint(self):\n if self.gpu_id != 0:\n return\n\n os.makedirs(self.hp.Checkpoint_Path, exist_ok= True)\n\n state_Dict = {\n 'Generator': {\n 'Model': self.model_Dict['Generator'].module.state_dict() if self.hp.Use_Multi_GPU else self.model_Dict['Generator'].state_dict(),\n 'Optimizer': self.optimizer_Dict['Generator'].state_dict(),\n 'Scheduler': self.scheduler_Dict['Generator'].state_dict(),\n },\n 'Discriminator': {\n 'Model': self.model_Dict['Discriminator'].module.state_dict() if self.hp.Use_Multi_GPU else self.model_Dict['Discriminator'].state_dict(),\n 'Optimizer': self.optimizer_Dict['Discriminator'].state_dict(),\n 'Scheduler': self.scheduler_Dict['Discriminator'].state_dict(),\n },\n 'Steps': self.steps\n }\n if self.hp.Use_Mixed_Precision:\n state_Dict['AMP'] = amp.state_dict()\n\n torch.save(\n state_Dict,\n os.path.join(self.hp.Checkpoint_Path, 'S_{}.pt'.format(self.steps).replace('\\\\', '/'))\n )\n\n logging.info('Checkpoint saved at {} steps.'.format(self.steps))\n\n def Train(self):\n hp_Path = os.path.join(self.hp.Checkpoint_Path, 'Hyper_Parameters.yaml').replace('\\\\', '/')\n if not os.path.exists(hp_Path):\n from shutil import copyfile\n os.makedirs(self.hp.Checkpoint_Path, exist_ok= True)\n copyfile(self.hp_Path, hp_Path)\n\n if self.steps == 0:\n self.Evaluation_Epoch()\n\n if self.hp.Train.Initial_Inference:\n self.Inference_Epoch()\n\n self.tqdm = tqdm(\n initial= self.steps,\n total= self.hp.Train.Max_Step,\n desc='[Training]'\n )\n\n while self.steps < self.hp.Train.Max_Step:\n try:\n self.Train_Epoch()\n except KeyboardInterrupt:\n self.Save_Checkpoint()\n exit(1)\n \n self.tqdm.close()\n logging.info('Finished training.')\n\n\ndef Worker(gpu, hp_path, steps):\n torch.distributed.init_process_group(\n backend= 'nccl',\n init_method='tcp://127.0.0.1:54321',\n world_size= torch.cuda.device_count(),\n rank= gpu\n )\n\n new_Trainer = Trainer(hp_path= hp_path, steps= steps, gpu_id= gpu)\n new_Trainer.Train()\n\nif __name__ == '__main__':\n argParser = argparse.ArgumentParser()\n argParser.add_argument('-hp', '--hyper_parameters', required= True, type= str)\n argParser.add_argument('-s', '--steps', default= 0, type= int)\n args = argParser.parse_args()\n \n hp = Recursive_Parse(yaml.load(\n open(args.hyper_parameters, encoding='utf-8'),\n Loader=yaml.Loader\n ))\n os.environ['CUDA_VISIBLE_DEVICES'] = hp.Device\n\n if hp.Use_Multi_GPU:\n mp.spawn(\n Worker,\n nprocs= torch.cuda.device_count(),\n args= (args.hyper_parameters, args.steps)\n )\n else:\n new_Trainer = Trainer(hp_path= args.hyper_parameters, steps= args.steps, gpu_id= 0)\n new_Trainer.Train()" ]
[ [ "matplotlib.pyplot.imshow", "torch.load", "matplotlib.pyplot.plot", "torch.no_grad", "torch.cuda.is_available", "torch.device", "matplotlib.pyplot.subplot2grid", "matplotlib.pyplot.tight_layout", "torch.utils.data.DistributedSampler", "numpy.clip", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "matplotlib.pyplot.margins", "torch.cuda.device_count", "torch.cuda.set_device", "matplotlib.use", "torch.utils.data.SequentialSampler", "torch.utils.data.RandomSampler", "torch.nn.MSELoss" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rguo12/pytorch-ntm
[ "d08291fac4dccaa3c8d081bad06802d9e4d737ea" ]
[ "ntm/head.py" ]
[ "\"\"\"NTM Read/Write Head.\"\"\"\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport numpy as np\n\n\ndef _split_cols(mat, lengths):\n \"\"\"Split a 2D matrix to variable length columns.\"\"\"\n assert mat.size()[1] == sum(lengths), \"Lengths must be summed to num columns\"\n l = np.cumsum([0] + lengths)\n results = []\n for s, e in zip(l[:-1], l[1:]):\n results += [mat[:, s:e]]\n return results\n\n\nclass NTMHeadBase(nn.Module):\n \"\"\"An NTM Read/Write Head.\"\"\"\n\n def __init__(self, memory, controller_size):\n \"\"\"Initilize the read/write head.\n\n :param memory: The :class:`NTMMemory` to be addressed by the head.\n :param controller_size: The size of the internal representation.\n \"\"\"\n super(NTMHeadBase, self).__init__()\n\n self.memory = memory\n self.N, self.M = memory.size()\n self.controller_size = controller_size\n\n def create_new_state(self, batch_size):\n raise NotImplementedError\n\n def init_weights(self):\n raise NotImplementedError\n\n def is_read_head(self):\n return NotImplementedError\n\n def _address_memory(self, k, β, g, s, γ, w_prev):\n # Activations\n k = F.relu(k)\n β = F.relu(β)\n g = F.sigmoid(g)\n s = F.softmax(F.relu(s))\n γ = 1 + F.relu(γ)\n\n w = self.memory.address(k, β, g, s, γ, w_prev)\n\n return w\n\n\nclass NTMReadHead(NTMHeadBase):\n def __init__(self, memory, controller_size):\n super(NTMReadHead, self).__init__(memory, controller_size)\n\n # Corresponding to k, β, g, s, γ sizes from the paper\n self.read_lengths = [self.M, 1, 1, 3, 1]\n self.fc_read = nn.Linear(controller_size, sum(self.read_lengths))\n self.reset_parameters()\n\n def create_new_state(self, batch_size):\n # The state holds the previous time step address weightings\n return Variable(torch.zeros(batch_size, self.N))\n\n def reset_parameters(self):\n # Initialize the linear layers\n nn.init.xavier_uniform(self.fc_read.weight, gain=1.4)\n nn.init.normal(self.fc_read.bias, std=0.01)\n\n def is_read_head(self):\n return True\n\n def forward(self, embeddings, w_prev):\n \"\"\"NTMReadHead forward function.\n\n :param embeddings: input representation of the controller.\n :param w_prev: previous step state\n \"\"\"\n o = self.fc_read(embeddings)\n k, β, g, s, γ = _split_cols(o, self.read_lengths)\n\n # Read from memory\n w = self._address_memory(k, β, g, s, γ, w_prev)\n r = self.memory.read(w)\n\n return r, w\n\n\nclass NTMWriteHead(NTMHeadBase):\n def __init__(self, memory, controller_size):\n super(NTMWriteHead, self).__init__(memory, controller_size)\n\n # Corresponding to k, β, g, s, γ, e, a sizes from the paper\n self.write_lengths = [self.M, 1, 1, 3, 1, self.M, self.M]\n self.fc_write = nn.Linear(controller_size, sum(self.write_lengths))\n self.reset_parameters()\n\n def create_new_state(self, batch_size):\n return Variable(torch.zeros(batch_size, self.N))\n\n def reset_parameters(self):\n # Initialize the linear layers\n nn.init.xavier_uniform(self.fc_write.weight, gain=1.4)\n nn.init.normal(self.fc_write.bias, std=0.01)\n\n def is_read_head(self):\n return False\n\n def forward(self, embeddings, w_prev):\n \"\"\"NTMWriteHead forward function.\n\n :param embeddings: input representation of the controller.\n :param w_prev: previous step state\n \"\"\"\n o = self.fc_write(embeddings)\n k, β, g, s, γ, e, a = _split_cols(o, self.write_lengths)\n\n # Handle activations\n e = F.relu(e)\n a = F.relu(a)\n\n # Write to memory\n w = self._address_memory(k, β, g, s, γ, w_prev)\n self.memory.write(w, e, a)\n\n return w\n" ]
[ [ "torch.zeros", "numpy.cumsum", "torch.nn.functional.sigmoid", "torch.nn.functional.relu", "torch.nn.init.xavier_uniform", "torch.nn.init.normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
greycubesgav/tensorflow-2-style-transfer
[ "87d5b88543b68064c33a6411a42ae1fd84708394" ]
[ "utils.py" ]
[ "# MIT License\n#\n# Copyright (c) 2019 Drew Szurko\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\nfrom __future__ import unicode_literals\n\nimport os\nimport shutil\n\nimport tensorflow as tf\nfrom absl import flags\nfrom tensorflow import io\n\nFLAGS = flags.FLAGS\n\n\ndef load_img(img_path):\n img = io.read_file(img_path)\n img = tf.image.decode_image(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n\n shape = tf.cast(tf.shape(img)[:-1], tf.float32)\n long_dim = max(shape)\n scale = FLAGS.max_dim / long_dim\n\n new_shape = tf.cast(shape * scale, tf.int32)\n\n img = tf.image.resize(img, new_shape, antialias=True)\n img = img[tf.newaxis, :]\n return img\n\n\ndef save_img(image_batch, epoch):\n file_name = f'{epoch}.jpg'\n output_dir = os.path.join(FLAGS.output_dir, file_name)\n\n for i in image_batch:\n img = tf.image.encode_jpeg(tf.cast(i * 255, tf.uint8), format='rgb')\n tf.io.write_file(output_dir, img)\n\n\ndef get_terminal_width():\n width = shutil.get_terminal_size(fallback=(200, 24))[0]\n if width == 0:\n width = 120\n return width\n" ]
[ [ "tensorflow.shape", "tensorflow.cast", "tensorflow.image.resize", "tensorflow.image.decode_image", "tensorflow.image.convert_image_dtype", "tensorflow.io.read_file", "tensorflow.io.write_file" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
freekang/m_hydra_nn
[ "7cbdb6f43fe1f02d712e6c803c770bd961140048" ]
[ "src/models/mnist_module.py" ]
[ "from typing import Any, List\n\nimport torch\nfrom pytorch_lightning import LightningModule\nfrom torchmetrics import MaxMetric\nfrom torchmetrics.classification.accuracy import Accuracy\n\nfrom src.models.components.simple_dense_net import SimpleDenseNet\n\n\nclass MNISTLitModule(LightningModule):\n \"\"\"\n Example of LightningModule for MNIST classification.\n\n A LightningModule organizes your PyTorch code into 5 sections:\n - Computations (init).\n - Train loop (training_step)\n - Validation loop (validation_step)\n - Test loop (test_step)\n - Optimizers (configure_optimizers)\n\n Read the docs:\n https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html\n \"\"\"\n\n def __init__(\n self,\n net: torch.nn.Module,\n lr: float = 0.001,\n weight_decay: float = 0.0005,\n ):\n super().__init__()\n\n # this line allows to access init params with 'self.hparams' attribute\n # it also ensures init params will be stored in ckpt\n self.save_hyperparameters(logger=False)\n\n self.net = net\n\n # loss function\n self.criterion = torch.nn.CrossEntropyLoss()\n\n # use separate metric instance for train, val and test step\n # to ensure a proper reduction over the epoch\n self.train_acc = Accuracy()\n self.val_acc = Accuracy()\n self.test_acc = Accuracy()\n\n # for logging best so far validation accuracy\n self.val_acc_best = MaxMetric()\n\n def forward(self, x: torch.Tensor):\n return self.net(x)\n\n def step(self, batch: Any):\n x, y = batch\n logits = self.forward(x)\n loss = self.criterion(logits, y)\n preds = torch.argmax(logits, dim=1)\n return loss, preds, y\n\n def training_step(self, batch: Any, batch_idx: int):\n loss, preds, targets = self.step(batch)\n\n # log train metrics\n acc = self.train_acc(preds, targets)\n self.log(\"train/loss\", loss, on_step=False, on_epoch=True, prog_bar=False)\n self.log(\"train/acc\", acc, on_step=False, on_epoch=True, prog_bar=True)\n\n # we can return here dict with any tensors\n # and then read it in some callback or in `training_epoch_end()`` below\n # remember to always return loss from `training_step()` or else backpropagation will fail!\n return {\"loss\": loss, \"preds\": preds, \"targets\": targets}\n\n def training_epoch_end(self, outputs: List[Any]):\n # `outputs` is a list of dicts returned from `training_step()`\n pass\n\n def validation_step(self, batch: Any, batch_idx: int):\n loss, preds, targets = self.step(batch)\n\n # log val metrics\n acc = self.val_acc(preds, targets)\n self.log(\"val/loss\", loss, on_step=False, on_epoch=True, prog_bar=False)\n self.log(\"val/acc\", acc, on_step=False, on_epoch=True, prog_bar=True)\n\n return {\"loss\": loss, \"preds\": preds, \"targets\": targets}\n\n def validation_epoch_end(self, outputs: List[Any]):\n acc = self.val_acc.compute() # get val accuracy from current epoch\n self.val_acc_best.update(acc)\n self.log(\"val/acc_best\", self.val_acc_best.compute(), on_epoch=True, prog_bar=True)\n\n def test_step(self, batch: Any, batch_idx: int):\n loss, preds, targets = self.step(batch)\n\n # log test metrics\n acc = self.test_acc(preds, targets)\n self.log(\"test/loss\", loss, on_step=False, on_epoch=True)\n self.log(\"test/acc\", acc, on_step=False, on_epoch=True)\n\n return {\"loss\": loss, \"preds\": preds, \"targets\": targets}\n\n def test_epoch_end(self, outputs: List[Any]):\n pass\n\n def on_epoch_end(self):\n # reset metrics at the end of every epoch\n self.train_acc.reset()\n self.test_acc.reset()\n self.val_acc.reset()\n\n def configure_optimizers(self):\n \"\"\"Choose what optimizers and learning-rate schedulers to use in your optimization.\n Normally you'd need one. But in the case of GANs or similar you might have multiple.\n\n See examples here:\n https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers\n \"\"\"\n return torch.optim.Adam(\n params=self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay\n )\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
PrivacyAmp/cardinality_estimation_evaluation_framework
[ "c6f16733f821bba99c1e5ca827025a063f5689ae" ]
[ "src/simulations/frequency_set_generator.py" ]
[ "# Copyright 2020 The Private Cardinality Estimation Framework 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\"\"\"Simulation data generators for frequency evaluation framework.\n\nWe have implemented the following simulation data:\n* Homogeneous user activities with a publisher\n* Heterogeneous user frequency\n* Publisher constant frequency.\n\nSee the following for further details:\n\nhttps://github.com/world-federation-of-advertisers/cardinality_estimation_evaluation_framework/blob/master/doc/cardinality_and_frequency_estimation_evaluation_framework.md#frequency-simulation-scenarios\n\"\"\"\nfrom absl import logging\nimport numpy as np\n\nfrom wfa_cardinality_estimation_evaluation_framework.common.random import choice_fast\nfrom wfa_cardinality_estimation_evaluation_framework.simulations.set_generator_base import SetGeneratorBase\nfrom wfa_cardinality_estimation_evaluation_framework.simulations.set_generator_base import _SetSizeGenerator\n\n\nclass HomogeneousPmfMultiSetGenerator(SetGeneratorBase):\n \"\"\"Homogeneous multiset generator for arbitrary Pmf.\n\n This generator returns a collection of multisets. Each multiset\n is drawn at random from a universe of specified size, so the overlap\n probabilities of two sets are independent. Each item in a multiset\n is assigned a frequency determined by a probability mass function \n that is passed to the constructor. There is one PMF per set.\n \"\"\"\n\n def __init__(self, universe_size, set_sizes, pmfs, random_state):\n \"\"\"Create a homogeneous multiset generator for an arbitrary pmf.\n\n Args:\n universe_size: An integer value that specifies the size of the whole\n universe from which the ids will be sampled.\n set_sizes: An iterable containing the size of each set, aka, the number of\n reached IDs.\n pmfs: Iterable of list of float, representing the shifted probability\n mass functions of the frequency distributions associated to each of \n thet sets. pmf[i][j] is the probability of frequency j+1 occurring \n in set i.\n random_state: a numpy random state.\n\n Raises: AssertionError when pmf is not valid.\n \"\"\"\n self.set_sizes = list(set_sizes)\n self.pmf_list = list(pmfs)\n\n assert len(self.set_sizes) == len(self.pmf_list), (\n 'Number of sets does not match number of pmfs')\n assert all(sum(p) == 1.0 for p in self.pmf_list), (\n 'At least one PMF does not sum to 1.0')\n \n self.universe_size = universe_size\n self.random_state = random_state\n\n def __iter__(self):\n for set_size, pmf in zip(self.set_sizes, self.pmf_list):\n set_ids = choice_fast(self.universe_size, set_size, self.random_state)\n freq_per_id = self.random_state.choice(len(pmf), size=set_size, p=pmf) + 1\n multiset_ids = []\n for i, freq in zip(set_ids, freq_per_id):\n multiset_ids += [i] * freq\n self.random_state.shuffle(multiset_ids)\n yield multiset_ids\n return self\n\n \nclass HomogeneousMultiSetGenerator(HomogeneousPmfMultiSetGenerator):\n \"\"\"Homogeneous multiset generator.\n\n This generator returns the multisets as described in section\n Frequency scenario 1: Homogeneous user activities within a publisher of this\n doc:\n https://github.com/world-federation-of-advertisers/cardinality_estimation_evaluation_framework/blob/master/doc/cardinality_and_frequency_estimation_evaluation_framework.md#frequency-scenario-1-homogeneous-user-activities-within-a-publisher\n\n Homogeneous means that all the reached ID's have the same frequency\n distribution.\n\n As a reached ID may appear one or more times in the returned set,\n to differentiate with a normal set whose elements can only appear once, we\n use the term multiset.\n\n The frequency distribution is defined as a shifted-Poisson distribution.\n I.e., freq ~ Poission(freq_rate) + 1.\n \"\"\"\n\n @classmethod\n def get_generator_factory_with_num_and_size(cls, universe_size, num_sets,\n set_size, freq_rates,\n freq_cap):\n\n def f(random_state):\n return cls(universe_size, list(_SetSizeGenerator(num_sets, set_size)),\n freq_rates, random_state, freq_cap)\n\n return f\n\n @classmethod\n def get_generator_factory_with_set_size_list(cls, universe_size,\n set_size_list, freq_rates,\n freq_cap):\n\n def f(random_state):\n return cls(universe_size, set_size_list, freq_rates, random_state,\n freq_cap)\n\n return f\n\n def _truncated_poisson_pmf(self, mu, max_freq):\n \"\"\"Probability mass function values of the truncated poisson.\n\n The PMF of the poisson distribution with parameter mu is given by:\n\n f(k) = exp(-mu) * mu^k / k!\n\n The truncated poisson pmf has value f(k) for k < max_freq. \n For k = max_freq, the value is equal to 1 - sum_{i=0}^{k-1} f(k).\n\n Args:\n mu: float, rate parameter\n max_freq: int, truncation point\n\n Returns:\n A list of floats of length max_freq, representing the values of the\n truncating poisson PMF.\n \"\"\"\n assert mu > 0, \"Invalid rate parameter\"\n assert max_freq > 0, \"Invalid frequency parameter\"\n k = np.arange(max_freq-1)\n log_k_factorial = np.array([0] + list(np.cumsum(np.log(k[1:]))))\n log_poisson = -mu + k * np.log(mu) - log_k_factorial\n poisson_pmf = list(np.exp(log_poisson))\n poisson_pmf.append(1.0 - sum(poisson_pmf))\n return poisson_pmf\n\n def __init__(self, universe_size, set_sizes, freq_rates, random_state,\n freq_cap=100):\n \"\"\"Create a homogeneous multiset generator.\n\n Args:\n universe_size: An integer value that specifies the size of the whole\n universe from which the ids will be sampled.\n set_sizes: An iterable containing the size of each set, aka, the number of\n reached IDs.\n freq_rates: An iterable of the same size as set_sizes, specifying the\n non-negative freq_rate parameter of the shifted-Possion distribution.\n random_state: a numpy random state.\n freq_cap: A positive integer which represents the maximum number\n of times an ID can be seen in the returned set. \n\n Raises: AssertionError when (1) set_size_list and freq_rate_list do not\n have equal length, (2) elements of freq_rate_list are not all\n non-negative, or (3) freq_cap is not None or positive.\n \"\"\"\n set_size_list = list(set_sizes)\n freq_rate_list = list(freq_rates)\n \n assert len(set_size_list) == len(freq_rate_list), (\n 'set_sizes and freq_rates do not have equal length.')\n assert all([freq_rate >= 0 for freq_rate in freq_rate_list]), (\n 'Elements of freq_rate_list should be non-negative.')\n assert freq_cap > 0, 'freq_cap should be positive.'\n\n poisson_pmfs = []\n for mu in freq_rate_list:\n poisson_pmfs.append(self._truncated_poisson_pmf(mu, freq_cap-1))\n\n super().__init__(universe_size, set_size_list, poisson_pmfs, random_state)\n\n\nclass HeterogeneousMultiSetGenerator(SetGeneratorBase):\n \"\"\"Heterogeneous multiset generator.\n\n This generator returns the multisets as described in section\n Frequency scenario 2: Heterogeneous user frequency of this doc:\n\n https://github.com/world-federation-of-advertisers/cardinality_estimation_evaluation_framework/blob/master/doc/cardinality_and_frequency_estimation_evaluation_framework.md#frequency-scenario-2-heterogeneous-user-frequency\n Heterogeneous means that the reached ID's have different frequency\n distribution.\n\n As a reached ID may appear one or more times in the returned set,\n to differentiate with a normal set whose elements can only appear once, we\n use the term multiset.\n\n The frequency distribution is defined as a shifted-Poisson distribution.\n I.e., freq ~ Poission(freq_rate) + 1.\n \"\"\"\n\n @classmethod\n def get_generator_factory_with_num_and_size(cls, universe_size, num_sets,\n set_size, gamma_params,\n freq_cap):\n\n assert num_sets == len(gamma_params), (\n 'num_sets not equal to len(gamma_params)')\n\n def f(random_state):\n return cls(universe_size, list(_SetSizeGenerator(num_sets, set_size)),\n gamma_params, random_state, freq_cap)\n\n return f\n\n @classmethod\n def get_generator_factory_with_set_size_list(cls, universe_size,\n set_size_list, gamma_params,\n freq_cap):\n\n assert len(set_size_list) == len(gamma_params), (\n 'set_size_list and gamma_params do not have equal length.')\n\n def f(random_state):\n return cls(universe_size, set_size_list, gamma_params, random_state,\n freq_cap)\n\n return f\n\n def __init__(self, universe_size, set_sizes, gamma_params, random_state,\n freq_cap=None):\n \"\"\"Create a heterogeneous multiset generator.\n\n Args:\n universe_size: An integer value that specifies the size of the whole\n universe from which the ids will be sampled.\n set_sizes: An iterable specifying the size of each set, aka, the number of\n reached IDs.\n gamma_params: An iterable of the same size as set_sizes, specifying the\n shape and rate parameters of the gamma distributions.\n random_state: a numpy random state.\n freq_cap: An optional positive integer which represents the maximum number\n of times an ID can be seen in the returned set. If not set, will not\n apply this capping.\n\n Raises: AssertionError when (1) set_sizes and gamma_params do not\n have equal length, (2) elements of gamma_params are not all\n non-negative, or (3) freq_cap is not None or positive.\n \"\"\"\n self.set_sizes = list(set_sizes)\n self.gamma_params = list(gamma_params)\n\n assert len(self.set_sizes) == len(self.gamma_params), (\n 'set_sizes and gamma_params do not have equal length.')\n assert all([params[0] > 0 for params in self.gamma_params]), (\n 'Gamma shape parameters must be positive.')\n assert all([params[1] > 0 for params in self.gamma_params]), (\n 'Gamma rate parameters must be positive.')\n assert freq_cap is None or freq_cap > 0, (\n 'freq_cap should be None or positive.')\n\n self.universe_size = universe_size\n self.freq_cap = freq_cap\n self.random_state = random_state\n\n def __iter__(self):\n for set_size, gamma_params in zip(self.set_sizes, self.gamma_params):\n set_ids = choice_fast(self.universe_size, set_size, self.random_state)\n rate_parameters = self.random_state.gamma(shape=gamma_params[0],\n scale=gamma_params[1],\n size=set_size)\n frequencies = self.random_state.poisson(lam=rate_parameters,\n size=set_size) + 1\n if self.freq_cap:\n frequencies = np.minimum(frequencies, self.freq_cap)\n multiset_ids = []\n for i, freq in zip(set_ids, frequencies):\n multiset_ids += [i] * freq\n self.random_state.shuffle(multiset_ids)\n yield multiset_ids\n return self\n\n\nclass PublisherConstantFrequencySetGenerator(HomogeneousPmfMultiSetGenerator):\n \"\"\"Frequency scenario 3: Publisher constant frequency\n\n This generator returns the multisets as described in section\n Frequency scenario 3: Publisher constant frequency\n doc:\n\n https://github.com/world-federation-of-advertisers/cardinality_estimation_evaluation_framework/blob/master/doc/cardinality_and_frequency_estimation_evaluation_framework.md#frequency-scenario-3-publisher-constant-frequency\n\n In the publisher constant frequency scenario, each publisher serves\n the same number of impressions to each user.\n \"\"\"\n\n @classmethod\n def get_generator_factory_with_num_and_size(cls, universe_size, num_sets,\n set_size, frequency):\n\n def f(random_state):\n return cls(universe_size, list(_SetSizeGenerator(num_sets, set_size)),\n frequency, random_state)\n\n return f\n\n @classmethod\n def get_generator_factory_with_set_size_list(cls, universe_size,\n set_size_list, frequency):\n\n\n def f(random_state):\n return cls(universe_size, set_size_list, frequency, random_state)\n\n return f\n\n def __init__(self, universe_size, set_sizes, frequency, random_state):\n \"\"\"Create a publisher constant frequency set generator.\n\n Args:\n universe_size: An integer value that specifies the size of the whole\n universe from which the ids will be sampled.\n set_sizes: An iterable containing the size of each set, aka, the number of\n reached IDs.\n frequency: The frequency that will be assigned to each of the generated\n IDs.\n random_state: a numpy random state.\n\n Raises: AssertionError when (1) non-positive set_size is set_size_list, \n (2) frequency is non-positive.\n \"\"\"\n\n set_size_list = list(set_sizes)\n \n assert all([s > 0 for s in set_size_list]), (\n 'Non-positive set size was found in set_size_list.')\n assert frequency > 0, 'Non-positive frequency given'\n\n pmf_list = [[0] * (frequency - 1) + [1]] * len(set_size_list)\n super().__init__(universe_size, set_size_list, pmf_list, random_state)\n" ]
[ [ "numpy.arange", "numpy.log", "numpy.exp", "numpy.minimum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aneeshnaik/HernquistFlows
[ "7f81f9b47297b115ae6b593593aac59afafc48b3" ]
[ "figures/fig2_derivs.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nFigure 2: Gradients of isotropic Hernquist DF and reconstructions.\n\nCreated: May 2021\nAuthor: A. P. Naik\n\"\"\"\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import SymLogNorm\nfrom os.path import exists\n\nsys.path.append(\"../src\")\nfrom constants import M_sun, kpc, G\nfrom hernquist import calc_DF_iso as df_exact\nfrom utils import diff_DF\nfrom ml import load_flow, calc_DF_ensemble as df_model\n\n\nif __name__ == \"__main__\":\n\n # hernquist params and scalings\n M = 1e+10 * M_sun\n a = 5 * kpc\n u_q = 10 * a\n u_p = np.sqrt(2 * G * M / a)\n\n # coord grid extents\n x_lim = 3 * a\n vx_lim = 1.1 * np.sqrt(2 * G * M / a)\n\n # check if plot data exists, otherwise generate\n dfile = \"fig2_data.npz\"\n if not exists(dfile):\n\n # load flows\n n_flows = 30\n flows = []\n for i in range(n_flows):\n fname = f\"../nflow_models/hq_iso_orig/{i}_best.pth\"\n flows.append(load_flow(fname, 6, 8, 64))\n\n # coordinate grid for gradient panels\n N_grid = 128\n x_arr = np.linspace(-x_lim, x_lim, N_grid)\n vx_arr = np.linspace(-vx_lim, vx_lim, N_grid)\n x_grid, vx_grid = np.meshgrid(x_arr, vx_arr, indexing='ij')\n x_grid = x_grid.reshape(N_grid**2)\n vx_grid = vx_grid.reshape(N_grid**2)\n zeros = np.zeros_like(x_grid)\n pos = np.stack((x_grid, zeros, zeros), axis=-1)\n vel = np.stack((vx_grid, zeros, zeros), axis=-1)\n\n # reference point\n x0 = np.array([a, 0, 0])\n v0 = np.array([0.5 * np.sqrt(G * M / (2 * a)), 0, 0])\n\n # evaluate exact DF gradients on grid\n df_args = {'M': M, 'a': a}\n dx_ref, dvx_ref = diff_DF(x0, v0, df_func=df_exact, df_args=df_args)\n gradxf, gradvf = diff_DF(pos, vel, df_exact, df_args)\n gradxf /= dx_ref[0]\n gradvf /= dvx_ref[0]\n dfdx0 = gradxf[:, 0].reshape((N_grid, N_grid))\n dfdz0 = gradxf[:, 2].reshape((N_grid, N_grid))\n dfdvx0 = gradvf[:, 0].reshape((N_grid, N_grid))\n dfdvz0 = gradvf[:, 2].reshape((N_grid, N_grid))\n\n # ditto model gradients\n df_args = {'u_q': u_q, 'u_p': u_p, 'flows': flows}\n dx_ref, dvx_ref = diff_DF(x0, v0, df_func=df_model, df_args=df_args)\n gradxf, gradvf = diff_DF(pos, vel, df_func=df_model, df_args=df_args)\n gradxf /= dx_ref[0]\n gradvf /= dvx_ref[0]\n dfdx1 = gradxf[:, 0].reshape((N_grid, N_grid))\n dfdz1 = gradxf[:, 2].reshape((N_grid, N_grid))\n dfdvx1 = gradvf[:, 0].reshape((N_grid, N_grid))\n dfdvz1 = gradvf[:, 2].reshape((N_grid, N_grid))\n\n # residuals\n with np.errstate(divide='ignore', invalid='ignore'):\n resdx = np.divide((dfdx1 - dfdx0), dfdx0)\n resdvx = np.divide((dfdvx1 - dfdvx0), dfdvx0)\n\n # save data file\n np.savez(dfile, dfdx0=dfdx0, dfdvx0=dfdvx0, dfdx1=dfdx1, dfdvx1=dfdvx1,\n resdx=resdx, resdvx=resdvx)\n\n else:\n # load data file\n data = np.load(dfile)\n dfdx0 = data['dfdx0']\n dfdvx0 = data['dfdvx0']\n dfdx1 = data['dfdx1']\n dfdvx1 = data['dfdvx1']\n resdx = data['resdx']\n resdvx = data['resdvx']\n\n # set up figure\n fig = plt.figure(figsize=(3.3, 4.5), dpi=150)\n bottom = 0.07\n top = 0.94\n left = 0.135\n right = 0.775\n CdX = 0.035\n dX = (right - left) / 2\n dY = (top - bottom) / 3\n\n # plot settings\n plt.rcParams['text.usetex'] = True\n plt.rcParams['font.family'] = 'serif'\n plt.rcParams['font.size'] = 9\n plt.rcParams['ytick.labelsize'] = 8\n plt.rcParams['xtick.labelsize'] = 8\n extent = [-x_lim / a, x_lim / a, -vx_lim / u_p, vx_lim / u_p]\n labels = ['Exact', 'Model', 'Residuals']\n norm = SymLogNorm(1e-6, vmax=2e+6, vmin=-2e+6, base=10)\n imargs1 = {\n 'extent': extent, 'origin': 'lower', 'aspect': 'auto',\n 'cmap': 'BrBG', 'norm': norm\n }\n imargs2 = {\n 'extent': extent, 'origin': 'lower', 'aspect': 'auto',\n 'cmap': 'Spectral_r', 'vmax': 0.75, 'vmin': -0.75\n }\n\n # loop over columns\n for i in range(2):\n\n # add panels\n X = left + i * dX\n Y1 = bottom + 2 * dY\n Y2 = bottom + 1 * dY\n Y3 = bottom\n ax1 = fig.add_axes([X, Y1, dX, dY])\n ax2 = fig.add_axes([X, Y2, dX, dY])\n ax3 = fig.add_axes([X, Y3, dX, dY])\n\n # plot\n f0 = [dfdx0, dfdvx0][i]\n f1 = [dfdx1, dfdvx1][i]\n res = [resdx, resdvx][i]\n im1 = ax1.imshow(f0.T, **imargs1)\n im2 = ax2.imshow(f1.T, **imargs1)\n im3 = ax3.imshow(res.T, **imargs2)\n\n # labels, ticks, etc.\n t = [r'$\\partial F / \\partial x$', r'$\\partial F / \\partial v_x$'][i]\n ax1.text(0.5, 1.1, t, ha='center', transform=ax1.transAxes)\n if i == 1:\n for j in range(3):\n ax = [ax1, ax2, ax3][j]\n bbox = dict(boxstyle='round', facecolor='white', alpha=1)\n ax.text(0, 0.925, labels[j], ha='center', va='top',\n transform=ax.transAxes, bbox=bbox, zorder=100)\n if i == 0:\n ax2.set_ylabel(r'$v_x\\ /\\ v_\\mathrm{esc}(r=0)$')\n ax2.yaxis.set_label_coords(-0.28, 0.5, transform=ax2.transAxes)\n if i == 1:\n ax3.set_xlabel(r'$x\\ /\\ a$')\n ax3.xaxis.set_label_coords(0, -0.13, transform=ax3.transAxes)\n for ax in [ax1, ax2, ax3]:\n ax.tick_params(right=True, top=True, direction='inout')\n ax.set_yticks([-1., -0.5, 0., 0.5, 1.])\n if i == 1:\n ax.tick_params(labelleft=False)\n\n # colourbars\n cax1 = fig.add_axes([left + 2 * dX, bottom + dY, CdX, 2 * dY])\n cax2 = fig.add_axes([left + 2 * dX, bottom, CdX, dY])\n cbar1 = plt.colorbar(im1, cax=cax1)\n cbar2 = plt.colorbar(im3, cax=cax2)\n ticks = [\n -1e+5, -1e+3, -1e+1, -1e-1, -1e-3, -1e-5,\n 0,\n 1e-5, 1e-3, 1e-1, 1e+1, 1e+3, 1e+5\n ]\n cbar1.set_ticks(ticks)\n cax1.set_ylabel(r\"$\\nabla F\\ /\\ \\nabla F |_\\mathrm{ref}$\")\n cax2.set_ylabel(r\"Model / Exact - 1\")\n\n # save\n fig.savefig(\"fig2_derivs.pdf\")\n" ]
[ [ "numpy.savez", "numpy.sqrt", "numpy.linspace", "matplotlib.colors.SymLogNorm", "numpy.stack", "matplotlib.pyplot.colorbar", "numpy.zeros_like", "numpy.errstate", "numpy.load", "numpy.array", "numpy.meshgrid", "numpy.divide", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
theonov13/pyscf
[ "490a20d406b33c5d168ae4152d5422cff516b3ea" ]
[ "pyscf/lib/gto/test/test_gridao.py" ]
[ "#!/usr/bin/env python\n# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ctypes\nimport unittest\nimport numpy\nfrom pyscf import lib, gto, df\nfrom pyscf.gto.eval_gto import BLKSIZE\n\nlibcgto = lib.load_library('libdft')\n\nmol = gto.M(atom='''\n O 0.5 0.5 0.\n H 1. 1.2 0.\n H 0. 0. 1.3\n ''',\n basis='ccpvqz')\n\ndef eval_gto(mol, eval_name, coords,\n comp=1, shls_slice=None, non0tab=None, ao_loc=None, out=None):\n atm = numpy.asarray(mol._atm, dtype=numpy.int32, order='C')\n bas = numpy.asarray(mol._bas, dtype=numpy.int32, order='C')\n env = numpy.asarray(mol._env, dtype=numpy.double, order='C')\n coords = numpy.asarray(coords, dtype=numpy.double, order='F')\n natm = atm.shape[0]\n nbas = bas.shape[0]\n ngrids = coords.shape[0]\n if ao_loc is None:\n ao_loc = gto.moleintor.make_loc(bas, eval_name)\n\n if shls_slice is None:\n shls_slice = (0, nbas)\n sh0, sh1 = shls_slice\n nao = ao_loc[sh1] - ao_loc[sh0];\n if 'spinor' in eval_name:\n ao = numpy.ndarray((2,comp,nao,ngrids), dtype=numpy.complex128, buffer=out)\n else:\n ao = numpy.ndarray((comp,nao,ngrids), buffer=out)\n\n if non0tab is None:\n non0tab = numpy.ones(((ngrids+BLKSIZE-1)//BLKSIZE,nbas),\n dtype=numpy.int8)\n\n drv = getattr(libcgto, eval_name)\n drv(ctypes.c_int(ngrids),\n (ctypes.c_int*2)(*shls_slice), ao_loc.ctypes.data_as(ctypes.c_void_p),\n ao.ctypes.data_as(ctypes.c_void_p),\n coords.ctypes.data_as(ctypes.c_void_p),\n non0tab.ctypes.data_as(ctypes.c_void_p),\n atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(natm),\n bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(nbas),\n env.ctypes.data_as(ctypes.c_void_p))\n\n ao = numpy.swapaxes(ao, -1, -2)\n if comp == 1:\n if 'spinor' in eval_name:\n ao = ao[:,0]\n else:\n ao = ao[0]\n return ao\n\nPTR_ENV_START = 20\nCHARGE_OF = 0\nPTR_COORD = 1\nNUC_MOD_OF = 2\nPTR_ZETA = 3\nRAD_GRIDS = 4\nANG_GRIDS = 5\nATM_SLOTS = 6\nATOM_OF = 0\nANG_OF = 1\nNPRIM_OF = 2\nNCTR_OF = 3\nKAPPA_OF = 4\nPTR_EXP = 5\nPTR_COEFF = 6\nBAS_SLOTS = 8\nnatm = 4\nnbas = 0\natm = numpy.zeros((natm,ATM_SLOTS), dtype=numpy.int32)\nbas = numpy.zeros((1000,BAS_SLOTS), dtype=numpy.int32)\nenv = numpy.zeros(10000)\noff = PTR_ENV_START\nfor i in range(natm):\n atm[i, CHARGE_OF] = (i+1)*2\n atm[i, PTR_COORD] = off\n env[off+0] = .2 * (i+1)\n env[off+1] = .3 + (i+1) * .5\n env[off+2] = .1 - (i+1) * .5\n off += 3\noff0 = off\n# basis with kappa > 0\nnh = 0\nbas[nh,ATOM_OF ] = 0\nbas[nh,ANG_OF ] = 1\nbas[nh,KAPPA_OF] = 1\nbas[nh,NPRIM_OF] = 1\nbas[nh,NCTR_OF ] = 1\nbas[nh,PTR_EXP] = off\nenv[off+0] = 1\nbas[nh,PTR_COEFF] = off + 1\nenv[off+1] = 1\noff += 2\nnh += 1\nbas[nh,ATOM_OF ] = 1\nbas[nh,ANG_OF ] = 2\nbas[nh,KAPPA_OF] = 2\nbas[nh,NPRIM_OF] = 2\nbas[nh,NCTR_OF ] = 2\nbas[nh,PTR_EXP] = off\nenv[off+0] = 5\nenv[off+1] = 3\nbas[nh,PTR_COEFF] = off + 2\nenv[off+2] = 1\nenv[off+3] = 2\nenv[off+4] = 4\nenv[off+5] = 1\noff += 6\nnh += 1\nbas[nh,ATOM_OF ] = 2\nbas[nh,ANG_OF ] = 3\nbas[nh,KAPPA_OF] = 3\nbas[nh,NPRIM_OF] = 1\nbas[nh,NCTR_OF ] = 1\nbas[nh,PTR_EXP ] = off\nenv[off+0] = 1\nbas[nh,PTR_COEFF] = off + 1\nenv[off+1] = 1\noff += 2\nnh += 1\nbas[nh,ATOM_OF ] = 3\nbas[nh,ANG_OF ] = 4\nbas[nh,KAPPA_OF] = 4\nbas[nh,NPRIM_OF] = 1\nbas[nh,NCTR_OF ] = 1\nbas[nh,PTR_EXP ] = off\nenv[off+0] = .5\nbas[nh,PTR_COEFF] = off + 1\nenv[off+1] = 1.\noff = off + 2\nnh += 1\n\nnbas = nh\n# basis with kappa < 0\nn = off - off0\nfor i in range(n):\n env[off+i] = env[off0+i]\nfor i in range(nh):\n bas[i+nh,ATOM_OF ] = bas[i,ATOM_OF ]\n bas[i+nh,ANG_OF ] = bas[i,ANG_OF ] - 1\n bas[i+nh,KAPPA_OF] =-bas[i,KAPPA_OF]\n bas[i+nh,NPRIM_OF] = bas[i,NPRIM_OF]\n bas[i+nh,NCTR_OF ] = bas[i,NCTR_OF ]\n bas[i+nh,PTR_EXP ] = bas[i,PTR_EXP ] + n\n bas[i+nh,PTR_COEFF]= bas[i,PTR_COEFF] + n\n env[bas[i+nh,PTR_COEFF]] /= 2 * env[bas[i,PTR_EXP]]\nenv[bas[5,PTR_COEFF]+0] = env[bas[1,PTR_COEFF]+0] / (2 * env[bas[1,PTR_EXP]+0])\nenv[bas[5,PTR_COEFF]+1] = env[bas[1,PTR_COEFF]+1] / (2 * env[bas[1,PTR_EXP]+1])\nenv[bas[5,PTR_COEFF]+2] = env[bas[1,PTR_COEFF]+2] / (2 * env[bas[1,PTR_EXP]+0])\nenv[bas[5,PTR_COEFF]+3] = env[bas[1,PTR_COEFF]+3] / (2 * env[bas[1,PTR_EXP]+1])\n\nmol1 = gto.Mole()\nmol1._atm = atm\nmol1._bas = bas[:nh*2]\nmol1._env = env\nmol1._built = True\n\n\nnumpy.random.seed(1)\nngrids = 2000\ncoords = numpy.random.random((ngrids,3))\ncoords = (coords-.5)**2 * 80\n\ndef tearDownModule():\n global mol, mol1, coords\n del mol, mol1, coords\n\n\nclass KnownValues(unittest.TestCase):\n def test_sph(self):\n ao = eval_gto(mol, 'GTOval_sph', coords)\n self.assertAlmostEqual(lib.fp(ao), -6.8109234394857712, 9)\n\n def test_cart(self):\n ao = eval_gto(mol, 'GTOval_cart', coords)\n self.assertAlmostEqual(lib.fp(ao), -16.384888666900274, 9)\n\n def test_ip_cart(self):\n ao = eval_gto(mol, 'GTOval_ip_cart', coords, comp=3)\n self.assertAlmostEqual(lib.fp(ao), 94.04527465181198, 9)\n\n def test_sph_deriv1(self):\n ao = eval_gto(mol, 'GTOval_sph_deriv1', coords, comp=4)\n self.assertAlmostEqual(lib.fp(ao), -45.129633361047482, 9)\n\n def test_sph_deriv2(self):\n ao = eval_gto(mol, 'GTOval_sph_deriv2', coords, comp=10)\n self.assertAlmostEqual(lib.fp(ao), -88.126901222477954, 9)\n\n def test_sph_deriv3(self):\n ao = eval_gto(mol, 'GTOval_sph_deriv3', coords, comp=20)\n self.assertAlmostEqual(lib.fp(ao), -402.84257273073263, 9)\n\n def test_sph_deriv4(self):\n ao = eval_gto(mol, 'GTOval_sph_deriv4', coords, comp=35)\n self.assertAlmostEqual(lib.fp(ao), 4933.0635429300246, 9)\n\n def test_shls_slice(self):\n ao0 = eval_gto(mol, 'GTOval_ip_cart', coords, comp=3)\n ao1 = ao0[:,:,14:77]\n ao = eval_gto(mol, 'GTOval_ip_cart', coords, comp=3, shls_slice=(7, 19))\n self.assertAlmostEqual(abs(ao-ao1).sum(), 0, 9)\n\n def test_ig_sph(self):\n ao = eval_gto(mol, 'GTOval_ig_sph', coords, comp=3)\n self.assertAlmostEqual(lib.fp(ao), 8.6601301646129052, 9)\n\n def test_ipig_sph(self):\n ao = eval_gto(mol, 'GTOval_ipig_sph', coords, comp=9)\n self.assertAlmostEqual(lib.fp(ao), -53.56608497643537, 9)\n\n def test_spinor(self):\n ao = eval_gto(mol, 'GTOval_spinor', coords)\n self.assertAlmostEqual(lib.fp(ao), -4.5941099464020079+5.9444339000526707j, 9)\n\n def test_sp_spinor(self):\n ao = eval_gto(mol, 'GTOval_sp_spinor', coords)\n self.assertAlmostEqual(lib.fp(ao), 26.212937567473656-68.970076521029782j, 9)\n\n numpy.random.seed(1)\n rs = numpy.random.random((213,3))\n rs = (rs-.5)**2 * 30\n ao1 = eval_gto(mol1, 'GTOval_spinor', rs, shls_slice=(0,mol1.nbas//2))\n ao2 = eval_gto(mol1, 'GTOval_sp_spinor', rs, shls_slice=(mol1.nbas//2,mol1.nbas))\n self.assertAlmostEqual(abs(ao1-ao2*1j).sum(), 0, 9)\n#\n# t = gto.cart2j_kappa(0, 2)\n# aonr = eval_gto(mol1, 'GTOval_cart', rs, shls_slice=(1,2))\n# aa = numpy.zeros((2,12))\n# aa[:1,:6] = aonr[:,:6]\n# aa[1:,6:] = aonr[:,:6]\n# print aa.dot(t[:,:4])\n#\n# t = gto.cart2j_kappa(0, 1)/0.488602511902919921\n# aonr = eval_gto(mol1, 'GTOval_ip_cart', rs, comp=3, shls_slice=(mol1.nbas//2+1,mol1.nbas//2+2))\n# print 'x', aonr[0,0,:3]\n# print 'y', aonr[1,0,:3]\n# print 'z', aonr[2,0,:3]\n# aa = numpy.zeros((3,2,6),dtype=numpy.complex)\n# aa[0,:1,3:] = aonr[0,0,:3]\n# aa[0,1:,:3] = aonr[0,0,:3]\n# aa[1,:1,3:] =-aonr[1,0,:3]*1j\n# aa[1,1:,:3] = aonr[1,0,:3]*1j\n# aa[2,:1,:3] = aonr[2,0,:3]\n# aa[2,1:,3:] =-aonr[2,0,:3]\n# aa = (aa[0]*-1j + aa[1]*-1j + aa[2]*-1j)\n# print 'p',aa.dot(t[:,2:])*1j\n\n def test_ip_spinor(self):\n ao = eval_gto(mol, 'GTOval_ip_spinor', coords, comp=3)\n self.assertAlmostEqual(lib.fp(ao), -52.516545034166775+24.765350351395604j, 9)\n\n def test_ipsp_spinor(self):\n ao = eval_gto(mol, 'GTOval_ipsp_spinor', coords, comp=3)\n self.assertAlmostEqual(lib.fp(ao), -159.94403505490939+400.80148912086418j, 9)\n\n numpy.random.seed(1)\n rs = numpy.random.random((213,3))\n rs = (rs-.5)**2 * 30\n ao1 = eval_gto(mol1, 'GTOval_ip_spinor', rs, comp=3, shls_slice=(0,mol1.nbas//2))\n ao2 = eval_gto(mol1, 'GTOval_ipsp_spinor', rs, comp=3, shls_slice=(mol1.nbas//2,mol1.nbas))\n self.assertAlmostEqual(abs(ao1-ao2*1j).sum(), 0, 9)\n\n def test_int1e_grids(self):\n mol1 = gto.M(atom='''\nO 0.5 0.5 0.\nH 1. 1.2 0.\nH 0. 0. 1.3''', basis='ccpvtz')\n ngrids = 201\n grids = numpy.random.random((ngrids, 3)) * 12 - 5\n fmol = gto.fakemol_for_charges(grids)\n ref = df.incore.aux_e2(mol1, fmol, intor='int3c2e').transpose(2,0,1)\n j3c = mol1.intor('int1e_grids', grids=grids)\n self.assertAlmostEqual(abs(j3c - ref).max(), 0, 12)\n\n ref = df.incore.aux_e2(mol1, fmol, intor='int3c2e_cart').transpose(2,0,1)\n j3c = mol1.intor('int1e_grids_cart', grids=grids)\n self.assertAlmostEqual(abs(j3c - ref).max(), 0, 12)\n\n ref = df.incore.aux_e2(mol1, fmol, intor='int3c2e_spinor').transpose(2,0,1)\n j3c = mol1.intor('int1e_grids_spinor', grids=grids)\n self.assertAlmostEqual(abs(j3c - ref).max(), 0, 12)\n\n def test_int1e_grids_ip(self):\n ngrids = 201\n grids = numpy.random.random((ngrids, 3)) * 12 - 5\n fmol = gto.fakemol_for_charges(grids)\n ref = df.incore.aux_e2(mol1, fmol, intor='int3c2e_ip1').transpose(0,3,1,2)\n j3c = mol1.intor('int1e_grids_ip', grids=grids)\n self.assertAlmostEqual(abs(j3c - ref).max(), 0, 12)\n\n ref = df.incore.aux_e2(mol1, fmol, intor='int3c2e_ip1_cart').transpose(0,3,1,2)\n j3c = mol1.intor('int1e_grids_ip_cart', grids=grids)\n self.assertAlmostEqual(abs(j3c - ref).max(), 0, 12)\n\n ref = df.incore.aux_e2(mol1, fmol, intor='int3c2e_ip1_spinor').transpose(0,3,1,2)\n j3c = mol1.intor('int1e_grids_ip_spinor', grids=grids)\n self.assertAlmostEqual(abs(j3c - ref).max(), 0, 12)\n\n def test_int1e_grids_spvsp(self):\n ngrids = 201\n grids = numpy.random.random((ngrids, 3)) * 12 - 5\n fmol = gto.fakemol_for_charges(grids)\n ref = df.r_incore.aux_e2(mol, fmol, intor='int3c2e_spsp1_spinor').transpose(2,0,1)\n j3c = mol.intor('int1e_grids_spvsp_spinor', grids=grids)\n self.assertAlmostEqual(abs(j3c - ref).max(), 0, 12)\n\n\nif __name__ == '__main__':\n print('Full Tests for grid_ao and grids_ints')\n unittest.main()\n" ]
[ [ "numpy.swapaxes", "numpy.random.random", "numpy.random.seed", "numpy.asarray", "numpy.ndarray", "numpy.ones", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
fabienbaradel/object_level_visual_reasoning
[ "f504715c2ea9464e8dd4076584c30ab34937de22" ]
[ "loader/videodataset.py" ]
[ "from __future__ import print_function\nimport torch\nimport torch.utils.data as data\nfrom torchvision import transforms\nimport os\nimport random\nfrom PIL import Image\nimport numpy as np\nimport ipdb\nimport pickle\nfrom pycocotools import mask as maskUtils\nimport lintel\nimport time\nfrom torch.utils.data.dataloader import default_collate\nfrom random import shuffle\nfrom abc import abstractmethod, ABCMeta\nimport torch.nn.functional as F\n\n\nclass VideoDataset(data.Dataset):\n __metaclass__ = ABCMeta\n \"\"\"\n Generic loader for videos dataset\n \"\"\"\n\n def __init__(self, options, nb_classes=30,\n dataset='train',\n nb_crops=1,\n #\n usual_transform=False,\n add_background=True,\n #\n video_dir='videos_256x256_30', mask_dir='masks/preds_100x100_50',\n #\n nb_obj_t_max=10, mask_confidence=0.5,\n video_suffix='.mp4',\n mask_size=28,\n w=224, h=224):\n # Settings\n self.root = options['root']\n self.w = w\n self.h = h\n self.t = options['t']\n self.video_dir = video_dir\n self.nb_classes = nb_classes\n self.usual_transform = usual_transform\n self.nb_obj_max_t = nb_obj_t_max\n self.mask_confidence = mask_confidence\n self.video_dir_full = os.path.join(self.root, self.video_dir)\n self.video_suffix = video_suffix\n self.mask_dir = mask_dir\n self.mask_dir_full = os.path.join(self.root, self.mask_dir)\n self.nb_crops = nb_crops\n self.dataset = dataset\n self.w_mask, self.h_mask = mask_size, mask_size\n self.dict_video_length_fn = os.path.join(self.video_dir_full, 'dict_id_length.pickle')\n self.minus_len = 2\n self.add_background = add_background\n self.video_label_pickle = ''\n self.list_video = []\n\n # Retrieve the real shape of the super_video\n self.retrieve_w_and_h_from_dir()\n\n # Max length of a clip\n self.max_len_clip = 3 * self.real_fps # sec by fps -> num of frames - 3 seconds\n\n # Video and length\n # self.list_video, self.dict_video_length = self.get_video_and_length()\n\n def store_dict_video_into_pickle(self, dict_video_label, dataset):\n with open(self.video_label_pickle, 'wb') as file:\n pickle.dump(dict_video_label, file, protocol=pickle.HIGHEST_PROTOCOL)\n print(\"Dict_video_label of {} saved! -> {}\\n\".format(dataset, self.video_label_pickle))\n\n def get_video_and_length(self):\n # Open the pickle file\n with open(self.dict_video_length_fn, 'rb') as file:\n dict_video_length = pickle.load(file)\n\n # Loop in each super_video dir to get th right super_video file\n list_video = []\n for video_id, length in dict_video_length.items():\n # Video id\n real_id = int(video_id.split('/')[1])\n list_video.append(real_id)\n\n return list_video, dict_video_length\n\n def retrieve_w_and_h_from_dir(self):\n _, w_h, fps = self.video_dir.split('_')\n w, h = w_h.split('x')\n self.real_w, self.real_h, self.real_fps = int(w), int(h), int(fps)\n self.ratio_real_crop_w, self.ratio_real_crop_h = self.real_w / self.w, self.real_h / self.h\n self.real_mask_w, self.real_mask_h = int(self.ratio_real_crop_w * self.w_mask), int(\n self.ratio_real_crop_h * self.h_mask)\n\n def time_sampling(self, video_len):\n # update the video_len on some dataset\n video_len = video_len - self.minus_len\n\n # Check that the super_video is not too long\n diff = self.max_len_clip - video_len\n\n # Change the start and adapt the length of the super_video\n if diff >= 0:\n start = 0\n else:\n start = random.sample(range(abs(diff)), 1)[0]\n\n video_len_up = video_len - start\n\n # Size of the sub-seq\n len_subseq = video_len_up / float(self.t)\n\n # Sample over each bin and add the start time\n if self.dataset != 'train' and self.nb_crops == 1:\n timesteps = [int((len_subseq / 2.0) + t * len_subseq + start) for t in range(self.t)]\n else:\n timesteps = [int(random.sample(range(int(len_subseq)), 1)[0] + t * len_subseq + start) for t in\n range(self.t)]\n\n return timesteps\n\n def extract_frames(self, video_file, timesteps):\n\n with open(video_file, 'rb') as f:\n encoded_video = f.read()\n\n decoded_frames = lintel.loadvid_frame_nums(encoded_video,\n frame_nums=timesteps,\n width=self.real_w,\n height=self.real_h)\n try:\n np_clip = np.frombuffer(decoded_frames, dtype=np.uint8)\n np_clip = np.reshape(np_clip,\n newshape=(len(timesteps), self.real_h, self.real_w, 3))\n np_clip = np_clip.transpose([3, 0, 1, 2])\n np_clip = np.float32(np_clip)\n except Exception as e:\n np_clip = decoded_frames\n print(\"cannot decode the stream...\")\n return np_clip\n\n @staticmethod\n def load_masks(file):\n with open(file, 'rb') as f:\n masks = pickle.load(f, encoding='latin-1')\n return (masks['segms'], masks['boxes'])\n\n def retrieve_associated_masks(self, masks_file, video_len, timesteps, add_background_mask=True, start=0):\n T = len(timesteps)\n\n # update the timesteps dpending on the starting point\n timesteps = [t + start for t in timesteps]\n\n np_obj_id = np.zeros((T, self.nb_obj_max_t, 81)).astype(np.float32)\n np_bbox = np.zeros((T, self.nb_obj_max_t, 4)).astype(np.float32)\n np_masks = np.zeros((T, self.nb_obj_max_t, self.real_mask_h, self.real_mask_w)).astype(np.float32)\n np_max_nb_obj = np.asarray([self.nb_obj_max_t]).reshape((1,))\n\n try:\n # raise Exception\n segms, boxes = self.load_masks(masks_file)\n\n # Timestep factor\n factor = video_len / len(segms)\n timesteps = [int(t / factor) for t in timesteps]\n\n # Retrieve information\n list_nb_obj = []\n for t_for_clip, t in enumerate(timesteps):\n nb_obj_t = 0\n # Range of objects\n range_objects = list(range(2, 81))\n shuffle(range_objects)\n range_objects = [1] + range_objects\n for c in range_objects:\n for i in range(len(boxes[t][c])):\n if boxes[t][c][i] is not None and len(boxes[t][c]) > 0 and boxes[t][c][i][\n -1] > self.mask_confidence:\n # Obj id\n np_obj_id[t_for_clip, nb_obj_t, c] = 1\n\n # Bounding box\n H, W = segms[t][c][i]['size']\n x1, y1, x2, y2, _ = boxes[t][c][i]\n x1, x2 = (x1 / W) * self.real_w, (x2 / W) * self.real_w\n y1, y2 = (y1 / H) * self.real_h, (y2 / H) * self.real_h\n np_bbox[t_for_clip, nb_obj_t] = [x1, y1, x2, y2]\n\n # Masks\n rle_obj = segms[t][c][i]\n m = maskUtils.decode(rle_obj) # Python COCO API\n # My resize\n # m = resize(m, (H, W), (self.real_mask_h, self.real_mask_w), thresold=0.1\n # Resize\n m_pil = Image.fromarray(m)\n m_pil = m_pil.resize((self.real_mask_w, self.real_mask_h))\n m = np.array(m_pil, copy=False)\n np_masks[t_for_clip, nb_obj_t] = m\n\n nb_obj_t += 1\n\n # Break if too much objects\n if nb_obj_t > (self.nb_obj_max_t - 1):\n break\n # Break if too much objects\n if nb_obj_t > (self.nb_obj_max_t - 1):\n break\n\n # Append\n list_nb_obj.append(nb_obj_t)\n\n # And now fill numpy array\n np_max_nb_obj[0] = max(list_nb_obj)\n\n\n except Exception as e:\n print(\"mask reading problem: \", e)\n ipdb.set_trace()\n np_max_nb_obj[0] = 1.\n\n # Add the background mask\n if add_background_mask:\n # Find the background pixels\n sum_masks = np.clip(np.sum(np_masks, 1), 0, 1)\n background_mask = 1 - sum_masks\n\n # Add meta data about background\n idx_bg_mask = int(np_max_nb_obj[0])\n idx_bg_mask -= 1 if self.nb_obj_max_t == idx_bg_mask else 0\n np_masks[:, idx_bg_mask] = background_mask\n np_obj_id[:, idx_bg_mask, 0] = 1\n np_bbox[:, idx_bg_mask] = [0, 0, 1, 1]\n\n # Update the number of mask\n np_max_nb_obj[0] = np_max_nb_obj[0] + 1 if np_max_nb_obj < self.nb_obj_max_t else np_max_nb_obj[0]\n\n return (np_obj_id, np_bbox, np_masks, np_max_nb_obj)\n\n def video_transform(self, np_clip, np_masks, np_bbox):\n\n # Random crop\n _, _, h, w = np_clip.shape\n w_min, h_min = random.sample(range(w - self.w), 1)[0], random.sample(range(h - self.h), 1)[0]\n # clip\n np_clip = np_clip[:, :, h_min:(self.h + h_min), w_min:(self.w + w_min)]\n # mask\n h_min_mask, w_min_mask = round((h_min / self.h) * self.h_mask), round((w_min / self.w) * self.w_mask)\n np_masks = np_masks[:, :, h_min_mask:(self.h_mask + h_min_mask), w_min_mask:(self.w_mask + w_min_mask)]\n # bbox\n np_bbox[:, :, [0, 2]] = np.clip(np_bbox[:, :, [0, 2]] - w_min, 0, self.w)\n np_bbox[:, :, [1, 3]] = np.clip(np_bbox[:, :, [1, 3]] - h_min, 0, self.h)\n # rescale to 0->1\n np_bbox[:, :, [0, 2]] /= self.w\n np_bbox[:, :, [1, 3]] /= self.h\n\n if self.usual_transform:\n # Div by 255\n np_clip /= 255.\n\n # Normalization\n np_clip -= np.asarray([0.485, 0.456, 0.406]).reshape(3, 1, 1, 1) # mean\n np_clip /= np.asarray([0.229, 0.224, 0.225]).reshape(3, 1, 1, 1) # std\n\n return np_clip, np_masks, np_bbox\n\n @abstractmethod\n def get_mask_file(self, id):\n return\n\n @abstractmethod\n def starting_point(self, id):\n return\n\n @abstractmethod\n def get_video_fn(self, id):\n return\n\n @abstractmethod\n def get_length(self, id):\n return\n\n @abstractmethod\n def get_target(self, index):\n return\n\n def extract_one_clip(self, id):\n\n # Length\n length = self.get_length(id)\n\n # Start of the video\n start = self.starting_point(id) # 0 except for EPIC\n\n # Timesteps\n timesteps = self.time_sampling(length)\n\n return self.retrieve_clip_and_masks(id, timesteps, length, start)\n\n def retrieve_clip_and_masks(self, id, timesteps, length, start):\n # Clip\n np_clip = self.extract_frames(self.get_video_fn(id), timesteps)\n\n # Get the masks\n (np_obj_id, np_bbox, np_masks, np_max_nb_obj) = self.retrieve_associated_masks(self.get_mask_file(id),\n length,\n timesteps,\n add_background_mask=self.add_background,\n start=start)\n\n # Data processing on the super_video\n np_clip, np_masks, np_bbox = self.video_transform(np_clip, np_masks, np_bbox)\n\n return np_clip, np_masks, np_bbox, np_obj_id, np_max_nb_obj\n\n def extract_multiple_clips(self, id):\n # Length\n length = self.get_length(id)\n\n # Start of the video\n start = self.starting_point(id) # 0 except for EPIC\n\n # NB_CROPS times\n list_timesteps = [self.time_sampling(length) for _ in range(self.nb_crops)]\n timesteps_union = list(set().union(*list_timesteps))\n timesteps_union.sort(key=int) # sort numerically\n\n # Get the gathered data\n (np_clip_union, np_masks_union, np_bbox_union,\n np_obj_id_union, np_max_nb_obj_union) = self.retrieve_clip_and_masks(id,\n timesteps_union,\n length,\n start)\n\n # Loop and retreieve the data per clip\n list_np_clip, list_np_masks, list_np_bbox, list_np_obj_id = [], [], [], []\n for _, timesteps in enumerate(list_timesteps):\n # Get the idx from the timesteps union\n idx_union = [timesteps_union.index(time) for time in timesteps]\n\n # retrieve\n np_clip = np_clip_union[:, idx_union]\n np_masks = np_masks_union[idx_union]\n np_bbox = np_bbox_union[idx_union]\n np_obj_id = np_obj_id_union[idx_union]\n\n # append\n list_np_clip.append(np_clip)\n list_np_masks.append(np_masks)\n list_np_bbox.append(np_bbox)\n list_np_obj_id.append(np_obj_id)\n\n # stack\n np_clip = np.stack(list_np_clip)\n np_masks = np.stack(list_np_masks)\n np_obj_id = np.stack(list_np_obj_id)\n np_bbox = np.stack(list_np_bbox)\n\n return np_clip, np_masks, np_bbox, np_obj_id, np_max_nb_obj_union\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n Returns:\n dict: info about the video\n \"\"\"\n\n try:\n # Get the super_video dir\n id = self.list_video[index]\n\n # Target\n torch_target = self.get_target(id)\n\n # If nb_crops = 1 it is easy\n if self.nb_crops == 1:\n np_clip, np_masks, np_bbox, np_obj_id, np_max_nb_obj = self.extract_one_clip(id)\n else:\n np_clip, np_masks, np_bbox, np_obj_id, np_max_nb_obj = self.extract_multiple_clips(id)\n\n # Video id\n np_uint8_id = np.fromstring(str(id), dtype=np.uint8)\n torch_id = torch.from_numpy(np_uint8_id)\n torch_id = F.pad(torch_id, (0, 300))[:300]\n\n # Torch world\n torch_clip = torch.from_numpy(np_clip)\n torch_masks = torch.from_numpy(np_masks)\n torch_obj_id = torch.from_numpy(np_obj_id)\n torch_obj_bboxs = torch.from_numpy(np_bbox)\n torch_max_nb_objs = torch.from_numpy(np_max_nb_obj)\n\n return {\"target\": torch_target,\n \"clip\": torch_clip,\n \"mask\": torch_masks,\n \"obj_id\": torch_obj_id,\n \"obj_bbox\": torch_obj_bboxs,\n \"max_nb_obj\": torch_max_nb_objs,\n \"id\": torch_id\n }\n except Exception as e:\n return None\n\n def __len__(self):\n return len(self.list_video)\n\n def __repr__(self):\n fmt_str = 'Dataset ' + self.__class__.__name__ + '\\n'\n fmt_str += ' Number of datapoints: {}\\n'.format(self.__len__())\n return fmt_str\n\n\ndef my_collate(batch):\n batch = list(filter(lambda x: x is not None, batch))\n return default_collate(batch)\n" ]
[ [ "numpy.clip", "numpy.asarray", "torch.from_numpy", "numpy.stack", "numpy.frombuffer", "numpy.float32", "numpy.array", "numpy.zeros", "numpy.sum", "torch.nn.functional.pad", "torch.utils.data.dataloader.default_collate" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hb-jones/rp1-ros
[ "afc2888f5da7a2b4cc6d9e07ce017f26996e58c3" ]
[ "src/ueye_sample.py" ]
[ "#===========================================================================#\r\n# #\r\n# Copyright (C) 2006 - 2018 #\r\n# IDS Imaging Development Systems GmbH #\r\n# Dimbacher Str. 6-8 #\r\n# D-74182 Obersulm, Germany #\r\n# #\r\n# The information in this document is subject to change without notice #\r\n# and should not be construed as a commitment by IDS Imaging Development #\r\n# Systems GmbH. IDS Imaging Development Systems GmbH does not assume any #\r\n# responsibility for any errors that may appear in this document. #\r\n# #\r\n# This document, or source code, is provided solely as an example #\r\n# of how to utilize IDS software libraries in a sample application. #\r\n# IDS Imaging Development Systems GmbH does not assume any responsibility #\r\n# for the use or reliability of any portion of this document or the #\r\n# described software. #\r\n# #\r\n# General permission to copy or modify, but not for profit, is hereby #\r\n# granted, provided that the above copyright notice is included and #\r\n# reference made to the fact that reproduction privileges were granted #\r\n# by IDS Imaging Development Systems GmbH. #\r\n# #\r\n# IDS Imaging Development Systems GmbH cannot assume any responsibility #\r\n# for the use or misuse of any portion of this software for other than #\r\n# its intended diagnostic purpose in calibrating and testing IDS #\r\n# manufactured cameras and software. #\r\n# #\r\n#===========================================================================#\r\n\r\n# Developer Note: I tried to let it as simple as possible.\r\n# Therefore there are no functions asking for the newest driver software or freeing memory beforehand, etc.\r\n# The sole purpose of this program is to show one of the simplest ways to interact with an IDS camera via the uEye API.\r\n# (XS cameras are not supported)\r\n#---------------------------------------------------------------------------------------------------------------------------------------\r\n\r\n#Libraries\r\nfrom pyueye import ueye\r\nimport numpy as np\r\nimport cv2\r\nimport sys\r\n\r\n#---------------------------------------------------------------------------------------------------------------------------------------\r\n\r\n#Variables\r\nhCam = ueye.HIDS(0) #0: first available camera; 1-254: The camera with the specified camera ID\r\nsInfo = ueye.SENSORINFO()\r\ncInfo = ueye.CAMINFO()\r\npcImageMemory = ueye.c_mem_p()\r\nMemID = ueye.int()\r\nrectAOI = ueye.IS_RECT()\r\npitch = ueye.INT()\r\nnBitsPerPixel = ueye.INT(24) #24: bits per pixel for color mode; take 8 bits per pixel for monochrome\r\nchannels = 3 #3: channels for color mode(RGB); take 1 channel for monochrome\r\nm_nColorMode = ueye.INT()\t\t# Y8/RGB16/RGB24/REG32\r\nbytes_per_pixel = int(nBitsPerPixel / 8)\r\n#---------------------------------------------------------------------------------------------------------------------------------------\r\nprint(\"START\")\r\nprint()\r\n\r\n\r\n# Starts the driver and establishes the connection to the camera\r\nnRet = ueye.is_InitCamera(hCam, None)\r\nif nRet != ueye.IS_SUCCESS:\r\n print(\"is_InitCamera ERROR\")\r\n\r\n# Reads out the data hard-coded in the non-volatile camera memory and writes it to the data structure that cInfo points to\r\nnRet = ueye.is_GetCameraInfo(hCam, cInfo)\r\nif nRet != ueye.IS_SUCCESS:\r\n print(\"is_GetCameraInfo ERROR\")\r\n\r\n# You can query additional information about the sensor type used in the camera\r\nnRet = ueye.is_GetSensorInfo(hCam, sInfo)\r\nif nRet != ueye.IS_SUCCESS:\r\n print(\"is_GetSensorInfo ERROR\")\r\n\r\nnRet = ueye.is_ResetToDefault( hCam)\r\nif nRet != ueye.IS_SUCCESS:\r\n print(\"is_ResetToDefault ERROR\")\r\n\r\n# Set display mode to DIB\r\nnRet = ueye.is_SetDisplayMode(hCam, ueye.IS_SET_DM_DIB)\r\n\r\n# Set the right color mode\r\nif int.from_bytes(sInfo.nColorMode.value, byteorder='big') == ueye.IS_COLORMODE_BAYER:\r\n # setup the color depth to the current windows setting\r\n print(nBitsPerPixel)\r\n ueye.is_GetColorDepth(hCam, nBitsPerPixel, m_nColorMode)\r\n print(nBitsPerPixel)\r\n bytes_per_pixel = int(nBitsPerPixel / 8)\r\n print(\"IS_COLORMODE_BAYER: \", )\r\n print(\"\\tm_nColorMode: \\t\\t\", m_nColorMode)\r\n print(\"\\tnBitsPerPixel: \\t\\t\", nBitsPerPixel)\r\n print(\"\\tbytes_per_pixel: \\t\\t\", bytes_per_pixel)\r\n print()\r\n\r\nelif int.from_bytes(sInfo.nColorMode.value, byteorder='big') == ueye.IS_COLORMODE_CBYCRY:\r\n # for color camera models use RGB32 mode\r\n m_nColorMode = ueye.IS_CM_BGRA8_PACKED\r\n nBitsPerPixel = ueye.INT(32)\r\n bytes_per_pixel = int(nBitsPerPixel / 8)\r\n print(\"IS_COLORMODE_CBYCRY: \", )\r\n print(\"\\tm_nColorMode: \\t\\t\", m_nColorMode)\r\n print(\"\\tnBitsPerPixel: \\t\\t\", nBitsPerPixel)\r\n print(\"\\tbytes_per_pixel: \\t\\t\", bytes_per_pixel)\r\n print()\r\n\r\nelif int.from_bytes(sInfo.nColorMode.value, byteorder='big') == ueye.IS_COLORMODE_MONOCHROME:\r\n # for color camera models use RGB32 mode\r\n m_nColorMode = ueye.IS_CM_MONO8\r\n nBitsPerPixel = ueye.INT(8)\r\n bytes_per_pixel = int(nBitsPerPixel / 8)\r\n print(\"IS_COLORMODE_MONOCHROME: \", )\r\n print(\"\\tm_nColorMode: \\t\\t\", m_nColorMode)\r\n print(\"\\tnBitsPerPixel: \\t\\t\", nBitsPerPixel)\r\n print(\"\\tbytes_per_pixel: \\t\\t\", bytes_per_pixel)\r\n print()\r\n\r\nelse:\r\n # for monochrome camera models use Y8 mode\r\n m_nColorMode = ueye.IS_CM_MONO8\r\n nBitsPerPixel = ueye.INT(8)\r\n bytes_per_pixel = int(nBitsPerPixel / 8)\r\n print(\"else\")\r\n\r\n# Can be used to set the size and position of an \"area of interest\"(AOI) within an image\r\nnRet = ueye.is_AOI(hCam, ueye.IS_AOI_IMAGE_GET_AOI, rectAOI, ueye.sizeof(rectAOI))\r\nif nRet != ueye.IS_SUCCESS:\r\n print(\"is_AOI ERROR\")\r\n\r\nwidth = rectAOI.s32Width\r\nheight = rectAOI.s32Height\r\n\r\n# Prints out some information about the camera and the sensor\r\nprint(\"Camera model:\\t\\t\", sInfo.strSensorName.decode('utf-8'))\r\nprint(\"Camera serial no.:\\t\", cInfo.SerNo.decode('utf-8'))\r\nprint(\"Maximum image width:\\t\", width)\r\nprint(\"Maximum image height:\\t\", height)\r\nprint()\r\n\r\n#---------------------------------------------------------------------------------------------------------------------------------------\r\n\r\n# Allocates an image memory for an image having its dimensions defined by width and height and its color depth defined by nBitsPerPixel\r\nnRet = ueye.is_AllocImageMem(hCam, width, height, nBitsPerPixel, pcImageMemory, MemID)\r\nif nRet != ueye.IS_SUCCESS:\r\n print(\"is_AllocImageMem ERROR\")\r\nelse:\r\n # Makes the specified image memory the active memory\r\n nRet = ueye.is_SetImageMem(hCam, pcImageMemory, MemID)\r\n if nRet != ueye.IS_SUCCESS:\r\n print(\"is_SetImageMem ERROR\")\r\n else:\r\n # Set the desired color mode\r\n nRet = ueye.is_SetColorMode(hCam, m_nColorMode)\r\n\r\n\r\n\r\n# Activates the camera's live video mode (free run mode)\r\nnRet = ueye.is_CaptureVideo(hCam, ueye.IS_DONT_WAIT)\r\nif nRet != ueye.IS_SUCCESS:\r\n print(\"is_CaptureVideo ERROR\")\r\n\r\n# Enables the queue mode for existing image memory sequences\r\nnRet = ueye.is_InquireImageMem(hCam, pcImageMemory, MemID, width, height, nBitsPerPixel, pitch)\r\nif nRet != ueye.IS_SUCCESS:\r\n print(\"is_InquireImageMem ERROR\")\r\nelse:\r\n print(\"Press q to leave the programm\")\r\n\r\n#---------------------------------------------------------------------------------------------------------------------------------------\r\n\r\n# Continuous image display\r\nwhile(nRet == ueye.IS_SUCCESS):\r\n\r\n # In order to display the image in an OpenCV window we need to...\r\n # ...extract the data of our image memory\r\n array = ueye.get_data(pcImageMemory, width, height, nBitsPerPixel, pitch, copy=False)\r\n\r\n # bytes_per_pixel = int(nBitsPerPixel / 8)\r\n\r\n # ...reshape it in an numpy array...\r\n frame = np.reshape(array,(height.value, width.value, bytes_per_pixel))\r\n\r\n # ...resize the image by a half\r\n frame = cv2.resize(frame,(0,0),fx=0.5, fy=0.5)\r\n \r\n#---------------------------------------------------------------------------------------------------------------------------------------\r\n #Include image data processing here\r\n\r\n#---------------------------------------------------------------------------------------------------------------------------------------\r\n\r\n #...and finally display it\r\n cv2.imshow(\"SimpleLive_Python_uEye_OpenCV\", frame)\r\n\r\n # Press q if you want to end the loop\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n#---------------------------------------------------------------------------------------------------------------------------------------\r\n\r\n# Releases an image memory that was allocated using is_AllocImageMem() and removes it from the driver management\r\nueye.is_FreeImageMem(hCam, pcImageMemory, MemID)\r\n\r\n# Disables the hCam camera handle and releases the data structures and memory areas taken up by the uEye camera\r\nueye.is_ExitCamera(hCam)\r\n\r\n# Destroys the OpenCv windows\r\ncv2.destroyAllWindows()\r\n\r\nprint()\r\nprint(\"END\")\r\n" ]
[ [ "numpy.reshape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
xiaoyu-liu/Titanic
[ "2551aa59ca8a46227aede777d31b70a0da962cbb" ]
[ "DataCleaning.py" ]
[ "##------------------- Import Packages -------------------------\n##-------------------------------------------------------------\n\n# Basic packages for database and for scientific computing\nimport os\nimport pandas as pd\nimport numpy as np\n# import random as rnd\n\n# Visualization tool\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n##--------------------- Input Dataset -------------------------\n##-------------------------------------------------------------\nos.chdir(\"C:\\\\Summer\\\\Databases by Python - Coursera\\\\Kaggle Project\\\\Titanic-180109\")\ntrain_df = pd.read_csv('train.csv')\ntest_df = pd.read_csv('test.csv')\ncombine = [train_df, test_df]\n\n##---------- Check the information of dataset -----------------\n##-------------------------------------------------------------\ntrain_df.info()\ntest_df.info()\n#**************************************************************\n# Summary of dataset through abservations:\n# 1. For training set, only Age, Cabin and Embarked have \n# missing value; while; for testing set, Age, Cabin and Fare\n# have missing value.\n# 2. Data Type:\n# Int - PassengerId, Pclass, SibSp, Parch, Survived\n# Float - Fare, Age\n# object - Name, Sex, Ticket, Cabin, Embarked\n# 3. Let Survived be response variable, then another 11 features are\n# predictors.\n# 4. Cabin has 77.11% missing value for training group, and 78.23% \n# for testing group. Therefore, I consider to eliminate this \n# features based on its absence.\n#**************************************************************\n\n##---------------- Create some new features -------------------\n##---------in order to reduce the dimension of predictor-------\n\n# Create a new feature 'FamSize'\nfor dataset in combine:\n dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1\nfor dataset in combine:\n dataset['FamSize'] = 0\n dataset.loc[(dataset['FamilySize'] > 0) & (dataset['FamilySize'] < 5), 'FamSize'] = 1\n dataset.loc[dataset['FamilySize'] >= 5, 'FamSize'] = 2\n ## 0: single\n ## 1: small family\n ## 2: big family\n#***************************************************************\n# 'FamSize' represents the size of family in this travels, after \n# building this, 'SibSp' and 'Parch' can be eliminated.\n#***************************************************************\n\n# Create a new feature 'FamName'\nfor dataset in combine:\n dataset['FamName'] = dataset.Name.str.extract('([A-Za-z]+)\\,', expand=False)\n#***************************************************************\n# 'FamName' represents the family name of travelers, after \n# building this, 'Name' can be eliminated.\n#\n# On the other hand, I will use this variable in building \n# variable 'FamwithChild' which will contain information from \n# 'FamName', 'FamSize', as well as 'Age'.\n#***************************************************************\n\n# Create a new feature 'Title'\nfor dataset in combine:\n dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\\.', expand=False)\nfor dataset in combine:\n dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col',\\\n \t'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')\n dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')\n dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')\n dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')\n ## From the chart shown above, I didn't seen any useful information from\n ## title except indication of age and sex from title.\n#***************************************************************\n# 'Title' represents the titles of travelers, after building this,\n# 'Name' can be eliminated.\n#\n# On the other hand, I will use this variable in prediction \n# missing value of age for both training and testing sets.\n#***************************************************************\n\n##---------------- Deal with missing values -------------------\n##-------------------------------------------------------------\n\n# For Age (both in Train and Test):\n# Step 1: Build another dataframe, it contains the mode of \n# age under each Title.\nAveAgeTitle = pd.DataFrame({'Title':['Master','Miss','Mr','Mrs','Rare']})\nfor title in AveAgeTitle['Title']:\n AveAgeTitle.loc[AveAgeTitle['Title']==title,'AveAge'] \\\n = train_df[train_df['Title'] == title]['Age'].dropna().mode()[0]\n# Step 2: Fill in missing value with mode with identical Title\nfor dataset in combine:\n for title in AveAgeTitle.Title:\n FillAge = AveAgeTitle.loc[AveAgeTitle['Title']==title , 'AveAge'].mean()\n dataset.loc[(dataset.Age.isnull()) & (dataset['Title'] == title), 'Age'] = FillAge\n\n# For Embarked (in Train):\n# Since Embarked contains categorical variables,\n# I decided to use the mode of it to fill in missing values.\ntrain_df.fillna(train_df.Embarked.dropna().mode()[0])\n\n# For Fare (in Test):\n# Since Fare contains continous variables,\n# I decided to use median of it to fill in missing values.\n# To be noticed, using mean is also meaningful to try, but \n# result will not change to much. (median is not so different with mean)\ntest_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True)\n\n##--------------------- Transfer Dataset ----------------------\n##-------------------------------------------------------------\n\n# Transfer continous data into limited groups\n# For Age:\n# 0: infants\n# 1: children\n# 2: teenagers\n# 3: adults\n# 4: middle ages\n# 5: aged people \nfor dataset in combine: \n dataset.loc[ dataset['Age'].dropna() <= 2, 'Age'] = 0\n dataset.loc[(dataset['Age'].dropna() > 2) & (dataset['Age'].dropna() <= 12), 'Age'] = 1\n dataset.loc[(dataset['Age'].dropna() > 12) & (dataset['Age'].dropna() <= 18), 'Age'] = 2\n dataset.loc[(dataset['Age'].dropna() > 18) & (dataset['Age'].dropna() <= 40), 'Age'] = 3\n dataset.loc[(dataset['Age'].dropna() > 40) & (dataset['Age'].dropna() <= 60), 'Age'] = 4\n dataset.loc[ dataset['Age'].dropna() > 60, 'Age'] = 5\n dataset['Age'] = dataset['Age'].astype(int)\n# For Fare:\n# 0: really low fare - (0, 7.75]\n# 1: low fare - (7.75, 8.05]\n# 2: medium low fare - (8.05, 12.48]\n# 3: medium fare - (12.48, 19.26]\n# 4: medium high low fare - (19.26, 27.9]\n# 5: high fare - (27.9, 56.9]\n# 6: really high fare - 56.9+\ntrain_df['FareBand'] = pd.qcut(train_df['Fare'], 7)\ntrain_df[['FareBand', 'Survived']].groupby(['FareBand'], as_index=False).mean().sort_values(by='FareBand', ascending=True)\nfor dataset in combine:\n dataset.loc[ dataset['Fare'] <= 7.75, 'Fare'] = 0\n dataset.loc[(dataset['Fare'] > 7.75) & (dataset['Fare'] <= 8.05), 'Fare'] = 1\n dataset.loc[(dataset['Fare'] > 8.05) & (dataset['Fare'] <= 12.48), 'Fare'] = 2\n dataset.loc[(dataset['Fare'] > 12.48) & (dataset['Fare'] <= 19.26), 'Fare'] = 3\n dataset.loc[(dataset['Fare'] > 19.26) & (dataset['Fare'] <= 27.9), 'Fare'] = 4\n dataset.loc[(dataset['Fare'] > 27.9) & (dataset['Fare'] <= 56.9), 'Fare'] = 5\n dataset.loc[ dataset['Fare'] > 56.9, 'Fare'] = 6\n dataset['Fare'] = dataset['Fare'].astype(int)\n\n# Transfer string data into int\n# for sex:\nfor dataset in combine:\n dataset['Sex'] = dataset['Sex'].map( {'female': 1, 'male': 0} ).astype(int)\n# for embarked \nfreq_port = train_df.Embarked.dropna().mode()[0]\nfor dataset in combine:\n dataset['Embarked'] = dataset['Embarked'].fillna(freq_port)\nfor dataset in combine:\n dataset['Embarked'] = dataset['Embarked'].map( {'Q': 2, 'S': 1, 'C': 0} ).astype(int)\n\n\n##-------------------- Create a feature -----------------------\n##--------- based on trasfered Age, FamName and FamSize -------\n\n# Create a new feature 'FamwithChild':\n# 0: no child in family in this trip\n# 1: infant with family in this trip\n# 2: child with family in this trip\nFamNameGroup = train_df[['FamName','Survived']].groupby(['FamName'],as_index=False).count()\nFamNameGroup = FamNameGroup[FamNameGroup['Survived']>1]\nFamName = FamNameGroup['FamName'].tolist()\ntrain_df['FamwithChild'] = 0\nfor lastname in FamName:\n train_df.loc[(train_df['FamName'] == lastname) & (train_df['FamSize'] > 0)\\\n & (train_df['Age'].min() == 0), 'FamwithChild'] = 1\n train_df.loc[(train_df['FamName'] == lastname) & (train_df['FamSize'] > 0)\\\n & (train_df['Age'].min() == 1), 'FamwithChild'] = 2\n \nFamNameGroup2 = test_df[['FamName','Age']].groupby(['FamName'],as_index=False).count()\nFamNameGroup2 = FamNameGroup2[FamNameGroup2['Age']>1]\nFamName2 = FamNameGroup2['FamName'].tolist()\ntest_df['FamwithChild'] = 0\nfor lastname in FamName2:\n test_df.loc[(test_df['FamName'] == lastname) & (test_df['FamSize'] > 0)\\\n & (train_df['Age'].min() == 0), 'FamwithChild'] = 1\n test_df.loc[(test_df['FamName'] == lastname) & (test_df['FamSize'] > 0)\\\n & (train_df['Age'].min() == 1), 'FamwithChild'] = 2\n\n##-------------------- Drop useless variables -----------------------\n##-------------------------------------------------------------------\ntrain_df = train_df.drop(['Ticket', 'Cabin', 'Name', 'Title', 'PassengerId',\\\n 'FamilySize', 'Parch', 'SibSp','FareBand', 'FamName'], axis=1)\ntest_df = test_df.drop(['Ticket', 'Cabin', 'Name', 'Title', 'PassengerId',\\\n 'FamilySize', 'Parch', 'SibSp','FamName'], axis=1)\n\n" ]
[ [ "pandas.read_csv", "pandas.qcut", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
checko/caffe-jacinto-models
[ "b224970200f36fc6d07d3f40348f2565bcb1b522" ]
[ "scripts/tools/utils/infer_segmentation.py" ]
[ "#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport sys\nimport numpy as np\nimport os, glob\nimport cv2\nimport caffe\n#import lmdb\nfrom PIL import Image\nimport argparse\nimport random\nimport shutil\nimport imageio\nimport math\n\ndef get_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', type=str, required=True, help='Path to image folder, video or list txt file')\n parser.add_argument('--label', type=str, default=None, help='Path to label folder, video or list txt file') \n parser.add_argument('--num_classes', type=int, default=None, help='Number of classes') \n parser.add_argument('--search', type=str, default='*.png', help='Wildcard. eg. train/*/*.png')\n parser.add_argument('--output', type=str, default=None, help='Path to output folder') \n parser.add_argument('--num_images', type=int, default=0, help='Max num images to process') \n parser.add_argument('--model', type=str, default='', help='Path to Model prototxt') \n parser.add_argument('--weights', type=str, default='', help='Path to pre-trained folder') \n parser.add_argument('--crop', nargs='+', help='crop-width crop-height') \n parser.add_argument('--resize', nargs='+', help='resize-width resize-height') \n parser.add_argument('--blend', type=int, default=0, help='0:raw labels(in gray scale), 1:Do chroma belnding at output for visualization, 2:output in color pallet form') \n parser.add_argument('--palette', type=str, default='', help='Color palette') \n parser.add_argument('--batch_size', type=int, default=1, help='Batch of images to process') \n parser.add_argument('--resize_back', action=\"store_true\", help='Upsize back a resized label for evaluation')\n parser.add_argument('--label_dict', type=str, default='', help='Lookup to be applied to prediction to match with gt labels') \n parser.add_argument('--class_dict', type=str, default='', help='Grouping of classes in evaluation. Also ignored classea') \n parser.add_argument('--resize_op_to_ip_size', action=\"store_true\", help='if ouput label needs to be resized to input size, def:disbale') \n return parser.parse_args()\n\ndef create_lut(label_dict):\n if label_dict:\n lut = np.zeros(256, dtype=np.uint8)\n for k in range(256):\n lut[k] = k\n for k in label_dict.keys():\n lut[k] = label_dict[k] \n return lut\n else:\n return None\n \ndef check_paths(args):\n output_type = None\n if args.output:\n ext = os.path.splitext(args.output)[1]\n if (ext == '.mp4' or ext == '.MP4'):\n output_type = 'video'\n elif (ext == '.png' or ext == '.jpg' or ext == '.jpeg' or ext == '.PNG' or ext == '.JPG' or ext == '.JPEG'):\n output_type = 'image'\n elif (ext == '.txt'):\n output_type = 'list' \n else:\n output_type = 'folder' \n\n if output_type == 'folder':\n print(args.output) \n if not os.path.exists(args.output):\n os.mkdir(args.output)\n else:\n print('path ' + args.output + ' exists')\n \n ext = os.path.splitext(args.input)[1]\n if (ext == '.mp4' or ext == '.MP4'):\n input_type = 'video'\n elif (ext == '.png' or ext == '.jpg' or ext == '.jpeg' or ext == '.PNG' or ext == '.JPG' or ext == '.JPEG'):\n input_type = 'image'\n elif (ext == '.txt'):\n input_type = 'list' \n else:\n input_type = 'folder' \n \n return input_type, output_type\n\ndef crop_color_image2(color_image, crop_size): #size in (height, width)\n image_size = color_image.shape\n extra_h = (image_size[0] - crop_size[0])//2 if image_size[0] > crop_size[0] else 0\n extra_w = (image_size[1] - crop_size[1]) // 2 if image_size[1] > crop_size[1] else 0\n out_image = color_image[extra_h:(extra_h+crop_size[0]), extra_w:(extra_w+crop_size[1]), :]\n return out_image\n\ndef crop_gray_image2(color_image, crop_size): #size in (height, width)\n image_size = color_image.shape\n extra_h = (image_size[0] - crop_size[0])//2 if image_size[0] > crop_size[0] else 0\n extra_w = (image_size[1] - crop_size[1])//2 if image_size[1] > crop_size[1] else 0\n out_image = color_image[extra_h:(extra_h+crop_size[0]), extra_w:(extra_w+crop_size[1])]\n return out_image\n \ndef chroma_blend(image, color):\n image_yuv = cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_BGR2YUV)\n image_y,image_u,image_v = cv2.split(image_yuv)\n color_yuv = cv2.cvtColor(color.astype(np.uint8), cv2.COLOR_BGR2YUV)\n color_y,color_u,color_v = cv2.split(color_yuv)\n image_y = np.uint8(image_y)\n color_u = np.uint8(color_u)\n color_v = np.uint8(color_v)\n image_yuv = cv2.merge((image_y,color_u,color_v))\n image = cv2.cvtColor(image_yuv.astype(np.uint8), cv2.COLOR_YUV2BGR)\n return image\n \ndef resize_image(color_image, size): #size in (height, width)\n im = Image.fromarray(color_image)\n #print(\"Resizing image to W: \", size[1], \"H: \", size[0]) \n im = im.resize((size[1], size[0]), Image.ANTIALIAS) #(width, height)\n im = np.array(im, dtype=np.uint8)\n return im\n\ndef resize_label(label_image, size): #size in (height, width)\n im = Image.fromarray(label_image.astype(np.uint8))\n #print(\"Resizing lable to W: \", size[1], \"H: \", size[0]) \n im = im.resize((size[1], size[0]), Image.NEAREST) #(width, height)\n im = np.array(im, dtype=np.uint8)\n return im\n \ndef infer_blob(args, net, input_bgr, input_label=None):\n input_bgr_orig = np.array(input_bgr, np.uint8)\n image_size = input_bgr.shape \n if args.crop:\n print('Croping to ' + str(args.crop))\n input_bgr = crop_color_image2(input_bgr, (args.crop[1], args.crop[0]))\n if (input_label is not None):\n input_label = crop_color_image2(input_label, (args.crop[1], args.crop[0]))\n\n if args.resize:\n print('Resizing to ' + str(args.resize))\n input_bgr = resize_image(input_bgr, (args.resize[1], args.resize[0]))\n if (input_label is not None) and (not args.resize_back):\n input_label = resize_label(input_label, (args.resize[1], args.resize[0])) \n \n input_blob = input_bgr.transpose((2, 0, 1)) #Interleaved to planar\n input_blob = input_blob[np.newaxis, ...]\n if net.blobs['data'].data.shape != input_blob.shape:\n #net.blobs['data'].data.reshape(input_blob.shape)\n raise ValueError(\"Pleae correct the input size in deploy prototxt to match with the input size given here: \"+str(input_blob.shape))\n \n blobs = None #['prob', 'argMaxOut']\n out = net.forward_all(blobs=blobs, **{net.inputs[0]: input_blob})\n\n if 'argMaxOut' in out:\n prob = out['argMaxOut'][0]\n prediction = prob[0].astype(int)\n else: \n prob = out['prob'][0]\n prediction = np.argmax(prob.transpose([1, 2, 0]), axis=2)\n \n if args.label_dict:\n prediction = args.label_lut[prediction]\n if input_label is not None:\n input_label = args.label_lut[input_label]\n \n if args.resize and args.resize_back:\n prediction = resize_label(prediction, image_size)\n input_bgr = input_bgr_orig\n\n if args.blend == 1:\n #blend output with input \n prediction_size = (prediction.shape[0], prediction.shape[1], 3) \n output_image = args.palette[prediction.ravel()].reshape(prediction_size)\n output_size = image_size\n if args.resize_op_to_ip_size:\n output_size = output_image.shape \n output_image = crop_color_image2(output_image, output_size) \n output_image = chroma_blend(input_bgr, output_image) \n elif args.blend == 0:\n #raw output\n prediction_size = (prediction.shape[0], prediction.shape[1])\n output_image = prediction.ravel().reshape(prediction_size)\n output_size = image_size\n if args.resize_op_to_ip_size:\n output_size = output_image.shape \n output_image = crop_gray_image2(output_image, output_size)\n elif args.blend == 2:\n #output in color pallet form\n prediction_size = (prediction.shape[0], prediction.shape[1], 3) \n output_image = args.palette[prediction.ravel()].reshape(prediction_size)\n output_size = image_size\n if args.resize_op_to_ip_size:\n output_size = output_image.shape \n output_image = crop_color_image2(output_image, output_size) \n return output_image, input_label\n \n \ndef infer_image_file(args, net):\n input_blob = cv2.imread(args.input)\n output_blob = infer_blob(args, net, input_blob) \n cv2.imwrite(args.output, output_blob)\n return\n \ndef infer_image_folder(args, net): \n print('Getting list of images...', end='')\n image_search = os.path.join(args.input, args.search)\n input_indices = glob.glob(image_search) \n numFrames = min(len(input_indices), args.num_images) \n input_indices = input_indices[:numFrames]\n input_indices.sort()\n print('running inference for ', len(input_indices), ' images...');\n for input_name in input_indices:\n print(input_name, end=' ') \n sys.stdout.flush() \n input_blob = cv2.imread(input_name) \n output_blob, _ = infer_blob(args, net, input_blob) \n output_name = os.path.join(args.output, os.path.basename(input_name));\n cv2.imwrite(output_name, output_blob)\n return\n \ndef eval_blob(args, net, input_blob, label_blob, confusion_matrix):\n output_blob, label_blob = infer_blob(args, net, input_blob, label_blob)\n \n #for r in range(output_blob.shape[0]):\n # for c in range(output_blob.shape[1]):\n # gt_label = label_blob[r][c][0]\n # det_label = output_blob[r][c]\n # det_label = min(det_label, args.num_classes)\n # if gt_label != 255:\n # confusion_matrix[gt_label][det_label] += 1\n\n if len(label_blob.shape)>2:\n label_blob = label_blob[:,:,0] \n gt_labels = label_blob.ravel()\n det_labels = output_blob.ravel().clip(0,args.num_classes)\n gt_labels_valid_ind = np.where(gt_labels != 255)\n #print(\"gt_labels.shape\", gt_labels.shape)\n #print(\"det_labels.shape\", det_labels.shape)\n gt_labels_valid = gt_labels[gt_labels_valid_ind]\n det_labels_valid = det_labels[gt_labels_valid_ind]\n #print(len(np.where(gt_labels_valid==det_labels_valid)[0]))\n #confusion_matrix[gt_labels_valid][det_labels_valid] += 1\n for r in range(confusion_matrix.shape[0]):\n for c in range(confusion_matrix.shape[1]):\n confusion_matrix[r,c] += np.sum((gt_labels_valid==r) & (det_labels_valid==c))\n\n return output_blob, confusion_matrix\n \n \ndef compute_accuracy(args, confusion_matrix):\n if args.class_dict:\n selected_classes = []\n for cls in args.class_dict:\n category = args.class_dict[cls]\n if category >= 0 and category<255:\n selected_classes.extend([category]) \n num_selected_classes = max(selected_classes) + 1\n print('num_selected_classes={}'.format(num_selected_classes)) \n tp = np.zeros(num_selected_classes)\n population = np.zeros(num_selected_classes)\n det = np.zeros(num_selected_classes)\n iou = np.zeros(num_selected_classes)\n for r in range(args.num_classes):\n for c in range(args.num_classes): \n r0 = args.class_dict[r]\n c0 = args.class_dict[c] \n if r0 >= 0 and r0 < 255:\n population[r0] += confusion_matrix[r][c]\n if c0 >= 0 and c0 < 255:\n det[c0] += confusion_matrix[r][c] \n if r == c:\n tp[r0] += confusion_matrix[r][c] \n else:\n num_selected_classes = args.num_classes\n tp = np.zeros(args.num_classes)\n population = np.zeros(args.num_classes)\n det = np.zeros(args.num_classes)\n iou = np.zeros(args.num_classes)\n for r in range(args.num_classes):\n for c in range(args.num_classes): \n population[r] += confusion_matrix[r][c]\n det[c] += confusion_matrix[r][c] \n if r == c:\n tp[r] += confusion_matrix[r][c]\n \n tp_total = 0\n population_total = 0 \n for cls in range(num_selected_classes):\n intersection = tp[cls]\n union = population[cls] + det[cls] - tp[cls]\n iou[cls] = (intersection / union) if union else 0\n tp_total += tp[cls]\n population_total += population[cls]\n \n #print('confusion_matrix={}'.format(confusion_matrix))\n accuracy = tp_total / population_total\n \n num_nonempty_classes = 0 \n for pop in population:\n if pop>0:\n num_nonempty_classes += 1\n \n mean_iou = np.sum(iou) / num_nonempty_classes\n return accuracy, mean_iou, iou\n \n \ndef infer_image_list(args, net):\n input_indices = []\n label_indices = [] \n print('Getting list of images...', end='')\n with open(args.input) as image_list_file:\n for img_name in image_list_file:\n input_indices.extend([img_name.strip()])\n \n if args.label:\n with open(args.label) as label_list_file:\n for label_name in label_list_file:\n label_indices.extend([label_name.strip()])\n \n if args.num_images:\n input_indices = input_indices[0:min(len(input_indices),args.num_images)] \n label_indices = label_indices[0:min(len(label_indices),args.num_images)] \n \n print('running inference for ', len(input_indices), ' images...');\n output_name_list = []\n if not label_indices:\n for input_name in input_indices:\n print(input_name) \n sys.stdout.flush() \n input_blob = cv2.imread(input_name) \n output_blob,_ = infer_blob(args, net, input_blob) \n output_name = os.path.join(args.output, os.path.basename(input_name));\n cv2.imwrite(output_name, output_blob) \n if args.output: \n output_name_list.append(output_name) \n else:\n confusion_matrix = np.zeros((args.num_classes, args.num_classes+1))\n total = len(input_indices)\n count = 0\n for (input_name, label_name) in zip(input_indices, label_indices):\n input_name_base = os.path.split(input_name)[-1]\n label_name_base = os.path.split(label_name)[-1] \n progress = count * 100 / total \n print((input_name_base, label_name_base, progress)) \n sys.stdout.flush() \n input_blob = cv2.imread(input_name) \n label_blob = cv2.imread(label_name) \n output_blob, confusion_matrix = eval_blob(args, net, input_blob, label_blob, confusion_matrix) \n if args.output:\n output_name = os.path.join(args.output, os.path.basename(input_name));\n cv2.imwrite(output_name, output_blob) \n output_name_list.append(output_name) \n count += 1\n #how many times intermediate accuracy needs to be shown\n num_times_show_accuracy = min(20, total)\n if ((count % (total/num_times_show_accuracy)) == 0):\n accuracy, mean_iou, iou = compute_accuracy(args, confusion_matrix) \n print('pixel_accuracy={}, mean_iou={}, iou={}'.format(accuracy, mean_iou, iou))\n \n print('-------------------------------------------------------------') \n accuracy, mean_iou, iou = compute_accuracy(args, confusion_matrix) \n print('Final: pixel_accuracy={}, mean_iou={}, iou={}'.format(accuracy, mean_iou, iou))\n print('-------------------------------------------------------------') \n \n if args.output: \n with open(os.path.join(args.output,\"output_name_list.txt\"), \"w\") as output_name_list_file:\n print(output_name_list)\n output_name_list_file.write('\\n'.join(str(line) for line in output_name_list))\n return\n \ndef infer_video(args, net):\n videoIpHandle = imageio.get_reader(args.input, 'ffmpeg')\n fps = math.ceil(videoIpHandle.get_meta_data()['fps'])\n print(videoIpHandle.get_meta_data())\n numFrames = min(len(videoIpHandle), args.num_images)\n videoOpHandle = imageio.get_writer(args.output,'ffmpeg', fps=fps)\n for num in range(numFrames):\n print(num, end=' ')\n sys.stdout.flush()\n input_blob = videoIpHandle.get_data(num) \n input_blob = input_blob[...,::-1] #RGB->BGR\n output_blob = infer_blob(args, net, input_blob) \n output_blob = output_blob[...,::-1] #BGR->RGB \n videoOpHandle.append_data(output_blob) \n videoOpHandle.close() \n return\n \n\ndef main(): \n args = get_arguments()\n print(args)\n if args.num_images == 0:\n args.num_images = sys.maxsize\n \n os.environ['IMAGEIO_FFMPEG_EXE'] = 'ffmpeg'\n \n if args.palette:\n print('Creating palette')\n exec('palette='+args.palette)\n args.palette = np.zeros((256,3))\n for i, p in enumerate(palette):\n \targs.palette[i,0] = p[0]\n \targs.palette[i,1] = p[1]\n \targs.palette[i,2] = p[2]\n args.palette = args.palette[...,::-1] #RGB->BGR, since palette is expected to be given in RGB format\n \n if args.crop and int(args.crop[0]) != 0:\n args.crop = [int(entry) for entry in args.crop]\n else:\n args.crop = None\n\n if args.resize and int(args.resize[0]) != 0:\n args.resize = [int(entry) for entry in args.resize]\n else:\n args.resize = None\n\n input_type, output_type = check_paths(args)\n \n if args.label and (args.blend!=0):\n raise ValueError('When doing evaluation by specifying --label, --blend should not be used')\n \n args.label_lut = [] \n if args.label_dict:\n label_dict_string = 'label_dict = ' + args.label_dict\n exec(label_dict_string)\n args.label_dict = label_dict\n print(args.label_dict) \n args.label_lut = create_lut(args.label_dict)\n \n if args.class_dict:\n class_dict_string = 'class_dict = ' + args.class_dict\n exec(class_dict_string)\n args.class_dict = class_dict\n \n caffe.set_mode_gpu()\n caffe.set_device(0)\n \n net = caffe.Net(args.model, args.weights, caffe.TEST)\n \n if input_type == 'image':\n print('Infering Images')\n infer_image_file(args, net) \n elif input_type == 'folder':\n print('Infering Folder') \n infer_image_folder(args, net)\n elif input_type == 'video':\n print('Infering Video') \n infer_video(args, net) \n elif input_type == 'list':\n print('Infering list') \n infer_image_list(args, net) \n else: \n print('Incorrect options')\n \n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.uint8", "numpy.array", "numpy.where", "numpy.sum", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
seabay/fairseq-py-mine
[ "641f1d3a492164f07de66a0bc75abd4fdb2e71a0" ]
[ "fairseq/models/fconv.py" ]
[ "# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the LICENSE file in\n# the root directory of this source tree. An additional grant of patent rights\n# can be found in the PATENTS file in the same directory.\n#\n\nimport math\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom fairseq.data import LanguagePairDataset\nfrom fairseq.modules import BeamableMM, GradMultiply, LinearizedConvolution\n\nfrom . import FairseqEncoder, FairseqIncrementalDecoder, FairseqModel\n\n#tokens = [1,5,8,10] => return [0,1,2], because the first token is padding\ndef make_positions(tokens, padding_idx, left_pad, offset=0): #padding_idx=1\n seqlen = tokens.size(1)\n if not hasattr(make_positions, 'range'):\n make_positions.range = tokens.new() # Constructs a new tensor of the same data type, not dimension, now there is 0 element\n if make_positions.range.numel() < offset + seqlen: ## numel - Returns the total number of elements\n # offset positions by the padding index\n torch.arange(padding_idx + 1, padding_idx + 1 + offset + seqlen,\n out=make_positions.range)\n mask = tokens.ne(padding_idx) # not padding characters, Computes input != other element-wise, return Tensor with 0-1\n positions = make_positions.range[offset:offset+seqlen].expand_as(tokens)\n if left_pad: #Casts this tensor to long type, sum(dim=1)沿列求和 unsequeeze(1) 增加第二维\n positions = positions - mask.size(1) + mask.long().sum(dim=1).unsqueeze(1)\n return tokens.clone().masked_scatter_(mask, positions[mask])\n #masked_scatter_(mask, source)\n #Copies elements from source into self tensor at positions where the mask is one.\n\nclass FConvModel(FairseqModel):\n def __init__(self, encoder, decoder):\n super().__init__(encoder, decoder)\n self.encoder.num_attention_layers = sum(layer is not None for layer in decoder.attention)\n\n\nclass FConvEncoder(FairseqEncoder):\n \"\"\"Convolutional encoder\"\"\"\n def __init__(self, dictionary, embed_dim=512, max_positions=1024,\n convolutions=((512, 3),) * 20, dropout=0.1): # 512*3 is a filter, size=3, dim vec = 512\n super().__init__()\n self.dictionary = dictionary\n self.dropout = dropout\n self.num_attention_layers = None\n\n num_embeddings = len(dictionary)\n padding_idx = dictionary.pad()\n self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx)\n self.embed_positions = Embedding(max_positions, embed_dim, padding_idx)\n\n in_channels = convolutions[0][0]\n self.fc1 = Linear(embed_dim, in_channels, dropout=dropout) # is word vec dim is not consitent with filter dim[channel]\n # because text is call 1d, so width is named channel\n self.projections = nn.ModuleList()\n self.convolutions = nn.ModuleList()\n for (out_channels, kernel_size) in convolutions:\n pad = (kernel_size - 1) // 2\n self.projections.append(Linear(in_channels, out_channels)\n if in_channels != out_channels else None)\n self.convolutions.append(\n ConvTBC(in_channels, out_channels * 2, kernel_size, padding=pad,\n dropout=dropout))\n in_channels = out_channels\n self.fc2 = Linear(in_channels, embed_dim)\n\n def forward(self, src_tokens):\n positions = Variable(make_positions(src_tokens.data, self.dictionary.pad(),\n left_pad=LanguagePairDataset.LEFT_PAD_SOURCE)) #left_pad=True # position embedding\n\n # embed tokens and positions\n x = self.embed_tokens(src_tokens) + self.embed_positions(positions)\n x = F.dropout(x, p=self.dropout, training=self.training)\n input_embedding = x\n\n # project to size of convolution\n x = self.fc1(x) # if embedding size does not equal with channel size\n\n # B x T x C -> T x B x C C=Channel\n x = x.transpose(0, 1)\n\n # temporal convolutions\n for proj, conv in zip(self.projections, self.convolutions):\n residual = x if proj is None else proj(x) # if dim of x does not equal with dim of conv output\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = conv(x)\n x = F.glu(x, dim=-1)\n x = (x + residual) * math.sqrt(0.5) # residual connection\n\n # T x B x C -> B x T x C\n x = x.transpose(1, 0)\n\n # project back to size of embedding\n x = self.fc2(x) # encoder_out[0], embed_dim\n\n # scale gradients (this only affects backward, not forward)\n x = GradMultiply.apply(x, 1.0 / (2.0 * self.num_attention_layers))\n\n # add output to input embedding for attention\n y = (x + input_embedding) * math.sqrt(0.5) # encoder_out[1]\n # z + e for conditional input c, scale by √0.5\n\n return x, y # \n\n def max_positions(self):\n \"\"\"Maximum input length supported by the encoder.\"\"\"\n return self.embed_positions.num_embeddings - self.dictionary.pad() - 1\n\n\nclass AttentionLayer(nn.Module):\n def __init__(self, conv_channels, embed_dim, bmm=None):\n super().__init__()\n # projects from output of convolution to embedding dimension\n self.in_projection = Linear(conv_channels, embed_dim)\n # projects from embedding dimension to convolution size\n self.out_projection = Linear(embed_dim, conv_channels)\n\n self.bmm = bmm if bmm is not None else torch.bmm\n\n def forward(self, x, target_embedding, encoder_out):\n residual = x # h\n\n # attention\n x = (self.in_projection(x) + target_embedding) * math.sqrt(0.5) # d = Wh + b + g\n x = self.bmm(x, encoder_out[0]) # batch matrix-matrix product, d * z\n\n # softmax over last dim\n sz = x.size() # get dimensions\n x = F.softmax(x.view(sz[0] * sz[1], sz[2])) \n # view: Returns a new tensor with the same data \n # as the self tensor but of a different size\n x = x.view(sz)\n attn_scores = x\n\n x = self.bmm(x, encoder_out[1]) # a * (z+e), encoder_out[1] : z+e\n # scale attention output\n s = encoder_out[1].size(1)\n x = x * (s * math.sqrt(1.0 / s)) # scale c by m√1/m\n\n # project back\n x = (self.out_projection(x) + residual) * math.sqrt(0.5)\n return x, attn_scores\n\n def make_generation_fast_(self, beamable_mm_beam_size=None, **kwargs):\n \"\"\"Replace torch.bmm with BeamableMM.\"\"\"\n if beamable_mm_beam_size is not None:\n self.bmm = BeamableMM(beamable_mm_beam_size)\n\n\nclass FConvDecoder(FairseqIncrementalDecoder):\n \"\"\"Convolutional decoder\"\"\"\n def __init__(self, dictionary, embed_dim=512, out_embed_dim=256,\n max_positions=1024, convolutions=((512, 3),) * 20,\n attention=True, dropout=0.1):\n super().__init__()\n self.dictionary = dictionary\n self.dropout = dropout\n\n in_channels = convolutions[0][0]\n if isinstance(attention, bool):\n # expand True into [True, True, ...] and do the same with False\n attention = [attention] * len(convolutions)\n\n num_embeddings = len(dictionary)\n padding_idx = dictionary.pad()\n self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx)\n self.embed_positions = Embedding(max_positions, embed_dim, padding_idx)\n\n self.fc1 = Linear(embed_dim, in_channels, dropout=dropout)\n self.projections = nn.ModuleList()\n self.convolutions = nn.ModuleList()\n self.attention = nn.ModuleList()\n for i, (out_channels, kernel_size) in enumerate(convolutions):\n pad = kernel_size - 1\n self.projections.append(Linear(in_channels, out_channels)\n if in_channels != out_channels else None)\n self.convolutions.append(\n LinearizedConv1d(in_channels, out_channels * 2, kernel_size,\n padding=pad, dropout=dropout))\n self.attention.append(AttentionLayer(out_channels, embed_dim)\n if attention[i] else None)\n in_channels = out_channels\n self.fc2 = Linear(in_channels, out_embed_dim)\n self.fc3 = Linear(out_embed_dim, num_embeddings, dropout=dropout)\n\n def forward(self, input_tokens, encoder_out):\n if self._is_incremental_eval:\n return self.incremental_forward(input_tokens, encoder_out)\n else:\n return self.batch_forward(input_tokens, encoder_out)\n\n def batch_forward(self, input_tokens, encoder_out):\n \"\"\"Forward pass for decoding multiple time steps in batch mode.\"\"\"\n positions = Variable(make_positions(input_tokens.data, self.dictionary.pad(),\n left_pad=LanguagePairDataset.LEFT_PAD_TARGET))\n return self._forward(input_tokens, positions, encoder_out)\n\n def incremental_forward(self, input_tokens, encoder_out):\n \"\"\"Forward pass for one time step.\"\"\"\n # positions is the same for every token when decoding a single step\n positions = Variable(input_tokens.data.new(1, 1).fill_(\n self.dictionary.pad() + input_tokens.size(1)))\n\n # keep only the last token for incremental forward pass\n return self._forward(input_tokens[:, -1:], positions, encoder_out)\n\n def _forward(self, input_tokens, positions, encoder_out): # call only once\n # split and transpose encoder outputs\n encoder_a, encoder_b = self._split_encoder_out(encoder_out)\n\n # embed tokens and positions\n x = self.embed_tokens(input_tokens) + self.embed_positions(positions)\n x = F.dropout(x, p=self.dropout, training=self.training)\n target_embedding = x\n\n # project to size of convolution\n x = self.fc1(x)\n\n # B x T x C -> T x B x C\n x = self._transpose_unless_incremental_eval(x)\n\n # temporal convolutions\n avg_attn_scores = None\n num_attn_layers = len(self.attention)\n for proj, conv, attention in zip(self.projections, self.convolutions, self.attention):\n residual = x if proj is None else proj(x)\n\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = conv(x)\n x = conv.remove_future_timesteps(x)\n x = F.glu(x)\n\n # attention\n if attention is not None:\n x = self._transpose_unless_incremental_eval(x)\n\n x, attn_scores = attention(x, target_embedding, (encoder_a, encoder_b))\n attn_scores = attn_scores / num_attn_layers\n if avg_attn_scores is None:\n avg_attn_scores = attn_scores\n else:\n avg_attn_scores.add_(attn_scores)\n\n x = self._transpose_unless_incremental_eval(x)\n\n # residual\n x = (x + residual) * math.sqrt(0.5)\n\n # T x B x C -> B x T x C\n x = self._transpose_unless_incremental_eval(x)\n\n # project back to size of vocabulary\n x = self.fc2(x)\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = self.fc3(x)\n\n return x, avg_attn_scores\n\n def reorder_incremental_state(self, new_order):\n \"\"\"Reorder buffered internal state (for incremental generation).\"\"\"\n super().reorder_incremental_state(new_order)\n\n def max_positions(self):\n \"\"\"Maximum output length supported by the decoder.\"\"\"\n return self.embed_positions.num_embeddings - self.dictionary.pad() - 1\n\n def _split_encoder_out(self, encoder_out):\n \"\"\"Split and transpose encoder outputs.\n\n This is cached when doing incremental inference.\n \"\"\"\n cached_result = self.get_incremental_state('encoder_out')\n if cached_result:\n return cached_result\n\n # transpose only once to speed up attention layers\n encoder_a, encoder_b = encoder_out\n encoder_a = encoder_a.transpose(1, 2).contiguous()\n result = (encoder_a, encoder_b)\n\n return self.set_incremental_state('encoder_out', result)\n\n def _transpose_unless_incremental_eval(self, x):\n if self._is_incremental_eval:\n return x\n return x.transpose(0, 1)\n\n\ndef Embedding(num_embeddings, embedding_dim, padding_idx):\n m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)\n m.weight.data.normal_(0, 0.1)\n return m\n\n\ndef Linear(in_features, out_features, dropout=0):\n \"\"\"Weight-normalized Linear layer (input: N x T x C)\"\"\"\n m = nn.Linear(in_features, out_features)\n m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features))\n m.bias.data.zero_()\n return nn.utils.weight_norm(m)\n\n\ndef LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0, **kwargs):\n \"\"\"Weight-normalized Conv1d layer optimized for decoding\"\"\"\n m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs)\n std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))\n m.weight.data.normal_(mean=0, std=std)\n m.bias.data.zero_()\n return nn.utils.weight_norm(m)\n\n\ndef ConvTBC(in_channels, out_channels, kernel_size, dropout=0, **kwargs):\n \"\"\"Weight-normalized Conv1d layer\"\"\"\n from fairseq.modules import ConvTBC\n m = ConvTBC(in_channels, out_channels, kernel_size, **kwargs)\n std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))\n m.weight.data.normal_(mean=0, std=std)\n m.bias.data.zero_()\n return nn.utils.weight_norm(m, dim=2)\n\n\ndef get_archs():\n return [\n 'fconv', 'fconv_iwslt_de_en', 'fconv_wmt_en_ro', 'fconv_wmt_en_de', 'fconv_wmt_en_fr',\n ]\n\n\ndef _check_arch(args):\n \"\"\"Check that the specified architecture is valid and not ambiguous.\"\"\"\n if args.arch not in get_archs():\n raise ValueError('Unknown fconv model architecture: {}'.format(args.arch))\n if args.arch != 'fconv':\n # check that architecture is not ambiguous\n for a in ['encoder_embed_dim', 'encoder_layers', 'decoder_embed_dim', 'decoder_layers',\n 'decoder_out_embed_dim']:\n if hasattr(args, a):\n raise ValueError('--{} cannot be combined with --arch={}'.format(a, args.arch))\n\n\ndef parse_arch(args):\n _check_arch(args)\n\n if args.arch == 'fconv_iwslt_de_en': ## http://workshop2017.iwslt.org/\n args.encoder_embed_dim = 256\n args.encoder_layers = '[(256, 3)] * 4'\n args.decoder_embed_dim = 256\n args.decoder_layers = '[(256, 3)] * 3'\n args.decoder_out_embed_dim = 256\n elif args.arch == 'fconv_wmt_en_ro':\n args.encoder_embed_dim = 512\n args.encoder_layers = '[(512, 3)] * 20' ## data less?\n args.decoder_embed_dim = 512\n args.decoder_layers = '[(512, 3)] * 20'\n args.decoder_out_embed_dim = 512\n elif args.arch == 'fconv_wmt_en_de':\n convs = '[(512, 3)] * 9' # first 9 layers have 512 units\n convs += ' + [(1024, 3)] * 4' # next 4 layers have 1024 units\n convs += ' + [(2048, 1)] * 2' # final 2 layers use 1x1 convolutions\n args.encoder_embed_dim = 768\n args.encoder_layers = convs\n args.decoder_embed_dim = 768\n args.decoder_layers = convs\n args.decoder_out_embed_dim = 512\n elif args.arch == 'fconv_wmt_en_fr':\n convs = '[(512, 3)] * 6' # first 6 layers have 512 units\n convs += ' + [(768, 3)] * 4' # next 4 layers have 768 units\n convs += ' + [(1024, 3)] * 3' # next 3 layers have 1024 units\n convs += ' + [(2048, 1)] * 1' # next 1 layer uses 1x1 convolutions\n convs += ' + [(4096, 1)] * 1' # final 1 layer uses 1x1 convolutions\n args.encoder_embed_dim = 768\n args.encoder_layers = convs\n args.decoder_embed_dim = 768\n args.decoder_layers = convs\n args.decoder_out_embed_dim = 512\n else:\n assert args.arch == 'fconv'\n\n # default architecture\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)\n args.encoder_layers = getattr(args, 'encoder_layers', '[(512, 3)] * 20')\n args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512)\n args.decoder_layers = getattr(args, 'decoder_layers', '[(512, 3)] * 20')\n args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256)\n args.decoder_attention = getattr(args, 'decoder_attention', 'True')\n return args\n\n\ndef build_model(args, src_dict, dst_dict):\n encoder = FConvEncoder(\n src_dict,\n embed_dim=args.encoder_embed_dim,\n convolutions=eval(args.encoder_layers),\n dropout=args.dropout,\n max_positions=args.max_source_positions,\n )\n decoder = FConvDecoder(\n dst_dict,\n embed_dim=args.decoder_embed_dim,\n convolutions=eval(args.decoder_layers),\n out_embed_dim=args.decoder_out_embed_dim,\n attention=eval(args.decoder_attention),\n dropout=args.dropout,\n max_positions=args.max_target_positions,\n )\n return FConvModel(encoder, decoder)\n" ]
[ [ "torch.nn.functional.glu", "torch.nn.functional.dropout", "torch.nn.utils.weight_norm", "torch.nn.ModuleList", "torch.nn.Embedding", "torch.nn.Linear", "torch.arange" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
StatNLP/discretezoo
[ "565552b894a5c9632ac7b949d61a6f71123031e4" ]
[ "textattack/constraints/grammaticality/language_models/google_language_model/alzantot_goog_lm.py" ]
[ "\"\"\"\n\nGoogle Language Models from Alzantot\n--------------------------------------\n\n Author: Moustafa Alzantot ([email protected])\n All rights reserved.\n\"\"\"\n\nimport os\n\nimport lru\nimport numpy as np\n\nfrom textattack.shared import utils\n\nfrom . import lm_data_utils, lm_utils\n\ntf = utils.LazyLoader(\"tensorflow\", globals(), \"tensorflow\")\n\n# @TODO automatically choose between GPU and CPU.\n\n\nclass GoogLMHelper:\n \"\"\"An implementation of `<https://arxiv.org/abs/1804.07998>`_ adapted from\n `<https://github.com/nesl/nlp_adversarial_examples>`_.\"\"\"\n\n CACHE_PATH = \"constraints/semantics/language-models/alzantot-goog-lm\"\n\n def __init__(self):\n tf.get_logger().setLevel(\"INFO\")\n lm_folder = utils.download_if_needed(GoogLMHelper.CACHE_PATH)\n self.PBTXT_PATH = os.path.join(lm_folder, \"graph-2016-09-10-gpu.pbtxt\")\n self.CKPT_PATH = os.path.join(lm_folder, \"ckpt-*\")\n self.VOCAB_PATH = os.path.join(lm_folder, \"vocab-2016-09-10.txt\")\n\n self.BATCH_SIZE = 1\n self.NUM_TIMESTEPS = 1\n self.MAX_WORD_LEN = 50\n\n self.vocab = lm_data_utils.CharsVocabulary(self.VOCAB_PATH,\n self.MAX_WORD_LEN)\n with tf.device(\"/gpu:1\"):\n self.graph = tf.Graph()\n self.sess = tf.compat.v1.Session(graph=self.graph)\n with self.graph.as_default():\n self.t = lm_utils.LoadModel(self.sess, self.graph, self.PBTXT_PATH,\n self.CKPT_PATH)\n\n self.lm_cache = lru.LRU(2**18)\n\n def clear_cache(self):\n self.lm_cache.clear()\n\n def get_words_probs_uncached(self, prefix_words, list_words):\n targets = np.zeros([self.BATCH_SIZE, self.NUM_TIMESTEPS], np.int32)\n weights = np.ones([self.BATCH_SIZE, self.NUM_TIMESTEPS], np.float32)\n\n if prefix_words.find(\"<S>\") != 0:\n prefix_words = \"<S> \" + prefix_words\n prefix = [self.vocab.word_to_id(w) for w in prefix_words.split()]\n prefix_char_ids = [\n self.vocab.word_to_char_ids(w) for w in prefix_words.split()\n ]\n\n inputs = np.zeros([self.BATCH_SIZE, self.NUM_TIMESTEPS], np.int32)\n char_ids_inputs = np.zeros(\n [self.BATCH_SIZE, self.NUM_TIMESTEPS, self.vocab.max_word_length],\n np.int32)\n\n samples = prefix[:]\n char_ids_samples = prefix_char_ids[:]\n inputs = [[samples[-1]]]\n char_ids_inputs[0, 0, :] = char_ids_samples[-1]\n softmax = self.sess.run(\n self.t[\"softmax_out\"],\n feed_dict={\n self.t[\"char_inputs_in\"]: char_ids_inputs,\n self.t[\"inputs_in\"]: inputs,\n self.t[\"targets_in\"]: targets,\n self.t[\"target_weights_in\"]: weights,\n },\n )\n words_ids = [self.vocab.word_to_id(w) for w in list_words]\n word_probs = [softmax[0][w_id] for w_id in words_ids]\n return np.array(word_probs)\n\n def get_words_probs(self, prefix, list_words):\n \"\"\"Retrieves the probability of words.\n\n Args:\n prefix_words\n list_words\n \"\"\"\n uncached_words = []\n for word in list_words:\n if (prefix, word) not in self.lm_cache:\n if word not in uncached_words:\n uncached_words.append(word)\n probs = self.get_words_probs_uncached(prefix, uncached_words)\n for word, prob in zip(uncached_words, probs):\n self.lm_cache[prefix, word] = prob\n return [self.lm_cache[prefix, word] for word in list_words]\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jayceyxc/YAD2K
[ "973cc74b0340f8ffa2d8e5c9d2c28700dddb15aa" ]
[ "train_overfit.py" ]
[ "#! /usr/bin/env python\n\"\"\"Overfit a YOLO_v2 model to a single image from the Pascal VOC dataset.\n\nThis is a sample training script used to test the implementation of the\nYOLO localization loss function.\n\"\"\"\nimport argparse\nimport io\nimport os\n\nimport h5py\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport PIL\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.layers import Input, Lambda\nfrom keras.models import Model\n\nfrom yad2k.models.keras_yolo import (preprocess_true_boxes, yolo_body,\n yolo_eval, yolo_head, yolo_loss)\nfrom yad2k.utils.draw_boxes import draw_boxes\n\nYOLO_ANCHORS = np.array(\n ((0.57273, 0.677385), (1.87446, 2.06253), (3.33843, 5.47434),\n (7.88282, 3.52778), (9.77052, 9.16828)))\n\nargparser = argparse.ArgumentParser(\n description='Train YOLO_v2 model to overfit on a single image.')\n\nargparser.add_argument(\n '-d',\n '--data_path',\n help='path to HDF5 file containing pascal voc dataset',\n default='~/datasets/VOCdevkit/pascal_voc_07_12.hdf5')\n\nargparser.add_argument(\n '-a',\n '--anchors_path',\n help='path to anchors file, defaults to yolo_anchors.txt',\n default='model_data/yolo_anchors.txt')\n\nargparser.add_argument(\n '-c',\n '--classes_path',\n help='path to classes file, defaults to pascal_classes.txt',\n default='model_data/pascal_classes.txt')\n\n\ndef _main(args):\n voc_path = os.path.expanduser(args.data_path)\n classes_path = os.path.expanduser(args.classes_path)\n anchors_path = os.path.expanduser(args.anchors_path)\n\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n\n if os.path.isfile(anchors_path):\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n anchors = np.array(anchors).reshape(-1, 2)\n else:\n anchors = YOLO_ANCHORS\n\n voc = h5py.File(voc_path, 'r')\n image = PIL.Image.open(io.BytesIO(voc['train/images'][28]))\n orig_size = np.array([image.width, image.height])\n orig_size = np.expand_dims(orig_size, axis=0)\n\n # Image preprocessing.\n image = image.resize((416, 416), PIL.Image.BICUBIC)\n image_data = np.array(image, dtype=np.float)\n image_data /= 255.\n\n # Box preprocessing.\n # Original boxes stored as 1D list of class, x_min, y_min, x_max, y_max.\n boxes = voc['train/boxes'][28]\n boxes = boxes.reshape((-1, 5))\n # Get extents as y_min, x_min, y_max, x_max, class for comparision with\n # model output.\n boxes_extents = boxes[:, [2, 1, 4, 3, 0]]\n\n # Get box parameters as x_center, y_center, box_width, box_height, class.\n boxes_xy = 0.5 * (boxes[:, 3:5] + boxes[:, 1:3])\n boxes_wh = boxes[:, 3:5] - boxes[:, 1:3]\n boxes_xy = boxes_xy / orig_size\n boxes_wh = boxes_wh / orig_size\n boxes = np.concatenate((boxes_xy, boxes_wh, boxes[:, 0:1]), axis=1)\n\n # Precompute detectors_mask and matching_true_boxes for training.\n # Detectors mask is 1 for each spatial position in the final conv layer and\n # anchor that should be active for the given boxes and 0 otherwise.\n # Matching true boxes gives the regression targets for the ground truth box\n # that caused a detector to be active or 0 otherwise.\n detectors_mask_shape = (13, 13, 5, 1)\n matching_boxes_shape = (13, 13, 5, 5)\n detectors_mask, matching_true_boxes = preprocess_true_boxes(boxes, anchors,\n [416, 416])\n\n # Create model input layers.\n image_input = Input(shape=(416, 416, 3))\n boxes_input = Input(shape=(None, 5))\n detectors_mask_input = Input(shape=detectors_mask_shape)\n matching_boxes_input = Input(shape=matching_boxes_shape)\n\n print('Boxes:')\n print(boxes)\n print('Box corners:')\n print(boxes_extents)\n print('Active detectors:')\n print(np.where(detectors_mask == 1)[:-1])\n print('Matching boxes for active detectors:')\n print(matching_true_boxes[np.where(detectors_mask == 1)[:-1]])\n\n # Create model body.\n model_body = yolo_body(image_input, len(anchors), len(class_names))\n model_body = Model(image_input, model_body.output)\n # Place model loss on CPU to reduce GPU memory usage.\n with tf.device('/cpu:0'):\n # TODO: Replace Lambda with custom Keras layer for loss.\n model_loss = Lambda(\n yolo_loss,\n output_shape=(1, ),\n name='yolo_loss',\n arguments={'anchors': anchors,\n 'num_classes': len(class_names)})([\n model_body.output, boxes_input,\n detectors_mask_input, matching_boxes_input\n ])\n model = Model(\n [image_input, boxes_input, detectors_mask_input,\n matching_boxes_input], model_loss)\n model.compile(\n optimizer='adam', loss={\n 'yolo_loss': lambda y_true, y_pred: y_pred\n }) # This is a hack to use the custom loss function in the last layer.\n\n # Add batch dimension for training.\n image_data = np.expand_dims(image_data, axis=0)\n boxes = np.expand_dims(boxes, axis=0)\n detectors_mask = np.expand_dims(detectors_mask, axis=0)\n matching_true_boxes = np.expand_dims(matching_true_boxes, axis=0)\n\n num_steps = 1000\n # TODO: For full training, put preprocessing inside training loop.\n # for i in range(num_steps):\n # loss = model.train_on_batch(\n # [image_data, boxes, detectors_mask, matching_true_boxes],\n # np.zeros(len(image_data)))\n model.fit([image_data, boxes, detectors_mask, matching_true_boxes],\n np.zeros(len(image_data)),\n batch_size=1,\n epochs=num_steps)\n model.save_weights('overfit_weights.h5')\n\n # Create output variables for prediction.\n yolo_outputs = yolo_head(model_body.output, anchors, len(class_names))\n input_image_shape = K.placeholder(shape=(2, ))\n boxes, scores, classes = yolo_eval(\n yolo_outputs, input_image_shape, score_threshold=.3, iou_threshold=.9)\n\n # Run prediction on overfit image.\n sess = K.get_session() # TODO: Remove dependence on Tensorflow session.\n out_boxes, out_scores, out_classes = sess.run(\n [boxes, scores, classes],\n feed_dict={\n model_body.input: image_data,\n input_image_shape: [image.size[1], image.size[0]],\n K.learning_phase(): 0\n })\n print('Found {} boxes for image.'.format(len(out_boxes)))\n print(out_boxes)\n\n # Plot image with predicted boxes.\n image_with_boxes = draw_boxes(image_data[0], out_boxes, out_classes,\n class_names, out_scores)\n plt.imshow(image_with_boxes, interpolation='nearest')\n plt.show()\n plt.savefig('train_overfit.jpg')\n\n\nif __name__ == '__main__':\n args = argparser.parse_args()\n _main(args)\n" ]
[ [ "matplotlib.pyplot.imshow", "numpy.expand_dims", "tensorflow.device", "matplotlib.pyplot.savefig", "numpy.concatenate", "numpy.array", "numpy.where", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
Mktan-18/collab
[ "6f0e3a0bf5b4be72985d02d33b15a23c685b963b" ]
[ "official/nlp/bert/run_squad.py" ]
[ "# 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\"\"\"Run BERT on SQuAD 1.1 and SQuAD 2.0 in TF 2.x.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport tensorflow as tf\n\nfrom official.modeling import model_training_utils\nfrom official.nlp import optimization\nfrom official.nlp.albert import configs as albert_configs\nfrom official.nlp.bert import bert_models\nfrom official.nlp.bert import common_flags\nfrom official.nlp.bert import configs as bert_configs\nfrom official.nlp.bert import input_pipeline\nfrom official.nlp.bert import model_saving_utils\nfrom official.nlp.bert import tokenization\n# word-piece tokenizer based squad_lib\nfrom official.nlp.data import squad_lib as squad_lib_wp\n# sentence-piece tokenizer based squad_lib\nfrom official.nlp.data import squad_lib_sp\nfrom official.utils.misc import distribution_utils\nfrom official.utils.misc import keras_utils\n\nflags.DEFINE_enum(\n 'mode', 'train_and_predict',\n ['train_and_predict', 'train', 'predict', 'export_only'],\n 'One of {\"train_and_predict\", \"train\", \"predict\", \"export_only\"}. '\n '`train_and_predict`: both train and predict to a json file. '\n '`train`: only trains the model. '\n '`predict`: predict answers from the squad json file. '\n '`export_only`: will take the latest checkpoint inside '\n 'model_dir and export a `SavedModel`.')\nflags.DEFINE_string('train_data_path', '',\n 'Training data path with train tfrecords.')\nflags.DEFINE_string(\n 'input_meta_data_path', None,\n 'Path to file that contains meta data about input '\n 'to be used for training and evaluation.')\n# Model training specific flags.\nflags.DEFINE_integer('train_batch_size', 32, 'Total batch size for training.')\n# Predict processing related.\nflags.DEFINE_string('predict_file', None,\n 'Prediction data path with train tfrecords.')\nflags.DEFINE_string('vocab_file', None,\n 'The vocabulary file that the BERT model was trained on.')\nflags.DEFINE_bool(\n 'do_lower_case', True,\n 'Whether to lower case the input text. Should be True for uncased '\n 'models and False for cased models.')\nflags.DEFINE_float(\n 'null_score_diff_threshold', 0.0,\n 'If null_score - best_non_null is greater than the threshold, '\n 'predict null. This is only used for SQuAD v2.')\nflags.DEFINE_bool(\n 'verbose_logging', False,\n 'If true, all of the warnings related to data processing will be printed. '\n 'A number of warnings are expected for a normal SQuAD evaluation.')\nflags.DEFINE_integer('predict_batch_size', 8,\n 'Total batch size for prediction.')\nflags.DEFINE_integer(\n 'n_best_size', 20,\n 'The total number of n-best predictions to generate in the '\n 'nbest_predictions.json output file.')\nflags.DEFINE_integer(\n 'max_answer_length', 30,\n 'The maximum length of an answer that can be generated. This is needed '\n 'because the start and end predictions are not conditioned on one another.')\nflags.DEFINE_string(\n 'sp_model_file', None,\n 'The path to the sentence piece model. Used by sentence piece tokenizer '\n 'employed by ALBERT.')\n\n\ncommon_flags.define_common_bert_flags()\n\nFLAGS = flags.FLAGS\n\nMODEL_CLASSES = {\n 'bert': (bert_configs.BertConfig, squad_lib_wp, tokenization.FullTokenizer),\n 'albert': (albert_configs.AlbertConfig, squad_lib_sp,\n tokenization.FullSentencePieceTokenizer),\n}\n\n\ndef squad_loss_fn(start_positions,\n end_positions,\n start_logits,\n end_logits,\n loss_factor=1.0):\n \"\"\"Returns sparse categorical crossentropy for start/end logits.\"\"\"\n start_loss = tf.keras.backend.sparse_categorical_crossentropy(\n start_positions, start_logits, from_logits=True)\n end_loss = tf.keras.backend.sparse_categorical_crossentropy(\n end_positions, end_logits, from_logits=True)\n\n total_loss = (tf.reduce_mean(start_loss) + tf.reduce_mean(end_loss)) / 2\n total_loss *= loss_factor\n return total_loss\n\n\ndef get_loss_fn(loss_factor=1.0):\n \"\"\"Gets a loss function for squad task.\"\"\"\n\n def _loss_fn(labels, model_outputs):\n start_positions = labels['start_positions']\n end_positions = labels['end_positions']\n start_logits, end_logits = model_outputs\n return squad_loss_fn(\n start_positions,\n end_positions,\n start_logits,\n end_logits,\n loss_factor=loss_factor)\n\n return _loss_fn\n\n\ndef get_raw_results(predictions):\n \"\"\"Converts multi-replica predictions to RawResult.\"\"\"\n squad_lib = MODEL_CLASSES[FLAGS.model_type][1]\n for unique_ids, start_logits, end_logits in zip(predictions['unique_ids'],\n predictions['start_logits'],\n predictions['end_logits']):\n for values in zip(unique_ids.numpy(), start_logits.numpy(),\n end_logits.numpy()):\n yield squad_lib.RawResult(\n unique_id=values[0],\n start_logits=values[1].tolist(),\n end_logits=values[2].tolist())\n\n\ndef get_dataset_fn(input_file_pattern, max_seq_length, global_batch_size,\n is_training):\n \"\"\"Gets a closure to create a dataset..\"\"\"\n\n def _dataset_fn(ctx=None):\n \"\"\"Returns tf.data.Dataset for distributed BERT pretraining.\"\"\"\n batch_size = ctx.get_per_replica_batch_size(\n global_batch_size) if ctx else global_batch_size\n dataset = input_pipeline.create_squad_dataset(\n input_file_pattern,\n max_seq_length,\n batch_size,\n is_training=is_training,\n input_pipeline_context=ctx)\n return dataset\n\n return _dataset_fn\n\n\ndef predict_squad_customized(strategy, input_meta_data, bert_config,\n predict_tfrecord_path, num_steps):\n \"\"\"Make predictions using a Bert-based squad model.\"\"\"\n predict_dataset_fn = get_dataset_fn(\n predict_tfrecord_path,\n input_meta_data['max_seq_length'],\n FLAGS.predict_batch_size,\n is_training=False)\n predict_iterator = iter(\n strategy.experimental_distribute_datasets_from_function(\n predict_dataset_fn))\n\n with strategy.scope():\n # Prediction always uses float32, even if training uses mixed precision.\n tf.keras.mixed_precision.experimental.set_policy('float32')\n squad_model, _ = bert_models.squad_model(\n bert_config,\n input_meta_data['max_seq_length'],\n hub_module_url=FLAGS.hub_module_url)\n\n checkpoint_path = tf.train.latest_checkpoint(FLAGS.model_dir)\n logging.info('Restoring checkpoints from %s', checkpoint_path)\n checkpoint = tf.train.Checkpoint(model=squad_model)\n checkpoint.restore(checkpoint_path).expect_partial()\n\n @tf.function\n def predict_step(iterator):\n \"\"\"Predicts on distributed devices.\"\"\"\n\n def _replicated_step(inputs):\n \"\"\"Replicated prediction calculation.\"\"\"\n x, _ = inputs\n unique_ids = x.pop('unique_ids')\n start_logits, end_logits = squad_model(x, training=False)\n return dict(\n unique_ids=unique_ids,\n start_logits=start_logits,\n end_logits=end_logits)\n\n outputs = strategy.experimental_run_v2(\n _replicated_step, args=(next(iterator),))\n return tf.nest.map_structure(strategy.experimental_local_results, outputs)\n\n all_results = []\n for _ in range(num_steps):\n predictions = predict_step(predict_iterator)\n for result in get_raw_results(predictions):\n all_results.append(result)\n if len(all_results) % 100 == 0:\n logging.info('Made predictions for %d records.', len(all_results))\n return all_results\n\n\ndef train_squad(strategy,\n input_meta_data,\n custom_callbacks=None,\n run_eagerly=False):\n \"\"\"Run bert squad training.\"\"\"\n if strategy:\n logging.info('Training using customized training loop with distribution'\n ' strategy.')\n # Enables XLA in Session Config. Should not be set for TPU.\n keras_utils.set_config_v2(FLAGS.enable_xla)\n\n use_float16 = common_flags.use_float16()\n if use_float16:\n tf.keras.mixed_precision.experimental.set_policy('mixed_float16')\n\n bert_config = MODEL_CLASSES[FLAGS.model_type][0].from_json_file(\n FLAGS.bert_config_file)\n epochs = FLAGS.num_train_epochs\n num_train_examples = input_meta_data['train_data_size']\n max_seq_length = input_meta_data['max_seq_length']\n steps_per_epoch = int(num_train_examples / FLAGS.train_batch_size)\n warmup_steps = int(epochs * num_train_examples * 0.1 / FLAGS.train_batch_size)\n train_input_fn = get_dataset_fn(\n FLAGS.train_data_path,\n max_seq_length,\n FLAGS.train_batch_size,\n is_training=True)\n\n def _get_squad_model():\n \"\"\"Get Squad model and optimizer.\"\"\"\n squad_model, core_model = bert_models.squad_model(\n bert_config,\n max_seq_length,\n hub_module_url=FLAGS.hub_module_url,\n hub_module_trainable=FLAGS.hub_module_trainable)\n squad_model.optimizer = optimization.create_optimizer(\n FLAGS.learning_rate, steps_per_epoch * epochs, warmup_steps)\n if use_float16:\n # Wraps optimizer with a LossScaleOptimizer. This is done automatically\n # in compile() with the \"mixed_float16\" policy, but since we do not call\n # compile(), we must wrap the optimizer manually.\n squad_model.optimizer = (\n tf.keras.mixed_precision.experimental.LossScaleOptimizer(\n squad_model.optimizer, loss_scale=common_flags.get_loss_scale()))\n if FLAGS.fp16_implementation == 'graph_rewrite':\n # Note: when flags_obj.fp16_implementation == \"graph_rewrite\", dtype as\n # determined by flags_core.get_tf_dtype(flags_obj) would be 'float32'\n # which will ensure tf.compat.v2.keras.mixed_precision and\n # tf.train.experimental.enable_mixed_precision_graph_rewrite do not double\n # up.\n squad_model.optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite(\n squad_model.optimizer)\n return squad_model, core_model\n\n # The original BERT model does not scale the loss by\n # 1/num_replicas_in_sync. It could be an accident. So, in order to use\n # the same hyper parameter, we do the same thing here by keeping each\n # replica loss as it is.\n loss_fn = get_loss_fn(\n loss_factor=1.0 /\n strategy.num_replicas_in_sync if FLAGS.scale_loss else 1.0)\n\n model_training_utils.run_customized_training_loop(\n strategy=strategy,\n model_fn=_get_squad_model,\n loss_fn=loss_fn,\n model_dir=FLAGS.model_dir,\n steps_per_epoch=steps_per_epoch,\n steps_per_loop=FLAGS.steps_per_loop,\n epochs=epochs,\n train_input_fn=train_input_fn,\n init_checkpoint=FLAGS.init_checkpoint,\n run_eagerly=run_eagerly,\n custom_callbacks=custom_callbacks)\n\n\ndef predict_squad(strategy, input_meta_data):\n \"\"\"Makes predictions for a squad dataset.\"\"\"\n config_cls, squad_lib, tokenizer_cls = MODEL_CLASSES[FLAGS.model_type]\n bert_config = config_cls.from_json_file(FLAGS.bert_config_file)\n if tokenizer_cls == tokenization.FullTokenizer:\n tokenizer = tokenizer_cls(\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n else:\n assert tokenizer_cls == tokenization.FullSentencePieceTokenizer\n tokenizer = tokenizer_cls(sp_model_file=FLAGS.sp_model_file)\n doc_stride = input_meta_data['doc_stride']\n max_query_length = input_meta_data['max_query_length']\n # Whether data should be in Ver 2.0 format.\n version_2_with_negative = input_meta_data.get('version_2_with_negative',\n False)\n eval_examples = squad_lib.read_squad_examples(\n input_file=FLAGS.predict_file,\n is_training=False,\n version_2_with_negative=version_2_with_negative)\n\n eval_writer = squad_lib.FeatureWriter(\n filename=os.path.join(FLAGS.model_dir, 'eval.tf_record'),\n is_training=False)\n eval_features = []\n\n def _append_feature(feature, is_padding):\n if not is_padding:\n eval_features.append(feature)\n eval_writer.process_feature(feature)\n\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on.\n kwargs = dict(\n examples=eval_examples,\n tokenizer=tokenizer,\n max_seq_length=input_meta_data['max_seq_length'],\n doc_stride=doc_stride,\n max_query_length=max_query_length,\n is_training=False,\n output_fn=_append_feature,\n batch_size=FLAGS.predict_batch_size)\n\n # squad_lib_sp requires one more argument 'do_lower_case'.\n if squad_lib == squad_lib_sp:\n kwargs['do_lower_case'] = FLAGS.do_lower_case\n dataset_size = squad_lib.convert_examples_to_features(**kwargs)\n eval_writer.close()\n\n logging.info('***** Running predictions *****')\n logging.info(' Num orig examples = %d', len(eval_examples))\n logging.info(' Num split examples = %d', len(eval_features))\n logging.info(' Batch size = %d', FLAGS.predict_batch_size)\n\n num_steps = int(dataset_size / FLAGS.predict_batch_size)\n all_results = predict_squad_customized(strategy, input_meta_data, bert_config,\n eval_writer.filename, num_steps)\n\n output_prediction_file = os.path.join(FLAGS.model_dir, 'predictions.json')\n output_nbest_file = os.path.join(FLAGS.model_dir, 'nbest_predictions.json')\n output_null_log_odds_file = os.path.join(FLAGS.model_dir, 'null_odds.json')\n\n squad_lib.write_predictions(\n eval_examples,\n eval_features,\n all_results,\n FLAGS.n_best_size,\n FLAGS.max_answer_length,\n FLAGS.do_lower_case,\n output_prediction_file,\n output_nbest_file,\n output_null_log_odds_file,\n version_2_with_negative=version_2_with_negative,\n null_score_diff_threshold=FLAGS.null_score_diff_threshold,\n verbose=FLAGS.verbose_logging)\n\n\ndef export_squad(model_export_path, input_meta_data):\n \"\"\"Exports a trained model as a `SavedModel` for inference.\n\n Args:\n model_export_path: a string specifying the path to the SavedModel directory.\n input_meta_data: dictionary containing meta data about input and model.\n\n Raises:\n Export path is not specified, got an empty string or None.\n \"\"\"\n if not model_export_path:\n raise ValueError('Export path is not specified: %s' % model_export_path)\n bert_config = MODEL_CLASSES[FLAGS.model_type][0].from_json_file(\n FLAGS.bert_config_file)\n # Export uses float32 for now, even if training uses mixed precision.\n tf.keras.mixed_precision.experimental.set_policy('float32')\n squad_model, _ = bert_models.squad_model(bert_config,\n input_meta_data['max_seq_length'])\n model_saving_utils.export_bert_model(\n model_export_path, model=squad_model, checkpoint_dir=FLAGS.model_dir)\n\n\ndef main(_):\n # Users should always run this script under TF 2.x\n assert tf.version.VERSION.startswith('2.')\n\n with tf.io.gfile.GFile(FLAGS.input_meta_data_path, 'rb') as reader:\n input_meta_data = json.loads(reader.read().decode('utf-8'))\n\n if FLAGS.mode == 'export_only':\n export_squad(FLAGS.model_export_path, input_meta_data)\n return\n\n # Configures cluster spec for multi-worker distribution strategy.\n if FLAGS.num_gpus > 0:\n _ = distribution_utils.configure_cluster(FLAGS.worker_hosts,\n FLAGS.task_index)\n strategy = distribution_utils.get_distribution_strategy(\n distribution_strategy=FLAGS.distribution_strategy,\n num_gpus=FLAGS.num_gpus,\n all_reduce_alg=FLAGS.all_reduce_alg,\n tpu_address=FLAGS.tpu)\n if FLAGS.mode in ('train', 'train_and_predict'):\n train_squad(strategy, input_meta_data, run_eagerly=FLAGS.run_eagerly)\n if FLAGS.mode in ('predict', 'train_and_predict'):\n predict_squad(strategy, input_meta_data)\n\n\nif __name__ == '__main__':\n flags.mark_flag_as_required('bert_config_file')\n flags.mark_flag_as_required('model_dir')\n app.run(main)\n" ]
[ [ "tensorflow.train.latest_checkpoint", "tensorflow.reduce_mean", "tensorflow.train.Checkpoint", "tensorflow.keras.mixed_precision.experimental.set_policy", "tensorflow.io.gfile.GFile", "tensorflow.keras.backend.sparse_categorical_crossentropy", "tensorflow.version.VERSION.startswith", "tensorflow.train.experimental.enable_mixed_precision_graph_rewrite", "tensorflow.nest.map_structure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dianna-ai/dianna
[ "88bcaec001e640c35e5e1e08517ef1624fd661cb" ]
[ "dianna/methods/shap.py" ]
[ "import numpy as np\n\n\nclass SHAP:\n \"\"\"\n SHAP implementation based on captum https://github.com/pytorch/captum\n \"\"\"\n def __init__(self, shap_arg_1=0, shap_arg_2=0):\n \"\"\"\n Example constructor for testing.\n \"\"\"\n self.shap_arg_1 = shap_arg_1\n self.shap_arg_2 = shap_arg_2\n\n def explain_image(self, model, input_data):\n \"\"\"\n Example call function.\n \"\"\"\n self.model = model\n\n return np.zeros(input_data.shape, dtype=float)\n" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
RTXteam/kgx
[ "902ad8e9ac9069616ded61c8a5a7a61c4467335c" ]
[ "kgx/pandas_transformer.py" ]
[ "import logging\nimport tarfile\nfrom tempfile import TemporaryFile\nfrom typing import List, Dict\n\nimport numpy as np\nimport pandas as pd\n\nfrom kgx.transformer import Transformer\nfrom kgx.utils import make_path\n\nLIST_DELIMITER = '|'\n\n_column_types = {\n 'publications': list,\n 'qualifiers': list,\n 'category': list,\n 'synonym': list,\n 'provided_by': list,\n 'same_as': list,\n 'negated': bool,\n}\n\n_extension_types = {\n 'csv': ',',\n 'tsv': '\\t',\n 'txt': '|'\n}\n\n_archive_mode = {\n 'tar': 'r',\n 'tar.gz': 'r:gz',\n 'tar.bz2': 'r:bz2'\n}\n\n_archive_format = {\n 'w': 'tar',\n 'w:gz': 'tar.gz',\n 'w:bz2': 'tar.bz2'\n}\n\n\nclass PandasTransformer(Transformer):\n \"\"\"\n Transformer that parses a pandas.DataFrame, and loads nodes and edges into a networkx.MultiDiGraph\n \"\"\"\n\n # TODO: Support parsing and export of neo4j-import tool compatible CSVs with appropriate headers\n\n def parse(self, filename: str, input_format: str = 'csv', **kwargs) -> None:\n \"\"\"\n Parse a CSV/TSV (or plain text) file.\n\n The file can represent either nodes (nodes.csv) or edges (edges.csv) or both (data.tar),\n where the tar archive contains nodes.csv and edges.csv\n\n The file can also be data.tar.gz or data.tar.bz2\n\n Parameters\n ----------\n filename: str\n File to read from\n input_format: str\n The input file format ('csv', by default)\n kwargs: Dict\n Any additional arguments\n\n \"\"\"\n if 'delimiter' not in kwargs:\n # infer delimiter from file format\n kwargs['delimiter'] = _extension_types[input_format]\n\n if filename.endswith('.tar'):\n mode = _archive_mode['tar']\n elif filename.endswith('.tar.gz'):\n mode = _archive_mode['tar.gz']\n elif filename.endswith('.tar.bz2'):\n mode = _archive_mode['tar.bz2']\n else:\n # file is not an archive\n mode = None\n\n if mode:\n with tarfile.open(filename, mode=mode) as tar:\n for member in tar.getmembers():\n f = tar.extractfile(member)\n df = pd.read_csv(f, comment='#', **kwargs) # type: pd.DataFrame\n if member.name == \"nodes.{}\".format(input_format):\n self.load_nodes(df)\n elif member.name == \"edges.{}\".format(input_format):\n self.load_edges(df)\n else:\n raise Exception('Tar archive contains an unrecognized file: {}'.format(member.name))\n else:\n df = pd.read_csv(filename, comment='#', dtype=str, **kwargs) # type: pd.DataFrame\n self.load(df)\n\n def load(self, df: pd.DataFrame) -> None:\n \"\"\"\n Load a panda.DataFrame, containing either nodes or edges, into a networkx.MultiDiGraph\n\n Parameters\n ----------\n df : pandas.DataFrame\n Dataframe containing records that represent nodes or edges\n\n \"\"\"\n if 'subject' in df:\n self.load_edges(df)\n else:\n self.load_nodes(df)\n\n def load_nodes(self, df: pd.DataFrame) -> None:\n \"\"\"\n Load nodes from pandas.DataFrame into a networkx.MultiDiGraph\n\n Parameters\n ----------\n df : pandas.DataFrame\n Dataframe containing records that represent nodes\n\n \"\"\"\n for obj in df.to_dict('record'):\n self.load_node(obj)\n\n def load_node(self, node: Dict) -> None:\n \"\"\"\n Load a node into a networkx.MultiDiGraph\n\n Parameters\n ----------\n node : dict\n A node\n\n \"\"\"\n node = Transformer.validate_node(node)\n kwargs = PandasTransformer._build_kwargs(node.copy())\n if 'id' in kwargs:\n n = kwargs['id']\n self.graph.add_node(n, **kwargs)\n else:\n logging.info(\"Ignoring node with no 'id': {}\".format(node))\n\n def load_edges(self, df: pd.DataFrame) -> None:\n \"\"\"\n Load edges from pandas.DataFrame into a networkx.MultiDiGraph\n\n Parameters\n ----------\n df : pandas.DataFrame\n Dataframe containing records that represent edges\n\n \"\"\"\n for obj in df.to_dict('record'):\n self.load_edge(obj)\n\n def load_edge(self, edge: Dict) -> None:\n \"\"\"\n Load an edge into a networkx.MultiDiGraph\n\n Parameters\n ----------\n edge : dict\n An edge\n\n \"\"\"\n edge = Transformer.validate_edge(edge)\n kwargs = PandasTransformer._build_kwargs(edge.copy())\n if 'subject' in kwargs and 'object' in kwargs:\n s = kwargs['subject']\n o = kwargs['object']\n self.graph.add_edge(s, o, **kwargs)\n else:\n logging.info(\"Ignoring edge with either a missing 'subject' or 'object': {}\".format(kwargs))\n\n def export_nodes(self) -> pd.DataFrame:\n \"\"\"\n Export nodes from networkx.MultiDiGraph as a pandas.DataFrame\n\n Returns\n -------\n pandas.DataFrame\n A Dataframe where each record corresponds to a node from the networkx.MultiDiGraph\n\n \"\"\"\n rows = []\n for n, data in self.graph.nodes(data=True):\n data = self.validate_node(data)\n row = PandasTransformer._build_export_row(data.copy())\n row['id'] = n\n rows.append(row)\n df = pd.DataFrame.from_records(rows)\n return df\n\n def export_edges(self) -> pd.DataFrame:\n \"\"\"\n Export edges from networkx.MultiDiGraph as a pandas.DataFrame\n\n Returns\n -------\n pandas.DataFrame\n A Dataframe where each record corresponds to an edge from the networkx.MultiDiGraph\n\n \"\"\"\n rows = []\n for s, o, data in self.graph.edges(data=True):\n data = self.validate_edge(data)\n row = PandasTransformer._build_export_row(data.copy())\n row['subject'] = s\n row['object'] = o\n rows.append(row)\n df = pd.DataFrame.from_records(rows)\n cols = df.columns.tolist()\n cols = PandasTransformer._order_cols(cols)\n df = df[cols]\n return df\n\n def save(self, filename: str, extension: str = 'csv', mode: str = 'w', **kwargs) -> str:\n \"\"\"\n Writes two files representing the node set and edge set of a networkx.MultiDiGraph,\n and add them to a .tar archive.\n\n Parameters\n ----------\n filename: str\n Name of tar archive file to create\n extension: str\n The output file format (csv, by default)\n mode: str\n Form of compression to use ('w', by default, signifies no compression)\n kwargs: dict\n Any additional arguments\n\n \"\"\"\n if extension not in _extension_types:\n raise Exception('Unsupported extension: ' + extension)\n\n archive_name = \"{}.{}\".format(filename, _archive_format[mode])\n delimiter = _extension_types[extension]\n\n nodes_content = self.export_nodes().to_csv(sep=delimiter, index=False, escapechar=\"\\\\\", doublequote=False)\n edges_content = self.export_edges().to_csv(sep=delimiter, index=False, escapechar=\"\\\\\", doublequote=False)\n\n nodes_file_name = 'nodes.' + extension\n edges_file_name = 'edges.' + extension\n\n make_path(archive_name)\n with tarfile.open(name=archive_name, mode=mode) as tar:\n PandasTransformer._add_to_tar(tar, nodes_file_name, nodes_content)\n PandasTransformer._add_to_tar(tar, edges_file_name, edges_content)\n\n return filename\n\n @staticmethod\n def _build_kwargs(data: Dict) -> Dict:\n \"\"\"\n Sanitize key-value pairs in dictionary.\n\n Parameters\n ----------\n data: dict\n A dictionary containing key-value pairs\n\n Returns\n -------\n dict\n A dictionary containing processed key-value pairs\n\n \"\"\"\n # remove numpy.nan\n data = {k : v for k, v in data.items() if v is not np.nan}\n\n for key, value in data.items():\n # process value as a list if key is a multi-valued property\n if key in _column_types:\n if _column_types[key] == list:\n if isinstance(value, (list, set, tuple)):\n data[key] = list(value)\n elif isinstance(value, str):\n data[key] = value.split(LIST_DELIMITER)\n else:\n data[key] = [str(value)]\n elif _column_types[key] == bool:\n try:\n data[key] = bool(value)\n except:\n data[key] = False\n else:\n data[key] = str(value)\n return data\n\n @staticmethod\n def _build_export_row(data: Dict) -> Dict:\n \"\"\"\n Casts all values to primitive types like str or bool according to the\n specified type in `_column_types`. Lists become pipe delimited strings.\n\n Parameters\n ----------\n data: dict\n A dictionary containing key-value pairs\n\n Returns\n -------\n dict\n A dictionary containing processed key-value pairs\n\n \"\"\"\n data = {k : v for k, v in data.items() if v is not np.nan}\n for key, value in data.items():\n if key in _column_types:\n if _column_types[key] == list:\n if isinstance(value, (list, set, tuple)):\n data[key] = LIST_DELIMITER.join(value)\n else:\n data[key] = str(value)\n elif _column_types[key] == bool:\n try:\n data[key] = bool(value)\n except:\n data[key] = False\n else:\n data[key] = str(value)\n return data\n\n @staticmethod\n def _order_cols(cols: List[str]) -> List[str]:\n \"\"\"\n Arrange columns in a defined order.\n\n Parameters\n ----------\n cols: list\n A list with elements in any order\n\n Returns\n -------\n list\n A list with elements in a particular order\n\n \"\"\"\n ORDER = ['id', 'subject', 'predicate', 'object', 'relation']\n cols2 = []\n for c in ORDER:\n if c in cols:\n cols2.append(c)\n cols.remove(c)\n return cols2 + cols\n\n @staticmethod\n def _add_to_tar(tar: tarfile.TarFile, filename: str, filecontent: pd.DataFrame) -> None:\n \"\"\"\n Write file contents to a given filename and add the file\n to a specified tar archive.\n\n Parameters\n ----------\n tar: tarfile.TarFile\n Tar archive handle\n filename: str\n Name of file to add to the archive\n filecontent: pandas.DataFrame\n DataFrame containing data to write to filename\n\n \"\"\"\n content = filecontent.encode()\n with TemporaryFile() as tmp:\n tmp.write(content)\n tmp.seek(0)\n info = tarfile.TarInfo(name=filename)\n info.size = len(content)\n tar.addfile(tarinfo=info, fileobj=tmp)\n" ]
[ [ "pandas.DataFrame.from_records", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
bjodah/finitediff
[ "bfb1940cf5c7ce5c9a3b440d1efd8f8c4128fed8" ]
[ "setup.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport io\nimport os\nimport pprint\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport warnings\n\nfrom setuptools import setup\n\ntry:\n import cython\nexcept ImportError:\n _HAVE_CYTHON = False\nelse:\n _HAVE_CYTHON = True\n assert cython # silence pep8\n\npkg_name = \"finitediff\"\nurl = \"https://github.com/bjodah/\" + pkg_name\nlicense = \"BSD\"\n\n\ndef _path_under_setup(*args):\n return os.path.join(*args)\n\n\nrelease_py_path = _path_under_setup(pkg_name, \"_release.py\")\nconfig_py_path = _path_under_setup(pkg_name, \"_config.py\")\nenv = None # silence pyflakes, 'env' is actually set on the next line\nwith open(config_py_path) as ifh:\n exec(ifh.read())\nfor k, v in list(env.items()):\n env[k] = os.environ.get(\"%s_%s\" % (pkg_name.upper(), k), v)\n\n_version_env_var = \"%s_RELEASE_VERSION\" % pkg_name.upper()\nRELEASE_VERSION = os.environ.get(_version_env_var, \"\")\n\nif len(RELEASE_VERSION) > 1 and RELEASE_VERSION[0] == \"v\":\n TAGGED_RELEASE = True\n __version__ = RELEASE_VERSION[1:]\nelse:\n TAGGED_RELEASE = False\n # read __version__ attribute from _release.py:\n with io.open(release_py_path, encoding=\"utf-8\") as ifh:\n exec(ifh.read())\n if __version__.endswith(\"git\"):\n try:\n _git_version = (\n subprocess.check_output([\"git\", \"describe\", \"--dirty\"])\n .rstrip()\n .decode(\"utf-8\")\n .replace(\"-dirty\", \".dirty\")\n )\n except subprocess.CalledProcessError:\n warnings.warn(\n \"A git-archive is being installed - version information incomplete.\"\n )\n else:\n if \"develop\" not in sys.argv:\n warnings.warn(\"Using git to derive version: dev-branches may compete.\")\n __version__ = re.sub(\n r\"v([0-9.]+)-(\\d+)-(\\w+)\", r\"\\1.post\\2+\\3\", _git_version\n ) # .dev < '' < .post\n\n\nbasename = \"_finitediff_c\"\n_src = {\n ext: _path_under_setup(pkg_name, \"%s.%s\" % (basename, ext))\n for ext in \"c pyx\".split()\n}\nif _HAVE_CYTHON and os.path.exists(_src[\"pyx\"]):\n # Possible that a new release of Python needs a re-rendered Cython source,\n # or that we want to include possible bug-fix to Cython, disable by manually\n # deleting .pyx file from source distribution.\n USE_CYTHON = True\n if os.path.exists(_src[\"c\"]):\n os.unlink(_src[\"c\"]) # ensure c++ source is re-generated.\nelse:\n USE_CYTHON = False\n\nother_sources = [\n os.path.join(\"src\", \"finitediff_c.c\"),\n os.path.join(\n \"finitediff\", \"external\", \"newton_interval\", \"src\", \"newton_interval.c\"\n ),\n]\n\ncmdclass = {}\next_modules = []\nif (\n len(sys.argv) > 1\n and \"--help\" not in sys.argv[1:]\n and not any(\n arg in (\"--help-commands\", \"egg_info\", \"clean\", \"--version\")\n for arg in sys.argv[1:]\n )\n):\n # e.g. egg_info must not import from dependencies (pycompilation)\n import numpy\n\n include_dirs = [\n os.path.join(\"finitediff\", \"external\", \"newton_interval\", \"include\"),\n os.path.join(\"finitediff\", \"include\"),\n numpy.get_include(),\n ]\n\n from setuptools.extension import Extension\n\n ext_modules = [\n Extension(\n \"%s.%s\" % (pkg_name, basename),\n [_src[\"pyx\" if USE_CYTHON else \"c\"]],\n include_dirs=include_dirs,\n )\n ]\n if USE_CYTHON:\n from Cython.Build import cythonize\n\n ext_modules = cythonize(\n ext_modules,\n include_path=include_dirs,\n compiler_directives={\"embedsignature\": True, \"binding\": True},\n )\n else:\n ext_modules[0].sources += other_sources\n\n if ext_modules[0].sources[0].startswith(\"/\"):\n raise ValueError(\"Absolute path not allowed: %s\" % ext_modules[0].sources[0])\n\nsubmodules = [\n pkg_name + \".grid\",\n]\n\ntests = [\n pkg_name + \".tests\",\n pkg_name + \".grid.tests\",\n]\n\nclassifiers = [\n \"Development Status :: 4 - Beta\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Topic :: Scientific/Engineering\",\n \"Topic :: Scientific/Engineering :: Mathematics\",\n]\n\nwith io.open(_path_under_setup(pkg_name, \"__init__.py\"), \"rt\", encoding=\"utf-8\") as f:\n short_description = f.read().split('\"\"\"')[1].split(\"\\n\")[1]\nif not 10 < len(short_description) < 255:\n warnings.warn(\"Short description from __init__.py proably not read correctly.\")\nwith io.open(_path_under_setup(\"README.rst\"), encoding=\"utf-8\") as ifh:\n long_description = ifh.read()\nif not len(long_description) > 100:\n warnings.warn(\"Long description from README.rst probably not read correctly.\")\nwith io.open(_path_under_setup(\"AUTHORS\"), \"rt\", encoding=\"utf-8\") as ifh:\n _author, _author_email = ifh.readline().split(\"<\")\n\n\nsetup_kwargs = dict(\n name=pkg_name,\n version=__version__, # from release_py_path\n description=short_description,\n long_description=long_description,\n author=_author.strip(),\n author_email=_author_email.split(\">\")[0].strip(),\n url=url,\n license=license,\n keywords=[\"finite-difference\", \"taylor series\", \"extrapolation\", \"interpolation\"],\n packages=[pkg_name] + submodules + tests,\n include_package_data=True,\n cmdclass=cmdclass,\n ext_modules=ext_modules,\n classifiers=classifiers,\n setup_requires=[\"numpy\"] + ([\"cython\"] if USE_CYTHON else []),\n install_requires=[\"numpy\"],\n extras_require={\n \"all\": [\"scipy\", \"pytest\", \"sphinx\", \"sphinx_rtd_theme\", \"numpydoc\"]\n },\n)\n\nif __name__ == \"__main__\":\n try:\n if TAGGED_RELEASE:\n # Same commit should generate different sdist\n # depending on tagged version (set FINITEDIFF_RELEASE_VERSION)\n # this will ensure source distributions contain the correct version\n shutil.move(release_py_path, release_py_path + \"__temp__\")\n with open(release_py_path, \"wt\") as ofh:\n ofh.write(\"__version__ = '{}'\\n\".format(__version__))\n shutil.move(config_py_path, config_py_path + \"__temp__\")\n with open(config_py_path, \"wt\") as fh:\n fh.write(\"env = {}\\n\".format(pprint.pformat(env)))\n setup(**setup_kwargs)\n finally:\n if TAGGED_RELEASE:\n shutil.move(release_py_path + \"__temp__\", release_py_path)\n shutil.move(config_py_path + \"__temp__\", config_py_path)\n" ]
[ [ "numpy.get_include" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
WayneDW/Interacting-Contour-Stochastic-Gradient-Langevin-Dynamics
[ "ecc073572d283895cf2629faf5522d83b23da1e3" ]
[ "mnist_energy_exploration/tools/uncertainty_test.py" ]
[ "#!/usr/bin/python\n\nimport math\nimport copy\nimport sys\nimport os\nimport timeit\nimport csv\nimport argparse\nfrom tqdm import tqdm ## better progressbar\nfrom math import exp\nfrom sys import getsizeof\nimport numpy as np\nimport random\nimport pickle\n## import pytorch modules\nimport torch\nfrom torch.autograd import Variable\nimport numpy as np\nimport torch.nn as nn\nfrom torchvision import datasets, transforms\nfrom torchvision.datasets import ImageFolder\nfrom torchvision.transforms import ToTensor\nfrom torch.utils.data import DataLoader\nimport torch.utils.data as data\nimport torchvision.datasets as datasets\n\nfrom tools import save_or_pretrain, loader\n#from trainer import trainer\n#from trainer_cyc import trainer\nfrom trainer_re_cyc import trainer\n#from trainer_period import trainer\n#from trainer_adaptive_c import trainer\n#from trainer_SWA_v2 import trainer\n\nimport models.fashion as fmnist_models\nimport models.cifar as cifar_models\nfrom models.cifar import PyramidNet as PYRM\n\nparser = argparse.ArgumentParser(description='Grid search')\nparser.add_argument('-aug', default=1, type=float, help='Data augmentation or not')\nparser.add_argument('-split', default=2, type=int, help='Bayes avg every split epochs')\n# numper of optimization/ sampling epochs\nparser.add_argument('-sn', default=500, type=int, help='Sampling Epochs')\nparser.add_argument('-wdecay', default=25, type=float, help='Samling weight decay')\nparser.add_argument('-lr', default=2e-6, type=float, help='Sampling learning rate')\nparser.add_argument('-momentum', default=0.9, type=float, help='Sampling momentum learning rate')\nparser.add_argument('-burn', default=0.6, type=float, help='burn in iterations for sampling (sn * burn)')\nparser.add_argument('-ifstop', default=1, type=int, help='stop iteration if acc is too low')\n\n# Parallel Tempering hyperparameters\nparser.add_argument('-chains', default=2, type=int, help='Total number of chains')\nparser.add_argument('-var_reduce', default=1, type=int, help='n>0 means update variance reduction every n epochs; n divides 10')\nparser.add_argument('-period', default=2, type=int, help='estimate adaptive variance every [period] epochs')\nparser.add_argument('-T', default=0.001, type=float, help='Inverse temperature for high temperature chain')\nparser.add_argument('-T_scale', default=1.0, type=float, help='Uncertainty calibration')\nparser.add_argument('-Tgap', default=0.2, type=float, help='Temperature gap between chains')\nparser.add_argument('-LRgap', default=0.66, type=float, help='Learning rate gap between chains')\nparser.add_argument('-anneal', default=1.002, type=float, help='temperature annealing factor')\nparser.add_argument('-lr_anneal', default=0.992, type=float, help='lr annealing factor')\nparser.add_argument('-F_jump', default=0.9, type=float, help='F jump factor')\nparser.add_argument('-cool', default=0, type=int, help='No swaps happen during the cooling time after a swap')\n\n# other settings\nparser.add_argument('-ck', default=False, type=bool, help='Check if we need overwriting check')\nparser.add_argument('-data', default='cifar10', dest='data', help='MNIST/ Fashion MNIST/ CIFAR10/ CIFAR100')\n#parser.add_argument('-no_c', default=100, type=int, help='number of classes')\nparser.add_argument('-model', default='resnet', type=str, help='resnet / preact / WRN')\nparser.add_argument('-depth', type=int, default=20, help='Model depth.')\nparser.add_argument('-total', default=50000, type=int, help='Total data points')\nparser.add_argument('-train', default=256, type=int, help='Training batch size')\nparser.add_argument('-test', default=1000, type=int, help='Testing batch size')\nparser.add_argument('-seed', default=random.randint(1, 1e6), type=int, help='Random Seed')\nparser.add_argument('-gpu', default=0, type=int, help='Default GPU')\nparser.add_argument('-multi', default=0, type=int, help='Multiple GPUs')\nparser.add_argument('-windows', default=20, type=int, help='Moving average of corrections')\nparser.add_argument('-alpha', default=0.3, type=float, help='forgetting rate')\nparser.add_argument('-bias_F', default=2000, type=float, help='correction factor F')\nparser.add_argument('-cycle', default=2, type=int, help='Number of cycles')\nparser.add_argument('-F_stop', default=0.8, type=float, help='F decay stop station')\nparser.add_argument('-repeats', default=50, type=int, help='number of samples to estimate sample std')\n\npars = parser.parse_args()\n\n\ntorch.cuda.set_device(pars.gpu)\n\nnet = cifar_models.__dict__['resnet'](num_classes=10, depth=pars.depth).cuda()\n\ndataloader = datasets.CIFAR10\n\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntestset = dataloader(root='./data/' + pars.data.upper(), train=False, download=False, transform=transform_test)\ntest_loader = data.DataLoader(testset, batch_size=pars.test, shuffle=False, num_workers=0)\n\nnotcifar = datasets.SVHN(root='./data/SVHN', split='test', download=True, transform=transform_test)\ntarget_loader = data.DataLoader(notcifar, batch_size=pars.test, shuffle=False, num_workers=0)\n\n\n\"\"\" Step 3: Load Model \"\"\"\ntorch.set_printoptions(precision=3)\n\ndef number_digits(x): return str(x)[:6]\nsoftmax = nn.Softmax(dim=1)\n\n\n\"\"\" Step 3.1: Ensemble outputs and then transform to prob \"\"\"\n\nBrier_seen = 0\nBrier_unseen = 0\nentropy_seen = 0\nentropy_unseen = 0\n\n\n\noutput_ensemble_seen = []\noutput_ensemble_unseen = []\nprob_ensemble_seen = []\nprob_ensemble_unseen = []\n\nidx = 1\n\nsub_sn = pars.sn / pars.cycle\n\n\nseeds_list = [pars.seed]\n\n# VR-reSGHMC\nseeds_list = [4114, 24072, 54346, 92678, 99759]\n\n# M-SGD\n\nseeds_list = [5122, 65045, 66219, 69629, 92098]\n\n# CSGHMC\n#seeds_list = [11576, 14939]\n\n# T = 1\n#seeds_list = [43204, 60252, 10993, 95810, 44456]\n\n# T = 0.01\n#seeds_list = [11766, 33390, 73113, 74527] \n\n# T = 0.03\n#seeds_list = [34712, 60003, 8574, 96052]\n#drwxrwxr-x 2 deng106 deng106 4096 Sep 16 23:19 cifar10_resnet20_batch_256_chain_2_T_0.03_VR_1_p_2_burn_0.6_seed_34712\n#drwxrwxr-x 2 deng106 deng106 4096 Sep 16 23:19 cifar10_resnet20_batch_256_chain_2_T_0.03_VR_1_p_2_burn_0.6_seed_60003\n#drwxrwxr-x 2 deng106 deng106 4096 Sep 16 23:19 cifar10_resnet20_batch_256_chain_2_T_0.03_VR_1_p_2_burn_0.6_seed_8574\n#drwxrwxr-x 2 deng106 deng106 4096 Sep 16 23:19 cifar10_resnet20_batch_256_chain_2_T_0.03_VR_1_p_2_burn_0.6_seed_96052\n\n\n#seeds_list = [12154, 27318, 30595, 4080]\n#seeds_list = [38432, 6167, 87392]\n\n# ensemble prob gives way better uniform predictions than taking ensemble prediction and softmax\n\n\nfor seed in seeds_list:\n if pars.chains == 2 and pars.var_reduce == 0:\n DIR = 'output/test_snapshot/' + pars.data + '_' + pars.model + str(pars.depth) + '_batch_' + str(pars.train) + '_chain_' + str(pars.chains) + '_T_' + str(pars.T) + '_VR_' + str(pars.var_reduce) + '_p_' + str(pars.period) + '_burn_' + str(pars.burn) + '_cycle_' + str(pars.cycle) + '_seed_' + str(seed)\n elif pars.chains == 2:\n DIR = 'output/test_snapshot/' + pars.data + '_' + pars.model + str(pars.depth) + '_batch_' + str(pars.train) + '_chain_' + str(pars.chains) + '_T_' + str(pars.T) + '_VR_' + str(pars.var_reduce) + '_p_' + str(pars.period) + '_burn_' + str(pars.burn) + '_seed_' + str(seed)\n #DIR = 'output/test_snapshot/' + pars.data + '_' + pars.model + str(pars.depth) + '_batch_' + str(pars.train) + '_chain_' + str(pars.chains) + '_T_' + str(pars.T) + '_VR_' + str(pars.var_reduce) + '_p_' + str(pars.period) + '_burn_' + str(pars.burn) + '_cycle_' + str(pars.cycle) + '_seed_' + str(seed)\n else:\n DIR = 'output/test_snapshot/' + pars.data + '_' + pars.model + str(pars.depth) + '_batch_' + str(pars.train) + '_chain_' + str(pars.chains) + '_T_' + str(pars.T) + '_VR_' + str(pars.var_reduce) + '_p_' + str(pars.period) + '_burn_' + str(pars.burn) + '_cycle_' + str(pars.cycle) + '_seed_' + str(seed)\n\n for filename in sorted(os.listdir(DIR)):\n if filename[-1] not in ['5']:\n continue\n file_idx = float(filename.split('_')[-1])\n cur_beta = (file_idx % sub_sn) * 1.0 / sub_sn\n if pars.cycle == 1 and cur_beta < 0.8:\n continue\n elif cur_beta < 0.7 or cur_beta in [0.94, 0.86, 0.78]:\n continue\n #elif cur_beta < 0.9:\n # continue\n elif pars.cycle == 4 and ((file_idx <=500 and cur_beta < 0.8) or (file_idx >500 and cur_beta < 0.85)):\n continue\n net.load_state_dict(torch.load(DIR + '/' + filename))\n net.eval()\n\n if pars.chains == 2 and filename.startswith('Chain_0'):\n continue\n\n\n for cnt, (images, labels) in enumerate(test_loader):\n images, labels = Variable(images).cuda(), Variable(labels).cuda()\n outputs = net.forward(images).data / pars.T_scale\n prob = softmax(outputs)\n if idx == 1:\n output_ensemble_seen.append(outputs)\n prob_ensemble_seen.append(prob)\n else:\n output_ensemble_seen[cnt] = (1. - 1. / idx) * output_ensemble_seen[cnt] + (1. / idx) * outputs\n prob_ensemble_seen[cnt] = (1. - 1. / idx) * prob_ensemble_seen[cnt] + (1. / idx) * prob\n\n for cnt, (images, labels) in enumerate(target_loader):\n images, labels = Variable(images).cuda(), Variable(labels).cuda()\n outputs = net.forward(images).data / pars.T_scale\n prob = softmax(outputs)\n if idx == 1:\n output_ensemble_unseen.append(outputs)\n prob_ensemble_unseen.append(prob)\n else:\n output_ensemble_unseen[cnt] = (1. - 1. / idx) * output_ensemble_unseen[cnt] + (1. / idx) * outputs\n prob_ensemble_unseen[cnt] = (1. - 1. / idx) * prob_ensemble_unseen[cnt] + (1. / idx) * prob\n \n idx += 1\n\n Brier_seen, counts_seen = 0, 0\n # entropy ranges from 0 to 2.5 roughly with each unit of width 0.05\n hist_brier_seen = [0] * 300000\n hist_entropy_seen = [0] * 50\n hist_entropy_unseen = [0] * 50\n for cnt, (images, labels) in enumerate(test_loader):\n images, labels = Variable(images).cuda(), Variable(labels).cuda()\n prob_seen = prob_ensemble_seen[cnt]\n #prob_seen = softmax(output_ensemble_seen[cnt])\n one_hot = torch.nn.functional.one_hot(labels, num_classes=10).float()\n counts_seen += prob_seen.shape[0]\n Brier_seen += torch.mean((prob_seen - one_hot)**2,dim=1).sum().item()\n prob_seen_reg = prob_seen + 1e-20\n entropy_idx = (torch.sum(-prob_seen_reg * torch.log(prob_seen_reg), dim=1) / 0.05).int().tolist()\n for idx_ in entropy_idx:\n hist_entropy_seen[idx_] += 1\n \n Brier_unseen = 0\n counts_unseen = 0\n for cnt, (images, labels) in enumerate(target_loader):\n images, labels = Variable(images).cuda(), Variable(labels).cuda()\n prob_unseen = prob_ensemble_unseen[cnt] \n #prob_unseen = softmax(output_ensemble_unseen[cnt])\n counts_unseen += prob_unseen.shape[0]\n Brier_unseen += torch.mean((prob_unseen)**2,dim=1).sum().item()\n prob_unseen_reg = prob_unseen + 1e-20\n entropy_idx = (torch.sum(-prob_unseen_reg * torch.log(prob_unseen_reg), dim=1) / 0.05).int().tolist()\n for idx_ in entropy_idx:\n hist_entropy_unseen[idx_] += 1\n print('===' * 100)\n print('Seed {} {} cur_beta {:.2f} Seen / Unseen / Total Brier score {:.4f} / {:.3f} / {:.3f}'.format(seed, filename, cur_beta, \\\n Brier_seen/counts_seen, Brier_unseen/counts_unseen, (Brier_seen+Brier_unseen)/(counts_seen+counts_seen)))\n\n print(\"Entropy seen (from low to high)\")\n print(hist_entropy_seen)\n print(\"Entropy unseen (from high to low)\")\n print(hist_entropy_unseen[::-1])\n" ]
[ [ "torch.nn.Softmax", "torch.mean", "torch.cuda.set_device", "torch.load", "torch.set_printoptions", "torch.utils.data.DataLoader", "torch.log", "torch.nn.functional.one_hot", "torch.autograd.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
prashantas/MyOwnR
[ "8db4f288b30840161c6422bde7c7a7770f85c09d" ]
[ "DeepNetwork/ImpNotes.py" ]
[ "#TO understand ImgeDataGenerator see https://www.youtube.com/watch?v=OUMDUq5OJLg&t=3297s from 25 mins\n\n#########################################################################################################################\n#### https://www.youtube.com/watch?v=yX8KuPZCAMo # Very Good Link from Edureka for tensorflow basics Really Good\n\n# A placeholder is nothing but a promise to provide the value later\n\na = tf.placeholder(tf.float32)\nb = tf.placeholder(tf.float32)\n\nadder_node = a+b\nsess = tf.Session()\n\nprint(sess.run(adder_node,{a:[1,3],b:[2,4]}))\n\n###########################################################################################################\n###########################################################################################################\n#When we train a model, we use variable to hold an update parameter. Variables allow us to add trainable parameters to a graph\nimport tensorflow as tf\n#Model parameters\nW = tf.Variable([.3],tf.float32)\nb = tf.Variable([-.3], tf.float32)\n\n#Inputs and Outputs\nx = tf.placeholder(tf.float32)\ny = tf.placeholder(tf.float32) # Actual output which we already know\n\nlinear_model = W*x+b\n\n#Loss ffunction\nsquared_delta = tf.square(linear_model - y)\nloss = tf.reduce_sum(squared_delta)\n\ninit = tf.global_variables_initializer()\n\nsess = tf.Session()\nsess.run(init)\nprint(sess.run(loss,{x:[1,2,3,4],y:[0,-1,-2,-3]}))\n### the output is 23.66\n###########################################################################################################################################\n### Now by changing W and b we can actually reduce the loss.\n## Now if W = -1 and b =1 then our our linear_model becomes y i.e. output of our model becomes the actual output\n## -1 x 1 + 1 = 0\n## -1 x 2 + 1 = -1\n## -1 x 3 + 1 = -2\n## -1 x 4 + 1 = -3\n## if we change W = tf.Variable([-1.0],tf.float32)\n## b = tf.Variable([1.0], tf.float32) , we will get loss as 0.0\n## If we want machine to learn W and b , we need optimizer\n## Optimizer modifies each variable according to the magnitude of the derivative of loss w.r.t that variable. here we will use\n## Gradient Descent optimizer i.e The optimizer will check the magnitude of the derivative of loss i.e the optimizer will check\n## the change in the loss w.r t the change in the variable and if the loss is decreasing then it will keep on changing the variable \n## in that particular direction # The rate at which the variable keeps chaging is the learning_rate.\n###### So the modified version of the above code is ::::\nimport tensorflow as tf\n#Model parameters\nW = tf.Variable([.3],tf.float32)\nb = tf.Variable([-.3], tf.float32)\n\n#Inputs and Outputs\nx = tf.placeholder(tf.float32)\ny = tf.placeholder(tf.float32) # Actual output which we already know\n\nlinear_model = W*x+b\n\n#Loss ffunction\nsquared_delta = tf.square(linear_model - y)\nloss = tf.reduce_sum(squared_delta)\n\n##optimize\noptimizer = tf.train.GradientDescentOptimizer(0.01)\ntrain = optimizer.minimize(loss)\n\n\ninit = tf.global_variables_initializer()\n\nsess = tf.Session()\nsess.run(init)\n#print(sess.run(loss,{x:[1,2,3,4],y:[0,-1,-2,-3]}))\nfor i in range(1000):\n sess.run(train,{x:[1,2,3,4],y:[0,-1,-2,-3]})\n \nprint(sess.run([W,b]))\n## The output comes as :: [array([-0.9999969], dtype=float32), array([ 0.99999082], dtype=float32)]\n#################################################################################################################\n#################################################################################################################\n" ]
[ [ "tensorflow.Variable", "tensorflow.reduce_sum", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.train.GradientDescentOptimizer", "tensorflow.square", "tensorflow.Session" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]