repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
mccutcheonlab/PPP_analysis | [
"08df6fe199d08ac807870adf8c2dbfc5cf81b44d"
] | [
"customized_scripts/ebbs_heatmap.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 13 13:37:11 2019\n\n@author: jmc010\n\"\"\"\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport matplotlib.lines as mlines\n\nimport numpy as np\n\n# install at an anaconda command prompt using: conda install -c anaconda dill\nimport dill\n\n#Colors\ngreen = mpl.colors.to_rgb('xkcd:kelly green')\nlight_green = mpl.colors.to_rgb('xkcd:light green')\nalmost_black = mpl.colors.to_rgb('#262626')\n\ndef heatmapCol(f, df, gs, diet, session, rat, event='', reverse=False, clims=[0,1], colorgroup='control'):\n \n if colorgroup == 'control':\n color = [almost_black, 'xkcd:bluish grey']\n errorcolors = ['xkcd:silver', 'xkcd:silver']\n else:\n color = [green, light_green]\n errorcolors = ['xkcd:silver', 'xkcd:silver']\n \n data_cas = df[session+'_cas'][rat]\n data_malt = df[session+'_malt'][rat]\n event_cas = df[session+'_cas_event'][rat]\n event_malt = df[session+'_malt_event'][rat]\n \n if reverse:\n event_cas = [-event for event in event_cas]\n event_malt = [-event for event in event_malt]\n \n col_gs = gridspec.GridSpecFromSubplotSpec(2,1,subplot_spec=gs[:,0],\n height_ratios=[0.05,1],\n hspace=0.0)\n \n plots_gs = gridspec.GridSpecFromSubplotSpec(3,2,subplot_spec=col_gs[1,0],\n width_ratios=[12,1],\n wspace=0.05)\n \n marker_gs = gridspec.GridSpecFromSubplotSpec(1,2,subplot_spec=col_gs[0,0],\n width_ratios=[12,1],\n wspace=0.05)\n\n ax1 = f.add_subplot(plots_gs[0,0])\n ax, mesh = makeheatmap(ax1, data_cas, events=event_cas, ylabel='Casein trials')\n mesh.set_clim(clims)\n \n ax2 = f.add_subplot(plots_gs[1,0], sharex=ax1)\n ax, mesh = makeheatmap(ax2, data_malt, events=event_malt, ylabel='Malt. trials')\n mesh.set_clim(clims)\n \n ax0 = f.add_subplot(marker_gs[0,0], sharex=ax1)\n ax0.axis('off')\n if event == 'Sipper':\n ax0.plot(0,0, 'v', color='xkcd:silver')\n ax0.annotate(event, xy=(0, 0), xytext=(0,5), textcoords='offset points',\n ha='center', va='bottom')\n elif event == 'Licks':\n ax0.plot([0,5], [0,0], color='xkcd:silver', linewidth=3)\n ax0.annotate(event, xy=(2.5, 0), xytext=(0,5), textcoords='offset points',\n ha='center', va='bottom')\n \n ax1.set_xlim([-10,20])\n \n cbar_ax = f.add_subplot(plots_gs[0,1]) \n cbar = f.colorbar(mesh, cax=cbar_ax, ticks=[clims[0], 0, clims[1]])\n cbar_labels = ['{0:.0f}%'.format(clims[0]*100),\n '0% \\u0394F',\n '{0:.0f}%'.format(clims[1]*100)]\n cbar.ax.set_yticklabels(cbar_labels)\n \n ax3 = f.add_subplot(plots_gs[2,0])\n \n shadedError(ax3, data_cas, linecolor=color[0], errorcolor=errorcolors[0])\n shadedError(ax3, data_malt, linecolor=color[1], errorcolor=errorcolors[1])\n \n ax3.axis('off')\n\n y = [y for y in ax3.get_yticks() if y>0][:2]\n l = y[1] - y[0]\n scale_label = '{0:.0f}% \\u0394F'.format(l*100)\n ax3.plot([50,50], [y[0], y[1]], c=almost_black)\n ax3.text(40, y[0]+(l/2), scale_label, va='center', ha='right')\n\n# Adds x scale bar \n y = ax3.get_ylim()[0]\n ax3.plot([251,300], [y, y], c=almost_black, linewidth=2)\n ax3.annotate('5 s', xy=(276,y), xycoords='data',\n xytext=(0,-5), textcoords='offset points',\n ha='center',va='top')\n\ndef makeheatmap(ax, data, events=None, ylabel='Trials'):\n ntrials = np.shape(data)[0]\n xvals = np.linspace(-9.9,20,300)\n yvals = np.arange(1, ntrials+2)\n xx, yy = np.meshgrid(xvals, yvals)\n \n mesh = ax.pcolormesh(xx, yy, data, cmap='jet', shading = 'flat')\n \n if events:\n ax.vlines(events, yvals[:-1], yvals[1:], color='w')\n else:\n print('No events')\n \n ax.set_ylabel(ylabel)\n ax.set_yticks([1, ntrials])\n ax.set_xticks([])\n ax.invert_yaxis()\n \n return ax, mesh\n\ndef shadedError(ax, yarray, linecolor='black', errorcolor = 'xkcd:silver', linewidth=1):\n yarray = np.array(yarray)\n y = np.mean(yarray, axis=0)\n yerror = np.std(yarray)/np.sqrt(len(yarray))\n x = np.arange(0, len(y))\n ax.plot(x, y, color=linecolor, linewidth=1)\n ax.fill_between(x, y-yerror, y+yerror, color=errorcolor, alpha=0.4)\n \n return ax\n\n# get data, change pickle_folder if needed\npickle_folder = '..\\\\data\\\\'\n\npickle_in = open(pickle_folder + 'ppp_dfs_pref.pickle', 'rb')\ndf_behav, df_photo, df_reptraces, df_heatmap, df_reptraces_sip, df_heatmap_sip, longtrace = dill.load(pickle_in)\n\n\n# initialize figure\ngs = gridspec.GridSpec(2, 1, wspace=0.8, hspace=0.3, left=0.2, right=0.8, bottom=0.05, top=0.95)\nf = plt.figure(figsize=(4,6))\n\ndiet='NR'\nsession='pref1'\nrat='PPP1-7'\nevent ='Licks'\nclims=[-0.05,0.17]\nreverse=True\ncolors='control'\n\nheatmapCol(f, df_heatmap, gs, diet, session, rat, event=event, clims=clims, reverse=reverse, colorgroup=colors)\nf.savefig('EBBS_heatmap.jpg')\nf.savefig('SfN_heatmap.pdf')"
] | [
[
"matplotlib.gridspec.GridSpecFromSubplotSpec",
"matplotlib.colors.to_rgb",
"numpy.linspace",
"numpy.arange",
"numpy.std",
"numpy.mean",
"matplotlib.gridspec.GridSpec",
"numpy.shape",
"numpy.array",
"numpy.meshgrid",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
iqbal-lab-org/pandora_paper_roc | [
"bb21c76faefa8021c86c3be9d77b8b5999fe2ef5",
"bb21c76faefa8021c86c3be9d77b8b5999fe2ef5"
] | [
"pipeline/scripts/calculate_recall_per_sample_vs_nb_of_samples.py",
"pipeline/scripts/utils.py"
] | [
"from pathlib import Path\nimport sys\nsys.path.append(str(Path().absolute()))\nimport logging\nlog_level = \"INFO\"\nlogging.basicConfig(\n filename=str(snakemake.log),\n filemode=\"w\",\n level=log_level,\n format=\"[%(asctime)s]:%(levelname)s: %(message)s\",\n datefmt=\"%d/%m/%Y %I:%M:%S %p\",\n)\nfrom evaluate.calculator import RecallCalculator\nfrom evaluate.report import RecallReport\nimport pandas as pd\n\n\n# setup\nall_recall_reports_for_one_sample = snakemake.input.all_recall_reports_for_one_sample\nsample = snakemake.wildcards.sample_id\ntool = snakemake.wildcards.tool\ncoverage = snakemake.wildcards.coverage\ncoverage_threshold = snakemake.wildcards.coverage_threshold\nstrand_bias_threshold = snakemake.wildcards.strand_bias_threshold\ngaps_threshold = snakemake.wildcards.gaps_threshold\nlist_with_number_of_samples = snakemake.params.list_with_number_of_samples\nrecall_file_for_one_sample_vs_nb_samples_filename = Path(snakemake.output.recall_file_for_one_sample_vs_nb_samples)\n\n\n# API usage\nlogging.info(f\"Loading report\")\nrecall_report = RecallReport.from_files(all_recall_reports_for_one_sample,\n concatenate_dfs_one_by_one_keeping_only_best_mappings=True)\n\nlogging.info(f\"Creating calculator\")\nrecall_calculator = RecallCalculator(recall_report)\n\nlogging.info(f\"Calculating recall\")\nrecall_df = recall_calculator.get_recall_report_wrt_truth_probes_for_those_present_in_a_given_nb_of_samples(list_with_number_of_samples)\n\nmetadata_df = pd.DataFrame(\n data={\n \"tool\": [tool] * len(recall_df),\n \"coverage\": [coverage] * len(recall_df),\n \"coverage_threshold\": [coverage_threshold] * len(recall_df),\n \"strand_bias_threshold\": [strand_bias_threshold] * len(recall_df),\n \"gaps_threshold\": [gaps_threshold] * len(recall_df),\n \"sample\": [sample] * len(recall_df)\n }\n)\noutput_df = pd.concat([recall_df, metadata_df], axis=1)\n\n\n# output\nlogging.info(f\"Outputting recall file\")\noutput_df.to_csv(recall_file_for_one_sample_vs_nb_samples_filename, index=False)\nlogging.info(f\"Done\")\n",
"import pandas as pd\n\ndef get_concatenated_df(files, separator, fields_to_keep = None):\n dfs = [pd.read_csv(file, sep=separator) for file in files]\n concatenated_df = pd.concat(dfs, ignore_index=True)\n if fields_to_keep is not None:\n concatenated_df = concatenated_df[fields_to_keep]\n return concatenated_df\n\n\ndef get_sample_pairs_containing_given_sample(sample_pairs, sample):\n sample_pairs_with_sample = [pair for pair in sample_pairs if sample in pair]\n sample_pairs_with_sample_as_str = [f\"{sample1}_and_{sample2}\" for sample1, sample2 in sample_pairs_with_sample]\n return sample_pairs_with_sample_as_str"
] | [
[
"pandas.concat"
],
[
"pandas.concat",
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
kendoo-solutions/amazon-sagemaker-workshop | [
"359a25dfb11fe98155347b0f8f194049548649c7"
] | [
"Modules/3 - Distributed Training with TensorFlow Notebook/utils.py"
] | [
"\"\"\"Converts MNIST data to TFRecords file format with Example protos.\"\"\"\nimport os\nimport tensorflow as tf\nfrom PIL import Image\nimport numpy as np\nfrom matplotlib.pyplot import imshow\n\ndef gen_image(arr):\n try:\n two_d = (np.reshape(arr, (28, 28)) * 255).astype(np.uint8)\n img = Image.fromarray(two_d, 'L')\n imshow(np.asarray(two_d))\n return True\n except Exception as e:\n print('[gen_image] error {}'.format(e))\n return False\n\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef convert_to(data_set, name, directory):\n \"\"\"Converts a dataset to tfrecords.\"\"\"\n images = data_set.images\n labels = data_set.labels\n num_examples = data_set.num_examples\n\n if images.shape[0] != num_examples:\n raise ValueError('Images size %d does not match label size %d.' %\n (images.shape[0], num_examples))\n rows = images.shape[1]\n cols = images.shape[2]\n depth = images.shape[3]\n\n filename = os.path.join(directory, name + '.tfrecords')\n print('Writing', filename)\n writer = tf.python_io.TFRecordWriter(filename)\n for index in range(num_examples):\n image_raw = images[index].tostring()\n example = tf.train.Example(features=tf.train.Features(feature={\n 'height': _int64_feature(rows),\n 'width': _int64_feature(cols),\n 'depth': _int64_feature(depth),\n 'label': _int64_feature(int(labels[index])),\n 'image_raw': _bytes_feature(image_raw)}))\n writer.write(example.SerializeToString())\n writer.close()"
] | [
[
"numpy.asarray",
"numpy.reshape",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.train.BytesList",
"tensorflow.train.Int64List"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Dakror/OpenMDAO | [
"3650622e0e96bed6979991bd096186c85050738f",
"3650622e0e96bed6979991bd096186c85050738f",
"3650622e0e96bed6979991bd096186c85050738f",
"3650622e0e96bed6979991bd096186c85050738f",
"3650622e0e96bed6979991bd096186c85050738f"
] | [
"openmdao/devtools/memory.py",
"openmdao/core/tests/test_coloring.py",
"openmdao/test_suite/test_examples/test_circuit_analysis_derivs.py",
"openmdao/solvers/linesearch/tests/test_backtracking.py",
"openmdao/recorders/tests/test_distrib_sqlite_recorder.py"
] | [
"\"\"\"Various debugging functions.\"\"\"\n\nimport sys\nimport os\nimport functools\nimport gc\n\ntry:\n import resource\n\n def max_mem_usage():\n \"\"\"\n Return the maximum resident memory used by this process and its children so far.\n\n Returns\n -------\n The max resident memory used by this process and its children, in MB.\n \"\"\"\n denom = 1024.\n if sys.platform == 'darwin':\n denom *= denom\n total = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / denom\n total += resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss / denom\n return total\n\nexcept ImportError:\n resource = None\n def max_mem_usage():\n raise RuntimeError(\"The 'max_mem_usage' function requires the 'resource' package.\")\n\ntry:\n import psutil\n\n def mem_usage(msg='', out=sys.stdout, resident=True):\n \"\"\"\n Display current resident or virtual memory usage.\n\n Parameters\n ----------\n msg : str\n String prepended to each reported memory usage.\n out : file-like\n Output will be sent to this stream.\n\n Returns\n -------\n The current memory used by this process, in MB.\n \"\"\"\n denom = 1024. * 1024.\n p = psutil.Process(os.getpid())\n if resident:\n mem = p.memory_info().rss / denom\n else:\n mem = p.memory_info().vms / denom\n if msg:\n print(msg,\"%6.3f MB\" % mem, file=out)\n return mem\n\n def diff_mem(fn):\n \"\"\"\n Decorator that prints the difference in resident memory usage resulting from the call.\n\n Does not show output unless there is a memory increase. Requires psutil to be installed.\n\n Parameters\n ----------\n fn : function\n The function being decorated.\n\n Returns\n -------\n function\n The wrapper function.\n \"\"\"\n @functools.wraps(fn)\n def wrapper(*args, **kwargs):\n startmem = mem_usage()\n ret = fn(*args, **kwargs)\n maxmem = mem_usage()\n diff = maxmem - startmem\n if diff > 0.0:\n if args and hasattr(args[0], 'pathname'):\n name = args[0].pathname\n else:\n name = str(args[0])\n print(name, \"%s added %.0f KB (total: %6.3f MB)\" %\n (fn.__name__, diff * 1024., maxmem))\n return ret\n return wrapper\n\n def check_iter_mem(niter, func, *args, **kwargs):\n \"\"\"\n Run func niter times and collect info on memory usage.\n\n Parameters\n ----------\n niter : int\n Number of times to run func.\n func : function\n A function that takes no arguments.\n *args : tuple\n Positional args passed to func.\n **kwargs : dict\n Named args to be passed to func.\n \"\"\"\n gc.collect()\n\n yield mem_usage()\n for i in range(niter):\n func(*args, **kwargs)\n gc.collect()\n yield mem_usage()\n\nexcept ImportError:\n psutil = None\n def mem_usage(*args, **kwargs):\n raise RuntimeError(\"The 'mem_usage' function requires the 'psutil' package. You can \"\n \"install it using 'pip install psutil'.\")\n def diff_mem(*args, **kwargs):\n raise RuntimeError(\"The 'diff_mem' function requires the 'psutil' package. You can \"\n \"install it using 'pip install psutil'.\")\n def check_iter_mem(*args, **kwargs):\n raise RuntimeError(\"The 'check_iter_mem' function requires the 'psutil' package. You can \"\n \"install it using 'pip install psutil'.\")\n\n\ntry:\n import objgraph\n\n def get_new_objects(lst, fn, *args, **kwargs):\n \"\"\"\n Collect types and numbers of new objects left over after the given function is called.\n\n If lst is not empty after the call, this MAY indicate a memory leak, but not necessarily,\n since some functions are intended to create new objects for later use.\n\n Parameters\n ----------\n lst : list\n List used to collect objects and deltas.\n fn : function\n The function being checked for possible memory leaks.\n *args : tuple\n Positional args passed to fn.\n **kwargs : dict\n Named args to be passed to fn.\n\n Returns\n -------\n object\n The object returned by the call to fn.\n \"\"\"\n gc.collect()\n start_objs = objgraph.typestats()\n start_objs['frame'] += 1\n start_objs['function'] += 1\n start_objs['builtin_function_or_method'] += 1\n start_objs['cell'] += 1\n ret = fn(*args, **kwargs)\n lst.extend([(str(o), delta) for o, _, delta in objgraph.growth(peak_stats=start_objs)])\n return ret\n\n\n def new_objects(fn):\n \"\"\"\n A decorator that prints types and numbers of new objects left over after calling fn.\n\n Parameters\n ----------\n fn : function\n The function being checked for possible memory leaks.\n\n Returns\n -------\n function\n A wrapper for fn that reports possible memory leaks.\n \"\"\"\n @functools.wraps(fn)\n def wrapper(*args, **kwargs):\n lst = []\n ret = get_new_objects(lst, fn, *args, **kwargs)\n for obj, delta_objs in lst:\n print(str(fn), \"added %s %+d\" % (obj, delta_objs))\n return ret\n return wrapper\n\n\n def check_iter_leaks(niter, func, *args, **kwargs):\n \"\"\"\n Run func niter times and collect info on new objects left over after each iteration.\n\n Parameters\n ----------\n niter : int\n Number of times to run func.\n func : function\n A function that takes no arguments.\n *args : tuple\n Positional args passed to func.\n **kwargs : dict\n Named args to be passed to func.\n\n Returns\n -------\n set\n set of tuples of the form (typename, count)\n \"\"\"\n if niter < 2:\n raise RuntimeError(\"Must run the function at least twice, but niter={}\".format(niter))\n iters = []\n gc.collect()\n start_objs = objgraph.typestats()\n if 'frame' in start_objs:\n start_objs['frame'] += 1\n start_objs['function'] += 1\n start_objs['builtin_function_or_method'] += 1\n start_objs['cell'] += 1\n for i in range(niter):\n func(*args, **kwargs)\n gc.collect()\n lst = [(str(o), delta) for o, _, delta in objgraph.growth(peak_stats=start_objs)]\n iters.append(lst)\n\n set1 = set(iters[-2])\n set2 = set(iters[-1])\n\n return set2 - set1\n\n\n def list_iter_leaks(leakset, out=sys.stdout):\n \"\"\"\n Print any new objects left over after each call to the specified function.\n\n Parameters\n ----------\n leakset : set of tuples of the form (objtype, count)\n Output of check_iter_leaks.\n out : file-like\n Output stream.\n \"\"\"\n if leakset:\n print(\"\\nPossible leaked objects:\", file=out)\n for objstr, deltas in leakset:\n print(objstr, deltas, file=out)\n print(file=out)\n else:\n print(\"\\nNo possible memory leaks detected.\\n\", file=out)\n\nexcept ImportError:\n objgraph = None\n def get_new_objects(*args, **kwargs):\n raise RuntimeError(\"The 'get_new_objects' function requires the 'objgraph' package. \"\n \"You can install it using 'pip install objgraph'.\")\n\n def new_objects(*args, **kwargs):\n raise RuntimeError(\"The 'new_objects' decorator requires the 'objgraph' package. You can \"\n \"install it using 'pip install objgraph'.\")\n\n def check_iter_leaks(*args, **kwargs):\n raise RuntimeError(\"The 'check_iter_leaks' function requires the 'objgraph' package. \"\n \"You can install it using 'pip install objgraph'.\")\n\n def list_iter_leaks(*args, **kwargs):\n raise RuntimeError(\"The 'list_iter_leaks' function requires the 'objgraph' package. \"\n \"You can install it using 'pip install objgraph'.\")\n\ndef plot_mem(mems, fname=None):\n \"\"\"\n Plot memory usage.\n\n Parameters\n ----------\n mems : iter of float\n Iterator containing memory usage values.\n fname : str (optional)\n If specified, save the plot to this file.\n \"\"\"\n import matplotlib.pyplot as plt\n fig, ax = plt.subplots()\n mems = list(mems)\n ax.plot(list(range(len(mems))), mems)\n ax.set(xlabel='Iterations', ylabel='Memory (MB)', title='Memory useage per iteration')\n ax.grid()\n if fname is not None:\n fig.savefig(fname)\n plt.show()\n\n",
"\nimport os\nimport sys\nimport shutil\nimport tempfile\nimport itertools\n\nimport unittest\nimport numpy as np\nimport math\n\nfrom io import StringIO\n\nfrom distutils.version import LooseVersion\nfrom numpy.testing import assert_array_almost_equal, assert_almost_equal\nimport scipy\ntry:\n from scipy.sparse import load_npz\nexcept ImportError:\n load_npz = None\n\nimport openmdao.api as om\nfrom openmdao.utils.assert_utils import assert_near_equal, assert_warning\nfrom openmdao.utils.general_utils import set_pyoptsparse_opt\nfrom openmdao.utils.coloring import Coloring, _compute_coloring, array_viz, compute_total_coloring\nfrom openmdao.utils.mpi import MPI\nfrom openmdao.utils.testing_utils import use_tempdirs\nfrom openmdao.test_suite.tot_jac_builder import TotJacBuilder\nfrom openmdao.utils.general_utils import run_driver\n\nimport openmdao.test_suite\n\ntry:\n from parameterized import parameterized\nexcept ImportError:\n from openmdao.utils.assert_utils import SkipParameterized as parameterized\n\ntry:\n from openmdao.vectors.petsc_vector import PETScVector\nexcept ImportError:\n PETScVector = None\n\n\n# check that pyoptsparse is installed\nOPT, OPTIMIZER = set_pyoptsparse_opt('SNOPT')\nif OPTIMIZER:\n from openmdao.drivers.pyoptsparse_driver import pyOptSparseDriver\n\n\nclass CounterGroup(om.Group):\n def __init__(self, *args, **kwargs):\n self._solve_count = 0\n self._solve_nl_count = 0\n self._apply_nl_count = 0\n super().__init__(*args, **kwargs)\n\n def _solve_linear(self, *args, **kwargs):\n super()._solve_linear(*args, **kwargs)\n self._solve_count += 1\n\n def _solve_nonlinear(self, *args, **kwargs):\n super()._solve_nonlinear(*args, **kwargs)\n self._solve_nl_count += 1\n\n def _apply_nonlinear(self, *args, **kwargs):\n super()._apply_nonlinear(*args, **kwargs)\n self._apply_nl_count += 1\n\n\n# note: size must be an even number\nSIZE = 10\n\n\nclass DynPartialsComp(om.ExplicitComponent):\n def __init__(self, size):\n super().__init__()\n self.size = size\n self.num_computes = 0\n\n def setup(self):\n self.add_input('y', np.ones(self.size))\n self.add_input('x', np.ones(self.size))\n self.add_output('g', np.ones(self.size))\n\n # turn on dynamic partial coloring\n self.declare_coloring(wrt='*', method='cs', perturb_size=1e-5, num_full_jacs=2, tol=1e-20,\n orders=20)\n\n def compute(self, inputs, outputs):\n outputs['g'] = np.arctan(inputs['y'] / inputs['x'])\n self.num_computes += 1\n\n\n\ndef run_opt(driver_class, mode, assemble_type=None, color_info=None, derivs=True,\n recorder=None, has_lin_constraint=True, has_diag_partials=True, partial_coloring=False,\n use_vois=True, auto_ivc=False, **options):\n\n p = om.Problem(model=CounterGroup())\n\n if assemble_type is not None:\n p.model.linear_solver = om.DirectSolver(assemble_jac=True)\n p.model.options['assembled_jac_type'] = assemble_type\n\n\n # the following were randomly generated using np.random.random(10)*2-1 to randomly\n # disperse them within a unit circle centered at the origin.\n x_init = np.array([ 0.55994437, -0.95923447, 0.21798656, -0.02158783, 0.62183717,\n 0.04007379, 0.46044942, -0.10129622, 0.27720413, -0.37107886])\n y_init = np.array([ 0.52577864, 0.30894559, 0.8420792 , 0.35039912, -0.67290778,\n -0.86236787, -0.97500023, 0.47739414, 0.51174103, 0.10052582])\n r_init = .7\n\n if auto_ivc:\n p.model.set_input_defaults('x', x_init)\n p.model.set_input_defaults('y', y_init)\n p.model.set_input_defaults('r', r_init)\n\n else:\n indeps = p.model.add_subsystem('indeps', om.IndepVarComp(), promotes_outputs=['*'])\n indeps.add_output('x', x_init)\n indeps.add_output('y', y_init)\n indeps.add_output('r', r_init)\n\n if partial_coloring:\n arctan_yox = DynPartialsComp(SIZE)\n else:\n arctan_yox = om.ExecComp('g=arctan(y/x)', has_diag_partials=has_diag_partials,\n g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE))\n\n p.model.add_subsystem('arctan_yox', arctan_yox)\n\n p.model.add_subsystem('circle', om.ExecComp('area=pi*r**2'))\n\n p.model.add_subsystem('r_con', om.ExecComp('g=x**2 + y**2 - r', has_diag_partials=has_diag_partials,\n g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE)))\n\n thetas = np.linspace(0, np.pi/4, SIZE)\n p.model.add_subsystem('theta_con', om.ExecComp('g = x - theta', has_diag_partials=has_diag_partials,\n g=np.ones(SIZE), x=np.ones(SIZE),\n theta=thetas))\n p.model.add_subsystem('delta_theta_con', om.ExecComp('g = even - odd', has_diag_partials=has_diag_partials,\n g=np.ones(SIZE//2), even=np.ones(SIZE//2),\n odd=np.ones(SIZE//2)))\n\n p.model.add_subsystem('l_conx', om.ExecComp('g=x-1', has_diag_partials=has_diag_partials, g=np.ones(SIZE), x=np.ones(SIZE)))\n\n IND = np.arange(SIZE, dtype=int)\n ODD_IND = IND[1::2] # all odd indices\n EVEN_IND = IND[0::2] # all even indices\n\n if auto_ivc:\n p.model.promotes('circle', inputs=['r'])\n p.model.promotes('r_con', inputs=['r', 'x', 'y'])\n p.model.promotes('l_conx', inputs=['x'])\n p.model.promotes('arctan_yox', inputs=['x', 'y'])\n else:\n p.model.connect('r', ('circle.r', 'r_con.r'))\n p.model.connect('x', ['r_con.x', 'arctan_yox.x', 'l_conx.x'])\n p.model.connect('y', ['r_con.y', 'arctan_yox.y'])\n\n p.model.connect('arctan_yox.g', 'theta_con.x')\n p.model.connect('arctan_yox.g', 'delta_theta_con.even', src_indices=EVEN_IND)\n p.model.connect('arctan_yox.g', 'delta_theta_con.odd', src_indices=ODD_IND)\n\n p.driver = driver_class()\n if 'method' in options:\n p.model.approx_totals(method=options['method'])\n del options['method']\n\n if 'dynamic_total_coloring' in options:\n p.driver.declare_coloring(tol=1e-15)\n del options['dynamic_total_coloring']\n\n p.driver.options['debug_print'] = ['totals']\n p.driver.options.update(options)\n\n if use_vois:\n p.model.add_design_var('x')\n p.model.add_design_var('y')\n p.model.add_design_var('r', lower=.5, upper=10)\n\n # nonlinear constraints\n p.model.add_constraint('r_con.g', equals=0)\n\n p.model.add_constraint('theta_con.g', lower=-1e-5, upper=1e-5, indices=EVEN_IND)\n p.model.add_constraint('delta_theta_con.g', lower=-1e-5, upper=1e-5)\n\n # this constrains x[0] to be 1 (see definition of l_conx)\n p.model.add_constraint('l_conx.g', equals=0, linear=False, indices=[0,])\n\n # linear constraint (if has_lin_constraint is set)\n p.model.add_constraint('y', equals=0, indices=[0,], linear=has_lin_constraint)\n\n p.model.add_objective('circle.area', ref=-1)\n\n # setup coloring\n if color_info is not None:\n p.driver.use_fixed_coloring(color_info)\n\n if recorder:\n p.driver.add_recorder(recorder)\n\n p.setup(mode=mode, derivatives=derivs)\n if use_vois:\n p.run_driver()\n else:\n p.run_model()\n\n return p\n\n\n@use_tempdirs\nclass SimulColoringPyoptSparseTestCase(unittest.TestCase):\n\n @unittest.skipUnless(OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\n def test_dynamic_total_coloring_snopt_auto(self):\n # first, run w/o coloring\n p = run_opt(pyOptSparseDriver, 'auto', optimizer='SNOPT', print_results=False)\n p_color = run_opt(pyOptSparseDriver, 'auto', optimizer='SNOPT', print_results=False,\n dynamic_total_coloring=True)\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n # - coloring saves 16 solves per driver iter (5 vs 21)\n # - initial solve for linear constraints takes 21 in both cases (only done once)\n # - dynamic case does 3 full compute_totals to compute coloring, which adds 21 * 3 solves\n # - (total_solves - N) / (solves_per_iter) should be equal between the two cases,\n # - where N is 21 for the uncolored case and 21 * 4 for the dynamic colored case.\n self.assertEqual((p.model._solve_count - 21) / 21,\n (p_color.model._solve_count - 21 * 4) / 5)\n\n @unittest.skipUnless(OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\n def test_dynamic_total_coloring_snopt_auto_autoivc(self):\n # first, run w/o coloring\n p = run_opt(pyOptSparseDriver, 'auto', optimizer='SNOPT', print_results=False,\n auto_ivc=True)\n p_color = run_opt(pyOptSparseDriver, 'auto', optimizer='SNOPT', print_results=False,\n dynamic_total_coloring=True, auto_ivc=True)\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n # - coloring saves 16 solves per driver iter (5 vs 21)\n # - initial solve for linear constraints takes 21 in both cases (only done once)\n # - dynamic case does 3 full compute_totals to compute coloring, which adds 21 * 3 solves\n # - (total_solves - N) / (solves_per_iter) should be equal between the two cases,\n # - where N is 21 for the uncolored case and 21 * 4 for the dynamic colored case.\n self.assertEqual((p.model._solve_count - 21) / 21,\n (p_color.model._solve_count - 21 * 4) / 5)\n\n @unittest.skipUnless(OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\n def test_dynamic_total_coloring_snopt_auto_dyn_partials(self):\n # first, run w/o coloring\n p = run_opt(pyOptSparseDriver, 'auto', optimizer='SNOPT', print_results=False)\n p_color = run_opt(pyOptSparseDriver, 'auto', optimizer='SNOPT', print_results=False,\n dynamic_total_coloring=True, partial_coloring=True)\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n # - coloring saves 16 solves per driver iter (5 vs 21)\n # - initial solve for linear constraints takes 21 in both cases (only done once)\n # - dynamic case does 3 full compute_totals to compute coloring, which adds 21 * 3 solves\n # - (total_solves - N) / (solves_per_iter) should be equal between the two cases,\n # - where N is 21 for the uncolored case and 21 * 4 for the dynamic colored case.\n self.assertEqual((p.model._solve_count - 21) / 21,\n (p_color.model._solve_count - 21 * 4) / 5)\n\n partial_coloring = p_color.model._get_subsystem('arctan_yox')._coloring_info['coloring']\n expected = [\n \"self.declare_partials(of='g', wrt='y', rows=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], cols=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\",\n \"self.declare_partials(of='g', wrt='x', rows=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], cols=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\"\n ]\n decl_partials_calls = partial_coloring.get_declare_partials_calls().strip()\n for i, d in enumerate(decl_partials_calls.split('\\n')):\n self.assertEqual(d.strip(), expected[i])\n\n fwd_solves, rev_solves = p_color.driver._coloring_info['coloring'].get_row_var_coloring('delta_theta_con.g')\n self.assertEqual(fwd_solves, 4)\n self.assertEqual(rev_solves, 0)\n\n @unittest.skipUnless(OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\n def test_dynamic_total_coloring_snopt_auto_dyn_partials_assembled_jac(self):\n # first, run w/o coloring\n p = run_opt(pyOptSparseDriver, 'auto', assemble_type='csc', optimizer='SNOPT', print_results=False)\n p_color = run_opt(pyOptSparseDriver, 'auto', assemble_type='csc', optimizer='SNOPT', print_results=False,\n dynamic_total_coloring=True, partial_coloring=True)\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n # - coloring saves 16 solves per driver iter (5 vs 21)\n # - initial solve for linear constraints takes 21 in both cases (only done once)\n # - dynamic case does 3 full compute_totals to compute coloring, which adds 21 * 3 solves\n # - (total_solves - N) / (solves_per_iter) should be equal between the two cases,\n # - where N is 21 for the uncolored case and 21 * 4 for the dynamic colored case.\n\n # This has been changed to greater or equal to 28 iterations. This change arose when updating\n # to pyOptSparse v2.1.0 and SNOPT 7.7\n self.assertGreaterEqual((p.model._solve_count - 21) / 21,\n (p_color.model._solve_count - 21 * 4) / 5)\n\n @unittest.skipUnless(OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\n def test_dynamic_total_coloring_snopt_auto_assembled(self):\n # first, run w/o coloring\n p = run_opt(pyOptSparseDriver, 'auto', assemble_type='dense', optimizer='SNOPT', print_results=False)\n p_color = run_opt(pyOptSparseDriver, 'auto', assemble_type='dense', optimizer='SNOPT', print_results=False,\n dynamic_total_coloring=True)\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n # - coloring saves 16 solves per driver iter (5 vs 21)\n # - initial solve for linear constraints takes 21 in both cases (only done once)\n # - dynamic case does 3 full compute_totals to compute coloring, which adds 21 * 3 solves\n # - (total_solves - N) / (solves_per_iter) should be equal between the two cases,\n # - where N is 21 for the uncolored case and 21 * 4 for the dynamic colored case.\n self.assertEqual((p.model._solve_count - 21) / 21,\n (p_color.model._solve_count - 21 * 4) / 5)\n\n @unittest.skipUnless(OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\n def test_dynamic_fwd_simul_coloring_snopt_approx_cs(self):\n # first, run w/o coloring\n p = run_opt(pyOptSparseDriver, 'fwd', optimizer='SNOPT', print_results=False, has_lin_constraint=False, method='cs')\n p_color = run_opt(pyOptSparseDriver, 'fwd', optimizer='SNOPT', has_lin_constraint=False,\n has_diag_partials=True, print_results=False,\n dynamic_total_coloring=True, method='cs')\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n\n # - fwd coloring saves 16 nonlinear solves per driver iter (6 vs 22).\n # - dynamic coloring takes 66 nonlinear solves (22 each for 3 full jacs)\n # - (total_solves - 2) / (solves_per_iter) should be equal to\n # (total_color_solves - 2 - dyn_solves) / color_solves_per_iter\n self.assertEqual((p.model._solve_nl_count - 2) / 22,\n (p_color.model._solve_nl_count - 2 - 66) / 6)\n\n @unittest.skipUnless(OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\n def test_dynamic_fwd_simul_coloring_snopt_approx_fd(self):\n # first, run w/o coloring\n p = run_opt(pyOptSparseDriver, 'fwd', optimizer='SNOPT', print_results=False, has_lin_constraint=False, method='cs')\n p_color = run_opt(pyOptSparseDriver, 'fwd', optimizer='SNOPT', has_lin_constraint=False,\n has_diag_partials=True, print_results=False,\n dynamic_total_coloring=True, method='fd')\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n\n # - fwd coloring saves 16 nonlinear solves per driver iter (6 vs 22).\n # - dynamic coloring takes 66 nonlinear solves (22 each for 3 full jacs)\n # - (total_solves - 2) / (solves_per_iter) should be equal to\n # (total_color_solves - 2 - dyn_solves) / color_solves_per_iter\n self.assertEqual((p.model._solve_nl_count - 2) / 22,\n (p_color.model._solve_nl_count - 2 - 66) / 6)\n\n def test_size_zero_array_in_component(self):\n class DynamicPartialsComp(om.ExplicitComponent):\n def __init__(self, size):\n super().__init__()\n self.size = size\n self.num_computes = 0\n\n def setup(self):\n self.add_input('y', np.ones(self.size))\n self.add_input('x', np.ones(self.size))\n self.add_output('g', np.ones(self.size))\n\n self.declare_partials('*', '*', method='cs')\n\n # turn on dynamic partial coloring\n self.declare_coloring(wrt='*', method='cs', perturb_size=1e-5, num_full_jacs=2, tol=1e-20,\n orders=20, show_summary=True, show_sparsity=True)\n\n def compute(self, inputs, outputs):\n outputs['g'] = np.arctan(inputs['y'] / inputs['x'])\n self.num_computes += 1\n\n SIZE = 0\n p = om.Problem()\n\n arctan_yox = p.model.add_subsystem('arctan_yox', DynamicPartialsComp(SIZE))\n\n p.driver = om.ScipyOptimizeDriver()\n p.driver.options['optimizer'] = 'SLSQP'\n p.driver.options['disp'] = False\n\n p.driver.declare_coloring(show_summary=True, show_sparsity=True)\n\n p.setup(mode='fwd')\n\n with self.assertRaises(Exception) as context:\n p.run_driver()\n self.assertEqual(str(context.exception),\n \"'arctan_yox' <class DynamicPartialsComp>: 'arctan_yox.g' is an array of size 0\")\n\n def test_size_zero_array_declare_partials(self):\n class DynamicPartialsComp(om.ExplicitComponent):\n def __init__(self, size):\n super().__init__()\n self.size = size\n self.num_computes = 0\n\n def setup(self):\n self.add_input('y', np.ones(self.size))\n self.add_input('x', np.ones(self.size))\n self.add_output('g', np.ones(self.size))\n self.add_output('r', np.ones(1))\n\n self.declare_partials('r', 'y', method='cs')\n\n # turn on dynamic partial coloring\n self.declare_coloring(wrt='*', method='cs', perturb_size=1e-5, num_full_jacs=2, tol=1e-20,\n orders=20, show_summary=True, show_sparsity=True)\n\n def compute(self, inputs, outputs):\n outputs['g'] = np.arctan(inputs['y'] / inputs['x'])\n self.num_computes += 1\n\n SIZE = 0\n p = om.Problem()\n\n arctan_yox = p.model.add_subsystem('arctan_yox', DynamicPartialsComp(SIZE))\n\n p.driver = om.ScipyOptimizeDriver()\n p.driver.options['optimizer'] = 'SLSQP'\n p.driver.options['disp'] = False\n\n p.driver.declare_coloring(show_summary=True, show_sparsity=True)\n\n p.setup(mode='fwd')\n\n with self.assertRaises(Exception) as context:\n p.run_driver()\n self.assertEqual(str(context.exception),\n \"'arctan_yox' <class DynamicPartialsComp>: 'arctan_yox.y' is an array of size 0\")\n\n\n def test_dynamic_total_coloring_pyoptsparse_slsqp_auto(self):\n try:\n from pyoptsparse import OPT\n except ImportError:\n raise unittest.SkipTest(\"This test requires pyoptsparse.\")\n\n try:\n OPT('SLSQP')\n except:\n raise unittest.SkipTest(\"This test requires pyoptsparse SLSQP.\")\n\n p_color = run_opt(pyOptSparseDriver, 'auto', optimizer='SLSQP', print_results=False,\n dynamic_total_coloring=True)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n # run w/o coloring\n p = run_opt(pyOptSparseDriver, 'auto', optimizer='SLSQP', print_results=False)\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n\n # - coloring saves 16 solves per driver iter (5 vs 21)\n # - initial solve for linear constraints takes 21 in both cases (only done once)\n # - dynamic case does 3 full compute_totals to compute coloring, which adds 21 * 3 solves\n # - (total_solves - N) / (solves_per_iter) should be equal between the two cases,\n # - where N is 21 for the uncolored case and 21 * 4 for the dynamic colored case.\n self.assertEqual((p.model._solve_count - 21) / 21,\n (p_color.model._solve_count - 21 * 4) / 5)\n\n # test __repr__\n rep = repr(p_color.driver._coloring_info['coloring'])\n self.assertEqual(rep.replace('L', ''), 'Coloring (direction: fwd, ncolors: 5, shape: (22, 21), pct nonzero: 13.42, tol: 1e-15')\n\n @unittest.skipUnless(OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\n def test_print_options_total_with_coloring_fwd(self):\n # first, run w/o coloring\n p = run_opt(pyOptSparseDriver, 'fwd', optimizer='SNOPT', print_results=False)\n p_color = run_opt(pyOptSparseDriver, 'fwd', optimizer='SNOPT', print_results=False,\n dynamic_total_coloring=True)\n\n failed, output = run_driver(p_color)\n\n self.assertFalse(failed, \"Optimization failed.\")\n\n self.assertTrue('In mode: fwd, Solving variable(s) using simul coloring:' in output)\n self.assertTrue(\"('indeps.y', [1, 3, 5, 7, 9])\" in output)\n self.assertTrue('Elapsed Time:' in output)\n\n @unittest.skipUnless(OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\n def test_print_options_total_with_coloring_rev(self):\n # first, run w/o coloring\n p = run_opt(pyOptSparseDriver, 'rev', optimizer='SNOPT', print_results=False)\n p_color = run_opt(pyOptSparseDriver, 'rev', optimizer='SNOPT', print_results=False,\n dynamic_total_coloring=True)\n\n failed, output = run_driver(p_color)\n\n self.assertFalse(failed, \"Optimization failed.\")\n\n self.assertTrue('In mode: rev, Solving variable(s) using simul coloring:' in output)\n self.assertTrue(\"('r_con.g', [0])\" in output)\n self.assertTrue('Elapsed Time:' in output)\n\n@use_tempdirs\[email protected](OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\nclass SimulColoringRecordingTestCase(unittest.TestCase):\n\n def test_recording(self):\n # coloring involves an underlying call to run_model (and final_setup),\n # this verifies that it is handled properly by the recording setup logic\n recorder = om.SqliteRecorder('cases.sql')\n\n p = run_opt(pyOptSparseDriver, 'auto', assemble_type='csc', optimizer='SNOPT',\n dynamic_total_coloring=True, print_results=False, recorder=recorder)\n\n cr = om.CaseReader('cases.sql')\n\n self.assertEqual(cr.list_cases(out_stream=None), ['rank0:pyOptSparse_SNOPT|%d' % i for i in range(p.driver.iter_count)])\n\n\n@use_tempdirs\nclass SimulColoringPyoptSparseRevTestCase(unittest.TestCase):\n \"\"\"Reverse coloring tests for pyoptsparse.\"\"\"\n\n @unittest.skipUnless(OPTIMIZER == 'SNOPT', \"This test requires SNOPT.\")\n def test_dynamic_rev_simul_coloring_snopt(self):\n # first, run w/o coloring\n p = run_opt(pyOptSparseDriver, 'rev', optimizer='SNOPT', print_results=False)\n p_color = run_opt(pyOptSparseDriver, 'rev', optimizer='SNOPT', print_results=False,\n dynamic_total_coloring=True)\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n # - rev coloring saves 11 solves per driver iter (11 vs 22)\n # - initial solve for linear constraints takes 1 in both cases (only done once)\n # - dynamic case does 3 full compute_totals to compute coloring, which adds 22 * 3 solves\n # - (total_solves - N) / (solves_per_iter) should be equal between the two cases,\n # - where N is 1 for the uncolored case and 22 * 3 + 1 for the dynamic colored case.\n self.assertEqual((p.model._solve_count - 1) / 22,\n (p_color.model._solve_count - 1 - 22 * 3) / 11)\n\n # improve coverage of coloring.py\n coloring = p_color.driver._coloring_info['coloring']\n coloring.display_txt()\n with open(os.devnull, 'w') as f:\n array_viz(coloring.get_dense_sparsity(), prob=p_color, stream=f)\n array_viz(coloring.get_dense_sparsity(), stream=f)\n\n def test_dynamic_rev_simul_coloring_pyoptsparse_slsqp(self):\n try:\n from pyoptsparse import OPT\n except ImportError:\n raise unittest.SkipTest(\"This test requires pyoptsparse.\")\n\n try:\n OPT('SLSQP')\n except:\n raise unittest.SkipTest(\"This test requires pyoptsparse SLSQP.\")\n\n p_color = run_opt(pyOptSparseDriver, 'rev', optimizer='SLSQP', print_results=False,\n dynamic_total_coloring=True)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n # Tests a bug where coloring ran the model when not needed.\n self.assertEqual(p_color.model.iter_count, 9)\n\n # run w/o coloring\n p = run_opt(pyOptSparseDriver, 'rev', optimizer='SLSQP', print_results=False)\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n\n # - coloring saves 11 solves per driver iter (11 vs 22)\n # - initial solve for linear constraints takes 1 in both cases (only done once)\n # - dynamic case does 3 full compute_totals to compute coloring, which adds 22 * 3 solves\n # - (total_solves - N) / (solves_per_iter) should be equal between the two cases,\n # - where N is 1 for the uncolored case and 22 * 3 + 1 for the dynamic colored case.\n self.assertEqual((p.model._solve_count - 1) / 22,\n (p_color.model._solve_count - 1 - 22 * 3) / 11)\n\n\n@use_tempdirs\nclass SimulColoringScipyTestCase(unittest.TestCase):\n\n def test_bad_mode(self):\n p_color_fwd = run_opt(om.ScipyOptimizeDriver, 'fwd', optimizer='SLSQP', disp=False, dynamic_total_coloring=True)\n coloring = p_color_fwd.driver._coloring_info['coloring']\n\n with self.assertRaises(Exception) as context:\n p_color = run_opt(om.ScipyOptimizeDriver, 'rev', color_info=coloring, optimizer='SLSQP', disp=False)\n self.assertEqual(str(context.exception),\n \"Simultaneous coloring does forward solves but mode has been set to 'rev'\")\n\n def test_dynamic_total_coloring_auto(self):\n\n # first, run w/o coloring\n p = run_opt(om.ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False)\n p_color = run_opt(om.ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False, dynamic_total_coloring=True)\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n # - bidirectional coloring saves 16 solves per driver iter (5 vs 21)\n # - initial solve for linear constraints takes 21 in both cases (only done once)\n # - dynamic case does 3 full compute_totals to compute coloring, which adds 21 * 3 solves\n # - (total_solves - N) / (solves_per_iter) should be equal between the two cases,\n # - where N is 21 for the uncolored case and 21 * 4 for the dynamic colored case.\n self.assertEqual((p.model._solve_count - 21) / 21,\n (p_color.model._solve_count - 21 * 4) / 5)\n\n def test_problem_total_coloring_auto(self):\n\n p = run_opt(om.ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False, use_vois=False)\n coloring = compute_total_coloring(p,\n of=['r_con.g', 'theta_con.g', 'delta_theta_con.g',\n 'l_conx.g', 'y', 'circle.area'],\n wrt=['x', 'y', 'r'])\n self.assertEqual(coloring.total_solves(), 5)\n\n def test_problem_total_coloring_auto_mixed_vois(self):\n\n p = run_opt(om.ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False,)\n coloring = compute_total_coloring(p,\n of=['r_con.g', 'theta_con.g', 'delta_theta_con.g',\n 'l_conx.g', 'y', 'circle.area'],\n wrt=['x', 'y', 'r'])\n self.assertEqual(coloring.total_solves(), 5)\n coloring.display_txt() # leave this in because at one point it caused an exception\n\n def test_simul_coloring_example(self):\n\n import numpy as np\n import openmdao.api as om\n\n SIZE = 10\n\n p = om.Problem()\n\n p.model.add_subsystem('arctan_yox', om.ExecComp('g=arctan(y/x)', has_diag_partials=True,\n g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE)),\n promotes_inputs=['x', 'y'])\n\n p.model.add_subsystem('circle', om.ExecComp('area=pi*r**2'), promotes_inputs=['r'])\n\n p.model.add_subsystem('r_con', om.ExecComp('g=x**2 + y**2 - r', has_diag_partials=True,\n g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE)),\n promotes_inputs=['r', 'x', 'y'])\n\n thetas = np.linspace(0, np.pi/4, SIZE)\n p.model.add_subsystem('theta_con', om.ExecComp('g = x - theta', has_diag_partials=True,\n g=np.ones(SIZE), x=np.ones(SIZE),\n theta=thetas))\n p.model.add_subsystem('delta_theta_con', om.ExecComp('g = even - odd', has_diag_partials=True,\n g=np.ones(SIZE//2), even=np.ones(SIZE//2),\n odd=np.ones(SIZE//2)))\n\n p.model.add_subsystem('l_conx', om.ExecComp('g=x-1', has_diag_partials=True, g=np.ones(SIZE), x=np.ones(SIZE)),\n promotes_inputs=['x'])\n\n IND = np.arange(SIZE, dtype=int)\n ODD_IND = IND[1::2] # all odd indices\n EVEN_IND = IND[0::2] # all even indices\n\n p.model.connect('arctan_yox.g', 'theta_con.x')\n p.model.connect('arctan_yox.g', 'delta_theta_con.even', src_indices=EVEN_IND)\n p.model.connect('arctan_yox.g', 'delta_theta_con.odd', src_indices=ODD_IND)\n\n p.driver = om.ScipyOptimizeDriver()\n p.driver.options['optimizer'] = 'SLSQP'\n p.driver.options['disp'] = False\n\n # set up dynamic total coloring here\n p.driver.declare_coloring()\n\n p.model.add_design_var('x')\n p.model.add_design_var('y')\n p.model.add_design_var('r', lower=.5, upper=10)\n\n # nonlinear constraints\n p.model.add_constraint('r_con.g', equals=0)\n\n p.model.add_constraint('theta_con.g', lower=-1e-5, upper=1e-5, indices=EVEN_IND)\n p.model.add_constraint('delta_theta_con.g', lower=-1e-5, upper=1e-5)\n\n # this constrains x[0] to be 1 (see definition of l_conx)\n p.model.add_constraint('l_conx.g', equals=0, linear=False, indices=[0,])\n\n # linear constraint\n p.model.add_constraint('y', equals=0, indices=[0,], linear=True)\n\n p.model.add_objective('circle.area', ref=-1)\n\n p.setup(mode='fwd')\n\n # the following were randomly generated using np.random.random(10)*2-1 to randomly\n # disperse them within a unit circle centered at the origin.\n p.set_val('x', np.array([ 0.55994437, -0.95923447, 0.21798656, -0.02158783, 0.62183717,\n 0.04007379, 0.46044942, -0.10129622, 0.27720413, -0.37107886]))\n p.set_val('y', np.array([ 0.52577864, 0.30894559, 0.8420792 , 0.35039912, -0.67290778,\n -0.86236787, -0.97500023, 0.47739414, 0.51174103, 0.10052582]))\n p.set_val('r', .7)\n\n p.run_driver()\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n\n def test_total_and_partial_coloring_example(self):\n\n import numpy as np\n import openmdao.api as om\n\n class DynamicPartialsComp(om.ExplicitComponent):\n def __init__(self, size):\n super().__init__()\n self.size = size\n self.num_computes = 0\n\n def setup(self):\n self.add_input('y', np.ones(self.size))\n self.add_input('x', np.ones(self.size))\n self.add_output('g', np.ones(self.size))\n\n self.declare_partials('*', '*', method='cs')\n\n # turn on dynamic partial coloring\n self.declare_coloring(wrt='*', method='cs', perturb_size=1e-5, num_full_jacs=2, tol=1e-20,\n orders=20, show_summary=True, show_sparsity=True)\n\n def compute(self, inputs, outputs):\n outputs['g'] = np.arctan(inputs['y'] / inputs['x'])\n self.num_computes += 1\n\n\n SIZE = 10\n\n p = om.Problem()\n model = p.model\n\n ########################################################################\n # DynamicPartialsComp is set up to do dynamic partial coloring\n arctan_yox = model.add_subsystem('arctan_yox', DynamicPartialsComp(SIZE),\n promotes_inputs=['x', 'y'])\n ########################################################################\n\n model.add_subsystem('circle', om.ExecComp('area=pi*r**2'),\n promotes_inputs=['r'])\n\n model.add_subsystem('r_con', om.ExecComp('g=x**2 + y**2 - r', has_diag_partials=True,\n g=np.ones(SIZE), x=np.ones(SIZE), y=np.ones(SIZE)),\n promotes_inputs=['x', 'y', 'r'])\n\n thetas = np.linspace(0, np.pi/4, SIZE)\n model.add_subsystem('theta_con', om.ExecComp('g = x - theta', has_diag_partials=True,\n g=np.ones(SIZE), x=np.ones(SIZE),\n theta=thetas))\n model.add_subsystem('delta_theta_con', om.ExecComp('g = even - odd', has_diag_partials=True,\n g=np.ones(SIZE//2), even=np.ones(SIZE//2),\n odd=np.ones(SIZE//2)))\n\n model.add_subsystem('l_conx', om.ExecComp('g=x-1', has_diag_partials=True,\n g=np.ones(SIZE), x=np.ones(SIZE)),\n promotes_inputs=['x'])\n\n IND = np.arange(SIZE, dtype=int)\n ODD_IND = IND[1::2] # all odd indices\n EVEN_IND = IND[0::2] # all even indices\n\n model.connect('arctan_yox.g', 'theta_con.x')\n model.connect('arctan_yox.g', 'delta_theta_con.even', src_indices=EVEN_IND)\n model.connect('arctan_yox.g', 'delta_theta_con.odd', src_indices=ODD_IND)\n\n p.driver = om.ScipyOptimizeDriver()\n p.driver.options['optimizer'] = 'SLSQP'\n p.driver.options['disp'] = False\n\n #####################################\n # set up dynamic total coloring here\n p.driver.declare_coloring(show_summary=True, show_sparsity=True)\n #####################################\n\n model.add_design_var('x')\n model.add_design_var('y')\n model.add_design_var('r', lower=.5, upper=10)\n\n # nonlinear constraints\n model.add_constraint('r_con.g', equals=0)\n\n model.add_constraint('theta_con.g', lower=-1e-5, upper=1e-5, indices=EVEN_IND)\n model.add_constraint('delta_theta_con.g', lower=-1e-5, upper=1e-5)\n\n # this constrains x[0] to be 1 (see definition of l_conx)\n model.add_constraint('l_conx.g', equals=0, linear=False, indices=[0,])\n\n # linear constraint\n model.add_constraint('y', equals=0, indices=[0,], linear=True)\n\n model.add_objective('circle.area', ref=-1)\n\n p.setup(mode='fwd')\n\n # the following were randomly generated using np.random.random(10)*2-1 to randomly\n # disperse them within a unit circle centered at the origin.\n p.set_val('x', np.array([ 0.55994437, -0.95923447, 0.21798656, -0.02158783, 0.62183717,\n 0.04007379, 0.46044942, -0.10129622, 0.27720413, -0.37107886]))\n p.set_val('y', np.array([ 0.52577864, 0.30894559, 0.8420792 , 0.35039912, -0.67290778,\n -0.86236787, -0.97500023, 0.47739414, 0.51174103, 0.10052582]))\n p.set_val('r', .7)\n\n # coloring info will be displayed during run_driver. The number of colors in the\n # partial coloring of arctan_yox should be 2 and the number of colors in the\n # total coloring should be 5.\n p.run_driver()\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n\n # Let's see how many calls to compute we need to determine partials for arctan_yox.\n # The partial derivatives are all diagonal, so we should be able to cover them using\n # only 2 colors.\n start_calls = arctan_yox.num_computes\n arctan_yox.run_linearize()\n self.assertEqual(arctan_yox.num_computes - start_calls, 2)\n\n\n@use_tempdirs\nclass SimulColoringRevScipyTestCase(unittest.TestCase):\n \"\"\"Rev mode coloring tests.\"\"\"\n\n def test_summary(self):\n p_color = run_opt(om.ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False, dynamic_total_coloring=True)\n coloring = p_color.driver._coloring_info['coloring']\n save_out = sys.stdout\n sys.stdout = StringIO()\n try:\n coloring.summary()\n summary = sys.stdout.getvalue()\n finally:\n sys.stdout = save_out\n\n self.assertTrue('Jacobian shape: (22, 21) (13.42% nonzero)' in summary)\n self.assertTrue('FWD solves: 5 REV solves: 0' in summary)\n self.assertTrue('Total colors vs. total size: 5 vs 21 (76.2% improvement)' in summary)\n self.assertTrue('Time to compute sparsity:' in summary)\n self.assertTrue('Time to compute coloring:' in summary)\n\n dense_J = np.ones((50, 50), dtype=bool)\n coloring = _compute_coloring(dense_J, 'auto')\n sys.stdout = StringIO()\n try:\n coloring.summary()\n summary = sys.stdout.getvalue()\n finally:\n sys.stdout = save_out\n\n self.assertTrue('Jacobian shape: (50, 50) (100.00% nonzero)' in summary)\n self.assertTrue('FWD solves: 50 REV solves: 0' in summary)\n self.assertTrue('Total colors vs. total size: 50 vs 50 (0.0% improvement)' in summary)\n self.assertFalse('Time to compute sparsity:' in summary)\n self.assertTrue('Time to compute coloring:' in summary)\n\n def test_repr(self):\n p_color = run_opt(om.ScipyOptimizeDriver, 'auto', optimizer='SLSQP', disp=False, dynamic_total_coloring=True)\n coloring = p_color.driver._coloring_info['coloring']\n rep = repr(coloring)\n self.assertEqual(rep.replace('L', ''), 'Coloring (direction: fwd, ncolors: 5, shape: (22, 21), pct nonzero: 13.42, tol: 1e-15')\n\n dense_J = np.ones((50, 50), dtype=bool)\n coloring = _compute_coloring(dense_J, 'auto')\n rep = repr(coloring)\n self.assertEqual(rep.replace('L', ''), 'Coloring (direction: fwd, ncolors: 50, shape: (50, 50), pct nonzero: 100.00, tol: None')\n\n def test_bad_mode(self):\n p_color_rev = run_opt(om.ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False, dynamic_total_coloring=True)\n coloring = p_color_rev.driver._coloring_info['coloring']\n\n with self.assertRaises(Exception) as context:\n p_color = run_opt(om.ScipyOptimizeDriver, 'fwd', color_info=coloring, optimizer='SLSQP', disp=False)\n self.assertEqual(str(context.exception),\n \"Simultaneous coloring does reverse solves but mode has been set to 'fwd'\")\n\n def test_dynamic_total_coloring(self):\n\n p_color = run_opt(om.ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False, dynamic_total_coloring=True)\n p = run_opt(om.ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False)\n\n assert_almost_equal(p['circle.area'], np.pi, decimal=7)\n assert_almost_equal(p_color['circle.area'], np.pi, decimal=7)\n\n # - rev coloring saves 11 solves per driver iter (11 vs 22)\n # - initial solve for linear constraints takes 1 in both cases (only done once)\n # - dynamic case does 3 full compute_totals to compute coloring, which adds 22 * 3 solves\n # - (total_solves - N) / (solves_per_iter) should be equal between the two cases,\n # - where N is 1 for the uncolored case and 22 * 3 + 1 for the dynamic colored case.\n self.assertEqual((p.model._solve_count - 1) / 22,\n (p_color.model._solve_count - 1 - 22 * 3) / 11)\n\n def test_dynamic_total_coloring_no_derivs(self):\n with self.assertRaises(Exception) as context:\n p_color = run_opt(om.ScipyOptimizeDriver, 'rev', optimizer='SLSQP', disp=False,\n dynamic_total_coloring=True, derivs=False)\n self.assertEqual(str(context.exception),\n \"Derivative support has been turned off but compute_totals was called.\")\n\n\ndef _test_func_name(func, num, param):\n args = []\n for p in param.args:\n try:\n arg = p.__name__\n except:\n arg = str(p)\n args.append(arg)\n return func.__name__ + '_'.join(args)\n\n\nclass BidirectionalTestCase(unittest.TestCase):\n def test_eisenstat(self):\n for n in range(6, 20, 2):\n builder = TotJacBuilder.eisenstat(n)\n builder.color('auto')\n tot_size, tot_colors, fwd_solves, rev_solves, pct = builder.coloring._solves_info()\n if tot_colors == n // 2 + 3:\n raise unittest.SkipTest(\"Current bicoloring algorithm requires n/2 + 3 solves, so skipping for now.\")\n self.assertLessEqual(tot_colors, n // 2 + 2,\n \"Eisenstat's example of size %d required %d colors but shouldn't \"\n \"need more than %d.\" % (n, tot_colors, n // 2 + 2))\n\n builder_fwd = TotJacBuilder.eisenstat(n)\n builder_fwd.color('fwd')\n tot_size, tot_colors, fwd_solves, rev_solves, pct = builder_fwd.coloring._solves_info()\n # The columns of Eisenstat's example are pairwise nonorthogonal, so fwd coloring\n # should require n colors.\n self.assertEqual(n, tot_colors,\n \"Eisenstat's example of size %d was not constructed properly. \"\n \"fwd coloring required only %d colors but should have required \"\n \"%d\" % (n, tot_colors, n))\n\n def test_arrowhead(self):\n for n in [5, 50, 55]:\n builder = TotJacBuilder(n, n)\n builder.add_row(n-1)\n builder.add_col(n-1)\n builder.add_block_diag([(1,1)] * (n-1), 0, 0)\n builder.color('auto')\n tot_size, tot_colors, fwd_solves, rev_solves, pct = builder.coloring._solves_info()\n self.assertEqual(tot_colors, 3)\n\n @parameterized.expand(itertools.product(\n [('n4c6-b15', 3), ('can_715', 21), ('lp_finnis', 14), ('ash608', 6), ('ash331', 6),\n ('D_6', 28), ('Harvard500', 26), ('illc1033', 5)],\n ), name_func=_test_func_name\n )\n @unittest.skipIf(load_npz is None, \"scipy version too old\")\n def test_bidir_coloring(self, tup):\n matname, expected_colors = tup\n matdir = os.path.join(os.path.dirname(openmdao.test_suite.__file__), 'matrices')\n\n # uses matrices from the sparse matrix collection website (sparse.tamu.edu)\n matfile = os.path.join(matdir, matname + '.npz')\n if not os.path.exists(matfile):\n raise unittest.SkipTest(\"Matrix test file were not included.\")\n\n mat = load_npz(matfile).toarray()\n mat = np.asarray(mat, dtype=bool)\n coloring = _compute_coloring(mat, 'auto')\n mat = None\n\n tot_size, tot_colors, fwd_solves, rev_solves, pct = coloring._solves_info()\n\n self.assertEqual(tot_colors, expected_colors)\n\n\ndef _get_random_mat(rows, cols):\n if MPI:\n if MPI.COMM_WORLD.rank == 0:\n mat = np.random.random(rows * cols).reshape((rows, cols)) - 0.5\n MPI.COMM_WORLD.bcast(mat, root=0)\n return mat\n else:\n return MPI.COMM_WORLD.bcast(None, root=0)\n else:\n return np.random.random(rows * cols).reshape((rows, cols)) - 0.5\n\n\n@use_tempdirs\[email protected](OPTIMIZER is not None, \"pyOptSparse required.\")\nclass MatMultMultipointTestCase(unittest.TestCase):\n\n def test_multipoint_with_coloring(self):\n size = 10\n num_pts = 4\n\n np.random.seed(11)\n\n p = om.Problem()\n p.driver = pyOptSparseDriver()\n p.driver.options['optimizer'] = OPTIMIZER\n p.driver.declare_coloring()\n if OPTIMIZER == 'SNOPT':\n p.driver.opt_settings['Major iterations limit'] = 100\n p.driver.opt_settings['Major feasibility tolerance'] = 1.0E-6\n p.driver.opt_settings['Major optimality tolerance'] = 1.0E-6\n # p.driver.opt_settings['iSumm'] = 6\n\n model = p.model\n for i in range(num_pts):\n model.add_subsystem('indep%d' % i, om.IndepVarComp('x', val=np.ones(size)))\n model.add_design_var('indep%d.x' % i)\n\n par1 = model.add_subsystem('par1', om.ParallelGroup())\n for i in range(num_pts):\n mat = _get_random_mat(5, size)\n par1.add_subsystem('comp%d' % i, om.ExecComp('y=A.dot(x)', A=mat, x=np.ones(size), y=np.ones(5)))\n model.connect('indep%d.x' % i, 'par1.comp%d.x' % i)\n\n par2 = model.add_subsystem('par2', om.ParallelGroup())\n for i in range(num_pts):\n mat = _get_random_mat(size, 5)\n par2.add_subsystem('comp%d' % i, om.ExecComp('y=A.dot(x)', A=mat, x=np.ones(5), y=np.ones(size)))\n model.connect('par1.comp%d.y' % i, 'par2.comp%d.x' % i)\n par2.add_constraint('comp%d.y' % i, lower=-1.)\n\n model.add_subsystem('normcomp%d' % i, om.ExecComp(\"y=sum(x*x)\", x=np.ones(size)))\n model.connect('par2.comp%d.y' % i, 'normcomp%d.x' % i)\n\n model.add_subsystem('obj', om.ExecComp(\"y=\" + '+'.join(['x%d' % i for i in range(num_pts)])))\n\n for i in range(num_pts):\n model.connect('normcomp%d.y' % i, 'obj.x%d' % i)\n\n model.add_objective('obj.y')\n\n p.setup()\n\n p.run_driver()\n\n J = p.compute_totals()\n\n for i in range(num_pts):\n cname = 'par2.comp%d' % i\n vname = cname + '.A'\n A1 = p.get_val('par1.comp%d.A'%i, get_remote=True)\n A2 = p.get_val('par2.comp%d.A'%i, get_remote=True)\n norm = np.linalg.norm(J['par2.comp%d.y'%i,'indep%d.x'%i] - A2.dot(A1))\n self.assertLess(norm, 1.e-7)\n\n print(\"final obj:\", p['obj.y'])\n\n\n# use_tempdirs is inherited\[email protected](MPI and PETScVector, \"MPI and PETSc are required.\")\nclass MatMultMultipointMPI2TestCase(MatMultMultipointTestCase):\n N_PROCS = 2\n\n\n# use_tempdirs is inherited\[email protected](MPI and PETScVector, \"MPI and PETSc are required.\")\nclass MatMultMultipointMPI4TestCase(MatMultMultipointTestCase):\n N_PROCS = 4\n\n\nclass SimulColoringVarOutputTestClass(unittest.TestCase):\n def test_multi_variable_coloring_debug_print_totals(self):\n size = 10\n num_pts = 4\n\n np.random.seed(11)\n\n p = om.Problem()\n p.driver = om.ScipyOptimizeDriver()\n p.driver.options['optimizer'] = 'SLSQP'\n p.driver.declare_coloring()\n p.driver.options['debug_print'] = ['totals']\n if OPTIMIZER == 'SNOPT':\n p.driver.opt_settings['Major iterations limit'] = 100\n p.driver.opt_settings['Major feasibility tolerance'] = 1.0E-6\n p.driver.opt_settings['Major optimality tolerance'] = 1.0E-6\n # p.driver.opt_settings['iSumm'] = 6\n\n model = p.model\n for i in range(num_pts):\n model.add_subsystem('indep%d' % i, om.IndepVarComp('x', val=np.ones(size)))\n model.add_design_var('indep%d.x' % i)\n\n par1 = model.add_subsystem('par1', om.ParallelGroup())\n for i in range(num_pts):\n mat = _get_random_mat(5, size)\n par1.add_subsystem('comp%d' % i, om.ExecComp('y=A.dot(x)', A=mat, x=np.ones(size), y=np.ones(5)))\n model.connect('indep%d.x' % i, 'par1.comp%d.x' % i)\n\n par2 = model.add_subsystem('par2', om.ParallelGroup())\n for i in range(num_pts):\n mat = _get_random_mat(size, 5)\n par2.add_subsystem('comp%d' % i, om.ExecComp('y=A.dot(x)', A=mat, x=np.ones(5), y=np.ones(size)))\n model.connect('par1.comp%d.y' % i, 'par2.comp%d.x' % i)\n par2.add_constraint('comp%d.y' % i, lower=-1.)\n\n model.add_subsystem('normcomp%d' % i, om.ExecComp(\"y=sum(x*x)\", x=np.ones(size)))\n model.connect('par2.comp%d.y' % i, 'normcomp%d.x' % i)\n\n model.add_subsystem('obj', om.ExecComp(\"y=\" + '+'.join(['x%d' % i for i in range(num_pts)])))\n\n for i in range(num_pts):\n model.connect('normcomp%d.y' % i, 'obj.x%d' % i)\n\n model.add_objective('obj.y')\n\n p.setup(check=False)\n\n failed, output = run_driver(p)\n\n self.assertFalse(failed, \"Optimization failed.\")\n\n self.assertTrue('In mode: fwd, Solving variable(s) using simul coloring:' in output)\n self.assertTrue(\"('indep0.x', [7])\" in output)\n self.assertTrue(\"('indep1.x', [7])\" in output)\n self.assertTrue(\"('indep2.x', [7])\" in output)\n self.assertTrue(\"('indep3.x', [7])\" in output)\n\n\nclass DumbComp(om.ExplicitComponent):\n def __init__(self, inputs, outputs, isizes, osizes, **kwargs):\n super().__init__(**kwargs)\n self._inames = inputs[:]\n self._onames = outputs[:]\n self._isizes = isizes[:]\n self._osizes = osizes[:]\n\n def setup(self):\n for name, size in zip(self._inames, self._isizes):\n self.add_input(name, val=np.zeros(size))\n\n for name, size in zip(self._onames, self._osizes):\n self.add_output(name, val=np.zeros(size))\n\n self.add_output('obj', val=0.0)\n\n self.declare_partials('*', '*', method='cs')\n\n def compute(self, inputs, outputs):\n mult = 1.0\n for iname, oname in zip(self._inames, self._onames):\n outputs[oname] = inputs[iname] * mult\n\n outputs['obj'] = outputs[self._onames[0]][0]\n\n\n@use_tempdirs\nclass SimulColoringConfigCheckTestCase(unittest.TestCase):\n def _build_model(self, ofnames, wrtnames, sizes, color, fixed):\n \"\"\"\n Build a model consisting of an IndepVarComp and an ExecComp with customizable vars and sizes.\n \"\"\"\n assert len(ofnames) == len(wrtnames), 'Must have same number of OF and WRT names'\n assert len(ofnames) == len(sizes), 'names and sizes must have same length'\n\n p = om.Problem()\n model = p.model\n p.driver = om.ScipyOptimizeDriver()\n p.driver.options['optimizer'] = 'SLSQP'\n p.driver.options['disp'] = False\n\n if color == 'total':\n p.driver.declare_coloring()\n if fixed:\n # NOTE: This call line is embedded in the 2.x->3.x api conversion guide. Do not\n # modify without carefully checking the guide.\n p.driver.use_fixed_coloring()\n\n indeps = model.add_subsystem('indeps', om.IndepVarComp())\n for name, sz in zip(wrtnames, sizes):\n indeps.add_output(name, val=np.ones(sz))\n model.add_design_var('indeps.' + name)\n\n for name in ofnames:\n model.add_constraint('comp.' + name, lower=0.0)\n\n inames = [n + '_in' for n in ofnames]\n comp = model.add_subsystem('comp', DumbComp(inames, ofnames, sizes, sizes))\n model.add_objective('comp.obj')\n\n if color == 'partial':\n comp.declare_coloring()\n if fixed:\n comp.use_fixed_coloring()\n\n for ofname, wrtname in zip(ofnames, wrtnames):\n model.connect('indeps.' + wrtname, 'comp.' + ofname + '_in')\n\n p.setup()\n p.final_setup()\n\n return p\n\n def test_good_total(self):\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='total', fixed=False)\n p.run_driver()\n\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='total', fixed=True)\n p.run_driver()\n\n def test_good_partial(self):\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='partial', fixed=False)\n p.run_driver()\n\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='partial', fixed=True)\n p.run_driver()\n\n def test_added_name_total(self):\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='total', fixed=False)\n p.run_driver()\n\n with self.assertRaises(RuntimeError) as ctx:\n p = self._build_model(ofnames=['w', 'x', 'y', 'z'], wrtnames=['a', 'b', 'c', 'd'],\n sizes=[3, 4, 5, 6], color='total', fixed=True)\n\n self.assertEqual(str(ctx.exception),\n \"ScipyOptimizeDriver: Current coloring configuration does not match the configuration of the current model.\\n The following row vars were added: ['comp.z'].\\n The following column vars were added: ['indeps.d'].\\nMake sure you don't have different problems that have the same coloring directory. Set the coloring directory by setting the value of problem.options['coloring_dir'].\")\n\n def test_added_name_partial(self):\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='partial', fixed=False)\n p.run_driver()\n\n p = self._build_model(ofnames=['w', 'x', 'y', 'z'], wrtnames=['a', 'b', 'c', 'd'],\n sizes=[3, 4, 5, 6], color='partial', fixed=True)\n\n with self.assertRaises(RuntimeError) as ctx:\n p.run_driver()\n\n self.assertEqual(str(ctx.exception), \"'comp' <class DumbComp>: Current coloring configuration does not match the configuration of the current model.\\n The following row vars were added: ['z'].\\n The following column vars were added: ['z_in'].\\nMake sure you don't have different problems that have the same coloring directory. Set the coloring directory by setting the value of problem.options['coloring_dir'].\")\n\n def test_removed_name_total(self):\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='total', fixed=False)\n p.run_driver()\n\n\n with self.assertRaises(RuntimeError) as ctx:\n p = self._build_model(ofnames=['w', 'y'], wrtnames=['a', 'c'],\n sizes=[3, 5], color='total', fixed=True)\n self.assertEqual(str(ctx.exception), \"ScipyOptimizeDriver: Current coloring configuration does not match the configuration of the current model.\\n The following row vars were removed: ['comp.x'].\\n The following column vars were removed: ['indeps.b'].\\nMake sure you don't have different problems that have the same coloring directory. Set the coloring directory by setting the value of problem.options['coloring_dir'].\")\n\n def test_removed_name_partial(self):\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='partial', fixed=False)\n p.run_driver()\n\n p = self._build_model(ofnames=['w', 'y'], wrtnames=['a', 'c'],\n sizes=[3, 5], color='partial', fixed=True)\n\n with self.assertRaises(RuntimeError) as ctx:\n p.run_driver()\n\n self.assertEqual(str(ctx.exception),\n \"'comp' <class DumbComp>: Current coloring configuration does not match the configuration of the current model.\\n The following row vars were removed: ['x'].\\n The following column vars were removed: ['x_in'].\\nMake sure you don't have different problems that have the same coloring directory. Set the coloring directory by setting the value of problem.options['coloring_dir'].\")\n\n def test_reordered_name_total(self):\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='total', fixed=False)\n p.run_driver()\n\n with self.assertRaises(RuntimeError) as ctx:\n p = self._build_model(ofnames=['w', 'y', 'x'], wrtnames=['a', 'c', 'b'],\n sizes=[3, 5, 4], color='total', fixed=True)\n self.assertEqual(str(ctx.exception), \"ScipyOptimizeDriver: Current coloring configuration does not match the configuration of the current model.\\n The row vars have changed order.\\n The column vars have changed order.\\nMake sure you don't have different problems that have the same coloring directory. Set the coloring directory by setting the value of problem.options['coloring_dir'].\")\n\n def test_reordered_name_partial(self):\n p = self._build_model(ofnames=['x', 'y', 'z'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='partial', fixed=False)\n p.run_driver()\n\n p = self._build_model(ofnames=['x', 'z', 'y'], wrtnames=['a', 'c', 'b'],\n sizes=[3, 4, 5], color='partial', fixed=True)\n\n with self.assertRaises(RuntimeError) as ctx:\n p.run_driver()\n\n self.assertEqual(str(ctx.exception), \"'comp' <class DumbComp>: Current coloring configuration does not match the configuration of the current model.\\n The row vars have changed order.\\n The column vars have changed order.\\nMake sure you don't have different problems that have the same coloring directory. Set the coloring directory by setting the value of problem.options['coloring_dir'].\")\n\n def test_size_change_total(self):\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='total', fixed=False)\n p.run_driver()\n\n with self.assertRaises(RuntimeError) as ctx:\n p = self._build_model(ofnames=['w', 'x', 'y'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 7, 5], color='total', fixed=True)\n self.assertEqual(str(ctx.exception), \"ScipyOptimizeDriver: Current coloring configuration does not match the configuration of the current model.\\n The following variables have changed sizes: ['comp.x', 'indeps.b'].\\nMake sure you don't have different problems that have the same coloring directory. Set the coloring directory by setting the value of problem.options['coloring_dir'].\")\n\n def test_size_change_partial(self):\n p = self._build_model(ofnames=['x', 'y', 'z'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 4, 5], color='partial', fixed=False)\n p.run_driver()\n\n p = self._build_model(ofnames=['x', 'y', 'z'], wrtnames=['a', 'b', 'c'],\n sizes=[3, 9, 5], color='partial', fixed=True)\n\n with self.assertRaises(RuntimeError) as ctx:\n p.run_driver()\n\n self.assertEqual(str(ctx.exception), \"'comp' <class DumbComp>: Current coloring configuration does not match the configuration of the current model.\\n The following variables have changed sizes: ['y', 'y_in'].\\nMake sure you don't have different problems that have the same coloring directory. Set the coloring directory by setting the value of problem.options['coloring_dir'].\")\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"import unittest\n\nimport numpy as np\n\nimport openmdao.api as om\nfrom openmdao.utils.assert_utils import assert_near_equal\n\n\nclass TestNonlinearCircuit(unittest.TestCase):\n\n def test_nonlinear_circuit_analysis(self):\n import numpy as np\n\n import openmdao.api as om\n\n class Resistor(om.ExplicitComponent):\n \"\"\"Computes current across a resistor using Ohm's law.\"\"\"\n\n def initialize(self):\n self.options.declare('R', default=1., desc='Resistance in Ohms')\n\n def setup(self):\n self.add_input('V_in', units='V')\n self.add_input('V_out', units='V')\n self.add_output('I', units='A')\n\n # partial derivs are constant, so we can assign their values in setup\n R = self.options['R']\n self.declare_partials('I', 'V_in', val=1 / R)\n self.declare_partials('I', 'V_out', val=-1 / R)\n\n def compute(self, inputs, outputs):\n deltaV = inputs['V_in'] - inputs['V_out']\n outputs['I'] = deltaV / self.options['R']\n\n class Diode(om.ExplicitComponent):\n \"\"\"Computes current across a diode using the Shockley diode equation.\"\"\"\n\n def initialize(self):\n self.options.declare('Is', default=1e-15, desc='Saturation current in Amps')\n self.options.declare('Vt', default=.025875, desc='Thermal voltage in Volts')\n\n def setup(self):\n self.add_input('V_in', units='V')\n self.add_input('V_out', units='V')\n self.add_output('I', units='A')\n\n # non-linear component, so we'll declare the partials here but compute them in compute_partials\n self.declare_partials('I', 'V_in')\n self.declare_partials('I', 'V_out')\n\n def compute(self, inputs, outputs):\n deltaV = inputs['V_in'] - inputs['V_out']\n Is = self.options['Is']\n Vt = self.options['Vt']\n outputs['I'] = Is * (np.exp(deltaV / Vt) - 1)\n\n def compute_partials(self, inputs, J):\n deltaV = inputs['V_in'] - inputs['V_out']\n Is = self.options['Is']\n Vt = self.options['Vt']\n I = Is * np.exp(deltaV / Vt)\n\n J['I', 'V_in'] = I/Vt\n J['I', 'V_out'] = -I/Vt\n\n class Node(om.ImplicitComponent):\n \"\"\"Computes voltage residual across a node based on incoming and outgoing current.\"\"\"\n\n def initialize(self):\n self.options.declare('n_in', default=1, types=int, desc='number of connections with + assumed in')\n self.options.declare('n_out', default=1, types=int, desc='number of current connections + assumed out')\n\n def setup(self):\n self.add_output('V', val=5., units='V')\n\n for i in range(self.options['n_in']):\n i_name = 'I_in:{}'.format(i)\n self.add_input(i_name, units='A')\n self.declare_partials('V', i_name, val=1)\n\n for i in range(self.options['n_out']):\n i_name = 'I_out:{}'.format(i)\n self.add_input(i_name, units='A')\n self.declare_partials('V', i_name, val=-1)\n\n # note: we don't declare any partials wrt `V` here,\n # because the residual doesn't directly depend on it\n\n def apply_nonlinear(self, inputs, outputs, residuals):\n residuals['V'] = 0.\n for i_conn in range(self.options['n_in']):\n residuals['V'] += inputs['I_in:{}'.format(i_conn)]\n for i_conn in range(self.options['n_out']):\n residuals['V'] -= inputs['I_out:{}'.format(i_conn)]\n\n class Circuit(om.Group):\n\n def setup(self):\n self.add_subsystem('n1', Node(n_in=1, n_out=2), promotes_inputs=[('I_in:0', 'I_in')])\n self.add_subsystem('n2', Node()) # leaving defaults\n\n self.add_subsystem('R1', Resistor(R=100.), promotes_inputs=[('V_out', 'Vg')])\n self.add_subsystem('R2', Resistor(R=10000.))\n self.add_subsystem('D1', Diode(), promotes_inputs=[('V_out', 'Vg')])\n\n self.connect('n1.V', ['R1.V_in', 'R2.V_in'])\n self.connect('R1.I', 'n1.I_out:0')\n self.connect('R2.I', 'n1.I_out:1')\n\n self.connect('n2.V', ['R2.V_out', 'D1.V_in'])\n self.connect('R2.I', 'n2.I_in:0')\n self.connect('D1.I', 'n2.I_out:0')\n\n self.nonlinear_solver = om.NewtonSolver()\n self.linear_solver = om.DirectSolver()\n\n self.nonlinear_solver.options['iprint'] = 2\n self.nonlinear_solver.options['maxiter'] = 10\n self.nonlinear_solver.options['solve_subsystems'] = True\n self.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS()\n self.nonlinear_solver.linesearch.options['maxiter'] = 10\n self.nonlinear_solver.linesearch.options['iprint'] = 2\n\n\n p = om.Problem()\n model = p.model\n\n model.add_subsystem('circuit', Circuit())\n\n p.setup()\n\n p.set_val('circuit.I_in', 0.1)\n p.set_val('circuit.Vg', 0.)\n\n # set some initial guesses\n p.set_val('circuit.n1.V', 10.)\n p.set_val('circuit.n2.V', 1e-3)\n\n p.run_model()\n\n assert_near_equal(p['circuit.n1.V'], 9.90804735, 1e-5)\n assert_near_equal(p['circuit.n2.V'], 0.71278185, 1e-5)\n assert_near_equal(p['circuit.R1.I'], 0.09908047, 1e-5)\n assert_near_equal(p['circuit.R2.I'], 0.00091953, 1e-5)\n assert_near_equal(p['circuit.D1.I'], 0.00091953, 1e-5)\n\n # sanity check: should sum to .1 Amps\n assert_near_equal(p['circuit.R1.I'] + p['circuit.D1.I'], .1, 1e-6)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\" Test for the Backtracking Line Search\"\"\"\n\nimport sys\nimport unittest\nfrom math import atan\n\nfrom io import StringIO\n\nimport numpy as np\n\nimport openmdao.api as om\nfrom openmdao.test_suite.components.double_sellar import DoubleSellar\nfrom openmdao.test_suite.components.implicit_newton_linesearch \\\n import ImplCompTwoStates, ImplCompTwoStatesArrays\nfrom openmdao.test_suite.components.sellar import SellarDis1, SellarDis2withDerivatives\nfrom openmdao.utils.assert_utils import assert_near_equal\n\n\nclass TestArmejoGoldsteinBounds(unittest.TestCase):\n\n def setUp(self):\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', 1.0))\n top.model.add_subsystem('comp', ImplCompTwoStates())\n top.model.connect('px.x', 'comp.x')\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.setup()\n\n self.top = top\n\n def test_nolinesearch(self):\n top = self.top\n top.model.nonlinear_solver.linesearch = None\n\n # Run without a line search at x=2.0\n top['px.x'] = 2.0\n top.run_model()\n assert_near_equal(top['comp.y'], 4.666666, 1e-4)\n assert_near_equal(top['comp.z'], 1.333333, 1e-4)\n\n # Run without a line search at x=0.5\n top['px.x'] = 0.5\n top.run_model()\n assert_near_equal(top['comp.y'], 5.833333, 1e-4)\n assert_near_equal(top['comp.z'], 2.666666, 1e-4)\n\n def test_linesearch_bounds_vector(self):\n top = self.top\n\n ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector')\n ls.options['maxiter'] = 10\n ls.options['alpha'] = 1.0\n\n # Setup again because we assigned a new linesearch\n top.setup()\n\n # Test lower bound: should go to the lower bound and stall\n top['px.x'] = 2.0\n top['comp.y'] = 0.0\n top['comp.z'] = 1.6\n top.run_model()\n assert_near_equal(top['comp.z'], 1.5, 1e-8)\n\n # Test upper bound: should go to the upper bound and stall\n top['px.x'] = 0.5\n top['comp.y'] = 0.0\n top['comp.z'] = 2.4\n top.run_model()\n assert_near_equal(top['comp.z'], 2.5, 1e-8)\n\n def test_linesearch_bounds_wall(self):\n top = self.top\n\n ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='wall')\n ls.options['maxiter'] = 10\n ls.options['alpha'] = 10.0\n\n # Setup again because we assigned a new linesearch\n top.setup()\n\n # Test lower bound: should go to the lower bound and stall\n top['px.x'] = 2.0\n top['comp.y'] = 0.0\n top['comp.z'] = 1.6\n top.run_model()\n assert_near_equal(top['comp.z'], 1.5, 1e-8)\n\n # Test upper bound: should go to the upper bound and stall\n top['px.x'] = 0.5\n top['comp.y'] = 0.0\n top['comp.z'] = 2.4\n top.run_model()\n assert_near_equal(top['comp.z'], 2.5, 1e-8)\n\n def test_linesearch_bounds_scalar(self):\n top = self.top\n\n ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='scalar')\n ls.options['maxiter'] = 10\n ls.options['alpha'] = 1.0\n\n # Setup again because we assigned a new linesearch\n top.setup()\n\n # Test lower bound: should stop just short of the lower bound\n top['px.x'] = 2.0\n top['comp.y'] = 0.0\n top['comp.z'] = 1.6\n top.run_model()\n self.assertGreaterEqual(top['comp.z'], 1.5)\n self.assertLessEqual(top['comp.z'], 1.6)\n\n # Test lower bound: should stop just short of the upper bound\n top['px.x'] = 0.5\n top['comp.y'] = 0.0\n top['comp.z'] = 2.4\n top.run_model()\n self.assertGreaterEqual(top['comp.z'], 2.5)\n self.assertLessEqual(top['comp.z'], 2.5)\n\n def test_bound_enforce_print_bug(self):\n # Error during print if bound was one-sided.\n\n class OneSidedBounds(ImplCompTwoStatesArrays):\n\n def setup(self):\n self.add_input('x', np.zeros((3, 1)))\n self.add_output('y', np.zeros((3, 1)))\n self.add_output('z', 2.0*np.ones((3, 1)),\n upper=np.array([2.6, 2.5, 2.65]).reshape((3,1)))\n\n self.maxiter = 10\n self.atol = 1.0e-12\n\n self.declare_partials(of='*', wrt='*')\n\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1))))\n top.model.add_subsystem('comp', OneSidedBounds())\n top.model.connect('px.x', 'comp.x')\n\n newt = top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 2\n top.model.linear_solver = om.ScipyKrylov()\n\n ls = newt.linesearch = om.ArmijoGoldsteinLS()\n ls.options['print_bound_enforce'] = True\n\n top.set_solver_print(level=2)\n top.setup()\n\n top['px.x'] = 2.0\n top['comp.y'] = 0.\n top['comp.z'] = 1.6\n\n # Should run without an exception being raised.\n top.run_model()\n\n\nclass ParaboloidAE(om.ExplicitComponent):\n \"\"\" Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3\n This version raises an analysis error if x < 2.0\n The AE in ParaboloidAE stands for AnalysisError.\"\"\"\n\n def setup(self):\n self.add_input('x', val=0.0)\n self.add_input('y', val=0.0)\n\n self.add_output('f_xy', val=0.0)\n\n self.declare_partials(of='*', wrt='*')\n\n def compute(self, inputs, outputs):\n \"\"\"f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3\n Optimal solution (minimum): x = 6.6667; y = -7.3333\n \"\"\"\n x = inputs['x']\n y = inputs['y']\n\n if x < 1.75:\n raise om.AnalysisError('Try Again.')\n\n outputs['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0\n\n def compute_partials(self, inputs, partials):\n \"\"\" Jacobian for our paraboloid.\"\"\"\n x = inputs['x']\n y = inputs['y']\n\n partials['f_xy', 'x'] = 2.0*x - 6.0 + y\n partials['f_xy', 'y'] = 2.0*y + 8.0 + x\n\n\nclass TestAnalysisErrorExplicit(unittest.TestCase):\n\n def setUp(self):\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', 1.0))\n top.model.add_subsystem('comp', ImplCompTwoStates())\n top.model.add_subsystem('par', ParaboloidAE())\n top.model.connect('px.x', 'comp.x')\n top.model.connect('comp.z', 'par.x')\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 1\n top.model.linear_solver = om.ScipyKrylov()\n\n ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector')\n ls.options['maxiter'] = 10\n ls.options['alpha'] = 1.0\n top.set_solver_print(level=0)\n\n self.top = top\n self.ls = ls\n\n def test_retry(self):\n # Test the behavior with the switch turned on.\n top = self.top\n top.setup()\n self.ls.options['retry_on_analysis_error'] = True\n\n # Test lower bound: should go as far as it can without going past 1.75 and triggering an\n # AnalysisError. It doesn't do a great job, so ends up at 1.8 instead of 1.75\n top['px.x'] = 2.0\n top['comp.y'] = 0.0\n top['comp.z'] = 2.1\n top.run_model()\n assert_near_equal(top['comp.z'], 1.8, 1e-8)\n\n def test_no_retry(self):\n # Test the behavior with the switch turned off.\n self.ls.options['retry_on_analysis_error'] = False\n\n top = self.top\n top.setup()\n\n top['px.x'] = 2.0\n top['comp.y'] = 0.0\n top['comp.z'] = 2.1\n\n with self.assertRaises(om.AnalysisError) as context:\n top.run_model()\n\n self.assertEqual(str(context.exception),\n \"'par' <class ParaboloidAE>: Error calling compute(), Try Again.\")\n\n\nclass ImplCompTwoStatesAE(om.ImplicitComponent):\n\n def setup(self):\n self.add_input('x', 0.5)\n self.add_output('y', 0.0)\n self.add_output('z', 2.0, lower=1.5, upper=2.5)\n\n self.maxiter = 10\n self.atol = 1.0e-12\n\n self.declare_partials(of='*', wrt='*')\n\n self.counter = 0\n\n def apply_nonlinear(self, inputs, outputs, residuals):\n \"\"\"\n Don't solve; just calculate the residual.\n \"\"\"\n self.upper = 1\n self.lower = 0\n\n x = inputs['x']\n y = outputs['y']\n z = outputs['z']\n\n residuals['y'] = y - x - 2.0*z\n residuals['z'] = x*z + z - 4.0\n\n self.counter += 1\n if self.counter > self.lower and self.counter < self.upper:\n raise om.AnalysisError('catch me')\n\n def linearize(self, inputs, outputs, jac):\n \"\"\"\n Analytical derivatives.\n \"\"\"\n\n # Output equation\n jac[('y', 'x')] = -1.0\n jac[('y', 'y')] = 1.0\n jac[('y', 'z')] = -2.0\n\n # State equation\n jac[('z', 'z')] = -inputs['x'] + 1.0\n jac[('z', 'x')] = -outputs['z']\n\nclass ImplCompTwoStatesGuess(ImplCompTwoStatesAE):\n\n def guess_nonlinear(self, inputs, outputs, residuals):\n outputs['z'] = 3.0\n\nclass TestAnalysisErrorImplicit(unittest.TestCase):\n\n def test_deep_analysis_error_iprint(self):\n\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', 7.0))\n\n sub = top.model.add_subsystem('sub', om.Group())\n sub.add_subsystem('comp', ImplCompTwoStatesAE())\n sub.upper = 5\n sub.lower = 11\n\n top.model.connect('px.x', 'sub.comp.x')\n\n top.model.nonlinear_solver = om.NewtonSolver()\n top.model.nonlinear_solver.options['maxiter'] = 2\n top.model.nonlinear_solver.options['solve_subsystems'] = True\n top.model.nonlinear_solver.linesearch = None\n top.model.linear_solver = om.ScipyKrylov()\n\n sub.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n sub.nonlinear_solver.options['maxiter'] = 2\n sub.nonlinear_solver.linesearch = None\n sub.linear_solver = om.ScipyKrylov()\n\n ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='wall')\n ls.options['maxiter'] = 5\n ls.options['alpha'] = 10.0\n ls.options['retry_on_analysis_error'] = True\n ls.options['c'] = 1.0\n\n top.setup()\n top.set_solver_print(level=2)\n\n stdout = sys.stdout\n strout = StringIO()\n\n sys.stdout = strout\n try:\n top.run_model()\n finally:\n sys.stdout = stdout\n\n output = strout.getvalue().split('\\n')\n\n correct = False\n for line in output:\n # make sure a line starting with this string is present in stdout\n if line.startswith('| LS: AG 3'):\n correct = True\n break\n self.assertTrue(correct, msg='Expected line search output not found in stdout')\n\n def test_read_only_bug(self):\n # this tests for a bug in which guess_nonlinear failed due to the output\n # vector being left in a read only state after the AnalysisError\n\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', 7.0))\n\n sub = top.model.add_subsystem('sub', om.Group())\n sub.add_subsystem('comp', ImplCompTwoStatesAE())\n sub.upper = 20\n sub.lower = 25\n\n top.model.connect('px.x', 'sub.comp.x')\n\n top.model.nonlinear_solver = om.NewtonSolver()\n top.model.nonlinear_solver.options['maxiter'] = 2\n top.model.nonlinear_solver.options['solve_subsystems'] = True\n top.model.nonlinear_solver.linesearch = None\n top.model.linear_solver = om.ScipyKrylov()\n\n sub.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n sub.nonlinear_solver.options['maxiter'] = 2\n sub.nonlinear_solver.linesearch = None\n sub.linear_solver = om.ScipyKrylov()\n\n ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='wall')\n ls.options['maxiter'] = 5\n ls.options['alpha'] = 10.0\n ls.options['retry_on_analysis_error'] = True\n ls.options['c'] = 1.0\n\n top.setup()\n top.set_solver_print(level=2)\n\n stdout = sys.stdout\n strout = StringIO()\n\n sys.stdout = strout\n try:\n top.run_model()\n finally:\n sys.stdout = stdout\n\n output = strout.getvalue().split('\\n')\n\n correct = False\n for line in output:\n # make sure a line starting with this string is present in stdout\n if line.startswith('| LS: AG 3'):\n correct = True\n break\n self.assertTrue(correct, msg='Expected line search output not found in stdout')\n\n\nclass TestBoundsEnforceLSArrayBounds(unittest.TestCase):\n\n def setUp(self):\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1))))\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays())\n top.model.connect('px.x', 'comp.x')\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.set_solver_print(level=0)\n top.setup()\n\n self.top = top\n self.ub = np.array([2.6, 2.5, 2.65])\n\n def test_linesearch_vector_bound_enforcement(self):\n top = self.top\n\n ls = top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='vector')\n ls.options['print_bound_enforce'] = True\n\n # Setup again because we assigned a new linesearch\n top.setup()\n\n # Test lower bounds: should go to the lower bound and stall\n top['px.x'] = 2.0\n top['comp.y'] = 0.\n top['comp.z'] = 1.6\n top.run_model()\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [1.5], 1e-8)\n\n # Test upper bounds: should go to the minimum upper bound and stall\n top['px.x'] = 0.5\n top['comp.y'] = 0.\n top['comp.z'] = 2.4\n\n stdout = sys.stdout\n strout = StringIO()\n\n sys.stdout = strout\n try:\n top.run_model()\n finally:\n sys.stdout = stdout\n\n txt = strout.getvalue()\n\n self.assertTrue(\"'comp.z' exceeds upper bound\" in txt)\n\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [2.5], 1e-8)\n\n def test_linesearch_wall_bound_enforcement_wall(self):\n top = self.top\n\n top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='wall')\n\n # Setup again because we assigned a new linesearch\n top.setup()\n\n # Test lower bounds: should go to the lower bound and stall\n top['px.x'] = 2.0\n top['comp.y'] = 0.\n top['comp.z'] = 1.6\n top.run_model()\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [1.5], 1e-8)\n\n # Test upper bounds: should go to the upper bound and stall\n top['px.x'] = 0.5\n top['comp.y'] = 0.\n top['comp.z'] = 2.4\n top.run_model()\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [self.ub[ind]], 1e-8)\n\n def test_linesearch_wall_bound_enforcement_scalar(self):\n top = self.top\n\n top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='scalar')\n\n # Setup again because we assigned a new linesearch\n top.setup()\n\n # Test lower bounds: should stop just short of the lower bound\n top['px.x'] = 2.0\n top['comp.y'] = 0.\n top['comp.z'] = 1.6\n top.run_model()\n for ind in range(3):\n self.assertGreaterEqual(top['comp.z'][ind], 1.5)\n self.assertLessEqual(top['comp.z'][ind], 1.6)\n\n # Test upper bounds: should stop just short of the minimum upper bound\n top['px.x'] = 0.5\n top['comp.y'] = 0.\n top['comp.z'] = 2.4\n top.run_model()\n for ind in range(3):\n self.assertTrue(2.4 <= top['comp.z'][ind] <= self.ub[ind])\n\n def test_error_handling(self):\n # Make sure the debug_print doesn't bomb out.\n\n class Bad(om.ExplicitComponent):\n\n def setup(self):\n self.add_input('x', val=0.0)\n self.add_input('y', val=0.0)\n\n self.add_output('f_xy', val=0.0, upper=1.0)\n\n self.declare_partials(of='*', wrt='*')\n self.count = 0\n\n def compute(self, inputs, outputs):\n if self.count < 1:\n x = inputs['x']\n y = inputs['y']\n outputs['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0\n else:\n outputs['f_xy'] = np.inf\n\n self.count += 1\n\n def compute_partials(self, inputs, partials):\n x = inputs['x']\n y = inputs['y']\n\n partials['f_xy', 'x'] = 2.0*x - 6.0 + y\n partials['f_xy', 'y'] = 2.0*y + 8.0 + x\n\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', 1.0))\n top.model.add_subsystem('comp', ImplCompTwoStates())\n top.model.add_subsystem('par', Bad())\n top.model.connect('px.x', 'comp.x')\n top.model.connect('comp.z', 'par.x')\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 3\n\n top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='vector')\n top.set_solver_print(level=0)\n\n top.setup()\n\n # Make sure we don't raise an error when we reach the final debug print.\n top.run_model()\n\n def test_undeclared_options(self):\n # Test that using options that should not exist in class, cause an\n # error if they are set when instantiating BoundsEnforceLS.\n # atol, rtol, maxiter, and err_on_non_converge are not used in BoundsEnforceLS\n\n with self.assertRaises(KeyError) as context:\n om.BoundsEnforceLS(bound_enforcement='scalar', atol=1.0)\n\n self.assertEqual(str(context.exception), \"\\\"BoundsEnforceLS: Option 'atol' cannot be set because it \"\n \"has not been declared.\\\"\")\n\n with self.assertRaises(KeyError) as context:\n om.BoundsEnforceLS(bound_enforcement='scalar', rtol=2.0)\n\n self.assertEqual(str(context.exception), \"\\\"BoundsEnforceLS: Option 'rtol' cannot be set because it \"\n \"has not been declared.\\\"\")\n\n with self.assertRaises(KeyError) as context:\n om.BoundsEnforceLS(bound_enforcement='scalar', maxiter=1)\n\n self.assertEqual(str(context.exception), \"\\\"BoundsEnforceLS: Option 'maxiter' cannot be set because it \"\n \"has not been declared.\\\"\")\n\n with self.assertRaises(KeyError) as context:\n om.BoundsEnforceLS(bound_enforcement='scalar', err_on_non_converge=True)\n\n self.assertEqual(str(context.exception), \"\\\"BoundsEnforceLS: Option 'err_on_non_converge' cannot be set because it \"\n \"has not been declared.\\\"\")\n\n\nclass SellarDis1withDerivativesMod(SellarDis1):\n # Version of Sellar discipline 1 with a slightly incorrect x derivative.\n # This will still solve, but will require some backtracking at times.\n\n def setup_partials(self):\n self.declare_partials(of='*', wrt='*')\n\n def compute_partials(self, inputs, partials):\n partials['y1', 'y2'] = -0.2\n partials['y1', 'z'] = np.array([[2.0 * inputs['z'][0], 1.0]])\n partials['y1', 'x'] = 1.5\n\n\nclass SubSellarMod(om.Group):\n\n def __init__(self, units=None, scaling=None, **kwargs):\n super().__init__(**kwargs)\n\n self.add_subsystem('d1', SellarDis1withDerivativesMod(units=units, scaling=scaling),\n promotes=['x', 'z', 'y1', 'y2'])\n self.add_subsystem('d2', SellarDis2withDerivatives(units=units, scaling=scaling),\n promotes=['z', 'y1', 'y2'])\n\n\nclass DoubleSellarMod(om.Group):\n\n def __init__(self, units=None, scaling=None, **kwargs):\n super().__init__(**kwargs)\n\n self.add_subsystem('g1', SubSellarMod(units=units, scaling=scaling))\n self.add_subsystem('g2', SubSellarMod(units=units, scaling=scaling))\n\n self.connect('g1.y2', 'g2.x')\n self.connect('g2.y2', 'g1.x')\n\n # Converge the outer loop with Gauss Seidel, with a looser tolerance.\n self.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n self.linear_solver = om.DirectSolver()\n\n\nclass TestArmijoGoldsteinLSArrayBounds(unittest.TestCase):\n\n def setUp(self):\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1))))\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays())\n top.model.connect('px.x', 'comp.x')\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.set_solver_print(level=0)\n top.setup()\n\n self.top = top\n self.ub = np.array([2.6, 2.5, 2.65])\n\n def test_linesearch_vector_bound_enforcement(self):\n top = self.top\n\n ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector')\n ls.options['c'] = .1\n\n # Setup again because we assigned a new linesearch\n top.setup()\n\n # Test lower bounds: should go to the lower bound and stall\n top['px.x'] = 2.0\n top['comp.y'] = 0.\n top['comp.z'] = 1.6\n top.run_model()\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [1.5], 1e-8)\n\n # Test upper bounds: should go to the minimum upper bound and stall\n top['px.x'] = 0.5\n top['comp.y'] = 0.\n top['comp.z'] = 2.4\n top.run_model()\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [2.5], 1e-8)\n\n def test_linesearch_wall_bound_enforcement_wall(self):\n top = self.top\n\n top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='wall')\n\n # Setup again because we assigned a new linesearch\n top.setup()\n\n # Test lower bounds: should go to the lower bound and stall\n top['px.x'] = 2.0\n top['comp.y'] = 0.\n top['comp.z'] = 1.6\n top.run_model()\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [1.5], 1e-8)\n\n # Test upper bounds: should go to the upper bound and stall\n top['px.x'] = 0.5\n top['comp.y'] = 0.\n top['comp.z'] = 2.4\n top.run_model()\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [self.ub[ind]], 1e-8)\n\n def test_linesearch_wall_bound_enforcement_scalar(self):\n top = self.top\n\n top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='scalar')\n\n # Setup again because we assigned a new linesearch\n top.setup()\n\n # Test lower bounds: should stop just short of the lower bound\n top['px.x'] = 2.0\n top['comp.y'] = 0.\n top['comp.z'] = 1.6\n top.run_model()\n for ind in range(3):\n self.assertTrue(1.5 <= top['comp.z'][ind] <= 1.6)\n\n # Test upper bounds: should stop just short of the minimum upper bound\n top['px.x'] = 0.5\n top['comp.y'] = 0.\n top['comp.z'] = 2.4\n top.run_model()\n for ind in range(3):\n self.assertTrue(2.4 <= top['comp.z'][ind] <= self.ub[ind])\n\n def test_with_subsolves(self):\n\n prob = om.Problem()\n model = prob.model = DoubleSellarMod()\n\n g1 = model.g1\n g1.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n g1.nonlinear_solver.options['rtol'] = 1.0e-5\n g1.linear_solver = om.DirectSolver()\n\n g2 = model.g2\n g2.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n g2.nonlinear_solver.options['rtol'] = 1.0e-5\n g2.linear_solver = om.DirectSolver()\n\n model.nonlinear_solver = om.NewtonSolver()\n model.linear_solver = om.ScipyKrylov()\n\n model.nonlinear_solver.options['solve_subsystems'] = True\n model.nonlinear_solver.options['max_sub_solves'] = 4\n ls = model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector')\n\n prob.set_solver_print(level=0)\n\n prob.setup()\n prob.run_model()\n\n assert_near_equal(prob['g1.y1'], 0.64, .00001)\n assert_near_equal(prob['g1.y2'], 0.80, .00001)\n assert_near_equal(prob['g2.y1'], 0.64, .00001)\n assert_near_equal(prob['g2.y2'], 0.80, .00001)\n\n\nclass CompAtan(om.ImplicitComponent):\n \"\"\"\n A simple implicit component with the following equation:\n\n F(x, y) = 33.0 * atan(y-20)**2 + x\n\n x is an input, y is the state to be solved.\n for x = -100, y should be 19.68734033\n\n This equation poses a challenge because a guess that is far from the solution yields large\n gradients and divergence. Additionally, the jacobian becomes singular at y = 20. To address\n this, a lower and upper bound are added on y so that a solver with a BoundsEnforceLS does not\n allow it to stray into problematic regions.\n \"\"\"\n\n def setup(self):\n self.add_input('x', 1.0)\n self.add_output('y', 1.0, lower=1.0, upper=19.9)\n\n self.declare_partials(of='y', wrt='x')\n self.declare_partials(of='y', wrt='y')\n\n def apply_nonlinear(self, inputs, outputs, residuals):\n x = inputs['x']\n y = outputs['y']\n\n residuals['y'] = (33.0 * atan(y-20.0))**2 + x\n\n def linearize(self, inputs, outputs, jacobian):\n x = inputs['x']\n y = outputs['y']\n\n jacobian['y', 'y'] = 2178.0*atan(y-20.0) / (y**2 - 40.0*y + 401.0)\n jacobian['y', 'x'] = 1.0\n\n\nclass TestFeatureLineSearch(unittest.TestCase):\n\n def test_feature_specification(self):\n import openmdao.api as om\n from openmdao.solvers.linesearch.tests.test_backtracking import CompAtan\n\n prob = om.Problem()\n model = prob.model\n\n model.add_subsystem('comp', CompAtan(), promotes_inputs=['x'])\n\n prob.setup()\n\n prob.set_val('x', -100.0)\n\n # Initial value for the state:\n prob.set_val('comp.y', 12.0)\n\n # You can change the om.NewtonSolver settings after setup is called\n newton = prob.model.nonlinear_solver = om.NewtonSolver()\n prob.model.linear_solver = om.DirectSolver()\n newton.options['iprint'] = 2\n newton.options['rtol'] = 1e-8\n newton.options['solve_subsystems'] = True\n\n newton.linesearch = om.BoundsEnforceLS()\n newton.linesearch.options['iprint'] = 2\n\n prob.run_model()\n\n assert_near_equal(prob.get_val('comp.y'), 19.68734033, 1e-6)\n\n def test_feature_boundsenforcels_basic(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1))))\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays())\n top.model.connect('px.x', 'comp.x')\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS()\n\n top.setup()\n\n # Test lower bounds: should go to the lower bound and stall\n top['px.x'] = 2.0\n top['comp.y'] = 0.\n top['comp.z'] = 1.6\n top.run_model()\n\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [1.5], 1e-8)\n\n def test_feature_armijogoldsteinls_basic(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS()\n\n top.setup()\n top.set_val('x', np.array([2., 2, 2]).reshape(3, 1))\n # Test lower bounds: should go to the lower bound and stall\n top.set_val('comp.y', 0.)\n top.set_val('comp.z', 1.6)\n top.run_model()\n\n for ind in range(3):\n assert_near_equal(top.get_val('comp.z', indices=ind), [1.5], 1e-8)\n\n def test_feature_boundscheck_basic(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS()\n\n top.setup()\n top.set_val('x', np.array([2., 2, 2]).reshape(3, 1))\n\n # Test lower bounds: should go to the lower bound and stall\n top.set_val('comp.y', 0.)\n top.set_val('comp.z', 1.6)\n top.run_model()\n\n for ind in range(3):\n assert_near_equal(top.get_val('comp.z', indices=ind), [1.5], 1e-8)\n\n def test_feature_boundscheck_vector(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='vector')\n\n top.setup()\n top.set_val('x', np.array([2., 2, 2]).reshape(3, 1))\n\n # Test lower bounds: should go to the lower bound and stall\n top.set_val('comp.y', 0.)\n top.set_val('comp.z', 1.6)\n top.run_model()\n\n for ind in range(3):\n assert_near_equal(top.get_val('comp.z', indices=ind), [1.5], 1e-8)\n\n def test_feature_boundscheck_wall(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='wall')\n\n top.setup()\n top.set_val('x', np.array([0.5, 0.5, 0.5]).reshape(3, 1))\n\n # Test upper bounds: should go to the upper bound and stall\n top.set_val('comp.y', 0.)\n top.set_val('comp.z', 2.4)\n top.run_model()\n\n assert_near_equal(top.get_val('comp.z', indices=0), [2.6], 1e-8)\n assert_near_equal(top.get_val('comp.z', indices=1), [2.5], 1e-8)\n assert_near_equal(top.get_val('comp.z', indices=2), [2.65], 1e-8)\n\n def test_feature_boundscheck_scalar(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='scalar')\n\n top.setup()\n top.set_val('x', np.array([2., 2, 2]).reshape(3, 1))\n top.run_model()\n\n # Test lower bounds: should stop just short of the lower bound\n top.set_val('comp.y', 0.)\n top.set_val('comp.z', 1.6)\n top.run_model()\n\n def test_feature_print_bound_enforce(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n\n newt = top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 2\n top.model.linear_solver = om.ScipyKrylov()\n\n ls = newt.linesearch = om.BoundsEnforceLS(bound_enforcement='vector')\n ls.options['print_bound_enforce'] = True\n\n top.set_solver_print(level=2)\n\n\n top.setup()\n top.set_val('x', np.array([2., 2, 2]).reshape(3, 1))\n\n # Test lower bounds: should go to the lower bound and stall\n top.set_val('comp.y', 0.)\n top.set_val('comp.z', 1.6)\n top.run_model()\n\n for ind in range(3):\n assert_near_equal(top.get_val('comp.z', indices=ind), [1.5], 1e-8)\n\n def test_feature_armijo_boundscheck_vector(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector')\n\n top.setup()\n\n top.set_val('x', np.array([2., 2, 2]).reshape(3, 1))\n\n # Test lower bounds: should go to the lower bound and stall\n top.set_val('comp.y', 0.)\n top.set_val('comp.z', 1.6)\n top.run_model()\n\n for ind in range(3):\n assert_near_equal(top.get_val('comp.z', indices=ind), [1.5], 1e-8)\n\n def test_feature_armijo_boundscheck_wall(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='wall')\n\n top.setup()\n\n top.set_val('x', np.array([0.5, 0.5, 0.5]).reshape(3, 1))\n\n # Test upper bounds: should go to the upper bound and stall\n top.set_val('comp.y', 0.)\n top.set_val('comp.z', 2.4)\n top.run_model()\n\n assert_near_equal(top.get_val('comp.z', indices=0), [2.6], 1e-8)\n assert_near_equal(top.get_val('comp.z', indices=1), [2.5], 1e-8)\n assert_near_equal(top.get_val('comp.z', indices=2), [2.65], 1e-8)\n\n def test_feature_armijo_boundscheck_scalar(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='scalar')\n\n top.setup()\n top.set_val('x', np.array([2., 2, 2]).reshape(3, 1))\n top.run_model()\n\n # Test lower bounds: should stop just short of the lower bound\n top.set_val('comp.y', 0.)\n top.set_val('comp.z', 1.6)\n top.run_model()\n\n def test_feature_armijo_print_bound_enforce(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1))))\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays())\n top.model.connect('px.x', 'comp.x')\n\n newt = top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 2\n top.model.linear_solver = om.ScipyKrylov()\n\n ls = newt.linesearch = om.ArmijoGoldsteinLS()\n ls.options['print_bound_enforce'] = True\n\n top.set_solver_print(level=2)\n top.setup()\n\n # Test lower bounds: should go to the lower bound and stall\n top['px.x'] = 2.0\n top['comp.y'] = 0.\n top['comp.z'] = 1.6\n top.run_model()\n\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [1.5], 1e-8)\n\n def test_feature_goldstein(self):\n import numpy as np\n\n import openmdao.api as om\n from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n\n top = om.Problem()\n top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1))))\n top.model.add_subsystem('comp', ImplCompTwoStatesArrays())\n top.model.connect('px.x', 'comp.x')\n\n top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n top.model.nonlinear_solver.options['maxiter'] = 10\n top.model.linear_solver = om.ScipyKrylov()\n\n ls = top.model.nonlinear_solver.linesearch = om.ArmijoGoldsteinLS(bound_enforcement='vector')\n ls.options['method'] = 'Goldstein'\n\n top.setup()\n\n # Test lower bounds: should go to the lower bound and stall\n top['px.x'] = 2.0\n top['comp.y'] = 0.\n top['comp.z'] = 1.6\n top.run_model()\n\n for ind in range(3):\n assert_near_equal(top['comp.z'][ind], [1.5], 1e-8)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"import errno\nimport os\nimport unittest\nfrom time import time\nfrom shutil import rmtree\nfrom tempfile import mkdtemp\n\nimport numpy as np\n\nfrom openmdao.utils.general_utils import set_pyoptsparse_opt\nfrom openmdao.utils.mpi import MPI\n\nfrom openmdao.api import ExecComp, ExplicitComponent, Problem, \\\n Group, ParallelGroup, IndepVarComp, SqliteRecorder, ScipyOptimizeDriver\nfrom openmdao.utils.array_utils import evenly_distrib_idxs\nfrom openmdao.recorders.tests.sqlite_recorder_test_utils import \\\n assertDriverIterDataRecorded, assertProblemDataRecorded\nfrom openmdao.recorders.tests.recorder_test_utils import run_driver\n\nif MPI:\n from openmdao.api import PETScVector\nelse:\n PETScVector = None\n\n\nclass DistributedAdder(ExplicitComponent):\n \"\"\"\n Distributes the work of adding 10 to every item in the param vector\n \"\"\"\n\n def __init__(self, size):\n super().__init__()\n\n self.options['distributed'] = True\n\n self.local_size = self.size = size\n\n def setup(self):\n \"\"\"\n specify the local sizes of the variables and which specific indices this specific\n distributed component will handle. Indices do NOT need to be sequential or\n contiguous!\n \"\"\"\n comm = self.comm\n rank = comm.rank\n\n # NOTE: evenly_distrib_idxs is a helper function to split the array\n # up as evenly as possible\n sizes, offsets = evenly_distrib_idxs(comm.size, self.size)\n local_size, local_offset = sizes[rank], offsets[rank]\n self.local_size = local_size\n\n start = local_offset\n end = local_offset + local_size\n\n self.add_input('x', val=np.zeros(local_size, float),\n src_indices=np.arange(start, end, dtype=int))\n self.add_output('y', val=np.zeros(local_size, float))\n\n def compute(self, inputs, outputs):\n\n # NOTE: Each process will get just its local part of the vector\n # print('process {0:d}: {1}'.format(self.comm.rank, params['x'].shape))\n\n outputs['y'] = inputs['x'] + 10.\n\n\nclass Summer(ExplicitComponent):\n \"\"\"\n Aggregation component that collects all the values from the distributed\n vector addition and computes a total\n \"\"\"\n\n def __init__(self, size):\n super().__init__()\n self.size = size\n\n def setup(self):\n # NOTE: this component depends on the full y array, so OpenMDAO\n # will automatically gather all the values for it\n self.add_input('y', val=np.zeros(self.size))\n self.add_output('sum', 0.0, shape=1)\n\n def compute(self, inputs, outputs):\n outputs['sum'] = np.sum(inputs['y'])\n\n\nclass Mygroup(Group):\n\n def setup(self):\n self.add_subsystem('indep_var_comp', IndepVarComp('x'), promotes=['*'])\n self.add_subsystem('Cy', ExecComp('y=2*x'), promotes=['*'])\n self.add_subsystem('Cc', ExecComp('c=x+2'), promotes=['*'])\n\n self.add_design_var('x')\n self.add_constraint('c', lower=-3.)\n\n\[email protected](MPI and PETScVector, \"MPI and PETSc are required.\")\nclass DistributedRecorderTest(unittest.TestCase):\n\n N_PROCS = 2\n\n def setUp(self):\n self.dir = mkdtemp()\n self.filename = os.path.join(self.dir, \"sqlite_test\")\n self.recorder = SqliteRecorder(self.filename)\n self.eps = 1e-5\n\n def tearDown(self):\n try:\n rmtree(self.dir)\n except OSError as e:\n # If directory already deleted, keep going\n if e.errno not in (errno.ENOENT, errno.EACCES, errno.EPERM):\n raise e\n\n def test_distrib_record_system(self):\n prob = Problem()\n\n try:\n prob.model.add_recorder(self.recorder)\n except RuntimeError as err:\n msg = \"Group: Recording of Systems when running parallel code is not supported yet\"\n self.assertEqual(str(err), msg)\n else:\n self.fail('RuntimeError expected.')\n\n def test_distrib_record_solver(self):\n prob = Problem()\n try:\n prob.model.nonlinear_solver.add_recorder(self.recorder)\n except RuntimeError as err:\n msg = \"Recording of Solvers when running parallel code is not supported yet\"\n self.assertEqual(str(err), msg)\n else:\n self.fail('RuntimeError expected.')\n\n def test_distrib_record_driver(self):\n size = 100 # how many items in the array\n prob = Problem()\n\n prob.model.add_subsystem('des_vars', IndepVarComp('x', np.ones(size)), promotes=['x'])\n prob.model.add_subsystem('plus', DistributedAdder(size), promotes=['x', 'y'])\n prob.model.add_subsystem('summer', Summer(size), promotes=['y', 'sum'])\n prob.driver.recording_options['record_desvars'] = True\n prob.driver.recording_options['record_objectives'] = True\n prob.driver.recording_options['record_constraints'] = True\n prob.driver.recording_options['includes'] = ['y']\n prob.driver.add_recorder(self.recorder)\n\n prob.model.add_design_var('x')\n prob.model.add_objective('sum')\n\n prob.setup()\n\n prob['x'] = np.ones(size)\n\n t0, t1 = run_driver(prob)\n prob.cleanup()\n\n coordinate = [0, 'Driver', (0,)]\n\n expected_desvars = {\n \"des_vars.x\": prob['des_vars.x'],\n }\n\n expected_objectives = {\n \"summer.sum\": prob['summer.sum'],\n }\n\n expected_outputs = expected_desvars.copy()\n expected_outputs['plus.y'] = prob.get_val('plus.y', get_remote=True)\n\n if prob.comm.rank == 0:\n expected_outputs.update(expected_objectives)\n\n expected_data = ((coordinate, (t0, t1), expected_outputs, None, None),)\n assertDriverIterDataRecorded(self, expected_data, self.eps)\n\n def test_recording_remote_voi(self):\n # Create a parallel model\n model = Group()\n\n model.add_subsystem('par', ParallelGroup())\n model.par.add_subsystem('G1', Mygroup())\n model.par.add_subsystem('G2', Mygroup())\n model.connect('par.G1.y', 'Obj.y1')\n model.connect('par.G2.y', 'Obj.y2')\n\n model.add_subsystem('Obj', ExecComp('obj=y1+y2'))\n model.add_objective('Obj.obj')\n\n # Configure driver to record VOIs on both procs\n driver = ScipyOptimizeDriver(disp=False)\n\n driver.recording_options['record_desvars'] = True\n driver.recording_options['record_objectives'] = True\n driver.recording_options['record_constraints'] = True\n driver.recording_options['includes'] = ['par.G1.y', 'par.G2.y']\n\n driver.add_recorder(self.recorder)\n\n # Create problem and run driver\n prob = Problem(model, driver)\n prob.add_recorder(self.recorder)\n prob.setup(mode='fwd')\n\n t0, t1 = run_driver(prob)\n prob.record('final')\n t2 = time()\n\n prob.cleanup()\n\n # Since the test will compare the last case recorded, just check the\n # current values in the problem. This next section is about getting those values\n\n # These involve collective gathers so all ranks need to run this\n expected_outputs = driver.get_design_var_values(get_remote=True)\n expected_outputs.update(driver.get_objective_values())\n expected_outputs.update(driver.get_constraint_values())\n\n # includes for outputs are specified as promoted names but we need absolute names\n prom2abs = model._var_allprocs_prom2abs_list['output']\n abs_includes = [prom2abs[n][0] for n in prob.driver.recording_options['includes']]\n\n # Absolute path names of includes on this rank\n rrank = model.comm.rank\n rowned = model._owning_rank\n local_includes = [n for n in abs_includes if rrank == rowned[n]]\n\n # Get values for all vars on this rank\n inputs, outputs, residuals = model.get_nonlinear_vectors()\n\n # Get values for includes on this rank\n local_vars = {n: outputs[n] for n in local_includes}\n\n # Gather values for includes on all ranks\n all_vars = model.comm.gather(local_vars, root=0)\n\n if prob.comm.rank == 0:\n # Only on rank 0 do we have all the values. The all_vars variable is a list of\n # dicts from all ranks 0,1,... In this case, just ranks 0 and 1\n dct = {}\n for d in all_vars:\n dct.update(d)\n\n expected_includes = {\n 'par.G1.Cy.y': dct['par.G1.Cy.y'],\n 'par.G2.Cy.y': dct['par.G2.Cy.y'],\n }\n\n expected_outputs.update(expected_includes)\n\n coordinate = [0, 'ScipyOptimize_SLSQP', (driver.iter_count-1,)]\n\n expected_data = ((coordinate, (t0, t1), expected_outputs, None, None),)\n assertDriverIterDataRecorded(self, expected_data, self.eps)\n\n expected_data = (('final', (t1, t2), expected_outputs),)\n assertProblemDataRecorded(self, expected_data, self.eps)\n\n\nif __name__ == \"__main__\":\n from openmdao.utils.mpi import mpirun_tests\n mpirun_tests()\n"
] | [
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots"
],
[
"numpy.random.random",
"numpy.arctan",
"numpy.linspace",
"numpy.asarray",
"numpy.arange",
"numpy.random.seed",
"scipy.sparse.load_npz",
"numpy.ones",
"numpy.testing.assert_almost_equal",
"numpy.array",
"numpy.zeros"
],
[
"numpy.exp"
],
[
"numpy.array",
"numpy.zeros",
"numpy.ones"
],
[
"numpy.arange",
"numpy.zeros",
"numpy.sum",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"0.19",
"1.5",
"1.2",
"1.7",
"1.0",
"1.3",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
asaelbarilan/deepvoice3_pytorch | [
"47118312309994a4a6c17e3918355f2ace947492"
] | [
"arabic_speech_corpus.py"
] | [
"from concurrent.futures import ProcessPoolExecutor\r\nfrom functools import partial\r\nimport numpy as np\r\nimport os\r\nimport audio\r\nfrom hparams import hparams\r\n\r\n\r\ndef build_from_path(in_dir, out_dir, num_workers=1, tqdm=lambda x: x):\r\n '''Preprocesses the LJ Speech dataset from a given input path into a given output directory.\r\n\r\n Args:\r\n in_dir: The directory where you have downloaded the LJ Speech dataset\r\n out_dir: The directory to write the output into\r\n num_workers: Optional number of worker processes to parallelize across\r\n tqdm: You can optionally pass tqdm to get a nice progress bar\r\n\r\n Returns:\r\n A list of tuples describing the training examples. This should be written to train.txt\r\n '''\r\n\r\n # We use ProcessPoolExecutor to parallize across processes. This is just an optimization and you\r\n # can omit it and just call _process_utterance on each input if you want.\r\n executor = ProcessPoolExecutor(max_workers=num_workers)\r\n futures = []\r\n index = 1\r\n with open(os.path.join(in_dir, 'metadata.csv'), encoding='utf-8') as f:\r\n for line in f:\r\n parts = line.strip().split(',')\r\n wav_path = os.path.join(in_dir, 'wav', parts[0])\r\n text = parts[1]\r\n if len(text) < hparams.min_text:\r\n continue\r\n futures.append(executor.submit(\r\n partial(_process_utterance, out_dir, index, wav_path, text)))\r\n index += 1\r\n return [future.result() for future in tqdm(futures)]\r\n\r\n\r\ndef _process_utterance(out_dir, index, wav_path, text):\r\n '''Preprocesses a single utterance audio/text pair.\r\n\r\n This writes the mel and linear scale spectrograms to disk and returns a tuple to write\r\n to the train.txt file.\r\n\r\n Args:\r\n out_dir: The directory to write the spectrograms into\r\n index: The numeric index to use in the spectrogram filenames.\r\n wav_path: Path to the audio file containing the speech input\r\n text: The text spoken in the input audio file\r\n\r\n Returns:\r\n A (spectrogram_filename, mel_filename, n_frames, text) tuple to write to train.txt\r\n '''\r\n\r\n # Load the audio to a numpy array:\r\n wav = audio.load_wav(wav_path)\r\n\r\n if hparams.rescaling:\r\n wav = wav / np.abs(wav).max() * hparams.rescaling_max\r\n\r\n # Compute the linear-scale spectrogram from the wav:\r\n spectrogram = audio.spectrogram(wav).astype(np.float32)\r\n n_frames = spectrogram.shape[1]\r\n\r\n # Compute a mel-scale spectrogram from the wav:\r\n mel_spectrogram = audio.melspectrogram(wav).astype(np.float32)\r\n\r\n # Write the spectrograms to disk:\r\n spectrogram_filename = 'ljspeech-spec-%05d.npy' % index\r\n mel_filename = 'ljspeech-mel-%05d.npy' % index\r\n np.save(os.path.join(out_dir, spectrogram_filename), spectrogram.T, allow_pickle=False)\r\n np.save(os.path.join(out_dir, mel_filename), mel_spectrogram.T, allow_pickle=False)\r\n\r\n # Return a tuple describing this training example:\r\n return (spectrogram_filename, mel_filename, n_frames, text)\r\n"
] | [
[
"numpy.abs"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
amnaabbassi/shapash | [
"6c867c8b1724f2737369557f8db056cb0027999b",
"6c867c8b1724f2737369557f8db056cb0027999b"
] | [
"tests/unit_tests/utils/test_explanation_metrics.py",
"tests/integration_tests/test_report_generation.py"
] | [
"import unittest\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nfrom shapash.utils.explanation_metrics import _df_to_array, \\\n _compute_distance, _compute_similarities, _get_radius, find_neighbors, \\\n shap_neighbors, get_min_nb_features, get_distance\n\n\nclass TestExplanationMetrics(unittest.TestCase):\n\n def test_df_to_array(self):\n df = pd.DataFrame([1, 2, 3], columns=[\"col\"])\n expected = np.array([[1], [2], [3]])\n t = _df_to_array(df)\n assert np.array_equal(t, expected)\n\n def test_compute_distance(self):\n x1 = np.array([1, 0, 1])\n x2 = np.array([0, 0, 1])\n mean_vector = np.array([2, 1, 3])\n epsilon = 0\n expected = 0.5\n t = _compute_distance(x1, x2, mean_vector, epsilon)\n assert t == expected\n\n def test_compute_similarities(self):\n df = pd.DataFrame(np.random.randint(0, 100, size=(5, 4)), columns=list('ABCD')).values\n instance = df[0, :]\n expected_len = 5\n expected_dist = 0\n t = _compute_similarities(instance, df)\n assert len(t) == expected_len\n assert t[0] == expected_dist\n\n def test_get_radius(self):\n df = pd.DataFrame(np.random.randint(0, 100, size=(5, 4)), columns=list('ABCD')).values\n t = _get_radius(df, n_neighbors=3)\n assert t > 0\n\n def test_find_neighbors(self):\n df = pd.DataFrame(np.random.randint(0, 100, size=(15, 4)), columns=list('ABCD'))\n selection = [1, 3]\n X = df.iloc[:, :-1]\n y = df.iloc[:, -1]\n model = LinearRegression().fit(X, y)\n mode = \"regression\"\n t = find_neighbors(selection, X, model, mode)\n assert len(t) == len(selection)\n assert t[0].shape[1] == X.shape[1] + 2\n\n def test_shap_neighbors(self):\n df = pd.DataFrame(np.random.randint(0, 100, size=(15, 4)), columns=list('ABCD'))\n contrib = pd.DataFrame(np.random.randint(10, size=(15, 4)), columns=list('EFGH'))\n instance = df.values[:2, :]\n extra_cols = np.repeat(np.array([0, 0]), 2).reshape(2, -1)\n instance = np.append(instance, extra_cols, axis=1)\n mode = \"regression\"\n t = shap_neighbors(instance, df, contrib, mode)\n assert t[0].shape == instance[:, :-2].shape\n assert t[1].shape == (len(df.columns),)\n assert t[2].shape == (len(df.columns),)\n\n def test_get_min_nb_features(self):\n contrib = pd.DataFrame(np.random.randint(10, size=(15, 4)), columns=list('ABCD'))\n selection = [1, 3]\n distance = 0.1\n mode = \"regression\"\n t = get_min_nb_features(selection, contrib, mode, distance)\n assert type(t) == list\n assert all(isinstance(x, int) for x in t)\n assert len(t) == len(selection)\n\n def test_get_distance(self):\n contrib = pd.DataFrame(np.random.randint(10, size=(15, 4)), columns=list('ABCD'))\n selection = [1, 3]\n nb_features = 2\n mode = \"regression\"\n t = get_distance(selection, contrib, mode, nb_features)\n assert type(t) == np.ndarray\n assert all(isinstance(x, float) for x in t)\n assert len(t) == len(selection)\n",
"import unittest\nimport tempfile\nimport shutil\nimport numpy as np\nimport os\nimport pandas as pd\nimport catboost as cb\n\nfrom shapash.explainer.smart_explainer import SmartExplainer\nfrom shapash.report.generation import execute_report, export_and_save_report\n\ncurrent_path = os.path.dirname(os.path.abspath(__file__))\n\n\nclass TestGeneration(unittest.TestCase):\n\n def setUp(self):\n df = pd.DataFrame(range(0, 21), columns=['id'])\n df['y'] = df['id'].apply(lambda x: 1 if x < 10 else 0)\n df['x1'] = np.random.randint(1, 123, df.shape[0])\n df['x2'] = np.random.randint(1, 3, df.shape[0])\n df = df.set_index('id')\n clf = cb.CatBoostClassifier(n_estimators=1).fit(df[['x1', 'x2']], df['y'])\n self.xpl = SmartExplainer()\n self.xpl.compile(model=clf, x=df[['x1', 'x2']])\n self.df = df\n\n def test_execute_report_1(self):\n tmp_dir_path = tempfile.mkdtemp()\n\n execute_report(\n working_dir=tmp_dir_path,\n explainer=self.xpl,\n project_info_file=os.path.join(current_path, '../data/metadata.yaml'),\n config=None,\n notebook_path=None\n )\n assert os.path.exists(os.path.join(tmp_dir_path, 'smart_explainer.pickle'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'base_report.ipynb'))\n\n shutil.rmtree(tmp_dir_path)\n\n def test_execute_report_2(self):\n tmp_dir_path = tempfile.mkdtemp()\n\n execute_report(\n working_dir=tmp_dir_path,\n explainer=self.xpl,\n project_info_file=os.path.join(current_path, '../data/metadata.yaml'),\n x_train=self.df[['x1', 'x2']],\n config=None,\n notebook_path=None\n )\n assert os.path.exists(os.path.join(tmp_dir_path, 'x_train.csv'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'smart_explainer.pickle'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'base_report.ipynb'))\n\n shutil.rmtree(tmp_dir_path)\n\n def test_execute_report_3(self):\n tmp_dir_path = tempfile.mkdtemp()\n\n execute_report(\n working_dir=tmp_dir_path,\n explainer=self.xpl,\n project_info_file=os.path.join(current_path, '../data/metadata.yaml'),\n x_train=self.df[['x1', 'x2']],\n y_test=self.df['y'],\n config=None,\n notebook_path=None\n )\n assert os.path.exists(os.path.join(tmp_dir_path, 'x_train.csv'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'y_test.csv'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'smart_explainer.pickle'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'base_report.ipynb'))\n\n shutil.rmtree(tmp_dir_path)\n\n def test_execute_report_4(self):\n tmp_dir_path = tempfile.mkdtemp()\n\n execute_report(\n working_dir=tmp_dir_path,\n explainer=self.xpl,\n project_info_file=os.path.join(current_path, '../data/metadata.yaml'),\n x_train=self.df[['x1', 'x2']],\n y_train=self.df['y'],\n y_test=self.df['y'],\n config=None,\n notebook_path=None\n )\n assert os.path.exists(os.path.join(tmp_dir_path, 'x_train.csv'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'y_test.csv'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'y_train.csv'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'smart_explainer.pickle'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'base_report.ipynb'))\n\n shutil.rmtree(tmp_dir_path)\n\n def test_execute_report_5(self):\n tmp_dir_path = tempfile.mkdtemp()\n\n self.xpl.palette_name = \"eurybia\"\n execute_report(\n working_dir=tmp_dir_path,\n explainer=self.xpl,\n project_info_file=os.path.join(current_path, '../data/metadata.yaml'),\n x_train=self.df[['x1', 'x2']],\n y_train=self.df['y'],\n y_test=self.df['y'],\n notebook_path=None\n )\n self.xpl.palette_name = \"default\"\n assert os.path.exists(os.path.join(tmp_dir_path, 'x_train.csv'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'y_test.csv'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'y_train.csv'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'smart_explainer.pickle'))\n assert os.path.exists(os.path.join(tmp_dir_path, 'base_report.ipynb'))\n\n shutil.rmtree(tmp_dir_path)\n\n def test_export_and_save_report_1(self):\n tmp_dir_path = tempfile.mkdtemp()\n\n execute_report(\n working_dir=tmp_dir_path,\n explainer=self.xpl,\n project_info_file=os.path.join(current_path, '../data/metadata.yaml'),\n )\n\n outfile = os.path.join(tmp_dir_path, 'report.html')\n export_and_save_report(working_dir=tmp_dir_path, output_file=outfile)\n assert os.path.exists(outfile)\n shutil.rmtree(tmp_dir_path)\n"
] | [
[
"numpy.array_equal",
"pandas.DataFrame",
"numpy.append",
"sklearn.linear_model.LinearRegression",
"numpy.array",
"numpy.random.randint"
],
[
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
roizhv22/IML.HUJI | [
"b6efdf4ca21ef5cf33da222d74330a19e2177527",
"b6efdf4ca21ef5cf33da222d74330a19e2177527"
] | [
"exercises/ex4/sub/decision_stump.py",
"exercises/ex3/sub/loss_functions.py"
] | [
"from __future__ import annotations\nfrom typing import Tuple, NoReturn\n\nimport IMLearn.metrics\nfrom ...base import BaseEstimator\nimport numpy as np\nfrom itertools import product\n\n\nclass DecisionStump(BaseEstimator):\n \"\"\"\n A decision stump classifier for {-1,1} labels according to the CART algorithm\n\n Attributes\n ----------\n self.threshold_ : float\n The threshold by which the data is split\n\n self.j_ : int\n The index of the feature by which to split the data\n\n self.sign_: int\n The label to predict for samples where the value of the j'th\n feature is about the threshold\n \"\"\"\n\n def __init__(self) -> DecisionStump:\n \"\"\"\n Instantiate a Decision stump classifier\n \"\"\"\n super().__init__()\n self.threshold_, self.j_, self.sign_ = None, None, None\n\n def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn:\n \"\"\"\n fits a decision stump to the given data\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Input data to fit an estimator for\n\n y : ndarray of shape (n_samples, )\n Responses of input data to fit to\n \"\"\"\n err = np.inf\n for j in range(len(X[0])):\n feature = X[:, j]\n for sign in (-1, 1):\n thr, tre_err = self._find_threshold(feature, y, sign)\n if tre_err < err:\n err, self.j_, self.threshold_, self.sign_ = tre_err, j, \\\n thr, sign\n\n def _predict(self, X: np.ndarray) -> np.ndarray:\n \"\"\"\n Predict responses for given samples using fitted estimator\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Input data to predict responses for\n\n Returns\n -------\n responses : ndarray of shape (n_samples, )\n Predicted responses of given samples\n\n Notes\n -----\n Feature values strictly below threshold are predicted as `-sign`\n whereas values which equal\n to or above the threshold are predicted as `sign`\n \"\"\"\n return np.where(X[:, self.j_] < self.threshold_, self.sign_ * -1,\n self.sign_)\n\n def _find_threshold(self, values: np.ndarray, labels: np.ndarray,\n sign: int) -> Tuple[float, float]:\n \"\"\"\n Given a feature vector and labels, find a threshold by which to perform a split\n The threshold is found according to the value minimizing the misclassification\n error along this feature\n\n Parameters\n ----------\n values: ndarray of shape (n_samples,)\n A feature vector to find a splitting threshold for\n\n labels: ndarray of shape (n_samples,)\n The labels to compare against\n\n sign: int\n Predicted label assigned to values equal to or above threshold\n\n Returns\n -------\n thr: float\n Threshold by which to perform split\n\n thr_err: float between 0 and 1\n Misclassificaiton error of returned threshold\n\n Notes\n -----\n For every tested threshold, values strictly below threshold are\n predicted as `-sign` whereas values\n which equal to or above the threshold are predicted as `sign`\n \"\"\"\n cut, err = 0, 1\n sort_label = labels[np.argsort(values)]\n sort_feature = np.sort(values)\n n_samples = values.shape[0]\n ones = np.ones(n_samples) * sign\n for i in range(n_samples):\n n_e = np.sum(\n np.where(np.sign(ones) != np.sign(sort_label),\n np.abs(sort_label), 0)) / \\\n n_samples\n if n_e < err:\n cut, err = sort_feature[i], n_e\n ones[i] *= -1 # update the threshold placement.\n\n return cut, err\n\n\n def _loss(self, X: np.ndarray, y: np.ndarray) -> float:\n \"\"\"\n Evaluate performance under misclassification loss function\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Test samples\n\n y : ndarray of shape (n_samples, )\n True labels of test samples\n\n Returns\n -------\n loss : float\n Performance under missclassification loss function\n \"\"\"\n from ...metrics.loss_functions import misclassification_error\n return misclassification_error(y, self.predict(X))\n",
"import numpy as np\n\n\ndef mean_square_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n \"\"\"\n Calculate MSE loss\n\n Parameters\n ----------\n y_true: ndarray of shape (n_samples, )\n True response values\n y_pred: ndarray of shape (n_samples, )\n Predicted response values\n\n Returns\n -------\n MSE of given predictions\n \"\"\"\n return float(np.mean(np.square(np.subtract(y_pred, y_true))))\n\n\ndef misclassification_error(y_true: np.ndarray, y_pred: np.ndarray,\n normalize: bool = True) -> float:\n \"\"\"\n Calculate misclassification loss\n\n Parameters\n ----------\n y_true: ndarray of shape (n_samples, )\n True response values\n y_pred: ndarray of shape (n_samples, )\n Predicted response values\n normalize: bool, default = True\n Normalize by number of samples or not\n\n Returns\n -------\n Misclassification of given predictions\n \"\"\"\n n = len(y_true)\n counter = 0\n for i in range(len(y_true)):\n if y_true[i] * y_pred[i] < 0:\n counter += 1\n if normalize:\n return counter / n\n return counter\n\n\ndef accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n \"\"\"\n Calculate accuracy of given predictions\n\n Parameters\n ----------\n y_true: ndarray of shape (n_samples, )\n True response values\n y_pred: ndarray of shape (n_samples, )\n Predicted response values\n\n Returns\n -------\n Accuracy of given predictions\n \"\"\"\n correct = 0\n for i in range(len(y_true)):\n if y_true[i] == y_pred[i]:\n correct += 1\n return correct/len(y_true)\n\n\ndef cross_entropy(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n \"\"\"\n Calculate the cross entropy of given predictions\n\n Parameters\n ----------\n y_true: ndarray of shape (n_samples, )\n True response values\n y_pred: ndarray of shape (n_samples, )\n Predicted response values\n\n Returns\n -------\n Cross entropy of given predictions\n \"\"\"\n raise NotImplementedError()\n"
] | [
[
"numpy.abs",
"numpy.sort",
"numpy.ones",
"numpy.sign",
"numpy.argsort",
"numpy.where"
],
[
"numpy.subtract"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gist-ailab/FSCE | [
"94ba3f4737d5e40af795db49b8c6914526c912b6",
"94ba3f4737d5e40af795db49b8c6914526c912b6",
"94ba3f4737d5e40af795db49b8c6914526c912b6"
] | [
"fsdet/modeling/meta_arch/rcnn.py",
"demo/predictor.py",
"fsdet/checkpoint/c2_model_loading.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport logging\nimport numpy as np\nimport torch\nfrom torch import nn\n\nfrom fsdet.structures import ImageList\nfrom fsdet.utils.logger import log_first_n\n\nfrom ..backbone import build_backbone\nfrom ..postprocessing import detector_postprocess\nfrom ..proposal_generator import build_proposal_generator\nfrom ..roi_heads import build_roi_heads\nfrom .build import META_ARCH_REGISTRY\n\nfrom fsdet.utils.events import get_event_storage\nfrom fsdet.utils.visualizer import Visualizer\nfrom fsdet.data.detection_utils import convert_image_to_rgb\nfrom fsdet.modeling.utils import concat_all_gathered\n\n__all__ = [\"GeneralizedRCNN\", \"ProposalNetwork\"]\n\n\n@META_ARCH_REGISTRY.register()\nclass GeneralizedRCNN(nn.Module):\n \"\"\"\n Generalized R-CNN. Any models that contains the following three components:\n 1. Per-image feature extraction (aka backbone)\n 2. Region proposal generation\n 3. Per-region feature extraction and prediction\n \"\"\"\n\n def __init__(self, cfg):\n super().__init__()\n # fmt on #\n self.input_format = cfg.INPUT.FORMAT\n self.vis_period = cfg.INPUT.VIS_PERIOD\n self.moco = cfg.MODEL.MOCO.ENABLED\n # fmt off #\n\n self.device = torch.device(cfg.MODEL.DEVICE)\n\n self.backbone = build_backbone(cfg)\n self.proposal_generator = build_proposal_generator(cfg, self.backbone.output_shape())\n self.roi_heads = build_roi_heads(cfg, self.backbone.output_shape()) # specify roi_heads name in yaml\n if self.moco:\n if self.roi_heads.__class__ == 'MoCoROIHeadsV1':\n self.roi_heads._moco_encoder_init(cfg)\n\n elif self.roi_heads.__class__ == 'MoCoROIHeadsV3':\n self.backbone_k = build_backbone(cfg)\n self.proposal_generator_k = build_proposal_generator(cfg, self.backbone_k.output_shape())\n self.roi_heads_k = build_roi_heads(cfg, self.backbone_k.output_shape())\n\n self.roi_heads._moco_encoder_init(cfg,\n self.backbone_k, self.proposal_generator_k, self.roi_heads_k)\n else:\n assert 'MoCo' not in cfg.MODEL.ROI_HEADS.NAME\n\n assert len(cfg.MODEL.PIXEL_MEAN) == len(cfg.MODEL.PIXEL_STD)\n num_channels = len(cfg.MODEL.PIXEL_MEAN)\n pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(num_channels, 1, 1)\n pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(num_channels, 1, 1)\n self.normalizer = lambda x: (x - pixel_mean) / pixel_std\n\n self.to(self.device)\n\n # s1 = 0\n # s2 = 0\n # for model in [self.backbone.fpn_lateral2, self.backbone.fpn_lateral3, self.backbone.fpn_lateral4, self.backbone.fpn_lateral5]:\n # s1 += sum(p.numel() for p in model.parameters())\n # for model in [self.backbone.fpn_output2, self.backbone.fpn_output3, self.backbone.fpn_output4, self.backbone.fpn_output5]:\n # s2 += sum(p.numel() for p in model.parameters())\n # print('FPN',s1, s2)\n\n if cfg.MODEL.BACKBONE.FREEZE:\n for p in self.backbone.parameters():\n p.requires_grad = False\n print('froze backbone parameters')\n\n if cfg.MODEL.BACKBONE.FREEZE_P5:\n for connection in [self.backbone.fpn_lateral5, self.backbone.fpn_output5]:\n for p in connection.parameters():\n p.requires_grad = False\n print('frozen P5 in FPN')\n\n\n if cfg.MODEL.PROPOSAL_GENERATOR.FREEZE:\n for p in self.proposal_generator.parameters():\n p.requires_grad = False\n print('froze proposal generator parameters')\n\n if cfg.MODEL.ROI_HEADS.FREEZE_FEAT:\n for p in self.roi_heads.box_head.parameters():\n p.requires_grad = False\n print('froze roi_box_head parameters')\n\n if cfg.MODEL.ROI_HEADS.UNFREEZE_FC2:\n for p in self.roi_heads.box_head.fc2.parameters():\n p.requires_grad = True\n print('unfreeze fc2 in roi head')\n\n # we do not ever need to use this in our works.\n if cfg.MODEL.ROI_HEADS.UNFREEZE_FC1:\n for p in self.roi_heads.box_head.fc1.parameters():\n p.requires_grad = True\n print('unfreeze fc1 in roi head')\n print('-------- Using Roi Head: {}---------\\n'.format(cfg.MODEL.ROI_HEADS.NAME))\n\n\n def forward(self, batched_inputs):\n \"\"\"\n Args:\n batched_inputs: a list, batched outputs of :class:`DatasetMapper` .\n Each item in the list contains the inputs for one image.\n For now, each item in the list is a dict that contains:\n\n * image: Tensor, image in (C, H, W) format.\n * instances (optional): groundtruth :class:`Instances`\n * proposals (optional): :class:`Instances`, precomputed proposals.\n\n Other information that's included in the original dicts, such as:\n\n * \"height\", \"width\" (int): the output resolution of the model, used in inference.\n See :meth:`postprocess` for details.\n\n Returns:\n list[dict]:\n Each dict is the output for one input image.\n The dict contains one key \"instances\" whose value is a :class:`Instances`.\n The :class:`Instances` object has the following keys:\n \"pred_boxes\", \"pred_classes\", \"scores\"\n \"\"\"\n if not self.training:\n return self.inference(batched_inputs)\n\n # backbone FPN\n images = self.preprocess_image(batched_inputs)\n features = self.backbone(images.tensor) # List of L, FPN features\n\n # RPN\n if \"instances\" in batched_inputs[0]:\n gt_instances = [x[\"instances\"].to(self.device) for x in batched_inputs] # List of N\n else:\n gt_instances = None\n\n if self.proposal_generator:\n proposals, proposal_losses = self.proposal_generator(images, features, gt_instances)\n # proposals is the output of find_top_rpn_proposals(), i.e., post_nms_top_K\n else:\n assert \"proposals\" in batched_inputs[0]\n proposals = [x[\"proposals\"].to(self.device) for x in batched_inputs]\n proposal_losses = {}\n\n # tensorboard visualize, visualize top-20 RPN proposals with largest objectness\n if self.vis_period > 0:\n storage = get_event_storage()\n if storage.iter % self.vis_period == 0:\n self.visualize_training(batched_inputs, proposals)\n\n if self.moco and self.roi_heads.__class__ == 'MoCoROIHeadsV2':\n self.roi_heads.gt_instances = gt_instances\n # RoI\n # ROI inputs are post_nms_top_k proposals.\n # detector_losses includes Contrast Loss, 和业务层的 cls loss, and reg loss\n _, detector_losses = self.roi_heads(images, features, proposals, gt_instances)\n\n losses = {}\n losses.update(detector_losses)\n losses.update(proposal_losses)\n return losses\n\n def visualize_training(self, batched_inputs, proposals):\n \"\"\"\n A function used to visualize images and proposals. It shows ground truth\n bounding boxes on the original image and up to 20 top-scoring predicted\n object proposals on the original image. Users can implement different\n visualization functions for different models.\n Args:\n batched_inputs (list): a list that contains input to the model.\n proposals (list): a list that contains predicted proposals. Both\n batched_inputs and proposals should have the same length.\n \"\"\"\n storage = get_event_storage()\n max_vis_prop = 20\n\n for input, prop in zip(batched_inputs, proposals):\n img = input[\"image\"]\n img = convert_image_to_rgb(img.permute(1, 2, 0), self.input_format)\n v_gt = Visualizer(img, None)\n v_gt = v_gt.overlay_instances(boxes=input[\"instances\"].gt_boxes)\n anno_img = v_gt.get_image()\n box_size = min(len(prop.proposal_boxes), max_vis_prop)\n v_pred = Visualizer(img, None)\n v_pred = v_pred.overlay_instances(\n boxes=prop.proposal_boxes[0:box_size].tensor.cpu().numpy()\n )\n prop_img = v_pred.get_image()\n vis_img = np.concatenate((anno_img, prop_img), axis=1)\n vis_img = vis_img.transpose(2, 0, 1)\n vis_name = \"Left: GT bounding boxes; Right: Predicted proposals\"\n storage.put_image(vis_name, vis_img)\n break # only visualize one image in a batch\n\n def inference(self, batched_inputs, detected_instances=None, do_postprocess=True):\n \"\"\"\n Run inference on the given inputs.\n\n Args:\n batched_inputs (list[dict]): same as in :meth:`forward`\n detected_instances (None or list[Instances]): if not None, it\n contains an `Instances` object per image. The `Instances`\n object contains \"pred_boxes\" and \"pred_classes\" which are\n known boxes in the image.\n The inference will then skip the detection of bounding boxes,\n and only predict other per-ROI outputs.\n do_postprocess (bool): whether to apply post-processing on the outputs.\n\n Returns:\n same as in :meth:`forward`.\n \"\"\"\n assert not self.training\n\n images = self.preprocess_image(batched_inputs)\n features = self.backbone(images.tensor)\n\n if detected_instances is None:\n if self.proposal_generator:\n proposals, _ = self.proposal_generator(images, features, None)\n else:\n assert \"proposals\" in batched_inputs[0]\n proposals = [x[\"proposals\"].to(self.device) for x in batched_inputs]\n\n results, _ = self.roi_heads(images, features, proposals, None)\n else:\n detected_instances = [x.to(self.device) for x in detected_instances]\n results = self.roi_heads.forward_with_given_boxes(features, detected_instances)\n\n if do_postprocess:\n processed_results = []\n for results_per_image, input_per_image, image_size in zip(\n results, batched_inputs, images.image_sizes\n ):\n height = input_per_image.get(\"height\", image_size[0])\n width = input_per_image.get(\"width\", image_size[1])\n r = detector_postprocess(results_per_image, height, width)\n processed_results.append({\"instances\": r})\n return processed_results\n else:\n return results\n\n def preprocess_image(self, batched_inputs):\n \"\"\"\n Normalize, pad and batch the input images.\n \"\"\"\n images = [x[\"image\"].to(self.device) for x in batched_inputs]\n images = [self.normalizer(x) for x in images]\n images = ImageList.from_tensors(images, self.backbone.size_divisibility)\n return images\n\n\n@META_ARCH_REGISTRY.register()\nclass ProposalNetwork(nn.Module):\n def __init__(self, cfg):\n super().__init__()\n self.device = torch.device(cfg.MODEL.DEVICE)\n\n self.backbone = build_backbone(cfg)\n self.proposal_generator = build_proposal_generator(cfg, self.backbone.output_shape())\n\n pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(-1, 1, 1)\n pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(-1, 1, 1)\n self.normalizer = lambda x: (x - pixel_mean) / pixel_std\n self.to(self.device)\n\n def forward(self, batched_inputs):\n \"\"\"\n Args:\n Same as in :class:`GeneralizedRCNN.forward`\n\n Returns:\n list[dict]: Each dict is the output for one input image.\n The dict contains one key \"proposals\" whose value is a\n :class:`Instances` with keys \"proposal_boxes\" and \"objectness_logits\".\n \"\"\"\n images = [x[\"image\"].to(self.device) for x in batched_inputs]\n images = [self.normalizer(x) for x in images]\n images = ImageList.from_tensors(images, self.backbone.size_divisibility)\n features = self.backbone(images.tensor)\n\n if \"instances\" in batched_inputs[0]:\n gt_instances = [x[\"instances\"].to(self.device) for x in batched_inputs]\n elif \"targets\" in batched_inputs[0]:\n log_first_n(\n logging.WARN, \"'targets' in the model inputs is now renamed to 'instances'!\", n=10\n )\n gt_instances = [x[\"targets\"].to(self.device) for x in batched_inputs]\n else:\n gt_instances = None\n proposals, proposal_losses = self.proposal_generator(images, features, gt_instances)\n # In training, the proposals are not useful at all but we generate them anyway.\n # This makes RPN-only models about 5% slower.\n if self.training:\n return proposal_losses\n\n processed_results = []\n for results_per_image, input_per_image, image_size in zip(\n proposals, batched_inputs, images.image_sizes\n ):\n height = input_per_image.get(\"height\", image_size[0])\n width = input_per_image.get(\"width\", image_size[1])\n # resize the raw outputs of an R-CNN detector to produce outputs according to the desired output resolution.\n r = detector_postprocess(results_per_image, height, width)\n processed_results.append({\"proposals\": r})\n return processed_results\n",
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport atexit\nimport bisect\nimport multiprocessing as mp\nfrom collections import deque\nimport cv2\nimport torch\n\nfrom fsdet.data import MetadataCatalog\nfrom fsdet.engine.defaults import DefaultPredictor\nfrom fsdet.utils.video_visualizer import VideoVisualizer\nfrom fsdet.utils.visualizer import ColorMode, Visualizer\n\n\nclass VisualizationDemo(object):\n def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False):\n \"\"\"\n Args:\n cfg (CfgNode):\n instance_mode (ColorMode):\n parallel (bool): whether to run the model in different processes from visualization.\n Useful since the visualization logic can be slow.\n \"\"\"\n self.metadata = MetadataCatalog.get(\n cfg.DATASETS.TEST[0] if len(cfg.DATASETS.TEST) else \"__unused\"\n )\n self.cpu_device = torch.device(\"cpu\")\n self.instance_mode = instance_mode\n\n self.parallel = parallel\n if parallel:\n num_gpu = torch.cuda.device_count()\n self.predictor = AsyncPredictor(cfg, num_gpus=num_gpu)\n else:\n self.predictor = DefaultPredictor(cfg)\n\n def run_on_image(self, image):\n \"\"\"\n Args:\n image (np.ndarray): an image of shape (H, W, C) (in BGR order).\n This is the format used by OpenCV.\n Returns:\n predictions (dict): the output of the model.\n vis_output (VisImage): the visualized image output.\n \"\"\"\n vis_output = None\n predictions = self.predictor(image)\n # Convert image from OpenCV BGR format to Matplotlib RGB format.\n image = image[:, :, ::-1]\n visualizer = Visualizer(image, self.metadata, instance_mode=self.instance_mode)\n if \"instances\" in predictions:\n instances = predictions[\"instances\"].to(self.cpu_device)\n vis_output = visualizer.draw_instance_predictions(predictions=instances)\n\n return predictions, vis_output\n\n def _frame_from_video(self, video):\n while video.isOpened():\n success, frame = video.read()\n if success:\n yield frame\n else:\n break\n\n def run_on_video(self, video):\n \"\"\"\n Visualizes predictions on frames of the input video.\n Args:\n video (cv2.VideoCapture): a :class:`VideoCapture` object, whose source can be\n either a webcam or a video file.\n Yields:\n ndarray: BGR visualizations of each video frame.\n \"\"\"\n video_visualizer = VideoVisualizer(self.metadata, self.instance_mode)\n\n def process_predictions(frame, predictions):\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n if \"instances\" in predictions:\n predictions = predictions[\"instances\"].to(self.cpu_device)\n vis_frame = video_visualizer.draw_instance_predictions(frame, predictions)\n\n # Converts Matplotlib RGB format to OpenCV BGR format\n vis_frame = cv2.cvtColor(vis_frame.get_image(), cv2.COLOR_RGB2BGR)\n return vis_frame\n\n frame_gen = self._frame_from_video(video)\n if self.parallel:\n buffer_size = self.predictor.default_buffer_size\n\n frame_data = deque()\n\n for cnt, frame in enumerate(frame_gen):\n frame_data.append(frame)\n self.predictor.put(frame)\n\n if cnt >= buffer_size:\n frame = frame_data.popleft()\n predictions = self.predictor.get()\n yield process_predictions(frame, predictions)\n\n while len(frame_data):\n frame = frame_data.popleft()\n predictions = self.predictor.get()\n yield process_predictions(frame, predictions)\n else:\n for frame in frame_gen:\n yield process_predictions(frame, self.predictor(frame))\n\n\nclass AsyncPredictor:\n \"\"\"\n A predictor that runs the model asynchronously, possibly on >1 GPUs.\n Because rendering the visualization takes considerably amount of time,\n this helps improve throughput when rendering videos.\n \"\"\"\n\n class _StopToken:\n pass\n\n class _PredictWorker(mp.Process):\n def __init__(self, cfg, task_queue, result_queue):\n self.cfg = cfg\n self.task_queue = task_queue\n self.result_queue = result_queue\n super().__init__()\n\n def run(self):\n predictor = DefaultPredictor(self.cfg)\n\n while True:\n task = self.task_queue.get()\n if isinstance(task, AsyncPredictor._StopToken):\n break\n idx, data = task\n result = predictor(data)\n self.result_queue.put((idx, result))\n\n def __init__(self, cfg, num_gpus: int = 1):\n \"\"\"\n Args:\n cfg (CfgNode):\n num_gpus (int): if 0, will run on CPU\n \"\"\"\n num_workers = max(num_gpus, 1)\n self.task_queue = mp.Queue(maxsize=num_workers * 3)\n self.result_queue = mp.Queue(maxsize=num_workers * 3)\n self.procs = []\n for gpuid in range(max(num_gpus, 1)):\n cfg = cfg.clone()\n cfg.defrost()\n cfg.MODEL.DEVICE = \"cuda:{}\".format(gpuid) if num_gpus > 0 else \"cpu\"\n self.procs.append(\n AsyncPredictor._PredictWorker(cfg, self.task_queue, self.result_queue)\n )\n\n self.put_idx = 0\n self.get_idx = 0\n self.result_rank = []\n self.result_data = []\n\n for p in self.procs:\n p.start()\n atexit.register(self.shutdown)\n\n def put(self, image):\n self.put_idx += 1\n self.task_queue.put((self.put_idx, image))\n\n def get(self):\n self.get_idx += 1 # the index needed for this request\n if len(self.result_rank) and self.result_rank[0] == self.get_idx:\n res = self.result_data[0]\n del self.result_data[0], self.result_rank[0]\n return res\n\n while True:\n # make sure the results are returned in the correct order\n idx, res = self.result_queue.get()\n if idx == self.get_idx:\n return res\n insert = bisect.bisect(self.result_rank, idx)\n self.result_rank.insert(insert, idx)\n self.result_data.insert(insert, res)\n\n def __len__(self):\n return self.put_idx - self.get_idx\n\n def __call__(self, image):\n self.put(image)\n return self.get()\n\n def shutdown(self):\n for _ in self.procs:\n self.task_queue.put(AsyncPredictor._StopToken())\n\n @property\n def default_buffer_size(self):\n return len(self.procs) * 5\n",
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport copy\nimport logging\nimport re\nimport torch\nfrom fvcore.common.checkpoint import (\n get_missing_parameters_message,\n get_unexpected_parameters_message,\n)\nfrom fsdet.config import global_cfg\n\n\ndef convert_basic_c2_names(original_keys):\n \"\"\"\n Apply some basic name conversion to names in C2 weights.\n It only deals with typical backbone models.\n\n Args:\n original_keys (list[str]):\n Returns:\n list[str]: The same number of strings matching those in original_keys.\n \"\"\"\n layer_keys = copy.deepcopy(original_keys)\n layer_keys = [\n {\"pred_b\": \"linear_b\", \"pred_w\": \"linear_w\"}.get(k, k) for k in layer_keys\n ] # some hard-coded mappings\n\n layer_keys = [k.replace(\"_\", \".\") for k in layer_keys]\n layer_keys = [re.sub(\"\\\\.b$\", \".bias\", k) for k in layer_keys]\n layer_keys = [re.sub(\"\\\\.w$\", \".weight\", k) for k in layer_keys]\n # Uniform both bn and gn names to \"norm\"\n layer_keys = [re.sub(\"bn\\\\.s$\", \"norm.weight\", k) for k in layer_keys]\n layer_keys = [re.sub(\"bn\\\\.bias$\", \"norm.bias\", k) for k in layer_keys]\n layer_keys = [re.sub(\"bn\\\\.rm\", \"norm.running_mean\", k) for k in layer_keys]\n layer_keys = [re.sub(\"bn\\\\.running.mean$\", \"norm.running_mean\", k) for k in layer_keys]\n layer_keys = [re.sub(\"bn\\\\.riv$\", \"norm.running_var\", k) for k in layer_keys]\n layer_keys = [re.sub(\"bn\\\\.running.var$\", \"norm.running_var\", k) for k in layer_keys]\n layer_keys = [re.sub(\"bn\\\\.gamma$\", \"norm.weight\", k) for k in layer_keys]\n layer_keys = [re.sub(\"bn\\\\.beta$\", \"norm.bias\", k) for k in layer_keys]\n layer_keys = [re.sub(\"gn\\\\.s$\", \"norm.weight\", k) for k in layer_keys]\n layer_keys = [re.sub(\"gn\\\\.bias$\", \"norm.bias\", k) for k in layer_keys]\n\n # stem\n layer_keys = [re.sub(\"^res\\\\.conv1\\\\.norm\\\\.\", \"conv1.norm.\", k) for k in layer_keys]\n # to avoid mis-matching with \"conv1\" in other components (e.g. detection head)\n layer_keys = [re.sub(\"^conv1\\\\.\", \"stem.conv1.\", k) for k in layer_keys]\n\n # layer1-4 is used by torchvision, however we follow the C2 naming strategy (res2-5)\n # layer_keys = [re.sub(\"^res2.\", \"layer1.\", k) for k in layer_keys]\n # layer_keys = [re.sub(\"^res3.\", \"layer2.\", k) for k in layer_keys]\n # layer_keys = [re.sub(\"^res4.\", \"layer3.\", k) for k in layer_keys]\n # layer_keys = [re.sub(\"^res5.\", \"layer4.\", k) for k in layer_keys]\n\n # blocks\n layer_keys = [k.replace(\".branch1.\", \".shortcut.\") for k in layer_keys]\n layer_keys = [k.replace(\".branch2a.\", \".conv1.\") for k in layer_keys]\n layer_keys = [k.replace(\".branch2b.\", \".conv2.\") for k in layer_keys]\n layer_keys = [k.replace(\".branch2c.\", \".conv3.\") for k in layer_keys]\n\n # DensePose substitutions\n layer_keys = [re.sub(\"^body.conv.fcn\", \"body_conv_fcn\", k) for k in layer_keys]\n layer_keys = [k.replace(\"AnnIndex.lowres\", \"ann_index_lowres\") for k in layer_keys]\n layer_keys = [k.replace(\"Index.UV.lowres\", \"index_uv_lowres\") for k in layer_keys]\n layer_keys = [k.replace(\"U.lowres\", \"u_lowres\") for k in layer_keys]\n layer_keys = [k.replace(\"V.lowres\", \"v_lowres\") for k in layer_keys]\n return layer_keys\n\n\ndef convert_c2_detectron_names(weights):\n \"\"\"\n Map Caffe2 Detectron weight names to Detectron2 names.\n\n Args:\n weights (dict): name -> tensor\n\n Returns:\n dict: detectron2 names -> tensor\n dict: detectron2 names -> C2 names\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.info(\"Remapping C2 weights ......\")\n original_keys = sorted(weights.keys())\n layer_keys = copy.deepcopy(original_keys)\n\n layer_keys = convert_basic_c2_names(layer_keys)\n\n # --------------------------------------------------------------------------\n # RPN hidden representation conv\n # --------------------------------------------------------------------------\n # FPN case\n # In the C2 model, the RPN hidden layer conv is defined for FPN level 2 and then\n # shared for all other levels, hence the appearance of \"fpn2\"\n layer_keys = [\n k.replace(\"conv.rpn.fpn2\", \"proposal_generator.rpn_head.conv\") for k in layer_keys\n ]\n # Non-FPN case\n layer_keys = [k.replace(\"conv.rpn\", \"proposal_generator.rpn_head.conv\") for k in layer_keys]\n\n # --------------------------------------------------------------------------\n # RPN box transformation conv\n # --------------------------------------------------------------------------\n # FPN case (see note above about \"fpn2\")\n layer_keys = [\n k.replace(\"rpn.bbox.pred.fpn2\", \"proposal_generator.rpn_head.anchor_deltas\")\n for k in layer_keys\n ]\n layer_keys = [\n k.replace(\"rpn.cls.logits.fpn2\", \"proposal_generator.rpn_head.objectness_logits\")\n for k in layer_keys\n ]\n # Non-FPN case\n layer_keys = [\n k.replace(\"rpn.bbox.pred\", \"proposal_generator.rpn_head.anchor_deltas\") for k in layer_keys\n ]\n layer_keys = [\n k.replace(\"rpn.cls.logits\", \"proposal_generator.rpn_head.objectness_logits\")\n for k in layer_keys\n ]\n\n # --------------------------------------------------------------------------\n # Fast R-CNN box head\n # --------------------------------------------------------------------------\n layer_keys = [re.sub(\"^bbox\\\\.pred\", \"bbox_pred\", k) for k in layer_keys]\n layer_keys = [re.sub(\"^cls\\\\.score\", \"cls_score\", k) for k in layer_keys]\n layer_keys = [re.sub(\"^fc6\\\\.\", \"box_head.fc1.\", k) for k in layer_keys]\n layer_keys = [re.sub(\"^fc7\\\\.\", \"box_head.fc2.\", k) for k in layer_keys]\n # 4conv1fc head tensor names: head_conv1_w, head_conv1_gn_s\n layer_keys = [re.sub(\"^head\\\\.conv\", \"box_head.conv\", k) for k in layer_keys]\n\n # --------------------------------------------------------------------------\n # FPN lateral and output convolutions\n # --------------------------------------------------------------------------\n def fpn_map(name):\n \"\"\"\n Look for keys with the following patterns:\n 1) Starts with \"fpn.inner.\"\n Example: \"fpn.inner.res2.2.sum.lateral.weight\"\n Meaning: These are lateral pathway convolutions\n 2) Starts with \"fpn.res\"\n Example: \"fpn.res2.2.sum.weight\"\n Meaning: These are FPN output convolutions\n \"\"\"\n splits = name.split(\".\")\n norm = \".norm\" if \"norm\" in splits else \"\"\n if name.startswith(\"fpn.inner.\"):\n # splits example: ['fpn', 'inner', 'res2', '2', 'sum', 'lateral', 'weight']\n stage = int(splits[2][len(\"res\") :])\n return \"fpn_lateral{}{}.{}\".format(stage, norm, splits[-1])\n elif name.startswith(\"fpn.res\"):\n # splits example: ['fpn', 'res2', '2', 'sum', 'weight']\n stage = int(splits[1][len(\"res\") :])\n return \"fpn_output{}{}.{}\".format(stage, norm, splits[-1])\n return name\n\n layer_keys = [fpn_map(k) for k in layer_keys]\n\n # --------------------------------------------------------------------------\n # Mask R-CNN mask head\n # --------------------------------------------------------------------------\n # roi_heads.StandardROIHeads case\n layer_keys = [k.replace(\".[mask].fcn\", \"mask_head.mask_fcn\") for k in layer_keys]\n layer_keys = [re.sub(\"^\\\\.mask\\\\.fcn\", \"mask_head.mask_fcn\", k) for k in layer_keys]\n layer_keys = [k.replace(\"mask.fcn.logits\", \"mask_head.predictor\") for k in layer_keys]\n # roi_heads.Res5ROIHeads case\n layer_keys = [k.replace(\"conv5.mask\", \"mask_head.deconv\") for k in layer_keys]\n\n # --------------------------------------------------------------------------\n # Keypoint R-CNN head\n # --------------------------------------------------------------------------\n # interestingly, the keypoint head convs have blob names that are simply \"conv_fcnX\"\n layer_keys = [k.replace(\"conv.fcn\", \"roi_heads.keypoint_head.conv_fcn\") for k in layer_keys]\n layer_keys = [\n k.replace(\"kps.score.lowres\", \"roi_heads.keypoint_head.score_lowres\") for k in layer_keys\n ]\n layer_keys = [k.replace(\"kps.score.\", \"roi_heads.keypoint_head.score.\") for k in layer_keys]\n\n # --------------------------------------------------------------------------\n # Done with replacements\n # --------------------------------------------------------------------------\n assert len(set(layer_keys)) == len(layer_keys)\n assert len(original_keys) == len(layer_keys)\n\n new_weights = {}\n new_keys_to_original_keys = {}\n for orig, renamed in zip(original_keys, layer_keys):\n new_keys_to_original_keys[renamed] = orig\n if renamed.startswith(\"bbox_pred.\") or renamed.startswith(\"mask_head.predictor.\"):\n # remove the meaningless prediction weight for background class\n new_start_idx = 4 if renamed.startswith(\"bbox_pred.\") else 1\n new_weights[renamed] = weights[orig][new_start_idx:]\n logger.info(\n \"Remove prediction weight for background class in {}. The shape changes from \"\n \"{} to {}.\".format(\n renamed, tuple(weights[orig].shape), tuple(new_weights[renamed].shape)\n )\n )\n elif renamed.startswith(\"cls_score.\"):\n # move weights of bg class from original index 0 to last index\n logger.info(\n \"Move classification weights for background class in {} from index 0 to \"\n \"index {}.\".format(renamed, weights[orig].shape[0] - 1)\n )\n new_weights[renamed] = torch.cat([weights[orig][1:], weights[orig][:1]])\n else:\n new_weights[renamed] = weights[orig]\n\n return new_weights, new_keys_to_original_keys\n\n\n# Note the current matching is not symmetric.\n# it assumes model_state_dict will have longer names.\ndef align_and_update_state_dicts(model_state_dict, ckpt_state_dict, c2_conversion=True):\n \"\"\"\n Match names between the two state-dict, and update the values of model_state_dict in-place with\n copies of the matched tensor in ckpt_state_dict.\n If `c2_conversion==True`, `ckpt_state_dict` is assumed to be a Caffe2\n model and will be renamed at first.\n\n Strategy: suppose that the models that we will create will have prefixes appended\n to each of its keys, for example due to an extra level of nesting that the original\n pre-trained weights from ImageNet won't contain. For example, model.state_dict()\n might return backbone[0].body.res2.conv1.weight, while the pre-trained model contains\n res2.conv1.weight. We thus want to match both parameters together.\n For that, we look for each model weight, look among all loaded keys if there is one\n that is a suffix of the current weight name, and use it if that's the case.\n If multiple matches exist, take the one with longest size\n of the corresponding name. For example, for the same model as before, the pretrained\n weight file can contain both res2.conv1.weight, as well as conv1.weight. In this case,\n we want to match backbone[0].body.conv1.weight to conv1.weight, and\n backbone[0].body.res2.conv1.weight to res2.conv1.weight.\n \"\"\"\n model_keys = sorted(list(model_state_dict.keys()))\n if c2_conversion:\n ckpt_state_dict, original_keys = convert_c2_detectron_names(ckpt_state_dict)\n # original_keys: the name in the original dict (before renaming)\n else:\n original_keys = {x: x for x in ckpt_state_dict.keys()}\n ckpt_keys = sorted(list(ckpt_state_dict.keys()))\n\n def match(a, b):\n # Matched ckpt_key should be a complete (starts with '.') suffix.\n # For example, roi_heads.mesh_head.whatever_conv1 does not match conv1,\n # but matches whatever_conv1 or mesh_head.whatever_conv1.\n return a == b or a.endswith(\".\" + b)\n\n # get a matrix of string matches, where each (i, j) entry correspond to the size of the\n # ckpt_key string, if it matches\n match_matrix = [len(j) if match(i, j) else 0 for i in model_keys for j in ckpt_keys]\n match_matrix = torch.as_tensor(match_matrix).view(len(model_keys), len(ckpt_keys))\n # use the matched one with longest size in case of multiple matches\n max_match_size, idxs = match_matrix.max(1)\n # remove indices that correspond to no-match\n idxs[max_match_size == 0] = -1\n\n # used for logging\n max_len_model = max(len(key) for key in model_keys) if model_keys else 1\n max_len_ckpt = max(len(key) for key in ckpt_keys) if ckpt_keys else 1\n log_str_template = \"{: <{}} loaded from {: <{}} of shape {}\"\n logger = logging.getLogger(__name__)\n # matched_pairs (matched checkpoint key --> matched model key)\n matched_keys = {}\n for idx_model, idx_ckpt in enumerate(idxs.tolist()):\n if idx_ckpt == -1:\n continue\n key_model = model_keys[idx_model]\n key_ckpt = ckpt_keys[idx_ckpt]\n value_ckpt = ckpt_state_dict[key_ckpt]\n shape_in_model = model_state_dict[key_model].shape\n\n if shape_in_model != value_ckpt.shape:\n logger.warning(\n \"Shape of {} in checkpoint is {}, while shape of {} in model is {}.\".format(\n key_ckpt, value_ckpt.shape, key_model, shape_in_model\n )\n )\n logger.warning(\n \"{} will not be loaded. Please double check and see if this is desired.\".format(\n key_ckpt\n )\n )\n continue\n\n model_state_dict[key_model] = value_ckpt.clone()\n if key_ckpt in matched_keys: # already added to matched_keys\n logger.error(\n \"Ambiguity found for {} in checkpoint!\"\n \"It matches at least two keys in the model ({} and {}).\".format(\n key_ckpt, key_model, matched_keys[key_ckpt]\n )\n )\n raise ValueError(\"Cannot match one checkpoint key to multiple keys in the model.\")\n\n matched_keys[key_ckpt] = key_model\n\n if not global_cfg.MUTE_HEADER:\n logger.info(\n log_str_template.format(\n key_model,\n max_len_model,\n original_keys[key_ckpt],\n max_len_ckpt,\n tuple(shape_in_model),\n )\n )\n matched_model_keys = matched_keys.values()\n matched_ckpt_keys = matched_keys.keys()\n # print warnings about unmatched keys on both side\n unmatched_model_keys = [k for k in model_keys if k not in matched_model_keys]\n if len(unmatched_model_keys):\n logger.info(get_missing_parameters_message(unmatched_model_keys))\n\n unmatched_ckpt_keys = [k for k in ckpt_keys if k not in matched_ckpt_keys]\n if len(unmatched_ckpt_keys):\n logger.info(\n get_unexpected_parameters_message(original_keys[x] for x in unmatched_ckpt_keys)\n )\n"
] | [
[
"torch.device",
"numpy.concatenate",
"torch.Tensor"
],
[
"torch.device",
"torch.cuda.device_count"
],
[
"torch.cat",
"torch.as_tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
June01/kinetics-i3d | [
"6f7d7101971a48a4c1bbfc7374d76d3071fd7e3b"
] | [
"feat_extractor(2019.7.25)/extract_feature_7.25.py"
] | [
"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport tensorflow as tf\nimport sonnet as snt\n\nfrom PIL import Image, ImageOps\nimport cv2\n\nimport numpy as np\n\nimport os\n\nimport i3d\n\nimport sys\n\ninp1 = sys.argv[1]\ninp2 = sys.argv[2]\n\n# In[2]:\n\n\n# Proprecessing for image(scale and crop)\ndef reshape_img_pil(img):\n width, height = np.array(img).shape[0:2]\n min_ = min(height, width)\n ratio = float(256/float(min_))\n new_w = int(ratio*width)\n new_h = int(ratio*height)\n \n img_resize = np.array(img.resize((new_w, new_h), resample=Image.BILINEAR))\n img_scale = (img_resize/255.0)*2-1\n new_img = img_scale[int((new_h-224)/2):int((new_h+224)/2),int((new_w-224)/2):int((new_w+224)/2),:]\n \n return new_img\n\ndef reshape_cv2(img, type):\n width, height = img.shape[0:2]\n min_ = min(height, width)\n ratio = float(256/float(min_))\n new_w = int(ratio*width)\n new_h = int(ratio*height)\n# print(width, height, new_w, new_h)\n# print((new_h-224)/2, (new_h+224)/2, (new_w-224)/2, (new_w+224)/2)\n if type=='rgb':\n frame = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n else:\n frame = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n frame = cv2.resize(frame, (new_w,new_h), interpolation=cv2.INTER_LINEAR)\n frame = (frame/255.0)*2-1\n frame = frame[int((new_h-224)/2):int((new_h+224)/2),int((new_w-224)/2):int((new_w+224)/2)]\n \n return frame\n\n\n# In[3]:\n\n\ndef get_batch(idx, step, video_path, video_name, type):\n raw_images = []\n for i in range(step):\n if type == 'rgb':\n image_name = 'img_%05d.jpg'%(idx+1+i)\n if os.path.exists(os.path.join(video_path, image_name)):\n img = cv2.imread(os.path.join(video_path, image_name))\n img = reshape_cv2(img, type='rgb')\n raw_images.append(img)\n elif type == 'flow':\n flow_x_name = 'flow_x_%05d.jpg'%(idx+1+i)\n flow_y_name = 'flow_y_%05d.jpg'%(idx+1+i)\n if os.path.exists(os.path.join(video_path, flow_x_name)):\n flow_x_img = cv2.imread(os.path.join(video_path, flow_x_name))\n flow_y_img = cv2.imread(os.path.join(video_path, flow_y_name))\n \n flow_x_img = reshape_cv2(flow_x_img, type='flow')\n flow_y_img = reshape_cv2(flow_y_img, type='flow')\n \n# print(flow_x_img.shape, flow_y_img.shape)\n# flow = np.stack((flow_x_img, flow_y_img))\n# print(flow.shape)\n flow = np.stack((flow_x_img, flow_y_img)).reshape(224,224,2)\n\n raw_images.append(flow)\n \n return np.array(raw_images)\n\n\n# In[13]:\n\n\nimage_size = 224\nnum_class = 20\n\nsample_path = {\n 'rgb': 'data/v_CricketShot_g04_c01_rgb.npy',\n 'flow': 'data/v_CricketShot_g04_c01_flow.npy',\n}\n\ncheckpoints = {\n 'rgb_scratch': 'data/checkpoints/rgb_scratch/model.ckpt',\n 'flow_scratch': 'data/checkpoints/flow_scratch/model.ckpt',\n 'rgb_imagenet': 'data/checkpoints/rgb_imagenet/model.ckpt',\n 'flow_imagenet': 'data/checkpoints/flow_imagenet/model.ckpt',\n}\n\nraw_path = {\n 'val': '/data/th14_raw/val_optical_flow_rgb',\n 'test': '/data/th14_raw/test_optical_flow_rgb',\n}\n\nsave_paths = {\n 'val_imagenet': '/data/th14_feature_i3d/feat_and_var/feat_imagenet/val_feat',\n 'test_imagenet': '/data/th14_feature_i3d/feat_and_var/feat_imagenet/test_feat',\n 'val_scratch': '/data/th14_feature_i3d/feat_and_var/feat_scratch/val_feat',\n 'test_scratch': '/data/th14_feature_i3d/feat_and_var/feat_scratch/test_feat',\n}\n\n\n# In[4]:\n\n\nrgb_input = tf.placeholder(tf.float32, shape=(1,None,image_size,image_size,3))\nflow_input = tf.placeholder(tf.float32, shape=(1,None,image_size,image_size,2))\nwith tf.variable_scope('RGB'):\n rgb_model = i3d.InceptionI3d(num_class+1, spatial_squeeze=True, final_endpoint='Mixed_5c')\n rgb_mixed5c, _ = rgb_model(rgb_input, is_training=False, dropout_keep_prob=1.0)\n# rgb_feat = tf.nn.avg_pool3d(rgb_mixed5c, ksize=[1, 2, 7, 7, 1],\n# strides=[1, 1, 1, 1, 1], padding=snt.VALID)\n rgb_feat = rgb_mixed5c\n\nrgb_variable_map = {}\nfor variable in tf.global_variables():\n if variable.name.split('/')[0] == 'RGB':\n rgb_variable_map[variable.name.replace(':0', '')] = variable\nrgb_saver = tf.train.Saver(var_list=rgb_variable_map, reshape=True)\n \nwith tf.variable_scope('Flow'):\n flow_model = i3d.InceptionI3d(num_class+1,spatial_squeeze=True, final_endpoint='Mixed_5c')\n flow_mixed5c, _ = flow_model(flow_input, is_training=False, dropout_keep_prob=1.0)\n# flow_feat = tf.nn.avg_pool3d(flow_mixed5c, ksize=[1, 2, 7, 7, 1],\n# strides=[1, 1, 1, 1, 1], padding=snt.VALID)\n flow_feat = flow_mixed5c\n \nflow_variable_map = {}\nfor variable in tf.global_variables():\n if variable.name.split('/')[0] == 'Flow':\n flow_variable_map[variable.name.replace(':0', '')] = variable\nflow_saver = tf.train.Saver(var_list=flow_variable_map, reshape=True)\n\n\n# In[9]:\n\n\ndef get_mean_var(feat):\n feat = np.reshape(feat, (-1, 1024))\n mean = np.mean(feat, axis=0)\n var = np.var(feat, axis=0)\n feat_all = np.hstack((mean, var))\n return feat_all\n\n\n# In[18]:\n\n\ndef extract_feat(feat_extractor='imagenet', data_source='test'):\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2) # 30% memory of TITAN is enough\n# self.sess = tf.Session(config = tf.ConfigProto(gpu_options=gpu_options)) \n with tf.Session(config = tf.ConfigProto(gpu_options=gpu_options)) as sess:\n feed_dict = {}\n \n rgb_feat_type = 'rgb' + '_' + feat_extractor\n flow_feat_type = 'flow' + '_' + feat_extractor\n \n rgb_saver.restore(sess, checkpoints[rgb_feat_type])\n flow_saver.restore(sess, checkpoints[flow_feat_type])\n# rgb_saver.restore(sess, checkpoints['rgb'])\n# flow_saver.restore(sess, checkpoints['flow'])\n \n tf.logging.info('RGB checkpoint restored')\n tf.logging.info('Flow checkpoint restored')\n \n feat_path = raw_path[data_source]\n \n save_pn = data_source + '_' + feat_extractor\n save_path = save_paths[save_pn]\n\n feat_step = 16\n\n video_list = os.listdir(feat_path)\n# print(len(video_list))\n for video in video_list:\n# video = 'video_test_0001292'\n \n video_path = os.path.join(feat_path, video)\n# if not os.path.exists(video_path):\n# os.makedirs(video_path)\n print(video_path)\n num_frames = len(os.listdir(video_path))/3\n index = np.arange(num_frames-8, step=8)\n# print(len(index))\n for idx in index:\n rgb_batch = get_batch(idx, feat_step, video_path, video, type='rgb')\n flow_batch = get_batch(idx, feat_step, video_path, video, type='flow')\n\n rgb_arr = rgb_batch[np.newaxis, :]\n# rgb_arr = (rgb_arr/255.0)*2-1\n flow_arr = flow_batch[np.newaxis, :]\n# flow_arr = (flow_arr/255.0)*2-1\n\n feed_dict[rgb_input] = rgb_arr\n feed_dict[flow_input] = flow_arr\n\n rgb, flow = sess.run([rgb_feat, flow_feat], feed_dict=feed_dict)\n# print(rgb.shape, flow.shape)\n rgb = get_mean_var(rgb)\n flow = get_mean_var(flow)\n print(rgb.shape, flow.shape)\n save_name = video+'.mp4_'+str(float(idx+1))+'_'+str(float(str(idx+1+feat_step)))+'.npy'\n print(save_path,save_name)\n np.save(os.path.join(save_path, 'rgb', save_name), rgb)\n np.save(os.path.join(save_path, 'flow', save_name), flow)\n \n# break\n \n\n\n# In[19]:\n\n\nextract_feat(feat_extractor=inp1, data_source=inp2)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n"
] | [
[
"numpy.hstack",
"numpy.reshape",
"numpy.arange",
"tensorflow.global_variables",
"tensorflow.placeholder",
"numpy.var",
"numpy.stack",
"tensorflow.ConfigProto",
"tensorflow.variable_scope",
"numpy.mean",
"tensorflow.GPUOptions",
"tensorflow.logging.info",
"tensorflow.train.Saver",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
guodashun/training-curve-vis | [
"eea830e3c981c136d2181d91c0534d6b6fcea902"
] | [
"boxplot.py"
] | [
"import seaborn as sns\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nclass BoxPlot:\n def __init__(\n self,\n title,\n x_label,\n y_label,\n ):\n self.title = title\n self.x_label = x_label\n self.y_label = y_label\n self.data = pd.DataFrame()\n \n\n def add_data(self, data, label):\n self.data[label] = data\n\n def show(self):\n sns.boxplot(data=self.data, width=0.5, fliersize=2)\n plt.title(self.title)\n plt.xlabel(self.x_label)\n plt.ylabel(self.y_label)\n plt.show()\n\n"
] | [
[
"matplotlib.pyplot.title",
"pandas.DataFrame",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"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": []
}
] |
oliver-contier/nipype | [
"47e149bbd6a9e865e9242e50fb7ca1a18adfc640"
] | [
"nipype/pipeline/engine/utils.py"
] | [
"# -*- coding: utf-8 -*-\n# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\"\"\"Utility routines for workflow graphs\"\"\"\nimport os\nimport sys\nimport pickle\nfrom collections import defaultdict\nimport re\nfrom copy import deepcopy\nfrom glob import glob\nfrom pathlib import Path\n\nfrom traceback import format_exception\nfrom hashlib import sha1\n\nfrom functools import reduce\n\nimport numpy as np\n\nfrom ... import logging, config, LooseVersion\nfrom ...utils.filemanip import (\n indirectory,\n relpath,\n fname_presuffix,\n ensure_list,\n get_related_files,\n save_json,\n savepkl,\n loadpkl,\n write_rst_header,\n write_rst_dict,\n write_rst_list,\n)\nfrom ...utils.misc import str2bool\nfrom ...utils.functions import create_function_from_source\nfrom ...interfaces.base.traits_extension import (\n rebase_path_traits,\n resolve_path_traits,\n OutputMultiPath,\n isdefined,\n Undefined,\n)\nfrom ...interfaces.base.support import Bunch, InterfaceResult\nfrom ...interfaces.base import CommandLine\nfrom ...interfaces.utility import IdentityInterface\nfrom ...utils.provenance import ProvStore, pm, nipype_ns, get_id\n\nfrom inspect import signature\n\nlogger = logging.getLogger(\"nipype.workflow\")\n\n\ndef _parameterization_dir(param):\n \"\"\"\n Returns the directory name for the given parameterization string as follows:\n - If the parameterization is longer than 32 characters, then\n return the SHA-1 hex digest.\n - Otherwise, return the parameterization unchanged.\n \"\"\"\n if len(param) > 32:\n return sha1(param.encode()).hexdigest()\n return param\n\n\ndef save_hashfile(hashfile, hashed_inputs):\n \"\"\"Store a hashfile\"\"\"\n try:\n save_json(hashfile, hashed_inputs)\n except (IOError, TypeError):\n err_type = sys.exc_info()[0]\n if err_type is TypeError:\n # XXX - SG current workaround is to just\n # create the hashed file and not put anything\n # in it\n with open(hashfile, \"wt\") as fd:\n fd.writelines(str(hashed_inputs))\n\n logger.debug(\"Unable to write a particular type to the json file\")\n else:\n logger.critical(\"Unable to open the file in write mode: %s\", hashfile)\n\n\ndef nodelist_runner(nodes, updatehash=False, stop_first=False):\n \"\"\"\n A generator that iterates and over a list of ``nodes`` and\n executes them.\n\n \"\"\"\n for i, node in nodes:\n err = None\n result = None\n try:\n result = node.run(updatehash=updatehash)\n except Exception:\n if stop_first:\n raise\n\n result = node.result\n err = []\n if result.runtime and hasattr(result.runtime, \"traceback\"):\n err = [result.runtime.traceback]\n\n err += format_exception(*sys.exc_info())\n err = \"\\n\".join(err)\n finally:\n yield i, result, err\n\n\ndef write_node_report(node, result=None, is_mapnode=False):\n \"\"\"Write a report file for a node.\"\"\"\n if not str2bool(node.config[\"execution\"][\"create_report\"]):\n return\n\n cwd = node.output_dir()\n report_file = Path(cwd) / \"_report\" / \"report.rst\"\n report_file.parent.mkdir(exist_ok=True, parents=True)\n\n lines = [\n write_rst_header(\"Node: %s\" % get_print_name(node), level=0),\n write_rst_list([\"Hierarchy : %s\" % node.fullname, \"Exec ID : %s\" % node._id]),\n write_rst_header(\"Original Inputs\", level=1),\n write_rst_dict(node.inputs.trait_get()),\n ]\n\n if result is None:\n logger.debug('[Node] Writing pre-exec report to \"%s\"', report_file)\n report_file.write_text(\"\\n\".join(lines))\n return\n\n logger.debug('[Node] Writing post-exec report to \"%s\"', report_file)\n lines += [\n write_rst_header(\"Execution Inputs\", level=1),\n write_rst_dict(node.inputs.trait_get()),\n write_rst_header(\"Execution Outputs\", level=1),\n ]\n\n outputs = result.outputs\n if outputs is None:\n lines += [\"None\"]\n report_file.write_text(\"\\n\".join(lines))\n return\n\n if isinstance(outputs, Bunch):\n lines.append(write_rst_dict(outputs.dictcopy()))\n elif outputs:\n lines.append(write_rst_dict(outputs.trait_get()))\n else:\n lines += [\"Outputs object was empty.\"]\n\n if is_mapnode:\n lines.append(write_rst_header(\"Subnode reports\", level=1))\n nitems = len(ensure_list(getattr(node.inputs, node.iterfield[0])))\n subnode_report_files = []\n for i in range(nitems):\n subnode_file = (\n Path(cwd)\n / \"mapflow\"\n / (\"_%s%d\" % (node.name, i))\n / \"_report\"\n / \"report.rst\"\n )\n subnode_report_files.append(\"subnode %d : %s\" % (i, subnode_file))\n\n lines.append(write_rst_list(subnode_report_files))\n report_file.write_text(\"\\n\".join(lines))\n return\n\n lines.append(write_rst_header(\"Runtime info\", level=1))\n # Init rst dictionary of runtime stats\n rst_dict = {\n \"hostname\": result.runtime.hostname,\n \"duration\": result.runtime.duration,\n \"working_dir\": result.runtime.cwd,\n \"prev_wd\": getattr(result.runtime, \"prevcwd\", \"<not-set>\"),\n }\n\n for prop in (\"cmdline\", \"mem_peak_gb\", \"cpu_percent\"):\n if hasattr(result.runtime, prop):\n rst_dict[prop] = getattr(result.runtime, prop)\n\n lines.append(write_rst_dict(rst_dict))\n\n # Collect terminal output\n if hasattr(result.runtime, \"merged\"):\n lines += [\n write_rst_header(\"Terminal output\", level=2),\n write_rst_list(result.runtime.merged),\n ]\n if hasattr(result.runtime, \"stdout\"):\n lines += [\n write_rst_header(\"Terminal - standard output\", level=2),\n write_rst_list(result.runtime.stdout),\n ]\n if hasattr(result.runtime, \"stderr\"):\n lines += [\n write_rst_header(\"Terminal - standard error\", level=2),\n write_rst_list(result.runtime.stderr),\n ]\n\n # Store environment\n if hasattr(result.runtime, \"environ\"):\n lines += [\n write_rst_header(\"Environment\", level=2),\n write_rst_dict(result.runtime.environ),\n ]\n\n report_file.write_text(\"\\n\".join(lines))\n\n\ndef write_report(node, report_type=None, is_mapnode=False):\n \"\"\"Write a report file for a node - DEPRECATED\"\"\"\n if report_type not in (\"preexec\", \"postexec\"):\n logger.warning('[Node] Unknown report type \"%s\".', report_type)\n return\n\n write_node_report(\n node,\n is_mapnode=is_mapnode,\n result=node.result if report_type == \"postexec\" else None,\n )\n\n\ndef save_resultfile(result, cwd, name, rebase=None):\n \"\"\"Save a result pklz file to ``cwd``.\"\"\"\n if rebase is None:\n rebase = config.getboolean(\"execution\", \"use_relative_paths\")\n\n cwd = os.path.abspath(cwd)\n resultsfile = os.path.join(cwd, \"result_%s.pklz\" % name)\n logger.debug(\"Saving results file: '%s'\", resultsfile)\n\n if result.outputs is None:\n logger.warning(\"Storing result file without outputs\")\n savepkl(resultsfile, result)\n return\n try:\n output_names = result.outputs.copyable_trait_names()\n except AttributeError:\n logger.debug(\"Storing non-traited results, skipping rebase of paths\")\n savepkl(resultsfile, result)\n return\n\n if not rebase:\n savepkl(resultsfile, result)\n return\n\n backup_traits = {}\n try:\n with indirectory(cwd):\n # All the magic to fix #2944 resides here:\n for key in output_names:\n old = getattr(result.outputs, key)\n if isdefined(old):\n if result.outputs.trait(key).is_trait_type(OutputMultiPath):\n old = result.outputs.trait(key).handler.get_value(\n result.outputs, key\n )\n backup_traits[key] = old\n val = rebase_path_traits(result.outputs.trait(key), old, cwd)\n setattr(result.outputs, key, val)\n savepkl(resultsfile, result)\n finally:\n # Restore resolved paths from the outputs dict no matter what\n for key, val in list(backup_traits.items()):\n setattr(result.outputs, key, val)\n\n\ndef load_resultfile(results_file, resolve=True):\n \"\"\"\n Load InterfaceResult file from path.\n\n Parameters\n ----------\n results_file : pathlike\n Path to an existing pickle (``result_<interface name>.pklz``) created with\n ``save_resultfile``.\n Raises ``FileNotFoundError`` if ``results_file`` does not exist.\n resolve : bool\n Determines whether relative paths will be resolved to absolute (default is ``True``).\n\n Returns\n -------\n result : InterfaceResult\n A Nipype object containing the runtime, inputs, outputs and other interface information\n such as a traceback in the case of errors.\n\n \"\"\"\n results_file = Path(results_file)\n if not results_file.exists():\n raise FileNotFoundError(results_file)\n\n result = loadpkl(results_file)\n if resolve and getattr(result, \"outputs\", None):\n try:\n outputs = result.outputs.get()\n except TypeError: # This is a Bunch\n logger.debug(\"Outputs object of loaded result %s is a Bunch.\", results_file)\n return result\n\n logger.debug(\"Resolving paths in outputs loaded from results file.\")\n for trait_name, old in list(outputs.items()):\n if isdefined(old):\n if result.outputs.trait(trait_name).is_trait_type(OutputMultiPath):\n old = result.outputs.trait(trait_name).handler.get_value(\n result.outputs, trait_name\n )\n value = resolve_path_traits(\n result.outputs.trait(trait_name), old, results_file.parent\n )\n setattr(result.outputs, trait_name, value)\n return result\n\n\ndef strip_temp(files, wd):\n \"\"\"Remove temp from a list of file paths\"\"\"\n out = []\n for f in files:\n if isinstance(f, list):\n out.append(strip_temp(f, wd))\n else:\n out.append(f.replace(os.path.join(wd, \"_tempinput\"), wd))\n return out\n\n\ndef _write_inputs(node):\n lines = []\n nodename = node.fullname.replace(\".\", \"_\")\n for key, _ in list(node.inputs.items()):\n val = getattr(node.inputs, key)\n if isdefined(val):\n if isinstance(val, (str, bytes)):\n try:\n func = create_function_from_source(val)\n except RuntimeError:\n lines.append(\"%s.inputs.%s = '%s'\" % (nodename, key, val))\n else:\n funcname = [\n name for name in func.__globals__ if name != \"__builtins__\"\n ][0]\n lines.append(pickle.loads(val))\n if funcname == nodename:\n lines[-1] = lines[-1].replace(\n \" %s(\" % funcname, \" %s_1(\" % funcname\n )\n funcname = \"%s_1\" % funcname\n lines.append(\"from nipype.utils.functions import getsource\")\n lines.append(\n \"%s.inputs.%s = getsource(%s)\" % (nodename, key, funcname)\n )\n else:\n lines.append(\"%s.inputs.%s = %s\" % (nodename, key, val))\n return lines\n\n\ndef format_node(node, format=\"python\", include_config=False):\n \"\"\"Format a node in a given output syntax.\"\"\"\n from .nodes import MapNode\n\n lines = []\n name = node.fullname.replace(\".\", \"_\")\n if format == \"python\":\n klass = node.interface\n importline = \"from %s import %s\" % (klass.__module__, klass.__class__.__name__)\n comment = \"# Node: %s\" % node.fullname\n spec = signature(node.interface.__init__)\n filled_args = []\n for param in spec.parameters.values():\n val = getattr(node.interface, f\"_{param.name}\", None)\n if val is not None:\n filled_args.append(f\"{param.name}={val!r}\")\n args = \", \".join(filled_args)\n klass_name = klass.__class__.__name__\n if isinstance(node, MapNode):\n nodedef = '%s = MapNode(%s(%s), iterfield=%s, name=\"%s\")' % (\n name,\n klass_name,\n args,\n node.iterfield,\n name,\n )\n else:\n nodedef = '%s = Node(%s(%s), name=\"%s\")' % (name, klass_name, args, name)\n lines = [importline, comment, nodedef]\n\n if include_config:\n lines = [\n importline,\n \"from collections import OrderedDict\",\n comment,\n nodedef,\n ]\n lines.append(\"%s.config = %s\" % (name, node.config))\n\n if node.iterables is not None:\n lines.append(\"%s.iterables = %s\" % (name, node.iterables))\n lines.extend(_write_inputs(node))\n\n return lines\n\n\ndef modify_paths(object, relative=True, basedir=None):\n \"\"\"Convert paths in data structure to either full paths or relative paths\n\n Supports combinations of lists, dicts, tuples, strs\n\n Parameters\n ----------\n\n relative : boolean indicating whether paths should be set relative to the\n current directory\n basedir : default os.getcwd()\n what base directory to use as default\n \"\"\"\n if not basedir:\n basedir = os.getcwd()\n if isinstance(object, dict):\n out = {}\n for key, val in sorted(object.items()):\n if isdefined(val):\n out[key] = modify_paths(val, relative=relative, basedir=basedir)\n elif isinstance(object, (list, tuple)):\n out = []\n for val in object:\n if isdefined(val):\n out.append(modify_paths(val, relative=relative, basedir=basedir))\n if isinstance(object, tuple):\n out = tuple(out)\n else:\n if isdefined(object):\n if isinstance(object, (str, bytes)) and os.path.isfile(object):\n if relative:\n if config.getboolean(\"execution\", \"use_relative_paths\"):\n out = relpath(object, start=basedir)\n else:\n out = object\n else:\n out = os.path.abspath(os.path.join(basedir, object))\n if not os.path.exists(out):\n raise IOError(\"File %s not found\" % out)\n else:\n out = object\n else:\n raise TypeError(\"Object {} is undefined\".format(object))\n return out\n\n\ndef get_print_name(node, simple_form=True):\n \"\"\"Get the name of the node\n\n For example, a node containing an instance of interfaces.fsl.BET\n would be called nodename.BET.fsl\n\n \"\"\"\n name = node.fullname\n if hasattr(node, \"_interface\"):\n pkglist = node.interface.__class__.__module__.split(\".\")\n interface = node.interface.__class__.__name__\n destclass = \"\"\n if len(pkglist) > 2:\n destclass = \".%s\" % pkglist[2]\n if simple_form:\n name = node.fullname + destclass\n else:\n name = \".\".join([node.fullname, interface]) + destclass\n if simple_form:\n parts = name.split(\".\")\n if len(parts) > 2:\n return \" (\".join(parts[1:]) + \")\"\n elif len(parts) == 2:\n return parts[1]\n return name\n\n\ndef _create_dot_graph(graph, show_connectinfo=False, simple_form=True):\n \"\"\"Create a graph that can be pickled.\n\n Ensures that edge info is pickleable.\n \"\"\"\n logger.debug(\"creating dot graph\")\n import networkx as nx\n\n pklgraph = nx.DiGraph()\n for edge in graph.edges():\n data = graph.get_edge_data(*edge)\n srcname = get_print_name(edge[0], simple_form=simple_form)\n destname = get_print_name(edge[1], simple_form=simple_form)\n if show_connectinfo:\n pklgraph.add_edge(srcname, destname, l=str(data[\"connect\"]))\n else:\n pklgraph.add_edge(srcname, destname)\n return pklgraph\n\n\ndef _write_detailed_dot(graph, dotfilename):\n r\"\"\"\n Create a dot file with connection info ::\n\n digraph structs {\n node [shape=record];\n struct1 [label=\"<f0> left|<f1> middle|<f2> right\"];\n struct2 [label=\"<f0> one|<f1> two\"];\n struct3 [label=\"hello\\nworld |{ b |{c|<here> d|e}| f}| g | h\"];\n struct1:f1 -> struct2:f0;\n struct1:f0 -> struct2:f1;\n struct1:f2 -> struct3:here;\n }\n \"\"\"\n import networkx as nx\n\n text = [\"digraph structs {\", \"node [shape=record];\"]\n # write nodes\n edges = []\n for n in nx.topological_sort(graph):\n nodename = n.itername\n inports = []\n for u, v, d in graph.in_edges(nbunch=n, data=True):\n for cd in d[\"connect\"]:\n if isinstance(cd[0], (str, bytes)):\n outport = cd[0]\n else:\n outport = cd[0][0]\n inport = cd[1]\n ipstrip = \"in%s\" % _replacefunk(inport)\n opstrip = \"out%s\" % _replacefunk(outport)\n edges.append(\n \"%s:%s:e -> %s:%s:w;\"\n % (\n u.itername.replace(\".\", \"\"),\n opstrip,\n v.itername.replace(\".\", \"\"),\n ipstrip,\n )\n )\n if inport not in inports:\n inports.append(inport)\n inputstr = (\n [\"{IN\"]\n + [\"|<in%s> %s\" % (_replacefunk(ip), ip) for ip in sorted(inports)]\n + [\"}\"]\n )\n outports = []\n for u, v, d in graph.out_edges(nbunch=n, data=True):\n for cd in d[\"connect\"]:\n if isinstance(cd[0], (str, bytes)):\n outport = cd[0]\n else:\n outport = cd[0][0]\n if outport not in outports:\n outports.append(outport)\n outputstr = (\n [\"{OUT\"]\n + [\n \"|<out%s> %s\" % (_replacefunk(oport), oport)\n for oport in sorted(outports)\n ]\n + [\"}\"]\n )\n srcpackage = \"\"\n if hasattr(n, \"_interface\"):\n pkglist = n.interface.__class__.__module__.split(\".\")\n if len(pkglist) > 2:\n srcpackage = pkglist[2]\n srchierarchy = \".\".join(nodename.split(\".\")[1:-1])\n nodenamestr = \"{ %s | %s | %s }\" % (\n nodename.split(\".\")[-1],\n srcpackage,\n srchierarchy,\n )\n text += [\n '%s [label=\"%s|%s|%s\"];'\n % (\n nodename.replace(\".\", \"\"),\n \"\".join(inputstr),\n nodenamestr,\n \"\".join(outputstr),\n )\n ]\n # write edges\n for edge in sorted(edges):\n text.append(edge)\n text.append(\"}\")\n with open(dotfilename, \"wt\") as filep:\n filep.write(\"\\n\".join(text))\n return text\n\n\ndef _replacefunk(x):\n return x.replace(\"_\", \"\").replace(\".\", \"\").replace(\"@\", \"\").replace(\"-\", \"\")\n\n\n# Graph manipulations for iterable expansion\ndef _get_valid_pathstr(pathstr):\n \"\"\"Remove disallowed characters from path\n\n Removes: [][ (){}?:<>#!|\"';]\n Replaces: ',' -> '.'\n \"\"\"\n if not isinstance(pathstr, (str, bytes)):\n pathstr = str(pathstr)\n pathstr = pathstr.replace(os.sep, \"..\")\n pathstr = re.sub(r\"\"\"[][ (){}?:<>#!|\"';]\"\"\", \"\", pathstr)\n pathstr = pathstr.replace(\",\", \".\")\n return pathstr\n\n\ndef expand_iterables(iterables, synchronize=False):\n if synchronize:\n return synchronize_iterables(iterables)\n return list(walk(list(iterables.items())))\n\n\ndef count_iterables(iterables, synchronize=False):\n \"\"\"Return the number of iterable expansion nodes.\n\n If synchronize is True, then the count is the maximum number\n of iterables value lists.\n Otherwise, the count is the product of the iterables value\n list sizes.\n \"\"\"\n op = max if synchronize else lambda x, y: x * y\n return reduce(op, [len(func()) for _, func in list(iterables.items())])\n\n\ndef walk(children, level=0, path=None, usename=True):\n \"\"\"Generate all the full paths in a tree, as a dict.\n\n Examples\n --------\n >>> from nipype.pipeline.engine.utils import walk\n >>> iterables = [('a', lambda: [1, 2]), ('b', lambda: [3, 4])]\n >>> [val['a'] for val in walk(iterables)]\n [1, 1, 2, 2]\n >>> [val['b'] for val in walk(iterables)]\n [3, 4, 3, 4]\n \"\"\"\n # Entry point\n if level == 0:\n path = {}\n # Exit condition\n if not children:\n yield path.copy()\n return\n # Tree recursion\n head, tail = children[0], children[1:]\n name, func = head\n for child in func():\n # We can use the arg name or the tree level as a key\n if usename:\n path[name] = child\n else:\n path[level] = child\n # Recurse into the next level\n for child_paths in walk(tail, level + 1, path, usename):\n yield child_paths\n\n\ndef synchronize_iterables(iterables):\n \"\"\"Synchronize the given iterables in item-wise order.\n\n Return: the {field: value} dictionary list\n\n Examples\n --------\n >>> from nipype.pipeline.engine.utils import synchronize_iterables\n >>> iterables = dict(a=lambda: [1, 2], b=lambda: [3, 4])\n >>> synced = synchronize_iterables(iterables)\n >>> synced == [{'a': 1, 'b': 3}, {'a': 2, 'b': 4}]\n True\n >>> iterables = dict(a=lambda: [1, 2], b=lambda: [3], c=lambda: [4, 5, 6])\n >>> synced = synchronize_iterables(iterables)\n >>> synced == [{'a': 1, 'b': 3, 'c': 4}, {'a': 2, 'c': 5}, {'c': 6}]\n True\n \"\"\"\n out_list = []\n iterable_items = [\n (field, iter(fvals())) for field, fvals in sorted(iterables.items())\n ]\n while True:\n cur_dict = {}\n for field, iter_values in iterable_items:\n try:\n cur_dict[field] = next(iter_values)\n except StopIteration:\n pass\n if cur_dict:\n out_list.append(cur_dict)\n else:\n break\n\n return out_list\n\n\ndef evaluate_connect_function(function_source, args, first_arg):\n func = create_function_from_source(function_source)\n try:\n output_value = func(first_arg, *list(args))\n except NameError as e:\n if e.args[0].startswith(\"global name\") and e.args[0].endswith(\"is not defined\"):\n e.args = (\n e.args[0],\n (\n \"Due to engine constraints all imports have to be done \"\n \"inside each function definition\"\n ),\n )\n raise e\n return output_value\n\n\ndef get_levels(G):\n import networkx as nx\n\n levels = {}\n for n in nx.topological_sort(G):\n levels[n] = 0\n for pred in G.predecessors(n):\n levels[n] = max(levels[n], levels[pred] + 1)\n return levels\n\n\ndef _merge_graphs(\n supergraph, nodes, subgraph, nodeid, iterables, prefix, synchronize=False\n):\n \"\"\"Merges two graphs that share a subset of nodes.\n\n If the subgraph needs to be replicated for multiple iterables, the\n merge happens with every copy of the subgraph. Assumes that edges\n between nodes of supergraph and subgraph contain data.\n\n Parameters\n ----------\n supergraph : networkx graph\n Parent graph from which subgraph was selected\n nodes : networkx nodes\n Nodes of the parent graph from which the subgraph was initially\n constructed.\n subgraph : networkx graph\n A subgraph that contains as a subset nodes from the supergraph.\n These nodes connect the subgraph to the supergraph\n nodeid : string\n Identifier of a node for which parameterization has been sought\n iterables : dict of functions\n see `pipeline.NodeWrapper` for iterable requirements\n\n Returns\n -------\n Returns a merged graph containing copies of the subgraph with\n appropriate edge connections to the supergraph.\n\n \"\"\"\n # Retrieve edge information connecting nodes of the subgraph to other\n # nodes of the supergraph.\n supernodes = supergraph.nodes()\n ids = [n._hierarchy + n._id for n in supernodes]\n if len(np.unique(ids)) != len(ids):\n # This should trap the problem of miswiring when multiple iterables are\n # used at the same level. The use of the template below for naming\n # updates to nodes is the general solution.\n raise Exception(\n (\n \"Execution graph does not have a unique set of node \"\n \"names. Please rerun the workflow\"\n )\n )\n edgeinfo = {}\n for n in list(subgraph.nodes()):\n nidx = ids.index(n._hierarchy + n._id)\n for edge in supergraph.in_edges(list(supernodes)[nidx]):\n # make sure edge is not part of subgraph\n if edge[0] not in subgraph.nodes():\n if n._hierarchy + n._id not in list(edgeinfo.keys()):\n edgeinfo[n._hierarchy + n._id] = []\n edgeinfo[n._hierarchy + n._id].append(\n (edge[0], supergraph.get_edge_data(*edge))\n )\n supergraph.remove_nodes_from(nodes)\n # Add copies of the subgraph depending on the number of iterables\n iterable_params = expand_iterables(iterables, synchronize)\n # If there are no iterable subgraphs, then return\n if not iterable_params:\n return supergraph\n # Make an iterable subgraph node id template\n count = len(iterable_params)\n template = \".%s%%0%dd\" % (prefix, np.ceil(np.log10(count)))\n # Copy the iterable subgraphs\n for i, params in enumerate(iterable_params):\n Gc = deepcopy(subgraph)\n ids = [n._hierarchy + n._id for n in Gc.nodes()]\n nodeidx = ids.index(nodeid)\n rootnode = list(Gc.nodes())[nodeidx]\n paramstr = \"\"\n for key, val in sorted(params.items()):\n paramstr = \"{}_{}_{}\".format(\n paramstr, _get_valid_pathstr(key), _get_valid_pathstr(val)\n )\n rootnode.set_input(key, val)\n\n logger.debug(\"Parameterization: paramstr=%s\", paramstr)\n levels = get_levels(Gc)\n for n in Gc.nodes():\n # update parameterization of the node to reflect the location of\n # the output directory. For example, if the iterables along a\n # path of the directed graph consisted of the variables 'a' and\n # 'b', then every node in the path including and after the node\n # with iterable 'b' will be placed in a directory\n # _a_aval/_b_bval/.\n\n path_length = levels[n]\n # enter as negative numbers so that earlier iterables with longer\n # path lengths get precedence in a sort\n paramlist = [(-path_length, paramstr)]\n if n.parameterization:\n n.parameterization = paramlist + n.parameterization\n else:\n n.parameterization = paramlist\n supergraph.add_nodes_from(Gc.nodes())\n supergraph.add_edges_from(Gc.edges(data=True))\n for node in Gc.nodes():\n if node._hierarchy + node._id in list(edgeinfo.keys()):\n for info in edgeinfo[node._hierarchy + node._id]:\n supergraph.add_edges_from([(info[0], node, info[1])])\n node._id += template % i\n return supergraph\n\n\ndef _connect_nodes(graph, srcnode, destnode, connection_info):\n \"\"\"Add a connection between two nodes\n \"\"\"\n data = graph.get_edge_data(srcnode, destnode, default=None)\n if not data:\n data = {\"connect\": connection_info}\n graph.add_edges_from([(srcnode, destnode, data)])\n else:\n data[\"connect\"].extend(connection_info)\n\n\ndef _remove_nonjoin_identity_nodes(graph, keep_iterables=False):\n \"\"\"Remove non-join identity nodes from the given graph\n\n Iterable nodes are retained if and only if the keep_iterables\n flag is set to True.\n \"\"\"\n # if keep_iterables is False, then include the iterable\n # and join nodes in the nodes to delete\n for node in _identity_nodes(graph, not keep_iterables):\n if not hasattr(node, \"joinsource\"):\n _remove_identity_node(graph, node)\n return graph\n\n\ndef _identity_nodes(graph, include_iterables):\n \"\"\"Return the IdentityInterface nodes in the graph\n\n The nodes are in topological sort order. The iterable nodes\n are included if and only if the include_iterables flag is set\n to True.\n \"\"\"\n import networkx as nx\n\n return [\n node\n for node in nx.topological_sort(graph)\n if isinstance(node.interface, IdentityInterface)\n and (include_iterables or getattr(node, \"iterables\") is None)\n ]\n\n\ndef _remove_identity_node(graph, node):\n \"\"\"Remove identity nodes from an execution graph\n \"\"\"\n portinputs, portoutputs = _node_ports(graph, node)\n for field, connections in list(portoutputs.items()):\n if portinputs:\n _propagate_internal_output(graph, node, field, connections, portinputs)\n else:\n _propagate_root_output(graph, node, field, connections)\n graph.remove_nodes_from([node])\n logger.debug(\"Removed the identity node %s from the graph.\", node)\n\n\ndef _node_ports(graph, node):\n \"\"\"Return the given node's input and output ports\n\n The return value is the (inputs, outputs) dictionaries.\n The inputs is a {destination field: (source node, source field)}\n dictionary.\n The outputs is a {source field: destination items} dictionary,\n where each destination item is a\n (destination node, destination field, source field) tuple.\n \"\"\"\n portinputs = {}\n portoutputs = {}\n for u, _, d in graph.in_edges(node, data=True):\n for src, dest in d[\"connect\"]:\n portinputs[dest] = (u, src)\n for _, v, d in graph.out_edges(node, data=True):\n for src, dest in d[\"connect\"]:\n if isinstance(src, tuple):\n srcport = src[0]\n else:\n srcport = src\n if srcport not in portoutputs:\n portoutputs[srcport] = []\n portoutputs[srcport].append((v, dest, src))\n return (portinputs, portoutputs)\n\n\ndef _propagate_root_output(graph, node, field, connections):\n \"\"\"Propagates the given graph root node output port\n field connections to the out-edge destination nodes.\"\"\"\n for destnode, inport, src in connections:\n value = getattr(node.inputs, field)\n if isinstance(src, tuple):\n value = evaluate_connect_function(src[1], src[2], value)\n destnode.set_input(inport, value)\n\n\ndef _propagate_internal_output(graph, node, field, connections, portinputs):\n \"\"\"Propagates the given graph internal node output port\n field connections to the out-edge source node and in-edge\n destination nodes.\"\"\"\n for destnode, inport, src in connections:\n if field in portinputs:\n srcnode, srcport = portinputs[field]\n if isinstance(srcport, tuple) and isinstance(src, tuple):\n src_func = srcport[1].split(\"\\\\n\")[0]\n dst_func = src[1].split(\"\\\\n\")[0]\n raise ValueError(\n \"Does not support two inline functions \"\n \"in series ('{}' and '{}'), found when \"\n \"connecting {} to {}. Please use a Function \"\n \"node.\".format(src_func, dst_func, srcnode, destnode)\n )\n\n connect = graph.get_edge_data(srcnode, destnode, default={\"connect\": []})\n if isinstance(src, tuple):\n connect[\"connect\"].append(((srcport, src[1], src[2]), inport))\n else:\n connect = {\"connect\": [(srcport, inport)]}\n old_connect = graph.get_edge_data(\n srcnode, destnode, default={\"connect\": []}\n )\n old_connect[\"connect\"] += connect[\"connect\"]\n graph.add_edges_from([(srcnode, destnode, old_connect)])\n else:\n value = getattr(node.inputs, field)\n if isinstance(src, tuple):\n value = evaluate_connect_function(src[1], src[2], value)\n destnode.set_input(inport, value)\n\n\ndef generate_expanded_graph(graph_in):\n \"\"\"Generates an expanded graph based on node parameterization\n\n Parameterization is controlled using the `iterables` field of the\n pipeline elements. Thus if there are two nodes with iterables a=[1,2]\n and b=[3,4] this procedure will generate a graph with sub-graphs\n parameterized as (a=1,b=3), (a=1,b=4), (a=2,b=3) and (a=2,b=4).\n \"\"\"\n import networkx as nx\n\n try:\n dfs_preorder = nx.dfs_preorder\n except AttributeError:\n dfs_preorder = nx.dfs_preorder_nodes\n\n logger.debug(\"PE: expanding iterables\")\n graph_in = _remove_nonjoin_identity_nodes(graph_in, keep_iterables=True)\n # standardize the iterables as {(field, function)} dictionaries\n for node in graph_in.nodes():\n if node.iterables:\n _standardize_iterables(node)\n allprefixes = list(\"abcdefghijklmnopqrstuvwxyz\")\n\n # the iterable nodes\n inodes = _iterable_nodes(graph_in)\n logger.debug(\"Detected iterable nodes %s\", inodes)\n # while there is an iterable node, expand the iterable node's\n # subgraphs\n while inodes:\n inode = inodes[0]\n logger.debug(\"Expanding the iterable node %s...\", inode)\n\n # the join successor nodes of the current iterable node\n jnodes = [\n node\n for node in graph_in.nodes()\n if hasattr(node, \"joinsource\")\n and inode.name == node.joinsource\n and nx.has_path(graph_in, inode, node)\n ]\n\n # excise the join in-edges. save the excised edges in a\n # {jnode: {source name: (destination name, edge data)}}\n # dictionary\n jedge_dict = {}\n for jnode in jnodes:\n in_edges = jedge_dict[jnode] = {}\n edges2remove = []\n for src, dest, data in graph_in.in_edges(jnode, True):\n in_edges[src.itername] = data\n edges2remove.append((src, dest))\n\n for src, dest in edges2remove:\n graph_in.remove_edge(src, dest)\n logger.debug(\"Excised the %s -> %s join node in-edge.\", src, dest)\n\n if inode.itersource:\n # the itersource is a (node name, fields) tuple\n src_name, src_fields = inode.itersource\n # convert a single field to a list\n if isinstance(src_fields, (str, bytes)):\n src_fields = [src_fields]\n # find the unique iterable source node in the graph\n try:\n iter_src = next(\n (\n node\n for node in graph_in.nodes()\n if node.name == src_name and nx.has_path(graph_in, node, inode)\n )\n )\n except StopIteration:\n raise ValueError(\n \"The node %s itersource %s was not found\"\n \" among the iterable predecessor nodes\" % (inode, src_name)\n )\n logger.debug(\"The node %s has iterable source node %s\", inode, iter_src)\n # look up the iterables for this particular itersource descendant\n # using the iterable source ancestor values as a key\n iterables = {}\n # the source node iterables values\n src_values = [getattr(iter_src.inputs, field) for field in src_fields]\n # if there is one source field, then the key is the the source value,\n # otherwise the key is the tuple of source values\n if len(src_values) == 1:\n key = src_values[0]\n else:\n key = tuple(src_values)\n # The itersource iterables is a {field: lookup} dictionary, where the\n # lookup is a {source key: iteration list} dictionary. Look up the\n # current iterable value using the predecessor itersource input values.\n iter_dict = dict(\n [\n (field, lookup[key])\n for field, lookup in inode.iterables\n if key in lookup\n ]\n )\n\n # convert the iterables to the standard {field: function} format\n\n def make_field_func(*pair):\n return pair[0], lambda: pair[1]\n\n iterables = dict(\n [make_field_func(*pair) for pair in list(iter_dict.items())]\n )\n else:\n iterables = inode.iterables.copy()\n inode.iterables = None\n logger.debug(\"node: %s iterables: %s\", inode, iterables)\n\n # collect the subnodes to expand\n subnodes = [s for s in dfs_preorder(graph_in, inode)]\n prior_prefix = [re.findall(r\"\\.(.)I\", s._id) for s in subnodes if s._id]\n prior_prefix = sorted([l for item in prior_prefix for l in item])\n if not prior_prefix:\n iterable_prefix = \"a\"\n else:\n if prior_prefix[-1] == \"z\":\n raise ValueError(\"Too many iterables in the workflow\")\n iterable_prefix = allprefixes[allprefixes.index(prior_prefix[-1]) + 1]\n logger.debug((\"subnodes:\", subnodes))\n\n # append a suffix to the iterable node id\n inode._id += \".%sI\" % iterable_prefix\n\n # merge the iterated subgraphs\n # dj: the behaviour of .copy changes in version 2\n if LooseVersion(nx.__version__) < LooseVersion(\"2\"):\n subgraph = graph_in.subgraph(subnodes)\n else:\n subgraph = graph_in.subgraph(subnodes).copy()\n graph_in = _merge_graphs(\n graph_in,\n subnodes,\n subgraph,\n inode._hierarchy + inode._id,\n iterables,\n iterable_prefix,\n inode.synchronize,\n )\n\n # reconnect the join nodes\n for jnode in jnodes:\n # the {node id: edge data} dictionary for edges connecting\n # to the join node in the unexpanded graph\n old_edge_dict = jedge_dict[jnode]\n # the edge source node replicates\n expansions = defaultdict(list)\n for node in graph_in.nodes():\n for src_id in list(old_edge_dict.keys()):\n # Drop the original JoinNodes; only concerned with\n # generated Nodes\n if hasattr(node, \"joinfield\") and node.itername == src_id:\n continue\n # Patterns:\n # - src_id : Non-iterable node\n # - src_id.[a-z]\\d+ :\n # IdentityInterface w/ iterables or nested JoinNode\n # - src_id.[a-z]I.[a-z]\\d+ :\n # Non-IdentityInterface w/ iterables\n # - src_idJ\\d+ : JoinNode(IdentityInterface)\n if re.match(\n src_id + r\"((\\.[a-z](I\\.[a-z])?|J)\\d+)?$\", node.itername\n ):\n expansions[src_id].append(node)\n for in_id, in_nodes in list(expansions.items()):\n logger.debug(\n \"The join node %s input %s was expanded\" \" to %d nodes.\",\n jnode,\n in_id,\n len(in_nodes),\n )\n # preserve the node iteration order by sorting on the node id\n for in_nodes in list(expansions.values()):\n in_nodes.sort(key=lambda node: node._id)\n\n # the number of join source replicates.\n iter_cnt = count_iterables(iterables, inode.synchronize)\n # make new join node fields to connect to each replicated\n # join in-edge source node.\n slot_dicts = [jnode._add_join_item_fields() for _ in range(iter_cnt)]\n # for each join in-edge, connect every expanded source node\n # which matches on the in-edge source name to the destination\n # join node. Qualify each edge connect join field name by\n # appending the next join slot index, e.g. the connect\n # from two expanded nodes from field 'out_file' to join\n # field 'in' are qualified as ('out_file', 'in1') and\n # ('out_file', 'in2'), resp. This preserves connection port\n # integrity.\n for old_id, in_nodes in list(expansions.items()):\n # reconnect each replication of the current join in-edge\n # source\n for in_idx, in_node in enumerate(in_nodes):\n olddata = old_edge_dict[old_id]\n newdata = deepcopy(olddata)\n # the (source, destination) field tuples\n connects = newdata[\"connect\"]\n # the join fields connected to the source\n join_fields = [\n field for _, field in connects if field in jnode.joinfield\n ]\n # the {field: slot fields} maps assigned to the input\n # node, e.g. {'image': 'imageJ3', 'mask': 'maskJ3'}\n # for the third join source expansion replicate of a\n # join node with join fields image and mask\n slots = slot_dicts[in_idx]\n for con_idx, connect in enumerate(connects):\n src_field, dest_field = connect\n # qualify a join destination field name\n if dest_field in slots:\n slot_field = slots[dest_field]\n connects[con_idx] = (src_field, slot_field)\n logger.debug(\n \"Qualified the %s -> %s join field %s as %s.\",\n in_node,\n jnode,\n dest_field,\n slot_field,\n )\n graph_in.add_edge(in_node, jnode, **newdata)\n logger.debug(\n \"Connected the join node %s subgraph to the\"\n \" expanded join point %s\",\n jnode,\n in_node,\n )\n\n # nx.write_dot(graph_in, '%s_post.dot' % node)\n # the remaining iterable nodes\n inodes = _iterable_nodes(graph_in)\n\n for node in graph_in.nodes():\n if node.parameterization:\n node.parameterization = [\n param for _, param in sorted(node.parameterization)\n ]\n logger.debug(\"PE: expanding iterables ... done\")\n\n return _remove_nonjoin_identity_nodes(graph_in)\n\n\ndef _iterable_nodes(graph_in):\n \"\"\"Returns the iterable nodes in the given graph and their join\n dependencies.\n\n The nodes are ordered as follows:\n\n - nodes without an itersource precede nodes with an itersource\n - nodes without an itersource are sorted in reverse topological order\n - nodes with an itersource are sorted in topological order\n\n This order implies the following:\n\n - every iterable node without an itersource is expanded before any\n node with an itersource\n\n - every iterable node without an itersource is expanded before any\n of it's predecessor iterable nodes without an itersource\n\n - every node with an itersource is expanded before any of it's\n successor nodes with an itersource\n\n Return the iterable nodes list\n \"\"\"\n import networkx as nx\n\n nodes = nx.topological_sort(graph_in)\n inodes = [node for node in nodes if node.iterables is not None]\n inodes_no_src = [node for node in inodes if not node.itersource]\n inodes_src = [node for node in inodes if node.itersource]\n inodes_no_src.reverse()\n return inodes_no_src + inodes_src\n\n\ndef _standardize_iterables(node):\n \"\"\"Converts the given iterables to a {field: function} dictionary,\n if necessary, where the function returns a list.\"\"\"\n if not node.iterables:\n return\n iterables = node.iterables\n # The candidate iterable fields\n fields = set(node.inputs.copyable_trait_names())\n # A synchronize iterables node without an itersource can be in\n # [fields, value tuples] format rather than\n # [(field, value list), (field, value list), ...]\n if node.synchronize:\n if len(iterables) == 2:\n first, last = iterables\n if all(\n (isinstance(item, (str, bytes)) and item in fields for item in first)\n ):\n iterables = _transpose_iterables(first, last)\n\n # Convert a tuple to a list\n if isinstance(iterables, tuple):\n iterables = [iterables]\n # Validate the standard [(field, values)] format\n _validate_iterables(node, iterables, fields)\n # Convert a list to a dictionary\n if isinstance(iterables, list):\n # Convert a values list to a function. This is a legacy\n # Nipype requirement with unknown rationale.\n if not node.itersource:\n\n def make_field_func(*pair):\n return pair[0], lambda: pair[1]\n\n iter_items = [make_field_func(*field_value1) for field_value1 in iterables]\n iterables = dict(iter_items)\n node.iterables = iterables\n\n\ndef _validate_iterables(node, iterables, fields):\n \"\"\"\n Raise TypeError if an iterables member is not iterable.\n\n Raise ValueError if an iterables member is not a (field, values) pair.\n\n Raise ValueError if an iterable field is not in the inputs.\n \"\"\"\n # The iterables can be a {field: value list} dictionary.\n if isinstance(iterables, dict):\n iterables = list(iterables.items())\n elif not isinstance(iterables, tuple) and not isinstance(iterables, list):\n raise ValueError(\n \"The %s iterables type is not a list or a dictionary:\"\n \" %s\" % (node.name, iterables.__class__)\n )\n for item in iterables:\n try:\n if len(item) != 2:\n raise ValueError(\n \"The %s iterables is not a [(field, values)]\" \" list\" % node.name\n )\n except TypeError as e:\n raise TypeError(\n \"A %s iterables member is not iterable: %s\" % (node.name, e)\n )\n field, _ = item\n if field not in fields:\n raise ValueError(\n \"The %s iterables field is unrecognized: %s\" % (node.name, field)\n )\n\n\ndef _transpose_iterables(fields, values):\n \"\"\"\n Converts the given fields and tuple values into a standardized\n iterables value.\n\n If the input values is a synchronize iterables dictionary, then\n the result is a (field, {key: values}) list.\n\n Otherwise, the result is a list of (field: value list) pairs.\n \"\"\"\n if isinstance(values, dict):\n transposed = dict([(field, defaultdict(list)) for field in fields])\n for key, tuples in list(values.items()):\n for kvals in tuples:\n for idx, val in enumerate(kvals):\n if val is not None:\n transposed[fields[idx]][key].append(val)\n return list(transposed.items())\n\n return list(\n zip(\n fields,\n [\n [v for v in list(transpose) if v is not None]\n for transpose in zip(*values)\n ],\n )\n )\n\n\ndef export_graph(\n graph_in,\n base_dir=None,\n show=False,\n use_execgraph=False,\n show_connectinfo=False,\n dotfilename=\"graph.dot\",\n format=\"png\",\n simple_form=True,\n):\n \"\"\" Displays the graph layout of the pipeline\n\n This function requires that pygraphviz and matplotlib are available on\n the system.\n\n Parameters\n ----------\n\n show : boolean\n Indicate whether to generate pygraphviz output fromn\n networkx. default [False]\n\n use_execgraph : boolean\n Indicates whether to use the specification graph or the\n execution graph. default [False]\n\n show_connectioninfo : boolean\n Indicates whether to show the edge data on the graph. This\n makes the graph rather cluttered. default [False]\n \"\"\"\n import networkx as nx\n\n graph = deepcopy(graph_in)\n if use_execgraph:\n graph = generate_expanded_graph(graph)\n logger.debug(\"using execgraph\")\n else:\n logger.debug(\"using input graph\")\n if base_dir is None:\n base_dir = os.getcwd()\n\n os.makedirs(base_dir, exist_ok=True)\n out_dot = fname_presuffix(\n dotfilename, suffix=\"_detailed.dot\", use_ext=False, newpath=base_dir\n )\n _write_detailed_dot(graph, out_dot)\n\n # Convert .dot if format != 'dot'\n outfname, res = _run_dot(out_dot, format_ext=format)\n if res is not None and res.runtime.returncode:\n logger.warning(\"dot2png: %s\", res.runtime.stderr)\n\n pklgraph = _create_dot_graph(graph, show_connectinfo, simple_form)\n simple_dot = fname_presuffix(\n dotfilename, suffix=\".dot\", use_ext=False, newpath=base_dir\n )\n nx.drawing.nx_pydot.write_dot(pklgraph, simple_dot)\n\n # Convert .dot if format != 'dot'\n simplefname, res = _run_dot(simple_dot, format_ext=format)\n if res is not None and res.runtime.returncode:\n logger.warning(\"dot2png: %s\", res.runtime.stderr)\n\n if show:\n pos = nx.graphviz_layout(pklgraph, prog=\"dot\")\n nx.draw(pklgraph, pos)\n if show_connectinfo:\n nx.draw_networkx_edge_labels(pklgraph, pos)\n\n return simplefname if simple_form else outfname\n\n\ndef format_dot(dotfilename, format=\"png\"):\n \"\"\"Dump a directed graph (Linux only; install via `brew` on OSX)\"\"\"\n try:\n formatted_dot, _ = _run_dot(dotfilename, format_ext=format)\n except IOError as ioe:\n if \"could not be found\" in str(ioe):\n raise IOError(\"Cannot draw directed graph; executable 'dot' is unavailable\")\n else:\n raise ioe\n return formatted_dot\n\n\ndef _run_dot(dotfilename, format_ext):\n if format_ext == \"dot\":\n return dotfilename, None\n\n dot_base = os.path.splitext(dotfilename)[0]\n formatted_dot = \"{}.{}\".format(dot_base, format_ext)\n cmd = 'dot -T{} -o\"{}\" \"{}\"'.format(format_ext, formatted_dot, dotfilename)\n res = CommandLine(cmd, terminal_output=\"allatonce\", resource_monitor=False).run()\n return formatted_dot, res\n\n\ndef get_all_files(infile):\n files = [infile]\n if infile.endswith(\".img\"):\n files.append(infile[:-4] + \".hdr\")\n files.append(infile[:-4] + \".mat\")\n if infile.endswith(\".img.gz\"):\n files.append(infile[:-7] + \".hdr.gz\")\n return files\n\n\ndef walk_outputs(object):\n \"\"\"Extract every file and directory from a python structure\n \"\"\"\n out = []\n if isinstance(object, dict):\n for _, val in sorted(object.items()):\n if isdefined(val):\n out.extend(walk_outputs(val))\n elif isinstance(object, (list, tuple)):\n for val in object:\n if isdefined(val):\n out.extend(walk_outputs(val))\n else:\n if isdefined(object) and isinstance(object, (str, bytes)):\n if os.path.islink(object) or os.path.isfile(object):\n out = [(filename, \"f\") for filename in get_all_files(object)]\n elif os.path.isdir(object):\n out = [(object, \"d\")]\n return out\n\n\ndef walk_files(cwd):\n for path, _, files in os.walk(cwd):\n for f in files:\n yield os.path.join(path, f)\n\n\ndef clean_working_directory(\n outputs, cwd, inputs, needed_outputs, config, files2keep=None, dirs2keep=None\n):\n \"\"\"Removes all files not needed for further analysis from the directory\n \"\"\"\n if not outputs:\n return\n outputs_to_keep = list(outputs.trait_get().keys())\n if needed_outputs and str2bool(config[\"execution\"][\"remove_unnecessary_outputs\"]):\n outputs_to_keep = needed_outputs\n # build a list of needed files\n output_files = []\n outputdict = outputs.trait_get()\n for output in outputs_to_keep:\n output_files.extend(walk_outputs(outputdict[output]))\n needed_files = [path for path, type in output_files if type == \"f\"]\n if str2bool(config[\"execution\"][\"keep_inputs\"]):\n input_files = []\n inputdict = inputs.trait_get()\n input_files.extend(walk_outputs(inputdict))\n needed_files += [path for path, type in input_files if type == \"f\"]\n for extra in [\n \"_0x*.json\",\n \"provenance.*\",\n \"pyscript*.m\",\n \"pyjobs*.mat\",\n \"command.txt\",\n \"result*.pklz\",\n \"_inputs.pklz\",\n \"_node.pklz\",\n \".proc-*\",\n ]:\n needed_files.extend(glob(os.path.join(cwd, extra)))\n if files2keep:\n needed_files.extend(ensure_list(files2keep))\n needed_dirs = [path for path, type in output_files if type == \"d\"]\n if dirs2keep:\n needed_dirs.extend(ensure_list(dirs2keep))\n for extra in [\"_nipype\", \"_report\"]:\n needed_dirs.extend(glob(os.path.join(cwd, extra)))\n temp = []\n for filename in needed_files:\n temp.extend(get_related_files(filename))\n needed_files = temp\n logger.debug(\"Needed files: %s\", \";\".join(needed_files))\n logger.debug(\"Needed dirs: %s\", \";\".join(needed_dirs))\n files2remove = []\n if str2bool(config[\"execution\"][\"remove_unnecessary_outputs\"]):\n for f in walk_files(cwd):\n if f not in needed_files:\n if not needed_dirs:\n files2remove.append(f)\n elif not any([f.startswith(dname) for dname in needed_dirs]):\n files2remove.append(f)\n else:\n if not str2bool(config[\"execution\"][\"keep_inputs\"]):\n input_files = []\n inputdict = inputs.trait_get()\n input_files.extend(walk_outputs(inputdict))\n input_files = [path for path, type in input_files if type == \"f\"]\n for f in walk_files(cwd):\n if f in input_files and f not in needed_files:\n files2remove.append(f)\n logger.debug(\"Removing files: %s\", \";\".join(files2remove))\n for f in files2remove:\n os.remove(f)\n for key in outputs.copyable_trait_names():\n if key not in outputs_to_keep:\n setattr(outputs, key, Undefined)\n return outputs\n\n\ndef merge_dict(d1, d2, merge=lambda x, y: y):\n \"\"\"\n Merges two dictionaries, non-destructively, combining\n values on duplicate keys as defined by the optional merge\n function. The default behavior replaces the values in d1\n with corresponding values in d2. (There is no other generally\n applicable merge strategy, but often you'll have homogeneous\n types in your dicts, so specifying a merge technique can be\n valuable.)\n\n Examples:\n\n >>> d1 = {'a': 1, 'c': 3, 'b': 2}\n >>> d2 = merge_dict(d1, d1)\n >>> len(d2)\n 3\n >>> [d2[k] for k in ['a', 'b', 'c']]\n [1, 2, 3]\n\n >>> d3 = merge_dict(d1, d1, lambda x,y: x+y)\n >>> len(d3)\n 3\n >>> [d3[k] for k in ['a', 'b', 'c']]\n [2, 4, 6]\n\n \"\"\"\n if not isinstance(d1, dict):\n return merge(d1, d2)\n result = dict(d1)\n if d2 is None:\n return result\n for k, v in list(d2.items()):\n if k in result:\n result[k] = merge_dict(result[k], v, merge=merge)\n else:\n result[k] = v\n return result\n\n\ndef merge_bundles(g1, g2):\n for rec in g2.get_records():\n g1._add_record(rec)\n return g1\n\n\ndef write_workflow_prov(graph, filename=None, format=\"all\"):\n \"\"\"Write W3C PROV Model JSON file\n \"\"\"\n if not filename:\n filename = os.path.join(os.getcwd(), \"workflow_provenance\")\n\n ps = ProvStore()\n\n processes = []\n nodes = graph.nodes()\n for node in nodes:\n result = node.result\n classname = node.interface.__class__.__name__\n _, hashval, _, _ = node.hash_exists()\n attrs = {\n pm.PROV[\"type\"]: nipype_ns[classname],\n pm.PROV[\"label\"]: \"_\".join((classname, node.name)),\n nipype_ns[\"hashval\"]: hashval,\n }\n process = ps.g.activity(get_id(), None, None, attrs)\n if isinstance(result.runtime, list):\n process.add_attributes({pm.PROV[\"type\"]: nipype_ns[\"MapNode\"]})\n # add info about sub processes\n for idx, runtime in enumerate(result.runtime):\n subresult = InterfaceResult(result.interface[idx], runtime, outputs={})\n if result.inputs:\n if idx < len(result.inputs):\n subresult.inputs = result.inputs[idx]\n if result.outputs:\n for key, _ in list(result.outputs.items()):\n values = getattr(result.outputs, key)\n if isdefined(values) and idx < len(values):\n subresult.outputs[key] = values[idx]\n sub_doc = ProvStore().add_results(subresult)\n sub_bundle = pm.ProvBundle(sub_doc.get_records(), identifier=get_id())\n ps.g.add_bundle(sub_bundle)\n bundle_entity = ps.g.entity(\n sub_bundle.identifier,\n other_attributes={\"prov:type\": pm.PROV_BUNDLE},\n )\n ps.g.wasGeneratedBy(bundle_entity, process)\n else:\n process.add_attributes({pm.PROV[\"type\"]: nipype_ns[\"Node\"]})\n if result.provenance:\n prov_doc = result.provenance\n else:\n prov_doc = ProvStore().add_results(result)\n result_bundle = pm.ProvBundle(prov_doc.get_records(), identifier=get_id())\n ps.g.add_bundle(result_bundle)\n bundle_entity = ps.g.entity(\n result_bundle.identifier, other_attributes={\"prov:type\": pm.PROV_BUNDLE}\n )\n ps.g.wasGeneratedBy(bundle_entity, process)\n processes.append(process)\n\n # add dependencies (edges)\n # Process->Process\n for idx, edgeinfo in enumerate(graph.in_edges()):\n ps.g.wasStartedBy(\n processes[list(nodes).index(edgeinfo[1])],\n starter=processes[list(nodes).index(edgeinfo[0])],\n )\n\n # write provenance\n ps.write_provenance(filename, format=format)\n return ps.g\n\n\ndef write_workflow_resources(graph, filename=None, append=None):\n \"\"\"\n Generate a JSON file with profiling traces that can be loaded\n in a pandas DataFrame or processed with JavaScript like D3.js\n \"\"\"\n import simplejson as json\n\n # Overwrite filename if nipype config is set\n filename = config.get(\"monitoring\", \"summary_file\", filename)\n\n # If filename still does not make sense, store in $PWD\n if not filename:\n filename = os.path.join(os.getcwd(), \"resource_monitor.json\")\n\n if append is None:\n append = str2bool(config.get(\"monitoring\", \"summary_append\", \"true\"))\n\n big_dict = {\n \"time\": [],\n \"name\": [],\n \"interface\": [],\n \"rss_GiB\": [],\n \"vms_GiB\": [],\n \"cpus\": [],\n \"mapnode\": [],\n \"params\": [],\n }\n\n # If file exists, just append new profile information\n # If we append different runs, then we will see different\n # \"bursts\" of timestamps corresponding to those executions.\n if append and os.path.isfile(filename):\n with open(filename, \"r\") as rsf:\n big_dict = json.load(rsf)\n\n for _, node in enumerate(graph.nodes()):\n nodename = node.fullname\n classname = node.interface.__class__.__name__\n\n params = \"\"\n if node.parameterization:\n params = \"_\".join([\"{}\".format(p) for p in node.parameterization])\n\n try:\n rt_list = node.result.runtime\n except Exception:\n logger.warning(\n \"Could not access runtime info for node %s\" \" (%s interface)\",\n nodename,\n classname,\n )\n continue\n\n if not isinstance(rt_list, list):\n rt_list = [rt_list]\n\n for subidx, runtime in enumerate(rt_list):\n try:\n nsamples = len(runtime.prof_dict[\"time\"])\n except AttributeError:\n logger.warning(\n 'Could not retrieve profiling information for node \"%s\" '\n \"(mapflow %d/%d).\",\n nodename,\n subidx + 1,\n len(rt_list),\n )\n continue\n\n for key in [\"time\", \"cpus\", \"rss_GiB\", \"vms_GiB\"]:\n big_dict[key] += runtime.prof_dict[key]\n\n big_dict[\"interface\"] += [classname] * nsamples\n big_dict[\"name\"] += [nodename] * nsamples\n big_dict[\"mapnode\"] += [subidx] * nsamples\n big_dict[\"params\"] += [params] * nsamples\n\n with open(filename, \"w\") as rsf:\n json.dump(big_dict, rsf, ensure_ascii=False)\n\n return filename\n\n\ndef topological_sort(graph, depth_first=False):\n \"\"\"Returns a depth first sorted order if depth_first is True\n \"\"\"\n import networkx as nx\n\n nodesort = list(nx.topological_sort(graph))\n if not depth_first:\n return nodesort, None\n logger.debug(\"Performing depth first search\")\n nodes = []\n groups = []\n group = 0\n G = nx.Graph()\n G.add_nodes_from(graph.nodes())\n G.add_edges_from(graph.edges())\n components = nx.connected_components(G)\n for desc in components:\n group += 1\n indices = []\n for node in desc:\n indices.append(nodesort.index(node))\n nodes.extend(\n np.array(nodesort)[np.array(indices)[np.argsort(indices)]].tolist()\n )\n for node in desc:\n nodesort.remove(node)\n groups.extend([group] * len(desc))\n return nodes, groups\n"
] | [
[
"numpy.argsort",
"numpy.array",
"numpy.log10",
"numpy.unique"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ankitasuman009/greyatom-python-for-data-science | [
"6ff5094885aaa3280c1b17d721d0c0ac07462cce"
] | [
"visualization/code.py"
] | [
"# --------------\n#Importing header files\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n#Reading the file\ndata=pd.read_csv(path)\nprint(data.iloc[25, 1])\n# df = pd.DataFrame(data)\n#Code starts here\nloan_status = data['Loan_Status'].value_counts()\nloan_status.plot(kind = 'bar')\n# # Step 1 \n#Reading the file\n\nproperty_and_loan = data.groupby(['Property_Area', 'Loan_Status'])\n#Creating a new variable to store the value counts\nproperty_and_loan = property_and_loan.size().unstack()\nproperty_and_loan = property_and_loan.plot(kind = 'bar', stacked = False)\nplt.xlabel('Property Area')\nplt.ylabel('Loan Status')\nplt.xticks(rotation = 45)\nplt.show()\n\n#Plotting bar plot\n\n\n\n# Step 2\n#Plotting an unstacked bar plot\neducation_and_loan = data.groupby(['Education', 'Loan_Status']).size().unstack().plot(kind = 'bar', stacked = True)\nplt.xlabel('Education Status')\nplt.ylabel('Loan Status')\nplt.xticks(rotation = 45)\nplt.show()\n\n#Changing the x-axis label\n\n\n#Changing the y-axis label\n\n\n#Rotating the ticks of X-axis\n\n\n# Step 3\n#Plotting a stacked bar plot\n\ngraduate = pd.DataFrame(data[data['Education'] == 'Graduate'])\nnot_graduate = pd.DataFrame(data[data['Education'] == 'Not Graduate']) \n\n#Changing the x-axis label\npd.Series(graduate['LoanAmount']).plot(kind = 'density', label = 'Graduate')\npd.Series(not_graduate['LoanAmount']).plot(kind = 'density', label = 'Not Graduate')\n#Changing the y-axis label\n\n\n#Rotating the ticks of X-axis\n\n\n# Step 4 \n#Subsetting the dataframe based on 'Education' column\nfig ,(ax_1,ax_2,ax_3) = plt.subplots(nrows = 3 , ncols = 1)\n\n#Subsetting the dataframe based on 'Education' column\ndata.plot.scatter(x= 'ApplicantIncome', y = 'LoanAmount', ax = ax_1)\nax_1.set_title('Applicant Income')\n\n# #Plotting density plot for 'Graduate'\ndata.plot.scatter(x = 'CoapplicantIncome', y = 'LoanAmount', ax = ax_2)\nax_2.set_title('Coapplicant Income')\n\n#Plotting density plot for 'Graduate'\ndata['TotalIncome'] = data['ApplicantIncome'] + data['CoapplicantIncome']\ndata.plot.scatter(x = 'TotalIncome', y = 'LoanAmount', ax = ax_3)\nax_3.set_title('Total Income')\n#For automatic legend display\nprint(data['TotalIncome'][1])\n\n# Step 5\n#Setting up the subplots\n\n\n#Plotting scatter plot\n\n\n#Setting the subplot axis title\n\n\n#Plotting scatter plot\n\n\n#Setting the subplot axis title\n\n\n#Creating a new column 'TotalIncome'\n\n\n#Plotting scatter plot\n\n\n\n#Setting the subplot axis title\n\n\n\n"
] | [
[
"pandas.read_csv",
"pandas.Series",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
yumaloop/predwm | [
"9cf757b5f8b13cff8da325838c8685700162754d",
"9cf757b5f8b13cff8da325838c8685700162754d"
] | [
"carracing/prednet/rnn.py",
"carracing/rnn_train.py"
] | [
"import numpy as np\nfrom collections import namedtuple\nimport json\nimport tensorflow as tf\n\n# hyperparameters for our model. I was using an older tf version, when HParams was not available ...\n\n# controls whether we concatenate (z, c, h), etc for features used for car.\nMODE_ZCH = 0\nMODE_ZC = 1\nMODE_Z = 2\nMODE_Z_HIDDEN = 3 # extra hidden later\nMODE_ZH = 4\n\nHyperParams = namedtuple('HyperParams', ['num_steps',\n 'max_seq_len',\n 'input_seq_width',\n 'output_seq_width',\n 'rnn_size',\n 'batch_size',\n 'grad_clip',\n 'num_mixture',\n 'learning_rate',\n 'decay_rate',\n 'min_learning_rate',\n 'use_layer_norm',\n 'use_recurrent_dropout',\n 'recurrent_dropout_prob',\n 'use_input_dropout',\n 'input_dropout_prob',\n 'use_output_dropout',\n 'output_dropout_prob',\n 'is_training',\n ])\n\ndef default_hps():\n return HyperParams(num_steps=2000, # train model for 2000 steps.\n max_seq_len=1000, # train on sequences of 100\n input_seq_width=35, # width of our data (32 + 3 actions)\n output_seq_width=32, # width of our data is 32\n rnn_size=256, # number of rnn cells\n batch_size=100, # minibatch sizes\n grad_clip=1.0, # \n num_mixture=5, # number of mixtures in MDN\n learning_rate=0.001,\n decay_rate=1.0,\n min_learning_rate=0.00001,\n use_layer_norm=0, # set this to 1 to get more stable results (less chance of NaN), but slower\n use_recurrent_dropout=0,\n recurrent_dropout_prob=0.90,\n use_input_dropout=0,\n input_dropout_prob=0.90,\n use_output_dropout=0,\n output_dropout_prob=0.90,\n is_training=1)\n\nhps_model = default_hps()\nhps_sample = hps_model._replace(batch_size=1, max_seq_len=1, use_recurrent_dropout=0, is_training=0) # replace params as default settings\n\n# MDN-RNN model\nclass MDNRNN():\n def __init__(self, hps, gpu_mode=True, reuse=False):\n self.hps = hps\n with tf.variable_scope('mdn_rnn', reuse=reuse):\n if not gpu_mode:\n with tf.device(\"/cpu:0\"):\n print(\"model using cpu\")\n self.g = tf.Graph()\n with self.g.as_default():\n self.build_model(hps)\n else:\n print(\"model using gpu\")\n self.g = tf.Graph()\n with self.g.as_default():\n self.build_model(hps)\n self.init_session()\n \n def build_model(self, hps):\n self.num_mixture = hps.num_mixture\n KMIX = self.num_mixture # 5 mixtures (5 classes)\n INWIDTH = hps.input_seq_width # 35 channels\n OUTWIDTH = hps.output_seq_width # 32 channels\n LENGTH = self.hps.max_seq_len # 1000 timesteps\n\n if hps.is_training:\n self.global_step = tf.Variable(0, name='global_step', trainable=False)\n\n cell_fn = tf.contrib.rnn.LayerNormBasicLSTMCell # use LayerNormLSTM\n\n use_recurrent_dropout = False if self.hps.use_recurrent_dropout == 0 else True\n use_input_dropout = False if self.hps.use_input_dropout == 0 else True\n use_output_dropout = False if self.hps.use_output_dropout == 0 else True\n is_training = False if self.hps.is_training == 0 else True\n use_layer_norm = False if self.hps.use_layer_norm == 0 else True\n\n if use_recurrent_dropout:\n cell = cell_fn(hps.rnn_size, layer_norm=use_layer_norm, dropout_keep_prob=self.hps.recurrent_dropout_prob)\n else:\n cell = cell_fn(hps.rnn_size, layer_norm=use_layer_norm)\n\n # multi-layer, and dropout:\n print(\"input dropout mode =\", use_input_dropout)\n print(\"output dropout mode =\", use_output_dropout)\n print(\"recurrent dropout mode =\", use_recurrent_dropout)\n \n if use_input_dropout:\n print(\"applying dropout to input with keep_prob =\", self.hps.input_dropout_prob)\n cell = tf.contrib.rnn.DropoutWrapper(cell, input_keep_prob=self.hps.input_dropout_prob)\n if use_output_dropout:\n print(\"applying dropout to output with keep_prob =\", self.hps.output_dropout_prob)\n cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=self.hps.output_dropout_prob)\n self.cell = cell\n\n self.sequence_lengths = LENGTH # assume every sample has same length.\n self.input_x = tf.placeholder(dtype=tf.float32, shape=[self.hps.batch_size, self.hps.max_seq_len, INWIDTH])\n self.output_x = tf.placeholder(dtype=tf.float32, shape=[self.hps.batch_size, self.hps.max_seq_len, OUTWIDTH])\n\n actual_input_x = self.input_x\n self.initial_state = cell.zero_state(batch_size=hps.batch_size, dtype=tf.float32) \n\n NOUT = OUTWIDTH * KMIX * 3\n\n with tf.variable_scope('RNN'):\n output_w = tf.get_variable(\"output_w\", [self.hps.rnn_size, NOUT])\n output_b = tf.get_variable(\"output_b\", [NOUT])\n\n output, last_state = tf.nn.dynamic_rnn(cell, actual_input_x, initial_state=self.initial_state, \n time_major=False, swap_memory=True, dtype=tf.float32, scope=\"RNN\")\n\n output = tf.reshape(output, [-1, hps.rnn_size])\n output = tf.nn.xw_plus_b(output, output_w, output_b)\n output = tf.reshape(output, [-1, KMIX * 3])\n self.final_state = last_state \n\n logSqrtTwoPI = np.log(np.sqrt(2.0 * np.pi))\n\n def tf_lognormal(y, mean, logstd):\n return -0.5 * ((y - mean) / tf.exp(logstd)) ** 2 - logstd - logSqrtTwoPI\n\n def get_lossfunc(logmix, mean, logstd, y):\n v = logmix + tf_lognormal(y, mean, logstd)\n v = tf.reduce_logsumexp(v, 1, keepdims=True)\n return -tf.reduce_mean(v)\n\n def get_mdn_coef(output):\n logmix, mean, logstd = tf.split(output, 3, 1)\n logmix = logmix - tf.reduce_logsumexp(logmix, 1, keepdims=True)\n return logmix, mean, logstd\n\n out_logmix, out_mean, out_logstd = get_mdn_coef(output)\n\n self.out_logmix = out_logmix\n self.out_mean = out_mean\n self.out_logstd = out_logstd\n\n # reshape target data so that it is compatible with prediction shape\n flat_target_data = tf.reshape(self.output_x,[-1, 1])\n\n lossfunc = get_lossfunc(out_logmix, out_mean, out_logstd, flat_target_data)\n\n self.cost = tf.reduce_mean(lossfunc)\n\n if self.hps.is_training == 1:\n self.lr = tf.Variable(self.hps.learning_rate, trainable=False)\n optimizer = tf.train.AdamOptimizer(self.lr)\n\n gvs = optimizer.compute_gradients(self.cost)\n capped_gvs = [(tf.clip_by_value(grad, -self.hps.grad_clip, self.hps.grad_clip), var) for grad, var in gvs]\n self.train_op = optimizer.apply_gradients(capped_gvs, global_step=self.global_step, name='train_step')\n\n # initialize vars\n self.init = tf.global_variables_initializer()\n\n t_vars = tf.trainable_variables()\n self.assign_ops = {}\n for var in t_vars:\n #if var.name.startswith('mdn_rnn'):\n pshape = var.get_shape()\n pl = tf.placeholder(tf.float32, pshape, var.name[:-2]+'_placeholder')\n assign_op = var.assign(pl)\n self.assign_ops[var] = (assign_op, pl)\n \n def init_session(self):\n \"\"\"Launch TensorFlow session and initialize variables\"\"\"\n self.sess = tf.Session(graph=self.g)\n self.sess.run(self.init)\n \n def close_sess(self):\n \"\"\" Close TensorFlow session \"\"\"\n self.sess.close()\n \n def get_model_params(self):\n # get trainable params.\n model_names = []\n model_params = []\n model_shapes = []\n\n with self.g.as_default():\n t_vars = tf.trainable_variables()\n for var in t_vars:\n #if var.name.startswith('mdn_rnn'):\n param_name = var.name\n p = self.sess.run(var)\n model_names.append(param_name)\n params = np.round(p*10000).astype(np.int).tolist()\n model_params.append(params)\n model_shapes.append(p.shape)\n return model_params, model_shapes, model_names\n \n def get_random_model_params(self, stdev=0.5):\n # get random params.\n _, mshape, _ = self.get_model_params()\n rparam = []\n for s in mshape:\n #rparam.append(np.random.randn(*s)*stdev)\n rparam.append(np.random.standard_cauchy(s)*stdev) # spice things up\n return rparam\n \n def set_random_params(self, stdev=0.5):\n rparam = self.get_random_model_params(stdev)\n self.set_model_params(rparam)\n \n def set_model_params(self, params):\n with self.g.as_default():\n t_vars = tf.trainable_variables()\n idx = 0\n for var in t_vars:\n #if var.name.startswith('mdn_rnn'):\n pshape = tuple(var.get_shape().as_list())\n p = np.array(params[idx])\n assert pshape == p.shape, \"inconsistent shape\"\n assign_op, pl = self.assign_ops[var]\n self.sess.run(assign_op, feed_dict={pl.name: p/10000.})\n idx += 1\n \n def load_json(self, jsonfile='rnn.json'):\n with open(jsonfile, 'r') as f:\n params = json.load(f)\n self.set_model_params(params)\n \n def save_json(self, jsonfile='rnn.json'):\n model_params, model_shapes, model_names = self.get_model_params()\n qparams = []\n for p in model_params:\n qparams.append(p)\n with open(jsonfile, 'wt') as outfile:\n json.dump(qparams, outfile, sort_keys=True, indent=0, separators=(',', ': '))\n\ndef get_pi_idx(x, pdf):\n # samples from a categorial distribution\n N = pdf.size\n accumulate = 0\n for i in range(0, N):\n accumulate += pdf[i]\n if (accumulate >= x):\n return i\n print('error with sampling ensemble')\n return -1\n\ndef sample_sequence(sess, s_model, hps, init_z, actions, temperature=1.0, seq_len=1000):\n # generates a random sequence using the trained model \n OUTWIDTH = hps.output_seq_width\n INWIDTH = hps.input_seq_width\n\n prev_x = np.zeros((1, 1, OUTWIDTH))\n prev_x[0][0] = init_z\n prev_state = sess.run(s_model.initial_state)\n\n '''\n if prev_data is not None:\n # encode the previous data into the hidden state first\n for i in range(prev_data.shape[0]):\n prev_x[0][0] = prev_data[i]\n feed = {s_model.input_x: prev_x, s_model.initial_state:prev_state}\n [next_state] = sess.run([s_model.final_state], feed)\n prev_state = next_state\n '''\n\n strokes = np.zeros((seq_len, OUTWIDTH), dtype=np.float32)\n\n for i in range(seq_len):\n input_x = np.concatenate((prev_x, actions[i].reshape((1, 1, 3))), axis=2)\n feed = {s_model.input_x: input_x, s_model.initial_state:prev_state}\n [logmix, mean, logstd, next_state] = sess.run([s_model.out_logmix, s_model.out_mean, s_model.out_logstd, s_model.final_state], feed)\n\n # adjust temperatures\n logmix2 = np.copy(logmix)/temperature\n logmix2 -= logmix2.max()\n logmix2 = np.exp(logmix2)\n logmix2 /= logmix2.sum(axis=1).reshape(OUTWIDTH, 1)\n\n mixture_idx = np.zeros(OUTWIDTH)\n chosen_mean = np.zeros(OUTWIDTH)\n chosen_logstd = np.zeros(OUTWIDTH)\n \n for j in range(OUTWIDTH):\n idx = get_pi_idx(np.random.rand(), logmix2[j])\n mixture_idx[j] = idx\n chosen_mean[j] = mean[j][idx]\n chosen_logstd[j] = logstd[j][idx]\n\n rand_gaussian = np.random.randn(OUTWIDTH)*np.sqrt(temperature)\n next_x = chosen_mean+np.exp(chosen_logstd)*rand_gaussian\n\n strokes[i,:] = next_x\n\n prev_x[0][0] = next_x\n prev_state = next_state\n\n return strokes\n\ndef rnn_init_state(rnn):\n return rnn.sess.run(rnn.initial_state)\n\ndef rnn_next_state(rnn, z, a, prev_state):\n input_x = np.concatenate((z.reshape((1, 1, 32)), a.reshape((1, 1, 3))), axis=2)\n feed = {rnn.input_x: input_x, rnn.initial_state:prev_state}\n return rnn.sess.run(rnn.final_state, feed)\n\ndef rnn_output_size(mode):\n if mode == MODE_ZCH:\n return (32+256+256)\n if (mode == MODE_ZC) or (mode == MODE_ZH):\n return (32+256)\n return 32 # MODE_Z or MODE_Z_HIDDEN\n\ndef rnn_output(state, z, mode):\n if mode == MODE_ZCH:\n return np.concatenate([z, np.concatenate((state.c,state.h), axis=1)[0]])\n if mode == MODE_ZC:\n return np.concatenate([z, state.c[0]])\n if mode == MODE_ZH:\n return np.concatenate([z, state.h[0]])\n return z # MODE_Z or MODE_Z_HIDDEN\n",
"'''\ntrain mdn-rnn from pre-processed data.\nalso save 1000 initial mu and logvar, for generative experiments (not related to training).\n'''\n\nimport os\nimport json\nimport random\nimport time\nimport numpy as np\nimport tensorflow as tf\nfrom vae.vae import ConvVAE, reset_graph\nfrom rnn.rnn import HyperParams, MDNRNN\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\nnp.set_printoptions(precision=4, edgeitems=6, linewidth=100, suppress=True)\n\nDATA_DIR = \"series\"\nmodel_save_path = \"tf_rnn\"\nif not os.path.exists(model_save_path):\n os.makedirs(model_save_path)\n \ninitial_z_save_path = \"tf_initial_z\"\nif not os.path.exists(initial_z_save_path):\n os.makedirs(initial_z_save_path)\n\ndef random_batch():\n indices = np.random.permutation(N_data)[0:batch_size]\n mu = data_mu[indices]\n logvar = data_logvar[indices]\n action = data_action[indices]\n s = logvar.shape\n z = mu + np.exp(logvar/2.0) * np.random.randn(*s)\n return z, action\n\ndef default_hps():\n return HyperParams(num_steps=4000,\n max_seq_len=999, # train on sequences of 1000 (so 999 + teacher forcing shift)\n input_seq_width=35, # width of our data (32 + 3 actions)\n output_seq_width=32, # width of our data is 32\n rnn_size=256, # number of rnn cells\n batch_size=100, # minibatch sizes\n grad_clip=1.0,\n num_mixture=5, # number of mixtures in MDN\n learning_rate=0.001,\n decay_rate=1.0,\n min_learning_rate=0.00001,\n use_layer_norm=0, # set this to 1 to get more stable results (less chance of NaN), but slower\n use_recurrent_dropout=0,\n recurrent_dropout_prob=0.90,\n use_input_dropout=0,\n input_dropout_prob=0.90,\n use_output_dropout=0,\n output_dropout_prob=0.90,\n is_training=1)\n\nhps_model = default_hps()\nhps_sample = hps_model._replace(batch_size=1, max_seq_len=1, use_recurrent_dropout=0, is_training=0)\nraw_data = np.load(os.path.join(DATA_DIR, \"series.npz\"))\n\n# load preprocessed data\ndata_mu = raw_data[\"mu\"]\ndata_logvar = raw_data[\"logvar\"]\ndata_action = raw_data[\"action\"]\nmax_seq_len = hps_model.max_seq_len\n\nN_data = len(data_mu) # should be 10k\nbatch_size = hps_model.batch_size\n\n# save 1000 initial mu and logvars:\ninitial_mu = np.copy(data_mu[:1000, 0, :]*10000).astype(np.int).tolist()\ninitial_logvar = np.copy(data_logvar[:1000, 0, :]*10000).astype(np.int).tolist()\nwith open(os.path.join(\"tf_initial_z\", \"initial_z.json\"), 'wt') as outfile:\n json.dump([initial_mu, initial_logvar], outfile, sort_keys=True, indent=0, separators=(',', ': '))\n\nreset_graph()\nrnn = MDNRNN(hps_model)\n\n# train loop:\nhps = hps_model\nstart = time.time()\nfor local_step in range(hps.num_steps):\n step = rnn.sess.run(rnn.global_step)\n curr_learning_rate = (hps.learning_rate - hps.min_learning_rate) * (hps.decay_rate) ** step + hps.min_learning_rate\n raw_z, raw_a = random_batch()\n inputs = np.concatenate((raw_z[:, :-1, :], raw_a[:, :-1, :]), axis=2)\n outputs = raw_z[:, 1:, :] # teacher forcing (shift by one predictions)\n feed = {rnn.input_x: inputs, rnn.output_x: outputs, rnn.lr: curr_learning_rate}\n\n # train rnn model\n (train_cost, state, train_step, _) = rnn.sess.run([rnn.cost, rnn.final_state, rnn.global_step, rnn.train_op], feed)\n\n if (step % 20 == 0 and step > 0):\n end = time.time()\n time_taken = end - start\n start = time.time()\n output_log = \"step: %d, lr: %.6f, cost: %.4f, train_time_taken: %.4f\" % (step, curr_learning_rate, train_cost, time_taken)\n print(output_log)\n\n# save the model (don't bother with tf checkpoints json all the way ...)\nrnn.save_json(os.path.join(model_save_path, \"rnn.json\"))\n"
] | [
[
"tensorflow.nn.dynamic_rnn",
"tensorflow.get_variable",
"tensorflow.device",
"numpy.sqrt",
"numpy.concatenate",
"numpy.round",
"numpy.random.randn",
"tensorflow.train.AdamOptimizer",
"numpy.exp",
"tensorflow.reduce_logsumexp",
"tensorflow.Graph",
"tensorflow.Variable",
"numpy.copy",
"tensorflow.Session",
"tensorflow.trainable_variables",
"numpy.zeros",
"tensorflow.nn.xw_plus_b",
"tensorflow.placeholder",
"tensorflow.exp",
"numpy.random.standard_cauchy",
"tensorflow.global_variables_initializer",
"numpy.random.rand",
"tensorflow.split",
"numpy.array",
"tensorflow.clip_by_value",
"tensorflow.reduce_mean",
"tensorflow.contrib.rnn.DropoutWrapper",
"tensorflow.reshape",
"tensorflow.variable_scope"
],
[
"numpy.set_printoptions",
"numpy.concatenate",
"numpy.copy",
"numpy.random.permutation",
"numpy.random.randn",
"numpy.exp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Tony-Tan/Reinforcement_Leanring_An_Introduction | [
"285b93b0108bb3401623149129fad4ec863db0d5"
] | [
"environment/k_arm_bandit.py"
] | [
"import copy\n\nimport numpy as np\nfrom environment.basic_classes import Space\n\n\n# class bandit:\n# def __init__(self, value_mean=0.0, value_var=1.0):\n# \"\"\"\n# bandit, reward is produced by a normal distribution with mean and variance;\n# :param value_mean: mean\n# :param value_var: variance\n# \"\"\"\n# self.value_mean = value_mean\n# self.value_var = value_var\n#\n# def run(self):\n# return np.random.normal(self.value_mean, self.value_var, 1)[0]\n\n\nclass KArmedBandit:\n def __init__(self, value_mean_array_, value_deviation_array_):\n self._k_value_mean = value_mean_array_\n self._k_value_deviation = value_deviation_array_\n self._k = len(value_mean_array_)\n self.action_space = Space([i for i in range(self._k)])\n self.optimal_action = np.flatnonzero(self._k_value_mean == self._k_value_mean.max())\n\n def reset(self):\n pass\n\n def step(self, action_):\n current_state = []\n if action_ < self._k:\n for i in self.action_space:\n current_state.append(\n np.random.normal(self._k_value_mean[i], self._k_value_deviation[i], 1)[0])\n return current_state, current_state[action_], False, {}\n else:\n raise ValueError(\"action must be a number less than k\")\n\n\nclass KArmedBanditRW(KArmedBandit):\n def __init__(self, value_mean_array_, value_deviation_array_, random_walk_mean_=0, random_walk_deviation_=0.01):\n super(KArmedBanditRW, self).__init__(value_mean_array_, value_deviation_array_)\n self._random_walk_mean = random_walk_mean_\n self._random_walk_deviation = random_walk_deviation_\n\n def step(self, action_):\n delta = np.random.normal(self._random_walk_mean, self._random_walk_deviation, self._k)\n self._k_value_mean += delta\n return super(KArmedBanditRW, self).step(action_)\n\n\nif __name__ == '__main__':\n env = KArmedBandit(np.random.normal(.0, 1.0, 10), np.ones(10))\n env_rw = KArmedBanditRW(np.random.normal(.0, 1.0, 10), np.ones(10))\n"
] | [
[
"numpy.random.normal",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
haleqiu/DROID-SLAM | [
"b7e09308d7672d22b28cd23ed401e2b4a4b9bf8d"
] | [
"droid_slam/factor_graph.py"
] | [
"import torch\nimport lietorch\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom lietorch import SE3\nfrom modules.corr import CorrBlock, AltCorrBlock\nimport geom.projective_ops as pops\n\n\nclass FactorGraph:\n def __init__(self, video, update_op, device=\"cuda:0\", corr_impl=\"volume\", max_factors=-1):\n self.video = video\n self.update_op = update_op\n self.device = device\n self.max_factors = max_factors\n self.corr_impl = corr_impl\n\n # operator at 1/8 resolution\n self.ht = ht = video.ht // 8\n self.wd = wd = video.wd // 8\n\n self.coords0 = pops.coords_grid(ht, wd, device=device)\n self.ii = torch.as_tensor([], dtype=torch.long, device=device)\n self.jj = torch.as_tensor([], dtype=torch.long, device=device)\n self.age = torch.as_tensor([], dtype=torch.long, device=device)\n\n self.corr, self.net, self.inp = None, None, None\n self.damping = 1e-6 * torch.ones_like(self.video.disps)\n\n self.target = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float)\n self.weight = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float)\n\n # inactive factors\n self.ii_inac = torch.as_tensor([], dtype=torch.long, device=device)\n self.jj_inac = torch.as_tensor([], dtype=torch.long, device=device)\n self.ii_bad = torch.as_tensor([], dtype=torch.long, device=device)\n self.jj_bad = torch.as_tensor([], dtype=torch.long, device=device)\n\n self.target_inac = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float)\n self.weight_inac = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float)\n\n def __filter_repeated_edges(self, ii, jj):\n \"\"\" remove duplicate edges \"\"\"\n\n keep = torch.zeros(ii.shape[0], dtype=torch.bool, device=ii.device)\n eset = set(\n [(i.item(), j.item()) for i, j in zip(self.ii, self.jj)] +\n [(i.item(), j.item()) for i, j in zip(self.ii_inac, self.jj_inac)])\n\n for k, (i, j) in enumerate(zip(ii, jj)):\n keep[k] = (i.item(), j.item()) not in eset\n\n return ii[keep], jj[keep]\n\n def print_edges(self):\n ii = self.ii.cpu().numpy()\n jj = self.jj.cpu().numpy()\n\n ix = np.argsort(ii)\n ii = ii[ix]\n jj = jj[ix]\n\n w = torch.mean(self.weight, dim=[0,2,3,4]).cpu().numpy()\n w = w[ix]\n for e in zip(ii, jj, w):\n print(e)\n print()\n\n def filter_edges(self):\n \"\"\" remove bad edges \"\"\"\n conf = torch.mean(self.weight, dim=[0,2,3,4])\n mask = (torch.abs(self.ii-self.jj) > 2) & (conf < 0.001)\n\n self.ii_bad = torch.cat([self.ii_bad, self.ii[mask]])\n self.jj_bad = torch.cat([self.jj_bad, self.jj[mask]])\n self.rm_factors(mask, store=False)\n\n def clear_edges(self):\n self.rm_factors(self.ii >= 0)\n self.net = None\n self.inp = None\n\n @torch.cuda.amp.autocast(enabled=True)\n def add_factors(self, ii, jj, remove=False):\n \"\"\" add edges to factor graph \"\"\"\n\n if not isinstance(ii, torch.Tensor):\n ii = torch.as_tensor(ii, dtype=torch.long, device=self.device)\n\n if not isinstance(jj, torch.Tensor):\n jj = torch.as_tensor(jj, dtype=torch.long, device=self.device)\n\n # remove duplicate edges\n ii, jj = self.__filter_repeated_edges(ii, jj)\n\n\n if ii.shape[0] == 0:\n return\n\n # place limit on number of factors\n if self.max_factors > 0 and self.ii.shape[0] + ii.shape[0] > self.max_factors \\\n and self.corr is not None and remove:\n \n ix = torch.arange(len(self.age))[torch.argsort(self.age).cpu()]\n self.rm_factors(ix >= self.max_factors - ii.shape[0], store=True)\n\n net = self.video.nets[ii].to(self.device).unsqueeze(0)\n\n # correlation volume for new edges\n if self.corr_impl == \"volume\":\n c = (ii == jj).long()\n fmap1 = self.video.fmaps[ii,0].to(self.device).unsqueeze(0)\n fmap2 = self.video.fmaps[jj,c].to(self.device).unsqueeze(0)\n corr = CorrBlock(fmap1, fmap2)\n self.corr = corr if self.corr is None else self.corr.cat(corr)\n\n inp = self.video.inps[ii].to(self.device).unsqueeze(0)\n self.inp = inp if self.inp is None else torch.cat([self.inp, inp], 1)\n\n with torch.cuda.amp.autocast(enabled=False):\n target, _ = self.video.reproject(ii, jj)\n weight = torch.zeros_like(target)\n\n self.ii = torch.cat([self.ii, ii], 0)\n self.jj = torch.cat([self.jj, jj], 0)\n self.age = torch.cat([self.age, torch.zeros_like(ii)], 0)\n\n # reprojection factors\n self.net = net if self.net is None else torch.cat([self.net, net], 1)\n\n self.target = torch.cat([self.target, target], 1)\n self.weight = torch.cat([self.weight, weight], 1)\n\n @torch.cuda.amp.autocast(enabled=True)\n def rm_factors(self, mask, store=False):\n \"\"\" drop edges from factor graph \"\"\"\n\n # store estimated factors\n if store:\n self.ii_inac = torch.cat([self.ii_inac, self.ii[mask]], 0)\n self.jj_inac = torch.cat([self.jj_inac, self.jj[mask]], 0)\n self.target_inac = torch.cat([self.target_inac, self.target[:,mask]], 1)\n self.weight_inac = torch.cat([self.weight_inac, self.weight[:,mask]], 1)\n\n self.ii = self.ii[~mask]\n self.jj = self.jj[~mask]\n self.age = self.age[~mask]\n \n if self.corr_impl == \"volume\":\n self.corr = self.corr[~mask]\n\n if self.net is not None:\n self.net = self.net[:,~mask]\n\n if self.inp is not None:\n self.inp = self.inp[:,~mask]\n\n self.target = self.target[:,~mask]\n self.weight = self.weight[:,~mask]\n\n\n @torch.cuda.amp.autocast(enabled=True)\n def rm_keyframe(self, ix):\n \"\"\" drop edges from factor graph \"\"\"\n\n\n with self.video.get_lock():\n self.video.poses[ix] = self.video.poses[ix+1]\n self.video.disps[ix] = self.video.disps[ix+1]\n self.video.disps_sens[ix] = self.video.disps_sens[ix+1]\n self.video.intrinsics[ix] = self.video.intrinsics[ix+1]\n\n self.video.nets[ix] = self.video.nets[ix+1]\n self.video.inps[ix] = self.video.inps[ix+1]\n self.video.fmaps[ix] = self.video.fmaps[ix+1]\n\n m = (self.ii_inac == ix) | (self.jj_inac == ix)\n self.ii_inac[self.ii_inac >= ix] -= 1\n self.jj_inac[self.jj_inac >= ix] -= 1\n\n if torch.any(m):\n self.ii_inac = self.ii_inac[~m]\n self.jj_inac = self.jj_inac[~m]\n self.target_inac = self.target_inac[:,~m]\n self.weight_inac = self.weight_inac[:,~m]\n\n m = (self.ii == ix) | (self.jj == ix)\n\n self.ii[self.ii >= ix] -= 1\n self.jj[self.jj >= ix] -= 1\n self.rm_factors(m, store=False)\n\n\n @torch.cuda.amp.autocast(enabled=True)\n def update(self, t0=None, t1=None, itrs=2, use_inactive=False, EP=1e-7, motion_only=False):\n \"\"\" run update operator on factor graph \"\"\"\n\n # motion features\n with torch.cuda.amp.autocast(enabled=False):\n coords1, mask = self.video.reproject(self.ii, self.jj)\n motn = torch.cat([coords1 - self.coords0, self.target - coords1], dim=-1)\n motn = motn.permute(0,1,4,2,3).clamp(-64.0, 64.0)\n \n # correlation features\n corr = self.corr(coords1)\n\n self.net, delta, weight, damping, upmask = \\\n self.update_op(self.net, self.inp, corr, motn, self.ii, self.jj)\n\n if t0 is None:\n t0 = max(1, self.ii.min().item()+1)\n\n with torch.cuda.amp.autocast(enabled=False):\n self.target = coords1 + delta.to(dtype=torch.float)\n self.weight = weight.to(dtype=torch.float)\n\n ht, wd = self.coords0.shape[0:2]\n self.damping[torch.unique(self.ii)] = damping\n\n if use_inactive:\n m = (self.ii_inac >= t0 - 3) & (self.jj_inac >= t0 - 3)\n ii = torch.cat([self.ii_inac[m], self.ii], 0)\n jj = torch.cat([self.jj_inac[m], self.jj], 0)\n target = torch.cat([self.target_inac[:,m], self.target], 1)\n weight = torch.cat([self.weight_inac[:,m], self.weight], 1)\n\n else:\n ii, jj, target, weight = self.ii, self.jj, self.target, self.weight\n\n\n damping = .2 * self.damping[torch.unique(ii)].contiguous() + EP\n\n target = target.view(-1, ht, wd, 2).permute(0,3,1,2).contiguous()\n weight = weight.view(-1, ht, wd, 2).permute(0,3,1,2).contiguous()\n\n # dense bundle adjustment\n self.video.ba(target, weight, damping, ii, jj, t0, t1, \n itrs=itrs, lm=1e-4, ep=0.1, motion_only=motion_only)\n \n self.age += 1\n\n\n @torch.cuda.amp.autocast(enabled=False)\n def update_lowmem(self, t0=None, t1=None, itrs=2, use_inactive=False, EP=1e-7, steps=8):\n \"\"\" run update operator on factor graph - reduced memory implementation \"\"\"\n\n # alternate corr implementation\n t = self.video.counter.value\n\n num, rig, ch, ht, wd = self.video.fmaps.shape\n corr_op = AltCorrBlock(self.video.fmaps.view(1, num*rig, ch, ht, wd))\n\n for step in range(steps):\n print(\"Global BA Iteration #{}\".format(step+1))\n with torch.cuda.amp.autocast(enabled=False):\n coords1, mask = self.video.reproject(self.ii, self.jj)\n motn = torch.cat([coords1 - self.coords0, self.target - coords1], dim=-1)\n motn = motn.permute(0,1,4,2,3).clamp(-64.0, 64.0)\n\n s = 8\n for i in range(0, self.jj.max()+1, s):\n v = (self.ii >= i) & (self.ii < i + s)\n iis = self.ii[v]\n jjs = self.jj[v]\n\n ht, wd = self.coords0.shape[0:2]\n corr1 = corr_op(coords1[:,v], rig * iis, rig * jjs + (iis == jjs).long())\n\n with torch.cuda.amp.autocast(enabled=True):\n \n net, delta, weight, damping, _ = \\\n self.update_op(self.net[:,v], self.video.inps[None,iis], corr1, motn[:,v], iis, jjs)\n\n\n self.net[:,v] = net\n self.target[:,v] = coords1[:,v] + delta.float()\n self.weight[:,v] = weight.float()\n self.damping[torch.unique(iis)] = damping\n\n damping = .2 * self.damping[torch.unique(self.ii)].contiguous() + EP\n target = self.target.view(-1, ht, wd, 2).permute(0,3,1,2).contiguous()\n weight = self.weight.view(-1, ht, wd, 2).permute(0,3,1,2).contiguous()\n\n # dense bundle adjustment\n self.video.ba(target, weight, damping, self.ii, self.jj, 1, t, \n itrs=itrs, lm=1e-5, ep=1e-2, motion_only=False)\n\n self.video.dirty[:t] = True\n\n def add_neighborhood_factors(self, t0, t1, r=3):\n \"\"\" add edges between neighboring frames within radius r \"\"\"\n\n ii, jj = torch.meshgrid(torch.arange(t0,t1), torch.arange(t0,t1))\n ii = ii.reshape(-1).to(dtype=torch.long, device=self.device)\n jj = jj.reshape(-1).to(dtype=torch.long, device=self.device)\n\n c = 1 if self.video.stereo else 0\n\n keep = ((ii - jj).abs() > c) & ((ii - jj).abs() <= r)\n self.add_factors(ii[keep], jj[keep])\n\n \n def add_proximity_factors(self, t0=0, t1=0, rad=2, nms=2, beta=0.25, thresh=16.0, remove=False):\n \"\"\" add edges to the factor graph based on distance \"\"\"\n\n t = self.video.counter.value\n ix = torch.arange(t0, t)\n jx = torch.arange(t1, t)\n\n ii, jj = torch.meshgrid(ix, jx)\n ii = ii.reshape(-1)\n jj = jj.reshape(-1)\n\n d = self.video.distance(ii, jj, beta=beta)\n d[ii - rad < jj] = np.inf\n d[d > 100] = np.inf\n\n ii1 = torch.cat([self.ii, self.ii_bad, self.ii_inac], 0)\n jj1 = torch.cat([self.jj, self.jj_bad, self.jj_inac], 0)\n for i, j in zip(ii1.cpu().numpy(), jj1.cpu().numpy()):\n for di in range(-nms, nms+1):\n for dj in range(-nms, nms+1):\n if abs(di) + abs(dj) <= max(min(abs(i-j)-2, nms), 0):\n i1 = i + di\n j1 = j + dj\n\n if (t0 <= i1 < t) and (t1 <= j1 < t):\n d[(i1-t0)*(t-t1) + (j1-t1)] = np.inf\n\n\n es = []\n for i in range(t0, t):\n if self.video.stereo:\n es.append((i, i))\n d[(i-t0)*(t-t1) + (i-t1)] = np.inf\n\n for j in range(max(i-rad-1,0), i):\n es.append((i,j))\n es.append((j,i))\n d[(i-t0)*(t-t1) + (j-t1)] = np.inf\n\n ix = torch.argsort(d)\n for k in ix:\n if d[k].item() > thresh:\n continue\n\n if len(es) > self.max_factors:\n break\n\n i = ii[k]\n j = jj[k]\n \n # bidirectional\n es.append((i, j))\n es.append((j, i))\n\n for di in range(-nms, nms+1):\n for dj in range(-nms, nms+1):\n if abs(di) + abs(dj) <= max(min(abs(i-j)-2, nms), 0):\n i1 = i + di\n j1 = j + dj\n\n if (t0 <= i1 < t) and (t1 <= j1 < t):\n d[(i1-t0)*(t-t1) + (j1-t1)] = np.inf\n\n ii, jj = torch.as_tensor(es, device=self.device).unbind(dim=-1)\n self.add_factors(ii, jj, remove)\n"
] | [
[
"torch.mean",
"torch.abs",
"torch.zeros",
"torch.cat",
"torch.zeros_like",
"torch.cuda.amp.autocast",
"torch.any",
"torch.unique",
"torch.arange",
"numpy.argsort",
"torch.argsort",
"torch.meshgrid",
"torch.ones_like",
"torch.as_tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
malk271828/pytorch-toolbelt | [
"d8a7d25c887c5f1c9a6c8e07e8b887bc6fc4617c"
] | [
"pytorch_toolbelt/inference/ensembling.py"
] | [
"from torch import nn, Tensor\nfrom typing import List, Union\n\n__all__ = [\"ApplySoftmaxTo\", \"ApplySigmoidTo\", \"Ensembler\", \"PickModelOutput\"]\n\n\nclass ApplySoftmaxTo(nn.Module):\n def __init__(self, model: nn.Module, output_key: Union[str, List[str]] = \"logits\", dim=1, temperature=1):\n \"\"\"\n Apply softmax activation on given output(s) of the model\n :param model: Model to wrap\n :param output_key: string or list of strings, indicating to what outputs softmax activation should be applied.\n :param dim: Tensor dimension for softmax activation\n :param temperature: Temperature scaling coefficient. Values > 1 will make logits sharper.\n \"\"\"\n super().__init__()\n output_key = output_key if isinstance(output_key, (list, tuple)) else [output_key]\n # By converting to set, we prevent double-activation by passing output_key=[\"logits\", \"logits\"]\n self.output_keys = set(output_key)\n self.model = model\n self.dim = dim\n self.temperature = temperature\n\n def forward(self, *input, **kwargs):\n output = self.model(*input, **kwargs)\n for key in self.output_keys:\n output[key] = output[key].mul(self.temperature).softmax(dim=1)\n return output\n\n\nclass ApplySigmoidTo(nn.Module):\n def __init__(self, model: nn.Module, output_key: Union[str, List[str]] = \"logits\", temperature=1):\n \"\"\"\n Apply sigmoid activation on given output(s) of the model\n :param model: Model to wrap\n :param output_key: string or list of strings, indicating to what outputs sigmoid activation should be applied.\n :param temperature: Temperature scaling coefficient. Values > 1 will make logits sharper.\n \"\"\"\n super().__init__()\n output_key = output_key if isinstance(output_key, (list, tuple)) else [output_key]\n # By converting to set, we prevent double-activation by passing output_key=[\"logits\", \"logits\"]\n self.output_keys = set(output_key)\n self.model = model\n self.temperature = temperature\n\n def forward(self, *input, **kwargs): # skipcq: PYL-W0221\n output = self.model(*input, **kwargs)\n for key in self.output_keys:\n output[key] = output[key].mul(self.temperature).sigmoid()\n return output\n\n\nclass Ensembler(nn.Module):\n \"\"\"\n Compute sum (or average) of outputs of several models.\n \"\"\"\n\n def __init__(self, models: List[nn.Module], average=True, outputs=None):\n \"\"\"\n\n :param models:\n :param average:\n :param outputs: Name of model outputs to average and return from Ensembler.\n If None, all outputs from the first model will be used.\n \"\"\"\n super().__init__()\n self.outputs = outputs\n self.models = nn.ModuleList(models)\n self.average = average\n\n def forward(self, *input, **kwargs): # skipcq: PYL-W0221\n output_0 = self.models[0](*input, **kwargs)\n num_models = len(self.models)\n\n if self.outputs:\n keys = self.outputs\n else:\n keys = output_0.keys()\n\n for index in range(1, num_models):\n output_i = self.models[index](*input, **kwargs)\n\n # Sum outputs\n for key in keys:\n output_0[key].add_(output_i[key])\n\n if self.average:\n for key in keys:\n output_0[key].mul_(1. / num_models)\n\n return output_0\n\n\nclass PickModelOutput(nn.Module):\n \"\"\"\n Assuming you have a model that outputs a dictionary, this module returns only a given element by it's key\n \"\"\"\n\n def __init__(self, model: nn.Module, key: str):\n super().__init__()\n self.model = model\n self.target_key = key\n\n def forward(self, *input, **kwargs) -> Tensor:\n output = self.model(*input, **kwargs)\n return output[self.target_key]\n"
] | [
[
"torch.nn.ModuleList"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
estherrolf/torchgeo | [
"c69bd1559b45e5d2bdbadd795bb32d6c0f1ffb48"
] | [
"torchgeo/datamodules/oscd.py"
] | [
"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n\"\"\"OSCD datamodule.\"\"\"\n\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport kornia.augmentation as K\nimport pytorch_lightning as pl\nimport torch\nfrom einops import repeat\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.utils.data._utils.collate import default_collate\nfrom torchvision.transforms import Compose, Normalize\n\nfrom ..datasets import OSCD\nfrom .utils import dataset_split\n\n\nclass OSCDDataModule(pl.LightningDataModule):\n \"\"\"LightningDataModule implementation for the OSCD dataset.\n\n Uses the train/test splits from the dataset and further splits\n the train split into train/val splits.\n\n .. versionadded: 0.2\n \"\"\"\n\n band_means = torch.tensor( # type: ignore[attr-defined]\n [\n 1583.0741,\n 1374.3202,\n 1294.1616,\n 1325.6158,\n 1478.7408,\n 1933.0822,\n 2166.0608,\n 2076.4868,\n 2306.0652,\n 690.9814,\n 16.2360,\n 2080.3347,\n 1524.6930,\n ]\n )\n\n band_stds = torch.tensor( # type: ignore[attr-defined]\n [\n 52.1937,\n 83.4168,\n 105.6966,\n 151.1401,\n 147.4615,\n 115.9289,\n 123.1974,\n 114.6483,\n 141.4530,\n 73.2758,\n 4.8368,\n 213.4821,\n 179.4793,\n ]\n )\n\n def __init__(\n self,\n root_dir: str,\n bands: str = \"all\",\n train_batch_size: int = 32,\n num_workers: int = 0,\n val_split_pct: float = 0.2,\n patch_size: Tuple[int, int] = (64, 64),\n num_patches_per_tile: int = 32,\n **kwargs: Any,\n ) -> None:\n \"\"\"Initialize a LightningDataModule for OSCD based DataLoaders.\n\n Args:\n root_dir: The ``root`` arugment to pass to the OSCD Dataset classes\n bands: \"rgb\" or \"all\"\n train_batch_size: The batch size used in the train DataLoader\n (val_batch_size == test_batch_size == 1)\n num_workers: The number of workers to use in all created DataLoaders\n val_split_pct: What percentage of the dataset to use as a validation set\n patch_size: Size of random patch from image and mask (height, width)\n num_patches_per_tile: number of random patches per sample\n \"\"\"\n super().__init__() # type: ignore[no-untyped-call]\n self.root_dir = root_dir\n self.bands = bands\n self.train_batch_size = train_batch_size\n self.num_workers = num_workers\n self.val_split_pct = val_split_pct\n self.patch_size = patch_size\n self.num_patches_per_tile = num_patches_per_tile\n\n if bands == \"rgb\":\n self.band_means = self.band_means[[3, 2, 1], None, None]\n self.band_stds = self.band_stds[[3, 2, 1], None, None]\n else:\n self.band_means = self.band_means[:, None, None]\n self.band_stds = self.band_stds[:, None, None]\n\n self.norm = Normalize(self.band_means, self.band_stds)\n self.rcrop = K.AugmentationSequential(\n K.RandomCrop(patch_size), data_keys=[\"input\", \"mask\"], same_on_batch=True\n )\n self.padto = K.PadTo((1280, 1280))\n\n def preprocess(self, sample: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Transform a single sample from the Dataset.\"\"\"\n sample[\"image\"] = sample[\"image\"].float()\n sample[\"mask\"] = sample[\"mask\"]\n sample[\"image\"] = self.norm(sample[\"image\"])\n sample[\"image\"] = torch.flatten( # type: ignore[attr-defined]\n sample[\"image\"], 0, 1\n )\n return sample\n\n def prepare_data(self) -> None:\n \"\"\"Make sure that the dataset is downloaded.\n\n This method is only called once per run.\n \"\"\"\n OSCD(self.root_dir, split=\"train\", bands=self.bands, checksum=False)\n\n def setup(self, stage: Optional[str] = None) -> None:\n \"\"\"Initialize the main ``Dataset`` objects.\n\n This method is called once per GPU per run.\n \"\"\"\n\n def n_random_crop(sample: Dict[str, Any]) -> Dict[str, Any]:\n images, masks = [], []\n for i in range(self.num_patches_per_tile):\n mask = repeat(sample[\"mask\"], \"h w -> t h w\", t=2).float()\n image, mask = self.rcrop(sample[\"image\"], mask)\n mask = mask.squeeze()[0]\n images.append(image.squeeze())\n masks.append(mask.long())\n sample[\"image\"] = torch.stack(images)\n sample[\"mask\"] = torch.stack(masks)\n return sample\n\n def pad_to(sample: Dict[str, Any]) -> Dict[str, Any]:\n sample[\"image\"] = self.padto(sample[\"image\"])[0]\n sample[\"mask\"] = self.padto(sample[\"mask\"].float()).long()[0, 0]\n return sample\n\n train_transforms = Compose([self.preprocess, n_random_crop])\n # for testing and validation we pad all inputs to a fixed size to avoid issues\n # with the upsampling paths in encoder-decoder architectures\n test_transforms = Compose([self.preprocess, pad_to])\n\n train_dataset = OSCD(\n self.root_dir, split=\"train\", bands=self.bands, transforms=train_transforms\n )\n\n self.train_dataset: Dataset[Any]\n self.val_dataset: Dataset[Any]\n\n if self.val_split_pct > 0.0:\n val_dataset = OSCD(\n self.root_dir,\n split=\"train\",\n bands=self.bands,\n transforms=test_transforms,\n )\n self.train_dataset, self.val_dataset, _ = dataset_split(\n train_dataset, val_pct=self.val_split_pct, test_pct=0.0\n )\n self.val_dataset.dataset = val_dataset\n else:\n self.train_dataset = train_dataset\n self.val_dataset = train_dataset\n\n self.test_dataset = OSCD(\n self.root_dir, split=\"test\", bands=self.bands, transforms=test_transforms\n )\n\n def train_dataloader(self) -> DataLoader[Any]:\n \"\"\"Return a DataLoader for training.\"\"\"\n\n def collate_wrapper(batch: List[Dict[str, Any]]) -> Dict[str, Any]:\n r_batch: Dict[str, Any] = default_collate( # type: ignore[no-untyped-call]\n batch\n )\n r_batch[\"image\"] = torch.flatten( # type: ignore[attr-defined]\n r_batch[\"image\"], 0, 1\n )\n r_batch[\"mask\"] = torch.flatten( # type: ignore[attr-defined]\n r_batch[\"mask\"], 0, 1\n )\n return r_batch\n\n return DataLoader(\n self.train_dataset,\n batch_size=self.train_batch_size,\n num_workers=self.num_workers,\n collate_fn=collate_wrapper,\n shuffle=True,\n )\n\n def val_dataloader(self) -> DataLoader[Any]:\n \"\"\"Return a DataLoader for validation.\"\"\"\n return DataLoader(\n self.val_dataset, batch_size=1, num_workers=self.num_workers, shuffle=False\n )\n\n def test_dataloader(self) -> DataLoader[Any]:\n \"\"\"Return a DataLoader for testing.\"\"\"\n return DataLoader(\n self.test_dataset, batch_size=1, num_workers=self.num_workers, shuffle=False\n )\n"
] | [
[
"torch.utils.data.DataLoader",
"torch.tensor",
"torch.utils.data._utils.collate.default_collate",
"torch.flatten",
"torch.stack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
uc-eqgeo/rnc2-earthquakes | [
"cfa6a68ab4bb3fee7a06683683f131d6413c53d1",
"cfa6a68ab4bb3fee7a06683683f131d6413c53d1"
] | [
"src/rsqsim_api/rsqsim_api/io/read_utils.py",
"src/rsqsim_api/rsqsim_api/fault/slip.py"
] | [
"import os\n\nimport meshio\nimport numpy as np\nimport pandas as pd\nimport ezdxf\n\ncatalogue_columns = [\"t0\", \"m0\", \"mw\", \"x\", \"y\", \"z\", \"area\", \"dt\"]\n\n\ndef read_binary(file: str, format: str, endian: str = \"little\"):\n \"\"\"\n Reads integer values from binary files that are output of RSQSim\n\n :param file: file to read\n :param format: either \"d\" (double) or \"i\" (integer)\n :param endian: usually \"little\" unless we end up running on a non-standard system\n :return:\n \"\"\"\n # Check that parameter supplied for endianness makes sense\n assert endian in (\"little\", \"big\"), \"Must specify either 'big' or 'little' endian\"\n endian_sign = \"<\" if endian == \"little\" else \">\"\n assert format in (\"d\", \"i\")\n assert os.path.exists(file)\n if format == \"d\":\n numbers = np.fromfile(file, endian_sign + \"f8\").flatten()\n else:\n numbers = np.fromfile(file, endian_sign + \"i4\").flatten()\n\n return numbers\n\n\ndef read_csv_and_array(prefix: str, read_index: bool = True):\n assert prefix, \"Empty prefix string supplied\"\n if prefix[-1] != \"_\":\n prefix += \"_\"\n suffixes = [\"catalogue.csv\", \"events.npy\", \"patches.npy\", \"slip.npy\", \"slip_time.npy\"]\n file_list = [prefix + suffix for suffix in suffixes]\n for file, suffix in zip(file_list, suffixes):\n if not os.path.exists(file):\n raise FileNotFoundError(\"{} file missing!\".format(suffix))\n if read_index:\n df = pd.read_csv(file_list[0], index_col=0)\n else:\n df = pd.read_csv(file_list[0])\n array_ls = [np.load(file) for file in file_list[1:]]\n\n return [df] + array_ls\n\n\n\ndef read_earthquakes(earthquake_file: str, get_patch: bool = False, eq_start_index: int = None,\n eq_end_index: int = None, endian: str = \"little\"):\n \"\"\"\n Reads earthquakes, inferring list file names from prefix of earthquake file.\n Based on R scripts by Keith Richards-Dinger.\n\n :param earthquake_file: usually has a \".out\" suffix\n :param get_patch:\n :param eq_start_index:\n :param eq_end_index:\n :param endian:\n :return:\n \"\"\"\n assert endian in (\"little\", \"big\"), \"Must specify either 'big' or 'little' endian\"\n assert os.path.exists(earthquake_file)\n if not any([a is None for a in (eq_start_index, eq_end_index)]):\n if eq_start_index >= eq_end_index:\n raise ValueError(\"eq_start index should be smaller than eq_end_index!\")\n\n # Get full path to file and working directory\n abs_file_path = os.path.abspath(earthquake_file)\n file_base_name = os.path.basename(abs_file_path)\n\n # Get file prefix from basename\n split_by_dots = file_base_name.split(\".\")\n # Check that filename fits expected format\n if not all([split_by_dots[0] == \"eqs\", split_by_dots[-1] == \"out\"]):\n print(\"Warning: non-standard file name.\")\n print(\"Expecting earthquake file name to have the format: eqs.{prefix}.out\")\n print(\"using 'catalogue' as prefix...\")\n prefix = \"catalogue\"\n else:\n # Join prefix back together if necessary, warning if empty\n prefix_list = split_by_dots[1:-1]\n if len(prefix_list) == 1:\n prefix = prefix_list[0]\n if prefix.strip() == \"\":\n print(\"Warning: empty prefix string\")\n else:\n prefix = \".\".join(*prefix_list)\n\n # Search for binary files in directory\n tau_file = abs_file_path + \"/tauDot.{}.out\".format(prefix)\n sigmat_file = abs_file_path + \"/sigmaDot.{}.out\".format(prefix)\n\n\ndef read_earthquake_catalogue(catalogue_file: str):\n\n assert os.path.exists(catalogue_file)\n\n with open(catalogue_file, \"r\") as fid:\n data = fid.readlines()\n\n start_eqs = data.index(\"%%% end input files\\n\") + 1\n data_array = np.loadtxt(data[start_eqs:])\n earthquake_catalogue = pd.DataFrame(data_array[:, :8], columns=catalogue_columns)\n return earthquake_catalogue\n\n\n\n\n# def read_fault(fault_file_name: str, check_if_grid: bool = True, )\n\ndef read_ts_coords(filename):\n \"\"\"\n This script reads in the tsurf (*.ts) files for the SCEC Community Fault Model (cfm)\n as a numpy array.\n The script is based on the matlab script ReadAndSaveCfm.m by Brendan Meade available\n from http://structure.rc.fas.harvard.edu/cfm/download/meade/ReadAndSaveCfm.m\n Copyright Paul Kaeufl, July 2014\n \"\"\"\n\n f = open(filename, 'r')\n lines = f.readlines()\n f.close()\n idxVrtx = [idx for idx, l in enumerate(lines)\n if 'VRTX' in l or 'PVRTX' in l]\n idxTrgl = [idx for idx, l in enumerate(lines) if 'TRGL' in l]\n nVrtx = len(idxVrtx)\n nTrgl = len(idxTrgl)\n vrtx = np.zeros((nVrtx, 4))\n trgl = np.zeros((nTrgl, 3), dtype='int')\n tri = np.zeros((nTrgl, 9))\n for k, iVrtx in enumerate(idxVrtx):\n line = lines[iVrtx]\n tmp = line.split()\n vrtx[k] = [int(tmp[1]), float(tmp[2]), float(tmp[3]), float(tmp[4])]\n\n for k, iTrgl in enumerate(idxTrgl):\n line = lines[iTrgl]\n tmp = line.split(' ')\n trgl[k] = [int(tmp[1]), int(tmp[2]), int(tmp[3])]\n for l in range(3):\n i1 = l * 3\n i2 = 3 * (l + 1)\n vertex_i = vrtx[vrtx[:, 0] == trgl[k, l]][0]\n tri[k, i1:i2] = vertex_i[1:]\n return vrtx, trgl, tri\n\n\ndef read_dxf(dxf_file: str):\n \"\"\"\n Reads mesh and boundary from dxf file exported from move. Returns boundary (as array) and triangles\n \"\"\"\n assert os.path.exists(dxf_file)\n dxf = ezdxf.readfile(dxf_file)\n msp = dxf.modelspace()\n dxftypes = [e.dxftype() for e in msp]\n assert all([a in dxftypes for a in (\"3DFACE\", \"POLYLINE\")]), \"{}: Expected triangles and boundary\".format(dxf_file)\n if dxftypes.count(\"POLYLINE\") > 1:\n raise ValueError(\"{}: Too many boundaries lines...\".format(dxf_file))\n\n\n triangle_ls = []\n boundary_array = None\n for entity in msp:\n if entity.dxftype() == \"3DFACE\":\n triangle = np.array([vertex.xyz for vertex in entity])\n unique_triangle = np.unique(triangle, axis=0).reshape((9,))\n triangle_ls.append(unique_triangle)\n\n elif entity.dxftype() == \"POLYLINE\":\n boundary_ls = []\n for point in entity.points():\n boundary_ls.append(point.xyz)\n boundary_array = np.array(boundary_ls)\n\n triangle_array = np.array(triangle_ls)\n\n return triangle_array, boundary_array\n\n\ndef read_stl(stl_file: str):\n assert os.path.exists(stl_file)\n\n mesh = meshio.read(stl_file)\n\n assert \"triangle\" in mesh.cells_dict.keys()\n triangles = mesh.cells_dict[\"triangle\"]\n point_dict = {i: point for i, point in enumerate(mesh.points)}\n mesh_as_array = np.array([np.hstack([point_dict[vertex] for vertex in tri]) for tri in triangles])\n return mesh_as_array\n\n\n",
"import geopandas as gpd\nimport numpy as np\nfrom shapely.geometry import LineString, Polygon, Point\nimport os\nimport pandas as pd\n\nfrom pyproj import Transformer\n\ntransformer = Transformer.from_crs(4326, 2193, always_xy=True)\ntrans_inv = Transformer.from_crs(2193, 4326, always_xy=True)\n\n\ndef fit_plane_to_points(points: np.ndarray, eps: float=1.0e-5):\n \"\"\"\n Find best-fit plane through a set of points, after first insuring the plane goes through\n the mean (centroid) of all the points in the array. This is probably better than my\n initial method, since the SVD is only over a 3x3 array (rather than the num_pointsxnum_points\n array).\n Returned values are:\n plane_normal: Normal vector to plane (A, B, C)\n plane_origin: Point on plane that may be considered as the plane origin\n \"\"\"\n # Compute plane origin and subract it from the points array.\n plane_origin = np.mean(points, axis=0)\n x = points - plane_origin\n\n # Dot product to yield a 3x3 array.\n moment = np.dot(x.T, x)\n\n # Extract single values from SVD computation to get normal.\n plane_normal = np.linalg.svd(moment)[0][:,-1]\n small = np.where(np.abs(plane_normal) < eps)\n plane_normal[small] = 0.0\n plane_normal /= np.linalg.norm(plane_normal)\n if (plane_normal[-1] < 0.0):\n plane_normal *= -1.0\n\n return plane_normal, plane_origin\n\n\n# Locations of points where slip rate changes\neast_cape = Point(178.9916, -39.1775)\nstart_0_2 = Point(180.0, -37.00)\nend_0_2 = Point(-177.3995, -32.5061)\nstart_0_5 = Point(-176.673, -31.016)\nconvergence_start = Point(179.098, -39.014)\nconvergence_end = Point(-174.162, -27.508)\n\n\n\n\n\ndef point_dist(point: Point):\n return np.dot(along_overall, np.array(transformer.transform(point.x, point.y)))\n\ndef point_dist_nztm(point: Point):\n return float(np.dot(along_overall, np.array([point.x, point.y])))\n\neast_cape_dist = point_dist(east_cape)\nstart_0_2_dist = point_dist(start_0_2)\nend_0_2_dist = point_dist(end_0_2)\nstart_0_5_dist = point_dist(start_0_5)\nconvergence_start_dist = point_dist(convergence_start)\nconvergence_end_dist = point_dist(convergence_end)\n\ndef coupling(dist: float):\n assert dist >= east_cape_dist\n if dist < start_0_2_dist:\n return 0.2 # * (dist - east_cape_dist) / (start_0_2_dist - east_cape_dist)\n elif dist < end_0_2_dist:\n return 0.2\n\n elif dist > start_0_5_dist:\n return 0.5\n else:\n # Linear gradient in the middle between two uniform areas\n return 0.2 + (0.5 - 0.2) * (dist - end_0_2_dist) / (start_0_5_dist - end_0_2_dist)\n\ndef convergence(dist: float):\n \"\"\"\n Linear between 49 mm/yr at -39 to 85 mm/yr at -27.5\n \"\"\"\n south_conv = 49.\n north_conv = 85.\n\n return south_conv + (north_conv - south_conv) * (dist - convergence_start_dist) / (convergence_end_dist -\n convergence_start_dist)\n\n\ndef convergence_dist(dist):\n pass\n\ndef kermadec_slip_rate(dist: float, modelled_value: float = 0.):\n if modelled_value > 0.:\n frac = (dist - east_cape_dist) / (start_0_2_dist - east_cape_dist)\n print(frac)\n return modelled_value * (1 - frac) + convergence(dist) * coupling(dist) * frac\n else:\n return convergence(dist) * coupling(dist)"
] | [
[
"numpy.hstack",
"pandas.read_csv",
"numpy.fromfile",
"numpy.unique",
"pandas.DataFrame",
"numpy.load",
"numpy.array",
"numpy.zeros",
"numpy.loadtxt"
],
[
"numpy.dot",
"numpy.linalg.svd",
"numpy.abs",
"numpy.linalg.norm",
"numpy.mean",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
w1ll1am-davis/lecture0 | [
"0c1ae34c69c9ff236457f52897af14839a4839e8",
"0c1ae34c69c9ff236457f52897af14839a4839e8"
] | [
"ocr/generate_samples.py",
"ocr/ocr_decoder.py"
] | [
"import time\nfrom pathlib import Path\nfrom random import choice\n\nimport cv2\nimport numpy as np\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\nfrom skimage.morphology import square, dilation\n\n\ndef get_grid_char_img(fonts_paths):\n font_name = choice(fonts_paths)\n size = np.random.randint(5, 40)\n font = ImageFont.truetype(font_name, size)\n\n image_size = 256\n\n img = 255 * np.ones((image_size, image_size, 3), np.uint8)\n mask = np.zeros((image_size, image_size), np.uint8)\n\n pil_img = Image.fromarray(img)\n draw = ImageDraw.Draw(pil_img)\n step = int(min(image_size / (1.2 * size), 30))\n for i in range(step):\n for j in range(step):\n\n start_x = int(i * size * 1.2)\n start_y = int(j * size * 1.2)\n\n if np.random.uniform(0, 1) < 0.2:\n integer = choice([1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n color = (\n (0, 0, 0)\n if np.random.uniform(0, 1) < 0.9\n else (\n np.random.randint(0, 255),\n np.random.randint(0, 255),\n np.random.randint(0, 255),\n )\n )\n\n draw.text((start_x, start_y), str(integer), color, font=font)\n\n img = np.array(pil_img)\n\n char_box = (\n 255\n - img[\n start_y : int(start_y + 1.2 * size),\n start_x : int(start_x + 1.2 * size),\n :,\n ]\n )\n char_mask = mask[\n start_y : int(start_y + 1.2 * size),\n start_x : int(start_x + 1.2 * size),\n ]\n char_mask[char_box[..., 0] > 10] = integer\n mask[\n start_y : int(start_y + 1.2 * size),\n start_x : int(start_x + 1.2 * size),\n ] = dilation(char_mask, square(3))\n\n for i in range(step):\n for j in range(step):\n\n start_x = int(i * size * 1.2) - 0.3 * size\n start_y = int(j * size * 1.2) + 0.1 * size\n\n if np.random.uniform(0, 1) < 0.05:\n draw.line(\n (start_x, 0, start_x, image_size),\n fill=(\n np.random.randint(0, 255),\n np.random.randint(0, 255),\n np.random.randint(0, 255),\n ),\n width=np.random.randint(0, 5),\n )\n\n if np.random.uniform(0, 1) < 0.05:\n draw.line(\n (0, start_y, image_size, start_y),\n fill=(\n np.random.randint(0, 255),\n np.random.randint(0, 255),\n np.random.randint(0, 255),\n ),\n width=np.random.randint(0, 5),\n )\n\n img = np.array(pil_img)\n\n if np.random.uniform(0, 1) < 0.1:\n\n for i in range(3):\n img[..., i] = (\n np.clip(1 - np.fabs(np.random.normal(0, 0.2)), 0, 1) * img[..., i]\n )\n\n return img, mask\n\n\ndef get_char_img(fonts_paths):\n font_name = choice(fonts_paths)\n size = np.random.randint(7, 40)\n font = ImageFont.truetype(font_name, size)\n\n image_size = int(np.random.uniform(0.9, 1.4) * size)\n\n img = 255 * np.ones((image_size, image_size, 3), np.uint8)\n\n pil_img = Image.fromarray(img)\n draw = ImageDraw.Draw(pil_img)\n\n integer = choice([1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n color = (\n (0, 0, 0)\n if np.random.uniform(0, 1) < 0.9\n else (\n np.random.randint(0, 255),\n np.random.randint(0, 255),\n np.random.randint(0, 255),\n )\n )\n\n draw.text(\n (np.random.randint(0, size // 2 + 1), np.random.randint(0, size // 5)),\n str(integer),\n color,\n font=font,\n )\n\n img = np.array(pil_img)\n\n img = cv2.resize(img, (32, 32))\n\n if np.random.uniform(0, 1) < 0.1:\n\n for i in range(3):\n img[..., i] = (\n np.clip(1 - np.fabs(np.random.normal(0, 0.2)), 0, 1) * img[..., i]\n )\n\n return img, integer\n\n\nif __name__ == \"__main__\":\n start = time.time()\n\n fonts_paths = [str(x) for x in Path(\"ttf\").glob(\"*.otf\")] + [\n str(x) for x in Path(\"ttf\").glob(\"*.ttf\")\n ]\n\n img, mask = get_grid_char_img(fonts_paths=fonts_paths)\n\n cv2.imwrite(\"img.png\", img)\n cv2.imwrite(\"mask.png\", 30 * mask)\n\n print(time.time() - start)\n\n img, label = get_char_img(fonts_paths=fonts_paths)\n\n cv2.imwrite(\"char_%s.png\" % label, img)\n",
"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom skimage import measure\n\nfrom ocr.ocr_detector import get_detector\nfrom ocr.ocr_recognizer import get_recognizer\n\n\ndef mask_to_bboxes(show_mask, threshold=40):\n label_image = measure.label(show_mask, background=0, connectivity=2)\n\n all_chars = []\n\n for region in measure.regionprops(label_image):\n if region.area >= threshold:\n minr, minc, maxr, maxc = region.bbox\n\n all_chars.append(\n {\"char\": None, \"minc\": minc, \"maxc\": maxc, \"minr\": minr, \"maxr\": maxr}\n )\n\n return all_chars\n\n\ndef predict_mask(detector_model, img):\n mask_pred = detector_model.predict(img[np.newaxis, ...].astype(np.float))\n mask_pred = (mask_pred > 0.5).astype(np.int).squeeze()\n return mask_pred\n\n\ndef predict_char_class(recognizer_model, img, all_chars):\n list_bboxes = []\n\n for char in all_chars:\n minr, minc, maxr, maxc = char[\"minr\"], char[\"minc\"], char[\"maxr\"], char[\"maxc\"]\n size = max(maxr - minr, maxc - minc)\n\n list_bboxes.append(img[minr : (minr + size), minc : (minc + size), :])\n\n list_bboxes = [cv2.resize(x, (32, 32)) for x in list_bboxes]\n\n array_bboxes = np.array(list_bboxes).astype(np.float)\n\n preds = recognizer_model.predict(array_bboxes).argmax(axis=-1).ravel().tolist()\n\n # list_bboxes = [cv2.imwrite(\"%s_%s.png\" % (j, i), x) for j, (i, x) in enumerate(zip(preds, list_bboxes))]\n\n for char, pred in zip(all_chars, preds):\n char[\"char\"] = pred\n\n return all_chars\n\n\ndef bucket_l(l, cutoff=10):\n res = [[]]\n\n for x in l:\n if len(res[-1]) == 0 or abs(res[-1][-1] - x) < cutoff:\n res[-1].append(x)\n else:\n res.append([x])\n\n return res\n\n\ndef infer_rows_and_cols(chars):\n cutoff = 10\n\n row = [(x[\"maxr\"] + x[\"minr\"]) / 2 for x in chars]\n col = [(x[\"maxc\"] + x[\"minc\"]) / 2 for x in chars]\n\n row = sorted(row)\n col = sorted(col)\n\n row = bucket_l(row, cutoff=cutoff)\n col = bucket_l(col, cutoff=cutoff)\n\n row = [np.median(x) for x in row]\n col = [np.median(x) for x in col]\n\n grid = []\n\n for r in row:\n r_i = []\n for c in col:\n char = 0\n for c_char in chars:\n if (\n abs((c_char[\"minc\"] + c_char[\"maxc\"]) / 2 - c)\n + abs((c_char[\"minr\"] + c_char[\"maxr\"]) / 2 - r)\n ) < 2 * cutoff:\n char = c_char[\"char\"]\n break\n r_i.append(char)\n grid.append(r_i)\n\n return grid\n\n\ndef img_to_grid(\n img, detector_model, recognizer_model, plot_path=None, print_result=False\n):\n img = cv2.resize(img, (256, 256))\n\n show_mask = predict_mask(detector_model, img)\n\n all_chars = mask_to_bboxes(show_mask)\n\n all_chars = predict_char_class(recognizer_model, img, all_chars)\n\n if plot_path is not None:\n\n fig, ax = plt.subplots(figsize=(15, 15))\n plt.axis(\"off\")\n\n ax.imshow(img, cmap=plt.cm.gray)\n\n for char in all_chars:\n minr, minc, maxr, maxc = (\n char[\"minr\"],\n char[\"minc\"],\n char[\"maxr\"],\n char[\"maxc\"],\n )\n\n bx = (minc, maxc, maxc, minc, minc)\n by = (minr, minr, maxr, maxr, minr)\n\n ax.plot(bx, by, \"-b\", linewidth=1)\n ax.text(minc, minr, str(char[\"char\"]), fontsize=24)\n\n plt.savefig(plot_path, bbox_inches=\"tight\", pad_inches=0)\n\n grid = infer_rows_and_cols(all_chars)\n\n if print_result:\n for r in grid:\n print(r)\n\n return grid\n\n\nif __name__ == \"__main__\":\n detector_model_h5 = \"ocr_detector.h5\"\n detector_model = get_detector()\n detector_model.load_weights(detector_model_h5)\n\n recognizer_model_h5 = \"ocr_recognizer.h5\"\n recognizer_model = get_recognizer()\n recognizer_model.load_weights(recognizer_model_h5)\n\n img = cv2.imread(\"example6.png\")\n\n img_to_grid(\n img, detector_model, recognizer_model, plot_path=\"plot.png\", print_result=False\n )\n"
] | [
[
"numpy.ones",
"numpy.random.normal",
"numpy.random.uniform",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
],
[
"numpy.median",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.axis",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SherwynBraganza31/csc514-crypto | [
"b4b9641c37041e465e652f5d84398101746d518b"
] | [
"Number_Theory/mod_inv.py"
] | [
"from Number_Theory.optimized_gcd import *\nimport numpy as np\n\n##################################################################\n# Function : mod_inv\n# Utilizes the extended gcd function defined in optimized_gcd.py\n# to find the modular inverse of a mod(n) when a and n are\n# relatively prime.\n#\n# Throws an error if a and n are not relatively prime.\n#\n# params : a - The number who's mod inverse needs to be found\n# : n - The mod number\n#\n# returns: nothing\n#################################################################\ndef mod_inv(a, n):\n if a < 0:\n a = a + n\n\n if a > n:\n a = a % n\n\n g, x, y = inner_ex_gcd(a, n)\n if g != 1:\n raise Exception('Mod inv does not exist because gcd != 1')\n else:\n return x % n\n\n##################################################################\n# Function : mod_inv\n# Implements the mod inverse\n#\n# Throws an error if a and n are not relatively prime.\n#\n# params : matrix - The matrix who's mod inverse needs to be found\n# : n - The mod number\n#\n# returns: nothing\n#################################################################\ndef matrix_mod_inv(matrix, n):\n det = np.linalg.det(matrix)\n matrix_inv = np.linalg.inv(matrix) * det\n det = round(det) % n\n\n with np.nditer(matrix_inv, op_flags=['readwrite']) as it:\n for x in it:\n x[...] = int((np.matrix.round(x) * mod_inv(det,n)) % n)\n\n matrix_inv.astype(int)\n return matrix_inv\n\n\n\n\n\n\n"
] | [
[
"numpy.linalg.det",
"numpy.linalg.inv",
"numpy.nditer",
"numpy.matrix.round"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
STAR-Center/selfSupervisedDescriptor | [
"f1fee51aee64914faf0a0af78cf9854a7230552c",
"f1fee51aee64914faf0a0af78cf9854a7230552c"
] | [
"data/3dmatch/desc2txt.py",
"data/augment.py"
] | [
"import sys\nimport numpy as np\nsys.path.append('../..')\nfrom data.datagenerator import DataGenerator\n\nif __name__ == '__main__':\n if(len(sys.argv) != 3):\n print('Usage: python thisfile.py desc.bin desc.txt')\n sys.exit(1)\n\n pc_mat = DataGenerator.load_point_cloud(sys.argv[1], 3+32)\n\n np.savetxt(sys.argv[2], pc_mat[:,3:], delimiter=',', encoding=None)\n\n\n\n\n\n\n\n",
"import numpy as np\n\n\ndef get_augmentations_from_list(str_list, upright_axis=2):\n '''\n :param str_list: List of string indicating the augmentation type\n :param upright_axis: Set to 1 for modelnet (i.e. y-axis is vertical axis), but 2 otherwise (i.e. z-axis)\n :return:\n '''\n\n if str_list is None:\n return []\n\n augmentations = []\n if 'Rotate1D' in str_list:\n if upright_axis == 1:\n augmentations.append(RotateY())\n elif upright_axis == 2:\n augmentations.append(RotateZ())\n if 'Jitter' in str_list:\n augmentations.append(Jitter())\n if 'Scale' in str_list:\n augmentations.append(Scale())\n if 'RotateSmall' in str_list:\n augmentations.append(RotateSmall())\n if 'Shift' in str_list:\n augmentations.append(Shift())\n\n return augmentations\n\n\nclass Augmentation(object):\n\n def apply(self, data):\n raise NotImplementedError\n\n\nclass Jitter(Augmentation):\n '''\n Applies a small jitter to the position of each point\n '''\n\n def __init__(self, sigma=0.01, clip=0.05):\n self.sigma = sigma\n self.clip = clip\n\n def apply(self, data):\n assert (self.clip > 0)\n jittered_data = np.clip(self.sigma * np.random.randn(*data.shape), -1 * self.clip, self.clip)\n jittered_data += data\n\n return jittered_data\n\n\nclass Shift(Augmentation):\n\n def __init__(self, shift_range=0.1):\n self.shift_range = shift_range\n\n def apply(self, data):\n shift = np.random.uniform(-self.shift_range, self.shift_range, 3)\n data += shift\n\n return data\n\n\nclass RotateZ(Augmentation):\n '''\n Rotation perturbation around Z-axis.\n '''\n\n def apply(self, data):\n rotation_angle = np.random.uniform() * 2 * np.pi\n cosval = np.cos(rotation_angle)\n sinval = np.sin(rotation_angle)\n rotation_matrix = np.array([[cosval, sinval, 0],\n [-sinval, cosval, 0],\n [0, 0, 1]])\n rotated_data = np.dot(data, rotation_matrix)\n\n return rotated_data\n\nclass RotateY(Augmentation):\n '''\n Rotation perturbation around Y-axis.\n '''\n\n def apply(self, data):\n rotation_angle = np.random.uniform() * 2 * np.pi\n cosval = np.cos(rotation_angle)\n sinval = np.sin(rotation_angle)\n rotation_matrix = np.array([[cosval, 0, sinval],\n [0, 1, 0],\n [-sinval, 0, cosval]])\n rotated_data = np.dot(data, rotation_matrix)\n\n return rotated_data\n\n\nclass RotateSmall(Augmentation):\n '''\n Applies a small rotation perturbation around all axes\n '''\n def __init__(self, angle_sigma=0.06, angle_clip=0.18):\n self.angle_sigma = angle_sigma\n self.angle_clip = angle_clip\n\n def apply(self, data):\n angles = np.clip(self.angle_sigma * np.random.randn(3), -self.angle_clip, self.angle_clip)\n Rx = np.array([[1, 0, 0],\n [0, np.cos(angles[0]), -np.sin(angles[0])],\n [0, np.sin(angles[0]), np.cos(angles[0])]])\n Ry = np.array([[np.cos(angles[1]), 0, np.sin(angles[1])],\n [0, 1, 0],\n [-np.sin(angles[1]), 0, np.cos(angles[1])]])\n Rz = np.array([[np.cos(angles[2]), -np.sin(angles[2]), 0],\n [np.sin(angles[2]), np.cos(angles[2]), 0],\n [0, 0, 1]])\n R = np.dot(Rz, np.dot(Ry, Rx))\n\n rotated_data = np.dot(data, R)\n\n return rotated_data\n\nclass RotateLarge_(Augmentation):\n '''\n Applies a small rotation perturbation around all axes\n '''\n def __init__(self, angle_sigma=0.06, angle_clip=0.18):\n self.angle_sigma = angle_sigma\n self.angle_clip = angle_clip\n\n def apply(self, data):\n angles = np.clip(self.angle_sigma * np.random.randn(3), -self.angle_clip, self.angle_clip)\n Rx = np.array([[1, 0, 0],\n [0, np.cos(angles[0]), -np.sin(angles[0])],\n [0, np.sin(angles[0]), np.cos(angles[0])]])\n Ry = np.array([[np.cos(angles[1]), 0, np.sin(angles[1])],\n [0, 1, 0],\n [-np.sin(angles[1]), 0, np.cos(angles[1])]])\n Rz = np.array([[np.cos(angles[2]), -np.sin(angles[2]), 0],\n [np.sin(angles[2]), np.cos(angles[2]), 0],\n [0, 0, 1]])\n R = np.dot(Rz, np.dot(Ry, Rx))\n\n rotated_data = np.dot(data, R)\n\n return rotated_data, R.T\n \n\nclass Scale(Augmentation):\n\n def __init__(self, scale_low=0.8, scale_high=1.25):\n self.scale_low = scale_low\n self.scale_high = scale_high\n\n def apply(self, data, keypoints=None):\n scale = np.random.uniform(self.scale_low, self.scale_high)\n data *= scale\n\n return data\n\n"
] | [
[
"numpy.savetxt"
],
[
"numpy.dot",
"numpy.cos",
"numpy.sin",
"numpy.random.randn",
"numpy.random.uniform",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ZhiangChen/tornado_gp | [
"224a5c4fdc867d9da2eeafbad21738d60f074fbd"
] | [
"average_results.py"
] | [
"\"\"\"\naverage results\nZhiang Chen, Oct 2\n\"\"\"\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntraining = True\nif training:\n npy_files = [f for f in os.listdir('results') if 'true' not in f]\nelse:\n npy_files = [f for f in os.listdir('results') if 'true' in f]\n\n\nresults_all = np.zeros((200, 200, len(npy_files)), dtype=float)\nfor i, f in enumerate(npy_files):\n result = np.load('results/'+f)\n results_all[:, :, i] = result[:, :, 0]\n\nresult_mean = np.mean(results_all, axis=2)\nplt.imshow(result_mean)\nplt.show()"
] | [
[
"numpy.load",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.show",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kaijieshi7/pytorch-loss | [
"24bd6716cc5f347b634041e4582cc728d0adccd6"
] | [
"pytorch_loss/label_smooth.py"
] | [
"#!/usr/bin/python\n# -*- encoding: utf-8 -*-\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.cuda.amp as amp\n\n\n\n##\n# version 1: use torch.autograd\nclass LabelSmoothSoftmaxCEV1(nn.Module):\n '''\n This is the autograd version, you can also try the LabelSmoothSoftmaxCEV2 that uses derived gradients\n '''\n\n def __init__(self, lb_smooth=0.1, reduction='mean', ignore_index=-100):\n super(LabelSmoothSoftmaxCEV1, self).__init__()\n self.lb_smooth = lb_smooth\n self.reduction = reduction\n self.lb_ignore = ignore_index\n self.log_softmax = nn.LogSoftmax(dim=1)\n\n def forward(self, logits, label):\n '''\n args: logits: tensor of shape (N, C, H, W)\n args: label: tensor of shape(N, H, W)\n '''\n # overcome ignored label\n logits = logits.float() # use fp32 to avoid nan\n with torch.no_grad():\n num_classes = logits.size(1)\n label = label.clone().detach()\n ignore = label.eq(self.lb_ignore)\n n_valid = ignore.eq(0).sum()\n label[ignore] = 0\n lb_pos, lb_neg = 1. - self.lb_smooth, self.lb_smooth / num_classes\n lb_one_hot = torch.empty_like(logits).fill_(\n lb_neg).scatter_(1, label.unsqueeze(1), lb_pos).detach()\n\n logs = self.log_softmax(logits)\n loss = -torch.sum(logs * lb_one_hot, dim=1)\n loss[ignore] = 0\n if self.reduction == 'mean':\n loss = loss.sum() / n_valid\n if self.reduction == 'sum':\n loss = loss.sum()\n\n return loss\n\n\n\n##\n# version 2: user derived grad computation\nclass LSRCrossEntropyFunctionV2(torch.autograd.Function):\n\n @staticmethod\n @amp.custom_fwd(cast_inputs=torch.float32)\n def forward(ctx, logits, label, lb_smooth, lb_ignore):\n # prepare label\n num_classes = logits.size(1)\n lb_pos, lb_neg = 1. - lb_smooth, lb_smooth / num_classes\n label = label.clone().detach()\n ignore = label.eq(lb_ignore)\n n_valid = ignore.eq(0).sum()\n label[ignore] = 0\n lb_one_hot = torch.empty_like(logits).fill_(\n lb_neg).scatter_(1, label.unsqueeze(1), lb_pos).detach()\n\n ignore = ignore.nonzero(as_tuple=False)\n _, M = ignore.size()\n a, *b = ignore.chunk(M, dim=1)\n mask = [a, torch.arange(logits.size(1)), *b]\n lb_one_hot[mask] = 0\n coeff = (num_classes - 1) * lb_neg + lb_pos\n\n ctx.variables = coeff, mask, logits, lb_one_hot\n\n loss = torch.log_softmax(logits, dim=1).neg_().mul_(lb_one_hot).sum(dim=1)\n return loss\n\n @staticmethod\n @amp.custom_bwd\n def backward(ctx, grad_output):\n coeff, mask, logits, lb_one_hot = ctx.variables\n\n scores = torch.softmax(logits, dim=1).mul_(coeff)\n grad = scores.sub_(lb_one_hot).mul_(grad_output.unsqueeze(1))\n grad[mask] = 0\n return grad, None, None, None\n\n\nclass LabelSmoothSoftmaxCEV2(nn.Module):\n\n def __init__(self, lb_smooth=0.1, reduction='mean', ignore_index=-100):\n super(LabelSmoothSoftmaxCEV2, self).__init__()\n self.lb_smooth = lb_smooth\n self.reduction = reduction\n self.lb_ignore = ignore_index\n\n def forward(self, logits, labels):\n losses = LSRCrossEntropyFunctionV2.apply(\n logits, labels, self.lb_smooth, self.lb_ignore)\n if self.reduction == 'sum':\n losses = losses.sum()\n elif self.reduction == 'mean':\n n_valid = (labels != self.lb_ignore).sum()\n losses = losses.sum() / n_valid\n return losses\n\n##\n# version 3: implement wit cpp/cuda to save memory and accelerate\nimport lsr_cpp\nclass LSRCrossEntropyFunctionV3(torch.autograd.Function):\n '''\n use cpp/cuda to accelerate and shrink memory usage\n '''\n @staticmethod\n @amp.custom_fwd(cast_inputs=torch.float32)\n def forward(ctx, logits, labels, lb_smooth, lb_ignore):\n losses = lsr_cpp.lsr_forward(logits, labels, lb_ignore, lb_smooth)\n\n ctx.variables = logits, labels, lb_ignore, lb_smooth\n return losses\n\n @staticmethod\n @amp.custom_bwd\n def backward(ctx, grad_output):\n logits, labels, lb_ignore, lb_smooth = ctx.variables\n\n grad = lsr_cpp.lsr_backward(logits, labels, lb_ignore, lb_smooth)\n grad.mul_(grad_output.unsqueeze(1))\n return grad, None, None, None\n\n\nclass LabelSmoothSoftmaxCEV3(nn.Module):\n\n def __init__(self, lb_smooth=0.1, reduction='mean', ignore_index=-100):\n super(LabelSmoothSoftmaxCEV3, self).__init__()\n self.lb_smooth = lb_smooth\n self.reduction = reduction\n self.lb_ignore = ignore_index\n\n def forward(self, logits, labels):\n losses = LSRCrossEntropyFunctionV3.apply(\n logits, labels, self.lb_smooth, self.lb_ignore)\n if self.reduction == 'sum':\n losses = losses.sum()\n elif self.reduction == 'mean':\n n_valid = (labels != self.lb_ignore).sum()\n losses = losses.sum() / n_valid\n return losses\n\n\nif __name__ == '__main__':\n import torchvision\n import torch\n import numpy as np\n import random\n torch.manual_seed(15)\n random.seed(15)\n np.random.seed(15)\n torch.backends.cudnn.deterministic = True\n\n class Model(nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n net = torchvision.models.resnet18(pretrained=False)\n self.conv1 = net.conv1\n self.bn1 = net.bn1\n self.maxpool = net.maxpool\n self.relu = net.relu\n self.layer1 = net.layer1\n self.layer2 = net.layer2\n self.layer3 = net.layer3\n self.layer4 = net.layer4\n self.fc = nn.Conv2d(512, 19, 3, 1, 1)\n def forward(self, x):\n feat = self.conv1(x)\n feat = self.bn1(feat)\n feat = self.relu(feat)\n feat = self.maxpool(feat)\n feat = self.layer1(feat)\n feat = self.layer2(feat)\n feat = self.layer3(feat)\n feat = self.layer4(feat)\n feat = self.fc(feat)\n out = F.interpolate(feat, x.size()[2:], mode='bilinear', align_corners=True)\n return out\n\n net1 = Model()\n net2 = Model()\n net2.load_state_dict(net1.state_dict())\n red = 'mean'\n criteria1 = LabelSmoothSoftmaxCEV2(lb_smooth=0.1, ignore_index=255, reduction=red)\n criteria2 = LabelSmoothSoftmaxCEV1(lb_smooth=0.1, ignore_index=255, reduction=red)\n net1.cuda()\n net2.cuda()\n net1.train()\n net2.train()\n criteria1.cuda()\n criteria2.cuda()\n\n optim1 = torch.optim.SGD(net1.parameters(), lr=1e-2)\n optim2 = torch.optim.SGD(net2.parameters(), lr=1e-2)\n\n bs = 64\n for it in range(300):\n inten = torch.randn(bs, 3, 224, 224).cuda()\n lbs = torch.randint(0, 19, (bs, 224, 224)).cuda()\n lbs[1, 1, 1] = 255\n lbs[30, 3, 2:200] = 255\n lbs[18, 4:7, 8:200] = 255\n logits = net1(inten)\n loss1 = criteria1(logits, lbs)\n optim1.zero_grad()\n loss1.backward()\n optim1.step()\n # print(net1.fc.weight[:, :5])\n logits = net2(inten)\n loss2 = criteria2(logits, lbs)\n optim2.zero_grad()\n loss2.backward()\n optim2.step()\n # net1.load_state_dict(net2.state_dict())\n # print(net2.fc.weight[:, :5])\n with torch.no_grad():\n if (it+1) % 50 == 0:\n print('iter: {}, ================='.format(it+1))\n # print(net1.fc.weight.numel())\n print('fc weight: ', torch.mean(torch.abs(net1.fc.weight - net2.fc.weight)).item())\n\n print('conv1 weight: ', torch.mean(torch.abs(net1.conv1.weight - net2.conv1.weight)).item())\n print('loss: ', loss1.item() - loss2.item())\n"
] | [
[
"torch.abs",
"torch.softmax",
"torch.nn.LogSoftmax",
"torch.randint",
"torch.empty_like",
"numpy.random.seed",
"torch.manual_seed",
"torch.randn",
"torch.nn.Conv2d",
"torch.sum",
"torch.cuda.amp.custom_fwd",
"torch.log_softmax",
"torch.no_grad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cvoelcker/spn-pytorch-experiments | [
"495d1fddf00f76fe28e926f7e558b26089e5428e",
"495d1fddf00f76fe28e926f7e558b26089e5428e",
"495d1fddf00f76fe28e926f7e558b26089e5428e"
] | [
"src/models/models.py",
"src/spn/layers.py",
"src/models/experiment.py"
] | [
"\"\"\"\nContains classes for the comparison of models on the MNIST dataset.\nMain models:\n- MLPNet: Feed forward NN with linear layers\n- SPNNet: Same as MLPNet but replaces certain layers with SPNLayer\n- SPNNeuron: Defines the SPN architecture of a single neuron in a SPNLayer\n\"\"\"\nimport logging\nimport time\n\nimport numpy as np\nimport torch\nfrom torch import distributions as dist\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom src.models.pytorch import GaussianNode, ProductNode, SumNode\nfrom src.models.resnet import resnet18, resnet34, resnet50, resnet101, resnet152\nfrom src.spn.distributions import Normal\nfrom src.spn import layers\nfrom src.utils.utils import count_params\nfrom src.utils.utils import time_delta_now\n\nlogger = logging.getLogger(__name__)\n\n###########\n# Neurons #\n###########\n\n\nclass SPNNeuronShallow(nn.Module):\n \"\"\"\n SPN Neuron implementation using the vectorized layers.\n \"\"\"\n\n def __init__(self, in_features, n_gaussians=3):\n \"\"\"\n Initialize the SPNNeuronShallow.\n\n Args:\n in_features: Number of input features.\n n_gaussians: Number of different pairwise independence mixtures of the leaf nodes.\n\n \"\"\"\n # Init\n super().__init__()\n self.n_gaussians = n_gaussians\n self.in_features = in_features\n\n self.gauss = Normal(multiplicity=3, in_features=in_features)\n self.prod = layers.Product(in_features=128, cardinality=2)\n self.sum = layers.Sum(in_channels=3, in_features=64, out_channels=1)\n self.out = layers.Product(in_features=64, cardinality=64)\n\n # Randomize features\n self.rand_idxs = torch.tensor(np.random.permutation(in_features))\n\n def forward(self, x):\n # Random permutation\n x = x[:, self.rand_idxs]\n\n x = self.gauss(x)\n x = self.prod(x)\n x = self.sum(x)\n x = self.out(x)\n return x\n\n\nclass SPNNeuronBig(nn.Module):\n \"\"\"\n SPN Neuron implementation using the vectorized layers.\n \"\"\"\n\n def __init__(self, in_features, n_gaussians=3):\n \"\"\"\n Initialize the SPNNeuron.\n\n Args:\n in_features: Number of input features.\n n_gaussians: Number of different pairwise independence mixtures of the leaf nodes.\n\n \"\"\"\n # Init\n super().__init__()\n self.n_gaussians = n_gaussians\n self.in_features = in_features\n\n ch = [2 ** i for i in range(4, 0, -1)]\n\n # self.spn = nn.Sequential(\n # Normal(multiplicity=n_gaussians, in_channels=1, in_features=in_features),\n # layers.Sum(\n # in_channels=n_gaussians, in_features=in_features, out_channels=ch[0]\n # ),\n # layers.Product(in_features=in_features, cardinality=2),\n # layers.Sum(\n # in_channels=ch[0], in_features=in_features / 2, out_channels=ch[1]\n # ),\n # layers.Product(in_features=in_features / 2, cardinality=2),\n # layers.Sum(\n # in_channels=ch[1], in_features=in_features / 4, out_channels=ch[2]\n # ),\n # layers.Product(in_features=in_features / 4, cardinality=2),\n # layers.Sum(\n # in_channels=ch[2], in_features=in_features / 8, out_channels=ch[3]\n # ),\n # layers.Product(in_features=in_features / 8, cardinality=2),\n # layers.Sum(in_channels=ch[3], in_features=in_features / 16, out_channels=1),\n # layers.Product(in_features=in_features / 16, cardinality=in_features // 16),\n # )\n\n ch = [1, 1, 1, 1]\n card = 5\n self.spn = nn.Sequential(\n Normal(multiplicity=n_gaussians, in_features=in_features),\n layers.Sum(\n in_channels=n_gaussians, in_features=in_features, out_channels=ch[0]\n ),\n layers.Product(in_features=in_features, cardinality=card),\n layers.Sum(\n in_channels=ch[0], in_features=in_features / 5, out_channels=ch[1]\n ),\n layers.Product(in_features=in_features / 5, cardinality=card),\n layers.Sum(\n in_channels=ch[1], in_features=in_features / 5 ** 2, out_channels=ch[2]\n ),\n layers.Product(in_features=in_features / 5 ** 2, cardinality=card),\n layers.Sum(\n in_channels=ch[2], in_features=in_features / 5 ** 3, out_channels=ch[3]\n ),\n layers.Product(in_features=in_features / 5 ** 3, cardinality=card),\n layers.Sum(\n in_channels=ch[3], in_features=in_features / 5 ** 4, out_channels=1\n ),\n layers.Product(\n in_features=in_features / 5 ** 4, cardinality=in_features // 5 ** 4\n ),\n )\n\n # Randomize features\n self.rand_idxs = torch.tensor(np.random.permutation(in_features))\n\n def forward(self, x):\n x = x[:, self.rand_idxs]\n x = self.spn(x)\n return x\n\n\n# class SPNNeuron(nn.Module):\n# def __init__(self, in_features, n_gaussians=3):\n# \"\"\"\n# Initialize the SPNNeuron.\n\n# Args:\n# in_features: Number of input features.\n# n_gaussians: Number of different pairwise independence mixtures of the leaf nodes.\n\n# \"\"\"\n# # Init\n# super().__init__()\n# self.n_gaussians = n_gaussians\n# self.in_features = in_features\n\n# # Create gaussian means and stds\n# self.means = nn.Parameter(torch.randn(n_gaussians, 1, in_features))\n# self.stds = nn.Parameter(torch.rand(n_gaussians, 1, in_features))\n# self.gauss = dist.Normal(loc=self.means, scale=self.stds)\n\n# # Create random sequence of scopes\n# scopes = np.random.permutation(in_features)\n\n# # sums = []\n\n# self.product_scopes_left = []\n# self.product_scopes_right = []\n\n# # Sum weights\n# self.sum_weights = nn.Parameter(torch.rand(n_gaussians, int(in_features / 2)))\n\n# # For two consecutive (random) scopes\n# for i in range(0, in_features, 2):\n# # Collect scopes\n# self.product_scopes_left.append(scopes[i])\n# self.product_scopes_right.append(scopes[i + 1])\n\n# def forward(self, x, marginals=[]):\n# # First apply gaussian\n# # Expand x to match the gaussian mean/std matrix\n# batch_size = x.shape[0]\n# x = x.expand([self.n_gaussians, batch_size, self.in_features])\n# x = self.gauss.log_prob(x)\n\n# # Marginalize certain leaf nodes: Set likelihood of the leaf to 1 (log(1)=0)\n# x[:, :, marginals] = 0.0\n\n# # Current dimensions: n_gaussian x batch_size x in_features\n# # ______\n# # / /|\n# # /_____/ |\n# # | | /\n# # | | /\n# # |____|/\n\n# # Apply products between features i and j: X[:, :, i] * X[:, :, j] ( sum in logspace )\n# x = x[:, :, self.product_scopes_left] + x[:, :, self.product_scopes_right]\n\n# # Current dimensions: n_gaussian x batch_size x in_features / 2\n# # ______\n# # / /|\n# # /_____/ |\n# # | | /\n# # | | /\n# # |____|/\n\n# # Apply sum over the n_gaussian axis (dim=0)\n# x = torch.logsumexp(x + torch.log(self.sum_weights.unsqueeze(1)), dim=0)\n\n# # Current dimensions: batch_size x in_features / 2\n# # ____\n# # | |\n# # | |\n# # |____|\n\n# # Apply product over all features ( sum in logspace )\n# x = torch.sum(x, dim=1)\n\n# return x\n\n\n# class MaxOutSpnNeuron(nn.Module):\n# def __init__(self, in_features, n_gaussians=3):\n# \"\"\"\n# Initialize the SPNNeuron.\n\n# Args:\n# in_features: Number of input features.\n# n_gaussians: Number of different pairwise independence mixtures of the leaf nodes.\n\n# \"\"\"\n# # Init\n# super(MaxOutSpnNeuron, self).__init__()\n# self.n_gaussians = n_gaussians\n# self.in_features = in_features\n\n# # Create gaussian means and stds\n# self.means = nn.Parameter(torch.randn(n_gaussians, 1, in_features))\n# self.stds = nn.Parameter(torch.rand(n_gaussians, 1, in_features))\n# self.gauss = dist.Normal(loc=self.means, scale=self.stds)\n\n# # Create random sequence of scopes\n# scopes = np.random.permutation(in_features)\n\n# # sums = []\n\n# self.product_scopes_left = []\n# self.product_scopes_right = []\n\n# # Sum weights\n# self.sum_weights = nn.Parameter(torch.rand(n_gaussians, int(in_features / 2)))\n\n# # For two consecutive (random) scopes\n# for i in range(0, in_features, 2):\n# # Collect scopes\n# self.product_scopes_left.append(scopes[i])\n# self.product_scopes_right.append(scopes[i + 1])\n\n# def forward(self, x, marginals=[]):\n# # First apply gaussian\n# # Expand x to match the gaussian mean/std matrix\n# batch_size = x.shape[0]\n# x = x.expand([self.n_gaussians, batch_size, self.in_features])\n# x = self.gauss.log_prob(x)\n\n# # Marginalize certain leaf nodes: Set likelihood of the leaf to 1 (log(1)=0)\n# x[:, :, marginals] = 0.0\n\n# # Current dimensions: n_gaussian x batch_size x in_features\n# # ______\n# # / /|\n# # /_____/ |\n# # | | /\n# # | | /\n# # |____|/\n\n# # Apply products between features i and j: X[:, :, i] * X[:, :, j] ( sum in logspace )\n# x = x[:, :, self.product_scopes_left] + x[:, :, self.product_scopes_right]\n\n# # Current dimensions: n_gaussian x batch_size x in_features / 2\n# # ______\n# # / /|\n# # /_____/ |\n# # | | /\n# # | | /\n# # |____|/\n\n# # The above is similar to the maxout approch but instead returns a weighted sum for each scope\n# x, _ = torch.max(x + torch.log(self.sum_weights.unsqueeze(1)), dim=0)\n# # x, _ = torch.max(x, dim=0)\n\n# # Current dimensions: batch_size x in_features / 2\n# # ____\n# # | |\n# # | |\n# # |____|\n\n# # Apply product over all features ( sum in logspace )\n# x = torch.sum(x, dim=1)\n\n# return x\n\n\n# class ConditionalSPNNeuron(nn.Module):\n# \"\"\"\n# Maps each input feature to the likeliood of that feature, given all other features:\n\n# z_i = P(x_i | X \\ {x_i})\n\n# Dimension in: N, dimension out: N\n# \"\"\"\n\n# def __init__(self, in_features: int):\n# # Init\n# super(ConditionalSPNNeuron, self).__init__()\n# self.spn = SPNNeuron(in_features=in_features)\n# self.in_features = in_features\n\n# def forward(self, x):\n# x_full_pass = self.spn(x)\n# x_marginalized = [self.spn(x, i) for i in range(self.in_features)]\n# x_stacked = torch.stack(x_marginalized, dim=1)\n# x_conditional = x_full_pass.view(-1, 1) - x_stacked\n# return x_conditional\n\n\n# class SPNNeuronOld(nn.Module):\n# def __init__(self, in_features, n_mv=2):\n# \"\"\"\n# Initialize the SPNNeuron.\n# Args:\n# in_features: Number of input features.\n# n_mv: Number of different pairwise independence mixtures of the leaf nodes.\n# \"\"\"\n# # Init\n# super(SPNNeuronOld, self).__init__()\n\n# # Create random sequence of scopes\n# scopes = np.random.permutation(in_features)\n\n# sums = []\n\n# # For two consecutive (random) scopes\n# for i in range(0, in_features, 2):\n# scope_1 = scopes[i]\n# scope_2 = scopes[i + 1]\n\n# # Create n_mv MultivariateGaussian from these two scopes\n# mvs = []\n# for _ in range(n_mv):\n# # TODO: MVG are currently not trainable\n# # mv = MultivariateGaussian(n_vars=2, scope=[scope_1, scope_2])\n# # mvs.append(mv)\n\n# g1 = GaussianNode(scope=scope_1)\n# g2 = GaussianNode(scope=scope_2)\n\n# prod = ProductNode([g1, g2])\n# mvs.append(prod)\n\n# sumnode = SumNode(children=mvs)\n# sums.append(sumnode)\n\n# self.root = ProductNode(children=sums)\n\n# def forward(self, x):\n# x = self.root(x)\n# return x\n\n\n##########\n# Layers #\n##########\n\n\nclass SPNOutLayer(nn.Module):\n \"\"\"\n A PyTorch module that contains multiple SPNs with the same structure and treats them as single nodes in a layer.\n \"\"\"\n\n def __init__(self, neuron: nn.Module, in_features: int, n_labels: int):\n \"\"\"\n Initialize the SPNLayer.\n\n Args:\n in_features (int): Number of input features for this layer.\n n_labels (int): Number of output labels for this layer.\n \"\"\"\n super().__init__()\n\n # Create out_features number of SPNNeurons\n neurons = [neuron(in_features) for _ in range(n_labels)]\n self.spns = nn.ModuleList(neurons)\n self.class_weights_log = nn.Parameter(\n torch.log(torch.ones(n_labels) / n_labels), requires_grad=False\n )\n self.n_labels = n_labels\n\n def forward(self, x):\n # Feed forward each neuron and stack the results\n spn_results = [spn(x) for spn in self.spns]\n x = torch.stack(spn_results, dim=1)\n x.squeeze_(2)\n\n # Normalize: S(y=i | x) = S_i(x) * w_i / sum_i { w_i p_i(x) }\n # In logspace: S(y=i | x) = S_i(x) + log(w_i) - logsumexp{ log(w_i) + p_i(x) }\n # w_i = 1/n_labels\n z = torch.logsumexp(self.class_weights_log + x, dim=1).view(x.shape[0], 1)\n y = x + self.class_weights_log - z\n return x\n\n\nclass SPNLayer(nn.Module):\n \"\"\"\n A PyTorch module that contains multiple SPNs with the same structure and treats them as single nodes in a layer.\n \"\"\"\n\n def __init__(self, neuron: nn.Module, in_features: int, out_features: int):\n \"\"\"\n Initialize the SPNLayer.\n\n Args:\n in_features (int): Number of input features for this layer.\n out_features (int): Number of output features for this layer.\n \"\"\"\n super(SPNLayer, self).__init__()\n\n # Create out_features number of SPNNeurons\n neurons = [neuron(in_features) for _ in range(out_features)]\n self.spns = nn.ModuleList(neurons)\n self.bn = nn.BatchNorm1d(out_features)\n\n def forward(self, x):\n # Feed forward each neuron and stack the results\n spn_results = [spn(x) for spn in self.spns]\n x = torch.stack(spn_results, dim=1)\n x = x.squeeze()\n x = self.bn(x)\n return x\n\n\n############\n# Networks #\n############\n\n\nclass ResNet(nn.Module):\n def __init__(self, in_features, n_labels, resnet_arch=resnet18, in_channels=1):\n \"\"\"\n Resnet.\n Args:\n in_features: Number of input features.\n n_labels: Number of output labels.\n resnet_arch: Resnet architecture.\n \"\"\"\n super(ResNet, self).__init__()\n\n self.n_labels = n_labels\n self.resnet = resnet_arch(\n pretrained=False, num_classes=128, in_channels=in_channels\n )\n self.linear = nn.Linear(128, n_labels)\n for m in self.modules():\n if isinstance(m, nn.Linear):\n torch.nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Conv2d):\n nn.init.xavier_normal_(m.weight)\n\n def forward(self, x):\n x = F.relu(self.resnet(x))\n x = self.linear(x)\n return x.sigmoid()\n\n\nclass ResNetCifar10(nn.Module):\n def __init__(self, in_features, n_labels, resnet_arch=resnet18, in_channels=3):\n \"\"\"\n Resnet.\n Args:\n in_features: Number of input features.\n n_labels: Number of output labels.\n resnet_arch: Resnet architecture.\n \"\"\"\n super().__init__()\n\n self.n_labels = n_labels\n self.resnet = resnet_arch(\n pretrained=False, num_classes=128, in_channels=in_channels\n )\n self.linear = nn.Linear(128, n_labels)\n for m in self.modules():\n if isinstance(m, nn.Linear):\n torch.nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Conv2d):\n nn.init.xavier_normal_(m.weight)\n\n def forward(self, x):\n x = F.relu(self.resnet(x))\n x = self.linear(x)\n return x\n\n\n# class SPNResnetParallel(nn.Module):\n# def __init__(self, in_features, n_labels, resnet_arch):\n# \"\"\"\n# Apply Resnet and SPN on the input in parallel, merge results and classify with 256 dimensional linear layer\n# afterwards.\n\n# Args:\n# in_features: Number of input features.\n# n_labels: Number of output labels.\n# resnet_arch: Resnet architecture.\n# \"\"\"\n# super(SPNResnetParallel, self).__init__()\n\n# self.n_labels = n_labels\n# self.resnet = resnet18(pretrained=False, num_classes=128, in_channels=1)\n# self.mid = SPNLayer(neuron=SPNNeuron, in_features=in_features, out_features=128)\n# self.linear = nn.Linear(128 * 2, n_labels)\n# for m in self.modules():\n# if isinstance(m, nn.Linear):\n# torch.nn.init.kaiming_normal_(m.weight)\n# elif isinstance(m, nn.BatchNorm2d):\n# m.weight.data.fill_(1)\n# m.bias.data.zero_()\n# elif isinstance(m, nn.Conv2d):\n# nn.init.xavier_normal_(m.weight)\n\n# def forward(self, x):\n# x_resnet = F.relu(self.resnet(x))\n# x_spn = self.mid(x.view(x.shape[0], -1))\n# x_concat = torch.cat([x_resnet, x_spn], dim=1)\n# x = self.linear(x_concat)\n# return x.sigmoid()\n\n\nclass SPNNetPure(nn.Module):\n def __init__(self, in_features, n_labels, spnneuron=SPNNeuronShallow):\n \"\"\"\n Apply SPN on input and directly produce the output.\n\n Args:\n in_features: Number of input features.\n n_labels: Number of output labels.\n \"\"\"\n super().__init__()\n\n self.n_labels = n_labels\n self.mid = SPNLayer(\n neuron=spnneuron, in_features=in_features, out_features=n_labels\n )\n\n def forward(self, x):\n x = x.view(x.shape[0], -1)\n x = self.mid(x)\n return x.sigmoid()\n\n\nclass SPNPosteriorNet(nn.Module):\n def __init__(\n self,\n in_features,\n n_labels,\n resnet_arch=resnet18,\n spnneuron=SPNNeuronShallow,\n in_channels=1,\n ):\n \"\"\"\n Apply Resnet and SPN sequentially.\n\n SPN models the posterior distribution P(Y | X)\n\n Args:\n in_features: Number of input features.\n n_labels: Number of output labels.\n resnet_arch: Resnet architecture.\n spnneuron: SPN neuron type that defines the SPN architecture.\n \"\"\"\n super().__init__()\n\n self.n_labels = n_labels\n self.resnet = resnet_arch(\n pretrained=False, num_classes=128, in_channels=in_channels\n )\n self.mid = SPNOutLayer(neuron=spnneuron, in_features=128, n_labels=n_labels)\n for m in self.modules():\n if isinstance(m, nn.Linear):\n torch.nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Conv2d):\n nn.init.xavier_normal_(m.weight)\n\n def forward(self, x):\n x = F.relu(self.resnet(x))\n x = self.mid(x)\n return x\n\n\nclass SPNNet(nn.Module):\n def __init__(\n self,\n in_features,\n n_labels,\n resnet_arch=resnet18,\n spnneuron=SPNNeuronShallow,\n in_channels=1,\n ):\n \"\"\"\n Apply Resnet and SPN sequentially.\n\n Args:\n in_features: Number of input features.\n n_labels: Number of output labels.\n resnet_arch: Resnet architecture.\n spnneuron: SPN neuron type that defines the SPN architecture.\n \"\"\"\n super().__init__()\n\n self.n_labels = n_labels\n self.resnet = resnet_arch(\n pretrained=False, num_classes=128, in_channels=in_channels\n )\n self.mid = SPNLayer(neuron=spnneuron, in_features=128, out_features=n_labels)\n for m in self.modules():\n if isinstance(m, nn.Linear):\n torch.nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Conv2d):\n nn.init.xavier_normal_(m.weight)\n\n def forward(self, x):\n x = F.relu(self.resnet(x))\n x = self.mid(x)\n return x.sigmoid()\n\n\nclass SPNNetCifar10(nn.Module):\n def __init__(\n self,\n in_features,\n n_labels,\n resnet_arch=resnet18,\n spnneuron=SPNNeuronShallow,\n in_channels=3,\n ):\n \"\"\"\n Apply Resnet and SPN sequentially.\n\n Args:\n in_features: Number of input features.\n n_labels: Number of output labels.\n resnet_arch: Resnet architecture.\n spnneuron: SPN neuron type that defines the SPN architecture.\n \"\"\"\n super().__init__()\n\n self.n_labels = n_labels\n self.resnet = resnet_arch(\n pretrained=False, num_classes=128, in_channels=in_channels\n )\n self.mid = SPNOutLayer(neuron=spnneuron, in_features=128, n_labels=n_labels)\n for m in self.modules():\n if isinstance(m, nn.Linear):\n torch.nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Conv2d):\n nn.init.xavier_normal_(m.weight)\n\n def forward(self, x):\n x = F.relu(self.resnet(x))\n x = self.mid(x)\n return x\n\n\ndef get_model_by_tag(\n tag, device, args, in_features, n_labels, in_channels=1\n) -> nn.Module:\n \"\"\"\n Return the model for a given tag.\n\n Args:\n tag (str): Model tag.\n device: Device to create the model on.\n args: Arguments\n in_features: Number of input features.\n n_labels: Number of output labels.\n in_channels: Number of input channels.\n\n Returns:\n nn.Module: PyTorch model.\n \"\"\"\n\n resnet_arch = {\n \"resnet18\": resnet18,\n \"resnet34\": resnet34,\n \"resnet50\": resnet50,\n \"resnet101\": resnet101,\n \"resnet152\": resnet152,\n }.get(args.resnet_arch)\n\n logger.info(\"Selecting model %s with device %s\", tag, device)\n\n # Select model\n if tag.lower() == \"resnet+spn\":\n model = SPNNet(\n in_features=in_features,\n n_labels=n_labels,\n spnneuron=SPNNeuronShallow,\n in_channels=in_channels,\n ).to(device)\n elif tag.lower() == \"resnet+posterior+spn\":\n model = SPNPosteriorNet(\n in_features=in_features,\n n_labels=n_labels,\n spnneuron=SPNNeuronShallow,\n in_channels=in_channels,\n ).to(device)\n elif tag.lower() == \"spn-shallow\":\n model = SPNNetPure(\n spnneuron=SPNNeuronShallow, in_features=in_features, n_labels=n_labels\n ).to(device)\n elif tag.lower() == \"spn-deep\":\n model = SPNNetPure(\n in_features=in_features, n_labels=n_labels, spnneuron=SPNNeuronBig\n ).to(device)\n elif tag.lower() == \"resnet\":\n model = ResNet(\n in_features=in_features,\n n_labels=n_labels,\n resnet_arch=resnet_arch,\n in_channels=in_channels,\n ).to(device)\n elif tag.lower() == \"resnet-cifar10\":\n model = ResNetCifar10(\n in_features=in_features,\n n_labels=n_labels,\n resnet_arch=resnet_arch,\n in_channels=in_channels,\n ).to(device)\n elif tag.lower() == \"resnet+spn-cifar10\":\n model = SPNNetCifar10(\n in_features=in_features,\n n_labels=n_labels,\n spnneuron=SPNNeuronShallow,\n in_channels=in_channels,\n ).to(device)\n else:\n raise Exception(\"Invalid network: %s\" % tag)\n\n return model\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n args = parser.parse_args(args=[])\n args.resnet_arch = \"resnet18\"\n dev = \"cuda:0\"\n resnet = get_model_by_tag(\"resnet\", torch.device(dev), args, 50 ** 2, 10)\n resnetspn = get_model_by_tag(\"resnet+spn\", torch.device(dev), args, 50 ** 2, 10)\n shallow = get_model_by_tag(\"spn-shallow\", torch.device(dev), args, 50 ** 2, 10)\n\n x = torch.rand(3, 1, 50, 50).to(torch.device(dev))\n for net, name in [\n (resnet, \"resnet\"),\n (resnetspn, \"resnetspn\"),\n (shallow, \"shallow\"),\n ]:\n print(f\"{name}: {count_params(net)}\")\n t = time.time()\n net(x)\n print(name, \"took\", time_delta_now(t))\n",
"import logging\nimport time\nfrom src.utils.utils import time_delta_now\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nlogger = logging.getLogger(__name__)\n\n\nclass Sum(nn.Module):\n def __init__(self, in_channels, in_features, out_channels, dropout=0.0):\n super(Sum, self).__init__()\n self.in_channels = in_channels\n self.in_features = in_features\n self.out_channels = out_channels\n self.dropout = dropout\n assert out_channels > 0, (\n \"Number of output channels must be at least 1, but was %s.\" % out_channels\n )\n in_features = int(in_features)\n # Weights, such that each sumnode has its own weights\n ws = torch.randn(in_features, in_channels, out_channels)\n self.sum_weights = nn.Parameter(ws)\n self._bernoulli_dist = torch.distributions.Bernoulli(probs=dropout)\n\n self.out_shape = f\"(N, {in_features}, C_in)\"\n\n def forward(self, x):\n \"\"\"\n Sum layer foward pass.\n\n Args:\n x: Input of shape [batch, in_features, in_channels].\n\n Returns:\n torch.Tensor: Output of shape [batch, in_features, out_channels]\n \"\"\"\n # Apply dropout: Set random sum node children to 0 (-inf in log domain)\n if self.dropout > 0.0:\n r = self._bernoulli_dist.sample(x.shape).type(torch.bool)\n x[r] = np.NINF\n\n # Multiply x with weights in logspace\n # Resuts in shape: [n, d, ic, oc]\n x = x.unsqueeze(3) + F.log_softmax(self.sum_weights, dim=1)\n\n # Compute sum via logsumexp along dimension \"ic\" (in_channels)\n # Resuts in shape: [n, d, oc]\n x = torch.logsumexp(x, dim=2)\n\n return x\n\n def __repr__(self):\n return \"Sum(in_channels={}, in_features={}, out_channels={}, dropout={}, out_shape={})\".format(\n self.in_channels,\n self.in_features,\n self.out_channels,\n self.dropout,\n self.out_shape,\n )\n\n\nclass Product(nn.Module):\n \"\"\"\n Product Node Layer that chooses k scopes as children for a product node.\n \"\"\"\n\n def __init__(self, in_features, cardinality):\n \"\"\"\n Create a product node layer.\n\n Args:\n in_features (int): Number of input features.\n cardinality (int): Number of random children for each product node.\n \"\"\"\n\n super(Product, self).__init__()\n self.in_features = in_features\n self.cardinality = int(cardinality)\n\n in_features = int(in_features)\n self._out_features = np.ceil(in_features / cardinality).astype(int)\n self.out_shape = f\"(N, {self._out_features}, C_in)\"\n\n def forward(self, x):\n \"\"\"\n Product layer forward pass.\n\n Args:\n x: Input of shape [batch, in_features, channel].\n\n Returns:\n torch.Tensor: Output of shape [batch, ceil(in_features/cardinality), channel].\n \"\"\"\n # Only one product node\n if self.cardinality == x.shape[1]:\n return x.sum(1)\n\n x_split = list(torch.split(x, self.cardinality, dim=1))\n\n # Check if splits have the same shape (If split cannot be made even, the last chunk will be smaller)\n if x_split[-1].shape != x_split[0].shape:\n # How much is the last chunk smaller\n diff = x_split[0].shape[1] - x_split[-1].shape[1]\n\n # Pad the last chunk by the difference with zeros (=maginalized nodes)\n x_split[-1] = F.pad(\n x_split[-1], pad=[0, 0, 0, diff], mode=\"constant\", value=0.0\n )\n\n # Stack along new split axis\n x_split_stack = torch.stack(x_split, dim=2)\n\n # Sum over feature axis\n result = torch.sum(x_split_stack, dim=1)\n return result\n\n def __repr__(self):\n return \"Product(in_features={}, cardinality={}, out_shape={})\".format(\n self.in_features, self.cardinality, self.out_shape\n )\n\n\nif __name__ == \"__main__\":\n from src.spn.distributions import Normal\n from src.spn.layers import Sum, Product\n import torch\n from torch import nn\n\n # 1 Sample, 4 features, 1 channel\n x = torch.rand(1, 4, 1)\n\n p = Product(in_features=4, cardinality=2)\n p(x)\n",
"import logging\nimport os\n\nimport numpy as np\nimport torch\nfrom torch import optim\nfrom src.utils.utils import count_params\n\nfrom src.data.data import store_results\nfrom src.data.data_loader import get_mnist_loaders\nfrom src.models.mnist import evaluate_model, train\nfrom src.models.models import get_model_by_tag\n\nlogger = logging.getLogger(__name__)\n\n\nclass MnistExperiment:\n \"\"\"Main experiment class.\"\"\"\n\n def __init__(self, args):\n \"\"\"\n Initialize the experiment.\n\n Args:\n args: Experiment options.\n \"\"\"\n self.args = args\n\n def run(self):\n \"\"\"Run the MNIST experiment.\"\"\"\n use_cuda = self.args.cuda and torch.cuda.is_available()\n torch.manual_seed(self.args.seed)\n if use_cuda:\n device = \"cuda:%s\" % self.args.cuda_device_id\n else:\n device = \"cpu\"\n\n logger.info(\"Selected device: {}\".format(device))\n\n # Get the mnist loader\n train_loader, test_loader = get_mnist_loaders(use_cuda, self.args)\n\n model = get_model_by_tag(self.args.net, device)\n logger.info(\"Model: {}\".format(model))\n\n # with SummaryWriter(comment=\"Model\", log_dir=\"tensorboard\") as w:\n # w.add_graph(model, torch.zeros(1, 28, 28), True)\n # exit()\n\n logger.info(\"Number of paramters: %s\", count_params(model))\n # Define optimizer\n optimizer = optim.Adam(model.parameters(), lr=self.args.lr)\n\n # Scheduler for learning rate\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=25, gamma=0.5)\n\n # Collect acc and loss\n train_accs, test_accs = [], []\n train_losses, test_losses = [], []\n\n # Run epochs\n for epoch in range(1, self.args.epochs + 1):\n scheduler.step()\n\n # Run train\n train(model, device, train_loader, optimizer, epoch, self.args.log_interval)\n\n # Evaluate model on train and test data\n train_loss, train_acc = evaluate_model(model, device, train_loader, \"Train\")\n test_loss, test_acc = evaluate_model(model, device, test_loader, \"Test\")\n\n # Store acc/loss\n train_accs.append(train_acc)\n train_losses.append(train_loss)\n test_accs.append(test_acc)\n test_losses.append(test_loss)\n\n # Store results\n column_names = [\"train_acc\", \"test_acc\", \"train_loss\", \"test_loss\"]\n data = np.c_[train_accs, test_accs, train_losses, test_losses]\n store_results(\n result_dir=os.path.join(self.args.result_dir, self.args.experiment_name),\n dataset_name=\"mnist\",\n column_names=column_names,\n data=data,\n )\n"
] | [
[
"torch.nn.BatchNorm1d",
"torch.ones",
"torch.nn.ModuleList",
"torch.nn.init.xavier_normal_",
"torch.nn.Linear",
"numpy.random.permutation",
"torch.rand",
"torch.stack",
"torch.device",
"torch.logsumexp",
"torch.nn.init.kaiming_normal_"
],
[
"torch.nn.Parameter",
"torch.nn.functional.log_softmax",
"torch.randn",
"torch.distributions.Bernoulli",
"torch.sum",
"numpy.ceil",
"torch.rand",
"torch.split",
"torch.stack",
"torch.logsumexp",
"torch.nn.functional.pad"
],
[
"torch.manual_seed",
"torch.cuda.is_available",
"torch.optim.lr_scheduler.StepLR"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tamuhey/pymatgen | [
"cf1793f0af59844ea9222d973212e3ab83e58209",
"cf1793f0af59844ea9222d973212e3ab83e58209"
] | [
"pymatgen/analysis/structure_analyzer.py",
"pymatgen/io/abinit/pseudos.py"
] | [
"# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\nfrom __future__ import division, unicode_literals\n\nimport warnings\nimport ruamel.yaml as yaml\nimport os\n\n\"\"\"\nThis module provides classes to perform topological analyses of structures.\n\"\"\"\n\n__author__ = \"Shyue Ping Ong, Geoffroy Hautier, Sai Jayaraman\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"1.0\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"[email protected]\"\n__status__ = \"Production\"\n__date__ = \"Sep 23, 2011\"\n\n\nfrom math import pi, acos\nimport numpy as np\nimport itertools\nimport collections\n\nfrom monty.dev import deprecated\n\nfrom warnings import warn\nfrom scipy.spatial import Voronoi\nfrom pymatgen import PeriodicSite\nfrom pymatgen import Element, Specie, Composition\nfrom pymatgen.util.num import abs_cap\nfrom pymatgen.symmetry.analyzer import SpacegroupAnalyzer\nfrom pymatgen.core.surface import SlabGenerator\nfrom pymatgen.analysis.local_env import VoronoiNN, JmolNN\n\n\ndef average_coordination_number(structures, freq=10):\n \"\"\"\n Calculates the ensemble averaged Voronoi coordination numbers\n of a list of Structures using VoronoiNN.\n Typically used for analyzing the output of a Molecular Dynamics run.\n Args:\n structures (list): list of Structures.\n freq (int): sampling frequency of coordination number [every freq steps].\n Returns:\n Dictionary of elements as keys and average coordination numbers as values.\n \"\"\"\n coordination_numbers = {}\n for spec in structures[0].composition.as_dict().keys():\n coordination_numbers[spec] = 0.0\n count = 0\n for t in range(len(structures)):\n if t % freq != 0:\n continue\n count += 1\n vnn = VoronoiNN()\n for atom in range(len(structures[0])):\n cn = vnn.get_cn(structures[t], atom, use_weights=True)\n coordination_numbers[structures[t][atom].species_string] += cn\n elements = structures[0].composition.as_dict()\n for el in coordination_numbers:\n coordination_numbers[el] = coordination_numbers[el] / elements[\n el] / count\n return coordination_numbers\n\n\nclass VoronoiAnalyzer(object):\n \"\"\"\n Performs a statistical analysis of Voronoi polyhedra around each site.\n Each Voronoi polyhedron is described using Schaefli notation.\n That is a set of indices {c_i} where c_i is the number of faces with i\n number of vertices. E.g. for a bcc crystal, there is only one polyhedron\n notation of which is [0,6,0,8,0,0,...].\n In perfect crystals, these also corresponds to the Wigner-Seitz cells.\n For distorted-crystals, liquids or amorphous structures, rather than one-type,\n there is a statistical distribution of polyhedra.\n See ref: Microstructure and its relaxation in Fe-B amorphous system\n simulated by molecular dynamics,\n Stepanyuk et al., J. Non-cryst. Solids (1993), 159, 80-87.\n\n Args:\n cutoff (float): cutoff distance to search for neighbors of a given atom\n (default = 5.0)\n qhull_options (str): options to pass to qhull (optional)\n \"\"\"\n\n def __init__(self, cutoff=5.0, qhull_options=\"Qbb Qc Qz\"):\n self.cutoff = cutoff\n self.qhull_options = qhull_options\n\n def analyze(self, structure, n=0):\n \"\"\"\n Performs Voronoi analysis and returns the polyhedra around atom n\n in Schlaefli notation.\n\n Args:\n structure (Structure): structure to analyze\n n (int): index of the center atom in structure\n\n Returns:\n voronoi index of n: <c3,c4,c6,c6,c7,c8,c9,c10>\n where c_i denotes number of facets with i vertices.\n \"\"\"\n center = structure[n]\n neighbors = structure.get_sites_in_sphere(center.coords, self.cutoff)\n neighbors = [i[0] for i in sorted(neighbors, key=lambda s: s[1])]\n qvoronoi_input = np.array([s.coords for s in neighbors])\n voro = Voronoi(qvoronoi_input, qhull_options=self.qhull_options)\n vor_index = np.array([0, 0, 0, 0, 0, 0, 0, 0])\n\n for key in voro.ridge_dict:\n if 0 in key: # This means if the center atom is in key\n if -1 in key: # This means if an infinity point is in key\n raise ValueError(\"Cutoff too short.\")\n else:\n try:\n vor_index[len(voro.ridge_dict[key]) - 3] += 1\n except IndexError:\n # If a facet has more than 10 edges, it's skipped here.\n pass\n return vor_index\n\n def analyze_structures(self, structures, step_freq=10,\n most_frequent_polyhedra=15):\n \"\"\"\n Perform Voronoi analysis on a list of Structures.\n Note that this might take a significant amount of time depending on the\n size and number of structures.\n\n Args:\n structures (list): list of Structures\n cutoff (float: cutoff distance around an atom to search for\n neighbors\n step_freq (int): perform analysis every step_freq steps\n qhull_options (str): options to pass to qhull\n most_frequent_polyhedra (int): this many unique polyhedra with\n highest frequences is stored.\n\n Returns:\n A list of tuples in the form (voronoi_index,frequency)\n \"\"\"\n voro_dict = {}\n step = 0\n for structure in structures:\n step += 1\n if step % step_freq != 0:\n continue\n\n v = []\n for n in range(len(structure)):\n v.append(str(self.analyze(structure, n=n).view()))\n for voro in v:\n if voro in voro_dict:\n voro_dict[voro] += 1\n else:\n voro_dict[voro] = 1\n return sorted(voro_dict.items(),\n key=lambda x: (x[1], x[0]),\n reverse=True)[:most_frequent_polyhedra]\n\n @staticmethod\n def plot_vor_analysis(voronoi_ensemble):\n t = zip(*voronoi_ensemble)\n labels = t[0]\n val = list(t[1])\n tot = np.sum(val)\n val = [float(j) / tot for j in val]\n pos = np.arange(len(val)) + .5 # the bar centers on the y axis\n import matplotlib.pyplot as plt\n plt.figure()\n plt.barh(pos, val, align='center', alpha=0.5)\n plt.yticks(pos, labels)\n plt.xlabel('Count')\n plt.title('Voronoi Spectra')\n plt.grid(True)\n return plt\n\n\nclass RelaxationAnalyzer(object):\n \"\"\"\n This class analyzes the relaxation in a calculation.\n \"\"\"\n\n def __init__(self, initial_structure, final_structure):\n \"\"\"\n Please note that the input and final structures should have the same\n ordering of sites. This is typically the case for most computational\n codes.\n\n Args:\n initial_structure (Structure): Initial input structure to\n calculation.\n final_structure (Structure): Final output structure from\n calculation.\n \"\"\"\n if final_structure.formula != initial_structure.formula:\n raise ValueError(\"Initial and final structures have different \" +\n \"formulas!\")\n self.initial = initial_structure\n self.final = final_structure\n\n def get_percentage_volume_change(self):\n \"\"\"\n Returns the percentage volume change.\n\n Returns:\n Volume change in percentage, e.g., 0.055 implies a 5.5% increase.\n \"\"\"\n initial_vol = self.initial.lattice.volume\n final_vol = self.final.lattice.volume\n return final_vol / initial_vol - 1\n\n def get_percentage_lattice_parameter_changes(self):\n \"\"\"\n Returns the percentage lattice parameter changes.\n\n Returns:\n A dict of the percentage change in lattice parameter, e.g.,\n {'a': 0.012, 'b': 0.021, 'c': -0.031} implies a change of 1.2%,\n 2.1% and -3.1% in the a, b and c lattice parameters respectively.\n \"\"\"\n initial_latt = self.initial.lattice\n final_latt = self.final.lattice\n d = {l: getattr(final_latt, l) / getattr(initial_latt, l) - 1\n for l in [\"a\", \"b\", \"c\"]}\n return d\n\n def get_percentage_bond_dist_changes(self, max_radius=3.0):\n \"\"\"\n Returns the percentage bond distance changes for each site up to a\n maximum radius for nearest neighbors.\n\n Args:\n max_radius (float): Maximum radius to search for nearest\n neighbors. This radius is applied to the initial structure,\n not the final structure.\n\n Returns:\n Bond distance changes as a dict of dicts. E.g.,\n {index1: {index2: 0.011, ...}}. For economy of representation, the\n index1 is always less than index2, i.e., since bonding between\n site1 and siten is the same as bonding between siten and site1,\n there is no reason to duplicate the information or computation.\n \"\"\"\n data = collections.defaultdict(dict)\n for inds in itertools.combinations(list(range(len(self.initial))), 2):\n (i, j) = sorted(inds)\n initial_dist = self.initial[i].distance(self.initial[j])\n if initial_dist < max_radius:\n final_dist = self.final[i].distance(self.final[j])\n data[i][j] = final_dist / initial_dist - 1\n return data\n\n\nclass VoronoiConnectivity(object):\n \"\"\"\n Computes the solid angles swept out by the shared face of the voronoi\n polyhedron between two sites.\n\n Args:\n structure (Structure): Input structure\n cutoff (float) Cutoff distance.\n \"\"\"\n\n # Radius in Angstrom cutoff to look for coordinating atoms\n\n def __init__(self, structure, cutoff=10):\n self.cutoff = cutoff\n self.s = structure\n recp_len = np.array(self.s.lattice.reciprocal_lattice.abc)\n i = np.ceil(cutoff * recp_len / (2 * pi))\n offsets = np.mgrid[-i[0]:i[0] + 1, -i[1]:i[1] + 1, -i[2]:i[2] + 1].T\n self.offsets = np.reshape(offsets, (-1, 3))\n # shape = [image, axis]\n self.cart_offsets = self.s.lattice.get_cartesian_coords(self.offsets)\n\n @property\n def connectivity_array(self):\n \"\"\"\n Provides connectivity array.\n\n Returns:\n connectivity: An array of shape [atomi, atomj, imagej]. atomi is\n the index of the atom in the input structure. Since the second\n atom can be outside of the unit cell, it must be described\n by both an atom index and an image index. Array data is the\n solid angle of polygon between atomi and imagej of atomj\n \"\"\"\n # shape = [site, axis]\n cart_coords = np.array(self.s.cart_coords)\n # shape = [site, image, axis]\n all_sites = cart_coords[:, None, :] + self.cart_offsets[None, :, :]\n vt = Voronoi(all_sites.reshape((-1, 3)))\n n_images = all_sites.shape[1]\n cs = (len(self.s), len(self.s), len(self.cart_offsets))\n connectivity = np.zeros(cs)\n vts = np.array(vt.vertices)\n for (ki, kj), v in vt.ridge_dict.items():\n atomi = ki // n_images\n atomj = kj // n_images\n\n imagei = ki % n_images\n imagej = kj % n_images\n\n if imagei != n_images // 2 and imagej != n_images // 2:\n continue\n\n if imagei == n_images // 2:\n # atomi is in original cell\n val = solid_angle(vt.points[ki], vts[v])\n connectivity[atomi, atomj, imagej] = val\n\n if imagej == n_images // 2:\n # atomj is in original cell\n val = solid_angle(vt.points[kj], vts[v])\n connectivity[atomj, atomi, imagei] = val\n\n if -10.101 in vts[v]:\n warn('Found connectivity with infinite vertex. '\n 'Cutoff is too low, and results may be '\n 'incorrect')\n return connectivity\n\n @property\n def max_connectivity(self):\n \"\"\"\n returns the 2d array [sitei, sitej] that represents\n the maximum connectivity of site i to any periodic\n image of site j\n \"\"\"\n return np.max(self.connectivity_array, axis=2)\n\n def get_connections(self):\n \"\"\"\n Returns a list of site pairs that are Voronoi Neighbors, along\n with their real-space distances.\n \"\"\"\n con = []\n maxconn = self.max_connectivity\n for ii in range(0, maxconn.shape[0]):\n for jj in range(0, maxconn.shape[1]):\n if maxconn[ii][jj] != 0:\n dist = self.s.get_distance(ii, jj)\n con.append([ii, jj, dist])\n return con\n\n def get_sitej(self, site_index, image_index):\n \"\"\"\n Assuming there is some value in the connectivity array at indices\n (1, 3, 12). sitei can be obtained directly from the input structure\n (structure[1]). sitej can be obtained by passing 3, 12 to this function\n\n Args:\n site_index (int): index of the site (3 in the example)\n image_index (int): index of the image (12 in the example)\n \"\"\"\n atoms_n_occu = self.s[site_index].species_and_occu\n lattice = self.s.lattice\n coords = self.s[site_index].frac_coords + self.offsets[image_index]\n return PeriodicSite(atoms_n_occu, coords, lattice)\n\n\ndef solid_angle(center, coords):\n \"\"\"\n Helper method to calculate the solid angle of a set of coords from the\n center.\n\n Args:\n center (3x1 array): Center to measure solid angle from.\n coords (Nx3 array): List of coords to determine solid angle.\n\n Returns:\n The solid angle.\n \"\"\"\n o = np.array(center)\n r = [np.array(c) - o for c in coords]\n r.append(r[0])\n n = [np.cross(r[i + 1], r[i]) for i in range(len(r) - 1)]\n n.append(np.cross(r[1], r[0]))\n vals = []\n for i in range(len(n) - 1):\n v = -np.dot(n[i], n[i + 1]) \\\n / (np.linalg.norm(n[i]) * np.linalg.norm(n[i + 1]))\n vals.append(acos(abs_cap(v)))\n phi = sum(vals)\n return phi + (3 - len(r)) * pi\n\n\ndef get_max_bond_lengths(structure, el_radius_updates=None):\n \"\"\"\n Provides max bond length estimates for a structure based on the JMol\n table and algorithms.\n \n Args:\n structure: (structure)\n el_radius_updates: (dict) symbol->float to update atomic radii\n \n Returns: (dict) - (Element1, Element2) -> float. The two elements are \n ordered by Z.\n \"\"\"\n #jmc = JMolCoordFinder(el_radius_updates)\n jmnn = JmolNN(el_radius_updates=el_radius_updates)\n\n bonds_lens = {}\n els = sorted(structure.composition.elements, key=lambda x: x.Z)\n\n for i1 in range(len(els)):\n for i2 in range(len(els) - i1):\n bonds_lens[els[i1], els[i1 + i2]] = jmnn.get_max_bond_distance(\n els[i1].symbol, els[i1 + i2].symbol)\n\n return bonds_lens\n\n\n@deprecated(message=(\"find_dimension has been moved to\"\n \"pymatgen.analysis.dimensionality.get_dimensionality_gorai\"\n \" this method will be removed in pymatgen v2019.1.1.\"))\ndef get_dimensionality(structure, max_hkl=2, el_radius_updates=None,\n min_slab_size=5, min_vacuum_size=5,\n standardize=True, bonds=None):\n \"\"\"\n This method returns whether a structure is 3D, 2D (layered), or 1D (linear\n chains or molecules) according to the algorithm published in Gorai, P.,\n Toberer, E. & Stevanovic, V. Computational Identification of Promising\n Thermoelectric Materials Among Known Quasi-2D Binary Compounds. J. Mater.\n Chem. A 2, 4136 (2016).\n\n Note that a 1D structure detection might indicate problems in the bonding\n algorithm, particularly for ionic crystals (e.g., NaCl)\n\n Users can change the behavior of bonds detection by passing either\n el_radius_updates to update atomic radii for auto-detection of max bond\n distances, or bonds to explicitly specify max bond distances for atom pairs.\n Note that if you pass both, el_radius_updates are ignored.\n\n Args:\n structure: (Structure) structure to analyze dimensionality for\n max_hkl: (int) max index of planes to look for layers\n el_radius_updates: (dict) symbol->float to update atomic radii\n min_slab_size: (float) internal surface construction parameter\n min_vacuum_size: (float) internal surface construction parameter\n standardize (bool): whether to standardize the structure before\n analysis. Set to False only if you already have the structure in a\n convention where layers / chains will be along low <hkl> indexes.\n bonds ({(specie1, specie2): max_bond_dist}: bonds are\n specified as a dict of tuples: float of specie1, specie2\n and the max bonding distance. For example, PO4 groups may be\n defined as {(\"P\", \"O\"): 3}.\n\n Returns: (int) the dimensionality of the structure - 1 (molecules/chains),\n 2 (layered), or 3 (3D)\n\n \"\"\"\n if standardize:\n structure = SpacegroupAnalyzer(structure). \\\n get_conventional_standard_structure()\n\n if not bonds:\n bonds = get_max_bond_lengths(structure, el_radius_updates)\n\n num_surfaces = 0\n for h in range(max_hkl):\n for k in range(max_hkl):\n for l in range(max_hkl):\n if max([h, k, l]) > 0 and num_surfaces < 2:\n sg = SlabGenerator(structure, (h, k, l),\n min_slab_size=min_slab_size,\n min_vacuum_size=min_vacuum_size)\n slabs = sg.get_slabs(bonds)\n for _ in slabs:\n num_surfaces += 1\n\n return 3 - min(num_surfaces, 2)\n\n\ndef contains_peroxide(structure, relative_cutoff=1.1):\n \"\"\"\n Determines if a structure contains peroxide anions.\n\n Args:\n structure (Structure): Input structure.\n relative_cutoff: The peroxide bond distance is 1.49 Angstrom.\n Relative_cutoff * 1.49 stipulates the maximum distance two O\n atoms must be to each other to be considered a peroxide.\n\n Returns:\n Boolean indicating if structure contains a peroxide anion.\n \"\"\"\n ox_type = oxide_type(structure, relative_cutoff)\n if ox_type == \"peroxide\":\n return True\n else:\n return False\n\n\nclass OxideType(object):\n \"\"\"\n Separate class for determining oxide type.\n\n Args:\n structure: Input structure.\n relative_cutoff: Relative_cutoff * act. cutoff stipulates the max.\n distance two O atoms must be from each other. Default value is\n 1.1. At most 1.1 is recommended, nothing larger, otherwise the\n script cannot distinguish between superoxides and peroxides.\n \"\"\"\n\n def __init__(self, structure, relative_cutoff=1.1):\n self.structure = structure\n self.relative_cutoff = relative_cutoff\n self.oxide_type, self.nbonds = self.parse_oxide()\n\n def parse_oxide(self):\n \"\"\"\n Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide.\n\n Returns:\n oxide_type (str): Type of oxide\n ozonide/peroxide/superoxide/hydroxide/None.\n nbonds (int): Number of peroxide/superoxide/hydroxide bonds in\n structure.\n \"\"\"\n structure = self.structure\n relative_cutoff = self.relative_cutoff\n o_sites_frac_coords = []\n h_sites_frac_coords = []\n lattice = structure.lattice\n\n if isinstance(structure.composition.elements[0], Element):\n comp = structure.composition\n elif isinstance(structure.composition.elements[0], Specie):\n elmap = collections.defaultdict(float)\n for site in structure:\n for species, occu in site.species_and_occu.items():\n elmap[species.element] += occu\n comp = Composition(elmap)\n if Element(\"O\") not in comp or comp.is_element:\n return \"None\", 0\n\n for site in structure:\n syms = [sp.symbol for sp in site.species_and_occu.keys()]\n if \"O\" in syms:\n o_sites_frac_coords.append(site.frac_coords)\n if \"H\" in syms:\n h_sites_frac_coords.append(site.frac_coords)\n\n if h_sites_frac_coords:\n dist_matrix = lattice.get_all_distances(o_sites_frac_coords,\n h_sites_frac_coords)\n if np.any(dist_matrix < relative_cutoff * 0.93):\n return \"hydroxide\", len(\n np.where(dist_matrix < relative_cutoff * 0.93)[0]) / 2.0\n dist_matrix = lattice.get_all_distances(o_sites_frac_coords,\n o_sites_frac_coords)\n np.fill_diagonal(dist_matrix, 1000)\n is_superoxide = False\n is_peroxide = False\n is_ozonide = False\n if np.any(dist_matrix < relative_cutoff * 1.35):\n bond_atoms = np.where(dist_matrix < relative_cutoff * 1.35)[0]\n is_superoxide = True\n elif np.any(dist_matrix < relative_cutoff * 1.49):\n is_peroxide = True\n bond_atoms = np.where(dist_matrix < relative_cutoff * 1.49)[0]\n if is_superoxide:\n if len(bond_atoms) > len(set(bond_atoms)):\n is_superoxide = False\n is_ozonide = True\n try:\n nbonds = len(set(bond_atoms))\n except UnboundLocalError:\n nbonds = 0.0\n if is_ozonide:\n str_oxide = \"ozonide\"\n elif is_superoxide:\n str_oxide = \"superoxide\"\n elif is_peroxide:\n str_oxide = \"peroxide\"\n else:\n str_oxide = \"oxide\"\n if str_oxide == \"oxide\":\n nbonds = comp[\"O\"]\n return str_oxide, nbonds\n\n\ndef oxide_type(structure, relative_cutoff=1.1, return_nbonds=False):\n \"\"\"\n Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide\n\n Args:\n structure (Structure): Input structure.\n relative_cutoff (float): Relative_cutoff * act. cutoff stipulates the\n max distance two O atoms must be from each other.\n return_nbonds (bool): Should number of bonds be requested?\n \"\"\"\n\n ox_obj = OxideType(structure, relative_cutoff)\n if return_nbonds:\n return ox_obj.oxide_type, ox_obj.nbonds\n else:\n return ox_obj.oxide_type\n\n\ndef sulfide_type(structure):\n \"\"\"\n Determines if a structure is a sulfide/polysulfide\n\n Args:\n structure (Structure): Input structure.\n\n Returns:\n (str) sulfide/polysulfide/sulfate\n \"\"\"\n structure = structure.copy()\n structure.remove_oxidation_states()\n s = Element(\"S\")\n comp = structure.composition\n if comp.is_element or s not in comp:\n return None\n\n finder = SpacegroupAnalyzer(structure, symprec=0.1)\n symm_structure = finder.get_symmetrized_structure()\n s_sites = [sites[0] for sites in symm_structure.equivalent_sites if\n sites[0].specie == s]\n\n def process_site(site):\n neighbors = structure.get_neighbors(site, 4)\n neighbors = sorted(neighbors, key=lambda n: n[1])\n nn, dist = neighbors[0]\n coord_elements = [site.specie for site, d in neighbors\n if d < dist + 0.4][:4]\n avg_electroneg = np.mean([e.X for e in coord_elements])\n if avg_electroneg > s.X:\n return \"sulfate\"\n elif avg_electroneg == s.X and s in coord_elements:\n return \"polysulfide\"\n else:\n return \"sulfide\"\n\n types = set([process_site(site) for site in s_sites])\n if \"sulfate\" in types:\n return None\n elif \"polysulfide\" in types:\n return \"polysulfide\"\n else:\n return \"sulfide\"\n\n\n",
"# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\"\"\"\nThis module provides objects describing the basic parameters of the\npseudopotentials used in Abinit, and a parser to instantiate pseudopotential objects..\n\"\"\"\nfrom __future__ import unicode_literals, division, print_function\n\nimport abc\nimport collections\nimport json\nimport logging\nimport os\nimport sys\nimport numpy as np\nimport six\n\nfrom collections import OrderedDict, defaultdict, namedtuple\nfrom monty.collections import AttrDict, Namespace\nfrom tabulate import tabulate\n#from monty.dev import deprecated\nfrom monty.functools import lazy_property\nfrom monty.itertools import iterator_from_slice\nfrom monty.json import MSONable, MontyDecoder\nfrom monty.os.path import find_exts\nfrom monty.string import list_strings, is_string\nfrom pymatgen.core.periodic_table import Element\nfrom pymatgen.core.xcfunc import XcFunc\nfrom pymatgen.util.serialization import pmg_serialize\nfrom pymatgen.util.plotting import add_fig_kwargs, get_ax_fig_plt\n\nlogger = logging.getLogger(__name__)\n\n\n__all__ = [\n \"Pseudo\",\n \"PseudoTable\",\n]\n\n__author__ = \"Matteo Giantomassi\"\n__version__ = \"0.1\"\n__maintainer__ = \"Matteo Giantomassi\"\n\n# Tools and helper functions.\n\ndef straceback():\n \"\"\"Returns a string with the traceback.\"\"\"\n import traceback\n return \"\\n\".join((traceback.format_exc(), str(sys.exc_info()[0])))\n\n\ndef _read_nlines(filename, nlines):\n \"\"\"\n Read at most nlines lines from file filename.\n If nlines is < 0, the entire file is read.\n \"\"\"\n if nlines < 0:\n with open(filename, 'r') as fh:\n return fh.readlines()\n\n lines = []\n with open(filename, 'r') as fh:\n for lineno, line in enumerate(fh):\n if lineno == nlines: break\n lines.append(line)\n return lines\n\n_l2str = {\n 0: \"s\",\n 1: \"p\",\n 2: \"d\",\n 3: \"f\",\n 4: \"g\",\n 5: \"h\",\n 6: \"i\",\n}\n\n_str2l = {v: k for k, v in _l2str.items()}\n\n\ndef l2str(l):\n \"\"\"Convert the angular momentum l (int) to string.\"\"\"\n try:\n return _l2str[l]\n except KeyError:\n return \"Unknown angular momentum, received l = %s\" % l\n\n\ndef str2l(s):\n \"\"\"Convert a string to the angular momentum l (int)\"\"\"\n return _str2l[s]\n\n\nclass Pseudo(six.with_metaclass(abc.ABCMeta, MSONable, object)):\n \"\"\"\n Abstract base class defining the methods that must be\n implemented by the concrete pseudopotential sub-classes.\n \"\"\"\n\n @classmethod\n def as_pseudo(cls, obj):\n \"\"\"\n Convert obj into a pseudo. Accepts:\n\n * Pseudo object.\n * string defining a valid path.\n \"\"\"\n return obj if isinstance(obj, cls) else cls.from_file(obj)\n\n @staticmethod\n def from_file(filename):\n \"\"\"\n Build an instance of a concrete Pseudo subclass from filename.\n Note: the parser knows the concrete class that should be instantiated\n Client code should rely on the abstract interface provided by Pseudo.\n \"\"\"\n return PseudoParser().parse(filename)\n\n def __eq__(self, other):\n if other is None: return False\n return (self.md5 == other.md5 and\n self.__class__ == other.__class__ and\n self.Z == other.Z and\n self.Z_val == other.Z_val and\n self.l_max == other.l_max )\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __repr__(self):\n try:\n return \"<%s at %s>\" % (self.__class__.__name__, os.path.relpath(self.filepath))\n except:\n # relpath can fail if the code is executed in demon mode.\n return \"<%s at %s>\" % (self.__class__.__name__, self.filepath)\n\n def __str__(self):\n return self.to_string()\n\n def to_string(self, verbose=0):\n \"\"\"String representation.\"\"\"\n lines = []\n app = lines.append\n app(\"<%s: %s>\" % (self.__class__.__name__, self.basename))\n app(\" summary: \" + self.summary.strip())\n app(\" number of valence electrons: %s\" % self.Z_val)\n app(\" maximum angular momentum: %s\" % l2str(self.l_max))\n app(\" angular momentum for local part: %s\" % l2str(self.l_local))\n app(\" XC correlation: %s\" % self.xc)\n app(\" supports spin-orbit: %s\" % self.supports_soc)\n\n if self.isnc:\n app(\" radius for non-linear core correction: %s\" % self.nlcc_radius)\n\n if self.has_hints:\n for accuracy in (\"low\", \"normal\", \"high\"):\n hint = self.hint_for_accuracy(accuracy=accuracy)\n app(\" hint for %s accuracy: %s\" % (accuracy, str(hint)))\n\n return \"\\n\".join(lines)\n\n @property\n @abc.abstractmethod\n def summary(self):\n \"\"\"String summarizing the most important properties.\"\"\"\n\n @property\n def filepath(self):\n return os.path.abspath(self.path)\n\n @property\n def basename(self):\n \"\"\"File basename.\"\"\"\n return os.path.basename(self.filepath)\n\n @property\n @abc.abstractmethod\n def Z(self):\n \"\"\"The atomic number of the atom.\"\"\"\n\n @property\n @abc.abstractmethod\n def Z_val(self):\n \"\"\"Valence charge.\"\"\"\n\n @property\n def type(self):\n return self.__class__.__name__\n\n @property\n def element(self):\n \"\"\"Pymatgen :class:`Element`.\"\"\"\n try:\n return Element.from_Z(self.Z)\n except (KeyError, IndexError):\n return Element.from_Z(int(self.Z))\n\n @property\n def symbol(self):\n \"\"\"Element symbol.\"\"\"\n return self.element.symbol\n\n @property\n @abc.abstractmethod\n def l_max(self):\n \"\"\"Maximum angular momentum.\"\"\"\n\n @property\n @abc.abstractmethod\n def l_local(self):\n \"\"\"Angular momentum used for the local part.\"\"\"\n\n @property\n def isnc(self):\n \"\"\"True if norm-conserving pseudopotential.\"\"\"\n return isinstance(self, NcPseudo)\n\n @property\n def ispaw(self):\n \"\"\"True if PAW pseudopotential.\"\"\"\n return isinstance(self, PawPseudo)\n\n @lazy_property\n def md5(self):\n \"\"\"MD5 hash value.\"\"\"\n #if self.has_dojo_report and \"md5\" in self.dojo_report: return self.dojo_report[\"md5\"]\n return self.compute_md5()\n\n def compute_md5(self):\n \"\"\"Compute and erturn MD5 hash value.\"\"\"\n import hashlib\n with open(self.path, \"rt\") as fh:\n text = fh.read()\n m = hashlib.md5(text.encode(\"utf-8\"))\n return m.hexdigest()\n\n @property\n @abc.abstractmethod\n def supports_soc(self):\n \"\"\"\n True if the pseudo can be used in a calculation with spin-orbit coupling.\n Base classes should provide a concrete implementation that computes this value.\n \"\"\"\n\n @pmg_serialize\n def as_dict(self, **kwargs):\n return dict(\n basename=self.basename,\n type=self.type,\n symbol=self.symbol,\n Z=self.Z,\n Z_val=self.Z_val,\n l_max=self.l_max,\n md5=self.md5,\n filepath=self.filepath,\n #xc=self.xc.as_dict(),\n )\n\n @classmethod\n def from_dict(cls, d):\n new = cls.from_file(d['filepath'])\n\n # Consistency test based on md5\n if \"md5\" in d and d[\"md5\"] != new.md5:\n raise ValueError(\"The md5 found in file does not agree with the one in dict\\n\"\n \"Received %s\\nComputed %s\" % (d[\"md5\"], new.md5))\n\n return new\n\n def as_tmpfile(self, tmpdir=None):\n \"\"\"\n Copy the pseudopotential to a temporary a file and returns a new pseudopotential object.\n Useful for unit tests in which we have to change the content of the file.\n\n Args:\n tmpdir: If None, a new temporary directory is created and files are copied here\n else tmpdir is used.\n \"\"\"\n import tempfile, shutil\n tmpdir = tempfile.mkdtemp() if tmpdir is None else tmpdir\n new_path = os.path.join(tmpdir, self.basename)\n shutil.copy(self.filepath, new_path)\n\n # Copy dojoreport file if present.\n root, ext = os.path.splitext(self.filepath)\n djrepo = root + \".djrepo\"\n if os.path.exists(djrepo):\n shutil.copy(djrepo, os.path.join(tmpdir, os.path.basename(djrepo)))\n\n # Build new object and copy dojo_report if present.\n new = self.__class__.from_file(new_path)\n if self.has_dojo_report: new.dojo_report = self.dojo_report.deepcopy()\n\n return new\n\n @property\n def has_dojo_report(self):\n \"\"\"True if the pseudo has an associated `DOJO_REPORT` section.\"\"\"\n return hasattr(self, \"dojo_report\") and bool(self.dojo_report)\n\n @property\n def djrepo_path(self):\n \"\"\"The path of the djrepo file. None if file does not exist.\"\"\"\n root, ext = os.path.splitext(self.filepath)\n path = root + \".djrepo\"\n return path\n #if os.path.exists(path): return path\n #return None\n\n def hint_for_accuracy(self, accuracy=\"normal\"):\n \"\"\"\n Returns a :class:`Hint` object with the suggested value of ecut [Ha] and\n pawecutdg [Ha] for the given accuracy.\n ecut and pawecutdg are set to zero if no hint is available.\n\n Args:\n accuracy: [\"low\", \"normal\", \"high\"]\n \"\"\"\n if not self.has_dojo_report:\n return Hint(ecut=0., pawecutdg=0.)\n\n # Get hints from dojoreport. Try first in hints then in ppgen_hints.\n if \"hints\" in self.dojo_report:\n return Hint.from_dict(self.dojo_report[\"hints\"][accuracy])\n elif \"ppgen_hints\" in self.dojo_report:\n return Hint.from_dict(self.dojo_report[\"ppgen_hints\"][accuracy])\n return Hint(ecut=0., pawecutdg=0.)\n\n @property\n def has_hints(self):\n \"\"\"\n True if self provides hints on the cutoff energy.\n \"\"\"\n for acc in [\"low\", \"normal\", \"high\"]:\n try:\n if self.hint_for_accuracy(acc) is None:\n return False\n except KeyError:\n return False\n return True\n\n def open_pspsfile(self, ecut=20, pawecutdg=None):\n \"\"\"\n Calls Abinit to compute the internal tables for the application of the\n pseudopotential part. Returns :class:`PspsFile` object providing methods\n to plot and analyze the data or None if file is not found or it's not readable.\n\n Args:\n ecut: Cutoff energy in Hartree.\n pawecutdg: Cutoff energy for the PAW double grid.\n \"\"\"\n from pymatgen.io.abinit.tasks import AbinitTask\n from abipy.core.structure import Structure\n from abipy.abio.factories import gs_input\n from abipy.electrons.psps import PspsFile\n\n # Build fake structure.\n lattice = 10 * np.eye(3)\n structure = Structure(lattice, [self.element], coords=[[0, 0, 0]])\n\n if self.ispaw and pawecutdg is None: pawecutdg = ecut * 4\n inp = gs_input(structure, pseudos=[self], ecut=ecut, pawecutdg=pawecutdg,\n spin_mode=\"unpolarized\", kppa=1)\n # Add prtpsps = -1 to make Abinit print the PSPS.nc file and stop.\n inp[\"prtpsps\"] = -1\n\n # Build temporary task and run it (ignore retcode because we don't exit cleanly)\n task = AbinitTask.temp_shell_task(inp)\n task.start_and_wait()\n\n filepath = task.outdir.has_abiext(\"_PSPS.nc\")\n if not filepath:\n logger.critical(\"Cannot find PSPS.nc file in %s\" % task.outdir)\n return None\n\n # Open the PSPS.nc file.\n try:\n return PspsFile(filepath)\n except Exception as exc:\n logger.critical(\"Exception while reading PSPS file at %s:\\n%s\" % (filepath, str(exc)))\n return None\n\n\nclass NcPseudo(six.with_metaclass(abc.ABCMeta, object)):\n \"\"\"\n Abstract class defining the methods that must be implemented\n by the concrete classes representing norm-conserving pseudopotentials.\n \"\"\"\n\n @property\n @abc.abstractmethod\n def nlcc_radius(self):\n \"\"\"\n Radius at which the core charge vanish (i.e. cut-off in a.u.).\n Returns 0.0 if nlcc is not used.\n \"\"\"\n\n @property\n def has_nlcc(self):\n \"\"\"True if the pseudo is generated with non-linear core correction.\"\"\"\n return self.nlcc_radius > 0.0\n\n @property\n def rcore(self):\n \"\"\"Radius of the pseudization sphere in a.u.\"\"\"\n try:\n return self._core\n except AttributeError:\n return None\n\n\nclass PawPseudo(six.with_metaclass(abc.ABCMeta, object)):\n \"\"\"\n Abstract class that defines the methods that must be implemented\n by the concrete classes representing PAW pseudopotentials.\n \"\"\"\n\n #def nlcc_radius(self):\n # \"\"\"\n # Radius at which the core charge vanish (i.e. cut-off in a.u.).\n # Returns 0.0 if nlcc is not used.\n # \"\"\"\n # return 0.0\n #\n\n #@property\n #def has_nlcc(self):\n # \"\"\"True if the pseudo is generated with non-linear core correction.\"\"\"\n # return True\n\n @property\n @abc.abstractmethod\n def paw_radius(self):\n \"\"\"Radius of the PAW sphere in a.u.\"\"\"\n\n @property\n def rcore(self):\n \"\"\"Alias of paw_radius.\"\"\"\n return self.paw_radius\n\n\nclass AbinitPseudo(Pseudo):\n \"\"\"\n An AbinitPseudo is a pseudopotential whose file contains an abinit header.\n \"\"\"\n def __init__(self, path, header):\n \"\"\"\n Args:\n path: Filename.\n header: :class:`AbinitHeader` instance.\n \"\"\"\n self.path = path\n self.header = header\n self._summary = header.summary\n\n # Build xc from header.\n self.xc = XcFunc.from_abinit_ixc(header[\"pspxc\"])\n\n for attr_name, desc in header.items():\n value = header.get(attr_name, None)\n\n # Hide these attributes since one should always use the public interface.\n setattr(self, \"_\" + attr_name, value)\n\n @property\n def summary(self):\n \"\"\"Summary line reported in the ABINIT header.\"\"\"\n return self._summary.strip()\n\n @property\n def Z(self):\n return self._zatom\n\n @property\n def Z_val(self):\n return self._zion\n\n @property\n def l_max(self):\n return self._lmax\n\n @property\n def l_local(self):\n return self._lloc\n\n @property\n def supports_soc(self):\n # Treate ONCVPSP pseudos\n if self._pspcod == 8:\n switch = self.header[\"extension_switch\"]\n if switch in (0, 1): return False\n if switch in (2, 3): return True\n raise ValueError(\"Don't know how to handle extension_switch: %s\" % switch)\n\n # TODO Treat HGH HGHK pseudos\n\n # As far as I know, other Abinit pseudos do not support SOC.\n return False\n\n\nclass NcAbinitPseudo(NcPseudo, AbinitPseudo):\n \"\"\"Norm-conserving pseudopotential in the Abinit format.\"\"\"\n @property\n def summary(self):\n return self._summary.strip()\n\n @property\n def Z(self):\n return self._zatom\n\n @property\n def Z_val(self):\n \"\"\"Number of valence electrons.\"\"\"\n return self._zion\n\n @property\n def l_max(self):\n return self._lmax\n\n @property\n def l_local(self):\n return self._lloc\n\n @property\n def nlcc_radius(self):\n return self._rchrg\n\n\nclass PawAbinitPseudo(PawPseudo, AbinitPseudo):\n \"\"\"Paw pseudopotential in the Abinit format.\"\"\"\n\n @property\n def paw_radius(self):\n return self._r_cut\n\n #def orbitals(self):\n\n @property\n def supports_soc(self):\n return True\n\n\nclass Hint(object):\n \"\"\"\n Suggested value for the cutoff energy [Hartree units]\n and the cutoff energy for the dense grid (only for PAW pseudos).\n \"\"\"\n def __init__(self, ecut, pawecutdg=None):\n self.ecut = ecut\n self.pawecutdg = ecut if pawecutdg is None else pawecutdg\n\n def __str__(self):\n if self.pawecutdg is not None:\n return \"ecut: %s, pawecutdg: %s\" % (self.ecut, self.pawecutdg)\n else:\n return \"ecut: %s\" % (self.ecut)\n\n @pmg_serialize\n def as_dict(self):\n return dict(ecut=self.ecut, pawecutdg=self.pawecutdg)\n\n @classmethod\n def from_dict(cls, d):\n return cls(**{k: v for k, v in d.items() if not k.startswith(\"@\")})\n\n\ndef _dict_from_lines(lines, key_nums, sep=None):\n \"\"\"\n Helper function to parse formatted text structured like:\n\n value1 value2 ... sep key1, key2 ...\n\n key_nums is a list giving the number of keys for each line. 0 if line should be skipped.\n sep is a string denoting the character that separates the keys from the value (None if\n no separator is present).\n\n Returns:\n dict{key1 : value1, key2 : value2, ...}\n\n Raises:\n ValueError if parsing fails.\n \"\"\"\n if is_string(lines):\n lines = [lines]\n\n if not isinstance(key_nums, collections.Iterable):\n key_nums = list(key_nums)\n\n if len(lines) != len(key_nums):\n err_msg = \"lines = %s\\n key_num = %s\" % (str(lines), str(key_nums))\n raise ValueError(err_msg)\n\n kwargs = Namespace()\n\n for (i, nk) in enumerate(key_nums):\n if nk == 0: continue\n line = lines[i]\n\n tokens = [t.strip() for t in line.split()]\n values, keys = tokens[:nk], \"\".join(tokens[nk:])\n # Sanitize keys: In some case we might get strings in the form: foo[,bar]\n keys.replace(\"[\", \"\").replace(\"]\", \"\")\n keys = keys.split(\",\")\n\n if sep is not None:\n check = keys[0][0]\n if check != sep:\n raise ValueError(\"Expecting separator %s, got %s\" % (sep, check))\n keys[0] = keys[0][1:]\n\n if len(values) != len(keys):\n msg = \"line: %s\\n len(keys) != len(value)\\nkeys: %s\\n values: %s\" % (line, keys, values)\n raise ValueError(msg)\n\n kwargs.update(zip(keys, values))\n\n return kwargs\n\n\nclass AbinitHeader(dict):\n \"\"\"Dictionary whose keys can be also accessed as attributes.\"\"\"\n def __getattr__(self, name):\n try:\n # Default behaviour\n return super(AbinitHeader, self).__getattribute__(name)\n except AttributeError:\n try:\n # Try in the dictionary.\n return self[name]\n except KeyError as exc:\n raise AttributeError(str(exc))\n\n\ndef _int_from_str(string):\n \"\"\"\n Convert string into integer\n\n Raise:\n TypeError if string is not a valid integer\n \"\"\"\n float_num = float(string)\n int_num = int(float_num)\n if float_num == int_num:\n return int_num\n else:\n # Needed to handle pseudos with fractional charge\n int_num = np.rint(float_num)\n logger.warning(\"Converting float %s to int %s\" % (float_num, int_num))\n return int_num\n\n\nclass NcAbinitHeader(AbinitHeader):\n \"\"\"The abinit header found in the NC pseudopotential files.\"\"\"\n _attr_desc = namedtuple(\"att\", \"default astype\")\n\n _VARS = {\n # Mandatory\n \"zatom\": _attr_desc(None, _int_from_str),\n \"zion\": _attr_desc(None, float),\n \"pspdat\": _attr_desc(None, float),\n \"pspcod\": _attr_desc(None, int),\n \"pspxc\": _attr_desc(None, int),\n \"lmax\": _attr_desc(None, int),\n \"lloc\": _attr_desc(None, int),\n \"r2well\": _attr_desc(None, float),\n \"mmax\": _attr_desc(None, float),\n # Optional variables for non linear-core correction. HGH does not have it.\n \"rchrg\": _attr_desc(0.0, float), # radius at which the core charge vanish (i.e. cut-off in a.u.)\n \"fchrg\": _attr_desc(0.0, float),\n \"qchrg\": _attr_desc(0.0, float),\n }\n del _attr_desc\n\n def __init__(self, summary, **kwargs):\n super(NcAbinitHeader, self).__init__()\n\n # pseudos generated by APE use llocal instead of lloc.\n if \"llocal\" in kwargs:\n kwargs[\"lloc\"] = kwargs.pop(\"llocal\")\n\n self.summary = summary.strip()\n\n for key, desc in NcAbinitHeader._VARS.items():\n default, astype = desc.default, desc.astype\n value = kwargs.pop(key, None)\n\n if value is None:\n value = default\n if default is None:\n raise RuntimeError(\"Attribute %s must be specified\" % key)\n else:\n try:\n value = astype(value)\n except:\n raise RuntimeError(\"Conversion Error for key %s, value %s\" % (key, value))\n\n self[key] = value\n\n # Add remaining arguments, e.g. extension_switch\n if kwargs:\n self.update(kwargs)\n\n @staticmethod\n def fhi_header(filename, ppdesc):\n \"\"\"\n Parse the FHI abinit header. Example:\n\n Troullier-Martins psp for element Sc Thu Oct 27 17:33:22 EDT 1994\n 21.00000 3.00000 940714 zatom, zion, pspdat\n 1 1 2 0 2001 .00000 pspcod,pspxc,lmax,lloc,mmax,r2well\n 1.80626423934776 .22824404341771 1.17378968127746 rchrg,fchrg,qchrg\n \"\"\"\n lines = _read_nlines(filename, 4)\n\n try:\n header = _dict_from_lines(lines[:4], [0, 3, 6, 3])\n except ValueError:\n # The last record with rchrg ... seems to be optional.\n header = _dict_from_lines(lines[:3], [0, 3, 6])\n\n summary = lines[0]\n\n return NcAbinitHeader(summary, **header)\n\n @staticmethod\n def hgh_header(filename, ppdesc):\n \"\"\"\n Parse the HGH abinit header. Example:\n\n Hartwigsen-Goedecker-Hutter psp for Ne, from PRB58, 3641 (1998)\n 10 8 010605 zatom,zion,pspdat\n 3 1 1 0 2001 0 pspcod,pspxc,lmax,lloc,mmax,r2well\n \"\"\"\n lines = _read_nlines(filename, 3)\n\n header = _dict_from_lines(lines[:3], [0, 3, 6])\n summary = lines[0]\n\n return NcAbinitHeader(summary, **header)\n\n @staticmethod\n def gth_header(filename, ppdesc):\n \"\"\"\n Parse the GTH abinit header. Example:\n\n Goedecker-Teter-Hutter Wed May 8 14:27:44 EDT 1996\n 1 1 960508 zatom,zion,pspdat\n 2 1 0 0 2001 0. pspcod,pspxc,lmax,lloc,mmax,r2well\n 0.2000000 -4.0663326 0.6778322 0 0 rloc, c1, c2, c3, c4\n 0 0 0 rs, h1s, h2s\n 0 0 rp, h1p\n 1.36 .2 0.6 rcutoff, rloc\n \"\"\"\n lines = _read_nlines(filename, 7)\n\n header = _dict_from_lines(lines[:3], [0, 3, 6])\n summary = lines[0]\n\n return NcAbinitHeader(summary, **header)\n\n @staticmethod\n def oncvpsp_header(filename, ppdesc):\n \"\"\"\n Parse the ONCVPSP abinit header. Example:\n\n Li ONCVPSP r_core= 2.01 3.02\n 3.0000 3.0000 140504 zatom,zion,pspd\n 8 2 1 4 600 0 pspcod,pspxc,lmax,lloc,mmax,r2well\n 5.99000000 0.00000000 0.00000000 rchrg fchrg qchrg\n 2 2 0 0 0 nproj\n 0 extension_switch\n 0 -2.5000025868368D+00 -1.2006906995331D+00\n 1 0.0000000000000D+00 0.0000000000000D+00 0.0000000000000D+00\n 2 1.0000000000000D-02 4.4140499497377D-02 1.9909081701712D-02\n \"\"\"\n lines = _read_nlines(filename, 6)\n\n header = _dict_from_lines(lines[:3], [0, 3, 6])\n summary = lines[0]\n\n # Replace pspd with pspdata\n header.update({'pspdat': header['pspd']})\n header.pop('pspd')\n\n # Read extension switch\n header[\"extension_switch\"] = int(lines[5].split()[0])\n\n return NcAbinitHeader(summary, **header)\n\n @staticmethod\n def tm_header(filename, ppdesc):\n \"\"\"\n Parse the TM abinit header. Example:\n\n Troullier-Martins psp for element Fm Thu Oct 27 17:28:39 EDT 1994\n 100.00000 14.00000 940714 zatom, zion, pspdat\n 1 1 3 0 2001 .00000 pspcod,pspxc,lmax,lloc,mmax,r2well\n 0 4.085 6.246 0 2.8786493 l,e99.0,e99.9,nproj,rcpsp\n .00000000 .0000000000 .0000000000 .00000000 rms,ekb1,ekb2,epsatm\n 1 3.116 4.632 1 3.4291849 l,e99.0,e99.9,nproj,rcpsp\n .00000000 .0000000000 .0000000000 .00000000 rms,ekb1,ekb2,epsatm\n 2 4.557 6.308 1 2.1865358 l,e99.0,e99.9,nproj,rcpsp\n .00000000 .0000000000 .0000000000 .00000000 rms,ekb1,ekb2,epsatm\n 3 23.251 29.387 1 2.4776730 l,e99.0,e99.9,nproj,rcpsp\n .00000000 .0000000000 .0000000000 .00000000 rms,ekb1,ekb2,epsatm\n 3.62474762267880 .07409391739104 3.07937699839200 rchrg,fchrg,qchrg\n \"\"\"\n lines = _read_nlines(filename, -1)\n header = []\n\n for lineno, line in enumerate(lines):\n header.append(line)\n if lineno == 2:\n # Read lmax.\n tokens = line.split()\n pspcod, pspxc, lmax, lloc = map(int, tokens[:4])\n mmax, r2well = map(float, tokens[4:6])\n #if tokens[-1].strip() != \"pspcod,pspxc,lmax,lloc,mmax,r2well\":\n # raise RuntimeError(\"%s: Invalid line\\n %s\" % (filename, line))\n\n lines = lines[3:]\n break\n\n # TODO\n # Parse the section with the projectors.\n #0 4.085 6.246 0 2.8786493 l,e99.0,e99.9,nproj,rcpsp\n #.00000000 .0000000000 .0000000000 .00000000 rms,ekb1,ekb2,epsatm\n projectors = OrderedDict()\n for idx in range(2*(lmax+1)):\n line = lines[idx]\n if idx % 2 == 0: proj_info = [line,]\n if idx % 2 == 1:\n proj_info.append(line)\n d = _dict_from_lines(proj_info, [5,4])\n projectors[int(d[\"l\"])] = d\n\n # Add the last line with info on nlcc.\n header.append(lines[idx+1])\n summary = header[0]\n\n header = _dict_from_lines(header, [0,3,6,3])\n\n return NcAbinitHeader(summary, **header)\n\n\nclass PawAbinitHeader(AbinitHeader):\n \"\"\"The abinit header found in the PAW pseudopotential files.\"\"\"\n _attr_desc = namedtuple(\"att\", \"default astype\")\n\n _VARS = {\n \"zatom\": _attr_desc(None, _int_from_str),\n \"zion\": _attr_desc(None, float),\n \"pspdat\": _attr_desc(None, float),\n \"pspcod\": _attr_desc(None, int),\n \"pspxc\": _attr_desc(None, int),\n \"lmax\": _attr_desc(None, int),\n \"lloc\": _attr_desc(None, int),\n \"mmax\": _attr_desc(None, int),\n \"r2well\": _attr_desc(None, float),\n \"pspfmt\": _attr_desc(None, str),\n \"creatorID\": _attr_desc(None, int),\n \"basis_size\": _attr_desc(None, int),\n \"lmn_size\": _attr_desc(None, int),\n \"orbitals\": _attr_desc(None, list),\n \"number_of_meshes\": _attr_desc(None, int),\n \"r_cut\": _attr_desc(None, float), # r_cut(PAW) in the header\n \"shape_type\": _attr_desc(None, int),\n \"rshape\": _attr_desc(None, float),\n }\n del _attr_desc\n\n def __init__(self, summary, **kwargs):\n super(PawAbinitHeader, self).__init__()\n\n self.summary = summary.strip()\n\n for key, desc in self._VARS.items():\n default, astype = desc.default, desc.astype\n\n value = kwargs.pop(key, None)\n\n if value is None:\n value = default\n if default is None:\n raise RuntimeError(\"Attribute %s must be specified\" % key)\n else:\n try:\n value = astype(value)\n except:\n raise RuntimeError(\"Conversion Error for key %s, with value %s\" % (key, value))\n\n self[key] = value\n\n if kwargs:\n raise RuntimeError(\"kwargs should be empty but got %s\" % str(kwargs))\n\n @staticmethod\n def paw_header(filename, ppdesc):\n \"\"\"\n Parse the PAW abinit header. Examples:\n\n Paw atomic data for element Ni - Generated by AtomPAW (N. Holzwarth) + AtomPAW2Abinit v3.0.5\n 28.000 18.000 20061204 : zatom,zion,pspdat\n 7 7 2 0 350 0. : pspcod,pspxc,lmax,lloc,mmax,r2well\n paw3 1305 : pspfmt,creatorID\n 5 13 : basis_size,lmn_size\n 0 0 1 1 2 : orbitals\n 3 : number_of_meshes\n 1 3 350 1.1803778368E-05 3.5000000000E-02 : mesh 1, type,size,rad_step[,log_step]\n 2 1 921 2.500000000000E-03 : mesh 2, type,size,rad_step[,log_step]\n 3 3 391 1.1803778368E-05 3.5000000000E-02 : mesh 3, type,size,rad_step[,log_step]\n 2.3000000000 : r_cut(SPH)\n 2 0.\n\n Another format:\n\n C (US d-loc) - PAW data extracted from US-psp (D.Vanderbilt) - generated by USpp2Abinit v2.3.0\n 6.000 4.000 20090106 : zatom,zion,pspdat\n 7 11 1 0 560 0. : pspcod,pspxc,lmax,lloc,mmax,r2well\n paw4 2230 : pspfmt,creatorID\n 4 8 : basis_size,lmn_size\n 0 0 1 1 : orbitals\n 5 : number_of_meshes\n 1 2 560 1.5198032759E-04 1.6666666667E-02 : mesh 1, type,size,rad_step[,log_step]\n 2 2 556 1.5198032759E-04 1.6666666667E-02 : mesh 2, type,size,rad_step[,log_step]\n 3 2 576 1.5198032759E-04 1.6666666667E-02 : mesh 3, type,size,rad_step[,log_step]\n 4 2 666 1.5198032759E-04 1.6666666667E-02 : mesh 4, type,size,rad_step[,log_step]\n 5 2 673 1.5198032759E-04 1.6666666667E-02 : mesh 5, type,size,rad_step[,log_step]\n 1.5550009124 : r_cut(PAW)\n 3 0. : shape_type,rshape\n\n Yet nnother one:\n\n Paw atomic data for element Si - Generated by atompaw v3.0.1.3 & AtomPAW2Abinit v3.3.1\n 14.000 4.000 20120814 : zatom,zion,pspdat\n 7 11 1 0 663 0. : pspcod,pspxc,lmax,lloc,mmax,r2well\n paw5 1331 : pspfmt,creatorID\n 4 8 : basis_size,lmn_size\n 0 0 1 1 : orbitals\n 5 : number_of_meshes\n 1 2 663 8.2129718540404674E-04 1.1498160595656655E-02 : mesh 1, type,size,rad_step[,log_step]\n 2 2 658 8.2129718540404674E-04 1.1498160595656655E-02 : mesh 2, type,size,rad_step[,log_step]\n 3 2 740 8.2129718540404674E-04 1.1498160595656655E-02 : mesh 3, type,size,rad_step[,log_step]\n 4 2 819 8.2129718540404674E-04 1.1498160595656655E-02 : mesh 4, type,size,rad_step[,log_step]\n 5 2 870 8.2129718540404674E-04 1.1498160595656655E-02 : mesh 5, type,size,rad_step[,log_step]\n 1.5669671236 : r_cut(PAW)\n 2 0. : shape_type,rshape\n \"\"\"\n supported_formats = [\"paw3\", \"paw4\", \"paw5\"]\n if ppdesc.format not in supported_formats:\n raise NotImplementedError(\"format %s not in %s\" % (ppdesc.format, supported_formats))\n\n lines = _read_nlines(filename, -1)\n\n summary = lines[0]\n header = _dict_from_lines(lines[:5], [0, 3, 6, 2, 2], sep=\":\")\n\n lines = lines[5:]\n # TODO\n # Parse orbitals and number of meshes.\n header[\"orbitals\"] = [int(t) for t in lines[0].split(\":\")[0].split()]\n header[\"number_of_meshes\"] = num_meshes = int(lines[1].split(\":\")[0])\n #print filename, header\n\n # Skip meshes =\n lines = lines[2+num_meshes:]\n #for midx in range(num_meshes):\n # l = midx + 1\n\n #print lines[0]\n header[\"r_cut\"] = float(lines[0].split(\":\")[0])\n #print lines[1]\n header.update(_dict_from_lines(lines[1], [2], sep=\":\"))\n\n #print(\"PAW header\\n\", header)\n return PawAbinitHeader(summary, **header)\n\n\nclass PseudoParserError(Exception):\n \"\"\"Base Error class for the exceptions raised by :class:`PseudoParser`\"\"\"\n\n\nclass PseudoParser(object):\n \"\"\"\n Responsible for parsing pseudopotential files and returning pseudopotential objects.\n\n Usage::\n\n pseudo = PseudoParser().parse(\"filename\")\n \"\"\"\n Error = PseudoParserError\n\n # Supported values of pspcod\n ppdesc = namedtuple(\"ppdesc\", \"pspcod name psp_type format\")\n\n # TODO Recheck\n _PSPCODES = OrderedDict( {\n 1: ppdesc(1, \"TM\", \"NC\", None),\n 2: ppdesc(2, \"GTH\", \"NC\", None),\n 3: ppdesc(3, \"HGH\", \"NC\", None),\n 4: ppdesc(4, \"Teter\", \"NC\", None),\n #5: ppdesc(5, \"NC\", , None),\n 6: ppdesc(6, \"FHI\", \"NC\", None),\n 7: ppdesc(6, \"PAW_abinit_text\", \"PAW\", None),\n 8: ppdesc(8, \"ONCVPSP\", \"NC\", None),\n 10: ppdesc(10, \"HGHK\", \"NC\", None),\n })\n del ppdesc\n # renumber functionals from oncvpsp todo confrim that 3 is 2\n #_FUNCTIONALS = {1: {'n': 4, 'name': 'Wigner'},\n # 2: {'n': 5, 'name': 'HL'},\n # 3: {'n': 2, 'name': 'PWCA'},\n # 4: {'n': 11, 'name': 'PBE'}}\n\n def __init__(self):\n # List of files that have been parsed succesfully.\n self._parsed_paths = []\n\n # List of files that could not been parsed.\n self._wrong_paths = []\n\n def scan_directory(self, dirname, exclude_exts=(), exclude_fnames=()):\n \"\"\"\n Analyze the files contained in directory dirname.\n\n Args:\n dirname: directory path\n exclude_exts: list of file extensions that should be skipped.\n exclude_fnames: list of file names that should be skipped.\n\n Returns:\n List of pseudopotential objects.\n \"\"\"\n for i, ext in enumerate(exclude_exts):\n if not ext.strip().startswith(\".\"):\n exclude_exts[i] = \".\" + ext.strip()\n\n # Exclude files depending on the extension.\n paths = []\n for fname in os.listdir(dirname):\n root, ext = os.path.splitext(fname)\n path = os.path.join(dirname, fname)\n if (ext in exclude_exts or fname in exclude_fnames or\n fname.startswith(\".\") or not os.path.isfile(path)): continue\n paths.append(path)\n\n pseudos = []\n for path in paths:\n # Parse the file and generate the pseudo.\n try:\n pseudo = self.parse(path)\n except:\n pseudo = None\n\n if pseudo is not None:\n pseudos.append(pseudo)\n self._parsed_paths.extend(path)\n else:\n self._wrong_paths.extend(path)\n\n return pseudos\n\n def read_ppdesc(self, filename):\n \"\"\"\n Read the pseudopotential descriptor from file filename.\n\n Returns:\n Pseudopotential descriptor. None if filename is not a valid pseudopotential file.\n\n Raises:\n `PseudoParserError` if fileformat is not supported.\n \"\"\"\n if filename.endswith(\".xml\"):\n raise self.Error(\"XML pseudo not supported yet\")\n\n else:\n # Assume file with the abinit header.\n lines = _read_nlines(filename, 80)\n\n for lineno, line in enumerate(lines):\n\n if lineno == 2:\n try:\n tokens = line.split()\n pspcod, pspxc = map(int, tokens[:2])\n except:\n msg = \"%s: Cannot parse pspcod, pspxc in line\\n %s\" % (filename, line)\n logger.critical(msg)\n return None\n\n #if tokens[-1].strip().replace(\" \",\"\") not in [\"pspcod,pspxc,lmax,lloc,mmax,r2well\",\n # \"pspcod,pspxc,lmax,llocal,mmax,r2well\"]:\n # raise self.Error(\"%s: Invalid line\\n %s\" % (filename, line))\n # return None\n\n if pspcod not in self._PSPCODES:\n raise self.Error(\"%s: Don't know how to handle pspcod %s\\n\" % (filename, pspcod))\n\n ppdesc = self._PSPCODES[pspcod]\n\n if pspcod == 7:\n # PAW -> need to know the format pspfmt\n tokens = lines[lineno+1].split()\n pspfmt, creatorID = tokens[:2]\n #if tokens[-1].strip() != \"pspfmt,creatorID\":\n # raise self.Error(\"%s: Invalid line\\n %s\" % (filename, line))\n # return None\n\n ppdesc = ppdesc._replace(format = pspfmt)\n\n return ppdesc\n\n return None\n\n def parse(self, filename):\n \"\"\"\n Read and parse a pseudopotential file. Main entry point for client code.\n\n Returns:\n pseudopotential object or None if filename is not a valid pseudopotential file.\n \"\"\"\n path = os.path.abspath(filename)\n\n # Only PAW supports XML at present.\n if filename.endswith(\".xml\"):\n return PawXmlSetup(path)\n\n ppdesc = self.read_ppdesc(path)\n\n if ppdesc is None:\n logger.critical(\"Cannot find ppdesc in %s\" % path)\n return None\n\n psp_type = ppdesc.psp_type\n\n parsers = {\n \"FHI\": NcAbinitHeader.fhi_header,\n \"GTH\": NcAbinitHeader.gth_header,\n \"TM\": NcAbinitHeader.tm_header,\n \"Teter\": NcAbinitHeader.tm_header,\n \"HGH\": NcAbinitHeader.hgh_header,\n \"HGHK\": NcAbinitHeader.hgh_header,\n \"ONCVPSP\": NcAbinitHeader.oncvpsp_header,\n \"PAW_abinit_text\": PawAbinitHeader.paw_header,\n }\n\n try:\n header = parsers[ppdesc.name](path, ppdesc)\n except Exception:\n raise self.Error(path + \":\\n\" + straceback())\n\n if psp_type == \"NC\":\n pseudo = NcAbinitPseudo(path, header)\n elif psp_type == \"PAW\":\n pseudo = PawAbinitPseudo(path, header)\n else:\n raise NotImplementedError(\"psp_type not in [NC, PAW]\")\n\n return pseudo\n\n\n#TODO use RadialFunction from pseudo_dojo.\nclass RadialFunction(namedtuple(\"RadialFunction\", \"mesh values\")):\n pass\n\n\nclass PawXmlSetup(Pseudo, PawPseudo):\n def __init__(self, filepath):\n self.path = os.path.abspath(filepath)\n\n # Get the XML root (this trick is used to that the object is pickleable).\n root = self.root\n\n # Get the version of the XML format\n self.paw_setup_version = root.get(\"version\")\n\n # Info on the atom.\n atom_attrib = root.find(\"atom\").attrib\n\n #self._symbol = atom_attrib[\"symbol\"]\n self._zatom = int(float(atom_attrib[\"Z\"]))\n self.core, self.valence = map(float, [atom_attrib[\"core\"], atom_attrib[\"valence\"]])\n\n # Build xc from header.\n xc_info = root.find(\"xc_functional\").attrib\n self.xc = XcFunc.from_type_name(xc_info[\"type\"], xc_info[\"name\"])\n\n # Old XML files do not define this field!\n # In this case we set the PAW radius to None.\n #self._paw_radius = float(root.find(\"PAW_radius\").attrib[\"rpaw\"])\n\n #self.ae_energy = {k: float(v) for k,v in root.find(\"ae_energy\").attrib.items()}\n pawr_element = root.find(\"PAW_radius\")\n self._paw_radius = None\n if pawr_element is not None:\n self._paw_radius = float(pawr_element.attrib[\"rpaw\"])\n\n #<valence_states>\n # <state n=\"2\" l=\"0\" f=\"2\" rc=\"1.10\" e=\"-0.6766\" id=\"N-2s\"/>\n # <state n=\"2\" l=\"1\" f=\"3\" rc=\"1.10\" e=\"-0.2660\" id=\"N-2p\"/>\n # <state l=\"0\" rc=\"1.10\" e=\" 0.3234\" id=\"N-s1\"/>\n # <state l=\"1\" rc=\"1.10\" e=\" 0.7340\" id=\"N-p1\"/>\n # <state l=\"2\" rc=\"1.10\" e=\" 0.0000\" id=\"N-d1\"/>\n #</valence_states>\n #\n # The valence_states element contains several state elements.\n # For this setup, the first two lines describe bound eigenstates\n # with occupation numbers and principal quantum numbers.\n # Notice, that the three additional unbound states should have no f and n attributes.\n # In this way, we know that only the first two bound states (with f and n attributes)\n # should be used for constructing an initial guess for the wave functions.\n\n self.valence_states = OrderedDict()\n for node in root.find(\"valence_states\"):\n attrib = AttrDict(node.attrib)\n assert attrib.id not in self.valence_states\n self.valence_states[attrib.id] = attrib\n #print(self.valence_states)\n\n # Parse the radial grids\n self.rad_grids = {}\n for node in root.findall(\"radial_grid\"):\n grid_params = node.attrib\n gid = grid_params[\"id\"]\n assert gid not in self.rad_grids\n\n self.rad_grids[gid] = self._eval_grid(grid_params)\n\n def __getstate__(self):\n \"\"\"\n Return state is pickled as the contents for the instance.\n\n In this case we just remove the XML root element process since Element object cannot be pickled.\n \"\"\"\n return {k: v for k, v in self.__dict__.items() if k not in [\"_root\"]}\n\n @lazy_property\n def root(self):\n from xml.etree import cElementTree as Et\n tree = Et.parse(self.filepath)\n return tree.getroot()\n\n @property\n def Z(self):\n return self._zatom\n\n @property\n def Z_val(self):\n \"\"\"Number of valence electrons.\"\"\"\n return self.valence\n\n # FIXME\n @property\n def l_max(self):\n \"\"\"Maximum angular momentum.\"\"\"\n return None\n\n @property\n def l_local(self):\n \"\"\"Angular momentum used for the local part.\"\"\"\n return None\n\n @property\n def summary(self):\n \"\"\"String summarizing the most important properties.\"\"\"\n return \"\"\n\n @property\n def paw_radius(self):\n return self._paw_radius\n\n @property\n def supports_soc(self):\n \"\"\"\n Here I assume that the ab-initio code can treat the SOC within the on-site approximation\n \"\"\"\n return True\n\n @staticmethod\n def _eval_grid(grid_params):\n \"\"\"\n This function receives a dictionary with the parameters defining the\n radial mesh and returns a `ndarray` with the mesh\n \"\"\"\n eq = grid_params.get(\"eq\").replace(\" \", \"\")\n istart, iend = int(grid_params.get(\"istart\")), int(grid_params.get(\"iend\"))\n indices = list(range(istart, iend+1))\n\n if eq == 'r=a*exp(d*i)':\n a, d = float(grid_params['a']), float(grid_params['d'])\n mesh = [a * np.exp(d * i) for i in indices]\n\n elif eq == 'r=a*i/(n-i)':\n a, n = float(grid_params['a']), float(grid_params['n'])\n mesh = [a * i / (n - i) for i in indices]\n\n elif eq == 'r=a*(exp(d*i)-1)':\n a, d = float(grid_params['a']), float(grid_params['d'])\n mesh = [a * (np.exp(d * i) - 1.0) for i in indices]\n\n elif eq == 'r=d*i':\n d = float(grid_params['d'])\n mesh = [d * i for i in indices]\n\n elif eq == 'r=(i/n+a)^5/a-a^4':\n a, n = float(grid_params['a']), float(grid_params['n'])\n mesh = [(i / n + a)**5 / a - a**4 for i in indices]\n\n else:\n raise ValueError('Unknown grid type: %s' % eq)\n\n return np.array(mesh)\n\n def _parse_radfunc(self, func_name):\n \"\"\"Parse the first occurence of func_name in the XML file.\"\"\"\n node = self.root.find(func_name)\n grid = node.attrib[\"grid\"]\n values = np.array([float(s) for s in node.text.split()])\n\n return self.rad_grids[grid], values, node.attrib\n\n def _parse_all_radfuncs(self, func_name):\n \"\"\"Parse all the nodes with tag func_name in the XML file.\"\"\"\n for node in self.root.findall(func_name):\n grid = node.attrib[\"grid\"]\n values = np.array([float(s) for s in node.text.split()])\n\n yield self.rad_grids[grid], values, node.attrib\n\n @lazy_property\n def ae_core_density(self):\n \"\"\"The all-electron radial density.\"\"\"\n mesh, values, attrib = self._parse_radfunc(\"ae_core_density\")\n return RadialFunction(mesh, values)\n\n @lazy_property\n def pseudo_core_density(self):\n \"\"\"The pseudized radial density.\"\"\"\n mesh, values, attrib = self._parse_radfunc(\"pseudo_core_density\")\n return RadialFunction(mesh, values)\n\n @lazy_property\n def ae_partial_waves(self):\n \"\"\"Dictionary with the AE partial waves indexed by state.\"\"\"\n ae_partial_waves = OrderedDict()\n for mesh, values, attrib in self._parse_all_radfuncs(\"ae_partial_wave\"):\n state = attrib[\"state\"]\n #val_state = self.valence_states[state]\n ae_partial_waves[state] = RadialFunction(mesh, values)\n\n return ae_partial_waves\n\n @property\n def pseudo_partial_waves(self):\n \"\"\"Dictionary with the pseudo partial waves indexed by state.\"\"\"\n pseudo_partial_waves = OrderedDict()\n for (mesh, values, attrib) in self._parse_all_radfuncs(\"pseudo_partial_wave\"):\n state = attrib[\"state\"]\n #val_state = self.valence_states[state]\n pseudo_partial_waves[state] = RadialFunction(mesh, values)\n\n return pseudo_partial_waves\n\n @lazy_property\n def projector_functions(self):\n \"\"\"Dictionary with the PAW projectors indexed by state.\"\"\"\n projector_functions = OrderedDict()\n for (mesh, values, attrib) in self._parse_all_radfuncs(\"projector_function\"):\n state = attrib[\"state\"]\n #val_state = self.valence_states[state]\n projector_functions[state] = RadialFunction(mesh, values)\n\n return projector_functions\n\n def yield_figs(self, **kwargs): # pragma: no cover\n \"\"\"\n This function *generates* a predefined list of matplotlib figures with minimal input from the user.\n \"\"\"\n yield self.plot_densities(title=\"PAW densities\", show=False)\n yield self.plot_waves(title=\"PAW waves\", show=False)\n yield self.plot_projectors(title=\"PAW projectors\", show=False)\n #yield self.plot_potentials(title=\"potentials\", show=False)\n\n @add_fig_kwargs\n def plot_densities(self, ax=None, **kwargs):\n \"\"\"\n Plot the PAW densities.\n\n Args:\n ax: matplotlib :class:`Axes` or None if a new figure should be created.\n\n Returns:\n `matplotlib` figure\n \"\"\"\n ax, fig, plt = get_ax_fig_plt(ax)\n\n ax.grid(True)\n ax.set_xlabel('r [Bohr]')\n #ax.set_ylabel('density')\n\n for i, den_name in enumerate([\"ae_core_density\", \"pseudo_core_density\"]):\n rden = getattr(self, den_name)\n label = \"$n_c$\" if i == 1 else r\"$\\tilde{n}_c$\"\n ax.plot(rden.mesh, rden.mesh * rden.values, label=label, lw=2)\n\n ax.legend(loc=\"best\")\n\n return fig\n\n @add_fig_kwargs\n def plot_waves(self, ax=None, fontsize=12, **kwargs):\n \"\"\"\n Plot the AE and the pseudo partial waves.\n\n Args:\n ax: matplotlib :class:`Axes` or None if a new figure should be created.\n fontsize: fontsize for legends and titles\n\n Returns: `matplotlib` figure\n \"\"\"\n ax, fig, plt = get_ax_fig_plt(ax)\n\n ax.grid(True)\n ax.set_xlabel(\"r [Bohr]\")\n ax.set_ylabel(r\"$r\\phi,\\, r\\tilde\\phi\\, [Bohr]^{-\\frac{1}{2}}$\")\n\n #ax.axvline(x=self.paw_radius, linewidth=2, color='k', linestyle=\"--\")\n #ax.annotate(\"$r_c$\", xy=(self.paw_radius + 0.1, 0.1))\n\n for state, rfunc in self.pseudo_partial_waves.items():\n ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label=\"PS-WAVE: \" + state)\n\n for state, rfunc in self.ae_partial_waves.items():\n ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label=\"AE-WAVE: \" + state)\n\n ax.legend(loc=\"best\", shadow=True, fontsize=fontsize)\n\n return fig\n\n @add_fig_kwargs\n def plot_projectors(self, ax=None, fontsize=12, **kwargs):\n \"\"\"\n Plot the PAW projectors.\n\n Args:\n ax: matplotlib :class:`Axes` or None if a new figure should be created.\n\n Returns: `matplotlib` figure\n \"\"\"\n ax, fig, plt = get_ax_fig_plt(ax)\n title = kwargs.pop(\"title\", \"Projectors\")\n ax.grid(True)\n ax.set_xlabel('r [Bohr]')\n ax.set_ylabel(r\"$r\\tilde p\\, [Bohr]^{-\\frac{1}{2}}$\")\n\n #ax.axvline(x=self.paw_radius, linewidth=2, color='k', linestyle=\"--\")\n #ax.annotate(\"$r_c$\", xy=(self.paw_radius + 0.1, 0.1))\n\n for state, rfunc in self.projector_functions.items():\n ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, label=\"TPROJ: \" + state)\n\n ax.legend(loc=\"best\", shadow=True, fontsize=fontsize)\n\n return fig\n\n #@add_fig_kwargs\n #def plot_potentials(self, **kwargs):\n # \"\"\"\n # ================ ==============================================================\n # kwargs Meaning\n # ================ ==============================================================\n # title Title of the plot (Default: None).\n # show True to show the figure (Default).\n # savefig 'abc.png' or 'abc.eps' to save the figure to a file.\n # ================ ==============================================================\n\n # Returns:\n # `matplotlib` figure\n # \"\"\"\n # title = kwargs.pop(\"title\", \"Potentials\")\n # show = kwargs.pop(\"show\", True)\n # savefig = kwargs.pop(\"savefig\", None)\n\n # import matplotlib.pyplot as plt\n\n # fig = plt.figure()\n\n # ax = fig.add_subplot(1,1,1)\n # ax.grid(True)\n # ax.set_xlabel('r [Bohr]')\n # ax.set_ylabel('density')\n # ax.axvline(x=self.paw_radius, linewidth=2, color='k', linestyle=\"--\")\n # ax.annotate(\"$r_c$\", xy=(self.paw_radius + 0.1, 0.1))\n\n # for state, rfunc in self.potentials.items():\n # ax.plot(rfunc.mesh, rfunc.values, label=\"TPROJ: \" + state)\n\n # ax.legend(loc=\"best\")\n\n # if title is not None: fig.suptitle(title)\n # if show: plt.show()\n # if savefig: fig.savefig(savefig)\n # return fig\n\n\nclass PseudoTable(six.with_metaclass(abc.ABCMeta, collections.Sequence, MSONable, object)):\n \"\"\"\n Define the pseudopotentials from the element table.\n Individidual elements are accessed by name, symbol or atomic number.\n\n For example, the following all retrieve iron:\n\n print elements[26]\n Fe\n print elements.Fe\n Fe\n print elements.symbol('Fe')\n Fe\n print elements.name('iron')\n Fe\n print elements.isotope('Fe')\n Fe\n \"\"\"\n @classmethod\n def as_table(cls, items):\n \"\"\"\n Return an instance of :class:`PseudoTable` from the iterable items.\n \"\"\"\n if isinstance(items, cls): return items\n return cls(items)\n\n @classmethod\n def from_dir(cls, top, exts=None, exclude_dirs=\"_*\"):\n \"\"\"\n Find all pseudos in the directory tree starting from top.\n\n Args:\n top: Top of the directory tree\n exts: List of files extensions. if exts == \"all_files\"\n we try to open all files in top\n exclude_dirs: Wildcard used to exclude directories.\n\n return: :class:`PseudoTable` sorted by atomic number Z.\n \"\"\"\n pseudos = []\n\n if exts == \"all_files\":\n for f in [os.path.join(top, fn) for fn in os.listdir(top)]:\n if os.path.isfile(f):\n try:\n p = Pseudo.from_file(f)\n if p:\n pseudos.append(p)\n else:\n logger.info('Skipping file %s' % f)\n except:\n logger.info('Skipping file %s' % f)\n if not pseudos:\n logger.warning('No pseudopotentials parsed from folder %s' % top)\n return None\n logger.info('Creating PseudoTable with %i pseudopotentials' % len(pseudos))\n\n else:\n if exts is None: exts=(\"psp8\",)\n\n for p in find_exts(top, exts, exclude_dirs=exclude_dirs):\n try:\n pseudos.append(Pseudo.from_file(p))\n except Exception as exc:\n logger.critical(\"Error in %s:\\n%s\" % (p, exc))\n\n return cls(pseudos).sort_by_z()\n\n def __init__(self, pseudos):\n \"\"\"\n Args:\n pseudos: List of pseudopotentials or filepaths\n \"\"\"\n # Store pseudos in a default dictionary with z as key.\n # Note that we can have more than one pseudo for given z.\n # hence the values are lists of pseudos.\n if not isinstance(pseudos, collections.Iterable):\n pseudos = [pseudos]\n\n if len(pseudos) and is_string(pseudos[0]):\n pseudos = list_strings(pseudos)\n\n self._pseudos_with_z = defaultdict(list)\n\n for pseudo in pseudos:\n if not isinstance(pseudo, Pseudo):\n pseudo = Pseudo.from_file(pseudo)\n if pseudo is not None:\n self._pseudos_with_z[pseudo.Z].append(pseudo)\n\n for z in self.zlist:\n pseudo_list = self._pseudos_with_z[z]\n symbols = [p.symbol for p in pseudo_list]\n symbol = symbols[0]\n if any(symb != symbol for symb in symbols):\n raise ValueError(\"All symbols must be equal while they are: %s\" % str(symbols))\n\n setattr(self, symbol, pseudo_list)\n\n def __getitem__(self, Z):\n \"\"\"\n Retrieve pseudos for the atomic number z. Accepts both int and slice objects.\n \"\"\"\n if isinstance(Z, slice):\n assert Z.stop is not None\n pseudos = []\n for znum in iterator_from_slice(Z):\n pseudos.extend(self._pseudos_with_z[znum])\n return self.__class__(pseudos)\n else:\n return self.__class__(self._pseudos_with_z[Z])\n\n def __len__(self):\n return len(list(self.__iter__()))\n\n def __iter__(self):\n \"\"\"Process the elements in Z order.\"\"\"\n for z in self.zlist:\n for pseudo in self._pseudos_with_z[z]:\n yield pseudo\n\n def __repr__(self):\n return \"<%s at %s>\" % (self.__class__.__name__, id(self))\n\n def __str__(self):\n return self.to_table()\n\n @property\n def allnc(self):\n \"\"\"True if all pseudos are norm-conserving.\"\"\"\n return all(p.isnc for p in self)\n\n @property\n def allpaw(self):\n \"\"\"True if all pseudos are PAW.\"\"\"\n return all(p.ispaw for p in self)\n\n @property\n def zlist(self):\n \"\"\"Ordered list with the atomic numbers available in the table.\"\"\"\n return sorted(list(self._pseudos_with_z.keys()))\n\n #def max_ecut_pawecutdg(self, accuracy):\n #\"\"\"Return the maximum value of ecut and pawecutdg based on the hints available in the pseudos.\"\"\"\n # ecut = max(p.hint_for_accuracy(accuracy=accuracy).ecut for p in self)\n # pawecutdg = max(p.hint_for_accuracy(accuracy=accuracy).pawecutdg for p in self)\n # return ecut, pawecutdg\n\n def as_dict(self, **kwargs):\n d = {}\n for p in self:\n k, count = p.element.name, 1\n # k, count = p.element, 1\n # Handle multiple-pseudos with the same name!\n while k in d:\n k += k.split(\"#\")[0] + \"#\" + str(count)\n count += 1\n d.update({k: p.as_dict()})\n d['@module'] = self.__class__.__module__\n d['@class'] = self.__class__.__name__\n return d\n\n @classmethod\n def from_dict(cls, d):\n pseudos = []\n dec = MontyDecoder()\n for k, v in d.items():\n if not k.startswith('@'):\n pseudos.append(dec.process_decoded(v))\n return cls(pseudos)\n\n def is_complete(self, zmax=118):\n \"\"\"\n True if table is complete i.e. all elements with Z < zmax have at least on pseudopotential\n \"\"\"\n for z in range(1, zmax):\n if not self[z]: return False\n return True\n\n def all_combinations_for_elements(self, element_symbols):\n \"\"\"\n Return a list with all the the possible combination of pseudos\n for the given list of element_symbols.\n Each item is a list of pseudopotential objects.\n\n Example::\n\n table.all_combinations_for_elements([\"Li\", \"F\"])\n \"\"\"\n d = OrderedDict()\n for symbol in element_symbols:\n d[symbol] = self.select_symbols(symbol, ret_list=True)\n\n from itertools import product\n return list(product(*d.values()))\n\n def pseudo_with_symbol(self, symbol, allow_multi=False):\n \"\"\"\n Return the pseudo with the given chemical symbol.\n\n Args:\n symbols: String with the chemical symbol of the element\n allow_multi: By default, the method raises ValueError\n if multiple occurrences are found. Use allow_multi to prevent this.\n\n Raises:\n ValueError if symbol is not found or multiple occurences are present and not allow_multi\n \"\"\"\n pseudos = self.select_symbols(symbol, ret_list=True)\n if not pseudos or (len(pseudos) > 1 and not allow_multi):\n raise ValueError(\"Found %d occurrences of symbol %s\" % (len(pseudos), symbol))\n\n if not allow_multi:\n return pseudos[0]\n else:\n return pseudos\n\n def pseudos_with_symbols(self, symbols):\n \"\"\"\n Return the pseudos with the given chemical symbols.\n\n Raises:\n ValueError if one of the symbols is not found or multiple occurences are present.\n \"\"\"\n pseudos = self.select_symbols(symbols, ret_list=True)\n found_symbols = [p.symbol for p in pseudos]\n duplicated_elements = [s for s, o in collections.Counter(found_symbols).items() if o > 1]\n\n if duplicated_elements:\n raise ValueError(\"Found multiple occurrences of symbol(s) %s\" % ', '.join(duplicated_elements))\n missing_symbols = [s for s in symbols if s not in found_symbols]\n\n if missing_symbols:\n raise ValueError(\"Missing data for symbol(s) %s\" % ', '.join(missing_symbols))\n\n return pseudos\n\n def select_symbols(self, symbols, ret_list=False):\n \"\"\"\n Return a :class:`PseudoTable` with the pseudopotentials with the given list of chemical symbols.\n\n Args:\n symbols: str or list of symbols\n Prepend the symbol string with \"-\", to exclude pseudos.\n ret_list: if True a list of pseudos is returned instead of a :class:`PseudoTable`\n \"\"\"\n symbols = list_strings(symbols)\n exclude = symbols[0].startswith(\"-\")\n\n if exclude:\n if not all(s.startswith(\"-\") for s in symbols):\n raise ValueError(\"When excluding symbols, all strings must start with `-`\")\n symbols = [s[1:] for s in symbols]\n\n symbols = set(symbols)\n pseudos = []\n for p in self:\n if exclude:\n if p.symbol in symbols: continue\n else:\n if p.symbol not in symbols: continue\n\n pseudos.append(p)\n\n if ret_list:\n return pseudos\n else:\n return self.__class__(pseudos)\n\n def get_pseudos_for_structure(self, structure):\n \"\"\"\n Return the list of :class:`Pseudo` objects to be used for this :class:`Structure`.\n\n Args:\n structure: pymatgen :class:`Structure`.\n\n Raises:\n `ValueError` if one of the chemical symbols is not found or\n multiple occurences are present in the table.\n \"\"\"\n return self.pseudos_with_symbols(structure.symbol_set)\n\n def print_table(self, stream=sys.stdout, filter_function=None):\n \"\"\"\n A pretty ASCII printer for the periodic table, based on some filter_function.\n\n Args:\n stream: file-like object\n filter_function:\n A filtering function that take a Pseudo as input and returns a boolean.\n For example, setting filter_function = lambda p: p.Z_val > 2 will print\n a periodic table containing only pseudos with Z_val > 2.\n \"\"\"\n print(self.to_table(filter_function=filter_function), file=stream)\n\n def to_table(self, filter_function=None):\n \"\"\"Return string with data in tabular form.\"\"\"\n table = []\n for p in self:\n if filter_function is not None and filter_function(p): continue\n table.append([p.basename, p.symbol, p.Z_val, p.l_max, p.l_local, p.xc, p.type])\n return tabulate(table, headers= [\"basename\", \"symbol\", \"Z_val\", \"l_max\", \"l_local\", \"XC\", \"type\"],\n tablefmt=\"grid\")\n\n def sorted(self, attrname, reverse=False):\n \"\"\"\n Sort the table according to the value of attribute attrname.\n\n Return:\n New class:`PseudoTable` object\n \"\"\"\n attrs = []\n for i, pseudo in self:\n try:\n a = getattr(pseudo, attrname)\n except AttributeError:\n a = np.inf\n attrs.append((i, a))\n\n # Sort attrs, and build new table with sorted pseudos.\n return self.__class__([self[a[0]] for a in sorted(attrs, key=lambda t: t[1], reverse=reverse)])\n\n def sort_by_z(self):\n \"\"\"Return a new :class:`PseudoTable` with pseudos sorted by Z\"\"\"\n return self.__class__(sorted(self, key=lambda p: p.Z))\n\n def select(self, condition):\n \"\"\"\n Select only those pseudopotentials for which condition is True.\n Return new class:`PseudoTable` object.\n\n Args:\n condition:\n Function that accepts a :class:`Pseudo` object and returns True or False.\n \"\"\"\n return self.__class__([p for p in self if condition(p)])\n\n def with_dojo_report(self):\n \"\"\"Select pseudos containing the DOJO_REPORT section. Return new class:`PseudoTable` object.\"\"\"\n return self.select(condition=lambda p: p.has_dojo_report)\n\n def select_rows(self, rows):\n \"\"\"\n Return new class:`PseudoTable` object with pseudos in the given rows of the periodic table.\n rows can be either a int or a list of integers.\n \"\"\"\n if not isinstance(rows, (list, tuple)): rows = [rows]\n return self.__class__([p for p in self if p.element.row in rows])\n\n def select_family(self, family):\n # e.g element.is_alkaline\n return self.__class__([p for p in self if getattr(p.element, \"is_\" + family)])\n"
] | [
[
"numpy.dot",
"scipy.spatial.Voronoi",
"matplotlib.pyplot.barh",
"numpy.max",
"numpy.mean",
"numpy.fill_diagonal",
"numpy.any",
"numpy.cross",
"numpy.where",
"numpy.reshape",
"numpy.ceil",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.array",
"numpy.sum",
"numpy.linalg.norm",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks"
],
[
"numpy.exp",
"numpy.array",
"numpy.rint",
"numpy.eye"
]
] | [
{
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cjs220/alre_experiments | [
"bb1969e1650368357b8e76d3b4f262dedd47f752",
"bb1969e1650368357b8e76d3b4f262dedd47f752"
] | [
"util/general.py",
"util/handler.py"
] | [
"import time\nfrom typing import Dict, Callable\nimport os\nimport random\nimport pprint\n\nimport numpy as np\nimport pandas as pd\nfrom joblib import Parallel, delayed\nfrom matplotlib.figure import Figure\nfrom pandas.core.generic import NDFrame\nimport tensorflow as tf\n\n\ndef disable_tensorflowgpu():\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\n\ndef set_all_random_seeds(seed=0):\n np.random.seed(seed)\n tf.random.set_seed(seed)\n random.seed(seed)\n\n\ndef save_results(\n path: str = None,\n figures: Dict[str, Figure] = None,\n frames: Dict[str, NDFrame] = None,\n config: Dict = None,\n exist_ok=False,\n):\n figures = figures or {}\n frames = frames or {}\n\n if path is None:\n # make a timestamped directory\n path = pd.Timestamp.now().strftime('%Y-%m-%d_%H%M')\n os.makedirs(path, exist_ok=exist_ok)\n\n for fig_name, fig in figures.items():\n fig_path = os.path.join(path, fig_name)\n fig.tight_layout()\n fig.savefig(fig_path + '.svg')\n\n for frame_name, frame in frames.items():\n frame_path = os.path.join(path, frame_name)\n frame.to_csv(frame_path + '.csv')\n\n if config:\n config_path = os.path.join(path, 'config.txt')\n with open(config_path, 'w+') as outfile:\n outfile.write(pprint.pformat(config))\n\n\ndef run_parallel_experiments(\n experiment_func: Callable,\n n_experiments: int,\n n_jobs: int = -2,\n verbose: int = 10,\n **experiment_func_kwargs\n):\n return Parallel(n_jobs=n_jobs, verbose=verbose)(\n delayed(experiment_func)(**experiment_func_kwargs)\n for _ in range(n_experiments)\n )\n\n\ndef experiment(func: Callable) -> Callable:\n # decorator for experiment functions\n\n def wrapper(*args, random_seed=0, **kwargs):\n logger = kwargs['logger']\n logger.info('Starting experiment')\n t0 = time.time()\n set_all_random_seeds(random_seed)\n results = func(*args, **kwargs)\n logger.info(f'Finished experiment; total time {int(time.time() - t0):.3E} s')\n return results\n\n return wrapper\n",
"import logging\nimport os\nimport shutil\nimport sys\nimport time\nfrom copy import copy\nfrom pathlib import Path\nfrom typing import Callable, List, Dict\nfrom warnings import warn\n\nimport pandas as pd\nimport yaml\nfrom joblib import Parallel, delayed\nfrom pkg_resources import resource_filename\n\nfrom util import save_results\nfrom util.plotting import matplotlib_setup\n\n\nclass ExperimentHandler:\n\n def __init__(self,\n experiment_name: str,\n config_name: str,\n run_func: Callable,\n analysis_func: Callable,\n logger_level=logging.INFO\n ):\n self.config_name = config_name\n self.config_path = \\\n resource_filename(\n 'experiments',\n os.path.join(experiment_name, 'config', f'{config_name}.yml')\n )\n self.run_func = run_func\n self.analysis_func = analysis_func\n self.logger_level = logger_level\n\n with open(self.config_path, 'r') as infile:\n self.config = yaml.safe_load(infile)\n\n self.out_dir = os.path.join('runs', config_name)\n os.makedirs(self.out_dir, exist_ok=True)\n self.results = self._load_existing_results()\n\n def run_experiments(self, n_experiments: int, n_jobs: int = 1) -> None:\n random_seeds = self._get_new_random_seeds(n_experiments)\n run_dirs = self._init_run_dirs(random_seeds)\n loggers = [self._get_logger(run_dir) for run_dir in run_dirs]\n\n if n_jobs == 1:\n new_results = [\n self.run_func(\n **self.config,\n random_seed=seed,\n logger=loggers[i]\n )\n for i, seed in enumerate(random_seeds)\n ]\n else:\n new_results = Parallel(n_jobs=n_jobs, verbose=10)(\n delayed(self.run_func)(\n **self.config,\n random_seed=seed,\n logger=loggers[i]\n )\n for i, seed in enumerate(random_seeds)\n )\n\n self._save_results_csv(new_results, run_dirs)\n self._store_new_results(new_results, random_seeds)\n\n def run_analysis(self) -> None:\n matplotlib_setup(use_tex=False)\n results_list = list(self.results.values())\n figures = self.analysis_func(\n self._list_of_dict_to_dict_of_list(results_list),\n self.config\n )\n save_results(\n path=os.path.join('plots', self.config_name),\n figures=figures,\n exist_ok=True\n )\n\n def _load_existing_results(self) -> Dict[int, Dict]:\n existing_results = dict() # Dict[random_seed] = Dict\n for dir_name in os.listdir(self.out_dir):\n dir_path = os.path.join(self.out_dir, dir_name)\n random_seed = self._check_config(dir_path)\n result = dict()\n csv_names = [fname for fname in os.listdir(dir_path)\n if fname.endswith('.csv')]\n\n if not csv_names:\n delete_dir = input(f'Directory {dir_path} contains no csv files; '\n f'would you like to delete it? (y/n)') == 'y'\n if delete_dir:\n shutil.rmtree(dir_path)\n continue\n\n for csv_name in csv_names:\n key, _ = csv_name.split('.csv')\n result[key] = pd.read_csv(\n os.path.join(dir_path, csv_name),\n index_col=0\n )\n if result:\n assert random_seed not in existing_results, \\\n 'Two experiments have been run with the same random seed'\n existing_results[random_seed] = result\n return existing_results\n\n @staticmethod\n def _save_results_csv(new_results: List[Dict],\n run_dirs: List[str]):\n for run_dir, result in zip(run_dirs, new_results):\n for frame_name, frame in result.items():\n out_path = os.path.join(run_dir, frame_name + '.csv')\n frame.to_csv(out_path)\n\n def _store_new_results(self,\n new_results: List[Dict],\n random_seeds: List[int]):\n if new_results:\n new_results = dict(zip(random_seeds, new_results))\n self.results.update(new_results)\n\n def _check_config(self, dir_path: str) -> int:\n # check same config and extract the random seed\n config_path = os.path.join(dir_path, 'config.yml')\n with open(config_path, 'r') as infile:\n config = yaml.safe_load(infile)\n\n random_seed = config.pop('random_seed')\n\n if set(config.keys()) != set(self.config.keys()):\n warn(f'Config {config_path} has different keys to this config.')\n for item_name, item_val in config.items():\n if item_val != self.config.get(item_name, None):\n warn(f'Config {config_path} '\n f'has different value for config item {item_name}.')\n\n return random_seed\n\n def _init_run_dir(self, random_seed: int) -> str:\n run_dir_name = pd.Timestamp.now().strftime('%Y-%m-%d_%H%M%S')\n run_dir_path = os.path.join(self.out_dir, run_dir_name)\n os.mkdir(run_dir_path)\n new_config_path = os.path.join(run_dir_path, 'config.yml')\n new_config = copy(self.config)\n new_config['random_seed'] = random_seed\n with open(new_config_path, 'w+') as outfile:\n yaml.dump(new_config, outfile)\n\n return run_dir_path\n\n def _init_run_dirs(self, random_seeds: List[int]) -> List[str]:\n run_dirs = []\n for seed in random_seeds:\n run_dirs.append(self._init_run_dir(seed))\n time.sleep(1)\n return run_dirs\n\n def _get_logger(self, run_dir: str) -> logging.Logger:\n logger_name = os.path.join(run_dir, 'run.log')\n Path(logger_name).touch()\n\n logger = logging.getLogger(logger_name)\n logger.setLevel(self.logger_level)\n format_string = \"%(asctime)s — %(name)s — %(levelname)s — %(message)s\"\n log_format = logging.Formatter(format_string)\n\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.setFormatter(log_format)\n logger.addHandler(console_handler)\n\n file_handler = logging.FileHandler(logger_name, mode='a')\n file_handler.setFormatter(log_format)\n logger.addHandler(file_handler)\n\n return logger\n\n @staticmethod\n def _list_of_dict_to_dict_of_list(list_of_dict: List[Dict]) -> Dict[str, List]:\n try:\n return {k: [d[k] for d in list_of_dict] for k in list_of_dict[0]}\n except IndexError:\n return {}\n\n @property\n def _trialed_seeds(self) -> List[int]:\n # random seeds for which the experiments have already been run\n return list(self.results.keys())\n\n def _get_new_random_seeds(self, n_experiments: int) -> List[int]:\n max_trialed_seed = max(self._trialed_seeds) \\\n if self._trialed_seeds else -1\n random_seeds = list(range(max_trialed_seed + 1,\n max_trialed_seed + n_experiments + 1))\n return random_seeds\n"
] | [
[
"pandas.Timestamp.now",
"numpy.random.seed",
"tensorflow.random.set_seed"
],
[
"pandas.Timestamp.now"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bdonkey/Advanced-Deep-Learning-with-Keras | [
"e8d72b3ac9c7bf746ebf4502a6208f90b025d617"
] | [
"chapter5-improved-gan/lsgan-mnist-5.2.1.py"
] | [
"'''Trains LSGAN on MNIST using Keras\n\nLSGAN is similar to DCGAN except for the MSE loss used by the \nDiscriminator and Adversarial networks.\n \n[1] Radford, Alec, Luke Metz, and Soumith Chintala.\n\"Unsupervised representation learning with deep convolutional\ngenerative adversarial networks.\" arXiv preprint arXiv:1511.06434 (2015).\n\n[2] Mao, Xudong, et al. \"Least squares generative adversarial networks.\" \n2017 IEEE International Conference on Computer Vision (ICCV). IEEE, 2017.\n'''\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom keras.layers import Input\nfrom keras.optimizers import RMSprop\nfrom keras.models import Model\nfrom keras.datasets import mnist\nfrom keras.models import load_model\n\nimport numpy as np\nimport argparse\n\nimport sys\nsys.path.append(\"..\")\nfrom lib import gan\n\n\ndef build_and_train_models():\n # load MNIST dataset\n (x_train, _), (_, _) = mnist.load_data()\n\n # reshape data for CNN as (28, 28, 1) and normalize\n image_size = x_train.shape[1]\n x_train = np.reshape(x_train, [-1, image_size, image_size, 1])\n x_train = x_train.astype('float32') / 255\n\n model_name = \"lsgan_mnist\"\n # network parameters\n # the latent or z vector is 100-dim\n latent_size = 100\n input_shape = (image_size, image_size, 1)\n batch_size = 64\n lr = 2e-4\n decay = 6e-8\n train_steps = 40000\n\n # build discriminator model\n inputs = Input(shape=input_shape, name='discriminator_input')\n discriminator = gan.discriminator(inputs, activation=None)\n # [1] uses Adam, but discriminator converges easily with RMSprop\n optimizer = RMSprop(lr=lr, decay=decay)\n # LSGAN uses MSE loss [2]\n discriminator.compile(loss='mse',\n optimizer=optimizer,\n metrics=['accuracy'])\n discriminator.summary()\n\n # build generator model\n input_shape = (latent_size, )\n inputs = Input(shape=input_shape, name='z_input')\n generator = gan.generator(inputs, image_size)\n generator.summary()\n\n # build adversarial model = generator + discriminator\n optimizer = RMSprop(lr=lr*0.5, decay=decay*0.5)\n # freeze the weights of discriminator during adversarial training\n discriminator.trainable = False\n adversarial = Model(inputs,\n discriminator(generator(inputs)),\n name=model_name)\n # LSGAN uses MSE loss [2]\n adversarial.compile(loss='mse',\n optimizer=optimizer,\n metrics=['accuracy'])\n adversarial.summary()\n\n # train discriminator and adversarial networks\n models = (generator, discriminator, adversarial)\n params = (batch_size, latent_size, train_steps, model_name)\n gan.train(models, x_train, params)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n help_ = \"Load generator h5 model with trained weights\"\n parser.add_argument(\"-g\", \"--generator\", help=help_)\n args = parser.parse_args()\n if args.generator:\n generator = load_model(args.generator)\n gan.test_generator(generator)\n else:\n build_and_train_models()\n"
] | [
[
"numpy.reshape"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RobertCsordas/modules | [
"efdb8790b074862581e035c9ab5bf889440a8023"
] | [
"models/conv.py"
] | [
"import torch\nfrom layers import Conv2d, Linear\n\nclass ConvModel(torch.nn.Module):\n def __init__(self, in_channels: int, out_channels: int, dropout: bool = True):\n super().__init__()\n\n self.features = torch.nn.Sequential(\n Conv2d(in_channels, 32, 3, padding=1),\n torch.nn.ReLU(),\n torch.nn.MaxPool2d(2),\n Conv2d(32, 64, 3, padding=1),\n torch.nn.ReLU(),\n torch.nn.MaxPool2d(2),\n Conv2d(64, 128, 3, padding=1),\n torch.nn.Dropout(0.25 if dropout else 0.0),\n torch.nn.ReLU(),\n torch.nn.MaxPool2d(2),\n Conv2d(128, 256, 3, padding=1),\n torch.nn.ReLU(),\n torch.nn.Dropout(0.5 if dropout else 0.0)\n )\n\n # Certain neurons play a crucial role\n\n self.out_layer = Linear(256, out_channels)\n\n def __call__(self, inp: torch.Tensor) -> torch.Tensor:\n return self.out_layer(self.features(inp).mean(dim=(2,3)))"
] | [
[
"torch.nn.Dropout",
"torch.nn.MaxPool2d",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mealworm/gammapy | [
"a838b2ca347dd6321f8da4e4097a33150d7b9be6",
"a838b2ca347dd6321f8da4e4097a33150d7b9be6"
] | [
"gammapy/utils/fits.py",
"gammapy/cube/tests/test_psf_kernel.py"
] | [
"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\n.. _utils-fits:\n\nGammapy FITS utilities\n======================\n\n.. _utils-fits-tables:\n\nFITS tables\n-----------\n\nIn Gammapy we use the nice `astropy.table.Table` class a lot to represent all\nkinds of data (e.g. event lists, spectral points, light curves, source catalogs).\nThe most common format to store tables is FITS. In this section we show examples\nand mention some limitations of Table FITS I/O.\n\nAlso, note that if you have the choice, you might want to use a better format\nthan FITS to store tables. All of these are nice and have very good support\nin Astropy: ``ECSV``, ``HDF5``, ``ASDF``.\n\nIn Astropy, there is the `~astropy.table.Table` class with a nice data model\nand API. Let's make an example table object that has some metadata on the\ntable and columns of different types:\n\n>>> from astropy.table import Table, Column\n>>> table = Table(meta={'version': 42})\n>>> table['a'] = [1, 2]\n>>> table['b'] = Column([1, 2], unit='m', description='Velocity')\n>>> table['c'] = ['x', 'yy']\n>>> table\n<Table length=2>\n a b c\n m\nint64 int64 str2\n----- ----- ----\n 1 1 x\n 2 2 yy\n>>> table.info()\n<Table length=2>\nname dtype unit description\n---- ----- ---- -----------\n a int64\n b int64 m Velocity\n c str2\n\nWriting and reading the table to FITS is easy:\n\n>>> table.write('table.fits')\n>>> table2 = Table.read('table.fits')\n\nand works very nicely, column units and description round-trip:\n\n>>> table2\n<Table length=2>\n a b c\n m\nint64 float64 bytes2\n----- ------- ------\n 1 1.0 x\n 2 2.0 yy\n>>> table2.info()\n<Table length=2>\nname dtype unit description\n---- ------- ---- -----------\n a int64\n b float64 m Velocity\n c bytes2\n\nThis is with Astropy 3.0. In older versions of Astropy this didn't use\nto work, namely column description was lost.\n\nLooking at the FITS header and ``table2.meta``, one can see that\nthey are cheating a bit, storing table meta in ``COMMENT``:\n\n>>> fits.open('table.fits')[1].header\nXTENSION= 'BINTABLE' / binary table extension\nBITPIX = 8 / array data type\nNAXIS = 2 / number of array dimensions\nNAXIS1 = 18 / length of dimension 1\nNAXIS2 = 2 / length of dimension 2\nPCOUNT = 0 / number of group parameters\nGCOUNT = 1 / number of groups\nTFIELDS = 3 / number of table fields\nTTYPE1 = 'a '\nTFORM1 = 'K '\nTTYPE2 = 'b '\nTFORM2 = 'K '\nTUNIT2 = 'm '\nTTYPE3 = 'c '\nTFORM3 = '2A '\nVERSION = 42\nCOMMENT --BEGIN-ASTROPY-SERIALIZED-COLUMNS--\nCOMMENT datatype:\nCOMMENT - {name: a, datatype: int64}\nCOMMENT - {name: b, unit: m, datatype: int64, description: Velocity}\nCOMMENT - {name: c, datatype: string}\nCOMMENT meta:\nCOMMENT __serialized_columns__: {}\nCOMMENT --END-ASTROPY-SERIALIZED-COLUMNS--\n>>> table2.meta\nOrderedDict([('VERSION', 42),\n ('comments',\n ['--BEGIN-ASTROPY-SERIALIZED-COLUMNS--',\n 'datatype:',\n '- {name: a, datatype: int64}',\n '- {name: b, unit: m, datatype: int64, description: Velocity}',\n '- {name: c, datatype: string}',\n 'meta:',\n ' __serialized_columns__: {}',\n '--END-ASTROPY-SERIALIZED-COLUMNS--'])])\n\n\nTODO: we'll have to see how to handle this, i.e. if we want that\nbehaviour or not, and how to get consistent output accross Astropy versions.\nSee https://github.com/astropy/astropy/issues/7364\n\nLet's make sure for the following examples we have a clean ``table.meta``\nlike we did at the start:\n\n>>> table.meta.pop('comments', None)\n\nIf you want to avoid writing to disk, the way to directly convert between\n`~astropy.table.Table` and `~astropy.io.fits.BinTableHDU` is like this:\n\n>>> hdu = fits.BinTableHDU(table)\n\nThis calls `astropy.io.fits.table_to_hdu` in ``BinTableHDU.__init__``,\ni.e. if you don't pass extra options, this is equivalent to\n\n>>> hdu = fits.table_to_hdu(table)\n\nHowever, in this case, the column metadata that is serialised is\ndoesn't include the column ``description``.\nTODO: how to get consistent behaviour and FITS headers?\n\n>>> hdu.header\nXTENSION= 'BINTABLE' / binary table extension\nBITPIX = 8 / array data type\nNAXIS = 2 / number of array dimensions\nNAXIS1 = 18 / length of dimension 1\nNAXIS2 = 2 / length of dimension 2\nPCOUNT = 0 / number of group parameters\nGCOUNT = 1 / number of groups\nTFIELDS = 3 / number of table fields\nVERSION = 42\nTTYPE1 = 'a '\nTFORM1 = 'K '\nTTYPE2 = 'b '\nTFORM2 = 'K '\nTUNIT2 = 'm '\nTTYPE3 = 'c '\nTFORM3 = '2A '\n\nSomewhat surprisingly, ``Table(hdu)`` doesn't work and there is no\n``hdu_to_table`` function; instead you have to call ``Table.read``\nif you want to convert in the other direction:\n\n>>> table2 = Table.read(hdu)\n>>> table2.info()\n<Table length=2>\nname dtype unit\n---- ----- ----\n a int64\n b int64 m\n c str2\n\n\nAnother trick worth knowing about is how to read and write multiple tables\nto one FITS file. There is support in the ``Table`` API to read any HDU\nfrom a FITS file with multiple HDUs via the ``hdu`` option to ``Table.read``;\nyou can pass an integer HDU index or an HDU extension name string\n(see :ref:`astropy:table_io_fits`).\n\nFor writing (or if you prefer also for reading) multiple tables, you should\nuse the in-memory conversion to HDU objects and the `~astropy.io.fits.HDUList`\nlike this::\n\n hdu_list = fits.HDUList([\n fits.PrimaryHDU(),\n fits.BinTableHDU(table, name='spam'),\n fits.BinTableHDU(table, name='ham'),\n ])\n hdu_list.info()\n hdu_list.writeto('tables.fits')\n\n\nFor further information on Astropy, see the Astropy docs at\n:ref:`astropy:astropy-table` and :ref:`astropy:table_io_fits`.\n\nWe will have to see if / what we need here in `gammapy.utils.fits`\nas a stable and nice interface on top of what Astropy provides.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom collections import OrderedDict\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom .scripts import make_path\nfrom .energy import EnergyBounds\n\n__all__ = [\n 'SmartHDUList',\n 'energy_axis_to_ebounds',\n]\n\n\n# TODO: decide what to call this class.\n# Would `FITSFile` be better than `SmartHDUList`?\nclass SmartHDUList(object):\n \"\"\"A FITS HDU list wrapper with some sugar.\n\n This is a thin wrapper around `~astropy.io.fits.HDUList`,\n with some conveniences built in.\n\n Parameters\n ----------\n hdu_list : `~astropy.io.fits.HDUList`\n HDU list (stored in ``hdu_list`` attribute)\n\n Examples\n --------\n\n Opening a SmartHDUList calls `astropy.io.fits.open` to get a `~astropy.io.fits.HDUList`\n object, and then stores it away in the ``hdu_list`` attribute:\n\n >>> from gammapy.utils.fits import SmartHDUList\n >>> hdus = SmartHDUList.open('$GAMMAPY_EXTRA/datasets/catalogs/fermi/gll_psch_v08.fit.gz')\n >>> type(hdus.hdu_list)\n astropy.io.fits.hdu.hdulist.HDUList\n\n So of course, you can do the usual things via ``hdus.hdu_list``:\n\n >>> hdus.hdu_list.filename()\n >>> hdus.hdu_list.info()\n >>> [hdu.name for hdu in hdus.hdu_list]\n\n In addition, for a `SmartHDUList`, it's easier to get the HDUs you want:\n\n >>> hdus.get_hdu('Extended Sources') # by name\n >>> hdus.get_hdu(2) # by index\n >>> hdus.get_hdu(hdu_type='image') # first image (skip primary if empty)\n >>> hdus.get_hdu(hdu_type='table') # first table\n\n TODO: add more conveniences, e.g. to create HDU lists from lists of Gammapy\n objects that can be serialised to FITS (e.g. SkyImage, SkyCube, EventList, ...)\n \"\"\"\n\n def __init__(self, hdu_list):\n self.hdu_list = hdu_list\n\n @classmethod\n def open(cls, filename, **kwargs):\n \"\"\"Create from FITS file (`SmartHDUList`).\n\n This calls `astropy.io.fits.open`, passing ``**kwargs``.\n It reads the FITS headers, but not the data.\n\n The ``filename`` is passed through `~gammapy.utils.scripts.make_path`,\n which accepts strings or Path objects and does environment variable expansion.\n\n Parameters\n ----------\n filename : `str`\n Filename\n \"\"\"\n filename = str(make_path(filename))\n memmap = kwargs.pop('memmap', False)\n hdu_list = fits.open(filename, memmap=memmap, **kwargs)\n return cls(hdu_list)\n\n def write(self, filename, **kwargs):\n \"\"\"Write HDU list to FITS file.\n\n This calls `astropy.io.fits.HDUList.writeto`, passing ``**kwargs``.\n\n The ``filename`` is passed through `~gammapy.utils.scripts.make_path`,\n which accepts strings or Path objects and does environment variable expansion.\n\n Parameters\n ----------\n filename : `str`\n Filename\n \"\"\"\n filename = str(make_path(filename))\n self.hdu_list.writeto(filename, **kwargs)\n\n @property\n def names(self):\n \"\"\"List of HDU names (stripped, upper-case).\"\"\"\n return [hdu.name.strip().upper() for hdu in self.hdu_list]\n\n def get_hdu_index(self, hdu=None, hdu_type=None):\n \"\"\"Get index of HDU with given name, number or type.\n\n If ``hdu`` is given, tries to find an HDU of that given name or number.\n Otherwise, if ``hdu_type`` is given, looks for the first suitable HDU.\n\n Raises ``KeyError`` if no suitable HDU is found.\n\n Parameters\n ----------\n hdu : int or str\n HDU number or name, passed to `astropy.io.fits.HDUList.index_of`.\n hdu_type : {'primary', 'image' , 'table'}\n Type of HDU to load\n\n Returns\n -------\n idx : int\n HDU index\n \"\"\"\n # For the external API, we want the argument name to be `hdu`\n # But in this method, it's confusing because later we'll have\n # actual HDU objects. So we rename here: `hdu` -> `hdu_key`\n hdu_key = hdu\n del hdu\n\n if (hdu_key is None) and (hdu_type is None):\n raise ValueError('Must give either `hdu` or `hdu_type`. Got `None` for both.')\n\n # if (hdu_key is not None) and (hdu_type is not None):\n # raise ValueError(\n # 'Must give either `hdu` or `hdu_type`.'\n # ' Got a value for both: hdu={} and hdu_type={}'\n # ''.format(hdu_key, hdu_type)\n # )\n\n if hdu_key is not None:\n idx = self.hdu_list.index_of(hdu_key)\n # `HDUList.index_of` for integer input doesn't raise, just return\n # the number unchanged. Here we want to raise an error in this case.\n if not (0 <= idx < len(self.hdu_list)):\n raise KeyError('HDU not found: hdu={}. Index out of range.'.format(hdu_key))\n return idx\n\n if hdu_type is not None:\n for hdu_idx, hdu_object in enumerate(self.hdu_list):\n if hdu_type == 'primary':\n if isinstance(hdu_object, fits.PrimaryHDU):\n return hdu_idx\n elif hdu_type == 'image':\n # The `hdu.shape` check is used to skip empty `PrimaryHDU`\n # with no data. Those aren't very useful, now, are they?\n if hdu_object.is_image and len(hdu_object.shape) > 0:\n return hdu_idx\n elif hdu_type == 'table':\n if isinstance(hdu_object, fits.BinTableHDU):\n return hdu_idx\n else:\n raise ValueError('Invalid hdu_type={}'.format(hdu_type))\n\n raise KeyError('HDU not found: hdu={}, hdu_type={}'.format(hdu_key, hdu_type))\n\n def get_hdu(self, hdu=None, hdu_type=None):\n \"\"\"Get HDU with given name, number or type.\n\n This method simply calls ``get_hdu_index(hdu, hdu_type)``,\n and if successful, returns the HDU for that given index.\n \"\"\"\n index = self.get_hdu_index(hdu=hdu, hdu_type=hdu_type)\n hdu = self.hdu_list[index]\n return hdu\n\n\ndef fits_header_to_meta_dict(header):\n \"\"\"Convert `astropy.io.fits.Header` to `~collections.OrderedDict`.\n\n This is a lossy conversion, only key, value is stored\n (and not e.g. comments for each FITS \"card\").\n Also, \"COMMENT\" and \"HISTORY\" cards are completely removed.\n \"\"\"\n meta = OrderedDict(header)\n\n # Drop problematic header content, i.e. values of type\n # `astropy.io.fits.header._HeaderCommentaryCards`\n # Handling this well and preserving it is a bit complicated, see\n # See https://github.com/astropy/astropy/blob/master/astropy/io/fits/connect.py\n # for how `astropy.table.Table.read` does it\n # and see https://github.com/gammapy/gammapy/issues/701\n meta.pop('COMMENT', None)\n meta.pop('HISTORY', None)\n\n return meta\n\n\ndef _fits_table_to_table(hdu):\n \"\"\"Convert `astropy.io.fits.BinTableHDU` to `astropy.table.Table`.\n\n See `table_to_fits_table` to convert in the other direction and\n :ref:`utils-fits-tables` for a description and examples.\n\n TODO: The name of the table is stored in the Table meta information\n under the ``name`` keyword.\n\n Additional column information ``description`` and ``ucd`` can will be\n read from the header and stored in the column.meta attribute.\n\n Parameters\n ----------\n hdu : `~astropy.io.fits.BinTableHDU`\n FITS bin table containing the astropy table columns\n\n Returns\n -------\n table : `~astropy.table.Table`\n astropy table containing the desired columns\n \"\"\"\n # Re-use Astropy BinTableHDU -> Table implementation\n table = Table.read(hdu)\n\n # In addition, copy over extra column meta-data from the HDU\n for idx, colname in enumerate(hdu.columns.names):\n idx = str(idx + 1)\n col = table[colname]\n\n # Unit is already handled correctly in Astropy since a long time\n # col.unit = hdu.columns[colname].unit\n\n description = hdu.header.pop('TCOMM' + idx, None)\n col.meta['description'] = description\n\n ucd = hdu.header.pop('TUCD' + idx, None)\n col.meta['ucd'] = ucd\n\n return table\n\n\ndef energy_axis_to_ebounds(energy):\n \"\"\"Convert `~gammapy.utils.energy.EnergyBounds` to OGIP ``EBOUNDS`` extension.\n\n See https://heasarc.gsfc.nasa.gov/docs/heasarc/caldb/docs/memos/cal_gen_92_002/cal_gen_92_002.html#tth_sEc3.2\n \"\"\"\n energy = EnergyBounds(energy)\n table = Table()\n\n table['CHANNEL'] = np.arange(energy.nbins, dtype=np.int16)\n table['E_MIN'] = energy[:-1]\n table['E_MAX'] = energy[1:]\n\n hdu = fits.BinTableHDU(table)\n\n header = hdu.header\n header['EXTNAME'] = 'EBOUNDS', 'Name of this binary table extension'\n header['TELESCOP'] = 'DUMMY', 'Mission/satellite name'\n header['INSTRUME'] = 'DUMMY', 'Instrument/detector'\n header['FILTER'] = 'None', 'Filter information'\n header['CHANTYPE'] = 'PHA', 'Type of channels (PHA, PI etc)'\n header['DETCHANS'] = energy.nbins, 'Total number of detector PHA channels'\n header['HDUCLASS'] = 'OGIP', 'Organisation devising file format'\n header['HDUCLAS1'] = 'RESPONSE', 'File relates to response of instrument'\n header['HDUCLAS2'] = 'EBOUNDS', 'This is an EBOUNDS extension'\n header['HDUVERS'] = '1.2.0', 'Version of file format'\n\n return hdu\n\n\ndef ebounds_to_energy_axis(ebounds):\n \"\"\"Convert ``EBOUNDS`` extension to `~gammapy.utils.energy.EnergyBounds`\n \"\"\"\n table = Table.read(ebounds)\n emin = table['E_MIN'].quantity\n emax = table['E_MAX'].quantity\n energy = np.append(emin.value, emax.value[-1]) * emin.unit\n return EnergyBounds(energy)\n",
"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport astropy.units as u\nfrom astropy.coordinates import Angle\nfrom ...utils.testing import requires_dependency, requires_data\nfrom ...irf import TablePSF, EnergyDependentMultiGaussPSF\nfrom ...maps import Map, WcsNDMap, MapAxis, WcsGeom\nfrom .. import PSFKernel\n\n\n@requires_dependency('scipy')\ndef test_table_psf_to_kernel_map():\n sigma = 0.5 * u.deg\n binsz = 0.1 * u.deg\n geom = WcsGeom.create(binsz=binsz, npix=150)\n\n rad = Angle(np.linspace(0., 3 * sigma.to('deg').value, 100), 'deg')\n table_psf = TablePSF.from_shape(shape='gauss', width=sigma, rad=rad)\n kernel = PSFKernel.from_table_psf(table_psf, geom)\n kernel_array = kernel.psf_kernel_map.data\n\n # Is normalization OK?\n assert_allclose(kernel_array.sum(), 1.0, atol=1e-5)\n\n # maximum at the center of map?\n ind = np.unravel_index(np.argmax(kernel_array, axis=None), kernel_array.shape)\n # absolute tolerance at 0.5 because of even number of pixel here\n assert_allclose(ind, geom.center_pix, atol=0.5)\n\n\n@requires_dependency('scipy')\ndef test_psf_kernel_from_gauss_read_write(tmpdir):\n sigma = 0.5 * u.deg\n binsz = 0.1 * u.deg\n geom = WcsGeom.create(binsz=binsz, npix=150, axes=[MapAxis((0, 1, 2))])\n\n kernel = PSFKernel.from_gauss(geom, sigma)\n\n # Check that both maps are identical\n assert_allclose(kernel.psf_kernel_map.data[0], kernel.psf_kernel_map.data[1])\n\n # Is there an odd number of pixels\n assert_allclose(np.array(kernel.psf_kernel_map.geom.npix) % 2, 1)\n\n filename = str(tmpdir / \"test_kernel.fits\")\n # Test read and write\n kernel.write(filename, overwrite=True)\n newkernel = PSFKernel.read(filename)\n assert_allclose(kernel.psf_kernel_map.data, newkernel.psf_kernel_map.data)\n\n\n@requires_dependency('scipy')\ndef test_psf_kernel_convolve():\n sigma = 0.5 * u.deg\n binsz = 0.05 * u.deg\n\n testmap = WcsNDMap.create(binsz=binsz, width=5 * u.deg)\n testmap.fill_by_coord(([1], [1]), weights=np.array([2]))\n\n kernel = PSFKernel.from_gauss(testmap.geom, sigma, max_radius=1.5 * u.deg)\n\n # is kernel size OK?\n assert kernel.psf_kernel_map.geom.npix[0] == 61\n # is kernel maximum at the center?\n assert kernel.psf_kernel_map.data[30, 30] == np.max(kernel.psf_kernel_map.data)\n\n conv_map = kernel.apply(testmap)\n\n # Is convolved map normalization OK\n assert_allclose(conv_map.data.sum(), 2.0, atol=1e-3)\n\n # Is the maximum in the convolved map at the right position?\n assert conv_map.get_by_coord([1, 1]) == np.max(conv_map.data)\n\n\n@requires_dependency('scipy')\n@requires_data('gammapy-extra')\ndef test_energy_dependent_psf_kernel():\n\n # Define energy axis\n energy_axis = MapAxis.from_edges(np.logspace(-1., 1., 4), unit='TeV', name='energy')\n\n # Create WcsGeom and map\n geom = WcsGeom.create(binsz=0.02 * u.deg, width=4.0 * u.deg, axes=[energy_axis])\n some_map = Map.from_geom(geom)\n some_map.fill_by_coord([[0.2, 0.4], [-0.1, 0.6], [0.5, 3.6]])\n\n # TODO : build EnergyDependentTablePSF programmatically rather than using CTA 1DC IRF\n filename = '$GAMMAPY_EXTRA/datasets/cta-1dc/caldb/data/cta//1dc/bcf/South_z20_50h/irf_file.fits'\n psf = EnergyDependentMultiGaussPSF.read(filename, hdu='POINT SPREAD FUNCTION')\n table_psf = psf.to_energy_dependent_table_psf(theta=0.5 * u.deg)\n\n psf_kernel = PSFKernel.from_table_psf(table_psf, geom, max_radius=1 * u.deg)\n\n assert psf_kernel.psf_kernel_map.data.shape == (3, 101, 101)\n\n some_map_convolved = psf_kernel.apply(some_map)\n\n assert_allclose(some_map_convolved.data.sum(axis=(1, 2)), np.array((0, 1, 1)))\n"
] | [
[
"numpy.arange",
"numpy.append"
],
[
"numpy.logspace",
"numpy.max",
"numpy.argmax",
"numpy.testing.assert_allclose",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
flowersw/compose | [
"d51a397988f4a9b78a489260b541d02d59a4d290"
] | [
"docs/source/examples/demo/turbofan_degredation/__init__.py"
] | [
"import os\nimport pandas as pd\nfrom demo import utils\n\nURL = r'https://ti.arc.nasa.gov/c/6/'\nPWD = os.path.dirname(__file__)\n\n\ndef _download_data():\n output = os.path.join(PWD, 'download')\n utils.download(URL, output)\n\n\ndef _data():\n path = os.path.join(PWD, 'download', 'train_FD004.txt')\n if not os.path.exists(path): _download_data()\n cols = ['engine_no', 'time_in_cycles']\n cols += ['operational_setting_{}'.format(i + 1) for i in range(3)]\n cols += ['sensor_measurement_{}'.format(i + 1) for i in range(26)]\n df = pd.read_csv(path, sep=' ', header=None, names=cols)\n df = df.drop(cols[-5:], axis=1).rename_axis('id')\n df['time'] = pd.date_range('1/1/2000', periods=df.shape[0], freq='600s')\n return df\n\n\ndef _read(file):\n path = os.path.join(PWD, file)\n df = pd.read_csv(path, parse_dates=['time'], index_col='id')\n return df\n\n\ndef load_sample():\n return _read('sample.csv')\n"
] | [
[
"pandas.read_csv",
"pandas.date_range"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
johanDDC/ttax | [
"eae0a307cf5099e3f97540231b4428291a6766ec",
"eae0a307cf5099e3f97540231b4428291a6766ec"
] | [
"ttax/random_.py",
"ttax/ops_test.py"
] | [
"import numpy as np\nimport jax\nimport jax.numpy as jnp\n\nfrom ttax.base_class import TT\nfrom ttax.base_class import TTMatrix\n\n\ndef tensor(rng, shape, tt_rank=2, batch_shape=None, dtype=jnp.float32):\n \"\"\"Generate a random `TT-Tensor` of the given shape and `TT-rank`.\n \n :param rng: JAX PRNG key\n :type rng: random state is described by two unsigned 32-bit integers\n :param shape: desired tensor shape\n :type shape: array\n :param tt_rank: desired `TT-ranks` of `TT-Tensor`\n :type tt_rank: single number for equal `TT-ranks` or array specifying all `TT-ranks`\n :param batch_shape: desired batch shape of `TT-Tensor`\n :type batch_shape: array\n :param dtype: type of elements in `TT-Tensor`\n :type dtype: `dtype`\n :return: generated `TT-Tensor`\n :rtype: TT\n \"\"\"\n shape = np.array(shape)\n tt_rank = np.array(tt_rank)\n batch_shape = list(batch_shape) if batch_shape else []\n\n num_dims = shape.size\n if tt_rank.size == 1:\n tt_rank = tt_rank * np.ones(num_dims - 1)\n tt_rank = np.insert(tt_rank, 0, 1)\n tt_rank = np.append(tt_rank, 1)\n\n tt_rank = tt_rank.astype(int)\n\n tt_cores = []\n rng_arr = jax.random.split(rng, num_dims)\n for i in range(num_dims):\n curr_core_shape = [tt_rank[i], shape[i], tt_rank[i + 1]]\n curr_core_shape = batch_shape + curr_core_shape\n tt_cores.append(jax.random.normal(rng_arr[i], curr_core_shape, dtype=dtype))\n\n return TT(tt_cores)\n\n\ndef matrix(rng, shape, tt_rank=2, batch_shape=None, dtype=jnp.float32):\n \"\"\"Generate a random `TT-Matrix` of the given shape and `TT-rank`.\n \n :param rng: JAX PRNG key\n :type rng: random state is described by two unsigned 32-bit integers\n :param shape: desired tensor shape\n :type shape: array\n :param tt_rank: desired `TT-ranks` of `TT-Matrix`\n :type tt_rank: single number for equal `TT-ranks` or array specifying all `TT-ranks`\n :param batch_shape: desired batch shape of `TT-Matrix`\n :type batch_shape: array\n :param dtype: type of elements in `TT-Matrix`\n :type dtype: `dtype`\n :return: generated `TT-Matrix`\n :rtype: TTMatrix\n \"\"\"\n shape = [np.array(shape[0]), np.array(shape[1])]\n tt_rank = np.array(tt_rank)\n batch_shape = list(batch_shape) if batch_shape else []\n\n num_dims = shape[0].size\n if tt_rank.size == 1:\n tt_rank = tt_rank * np.ones(num_dims - 1)\n tt_rank = np.insert(tt_rank, 0, 1)\n tt_rank = np.append(tt_rank, 1)\n\n tt_rank = tt_rank.astype(int)\n\n tt_cores = []\n rng_arr = jax.random.split(rng, num_dims)\n for i in range(num_dims):\n curr_core_shape = [tt_rank[i], shape[0][i], shape[1][i], tt_rank[i + 1]]\n curr_core_shape = batch_shape + curr_core_shape\n tt_cores.append(jax.random.normal(rng_arr[i], curr_core_shape, dtype=dtype))\n\n return TTMatrix(tt_cores)\n",
"from absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport numpy as np\nimport jax\nimport jax.numpy as jnp\nimport jax.test_util as jtu\nfrom jax.config import config\n\nfrom ttax.base_class import TT\nfrom ttax.base_class import TTMatrix\nfrom ttax import random_\nfrom ttax import ops\n\nconfig.parse_flags_with_absl()\n\n\nclass TTTensorTest(jtu.JaxTestCase):\n\n def testFullTensor2d(self):\n np.random.seed(1)\n for rank in [1, 2]:\n a = np.random.rand(10, rank)\n b = np.random.rand(rank, 9)\n tt_cores = (a.reshape(1, 10, rank), b.reshape(rank, 9, 1))\n desired = np.dot(a, b)\n tt_tens = TT(tt_cores)\n actual = ops.full(tt_tens)\n self.assertAllClose(desired, actual)\n\n def testFullTensor2dBatch(self):\n np.random.seed(1)\n for rank in [1, 2]:\n a = np.random.rand(3, 10, rank)\n b = np.random.rand(3, rank, 9)\n tt_cores = (a.reshape(3, 1, 10, rank), b.reshape(3, rank, 9, 1))\n desired = np.einsum('bij,bjk->bik', a, b)\n tt_tens = TT(tt_cores)\n actual = ops.full(tt_tens)\n self.assertAllClose(desired, actual)\n\n def testMultiply(self):\n # Multiply two TT-tensors.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n tt_a = random_.tensor(rng1, (1, 2, 3, 4), tt_rank=2, dtype=dtype)\n tt_b = random_.tensor(rng2, (1, 2, 3, 4), tt_rank=[1, 1, 4, 3, 1],\n dtype=dtype)\n\n res_actual1 = ops.full(ops.multiply(tt_a, tt_b))\n res_actual2 = ops.full(tt_a * tt_b)\n res_desired = ops.full(tt_a) * ops.full(tt_b)\n self.assertAllClose(res_actual1, res_desired)\n self.assertAllClose(res_actual2, res_desired)\n\n def testMultiplyBatch(self):\n # Multiply two batches of TT-tensors.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n tt_a = random_.tensor(rng1, (1, 2, 3, 4), tt_rank=2, batch_shape=(3,),\n dtype=dtype)\n tt_b = random_.tensor(rng2, (1, 2, 3, 4), tt_rank=[1, 1, 4, 3, 1],\n batch_shape=(3,), dtype=dtype)\n\n res_actual1 = ops.full(ops.multiply(tt_a, tt_b))\n res_actual2 = ops.full(tt_a * tt_b)\n res_desired = ops.full(tt_a) * ops.full(tt_b)\n self.assertAllClose(res_actual1, res_desired)\n self.assertAllClose(res_actual2, res_desired)\n\n def testFlatInner(self):\n # Multiply two TT-tensors.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n tt_a = random_.tensor(rng1, (1, 2, 3, 4), tt_rank=2, dtype=dtype)\n tt_b = random_.tensor(rng2, (1, 2, 3, 4), tt_rank=[1, 1, 4, 3, 1], dtype=dtype)\n res_actual = ops.flat_inner(tt_a, tt_b)\n res_desired = jnp.sum(ops.full(tt_a) * ops.full(tt_b))\n self.assertAllClose(res_actual, res_desired)\n \n def testAdd(self):\n # Add two TT-tensors.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n tt_a = random_.tensor(rng1, (2, 1, 3, 4), tt_rank=2, dtype=dtype)\n tt_b = random_.tensor(rng2, (2, 1, 3, 4), tt_rank=[1, 2, 4, 3, 1],\n dtype=dtype)\n\n res_actual1 = ops.full(ops.add(tt_a, tt_b))\n res_actual2 = ops.full(tt_a + tt_b)\n res_desired = ops.full(tt_a) + ops.full(tt_b)\n self.assertAllClose(res_actual1, res_desired)\n self.assertAllClose(res_actual2, res_desired)\n\n def testAddSameBatchSize(self):\n # Add two batches of TT-tensors.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n tt_a = random_.tensor(rng1, (2, 1, 3, 4), tt_rank=2, batch_shape=(3,),\n dtype=dtype)\n tt_b = random_.tensor(rng2, (2, 1, 3, 4), tt_rank=[1, 2, 4, 3, 1],\n batch_shape=(3,), dtype=dtype)\n\n res_actual1 = ops.full(ops.add(tt_a, tt_b))\n res_actual2 = ops.full(tt_a + tt_b)\n res_desired = ops.full(tt_a) + ops.full(tt_b)\n self.assertAllClose(res_actual1, res_desired)\n self.assertAllClose(res_actual2, res_desired)\n \n def testAddBroadcasting(self):\n # Sum two TT-tensors with broadcasting.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n tt_a = random_.tensor(rng1, (2, 1, 4), tt_rank=2, \n batch_shape=(1,), dtype=dtype)\n tt_b = random_.tensor(rng2, (2, 1, 4), tt_rank=[1, 2, 4, 1],\n batch_shape=(3,), dtype=dtype)\n \n res_actual1 = ops.full(ops.add(tt_a, tt_b))\n res_actual2 = ops.full(tt_b + tt_a)\n res_desired = ops.full(tt_a) + ops.full(tt_b)\n self.assertAllClose(res_actual1, res_desired)\n self.assertAllClose(res_actual2, res_desired)\n\n def testMultiplyByScalar(self):\n # Multiply batch of TT-tensor by scalar.\n c = 4.5\n rng = jax.random.PRNGKey(0)\n dtype = jnp.float32\n tt = random_.tensor(rng, (2, 1, 3, 4), tt_rank=[1, 2, 4, 3, 1],\n dtype=dtype)\n res_actual1 = ops.full(ops.multiply(tt, c))\n res_actual2 = ops.full(tt * c)\n res_actual3 = ops.full(c * tt)\n res_desired = c * ops.full(tt)\n self.assertAllClose(res_actual1, res_desired, rtol=1e-4)\n self.assertAllClose(res_actual2, res_desired, rtol=1e-4)\n self.assertAllClose(res_actual3, res_desired, rtol=1e-4)\n\n def testMultiplyBatchByScalar(self):\n # Multiply batch of TT-tensor by scalar.\n c = 4.5\n rng = jax.random.PRNGKey(0)\n dtype = jnp.float32\n tt = random_.tensor(rng, (2, 1, 3, 4), tt_rank=[1, 2, 4, 3, 1],\n batch_shape=(3,), dtype=dtype)\n res_actual1 = ops.full(ops.multiply(tt, c))\n res_actual2 = ops.full(tt * c)\n res_actual3 = ops.full(c * tt)\n res_desired = c * ops.full(tt)\n self.assertAllClose(res_actual1, res_desired, rtol=1e-4)\n self.assertAllClose(res_actual2, res_desired, rtol=1e-4)\n self.assertAllClose(res_actual3, res_desired, rtol=1e-4)\n\n\nclass TTMatrixTest(jtu.JaxTestCase):\n\n def testFull2d(self):\n np.random.seed(1)\n for rank in [1, 2]:\n a = np.random.rand(9, rank)\n b = np.random.rand(rank, 10)\n tt_cores = (a.reshape(1, 3, 3, rank), b.reshape(rank, 2, 5, 1))\n desired = np.einsum('aijb,bpqc->ipjq', *tt_cores)\n desired = desired.reshape(6, 15)\n tt_tens = TTMatrix(tt_cores)\n actual = ops.full(tt_tens)\n self.assertAllClose(desired, actual)\n\n def testFull2dBatch(self):\n np.random.seed(1)\n for rank in [1, 2]:\n a = np.random.rand(7, 9, rank)\n b = np.random.rand(7, rank, 10)\n tt_cores = (a.reshape(7, 1, 3, 3, rank), b.reshape(7, rank, 2, 5, 1))\n desired = np.einsum('taijb,tbpqc->tipjq', *tt_cores)\n desired = desired.reshape(7, 6, 15)\n tt_tens = TTMatrix(tt_cores)\n actual = ops.full(tt_tens)\n self.assertAllClose(desired, actual)\n\n def testMatmul(self):\n # Multiply two TT-matrices.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n left_shape = (2, 3, 4)\n sum_shape = (4, 3, 5)\n right_shape = (4, 4, 4)\n tt_a = random_.matrix(rng1, (left_shape, sum_shape), tt_rank=3, dtype=dtype)\n tt_b = random_.matrix(rng2, (sum_shape, right_shape), tt_rank=[1, 4, 3, 1],\n dtype=dtype)\n\n res_actual = ops.full(ops.matmul(tt_a, tt_b))\n res_desired = ops.full(tt_a) @ ops.full(tt_b)\n # TODO: why such low precision?\n self.assertAllClose(res_actual, res_desired, rtol=1e-3)\n\n def testMultiply(self):\n # Elementwise multiply two TT-matrices.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n left_shape = (2, 3, 4)\n right_shape = (4, 4, 4)\n tt_a = random_.matrix(rng1, (left_shape, right_shape), tt_rank=3,\n dtype=dtype)\n tt_b = random_.matrix(rng2, (left_shape, right_shape), tt_rank=[1, 4, 3, 1],\n dtype=dtype)\n\n res_actual1 = ops.full(ops.multiply(tt_a, tt_b))\n res_actual2 = ops.full(tt_a * tt_b)\n res_desired = ops.full(tt_a) * ops.full(tt_b)\n self.assertAllClose(res_actual1, res_desired, rtol=1e-4)\n self.assertAllClose(res_actual2, res_desired, rtol=1e-4)\n\n def testMultiplyBatch(self):\n # Elementwise multiply two batches of TT-matrices.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n left_shape = (2, 3, 4)\n right_shape = (4, 4, 4)\n tt_a = random_.matrix(rng1, (left_shape, right_shape), tt_rank=3,\n batch_shape=(3,), dtype=dtype)\n tt_b = random_.matrix(rng2, (left_shape, right_shape), tt_rank=[1, 4, 3, 1],\n batch_shape=(3,), dtype=dtype)\n\n res_actual1 = ops.full(ops.multiply(tt_a, tt_b))\n res_actual2 = ops.full(tt_a * tt_b)\n res_desired = ops.full(tt_a) * ops.full(tt_b)\n # TODO: why such low precision?\n self.assertAllClose(res_actual1, res_desired, rtol=1e-3)\n self.assertAllClose(res_actual2, res_desired, rtol=1e-3)\n\n def testFlatInner(self):\n # Multiply two TT-matrices.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n left_shape = (2, 3, 4)\n right_shape = (4, 4, 4)\n tt_a = random_.matrix(rng1, (left_shape, right_shape), tt_rank=3,\n dtype=dtype)\n tt_b = random_.matrix(rng2, (left_shape, right_shape), tt_rank=[1, 4, 3, 1],\n dtype=dtype)\n res_actual = ops.flat_inner(tt_a, tt_b)\n res_desired = jnp.sum(ops.full(tt_a) * ops.full(tt_b))\n self.assertAllClose(res_actual, res_desired)\n \n def testAdd(self):\n # Add two TT-matrices.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n left_shape = (2, 3, 4)\n right_shape = (4, 4, 4)\n tt_a = random_.matrix(rng1, (left_shape, right_shape), tt_rank=3,\n dtype=dtype)\n tt_b = random_.matrix(rng2, (left_shape, right_shape), tt_rank=[1, 4, 3, 1],\n dtype=dtype)\n\n res_actual1 = ops.full(ops.add(tt_a, tt_b))\n res_actual2 = ops.full(tt_a + tt_b)\n res_desired = ops.full(tt_a) + ops.full(tt_b)\n self.assertAllClose(res_actual1, res_desired, rtol=1e-5)\n self.assertAllClose(res_actual2, res_desired, rtol=1e-5)\n\n def testAddSameBatchSize(self):\n # Add two batches of TT-matrices.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n left_shape = (2, 3, 4)\n right_shape = (4, 4, 4)\n tt_a = random_.matrix(rng1, (left_shape, right_shape), tt_rank=3,\n batch_shape=(3,), dtype=dtype)\n tt_b = random_.matrix(rng2, (left_shape, right_shape), tt_rank=[1, 4, 3, 1],\n batch_shape=(3,), dtype=dtype)\n\n res_actual1 = ops.full(ops.add(tt_a, tt_b))\n res_actual2 = ops.full(tt_a + tt_b)\n res_desired = ops.full(tt_a) + ops.full(tt_b)\n self.assertAllClose(res_actual1, res_desired, rtol=1e-3)\n self.assertAllClose(res_actual2, res_desired, rtol=1e-3) \n \n def testAddBroadcasting(self):\n # Sum two TT-Matrices with broadcasting.\n rng1, rng2 = jax.random.split(jax.random.PRNGKey(0))\n dtype = jnp.float32\n left_shape = (2, 3, 4)\n right_shape = (4, 4, 4)\n tt_a = random_.matrix(rng1, (left_shape, right_shape), tt_rank=3,\n batch_shape=(3, 1, 3,), dtype=dtype)\n tt_b = random_.matrix(rng2, (left_shape, right_shape), tt_rank=[1, 4, 3, 1],\n batch_shape=(3, 3, 3), dtype=dtype)\n \n res_actual1 = ops.full(ops.add(tt_a, tt_b))\n res_actual2 = ops.full(tt_b + tt_a)\n res_desired = ops.full(tt_a) + ops.full(tt_b)\n self.assertAllClose(res_actual1, res_desired, rtol=1e-4)\n self.assertAllClose(res_actual2, res_desired, rtol=1e-4)\n\n def testMultiplyByScalar(self):\n # Multiply TT-matrix by scalar.\n c = 4.5\n rng = jax.random.PRNGKey(0)\n dtype = jnp.float32\n left_shape = (2, 3, 4)\n right_shape = (4, 4, 4)\n tt = random_.matrix(rng, (left_shape, right_shape), tt_rank=3,\n dtype=dtype)\n res_actual1 = ops.full(ops.multiply(tt, c))\n res_actual2 = ops.full(tt * c)\n res_actual3 = ops.full(c * tt)\n res_desired = c * ops.full(tt)\n self.assertAllClose(res_actual1, res_desired, rtol=1e-4) \n self.assertAllClose(res_actual2, res_desired, rtol=1e-4) \n self.assertAllClose(res_actual3, res_desired, rtol=1e-4)\n\n def testMultiplyBatchByScalar(self):\n # Multiply batch of TT-matrix by scalar.\n c = 4.5\n rng = jax.random.PRNGKey(0)\n dtype = jnp.float32\n left_shape = (2, 3, 4)\n right_shape = (4, 4, 4)\n tt = random_.matrix(rng, (left_shape, right_shape), tt_rank=3,\n batch_shape=(3, 1, 3,), dtype=dtype)\n res_actual1 = ops.full(ops.multiply(tt, c))\n res_actual2 = ops.full(tt * c)\n res_actual3 = ops.full(c * tt)\n res_desired = c * ops.full(tt)\n self.assertAllClose(res_actual1, res_desired, rtol=1e-3) \n self.assertAllClose(res_actual2, res_desired, rtol=1e-3) \n self.assertAllClose(res_actual3, res_desired, rtol=1e-3) \n\n def testNorm(self):\n rng = jax.random.PRNGKey(0)\n shape = (6, 6, 6, 6)\n tt = random_.tensor(rng, shape)\n self.assertAllClose(ops.norm(tt), ops.norm(tt, True))\n self.assertAllClose(ops.norm(tt), np.linalg.norm(ops.full(tt)))\n\nif __name__ == '__main__':\n absltest.main(testLoader=jtu.JaxTestLoader())\n"
] | [
[
"numpy.append",
"numpy.array",
"numpy.insert",
"numpy.ones"
],
[
"numpy.dot",
"numpy.einsum",
"numpy.random.rand",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mjseong0414/SPA_Radar_mmdet3d | [
"ae4eee101a5665b72586d3d5db06832bf45b3b33",
"ae4eee101a5665b72586d3d5db06832bf45b3b33",
"ae4eee101a5665b72586d3d5db06832bf45b3b33",
"ae4eee101a5665b72586d3d5db06832bf45b3b33"
] | [
"tools/test.py",
"mmdet3d/core/bbox/assigners/hungarian_assigner_3d.py",
"mmdet3d/core/points/base_points.py",
"nuscenes_radar_devkit/eval/detection/tests/test_algo.py"
] | [
"# Copyright (c) OpenMMLab. All rights reserved.\nimport argparse\nimport mmcv\nimport os\nimport torch\nimport warnings\nfrom mmcv import Config, DictAction\nfrom mmcv.cnn import fuse_conv_bn\nfrom mmcv.parallel import MMDataParallel, MMDistributedDataParallel\nfrom mmcv.runner import (get_dist_info, init_dist, load_checkpoint,\n wrap_fp16_model)\n\nfrom mmdet3d.apis import single_gpu_test\nfrom mmdet3d.datasets import build_dataloader, build_dataset\nfrom mmdet3d.models import build_model\nfrom mmdet.apis import multi_gpu_test, set_random_seed\nfrom mmdet.datasets import replace_ImageToTensor\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='MMDet test (and eval) a model')\n parser.add_argument('config', help='test config file path')\n parser.add_argument('checkpoint', help='checkpoint file')\n parser.add_argument('--out', help='output result file in pickle format')\n parser.add_argument(\n '--fuse-conv-bn',\n action='store_true',\n help='Whether to fuse conv and bn, this will slightly increase'\n 'the inference speed')\n parser.add_argument(\n '--format-only',\n action='store_true',\n help='Format the output results without perform evaluation. It is'\n 'useful when you want to format the result to a specific format and '\n 'submit it to the test server')\n parser.add_argument(\n '--eval',\n type=str,\n nargs='+',\n help='evaluation metrics, which depends on the dataset, e.g., \"bbox\",'\n ' \"segm\", \"proposal\" for COCO, and \"mAP\", \"recall\" for PASCAL VOC')\n parser.add_argument('--show', action='store_true', help='show results')\n parser.add_argument(\n '--show-dir', help='directory where results will be saved')\n parser.add_argument(\n '--gpu-collect',\n action='store_true',\n help='whether to use gpu to collect results.')\n parser.add_argument(\n '--tmpdir',\n help='tmp directory used for collecting results from multiple '\n 'workers, available when gpu-collect is not specified')\n parser.add_argument('--seed', type=int, default=0, help='random seed')\n parser.add_argument(\n '--deterministic',\n action='store_true',\n help='whether to set deterministic options for CUDNN backend.')\n parser.add_argument(\n '--cfg-options',\n nargs='+',\n action=DictAction,\n help='override some settings in the used config, the key-value pair '\n 'in xxx=yyy format will be merged into config file. If the value to '\n 'be overwritten is a list, it should be like key=\"[a,b]\" or key=a,b '\n 'It also allows nested list/tuple values, e.g. key=\"[(a,b),(c,d)]\" '\n 'Note that the quotation marks are necessary and that no white space '\n 'is allowed.')\n parser.add_argument(\n '--options',\n nargs='+',\n action=DictAction,\n help='custom options for evaluation, the key-value pair in xxx=yyy '\n 'format will be kwargs for dataset.evaluate() function (deprecate), '\n 'change to --eval-options instead.')\n parser.add_argument(\n '--eval-options',\n nargs='+',\n action=DictAction,\n help='custom options for evaluation, the key-value pair in xxx=yyy '\n 'format will be kwargs for dataset.evaluate() function')\n parser.add_argument(\n '--launcher',\n choices=['none', 'pytorch', 'slurm', 'mpi'],\n default='none',\n help='job launcher')\n parser.add_argument('--local_rank', type=int, default=0)\n parser.add_argument(\n '--use-radar-nusc',\n action='store_true',\n help='whether to use radar dataset. This args will use how to show eval results')\n args = parser.parse_args()\n if 'LOCAL_RANK' not in os.environ:\n os.environ['LOCAL_RANK'] = str(args.local_rank)\n\n if args.options and args.eval_options:\n raise ValueError(\n '--options and --eval-options cannot be both specified, '\n '--options is deprecated in favor of --eval-options')\n if args.options:\n warnings.warn('--options is deprecated in favor of --eval-options')\n args.eval_options = args.options\n return args\n\n\ndef main():\n args = parse_args()\n\n assert args.out or args.eval or args.format_only or args.show \\\n or args.show_dir, \\\n ('Please specify at least one operation (save/eval/format/show the '\n 'results / save the results) with the argument \"--out\", \"--eval\"'\n ', \"--format-only\", \"--show\" or \"--show-dir\"')\n\n if args.eval and args.format_only:\n raise ValueError('--eval and --format_only cannot be both specified')\n\n if args.out is not None and not args.out.endswith(('.pkl', '.pickle')):\n raise ValueError('The output file must be a pkl file.')\n\n cfg = Config.fromfile(args.config)\n if args.cfg_options is not None:\n cfg.merge_from_dict(args.cfg_options)\n # import modules from string list.\n if cfg.get('custom_imports', None):\n from mmcv.utils import import_modules_from_strings\n import_modules_from_strings(**cfg['custom_imports'])\n # set cudnn_benchmark\n if cfg.get('cudnn_benchmark', False):\n torch.backends.cudnn.benchmark = True\n\n cfg.model.pretrained = None\n # in case the test dataset is concatenated\n samples_per_gpu = 1\n if isinstance(cfg.data.test, dict):\n cfg.data.test.test_mode = True\n samples_per_gpu = cfg.data.test.pop('samples_per_gpu', 1)\n if samples_per_gpu > 1:\n # Replace 'ImageToTensor' to 'DefaultFormatBundle'\n cfg.data.test.pipeline = replace_ImageToTensor(\n cfg.data.test.pipeline)\n elif isinstance(cfg.data.test, list):\n for ds_cfg in cfg.data.test:\n ds_cfg.test_mode = True\n samples_per_gpu = max(\n [ds_cfg.pop('samples_per_gpu', 1) for ds_cfg in cfg.data.test])\n if samples_per_gpu > 1:\n for ds_cfg in cfg.data.test:\n ds_cfg.pipeline = replace_ImageToTensor(ds_cfg.pipeline)\n\n # init distributed env first, since logger depends on the dist info.\n if args.launcher == 'none':\n distributed = False\n else:\n distributed = True\n init_dist(args.launcher, **cfg.dist_params)\n\n # set random seeds\n if args.seed is not None:\n set_random_seed(args.seed, deterministic=args.deterministic)\n\n # build the dataloader\n dataset = build_dataset(cfg.data.test)\n data_loader = build_dataloader(\n dataset,\n samples_per_gpu=samples_per_gpu,\n workers_per_gpu=cfg.data.workers_per_gpu,\n dist=distributed,\n shuffle=False)\n\n # build the model and load checkpoint\n cfg.model.train_cfg = None\n model = build_model(cfg.model, test_cfg=cfg.get('test_cfg'))\n fp16_cfg = cfg.get('fp16', None)\n if fp16_cfg is not None:\n wrap_fp16_model(model)\n checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')\n if args.fuse_conv_bn:\n model = fuse_conv_bn(model)\n # old versions did not save class info in checkpoints, this walkaround is\n # for backward compatibility\n if 'CLASSES' in checkpoint.get('meta', {}):\n model.CLASSES = checkpoint['meta']['CLASSES']\n else:\n model.CLASSES = dataset.CLASSES\n # palette for visualization in segmentation tasks\n if 'PALETTE' in checkpoint.get('meta', {}):\n model.PALETTE = checkpoint['meta']['PALETTE']\n elif hasattr(dataset, 'PALETTE'):\n # segmentation dataset has `PALETTE` attribute\n model.PALETTE = dataset.PALETTE\n if not distributed:\n model = MMDataParallel(model, device_ids=[0])\n outputs = single_gpu_test(model, data_loader, args.show, args.show_dir)\n else:\n model = MMDistributedDataParallel(\n model.cuda(),\n device_ids=[torch.cuda.current_device()],\n broadcast_buffers=False)\n outputs = multi_gpu_test(model, data_loader, args.tmpdir,\n args.gpu_collect)\n\n rank, _ = get_dist_info()\n if rank == 0:\n if args.out:\n print(f'\\nwriting results to {args.out}')\n mmcv.dump(outputs, args.out)\n kwargs = {} if args.eval_options is None else args.eval_options\n if args.format_only:\n dataset.format_results(outputs, **kwargs)\n if args.eval:\n eval_kwargs = cfg.get('evaluation', {}).copy()\n # hard-code way to remove EvalHook args\n for key in [\n 'interval', 'tmpdir', 'start', 'gpu_collect', 'save_best',\n 'rule'\n ]:\n eval_kwargs.pop(key, None)\n eval_kwargs.update(dict(metric=args.eval, **kwargs))\n if not args.use_radar_nusc:\n print(dataset.evaluate(outputs, **eval_kwargs)) # 기존 코드\n else:\n dataset.evaluate(outputs, **eval_kwargs)\n \n\n \n\n\n\nif __name__ == '__main__':\n main()\n",
"import torch\n\nfrom mmdet.core.bbox.builder import BBOX_ASSIGNERS\nfrom mmdet.core.bbox.assigners import AssignResult\nfrom mmdet.core.bbox.assigners import BaseAssigner\nfrom mmdet.core.bbox.match_costs import build_match_cost\nfrom mmdet.models.utils.transformer import inverse_sigmoid\nfrom mmdet3d.core.bbox.util import normalize_bbox\n\ntry:\n from scipy.optimize import linear_sum_assignment\nexcept ImportError:\n linear_sum_assignment = None\n\n\n@BBOX_ASSIGNERS.register_module()\nclass HungarianAssigner3D(BaseAssigner):\n \"\"\"Computes one-to-one matching between predictions and ground truth.\n This class computes an assignment between the targets and the predictions\n based on the costs. The costs are weighted sum of three components:\n classification cost, regression L1 cost and regression iou cost. The\n targets don't include the no_object, so generally there are more\n predictions than targets. After the one-to-one matching, the un-matched\n are treated as backgrounds. Thus each query prediction will be assigned\n with `0` or a positive integer indicating the ground truth index:\n - 0: negative sample, no assigned gt\n - positive integer: positive sample, index (1-based) of assigned gt\n Args:\n cls_weight (int | float, optional): The scale factor for classification\n cost. Default 1.0.\n bbox_weight (int | float, optional): The scale factor for regression\n L1 cost. Default 1.0.\n iou_weight (int | float, optional): The scale factor for regression\n iou cost. Default 1.0.\n iou_calculator (dict | optional): The config for the iou calculation.\n Default type `BboxOverlaps2D`.\n iou_mode (str | optional): \"iou\" (intersection over union), \"iof\"\n (intersection over foreground), or \"giou\" (generalized\n intersection over union). Default \"giou\".\n \"\"\"\n\n def __init__(self,\n cls_cost=dict(type='ClassificationCost', weight=1.),\n reg_cost=dict(type='BBoxL1Cost', weight=1.0),\n iou_cost=dict(type='IoUCost', weight=0.0),\n pc_range=None):\n self.cls_cost = build_match_cost(cls_cost)\n self.reg_cost = build_match_cost(reg_cost)\n self.iou_cost = build_match_cost(iou_cost)\n self.pc_range = pc_range\n\n def assign(self,\n bbox_pred,\n cls_pred,\n gt_bboxes, \n gt_labels,\n gt_bboxes_ignore=None,\n eps=1e-7):\n \"\"\"Computes one-to-one matching based on the weighted costs.\n This method assign each query prediction to a ground truth or\n background. The `assigned_gt_inds` with -1 means don't care,\n 0 means negative sample, and positive number is the index (1-based)\n of assigned gt.\n The assignment is done in the following steps, the order matters.\n 1. assign every prediction to -1\n 2. compute the weighted costs\n 3. do Hungarian matching on CPU based on the costs\n 4. assign all to 0 (background) first, then for each matched pair\n between predictions and gts, treat this prediction as foreground\n and assign the corresponding gt index (plus 1) to it.\n Args:\n bbox_pred (Tensor): Predicted boxes with normalized coordinates\n (cx, cy, w, h), which are all in range [0, 1]. Shape\n [num_query, 4].\n cls_pred (Tensor): Predicted classification logits, shape\n [num_query, num_class].\n gt_bboxes (Tensor): Ground truth boxes with unnormalized\n coordinates (x1, y1, x2, y2). Shape [num_gt, 4].\n gt_labels (Tensor): Label of `gt_bboxes`, shape (num_gt,).\n gt_bboxes_ignore (Tensor, optional): Ground truth bboxes that are\n labelled as `ignored`. Default None.\n eps (int | float, optional): A value added to the denominator for\n numerical stability. Default 1e-7.\n Returns:\n :obj:`AssignResult`: The assigned result.\n \"\"\"\n assert gt_bboxes_ignore is None, \\\n 'Only case when gt_bboxes_ignore is None is supported.'\n num_gts, num_bboxes = gt_bboxes.size(0), bbox_pred.size(0)\n\n # 1. assign -1 by default\n assigned_gt_inds = bbox_pred.new_full((num_bboxes, ),\n -1,\n dtype=torch.long)\n assigned_labels = bbox_pred.new_full((num_bboxes, ),\n -1,\n dtype=torch.long)\n if num_gts == 0 or num_bboxes == 0:\n # No ground truth or boxes, return empty assignment\n if num_gts == 0:\n # No ground truth, assign all to background\n assigned_gt_inds[:] = 0\n return AssignResult(\n num_gts, assigned_gt_inds, None, labels=assigned_labels)\n\n # 2. compute the weighted costs\n # classification and bboxcost.\n cls_cost = self.cls_cost(cls_pred, gt_labels)\n # regression L1 cost\n normalized_gt_bboxes = normalize_bbox(gt_bboxes, self.pc_range)\n reg_cost = self.reg_cost(bbox_pred[:, :8], normalized_gt_bboxes[:, :8])\n \n # weighted sum of above two costs\n cost = cls_cost + reg_cost\n \n # 3. do Hungarian matching on CPU using linear_sum_assignment\n cost = cost.detach().cpu()\n if linear_sum_assignment is None:\n raise ImportError('Please run \"pip install scipy\" '\n 'to install scipy first.')\n matched_row_inds, matched_col_inds = linear_sum_assignment(cost)\n matched_row_inds = torch.from_numpy(matched_row_inds).to(\n bbox_pred.device)\n matched_col_inds = torch.from_numpy(matched_col_inds).to(\n bbox_pred.device)\n\n # 4. assign backgrounds and foregrounds\n # assign all indices to backgrounds first\n assigned_gt_inds[:] = 0\n # assign foregrounds based on matching results\n assigned_gt_inds[matched_row_inds] = matched_col_inds + 1\n assigned_labels[matched_row_inds] = gt_labels[matched_col_inds]\n return AssignResult(\n num_gts, assigned_gt_inds, None, labels=assigned_labels)",
"# Copyright (c) OpenMMLab. All rights reserved.\nimport numpy as np\nimport torch\nimport warnings\nfrom abc import abstractmethod\n\n\nclass BasePoints(object):\n \"\"\"Base class for Points.\n\n Args:\n tensor (torch.Tensor | np.ndarray | list): a N x points_dim matrix.\n points_dim (int): Number of the dimension of a point.\n Each row is (x, y, z). Default to 3.\n attribute_dims (dict): Dictionary to indicate the meaning of extra\n dimension. Default to None.\n\n Attributes:\n tensor (torch.Tensor): Float matrix of N x points_dim. tensor is point clouds\n points_dim (int): Integer indicating the dimension of a point.\n Each row is (x, y, z, ...).\n attribute_dims (bool): Dictionary to indicate the meaning of extra\n dimension. Default to None.\n rotation_axis (int): Default rotation axis for points rotation.\n \"\"\"\n\n def __init__(self, tensor, points_dim=3, attribute_dims=None):\n if isinstance(tensor, torch.Tensor):\n device = tensor.device\n else:\n device = torch.device('cpu')\n tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device)\n if tensor.numel() == 0:\n # Use reshape, so we don't end up creating a new tensor that\n # does not depend on the inputs (and consequently confuses jit)\n tensor = tensor.reshape((0, points_dim)).to(\n dtype=torch.float32, device=device)\n assert tensor.dim() == 2 and tensor.size(-1) == \\\n points_dim, tensor.size()\n\n self.tensor = tensor\n self.points_dim = points_dim\n self.attribute_dims = attribute_dims\n self.rotation_axis = 0\n\n @property\n def coord(self):\n \"\"\"torch.Tensor: Coordinates of each point with size (N, 3).\"\"\"\n return self.tensor[:, :3]\n\n @coord.setter\n def coord(self, tensor):\n \"\"\"Set the coordinates of each point.\"\"\"\n try:\n tensor = tensor.reshape(self.shape[0], 3)\n except (RuntimeError, ValueError): # for torch.Tensor and np.ndarray\n raise ValueError(f'got unexpected shape {tensor.shape}')\n if not isinstance(tensor, torch.Tensor):\n tensor = self.tensor.new_tensor(tensor)\n self.tensor[:, :3] = tensor\n\n @property\n def height(self):\n \"\"\"torch.Tensor: A vector with height of each point.\"\"\"\n if self.attribute_dims is not None and \\\n 'height' in self.attribute_dims.keys():\n return self.tensor[:, self.attribute_dims['height']]\n else:\n return None\n\n @height.setter\n def height(self, tensor):\n \"\"\"Set the height of each point.\"\"\"\n try:\n tensor = tensor.reshape(self.shape[0])\n except (RuntimeError, ValueError): # for torch.Tensor and np.ndarray\n raise ValueError(f'got unexpected shape {tensor.shape}')\n if not isinstance(tensor, torch.Tensor):\n tensor = self.tensor.new_tensor(tensor)\n if self.attribute_dims is not None and \\\n 'height' in self.attribute_dims.keys():\n self.tensor[:, self.attribute_dims['height']] = tensor\n else:\n # add height attribute\n if self.attribute_dims is None:\n self.attribute_dims = dict()\n attr_dim = self.shape[1]\n self.tensor = torch.cat([self.tensor, tensor.unsqueeze(1)], dim=1)\n self.attribute_dims.update(dict(height=attr_dim))\n self.points_dim += 1\n\n @property\n def color(self):\n \"\"\"torch.Tensor: A vector with color of each point.\"\"\"\n if self.attribute_dims is not None and \\\n 'color' in self.attribute_dims.keys():\n return self.tensor[:, self.attribute_dims['color']]\n else:\n return None\n\n @color.setter\n def color(self, tensor):\n \"\"\"Set the color of each point.\"\"\"\n try:\n tensor = tensor.reshape(self.shape[0], 3)\n except (RuntimeError, ValueError): # for torch.Tensor and np.ndarray\n raise ValueError(f'got unexpected shape {tensor.shape}')\n if tensor.max() >= 256 or tensor.min() < 0:\n warnings.warn('point got color value beyond [0, 255]')\n if not isinstance(tensor, torch.Tensor):\n tensor = self.tensor.new_tensor(tensor)\n if self.attribute_dims is not None and \\\n 'color' in self.attribute_dims.keys():\n self.tensor[:, self.attribute_dims['color']] = tensor\n else:\n # add color attribute\n if self.attribute_dims is None:\n self.attribute_dims = dict()\n attr_dim = self.shape[1]\n self.tensor = torch.cat([self.tensor, tensor], dim=1)\n self.attribute_dims.update(\n dict(color=[attr_dim, attr_dim + 1, attr_dim + 2]))\n self.points_dim += 3\n\n @property\n def shape(self):\n \"\"\"torch.Shape: Shape of points.\"\"\"\n return self.tensor.shape\n\n def shuffle(self):\n \"\"\"Shuffle the points.\n\n Returns:\n torch.Tensor: The shuffled index.\n \"\"\"\n idx = torch.randperm(self.__len__(), device=self.tensor.device)\n self.tensor = self.tensor[idx]\n return idx\n\n def rotate(self, rotation, axis=None):\n \"\"\"Rotate points with the given rotation matrix or angle.\n\n Args:\n rotation (float, np.ndarray, torch.Tensor): Rotation matrix\n or angle.\n axis (int): Axis to rotate at. Defaults to None.\n \"\"\"\n if not isinstance(rotation, torch.Tensor):\n rotation = self.tensor.new_tensor(rotation)\n assert rotation.shape == torch.Size([3, 3]) or \\\n rotation.numel() == 1, f'invalid rotation shape {rotation.shape}'\n\n if axis is None:\n axis = self.rotation_axis\n\n if rotation.numel() == 1:\n rot_sin = torch.sin(rotation)\n rot_cos = torch.cos(rotation)\n if axis == 1:\n rot_mat_T = rotation.new_tensor([[rot_cos, 0, -rot_sin],\n [0, 1, 0],\n [rot_sin, 0, rot_cos]])\n elif axis == 2 or axis == -1:\n rot_mat_T = rotation.new_tensor([[rot_cos, -rot_sin, 0],\n [rot_sin, rot_cos, 0],\n [0, 0, 1]])\n elif axis == 0:\n rot_mat_T = rotation.new_tensor([[0, rot_cos, -rot_sin],\n [0, rot_sin, rot_cos],\n [1, 0, 0]])\n else:\n raise ValueError('axis should in range')\n rot_mat_T = rot_mat_T.T\n elif rotation.numel() == 9:\n rot_mat_T = rotation\n else:\n raise NotImplementedError\n self.tensor[:, :3] = self.tensor[:, :3] @ rot_mat_T\n\n return rot_mat_T\n\n @abstractmethod\n def flip(self, bev_direction='horizontal'):\n \"\"\"Flip the points in BEV along given BEV direction.\"\"\"\n pass\n\n def translate(self, trans_vector):\n \"\"\"Translate points with the given translation vector.\n\n Args:\n trans_vector (np.ndarray, torch.Tensor): Translation\n vector of size 3 or nx3.\n \"\"\"\n if not isinstance(trans_vector, torch.Tensor):\n trans_vector = self.tensor.new_tensor(trans_vector)\n trans_vector = trans_vector.squeeze(0)\n if trans_vector.dim() == 1:\n assert trans_vector.shape[0] == 3\n elif trans_vector.dim() == 2:\n assert trans_vector.shape[0] == self.tensor.shape[0] and \\\n trans_vector.shape[1] == 3\n else:\n raise NotImplementedError(\n f'Unsupported translation vector of shape {trans_vector.shape}'\n )\n self.tensor[:, :3] += trans_vector\n\n def in_range_3d(self, point_range):\n \"\"\"Check whether the points are in the given range.\n\n Args:\n point_range (list | torch.Tensor): The range of point\n (x_min, y_min, z_min, x_max, y_max, z_max)\n\n Note:\n In the original implementation of SECOND, checking whether\n a box in the range checks whether the points are in a convex\n polygon, we try to reduce the burden for simpler cases.\n\n Returns:\n torch.Tensor: A binary vector indicating whether each point is \\\n inside the reference range.\n \"\"\"\n in_range_flags = ((self.tensor[:, 0] > point_range[0])\n & (self.tensor[:, 1] > point_range[1])\n & (self.tensor[:, 2] > point_range[2])\n & (self.tensor[:, 0] < point_range[3])\n & (self.tensor[:, 1] < point_range[4])\n & (self.tensor[:, 2] < point_range[5]))\n return in_range_flags\n\n @abstractmethod\n def in_range_bev(self, point_range):\n \"\"\"Check whether the points are in the given range.\n\n Args:\n point_range (list | torch.Tensor): The range of point\n in order of (x_min, y_min, x_max, y_max).\n\n Returns:\n torch.Tensor: Indicating whether each point is inside \\\n the reference range.\n \"\"\"\n pass\n\n @abstractmethod\n def convert_to(self, dst, rt_mat=None):\n \"\"\"Convert self to ``dst`` mode.\n\n Args:\n dst (:obj:`CoordMode`): The target Box mode.\n rt_mat (np.ndarray | torch.Tensor): The rotation and translation\n matrix between different coordinates. Defaults to None.\n The conversion from `src` coordinates to `dst` coordinates\n usually comes along the change of sensors, e.g., from camera\n to LiDAR. This requires a transformation matrix.\n\n Returns:\n :obj:`BasePoints`: The converted box of the same type \\\n in the `dst` mode.\n \"\"\"\n pass\n\n def scale(self, scale_factor):\n \"\"\"Scale the points with horizontal and vertical scaling factors.\n\n Args:\n scale_factors (float): Scale factors to scale the points.\n \"\"\"\n self.tensor[:, :3] *= scale_factor\n\n def __getitem__(self, item):\n \"\"\"\n Note:\n The following usage are allowed:\n 1. `new_points = points[3]`:\n return a `Points` that contains only one point.\n 2. `new_points = points[2:10]`:\n return a slice of points.\n 3. `new_points = points[vector]`:\n where vector is a torch.BoolTensor with `length = len(points)`.\n Nonzero elements in the vector will be selected.\n 4. `new_points = points[3:11, vector]`:\n return a slice of points and attribute dims.\n 5. `new_points = points[4:12, 2]`:\n return a slice of points with single attribute.\n Note that the returned Points might share storage with this Points,\n subject to Pytorch's indexing semantics.\n\n Returns:\n :obj:`BasePoints`: A new object of \\\n :class:`BasePoints` after indexing.\n \"\"\"\n original_type = type(self)\n if isinstance(item, int):\n return original_type(\n self.tensor[item].view(1, -1),\n points_dim=self.points_dim,\n attribute_dims=self.attribute_dims)\n elif isinstance(item, tuple) and len(item) == 2:\n if isinstance(item[1], slice):\n start = 0 if item[1].start is None else item[1].start\n stop = self.tensor.shape[1] if \\\n item[1].stop is None else item[1].stop\n step = 1 if item[1].step is None else item[1].step\n item = list(item)\n item[1] = list(range(start, stop, step))\n item = tuple(item)\n elif isinstance(item[1], int):\n item = list(item)\n item[1] = [item[1]]\n item = tuple(item)\n p = self.tensor[item[0], item[1]]\n\n keep_dims = list(\n set(item[1]).intersection(set(range(3, self.tensor.shape[1]))))\n if self.attribute_dims is not None:\n attribute_dims = self.attribute_dims.copy()\n for key in self.attribute_dims.keys():\n cur_attribute_dims = attribute_dims[key]\n if isinstance(cur_attribute_dims, int):\n cur_attribute_dims = [cur_attribute_dims]\n intersect_attr = list(\n set(cur_attribute_dims).intersection(set(keep_dims)))\n if len(intersect_attr) == 1:\n attribute_dims[key] = intersect_attr[0]\n elif len(intersect_attr) > 1:\n attribute_dims[key] = intersect_attr\n else:\n attribute_dims.pop(key)\n else:\n attribute_dims = None\n elif isinstance(item, (slice, np.ndarray, torch.Tensor)):\n p = self.tensor[item]\n attribute_dims = self.attribute_dims\n else:\n raise NotImplementedError(f'Invalid slice {item}!')\n\n assert p.dim() == 2, \\\n f'Indexing on Points with {item} failed to return a matrix!'\n return original_type(\n p, points_dim=p.shape[1], attribute_dims=attribute_dims)\n\n def __len__(self):\n \"\"\"int: Number of points in the current object.\"\"\"\n return self.tensor.shape[0]\n\n def __repr__(self):\n \"\"\"str: Return a strings that describes the object.\"\"\"\n return self.__class__.__name__ + '(\\n ' + str(self.tensor) + ')'\n\n @classmethod\n def cat(cls, points_list):\n \"\"\"Concatenate a list of Points into a single Points.\n\n Args:\n points_list (list[:obj:`BasePoints`]): List of points.\n\n Returns:\n :obj:`BasePoints`: The concatenated Points.\n \"\"\"\n assert isinstance(points_list, (list, tuple))\n if len(points_list) == 0:\n return cls(torch.empty(0))\n assert all(isinstance(points, cls) for points in points_list)\n\n # use torch.cat (v.s. layers.cat)\n # so the returned points never share storage with input\n cat_points = cls(\n torch.cat([p.tensor for p in points_list], dim=0),\n points_dim=points_list[0].tensor.shape[1],\n attribute_dims=points_list[0].attribute_dims)\n return cat_points\n\n def to(self, device):\n \"\"\"Convert current points to a specific device.\n\n Args:\n device (str | :obj:`torch.device`): The name of the device.\n\n Returns:\n :obj:`BasePoints`: A new boxes object on the \\\n specific device.\n \"\"\"\n original_type = type(self)\n return original_type(\n self.tensor.to(device),\n points_dim=self.points_dim,\n attribute_dims=self.attribute_dims)\n\n def clone(self):\n \"\"\"Clone the Points.\n\n Returns:\n :obj:`BasePoints`: Box object with the same properties \\\n as self.\n \"\"\"\n original_type = type(self)\n return original_type(\n self.tensor.clone(),\n points_dim=self.points_dim,\n attribute_dims=self.attribute_dims)\n\n @property\n def device(self):\n \"\"\"str: The device of the points are on.\"\"\"\n return self.tensor.device\n\n def __iter__(self):\n \"\"\"Yield a point as a Tensor of shape (4,) at a time.\n\n Returns:\n torch.Tensor: A point of shape (4,).\n \"\"\"\n yield from self.tensor\n\n def new_point(self, data):\n \"\"\"Create a new point object with data.\n\n The new point and its tensor has the similar properties \\\n as self and self.tensor, respectively.\n\n Args:\n data (torch.Tensor | numpy.array | list): Data to be copied.\n\n Returns:\n :obj:`BasePoints`: A new point object with ``data``, \\\n the object's other properties are similar to ``self``.\n \"\"\"\n new_tensor = self.tensor.new_tensor(data) \\\n if not isinstance(data, torch.Tensor) else data.to(self.device)\n original_type = type(self)\n return original_type(\n new_tensor,\n points_dim=self.points_dim,\n attribute_dims=self.attribute_dims)\n",
"# nuScenes dev-kit.\n# Code written by Oscar Beijbom and Varun Bankiti, 2019.\n\nimport random\nimport unittest\nfrom typing import Dict, List\n\nimport numpy as np\nfrom pyquaternion import Quaternion\n\nfrom nuscenes_radar_devkit.eval.common.config import config_factory\nfrom nuscenes_radar_devkit.eval.common.data_classes import EvalBoxes\nfrom nuscenes_radar_devkit.eval.common.utils import center_distance\nfrom nuscenes_radar_devkit.eval.detection.algo import accumulate, calc_ap, calc_tp\nfrom nuscenes_radar_devkit.eval.detection.constants import TP_METRICS\nfrom nuscenes_radar_devkit.eval.detection.data_classes import DetectionMetrics, DetectionMetricData, DetectionBox, \\\n DetectionMetricDataList\nfrom nuscenes_radar_devkit.eval.detection.utils import detection_name_to_rel_attributes\n\n\nclass TestAlgo(unittest.TestCase):\n\n cfg = config_factory('detection_cvpr_2019')\n\n @staticmethod\n def _mock_results(nsamples, ngt, npred, detection_name):\n\n def random_attr():\n \"\"\"\n This is the most straight-forward way to generate a random attribute.\n Not currently used b/c we want the test fixture to be back-wards compatible.\n \"\"\"\n # Get relevant attributes.\n rel_attributes = detection_name_to_rel_attributes(detection_name)\n\n if len(rel_attributes) == 0:\n # Empty string for classes without attributes.\n return ''\n else:\n # Pick a random attribute otherwise.\n return rel_attributes[np.random.randint(0, len(rel_attributes))]\n\n pred = EvalBoxes()\n gt = EvalBoxes()\n\n for sample_itt in range(nsamples):\n\n this_gt = []\n\n for box_itt in range(ngt):\n translation_xy = tuple(np.random.rand(2) * 15)\n this_gt.append(DetectionBox(\n sample_token=str(sample_itt),\n translation=(translation_xy[0], translation_xy[1], 0.0),\n size=tuple(np.random.rand(3)*4),\n rotation=tuple(np.random.rand(4)),\n velocity=tuple(np.random.rand(3)[:2]*4),\n detection_name=detection_name,\n detection_score=random.random(),\n attribute_name=random_attr(),\n ego_translation=(random.random() * 10, 0, 0),\n ))\n gt.add_boxes(str(sample_itt), this_gt)\n\n for sample_itt in range(nsamples):\n this_pred = []\n\n for box_itt in range(npred):\n translation_xy = tuple(np.random.rand(2) * 10)\n this_pred.append(DetectionBox(\n sample_token=str(sample_itt),\n translation=(translation_xy[0], translation_xy[1], 0.0),\n size=tuple(np.random.rand(3) * 4),\n rotation=tuple(np.random.rand(4)),\n velocity=tuple(np.random.rand(3)[:2] * 4),\n detection_name=detection_name,\n detection_score=random.random(),\n attribute_name=random_attr(),\n ego_translation=(random.random() * 10, 0, 0),\n ))\n\n pred.add_boxes(str(sample_itt), this_pred)\n\n return gt, pred\n\n def test_nd_score(self):\n \"\"\"\n This tests runs the full evaluation for an arbitrary random set of predictions.\n \"\"\"\n\n random.seed(42)\n np.random.seed(42)\n\n mdl = DetectionMetricDataList()\n for class_name in self.cfg.class_names:\n gt, pred = self._mock_results(30, 3, 25, class_name)\n for dist_th in self.cfg.dist_ths:\n mdl.set(class_name, dist_th, accumulate(gt, pred, class_name, center_distance, 2))\n\n metrics = DetectionMetrics(self.cfg)\n for class_name in self.cfg.class_names:\n for dist_th in self.cfg.dist_ths:\n ap = calc_ap(mdl[(class_name, dist_th)], self.cfg.min_recall, self.cfg.min_precision)\n metrics.add_label_ap(class_name, dist_th, ap)\n\n for metric_name in TP_METRICS:\n metric_data = mdl[(class_name, self.cfg.dist_th_tp)]\n if class_name in ['traffic_cone'] and metric_name in ['attr_err', 'vel_err', 'orient_err']:\n tp = np.nan\n elif class_name in ['barrier'] and metric_name in ['attr_err', 'vel_err']:\n tp = np.nan\n else:\n tp = calc_tp(metric_data, self.cfg.min_recall, metric_name)\n metrics.add_label_tp(class_name, metric_name, tp)\n\n self.assertEqual(0.08606662159639042, metrics.nd_score)\n\n def test_calc_tp(self):\n \"\"\"Test for calc_tp().\"\"\"\n\n random.seed(42)\n np.random.seed(42)\n\n md = DetectionMetricData.random_md()\n\n # min_recall greater than 1.\n self.assertEqual(1.0, calc_tp(md, min_recall=1, metric_name='trans_err'))\n\n def test_calc_ap(self):\n \"\"\"Test for calc_ap().\"\"\"\n\n random.seed(42)\n np.random.seed(42)\n\n md = DetectionMetricData.random_md()\n\n # Negative min_recall and min_precision\n self.assertRaises(AssertionError, calc_ap, md, -0.5, 0.4)\n self.assertRaises(AssertionError, calc_ap, md, 0.5, -0.8)\n\n # More than 1 min_precision/min_recall\n self.assertRaises(AssertionError, calc_ap, md, 0.7, 1)\n self.assertRaises(AssertionError, calc_ap, md, 1.2, 0)\n\n\ndef get_metric_data(gts: Dict[str, List[Dict]],\n preds: Dict[str, List[Dict]],\n detection_name: str,\n dist_th: float) -> DetectionMetricData:\n \"\"\"\n Calculate and check the AP value.\n :param gts: Ground truth data.\n :param preds: Predictions.\n :param detection_name: Name of the class we are interested in.\n :param dist_th: Distance threshold for matching.\n \"\"\"\n\n # Some or all of the defaults will be replaced by if given.\n defaults = {'trans': (0, 0, 0), 'size': (1, 1, 1), 'rot': (0, 0, 0, 0),\n 'vel': (0, 0), 'attr': 'vehicle.parked', 'score': -1.0, 'name': 'car'}\n # Create GT EvalBoxes instance.\n gt_eval_boxes = EvalBoxes()\n for sample_token, data in gts.items():\n gt_boxes = []\n for gt in data:\n gt = {**defaults, **gt} # The defaults will be replaced by gt if given.\n eb = DetectionBox(sample_token=sample_token, translation=gt['trans'], size=gt['size'],\n rotation=gt['rot'], detection_name=gt['name'], attribute_name=gt['attr'],\n velocity=gt['vel'])\n gt_boxes.append(eb)\n\n gt_eval_boxes.add_boxes(sample_token, gt_boxes)\n\n # Create Predictions EvalBoxes instance.\n pred_eval_boxes = EvalBoxes()\n for sample_token, data in preds.items():\n pred_boxes = []\n for pred in data:\n pred = {**defaults, **pred}\n eb = DetectionBox(sample_token=sample_token, translation=pred['trans'], size=pred['size'],\n rotation=pred['rot'], detection_name=pred['name'], detection_score=pred['score'],\n velocity=pred['vel'], attribute_name=pred['attr'])\n pred_boxes.append(eb)\n pred_eval_boxes.add_boxes(sample_token, pred_boxes)\n\n metric_data = accumulate(gt_eval_boxes, pred_eval_boxes, class_name=detection_name,\n dist_fcn=center_distance, dist_th=dist_th)\n\n return metric_data\n\n\nclass TestAPSimple(unittest.TestCase):\n \"\"\" Tests the correctness of AP calculation for simple cases. \"\"\"\n\n def setUp(self):\n self.car1 = {'trans': (1, 1, 1), 'name': 'car', 'score': 1.0, }\n self.car2 = {'trans': (3, 3, 1), 'name': 'car', 'score': 0.7}\n self.bicycle1 = {'trans': (5, 5, 1), 'name': 'bicycle', 'score': 1.0}\n self.bicycle2 = {'trans': (7, 7, 1), 'name': 'bicycle', 'score': 0.7}\n\n def check_ap(self, gts: Dict[str, List[Dict]],\n preds: Dict[str, List[Dict]],\n target_ap: float,\n detection_name: str = 'car',\n dist_th: float = 2.0,\n min_precision: float = 0.1,\n min_recall: float = 0.1) -> None:\n \"\"\"\n Calculate and check the AP value.\n :param gts: Ground truth data.\n :param preds: Predictions.\n :param target_ap: Expected Average Precision value.\n :param detection_name: Name of the class we are interested in.\n :param dist_th: Distance threshold for matching.\n :param min_precision: Minimum precision value.\n :param min_recall: Minimum recall value.\n \"\"\"\n metric_data = get_metric_data(gts, preds, detection_name, dist_th)\n ap = calc_ap(metric_data, min_precision=min_precision, min_recall=min_recall)\n\n # We quantize the curve into 100 bins to calculate integral so the AP is accurate up to 1%.\n self.assertGreaterEqual(0.01, abs(ap - target_ap), msg='Incorrect AP')\n\n def test_no_data(self):\n \"\"\" Test empty ground truth and/or predictions. \"\"\"\n\n gts = {'sample1': [self.car1]}\n preds = {'sample1': [self.car1]}\n empty = {'sample1': []}\n\n # No ground truth objects (all False positives)\n self.check_ap(empty, preds, target_ap=0.0)\n\n # No predictions (all False negatives)\n self.check_ap(gts, empty, target_ap=0.0)\n\n # No predictions and no ground truth objects.\n self.check_ap(empty, empty, target_ap=0.0)\n\n def test_one_sample(self):\n \"\"\" Test the single sample case. \"\"\"\n # Perfect detection.\n self.check_ap({'sample1': [self.car1]},\n {'sample1': [self.car1]},\n target_ap=1.0, detection_name='car')\n\n # Detect one of the two objects\n self.check_ap({'sample1': [self.car1, self.car2]},\n {'sample1': [self.car1]},\n target_ap=0.4/0.9, detection_name='car')\n\n # One detection and one FP. FP score is less than TP score.\n self.check_ap({'sample1': [self.car1]},\n {'sample1': [self.car1, self.car2]},\n target_ap=1.0, detection_name='car')\n\n # One detection and one FP. FP score is more than TP score.\n self.check_ap({'sample1': [self.car2]},\n {'sample1': [self.car1, self.car2]},\n target_ap=((0.8*0.4)/2)/(0.9*0.9), detection_name='car')\n\n # FP but different class.\n self.check_ap({'sample1': [self.car1]},\n {'sample1': [self.car1, self.bicycle1]},\n target_ap=1.0, detection_name='car')\n\n def test_two_samples(self):\n \"\"\" Test more than one sample case. \"\"\"\n # Objects in both samples are detected.\n self.check_ap({'sample1': [self.car1], 'sample2': [self.car2]},\n {'sample1': [self.car1], 'sample2': [self.car2]},\n target_ap=1.0, detection_name='car')\n\n # Object in first sample is detected, second sample is empty.\n self.check_ap({'sample1': [self.car1], 'sample2': []},\n {'sample1': [self.car1], 'sample2': []},\n target_ap=1.0, detection_name='car')\n\n # Perfect detection in one image, FN in other.\n self.check_ap({'sample1': [self.car1], 'sample2': [self.car2]},\n {'sample1': [self.car1], 'sample2': []},\n target_ap=0.4/0.9, detection_name='car')\n\n\nclass TestTPSimple(unittest.TestCase):\n \"\"\" Tests the correctness of true positives metrics calculation for simple cases. \"\"\"\n\n def setUp(self):\n\n self.car3 = {'trans': (3, 3, 1), 'size': (2, 4, 2), 'rot': Quaternion(axis=(0, 0, 1), angle=0), 'score': 1.0}\n self.car4 = {'trans': (3, 3, 1), 'size': (2, 4, 2), 'rot': Quaternion(axis=(0, 0, 1), angle=0), 'score': 1.0}\n\n def check_tp(self, gts: Dict[str, List[Dict]],\n preds: Dict[str, List[Dict]],\n target_error: float,\n metric_name: str,\n detection_name: str = 'car',\n min_recall: float = 0.1):\n \"\"\"\n Calculate and check the AP value.\n :param gts: Ground truth data.\n :param preds: Predictions.\n :param target_error: Expected error value.\n :param metric_name: Name of the TP metric.\n :param detection_name: Name of the class we are interested in.\n :param min_recall: Minimum recall value.\n \"\"\"\n\n metric_data = get_metric_data(gts, preds, detection_name, 2.0) # Distance threshold for TP metrics is 2.0\n tp_error = calc_tp(metric_data, min_recall=min_recall, metric_name=metric_name)\n # We quantize the error curve into 100 bins to calculate the metric so it is only accurate up to 1%.\n self.assertGreaterEqual(0.01, abs(tp_error - target_error), msg='Incorrect {} value'.format(metric_name))\n\n def test_no_positives(self):\n \"\"\" Tests the error if there are no matches. The expected behaviour is to return error of 1.0. \"\"\"\n\n # Same type of objects but are more than 2m away.\n car1 = {'trans': (1, 1, 1), 'score': 1.0}\n car2 = {'trans': (3, 3, 1), 'score': 1.0}\n bike1 = {'trans': (1, 1, 1), 'score': 1.0, 'name': 'bicycle', 'attr': 'cycle.with_rider'}\n for metric_name in TP_METRICS:\n self.check_tp({'sample1': [car1]}, {'sample1': [car2]}, target_error=1.0, metric_name=metric_name)\n\n # Within distance threshold away but different classes.\n for metric_name in TP_METRICS:\n self.check_tp({'sample1': [car1]}, {'sample1': [bike1]}, target_error=1.0, metric_name=metric_name)\n\n def test_perfect(self):\n \"\"\" Tests when everything is estimated perfectly. \"\"\"\n\n car1 = {'trans': (1, 1, 1), 'score': 1.0}\n car2 = {'trans': (1, 1, 1), 'score': 0.3}\n for metric_name in TP_METRICS:\n # Detected with perfect score.\n self.check_tp({'sample1': [car1]}, {'sample1': [car1]}, target_error=0.0, metric_name=metric_name)\n\n # Detected with low score.\n self.check_tp({'sample1': [car1]}, {'sample1': [car2]}, target_error=0.0, metric_name=metric_name)\n\n def test_one_img(self):\n \"\"\" Test single sample case. \"\"\"\n\n # Note all the following unit tests can be repeated to other metrics, but they are not needed.\n # The intention of these tests is to measure the calc_tp function which is common for all metrics.\n\n gt1 = {'trans': (1, 1, 1)}\n gt2 = {'trans': (10, 10, 1), 'size': (2, 2, 2)}\n gt3 = {'trans': (20, 20, 1), 'size': (2, 4, 2)}\n\n pred1 = {'trans': (1, 1, 1), 'score': 1.0}\n pred2 = {'trans': (11, 10, 1), 'size': (2, 2, 2), 'score': 0.9}\n pred3 = {'trans': (100, 10, 1), 'size': (2, 2, 2), 'score': 0.8}\n pred4 = {'trans': (20, 20, 1), 'size': (2, 4, 2), 'score': 0.7}\n pred5 = {'trans': (21, 20, 1), 'size': (2, 4, 2), 'score': 0.7}\n\n # one GT and one matching prediction. Object location is off by 1 meter, so error 1.\n self.check_tp({'sample1': [gt2]}, {'sample1': [pred2]}, target_error=1, metric_name='trans_err')\n\n # Two GT's and two detections.\n # The target is the average value of the recall vs. Error curve.\n # In this case there will three points on the curve. (0.1, 0), (0.5, 0), (1.0, 0.5).\n # (0.1, 0): Minimum recall we start from.\n # (0.5, 0): Detection with highest score has no translation error, and one of out of two objects recalled.\n # (1.0, 0.5): The last object is recalled but with 1m translation error, the cumulative mean gets to 0.5m error.\n # Error value of first segment of curve starts at 0 and ends at 0, so the average of this segment is 0.\n # Next segment of the curve starts at 0 and ends at 0.5, so the average is 0.25.\n # Then we take average of all segments and normalize it with the recall values we averaged over.\n target_error = ((0 + 0) / 2 + (0 + 0.5) / 2) / (2 * 0.9)\n self.check_tp({'sample1': [gt1, gt2]}, {'sample1': [pred1, pred2]}, target_error=target_error,\n metric_name='trans_err')\n\n # Adding a false positive with smaller detection score should not affect the true positive metric.\n self.check_tp({'sample1': [gt1, gt2]}, {'sample1': [pred1, pred2, pred3]}, target_error=target_error,\n metric_name='trans_err')\n\n # In this case there will four points on the curve. (0.1, 0), (0.33, 0), (0.66, 0.5) (1.0, 0.33).\n # (0.1, 0): Minimum recall we start from.\n # (0.33, 0): One of out of three objects recalled with no error.\n # (0.66, 0.5): Second object is recalled but with 1m error. Cumulative error becomes 0.5m.\n # (1.0, 0.33): Third object recalled with no error. Cumulative error becomes 0.33m.\n # First segment starts at 0 and ends at 0: average error 0.\n # Next segment starts at 0 and ends at 0.5: average error is 0.25.\n # Next segment starts at 0.5 and ends at 0.33: average error is 0.416\n # Then we take average of all segments and normalize it with the recall values we averaged over.\n target_error = ((0+0)/2 + (0+0.5)/2 + (0.5 + 0.33)/2) / (3 * 0.9) # It is a piecewise linear with 3 segments\n self.check_tp({'sample1': [gt1, gt2, gt3]}, {'sample1': [pred1, pred2, pred4]}, target_error=target_error,\n metric_name='trans_err')\n\n # Both matches have same translational error (1 meter), so the overall error is also 1 meter\n self.check_tp({'sample1': [gt2, gt3]}, {'sample1': [pred2, pred5]}, target_error=1.0,\n metric_name='trans_err')\n\n def test_two_imgs(self):\n \"\"\" Test the more than one sample case. \"\"\"\n\n # Note all the following unit tests can be repeated to other metrics, but they are not needed.\n # The intention of these tests is to measure the calc_tp function which is common for all metrics.\n\n gt1 = {'trans': (1, 1, 1)}\n gt2 = {'trans': (10, 10, 1), 'size': (2, 2, 2)}\n gt3 = {'trans': (20, 20, 1), 'size': (2, 4, 2)}\n\n pred1 = {'trans': (1, 1, 1), 'score': 1.0}\n pred2 = {'trans': (11, 10, 1), 'size': (2, 2, 2), 'score': 0.9}\n pred3 = {'trans': (100, 10, 1), 'size': (2, 2, 2), 'score': 0.8}\n pred4 = {'trans': (21, 20, 1), 'size': (2, 4, 2), 'score': 0.7}\n\n # One GT and one detection\n self.check_tp({'sample1': [gt2]}, {'sample1': [pred2]}, target_error=1, metric_name='trans_err')\n\n # Two GT's and two detections.\n # The target is the average value of the recall vs. Error curve.\n target_error = ((0 + 0) / 2 + (0 + 0.5) / 2) / (2 * 0.9) # It is a piecewise linear with 2 segments.\n self.check_tp({'sample1': [gt1], 'sample2': [gt2]}, {'sample1': [pred1], 'sample2': [pred2]},\n target_error=target_error, metric_name='trans_err')\n\n # Adding a false positive and/or an empty sample should not affect the score\n self.check_tp({'sample1': [gt1], 'sample2': [gt2], 'sample3': []},\n {'sample1': [pred1], 'sample2': [pred2, pred3], 'sample3': []},\n target_error=target_error, metric_name='trans_err')\n\n # All the detections does have same error, so the overall error is also same.\n self.check_tp({'sample1': [gt2, gt3], 'sample2': [gt3]}, {'sample1': [pred2], 'sample2': [pred4]},\n target_error=1.0, metric_name='trans_err')\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] | [
[
"torch.cuda.current_device"
],
[
"scipy.optimize.linear_sum_assignment",
"torch.from_numpy"
],
[
"torch.Size",
"torch.empty",
"torch.sin",
"torch.cat",
"torch.device",
"torch.cos",
"torch.as_tensor"
],
[
"numpy.random.rand",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.4",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Magnety/tuFramework | [
"b31cb34d476ef306b52da955021f93c91c14ddf4",
"b31cb34d476ef306b52da955021f93c91c14ddf4",
"b31cb34d476ef306b52da955021f93c91c14ddf4",
"b31cb34d476ef306b52da955021f93c91c14ddf4"
] | [
"tuframework/training/network_training/nnUNet_variants/architectural_variants/nnUNetTrainerV2_noDeepSupervision.py",
"tuframework/network_architecture/generic_modular_UNet.py",
"tuframework/training/model_restore.py",
"tuframework/training/network_training/tuTrainerCascadeFullRes.py"
] | [
"# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport numpy as np\nfrom batchgenerators.utilities.file_and_folder_operations import *\nfrom tuframework.network_architecture.generic_UNet import Generic_UNet\nfrom tuframework.network_architecture.initialization import InitWeights_He\nfrom tuframework.network_architecture.neural_network import SegmentationNetwork\nfrom tuframework.training.data_augmentation.data_augmentation_moreDA import get_moreDA_augmentation\nfrom tuframework.training.data_augmentation.default_data_augmentation import default_3D_augmentation_params, \\\n default_2D_augmentation_params, get_patch_size\nfrom tuframework.training.dataloading.dataset_loading import unpack_dataset\nfrom tuframework.training.loss_functions.dice_loss import DC_and_CE_loss\nfrom tuframework.training.network_training.tuTrainer import tuframeworkTrainer\nfrom tuframework.training.network_training.tuTrainerV2 import tuframeworkTrainerV2\nfrom tuframework.utilities.nd_softmax import softmax_helper\nfrom torch import nn\nimport torch\n\n\nclass tuframeworkTrainerV2_noDeepSupervision(tuframeworkTrainerV2):\n def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,\n unpack_data=True, deterministic=True, fp16=False):\n super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data,\n deterministic, fp16)\n self.loss = DC_and_CE_loss({'batch_dice': self.batch_dice, 'smooth': 1e-5, 'do_bg': False}, {})\n\n def setup_DA_params(self):\n \"\"\"\n we leave out the creation of self.deep_supervision_scales, so it remains None\n :return:\n \"\"\"\n if self.threeD:\n self.data_aug_params = default_3D_augmentation_params\n self.data_aug_params['rotation_x'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi)\n self.data_aug_params['rotation_y'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi)\n self.data_aug_params['rotation_z'] = (-30. / 360 * 2. * np.pi, 30. / 360 * 2. * np.pi)\n if self.do_dummy_2D_aug:\n self.data_aug_params[\"dummy_2D\"] = True\n self.print_to_log_file(\"Using dummy2d data augmentation\")\n self.data_aug_params[\"elastic_deform_alpha\"] = \\\n default_2D_augmentation_params[\"elastic_deform_alpha\"]\n self.data_aug_params[\"elastic_deform_sigma\"] = \\\n default_2D_augmentation_params[\"elastic_deform_sigma\"]\n self.data_aug_params[\"rotation_x\"] = default_2D_augmentation_params[\"rotation_x\"]\n else:\n self.do_dummy_2D_aug = False\n if max(self.patch_size) / min(self.patch_size) > 1.5:\n default_2D_augmentation_params['rotation_x'] = (-15. / 360 * 2. * np.pi, 15. / 360 * 2. * np.pi)\n self.data_aug_params = default_2D_augmentation_params\n self.data_aug_params[\"mask_was_used_for_normalization\"] = self.use_mask_for_norm\n\n if self.do_dummy_2D_aug:\n self.basic_generator_patch_size = get_patch_size(self.patch_size[1:],\n self.data_aug_params['rotation_x'],\n self.data_aug_params['rotation_y'],\n self.data_aug_params['rotation_z'],\n self.data_aug_params['scale_range'])\n self.basic_generator_patch_size = np.array([self.patch_size[0]] + list(self.basic_generator_patch_size))\n patch_size_for_spatialtransform = self.patch_size[1:]\n else:\n self.basic_generator_patch_size = get_patch_size(self.patch_size, self.data_aug_params['rotation_x'],\n self.data_aug_params['rotation_y'],\n self.data_aug_params['rotation_z'],\n self.data_aug_params['scale_range'])\n patch_size_for_spatialtransform = self.patch_size\n\n self.data_aug_params[\"scale_range\"] = (0.7, 1.4)\n self.data_aug_params[\"do_elastic\"] = False\n self.data_aug_params['selected_seg_channels'] = [0]\n self.data_aug_params['patch_size_for_spatialtransform'] = patch_size_for_spatialtransform\n\n def initialize(self, training=True, force_load_plans=False):\n \"\"\"\n removed deep supervision\n :return:\n \"\"\"\n if not self.was_initialized:\n maybe_mkdir_p(self.output_folder)\n\n if force_load_plans or (self.plans is None):\n self.load_plans_file()\n\n self.process_plans(self.plans)\n\n self.setup_DA_params()\n\n self.folder_with_preprocessed_data = join(self.dataset_directory, self.plans['data_identifier'] +\n \"_stage%d\" % self.stage)\n if training:\n self.dl_tr, self.dl_val = self.get_basic_generators()\n if self.unpack_data:\n print(\"unpacking dataset\")\n unpack_dataset(self.folder_with_preprocessed_data)\n print(\"done\")\n else:\n print(\n \"INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you \"\n \"will wait all winter for your model to finish!\")\n\n assert self.deep_supervision_scales is None\n self.tr_gen, self.val_gen = get_moreDA_augmentation(self.dl_tr, self.dl_val,\n self.data_aug_params[\n 'patch_size_for_spatialtransform'],\n self.data_aug_params,\n deep_supervision_scales=self.deep_supervision_scales,\n classes=None,\n pin_memory=self.pin_memory)\n\n self.print_to_log_file(\"TRAINING KEYS:\\n %s\" % (str(self.dataset_tr.keys())),\n also_print_to_console=False)\n self.print_to_log_file(\"VALIDATION KEYS:\\n %s\" % (str(self.dataset_val.keys())),\n also_print_to_console=False)\n else:\n pass\n\n self.initialize_network()\n self.initialize_optimizer_and_scheduler()\n\n assert isinstance(self.network, (SegmentationNetwork, nn.DataParallel))\n else:\n self.print_to_log_file('self.was_initialized is True, not running self.initialize again')\n self.was_initialized = True\n\n def initialize_network(self):\n \"\"\"\n changed deep supervision to False\n :return:\n \"\"\"\n if self.threeD:\n conv_op = nn.Conv3d\n dropout_op = nn.Dropout3d\n norm_op = nn.InstanceNorm3d\n\n else:\n conv_op = nn.Conv2d\n dropout_op = nn.Dropout2d\n norm_op = nn.InstanceNorm2d\n\n norm_op_kwargs = {'eps': 1e-5, 'affine': True}\n dropout_op_kwargs = {'p': 0, 'inplace': True}\n net_nonlin = nn.LeakyReLU\n net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True}\n self.network = Generic_UNet(self.num_input_channels, self.base_num_features, self.num_classes,\n len(self.net_num_pool_op_kernel_sizes),\n self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs,\n net_nonlin, net_nonlin_kwargs, False, False, lambda x: x, InitWeights_He(1e-2),\n self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True)\n if torch.cuda.is_available():\n self.network.cuda()\n self.network.inference_apply_nonlin = softmax_helper\n\n def run_online_evaluation(self, output, target):\n return tuframeworkTrainer.run_online_evaluation(self, output, target)\n",
"# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport torch\nfrom tuframework.network_architecture.custom_modules.conv_blocks import StackedConvLayers\nfrom tuframework.network_architecture.generic_UNet import Upsample\nfrom tuframework.network_architecture.neural_network import SegmentationNetwork\nfrom tuframework.training.loss_functions.dice_loss import DC_and_CE_loss\nfrom torch import nn\nimport numpy as np\nfrom torch.optim import SGD\n\n\"\"\"\nThe idea behind this modular U-net ist that we decouple encoder and decoder and thus make things a) a lot more easy to \ncombine and b) enable easy swapping between segmentation or classification mode of the same architecture\n\"\"\"\n\n\ndef get_default_network_config(dim=2, dropout_p=None, nonlin=\"LeakyReLU\", norm_type=\"bn\"):\n \"\"\"\n returns a dictionary that contains pointers to conv, nonlin and norm ops and the default kwargs I like to use\n :return:\n \"\"\"\n props = {}\n if dim == 2:\n props['conv_op'] = nn.Conv2d\n props['dropout_op'] = nn.Dropout2d\n elif dim == 3:\n props['conv_op'] = nn.Conv3d\n props['dropout_op'] = nn.Dropout3d\n else:\n raise NotImplementedError\n\n if norm_type == \"bn\":\n if dim == 2:\n props['norm_op'] = nn.BatchNorm2d\n elif dim == 3:\n props['norm_op'] = nn.BatchNorm3d\n props['norm_op_kwargs'] = {'eps': 1e-5, 'affine': True}\n elif norm_type == \"in\":\n if dim == 2:\n props['norm_op'] = nn.InstanceNorm2d\n elif dim == 3:\n props['norm_op'] = nn.InstanceNorm3d\n props['norm_op_kwargs'] = {'eps': 1e-5, 'affine': True}\n else:\n raise NotImplementedError\n\n if dropout_p is None:\n props['dropout_op'] = None\n props['dropout_op_kwargs'] = {'p': 0, 'inplace': True}\n else:\n props['dropout_op_kwargs'] = {'p': dropout_p, 'inplace': True}\n\n props['conv_op_kwargs'] = {'stride': 1, 'dilation': 1, 'bias': True} # kernel size will be set by network!\n\n if nonlin == \"LeakyReLU\":\n props['nonlin'] = nn.LeakyReLU\n props['nonlin_kwargs'] = {'negative_slope': 1e-2, 'inplace': True}\n elif nonlin == \"ReLU\":\n props['nonlin'] = nn.ReLU\n props['nonlin_kwargs'] = {'inplace': True}\n else:\n raise ValueError\n\n return props\n\n\n\nclass PlainConvUNetEncoder(nn.Module):\n def __init__(self, input_channels, base_num_features, num_blocks_per_stage, feat_map_mul_on_downscale,\n pool_op_kernel_sizes, conv_kernel_sizes, props, default_return_skips=True,\n max_num_features=480):\n \"\"\"\n Following UNet building blocks can be added by utilizing the properties this class exposes (TODO)\n\n this one includes the bottleneck layer!\n\n :param input_channels:\n :param base_num_features:\n :param num_blocks_per_stage:\n :param feat_map_mul_on_downscale:\n :param pool_op_kernel_sizes:\n :param conv_kernel_sizes:\n :param props:\n \"\"\"\n super(PlainConvUNetEncoder, self).__init__()\n\n self.default_return_skips = default_return_skips\n self.props = props\n\n self.stages = []\n self.stage_output_features = []\n self.stage_pool_kernel_size = []\n self.stage_conv_op_kernel_size = []\n\n assert len(pool_op_kernel_sizes) == len(conv_kernel_sizes)\n\n num_stages = len(conv_kernel_sizes)\n\n if not isinstance(num_blocks_per_stage, (list, tuple)):\n num_blocks_per_stage = [num_blocks_per_stage] * num_stages\n else:\n assert len(num_blocks_per_stage) == num_stages\n\n self.num_blocks_per_stage = num_blocks_per_stage # decoder may need this\n\n current_input_features = input_channels\n for stage in range(num_stages):\n current_output_features = min(int(base_num_features * feat_map_mul_on_downscale ** stage), max_num_features)\n current_kernel_size = conv_kernel_sizes[stage]\n current_pool_kernel_size = pool_op_kernel_sizes[stage]\n\n current_stage = StackedConvLayers(current_input_features, current_output_features, current_kernel_size,\n props, num_blocks_per_stage[stage], current_pool_kernel_size)\n\n self.stages.append(current_stage)\n self.stage_output_features.append(current_output_features)\n self.stage_conv_op_kernel_size.append(current_kernel_size)\n self.stage_pool_kernel_size.append(current_pool_kernel_size)\n\n # update current_input_features\n current_input_features = current_output_features\n\n self.stages = nn.ModuleList(self.stages)\n\n def forward(self, x, return_skips=None):\n \"\"\"\n\n :param x:\n :param return_skips: if none then self.default_return_skips is used\n :return:\n \"\"\"\n skips = []\n\n for s in self.stages:\n x = s(x)\n if self.default_return_skips:\n skips.append(x)\n\n if return_skips is None:\n return_skips = self.default_return_skips\n\n if return_skips:\n return skips\n else:\n return x\n\n @staticmethod\n def compute_approx_vram_consumption(patch_size, base_num_features, max_num_features,\n num_modalities, pool_op_kernel_sizes, num_blocks_per_stage_encoder,\n feat_map_mul_on_downscale, batch_size):\n npool = len(pool_op_kernel_sizes) - 1\n\n current_shape = np.array(patch_size)\n\n tmp = num_blocks_per_stage_encoder[0] * np.prod(current_shape) * base_num_features \\\n + num_modalities * np.prod(current_shape)\n\n num_feat = base_num_features\n\n for p in range(1, npool + 1):\n current_shape = current_shape / np.array(pool_op_kernel_sizes[p])\n num_feat = min(num_feat * feat_map_mul_on_downscale, max_num_features)\n num_convs = num_blocks_per_stage_encoder[p]\n print(p, num_feat, num_convs, current_shape)\n tmp += num_convs * np.prod(current_shape) * num_feat\n return tmp * batch_size\n\n\nclass PlainConvUNetDecoder(nn.Module):\n def __init__(self, previous, num_classes, num_blocks_per_stage=None, network_props=None, deep_supervision=False,\n upscale_logits=False):\n super(PlainConvUNetDecoder, self).__init__()\n self.num_classes = num_classes\n self.deep_supervision = deep_supervision\n \"\"\"\n We assume the bottleneck is part of the encoder, so we can start with upsample -> concat here\n \"\"\"\n previous_stages = previous.stages\n previous_stage_output_features = previous.stage_output_features\n previous_stage_pool_kernel_size = previous.stage_pool_kernel_size\n previous_stage_conv_op_kernel_size = previous.stage_conv_op_kernel_size\n\n if network_props is None:\n self.props = previous.props\n else:\n self.props = network_props\n\n if self.props['conv_op'] == nn.Conv2d:\n transpconv = nn.ConvTranspose2d\n upsample_mode = \"bilinear\"\n elif self.props['conv_op'] == nn.Conv3d:\n transpconv = nn.ConvTranspose3d\n upsample_mode = \"trilinear\"\n else:\n raise ValueError(\"unknown convolution dimensionality, conv op: %s\" % str(self.props['conv_op']))\n\n if num_blocks_per_stage is None:\n num_blocks_per_stage = previous.num_blocks_per_stage[:-1][::-1]\n\n assert len(num_blocks_per_stage) == len(previous.num_blocks_per_stage) - 1\n\n self.stage_pool_kernel_size = previous_stage_pool_kernel_size\n self.stage_output_features = previous_stage_output_features\n self.stage_conv_op_kernel_size = previous_stage_conv_op_kernel_size\n\n num_stages = len(previous_stages) - 1 # we have one less as the first stage here is what comes after the\n # bottleneck\n\n self.tus = []\n self.stages = []\n self.deep_supervision_outputs = []\n\n # only used for upsample_logits\n cum_upsample = np.cumprod(np.vstack(self.stage_pool_kernel_size), axis=0).astype(int)\n\n for i, s in enumerate(np.arange(num_stages)[::-1]):\n features_below = previous_stage_output_features[s + 1]\n features_skip = previous_stage_output_features[s]\n\n self.tus.append(transpconv(features_below, features_skip, previous_stage_pool_kernel_size[s + 1],\n previous_stage_pool_kernel_size[s + 1], bias=False))\n # after we tu we concat features so now we have 2xfeatures_skip\n self.stages.append(StackedConvLayers(2 * features_skip, features_skip,\n previous_stage_conv_op_kernel_size[s], self.props,\n num_blocks_per_stage[i]))\n\n if deep_supervision and s != 0:\n seg_layer = self.props['conv_op'](features_skip, num_classes, 1, 1, 0, 1, 1, False)\n if upscale_logits:\n upsample = Upsample(scale_factor=cum_upsample[s], mode=upsample_mode)\n self.deep_supervision_outputs.append(nn.Sequential(seg_layer, upsample))\n else:\n self.deep_supervision_outputs.append(seg_layer)\n\n self.segmentation_output = self.props['conv_op'](features_skip, num_classes, 1, 1, 0, 1, 1, False)\n\n self.tus = nn.ModuleList(self.tus)\n self.stages = nn.ModuleList(self.stages)\n self.deep_supervision_outputs = nn.ModuleList(self.deep_supervision_outputs)\n\n def forward(self, skips, gt=None, loss=None):\n # skips come from the encoder. They are sorted so that the bottleneck is last in the list\n # what is maybe not perfect is that the TUs and stages here are sorted the other way around\n # so let's just reverse the order of skips\n skips = skips[::-1]\n seg_outputs = []\n\n x = skips[0] # this is the bottleneck\n\n for i in range(len(self.tus)):\n x = self.tus[i](x)\n x = torch.cat((x, skips[i + 1]), dim=1)\n x = self.stages[i](x)\n if self.deep_supervision and (i != len(self.tus) - 1):\n tmp = self.deep_supervision_outputs[i](x)\n if gt is not None:\n tmp = loss(tmp, gt)\n seg_outputs.append(tmp)\n\n segmentation = self.segmentation_output(x)\n\n if self.deep_supervision:\n tmp = segmentation\n if gt is not None:\n tmp = loss(tmp, gt)\n seg_outputs.append(tmp)\n return seg_outputs[::-1] # seg_outputs are ordered so that the seg from the highest layer is first, the seg from\n # the bottleneck of the UNet last\n else:\n return segmentation\n\n @staticmethod\n def compute_approx_vram_consumption(patch_size, base_num_features, max_num_features,\n num_classes, pool_op_kernel_sizes, num_blocks_per_stage_decoder,\n feat_map_mul_on_downscale, batch_size):\n \"\"\"\n This only applies for num_blocks_per_stage and convolutional_upsampling=True\n not real vram consumption. just a constant term to which the vram consumption will be approx proportional\n (+ offset for parameter storage)\n :param patch_size:\n :param num_pool_per_axis:\n :param base_num_features:\n :param max_num_features:\n :return:\n \"\"\"\n npool = len(pool_op_kernel_sizes) - 1\n\n current_shape = np.array(patch_size)\n tmp = (num_blocks_per_stage_decoder[-1] + 1) * np.prod(current_shape) * base_num_features + num_classes * np.prod(current_shape)\n\n num_feat = base_num_features\n\n for p in range(1, npool):\n current_shape = current_shape / np.array(pool_op_kernel_sizes[p])\n num_feat = min(num_feat * feat_map_mul_on_downscale, max_num_features)\n num_convs = num_blocks_per_stage_decoder[-(p+1)] + 1\n print(p, num_feat, num_convs, current_shape)\n tmp += num_convs * np.prod(current_shape) * num_feat\n\n return tmp * batch_size\n\n\nclass PlainConvUNet(SegmentationNetwork):\n use_this_for_batch_size_computation_2D = 1167982592.0\n use_this_for_batch_size_computation_3D = 1152286720.0\n\n def __init__(self, input_channels, base_num_features, num_blocks_per_stage_encoder, feat_map_mul_on_downscale,\n pool_op_kernel_sizes, conv_kernel_sizes, props, num_classes, num_blocks_per_stage_decoder,\n deep_supervision=False, upscale_logits=False, max_features=512, initializer=None):\n super(PlainConvUNet, self).__init__()\n self.conv_op = props['conv_op']\n self.num_classes = num_classes\n\n self.encoder = PlainConvUNetEncoder(input_channels, base_num_features, num_blocks_per_stage_encoder,\n feat_map_mul_on_downscale, pool_op_kernel_sizes, conv_kernel_sizes,\n props, default_return_skips=True, max_num_features=max_features)\n self.decoder = PlainConvUNetDecoder(self.encoder, num_classes, num_blocks_per_stage_decoder, props,\n deep_supervision, upscale_logits)\n if initializer is not None:\n self.apply(initializer)\n\n def forward(self, x):\n skips = self.encoder(x)\n return self.decoder(skips)\n\n @staticmethod\n def compute_approx_vram_consumption(patch_size, base_num_features, max_num_features,\n num_modalities, num_classes, pool_op_kernel_sizes, num_blocks_per_stage_encoder,\n num_blocks_per_stage_decoder, feat_map_mul_on_downscale, batch_size):\n enc = PlainConvUNetEncoder.compute_approx_vram_consumption(patch_size, base_num_features, max_num_features,\n num_modalities, pool_op_kernel_sizes,\n num_blocks_per_stage_encoder,\n feat_map_mul_on_downscale, batch_size)\n dec = PlainConvUNetDecoder.compute_approx_vram_consumption(patch_size, base_num_features, max_num_features,\n num_classes, pool_op_kernel_sizes,\n num_blocks_per_stage_decoder,\n feat_map_mul_on_downscale, batch_size)\n\n return enc + dec\n\n @staticmethod\n def compute_reference_for_vram_consumption_3d():\n patch_size = (160, 128, 128)\n pool_op_kernel_sizes = ((1, 1, 1),\n (2, 2, 2),\n (2, 2, 2),\n (2, 2, 2),\n (2, 2, 2),\n (2, 2, 2))\n conv_per_stage_encoder = (2, 2, 2, 2, 2, 2)\n conv_per_stage_decoder = (2, 2, 2, 2, 2)\n\n return PlainConvUNet.compute_approx_vram_consumption(patch_size, 32, 512, 4, 3, pool_op_kernel_sizes,\n conv_per_stage_encoder, conv_per_stage_decoder, 2, 2)\n\n @staticmethod\n def compute_reference_for_vram_consumption_2d():\n patch_size = (256, 256)\n pool_op_kernel_sizes = (\n (1, 1), # (256, 256)\n (2, 2), # (128, 128)\n (2, 2), # (64, 64)\n (2, 2), # (32, 32)\n (2, 2), # (16, 16)\n (2, 2), # (8, 8)\n (2, 2) # (4, 4)\n )\n conv_per_stage_encoder = (2, 2, 2, 2, 2, 2, 2)\n conv_per_stage_decoder = (2, 2, 2, 2, 2, 2)\n\n return PlainConvUNet.compute_approx_vram_consumption(patch_size, 32, 512, 4, 3, pool_op_kernel_sizes,\n conv_per_stage_encoder, conv_per_stage_decoder, 2, 56)\n\n\nif __name__ == \"__main__\":\n conv_op_kernel_sizes = ((3, 3),\n (3, 3),\n (3, 3),\n (3, 3),\n (3, 3),\n (3, 3),\n (3, 3))\n pool_op_kernel_sizes = ((1, 1),\n (2, 2),\n (2, 2),\n (2, 2),\n (2, 2),\n (2, 2),\n (2, 2))\n patch_size = (256, 256)\n batch_size = 56\n unet = PlainConvUNet(4, 32, (2, 2, 2, 2, 2, 2, 2), 2, pool_op_kernel_sizes, conv_op_kernel_sizes,\n get_default_network_config(2, dropout_p=None), 4, (2, 2, 2, 2, 2, 2), False, False, max_features=512).cuda()\n optimizer = SGD(unet.parameters(), lr=0.1, momentum=0.95)\n\n unet.compute_reference_for_vram_consumption_3d()\n unet.compute_reference_for_vram_consumption_2d()\n\n dummy_input = torch.rand((batch_size, 4, *patch_size)).cuda()\n dummy_gt = (torch.rand((batch_size, 1, *patch_size)) * 4).round().clamp_(0, 3).cuda().long()\n\n optimizer.zero_grad()\n skips = unet.encoder(dummy_input)\n print([i.shape for i in skips])\n loss = DC_and_CE_loss({'batch_dice': True, 'smooth': 1e-5, 'smooth_in_nom': True,\n 'do_bg': False, 'rebalance_weights': None, 'background_weight': 1}, {})\n output = unet.decoder(skips)\n\n l = loss(output, dummy_gt)\n l.backward()\n\n optimizer.step()\n\n import hiddenlayer as hl\n g = hl.build_graph(unet, dummy_input)\n g.save(\"/home/fabian/test.pdf\")\n\n \"\"\"conv_op_kernel_sizes = ((3, 3, 3),\n (3, 3, 3),\n (3, 3, 3),\n (3, 3, 3),\n (3, 3, 3),\n (3, 3, 3))\n pool_op_kernel_sizes = ((1, 1, 1),\n (2, 2, 2),\n (2, 2, 2),\n (2, 2, 2),\n (2, 2, 2),\n (2, 2, 2))\n patch_size = (160, 128, 128)\n unet = PlainConvUNet(4, 32, (2, 2, 2, 2, 2, 2), 2, pool_op_kernel_sizes, conv_op_kernel_sizes,\n get_default_network_config(3, dropout_p=None), 4, (2, 2, 2, 2, 2), False, False, max_features=512).cuda()\n optimizer = SGD(unet.parameters(), lr=0.1, momentum=0.95)\n\n unet.compute_reference_for_vram_consumption_3d()\n unet.compute_reference_for_vram_consumption_2d()\n\n dummy_input = torch.rand((2, 4, *patch_size)).cuda()\n dummy_gt = (torch.rand((2, 1, *patch_size)) * 4).round().clamp_(0, 3).cuda().long()\n\n optimizer.zero_grad()\n skips = unet.encoder(dummy_input)\n print([i.shape for i in skips])\n loss = DC_and_CE_loss({'batch_dice': True, 'smooth': 1e-5, 'smooth_in_nom': True,\n 'do_bg': False, 'rebalance_weights': None, 'background_weight': 1}, {})\n output = unet.decoder(skips)\n\n l = loss(output, dummy_gt)\n l.backward()\n\n optimizer.step()\n\n import hiddenlayer as hl\n g = hl.build_graph(unet, dummy_input)\n g.save(\"/home/fabian/test.pdf\")\"\"\"\n",
"# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany\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 tuframework\nimport torch\nfrom batchgenerators.utilities.file_and_folder_operations import *\nimport importlib\nimport pkgutil\nfrom tuframework.training.network_training.tuTrainer import tuframeworkTrainer\n\n\ndef recursive_find_python_class(folder, trainer_name, current_module):\n tr = None\n for importer, modname, ispkg in pkgutil.iter_modules(folder):\n print(modname, ispkg)\n if not ispkg:\n m = importlib.import_module(current_module + \".\" + modname)\n if hasattr(m, trainer_name):\n tr = getattr(m, trainer_name)\n break\n\n if tr is None:\n for importer, modname, ispkg in pkgutil.iter_modules(folder):\n if ispkg:\n next_current_module = current_module + \".\" + modname\n tr = recursive_find_python_class([join(folder[0], modname)], trainer_name, current_module=next_current_module)\n if tr is not None:\n break\n\n return tr\n\n\ndef restore_model(pkl_file, checkpoint=None, train=False, fp16=None):\n \"\"\"\n This is a utility function to load any tuframework trainer from a pkl. It will recursively search\n tuframework.trainig.network_training for the file that contains the trainer and instantiate it with the arguments saved in the pkl file. If checkpoint\n is specified, it will furthermore load the checkpoint file in train/test mode (as specified by train).\n The pkl file required here is the one that will be saved automatically when calling tuframeworkTrainer.save_checkpoint.\n :param pkl_file:\n :param checkpoint:\n :param train:\n :param fp16: if None then we take no action. If True/False we overwrite what the model has in its init\n :return:\n \"\"\"\n info = load_pickle(pkl_file)\n init = info['init']\n name = info['name']\n search_in = join(tuframework.__path__[0], \"training\", \"network_training\")\n tr = recursive_find_python_class([search_in], name, current_module=\"tuframework.training.network_training\")\n\n if tr is None:\n \"\"\"\n Fabian only. This will trigger searching for trainer classes in other repositories as well\n \"\"\"\n try:\n import meddec\n search_in = join(meddec.__path__[0], \"model_training\")\n tr = recursive_find_python_class([search_in], name, current_module=\"meddec.model_training\")\n except ImportError:\n pass\n\n if tr is None:\n raise RuntimeError(\"Could not find the model trainer specified in checkpoint in tuframework.trainig.network_training. If it \"\n \"is not located there, please move it or change the code of restore_model. Your model \"\n \"trainer can be located in any directory within tuframework.trainig.network_training (search is recursive).\"\n \"\\nDebug info: \\ncheckpoint file: %s\\nName of trainer: %s \" % (checkpoint, name))\n assert issubclass(tr, tuframeworkTrainer), \"The network trainer was found but is not a subclass of tuframeworkTrainer. \" \\\n \"Please make it so!\"\n\n # this is now deprecated\n \"\"\"if len(init) == 7:\n print(\"warning: this model seems to have been saved with a previous version of tuframework. Attempting to load it \"\n \"anyways. Expect the unexpected.\")\n print(\"manually editing init args...\")\n init = [init[i] for i in range(len(init)) if i != 2]\"\"\"\n\n # ToDo Fabian make saves use kwargs, please...\n\n trainer = tr(*init)\n\n # We can hack fp16 overwriting into the trainer without changing the init arguments because nothing happens with\n # fp16 in the init, it just saves it to a member variable\n if fp16 is not None:\n trainer.fp16 = fp16\n\n trainer.process_plans(info['plans'])\n if checkpoint is not None:\n trainer.load_checkpoint(checkpoint, train)\n return trainer\n\n\ndef load_best_model_for_inference(folder):\n checkpoint = join(folder, \"model_best.model\")\n pkl_file = checkpoint + \".pkl\"\n return restore_model(pkl_file, checkpoint, False)\n\n\ndef load_model_and_checkpoint_files(folder, folds=None, mixed_precision=None, checkpoint_name=\"model_best\"):\n \"\"\"\n used for if you need to ensemble the five models of a cross-validation. This will restore the model from the\n checkpoint in fold 0, load all parameters of the five folds in ram and return both. This will allow for fast\n switching between parameters (as opposed to loading them form disk each time).\n\n This is best used for inference and test prediction\n :param folder:\n :param folds:\n :param mixed_precision: if None then we take no action. If True/False we overwrite what the model has in its init\n :return:\n \"\"\"\n if isinstance(folds, str):\n folds = [join(folder, \"all\")]\n assert isdir(folds[0]), \"no output folder for fold %s found\" % folds\n elif isinstance(folds, (list, tuple)):\n if len(folds) == 1 and folds[0] == \"all\":\n folds = [join(folder, \"all\")]\n else:\n folds = [join(folder, \"fold_%d\" % i) for i in folds]\n assert all([isdir(i) for i in folds]), \"list of folds specified but not all output folders are present\"\n elif isinstance(folds, int):\n folds = [join(folder, \"fold_%d\" % folds)]\n assert all([isdir(i) for i in folds]), \"output folder missing for fold %d\" % folds\n elif folds is None:\n print(\"folds is None so we will automatically look for output folders (not using \\'all\\'!)\")\n folds = subfolders(folder, prefix=\"fold\")\n print(\"found the following folds: \", folds)\n else:\n raise ValueError(\"Unknown value for folds. Type: %s. Expected: list of int, int, str or None\", str(type(folds)))\n\n trainer = restore_model(join(folds[0], \"%s.model.pkl\" % checkpoint_name), fp16=mixed_precision)\n trainer.output_folder = folder\n trainer.output_folder_base = folder\n trainer.update_fold(0)\n trainer.initialize(False)\n all_best_model_files = [join(i, \"%s.model\" % checkpoint_name) for i in folds]\n print(\"using the following model files: \", all_best_model_files)\n all_params = [torch.load(i, map_location=torch.device('cpu')) for i in all_best_model_files]\n return trainer, all_params\n\n\nif __name__ == \"__main__\":\n pkl = \"/home/fabian/PhD/results/tuframeworkV2/tuframeworkV2_3D_fullres/Task004_Hippocampus/fold0/model_best.model.pkl\"\n checkpoint = pkl[:-4]\n train = False\n trainer = restore_model(pkl, checkpoint, train)\n",
"# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom multiprocessing.pool import Pool\nfrom time import sleep\n\nimport matplotlib\nfrom tuframework.postprocessing.connected_components import determine_postprocessing\nfrom tuframework.training.data_augmentation.default_data_augmentation import get_default_augmentation\nfrom tuframework.training.dataloading.dataset_loading import DataLoader3D, unpack_dataset\nfrom tuframework.evaluation.evaluator import aggregate_scores\nfrom tuframework.training.network_training.tuTrainer import tuframeworkTrainer\nfrom tuframework.network_architecture.neural_network import SegmentationNetwork\nfrom tuframework.paths import network_training_output_dir\nfrom tuframework.inference.segmentation_export import save_segmentation_nifti_from_softmax\nfrom batchgenerators.utilities.file_and_folder_operations import *\nimport numpy as np\nfrom tuframework.utilities.one_hot_encoding import to_one_hot\nimport shutil\n\nmatplotlib.use(\"agg\")\n\n\nclass tuframeworkTrainerCascadeFullRes(tuframeworkTrainer):\n def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,\n unpack_data=True, deterministic=True, previous_trainer=\"tuframeworkTrainer\", fp16=False):\n super(tuframeworkTrainerCascadeFullRes, self).__init__(plans_file, fold, output_folder, dataset_directory,\n batch_dice, stage, unpack_data, deterministic, fp16)\n self.init_args = (plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data,\n deterministic, previous_trainer, fp16)\n\n if self.output_folder is not None:\n task = self.output_folder.split(\"/\")[-3]\n plans_identifier = self.output_folder.split(\"/\")[-2].split(\"__\")[-1]\n\n folder_with_segs_prev_stage = join(network_training_output_dir, \"3d_lowres\",\n task, previous_trainer + \"__\" + plans_identifier, \"pred_next_stage\")\n if not isdir(folder_with_segs_prev_stage):\n raise RuntimeError(\n \"Cannot run final stage of cascade. Run corresponding 3d_lowres first and predict the \"\n \"segmentations for the next stage\")\n self.folder_with_segs_from_prev_stage = folder_with_segs_prev_stage\n # Do not put segs_prev_stage into self.output_folder as we need to unpack them for performance and we\n # don't want to do that in self.output_folder because that one is located on some network drive.\n else:\n self.folder_with_segs_from_prev_stage = None\n\n def do_split(self):\n super(tuframeworkTrainerCascadeFullRes, self).do_split()\n for k in self.dataset:\n self.dataset[k]['seg_from_prev_stage_file'] = join(self.folder_with_segs_from_prev_stage,\n k + \"_segFromPrevStage.npz\")\n assert isfile(self.dataset[k]['seg_from_prev_stage_file']), \\\n \"seg from prev stage missing: %s\" % (self.dataset[k]['seg_from_prev_stage_file'])\n for k in self.dataset_val:\n self.dataset_val[k]['seg_from_prev_stage_file'] = join(self.folder_with_segs_from_prev_stage,\n k + \"_segFromPrevStage.npz\")\n for k in self.dataset_tr:\n self.dataset_tr[k]['seg_from_prev_stage_file'] = join(self.folder_with_segs_from_prev_stage,\n k + \"_segFromPrevStage.npz\")\n\n def get_basic_generators(self):\n self.load_dataset()\n self.do_split()\n if self.threeD:\n dl_tr = DataLoader3D(self.dataset_tr, self.basic_generator_patch_size, self.patch_size, self.batch_size,\n True, oversample_foreground_percent=self.oversample_foreground_percent)\n dl_val = DataLoader3D(self.dataset_val, self.patch_size, self.patch_size, self.batch_size, True,\n oversample_foreground_percent=self.oversample_foreground_percent)\n else:\n raise NotImplementedError\n return dl_tr, dl_val\n\n def process_plans(self, plans):\n super(tuframeworkTrainerCascadeFullRes, self).process_plans(plans)\n self.num_input_channels += (self.num_classes - 1) # for seg from prev stage\n\n def setup_DA_params(self):\n super().setup_DA_params()\n self.data_aug_params['move_last_seg_chanel_to_data'] = True\n self.data_aug_params['cascade_do_cascade_augmentations'] = True\n\n self.data_aug_params['cascade_random_binary_transform_p'] = 0.4\n self.data_aug_params['cascade_random_binary_transform_p_per_label'] = 1\n self.data_aug_params['cascade_random_binary_transform_size'] = (1, 8)\n\n self.data_aug_params['cascade_remove_conn_comp_p'] = 0.2\n self.data_aug_params['cascade_remove_conn_comp_max_size_percent_threshold'] = 0.15\n self.data_aug_params['cascade_remove_conn_comp_fill_with_other_class_p'] = 0.0\n\n # we have 2 channels now because the segmentation from the previous stage is stored in 'seg' as well until it\n # is moved to 'data' at the end\n self.data_aug_params['selected_seg_channels'] = [0, 1]\n # needed for converting the segmentation from the previous stage to one hot\n self.data_aug_params['all_segmentation_labels'] = list(range(1, self.num_classes))\n\n def initialize(self, training=True, force_load_plans=False):\n \"\"\"\n For prediction of test cases just set training=False, this will prevent loading of training data and\n training batchgenerator initialization\n :param training:\n :return:\n \"\"\"\n if force_load_plans or (self.plans is None):\n self.load_plans_file()\n\n self.process_plans(self.plans)\n\n self.setup_DA_params()\n\n self.folder_with_preprocessed_data = join(self.dataset_directory, self.plans['data_identifier'] +\n \"_stage%d\" % self.stage)\n if training:\n self.setup_DA_params()\n\n if self.folder_with_preprocessed_data is not None:\n self.dl_tr, self.dl_val = self.get_basic_generators()\n\n if self.unpack_data:\n print(\"unpacking dataset\")\n unpack_dataset(self.folder_with_preprocessed_data)\n print(\"done\")\n else:\n print(\n \"INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you \"\n \"will wait all winter for your model to finish!\")\n\n self.tr_gen, self.val_gen = get_default_augmentation(self.dl_tr, self.dl_val,\n self.data_aug_params[\n 'patch_size_for_spatialtransform'],\n self.data_aug_params)\n self.print_to_log_file(\"TRAINING KEYS:\\n %s\" % (str(self.dataset_tr.keys())))\n self.print_to_log_file(\"VALIDATION KEYS:\\n %s\" % (str(self.dataset_val.keys())))\n else:\n pass\n self.initialize_network()\n assert isinstance(self.network, SegmentationNetwork)\n self.was_initialized = True\n\n def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True,\n step_size: float = 0.5,\n save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True,\n validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False,\n segmentation_export_kwargs: dict = None, run_postprocessing_on_folds: bool = True):\n\n current_mode = self.network.training\n self.network.eval()\n\n assert self.was_initialized, \"must initialize, ideally with checkpoint (or train first)\"\n if self.dataset_val is None:\n self.load_dataset()\n self.do_split()\n\n if segmentation_export_kwargs is None:\n if 'segmentation_export_params' in self.plans.keys():\n force_separate_z = self.plans['segmentation_export_params']['force_separate_z']\n interpolation_order = self.plans['segmentation_export_params']['interpolation_order']\n interpolation_order_z = self.plans['segmentation_export_params']['interpolation_order_z']\n else:\n force_separate_z = None\n interpolation_order = 1\n interpolation_order_z = 0\n else:\n force_separate_z = segmentation_export_kwargs['force_separate_z']\n interpolation_order = segmentation_export_kwargs['interpolation_order']\n interpolation_order_z = segmentation_export_kwargs['interpolation_order_z']\n\n output_folder = join(self.output_folder, validation_folder_name)\n maybe_mkdir_p(output_folder)\n\n if do_mirroring:\n mirror_axes = self.data_aug_params['mirror_axes']\n else:\n mirror_axes = ()\n\n pred_gt_tuples = []\n\n export_pool = Pool(2)\n results = []\n\n transpose_backward = self.plans.get('transpose_backward')\n\n for k in self.dataset_val.keys():\n properties = load_pickle(self.dataset[k]['properties_file'])\n data = np.load(self.dataset[k]['data_file'])['data']\n\n # concat segmentation of previous step\n seg_from_prev_stage = np.load(join(self.folder_with_segs_from_prev_stage,\n k + \"_segFromPrevStage.npz\"))['data'][None]\n\n print(data.shape)\n data[-1][data[-1] == -1] = 0\n data_for_net = np.concatenate((data[:-1], to_one_hot(seg_from_prev_stage[0], range(1, self.num_classes))))\n\n softmax_pred = self.predict_preprocessed_data_return_seg_and_softmax(data_for_net,\n do_mirroring=do_mirroring,\n mirror_axes=mirror_axes,\n use_sliding_window=use_sliding_window,\n step_size=step_size,\n use_gaussian=use_gaussian,\n all_in_gpu=all_in_gpu,\n mixed_precision=self.fp16)[1]\n\n if transpose_backward is not None:\n transpose_backward = self.plans.get('transpose_backward')\n softmax_pred = softmax_pred.transpose([0] + [i + 1 for i in transpose_backward])\n\n fname = properties['list_of_data_files'][0].split(\"/\")[-1][:-12]\n\n if save_softmax:\n softmax_fname = join(output_folder, fname + \".npz\")\n else:\n softmax_fname = None\n\n \"\"\"There is a problem with python process communication that prevents us from communicating obejcts \n larger than 2 GB between processes (basically when the length of the pickle string that will be sent is \n communicated by the multiprocessing.Pipe object then the placeholder (\\%i I think) does not allow for long \n enough strings (lol). This could be fixed by changing i to l (for long) but that would require manually \n patching system python code. We circumvent that problem here by saving softmax_pred to a npy file that will \n then be read (and finally deleted) by the Process. save_segmentation_nifti_from_softmax can take either \n filename or np.ndarray and will handle this automatically\"\"\"\n if np.prod(softmax_pred.shape) > (2e9 / 4 * 0.85): # *0.85 just to be save\n np.save(fname + \".npy\", softmax_pred)\n softmax_pred = fname + \".npy\"\n\n results.append(export_pool.starmap_async(save_segmentation_nifti_from_softmax,\n ((softmax_pred, join(output_folder, fname + \".nii.gz\"),\n properties, interpolation_order, self.regions_class_order,\n None, None,\n softmax_fname, None, force_separate_z,\n interpolation_order_z),\n )\n )\n )\n\n pred_gt_tuples.append([join(output_folder, fname + \".nii.gz\"),\n join(self.gt_niftis_folder, fname + \".nii.gz\")])\n\n _ = [i.get() for i in results]\n\n task = self.dataset_directory.split(\"/\")[-1]\n job_name = self.experiment_name\n _ = aggregate_scores(pred_gt_tuples, labels=list(range(self.num_classes)),\n json_output_file=join(output_folder, \"summary.json\"), json_name=job_name,\n json_author=\"Fabian\", json_description=\"\",\n json_task=task)\n\n if run_postprocessing_on_folds:\n # in the old tuframework we would stop here. Now we add a postprocessing. This postprocessing can remove everything\n # except the largest connected component for each class. To see if this improves results, we do this for all\n # classes and then rerun the evaluation. Those classes for which this resulted in an improved dice score will\n # have this applied during inference as well\n self.print_to_log_file(\"determining postprocessing\")\n determine_postprocessing(self.output_folder, self.gt_niftis_folder, validation_folder_name,\n final_subf_name=validation_folder_name + \"_postprocessed\", debug=debug)\n # after this the final predictions for the vlaidation set can be found in validation_folder_name_base + \"_postprocessed\"\n # They are always in that folder, even if no postprocessing as applied!\n\n # detemining postprocesing on a per-fold basis may be OK for this fold but what if another fold finds another\n # postprocesing to be better? In this case we need to consolidate. At the time the consolidation is going to be\n # done we won't know what self.gt_niftis_folder was, so now we copy all the niftis into a separate folder to\n # be used later\n gt_nifti_folder = join(self.output_folder_base, \"gt_niftis\")\n maybe_mkdir_p(gt_nifti_folder)\n for f in subfiles(self.gt_niftis_folder, suffix=\".nii.gz\"):\n success = False\n attempts = 0\n while not success and attempts < 10:\n try:\n shutil.copy(f, gt_nifti_folder)\n success = True\n except OSError:\n attempts += 1\n sleep(1)\n\n self.network.train(current_mode)\n export_pool.close()\n export_pool.join()"
] | [
[
"torch.cuda.is_available"
],
[
"torch.nn.Sequential",
"torch.cat",
"numpy.arange",
"torch.nn.ModuleList",
"torch.rand",
"numpy.prod",
"numpy.array",
"numpy.vstack"
],
[
"torch.device"
],
[
"matplotlib.use",
"numpy.load",
"numpy.save",
"numpy.prod"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mohcineelharras/yolo-mask | [
"3a163b3534dae9507d4b2e39170b0fe6abcd5e8d"
] | [
"train.py"
] | [
"\"\"\"\nRetrain the YOLO model for your own dataset.\n\"\"\"\n\nimport numpy as np\nimport keras.backend as K\nfrom keras.layers import Input, Lambda\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\n\nfrom yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss\nfrom yolo3.utils import get_random_data\n\n\ndef _main():\n annotation_path = './data/train.txt'\n log_dir = 'logs/002/'\n classes_path = 'model_data/coco_classes.txt'\n anchors_path = 'model_data/yolo_anchors.txt'\n class_names = get_classes(classes_path)\n num_classes = len(class_names)\n anchors = get_anchors(anchors_path)\n\n input_shape = (256,256) # multiple of 32, hw\n\n is_tiny_version = len(anchors)==6 # default setting\n if is_tiny_version:\n model = create_tiny_model(input_shape, anchors, num_classes,\n freeze_body=2, weights_path='model_data/tiny_yolo_weights.h5')\n else:\n model = create_model(input_shape, anchors, num_classes,\n freeze_body=2, weights_path='logs/000/ep048-loss19.960-val_loss23.728.h5') # make sure you know what you freeze\n\n logging = TensorBoard(log_dir=log_dir)\n checkpoint = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5',\n monitor='val_loss', save_weights_only=True, save_best_only=True, period=5)\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1)\n early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)\n\n val_split = 0.1\n with open(annotation_path) as f:\n lines = f.readlines()\n np.random.seed(10101)\n np.random.shuffle(lines)\n np.random.seed(None)\n num_val = int(len(lines)*val_split)\n num_train = len(lines) - num_val\n\n # Train with frozen layers first, to get a stable loss.\n # Adjust num epochs to your dataset. This step is enough to obtain a not bad model.\n if True:\n model.compile(optimizer=Adam(lr=1e-3), loss={\n # use custom yolo_loss Lambda layer.\n 'yolo_loss': lambda y_true, y_pred: y_pred})\n\n batch_size = 16\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))\n model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n steps_per_epoch=max(1, num_train//batch_size),\n validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),\n validation_steps=max(1, num_val//batch_size),\n epochs=5,\n initial_epoch=0,\n callbacks=[logging, checkpoint])\n model.save_weights(log_dir + 'trained_weights_stage_1.h5')\n\n # Unfreeze and continue training, to fine-tune.\n # Train longer if the result is not good.\n if True:\n for i in range(len(model.layers)):\n model.layers[i].trainable = True\n model.compile(optimizer=Adam(lr=1e-4), loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change\n print('Unfreeze all of the layers.')\n\n batch_size = 16 # note that more GPU memory is required after unfreezing the body\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))\n model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n steps_per_epoch=max(1, num_train//batch_size),\n validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),\n validation_steps=max(1, num_val//batch_size),\n epochs=25,\n initial_epoch=5,\n callbacks=[logging, checkpoint, reduce_lr, early_stopping])\n model.save_weights(log_dir + 'trained_weights_final.h5')\n\n # Further training if needed.\n\n\ndef get_classes(classes_path):\n '''loads the classes'''\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\ndef get_anchors(anchors_path):\n '''loads the anchors from a file'''\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\n\ndef create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,\n weights_path='model_data/yolo_weights.h5'):\n '''create the training model'''\n #K.clear_session() # get a new session\n image_input = Input(shape=(None, None, 3))\n h, w = input_shape\n num_anchors = len(anchors)\n\n y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \\\n num_anchors//3, num_classes+5)) for l in range(3)]\n\n model_body = yolo_body(image_input, num_anchors//3, num_classes)\n print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))\n\n if load_pretrained:\n model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)\n print('Load weights {}.'.format(weights_path))\n if freeze_body in [1, 2]:\n # Freeze darknet53 body or freeze all but 3 output layers.\n num = (185, len(model_body.layers)-3)[freeze_body-1]\n for i in range(num): model_body.layers[i].trainable = False\n print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))\n\n model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',\n arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})(\n [*model_body.output, *y_true])\n model = Model([model_body.input, *y_true], model_loss)\n\n return model\n\ndef create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,\n weights_path='model_data/tiny_yolo_weights.h5'):\n '''create the training model, for Tiny YOLOv3'''\n K.clear_session() # get a new session\n image_input = Input(shape=(None, None, 3))\n h, w = input_shape\n num_anchors = len(anchors)\n\n y_true = [Input(shape=(h//{0:32, 1:16}[l], w//{0:32, 1:16}[l], \\\n num_anchors//2, num_classes+5)) for l in range(2)]\n\n model_body = tiny_yolo_body(image_input, num_anchors//2, num_classes)\n print('Create Tiny YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))\n\n if load_pretrained:\n model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)\n print('Load weights {}.'.format(weights_path))\n if freeze_body in [1, 2]:\n # Freeze the darknet body or freeze all but 2 output layers.\n num = (20, len(model_body.layers)-2)[freeze_body-1]\n for i in range(num): model_body.layers[i].trainable = False\n print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))\n\n model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',\n arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.7})(\n [*model_body.output, *y_true])\n model = Model([model_body.input, *y_true], model_loss)\n\n return model\n\ndef data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):\n '''data generator for fit_generator'''\n n = len(annotation_lines)\n i = 0\n while True:\n image_data = []\n box_data = []\n for b in range(batch_size):\n if i==0:\n np.random.shuffle(annotation_lines)\n image, box = get_random_data(annotation_lines[i], input_shape, random=True)\n image_data.append(image)\n box_data.append(box)\n i = (i+1) % n\n image_data = np.array(image_data)\n box_data = np.array(box_data)\n y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)\n yield [image_data, *y_true], np.zeros(batch_size)\n\ndef data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes):\n n = len(annotation_lines)\n if n==0 or batch_size<=0: return None\n return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)\n\nif __name__ == '__main__':\n _main()\n"
] | [
[
"numpy.random.shuffle",
"numpy.array",
"numpy.zeros",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AthanatiusC/Python-face-recognition-V2 | [
"cbb3908448e2575e2cd10294add8ec58ced43be0"
] | [
"register/register.py"
] | [
"\"\"\"Demo code shows how to estimate human head pose.\nCurrently, human face is detected by a detector from an OpenCV DNN module.\nThen the face box is modified a little to suits the need of landmark\ndetection. The facial landmark detection is done by a custom Convolutional\nNeural Network trained with TensorFlow. After that, head pose is estimated\nby solving a PnP problem.\n\"\"\"\nfrom argparse import ArgumentParser\n# from multiprocessing import Process, Queue\nfrom queue import Queue\nfrom threading import Thread\n\nimport cv2\nimport numpy as np\nimport PySimpleGUI as sg\nfrom mark_detector import MarkDetector\nfrom os_detector import detect_os\nfrom pose_estimator import PoseEstimator\nfrom stabilizer import Stabilizer\nimport os\nfrom align import AlignDlib\nimport requests\nimport json\n\nalignment = AlignDlib('models\\\\landmarks.dat')\ndef align_image(img):\n return alignment.align(96, img, alignment.getLargestFaceBoundingBox(img), \n landmarkIndices=AlignDlib.OUTER_EYES_AND_NOSE)\n\nprint(\"OpenCV version: {}\".format(cv2.__version__))\n\n# multiprocessing may not work on Windows and macOS, check OS for safety.\n# detect_os()\n\n\nclass Register:\n def __init__(self):\n self.imagelist = []\n self.CNN_INPUT_SIZE = 128\n self.central = 0\n self.right = 0\n self.left = 0\n self.down = 0\n self.up = 0\n self.min_sample = 4\n self.capture = False\n self.path = \"\"\n self.user_id = \"\"\n self.protoPath = os.path.join(\"models\", \"deploy.prototxt\")\n self.modelPath = os.path.join(\"models\",\n \"res10_300x300_ssd_iter_140000.caffemodel\")\n self.embeddings = []\n\n self.protoPath = os.path.join(\"models\", \"deploy.prototxt\")\n self.modelPath = os.path.join(\"models\",\n \"res10_300x300_ssd_iter_140000.caffemodel\")\n\n self.detector = cv2.dnn.readNetFromCaffe(self.protoPath, self.modelPath)\n self.embedder = cv2.dnn.readNetFromTorch(\"models/openface_nn4.small2.v1.t7\")\n\n self.embedder.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\n self.embedder.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n\n self.detector.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\n self.detector.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n\n self.alignment = AlignDlib('models\\\\landmarks.dat')\n self.failed = False\n\n sg.change_look_and_feel('Material2')\n layout = [\n [sg.Image(filename='D:\\\\Athanatius\\\\Pictures\\\\faceid.png', key='-IMAGE-', tooltip='Enter NIK or NIS and hit register to start')],\n [sg.Text(\"Please Enter your NIK or NIS below\")],\n [sg.Text('NIS or NIK : '), sg.InputText()],\n [sg.Button('Register'), sg.Button('Cancel')]\n ]\n self.window = sg.Window('Register - CyberNet Facial Recognition', layout, location=(250,250),) # if trying Qt, you will need to remove this right click menu\n self.window.Finalize()\n\n def align_image(self,img):\n return alignment.align(96, img, alignment.getLargestFaceBoundingBox(img), \n landmarkIndices=AlignDlib.OUTER_EYES_AND_NOSE)\n \n def Verify(self,directory):\n images = os.listdir(directory)\n for path in images:\n frame = cv2.imread(os.path.join(directory,path))\n try:\n (h, w) = frame.shape[:2]\n except:\n continue\n imageBlob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), swapRB=False, crop=False)\n self.detector.setInput(imageBlob)\n detections = self.detector.forward()\n for i in range(0, detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n if confidence > 0.7:\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n y = startY - 10 if startY - 10 > 10 else startY + 10\n try:\n # face = frame[startY-10:endY+10, startX-10:endX+10]\n (h,w) =frame.shape[:2]\n aligned = self.align_image(frame)\n faceBlob = cv2.dnn.blobFromImage(aligned, 1.0 / 255,\n (96, 96), (0, 0, 0), swapRB=True, crop=False)\n self.embedder.setInput(faceBlob)\n vec = self.embedder.forward()\n print(np.array(vec[0]).astype(\"float64\").tolist())\n self.embeddings.append(np.array(vec[0]).astype(\"float64\").tolist())\n cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 4)\n # self.window['-IMAGE-'].update(data=cv2.imencode('.png', frame)[1].tobytes())\n except Exception as e:\n print(e)\n pass\n k = cv2.waitKey(5) & 0xFF\n if k == 27 or len(self.embeddings) == 20:\n cv2.destroyAllWindows()\n break\n try:\n print(self.embeddings)\n r = requests.post(url=\"http://192.168.1.12:8088/api/v2/user/verify\",json= {\"user_id\":int(self.user_id),\"embeddings\":np.array(self.embeddings).astype(\"float64\").tolist()})\n print(r.json())\n except:\n sg.Popup(\"Register Failed! Api not Online!\")\n self.failed = True\n try:\n os.remove(self.path)\n except:\n print(\"Cannot remove folder! please remove folder manually! :{}\".format(self.path))\n self.window['-IMAGE-'].Update(data=self.noimage)\n\n def get_face(self,detector, img_queue, box_queue):\n \"\"\"Get face from image queue. This function is used for multiprocessing\"\"\"\n while True:\n image = img_queue.get()\n box = detector.extract_cnn_facebox(image)\n box_queue.put(box)\n\n def get_interface(self,x, y, z):\n if x > 0.45:\n horizontal = \"Right\"\n elif x < -0.45:\n horizontal = \"Left\"\n else:\n horizontal= \"Center\"\n if y > 0.35:\n vertical = \"Down\"\n elif y < -0.1:\n vertical = \"Up\"\n else:\n vertical = \"Center\"\n return vertical, horizontal\n \n def auto_sort_save(self,vertical,horizontal, face):\n if vertical == \"Center\" and horizontal == \"Center\" and self.central < self.min_sample:\n self.central +=1\n cv2.imwrite(os.path.join(self.path,\"sample_central_{}.jpg\".format(self.central)),face)\n self.imagelist.append(face)\n elif vertical == \"Down\" and horizontal == \"Center\" and self.down < self.min_sample:\n self.down +=1\n cv2.imwrite(os.path.join(self.path,\"sample_down_{}.jpg\".format(self.down)), face)\n self.imagelist.append(face)\n elif vertical == \"Up\" and horizontal == \"Center\" and self.up < self.min_sample:\n self.up +=1\n cv2.imwrite(os.path.join(self.path, \"sample_up_{}.jpg\".format(self.up)), face)\n self.imagelist.append(face)\n elif vertical == \"Center\" and horizontal == \"Left\" and self.left < self.min_sample:\n self.left +=1\n cv2.imwrite(os.path.join(self.path, \"sample_left_{}.jpg\".format(self.left)), face)\n self.imagelist.append(face)\n elif vertical == \"Center\" and horizontal == \"Right\" and self.right < self.min_sample:\n self.right +=1\n cv2.imwrite(os.path.join(self.path,\"sample_right_{}.jpg\".format(self.right)),face)\n self.imagelist.append(face)\n # else:\n # exit(0)\n \n\n def main(self):\n \"\"\"MAIN\"\"\"\n # Video source from webcam or video file.\n video_src = 0\n\n cap = cv2.VideoCapture(video_src)\n if video_src == 0:\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n _, sample_frame = cap.read()\n\n # Introduce mark_detector to detect landmarks.\n mark_detector = MarkDetector()\n\n # Setup process and queues for multiprocessing.\n img_queue = Queue()\n box_queue = Queue()\n img_queue.put(sample_frame)\n box_process = Thread(target=self.get_face, args=(\n mark_detector, img_queue, box_queue,))\n box_process.start()\n # Introduce pose estimator to solve pose. Get one frame to setup the\n # estimator according to the image size.\n height, width = sample_frame.shape[:2]\n pose_estimator = PoseEstimator(img_size=(height, width))\n # Introduce scalar stabilizers for pose.\n pose_stabilizers = [Stabilizer(\n state_num=2,\n measure_num=1,\n cov_process=0.1,\n cov_measure=0.1) for _ in range(6)]\n\n tm = cv2.TickMeter()\n self.noimage =cv2.imread(\"D:\\\\Athanatius\\\\Pictures\\\\faceid.png\")\n self.noimage =cv2.imencode('.png', self.noimage)[1].tobytes()\n\n while True:\n # print(img_queue.qsize())\n # print(self.capture)\n event, values = self.window.read(timeout=20)\n if event in (None, \"Cancel\"):\n os._exit(0)\n if event in (None, \"Register\"):\n self.path = os.path.join(\"sample\",values[0])\n self.user_id = values[0]\n try:\n os.mkdir(self.path)\n self.capture = True\n except:\n sg.Popup(\"FaceID of this person already existed!\")\n self.window['-IMAGE-'].Update(data=self.noimage)\n # pass\n if self.capture:\n \n # Read frame, crop it, flip it, suits your needs.\n frame_got, frame = cap.read()\n if frame_got is False:\n break\n original = frame\n if video_src == 0:\n frame = cv2.flip(frame, 2)\n img_queue.put(frame)\n facebox = box_queue.get()\n if facebox is not None:\n # Detect landmarks from image of 128x128.\n face_img = frame[facebox[1]: facebox[3],\n facebox[0]: facebox[2]]\n face_img = cv2.resize(face_img, (self.CNN_INPUT_SIZE, self.CNN_INPUT_SIZE))\n face_img = cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB)\n\n tm.start()\n marks = mark_detector.detect_marks([face_img])\n tm.stop()\n\n # Convert the marks locations from local CNN to global image.\n marks *= (facebox[2] - facebox[0])\n marks[:, 0] += facebox[0]\n marks[:, 1] += facebox[1]\n\n # Uncomment following line to show raw marks.\n mark_detector.draw_marks(\n frame, marks, color=(0, 255, 0))\n\n # Uncomment following line to show facebox.\n # mark_detector.draw_box(frame, [facebox])\n\n # Try pose estimation with 68 points.\n pose = pose_estimator.solve_pose_by_68_points(marks)\n\n # Stabilize the pose.\n steady_pose = []\n pose_np = np.array(pose).flatten()\n for value, ps_stb in zip(pose_np, pose_stabilizers):\n ps_stb.update([value])\n steady_pose.append(ps_stb.state[0])\n steady_pose = np.reshape(steady_pose, (-1, 3))\n pose_estimator.draw_annotation_box(\n frame, steady_pose[0], steady_pose[1], color=(128, 255, 128))\n\n x = steady_pose[0][0]\n y = steady_pose[0][1]\n z = steady_pose[0][2]\n\n vertical,horizontal = self.get_interface(x,y,z)\n face_img = cv2.cvtColor(face_img,cv2.COLOR_RGB2BGR)\n self.auto_sort_save(vertical,horizontal,face_img)\n # print(x)\n cv2.putText(frame,\"horizontal : {} vertical : {} \".format(horizontal,vertical),(100,100),cv2.FONT_HERSHEY_TRIPLEX,0.6,(0,255,0),1)\n # Uncomment following line to draw head axes on frame.\n # pose_estimator.draw_axes(frame, stabile_pose[0], stabile_pose[1])\n\n # Show preview.\n self.window['-IMAGE-'].update(data=cv2.imencode('.png', frame)[1].tobytes())\n # cv2.imshow(\"Preview\", frame)\n if self.central == self.min_sample and self.up == self.min_sample and self.left == self.min_sample and self.right == self.min_sample and self.down == self.min_sample:\n self.capture = False\n self.up = 0\n self.down = 0\n self.left = 0\n self.right = 0\n self.Verify(self.path)\n if not self.failed:\n self.window['-IMAGE-'].Update(data=self.noimage)\n sg.Popup(\"FaceID successfully Registered!\\nYou may add more FaceID!\")\n\n # Clean up the multiprocessing process.\n # box_process.terminate()\n box_process.join()\n self.window.Close()\n\n\nif __name__ == '__main__':\n register = Register()\n register.main()\n"
] | [
[
"numpy.reshape",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Busdriver26/walkingin | [
"6401127fc2e3159bc19892c1d6b74246535cd880"
] | [
"main.py"
] | [
"print('{:*^80}'.format(\" WALKING IN \"))\nprint(\"AUTHOR: BU5DR1V3R , INSPIRED BY ULTRA GUO.\")\nprint(\"Version -0.03, 2020/12/14\")\nprint(\"Make sure that your pic is in the same folder of this .exe\")\n\ntry:\n from PIL import Image, ImageDraw, ImageFont\nexcept:\n print(\"There is no PIL found in your environment.Please install it first.\")\n input(\"Press <enter>\")\n quit()\nimport os,sys\ntry:\n import numpy as np\n from matplotlib import cm\n import matplotlib.pyplot as plt\nexcept:\n print(\"There is no numpy or matplotlib found in your environment.Please install it first.\")\n input(\"Press <enter>\")\n quit()\nfrom queue import Queue\n\nmax_row = 999\nmax_col = 999\nq = Queue()\nflag = np.full((1,3),0)\nnew_array = []\nmax_step = 0\noutput = np.full((1,3),0)\n\npt = os.path.dirname(sys.argv[0])\nif pt!= '':\n os.chdir(os.path.dirname(sys.argv[0]))\nos.getcwd()\n\npathLoad = input(\"Please input the name of your picture:(e.g. test.jpg, default:1.jpg)\")\nif len(pathLoad)<=4:\n pathLoad = \"1.jpg\"\ntry:\n img = Image.open(pathLoad).convert('RGB')\nexcept:\n print(\"Wrong path.Try again!\")\n input(\"Press <enter>\")\n quit()\npathSave = input(\"Please input the name of the output picture:(e.g. out.jpg, default:1-out.jpg)\")\nif len(pathSave)<=4:\n pathSave = \"1-out.jpg\"\ntry:\n print(\"*When you see the picture is 1234X5678, the 5678 is ROW and 1234 is COL\")\n rowEnterPoint = int(input(\"Please input the ROW enter point:(e.g.123,default:0)\"))\n colEnterPoint = int(input(\"Please input the COLUMN enter point:(e.g.456,default:0)\"))\nexcept:\n rowEnterPoint = 0\n colEnterPoint = 0\n\ndef change(row,col,point):\n new_point = [(row,col),point,0]\n return new_point\n \ndef findEntry(array):\n global rowEnterPoint\n global colEnterPoint\n if array[rowEnterPoint][colEnterPoint][1] == [255,255,255]:\n print(array[rowEnterPoint][colEnterPoint])\n for row in array:\n for col in row:\n if col[1][0]!=[255,255,255]:\n rowEnterPoint = col[0][0]\n colEnterPoint = col[0][1]\n return\n print(\"ERROR:ALL WHITE.\")\n input(\"Press <enter>\")\n quit()\n return\n\ndef inq(x,y,step):\n global q\n global flag\n global new_array\n global max_col\n global max_row\n global output\n if x<max_row and x>=0 and y<max_col and y>=0:\n if flag[x][y] == 0:\n flag[x][y] = 1\n if new_array[x][y][1] != [255,255,255]:\n new_array[x][y][2] = step + 1\n q.put(new_array[x][y])\n return\n\ndef walk():\n global q\n global flag\n global new_array\n global max_step\n ele = q.get()\n loc_x,loc_y = ele[0]\n step = ele[2]\n inq(loc_x+1,loc_y,step)\n inq(loc_x-1,loc_y,step)\n inq(loc_x,loc_y+1,step)\n inq(loc_x,loc_y-1,step)\n if step>max_step:\n max_step = step\n return\n \ndef main(pathLoad,pathSave):\n global flag\n global q\n global max_col\n global max_row\n global new_array\n global output\n global max_step\n img = Image.open(pathLoad).convert('RGB')\n array = np.array(img)\n array = array.tolist()\n while True:\n if array[rowEnterPoint][colEnterPoint] == [255,255,255]:\n print(\"You have chosen a white pixel,please try again.\")\n input(\"Press <enter>\")\n quit()\n else:\n break\n max_col = len(array[0])\n max_row = len(array)\n if rowEnterPoint<0 or rowEnterPoint>=max_row or colEnterPoint<0 or colEnterPoint>=max_col:\n print(\"row or col out of range, please check your input!\")\n input(\"Press <enter>\")\n quit()\n output = np.array(img)\n flag = np.full((max_row,max_col),0)\n for i in range(max_row):\n temp_row = []\n for j in range(max_col):\n temp_row.append(change(i,j,array[i][j]))\n new_array.append(temp_row)\n findEntry(new_array)\n q.put(new_array[rowEnterPoint][colEnterPoint])\n print(\"Drawing the route...\")\n while not q.empty():\n walk()\n print(\"Drawing done. Now outputing pic.\")\n cmap = cm.get_cmap('plasma')\n color = cmap([int(i/(max_step+1)*255) for i in range(max_step+1)])\n new_color = []\n for i in color:\n new_color.append([int(i[0]*255),int(i[1]*255),int(i[2]*255)])\n new_color = np.array(new_color)\n for i in range(max_row):\n for j in range(max_col):\n if output[i][j][0]!=255 and output[i][j][1]!=255 and output[i][j][2]!=255:\n output[i][j][0] = new_color[new_array[i][j][2]][0]\n output[i][j][1] = new_color[new_array[i][j][2]][1]\n output[i][j][2] = new_color[new_array[i][j][2]][2]\n img_tr = Image.fromarray(output).convert('RGB')\n img_tr.save(pathSave)\n print(\"done\")\n input(\"Press <enter>\")\n quit()\n return\n\nmain(pathLoad,pathSave)"
] | [
[
"numpy.array",
"matplotlib.cm.get_cmap",
"numpy.full"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yugangzhang/SciAnalysis | [
"06f20143ad40bbd6756fcdb5d2aade8823bffb9a"
] | [
"examples/history/make_map_sequence.py"
] | [
"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n# This generates a map (2D false-color plot or 3D height plot) for a set of\n# experiments (that are presumptively defined in some (x,y) space). The code\n# assumes you've already used SciAnalysis to process your data, such that you\n# have XML files in your \"results\" sub-folder with the analysis results of\n# interest. This code then compiles that data and generates the plot.\n\n# The code can also be used to generate an animation of the sequence of\n# measurements during the experiment.\n\n\n# Imports\n########################################\n\nimport sys, os\nSciAnalysis_PATH='/home/kyager/current/code/SciAnalysis/main/'\nSciAnalysis_PATH in sys.path or sys.path.append(SciAnalysis_PATH)\n\nimport glob\nimport numpy as np\nimport re\n\nfrom SciAnalysis import tools\nfrom SciAnalysis.Data import *\n#from SciAnalysis.XSAnalysis.Data import *\n#from SciAnalysis.XSAnalysis import Protocols\n\n\n# Settings\n########################################\nverbosity = 3\npattern = 'PWM_sample_AM3' # Files to consider\nsource_dir = '../' # The location of the SciAnalysis outputs\noutput_dir = './{}/'.format(pattern)\ntools.make_dir(output_dir)\n\n\n\n\n\n# Helpers\n########################################\n\nfilename_re = re.compile('(.+)_x(-?\\d+\\.\\d+)_yy(-?\\d+\\.\\d+)_.+_(\\d+)_saxs\\.xml')\ndef parse_filename(filename, verbosity=3):\n \n parsed = {'filename' : filename}\n m = filename_re.match(filename)\n if m:\n parsed['basename'] = m.groups()[0]\n parsed['x'] = float(m.groups()[1])\n parsed['y'] = float(m.groups()[2])\n parsed['scan_id'] = int(m.groups()[-1])\n \n else:\n if verbosity>=2:\n print(\"WARNING: RE doesn't match for {}\".format(filename))\n \n return parsed\n \n\ndef val_stats(values, name='z'):\n span = np.max(values)-np.min(values)\n print(\" {} = {:.2g} ± {:.2g} (span {:.2g}, from {:.2g} to {:.2g})\".format(name, np.average(values), np.std(values), span, np.min(values), np.max(values)))\n \n \ndef power_N_list(N_max, N_min=3, num=40, exponent=3.0):\n '''Generates a list of integers that are spread out more logarithmically.\n That is, the list starts with small increments between integers, but finishes\n with large increments.'''\n \n #N_list = ( (np.exp( np.linspace(0, 1, num=40) ) - 1)/(np.exp(1)-1) )*len(z_vals)\n x = np.linspace(0, 1, num=num)\n N_list = np.power(x, exponent)*(N_max-N_min) + N_min\n N_list = np.unique(N_list.astype(int))\n #N_list = N_list[ (N_list>=N_min) & (N_list<=N_max) ] # Unnecessary\n \n return N_list\n \n\n\n# Extract results from xml files\n########################################\nfrom SciAnalysis.Result import * # Results() object\ndef extract_results(infiles, extractions, outfile, verbosity=3):\n if verbosity>=3:\n print(\"Extracting results for {} infiles...\".format(len(infiles)))\n \n results = Results().extract_multi_save_txt(outfile, infiles, extractions, verbosity=verbosity)\n \n return results\n\n\n\n\n# Results\n########################################\n\ndef load_file(infile, verbosity=3):\n if verbosity>=3:\n print(\" Loading data from file: {}\".format(infile))\n if verbosity>=4:\n print('Saved data has {} columns:'.format(len(names)))\n print(names)\n \n with open(infile, 'r') as fin:\n names = fin.readline().split()\n lines = fin.readlines()\n \n return names, lines\n\ndef load_results(names, lines, x_coord, y_coord, z_signal, sequence, verbosity=3):\n \n # Load results\n x_vals = []\n y_vals = []\n z_vals = []\n seq_vals = []\n \n signal_idx = names.index(z_signal)\n x_idx = names.index(x_coord)\n y_idx = names.index(y_coord)\n sequence_idx = names.index(sequence)\n \n if verbosity>=3:\n print(\" Plot signal: {} (column index {})\".format(z_signal, signal_idx))\n print(\" Plot x: {} (column index {})\".format(x_coord, x_idx))\n print(\" Plot y: {} (column index {})\".format(y_coord, y_idx))\n print(\" Sorting: {} (column index {})\".format(sequence, sequence_idx))\n \n \n for line in lines:\n els = line.split()\n if len(els)==len(names) and els[0][0]!='#' and els[signal_idx]!='-':\n x_vals.append(float(els[x_idx]))\n y_vals.append(float(els[y_idx]))\n z_vals.append(float(els[signal_idx]))\n seq_vals.append(int(float(els[sequence_idx])))\n else:\n if verbosity>=3:\n print(' Skipping line: {}'.format(line.strip()))\n \n \n if verbosity>=4:\n print(\" Nx, Ny, Nz = {}, {}, {}\".format(len(x_vals), len(y_vals), len(z_vals)))\n val_stats(z_vals, name='z')\n\n \n # Sort data\n indices = np.argsort(seq_vals)\n x_vals = np.asarray(x_vals)[indices]\n y_vals = np.asarray(y_vals)[indices]\n z_vals = np.asarray(z_vals)[indices]\n seq_vals = np.asarray(seq_vals)[indices]\n \n return x_vals, y_vals, z_vals, seq_vals\n\n\ndef trim_vals(vals_list, N_max, verbosity=3):\n \n trimmed_vals_list = []\n for i, vals in enumerate(vals_list):\n if N_max is not None and len(vals)>N_max:\n if verbosity>=4:\n print(' Reducing list {} to size N_max = {}'.format(i, N_max))\n vals = np.asarray(vals)[:N_max]\n trimmed_vals_list.append(vals)\n \n return trimmed_vals_list\n \n \n# Plot\n########################################\n \nimport SciAnalysis.colormaps as cmaps\nplt.register_cmap(name='viridis', cmap=cmaps.viridis)\nplt.register_cmap(name='magma', cmap=cmaps.magma)\nplt.register_cmap(name='inferno', cmap=cmaps.inferno)\nplt.register_cmap(name='plasma', cmap=cmaps.plasma)\nplt.set_cmap(cmaps.viridis) \n\nclass Data2D_current(Data2D):\n def _plot_extra(self, **plot_args):\n \n xi, xf, yi, yf = self.ax.axis()\n \n # Faded overlay\n rect = mpl.patches.Rectangle((xi,yi), xf-xi, yf-yi, linewidth=1, edgecolor='none', facecolor='white', alpha=self.alpha, zorder=10)\n self.ax.add_patch(rect) \n \n \n # Scatterplot\n cmap = plot_args['cmap'] if 'cmap' in plot_args else 'viridis'\n zmin = plot_args['zmin']\n zmax = plot_args['zmax']\n self.ax.scatter(self.x_vals, self.y_vals, s=100, c=self.z_vals, cmap=cmap, vmin=zmin, vmax=zmax, edgecolor='k', zorder=100)\n \n \n # Colorbar\n n = 5\n colorbar_labels = [ zmin + i*(zmax-zmin)/(n-1) for i in range(n) ]\n \n tick_positions = self._plot_z_transform(data=colorbar_labels, set_Z=False)\n cbar = self.fig.colorbar(self.im, ax=self.ax, ticks=tick_positions, fraction=0.056, pad=0.02)\n colorbar_labels = [\"{:.3g}\".format(c) for c in colorbar_labels]\n cbar.ax.set_yticklabels(colorbar_labels, size=18)\n \n # Titles\n size = plot_args['rcParams']['axes.labelsize']\n #size = plot_args['rcParams']['xtick.labelsize']\n plt.figtext(0, 1, '$N = {:,d}$'.format(len(self.z_vals)), size=size, weight='bold', verticalalignment='top', horizontalalignment='left')\n z_label = self.z_rlabel if self.z_rlabel is not None else self.z_label\n if z_label is not None:\n plt.figtext(1, 1, z_label, size=size, weight='bold', verticalalignment='top', horizontalalignment='right')\n \n #self.ax.set_aspect('equal', 'datalim')\n \n \n def _plot_extra3D(self, **plot_args):\n # Colorbar\n cbar = self.fig.colorbar(self.surf, ax=self.ax, aspect=40, fraction=0.02, pad=0.0)\n cbar.ax.yaxis.set_tick_params(labelsize=15)\n\n # Titles\n size = plot_args['rcParams']['axes.labelsize']\n #size = plot_args['rcParams']['xtick.labelsize']\n plt.figtext(0, 1, '$N = {:,d}$'.format(len(self.z_vals)), size=size, weight='bold', verticalalignment='top', horizontalalignment='left')\n z_label = self.z_rlabel if self.z_rlabel is not None else self.z_label\n if z_label is not None:\n plt.figtext(1, 1, z_label, size=size, weight='bold', verticalalignment='top', horizontalalignment='right')\n \n \n \ndef plot_results(x_vals, y_vals, z_vals, outfile, plot2d=True, plot3d=False, grid=None, dgrid=None, title=None, cmap='viridis', alpha=0.5, x_label='$x$', y_label='$y$', z_label=None, interpolate_cyclic=None, verbosity=3):\n \n if verbosity>=3:\n print(\"Plotting for {}\".format(outfile))\n val_stats(z_vals, name='z_vals')\n \n # Define grid for interpolation\n if grid is None:\n grid = [np.min(x_vals), np.max(x_vals), np.min(y_vals), np.max(y_vals)]\n if dgrid is None:\n dgrid = [ (grid[1]-grid[0])/200 , (grid[3]-grid[2])/200 ]\n if isinstance(dgrid, float):\n dgrid = [dgrid, dgrid]\n \n xi = np.arange(grid[0], grid[1]+dgrid[0], dgrid[0])\n yi = np.arange(grid[2], grid[3]+dgrid[1], dgrid[1])\n XI, YI = np.meshgrid(xi, yi)\n\n\n # Interpolation\n import scipy.interpolate\n POINTS = np.column_stack((x_vals,y_vals))\n VALUES = z_vals\n if verbosity>=4:\n print(\"Interpolating {:,} points to {:,}×{:,} = {:,} points\".format(len(VALUES), len(xi), len(yi), len(xi)*len(yi))) \n \n \n if interpolate_cyclic is not None:\n xlike = np.cos(VALUES*2*np.pi/interpolate_cyclic)\n ylike = np.sin(VALUES*2*np.pi/interpolate_cyclic)\n XLIKE = scipy.interpolate.griddata(POINTS, xlike, (XI, YI), method='linear')\n YLIKE = scipy.interpolate.griddata(POINTS, ylike, (XI, YI), method='linear')\n \n ZI = ( np.arctan2(YLIKE, XLIKE)/(2*np.pi) )*interpolate_cyclic\n ZI_mask = np.ma.masked_where( np.isnan(ZI), ZI)\n \n else: \n ZI = scipy.interpolate.griddata(POINTS, VALUES, (XI, YI), method='linear') # method='nearest' 'linear' 'cubic'\n ZI_mask = np.ma.masked_where( np.isnan(ZI), ZI)\n\n if verbosity>=4:\n val_stats(ZI, name='ZI')\n val_stats(ZI_mask, name='ZI_mask')\n \n d = Data2D_current()\n d.data = ZI_mask\n d.x_axis = xi\n d.y_axis = yi\n \n d.x_vals = x_vals\n d.y_vals = y_vals\n d.z_vals = z_vals\n\n\n d.set_z_display([None, None, 'linear', 1.0])\n d.x_rlabel = x_label\n d.y_rlabel = y_label\n d.z_rlabel = z_label\n \n if plot2d:\n d.plot_args['rcParams'] = { \n 'axes.labelsize': 50,\n 'xtick.labelsize': 40,\n 'ytick.labelsize': 40, \n }\n d.alpha = alpha\n\n \n d.plot(save=outfile, show=False, cmap=cmap, zmin=zmin, zmax=zmax, title=title, plot_buffers=[0.21, 0.12, 0.18, 0.10], plot_range=grid, plot_2D_type='pcolormesh', dpi=150, transparent=False)\n \n \n if plot3d:\n d.plot_args['rcParams'] = { \n 'axes.labelsize': 40,\n 'xtick.labelsize': 20,\n 'ytick.labelsize': 20, \n } \n d.X = XI\n d.Y = YI\n \n elev = 30\n azim = 30\n azim = 30-90\n \n #outfile = outfile[:-4]+'-3D.png'\n outfile = tools.Filename(outfile).path_append('3D')\n d.plot3D(save=outfile, show=False, cmap=cmap, zmin=zmin, zmax=zmax, title=title, plot_buffers=[0.05, 0.10, 0.05, 0.05], plot_range=grid, elev=elev, azim=azim, dpi=150, transparent=False)\n \n\ndef plot_grids(results, N_list, grid=[None, None, None, None], n_grid=200, plot2d=True, plot3d=False, cmap='viridis', x_label='$x \\, (\\mathrm{mm})$', y_label='$y \\, (\\mathrm{mm})$', z_label='$z$', interpolate_cyclic=None, verbosity=3):\n \n x_vals, y_vals, z_vals, seq_vals = results\n \n if grid[0] is None: grid[0] = np.min(x_vals)\n if grid[1] is None: grid[1] = np.max(x_vals)\n if grid[2] is None: grid[2] = np.min(y_vals)\n if grid[3] is None: grid[3] = np.max(y_vals)\n n_grid = [n_grid, n_grid]\n dgrid = [ (grid[1]-grid[0])/n_grid[0] , (grid[3]-grid[2])/n_grid[1] ]\n \n \n #N_list = [len(z_vals)] # Plot final value only\n \n for N in N_list:\n x_vals, y_vals, z_vals, seq_vals = trim_vals(results, N_max=N, verbosity=verbosity)\n if verbosity>=4:\n val_stats(z_vals, name='z_reduced') \n \n outfile = os.path.join(output_dir, signal, '{}-{}-N{:04d}.png'.format(pattern, signal, N))\n plot_results(x_vals, y_vals, z_vals, outfile=outfile, plot2d=plot2d, plot3d=plot3d, grid=grid, dgrid=dgrid, cmap=cmap, alpha=0.2, x_label=x_label, y_label=y_label, z_label=z_label, interpolate_cyclic=interpolate_cyclic, verbosity=verbosity)\n \n \n\ndef animated_gif(source_dir='./', pattern='*.png', outfile=None, skip=None, verbosity=3):\n \n # If you get a 'cache resources exhausted' error, you can increase the cache sizes:\n # sudo nano /etc/ImageMagick-6/policy.xml \n \n if verbosity>=3:\n print('Generating animated gif for {}/{}'.format(source_dir, pattern))\n \n # Select the files to animate\n infiles = glob.glob(os.path.join(source_dir, pattern))\n if verbosity>=3:\n print(' {} infiles'.format(len(infiles)))\n \n \n infiles.sort()\n \n if skip is not None:\n infiles = infiles[0::skip]\n \n \n if outfile is None:\n outfile = os.path.join(source_dir, 'anim.gif')\n elif outfile[-4:]!='.gif':\n outfile = outfile+'.gif'\n\n # Prepare command\n # (Animation is generated using imagemagick 'convert' bash command.)\n\n #cmd = \"convert -delay 20 -resize 50% -fill white -undercolor '#00000080' -gravity NorthWest -annotate +0+5 ' Text ' \"\n #cmd = \"convert -delay 15 -loop 1 -resize 50% \"\n #cmd = \"convert -crop 450x450+60+220 +repage -delay 15 -loop 1 -resize 50% \"\n cmd = \"convert -dispose previous +repage -delay 30 -loop 1 -resize 30% \"\n \n for infile in infiles:\n cmd += '{} '.format(infile)\n \n cmd += ' {}'.format(outfile)\n\n # Execute command\n print(' Saving {}'.format(outfile))\n os.system(cmd)\n \n # Add a white background\n #cmd = 'convert {} -coalesce -background white -alpha remove {}'.format(outfile, outfile[:-4]+'w.gif')\n #os.system(cmd)\n \n \n \n \n# Run\n########################################\n \n# Extract results from XML files\nresults_dir = source_dir + '/results/' # Location of xml files\ninfiles = glob.glob(os.path.join(results_dir, '{}*.xml'.format(pattern)))\noutfile = os.path.join(output_dir, '{}-extracted.txt'.format(pattern))\n\n\nextractions = [ [ 'metadata_extract', ['x_position', 'y_position', 'sequence_ID'] ] ,\n ['linecut_angle_fit', ['fit_eta_eta', 'orientation_factor', 'orientation_angle', 'fit_eta_span_prefactor'] ],\n ]\nextractions = [ [ 'metadata_extract', ['x_position', 'y_position', 'sequence_ID'] ] ,\n ['circular_average_q2I', ['fit_peaks_prefactor1', 'fit_peaks_x_center1', 'fit_peaks_sigma1', 'fit_peaks_chi_squared', 'fit_peaks_d0', 'fit_peaks_grain_size' ] ],\n ] \n\nresults = extract_results(infiles, extractions, outfile=outfile, verbosity=verbosity)\n\n\n# Plot results\nx_coord, x_label = 'metadata_extract__x_position', '$x \\, (\\mathrm{mm})$'\ny_coord, y_label = 'metadata_extract__y_position', '$y \\, (\\mathrm{mm})$'\nsequence = 'metadata_extract__sequence_ID'\n\n\n\nsignals = [\n [ 'linecut_angle_fit__fit_eta_eta', r'$\\eta$', 0, 1, 'inferno' ],\n [ 'linecut_angle_fit__orientation_factor', r'$f_{\\mathrm{ori}}$', -1, 1, 'gray' ],\n [ 'linecut_angle_fit__orientation_angle', r'$\\chi \\, (\\mathrm{^{\\circ}})$', -90, 90, cmap_cyclic_rb ],\n [ 'linecut_angle_fit__fit_eta_span_prefactor', r'$p \\, (\\mathrm{a.u.})$', 10, 120, cmap_vge ],\n ]\n\n\nsignals = [\n #[ 'circular_average_q2I__fit_peaks_x_center1', '$q_0 \\, (\\mathrm{\\AA^{-1}})$', 0.0129, 0.0138, 'viridis' ],\n #[ 'circular_average_q2I__fit_peaks_d0', '$d_0 \\, (\\mathrm{nm})$', 35, 62, 'viridis' ],\n #[ 'circular_average_q2I__fit_peaks_sigma1', r'$\\sigma_0 \\, (\\mathrm{\\AA^{-1}})$', 0.001, 0.005, 'inferno' ],\n [ 'circular_average_q2I__fit_peaks_grain_size', r'$\\xi \\, (\\mathrm{nm})$', 100, 300, 'inferno' ],\n #[ 'circular_average_q2I__fit_peaks_prefactor1', '$p \\, (\\mathrm{a.u.})$', 0.0, 0.003, cmap_vge ],\n #[ 'circular_average_q2I__fit_peaks_chi_squared', '$\\chi^2\\, (\\mathrm{a.u.})$', 0.000, 1e-6, 'plasma' ],\n ]\n\n\n# Transform coordinates\ndef coord_transform(results, x_label, y_label):\n return results, x_label, y_label\n\ndef _coord_transform(results, x_label, y_label):\n x_vals, y_vals, z_vals, seq_vals = results\n \n x_vals = (x_vals/50)*(200-140) + 140 # thickness\n y_vals = ((y_vals+50)/50)*(200-30) + 30 # Temperature\n \n results = x_vals, y_vals, z_vals, seq_vals\n return results, '$T \\, (\\mathrm{^{\\circ}C})$', '$h \\, (\\mathrm{nm})$'\n\n\nnames, lines = load_file(outfile, verbosity=verbosity)\n\nfor signal in signals:\n \n z_signal, z_label, zmin, zmax, cmap = signal\n protocol, signal = z_signal.split('__')\n\n grid = [None, None, None, None]\n #grid = [None, None, None, 130]\n\n if verbosity>=3:\n print(\"========================================\")\n print(\"Plotting signal {}...\".format(signal))\n print(\"========================================\")\n\n tools.make_dir(os.path.join(output_dir,signal))\n tools.make_dir(os.path.join(output_dir,signal,'3D'))\n \n results = load_results(names, lines, x_coord=x_coord, y_coord=y_coord, z_signal=z_signal, sequence=sequence, verbosity=verbosity)\n results, x_label, y_label = coord_transform(results, x_label, y_label)\n x_vals, y_vals, z_vals, seq_vals = results\n \n \n # Single result\n if True:\n plot_grids(results, [len(z_vals)], grid=grid, n_grid=200, plot2d=True, plot3d=False, cmap=cmap, x_label=x_label, y_label=y_label, z_label=z_label, verbosity=verbosity)\n plot_grids(results, [len(z_vals)], grid=grid, n_grid=40, plot2d=False, plot3d=True, cmap=cmap, x_label=x_label, y_label=y_label, z_label=z_label, verbosity=verbosity)\n\n\n # Sequence of results\n if True:\n # 2D plots\n N_spacing = 50\n N_list = np.arange(N_spacing, len(z_vals), N_spacing)\n N_list = power_N_list(len(z_vals), num=140, exponent=5.0)\n plot_grids(results, N_list, grid=grid, n_grid=200, plot2d=True, plot3d=False, cmap=cmap, x_label=x_label, y_label=y_label, z_label=z_label, verbosity=verbosity)\n \n # 3D plots\n plot_grids(results, N_list, grid=grid, n_grid=40, plot2d=False, plot3d=True, cmap=cmap, x_label=x_label, y_label=y_label, z_label=z_label, verbosity=verbosity)\n \n \n # Animated gif\n if True:\n outfile = os.path.join(output_dir, '{}-{}.gif'.format(pattern, signal))\n animated_gif(source_dir=os.path.join(output_dir, signal), outfile=outfile, verbosity=verbosity)\n\n outfile = os.path.join(output_dir, '{}-{}-3D.gif'.format(pattern, signal))\n animated_gif(source_dir=os.path.join(output_dir, signal, '3D'), outfile=outfile, verbosity=verbosity)\n\n\n\n\n \n"
] | [
[
"numpy.linspace",
"numpy.min",
"numpy.asarray",
"numpy.arange",
"numpy.power",
"numpy.isnan",
"numpy.cos",
"numpy.average",
"numpy.sin",
"numpy.arctan2",
"numpy.max",
"numpy.std",
"numpy.column_stack",
"numpy.argsort",
"numpy.meshgrid"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
frankwhzhang/Paddle | [
"131b1dc3240e53ea295cc49323bb2a7e7dcc717f",
"131b1dc3240e53ea295cc49323bb2a7e7dcc717f",
"131b1dc3240e53ea295cc49323bb2a7e7dcc717f",
"131b1dc3240e53ea295cc49323bb2a7e7dcc717f",
"131b1dc3240e53ea295cc49323bb2a7e7dcc717f",
"131b1dc3240e53ea295cc49323bb2a7e7dcc717f",
"131b1dc3240e53ea295cc49323bb2a7e7dcc717f"
] | [
"python/paddle/fluid/tests/unittests/test_bilinear_interp_op.py",
"python/paddle/fluid/tests/unittests/test_sequence_topk_avg_pooling.py",
"python/paddle/fluid/tests/unittests/test_split_op.py",
"python/paddle/fluid/tests/unittests/test_layer_norm_op.py",
"python/paddle/fluid/tests/unittests/test_conv2d_transpose_op.py",
"python/paddle/fluid/tests/unittests/test_dropout_op.py",
"python/paddle/fluid/tests/unittests/test_dist_base.py"
] | [
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nfrom op_test import OpTest\nimport paddle.fluid.core as core\nimport paddle.fluid as fluid\n\n\ndef bilinear_interp_np(input,\n out_h,\n out_w,\n out_size=None,\n actual_shape=None,\n align_corners=True,\n align_mode=0,\n data_layout='NCHW'):\n \"\"\"bilinear interpolation implement in shape [N, C, H, W]\"\"\"\n if data_layout == \"NHWC\":\n input = np.transpose(input, (0, 3, 1, 2)) # NHWC => NCHW\n if out_size is not None:\n out_h = out_size[0]\n out_w = out_size[1]\n if actual_shape is not None:\n out_h = actual_shape[0]\n out_w = actual_shape[1]\n batch_size, channel, in_h, in_w = input.shape\n\n ratio_h = ratio_w = 0.0\n if out_h > 1:\n if (align_corners):\n ratio_h = (in_h - 1.0) / (out_h - 1.0)\n else:\n ratio_h = 1.0 * in_h / out_h\n if out_w > 1:\n if (align_corners):\n ratio_w = (in_w - 1.0) / (out_w - 1.0)\n else:\n ratio_w = 1.0 * in_w / out_w\n\n out = np.zeros((batch_size, channel, out_h, out_w))\n\n for i in range(out_h):\n if (align_mode == 0 and not align_corners):\n h = int(ratio_h * (i + 0.5) - 0.5)\n else:\n h = int(ratio_h * i)\n\n h = max(0, h)\n hid = 1 if h < in_h - 1 else 0\n if (align_mode == 0 and not align_corners):\n idx_src_h = max(ratio_h * (i + 0.5) - 0.5, 0)\n h1lambda = idx_src_h - h\n else:\n h1lambda = ratio_h * i - h\n h2lambda = 1.0 - h1lambda\n for j in range(out_w):\n if (align_mode == 0 and not align_corners):\n w = int(ratio_w * (j + 0.5) - 0.5)\n else:\n w = int(ratio_w * j)\n w = max(0, w)\n wid = 1 if w < in_w - 1 else 0\n if (align_mode == 0 and not align_corners):\n idx_src_w = max(ratio_w * (j + 0.5) - 0.5, 0)\n w1lambda = idx_src_w - w\n else:\n w1lambda = ratio_w * j - w\n w2lambda = 1.0 - w1lambda\n\n out[:, :, i, j] = h2lambda*(w2lambda*input[:, :, h, w] +\n w1lambda*input[:, :, h, w+wid]) + \\\n h1lambda*(w2lambda*input[:, :, h+hid, w] +\n w1lambda*input[:, :, h+hid, w+wid])\n\n if data_layout == \"NHWC\":\n out = np.transpose(out, (0, 2, 3, 1)) # NCHW => NHWC\n\n return out.astype(input.dtype)\n\n\nclass TestBilinearInterpOp(OpTest):\n def setUp(self):\n self.out_size = None\n self.actual_shape = None\n self.data_layout = 'NCHW'\n self.init_test_case()\n self.op_type = \"bilinear_interp\"\n input_np = np.random.random(self.input_shape).astype(\"float32\")\n\n if self.data_layout == \"NCHW\":\n in_h = self.input_shape[2]\n in_w = self.input_shape[3]\n else:\n in_h = self.input_shape[1]\n in_w = self.input_shape[2]\n\n if self.scale > 0:\n out_h = int(in_h * self.scale)\n out_w = int(in_w * self.scale)\n else:\n out_h = self.out_h\n out_w = self.out_w\n\n output_np = bilinear_interp_np(input_np, out_h, out_w, self.out_size,\n self.actual_shape, self.align_corners,\n self.align_mode, self.data_layout)\n self.inputs = {'X': input_np}\n if self.out_size is not None:\n self.inputs['OutSize'] = self.out_size\n if self.actual_shape is not None:\n self.inputs['OutSize'] = self.actual_shape\n\n self.attrs = {\n 'out_h': self.out_h,\n 'out_w': self.out_w,\n 'scale': self.scale,\n 'interp_method': self.interp_method,\n 'align_corners': self.align_corners,\n 'align_mode': self.align_mode,\n 'data_layout': self.data_layout\n }\n self.outputs = {'Out': output_np}\n\n def test_check_output(self):\n self.check_output()\n\n def test_check_grad(self):\n self.check_grad(['X'], 'Out', in_place=True)\n\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [2, 3, 4, 4]\n self.out_h = 2\n self.out_w = 2\n self.scale = 0.\n self.out_size = np.array([3, 3]).astype(\"int32\")\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpCase1(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [4, 1, 7, 8]\n self.out_h = 1\n self.out_w = 1\n self.scale = 0.\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpCase2(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [3, 3, 9, 6]\n self.out_h = 12\n self.out_w = 12\n self.scale = 0.\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpCase3(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [1, 1, 128, 64]\n self.out_h = 64\n self.out_w = 128\n self.scale = 0.\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpCase4(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [4, 1, 7, 8]\n self.out_h = 1\n self.out_w = 1\n self.scale = 0.\n self.out_size = np.array([2, 2]).astype(\"int32\")\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpCase5(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [3, 3, 9, 6]\n self.out_h = 12\n self.out_w = 12\n self.scale = 0.\n self.out_size = np.array([11, 11]).astype(\"int32\")\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpCase6(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [1, 1, 128, 64]\n self.out_h = 64\n self.out_w = 128\n self.scale = 0.\n self.out_size = np.array([65, 129]).astype(\"int32\")\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpSame(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [2, 3, 128, 64]\n self.out_h = 128\n self.out_w = 64\n self.scale = 0.\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpActualShape(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [3, 2, 32, 16]\n self.out_h = 64\n self.out_w = 32\n self.scale = 0.\n self.out_size = np.array([66, 40]).astype(\"int32\")\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpDataLayout(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [2, 4, 4, 3]\n self.out_h = 2\n self.out_w = 2\n self.scale = 0.\n self.out_size = np.array([3, 3]).astype(\"int32\")\n self.align_corners = True\n self.align_mode = 1\n self.data_layout = \"NHWC\"\n\n\nclass TestBilinearInterpOpUint8(OpTest):\n def setUp(self):\n self.out_size = None\n self.actual_shape = None\n self.init_test_case()\n self.op_type = \"bilinear_interp\"\n input_np = np.random.randint(\n low=0, high=256, size=self.input_shape).astype(\"uint8\")\n\n if self.scale > 0:\n out_h = int(self.input_shape[2] * self.scale)\n out_w = int(self.input_shape[3] * self.scale)\n else:\n out_h = self.out_h\n out_w = self.out_w\n\n output_np = bilinear_interp_np(input_np, out_h, out_w, self.out_size,\n self.actual_shape, self.align_corners,\n self.align_mode)\n self.inputs = {'X': input_np}\n if self.out_size is not None:\n self.inputs['OutSize'] = self.out_size\n\n self.attrs = {\n 'out_h': self.out_h,\n 'out_w': self.out_w,\n 'scale': self.scale,\n 'interp_method': self.interp_method,\n 'align_corners': self.align_corners,\n 'align_mode': self.align_mode\n }\n self.outputs = {'Out': output_np}\n\n def test_check_output(self):\n self.check_output_with_place(place=core.CPUPlace(), atol=1)\n\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [1, 3, 9, 6]\n self.out_h = 10\n self.out_w = 9\n self.scale = 0.\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpCase1Uint8(TestBilinearInterpOpUint8):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [2, 3, 128, 64]\n self.out_h = 120\n self.out_w = 50\n self.scale = 0.\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpCase2Uint8(TestBilinearInterpOpUint8):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [4, 1, 7, 8]\n self.out_h = 5\n self.out_w = 13\n self.scale = 0.\n self.out_size = np.array([6, 15]).astype(\"int32\")\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpOtherMethod1(TestBilinearInterpOp):\n def set_align_mode(self):\n self.align_corners = False\n self.align_mode = 1\n\n\nclass TestBilinearInterpWithMethod2(TestBilinearInterpOp):\n def set_align_mode(self):\n self.align_corners = False\n self.align_mode = 0\n\n\nclass TestBilinearInterpWithMethod3(TestBilinearInterpOp):\n def set_align_mode(self):\n self.align_corners = True\n self.align_mode = 0\n\n\nclass TestBilinearInterpScale1(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [2, 3, 5, 7]\n self.out_h = 60\n self.out_w = 25\n self.scale = 2.\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpScale2(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [2, 3, 5, 7]\n self.out_h = 60\n self.out_w = 25\n self.scale = 1.\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpScale3(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [2, 3, 5, 7]\n self.out_h = 60\n self.out_w = 25\n self.scale = 1.5\n self.align_corners = True\n self.align_mode = 1\n\n\nclass TestBilinearInterpZero(TestBilinearInterpOp):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [2, 3, 5, 7]\n self.out_h = 60\n self.out_w = 25\n self.scale = 0.2\n self.align_corners = False\n self.align_mode = 0\n\n\nclass TestBilinearInterpOp_attr_tensor(OpTest):\n def setUp(self):\n self.out_size = None\n self.actual_shape = None\n self.init_test_case()\n self.op_type = \"bilinear_interp\"\n self.shape_by_1Dtensor = False\n self.scale_by_1Dtensor = False\n self.attrs = {\n 'interp_method': self.interp_method,\n 'align_corners': self.align_corners,\n }\n\n input_np = np.random.random(self.input_shape).astype(\"float32\")\n self.inputs = {'X': input_np}\n\n if self.scale_by_1Dtensor:\n self.inputs['Scale'] = np.array([self.scale]).astype(\"float32\")\n elif self.scale > 0:\n out_h = int(self.input_shape[2] * self.scale)\n out_w = int(self.input_shape[3] * self.scale)\n self.attrs['scale'] = self.scale\n else:\n out_h = self.out_h\n out_w = self.out_w\n\n if self.shape_by_1Dtensor:\n self.inputs['OutSize'] = self.out_size\n elif self.out_size is not None:\n size_tensor = []\n for index, ele in enumerate(self.out_size):\n size_tensor.append((\"x\" + str(index), np.ones(\n (1)).astype('int32') * ele))\n self.inputs['SizeTensor'] = size_tensor\n\n self.attrs['out_h'] = self.out_h\n self.attrs['out_w'] = self.out_w\n output_np = bilinear_interp_np(input_np, out_h, out_w, self.out_size,\n self.actual_shape, self.align_corners)\n self.outputs = {'Out': output_np}\n\n def test_check_output(self):\n self.check_output()\n\n def test_check_grad(self):\n self.check_grad(['X'], 'Out', in_place=True)\n\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [2, 3, 4, 4]\n self.out_h = 3\n self.out_w = 3\n self.scale = 0.\n self.out_size = [3, 3]\n self.align_corners = True\n\n\n# out_size is a 1-D tensor\nclass TestBilinearInterp_attr_tensor_Case1(TestBilinearInterpOp_attr_tensor):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [3, 3, 9, 6]\n self.out_h = 12\n self.out_w = 12\n self.scale = 0.\n self.out_size = [8, 12]\n self.align_corners = True\n\n\n# scale is a 1-D tensor\nclass TestBilinearInterp_attr_tensor_Case2(TestBilinearInterpOp_attr_tensor):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [3, 2, 32, 16]\n self.out_h = 64\n self.out_w = 32\n self.scale = 0.\n self.out_size = np.array([66, 40]).astype(\"int32\")\n self.align_corners = True\n self.shape_by_1Dtensor = True\n\n\n# scale is a 1-D tensor\nclass TestBilinearInterp_attr_tensor_Case3(TestBilinearInterpOp_attr_tensor):\n def init_test_case(self):\n self.interp_method = 'bilinear'\n self.input_shape = [3, 2, 32, 16]\n self.out_h = 64\n self.out_w = 32\n self.scale = 2.0\n self.out_size = None\n self.align_corners = True\n self.scale_by_1Dtensor = True\n\n\nclass TestBilinearInterpOpAPI(OpTest):\n def test_case(self):\n x = fluid.layers.data(name=\"x\", shape=[3, 6, 6], dtype=\"float32\")\n\n dim = fluid.layers.data(\n name=\"dim\", shape=[1], dtype=\"int32\", append_batch_size=False)\n shape_tensor = fluid.layers.data(\n name=\"shape_tensor\",\n shape=[2],\n dtype=\"int32\",\n append_batch_size=False)\n actual_size = fluid.layers.data(\n name=\"actual_size\",\n shape=[2],\n dtype=\"int32\",\n append_batch_size=False)\n scale_tensor = fluid.layers.data(\n name=\"scale_tensor\",\n shape=[1],\n dtype=\"float32\",\n append_batch_size=False)\n\n out1 = fluid.layers.resize_bilinear(x, out_shape=[12, 12])\n out2 = fluid.layers.resize_bilinear(x, out_shape=[12, dim])\n out3 = fluid.layers.resize_bilinear(x, out_shape=shape_tensor)\n out4 = fluid.layers.resize_bilinear(\n x, out_shape=[4, 4], actual_shape=actual_size)\n out5 = fluid.layers.resize_bilinear(x, scale=scale_tensor)\n\n x_data = np.random.random((1, 3, 6, 6)).astype(\"float32\")\n dim_data = np.array([12]).astype(\"int32\")\n shape_data = np.array([12, 12]).astype(\"int32\")\n actual_size_data = np.array([12, 12]).astype(\"int32\")\n scale_data = np.array([2.0]).astype(\"float32\")\n\n place = core.CPUPlace()\n exe = fluid.Executor(place)\n results = exe.run(fluid.default_main_program(),\n feed={\n \"x\": x_data,\n \"dim\": dim_data,\n \"shape_tensor\": shape_data,\n \"actual_size\": actual_size_data,\n \"scale_tensor\": scale_data\n },\n fetch_list=[out1, out2, out3, out4, out5],\n return_numpy=True)\n\n expect_res = bilinear_interp_np(\n x_data, out_h=12, out_w=12, align_corners=True)\n for res in results:\n self.assertTrue(np.allclose(res, expect_res))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nfrom op_test import OpTest\nfrom copy import deepcopy\n\n\nclass TestSequenceTopkAvgPoolingOp(OpTest):\n def setUp(self):\n self.init_op_type()\n self.set_data()\n self.compute()\n\n def init_op_type(self):\n self.op_type = \"sequence_topk_avg_pooling\"\n\n def set_data(self):\n topks = [2]\n channel_num = 3\n dim = 10\n row = [2, 4]\n col = [3, 2]\n self.init_data(topks, channel_num, row, col, dim)\n\n def init_data(self, topks, channel_num, row, col, dim=10):\n self.attrs = {\"topks\": topks, \"channel_num\": channel_num}\n feature = [row[i] * col[i] for i in range(len(row))]\n numel = sum(feature) * channel_num\n x_data = np.random.random((numel, )).astype('float32')\n x_lod = [[x * channel_num for x in feature]]\n row_data = np.random.random((sum(row), dim)).astype('float32')\n col_data = np.random.random((sum(col), dim)).astype('float32')\n self.inputs = {\n 'X': (x_data, x_lod),\n 'ROW': (row_data, [row]),\n 'COLUMN': (col_data, [col])\n }\n\n def compute(self):\n topks = self.attrs['topks']\n max_k = topks[-1]\n x_data, x_lod = self.inputs['X']\n row_data, row_lod = self.inputs['ROW']\n col_data, col_lod = self.inputs['COLUMN']\n channel_num = self.attrs['channel_num']\n out = np.zeros((0, len(topks) * channel_num), dtype=x_data.dtype)\n pos = np.zeros((0, ), dtype='int32')\n out_lod = deepcopy(row_lod)\n\n offset = 0\n for idx in range(len(x_lod[0])):\n x_len = x_lod[0][idx]\n self.assertTrue(\n x_len == channel_num * row_lod[0][idx] * col_lod[0][idx],\n \"x_len: %s can't mod channel_num: %s\" % (x_len, channel_num))\n # feature = x_len / channel_num\n out_tmp = np.zeros((0, ), dtype=x_data.dtype)\n pos_tmp = np.zeros((0, ), dtype='int32')\n for ch in range(channel_num):\n for r_id in range(row_lod[0][idx]):\n x_sub = x_data[offset:(offset + col_lod[0][idx])]\n topk_val, topk_pos = self.get_topk(x_sub, max_k)\n sum_data = self.topk_sum(topk_val, topk_pos, max_k)\n new_feature = np.array(\n [sum_data[topk] / topk for topk in topks])\n out_tmp = np.hstack((out_tmp, new_feature))\n pos_tmp = np.hstack((pos_tmp, topk_pos))\n\n offset += col_lod[0][idx]\n\n out_tmp = out_tmp.reshape([channel_num, -1, len(topks)]).transpose(\n 1, 0, 2)\n pos_tmp = pos_tmp.reshape([channel_num, -1, max_k]).transpose(1, 0,\n 2)\n out = np.vstack(\n (out, out_tmp.reshape([-1, len(topks) * channel_num])))\n pos = np.hstack((pos, pos_tmp.flatten()))\n\n self.outputs = {'Out': (out.astype('float32'), out_lod), 'pos': pos}\n\n def get_topk(self, x, topk):\n real_topk = topk if topk < len(x) else len(x)\n topk_pos = np.array(x).argsort()[-topk:][::-1]\n topk_val = np.array(x)[topk_pos]\n if real_topk < topk:\n topk_pos = np.hstack((topk_pos, np.full((topk - real_topk, ), -1)))\n topk_val = np.hstack((topk_val, np.full((topk - real_topk, ), 0.0)))\n\n return topk_val, topk_pos\n\n def topk_sum(self, x, pos, max_k):\n sum_data = [0.] * (max_k + 1)\n for i in range(1, max_k + 1):\n if pos[i - 1] == -1:\n sum_data[i] = sum_data[i - 1]\n else:\n sum_data[i] = sum_data[i - 1] + x[i - 1]\n return sum_data\n\n def test_check_output(self):\n self.check_output()\n\n def test_check_grad(self):\n self.check_grad(['X'], 'Out', max_relative_error=0.005)\n\n\nclass TestSequenceTopkAvgPoolingOpCase1(TestSequenceTopkAvgPoolingOp):\n def set_data(self):\n topks = [2, 3]\n channel_num = 3\n dim = 10\n row = [3]\n col = [4]\n self.init_data(topks, channel_num, row, col, dim)\n\n def test_api(self):\n import paddle.fluid as fluid\n x = fluid.layers.data(name='x', shape=[1], lod_level=1)\n row = fluid.layers.data(name='row', shape=[10], lod_level=1)\n col = fluid.layers.data(name='col', shape=[10], lod_level=1)\n topk_avg = fluid.contrib.sequence_topk_avg_pooling(\n input=x, row=row, col=col, topks=[1, 3, 5], channel_num=5)\n\n place = fluid.CPUPlace()\n x_tensor = fluid.create_lod_tensor(\n np.random.rand(45, 1).astype('float32'), [[30, 15]], place)\n row_tensor = fluid.create_lod_tensor(\n np.random.rand(5, 10).astype('float32'), [[2, 3]], place)\n col_tensor = fluid.create_lod_tensor(\n np.random.rand(4, 10).astype('float32'), [[3, 1]], place)\n\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n ret = exe.run(\n feed={'x': x_tensor,\n 'row': row_tensor,\n 'col': col_tensor},\n fetch_list=[topk_avg],\n return_numpy=False)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nfrom op_test import OpTest\n\n\nclass TestSplitOp(OpTest):\n def setUp(self):\n self._set_op_type()\n self.dtype = self.get_dtype()\n axis = 1\n x = np.random.random((4, 5, 6)).astype(self.dtype)\n out = np.split(x, [2, 3], axis)\n self.inputs = {'X': x}\n self.attrs = {'axis': axis, 'sections': [2, 1, 2]}\n self.outputs = {'Out': [('out%d' % i, out[i]) \\\n for i in range(len(out))]}\n\n def get_dtype(self):\n return \"float32\"\n\n def _set_op_type(self):\n self.op_type = \"split\"\n\n def test_check_output(self):\n self.check_output()\n\n def test_check_grad(self):\n self.check_grad(['X'], ['out0', 'out1', 'out2'])\n\n\nclass TestSplitByrefOp(OpTest):\n def _set_op_type(self):\n self.op_type = \"split_byref\"\n\n\n#----------------Split Fp16----------------\n\n\ndef create_test_fp16(parent):\n class TestSplitFp16(parent):\n def get_dtype(self):\n return np.float16\n\n def test_check_grad(self):\n pass\n\n cls_name = \"{0}_{1}\".format(parent.__name__, \"Fp16\")\n TestSplitFp16.__name__ = cls_name\n globals()[cls_name] = TestSplitFp16\n\n\ncreate_test_fp16(TestSplitOp)\n\nif __name__ == '__main__':\n unittest.main()\n",
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport unittest\nimport numpy as np\n\nfrom operator import mul\nimport paddle.fluid.core as core\nimport paddle.fluid as fluid\nfrom functools import reduce\n\nnp.random.random(123)\n\n\ndef _reference_layer_norm_naive(x, scale, beta, epsilon, begin_norm_axis=1):\n x_shape = x.shape\n N = reduce(mul, x_shape[0:begin_norm_axis], 1)\n D = reduce(mul, x_shape[begin_norm_axis:len(x_shape)], 1)\n x.shape = [N, D]\n\n mean = np.mean(x, axis=1)\n var = np.var(x, axis=1) + epsilon\n output = scale.reshape([1, D]) * np.divide(\n (x - mean.reshape([N, 1])),\n (np.sqrt(var)).reshape([N, 1])) + beta.reshape([1, D])\n\n x.shape, output.shape = x_shape, x_shape\n return output, mean, var\n\n\ndef _reference_layer_norm_grad(x, grad_y, scale, mean, var, begin_norm_axis=1):\n x_shape = x.shape\n scale_shape = scale.shape\n N = reduce(mul, x_shape[0:begin_norm_axis], 1)\n D = reduce(mul, x_shape[begin_norm_axis:len(x_shape)], 1)\n x.shape, grad_y.shape = [N, D], [N, D]\n var.shape, mean.shape = [N, 1], [N, 1]\n scale.shape = [1, D]\n\n # d_bias\n d_bias = np.sum(grad_y, axis=0).reshape([1, D])\n # d_scale\n d_scale = np.sum(((x - mean) * np.sqrt(1 / var)) * grad_y,\n axis=0).reshape([1, D])\n # dx\n dx_end = scale * np.sqrt(1.0 / var) * grad_y\n d_mean_0 = np.sum(-np.sqrt(1.0 / var) * grad_y * scale, axis=1).reshape(\n [N, 1]) # the second part equals to zero.\n d_mean = 1.0 / D * d_mean_0\n d_std = np.sum(\n -(1.0 / var) * (x - mean) * grad_y * scale, axis=1).reshape([N, 1]) * (\n 1.0 / D * np.sqrt(1.0 / var).reshape([N, 1]) * (x - mean))\n\n grad_x = dx_end + d_mean + d_std\n\n grad_x.shape, x.shape, grad_y.shape = x_shape, x_shape, x_shape\n scale.shape = scale_shape\n var.shape, mean.shape = [N, ], [N, ]\n return grad_x, d_scale, d_bias\n\n\nclass TestLayerNormOp(unittest.TestCase):\n def setUp(self):\n self.use_cudnn = True\n\n def __assert_close(self, tensor, np_array, msg, atol=1e-4):\n self.assertTrue(np.allclose(np.array(tensor), np_array, atol=atol), msg)\n\n def check_forward_backward(self, shape, begin_norm_axis):\n def test_with_place(place, shape, begin_norm_axis):\n # attr\n epsilon = 0.00001\n x_shape = shape\n D = reduce(mul, x_shape[begin_norm_axis:len(x_shape)], 1)\n scale_shape = [D]\n\n np.random.seed(123)\n x = np.random.random_sample(x_shape).astype(np.float32)\n scale = np.random.random_sample(scale_shape).astype(np.float32)\n bias = np.random.random_sample(scale_shape).astype(np.float32)\n y_grad = np.random.random_sample(x_shape).astype(np.float32)\n\n # reference forward & backward\n y, mean, variance = _reference_layer_norm_naive(\n x, scale, bias, epsilon, begin_norm_axis)\n x_grad, scale_grad, bias_grad = _reference_layer_norm_grad(\n x, y_grad, scale, mean, variance, begin_norm_axis)\n\n var_dict = locals()\n var_dict['y@GRAD'] = y_grad\n var_names = [\n 'x', 'scale', 'bias', 'mean', 'variance', 'y', 'y@GRAD'\n ]\n ground_truth = {name: var_dict[name] for name in var_names}\n\n program = fluid.Program()\n with fluid.program_guard(program):\n block = program.global_block()\n for name in ground_truth:\n block.create_var(\n name=name,\n dtype='float32',\n shape=ground_truth[name].shape)\n layer_norm_op = block.append_op(\n type=\"layer_norm\",\n inputs={\n \"X\": block.var('x'),\n \"Scale\": block.var('scale'),\n \"Bias\": block.var('bias'),\n },\n outputs={\n \"Y\": block.var('y'),\n \"Mean\": block.var('mean'), # share the same memory\n \"Variance\":\n block.var('variance'), # share the same memory\n },\n attrs={\n \"epsilon\": epsilon,\n \"begin_norm_axis\": begin_norm_axis\n })\n\n # generate backward op_desc\n grad_op_desc_list, op_grad_to_var = core.get_grad_op_desc(\n layer_norm_op.desc, set(), [])\n grad_op_desc = grad_op_desc_list[0]\n new_op_desc = block.desc.append_op()\n new_op_desc.copy_from(grad_op_desc)\n for var_name in grad_op_desc.output_arg_names():\n block.desc.var(var_name.encode(\"ascii\"))\n grad_op_desc.infer_var_type(block.desc)\n grad_op_desc.infer_shape(block.desc)\n for arg in grad_op_desc.output_arg_names():\n grad_var = block.desc.find_var(arg.encode(\"ascii\"))\n grad_var.set_dtype(core.VarDesc.VarType.FP32)\n\n exe = fluid.Executor(place)\n out = exe.run(program,\n feed={\n name: var_dict[name]\n for name in ['x', 'scale', 'bias', 'y@GRAD']\n },\n fetch_list=[\n 'y', 'mean', 'variance', 'x@GRAD',\n 'scale@GRAD', 'bias@GRAD'\n ])\n self.__assert_close(y, out[0], \"y\")\n self.__assert_close(mean, out[1], \"mean\")\n self.__assert_close(variance, out[2], \"variance\", 1e-3)\n self.__assert_close(x_grad, out[3], \"x_grad\")\n self.__assert_close(scale_grad, out[4], \"scale_grad\", 1e-3)\n self.__assert_close(bias_grad, out[5], \"bias_grad\")\n\n places = [core.CPUPlace()]\n if core.is_compiled_with_cuda() and core.op_support_gpu(\n \"layer_norm\") and self.use_cudnn:\n places.append(core.CUDAPlace(0))\n\n for place in places:\n test_with_place(place, shape, begin_norm_axis)\n\n def test_check_forward_backward_with_scale_and_bias(self):\n self.check_forward_backward(shape=[2, 3, 4, 5], begin_norm_axis=1)\n self.check_forward_backward(shape=[2, 3, 4, 5], begin_norm_axis=3)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\n\nimport paddle.fluid.core as core\nimport paddle.fluid as fluid\nfrom op_test import OpTest\n\n\ndef conv2dtranspose_forward_naive(input_, filter_, attrs):\n padding_algorithm = attrs['padding_algorithm']\n if padding_algorithm not in [\"SAME\", \"VALID\", \"EXPLICIT\"]:\n raise ValueError(\"Unknown Attr(padding_algorithm): '%s'. \"\n \"It can only be 'SAME' or 'VALID'.\" %\n str(padding_algorithm))\n\n if attrs['data_format'] == 'NHWC':\n input_ = np.transpose(input_, [0, 3, 1, 2])\n in_n, in_c, in_h, in_w = input_.shape\n f_c, f_out_c, f_h, f_w = filter_.shape\n groups = attrs['groups']\n assert in_c == f_c\n out_c = f_out_c * groups\n sub_in_c = in_c // groups\n\n stride, pad, dilations = attrs['strides'], attrs['paddings'], attrs[\n 'dilations']\n\n # update pad and dilation\n def _get_padding_with_SAME(input_shape, kernel_size, kernel_stride):\n padding = []\n for input_size, filter_size, stride_size in zip(\n input_shape, kernel_size, kernel_stride):\n out_size = int((input_size + stride_size - 1) / stride_size)\n pad_sum = np.max((\n (out_size - 1) * stride_size + filter_size - input_size, 0))\n pad_0 = int(pad_sum / 2)\n pad_1 = int(pad_sum - pad_0)\n padding.append(pad_0)\n padding.append(pad_1)\n return padding\n\n ksize = filter_.shape[2:4]\n if padding_algorithm == \"VALID\":\n pad = [0, 0, 0, 0]\n elif padding_algorithm == \"SAME\":\n dilation = [1, 1]\n input_data_shape = []\n if attrs['data_format'] == \"NCHW\":\n input_data_shape = input_.shape[2:4]\n elif attrs['data_format'] == \"NHWC\":\n input_data_shape = input_.shape[1:3]\n pad = _get_padding_with_SAME(input_data_shape, ksize, stride)\n\n pad_h_0, pad_h_1 = pad[0], pad[0]\n pad_w_0, pad_w_1 = pad[1], pad[1]\n if len(pad) == 4:\n pad_h_0, pad_h_1 = pad[0], pad[1]\n pad_w_0, pad_w_1 = pad[2], pad[3]\n\n d_bolck_h = dilations[0] * (f_h - 1) + 1\n d_bolck_w = dilations[1] * (f_w - 1) + 1\n out_h = (in_h - 1) * stride[0] + d_bolck_h\n out_w = (in_w - 1) * stride[1] + d_bolck_w\n if 'output_size' in attrs:\n output_size = attrs['output_size']\n out_h = output_size[0] + pad_h_0 + pad_h_1\n out_w = output_size[1] + pad_w_0 + pad_w_1\n\n out = np.zeros((in_n, out_c, out_h, out_w))\n\n for n in range(in_n):\n for i in range(in_h):\n for j in range(in_w):\n for g in range(groups):\n input_masked = input_[n, g * sub_in_c:(g + 1) * sub_in_c, i,\n j] # (c)\n input_masked = np.reshape(input_masked, (sub_in_c, 1, 1))\n input_masked = np.tile(input_masked, (1, f_h, f_w))\n\n for k in range(f_out_c):\n tmp_out = np.sum(\n input_masked *\n filter_[g * sub_in_c:(g + 1) * sub_in_c, k, :, :],\n axis=0)\n i1, i2 = i * stride[0], i * stride[0] + d_bolck_h\n j1, j2 = j * stride[0], j * stride[0] + d_bolck_h\n out[n, g * f_out_c + k, i1:i2:dilations[0], j1:j2:\n dilations[1]] += tmp_out\n\n out = out[:, :, pad_h_0:out_h - pad_h_1, pad_w_0:out_w - pad_w_1]\n if attrs['data_format'] == 'NHWC':\n out = np.transpose(out, [0, 2, 3, 1])\n return out\n\n\nclass TestConv2dTransposeOp(OpTest):\n def setUp(self):\n # init as conv transpose\n self.is_test = False\n self.use_cudnn = False\n self.use_mkldnn = False\n self.output_size = None\n self.data_format = \"NCHW\"\n self.pad = [0, 0]\n self.padding_algorithm = \"EXPLICIT\"\n self.init_op_type()\n self.init_test_case()\n\n input_ = np.random.random(self.input_size).astype(\"float32\")\n filter_ = np.random.random(self.filter_size).astype(\"float32\")\n\n self.inputs = {'Input': input_, 'Filter': filter_}\n self.attrs = {\n 'strides': self.stride,\n 'paddings': self.pad,\n 'padding_algorithm': self.padding_algorithm,\n 'groups': self.groups,\n 'dilations': self.dilations,\n 'use_cudnn': self.use_cudnn,\n 'is_test': self.is_test,\n 'use_mkldnn': self.use_mkldnn,\n 'data_format': self.data_format\n }\n if self.output_size is not None:\n self.attrs['output_size'] = self.output_size\n\n output = conv2dtranspose_forward_naive(input_, filter_,\n self.attrs).astype('float32')\n\n self.outputs = {'Output': output}\n\n def test_check_output(self):\n if self.use_cudnn:\n place = core.CUDAPlace(0)\n self.check_output_with_place(place, atol=1e-5)\n else:\n self.check_output()\n\n def test_check_grad_no_input(self):\n if self.use_cudnn:\n place = core.CUDAPlace(0)\n self.check_grad_with_place(\n place, ['Filter'],\n 'Output',\n max_relative_error=0.02,\n no_grad_set=set(['Input']))\n else:\n self.check_grad(\n ['Filter'],\n 'Output',\n max_relative_error=0.02,\n no_grad_set=set(['Input']))\n\n def test_check_grad_no_filter(self):\n if self.use_cudnn:\n place = core.CUDAPlace(0)\n self.check_grad_with_place(\n place, ['Input'],\n 'Output',\n max_relative_error=0.02,\n no_grad_set=set(['Filter']))\n else:\n self.check_grad(\n ['Input'],\n 'Output',\n max_relative_error=0.02,\n no_grad_set=set(['Filter']))\n\n def test_check_grad(self):\n if self.use_cudnn:\n place = core.CUDAPlace(0)\n self.check_grad_with_place(\n place,\n set(['Input', 'Filter']),\n 'Output',\n max_relative_error=0.02)\n else:\n self.check_grad(\n set(['Input', 'Filter']), 'Output', max_relative_error=0.02)\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n def init_op_type(self):\n self.op_type = \"conv2d_transpose\"\n\n\nclass TestWithSymmetricPad(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n\nclass TestWithAsymmetricPad(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 0, 1, 2]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n\nclass TestWithSAMEPad(TestConv2dTransposeOp):\n def init_test_case(self):\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n self.padding_algorithm = 'SAME'\n\n\nclass TestWithVALIDPad(TestConv2dTransposeOp):\n def init_test_case(self):\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n self.padding_algorithm = 'VALID'\n\n\nclass TestWithGroups(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 2\n self.input_size = [2, 4, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 3, 3, 3]\n\n\nclass TestWithStride(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n\nclass TestWithDilation(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.groups = 1\n self.dilations = [2, 2]\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n\nclass TestWithEvenUpsample(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [2, 2]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.output_size = [14, 14]\n self.input_size = [2, 3, 7, 7] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 5, 5]\n\n\nclass Test_NHWC(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithSymmetricPad_NHWC(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithAsymmetricPad_NHWC(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 0, 1, 2]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithGroups_NHWC(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 2\n self.input_size = [2, 5, 5, 4] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 3, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithStride_NHWC(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 5, 5, 3] # NCHW\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithDilation_NHWC(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.groups = 1\n self.dilations = [2, 2]\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithEvenUpsample_NHWC(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [2, 2]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.output_size = [14, 14]\n self.input_size = [2, 7, 7, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 5, 5]\n self.data_format = 'NHWC'\n\n\n# ------------ test_cudnn ------------\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNN(TestConv2dTransposeOp):\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithSymmetricPad(TestWithSymmetricPad):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.groups = 1\n self.dilations = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithAsymmetricPad(TestWithAsymmetricPad):\n def init_test_case(self):\n self.pad = [1, 0, 1, 2]\n self.stride = [1, 1]\n self.groups = 1\n self.dilations = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithSAMEPad(TestWithSAMEPad):\n def init_test_case(self):\n self.pad = [1, 0, 1, 2]\n self.stride = [1, 1]\n self.groups = 1\n self.dilations = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithVALIDPad(TestWithVALIDPad):\n def init_test_case(self):\n self.pad = [1, 0, 1, 2]\n self.stride = [1, 1]\n self.groups = 1\n self.dilations = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithStride(TestWithStride):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithGroups(TestWithGroups):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 2\n self.input_size = [2, 4, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 3, 3, 3]\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\n# ------------ test_cudnn ------------\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithEvenUpsample(TestWithEvenUpsample):\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\n# Please Don't remove the following code.\n# Currently, CI use cudnn V5.0 which not support dilation conv.\n# class TestCUDNNWithDilation(TestWithDilation):\n# def init_test_case(self):\n# self.pad = [1, 1]\n# self.stride = [2, 2]\n# self.dilations = [2, 2]\n# self.input_size = [2, 3, 5, 5] # NCHW\n# f_c = self.input_size[1]\n# self.filter_size = [f_c, 6, 3, 3]\n#\n# def init_op_type(self):\n# self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNN_NHWC(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithSymmetricPad_NHWC(TestWithSymmetricPad):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.groups = 1\n self.dilations = [1, 1]\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithAsymmetricPad_NHWC(TestWithSymmetricPad):\n def init_test_case(self):\n self.pad = [1, 0, 2, 3]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithStride_NHWC(TestWithStride):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithGroups_NHWC(TestWithGroups):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 2\n self.input_size = [2, 5, 5, 4] # NCHW\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 3, 3, 3]\n self.data_format = 'NHWC'\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\[email protected](not core.is_compiled_with_cuda(),\n \"core is not compiled with CUDA\")\nclass TestCUDNNWithEvenUpsample_NHWC(TestWithEvenUpsample):\n def init_test_case(self):\n self.pad = [2, 2]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.output_size = [14, 14]\n self.input_size = [2, 7, 7, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 5, 5]\n self.data_format = 'NHWC'\n\n def init_op_type(self):\n self.use_cudnn = True\n self.op_type = \"conv2d_transpose\"\n\n\nclass TestDepthwiseConvTranspose(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.input_size = [2, 8, 16, 16] # NCHW\n self.groups = 8\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [self.input_size[1], f_c, 4, 4]\n self.op_type = \"depthwise_conv2d_transpose\"\n\n\nclass TestDepthwiseConvTransposeAsymmetricPad(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 0, 1, 2]\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.input_size = [2, 8, 16, 16] # NCHW\n self.groups = 8\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [self.input_size[1], f_c, 3, 3]\n self.op_type = \"depthwise_conv2d_transpose\"\n self.data_format = 'NCHW'\n\n\nclass TestDepthwiseConvTransposeSAMEPad(TestConv2dTransposeOp):\n def init_test_case(self):\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.input_size = [2, 8, 16, 16] # NHWC\n self.groups = 8\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [self.input_size[1], f_c, 3, 3]\n self.op_type = \"depthwise_conv2d_transpose\"\n self.padding_algorithm = 'SAME'\n\n\nclass TestDepthwiseConvTransposeVALIDPad(TestConv2dTransposeOp):\n def init_test_case(self):\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.input_size = [2, 8, 16, 16] # NHWC\n self.groups = 8\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [self.input_size[1], f_c, 3, 3]\n self.op_type = \"depthwise_conv2d_transpose\"\n self.padding_algorithm = 'VALID'\n\n\nclass TestDepthwiseConvTranspose_NHWC_4x4kernel(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.input_size = [2, 16, 16, 8] # NHWC\n self.groups = 8\n assert np.mod(self.input_size[3], self.groups) == 0\n f_c = self.input_size[3] // self.groups\n self.filter_size = [self.input_size[3], f_c, 4, 4]\n self.op_type = \"depthwise_conv2d_transpose\"\n self.data_format = 'NHWC'\n\n\nclass TestDepthwiseConvTranspose_NHWC_3x3kernel(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.input_size = [2, 16, 16, 8] # NHWC\n self.groups = 8\n assert np.mod(self.input_size[3], self.groups) == 0\n f_c = self.input_size[3] // self.groups\n self.filter_size = [self.input_size[3], f_c, 3, 3]\n self.op_type = \"depthwise_conv2d_transpose\"\n self.data_format = 'NHWC'\n\n\nclass TestDepthwiseConvTransposeAsymmetricPad_NHWC(TestConv2dTransposeOp):\n def init_test_case(self):\n self.pad = [1, 0, 1, 2]\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.input_size = [2, 16, 16, 8] # NHWC\n self.groups = 8\n assert np.mod(self.input_size[3], self.groups) == 0\n f_c = self.input_size[3] // self.groups\n self.filter_size = [self.input_size[3], f_c, 3, 3]\n self.op_type = \"depthwise_conv2d_transpose\"\n self.data_format = 'NHWC'\n\n\nclass TestConv2dTransposeAPI(OpTest):\n def test_case1(self):\n data1 = fluid.layers.data(\n name='data1', shape=[3, 5, 5], dtype='float32')\n data2 = fluid.layers.data(\n name='data2', shape=[5, 5, 3], dtype='float32')\n out1 = fluid.layers.conv2d_transpose(\n input=data1,\n groups=1,\n num_filters=6,\n filter_size=3,\n data_format='NCHW')\n out2 = fluid.layers.conv2d_transpose(\n input=data2,\n groups=1,\n num_filters=6,\n filter_size=3,\n data_format='NHWC')\n out3 = fluid.layers.conv2d_transpose(\n input=data1,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding=[[0, 0], [1, 1], [1, 1], [0, 0]],\n data_format='NHWC')\n out4 = fluid.layers.conv2d_transpose(\n input=data1,\n groups=3,\n num_filters=6,\n filter_size=3,\n padding=[[0, 0], [0, 0], [2, 1], [0, 0]],\n data_format='NCHW')\n out5 = fluid.layers.conv2d_transpose(\n input=data2,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding='SAME',\n data_format='NCHW')\n out6 = fluid.layers.conv2d_transpose(\n input=data1,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding='VALID',\n data_format='NHWC')\n out7 = fluid.layers.conv2d_transpose(\n input=data1,\n groups=1,\n num_filters=6,\n output_size=[7, 7],\n padding=[0, 0],\n data_format='NHWC')\n\n data1_np = np.random.random((2, 3, 5, 5)).astype(\"float32\")\n data2_np = np.random.random((2, 5, 5, 3)).astype(\"float32\")\n\n if core.is_compiled_with_cuda():\n place = core.CUDAPlace(0)\n else:\n place = core.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n results = exe.run(\n fluid.default_main_program(),\n feed={\"data1\": data1_np,\n \"data2\": data2_np},\n fetch_list=[out1, out2, out3, out4, out5, out6, out7],\n return_numpy=True)\n self.assertIsNotNone(results[0])\n self.assertIsNotNone(results[1])\n self.assertIsNotNone(results[2])\n self.assertIsNotNone(results[3])\n self.assertIsNotNone(results[4])\n self.assertIsNotNone(results[5])\n self.assertIsNotNone(results[6])\n\n\nclass TestConv2dTransposeOpException(OpTest):\n def test_exception(self):\n data = fluid.layers.data(name='data', shape=[3, 5, 5], dtype=\"float32\")\n\n def attr_data_format():\n out = fluid.layers.conv2d_transpose(\n input=data,\n groups=1,\n num_filters=6,\n filter_size=3,\n data_format=\"NCDHW\")\n\n self.assertRaises(ValueError, attr_data_format)\n\n def attr_padding_str():\n out = fluid.layers.conv2d_transpose(\n input=data,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding='Vald')\n\n self.assertRaises(ValueError, attr_padding_str)\n\n def attr_padding_list():\n out = fluid.layers.conv2d_transpose(\n input=data,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding=[[1, 1], [1, 1], [0, 0], [0, 0]])\n\n self.assertRaises(ValueError, attr_padding_list)\n\n def attr_padding_with_data_format():\n out = fluid.layers.conv2d_transpose(\n input=data,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding=[[1, 1], [0, 0], [0, 0], [1, 1]],\n data_format='NHWC')\n\n self.assertRaises(ValueError, attr_padding_with_data_format)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport paddle.fluid.core as core\nfrom op_test import OpTest\nimport paddle.fluid as fluid\nfrom paddle.fluid import Program, program_guard\n\n\nclass TestDropoutOp(OpTest):\n def setUp(self):\n self.op_type = \"dropout\"\n self.inputs = {'X': np.random.random((32, 64)).astype(\"float32\")}\n self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}\n self.outputs = {\n 'Out': self.inputs['X'],\n 'Mask': np.ones((32, 64)).astype('uint8')\n }\n\n def test_check_output(self):\n self.check_output()\n\n def test_check_grad_normal(self):\n self.check_grad(['X'], 'Out', max_relative_error=0.05)\n\n\nclass TestDropoutOp2(TestDropoutOp):\n def setUp(self):\n self.op_type = \"dropout\"\n self.inputs = {'X': np.random.random((32, 64)).astype(\"float32\")}\n self.attrs = {'dropout_prob': 1.0, 'fix_seed': True, 'is_test': False}\n self.outputs = {\n 'Out': np.zeros((32, 64)).astype('float32'),\n 'Mask': np.zeros((32, 64)).astype('uint8')\n }\n\n\nclass TestDropoutOp3(TestDropoutOp):\n def setUp(self):\n self.op_type = \"dropout\"\n self.inputs = {'X': np.random.random((32, 64, 2)).astype(\"float32\")}\n self.attrs = {'dropout_prob': 0.0, 'fix_seed': True, 'is_test': False}\n self.outputs = {\n 'Out': self.inputs['X'],\n 'Mask': np.ones((32, 64, 2)).astype('uint8')\n }\n\n\nclass TestDropoutOp4(OpTest):\n def setUp(self):\n self.op_type = \"dropout\"\n self.inputs = {'X': np.random.random((32, 64)).astype(\"float32\")}\n self.attrs = {'dropout_prob': 0.35, 'fix_seed': True, 'is_test': True}\n self.outputs = {\n 'Out': self.inputs['X'] * (1.0 - self.attrs['dropout_prob'])\n }\n\n def test_check_output(self):\n self.check_output()\n\n\nclass TestDropoutOp5(OpTest):\n def setUp(self):\n self.op_type = \"dropout\"\n self.inputs = {'X': np.random.random((32, 64, 3)).astype(\"float32\")}\n self.attrs = {'dropout_prob': 0.75, 'is_test': True}\n self.outputs = {\n 'Out': self.inputs['X'] * (1.0 - self.attrs['dropout_prob'])\n }\n\n def test_check_output(self):\n self.check_output()\n\n\nclass TestDropoutOp6(TestDropoutOp):\n def setUp(self):\n self.op_type = \"dropout\"\n self.inputs = {'X': np.random.random((32, 64)).astype(\"float32\")}\n self.attrs = {\n 'dropout_prob': 1.0,\n 'fix_seed': True,\n 'is_test': False,\n 'dropout_implementation': 'upscale_in_train'\n }\n self.outputs = {\n 'Out': np.zeros((32, 64)).astype('float32'),\n 'Mask': np.zeros((32, 64)).astype('uint8')\n }\n\n\nclass TestDropoutOp7(TestDropoutOp):\n def setUp(self):\n self.op_type = \"dropout\"\n self.inputs = {'X': np.random.random((32, 64, 2)).astype(\"float32\")}\n self.attrs = {\n 'dropout_prob': 0.0,\n 'fix_seed': True,\n 'is_test': False,\n 'dropout_implementation': 'upscale_in_train'\n }\n self.outputs = {\n 'Out': self.inputs['X'],\n 'Mask': np.ones((32, 64, 2)).astype('uint8')\n }\n\n\nclass TestDropoutOp8(OpTest):\n def setUp(self):\n self.op_type = \"dropout\"\n self.inputs = {'X': np.random.random((32, 64)).astype(\"float32\")}\n self.attrs = {\n 'dropout_prob': 0.35,\n 'fix_seed': True,\n 'is_test': True,\n 'dropout_implementation': 'upscale_in_train'\n }\n self.outputs = {'Out': self.inputs['X']}\n\n def test_check_output(self):\n self.check_output()\n\n\nclass TestDropoutOp9(OpTest):\n def setUp(self):\n self.op_type = \"dropout\"\n self.inputs = {'X': np.random.random((32, 64, 3)).astype(\"float32\")}\n self.attrs = {\n 'dropout_prob': 0.75,\n 'is_test': True,\n 'dropout_implementation': 'upscale_in_train'\n }\n self.outputs = {'Out': self.inputs['X']}\n\n def test_check_output(self):\n self.check_output()\n\n\nclass TestFP16DropoutOp(OpTest):\n def setUp(self):\n self.op_type = \"dropout\"\n self.init_test_case()\n\n x = np.random.random(self.input_size).astype(\"float16\")\n out = x * (1.0 - self.prob)\n self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}\n self.attrs = {\n 'dropout_prob': self.prob,\n 'fix_seed': self.fix_seed,\n 'is_test': True\n }\n self.outputs = {'Out': out}\n\n def init_test_case(self):\n self.input_size = [32, 64]\n self.prob = 0.35\n self.fix_seed = True\n\n def test_check_output(self):\n if core.is_compiled_with_cuda() and core.op_support_gpu(\"dropout\"):\n self.check_output_with_place(core.CUDAPlace(0), atol=1e-3)\n\n\nclass TestFP16DropoutOp2(TestFP16DropoutOp):\n def init_test_case(self):\n self.input_size = [32, 64, 3]\n self.prob = 0.75\n self.fix_seed = False\n\n\nclass TestDropoutOpError(OpTest):\n def test_errors(self):\n with program_guard(Program(), Program()):\n\n def test_Variable():\n # the input of dropout must be Variable.\n x1 = fluid.create_lod_tensor(\n np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace())\n fluid.layers.dropout(x1, dropout_prob=0.5)\n\n self.assertRaises(TypeError, test_Variable)\n\n def test_dtype():\n # the input dtype of dropout must be float16 or float32 or float64\n # float16 only can be set on GPU place\n x2 = fluid.layers.data(\n name='x2', shape=[3, 4, 5, 6], dtype=\"int32\")\n fluid.layers.dropout(x2, dropout_prob=0.5)\n\n self.assertRaises(TypeError, test_dtype)\n\n\nif __name__ == '__main__':\n unittest.main()\n",
"# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport time\n\nimport unittest\nimport os\nimport sys\nimport signal\nimport subprocess\nimport six\nimport argparse\nimport pickle\nimport numpy as np\nimport time\nimport paddle.fluid as fluid\nfrom paddle.fluid import compiler\nimport paddle.fluid.dygraph as dygraph\nfrom paddle.fluid.dygraph.base import to_variable\nfrom paddle.fluid.dygraph.parallel import DataParallel\n\nfrom paddle.fluid.incubate.fleet.collective import fleet, DistributedStrategy\nimport paddle.fluid.incubate.fleet.base.role_maker as role_maker\n\nRUN_STEP = 5\nDEFAULT_BATCH_SIZE = 2\n\n\ndef print_to_out(out_losses):\n if six.PY2:\n print(pickle.dumps(out_losses))\n else:\n sys.stdout.buffer.write(pickle.dumps(out_losses))\n\n\ndef print_to_err(class_name, log_str):\n localtime = time.asctime(time.localtime(time.time()))\n print_str = localtime + \"\\t\" + class_name + \"\\t\" + log_str\n if six.PY2:\n sys.stderr.write(pickle.dumps(print_str))\n else:\n sys.stderr.buffer.write(pickle.dumps(print_str))\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\nclass TestDistRunnerBase(object):\n def get_model(self,\n batch_size=DEFAULT_BATCH_SIZE,\n lr=0.1,\n single_device=False,\n use_dgc=False):\n raise NotImplementedError(\n \"get_model should be implemented by child classes.\")\n\n @staticmethod\n def get_transpiler(trainer_id,\n main_program,\n pserver_endpoints,\n trainers,\n sync_mode,\n dc_asgd=False,\n current_endpoint=None,\n nccl_comm_num=1,\n hogwild_mode=False):\n # NOTE: import fluid until runtime, or else forking processes will cause error.\n config = fluid.DistributeTranspilerConfig()\n config.enable_dc_asgd = dc_asgd\n config.sync_mode = sync_mode\n config.runtime_split_send_recv = hogwild_mode\n\n if nccl_comm_num > 1:\n config.nccl_comm_num = nccl_comm_num\n # config.runtime_split_send_recv = True\n t = fluid.DistributeTranspiler(config=config)\n t.transpile(\n trainer_id=trainer_id,\n program=main_program,\n pservers=pserver_endpoints,\n trainers=trainers,\n sync_mode=sync_mode,\n current_endpoint=current_endpoint)\n return t\n\n def run_pserver(self, args):\n self.lr = args.lr\n self.get_model(batch_size=args.batch_size)\n # NOTE: pserver should not call memory optimize\n\n t = self.get_transpiler(\n trainer_id=args.trainer_id,\n main_program=fluid.default_main_program(),\n pserver_endpoints=args.endpoints,\n trainers=args.trainers,\n sync_mode=args.sync_mode,\n dc_asgd=args.dc_asgd,\n hogwild_mode=args.hogwild)\n pserver_prog = t.get_pserver_program(args.current_endpoint)\n startup_prog = t.get_startup_program(args.current_endpoint,\n pserver_prog)\n\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(startup_prog)\n print_to_err(type(self).__name__, \"run pserver startup program done.\")\n exe.run(pserver_prog)\n print_to_err(type(self).__name__, \"run pserver main program done.\")\n\n def run_gpu_fleet_api_trainer(self, args):\n assert args.update_method == \"nccl2\"\n\n self.lr = args.lr\n\n exec_strategy = fluid.ExecutionStrategy()\n exec_strategy.num_threads = 1\n\n dist_strategy = DistributedStrategy()\n dist_strategy.exec_strategy = exec_strategy\n dist_strategy.fuse_memory_size = 1 # MB\n dist_strategy.fuse_laryer_size = 1\n if args.use_local_sgd:\n dist_strategy.use_local_sgd = True\n if args.ut4grad_allreduce:\n dist_strategy._ut4grad_allreduce = True\n\n role = role_maker.PaddleCloudRoleMaker(is_collective=True)\n fleet.init(role)\n print_to_err(\"gpu_fleet\", \"fleet.node_num:\")\n # \"fleet.node_id:\", fleet.node_id(),\n # \"fleet.trainer_num:\", fleet.worker_num())\n\n test_program, avg_cost, train_reader, test_reader, batch_acc, predict = \\\n self.get_model(batch_size=args.batch_size, dist_strategy=dist_strategy)\n\n trainer_prog = fleet._origin_program\n dist_prog = fleet.main_program\n\n device_id = int(os.getenv(\"FLAGS_selected_gpus\", \"0\"))\n place = fluid.CUDAPlace(device_id)\n\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n eprint(type(self).__name__, \"run worker startup program done.\")\n\n feed_var_list = [\n var for var in trainer_prog.global_block().vars.values()\n if var.is_data\n ]\n\n feeder = fluid.DataFeeder(feed_var_list, place)\n reader_generator = train_reader()\n\n def get_data():\n origin_batch = next(reader_generator)\n if args.update_method != \"local\" and args.use_reader_alloc:\n new_batch = []\n for offset, item in enumerate(origin_batch):\n if offset % 2 == args.trainer_id:\n new_batch.append(item)\n return new_batch\n else:\n return origin_batch\n\n print_to_err(type(self).__name__, \"begin to train on trainer\")\n out_losses = []\n for i in six.moves.xrange(RUN_STEP):\n loss, = exe.run(dist_prog,\n fetch_list=[avg_cost.name],\n feed=feeder.feed(get_data()))\n out_losses.append(loss[0])\n print_to_err(type(self).__name__, \"run step %d finished\" % i)\n print_to_err(type(self).__name__, \"trainer run finished\")\n\n if six.PY2:\n print(pickle.dumps(out_losses))\n else:\n sys.stdout.buffer.write(pickle.dumps(out_losses))\n\n def run_trainer(self, args):\n self.lr = args.lr\n if args.nccl2_reduce_layer_local_run:\n test_program, avg_cost, train_reader, test_reader, batch_acc, predict = \\\n self.get_model(batch_size=args.batch_size, single_device=True)\n elif args.use_dgc:\n test_program, avg_cost, train_reader, test_reader, batch_acc, predict = \\\n self.get_model(batch_size=args.batch_size, use_dgc=args.use_dgc)\n else:\n test_program, avg_cost, train_reader, test_reader, batch_acc, predict = \\\n self.get_model(batch_size=args.batch_size)\n\n if args.update_method == \"pserver\":\n print_to_err(\n type(self).__name__,\n \"begin to run transpile on trainer with pserver mode\")\n t = self.get_transpiler(\n trainer_id=args.trainer_id,\n main_program=fluid.default_main_program(),\n pserver_endpoints=args.endpoints,\n trainers=args.trainers,\n sync_mode=args.sync_mode,\n dc_asgd=args.dc_asgd,\n hogwild_mode=args.hogwild)\n\n trainer_prog = t.get_trainer_program()\n print_to_err(\n type(self).__name__,\n \"get trainer program done with pserver mode.\")\n elif args.update_method == \"nccl2\" or args.update_method == \"nccl2_reduce_layer\":\n # transpile for nccl2\n config = fluid.DistributeTranspilerConfig()\n config.mode = \"nccl2\"\n config.nccl_comm_num = args.nccl_comm_num\n if args.use_hallreduce:\n config.use_hierarchical_allreduce = True\n config.hierarchical_allreduce_inter_nranks = args.hallreduce_inter_nranks\n print_to_err(\n type(self).__name__,\n \"begin to run transpile on trainer with nccl2 mode\")\n nccl2_t = fluid.DistributeTranspiler(config=config)\n nccl2_t.transpile(\n args.trainer_id,\n program=fluid.default_main_program(),\n startup_program=fluid.default_startup_program(),\n trainers=args.endpoints,\n current_endpoint=args.current_endpoint)\n print_to_err(\n type(self).__name__,\n \"get trainer program done. with nccl2 mode\")\n trainer_prog = fluid.default_main_program()\n else:\n print_to_err(\n type(self).__name__,\n \"do nothing about main program, just use it\")\n trainer_prog = fluid.default_main_program()\n print_to_err(type(self).__name__, \"use main program done.\")\n\n if args.use_cuda:\n device_id = int(os.getenv(\"FLAGS_selected_gpus\", \"0\"))\n place = fluid.CUDAPlace(device_id)\n else:\n place = fluid.CPUPlace()\n\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n print_to_err(type(self).__name__, \"run worker startup program done.\")\n\n exec_strategy = fluid.ExecutionStrategy()\n exec_strategy.num_threads = 1\n\n build_stra = fluid.BuildStrategy()\n # FIXME force disable enable_inplace and memory_optimize\n build_stra.enable_inplace = False\n build_stra.memory_optimize = False\n\n if args.hogwild:\n build_stra.async_mode = True\n\n if args.enable_backward_deps:\n build_stra.enable_backward_optimizer_op_deps = True\n\n if args.use_reduce:\n build_stra.reduce_strategy = fluid.BuildStrategy.ReduceStrategy.Reduce\n else:\n build_stra.reduce_strategy = fluid.BuildStrategy.ReduceStrategy.AllReduce\n\n pass_builder = None\n if args.batch_merge_repeat > 1:\n pass_builder = build_stra._finalize_strategy_and_create_passes()\n mypass = pass_builder.insert_pass(0, \"multi_batch_merge_pass\")\n mypass.set(\"num_repeats\", args.batch_merge_repeat)\n\n if args.update_method == \"nccl2\" or args.update_method == \"nccl2_reduce_layer\":\n build_stra.num_trainers = len(args.endpoints.split(\",\"))\n build_stra.trainer_id = args.trainer_id\n else:\n # case args.update_method == \"nccl2_reduce_layer\":\n build_stra.num_trainers = 1\n build_stra.trainer_id = 0\n\n print_to_err(type(self).__name__, \"begin to compile with data parallel\")\n binary = compiler.CompiledProgram(trainer_prog).with_data_parallel(\n loss_name=avg_cost.name,\n build_strategy=build_stra,\n exec_strategy=exec_strategy)\n print_to_err(type(self).__name__, \"program compiled with data parallel\")\n\n feed_var_list = [\n var for var in trainer_prog.global_block().vars.values()\n if var.is_data\n ]\n\n feeder = fluid.DataFeeder(feed_var_list, place)\n reader_generator = train_reader()\n\n def get_data():\n origin_batch = next(reader_generator)\n if args.update_method != \"local\" and args.use_reader_alloc:\n new_batch = []\n for offset, item in enumerate(origin_batch):\n if offset % 2 == args.trainer_id:\n new_batch.append(item)\n return new_batch\n else:\n return origin_batch\n\n print_to_err(type(self).__name__, \"begin to train on trainer\")\n out_losses = []\n for i in six.moves.xrange(RUN_STEP):\n loss, = exe.run(binary,\n fetch_list=[avg_cost.name],\n feed=feeder.feed(get_data()))\n out_losses.append(loss[0])\n print_to_err(type(self).__name__, \"run step %d finished\" % i)\n print_to_err(type(self).__name__, \"trainer run finished\")\n\n print_to_out(out_losses)\n\n\nclass TestParallelDyGraphRunnerBase(object):\n def get_model(self):\n raise NotImplementedError(\n \"get_model should be implemented by child classes.\")\n\n def run_one_loop(self, model, opt, data):\n raise NotImplementedError(\n \"train_one_loop should be implemented by the child classes.\")\n\n def run_trainer(self, args):\n\n seed = 90\n device_id = int(os.getenv(\"FLAGS_selected_gpus\", \"0\"))\n place = fluid.CUDAPlace(device_id)\n\n def _get_data(batch):\n if args.update_method != \"local\":\n new_batch = []\n for offset, item in enumerate(batch):\n if offset % 2 == args.trainer_id:\n new_batch.append(item)\n return new_batch\n else:\n return batch\n\n with fluid.dygraph.guard(place):\n fluid.default_startup_program().random_seed = seed\n fluid.default_main_program().random_seed = seed\n np.random.seed(seed)\n import random\n random.seed = seed\n model, train_reader, opt = self.get_model()\n nranks = len(args.endpoints.split(\",\")) if args.endpoints else 1\n\n if args.update_method == \"nccl2\":\n strategy = dygraph.parallel.ParallelStrategy()\n strategy.nranks = nranks\n strategy.local_rank = args.trainer_id\n strategy.trainer_endpoints = args.endpoints.split(\",\")\n strategy.current_endpoint = args.current_endpoint\n print_to_err(\n type(self).__name__,\n \"begin to prepare context in dygraph with nccl2\")\n dygraph.parallel.prepare_context(strategy)\n model = dygraph.parallel.DataParallel(model, strategy)\n print_to_err(type(self).__name__, \"model built in dygraph\")\n out_losses = []\n print_to_err(type(self).__name__, \"begin to run dygraph training\")\n for step_id, data in enumerate(train_reader()):\n data = _get_data(data)\n if step_id == RUN_STEP:\n break\n loss = self.run_one_loop(model, opt, data)\n if step_id % 10 == 0:\n print_to_err(\n type(self).__name__,\n \"loss at step %d: %f\" % (step_id, loss.numpy()))\n out_losses.append(loss.numpy())\n\n # FIXME(Yancey1989): scale the loss inplace\n if args.update_method == \"nccl2\":\n loss = model.scale_loss(loss)\n\n loss.backward()\n if args.update_method == \"nccl2\":\n model.apply_collective_grads()\n\n opt.minimize(loss)\n model.clear_gradients()\n print_to_out(out_losses)\n\n\ndef runtime_main(test_class):\n parser = argparse.ArgumentParser(description='Run dist test.')\n parser.add_argument(\n '--role', type=str, required=True, choices=['pserver', 'trainer'])\n parser.add_argument('--endpoints', type=str, required=False, default=\"\")\n parser.add_argument(\n '--update_method',\n type=str,\n default=\"local\",\n choices=[\"pserver\", \"nccl2\", \"local\", \"nccl2_reduce_layer\"])\n parser.add_argument('--trainer_id', type=int, required=False, default=0)\n parser.add_argument('--trainers', type=int, required=False, default=1)\n parser.add_argument('--nccl_comm_num', type=int, required=False, default=1)\n parser.add_argument('--enable_backward_deps', action='store_true')\n parser.add_argument('--use_hallreduce', action='store_true')\n parser.add_argument('--gpu_fleet_api', action='store_true')\n parser.add_argument('--use_local_sgd', action='store_true')\n parser.add_argument('--ut4grad_allreduce', action='store_true')\n parser.add_argument(\n '--hallreduce_inter_nranks', type=int, required=False, default=2)\n parser.add_argument(\n '--current_endpoint', type=str, required=False, default=\"\")\n parser.add_argument('--sync_mode', action='store_true')\n parser.add_argument('--use_cuda', action='store_true')\n parser.add_argument('--use_dgc', action='store_true')\n parser.add_argument('--use_reduce', action='store_true')\n parser.add_argument('--dc_asgd', action='store_true')\n parser.add_argument('--hogwild', action='store_true')\n parser.add_argument(\n '--use_reader_alloc', action='store_true', required=False)\n parser.add_argument('--batch_size', required=False, type=int, default=2)\n parser.add_argument('--lr', required=False, type=float, default=0.001)\n parser.add_argument(\n '--batch_merge_repeat', required=False, type=int, default=1)\n parser.add_argument(\n '--nccl2_reduce_layer_local_run',\n required=False,\n type=bool,\n default=False)\n\n args = parser.parse_args()\n\n model = test_class()\n if args.role == \"pserver\" and args.update_method == \"pserver\":\n model.run_pserver(args)\n elif args.gpu_fleet_api:\n model.run_gpu_fleet_api_trainer(args)\n else:\n model.run_trainer(args)\n\n\nimport paddle.compat as cpt\nimport socket\nfrom contextlib import closing\n\n\nclass TestDistBase(unittest.TestCase):\n def _setup_config(self):\n raise NotImplementedError(\"tests should have _setup_config implemented\")\n\n def _after_setup_config(self):\n if self._enforce_place == \"CPU\":\n self.__use_cuda = False\n self._use_dgc = False\n elif self._enforce_place == \"GPU\":\n self.__use_cuda = True\n else:\n if fluid.core.is_compiled_with_cuda():\n self.__use_cuda = True\n else:\n self.__use_cuda = False\n self._use_dgc = False\n\n if self._use_reduce:\n assert not self._use_dgc\n\n def setUp(self):\n self._trainers = 2\n self._pservers = 2\n self._port_set = set()\n self._ps_endpoints = \"127.0.0.1:%s,127.0.0.1:%s\" % (\n self._find_free_port(), self._find_free_port())\n self._python_interp = sys.executable\n self._sync_mode = True\n self._hogwild_mode = False\n self._enforce_place = None\n self._use_reduce = False\n self._dc_asgd = False # must use with async mode\n self._use_reader_alloc = True\n self._nccl2_mode = False\n self._mp_mode = False\n # FIXME(typhoonzero): I added this stupid argument to enable\n # testing allreduce layers, which users can call layers.allreduce\n # to accumulate tensors at anywhere. Find a better way to do this\n # test, reduce check this argument everywhere.\n self._nccl2_reduce_layer = False\n self._lr = 0.001\n self._use_dgc = False\n self._dygraph = False\n self._nccl_comm_num = 1\n self._enable_backward_deps = False\n self._gpu_fleet_api = False\n self._use_local_sgd = False\n self._ut4grad_allreduce = False\n self._use_hallreduce = False\n self._setup_config()\n self._after_setup_config()\n\n def _find_free_port(self):\n def __free_port():\n with closing(socket.socket(socket.AF_INET,\n socket.SOCK_STREAM)) as s:\n s.bind(('', 0))\n print_to_err(\n type(self).__name__, \"socket name: %s\" % s.getsockname()[1])\n return s.getsockname()[1]\n\n while True:\n port = __free_port()\n if port not in self._port_set:\n self._port_set.add(port)\n return port\n\n def start_pserver(self, model_file, check_error_log, required_envs):\n ps0_ep, ps1_ep = self._ps_endpoints.split(\",\")\n ps_cmd = \"%s\"\n\n if os.getenv('WITH_COVERAGE', 'OFF') == 'ON':\n required_envs['COVERAGE_FILE'] = os.getenv('COVERAGE_FILE', '')\n ps_cmd += \" -m coverage run --branch -p\"\n\n ps_cmd += \" %s --role pserver --endpoints %s --trainer_id 0 --current_endpoint %s --trainers %d --update_method pserver\"\n\n ps0_cmd = ps_cmd % \\\n (self._python_interp, model_file, self._ps_endpoints, ps0_ep,\n self._trainers)\n ps1_cmd = ps_cmd % \\\n (self._python_interp, model_file, self._ps_endpoints, ps1_ep,\n self._trainers)\n\n if self._sync_mode:\n ps0_cmd += \" --sync_mode\"\n ps1_cmd += \" --sync_mode\"\n\n print(ps0_cmd)\n print(ps1_cmd)\n ps0_pipe = open(\"/tmp/ps0_err.log\", \"wb\")\n ps1_pipe = open(\"/tmp/ps1_err.log\", \"wb\")\n\n print_to_err(type(self).__name__, \"going to start pserver process 0\")\n ps0_proc = subprocess.Popen(\n ps0_cmd.strip().split(\" \"),\n stdout=subprocess.PIPE,\n stderr=ps0_pipe,\n env=required_envs)\n print_to_err(type(self).__name__, \"going to start pserver process 1\")\n ps1_proc = subprocess.Popen(\n ps1_cmd.strip().split(\" \"),\n stdout=subprocess.PIPE,\n stderr=ps1_pipe,\n env=required_envs)\n\n return ps0_proc, ps1_proc, ps0_pipe, ps1_pipe\n\n def _run_local(self,\n model,\n envs,\n check_error_log=False,\n batch_size=DEFAULT_BATCH_SIZE,\n batch_merge_repeat=1):\n\n cmd = self._python_interp\n\n if os.getenv('WITH_COVERAGE', 'OFF') == 'ON':\n envs['COVERAGE_FILE'] = os.getenv('COVERAGE_FILE', '')\n cmd += \" -m coverage run --branch -p\"\n\n cmd += \" %s --role trainer --lr %f\" % (model, self._lr)\n\n if batch_size != DEFAULT_BATCH_SIZE:\n cmd += \" --batch_size %d\" % batch_size\n if batch_merge_repeat > 1:\n cmd += \" --batch_merge_repeat %d\" % batch_merge_repeat\n if self._nccl2_reduce_layer:\n cmd += \" --nccl2_reduce_layer_local_run 1\"\n\n if self.__use_cuda:\n cmd += \" --use_cuda\"\n env_local = {\n \"CUDA_VISIBLE_DEVICES\": \"0\",\n \"PADDLE_TRAINERS_NUM\": \"1\",\n \"PADDLE_TRAINER_ID\": \"0\"\n }\n else:\n env_local = {'CPU_NUM': '1'}\n\n env_local.update(envs)\n print(\"local_cmd: {}, env: {}\".format(cmd, env_local))\n\n if check_error_log:\n err_log = open(\"/tmp/trainer.err.log\", \"wb\")\n local_proc = subprocess.Popen(\n cmd.split(\" \"),\n stdout=subprocess.PIPE,\n stderr=err_log,\n env=env_local)\n else:\n local_proc = subprocess.Popen(\n cmd.split(\" \"),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n env=env_local)\n\n local_out, local_err = local_proc.communicate()\n\n if check_error_log:\n err_log.close()\n\n sys.stderr.write('local_stderr: %s\\n' % local_err)\n sys.stderr.write('local_stdout: %s\\n' % pickle.loads(local_out))\n\n return pickle.loads(local_out)\n\n def _run_cluster(self, model, envs, check_error_log):\n # Run dist train to compare with local results\n ps0, ps1, ps0_pipe, ps1_pipe = self.start_pserver(model,\n check_error_log, envs)\n\n ps0_ep, ps1_ep = self._ps_endpoints.split(\",\")\n\n tr_cmd = \"%s\"\n\n if os.getenv('WITH_COVERAGE', 'OFF') == 'ON':\n envs['COVERAGE_FILE'] = os.getenv('COVERAGE_FILE', '')\n tr_cmd += \" -m coverage run --branch -p\"\n\n tr_cmd += \" %s --role trainer --endpoints %s --trainer_id %d --current_endpoint %s --trainers %d --update_method pserver --lr %f\"\n\n tr0_cmd = tr_cmd % \\\n (self._python_interp, model, self._ps_endpoints,\n 0, ps0_ep, self._trainers, self._lr)\n tr1_cmd = tr_cmd % \\\n (self._python_interp, model, self._ps_endpoints,\n 1, ps1_ep, self._trainers, self._lr)\n\n if self._sync_mode:\n tr0_cmd += \" --sync_mode\"\n tr1_cmd += \" --sync_mode\"\n if self._hogwild_mode:\n tr0_cmd += \" --hogwild\"\n tr1_cmd += \" --hogwild\"\n if self._use_reduce:\n tr0_cmd += \" --use_reduce\"\n tr1_cmd += \" --use_reduce\"\n if self._use_reader_alloc:\n tr0_cmd += \" --use_reader_alloc\"\n tr1_cmd += \" --use_reader_alloc\"\n if self.__use_cuda:\n tr0_cmd += \" --use_cuda\"\n tr1_cmd += \" --use_cuda\"\n env0 = {\"CUDA_VISIBLE_DEVICES\": \"0\"}\n env1 = {\"CUDA_VISIBLE_DEVICES\": \"1\"}\n else:\n env0 = {'CPU_NUM': '1'}\n env1 = {'CPU_NUM': '1'}\n\n env0.update(envs)\n env1.update(envs)\n\n print(\"tr0_cmd: {}, env: {}\".format(tr0_cmd, env0))\n print(\"tr1_cmd: {}, env: {}\".format(tr1_cmd, env1))\n tr0_pipe = open(\"/tmp/tr0_err.log\", \"wb\")\n tr1_pipe = open(\"/tmp/tr1_err.log\", \"wb\")\n\n print_to_err(type(self).__name__, \"going to start trainer process 0\")\n tr0_proc = subprocess.Popen(\n tr0_cmd.strip().split(\" \"),\n stdout=subprocess.PIPE,\n stderr=tr0_pipe,\n env=env0)\n print_to_err(type(self).__name__, \"going to start trainer process 1\")\n tr1_proc = subprocess.Popen(\n tr1_cmd.strip().split(\" \"),\n stdout=subprocess.PIPE,\n stderr=tr1_pipe,\n env=env1)\n\n # Wait until trainer process terminate\n while True:\n stat0 = tr0_proc.poll()\n time.sleep(0.1)\n if stat0 is not None:\n break\n while True:\n stat1 = tr1_proc.poll()\n time.sleep(0.1)\n if stat1 is not None:\n break\n\n tr0_out, tr0_err = tr0_proc.communicate()\n tr1_out, tr1_err = tr1_proc.communicate()\n\n # close trainer file\n tr0_pipe.close()\n tr1_pipe.close()\n ps0_pipe.close()\n ps1_pipe.close()\n\n ps0.terminate()\n ps1.terminate()\n\n return pickle.loads(tr0_out), pickle.loads(tr1_out)\n\n def _get_nccl2_trainer_cmd(self, model, ep, update_method, trainer_id,\n trainer_num):\n env = {}\n tr_cmd = \"%s -u\"\n\n if os.getenv('WITH_COVERAGE', 'OFF') == 'ON':\n tr_cmd += \" -m coverage run --branch -p\"\n\n tr_cmd += \" %s --role trainer --endpoints %s --trainer_id %d --current_endpoint %s --update_method %s --lr %f\"\n\n tr_cmd = tr_cmd % \\\n (self._python_interp, model, self._ps_endpoints,\n trainer_id, ep, update_method, self._lr)\n\n if self._use_reduce:\n tr_cmd += \" --use_reduce\"\n if self._use_reader_alloc:\n tr_cmd += \" --use_reader_alloc\"\n if self.__use_cuda:\n tr_cmd += \" --use_cuda\"\n env.update({\n \"CUDA_VISIBLE_DEVICES\": \"{}\".format(trainer_id),\n \"PADDLE_TRAINERS_NUM\": \"{}\".format(trainer_num),\n \"PADDLE_TRAINER_ID\": \"{}\".format(trainer_id),\n \"PADDLE_TRAINER_ENDPOINTS\": self._ps_endpoints,\n \"PADDLE_CURRENT_ENDPOINT\": ep,\n })\n else:\n env.update({'CPU_NUM': '1'})\n\n if self._use_dgc:\n tr_cmd += \" --use_dgc\"\n\n if self._mp_mode:\n env = {\"FLAGS_selected_gpus\": \"{}\".format(trainer_id)}\n\n if self._nccl_comm_num > 1:\n tr_cmd += \" --nccl_comm_num {}\".format(self._nccl_comm_num)\n\n if self._use_hallreduce:\n tr_cmd += \" --use_hallreduce --hallreduce_inter_nranks 2\"\n\n if self._enable_backward_deps:\n tr_cmd += \" --enable_backward_deps\"\n\n if self._gpu_fleet_api:\n tr_cmd += \" --gpu_fleet_api\"\n if self._use_local_sgd:\n tr_cmd += \" --use_local_sgd\"\n if self._ut4grad_allreduce:\n tr_cmd += \" --ut4grad_allreduce\"\n\n if os.getenv('WITH_COVERAGE', 'OFF') == 'ON':\n env['COVERAGE_FILE'] = os.getenv('COVERAGE_FILE', '')\n\n return tr_cmd, env\n\n def _run_cluster_nccl2(self, model, envs, nccl2_reduce_layer,\n check_error_log):\n if self._use_hallreduce:\n self._ps_endpoints = \"\"\n for i in range(0, 4):\n self._ps_endpoints += \"127.0.0.1:%s,\" % (self._find_free_port())\n self._ps_endpoints = self._ps_endpoints[:-1]\n\n # NOTE: we reuse ps_endpoints as nccl2 worker endpoints\n worker_endpoints = self._ps_endpoints.split(\",\")\n if nccl2_reduce_layer:\n update_method = \"nccl2_reduce_layer\"\n else:\n update_method = \"nccl2\"\n\n trainer_num = len(worker_endpoints)\n\n procs = []\n pipes = []\n for i in range(0, trainer_num):\n tr_cmd, tr_env = self._get_nccl2_trainer_cmd(\n model, worker_endpoints[i], update_method, i, trainer_num)\n tr_env.update(envs)\n print(\"use_hallreduce:{} tr_cmd:{}, env: {}\".format(\n self._use_hallreduce, tr_cmd, tr_env))\n\n tr_pipe = open(\"/tmp/tr{}_err.log\".format(i), \"wb\")\n\n print_to_err(\n type(self).__name__,\n \"going to start process {} with nccl2\".format(i))\n tr_proc = subprocess.Popen(\n tr_cmd.strip().split(\" \"),\n stdout=subprocess.PIPE,\n stderr=tr_pipe,\n env=tr_env)\n\n procs.append(tr_proc)\n pipes.append(tr_pipe)\n\n outs = []\n for i in range(0, trainer_num):\n tr_out, tr_err = procs[i].communicate()\n outs.append(tr_out)\n pipes[i].close()\n sys.stderr.write('trainer {} stderr: {}\\n'.format(i, tr_err))\n\n if check_error_log:\n print(\"outs[0]:\", outs[0])\n print(\"outs[1]:\", outs[1])\n return pickle.loads(outs[0]), pickle.loads(outs[1])\n\n def check_with_place(self,\n model_file,\n delta=1e-3,\n check_error_log=False,\n need_envs={}):\n # TODO(typhoonzero): should auto adapt GPU count on the machine.\n required_envs = {\n \"PATH\": os.getenv(\"PATH\", \"\"),\n \"PYTHONPATH\": os.getenv(\"PYTHONPATH\", \"\"),\n \"LD_LIBRARY_PATH\": os.getenv(\"LD_LIBRARY_PATH\", \"\"),\n \"FLAGS_fraction_of_gpu_memory_to_use\": \"0.15\",\n \"FLAGS_rpc_deadline\": \"30000\", # 5sec to fail fast\n \"FLAGS_cudnn_deterministic\": \"1\",\n \"http_proxy\": \"\",\n \"NCCL_P2P_DISABLE\": \"1\",\n \"NCCL_SHM_DISABLE\": \"1\"\n }\n\n required_envs.update(need_envs)\n\n if check_error_log:\n required_envs[\"GLOG_v\"] = \"10\"\n required_envs[\"GLOG_logtostderr\"] = \"1\"\n\n local_losses \\\n = self._run_local(model_file, required_envs,\n check_error_log)\n if self._nccl2_mode:\n if self._nccl2_reduce_layer:\n tr0_losses, tr1_losses = self._run_cluster_nccl2(\n model_file, required_envs, True, check_error_log)\n else:\n tr0_losses, tr1_losses = self._run_cluster_nccl2(\n model_file, required_envs, False, check_error_log)\n else:\n tr0_losses, tr1_losses = self._run_cluster(\n model_file, required_envs, check_error_log)\n\n for step_id in range(RUN_STEP):\n local_loss = local_losses[step_id]\n tr0_loss = tr0_losses[step_id]\n tr1_loss = tr1_losses[step_id]\n dist_loss = (np.array([tr0_loss]) + np.array([tr1_loss])) / 2\n print(\"=======\", local_loss, \":\", dist_loss[0], \"=======\")\n self.assertAlmostEqual(local_loss, dist_loss[0], delta=delta)\n"
] | [
[
"numpy.random.random",
"numpy.allclose",
"numpy.ones",
"numpy.transpose",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
],
[
"numpy.hstack",
"numpy.random.random",
"numpy.full",
"numpy.random.rand",
"numpy.array",
"numpy.zeros"
],
[
"numpy.split",
"numpy.random.random"
],
[
"numpy.random.random",
"numpy.sqrt",
"numpy.random.seed",
"numpy.random.random_sample",
"numpy.mean",
"numpy.var",
"numpy.array",
"numpy.sum"
],
[
"numpy.random.random",
"numpy.reshape",
"numpy.tile",
"numpy.max",
"numpy.transpose",
"numpy.mod",
"numpy.zeros",
"numpy.sum"
],
[
"numpy.array",
"numpy.random.random",
"numpy.zeros",
"numpy.ones"
],
[
"numpy.array",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xxheyu/CL-Face-Anti-spoofing | [
"b6c427151572bfafd41355a3942a361a6579d19a"
] | [
"util.py"
] | [
"from __future__ import print_function\n\nimport math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision.utils as vutils\nimport matplotlib.pyplot as plt\nplt.switch_backend('agg') \n\n\nclass TwoCropTransform:\n \"\"\"Create two crops of the same image\"\"\"\n def __init__(self, transform):\n self.transform = transform\n\n def __call__(self, x):\n return [self.transform(x), self.transform(x)]\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n with torch.no_grad():\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\ndef adjust_learning_rate(args, optimizer, epoch):\n lr = args.learning_rate\n if args.cosine:\n eta_min = lr * (args.lr_decay_rate ** 3)\n lr = eta_min + (lr - eta_min) * (\n 1 + math.cos(math.pi * epoch / args.epochs)) / 2\n else:\n steps = np.sum(epoch > np.asarray(args.lr_decay_epochs))\n if steps > 0:\n lr = lr * (args.lr_decay_rate ** steps)\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef warmup_learning_rate(args, epoch, batch_id, total_batches, optimizer):\n if args.warm and epoch <= args.warm_epochs:\n p = (batch_id + (epoch - 1) * total_batches) / \\\n (args.warm_epochs * total_batches)\n lr = args.warmup_from + p * (args.warmup_to - args.warmup_from)\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef set_optimizer(opt, model):\n optimizer = optim.SGD(model.parameters(),\n lr=opt.learning_rate,\n momentum=opt.momentum,\n weight_decay=opt.weight_decay)\n return optimizer\n\n\ndef save_model(model, optimizer, opt, epoch, save_file):\n print('==> Saving...')\n state = {\n 'opt': opt,\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'epoch': epoch,\n }\n torch.save(state, save_file)\n del state\n\ndef ImageShow(data_loader, encoder, decoder, opt, epoch, save=True):\n encoder.eval()\n decoder.eval()\n\n fake_img, real_img = [], []\n for i, (images, labels, idxs) in enumerate(data_loader):\n if i > 1:\n break\n if torch.cuda.is_available():\n images = images.cuda(non_blocking=True)\n batch_size = labels.size(0)\n # inference\n _, features, feat_enc = encoder(images.detach())\n feat_enc = feat_enc[5].view(batch_size, 1, 32, 64)\n out = decoder(feat_enc)\n fake_img.append(vutils.make_grid(out.detach().cpu(), padding=2, normalize=True))\n real_img.append(vutils.make_grid(images.detach().cpu(), padding=2, normalize=True))\n\n # Plot the fake images from the first epoch\n plt.subplot(1, 2, 1)\n plt.axis(\"off\")\n plt.title(\"Fake Images\")\n plt.imshow(np.transpose(fake_img[-1], (1, 2, 0)))\n \n\n # Plot the real images from the first epoch\n plt.subplot(1, 2, 2)\n plt.axis(\"off\")\n plt.title(\"Real Images\")\n plt.imshow(np.transpose(real_img[-1], (1, 2, 0)))\n if save:\n plt.savefig('./figures/images/alpha_5/real_fake_epoch_{epoch}.jpg'.format(epoch=epoch))\n print('**********************')\n print('images saved')\n else:\n plt.show()\n \n plt.close()\n \n\ndef normalization(data):\n _range = np.max(data) - np.min(data)\n return (data - np.min(data)) / _range\n\ndef PSNR(fake_img, ori_img):\n MSE = nn.MSELoss()\n batch_size = fake_img.size(0)\n return - 10 * MSE(fake_img.cuda(), ori_img.cuda()).log10()\n\n\ndef ReconstructionErrorHist(data_loader, encoder, decoder, opt, epoch, save=True):\n encoder.eval()\n decoder.eval()\n\n all_labels = []\n fake_img, real_img = torch.Tensor(), torch.Tensor()\n for i, (images, labels, idxs) in enumerate(data_loader):\n batch_size = labels.size(0)\n # Modify labels first\n for ind, k in enumerate(labels):\n if k in opt.original_index:\n labels[ind] = opt.original_index.index(k)\n else:\n labels[ind] = len(opt.original_index) # label as last label\n\n if torch.cuda.is_available():\n images = images.cuda(non_blocking=True)\n labels = labels.cuda(non_blocking=True)\n\n all_labels.append(labels.data.cpu().numpy())\n\n # inference\n _, features, feat_enc = encoder(images.detach())\n feat_enc = feat_enc[5].view(batch_size, 1, 32, 64)\n out = decoder(feat_enc)\n # for renconstruction error histogram\n real_img = torch.cat([real_img, images.detach().cpu()], dim=0)\n fake_img = torch.cat([fake_img, out.detach().cpu()], dim=0)\n\n test_labels = np.concatenate(all_labels, 0)\n\n MSE = nn.MSELoss()\n bsz = fake_img.size(0)\n match_err = []\n unmatch_err = []\n\n for i in range(bsz):\n if test_labels[i] == len(opt.original_index):\n #unmatch_err.append(torch.mean(torch.abs(fake_img[i] - real_img[i])).data.cpu().numpy())\n unmatch_err.append(MSE(fake_img[i], real_img[i]).data.cpu().numpy())\n else:\n #match_err.append(torch.mean(torch.abs(fake_img[i] - real_img[i])).data.cpu().numpy())\n match_err.append(MSE(fake_img[i], real_img[i]).data.cpu().numpy())\n\n match_err = np.array(match_err)\n unmatch_err = np.array(unmatch_err)\n # print('**********************')\n # print('size of matching pairs is {size}'.format(size=match_err.size))\n # print('size of unmatching pairs is {size}'.format(size=unmatch_err.size))\n\n # plot histogram of reconstruction error\n bins_1 = np.linspace(min(match_err), max(match_err), 300)\n bins_2 = np.linspace(min(unmatch_err), max(unmatch_err), 200)\n plt.hist(match_err, bins_1, facecolor='g', label='Known')\n plt.hist(unmatch_err, bins_2, facecolor='r', label='Unknown')\n plt.xlabel('Reconstruction Error')\n plt.ylabel('Histogram')\n plt.legend()\n if save:\n plt.savefig('./figures/hist/alpha_5/hist_epoch_{epoch}.jpg'.format(epoch=epoch))\n print('**********************')\n print('histogram saved')\n print('**********************')\n else:\n plt.show()\n \n plt.close()\n "
] | [
[
"matplotlib.pyplot.legend",
"numpy.asarray",
"numpy.concatenate",
"numpy.max",
"torch.no_grad",
"torch.cuda.is_available",
"torch.save",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.title",
"numpy.min",
"matplotlib.pyplot.switch_backend",
"numpy.transpose",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"torch.Tensor",
"matplotlib.pyplot.xlabel",
"torch.nn.MSELoss"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gpetretto/pymatgen | [
"68a7c51fa3e2a2392534d29eae1c9045e8ff9e73"
] | [
"pymatgen/io/cif.py"
] | [
"# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\nfrom __future__ import division, unicode_literals, print_function\n\nimport math\nimport re\nimport os\nimport textwrap\nimport warnings\nfrom collections import OrderedDict, deque\n\nimport six\nfrom six.moves import zip, cStringIO\n\nimport numpy as np\nfrom functools import partial\n\ntry:\n from inspect import getfullargspec as getargspec\nexcept ImportError:\n from inspect import getargspec\nfrom itertools import groupby\nfrom pymatgen.core.periodic_table import Element, Specie, get_el_sp, DummySpecie\nfrom monty.io import zopen\nfrom pymatgen.util.coord import in_coord_list_pbc, pbc_diff, \\\n find_in_coord_list_pbc\nfrom monty.string import remove_non_ascii\nfrom pymatgen.core.lattice import Lattice\nfrom pymatgen.core.structure import Structure\nfrom pymatgen.core.composition import Composition\nfrom pymatgen.core.operations import SymmOp\nfrom pymatgen.symmetry.groups import SpaceGroup, SYMM_DATA\nfrom pymatgen.symmetry.analyzer import SpacegroupAnalyzer\nfrom pymatgen.electronic_structure.core import Magmom\nfrom pymatgen.core.operations import MagSymmOp\nfrom pymatgen.symmetry.maggroups import MagneticSpaceGroup\n\ntry:\n from pybtex.database import BibliographyData, Entry\nexcept ImportError:\n warnings.warn(\"Please install optional dependency pybtex if you\"\n \"want to extract references from CIF files.\")\n\n\"\"\"\nWrapper classes for Cif input and output from Structures.\n\"\"\"\n\n__author__ = \"Shyue Ping Ong, Will Richards, Matthew Horton\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"4.0\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"[email protected]\"\n__status__ = \"Production\"\n__date__ = \"Sep 23, 2011\"\n\nsub_spgrp = partial(re.sub, r\"[\\s_]\", \"\")\n\nspace_groups = {sub_spgrp(k): k\n for k in SYMM_DATA['space_group_encoding'].keys()}\n\nspace_groups.update({sub_spgrp(k): k\n for k in SYMM_DATA['space_group_encoding'].keys()})\n\n_COD_DATA = None\n\n\ndef _get_cod_data():\n global _COD_DATA\n if _COD_DATA is None:\n import pymatgen\n with open(os.path.join(pymatgen.symmetry.__path__[0],\n \"symm_ops.json\")) \\\n as f:\n import json\n _COD_DATA = json.load(f)\n\n return _COD_DATA\n\n\nclass CifBlock(object):\n maxlen = 70 # not quite 80 so we can deal with semicolons and things\n\n def __init__(self, data, loops, header):\n \"\"\"\n Object for storing cif data. All data is stored in a single dictionary.\n Data inside loops are stored in lists in the data dictionary, and\n information on which keys are grouped together are stored in the loops\n attribute.\n\n Args:\n data: dict or OrderedDict of data to go into the cif. Values should\n be convertible to string, or lists of these if the key is\n in a loop\n loops: list of lists of keys, grouped by which loop they should\n appear in\n header: name of the block (appears after the data_ on the first\n line)\n \"\"\"\n self.loops = loops\n self.data = data\n # AJ says: CIF Block names cannot be more than 75 characters or you\n # get an Exception\n self.header = header[:74]\n\n def __eq__(self, other):\n return self.loops == other.loops \\\n and self.data == other.data \\\n and self.header == other.header\n\n def __getitem__(self, key):\n return self.data[key]\n\n def __str__(self):\n \"\"\"\n Returns the cif string for the data block\n \"\"\"\n s = [\"data_{}\".format(self.header)]\n keys = self.data.keys()\n written = []\n for k in keys:\n if k in written:\n continue\n for l in self.loops:\n # search for a corresponding loop\n if k in l:\n s.append(self._loop_to_string(l))\n written.extend(l)\n break\n if k not in written:\n # k didn't belong to a loop\n v = self._format_field(self.data[k])\n if len(k) + len(v) + 3 < self.maxlen:\n s.append(\"{} {}\".format(k, v))\n else:\n s.extend([k, v])\n return \"\\n\".join(s)\n\n def _loop_to_string(self, loop):\n s = \"loop_\"\n for l in loop:\n s += '\\n ' + l\n for fields in zip(*[self.data[k] for k in loop]):\n line = \"\\n\"\n for val in map(self._format_field, fields):\n if val[0] == \";\":\n s += line + \"\\n\" + val\n line = \"\\n\"\n elif len(line) + len(val) + 2 < self.maxlen:\n line += \" \" + val\n else:\n s += line\n line = '\\n ' + val\n s += line\n return s\n\n def _format_field(self, v):\n v = v.__str__().strip()\n if len(v) > self.maxlen:\n return ';\\n' + textwrap.fill(v, self.maxlen) + '\\n;'\n # add quotes if necessary\n if v == '':\n return '\"\"'\n if (\" \" in v or v[0] == \"_\") \\\n and not (v[0] == \"'\" and v[-1] == \"'\") \\\n and not (v[0] == '\"' and v[-1] == '\"'):\n if \"'\" in v:\n q = '\"'\n else:\n q = \"'\"\n v = q + v + q\n return v\n\n @classmethod\n def _process_string(cls, string):\n # remove comments\n string = re.sub(r\"(\\s|^)#.*$\", \"\", string, flags=re.MULTILINE)\n # remove empty lines\n string = re.sub(r\"^\\s*\\n\", \"\", string, flags=re.MULTILINE)\n # remove non_ascii\n string = remove_non_ascii(string)\n\n # since line breaks in .cif files are mostly meaningless,\n # break up into a stream of tokens to parse, rejoining multiline\n # strings (between semicolons)\n q = deque()\n multiline = False\n ml = []\n # this regex splits on spaces, except when in quotes.\n # starting quotes must not be preceded by non-whitespace\n # (these get eaten by the first expression)\n # ending quotes must not be followed by non-whitespace\n p = re.compile(r'''([^'\"\\s][\\S]*)|'(.*?)'(?!\\S)|\"(.*?)\"(?!\\S)''')\n for l in string.splitlines():\n if multiline:\n if l.startswith(\";\"):\n multiline = False\n q.append(('', '', '', ' '.join(ml)))\n ml = []\n l = l[1:].strip()\n else:\n ml.append(l)\n continue\n if l.startswith(\";\"):\n multiline = True\n ml.append(l[1:].strip())\n else:\n for s in p.findall(l):\n # s is tuple. location of the data in the tuple\n # depends on whether it was quoted in the input\n q.append(s)\n return q\n\n @classmethod\n def from_string(cls, string):\n q = cls._process_string(string)\n header = q.popleft()[0][5:]\n data = OrderedDict()\n loops = []\n while q:\n s = q.popleft()\n # cif keys aren't in quotes, so show up in s[0]\n if s[0] == \"_eof\":\n break\n if s[0].startswith(\"_\"):\n data[s[0]] = \"\".join(q.popleft())\n elif s[0].startswith(\"loop_\"):\n columns = []\n items = []\n while q:\n s = q[0]\n if s[0].startswith(\"loop_\") or not s[0].startswith(\"_\"):\n break\n columns.append(\"\".join(q.popleft()))\n data[columns[-1]] = []\n while q:\n s = q[0]\n if s[0].startswith(\"loop_\") or s[0].startswith(\"_\"):\n break\n items.append(\"\".join(q.popleft()))\n n = len(items) // len(columns)\n assert len(items) % n == 0\n loops.append(columns)\n for k, v in zip(columns * n, items):\n data[k].append(v.strip())\n elif \"\".join(s).strip() != \"\":\n warnings.warn(\"Possible error in cif format\"\n \" error at {}\".format(\"\".join(s).strip()))\n return cls(data, loops, header)\n\n\nclass CifFile(object):\n \"\"\"\n Reads and parses CifBlocks from a .cif file or string\n \"\"\"\n\n def __init__(self, data, orig_string=None, comment=None):\n \"\"\"\n Args:\n data (OrderedDict): Of CifBlock objects.å\n orig_string (str): The original cif string.\n comment (str): Comment string.\n \"\"\"\n self.data = data\n self.orig_string = orig_string\n self.comment = comment or \"# generated using pymatgen\"\n\n def __str__(self):\n s = [\"%s\" % v for v in self.data.values()]\n return self.comment + \"\\n\" + \"\\n\".join(s) + \"\\n\"\n\n @classmethod\n def from_string(cls, string):\n d = OrderedDict()\n for x in re.split(r\"^\\s*data_\", \"x\\n\" + string,\n flags=re.MULTILINE | re.DOTALL)[1:]:\n\n # Skip over Cif block that contains powder diffraction data.\n # Some elements in this block were missing from CIF files in\n # Springer materials/Pauling file DBs.\n # This block anyway does not contain any structure information, and\n # CifParser was also not parsing it.\n if 'powder_pattern' in re.split(r\"\\n\", x, 1)[0]:\n continue\n c = CifBlock.from_string(\"data_\" + x)\n d[c.header] = c\n return cls(d, string)\n\n @classmethod\n def from_file(cls, filename):\n with zopen(filename, \"rt\", errors=\"replace\") as f:\n return cls.from_string(f.read())\n\n\nclass CifParser(object):\n \"\"\"\n Parses a cif file\n\n Args:\n filename (str): Cif filename. bzipped or gzipped cifs are fine too.\n occupancy_tolerance (float): If total occupancy of a site is between 1\n and occupancy_tolerance, the occupancies will be scaled down to 1.\n site_tolerance (float): This tolerance is used to determine if two\n sites are sitting in the same position, in which case they will be\n combined to a single disordered site. Defaults to 1e-4.\n \"\"\"\n\n def __init__(self, filename, occupancy_tolerance=1., site_tolerance=1e-4):\n self._occupancy_tolerance = occupancy_tolerance\n self._site_tolerance = site_tolerance\n if isinstance(filename, six.string_types):\n self._cif = CifFile.from_file(filename)\n else:\n self._cif = CifFile.from_string(filename.read())\n\n # store if CIF contains features from non-core CIF dictionaries\n # e.g. magCIF\n self.feature_flags = {}\n\n def is_magcif():\n \"\"\"\n Checks to see if file appears to be a magCIF file (heuristic).\n \"\"\"\n # Doesn't seem to be a canonical way to test if file is magCIF or\n # not, so instead check for magnetic symmetry datanames\n prefixes = ['_space_group_magn', '_atom_site_moment',\n '_space_group_symop_magn']\n for d in self._cif.data.values():\n for k in d.data.keys():\n for prefix in prefixes:\n if prefix in k:\n return True\n return False\n\n self.feature_flags['magcif'] = is_magcif()\n\n def is_magcif_incommensurate():\n \"\"\"\n Checks to see if file contains an incommensurate magnetic\n structure (heuristic).\n \"\"\"\n # Doesn't seem to be a canonical way to test if magCIF file\n # describes incommensurate strucure or not, so instead check\n # for common datanames\n if not self.feature_flags[\"magcif\"]:\n return False\n prefixes = ['_cell_modulation_dimension', '_cell_wave_vector']\n for d in self._cif.data.values():\n for k in d.data.keys():\n for prefix in prefixes:\n if prefix in k:\n return True\n return False\n\n self.feature_flags['magcif_incommensurate'] = is_magcif_incommensurate()\n\n for k in self._cif.data.keys():\n # pass individual CifBlocks to _sanitize_data\n self._cif.data[k] = self._sanitize_data(self._cif.data[k])\n\n @staticmethod\n def from_string(cif_string, occupancy_tolerance=1.):\n \"\"\"\n Creates a CifParser from a string.\n\n Args:\n cif_string (str): String representation of a CIF.\n occupancy_tolerance (float): If total occupancy of a site is\n between 1 and occupancy_tolerance, the occupancies will be\n scaled down to 1.\n\n Returns:\n CifParser\n \"\"\"\n stream = cStringIO(cif_string)\n return CifParser(stream, occupancy_tolerance)\n\n def _sanitize_data(self, data):\n \"\"\"\n Some CIF files do not conform to spec. This function corrects\n known issues, particular in regards to Springer materials/\n Pauling files.\n\n This function is here so that CifParser can assume its\n input conforms to spec, simplifying its implementation.\n :param data: CifBlock\n :return: data CifBlock\n \"\"\"\n\n \"\"\"\n This part of the code deals with handling formats of data as found in\n CIF files extracted from the Springer Materials/Pauling File\n databases, and that are different from standard ICSD formats.\n \"\"\"\n\n # Check to see if \"_atom_site_type_symbol\" exists, as some test CIFs do\n # not contain this key.\n if \"_atom_site_type_symbol\" in data.data.keys():\n\n # Keep a track of which data row needs to be removed.\n # Example of a row: Nb,Zr '0.8Nb + 0.2Zr' .2a .m-3m 0 0 0 1 14\n # 'rhombic dodecahedron, Nb<sub>14</sub>'\n # Without this code, the above row in a structure would be parsed\n # as an ordered site with only Nb (since\n # CifParser would try to parse the first two characters of the\n # label \"Nb,Zr\") and occupancy=1.\n # However, this site is meant to be a disordered site with 0.8 of\n # Nb and 0.2 of Zr.\n idxs_to_remove = []\n\n new_atom_site_label = []\n new_atom_site_type_symbol = []\n new_atom_site_occupancy = []\n new_fract_x = []\n new_fract_y = []\n new_fract_z = []\n\n for idx, el_row in enumerate(data[\"_atom_site_label\"]):\n\n # CIF files from the Springer Materials/Pauling File have\n # switched the label and symbol. Thus, in the\n # above shown example row, '0.8Nb + 0.2Zr' is the symbol.\n # Below, we split the strings on ' + ' to\n # check if the length (or number of elements) in the label and\n # symbol are equal.\n if len(data[\"_atom_site_type_symbol\"][idx].split(' + ')) > \\\n len(data[\"_atom_site_label\"][idx].split(' + ')):\n\n # Dictionary to hold extracted elements and occupancies\n els_occu = {}\n\n # parse symbol to get element names and occupancy and store\n # in \"els_occu\"\n symbol_str = data[\"_atom_site_type_symbol\"][idx]\n symbol_str_lst = symbol_str.split(' + ')\n for elocc_idx in range(len(symbol_str_lst)):\n # Remove any bracketed items in the string\n symbol_str_lst[elocc_idx] = re.sub(\n r'\\([0-9]*\\)', '',\n symbol_str_lst[elocc_idx].strip())\n\n # Extract element name and its occupancy from the\n # string, and store it as a\n # key-value pair in \"els_occ\".\n els_occu[str(re.findall(r'\\D+', symbol_str_lst[\n elocc_idx].strip())[1]).replace('<sup>', '')] = \\\n float('0' + re.findall(r'\\.?\\d+', symbol_str_lst[\n elocc_idx].strip())[1])\n\n x = str2float(data[\"_atom_site_fract_x\"][idx])\n y = str2float(data[\"_atom_site_fract_y\"][idx])\n z = str2float(data[\"_atom_site_fract_z\"][idx])\n\n for et, occu in els_occu.items():\n # new atom site labels have 'fix' appended\n new_atom_site_label.append(\n et + '_fix' + str(len(new_atom_site_label)))\n new_atom_site_type_symbol.append(et)\n new_atom_site_occupancy.append(str(occu))\n new_fract_x.append(str(x))\n new_fract_y.append(str(y))\n new_fract_z.append(str(z))\n\n idxs_to_remove.append(idx)\n\n # Remove the original row by iterating over all keys in the CIF\n # data looking for lists, which indicates\n # multiple data items, one for each row, and remove items from the\n # list that corresponds to the removed row,\n # so that it's not processed by the rest of this function (which\n # would result in an error).\n for original_key in data.data:\n if isinstance(data.data[original_key], list):\n for id in sorted(idxs_to_remove, reverse=True):\n del data.data[original_key][id]\n\n if len(idxs_to_remove) > 0:\n data.data[\"_atom_site_label\"] += new_atom_site_label\n data.data[\"_atom_site_type_symbol\"] += new_atom_site_type_symbol\n data.data[\"_atom_site_occupancy\"] += new_atom_site_occupancy\n data.data[\"_atom_site_fract_x\"] += new_fract_x\n data.data[\"_atom_site_fract_y\"] += new_fract_y\n data.data[\"_atom_site_fract_z\"] += new_fract_z\n\n \"\"\"\n This fixes inconsistencies in naming of several magCIF tags\n as a result of magCIF being in widespread use prior to\n specification being finalized (on advice of Branton Campbell).\n \"\"\"\n\n if self.feature_flags[\"magcif\"]:\n\n # CIF-1 style has all underscores, interim standard\n # had period before magn instead of before the final\n # component (e.g. xyz)\n # we want to standardize on a specific key, to simplify\n # parsing code\n correct_keys = [\"_space_group_symop_magn_operation.xyz\",\n \"_space_group_symop_magn_centering.xyz\",\n \"_space_group_magn.name_BNS\",\n \"_space_group_magn.number_BNS\",\n \"_atom_site_moment_crystalaxis_x\",\n \"_atom_site_moment_crystalaxis_y\",\n \"_atom_site_moment_crystalaxis_z\",\n \"_atom_site_moment_label\"]\n\n # cannot mutate OrderedDict during enumeration,\n # so store changes we want to make\n changes_to_make = {}\n\n for original_key in data.data:\n for correct_key in correct_keys:\n # convert to all underscore\n trial_key = \"_\".join(correct_key.split(\".\"))\n test_key = \"_\".join(original_key.split(\".\"))\n if trial_key == test_key:\n changes_to_make[correct_key] = original_key\n\n # make changes\n for correct_key, original_key in changes_to_make.items():\n data.data[correct_key] = data.data[original_key]\n\n # renamed_keys maps interim_keys to final_keys\n renamed_keys = {\n \"_magnetic_space_group.transform_to_standard_Pp_abc\":\n \"_space_group_magn.transform_BNS_Pp_abc\"}\n changes_to_make = {}\n\n for interim_key, final_key in renamed_keys.items():\n if data.data.get(interim_key):\n changes_to_make[final_key] = interim_key\n for final_key, interim_key in changes_to_make.items():\n data.data[final_key] = data.data[interim_key]\n\n return data\n\n def _unique_coords(self, coords_in, magmoms_in=None, lattice=None):\n \"\"\"\n Generate unique coordinates using coord and symmetry positions\n and also their corresponding magnetic moments, if supplied.\n \"\"\"\n coords = []\n if magmoms_in:\n magmoms = []\n if len(magmoms_in) != len(coords_in):\n raise ValueError\n for tmp_coord, tmp_magmom in zip(coords_in, magmoms_in):\n for op in self.symmetry_operations:\n coord = op.operate(tmp_coord)\n coord = np.array([i - math.floor(i) for i in coord])\n if isinstance(op, MagSymmOp):\n # Up to this point, magmoms have been defined relative\n # to crystal axis. Now convert to Cartesian and into\n # a Magmom object.\n magmom = Magmom.from_moment_relative_to_crystal_axes(\n op.operate_magmom(tmp_magmom),\n lattice=lattice\n )\n else:\n magmom = Magmom(tmp_magmom)\n if not in_coord_list_pbc(coords, coord,\n atol=self._site_tolerance):\n coords.append(coord)\n magmoms.append(magmom)\n return coords, magmoms\n else:\n for tmp_coord in coords_in:\n for op in self.symmetry_operations:\n coord = op.operate(tmp_coord)\n coord = np.array([i - math.floor(i) for i in coord])\n if not in_coord_list_pbc(coords, coord,\n atol=self._site_tolerance):\n coords.append(coord)\n return coords, [Magmom(0)] * len(coords) # return dummy magmoms\n\n def get_lattice(self, data, length_strings=(\"a\", \"b\", \"c\"),\n angle_strings=(\"alpha\", \"beta\", \"gamma\"),\n lattice_type=None):\n \"\"\"\n Generate the lattice from the provided lattice parameters. In\n the absence of all six lattice parameters, the crystal system\n and necessary parameters are parsed\n \"\"\"\n try:\n\n lengths = [str2float(data[\"_cell_length_\" + i])\n for i in length_strings]\n angles = [str2float(data[\"_cell_angle_\" + i])\n for i in angle_strings]\n if not lattice_type:\n return Lattice.from_lengths_and_angles(lengths, angles)\n\n else:\n return getattr(Lattice, lattice_type)(*(lengths + angles))\n\n except KeyError:\n # Missing Key search for cell setting\n for lattice_lable in [\"_symmetry_cell_setting\",\n \"_space_group_crystal_system\"]:\n if data.data.get(lattice_lable):\n lattice_type = data.data.get(lattice_lable).lower()\n try:\n\n required_args = getargspec(\n getattr(Lattice, lattice_type)).args\n\n lengths = (l for l in length_strings\n if l in required_args)\n angles = (a for a in angle_strings\n if a in required_args)\n return self.get_lattice(data, lengths, angles,\n lattice_type=lattice_type)\n except AttributeError as exc:\n warnings.warn(exc)\n\n else:\n return None\n\n def get_symops(self, data):\n \"\"\"\n In order to generate symmetry equivalent positions, the symmetry\n operations are parsed. If the symops are not present, the space\n group symbol is parsed, and symops are generated.\n \"\"\"\n symops = []\n for symmetry_label in [\"_symmetry_equiv_pos_as_xyz\",\n \"_symmetry_equiv_pos_as_xyz_\",\n \"_space_group_symop_operation_xyz\",\n \"_space_group_symop_operation_xyz_\"]:\n if data.data.get(symmetry_label):\n xyz = data.data.get(symmetry_label)\n if isinstance(xyz, six.string_types):\n warnings.warn(\"A 1-line symmetry op P1 CIF is detected!\")\n xyz = [xyz]\n try:\n symops = [SymmOp.from_xyz_string(s)\n for s in xyz]\n break\n except ValueError:\n continue\n if not symops:\n # Try to parse symbol\n for symmetry_label in [\"_symmetry_space_group_name_H-M\",\n \"_symmetry_space_group_name_H_M\",\n \"_symmetry_space_group_name_H-M_\",\n \"_symmetry_space_group_name_H_M_\",\n \"_space_group_name_Hall\",\n \"_space_group_name_Hall_\",\n \"_space_group_name_H-M_alt\",\n \"_space_group_name_H-M_alt_\",\n \"_symmetry_space_group_name_hall\",\n \"_symmetry_space_group_name_hall_\",\n \"_symmetry_space_group_name_h-m\",\n \"_symmetry_space_group_name_h-m_\"]:\n sg = data.data.get(symmetry_label)\n\n if sg:\n sg = sub_spgrp(sg)\n try:\n spg = space_groups.get(sg)\n if spg:\n symops = SpaceGroup(spg).symmetry_ops\n warnings.warn(\n \"No _symmetry_equiv_pos_as_xyz type key found. \"\n \"Spacegroup from %s used.\" % symmetry_label)\n break\n except ValueError:\n # Ignore any errors\n pass\n\n try:\n for d in _get_cod_data():\n if sg == re.sub(r\"\\s+\", \"\",\n d[\"hermann_mauguin\"]):\n xyz = d[\"symops\"]\n symops = [SymmOp.from_xyz_string(s)\n for s in xyz]\n warnings.warn(\n \"No _symmetry_equiv_pos_as_xyz type key found. \"\n \"Spacegroup from %s used.\" % symmetry_label)\n break\n except Exception as ex:\n continue\n\n if symops:\n break\n if not symops:\n # Try to parse International number\n for symmetry_label in [\"_space_group_IT_number\",\n \"_space_group_IT_number_\",\n \"_symmetry_Int_Tables_number\",\n \"_symmetry_Int_Tables_number_\"]:\n if data.data.get(symmetry_label):\n try:\n i = int(str2float(data.data.get(symmetry_label)))\n symops = SpaceGroup.from_int_number(i).symmetry_ops\n break\n except ValueError:\n continue\n\n if not symops:\n warnings.warn(\"No _symmetry_equiv_pos_as_xyz type key found. \"\n \"Defaulting to P1.\")\n symops = [SymmOp.from_xyz_string(s) for s in ['x', 'y', 'z']]\n\n return symops\n\n def get_magsymops(self, data):\n \"\"\"\n Equivalent to get_symops except for magnetic symmetry groups.\n Separate function since additional operation for time reversal symmetry\n (which changes magnetic moments on sites) needs to be returned.\n \"\"\"\n magsymmops = []\n\n # check to see if magCIF file explicitly contains magnetic symmetry operations\n if data.data.get(\"_space_group_symop_magn_operation.xyz\"):\n\n xyzt = data.data.get(\"_space_group_symop_magn_operation.xyz\")\n if isinstance(xyzt, six.string_types):\n xyzt = [xyzt]\n magsymmops = [MagSymmOp.from_xyzt_string(s) for s in xyzt]\n\n if data.data.get(\"_space_group_symop_magn_centering.xyz\"):\n\n xyzt = data.data.get(\"_space_group_symop_magn_centering.xyz\")\n if isinstance(xyzt, six.string_types):\n xyzt = [xyzt]\n centering_symops = [MagSymmOp.from_xyzt_string(s) for s in xyzt]\n\n all_ops = []\n for op in magsymmops:\n for centering_op in centering_symops:\n new_translation = [i - np.floor(i) for i\n in\n op.translation_vector + centering_op.translation_vector]\n new_time_reversal = op.time_reversal * centering_op.time_reversal\n all_ops.append(\n MagSymmOp.from_rotation_and_translation_and_time_reversal(\n rotation_matrix=op.rotation_matrix,\n translation_vec=new_translation,\n time_reversal=new_time_reversal))\n magsymmops = all_ops\n\n # else check to see if it specifies a magnetic space group\n elif data.data.get(\"_space_group_magn.name_BNS\") or data.data.get(\n \"_space_group_magn.number_BNS\"):\n\n if data.data.get(\"_space_group_magn.name_BNS\"):\n # get BNS label for MagneticSpaceGroup()\n id = data.data.get(\"_space_group_magn.name_BNS\")\n else:\n # get BNS number for MagneticSpaceGroup()\n # by converting string to list of ints\n id = list(map(int, (\n data.data.get(\"_space_group_magn.number_BNS\").split(\".\"))))\n\n msg = MagneticSpaceGroup(id)\n\n if data.data.get(\"_space_group_magn.transform_BNS_Pp_abc\"):\n if data.data.get(\n \"_space_group_magn.transform_BNS_Pp_abc\") != \"a,b,c;0,0,0\":\n return NotImplementedError(\n \"Non-standard settings not currently supported.\")\n elif data.data.get(\"_space_group_magn.transform_BNS_Pp\"):\n return NotImplementedError(\n \"Incomplete specification to implement.\")\n\n magsymmops = msg.symmetry_ops\n\n if not magsymmops:\n warnings.warn(\n \"No magnetic symmetry detected, using primitive symmetry.\")\n magsymmops = [MagSymmOp.from_xyzt_string(\"x, y, z, 1\")]\n\n return magsymmops\n\n def parse_oxi_states(self, data):\n \"\"\"\n Parse oxidation states from data dictionary\n \"\"\"\n try:\n oxi_states = {\n data[\"_atom_type_symbol\"][i]:\n str2float(data[\"_atom_type_oxidation_number\"][i])\n for i in range(len(data[\"_atom_type_symbol\"]))}\n # attempt to strip oxidation state from _atom_type_symbol\n # in case the label does not contain an oxidation state\n for i, symbol in enumerate(data[\"_atom_type_symbol\"]):\n oxi_states[re.sub(r\"\\d?[\\+,\\-]?$\", \"\", symbol)] = \\\n str2float(data[\"_atom_type_oxidation_number\"][i])\n\n except (ValueError, KeyError):\n oxi_states = None\n return oxi_states\n\n def parse_magmoms(self, data, lattice=None):\n \"\"\"\n Parse atomic magnetic moments from data dictionary\n \"\"\"\n if lattice is None:\n raise Exception(\n 'Magmoms given in terms of crystal axes in magCIF spec.')\n try:\n magmoms = {\n data[\"_atom_site_moment_label\"][i]:\n np.array(\n [str2float(data[\"_atom_site_moment_crystalaxis_x\"][i]),\n str2float(data[\"_atom_site_moment_crystalaxis_y\"][i]),\n str2float(data[\"_atom_site_moment_crystalaxis_z\"][i])]\n )\n for i in range(len(data[\"_atom_site_moment_label\"]))\n }\n except (ValueError, KeyError):\n return None\n return magmoms\n\n def _get_structure(self, data, primitive):\n \"\"\"\n Generate structure from part of the cif.\n \"\"\"\n\n def parse_symbol(sym):\n # Common representations for elements/water in cif files\n # TODO: fix inconsistent handling of water\n special = {\"D\": \"D\", \"Hw\": \"H\", \"Ow\": \"O\", \"Wat\": \"O\",\n \"wat\": \"O\", \"OH\": \"\", \"OH2\": \"\"}\n m = re.findall(r\"w?[A-Z][a-z]*\", sym)\n if m and m != \"?\":\n if sym in special:\n v = special[sym]\n else:\n v = special.get(m[0], m[0])\n if len(m) > 1 or (m[0] in special):\n warnings.warn(\"{} parsed as {}\".format(sym, v))\n return v\n\n def get_num_implicit_hydrogens(sym):\n num_h = {\"Wat\": 2, \"wat\": 2, \"O-H\": 1}\n return num_h.get(sym[:3], 0)\n\n lattice = self.get_lattice(data)\n\n # if magCIF, get magnetic symmetry moments and magmoms\n # else standard CIF, and use empty magmom dict\n if self.feature_flags[\"magcif_incommensurate\"]:\n raise NotImplementedError(\n \"Incommensurate structures not currently supported.\")\n elif self.feature_flags[\"magcif\"]:\n self.symmetry_operations = self.get_magsymops(data)\n magmoms = self.parse_magmoms(data, lattice=lattice)\n else:\n self.symmetry_operations = self.get_symops(data)\n magmoms = {}\n\n oxi_states = self.parse_oxi_states(data)\n\n coord_to_species = OrderedDict()\n coord_to_magmoms = OrderedDict()\n\n def get_matching_coord(coord):\n keys = list(coord_to_species.keys())\n coords = np.array(keys)\n for op in self.symmetry_operations:\n c = op.operate(coord)\n inds = find_in_coord_list_pbc(coords, c,\n atol=self._site_tolerance)\n # cant use if inds, because python is dumb and np.array([0]) evaluates\n # to False\n if len(inds):\n return keys[inds[0]]\n return False\n\n for i in range(len(data[\"_atom_site_label\"])):\n try:\n # If site type symbol exists, use it. Otherwise, we use the\n # label.\n symbol = parse_symbol(data[\"_atom_site_type_symbol\"][i])\n num_h = get_num_implicit_hydrogens(\n data[\"_atom_site_type_symbol\"][i])\n except KeyError:\n symbol = parse_symbol(data[\"_atom_site_label\"][i])\n num_h = get_num_implicit_hydrogens(data[\"_atom_site_label\"][i])\n if not symbol:\n continue\n\n if oxi_states is not None:\n o_s = oxi_states.get(symbol, 0)\n # use _atom_site_type_symbol if possible for oxidation state\n if \"_atom_site_type_symbol\" in data.data.keys():\n oxi_symbol = data[\"_atom_site_type_symbol\"][i]\n o_s = oxi_states.get(oxi_symbol, o_s)\n try:\n el = Specie(symbol, o_s)\n except:\n el = DummySpecie(symbol, o_s)\n else:\n el = get_el_sp(symbol)\n\n x = str2float(data[\"_atom_site_fract_x\"][i])\n y = str2float(data[\"_atom_site_fract_y\"][i])\n z = str2float(data[\"_atom_site_fract_z\"][i])\n magmom = magmoms.get(data[\"_atom_site_label\"][i],\n np.array([0, 0, 0]))\n\n try:\n occu = str2float(data[\"_atom_site_occupancy\"][i])\n except (KeyError, ValueError):\n occu = 1\n\n if occu > 0:\n coord = (x, y, z)\n match = get_matching_coord(coord)\n comp_d = {el: occu}\n if num_h > 0:\n comp_d[\"H\"] = num_h\n comp = Composition(comp_d)\n if not match:\n coord_to_species[coord] = comp\n coord_to_magmoms[coord] = magmom\n else:\n coord_to_species[match] += comp\n # disordered magnetic not currently supported\n coord_to_magmoms[match] = None\n\n sum_occu = [sum(c.values()) for c in coord_to_species.values()\n if not set(c.elements) == {Element(\"O\"), Element(\"H\")}]\n if any([o > 1 for o in sum_occu]):\n warnings.warn(\n \"Some occupancies (%s) sum to > 1! If they are within \"\n \"the tolerance, they will be rescaled.\" % str(sum_occu))\n\n allspecies = []\n allcoords = []\n allmagmoms = []\n allhydrogens = []\n\n # check to see if magCIF file is disordered\n if self.feature_flags[\"magcif\"]:\n for k, v in coord_to_magmoms.items():\n if v is None:\n # Proposed solution to this is to instead store magnetic\n # moments as Specie 'spin' property, instead of site\n # property, but this introduces ambiguities for end user\n # (such as unintended use of `spin` and Specie will have\n # fictious oxidation state).\n raise NotImplementedError(\n 'Disordered magnetic structures not currently supported.')\n\n if coord_to_species.items():\n for comp, group in groupby(\n sorted(list(coord_to_species.items()), key=lambda x: x[1]),\n key=lambda x: x[1]):\n tmp_coords = [site[0] for site in group]\n tmp_magmom = [coord_to_magmoms[tmp_coord] for tmp_coord in\n tmp_coords]\n\n if self.feature_flags[\"magcif\"]:\n coords, magmoms = self._unique_coords(tmp_coords,\n magmoms_in=tmp_magmom,\n lattice=lattice)\n else:\n coords, magmoms = self._unique_coords(tmp_coords)\n\n if set(comp.elements) == {Element(\"O\"), Element(\"H\")}:\n # O with implicit hydrogens\n im_h = comp[\"H\"]\n species = Composition({\"O\": comp[\"O\"]})\n else:\n im_h = 0\n species = comp\n\n allhydrogens.extend(len(coords) * [im_h])\n allcoords.extend(coords)\n allspecies.extend(len(coords) * [species])\n allmagmoms.extend(magmoms)\n\n # rescale occupancies if necessary\n for i, species in enumerate(allspecies):\n totaloccu = sum(species.values())\n if 1 < totaloccu <= self._occupancy_tolerance:\n allspecies[i] = species / totaloccu\n\n if allspecies and len(allspecies) == len(allcoords) \\\n and len(allspecies) == len(allmagmoms):\n site_properties = dict()\n if any(allhydrogens):\n assert len(allhydrogens) == len(allcoords)\n site_properties[\"implicit_hydrogens\"] = allhydrogens\n\n if self.feature_flags[\"magcif\"]:\n site_properties[\"magmom\"] = allmagmoms\n\n if len(site_properties) == 0:\n site_properties = None\n\n struct = Structure(lattice, allspecies, allcoords,\n site_properties=site_properties)\n\n struct = struct.get_sorted_structure()\n\n if primitive and self.feature_flags['magcif']:\n struct = struct.get_primitive_structure(use_site_props=True)\n elif primitive:\n struct = struct.get_primitive_structure()\n struct = struct.get_reduced_structure()\n\n return struct\n\n def get_structures(self, primitive=True):\n \"\"\"\n Return list of structures in CIF file. primitive boolean sets whether a\n conventional cell structure or primitive cell structure is returned.\n\n Args:\n primitive (bool): Set to False to return conventional unit cells.\n Defaults to True. With magnetic CIF files, will return primitive\n magnetic cell which may be larger than nuclear primitive cell.\n\n Returns:\n List of Structures.\n \"\"\"\n structures = []\n for d in self._cif.data.values():\n try:\n s = self._get_structure(d, primitive)\n if s:\n structures.append(s)\n except (KeyError, ValueError) as exc:\n # Warn the user (Errors should never pass silently)\n # A user reported a problem with cif files produced by Avogadro\n # in which the atomic coordinates are in Cartesian coords.\n warnings.warn(str(exc))\n if len(structures) == 0:\n raise ValueError(\"Invalid cif file with no structures!\")\n return structures\n\n def get_bibtex_string(self):\n \"\"\"\n Get BibTeX reference from CIF file.\n :param data:\n :return: BibTeX string\n \"\"\"\n\n bibtex_keys = {'author': ('_publ_author_name', '_citation_author_name'),\n 'title': ('_publ_section_title', '_citation_title'),\n 'journal': ('_journal_name_full', '_journal_name_abbrev',\n '_citation_journal_full', '_citation_journal_abbrev'),\n 'volume': ('_journal_volume', '_citation_journal_volume'),\n 'year': ('_journal_year', '_citation_year'),\n 'number': ('_journal_number', '_citation_number'),\n 'page_first': ('_journal_page_first', '_citation_page_first'),\n 'page_last': ('_journal_page_last', '_citation_page_last'),\n 'doi': ('_journal_DOI', '_citation_DOI')}\n\n entries = {}\n\n # TODO: parse '_publ_section_references' when it exists?\n # TODO: CIF specification supports multiple citations.\n\n for idx, data in enumerate(self._cif.data.values()):\n\n # convert to lower-case keys, some cif files inconsistent\n data = {k.lower(): v for k, v in data.data.items()}\n\n bibtex_entry = {}\n\n for field, tags in bibtex_keys.items():\n for tag in tags:\n if tag in data:\n bibtex_entry[field] = data[tag]\n\n # convert to bibtex author format ('and' delimited)\n if 'author' in bibtex_entry:\n bibtex_entry['author'] = ' and '.join(bibtex_entry['author'])\n\n # convert to bibtex page range format, use empty string if not specified\n if ('page_first' in bibtex_entry) or ('page_last' in bibtex_entry):\n bibtex_entry['pages'] = '{0}--{1}'.format(bibtex_entry.get('page_first', ''),\n bibtex_entry.get('page_last', ''))\n bibtex_entry.pop('page_first', None) # and remove page_first, page_list if present\n bibtex_entry.pop('page_last', None)\n\n\n # cite keys are given as cif-reference-idx in order they are found\n entries['cif-reference-{}'.format(idx)] = Entry('article', list(bibtex_entry.items()))\n\n return BibliographyData(entries).to_string(bib_format='bibtex')\n\n def as_dict(self):\n d = OrderedDict()\n for k, v in self._cif.data.items():\n d[k] = {}\n for k2, v2 in v.data.items():\n d[k][k2] = v2\n return d\n\n\nclass CifWriter(object):\n def __init__(self, struct, symprec=None, write_magmoms=False):\n \"\"\"\n A wrapper around CifFile to write CIF files from pymatgen structures.\n\n Args:\n struct (Structure): structure to write\n symprec (float): If not none, finds the symmetry of the structure\n and writes the cif with symmetry information. Passes symprec\n to the SpacegroupAnalyzer\n write_magmoms (bool): If True, will write magCIF file. Incompatible\n with symprec\n \"\"\"\n\n if write_magmoms and symprec:\n warnings.warn(\n \"Magnetic symmetry cannot currently be detected by pymatgen,\"\n \"disabling symmetry detection.\")\n symprec = None\n\n format_str = \"{:.8f}\"\n\n block = OrderedDict()\n loops = []\n spacegroup = (\"P 1\", 1)\n if symprec is not None:\n sf = SpacegroupAnalyzer(struct, symprec)\n spacegroup = (sf.get_space_group_symbol(),\n sf.get_space_group_number())\n # Needs the refined struture when using symprec. This converts\n # primitive to conventional structures, the standard for CIF.\n struct = sf.get_refined_structure()\n\n latt = struct.lattice\n comp = struct.composition\n no_oxi_comp = comp.element_composition\n block[\"_symmetry_space_group_name_H-M\"] = spacegroup[0]\n for cell_attr in ['a', 'b', 'c']:\n block[\"_cell_length_\" + cell_attr] = format_str.format(\n getattr(latt, cell_attr))\n for cell_attr in ['alpha', 'beta', 'gamma']:\n block[\"_cell_angle_\" + cell_attr] = format_str.format(\n getattr(latt, cell_attr))\n block[\"_symmetry_Int_Tables_number\"] = spacegroup[1]\n block[\"_chemical_formula_structural\"] = no_oxi_comp.reduced_formula\n block[\"_chemical_formula_sum\"] = no_oxi_comp.formula\n block[\"_cell_volume\"] = \"%.8f\" % latt.volume\n\n reduced_comp, fu = no_oxi_comp.get_reduced_composition_and_factor()\n block[\"_cell_formula_units_Z\"] = str(int(fu))\n\n if symprec is None:\n block[\"_symmetry_equiv_pos_site_id\"] = [\"1\"]\n block[\"_symmetry_equiv_pos_as_xyz\"] = [\"x, y, z\"]\n else:\n sf = SpacegroupAnalyzer(struct, symprec)\n\n symmops = []\n for op in sf.get_symmetry_operations():\n v = op.translation_vector\n symmops.append(SymmOp.from_rotation_and_translation(\n op.rotation_matrix, v))\n\n ops = [op.as_xyz_string() for op in symmops]\n block[\"_symmetry_equiv_pos_site_id\"] = \\\n [\"%d\" % i for i in range(1, len(ops) + 1)]\n block[\"_symmetry_equiv_pos_as_xyz\"] = ops\n\n loops.append([\"_symmetry_equiv_pos_site_id\",\n \"_symmetry_equiv_pos_as_xyz\"])\n\n contains_oxidation = True\n try:\n symbol_to_oxinum = OrderedDict([\n (el.__str__(),\n float(el.oxi_state))\n for el in sorted(comp.elements)])\n except AttributeError:\n symbol_to_oxinum = OrderedDict([(el.symbol, 0) for el in\n sorted(comp.elements)])\n contains_oxidation = False\n if contains_oxidation:\n block[\"_atom_type_symbol\"] = symbol_to_oxinum.keys()\n block[\"_atom_type_oxidation_number\"] = symbol_to_oxinum.values()\n loops.append([\"_atom_type_symbol\", \"_atom_type_oxidation_number\"])\n\n atom_site_type_symbol = []\n atom_site_symmetry_multiplicity = []\n atom_site_fract_x = []\n atom_site_fract_y = []\n atom_site_fract_z = []\n atom_site_label = []\n atom_site_occupancy = []\n atom_site_moment_label = []\n atom_site_moment_crystalaxis_x = []\n atom_site_moment_crystalaxis_y = []\n atom_site_moment_crystalaxis_z = []\n count = 1\n if symprec is None:\n for site in struct:\n for sp, occu in sorted(site.species_and_occu.items()):\n atom_site_type_symbol.append(sp.__str__())\n atom_site_symmetry_multiplicity.append(\"1\")\n atom_site_fract_x.append(\"{0:f}\".format(site.a))\n atom_site_fract_y.append(\"{0:f}\".format(site.b))\n atom_site_fract_z.append(\"{0:f}\".format(site.c))\n atom_site_label.append(\"{}{}\".format(sp.symbol, count))\n atom_site_occupancy.append(occu.__str__())\n\n magmom = Magmom(\n site.properties.get('magmom', getattr(sp, 'spin', 0)))\n if write_magmoms and abs(magmom) > 0:\n moment = Magmom.get_moment_relative_to_crystal_axes(\n magmom, latt)\n atom_site_moment_label.append(\n \"{}{}\".format(sp.symbol, count))\n atom_site_moment_crystalaxis_x.append(\"%.5f\" % moment[0])\n atom_site_moment_crystalaxis_y.append(\"%.5f\" % moment[1])\n atom_site_moment_crystalaxis_z.append(\"%.5f\" % moment[2])\n\n count += 1\n else:\n # The following just presents a deterministic ordering.\n unique_sites = [\n (sorted(sites, key=lambda s: tuple([abs(x) for x in\n s.frac_coords]))[0],\n len(sites))\n for sites in sf.get_symmetrized_structure().equivalent_sites\n ]\n for site, mult in sorted(\n unique_sites,\n key=lambda t: (t[0].species_and_occu.average_electroneg,\n -t[1], t[0].a, t[0].b, t[0].c)):\n for sp, occu in site.species_and_occu.items():\n atom_site_type_symbol.append(sp.__str__())\n atom_site_symmetry_multiplicity.append(\"%d\" % mult)\n atom_site_fract_x.append(\"{0:f}\".format(site.a))\n atom_site_fract_y.append(\"{0:f}\".format(site.b))\n atom_site_fract_z.append(\"{0:f}\".format(site.c))\n atom_site_label.append(\"{}{}\".format(sp.symbol, count))\n atom_site_occupancy.append(occu.__str__())\n count += 1\n\n block[\"_atom_site_type_symbol\"] = atom_site_type_symbol\n block[\"_atom_site_label\"] = atom_site_label\n block[\"_atom_site_symmetry_multiplicity\"] = \\\n atom_site_symmetry_multiplicity\n block[\"_atom_site_fract_x\"] = atom_site_fract_x\n block[\"_atom_site_fract_y\"] = atom_site_fract_y\n block[\"_atom_site_fract_z\"] = atom_site_fract_z\n block[\"_atom_site_occupancy\"] = atom_site_occupancy\n loops.append([\"_atom_site_type_symbol\",\n \"_atom_site_label\",\n \"_atom_site_symmetry_multiplicity\",\n \"_atom_site_fract_x\",\n \"_atom_site_fract_y\",\n \"_atom_site_fract_z\",\n \"_atom_site_occupancy\"])\n if write_magmoms:\n block[\"_atom_site_moment_label\"] = atom_site_moment_label\n block[\n \"_atom_site_moment_crystalaxis_x\"] = atom_site_moment_crystalaxis_x\n block[\n \"_atom_site_moment_crystalaxis_y\"] = atom_site_moment_crystalaxis_y\n block[\n \"_atom_site_moment_crystalaxis_z\"] = atom_site_moment_crystalaxis_z\n loops.append([\"_atom_site_moment_label\",\n \"_atom_site_moment_crystalaxis_x\",\n \"_atom_site_moment_crystalaxis_y\",\n \"_atom_site_moment_crystalaxis_z\"])\n d = OrderedDict()\n d[comp.reduced_formula] = CifBlock(block, loops, comp.reduced_formula)\n self._cf = CifFile(d)\n\n def __str__(self):\n \"\"\"\n Returns the cif as a string.\n \"\"\"\n return self._cf.__str__()\n\n def write_file(self, filename):\n \"\"\"\n Write the cif file.\n \"\"\"\n with zopen(filename, \"wt\") as f:\n f.write(self.__str__())\n\n\ndef str2float(text):\n \"\"\"\n Remove uncertainty brackets from strings and return the float.\n \"\"\"\n\n try:\n # Note that the ending ) is sometimes missing. That is why the code has\n # been modified to treat it as optional. Same logic applies to lists.\n return float(re.sub(r\"\\(.+\\)*\", \"\", text))\n except TypeError:\n if isinstance(text, list) and len(text) == 1:\n return float(re.sub(r\"\\(.+\\)*\", \"\", text[0]))\n except ValueError as ex:\n if text.strip() == \".\":\n return 0\n raise ex\n"
] | [
[
"numpy.array",
"numpy.floor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
marcograss/Lean | [
"7b826eb38631b0e72a06c56706624d2a21279b09"
] | [
"Algorithm.Framework/Portfolio/BlackLittermanOptimizationPortfolioConstructionModel.py"
] | [
"# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.\n# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.\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 http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom clr import AddReference\nAddReference(\"System\")\nAddReference(\"QuantConnect.Algorithm\")\nAddReference(\"QuantConnect.Common\")\nAddReference(\"QuantConnect.Logging\")\nAddReference(\"QuantConnect.Indicators\")\n\nfrom System import *\nfrom QuantConnect import *\nfrom QuantConnect.Indicators import *\nfrom QuantConnect.Algorithm import *\nfrom QuantConnect.Logging import Log\nfrom QuantConnect.Algorithm.Framework import *\nfrom QuantConnect.Algorithm.Framework.Alphas import *\nfrom QuantConnect.Algorithm.Framework.Portfolio import *\nfrom Portfolio.MaximumSharpeRatioPortfolioOptimizer import MaximumSharpeRatioPortfolioOptimizer\nfrom datetime import datetime, timedelta\nfrom itertools import groupby\nimport pandas as pd\nimport numpy as np\nfrom numpy import dot, transpose\nfrom numpy.linalg import inv\n\n### <summary>\n### Provides an implementation of Black-Litterman portfolio optimization. The model adjusts equilibrium market\n### returns by incorporating views from multiple alpha models and therefore to get the optimal risky portfolio\n### reflecting those views. If insights of all alpha models have None magnitude or there are linearly dependent\n### vectors in link matrix of views, the expected return would be the implied excess equilibrium return.\n### The interval of weights in optimization method can be changed based on the long-short algorithm.\n### The default model uses the 0.0025 as weight-on-views scalar parameter tau and\n### MaximumSharpeRatioPortfolioOptimizer that accepts a 63-row matrix of 1-day returns.\n### </summary>\nclass BlackLittermanOptimizationPortfolioConstructionModel(PortfolioConstructionModel):\n def __init__(self,\n rebalance = Resolution.Daily,\n portfolioBias = PortfolioBias.LongShort,\n lookback = 1,\n period = 63,\n resolution = Resolution.Daily,\n risk_free_rate = 0,\n delta = 2.5,\n tau = 0.05,\n optimizer = None):\n \"\"\"Initialize the model\n Args:\n rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.\n If None will be ignored.\n The function returns the next expected rebalance time for a given algorithm UTC DateTime.\n The function returns null if unknown, in which case the function will be called again in the\n next loop. Returning current time will trigger rebalance.\n portfolioBias: Specifies the bias of the portfolio (Short, Long/Short, Long)\n lookback(int): Historical return lookback period\n period(int): The time interval of history price to calculate the weight\n resolution: The resolution of the history price\n risk_free_rate(float): The risk free rate\n delta(float): The risk aversion coeffficient of the market portfolio\n tau(float): The model parameter indicating the uncertainty of the CAPM prior\"\"\"\n self.lookback = lookback\n self.period = period\n self.resolution = resolution\n self.risk_free_rate = risk_free_rate\n self.delta = delta\n self.tau = tau\n self.portfolioBias = portfolioBias\n\n lower = 0 if portfolioBias == PortfolioBias.Long else -1\n upper = 0 if portfolioBias == PortfolioBias.Short else 1\n self.optimizer = MaximumSharpeRatioPortfolioOptimizer(lower, upper, risk_free_rate) if optimizer is None else optimizer\n\n self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)\n self.symbolDataBySymbol = {}\n\n # If the argument is an instance of Resolution or Timedelta\n # Redefine rebalancingFunc\n rebalancingFunc = rebalance\n if isinstance(rebalance, int):\n rebalance = Extensions.ToTimeSpan(rebalance)\n if isinstance(rebalance, timedelta):\n rebalancingFunc = lambda dt: dt + rebalance\n if rebalancingFunc:\n self.SetRebalancingFunc(rebalancingFunc)\n\n def ShouldCreateTargetForInsight(self, insight):\n return len(PortfolioConstructionModel.FilterInvalidInsightMagnitude(self.Algorithm, [ insight ])) != 0\n\n def DetermineTargetPercent(self, lastActiveInsights):\n targets = {}\n\n # Get view vectors\n P, Q = self.get_views(lastActiveInsights)\n if P is not None:\n returns = dict()\n # Updates the BlackLittermanSymbolData with insights\n # Create a dictionary keyed by the symbols in the insights with an pandas.Series as value to create a data frame\n for insight in lastActiveInsights:\n symbol = insight.Symbol\n symbolData = self.symbolDataBySymbol.get(symbol, self.BlackLittermanSymbolData(symbol, self.lookback, self.period))\n if insight.Magnitude is None:\n self.Algorithm.SetRunTimeError(ArgumentNullException('BlackLittermanOptimizationPortfolioConstructionModel does not accept \\'None\\' as Insight.Magnitude. Please make sure your Alpha Model is generating Insights with the Magnitude property set.'))\n return targets\n symbolData.Add(insight.GeneratedTimeUtc, insight.Magnitude)\n returns[symbol] = symbolData.Return\n\n returns = pd.DataFrame(returns)\n\n # Calculate prior estimate of the mean and covariance\n Pi, Sigma = self.get_equilibrium_return(returns)\n\n # Calculate posterior estimate of the mean and covariance\n Pi, Sigma = self.apply_blacklitterman_master_formula(Pi, Sigma, P, Q)\n\n # Create portfolio targets from the specified insights\n weights = self.optimizer.Optimize(returns, Pi, Sigma)\n weights = pd.Series(weights, index = Sigma.columns)\n\n for symbol, weight in weights.items():\n for insight in lastActiveInsights:\n if str(insight.Symbol) == str(symbol):\n # don't trust the optimizer\n if self.portfolioBias != PortfolioBias.LongShort and self.sign(weight) != self.portfolioBias:\n weight = 0\n targets[insight] = weight\n break\n\n return targets\n\n def GetTargetInsights(self):\n # Get insight that haven't expired of each symbol that is still in the universe\n activeInsights = self.InsightCollection.GetActiveInsights(self.Algorithm.UtcTime)\n\n # Get the last generated active insight for each symbol\n lastActiveInsights = []\n for sourceModel, f in groupby(sorted(activeInsights, key = lambda ff: ff.SourceModel), lambda fff: fff.SourceModel):\n for symbol, g in groupby(sorted(list(f), key = lambda gg: gg.Symbol), lambda ggg: ggg.Symbol):\n lastActiveInsights.append(sorted(g, key = lambda x: x.GeneratedTimeUtc)[-1])\n return lastActiveInsights\n\n def OnSecuritiesChanged(self, algorithm, changes):\n '''Event fired each time the we add/remove securities from the data feed\n Args:\n algorithm: The algorithm instance that experienced the change in securities\n changes: The security additions and removals from the algorithm'''\n\n # Get removed symbol and invalidate them in the insight collection\n super().OnSecuritiesChanged(algorithm, changes)\n\n for security in changes.RemovedSecurities:\n symbol = security.Symbol\n symbolData = self.symbolDataBySymbol.pop(symbol, None)\n if symbolData is not None:\n symbolData.Reset()\n\n # initialize data for added securities\n addedSymbols = { x.Symbol: x.Exchange.TimeZone for x in changes.AddedSecurities }\n history = algorithm.History(list(addedSymbols.keys()), self.lookback * self.period, self.resolution)\n\n if history.empty:\n return\n\n history = history.close.unstack(0)\n symbols = history.columns\n\n for symbol, timezone in addedSymbols.items():\n if str(symbol) not in symbols:\n continue\n\n symbolData = self.symbolDataBySymbol.get(symbol, self.BlackLittermanSymbolData(symbol, self.lookback, self.period))\n for time, close in history[symbol].items():\n utcTime = Extensions.ConvertToUtc(time, timezone)\n symbolData.Update(utcTime, close)\n\n self.symbolDataBySymbol[symbol] = symbolData\n\n def apply_blacklitterman_master_formula(self, Pi, Sigma, P, Q):\n '''Apply Black-Litterman master formula\n http://www.blacklitterman.org/cookbook.html\n Args:\n Pi: Prior/Posterior mean array\n Sigma: Prior/Posterior covariance matrix\n P: A matrix that identifies the assets involved in the views (size: K x N)\n Q: A view vector (size: K x 1)'''\n ts = self.tau * Sigma\n\n # Create the diagonal Sigma matrix of error terms from the expressed views\n omega = np.dot(np.dot(P, ts), P.T) * np.eye(Q.shape[0])\n if np.linalg.det(omega) == 0:\n return Pi, Sigma\n\n A = np.dot(np.dot(ts, P.T), inv(np.dot(np.dot(P, ts), P.T) + omega))\n\n Pi = np.squeeze(np.asarray((\n np.expand_dims(Pi, axis=0).T +\n np.dot(A, (Q - np.expand_dims(np.dot(P, Pi.T), axis=1))))\n ))\n\n M = ts - np.dot(np.dot(A, P), ts)\n Sigma = (Sigma + M) * self.delta\n\n return Pi, Sigma\n\n def get_equilibrium_return(self, returns):\n '''Calculate equilibrium returns and covariance\n Args:\n returns: Matrix of returns where each column represents a security and each row returns for the given date/time (size: K x N)\n Returns:\n equilibrium_return: Array of double of equilibrium returns\n cov: Multi-dimensional array of double with the portfolio covariance of returns (size: K x K)'''\n\n size = len(returns.columns)\n # equal weighting scheme\n W = np.array([1/size]*size)\n # the covariance matrix of excess returns (N x N matrix)\n cov = returns.cov()*252\n # annualized return\n annual_return = np.sum(((1 + returns.mean())**252 -1) * W)\n # annualized variance of return\n annual_variance = dot(W.T, dot(cov, W))\n # the risk aversion coefficient\n risk_aversion = (annual_return - self.risk_free_rate ) / annual_variance\n # the implied excess equilibrium return Vector (N x 1 column vector)\n equilibrium_return = dot(dot(risk_aversion, cov), W)\n\n return equilibrium_return, cov\n\n def get_views(self, insights):\n '''Generate views from multiple alpha models\n Args\n insights: Array of insight that represent the investors' views\n Returns\n P: A matrix that identifies the assets involved in the views (size: K x N)\n Q: A view vector (size: K x 1)'''\n try:\n P = {}\n Q = {}\n for model, group in groupby(insights, lambda x: x.SourceModel):\n group = list(group)\n\n up_insights_sum = 0.0\n dn_insights_sum = 0.0\n for insight in group:\n if insight.Direction == InsightDirection.Up:\n up_insights_sum = up_insights_sum + np.abs(insight.Magnitude)\n if insight.Direction == InsightDirection.Down:\n dn_insights_sum = dn_insights_sum + np.abs(insight.Magnitude)\n\n q = up_insights_sum if up_insights_sum > dn_insights_sum else dn_insights_sum\n if q == 0:\n continue\n\n Q[model] = q\n\n # generate the link matrix of views: P\n P[model] = dict()\n for insight in group:\n value = insight.Direction * np.abs(insight.Magnitude)\n P[model][insight.Symbol] = value / q\n # Add zero for other symbols that are listed but active insight\n for symbol in self.symbolDataBySymbol.keys():\n if symbol not in P[model]:\n P[model][symbol] = 0\n\n Q = np.array([[x] for x in Q.values()])\n if len(Q) > 0:\n P = np.array([list(x.values()) for x in P.values()])\n return P, Q\n except:\n pass\n\n return None, None\n\n\n class BlackLittermanSymbolData:\n '''Contains data specific to a symbol required by this model'''\n def __init__(self, symbol, lookback, period):\n self.symbol = symbol\n self.roc = RateOfChange(f'{symbol}.ROC({lookback})', lookback)\n self.roc.Updated += self.OnRateOfChangeUpdated\n self.window = RollingWindow[IndicatorDataPoint](period)\n\n def Reset(self):\n self.roc.Updated -= self.OnRateOfChangeUpdated\n self.roc.Reset()\n self.window.Reset()\n\n def Update(self, utcTime, close):\n self.roc.Update(utcTime, close)\n\n def OnRateOfChangeUpdated(self, roc, value):\n if roc.IsReady:\n self.window.Add(value)\n\n def Add(self, time, value):\n if self.window.Samples > 0 and self.window[0].EndTime == time:\n return\n\n item = IndicatorDataPoint(self.symbol, time, value)\n self.window.Add(item)\n\n @property\n def Return(self):\n return pd.Series(\n data = [x.Value for x in self.window],\n index = [x.EndTime for x in self.window])\n\n @property\n def IsReady(self):\n return self.window.IsReady\n\n def __str__(self, **kwargs):\n return f'{self.roc.Name}: {(1 + self.window[0])**252 - 1:.2%}'\n"
] | [
[
"numpy.dot",
"numpy.expand_dims",
"pandas.Series",
"numpy.abs",
"numpy.eye",
"pandas.DataFrame",
"numpy.linalg.det",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
sijunhe/tensorflow | [
"d7e858192d1de827bc03705ac62e1bd38daf06d8",
"d7e858192d1de827bc03705ac62e1bd38daf06d8"
] | [
"tensorflow/python/autograph/impl/conversion_test.py",
"tensorflow/python/data/kernel_tests/test_base.py"
] | [
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for conversion module.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport imp\nimport sys\nimport threading\n\nimport gast\nimport six\n\nfrom tensorflow.python.autograph import utils\nfrom tensorflow.python.autograph.core import config\nfrom tensorflow.python.autograph.core import converter\nfrom tensorflow.python.autograph.impl import api\nfrom tensorflow.python.autograph.impl import conversion\nfrom tensorflow.python.autograph.pyct import compiler\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.keras.engine import training\nfrom tensorflow.python.platform import test\n\n\nclass ConversionTest(test.TestCase):\n\n def _simple_program_ctx(self):\n return converter.ProgramContext(\n options=converter.ConversionOptions(recursive=True),\n autograph_module=api)\n\n def test_is_whitelisted_for_graph(self):\n\n def test_fn():\n return constant_op.constant(1)\n\n self.assertFalse(conversion.is_whitelisted_for_graph(test_fn))\n self.assertTrue(conversion.is_whitelisted_for_graph(utils))\n self.assertTrue(conversion.is_whitelisted_for_graph(constant_op.constant))\n\n def test_is_whitelisted_for_graph_tensorflow_like(self):\n\n tf_like = imp.new_module('tensorflow_foo')\n def test_fn():\n pass\n tf_like.test_fn = test_fn\n test_fn.__module__ = tf_like\n\n self.assertFalse(conversion.is_whitelisted_for_graph(tf_like.test_fn))\n\n def test_is_whitelisted_for_graph_callable_whitelisted_call(self):\n\n whitelisted_mod = imp.new_module('test_whitelisted_call')\n sys.modules['test_whitelisted_call'] = whitelisted_mod\n config.CONVERSION_RULES = ((config.DoNotConvert('test_whitelisted_call'),) +\n config.CONVERSION_RULES)\n\n class TestClass(object):\n\n def __call__(self):\n pass\n\n def whitelisted_method(self):\n pass\n\n TestClass.__module__ = 'test_whitelisted_call'\n if six.PY2:\n TestClass.__call__.__func__.__module__ = 'test_whitelisted_call'\n else:\n TestClass.__call__.__module__ = 'test_whitelisted_call'\n\n class Subclass(TestClass):\n\n def converted_method(self):\n pass\n\n tc = Subclass()\n\n self.assertTrue(conversion.is_whitelisted_for_graph(TestClass.__call__))\n self.assertTrue(conversion.is_whitelisted_for_graph(tc))\n self.assertTrue(conversion.is_whitelisted_for_graph(tc.__call__))\n self.assertTrue(conversion.is_whitelisted_for_graph(tc.whitelisted_method))\n self.assertFalse(conversion.is_whitelisted_for_graph(Subclass))\n self.assertFalse(conversion.is_whitelisted_for_graph(tc.converted_method))\n\n def test_convert_entity_to_ast_unsupported_types(self):\n with self.assertRaises(NotImplementedError):\n program_ctx = self._simple_program_ctx()\n conversion.convert_entity_to_ast('dummy', program_ctx)\n\n def test_convert_entity_to_ast_callable(self):\n b = 2\n\n def f(a):\n return a + b\n\n program_ctx = self._simple_program_ctx()\n nodes, name, info = conversion.convert_entity_to_ast(f, program_ctx)\n fn_node, = nodes\n self.assertIsInstance(fn_node, gast.FunctionDef)\n self.assertEqual('tf__f', name)\n self.assertIs(info.namespace['b'], b)\n\n def test_convert_entity_to_ast_function_with_defaults(self):\n b = 2\n c = 1\n\n def f(a, d=c + 1):\n return a + b + d\n\n program_ctx = self._simple_program_ctx()\n nodes, name, _ = conversion.convert_entity_to_ast(f, program_ctx)\n fn_node, = nodes\n self.assertIsInstance(fn_node, gast.FunctionDef)\n self.assertEqual('tf__f', name)\n self.assertEqual(\n compiler.ast_to_source(fn_node.args.defaults[0]).strip(), 'None')\n\n def test_convert_entity_to_ast_call_tree(self):\n\n def g(a):\n return a\n\n def f(a):\n return g(a)\n\n program_ctx = self._simple_program_ctx()\n nodes, _, _ = conversion.convert_entity_to_ast(f, program_ctx)\n f_node, = nodes\n self.assertEqual('tf__f', f_node.name)\n\n def test_convert_entity_to_ast_class_hierarchy(self):\n\n class TestBase(object):\n\n def __init__(self, x='base'):\n self.x = x\n\n def foo(self):\n return self.x\n\n def bar(self):\n return self.x\n\n class TestSubclass(TestBase):\n\n def __init__(self, y):\n super(TestSubclass, self).__init__('sub')\n self.y = y\n\n def foo(self):\n return self.y\n\n def baz(self):\n return self.y\n\n program_ctx = self._simple_program_ctx()\n with self.assertRaisesRegex(NotImplementedError, 'classes.*whitelisted'):\n conversion.convert_entity_to_ast(TestSubclass, program_ctx)\n\n def test_convert_entity_to_ast_class_hierarchy_whitelisted(self):\n\n class TestSubclass(training.Model):\n\n def __init__(self, y):\n super(TestSubclass, self).__init__()\n self.built = False\n\n def call(self, x):\n return 3 * x\n\n program_ctx = self._simple_program_ctx()\n (import_node, class_node), name, _ = conversion.convert_entity_to_ast(\n TestSubclass, program_ctx)\n self.assertEqual(import_node.names[0].name, 'Model')\n self.assertEqual(name, 'TfTestSubclass')\n self.assertEqual(class_node.name, 'TfTestSubclass')\n\n def test_convert_entity_to_ast_lambda(self):\n b = 2\n f = lambda x: b * x if x > 0 else -x\n\n program_ctx = self._simple_program_ctx()\n (fn_node,), name, entity_info = conversion.convert_entity_to_ast(\n f, program_ctx)\n self.assertIsInstance(fn_node, gast.Assign)\n self.assertIsInstance(fn_node.value, gast.Lambda)\n self.assertEqual('tf__lambda', name)\n self.assertIs(entity_info.namespace['b'], b)\n\n def test_convert_entity_to_ast_multiple_lambdas(self):\n a, b = 1, 2\n f, _ = (lambda x: a * x, lambda y: b * y)\n\n program_ctx = self._simple_program_ctx()\n (fn_node,), name, entity_info = conversion.convert_entity_to_ast(\n f, program_ctx)\n self.assertIsInstance(fn_node, gast.Assign)\n self.assertIsInstance(fn_node.value, gast.Lambda)\n self.assertEqual('tf__lambda', name)\n self.assertIs(entity_info.namespace['a'], a)\n\n def test_convert_entity_to_ast_multiple_lambdas_ambiguous_definitions(self):\n a, b = 1, 2\n f, _ = (lambda x: a * x, lambda x: b * x)\n\n program_ctx = self._simple_program_ctx()\n with self.assertRaises(ValueError):\n conversion.convert_entity_to_ast(f, program_ctx)\n\n def test_convert_entity_to_ast_lambda_code_with_garbage(self):\n # pylint:disable=g-long-lambda\n f = ( # intentional wrap\n lambda x: (\n x # intentional wrap\n + 1),)[0]\n # pylint:enable=g-long-lambda\n\n program_ctx = self._simple_program_ctx()\n (fn_node,), name, _ = conversion.convert_entity_to_ast(f, program_ctx)\n self.assertIsInstance(fn_node, gast.Assign)\n self.assertIsInstance(fn_node.value, gast.Lambda)\n self.assertEqual('tf__lambda', name)\n\n def test_convert_entity_to_ast_nested_functions(self):\n b = 2\n\n def f(x):\n\n def g(x):\n return b * x\n\n return g(x)\n\n program_ctx = self._simple_program_ctx()\n (fn_node,), name, entity_info = conversion.convert_entity_to_ast(\n f, program_ctx)\n self.assertIsInstance(fn_node, gast.FunctionDef)\n self.assertEqual(fn_node.name, 'tf__f')\n self.assertEqual('tf__f', name)\n self.assertIs(entity_info.namespace['b'], b)\n\n def test_convert_concurrency(self):\n\n def test_fn():\n pass\n\n generated_file_names = []\n\n def conversion_thread():\n new_f = conversion.convert(test_fn, self._simple_program_ctx())\n generated_file_names.append(new_f.__code__.co_filename)\n\n threads = tuple(\n threading.Thread(target=conversion_thread) for _ in range(10))\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n # Races would potentially create multiple files (non-deterministically,\n # but with high likelihood).\n self.assertEqual(len(set(generated_file_names)), 1)\n\n def test_convert_reentrance(self):\n\n def test_fn():\n pass\n\n # There are no known ways to cause convert to re-enter. So we instrument\n # an internal function to do that instead.\n old_node_to_graph = conversion.node_to_graph\n self.num_conversions = 0\n def node_to_graph_wrapper(node, context):\n self.num_conversions += 1\n if self.num_conversions < 2:\n conversion.convert(test_fn, self._simple_program_ctx())\n return old_node_to_graph(node, context)\n\n try:\n conversion.node_to_graph = node_to_graph_wrapper\n new_f = conversion.convert(test_fn, self._simple_program_ctx())\n self.assertIsNotNone(new_f)\n finally:\n conversion.node_to_graph = old_node_to_graph\n\n\nif __name__ == '__main__':\n test.main()\n",
"# 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\"\"\"Test utilities for tf.data functionality.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\n\nfrom tensorflow.python import tf2\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.util import nest\nfrom tensorflow.python.data.util import structure\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.ops.ragged import ragged_test_util\nfrom tensorflow.python.platform import test\n\n\nclass DatasetTestBase(ragged_test_util.RaggedTensorTestCase, test.TestCase):\n \"\"\"Base class for dataset tests.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n if tf2.enabled():\n dataset_ops.Dataset = dataset_ops.DatasetV2\n else:\n dataset_ops.Dataset = dataset_ops.DatasetV1\n\n def assert_op_cancelled(self, op):\n with self.assertRaisesRegexp(errors.CancelledError, \"was cancelled\"):\n self.evaluate(op)\n\n def assertSparseValuesEqual(self, a, b):\n \"\"\"Asserts that two SparseTensors/SparseTensorValues are equal.\"\"\"\n self.assertAllEqual(a.indices, b.indices)\n self.assertAllEqual(a.values, b.values)\n self.assertAllEqual(a.dense_shape, b.dense_shape)\n\n def getNext(self, dataset, requires_initialization=False):\n \"\"\"Returns a callable that returns the next element of the dataset.\n\n Example use:\n ```python\n # In both graph and eager modes\n dataset = ...\n get_next = self.getNext(dataset)\n result = self.evaluate(get_next())\n ```\n\n Args:\n dataset: A dataset whose elements will be returned.\n requires_initialization: Indicates that when the test is executed in graph\n mode, it should use an initializable iterator to iterate through the\n dataset (e.g. when it contains stateful nodes). Defaults to False.\n Returns:\n A callable that returns the next element of `dataset`. Any `TensorArray`\n objects `dataset` outputs are stacked.\n \"\"\"\n def ta_wrapper(gn):\n def _wrapper():\n r = gn()\n if isinstance(r, tensor_array_ops.TensorArray):\n return r.stack()\n else:\n return r\n return _wrapper\n if context.executing_eagerly():\n iterator = iter(dataset)\n return ta_wrapper(iterator._next_internal) # pylint: disable=protected-access\n else:\n if requires_initialization:\n iterator = dataset_ops.make_initializable_iterator(dataset)\n self.evaluate(iterator.initializer)\n else:\n iterator = dataset_ops.make_one_shot_iterator(dataset)\n get_next = iterator.get_next()\n return ta_wrapper(lambda: get_next)\n\n def _compareOutputToExpected(self, result_values, expected_values,\n assert_items_equal):\n if assert_items_equal:\n # TODO(shivaniagrawal): add support for nested elements containing sparse\n # tensors when needed.\n self.assertItemsEqual(result_values, expected_values)\n return\n for i in range(len(result_values)):\n nest.assert_same_structure(result_values[i], expected_values[i])\n for result_value, expected_value in zip(\n nest.flatten(result_values[i]), nest.flatten(expected_values[i])):\n if sparse_tensor.is_sparse(result_value):\n self.assertSparseValuesEqual(result_value, expected_value)\n elif ragged_tensor.is_ragged(result_value):\n self.assertRaggedEqual(result_value, expected_value)\n else:\n self.assertAllEqual(\n result_value,\n expected_value,\n msg=(\"Result value: {}. Expected value: {}\"\n .format(result_value, expected_value)))\n\n def assertDatasetProduces(self,\n dataset,\n expected_output=None,\n expected_shapes=None,\n expected_error=None,\n requires_initialization=False,\n num_test_iterations=1,\n assert_items_equal=False,\n expected_error_iter=1):\n \"\"\"Asserts that a dataset produces the expected output / error.\n\n Args:\n dataset: A dataset to check for the expected output / error.\n expected_output: A list of elements that the dataset is expected to\n produce.\n expected_shapes: A list of TensorShapes which is expected to match\n output_shapes of dataset.\n expected_error: A tuple `(type, predicate)` identifying the expected error\n `dataset` should raise. The `type` should match the expected exception\n type, while `predicate` should either be 1) a unary function that inputs\n the raised exception and returns a boolean indicator of success or 2) a\n regular expression that is expected to match the error message\n partially.\n requires_initialization: Indicates that when the test is executed in graph\n mode, it should use an initializable iterator to iterate through the\n dataset (e.g. when it contains stateful nodes). Defaults to False.\n num_test_iterations: Number of times `dataset` will be iterated. Defaults\n to 2.\n assert_items_equal: Tests expected_output has (only) the same elements\n regardless of order.\n expected_error_iter: How many times to iterate before expecting an error,\n if an error is expected.\n \"\"\"\n self.assertTrue(\n expected_error is not None or expected_output is not None,\n \"Exactly one of expected_output or expected error should be provided.\")\n if expected_error:\n self.assertTrue(\n expected_output is None,\n \"Exactly one of expected_output or expected error should be provided.\"\n )\n with self.assertRaisesWithPredicateMatch(expected_error[0],\n expected_error[1]):\n get_next = self.getNext(\n dataset, requires_initialization=requires_initialization)\n for _ in range(expected_error_iter):\n self.evaluate(get_next())\n return\n if expected_shapes:\n self.assertEqual(expected_shapes,\n dataset_ops.get_legacy_output_shapes(dataset))\n self.assertGreater(num_test_iterations, 0)\n for _ in range(num_test_iterations):\n get_next = self.getNext(\n dataset, requires_initialization=requires_initialization)\n result = []\n for _ in range(len(expected_output)):\n result.append(self.evaluate(get_next()))\n self._compareOutputToExpected(result, expected_output, assert_items_equal)\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n def assertDatasetsEqual(self, dataset1, dataset2):\n \"\"\"Checks that datasets are equal. Supports both graph and eager mode.\"\"\"\n self.assertTrue(\n structure.are_compatible(\n dataset_ops.get_structure(dataset1),\n dataset_ops.get_structure(dataset2)))\n\n flattened_types = nest.flatten(\n dataset_ops.get_legacy_output_types(dataset1))\n\n next1 = self.getNext(dataset1)\n next2 = self.getNext(dataset2)\n\n while True:\n try:\n op1 = self.evaluate(next1())\n except errors.OutOfRangeError:\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(next2())\n break\n op2 = self.evaluate(next2())\n\n op1 = nest.flatten(op1)\n op2 = nest.flatten(op2)\n assert len(op1) == len(op2)\n for i in range(len(op1)):\n if sparse_tensor.is_sparse(op1[i]):\n self.assertSparseValuesEqual(op1[i], op2[i])\n elif ragged_tensor.is_ragged(op1[i]):\n self.assertRaggedEqual(op1[i], op2[i])\n elif flattened_types[i] == dtypes.string:\n self.assertAllEqual(op1[i], op2[i])\n else:\n self.assertAllClose(op1[i], op2[i])\n\n def assertDatasetsRaiseSameError(self,\n dataset1,\n dataset2,\n exception_class,\n replacements=None):\n \"\"\"Checks that datasets raise the same error on the first get_next call.\"\"\"\n if replacements is None:\n replacements = []\n next1 = self.getNext(dataset1)\n next2 = self.getNext(dataset2)\n try:\n self.evaluate(next1())\n raise ValueError(\n \"Expected dataset to raise an error of type %s, but it did not.\" %\n repr(exception_class))\n except exception_class as e:\n expected_message = e.message\n for old, new, count in replacements:\n expected_message = expected_message.replace(old, new, count)\n # Check that the first segment of the error messages are the same.\n with self.assertRaisesRegexp(exception_class,\n re.escape(expected_message)):\n self.evaluate(next2())\n\n def structuredDataset(self, dataset_structure, shape=None,\n dtype=dtypes.int64):\n \"\"\"Returns a singleton dataset with the given structure.\"\"\"\n if shape is None:\n shape = []\n if dataset_structure is None:\n return dataset_ops.Dataset.from_tensors(\n array_ops.zeros(shape, dtype=dtype))\n else:\n return dataset_ops.Dataset.zip(\n tuple([\n self.structuredDataset(substructure, shape, dtype)\n for substructure in dataset_structure\n ]))\n\n def structuredElement(self, element_structure, shape=None,\n dtype=dtypes.int64):\n \"\"\"Returns an element with the given structure.\"\"\"\n if shape is None:\n shape = []\n if element_structure is None:\n return array_ops.zeros(shape, dtype=dtype)\n else:\n return tuple([\n self.structuredElement(substructure, shape, dtype)\n for substructure in element_structure\n ])\n"
] | [
[
"tensorflow.python.autograph.core.converter.ConversionOptions",
"tensorflow.python.autograph.impl.conversion.is_whitelisted_for_graph",
"tensorflow.python.autograph.impl.conversion.convert_entity_to_ast",
"tensorflow.python.platform.test.main",
"tensorflow.python.autograph.pyct.compiler.ast_to_source",
"tensorflow.python.autograph.core.config.DoNotConvert",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.framework.sparse_tensor.is_sparse",
"tensorflow.python.data.ops.dataset_ops.make_initializable_iterator",
"tensorflow.python.data.ops.dataset_ops.get_structure",
"tensorflow.python.data.util.nest.assert_same_structure",
"tensorflow.python.data.ops.dataset_ops.make_one_shot_iterator",
"tensorflow.python.ops.ragged.ragged_tensor.is_ragged",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.tf2.enabled",
"tensorflow.python.data.util.nest.flatten",
"tensorflow.python.data.ops.dataset_ops.get_legacy_output_shapes",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.data.ops.dataset_ops.get_legacy_output_types"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"2.7",
"2.6",
"2.4",
"2.3",
"2.9",
"2.5",
"2.2",
"2.10"
]
}
] |
makinarocks/IGNN | [
"5d4fd69951c10cda452773ac92f98440ffebd453"
] | [
"graphclassification/models.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom layers import ImplicitGraph\nfrom torch.nn import Parameter\nfrom utils import get_spectral_rad, SparseDropout\nimport torch.sparse as sparse\nfrom torch_geometric.nn import global_add_pool\n\n\nclass IGNN(nn.Module):\n def __init__(self, nfeat, nhid, nclass, num_node, dropout, kappa=0.9, adj_orig=None):\n super(IGNN, self).__init__()\n\n self.adj = None\n self.adj_rho = None\n self.adj_orig = adj_orig\n\n #three layers and two MLP\n self.ig1 = ImplicitGraph(nfeat, nhid, num_node, kappa)\n self.ig2 = ImplicitGraph(nhid, nhid, num_node, kappa)\n self.ig3 = ImplicitGraph(nhid, nhid, num_node, kappa)\n self.dropout = dropout\n self.X_0 = None\n self.V_0 = nn.Linear(nhid, nhid)\n self.V_1 = nn.Linear(nhid, nclass)\n\n def forward(self, features, adj, batch):\n '''\n if adj is not self.adj:\n self.adj = adj\n self.adj_rho = get_spectral_rad(adj)\n '''\n self.adj_rho = 1\n\n x = features\n\n #three layers and two MLP\n x = self.ig1(self.X_0, adj, x, F.relu, self.adj_rho, A_orig=self.adj_orig)\n x = self.ig2(self.X_0, adj, x, F.relu, self.adj_rho, A_orig=self.adj_orig)\n x = self.ig3(self.X_0, adj, x, F.relu, self.adj_rho, A_orig=self.adj_orig).T\n x = global_add_pool(x, batch)\n x = F.relu(self.V_0(x))\n x = F.dropout(x, self.dropout, training=self.training)\n x = self.V_1(x)\n return F.log_softmax(x, dim=1)\n\n\n"
] | [
[
"torch.nn.Linear",
"torch.nn.functional.log_softmax",
"torch.nn.functional.dropout"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
quanpn90/SpeechGAN | [
"b2aa923ac40474bd7a6fa2acfd290eb2770e0972",
"b2aa923ac40474bd7a6fa2acfd290eb2770e0972",
"b2aa923ac40474bd7a6fa2acfd290eb2770e0972"
] | [
"onmt/models/relative_transformer.py",
"pynn/trainer/adam_ctc.py",
"pynn/trainer/adam_seq2seq_v2.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom onmt.models.transformer_layers import PositionalEncoding, PrePostProcessing\nfrom onmt.models.transformer_layers import EncoderLayer, DecoderLayer\nfrom onmt.models.transformers import TransformerEncoder, TransformerDecoder, Transformer, TransformerDecodingState\nimport onmt\nfrom onmt.modules.base_seq2seq import NMTModel, Reconstructor, DecoderState\nfrom onmt.modules.dropout import embedded_dropout\nfrom onmt.models.transformer_layers import XavierLinear, MultiHeadAttention, FeedForward, PrePostProcessing\nfrom onmt.models.relative_transformer_layers import RelativeTransformerEncoderLayer, RelativeTransformerDecoderLayer\nfrom onmt.reversible_models.relative_transformers import ReversibleEncoderFunction, ReversibleDecoderFunction, \\\n ReversibleTransformerDecoderLayer, ReversibleTransformerEncoderLayer\nfrom onmt.utils import flip, expected_length\nfrom collections import defaultdict\nimport math\nimport sys\n\ntorch.set_printoptions(threshold=500000)\n\n\n# Positional Embedding with discrete inputs\nclass SinusoidalPositionalEmbedding(nn.Module):\n def __init__(self, demb):\n super(SinusoidalPositionalEmbedding, self).__init__()\n\n self.demb = demb\n\n inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb))\n self.register_buffer('inv_freq', inv_freq)\n\n def forward(self, pos_seq, sin_first=True, bsz=None):\n \"\"\"\n :param bsz: integer to repeat\n :param pos_seq: sequences of RELATIVE position indices (can be negative for future)\n :param sin_first: in Attention is all you need paper, sin is first then cosin\n \"\"\"\n sinusoid_inp = torch.ger(pos_seq, self.inv_freq.type_as(pos_seq))\n\n if sin_first:\n pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)\n else:\n pos_emb = torch.cat([sinusoid_inp.cos(), sinusoid_inp.sin()], dim=-1)\n\n if bsz is not None:\n return pos_emb[:, None, :].repeat(1, bsz, 1)\n else:\n return pos_emb[:, None, :]\n\n\nclass RelativeTransformerEncoder(TransformerEncoder):\n\n def __init__(self, opt, dicts, positional_encoder, encoder_type='text', language_embeddings=None):\n self.death_rate = opt.death_rate\n self.learnable_position_encoding = opt.learnable_position_encoding\n self.layer_modules = list()\n self.asynchronous = opt.asynchronous\n self.max_memory_size = opt.max_memory_size\n self.extra_context_size = opt.extra_context_size\n self.experimental = opt.experimental\n self.unidirectional = opt.unidirectional\n self.reversible = opt.src_reversible\n self.n_heads = opt.n_heads\n self.fast_self_attn = opt.fast_self_attention\n self.add_position_encoding = opt.add_position_encoding\n\n # build_modules will be called from the inherited constructor\n super(RelativeTransformerEncoder, self).__init__(opt, dicts, positional_encoder, encoder_type,\n language_embeddings)\n\n # learnable position encoding\n if self.learnable_position_encoding:\n raise NotImplementedError\n else:\n # or using pre-set sinusoidal\n self.positional_encoder = SinusoidalPositionalEmbedding(opt.model_size)\n\n self.d_head = self.model_size // self.n_heads\n\n def build_modules(self):\n\n e_length = expected_length(self.layers, self.death_rate)\n if self.reversible:\n print(\"* Reversible Encoder with Relative Attention with %.2f expected layers\" % e_length)\n else:\n print(\"* Transformer Encoder with Relative Attention with %.2f expected layers\" % e_length)\n if self.unidirectional:\n print(\"* Running a unidirectional Encoder.\")\n\n self.layer_modules = nn.ModuleList()\n\n for _l in range(self.layers):\n # linearly decay the death rate\n death_r = (_l + 1.0) / self.layers * self.death_rate\n\n if not self.reversible:\n block = RelativeTransformerEncoderLayer(self.opt, death_rate=death_r)\n else:\n block = ReversibleTransformerEncoderLayer(self.opt, death_rate=death_r)\n\n self.layer_modules.append(block)\n\n def create_stream_mask(self, input, input_length, prev_mem_size):\n\n lengths = input_length.tolist()\n mask = None\n\n for length in lengths:\n\n # the current mask should be either None or\n\n if mask is None:\n prev_length = 0\n else:\n prev_length = mask.size(1)\n\n # n current queries attend to n + p keys\n current_mask = input.new_zeros(length, length + prev_length)\n\n if prev_length > 0:\n prev_mask = input.new_ones(prev_length, length)\n prev_mask = torch.cat([mask, prev_mask], dim=-1)\n else:\n prev_mask = None\n\n if prev_mask is not None:\n mask = torch.cat([prev_mask, current_mask], dim=0)\n else:\n mask = current_mask\n\n if prev_mem_size > 0:\n # all current elements attend to all buffer elements\n buffer_mask = mask.new_zeros(mask.size(0), prev_mem_size)\n mask = torch.cat([buffer_mask, mask], dim=-1)\n\n mask = mask.bool()\n\n return mask\n\n def forward(self, input, input_pos=None, input_lang=None, streaming=False, **kwargs):\n \"\"\"\n Inputs Shapes:\n input: batch_size x src_len (wanna tranpose)\n Outputs Shapes:\n out: batch_size x src_len x d_model\n mask_src\n \"\"\"\n\n \"\"\" Embedding: batch_size x src_len x d_model \"\"\"\n if self.input_type == \"text\":\n bsz_first_input = input\n input = input.transpose(0, 1)\n # mask_src = input.eq(onmt.constants.PAD).unsqueeze(1) # batch_size x src_len x 1 for broadcasting\n\n dec_attn_mask = bsz_first_input.eq(onmt.constants.PAD).unsqueeze(1)\n\n if streaming:\n streaming_state = kwargs.get('streaming_state', None)\n mems = streaming_state.src_mems\n # mem_len = streaming_state.src_mems[0].size(0)\n # mem_len = streaming_state.prev_src_mem_size\n mem_len = mems[0].size(0) if mems is not None else 0\n input_length = kwargs.get('src_lengths', None)\n streaming_state = kwargs.get('streaming_state', None)\n mask_src = self.create_stream_mask(input, input_length, mem_len)\n mask_src = mask_src.unsqueeze(2)\n else:\n mem_len = 0\n mask_src = input.eq(onmt.constants.PAD).unsqueeze(0) # batch_size x src_len x 1 for broadcasting\n mems = None\n\n emb = embedded_dropout(self.word_lut, input, dropout=self.word_dropout if self.training else 0)\n\n \"\"\" Adding language embeddings \"\"\"\n if self.use_language_embedding:\n assert self.language_embedding is not None\n # There is no \"unsqueeze\" here because the input is T x B x H and lang_emb is B x H\n if self.language_embedding_type in ['sum', 'all_sum']:\n lang_emb = self.language_embedding(input_lang)\n # print(lang_emb.size(), emb.size())\n emb = emb + lang_emb.unsqueeze(0)\n\n else:\n if streaming:\n raise NotImplementedError\n\n if not self.cnn_downsampling:\n mask_src = input.narrow(2, 0, 1).squeeze(2).transpose(0, 1).eq(onmt.constants.PAD).unsqueeze(0)\n dec_attn_mask = input.narrow(2, 0, 1).squeeze(2).eq(onmt.constants.PAD).unsqueeze(1)\n input = input.narrow(2, 1, input.size(2) - 1)\n emb = self.audio_trans(input.contiguous().view(-1, input.size(2))).view(input.size(0),\n input.size(1), -1)\n emb = emb.type_as(input)\n else:\n long_mask = input.narrow(2, 0, 1).squeeze(2).eq(onmt.constants.PAD)\n input = input.narrow(2, 1, input.size(2) - 1)\n\n # first resizing to fit the CNN format\n input = input.view(input.size(0), input.size(1), -1, self.channels)\n input = input.permute(0, 3, 1, 2)\n\n input = self.audio_trans(input)\n input = input.permute(0, 2, 1, 3).contiguous()\n input = input.view(input.size(0), input.size(1), -1)\n # print(input.size())\n input = self.linear_trans(input)\n\n mask_src = long_mask[:, 0:input.size(1) * 4:4].transpose(0, 1).unsqueeze(0)\n dec_attn_mask = long_mask[:, 0:input.size(1) * 4:4].unsqueeze(1)\n # the size seems to be B x T ?\n emb = input\n\n emb = emb.transpose(0, 1)\n input = input.transpose(0, 1)\n abs_pos = None\n mem_len = 0\n mems = None\n\n if self.unidirectional:\n qlen = input.size(0)\n klen = qlen + mem_len\n attn_mask_src = torch.triu(\n emb.new_ones(qlen, klen), diagonal=1 + mem_len).byte()[:, :, None]\n\n pad_mask = mask_src\n\n mask_src = pad_mask + attn_mask_src\n # dec_attn_mask = dec_attn_mask + pad_mask.unsqueeze(0)\n mask_src = mask_src.gt(0)\n\n if onmt.constants.torch_version >= 1.2:\n mask_src = mask_src.bool()\n\n \"\"\" Scale the emb by sqrt(d_model) \"\"\"\n emb = emb * math.sqrt(self.model_size)\n\n \"\"\" Adding positional encoding \"\"\"\n qlen = input.size(0)\n klen = qlen + mem_len\n\n # Asynchronous positions: 2K+1 positions instead of K+1\n if self.unidirectional:\n pos = torch.arange(klen - 1, -1, -1.0, device=emb.device, dtype=emb.dtype)\n else:\n pos = torch.arange(klen - 1, -klen, -1.0, device=emb.device, dtype=emb.dtype)\n\n # pos_emb has size 2T+1 x 1 x H\n pos_emb = self.positional_encoder(pos, bsz=input.size(1) if self.fast_self_attn else None)\n\n if self.learnable_position_encoding:\n raise NotImplementedError\n\n # B x T x H -> T x B x H\n context = emb\n\n if streaming:\n hids = [context]\n\n # Apply dropout to both context and pos_emb\n context = self.preprocess_layer(context)\n\n pos_emb = self.preprocess_layer(pos_emb)\n\n if self.reversible:\n context = torch.cat([context, context], dim=-1)\n\n assert streaming is not True, \"Streaming and Reversible is not usable yet.\"\n # print(context.size(), pos_emb.size())\n context = ReversibleEncoderFunction.apply(context, pos_emb, self.layer_modules, mask_src)\n else:\n for i, layer in enumerate(self.layer_modules):\n # src_len x batch_size x d_model\n\n mems_i = mems[i] if mems is not None and streaming and self.max_memory_size > 0 else None\n context = layer(context, pos_emb, mask_src, mems=mems_i)\n\n if streaming:\n hids.append(context)\n\n # final layer norm\n context = self.postprocess_layer(context)\n\n output_dict = defaultdict(lambda: None, {'context': context, 'src_mask': dec_attn_mask, 'src': input})\n\n if streaming:\n # streaming_state.prev_src_mem_size += sum(input_length.tolist())\n # streaming_state.prune_source_memory(self.max_memory_size)\n streaming_state.update_src_mems(hids, qlen)\n output_dict['streaming_state'] = streaming_state\n\n return output_dict\n\n\nclass RelativeTransformerDecoder(TransformerDecoder):\n\n def __init__(self, opt, dicts, positional_encoder, language_embeddings=None, ignore_source=False):\n\n self.death_rate = opt.death_rate\n self.max_memory_size = opt.max_memory_size\n self.stream_context = opt.stream_context\n self.extra_context_size = opt.extra_context_size\n self.n_heads = opt.n_heads\n self.fast_self_attn = opt.fast_self_attention\n\n # build_modules will be called from the inherited constructor\n super(RelativeTransformerDecoder, self).__init__(opt, dicts,\n positional_encoder,\n language_embeddings,\n ignore_source,\n allocate_positions=False)\n\n self.positional_encoder = SinusoidalPositionalEmbedding(opt.model_size)\n self.d_head = self.model_size // self.n_heads\n # Parameters for the position biases - deprecated. kept for backward compatibility\n self.r_w_bias = nn.Parameter(torch.Tensor(self.n_heads, self.d_head))\n self.r_r_bias = nn.Parameter(torch.Tensor(self.n_heads, self.d_head))\n\n def renew_buffer(self, new_len):\n return\n\n def build_modules(self):\n\n e_length = expected_length(self.layers, self.death_rate)\n self.opt.ignore_source = self.ignore_source\n if self.reversible:\n print(\"* Transformer Reversible Decoder with Relative Attention with %.2f expected layers\" % e_length)\n else:\n print(\"* Transformer Decoder with Relative Attention with %.2f expected layers\" % e_length)\n\n self.layer_modules = nn.ModuleList()\n\n for l in range(self.layers):\n # linearly decay the death rate\n death_r = (l + 1.0) / self.layers * self.death_rate\n\n if not self.reversible:\n block = RelativeTransformerDecoderLayer(self.opt, death_rate=death_r)\n else:\n block = ReversibleTransformerDecoderLayer(self.opt, death_rate=death_r)\n\n self.layer_modules.append(block)\n\n def process_embedding(self, input, input_lang=None):\n\n return input\n\n def create_context_mask(self, input, src, src_lengths, tgt_lengths, extra_context_length=0):\n \"\"\"\n Generate the mask so that part of the target attends to a part of the source\n :param extra_context_length:\n :param input:\n :param src:\n :param src_lengths:\n :param tgt_lengths:\n :return:\n \"\"\"\n\n mask = None\n\n if self.stream_context == 'global':\n # Global context: one target attends to everything in the source\n for (src_length, tgt_length) in zip(src_lengths, tgt_lengths):\n\n if mask is None:\n prev_src_length = 0\n prev_tgt_length = 0\n else:\n prev_src_length, prev_tgt_length = mask.size(1), mask.size(0)\n\n # current sent attend to current src sent and all src in the past\n current_mask = input.new_zeros(tgt_length, src_length + prev_src_length)\n\n # the previous target cannot attend to the current source\n if prev_tgt_length > 0:\n prev_mask = input.new_ones(prev_tgt_length, src_length)\n prev_mask = torch.cat([mask, prev_mask], dim=-1)\n else:\n prev_mask = None\n\n # the output mask has two parts: the prev and the current\n if prev_mask is not None:\n mask = torch.cat([prev_mask, current_mask], dim=0)\n else:\n mask = current_mask\n\n elif self.stream_context in ['local', 'limited']:\n # Local context: only attends to the aligned context\n for (src_length, tgt_length) in zip(src_lengths, tgt_lengths):\n\n if mask is None:\n prev_src_length = 0\n prev_tgt_length = 0\n else:\n prev_src_length, prev_tgt_length = mask.size(1), mask.size(0)\n\n # current tgt sent attend to only current src sent\n if prev_src_length > 0:\n current_mask = torch.cat([input.new_ones(tgt_length, prev_src_length - extra_context_length),\n input.new_zeros(tgt_length, src_length + extra_context_length)], dim=-1)\n else:\n current_mask = input.new_zeros(tgt_length, src_length + extra_context_length)\n\n # the previous target cannot attend to the current source\n if prev_tgt_length > 0:\n prev_mask = input.new_ones(prev_tgt_length, src_length)\n prev_mask = torch.cat([mask, prev_mask], dim=-1)\n else:\n prev_mask = None\n\n # the output mask has two parts: the prev and the current\n if prev_mask is not None:\n mask = torch.cat([prev_mask, current_mask], dim=0)\n else:\n mask = current_mask\n\n mask = mask.bool()\n return mask\n\n def create_self_attn_mask(self, input, tgt_lengths, prev_tgt_mem_size):\n \"\"\"\n Create a mask for the target words attending to the past\n :param input:\n :param tgt_lengths:\n :param prev_tgt_mem_size:\n :return:\n \"\"\"\n\n if self.stream_context in ['local', 'global']:\n qlen = sum(tgt_lengths.tolist())\n mlen = prev_tgt_mem_size\n klen = qlen + mlen\n mask = torch.triu(input.new_ones(qlen, klen), diagonal=1 + mlen).bool()[:, :, None]\n elif self.stream_context in ['limited']:\n # limited means that every sentence only pay attention to the extra memory size\n extra_mem_len = self.max_memory_size\n # past_length = prev_tgt_mem_size\n mask = None\n memory_size = prev_tgt_mem_size\n\n for length in tgt_lengths:\n\n past_length = mask.size(0) if mask is not None else 0\n\n qlen = length\n mlen = min(memory_size, self.max_memory_size)\n klen = qlen + mlen\n\n cur_attn_mask = torch.triu(input.new_ones(qlen, klen), diagonal=1 + mlen)\n\n # for the rest of the past sequence: don't look at them\n if mlen < memory_size:\n no_attn_mask = input.new_ones(qlen, memory_size - mlen)\n cur_attn_mask = torch.cat([no_attn_mask, cur_attn_mask], dim=1)\n\n if mask is not None:\n prev_q, prev_k = mask.size(0), mask.size(1)\n # the past doesn't look at future\n prev_mask = input.new_ones(prev_q, qlen)\n mask = torch.cat([mask, prev_mask], dim=1) # first, concatenate for the K dim\n mask = torch.cat([mask, cur_attn_mask], dim=0) # concatenate for the Q dim\n else:\n mask = cur_attn_mask\n\n memory_size = mask.size(1)\n\n mask = mask.bool().unsqueeze(-1)\n\n return mask\n\n # TODO: merging forward_stream and forward\n # TODO: write a step function for encoder\n\n def forward(self, input, context, src, input_pos=None, tgt_lang=None, streaming=False, **kwargs):\n \"\"\"\n Inputs Shapes:\n input: (Variable) batch_size x len_tgt (wanna tranpose)\n context: (Variable) batch_size x src_len x d_model\n mask_src (Tensor) batch_size x src_len\n Outputs Shapes:\n out: batch_size x len_tgt x d_model\n coverage: batch_size x len_tgt x src_len\n\n \"\"\"\n\n \"\"\" Embedding: batch_size x len_tgt x d_model \"\"\"\n input = input.transpose(0, 1) # T x B\n emb = embedded_dropout(self.word_lut, input, dropout=self.word_dropout if self.training else 0)\n emb = emb * math.sqrt(self.model_size)\n\n if streaming:\n src_lengths = kwargs.get(\"src_lengths\", None)\n tgt_lengths = kwargs.get(\"tgt_lengths\", None)\n streaming_state = kwargs.get(\"streaming_state\")\n mems = streaming_state.tgt_mems\n\n extra_context = streaming_state.extra_context\n extra_context_length = extra_context.size(0) if extra_context is not None else 0\n\n # mem_len = streaming_state.prev_tgt_mem_size\n mem_len = mems[0].size(0) if mems is not None else 0\n else:\n mem_len = 0\n mems = None\n extra_context = None\n\n if self.use_language_embedding:\n lang_emb = self.language_embeddings(tgt_lang) # B x H or 1 x H\n if self.language_embedding_type == 'sum':\n print(emb.shape)\n print(lang_emb.shape)\n emb = emb + lang_emb\n elif self.language_embedding_type == 'concat':\n print(emb.shape)\n print(lang_emb.shape)\n # replace the bos embedding with the language\n bos_emb = lang_emb.expand_as(emb[0])\n emb[0] = bos_emb\n\n lang_emb = lang_emb.unsqueeze(0).expand_as(emb)\n concat_emb = torch.cat([emb, lang_emb], dim=-1)\n emb = torch.relu(self.projector(concat_emb))\n else:\n raise NotImplementedError\n\n if context is not None:\n if self.encoder_type == \"audio\":\n if not self.encoder_cnn_downsampling:\n mask_src = src.narrow(2, 0, 1).squeeze(2).eq(onmt.constants.PAD).unsqueeze(1)\n else:\n long_mask = src.data.narrow(2, 0, 1).squeeze(2).eq(onmt.constants.PAD)\n mask_src = long_mask[:, 0:context.size(0) * 4:4].unsqueeze(1)\n else:\n if streaming:\n context_attn_mask = self.create_context_mask(input, src,\n src_lengths, tgt_lengths,\n extra_context_length)\n mask_src = context_attn_mask.unsqueeze(0)\n else:\n mask_src = src.eq(onmt.constants.PAD).unsqueeze(1)\n else:\n mask_src = None\n\n qlen = input.size(0)\n klen = qlen + mem_len\n # preparing self-attention mask. The input is either left or right aligned\n\n if streaming:\n dec_attn_mask = self.create_self_attn_mask(input, tgt_lengths, mem_len)\n else:\n dec_attn_mask = torch.triu(\n emb.new_ones(qlen, klen), diagonal=1 + mem_len).byte()[:, :, None]\n # pad_mask = input.eq(onmt.constants.PAD).byte() # L x B\n #\n # dec_attn_mask = dec_attn_mask + pad_mask.unsqueeze(0)\n # dec_attn_mask = dec_attn_mask.gt(0)\n dec_attn_mask = dec_attn_mask.bool()\n\n pos = torch.arange(klen - 1, -1, -1.0, device=emb.device, dtype=emb.dtype)\n\n pos_emb = self.positional_encoder(pos, bsz=input.size(1) if self.fast_self_attn else None)\n\n output = self.preprocess_layer(emb.contiguous())\n\n if streaming:\n hids = [output]\n if extra_context is not None:\n context = torch.cat([extra_context, context], dim=0)\n\n pos_emb = self.preprocess_layer(pos_emb)\n\n if self.reversible:\n output = torch.cat([output, output], dim=-1)\n\n output = ReversibleDecoderFunction.apply(output, pos_emb, context, self.layer_modules,\n dec_attn_mask, mask_src)\n coverage = None\n else:\n\n for i, layer in enumerate(self.layer_modules):\n # batch_size x src_len x d_model output, coverage = layer(output, context, pos_emb, self.r_w_bias,\n # self.r_r_bias, dec_attn_mask, mask_src)\n mems_i = mems[i] if mems is not None and streaming and \\\n self.stream_context in ['local', 'global'] and self.max_memory_size > 0 else None\n\n output, coverage, _ = layer(output, context, pos_emb, dec_attn_mask, mask_src, mems=mems_i)\n if streaming:\n hids.append(output)\n\n # From Google T2T\n # if normalization is done in layer_preprocess, then it should also be done\n # on the output, since the output can grow very large, being the sum of\n # a whole stack of unnormalized layer outputs.\n output = self.postprocess_layer(output)\n\n output_dict = {'hidden': output, 'coverage': coverage, 'context': context}\n output_dict = defaultdict(lambda: None, output_dict)\n\n if streaming:\n # streaming_state.prev_tgt_mem_size += sum(tgt_lengths.tolist())\n # streaming_state.prune_target_memory(self.max_memory_size)\n\n # if we use the extra context: keep the last context\n if self.extra_context_size > 0:\n extra_context = context[-self.extra_context_size:].detach()\n streaming_state.extra_context = extra_context\n\n if self.stream_context in ['local', 'global']:\n streaming_state.update_tgt_mems(hids, qlen)\n\n output_dict['streaming_state'] = streaming_state\n\n return output_dict\n\n def step(self, input, decoder_state, streaming=False):\n \"\"\"\n Inputs Shapes:\n input: (Variable) batch_size x len_tgt (wanna tranpose)\n context: (Variable) batch_size x src_len x d_model\n mask_src (Tensor) batch_size x src_len\n buffer (List of tensors) List of batch_size * len_tgt-1 * d_model for self-attention recomputing\n Outputs Shapes:\n out: batch_size x len_tgt x d_model\n coverage: batch_size x len_tgt x src_len\n\n \"\"\"\n\n if streaming:\n return self.step_streaming(input, decoder_state)\n\n context = decoder_state.context\n buffers = decoder_state.attention_buffers\n lang = decoder_state.tgt_lang\n buffering = decoder_state.buffering\n\n if decoder_state.concat_input_seq:\n if decoder_state.input_seq is None:\n decoder_state.input_seq = input\n else:\n # concatenate the last input to the previous input sequence\n decoder_state.input_seq = torch.cat([decoder_state.input_seq, input], 0)\n input = decoder_state.input_seq.transpose(0, 1) # B x T\n\n src = decoder_state.src.transpose(0, 1) if decoder_state.src is not None else None\n\n if buffering:\n # use the last value of input to continue decoding\n if input.size(1) > 1:\n input_ = input[:, -1].unsqueeze(1).transpose(0, 1)\n else:\n input_ = input.transpose(0, 1)\n else:\n input_ = input.transpose(0, 1) # from B x T to T x B\n\n \"\"\" Embedding: batch_size x 1 x d_model \"\"\"\n emb = self.word_lut(input_) * math.sqrt(self.model_size)\n input = input.transpose(0, 1)\n klen = input.size(0)\n # emb = self.word_lut(input) * math.sqrt(self.model_size)\n\n if self.use_language_embedding:\n lang_emb = self.language_embeddings(lang) # B x H\n\n if self.language_embedding_type in ['sum', 'all_sum']:\n emb = emb + lang_emb\n elif self.language_embedding_type == 'concat':\n if input.size(0) == 1:\n emb[0] = lang_emb\n\n lang_emb = lang_emb.unsqueeze(0).expand_as(emb)\n concat_emb = torch.cat([emb, lang_emb], dim=-1)\n emb = torch.relu(self.projector(concat_emb))\n else:\n raise NotImplementedError\n\n # prepare position encoding\n qlen = emb.size(0)\n mlen = klen - qlen\n\n pos = torch.arange(klen - 1, -1, -1.0, device=emb.device, dtype=emb.dtype)\n\n pos_emb = self.positional_encoder(pos)\n\n dec_attn_mask = torch.triu(\n emb.new_ones(qlen, klen), diagonal=1 + mlen).byte()[:, :, None]\n\n # pad_mask = input.eq(onmt.constants.PAD).byte() # L x B\n\n # dec_attn_mask = dec_attn_mask + pad_mask.unsqueeze(0)\n # dec_attn_mask = dec_attn_mask.gt(0)\n\n if onmt.constants.torch_version >= 1.2:\n dec_attn_mask = dec_attn_mask.bool()\n\n if context is not None:\n if self.encoder_type == \"audio\":\n if not self.encoder_cnn_downsampling:\n mask_src = src.narrow(2, 0, 1).squeeze(2).eq(onmt.constants.PAD).unsqueeze(1)\n else:\n long_mask = src.data.narrow(2, 0, 1).squeeze(2).eq(onmt.constants.PAD)\n mask_src = long_mask[:, 0:context.size(0) * 4:4].unsqueeze(1)\n else:\n mask_src = src.eq(onmt.constants.PAD).unsqueeze(1)\n else:\n mask_src = None\n\n output = emb.contiguous()\n\n if self.reversible:\n output_1, output_2 = output, output\n\n for i, layer in enumerate(self.layer_modules):\n buffer = buffers[i] if i in buffers else None\n\n if self.reversible:\n if buffering:\n output_1, output_2, coverage, buffer = layer(output_1, output_2, pos_emb, context,\n dec_attn_mask, mask_src, incremental=True,\n incremental_cache=buffer)\n decoder_state.update_attention_buffer(buffer, i)\n else:\n output_1, output_2, coverage, _ = layer(output_1, output_2, pos_emb, context,\n dec_attn_mask, mask_src)\n else:\n if buffering:\n output, coverage, buffer = layer(output, context, pos_emb, dec_attn_mask, mask_src,\n incremental=True, incremental_cache=buffer)\n decoder_state.update_attention_buffer(buffer, i)\n else:\n output, coverage, _ = layer(output, context, pos_emb, dec_attn_mask, mask_src)\n\n if self.reversible:\n output = output_1 + output_2\n\n # normalize and take the last time step\n output = self.postprocess_layer(output)\n output = output[-1].unsqueeze(0)\n\n output_dict = defaultdict(lambda: None)\n output_dict['hidden'] = output\n output_dict['coverage'] = coverage\n output_dict['context'] = context\n\n return output_dict\n\n def step_streaming(self, input, decoder_state):\n \"\"\"Step function in streaming case\"\"\"\n\n context = decoder_state.context\n lang = decoder_state.tgt_lang\n streaming_state = decoder_state.streaming_state\n\n # for global model: push the context in\n\n if decoder_state.concat_input_seq:\n if decoder_state.input_seq is None:\n decoder_state.input_seq = input\n else:\n # concatenate the last input to the previous input sequence\n decoder_state.input_seq = torch.cat([decoder_state.input_seq, input], 0)\n input = decoder_state.input_seq.transpose(0, 1) # B x T\n\n src = decoder_state.src.transpose(0, 1) if decoder_state.src is not None else None\n\n # use the last value of input to continue decoding\n if input.size(1) > 1:\n input_ = input[:, -1].unsqueeze(1).transpose(0, 1)\n else:\n input_ = input.transpose(0, 1)\n\n emb = self.word_lut(input_) * math.sqrt(self.model_size)\n input = input.transpose(0, 1) # B x T to T x B\n klen = input.size(0)\n\n # If we start a new sentence to decode: reset the context memory\n if klen == 1:\n streaming_state.reset_context_memory()\n\n if self.use_language_embedding:\n lang_emb = self.language_embeddings(lang) # B x H or 1 x H\n if self.language_embedding_type == 'sum':\n emb = emb + lang_emb\n elif self.language_embedding_type == 'concat':\n # replace the bos embedding with the language\n bos_emb = lang_emb.expand_as(emb[0])\n emb[0] = bos_emb\n\n lang_emb = lang_emb.unsqueeze(0).expand_as(emb)\n concat_emb = torch.cat([emb, lang_emb], dim=-1)\n emb = torch.relu(self.projector(concat_emb))\n else:\n raise NotImplementedError\n\n # need to manually definte src_lengths and tgt_lengths here\n src_lengths = torch.LongTensor([context.size(0)])\n tgt_lengths = torch.LongTensor([1])\n\n if context is not None:\n context_attn_mask = self.create_context_mask(input, src, src_lengths, tgt_lengths)\n context_attn_mask = context_attn_mask.unsqueeze(0)\n else:\n context_attn_mask = None\n\n dec_attn_mask = self.create_self_attn_mask(input, tgt_lengths, streaming_state.prev_tgt_mem_size)\n\n dec_attn_mask = dec_attn_mask[:, -1:, :]\n\n klen = 1 + streaming_state.prev_tgt_mem_size\n pos = torch.arange(klen - 1, -1, -1.0, device=emb.device, dtype=emb.dtype)\n\n pos_emb = self.positional_encoder(pos)\n\n output = emb\n\n for i, layer in enumerate(self.layer_modules):\n # T x B x d_model\n buffer = streaming_state.tgt_buffer[i]\n # output, coverage = layer(output, context, pos_emb, self.r_w_bias, self.r_r_bias, dec_attn_mask, mask_src)\n # reuse_source = True if input.size(1) == 1 else False\n reuse_source = True\n\n # reuse source is True in this case because we can reuse the context ...\n output, coverage, buffer = layer(output, context, pos_emb, dec_attn_mask, context_attn_mask,\n incremental=True, incremental_cache=buffer, reuse_source=reuse_source)\n streaming_state.tgt_buffer[i] = buffer\n\n output = self.postprocess_layer(output)\n\n streaming_state.prev_tgt_mem_size += 1\n streaming_state.prune_target_memory(self.max_memory_size)\n\n extra_context = context[-self.extra_context_size:].detach()\n\n output_dict = defaultdict(lambda: None, {'hidden': output, 'coverage': coverage, 'context': context})\n output_dict['streaming_state'] = streaming_state\n\n return output_dict\n\n\nclass RelativeTransformer(Transformer):\n\n def create_decoder_state(self, batch, beam_size=1, type=1, streaming=False, previous_decoding_state=None,\n **kwargs):\n \"\"\"\n Generate a new decoder state based on the batch input\n :param previous_decoding_state:\n :param streaming:\n :param type:\n :param batch: Batch object (may not contain target during decoding)\n :param beam_size: Size of beam used in beam search\n :return:\n \"\"\"\n\n # in this case batch size should be 1\n src = batch.get('source')\n src_pos = batch.get('source_pos')\n src_lang = batch.get('source_lang')\n tgt_lang = batch.get('target_lang')\n src_lengths = batch.src_lengths\n\n src_transposed = src.transpose(0, 1)\n\n if previous_decoding_state is None:\n\n # if the previous stream is None (the first segment in the stream)\n # then proceed normally like normal translation\n # init a new stream state\n # if streaming:\n streaming_state = self.init_stream() if streaming else None\n\n encoder_output = self.encoder(src_transposed, input_pos=src_pos,\n input_lang=src_lang, src_lengths=src_lengths,\n streaming=streaming, streaming_state=streaming_state)\n\n if streaming:\n decoder_state = StreamDecodingState(src, tgt_lang, encoder_output['context'],\n src_lang,\n beam_size=beam_size, model_size=self.model_size, type=type,\n cloning=True, streaming_state=streaming_state)\n else:\n decoder_state = TransformerDecodingState(src, tgt_lang, encoder_output['context'],\n src_lang,\n beam_size=beam_size, model_size=self.model_size, type=type)\n else:\n streaming_state = previous_decoding_state.streaming_state\n\n # to have the same batch/beam size with the previous memory ..\n src_transposed = src_transposed.repeat(beam_size, 1)\n src = src.repeat(1, beam_size)\n\n encoder_output = self.encoder(src_transposed, input_pos=src_pos,\n input_lang=src_lang, src_lengths=src_lengths,\n streaming=True, streaming_state=streaming_state)\n\n context = encoder_output['context']\n\n if self.decoder.extra_context_size > 0:\n # print(\"Using extra context with extra %d states\" % self.decoder.extra_context_size)\n # print(\"\")\n prev_context = previous_decoding_state.context\n extra_context = prev_context[-self.decoder.extra_context_size:].detach()\n context = torch.cat([extra_context, context], dim=0)\n\n prev_src = previous_decoding_state.src[-self.decoder.extra_context_size:].detach()\n src = torch.cat([prev_src, src], dim=0)\n\n decoder_state = StreamDecodingState(src, tgt_lang, context,\n encoder_output['src_mask'],\n beam_size=beam_size, model_size=self.model_size, type=type,\n cloning=False, streaming_state=streaming_state)\n\n return decoder_state\n\n def init_stream(self):\n\n param = next(self.parameters())\n layers = self.decoder.layers\n streaming_state = StreamState(layers, self.decoder.max_memory_size, param.device, param.dtype)\n return streaming_state\n\n def step(self, input_t, decoder_state, streaming=False):\n \"\"\"\n Decoding function:\n generate new decoder output based on the current input and current decoder state\n the decoder state is updated in the process\n :param streaming:\n :param input_t: the input word index at time t\n :param decoder_state: object DecoderState containing the buffers required for decoding\n :return: a dictionary containing: log-prob output and the attention coverage\n \"\"\"\n\n output_dict = self.decoder.step(input_t, decoder_state, streaming=streaming)\n output_dict['src'] = decoder_state.src.transpose(0, 1)\n\n log_prob = self.generator[0](output_dict)['logits'].squeeze(0)\n log_prob = F.log_softmax(log_prob.float(), dim=-1)\n\n coverage = output_dict['coverage']\n last_coverage = coverage[:, -1, :].squeeze(1)\n\n output_dict['log_prob'] = log_prob\n output_dict['coverage'] = last_coverage\n\n return output_dict\n\n def set_memory_size(self, src_memory_size, tgt_memory_size):\n\n self.encoder.max_memory_size = src_memory_size\n self.decoder.max_memory_size = tgt_memory_size\n\n\nclass StreamState(object):\n\n def __init__(self, nlayers, mem_len, device, dtype, training=True):\n # Currently I implement two types of stream states\n self.src_buffer = defaultdict(lambda: None)\n self.prev_src_mem_size = 0\n self.src_lengths = []\n self.tgt_buffer = defaultdict(lambda: None)\n self.prev_tgt_mem_size = 0\n self.tgt_lengths = []\n self.training = training\n self.mem_len = mem_len\n self.nlayers = nlayers\n\n if self.training:\n # initialize the memory\n self.src_mems = []\n self.tgt_mems = []\n\n for i in range(self.nlayers + 1):\n empty = torch.empty(0, dtype=dtype, device=device)\n self.src_mems.append(empty)\n empty = torch.empty(0, dtype=dtype, device=device)\n self.tgt_mems.append(empty)\n\n self.extra_context = None\n self.context_memory = None\n\n def prune_source_memory(self, mem_size):\n\n pruning = mem_size < self.prev_src_mem_size\n self.prev_src_mem_size = min(mem_size, self.prev_src_mem_size)\n\n if pruning:\n for i in self.src_buffer:\n if self.src_buffer[i] is not None:\n for key in self.src_buffer[i]:\n self.src_buffer[i][key] = self.src_buffer[i][key][-mem_size:]\n\n def prune_target_memory(self, mem_size):\n\n pruning = mem_size < self.prev_tgt_mem_size\n self.prev_tgt_mem_size = min(mem_size, self.prev_tgt_mem_size)\n\n if pruning:\n for i in self.tgt_buffer:\n if self.tgt_buffer[i] is not None:\n for key in self.tgt_buffer[i]:\n # Don't prune the buffer for enc-dec context, only prune the memory\n if key not in ['c_k', 'c_v']:\n self.tgt_buffer[i][key] = self.tgt_buffer[i][key][-mem_size:]\n\n def get_beam_buffer(self, beam_id):\n\n buffer = dict()\n\n for i in self.tgt_buffer:\n buffer[i] = dict()\n\n buffer[i]['v'] = self.tgt_buffer[i]['v'].index_select(1, beam_id) # the batch dim is 1\n buffer[i]['k'] = self.tgt_buffer[i]['k'].index_select(1, beam_id)\n\n return buffer\n\n def set_beam_buffer(self, sent_states):\n\n # assert(len(sent_states) == len(self.tgt_buffer))\n tensor = self.tgt_buffer[0]['v']\n hidden_size = tensor.size(-1)\n\n # first let's try with min_length\n beam_size = len(sent_states)\n min_length = min([sent_states[b]['hidden_buffer'][0]['k'].size(0) for b in range(beam_size)])\n\n mem_length = min_length\n for l in self.tgt_buffer:\n self.tgt_buffer[l]['v'] = tensor.new(mem_length, beam_size, hidden_size).zero_()\n self.tgt_buffer[l]['k'] = tensor.new(mem_length, beam_size, hidden_size).zero_()\n\n for b in range(beam_size):\n self.tgt_buffer[l]['v'][:, b, :].copy_(sent_states[b]['hidden_buffer'][l]['v'][-mem_length:, 0])\n self.tgt_buffer[l]['k'][:, b, :].copy_(sent_states[b]['hidden_buffer'][l]['k'][-mem_length:, 0])\n\n # When we start a sentence a new, the context key and value buffers need to be reset\n def reset_context_memory(self):\n for l in self.tgt_buffer:\n buffer_ = self.tgt_buffer[l]\n buffer_.pop('c_k', None)\n buffer_.pop('c_v', None)\n\n def reset_target_memory(self):\n for l in self.tgt_buffer:\n buffer_ = self.tgt_buffer[l]\n buffer_.pop('k', None)\n buffer_.pop('v', None)\n\n self.prev_tgt_mem_size = 0\n\n def update_src_mems(self, hids, qlen):\n # does not deal with None\n if self.src_mems is None:\n return None\n\n mlen = self.src_mems[0].size(0) if self.src_mems is not None else 0\n\n # mems is not None\n assert len(hids) == len(self.src_mems), 'len(hids) != len(mems)'\n # There are `mlen + qlen` steps that can be cached into mems\n # For the next step, the last `ext_len` of the `qlen` tokens\n # will be used as the extended context. Hence, we only cache\n # the tokens from `mlen + qlen - self.ext_len - self.mem_len`\n # to `mlen + qlen - self.ext_len`.\n with torch.no_grad():\n new_mems = []\n end_idx = mlen + qlen\n beg_idx = max(0, end_idx - self.mem_len)\n\n for i in range(len(hids)):\n cat = torch.cat([self.src_mems[i], hids[i]], dim=0)\n extra_mem = cat[beg_idx:end_idx].detach()\n new_mems.append(extra_mem)\n\n # Important:\n\n self.src_mems = new_mems\n\n def update_tgt_mems(self, hids, qlen):\n # does not deal with None\n if self.tgt_mems is None:\n return None\n\n mlen = self.tgt_mems[0].size(0) if self.tgt_mems is not None else 0\n\n # mems is not None\n assert len(hids) == len(self.tgt_mems), 'len(hids) != len(mems)'\n # There are `mlen + qlen` steps that can be cached into mems\n # For the next step, the last `ext_len` of the `qlen` tokens\n # will be used as the extended context. Hence, we only cache\n # the tokens from `mlen + qlen - self.ext_len - self.mem_len`\n # to `mlen + qlen - self.ext_len`.\n with torch.no_grad():\n new_mems = []\n end_idx = mlen + qlen\n beg_idx = max(0, end_idx - self.mem_len)\n for i in range(len(hids)):\n cat = torch.cat([self.tgt_mems[i], hids[i]], dim=0)\n new_mems.append(cat[beg_idx:end_idx].detach())\n\n # Important:\n\n self.tgt_mems = new_mems\n\n\nclass StreamDecodingState(DecoderState):\n\n # We need to somehow create the state w.r.t the previous states of the encoder and decoder\n def __init__(self, src, tgt_lang, context, src_mask, beam_size=1, model_size=512,\n cloning=True, streaming_state=None, **kwargs):\n\n self.beam_size = beam_size\n self.model_size = model_size\n self.src_mask = None\n # self.attention_buffers = dict()\n self.streaming_state = streaming_state\n\n bsz = src.size(1) # this value should be 1 for\n\n if cloning:\n new_order = torch.arange(bsz).view(-1, 1).repeat(1, self.beam_size).view(-1)\n new_order = new_order.to(src.device)\n\n if context is not None:\n self.context = context.index_select(1, new_order)\n else:\n self.context = None\n\n self.src = src.index_select(1, new_order) # because src is batch first\n else:\n self.context = context\n self.src = src\n\n self.concat_input_seq = False\n self.tgt_lang = tgt_lang\n self.origin = torch.arange(self.beam_size).to(src.device)\n # to know where each hypothesis comes from the previous beam\n\n def get_beam_buffer(self, beam_id):\n\n return self.streaming_state.get_beam_buffer(beam_id)\n\n def set_beam_buffer(self, sent_states):\n\n return self.streaming_state.set_beam_buffer(sent_states)\n\n def update_attention_buffer(self, buffer, layer):\n\n self.attention_buffers[layer] = buffer # dict of 2 keys (k, v) : T x B x H\n\n # For the new decoder version only\n def _reorder_incremental_state(self, reorder_state):\n\n if self.context is not None:\n self.context = self.context.index_select(1, reorder_state)\n\n if self.src_mask is not None:\n self.src_mask = self.src_mask.index_select(0, reorder_state)\n self.src = self.src.index_select(1, reorder_state)\n\n for l in self.streaming_state.src_buffer:\n buffer_ = self.streaming_state.src_buffer[l]\n if buffer_ is not None:\n for k in buffer_.keys():\n if buffer_[k] is not None:\n t_, br_, d_ = buffer_[k].size()\n buffer_[k] = buffer_[k].index_select(1, reorder_state) # 1 for time first\n\n for l in self.streaming_state.tgt_buffer:\n buffer_ = self.streaming_state.tgt_buffer[l]\n if buffer_ is not None:\n for k in buffer_.keys():\n if buffer_[k] is not None:\n t_, br_, d_ = buffer_[k].size()\n buffer_[k] = buffer_[k].index_select(1, reorder_state) # 1 for time first\n\n if self.streaming_state.src_mems is not None:\n for l in range(len(self.streaming_state.src_mems)):\n mems = self.streaming_state.src_mems[l]\n if mems.size(0) > 0:\n self.streaming_state.src_mems[l] = mems.index_select(1, reorder_state)\n\n if self.streaming_state.tgt_mems is not None:\n for l in range(len(self.streaming_state.tgt_mems)):\n mems = self.streaming_state.tgt_mems[l]\n if mems.size(0) > 0:\n self.streaming_state.tgt_mems[l] = mems.index_select(1, reorder_state)\n\n if self.streaming_state.context_memory is not None:\n self.streaming_state.context_memory = self.streaming_state.context_memory.index_select(1, reorder_state)\n\n self.origin = self.origin.index_select(0, reorder_state)\n\n def prune_complete_beam(self, active_idx, remaining_sents):\n pass\n\n def update_beam(self, beam, b, remaining_sents, idx):\n pass\n",
"# Copyright 2019 Thai-Son Nguyen\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n\nimport time\nimport math\nimport os\nimport copy\nimport random\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom pynn.util.decoder import Decoder\n\nfrom . import ScheduledOptim, EpochPool\nfrom . import load_last_chkpt, save_last_chkpt\n\ndef compute_ter(outputs, targets, target_sizes, average=True):\n refs = []\n targets = targets.numpy().tolist()\n for idx in range(len(target_sizes)):\n size = int(target_sizes[idx])\n refs.append(targets[idx][0:size])\n\n hypos = Decoder.decode(outputs)\n ter = 0.\n for i in range(len(refs)):\n ter += Decoder.score(hypos[i], refs[i])[2]\n if average: ter /= len(refs)\n return ter\n \ndef train_epoch(criterion, model, data, opt, eps, device, batch_input, batch_update, n_print, grad_clip=40.):\n ''' Epoch operation in training phase'''\n model.train()\n \n total_loss = 0.; n_loss = 0\n total_acc = 0. ; n_acc = 0\n prints = n_print\n\n updates = 0\n n_seq = 0\n data.initialize()\n opt.zero_grad()\n while data.available():\n # prepare data\n batch = data.next(batch_input)\n seqs, tgs, last = batch[-3:]\n batch = batch[:-3]\n inputs, masks, targets = map(lambda x: x.to(device), batch)\n n_seq += seqs\n\n # forward\n outputs, masks = model(inputs, masks)\n # backward\n input_sizes = masks.sum(-1)\n target_sizes = targets.gt(0).sum(-1)\n pred = F.log_softmax(outputs.transpose(0, 1), dim=-1) # seq x batch x dim\n loss = criterion(pred, targets, input_sizes, target_sizes)\n loss.backward()\n\n updates += tgs\n # update parameters\n if last or updates >= batch_update:\n if grad_clip > 0.:\n nn.utils.clip_grad_norm_(model.parameters(), grad_clip)\n opt.step_and_update_lr()\n opt.zero_grad()\n updates = 0\n\n # note keeping\n total_loss += loss.data\n n_loss += 1\n \n if n_seq > prints:\n outputs, targets = outputs.cpu(), targets.cpu()\n acc = 1 - compute_ter(outputs, targets, target_sizes)\n print(' Seq: {:6d}, lr: {:.7f}, loss: {:9.4f}, '\\\n 'updates: {:6d}, correct: {:.2f}'.format(n_seq, opt.lr, loss.data, opt.steps, acc))\n total_acc += acc; n_acc += 1\n prints += n_print\n \n total_loss = total_loss / n_loss\n total_acc = total_acc / n_acc\n return total_loss, total_acc\n\ndef eval_epoch(criterion, model, data, device, batch_input):\n ''' Epoch operation in evaluation phase '''\n\n model.eval()\n\n total_loss = 0.; n_loss = 0\n total_acc = 0. ; n_acc = 0\n \n with torch.no_grad():\n data.initialize()\n while data.available():\n # prepare data\n batch = data.next(batch_input)\n batch = batch[:-3]\n inputs, masks, targets = map(lambda x: x.to(device), batch)\n \n # forward\n outputs, masks = model(inputs, masks)\n # backward\n input_sizes = masks.sum(-1)\n target_sizes = targets.gt(0).sum(-1)\n pred = F.log_softmax(outputs.transpose(0, 1), dim=-1)\n loss = criterion(pred, targets, input_sizes, target_sizes)\n\n total_loss += loss.data\n n_loss += 1\n\n outputs, targets = outputs.cpu(), targets.cpu()\n acc = 1 - compute_ter(outputs, targets, target_sizes)\n total_acc += acc; n_acc += 1\n\n total_loss = total_loss / n_loss\n total_acc = total_acc / n_acc\n return total_loss, total_acc\n \ndef train_model(model, datasets, epochs, device, cfg):\n ''' Start training '''\n\n model_path = cfg['model_path']\n lr = cfg['lr']\n eps = cfg['smooth']\n\n n_warmup = cfg['n_warmup']\n n_print = cfg['n_print'] \n b_input = cfg['b_input']\n b_update = cfg['b_update']\n \n opt = ScheduledOptim(\n optim.Adam(\n filter(lambda x: x.requires_grad, model.parameters()),\n betas=(0.9, 0.98), eps=1e-09), 512, n_warmup, 0, lr)\n\n criterion = nn.CTCLoss(reduction='sum')\n\n tr_data, cv_dat = datasets\n pool = EpochPool(5)\n epoch_i, _ = load_last_chkpt(model_path, model, opt)\n \n while epoch_i < epochs:\n epoch_i += 1\n print('[ Epoch', epoch_i, ']')\n \n start = time.time()\n tr_loss, tr_accu = train_epoch(criterion, model, tr_data, opt, eps, device, b_input, b_update, n_print)\n \n print(' (Training) loss: {loss: 8.5f}, accuracy: {accu:3.3f} %, '\\\n 'elapse: {elapse:3.3f} min'.format(loss=tr_loss, accu=100*tr_accu, elapse=(time.time()-start)/60))\n\n start = time.time()\n cv_loss, cv_accu = eval_epoch(criterion, model, cv_dat, device, b_input)\n print(' (Validation) loss: {loss: 8.5f}, accuracy: {accu:3.3f} %, '\\\n 'elapse: {elapse:3.3f} min'.format(loss=cv_loss, accu=100*cv_accu, elapse=(time.time()-start)/60))\n\n if math.isnan(cv_loss): break\n model_file = model_path + '/epoch-{}.pt'.format(epoch_i)\n pool.save(cv_loss, model_file, model)\n save_last_chkpt(model_path, epoch_i, model, opt)\n",
"# Copyright 2019 Thai-Son Nguyen\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n\nimport time\nimport math\nimport os\nimport copy\nimport random\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom . import EpochPool, load_last_chkpt, save_last_chkpt\nfrom . import ScheduledOptim, cal_ce_loss\n\ndef time_constraint_loss(attn, mask, sid, eid):\n T = attn.size(-1) \n rg = torch.arange(T, device=mask.device).view(1, 1, 1, -1)\n rg = rg.expand(attn.size(0), attn.size(1), attn.size(2), -1)\n\n sid = sid.unsqueeze(1).unsqueeze(-1).expand(-1, -1, -1, T) \n sid = sid.gt(rg)\n\n eid = eid.unsqueeze(1).unsqueeze(-1).expand(-1, -1, -1, T)\n eid = eid.le(rg)\n \n mask = mask.unsqueeze(1).unsqueeze(2)\n mask = mask.expand(-1, attn.size(1), attn.size(2), -1)\n #tid = (sid + eid + mask).gt(1)\n tid = (eid + mask).gt(1) # fwd\n #tid = (sid + mask).gt(1) # bwd\n\n attn = attn.masked_select(tid)\n #loss = torch.log(attn+0.1).sum() / tid.size(1)\n #loss = torch.log(attn+0.1).sum() / (tid.size(1)*tid.size(-1))\n #loss = attn.sum() / (tid.size(1)*tid.size(-1))\n loss = attn.sum()\n\n return loss\n\ndef train_epoch(model, data, opt, eps, device, batch_input, batch_update, n_print,\n loss_norm=False, grad_norm=True, grad_clip=0.):\n ''' Epoch operation in training phase'''\n model.train()\n \n total_loss = 0.; n_word_total = 0; n_word_correct = 0\n prints = n_print\n p_loss = 0.; p_total = 0; p_correct = 0;\n a_loss = 0.\n\n updates = 0\n n_seq = 0\n\n data.initialize()\n opt.zero_grad()\n while data.available():\n # prepare data\n batch = data.next(batch_input)\n seqs, last = batch[-2:]\n src_seq, src_mask, tgt_seq, sid, eid = map(lambda x: x.to(device), batch[:-2])\n\n gold = tgt_seq[:, 1:]\n tgt_seq = tgt_seq[:, :-1]\n n_seq += seqs\n\n try:\n # forward\n pred, attn, masks = model.attend(src_seq, src_mask, tgt_seq)\n # backward\n pred = pred.view(-1, pred.size(2))\n loss, loss_data, n_correct, n_total = cal_ce_loss(pred, gold, eps)\n attn_loss = time_constraint_loss(attn, masks, sid, eid)\n\n loss += attn_loss*0.2\n if torch.isnan(loss.data):\n print(\" inf loss at %d\" % n_seq); continue\n if loss_norm: loss = loss.div(n_total)\n opt.backward(loss)\n except RuntimeError as err:\n if 'CUDA out of memory' in str(err):\n print(' WARNING: ran out of memory on GPU at %d' % n_seq)\n torch.cuda.empty_cache(); continue\n raise err\n\n updates += n_total\n # update parameters\n if last or updates >= batch_update:\n if grad_clip > 0.:\n nn.utils.clip_grad_norm_(model.parameters(), grad_clip)\n g_norm = updates if grad_norm else 1.\n opt.step_and_update_lr(updates)\n opt.zero_grad()\n updates = 0\n\n # note keeping\n total_loss += loss_data\n\n n_word_total += n_total; n_word_correct += n_correct\n p_loss += loss_data; p_total += n_total; p_correct += n_correct;\n a_loss += attn_loss.data.item()\n \n if n_seq > prints:\n ppl = math.exp(min(p_loss/p_total, 100))\n pred = p_correct * 1. / p_total\n a_loss /= p_total\n print(' Seq: {:6d}, lr: {:.7f}, ppl: {:9.4f}, attn-loss: {:.3f}, '\\\n 'updates: {:6d}, correct: {:.2f}'.format(n_seq, opt.lr, ppl, a_loss, opt.steps, pred))\n prints += n_print\n p_loss = 0.; p_total = 0; p_correct = 0\n a_loss = 0.\n \n loss_per_word = total_loss / n_word_total\n accuracy = n_word_correct / n_word_total\n return loss_per_word, accuracy\n\ndef eval_epoch(model, data, device, batch_input):\n ''' Epoch operation in evaluation phase '''\n\n model.eval()\n\n total_loss = 0\n n_word_total = 0\n n_word_correct = 0\n \n with torch.no_grad():\n data.initialize()\n while data.available():\n # prepare data\n batch = data.next(batch_input)\n src_seq, src_mask, tgt_seq = map(lambda x: x.to(device), batch[:-4])\n gold = tgt_seq[:, 1:]\n tgt_seq = tgt_seq[:, :-1]\n\n # forward\n pred = model(src_seq, src_mask, tgt_seq)[0]\n loss, loss_data, n_correct, n_total = cal_ce_loss(pred, gold)\n\n # note keeping\n total_loss += loss_data\n\n n_word_total += n_total\n n_word_correct += n_correct\n\n loss_per_word = total_loss / n_word_total\n accuracy = n_word_correct / n_word_total\n return loss_per_word, accuracy\n \ndef train_model(model, datasets, epochs, device, cfg,\n loss_norm=False, grad_norm=True, fp16=False):\n ''' Start training '''\n\n model_path = cfg['model_path']\n lr = cfg['lr']\n eps = cfg['smooth']\n\n n_warmup = cfg['n_warmup']\n n_const = cfg['n_const']\n n_print = cfg['n_print'] \n b_input = cfg['b_input']\n b_update = cfg['b_update']\n \n opt = ScheduledOptim(512, n_warmup, n_const, lr)\n model = opt.initialize(model, fp16=fp16)\n\n tr_data, cv_dat = datasets\n pool = EpochPool(5)\n epoch_i, _ = load_last_chkpt(model_path, model, opt)\n \n while epoch_i < epochs:\n epoch_i += 1\n print('[ Epoch', epoch_i, ']')\n \n start = time.time()\n tr_loss, tr_accu = train_epoch(model, tr_data, opt, eps, device, b_input, b_update, n_print,\n loss_norm=loss_norm, grad_norm=grad_norm)\n \n print(' (Training) ppl: {ppl: 8.5f}, accuracy: {accu:3.3f} %, '\\\n 'elapse: {elapse:3.3f} min'.format(\n ppl=math.exp(min(tr_loss, 100)), accu=100*tr_accu,\n elapse=(time.time()-start)/60))\n\n start = time.time()\n cv_loss, cv_accu = eval_epoch(model, cv_dat, device, b_input)\n print(' (Validation) ppl: {ppl: 8.5f}, accuracy: {accu:3.3f} %, '\\\n 'elapse: {elapse:3.3f} min'.format(\n ppl=math.exp(min(cv_loss, 100)), accu=100*cv_accu,\n elapse=(time.time()-start)/60))\n\n if math.isnan(cv_loss): break\n model_file = model_path + '/epoch-{}.pt'.format(epoch_i)\n pool.save(cv_loss, model_file, model)\n save_last_chkpt(model_path, epoch_i, model, opt)\n"
] | [
[
"torch.LongTensor",
"torch.empty",
"torch.Tensor",
"torch.cat",
"torch.set_printoptions",
"torch.nn.ModuleList",
"torch.no_grad",
"torch.arange"
],
[
"torch.no_grad",
"torch.nn.CTCLoss"
],
[
"torch.no_grad",
"torch.cuda.empty_cache",
"torch.isnan",
"torch.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
noppakorn/ddc-dashboard-scraping | [
"80fd2df7beea4b5d48c051f07d78f0e1aaf03ef6"
] | [
"src/get_dashboard_link.py"
] | [
"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport os\nimport time\nimport json\nimport pandas as pd\nimport sys\n\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_argument(\"--headless\")\nchrome_options.add_argument(\"--no-sandbox\")\nchrome_options.add_argument(\"--disable-dev-shm-usage\")\nchrome_options.add_argument(\"--window-size=1920,5000\")\n\n\ndef get_date_share_link(wd: webdriver.Chrome, date: str) -> str:\n wd.switch_to.default_content()\n print(\"Changing Date to:\", date)\n wd.find_element_by_id(\"dpick\").send_keys(date)\n frame = wd.find_element(By.XPATH, \"//div[@id='tableauPlaceholder']/iframe\")\n wd.switch_to.frame(frame)\n # Wait till loading finished\n time.sleep(15)\n share_button = wd.find_element(By.XPATH, \"//div[@id='share-ToolbarButton']\").click()\n share_link = wd.find_elements(By.XPATH, \"//input[@class='tabTextInputViewInputElement tab-shareInput']\")\n out = share_link[1].get_attribute(\"value\")\n # Close share window\n wd.find_element(By.XPATH, \"//button[@class='f1odzkbq fyvorft fdxv97z low-density']\").click()\n return out\n\n\nif __name__ == '__main__':\n wd = webdriver.Chrome(\"chromedriver\", options=chrome_options)\n wd.get(\"https://ddc.moph.go.th/covid19-dashboard/\")\n time.sleep(5)\n start, end = sys.argv[1], sys.argv[2]\n share_link_dict = {}\n for dto in pd.date_range(start, end):\n date_to_scrape = f\"{str(dto.month).zfill(2)}/{str(dto.day).zfill(2)}/{dto.year}\"\n share_link = get_date_share_link(wd, date_to_scrape)\n share_link_dict[date_to_scrape] = share_link\n print(date_to_scrape, \":\", share_link)\n wd.close()\n out_path = \"../dashboard_links\"\n os.makedirs(out_path, exist_ok=True)\n with open(os.path.join(out_path, f\"covid-dashboard-link-{start}-{end}.json\"), \"w+\", encoding=\"utf-8\") as fout:\n json.dump(share_link_dict, fout, ensure_ascii=False, indent=2)\n"
] | [
[
"pandas.date_range"
]
] | [
{
"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": []
}
] |
christinahedges/exoplanet | [
"55d2252c71191044613fabb9c8bd3062aca3bc1b"
] | [
"src/exoplanet/distributions/eccentricity.py"
] | [
"# -*- coding: utf-8 -*-\n\n__all__ = [\"kipping13\", \"vaneylen19\"]\n\nimport numpy as np\nimport pymc3 as pm\nimport theano.tensor as tt\n\nfrom ..citations import add_citations_to_model\nfrom .base import UnitUniform\n\n\ndef kipping13(\n name, fixed=False, long=None, lower=None, upper=None, model=None, **kwargs\n):\n \"\"\"The beta eccentricity distribution fit by Kipping (2013)\n\n The beta distribution parameters fit by `Kipping (2013b)\n <https://arxiv.org/abs/1306.4982>`_.\n\n Args:\n name (str): The name of the eccentricity variable.\n fixed (bool, optional): If ``True``, use the posterior median\n hyperparameters. Otherwise, marginalize over the parameters.\n long (bool, optional): If ``True``, use the parameters for the long\n period fit. If ``False``, use the parameters for the short period\n fit. If not given, the parameters fit using the full dataset are\n used.\n lower (float, optional): Restrict the eccentricity to be larger than\n this value.\n upper (float, optional): Restrict the eccentricity to be smaller than\n this value.\n\n Returns:\n The eccentricity distribution.\n\n \"\"\"\n model = pm.modelcontext(model)\n add_citations_to_model([\"kipping13b\"], model=model)\n\n if long is None:\n # If 'long' is not provided, use the fit for the parameters from the\n # full dataset\n alpha_mu = 1.12\n alpha_sd = 0.1\n beta_mu = 3.09\n beta_sd = 0.3\n else:\n # If 'long' is set, select either the long or short period model\n # parameters\n if long:\n alpha_mu = 1.12\n alpha_sd = 0.1\n beta_mu = 3.09\n beta_sd = 0.3\n else:\n alpha_mu = 0.697\n alpha_sd = 0.4\n beta_mu = 3.27\n beta_sd = 0.3\n\n with model:\n if fixed:\n # Use the posterior median parameters\n alpha = alpha_mu\n beta = beta_mu\n else:\n # Marginalize over the uncertainty on the parameters of the beta\n with pm.Model(name=name):\n bounded_normal = pm.Bound(pm.Normal, lower=0)\n alpha = bounded_normal(\n \"alpha\", mu=alpha_mu, sd=alpha_sd, testval=alpha_mu\n )\n beta = bounded_normal(\n \"beta\", mu=beta_mu, sd=beta_sd, testval=beta_mu\n )\n\n # Allow for upper and lower bounds\n if lower is not None or upper is not None:\n dist = pm.Bound(\n pm.Beta,\n lower=0.0 if lower is None else lower,\n upper=1.0 if upper is None else upper,\n )\n return dist(name, alpha=alpha, beta=beta, **kwargs)\n\n return pm.Beta(name, alpha=alpha, beta=beta, **kwargs)\n\n\ndef vaneylen19(\n name,\n fixed=False,\n multi=False,\n lower=None,\n upper=None,\n model=None,\n **kwargs,\n):\n \"\"\"The eccentricity distribution for small planets\n\n The mixture distribution fit by `Van Eylen et al. (2019)\n <https://arxiv.org/abs/1807.00549>`_ to a population of well-characterized\n small transiting planets observed by Kepler.\n\n Args:\n name (str): The name of the eccentricity variable.\n fixed (bool, optional): If ``True``, use the posterior median\n hyperparameters. Otherwise, marginalize over the parameters.\n multi (bool, optional): If ``True``, use the distribution for systems\n with multiple transiting planets. If ``False`` (default), use the\n distribution for systems with only one detected transiting planet.\n lower (float, optional): Restrict the eccentricity to be larger than\n this value.\n upper (float, optional): Restrict the eccentricity to be smaller than\n this value.\n\n Returns:\n The eccentricity distribution.\n\n \"\"\"\n\n model = pm.modelcontext(model)\n add_citations_to_model([\"vaneylen19\"], model=model)\n\n sigma_gauss_mu = 0.049\n sigma_gauss_sd = 0.02\n sigma_rayleigh_mu = 0.26\n sigma_rayleigh_sd = 0.05\n if multi:\n frac_mu = 0.08\n frac_sd = 0.08\n else:\n frac_mu = 0.76\n frac_sd = 0.2\n\n with model:\n if lower is None and upper is None:\n ecc = UnitUniform(name, **kwargs)\n else:\n ecc = pm.Uniform(\n name,\n lower=0.0 if lower is None else lower,\n upper=1.0 if upper is None else upper,\n **kwargs,\n )\n\n with pm.Model(name=name):\n\n if fixed:\n sigma_gauss = sigma_gauss_mu\n sigma_rayleigh = sigma_rayleigh_mu\n frac = frac_mu\n else:\n\n bounded_normal = pm.Bound(pm.Normal, lower=0)\n sigma_gauss = bounded_normal(\n \"sigma_gauss\",\n mu=sigma_gauss_mu,\n sd=sigma_gauss_sd,\n testval=sigma_gauss_mu,\n )\n sigma_rayleigh = bounded_normal(\n \"sigma_rayleigh\",\n mu=sigma_rayleigh_mu,\n sd=sigma_rayleigh_sd,\n testval=sigma_rayleigh_mu,\n )\n frac = pm.Bound(pm.Normal, lower=0, upper=1)(\n \"frac\", mu=frac_mu, sd=frac_sd, testval=frac_mu\n )\n\n gauss = pm.HalfNormal.dist(sigma=sigma_gauss)\n rayleigh = pm.Weibull.dist(\n alpha=2, beta=np.sqrt(2) * sigma_rayleigh\n )\n\n pm.Potential(\n \"prior\",\n pm.math.logaddexp(\n tt.log(1 - frac) + gauss.logp(ecc),\n tt.log(frac) + rayleigh.logp(ecc),\n ),\n )\n\n return ecc\n"
] | [
[
"numpy.sqrt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Z223I/deephyper | [
"4fd1054dc22f15197567bdd93c6e7a95a614b8e2",
"4fd1054dc22f15197567bdd93c6e7a95a614b8e2",
"4fd1054dc22f15197567bdd93c6e7a95a614b8e2"
] | [
"deephyper/nas/space/op/op1d.py",
"tests/deephyper/nas/space/keras_architecture.py",
"deephyper/benchmark/datasets/dionis.py"
] | [
"import tensorflow as tf\nfrom tensorflow import keras\n\nfrom . import Operation\n\n\nclass Dense(Operation):\n \"\"\"Multi Layer Perceptron operation.\n\n Help you to create a perceptron with n layers, m units per layer and an activation function.\n\n Args:\n units (int): number of units per layer.\n activation: an activation function from tensorflow.\n \"\"\"\n\n def __init__(self, units, activation=None, *args, **kwargs):\n # Layer args\n self.units = units\n self.activation = activation\n self.kwargs = kwargs\n\n # Reuse arg\n self._layer = None\n self._activation = None\n\n def __str__(self):\n if isinstance(self.activation, str):\n return f\"Dense_{self.units}_{self.activation}\"\n elif self.activation is None:\n return f\"Dense_{self.units}\"\n else:\n return f\"Dense_{self.units}_{self.activation.__name__}\"\n\n def __call__(self, inputs, seed=None, **kwargs):\n assert (\n len(inputs) == 1\n ), f\"{type(self).__name__} as {len(inputs)} inputs when 1 is required.\"\n if self._layer is None: # reuse mechanism\n self._layer = keras.layers.Dense(\n units=self.units,\n kernel_initializer=tf.keras.initializers.glorot_uniform(seed=seed),\n **self.kwargs,\n )\n\n out = self._layer(inputs[0])\n\n if self.activation is not None: # better for visualisation\n if self._activation is None:\n self._activation = keras.layers.Activation(activation=self.activation)\n\n out = self._activation(out)\n return out\n\n\nclass Dropout(Operation):\n \"\"\"Dropout operation.\n\n Help you to create a dropout operation.\n\n Args:\n rate (float): rate of deactivated inputs.\n \"\"\"\n\n def __init__(self, rate):\n self.rate = rate\n super().__init__(layer=keras.layers.Dropout(rate=self.rate))\n\n def __str__(self):\n return f\"Dropout({self.rate})\"\n\n\nclass Identity(Operation):\n def __init__(self):\n pass\n\n def __call__(self, inputs, **kwargs):\n assert (\n len(inputs) == 1\n ), f\"{type(self).__name__} as {len(inputs)} inputs when 1 is required.\"\n return inputs[0]\n\n\nclass Conv1D(Operation):\n \"\"\"Convolution for one dimension.\n\n Help you to create a one dimension convolution operation.\n\n Args:\n filter_size (int): size kernels/filters\n num_filters (int): number of kernels/filters\n strides (int):\n padding (str): 'same' or 'valid'\n \"\"\"\n\n def __init__(self, filter_size, num_filters=1, strides=1, padding=\"same\"):\n self.filter_size = filter_size\n self.num_filters = num_filters\n self.strides = strides\n self.padding = padding\n self._layer = None\n\n def __str__(self):\n return f\"{type(self).__name__}_{self.filter_size}_{self.num_filters}\"\n\n def __call__(self, inputs, **kwargs):\n assert (\n len(inputs) == 1\n ), f\"{type(self).__name__} as {len(inputs)} inputs when only 1 is required.\"\n inpt = inputs[0]\n if len(inpt.get_shape()) == 2:\n out = keras.layers.Reshape((inpt.get_shape()[1], 1))(inpt)\n else:\n out = inpt\n if self._layer is None: # reuse mechanism\n self._layer = keras.layers.Conv1D(\n filters=self.num_filters,\n kernel_size=self.filter_size,\n strides=self.strides,\n padding=self.padding,\n )\n out = self._layer(out)\n return out\n\n\nclass MaxPooling1D(Operation):\n \"\"\"MaxPooling over one dimension.\n\n Args:\n pool_size ([type]): [description]\n strides (int, optional): Defaults to 1. [description]\n padding (str, optional): Defaults to 'valid'. [description]\n data_format (str, optional): Defaults to 'channels_last'. [description]\n \"\"\"\n\n def __init__(\n self, pool_size, strides=1, padding=\"valid\", data_format=\"channels_last\"\n ):\n self.pool_size = pool_size\n self.strides = strides\n self.padding = padding\n self.data_format = data_format\n\n def __str__(self):\n return f\"{type(self).__name__}_{self.pool_size}_{self.padding}\"\n\n def __call__(self, inputs, **kwargs):\n assert (\n len(inputs) == 1\n ), f\"{type(self).__name__} as {len(inputs)} inputs when only 1 is required.\"\n inpt = inputs[0]\n if len(inpt.get_shape()) == 2:\n out = keras.layers.Reshape((inpt.get_shape()[1], 1))(inpt)\n else:\n out = inpt\n out = keras.layers.MaxPooling1D(\n pool_size=self.pool_size,\n strides=self.strides,\n padding=self.padding,\n data_format=self.data_format,\n )(out)\n return out\n\n\nclass Flatten(Operation):\n \"\"\"Flatten operation.\n\n Args:\n data_format (str, optional): Defaults to None.\n \"\"\"\n\n def __init__(self, data_format=None):\n self.data_format = data_format\n\n def __call__(self, inputs, **kwargs):\n assert (\n len(inputs) == 1\n ), f\"{type(self).__name__} as {len(inputs)} inputs when only 1 is required.\"\n inpt = inputs[0]\n if len(inpt.get_shape()) == 2:\n out = inpt\n else:\n out = keras.layers.Flatten(data_format=self.data_format)(inpt)\n return out\n\n\nclass Activation(Operation):\n \"\"\"Activation function operation.\n\n Args:\n activation (callable): an activation function\n \"\"\"\n\n def __init__(self, activation=None, *args, **kwargs):\n self.activation = activation\n self._layer = None\n\n def __str__(self):\n return f\"{type(self).__name__}_{self.activation}\"\n\n def __call__(self, inputs, *args, **kwargs):\n inpt = inputs[0]\n if self._layer is None:\n self._layer = keras.layers.Activation(activation=self.activation)\n out = self._layer(inpt)\n return out\n\n\nclass BatchNormalization(Operation):\n def __init__(self, *args, activation=None, **kwargs):\n self.args = args\n self.activation = None\n self.kwargs = kwargs\n\n self._bn = None\n self._activation = None\n\n def __str__(self):\n return f\"{type(self).__name__}\"\n\n def __call__(self, inputs, *args, **kwargs):\n inpt = inputs[0]\n\n if self._bn is None:\n self._bn = keras.layers.BatchNormalization(*self.args, **self.kwargs)\n if not(self.activation is None):\n self._activation = keras.layers.Activation(self.activation)\n\n out = self._bn (inpt)\n if not(self._activation is None):\n out = self._activation(out)\n\n return out\n",
"import pytest\nfrom deephyper.core.exceptions.nas.space import WrongOutputShape\n\n\[email protected]\nclass TestKSearchSpace:\n def test_import(self):\n from deephyper.nas.space import KSearchSpace\n\n def test_create(self):\n from deephyper.nas.space import KSearchSpace\n\n KSearchSpace((5,), (1,))\n\n def test_create_one_vnode(self):\n from deephyper.nas.space import KSearchSpace\n\n struct = KSearchSpace((5,), (1,))\n\n from deephyper.nas.space.node import VariableNode\n\n vnode = VariableNode()\n\n struct.connect(struct.input_nodes[0], vnode)\n\n from deephyper.nas.space.op.op1d import Dense\n\n vnode.add_op(Dense(1))\n\n struct.set_ops([0])\n\n falias = \"test_keras_search_spaceure\"\n struct.draw_graphviz(f\"{falias}.dot\")\n\n model = struct.create_model()\n from tensorflow.keras.utils import plot_model\n\n plot_model(model, to_file=f\"{falias}.png\", show_shapes=True)\n\n def test_create_one_vnode_with_wrong_output_shape(self):\n from deephyper.nas.space import KSearchSpace\n\n struct = KSearchSpace((5,), (1,))\n\n from deephyper.nas.space.node import VariableNode\n\n vnode = VariableNode()\n\n struct.connect(struct.input_nodes[0], vnode)\n\n from deephyper.nas.space.op.op1d import Dense\n\n vnode.add_op(Dense(10))\n\n struct.set_ops([0])\n\n with pytest.raises(WrongOutputShape):\n struct.create_model()\n\n def test_create_more_nodes(self):\n from deephyper.nas.space import KSearchSpace\n from deephyper.nas.space.node import VariableNode\n from deephyper.nas.space.op.op1d import Dense\n\n struct = KSearchSpace((5,), (1,))\n\n vnode1 = VariableNode()\n struct.connect(struct.input_nodes[0], vnode1)\n\n vnode1.add_op(Dense(10))\n\n vnode2 = VariableNode()\n vnode2.add_op(Dense(1))\n\n struct.connect(vnode1, vnode2)\n\n struct.set_ops([0, 0])\n\n falias = \"test_keras_search_spaceure\"\n struct.draw_graphviz(f\"{falias}.dot\")\n\n model = struct.create_model()\n from tensorflow.keras.utils import plot_model\n\n plot_model(model, to_file=f\"{falias}.png\", show_shapes=True)\n\n def test_create_multiple_inputs_with_one_vnode(self):\n from deephyper.nas.space import KSearchSpace\n from deephyper.nas.space.node import VariableNode, ConstantNode\n from deephyper.nas.space.op.op1d import Dense\n from deephyper.nas.space.op.merge import Concatenate\n\n struct = KSearchSpace([(5,), (5,)], (1,))\n\n merge = ConstantNode()\n merge.set_op(Concatenate(struct, struct.input_nodes))\n\n vnode1 = VariableNode()\n struct.connect(merge, vnode1)\n\n vnode1.add_op(Dense(1))\n\n struct.set_ops([0])\n\n struct.create_model()\n\n def test_create_multiple_inputs_with_wrong_output_shape(self):\n from deephyper.nas.space import KSearchSpace\n from deephyper.nas.space.node import VariableNode\n from deephyper.nas.space.op.op1d import Dense\n\n struct = KSearchSpace([(5,), (5,)], (1,))\n\n struct.set_ops([])\n\n with pytest.raises(WrongOutputShape):\n struct.create_model()\n",
"import numpy as np\nimport openml\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn import model_selection\n\n\ndef load_data(\n random_state=42,\n verbose=False,\n test_size=0.33,\n valid_size=0.33,\n categoricals_to_integers=False,\n):\n \"\"\"Load the \"Dionis\" dataset from OpenML.\n\n Args:\n random_state (int, optional): A numpy `RandomState`. Defaults to 42.\n verbose (bool, optional): Print informations about the dataset. Defaults to False.\n test_size (float, optional): The proportion of the test dataset out of the whole data. Defaults to 0.33.\n valid_size (float, optional): The proportion of the train dataset out of the whole data without the test data. Defaults to 0.33.\n categoricals_to_integers (bool, optional): Convert categoricals features to integer values. Defaults to False.\n\n Returns:\n tuple: Numpy arrays as, `(X_train, y_train), (X_valid, y_valid), (X_test, y_test)`.\n \"\"\"\n random_state = (\n np.random.RandomState(random_state) if type(random_state) is int else random_state\n )\n\n dataset = openml.datasets.get_dataset(41167)\n\n if verbose:\n print(\n f\"This is dataset '{dataset.name}', the target feature is \"\n f\"'{dataset.default_target_attribute}'\"\n )\n print(f\"URL: {dataset.url}\")\n print(dataset.description[:500])\n\n X, y, categorical_indicator, ft_names = dataset.get_data(\n target=dataset.default_target_attribute\n )\n\n # encode categoricals as integers\n if categoricals_to_integers:\n for (ft_ind, ft_name) in enumerate(ft_names):\n if categorical_indicator[ft_ind]:\n labenc = LabelEncoder().fit(X[ft_name])\n X[ft_name] = labenc.transform(X[ft_name])\n n_classes = len(labenc.classes_)\n else:\n n_classes = -1\n categorical_indicator[ft_ind] = (\n categorical_indicator[ft_ind],\n n_classes,\n )\n\n X, y = X.to_numpy(), y.to_numpy()\n\n X_train, X_test, y_train, y_test = model_selection.train_test_split(\n X, y, test_size=test_size, shuffle=True, random_state=random_state\n )\n\n # relative valid_size on Train set\n r_valid_size = valid_size / (1.0 - test_size)\n X_train, X_valid, y_train, y_valid = model_selection.train_test_split(\n X_train, y_train, test_size=r_valid_size, shuffle=True, random_state=random_state\n )\n\n return (X_train, y_train), (X_valid, y_valid), (X_test, y_test), categorical_indicator\n\n\ndef test_load_data_dionis():\n from deephyper.benchmark.datasets import dionis\n import numpy as np\n\n names = [\"train\", \"valid\", \"test \"]\n data = dionis.load_data(random_state=42, verbose=True, categoricals_to_integers=True)[:-1]\n for (X, y), subset_name in zip(data, names):\n print(\n f\"X_{subset_name} shape: \",\n np.shape(X),\n f\", y_{subset_name} shape: \",\n np.shape(y),\n )\n\n\nif __name__ == \"__main__\":\n test_load_data_dionis()\n"
] | [
[
"tensorflow.keras.layers.Activation",
"tensorflow.keras.layers.Conv1D",
"tensorflow.keras.layers.MaxPooling1D",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.initializers.glorot_uniform",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Flatten"
],
[
"tensorflow.keras.utils.plot_model"
],
[
"sklearn.preprocessing.LabelEncoder",
"numpy.random.RandomState",
"numpy.shape",
"sklearn.model_selection.train_test_split"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
modelearth/flowsa | [
"d4dcf5ef8764b4ef895080a54d0546668daf0e1a"
] | [
"scripts/write_NAICS_from_useeior.py"
] | [
"# write_NAICS_from_useeior.py (scripts)\n# !/usr/bin/env python3\n# coding=utf-8\n\n\"\"\"\n3 scripts:\n\nA script to get NAICS names and a NAICS 2-3-4-5-6 crosswalk.\n\n- from useeior amd store them as .csv.\n- Depends on rpy2 and tzlocal as well as having R installed and useeior installed.\n\nLoops through the source crosswalks to find any NAICS not in\nofficial Census NAICS Code list. Adds the additional NAICS\nto NAICS crosswalk.\n\n- Writes reshaped file to datapath as csv.\n\"\"\"\n\nimport glob\nimport pandas as pd\nimport numpy as np\nimport rpy2.robjects.packages as packages\nfrom rpy2.robjects import pandas2ri\nfrom flowsa.common import datapath, crosswalkpath\nfrom flowsa.flowbyfunctions import replace_NoneType_with_empty_cells\nfrom flowsa.dataclean import replace_strings_with_NoneType\n\n\ndef import_useeior_mastercrosswalk():\n \"\"\"\n Load USEEIOR's MasterCrosswalk that links BEA data to NAICS\n :return:\n \"\"\"\n pandas2ri.activate()\n # import the useeior package (r package)\n useeior = packages.importr('useeior')\n # load the .Rd file for\n cw = packages.data(useeior).fetch('MasterCrosswalk2012')['MasterCrosswalk2012']\n\n return cw\n\n\ndef write_naics_2012_crosswalk():\n \"\"\"\n Create a NAICS 2 - 6 digit crosswalk\n :return:\n \"\"\"\n\n # load the useeior mastercrosswalk\n cw_load = import_useeior_mastercrosswalk()\n\n # extract naics 2012 code column and drop duplicates and empty cells\n cw = cw_load[['NAICS_2012_Code']].drop_duplicates()\n cw = replace_NoneType_with_empty_cells(cw)\n cw = cw[cw['NAICS_2012_Code'] != '']\n\n # dictionary to replace housing and gov't transport sectors after subsetting by naics length\n dict_replacement = {'F0': 'F010',\n 'F01': 'F010',\n 'F0100': 'F01000',\n 'S0': 'S00201',\n 'S00': 'S00201',\n 'S002': 'S00201',\n 'S0020': 'S00201'\n }\n\n # define sectors that might need to be appended\n house_4 = ['F010']\n house_6 = ['F01000']\n govt = ['S00201']\n\n # create a list of crosswalk dfs at each length\n cw_list = []\n # extract naics by length\n for i in range(2, 7):\n cw_name = 'cw_' + str(i)\n cw_col = 'NAICS_' + str(i)\n cw_col_m1 = 'NAICS_' + str(i-1)\n vars()[cw_name] = cw[cw['NAICS_2012_Code'].apply(lambda x: len(x) == i)].\\\n reset_index(drop=True).rename(columns={'NAICS_2012_Code': cw_col})\n # address exceptions to naics length rule - housing and gov't sector transport\n vars()[cw_name][cw_col] = vars()[cw_name][cw_col].replace(dict_replacement)\n # add some housing/gov't transport sectors, depending on length\n if i in range(2, 4):\n vars()[cw_name] = vars()[cw_name].append(\n pd.DataFrame(house_4,columns=[cw_col]), ignore_index=True)\n if i == 5:\n vars()[cw_name] = vars()[cw_name].append(\n pd.DataFrame(house_6, columns=[cw_col]), ignore_index=True)\n if i in range(2, 6):\n vars()[cw_name] = vars()[cw_name].append(\n pd.DataFrame(govt, columns=[cw_col]), ignore_index=True)\n # add columns to dfs with naics length - 1\n if i in range(3, 7):\n vars()[cw_name][cw_col_m1] = vars()[cw_name][cw_col].apply(lambda x: x[0:i-1])\n # address exceptions to naics length rule - housing and gov't sector transport\n vars()[cw_name][cw_col_m1] = vars()[cw_name][cw_col_m1].replace(dict_replacement)\n cw_list.append(vars()[cw_name])\n\n # loop through the df list and merge\n naics_cw = cw_list[0]\n for df in cw_list[1:5]:\n naics_cw = naics_cw.merge(df, how='outer')\n\n # save as csv\n naics_cw.to_csv(datapath + \"NAICS_2012_Crosswalk.csv\", index=False)\n\n return None\n\n\ndef load_naics_02_to_07_crosswalk():\n \"\"\"\n Load the 2002 to 2007 crosswalk from US Census\n :return:\n \"\"\"\n naics_url = 'https://www.census.gov/eos/www/naics/concordances/2002_to_2007_NAICS.xls'\n df_load = pd.read_excel(naics_url)\n # drop first rows\n df = pd.DataFrame(df_load.loc[2:]).reset_index(drop=True)\n # Assign the column titles\n df.columns = df_load.loc[1, ]\n\n # df subset columns\n naics_02_to_07_cw = df[['2002 NAICS Code','2007 NAICS Code']].rename(\n columns={'2002 NAICS Code': 'NAICS_2002_Code', '2007 NAICS Code': 'NAICS_2007_Code'})\n # ensure datatype is string\n naics_02_to_07_cw = naics_02_to_07_cw.astype(str)\n\n naics_02_to_07_cw = \\\n naics_02_to_07_cw.apply(lambda x: x.str.strip() if isinstance(x, str) else x)\n\n return naics_02_to_07_cw\n\n\ndef update_naics_crosswalk():\n \"\"\"\n update the useeior crosswalk with crosswalks created for\n flowsa datasets - want to add any NAICS > 6 digits\n\n Add NAICS 2002\n :return:\n \"\"\"\n\n # read useeior master crosswalk, subset NAICS columns\n naics_load = import_useeior_mastercrosswalk()\n naics = naics_load[['NAICS_2007_Code', 'NAICS_2012_Code',\n 'NAICS_2017_Code']].drop_duplicates().reset_index(drop=True)\n # convert all rows to string\n naics = naics.astype(str)\n # ensure all None are NoneType\n naics = replace_strings_with_NoneType(naics)\n # drop rows where all None\n naics = naics.dropna(how='all')\n\n # drop naics > 6 in mastercrosswalk (all manufacturing) because unused and slows functions\n naics = naics[naics['NAICS_2012_Code'].apply(lambda x: len(x) < 7)].reset_index(drop=True)\n\n # find any NAICS where length > 6 that are used for allocation purposes and add to naics list\n missing_naics_df_list = []\n # read in all the crosswalk csv files (ends in toNAICS.csv)\n for file_name in glob.glob(datapath + \"activitytosectormapping/\"+'*_toNAICS.csv'):\n # skip Statistics Canada GDP because not all sectors relevant\n if file_name != crosswalkpath + 'Crosswalk_StatCan_GDP_toNAICS.csv':\n df = pd.read_csv(file_name, low_memory=False, dtype=str)\n # convert all rows to string\n df = df.astype(str)\n # determine sector year\n naics_year = df['SectorSourceName'].all()\n # subset dataframe so only sector\n df = df[['Sector']]\n # trim whitespace and cast as string, rename column\n df['Sector'] = df['Sector'].astype(str).str.strip()\n df = df.rename(columns={'Sector': naics_year})\n # extract sector year column from master crosswalk\n df_naics = naics[[naics_year]]\n # find any NAICS that are in source crosswalk but not in mastercrosswalk\n common = df.merge(df_naics, on=[naics_year, naics_year])\n missing_naics = df[(~df[naics_year].isin(common[naics_year]))]\n # extract sectors where len > 6 and that does not include a '-'\n missing_naics = missing_naics[missing_naics[naics_year].apply(lambda x: len(x) > 6)]\n if len(missing_naics) != 0:\n missing_naics = missing_naics[~missing_naics[naics_year].str.contains('-')]\n # append to df list\n missing_naics_df_list.append(missing_naics)\n # concat df list and drop duplications\n missing_naics_df = \\\n pd.concat(missing_naics_df_list,\n ignore_index=True, sort=False).drop_duplicates().reset_index(drop=True)\n # sort df\n missing_naics_df = missing_naics_df.sort_values(['NAICS_2012_Code'])\n missing_naics_df = missing_naics_df.reset_index(drop=True)\n\n # add missing naics to master naics crosswalk\n total_naics= naics.append(missing_naics_df, ignore_index=True)\n\n # sort df\n total_naics = total_naics.sort_values(['NAICS_2012_Code', 'NAICS_2007_Code']).drop_duplicates()\n total_naics = \\\n total_naics[~total_naics['NAICS_2012_Code'].isin(['None', 'unknown', 'nan',\n 'Unknown', np.nan]\n )].reset_index(drop=True)\n\n # convert all columns to string\n total_naics = total_naics.astype(str)\n\n # add naics 2002\n naics_02 = load_naics_02_to_07_crosswalk()\n naics_cw = pd.merge(total_naics, naics_02, how='left')\n\n # ensure NoneType\n naics_cw = replace_strings_with_NoneType(naics_cw)\n\n # reorder\n naics_cw = naics_cw[['NAICS_2002_Code', 'NAICS_2007_Code',\n 'NAICS_2012_Code', 'NAICS_2017_Code']]\n\n # save as csv\n naics_cw.to_csv(datapath + \"NAICS_Crosswalk.csv\", index=False)\n"
] | [
[
"pandas.merge",
"pandas.read_excel",
"pandas.read_csv",
"pandas.concat",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
PingHuskar/hackerrank | [
"1bfdbc63de5d0f94cd9e6ae250476b4a267662f2"
] | [
"mathematics/linear-algebra-foundations/linear-algebra-foundations-4-matrix-multiplication.py"
] | [
"# Mathematics > Linear Algebra Foundations > Linear Algebra Foundations #4- Matrix Multiplication\n# Matrix Multiplication of 2x2 Matrices\n#\n# https://www.hackerrank.com/challenges/linear-algebra-foundations-4-matrix-multiplication/problem\n#\n\nimport numpy as np\n\na = np.matrix([[1,2,3], [2,3,4], [1,1,1]])\nb = np.matrix([[4,5,6], [7,8,9], [4,5,7]])\nprint(a * b)\n\n\"\"\"\nréponse:\n\n30\n36\n45\n45\n54\n67\n15\n18\n22\n\"\"\""
] | [
[
"numpy.matrix"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
huberthomas/bdcn | [
"15eb45d48d2f65e19bc397a4e231d7b986827ebd"
] | [
"test_ms.py"
] | [
"import numpy as np\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport time\nimport re\nimport os\nimport sys\nimport cv2\nimport bdcn\nfrom datasets.dataset import Data\nimport argparse\nimport cfg\n\n\ndef test(model, args):\n test_root = cfg.config_test[args.dataset]['data_root']\n test_lst = cfg.config_test[args.dataset]['data_lst']\n test_name_lst = os.path.join(test_root, 'voc_valtest.txt')\n if 'Multicue' in args.dataset:\n test_lst = test_lst % args.k\n test_name_lst = os.path.join(test_root, 'test%d_id.txt' % args.k)\n mean_bgr = np.array(cfg.config_test[args.dataset]['mean_bgr'])\n test_img = Data(test_root, test_lst, mean_bgr=mean_bgr, scale=[0.5, 1, 1.5])\n testloader = torch.utils.data.DataLoader(\n test_img, batch_size=1, shuffle=False, num_workers=8)\n nm = np.loadtxt(test_name_lst, dtype=str)\n assert len(testloader) == len(nm)\n\n save_dir = args.res_dir\n if not os.path.exists(save_dir):\n os.mkdir(save_dir)\n if args.cuda:\n model.cuda()\n model.eval()\n data_iter = iter(testloader)\n iter_per_epoch = len(testloader)\n start_time = time.time()\n for i, (ms_data, label) in enumerate(testloader):\n ms_fuse = np.zeros((label.size()[2], label.size()[3]))\n for data in ms_data:\n if args.cuda:\n data = data.cuda()\n data = Variable(data, volatile=True)\n out = model(data)\n fuse = torch.sigmoid(out[-1]).cpu().data.numpy()[0, 0, :, :]\n fuse = cv2.resize(fuse, (label.size()[3], label.size()[2]), interpolation=cv2.INTER_LINEAR)\n ms_fuse += fuse\n ms_fuse /= len(ms_data)\n if not os.path.exists(os.path.join(save_dir, 'fuse')):\n os.mkdir(os.path.join(save_dir, 'fuse'))\n cv2.imwrite(os.path.join(save_dir, 'fuse', '%s.jpg' % nm[i]), 255-ms_fuse*255)\n print('Overall Time use: ', time.time() - start_time)\n\n\ndef main():\n import time\n print(time.localtime())\n args = parse_args()\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n model = bdcn.BDCN()\n model.load_state_dict(torch.load('%s' % (args.model)))\n test(model, args)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser('test BDCN')\n parser.add_argument('-d', '--dataset', type=str, choices=cfg.config_test.keys(), default='bsds500', help='The dataset to train')\n parser.add_argument('-c', '--cuda', action='store_true', help='whether use gpu to train network')\n parser.add_argument('-g', '--gpu', type=str, default='0', help='the gpu id to train net')\n parser.add_argument('-m', '--model', type=str, default='params/bdcn_40000.pth', help='the model to test')\n parser.add_argument('--res-dir', type=str, default='result', help='the dir to store result')\n parser.add_argument('-k', type=int, default=1, help='the k-th split set of multicue')\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"torch.sigmoid",
"torch.load",
"torch.utils.data.DataLoader",
"numpy.array",
"numpy.loadtxt",
"torch.autograd.Variable"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
windyrobin/TorchSeg | [
"304871d578c8f1bb3eb2c896c26528b437001268"
] | [
"model/bisenet/cityscapes.bisenet.R18.speed/infer.py"
] | [
"#!/usr/bin/env python3\n# encoding: utf-8\nimport os\nimport cv2\nimport argparse\nimport numpy as np\n\nimport torch\nimport torch.multiprocessing as mp\n\nfrom config import config\nfrom utils.pyt_utils import ensure_dir, link_file, load_model, parse_devices\nfrom utils.visualize import print_iou, show_img\nfrom engine.inferencer import Inferencer\nfrom engine.logger import get_logger\nfrom seg_opr.metric import hist_info, compute_score\nfrom tools.benchmark import compute_speed, stat\nfrom datasets.TestData import TestData\n#from datasets.cityscapes import Cityscapes\nfrom datasets.etseg import ETSeg\nfrom network import BiSeNet\n\nlogger = get_logger()\n\n\nclass SegInferencer(Inferencer):\n def func_per_iteration(self, data, device):\n img = data['data']\n name = data['fn']\n\n #img = cv2.resize(img, (config.image_width, config.image_height),\n # interpolation=cv2.INTER_LINEAR)\n img = cv2.resize(img, (config.image_width, config.image_height))\n\n pred = self.whole_eval(img,\n #(config.image_height // config.gt_down_sampling,\n # config.image_width // config.gt_down_sampling),\n (config.image_height,\n config.image_width),\n device)\n\n if self.save_path is not None:\n colors = ETSeg.get_class_colors()\n image = img\n comp_img = show_img(colors, config.background, image,\n pred)\n\n fn = name + '.png'\n cv2.imwrite(os.path.join(self.save_path, fn), comp_img[:, :, ::-1])\n logger.info('Save the image ' + fn)\n\n if self.show_image:\n colors = self.dataset.get_class_colors\n image = img\n clean = np.zeros(label.shape)\n comp_img = show_img(colors, config.background, image, clean,\n label,\n pred)\n cv2.imshow('comp_image', comp_img)\n cv2.waitKey(0)\n\n #return results_dict\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-e', '--epochs', default='last', type=str)\n parser.add_argument('-d', '--devices', default='1', type=str)\n parser.add_argument('-v', '--verbose', default=False, action='store_true')\n parser.add_argument('--show_image', '-s', default=False,\n action='store_true')\n parser.add_argument('--save_path', '-p', default=None)\n parser.add_argument('--input_size', type=str, default='1x3x512x1024',\n help='Input size. '\n 'channels x height x width (default: 1x3x224x224)')\n parser.add_argument('-speed', '--speed_test', action='store_true')\n parser.add_argument('--iteration', type=int, default=5000)\n parser.add_argument('-summary', '--summary', action='store_true')\n parser.add_argument('-trt', '--tensorrt', default=False, action='store_true')\n\n args = parser.parse_args()\n all_dev = parse_devices(args.devices)\n\n network = BiSeNet(config.num_classes, is_training=False,\n criterion=None, ohem_criterion=None)\n dataset = TestData('./sample_test')\n\n if args.speed_test:\n device = all_dev[0]\n logger.info(\"=========DEVICE:%s SIZE:%s=========\" % (\n torch.cuda.get_device_name(device), args.input_size))\n input_size = tuple(int(x) for x in args.input_size.split('x'))\n compute_speed(network, input_size, device, args.iteration)\n elif args.summary:\n input_size = tuple(int(x) for x in args.input_size.split('x'))\n stat(network, input_size)\n else:\n with torch.no_grad():\n segmentor = SegInferencer(dataset, config.num_classes, config.image_mean,\n config.image_std, network,\n config.eval_scale_array, config.eval_flip,\n all_dev, args.verbose, args.save_path,\n args.show_image, args.tensorrt)\n segmentor.run(config.snapshot_dir, args.epochs, config.val_log_file,\n config.link_val_log_file)\n"
] | [
[
"torch.no_grad",
"numpy.zeros",
"torch.cuda.get_device_name"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
liyi193328/warp_seq2seq | [
"e5cbed8305aa27a76eab3e4250e0d30d96058f96",
"e5cbed8305aa27a76eab3e4250e0d30d96058f96"
] | [
"seq2seq/features/extend_ids.py",
"seq2seq/contrib/seq2seq/backup/helper.py"
] | [
"#encoding=utf-8\n\nimport tensorflow as tf\n\ndef should_continue(t, timestaps, *args):\n return tf.less(t, timestaps)\n\ndef get_extend_source_ids(source_words, source_ids, source_unk_id, oringin_vocab_size):\n new_source_ids = []\n source_oov_words_list = []\n\n unk_num_list = []\n extend_source_ids = []\n for source_id, source_word in zip(tf.unstack(source_ids), tf.unstack(source_words)):\n source_len = tf.shape(source_id)[0]\n unk_bool = tf.equal(source_id, source_unk_id)\n unk_index = tf.where(unk_bool)\n unk_index = tf.cast(unk_index, tf.int32)\n unk_words = tf.gather(source_word, unk_index)\n unk_nums = tf.reduce_sum(tf.cast(unk_bool, tf.int32))\n unk_num_list.append(unk_nums)\n updates = tf.expand_dims(tf.range(oringin_vocab_size, oringin_vocab_size + unk_nums), 1)\n new_shape = tf.convert_to_tensor([source_len, 1])\n new_source_id = tf.scatter_nd(unk_index, updates, new_shape)\n new_source_id = tf.reshape(new_source_id, (-1,))\n new_source_id = tf.where(unk_bool, new_source_id, source_id)\n extend_source_ids.append(new_source_id)\n source_oov_words_list.append(unk_words)\n\n extend_source_ids = tf.convert_to_tensor(extend_source_ids, dtype=tf.int32)\n return extend_source_ids, source_oov_words_list\n\n\ndef get_extend_target_ids(extend_source_ids, source_words, target_words, target_ids, target_len,\n target_unk_id, prefer_local=\"first\"):\n unstack_target_ids = tf.unstack(target_ids)\n extend_target_ids = []\n target_unk_token_nums = []\n\n def get_target_id(t, max_t, seq_target_word, seq_target_id, extend_target_id, seq_extend_source_id, seq_source_word,\n target_unk_id):\n\n cur_target_word = seq_target_word[t]\n cur_target_id = seq_target_id[t]\n\n def f1():\n extend_target_id.write(t, cur_target_id)\n return extend_target_id\n\n def f2():\n\n equal_bool = tf.equal(seq_source_word, cur_target_word)\n cond = tf.equal(tf.reduce_sum(tf.cast(equal_bool, tf.int32)), 0)\n def f2_1():\n extend_target_id.write(t, target_unk_id)\n return extend_target_id\n def f2_2():\n equal_index = tf.cast(tf.reduce_min(tf.where(equal_bool)), tf.int32)\n new_target_id = seq_extend_source_id[equal_index]\n extend_target_id.write(t, new_target_id)\n return extend_target_id\n\n return tf.cond(cond, f2_1, f2_2)\n\n extend_target_id = tf.cond( tf.equal(cur_target_id, target_unk_id), f1, f2)\n\n return t + 1, max_t, seq_target_word, seq_target_id, extend_target_id, seq_extend_source_id, seq_source_word, target_unk_id\n\n for i, seq_target_id in enumerate(unstack_target_ids): # loop batch\n extend_source_id = extend_source_ids[i]\n new_seq_target_ids = []\n tlen = target_len[i]\n extend_target_id = tf.TensorArray(tf.int32, dynamic_size=True, size=tlen)\n t = 0\n args = (t, tlen, target_words[i], seq_target_id, extend_target_id, extend_source_ids[i], source_words[i], target_unk_id)\n result = tf.while_loop(should_continue, get_target_id, loop_vars=args)\n extend_target_id = result[4].stack()\n unk_token_nums = tf.reduce_sum(tf.cast(tf.equal(extend_target_id, target_unk_id), tf.int32))\n target_unk_token_nums.append(unk_token_nums)\n extend_target_ids.append(extend_target_id)\n\n return extend_target_ids, tf.convert_to_tensor(target_unk_token_nums, dtype=tf.int32)\n\nif __name__ == \"__main__\":\n source_ids = tf.constant([[1, 10, 20, 10], [2, 10, 30, -1]], dtype=tf.int32)\n source_words = tf.constant([[\"a1\", \"a10\", \"a20\", \"a10\"], [\"a2\", \"a10\", \"a30\", \"a-1\"]], dtype=tf.string)\n target_ids = tf.constant([[1, 10, 12, 20, 2], [-1, 30, 12, -1, -1]])\n target_words = tf.constant([[\"a1\",\"b10\", \"b20\", \"a20\", \"c10\"], [\"a-1\", \"a30\", \"bq\", \"cd\", \"qy\"]], dtype=tf.string)\n unk_id = -1\n vocab_size = 200\n extend_source_ids, source_oov_words_list = get_extend_source_ids(source_words,source_ids, unk_id, oringin_vocab_size=vocab_size)\n target_len = [target_words[0].shape[0].value, target_words[1].shape[0].value]\n extend_target_ids, target_unk_token_nums = get_extend_target_ids(extend_source_ids,source_words, target_words, target_ids, target_len, unk_id)\n with tf.Session() as sess:\n [n_source_ids, n_target_ids, target_oov_nums] = sess.run(extend_source_ids, extend_target_ids, target_unk_token_nums)\n print(\"new source ids:\")\n print(n_source_ids)\n print(\"\\nnew target ids:\")\n print(n_target_ids)\n print(\"\\ntarget oov nums:\")\n print(target_oov_nums)\n\n",
"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"\nIMPORTANT: This code is taken directly from Tensorflow\n(https://github.com/tensorflow/tensorflow) and is copied temporarily\nuntil it is available in a packaged Tensorflow version on pypi.\n\nTODO(dennybritz): Delete this code when it becomes available in TF.\n\nA library of helpers for use with SamplingDecoders.\n\"\"\"\n\n# pylint: skip-file\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\n\nimport six\n\ntry:\n from tensorflow.python.ops.distributions import bernoulli\n from tensorflow.python.ops.distributions import categorical\nexcept:\n # Backwards compatibility with TensorFlow prior to 1.2.\n from tensorflow.contrib.distributions.python.ops import bernoulli\n from tensorflow.contrib.distributions.python.ops import categorical\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.layers import base as layers_base\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import embedding_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.util import nest\n\nfrom seq2seq.contrib.seq2seq import decoder\n\n__all__ = [\n \"Helper\",\n \"TrainingHelper\",\n \"GreedyEmbeddingHelper\",\n \"CustomHelper\",\n \"ScheduledEmbeddingTrainingHelper\",\n \"ScheduledOutputTrainingHelper\",\n]\n\n_transpose_batch_time = decoder._transpose_batch_time # pylint: disable=protected-access\n\n\ndef _unstack_ta(inp):\n return tensor_array_ops.TensorArray(\n dtype=inp.dtype, size=array_ops.shape(inp)[0],\n element_shape=inp.get_shape()[1:]).unstack(inp)\n\n\[email protected]_metaclass(abc.ABCMeta)\nclass Helper(object):\n \"\"\"Helper interface. Helper instances are used by SamplingDecoder.\"\"\"\n\n @abc.abstractproperty\n def batch_size(self):\n \"\"\"Returns a scalar int32 tensor.\"\"\"\n raise NotImplementedError(\"batch_size has not been implemented\")\n\n @abc.abstractmethod\n def initialize(self, name=None):\n \"\"\"Returns `(initial_finished, initial_inputs)`.\"\"\"\n pass\n\n @abc.abstractmethod\n def sample(self, time, outputs, state, name=None):\n \"\"\"Returns `sample_ids`.\"\"\"\n pass\n\n @abc.abstractmethod\n def next_inputs(self, time, outputs, state, sample_ids, name=None):\n \"\"\"Returns `(finished, next_inputs, next_state)`.\"\"\"\n pass\n\n\nclass CustomHelper(Helper):\n \"\"\"Base abstract class that allows the user to customize sampling.\"\"\"\n\n def __init__(self, initialize_fn, sample_fn, next_inputs_fn):\n \"\"\"Initializer.\n\n Args:\n initialize_fn: callable that returns `(finished, next_inputs)`\n for the first iteration.\n sample_fn: callable that takes `(time, outputs, state)`\n and emits tensor `sample_ids`.\n next_inputs_fn: callable that takes `(time, outputs, state, sample_ids)`\n and emits `(finished, next_inputs, next_state)`.\n \"\"\"\n self._initialize_fn = initialize_fn\n self._sample_fn = sample_fn\n self._next_inputs_fn = next_inputs_fn\n self._batch_size = None\n\n @property\n def batch_size(self):\n if self._batch_size is None:\n raise ValueError(\"batch_size accessed before initialize was called\")\n return self._batch_size\n\n def initialize(self, name=None):\n with ops.name_scope(name, \"%sInitialize\" % type(self).__name__):\n (finished, next_inputs) = self._initialize_fn()\n if self._batch_size is None:\n self._batch_size = array_ops.size(finished)\n return (finished, next_inputs)\n\n def sample(self, time, outputs, state, name=None):\n with ops.name_scope(\n name, \"%sSample\" % type(self).__name__, (time, outputs, state)):\n return self._sample_fn(time=time, outputs=outputs, state=state)\n\n def next_inputs(self, time, outputs, state, sample_ids, name=None):\n with ops.name_scope(\n name, \"%sNextInputs\" % type(self).__name__, (time, outputs, state)):\n return self._next_inputs_fn(\n time=time, outputs=outputs, state=state, sample_ids=sample_ids)\n\n\nclass TrainingHelper(Helper):\n \"\"\"A helper for use during training. Only reads inputs.\n\n Returned sample_ids are the argmax of the RNN output logits.\n \"\"\"\n\n def __init__(self, inputs, sequence_length, time_major=False, name=None):\n \"\"\"Initializer.\n\n Args:\n inputs: A (structure of) input tensors.\n sequence_length: An int32 vector tensor.\n time_major: Python bool. Whether the tensors in `inputs` are time major.\n If `False` (default), they are assumed to be batch major.\n name: Name scope for any created operations.\n\n Raises:\n ValueError: if `sequence_length` is not a 1D tensor.\n \"\"\"\n with ops.name_scope(name, \"TrainingHelper\", [inputs, sequence_length]):\n inputs = ops.convert_to_tensor(inputs, name=\"inputs\")\n if not time_major:\n inputs = nest.map_structure(_transpose_batch_time, inputs)\n\n self._input_tas = nest.map_structure(_unstack_ta, inputs)\n self._sequence_length = ops.convert_to_tensor(\n sequence_length, name=\"sequence_length\")\n if self._sequence_length.get_shape().ndims != 1:\n raise ValueError(\n \"Expected sequence_length to be a vector, but received shape: %s\" %\n self._sequence_length.get_shape())\n\n self._zero_inputs = nest.map_structure(\n lambda inp: array_ops.zeros_like(inp[0, :]), inputs)\n\n self._batch_size = array_ops.size(sequence_length)\n\n @property\n def batch_size(self):\n return self._batch_size\n\n def initialize(self, name=None):\n with ops.name_scope(name, \"TrainingHelperInitialize\"):\n finished = math_ops.equal(0, self._sequence_length)\n all_finished = math_ops.reduce_all(finished)\n next_inputs = control_flow_ops.cond(\n all_finished, lambda: self._zero_inputs,\n lambda: nest.map_structure(lambda inp: inp.read(0), self._input_tas))\n return (finished, next_inputs)\n\n def sample(self, time, outputs, name=None, **unused_kwargs):\n with ops.name_scope(name, \"TrainingHelperSample\", [time, outputs]):\n sample_ids = math_ops.cast(\n math_ops.argmax(outputs, axis=-1), dtypes.int32)\n return sample_ids\n\n def next_inputs(self, time, outputs, state, name=None, **unused_kwargs):\n \"\"\"next_inputs_fn for TrainingHelper.\"\"\"\n with ops.name_scope(name, \"TrainingHelperNextInputs\",\n [time, outputs, state]):\n next_time = time + 1\n finished = (next_time >= self._sequence_length)\n all_finished = math_ops.reduce_all(finished)\n def read_from_ta(inp):\n return inp.read(next_time)\n next_inputs = control_flow_ops.cond(\n all_finished, lambda: self._zero_inputs,\n lambda: nest.map_structure(read_from_ta, self._input_tas))\n return (finished, next_inputs, state)\n\n\nclass ScheduledEmbeddingTrainingHelper(TrainingHelper):\n \"\"\"A training helper that adds scheduled sampling.\n\n Returns -1s for sample_ids where no sampling took place; valid sample id\n values elsewhere.\n \"\"\"\n\n def __init__(self, inputs, sequence_length, embedding, sampling_probability,\n time_major=False, seed=None, scheduling_seed=None, name=None):\n \"\"\"Initializer.\n\n Args:\n inputs: A (structure of) input tensors.\n sequence_length: An int32 vector tensor.\n embedding: A callable that takes a vector tensor of `ids` (argmax ids),\n or the `params` argument for `embedding_lookup`.\n sampling_probability: A 0D `float32` tensor: the probability of sampling\n categorically from the output ids instead of reading directly from the\n inputs.\n time_major: Python bool. Whether the tensors in `inputs` are time major.\n If `False` (default), they are assumed to be batch major.\n seed: The sampling seed.\n scheduling_seed: The schedule decision rule sampling seed.\n name: Name scope for any created operations.\n\n Raises:\n ValueError: if `sampling_probability` is not a scalar or vector.\n \"\"\"\n with ops.name_scope(name, \"ScheduledEmbeddingSamplingWrapper\",\n [embedding, sampling_probability]):\n if callable(embedding):\n self._embedding_fn = embedding\n else:\n self._embedding_fn = (\n lambda ids: embedding_ops.embedding_lookup(embedding, ids))\n self._sampling_probability = ops.convert_to_tensor(\n sampling_probability, name=\"sampling_probability\")\n if self._sampling_probability.get_shape().ndims not in (0, 1):\n raise ValueError(\n \"sampling_probability must be either a scalar or a vector. \"\n \"saw shape: %s\" % (self._sampling_probability.get_shape()))\n self._seed = seed\n self._scheduling_seed = scheduling_seed\n super(ScheduledEmbeddingTrainingHelper, self).__init__(\n inputs=inputs,\n sequence_length=sequence_length,\n time_major=time_major,\n name=name)\n\n def initialize(self, name=None):\n return super(ScheduledEmbeddingTrainingHelper, self).initialize(name=name)\n\n def sample(self, time, outputs, state, name=None):\n with ops.name_scope(name, \"ScheduledEmbeddingTrainingHelperSample\",\n [time, outputs, state]):\n # Return -1s where we did not sample, and sample_ids elsewhere\n select_sample_noise = random_ops.random_uniform(\n [self.batch_size], seed=self._scheduling_seed)\n select_sample = (self._sampling_probability > select_sample_noise)\n sample_id_sampler = categorical.Categorical(logits=outputs)\n return array_ops.where(\n select_sample,\n sample_id_sampler.sample(seed=self._seed),\n array_ops.tile([-1], [self.batch_size]))\n\n def next_inputs(self, time, outputs, state, sample_ids, name=None):\n with ops.name_scope(name, \"ScheduledEmbeddingTrainingHelperSample\",\n [time, outputs, state, sample_ids]):\n (finished, base_next_inputs, state) = (\n super(ScheduledEmbeddingTrainingHelper, self).next_inputs(\n time=time,\n outputs=outputs,\n state=state,\n sample_ids=sample_ids,\n name=name))\n\n def maybe_sample():\n \"\"\"Perform scheduled sampling.\"\"\"\n where_sampling = math_ops.cast(\n array_ops.where(sample_ids > -1), dtypes.int32)\n where_not_sampling = math_ops.cast(\n array_ops.where(sample_ids <= -1), dtypes.int32)\n where_sampling_flat = array_ops.reshape(where_sampling, [-1])\n where_not_sampling_flat = array_ops.reshape(where_not_sampling, [-1])\n sample_ids_sampling = array_ops.gather(sample_ids, where_sampling_flat)\n inputs_not_sampling = array_ops.gather(\n base_next_inputs, where_not_sampling_flat)\n sampled_next_inputs = self._embedding_fn(sample_ids_sampling)\n base_shape = array_ops.shape(base_next_inputs)\n return (array_ops.scatter_nd(indices=where_sampling,\n updates=sampled_next_inputs,\n shape=base_shape)\n + array_ops.scatter_nd(indices=where_not_sampling,\n updates=inputs_not_sampling,\n shape=base_shape))\n\n all_finished = math_ops.reduce_all(finished)\n next_inputs = control_flow_ops.cond(\n all_finished, lambda: base_next_inputs, maybe_sample)\n return (finished, next_inputs, state)\n\n\nclass ScheduledOutputTrainingHelper(TrainingHelper):\n \"\"\"A training helper that adds scheduled sampling directly to outputs.\n\n Returns False for sample_ids where no sampling took place; True elsewhere.\n \"\"\"\n\n def __init__(self, inputs, sequence_length, sampling_probability,\n time_major=False, seed=None, next_input_layer=None,\n auxiliary_inputs=None, name=None):\n \"\"\"Initializer.\n\n Args:\n inputs: A (structure) of input tensors.\n sequence_length: An int32 vector tensor.\n sampling_probability: A 0D `float32` tensor: the probability of sampling\n from the outputs instead of reading directly from the inputs.\n time_major: Python bool. Whether the tensors in `inputs` are time major.\n If `False` (default), they are assumed to be batch major.\n seed: The sampling seed.\n next_input_layer: (Optional) An instance of `tf.layers.Layer`, i.e.,\n `tf.layers.Dense`. Optional layer to apply to the RNN output to create\n the next input.\n auxiliary_inputs: An optional (structure of) auxiliary input tensors with\n a shape that matches `inputs` in all but (potentially) the final\n dimension. These tensors will be concatenated to the sampled output or\n the `inputs` when not sampling for use as the next input.\n name: Name scope for any created operations.\n\n Raises:\n ValueError: if `sampling_probability` is not a scalar or vector.\n \"\"\"\n with ops.name_scope(name, \"ScheduledOutputTrainingHelper\",\n [inputs, auxiliary_inputs, sampling_probability]):\n self._sampling_probability = ops.convert_to_tensor(\n sampling_probability, name=\"sampling_probability\")\n if self._sampling_probability.get_shape().ndims not in (0, 1):\n raise ValueError(\n \"sampling_probability must be either a scalar or a vector. \"\n \"saw shape: %s\" % (self._sampling_probability.get_shape()))\n\n if auxiliary_inputs is None:\n maybe_concatenated_inputs = inputs\n else:\n inputs = ops.convert_to_tensor(inputs, name=\"inputs\")\n auxiliary_inputs = ops.convert_to_tensor(\n auxiliary_inputs, name=\"auxiliary_inputs\")\n maybe_concatenated_inputs = nest.map_structure(\n lambda x, y: array_ops.concat((x, y), -1),\n inputs, auxiliary_inputs)\n if not time_major:\n auxiliary_inputs = nest.map_structure(\n _transpose_batch_time, auxiliary_inputs)\n\n self._auxiliary_input_tas = (\n nest.map_structure(_unstack_ta, auxiliary_inputs)\n if auxiliary_inputs is not None else None)\n\n self._seed = seed\n\n if (next_input_layer is not None and not isinstance(next_input_layer,\n layers_base._Layer)): # pylint: disable=protected-access\n raise TypeError(\"next_input_layer must be a Layer, received: %s\" %\n type(next_input_layer))\n self._next_input_layer = next_input_layer\n\n super(ScheduledOutputTrainingHelper, self).__init__(\n inputs=maybe_concatenated_inputs,\n sequence_length=sequence_length,\n time_major=time_major,\n name=name)\n\n def initialize(self, name=None):\n return super(ScheduledOutputTrainingHelper, self).initialize(name=name)\n\n def sample(self, time, outputs, state, name=None):\n with ops.name_scope(name, \"ScheduledOutputTrainingHelperSample\",\n [time, outputs, state]):\n sampler = bernoulli.Bernoulli(probs=self._sampling_probability)\n return math_ops.cast(\n sampler.sample(sample_shape=self.batch_size, seed=self._seed),\n dtypes.bool)\n\n def next_inputs(self, time, outputs, state, sample_ids, name=None):\n with ops.name_scope(name, \"ScheduledOutputTrainingHelperNextInputs\",\n [time, outputs, state, sample_ids]):\n (finished, base_next_inputs, state) = (\n super(ScheduledOutputTrainingHelper, self).next_inputs(\n time=time,\n outputs=outputs,\n state=state,\n sample_ids=sample_ids,\n name=name))\n\n def maybe_sample():\n \"\"\"Perform scheduled sampling.\"\"\"\n\n def maybe_concatenate_auxiliary_inputs(outputs_, indices=None):\n \"\"\"Concatenate outputs with auxiliary inputs, if they exist.\"\"\"\n if self._auxiliary_input_tas is None:\n return outputs_\n\n next_time = time + 1\n auxiliary_inputs = nest.map_structure(\n lambda ta: ta.read(next_time), self._auxiliary_input_tas)\n if indices is not None:\n auxiliary_inputs = array_ops.gather_nd(auxiliary_inputs, indices)\n return nest.map_structure(\n lambda x, y: array_ops.concat((x, y), -1),\n outputs_, auxiliary_inputs)\n\n if self._next_input_layer is None:\n return array_ops.where(\n sample_ids, maybe_concatenate_auxiliary_inputs(outputs),\n base_next_inputs)\n\n where_sampling = math_ops.cast(\n array_ops.where(sample_ids), dtypes.int32)\n where_not_sampling = math_ops.cast(\n array_ops.where(math_ops.logical_not(sample_ids)), dtypes.int32)\n outputs_sampling = array_ops.gather_nd(outputs, where_sampling)\n inputs_not_sampling = array_ops.gather_nd(base_next_inputs,\n where_not_sampling)\n sampled_next_inputs = maybe_concatenate_auxiliary_inputs(\n self._next_input_layer(outputs_sampling), where_sampling)\n\n base_shape = array_ops.shape(base_next_inputs)\n return (array_ops.scatter_nd(indices=where_sampling,\n updates=sampled_next_inputs,\n shape=base_shape)\n + array_ops.scatter_nd(indices=where_not_sampling,\n updates=inputs_not_sampling,\n shape=base_shape))\n\n all_finished = math_ops.reduce_all(finished)\n next_inputs = control_flow_ops.cond(\n all_finished, lambda: base_next_inputs, maybe_sample)\n return (finished, next_inputs, state)\n\n\nclass GreedyEmbeddingHelper(Helper):\n \"\"\"A helper for use during inference.\n\n Uses the argmax of the output (treated as logits) and passes the\n result through an embedding layer to get the next input.\n \"\"\"\n\n def __init__(self, embedding, start_tokens, end_token):\n \"\"\"Initializer.\n\n Args:\n embedding: A callable that takes a vector tensor of `ids` (argmax ids),\n or the `params` argument for `embedding_lookup`.\n start_tokens: `int32` vector shaped `[batch_size]`, the start tokens.\n end_token: `int32` scalar, the token that marks end of decoding.\n\n Raises:\n ValueError: if `sequence_length` is not a 1D tensor.\n \"\"\"\n if callable(embedding):\n self._embedding_fn = embedding\n else:\n self._embedding_fn = (\n lambda ids: embedding_ops.embedding_lookup(embedding, ids))\n\n self._start_tokens = ops.convert_to_tensor(\n start_tokens, dtype=dtypes.int32, name=\"start_tokens\")\n self._end_token = ops.convert_to_tensor(\n end_token, dtype=dtypes.int32, name=\"end_token\")\n if self._start_tokens.get_shape().ndims != 1:\n raise ValueError(\"start_tokens must be a vector\")\n self._batch_size = array_ops.size(start_tokens)\n if self._end_token.get_shape().ndims != 0:\n raise ValueError(\"end_token must be a scalar\")\n self._start_inputs = self._embedding_fn(self._start_tokens)\n\n @property\n def batch_size(self):\n return self._batch_size\n\n def initialize(self, name=None):\n finished = array_ops.tile([False], [self._batch_size])\n return (finished, self._start_inputs)\n\n def sample(self, time, outputs, state, name=None):\n \"\"\"sample for GreedyEmbeddingHelper.\"\"\"\n del time, state # unused by sample_fn\n # Outputs are logits, use argmax to get the most probable id\n if not isinstance(outputs, ops.Tensor):\n raise TypeError(\"Expected outputs to be a single Tensor, got: %s\" %\n type(outputs))\n sample_ids = math_ops.cast(\n math_ops.argmax(outputs, axis=-1), dtypes.int32)\n return sample_ids\n\n def next_inputs(self, time, outputs, state, sample_ids, name=None):\n \"\"\"next_inputs_fn for GreedyEmbeddingHelper.\"\"\"\n del time, outputs # unused by next_inputs_fn\n finished = math_ops.equal(sample_ids, self._end_token)\n all_finished = math_ops.reduce_all(finished)\n next_inputs = control_flow_ops.cond(\n all_finished,\n # If we're finished, the next_inputs value doesn't matter\n lambda: self._start_inputs,\n lambda: self._embedding_fn(sample_ids))\n return (finished, next_inputs, state)\n"
] | [
[
"tensorflow.convert_to_tensor",
"tensorflow.cond",
"tensorflow.constant",
"tensorflow.while_loop",
"tensorflow.unstack",
"tensorflow.less",
"tensorflow.TensorArray",
"tensorflow.shape",
"tensorflow.range",
"tensorflow.equal",
"tensorflow.cast",
"tensorflow.scatter_nd",
"tensorflow.reshape",
"tensorflow.gather",
"tensorflow.where",
"tensorflow.Session"
],
[
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.array_ops.gather_nd",
"tensorflow.python.ops.control_flow_ops.cond",
"tensorflow.python.ops.math_ops.logical_not",
"tensorflow.python.ops.math_ops.reduce_all",
"tensorflow.python.ops.math_ops.argmax",
"tensorflow.python.ops.array_ops.where",
"tensorflow.python.ops.array_ops.gather",
"tensorflow.python.ops.array_ops.size",
"tensorflow.python.ops.embedding_ops.embedding_lookup",
"tensorflow.python.util.nest.map_structure",
"tensorflow.contrib.distributions.python.ops.categorical.Categorical",
"tensorflow.python.ops.array_ops.tile",
"tensorflow.python.ops.array_ops.zeros_like",
"tensorflow.python.ops.math_ops.equal",
"tensorflow.python.ops.array_ops.scatter_nd",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.contrib.distributions.python.ops.bernoulli.Bernoulli",
"tensorflow.python.ops.array_ops.concat",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.random_ops.random_uniform"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.0"
]
}
] |
askprash/pyCycle | [
"e0845d7e320b6cb47367734c26ec3410c9fa5bf7"
] | [
"pycycle/elements/compressor.py"
] | [
"import numpy as np\nfrom collections.abc import Iterable\nimport itertools\n\nimport openmdao.api as om\n\nfrom pycycle.thermo.cea import species_data\nfrom pycycle.thermo.thermo import Thermo\nfrom pycycle.flow_in import FlowIn\nfrom pycycle.passthrough import PassThrough\nfrom pycycle.constants import AIR_ELEMENTS, BTU_s2HP, HP_per_RPM_to_FT_LBF, T_STDeng, P_STDeng\nfrom pycycle.elements.compressor_map import CompressorMap\nfrom pycycle.maps.ncp01 import NCP01\n\n\nclass CorrectedInputsCalc(om.ExplicitComponent):\n \"\"\"Compute design corrected flow (Wc) and design corrected speed (Nc)\"\"\"\n\n def setup(self):\n # inputs\n self.add_input('Tt', val=500., units='degR',\n desc='incoming temperature')\n self.add_input('Pt', val=14., units='psi', desc='incoming pressure')\n self.add_input('W_in', val=30.0, units='lbm/s', desc='mass flow')\n self.add_input('Nmech', val=1000.0, units='rpm', desc='shaft speed')\n # outputs\n self.add_output('Wc', val=30.0, units='lbm/s',\n desc='corrected mass flow')\n self.add_output('Nc', val=100., lower=1e-5,\n units='rpm', desc='corrected shaft speed')\n\n self.declare_partials('Wc', ['Tt', 'Pt', 'W_in'])\n self.declare_partials('Nc', ['Nmech', 'Tt'])\n\n def compute(self, inputs, outputs):\n\n self.delta = inputs['Pt'] / P_STDeng\n self.W = inputs['W_in']\n self.theta = inputs['Tt'] / T_STDeng\n\n outputs['Wc'] = self.W * self.theta**0.5 / self.delta\n outputs['Nc'] = inputs['Nmech'] * self.theta**-0.5\n\n def compute_partials(self, inputs, J):\n\n theta = self.theta\n delta = self.delta\n\n J['Wc', 'Tt'] = 0.5 * self.W / delta * theta**-0.5 / T_STDeng\n J['Wc', 'Pt'] = -self.W * theta**0.5 * delta**-2. / P_STDeng\n J['Wc', 'W_in'] = theta**0.5 / delta\n J['Nc', 'Nmech'] = theta**-0.5\n J['Nc', 'Tt'] = -0.5 * inputs['Nmech'] * theta**-1.5 / T_STDeng\n\nclass eff_poly_calc(om.ExplicitComponent):\n \"\"\" Calculate polytropic efficiency for compressor\"\"\"\n\n def setup(self):\n self.add_input('PR', 1.0,units=None, desc='element pressure ratio Pt_out/Pt_in')\n self.add_input('S_in', 1.0,units='Btu/(lbm*degR)', desc='element input entropy')\n self.add_input('S_out', 1.0,units='Btu/(lbm*degR)', desc='element output entropy')\n self.add_input('Rt', val=0.0686, units='Btu/(lbm*degR)', desc='specific gas constant')\n # list_outputs\n self.add_output('eff_poly', val=1.0, units=None, desc='polytropic efficiency', lower=1e-6)\n # define partials\n self.declare_partials('eff_poly','*')\n def compute(self, inputs, outputs):\n PR = inputs['PR']\n S_in = inputs['S_in']\n S_out = inputs['S_out']\n Rt = inputs['Rt']\n\n outputs['eff_poly'] = Rt * np.log(PR) / ( Rt*np.log(PR) + S_out - S_in )\n\n def compute_partials(self, inputs, J):\n PR = inputs['PR']\n S_in = inputs['S_in']\n S_out = inputs['S_out']\n Rt = inputs['Rt']\n\n J['eff_poly', 'PR'] = (Rt*(S_out - S_in))/(PR*(np.log(PR)*Rt+S_out-S_in)**2)\n\n J['eff_poly', 'S_in'] = (np.log(PR)*Rt)/(np.log(PR)*Rt+S_out-S_in)**2\n J['eff_poly', 'S_out'] = -(np.log(PR)*Rt)/(np.log(PR)*Rt+S_out-S_in)**2\n\n J['eff_poly', 'Rt'] = (np.log(PR)*(S_out-S_in))/(np.log(PR)*Rt+S_out-S_in)**2\n\n\nclass Power(om.ExplicitComponent):\n \"\"\"Power calculates shaft power for the compressor or turbine\"\"\"\n\n def setup(self):\n # inputs\n self.add_input('W', val=30.0, units='lbm/s', desc='mass flow')\n self.add_input('ht_out', val=20.0, units='Btu/lbm',\n desc='downstream enthalpy')\n self.add_input('ht_in', val=10.0, units='Btu/lbm',\n desc='incoming enthalpy')\n self.add_input('Nmech', val=1000.0, units='rpm', desc='shaft speed')\n # self.add_input('Tt_in', val=500., units='degR', desc='incoming temperature')\n # outputs\n self.add_output('power', shape=1, units='hp', desc='turbine power')\n self.add_output('trq', shape=1, units='ft*lbf', desc='turbine torque')\n\n self.declare_partials('power', ['W', 'ht_out', 'ht_in'])\n self.declare_partials('trq', '*')\n\n def compute(self, inputs, outputs):\n\n outputs['power'] = inputs['W'] * (inputs['ht_in'] - inputs['ht_out']) * BTU_s2HP\n outputs['trq'] = HP_per_RPM_to_FT_LBF * outputs['power'] / inputs['Nmech']\n\n\n def compute_partials(self, inputs, J):\n ht_in = inputs['ht_in']\n ht_out = inputs['ht_out']\n W = inputs['W']\n Nmech = inputs['Nmech']\n\n J['power', 'W'] = (ht_in - ht_out) * BTU_s2HP\n J['power', 'ht_out'] = -W * BTU_s2HP\n J['power', 'ht_in'] = W * BTU_s2HP\n # J['power','Nmech'] = 0.\n\n J['trq', 'W'] = (ht_in - ht_out) * BTU_s2HP * HP_per_RPM_to_FT_LBF / Nmech\n J['trq', 'ht_out'] = -W * BTU_s2HP * HP_per_RPM_to_FT_LBF / Nmech\n J['trq', 'ht_in'] = W * BTU_s2HP * HP_per_RPM_to_FT_LBF / Nmech\n J['trq', 'Nmech'] = -W * (ht_in - ht_out) * BTU_s2HP * HP_per_RPM_to_FT_LBF * Nmech**-2.\n\n\nclass BleedsAndPower(om.ExplicitComponent):\n \"\"\"BleedsAndPower calculates the bleed flows and shaft power for the compressor\"\"\"\n\n def initialize(self):\n self.options.declare('bleed_names', types=Iterable,\n desc='list of names for the bleed ports')\n\n def setup(self):\n self.add_input('W_in', val=30.0, units='lbm/s',\n desc='entrance mass flow')\n self.add_input('ht_out', val=20.0, units='Btu/lbm',\n desc='exit total enthalpy')\n self.add_input('ht_in', val=10.0, units='Btu/lbm',\n desc='entrance total enthalpy')\n self.add_input('Pt_out', val=20.0, units='psi',\n desc='exit total pressure')\n self.add_input('Pt_in', val=10.0, units='psi',\n desc='entrance total pressure')\n self.add_input('Nmech', val=1000.0, units='rpm', desc='shaft speed')\n\n self.add_output('W_out', shape=1, units='lbm/s', desc='exit mass flow')\n self.add_output('power', shape=1, units='hp', desc='shaft power')\n self.add_output('trq', shape=1, units='ft*lbf', desc='shaft torque')\n\n self.declare_partials('W_out', 'W_in')\n self.declare_partials('power', ['W_in', 'ht_in', 'ht_out'])\n self.declare_partials('trq', ['W_in', 'ht_in', 'ht_out', 'Nmech'])\n\n # bleed inputs and outputs\n for BN in self.options['bleed_names']:\n self.add_input(BN + ':frac_W', val=0.0,\n desc='bleed mass flow fraction (W_bld/W_in)')\n self.add_input(BN + ':frac_P', val=0.0,\n desc='bleed pressure fraction ((P_bld-P_in)/(P_out-P_in))')\n self.add_input(BN + ':frac_work', val=0.0,\n desc='bleed work fraction ((h_bld-h_in)/(h_out-h_in))')\n\n self.add_output(BN + ':stat:W', shape=1, lower=0.0,\n units='lbm/s', desc='bleed mass flow')\n self.add_output(BN + ':Pt', shape=1, lower=1e-6,\n units='psi', desc='bleed total pressure')\n self.add_output(BN + ':ht', shape=1, units='Btu/lbm',\n desc='bleed total enthalpy')\n # self.add_output(BN+':power', shape=1, desc='bleed power reduction')\n\n self.declare_partials('W_out', BN+':frac_W')\n self.declare_partials('power', [BN+':frac_W', BN+':frac_work'])\n self.declare_partials(BN+':stat:W', ['W_in', BN+':frac_W'])\n self.declare_partials(BN+':Pt', ['Pt_in', BN+':frac_P', 'Pt_out'])\n self.declare_partials(BN+':ht', ['ht_in', BN+':frac_work', 'ht_out'])\n self.declare_partials('trq', [BN+':frac_W', BN+':frac_work'])\n\n def compute(self, inputs, outputs):\n\n Pt_in = inputs['Pt_in']\n Pt_out = inputs['Pt_out']\n ht_in = inputs['ht_in']\n ht_out = inputs['ht_out']\n W_in = inputs['W_in']\n\n # calculate flow and power without bleed flows\n outputs['W_out'] = W_in\n outputs['power'] = W_in * (ht_in - ht_out) * BTU_s2HP\n\n # calculate bleed specific outputs and modify exit flow and power\n for BN in self.options['bleed_names']:\n BN_stat_W = BN + ':stat:W'\n BN_ht = BN + ':ht'\n\n stat_W = W_in * inputs[BN + ':frac_W']\n outputs[BN + ':Pt'] = Pt_in + inputs[BN + ':frac_P'] * (Pt_out - Pt_in)\n ht = ht_in + inputs[BN + ':frac_work'] * (ht_out - ht_in)\n\n outputs['W_out'] -= stat_W\n outputs['power'] -= stat_W * (ht - ht_out) * BTU_s2HP\n outputs[BN_stat_W] = stat_W\n outputs[BN_ht] = ht\n\n # calculate torque based on revised power and shaft speed\n outputs['trq'] = HP_per_RPM_to_FT_LBF * outputs['power'] / inputs['Nmech']\n\n def compute_partials(self, inputs, J):\n\n ht_in = inputs['ht_in']\n ht_out = inputs['ht_out']\n W_in = inputs['W_in']\n Nmech = inputs['Nmech']\n delta_Pt = inputs['Pt_out'] - inputs['Pt_in']\n\n # Jacobian elements without bleed flows\n dW_out_dW_in = 1.0\n\n dpower_dW_in = (ht_in - ht_out) * BTU_s2HP\n dpower_dht_in = W_in * BTU_s2HP\n dpower_dht_out = -W_in * BTU_s2HP\n\n dtrq_dW_in = (ht_in - ht_out) * BTU_s2HP * HP_per_RPM_to_FT_LBF / Nmech\n dtrq_dht_in = W_in * BTU_s2HP * HP_per_RPM_to_FT_LBF / Nmech\n dtrq_dht_out = -W_in * BTU_s2HP * HP_per_RPM_to_FT_LBF / Nmech\n dtrq_dNmech = -W_in * (ht_in - ht_out) * BTU_s2HP * HP_per_RPM_to_FT_LBF * Nmech**-2.\n\n # Jacobian elements and modifications due to bleed flows\n for BN in self.options['bleed_names']:\n BN_frac_W = BN + ':frac_W'\n BN_frac_work = BN + ':frac_work'\n BN_Pt = BN + ':Pt'\n BN_stat_W = BN + ':stat:W'\n BN_frac_P = BN + ':frac_P'\n BN_ht = BN + ':ht'\n\n frac_W = inputs[BN_frac_W]\n frac_work = inputs[BN_frac_work]\n frac_P = inputs[BN_frac_P]\n\n dW_out_dW_in -= frac_W\n J['W_out', BN_frac_W] = -W_in\n\n dpower_dW_in -= frac_W * (1.0 - frac_work) * (ht_in - ht_out) * BTU_s2HP\n dpower_dht_in -= W_in * frac_W * (1.0 - frac_work) * BTU_s2HP\n dpower_dht_out -= -W_in * frac_W * (1.0 - frac_work) * BTU_s2HP\n J['power', BN_frac_W] = -W_in * (1.0 - frac_work) * (ht_in - ht_out) * BTU_s2HP\n J['power', BN_frac_work] = W_in * frac_W * (ht_in - ht_out) * BTU_s2HP\n\n J[BN_stat_W, 'W_in'] = frac_W\n J[BN_stat_W, BN_frac_W] = W_in\n\n J[BN_Pt, 'Pt_in'] = 1.0 - frac_P\n J[BN_Pt, BN_frac_P] = delta_Pt\n J[BN_Pt, 'Pt_out'] = frac_P\n\n J[BN_ht, 'ht_in'] = 1.0 - frac_work\n J[BN_ht, BN_frac_work] = ht_out - ht_in\n J[BN_ht, 'ht_out'] = frac_work\n\n dtrq_dW_in -= frac_W * (1.0 - frac_work) * (\n ht_in - ht_out) * BTU_s2HP * HP_per_RPM_to_FT_LBF / Nmech\n dtrq_dht_in -= W_in * frac_W * (1.0 - frac_work) * BTU_s2HP * \\\n HP_per_RPM_to_FT_LBF / Nmech\n dtrq_dht_out -= -W_in * frac_W * (1.0 - frac_work) * BTU_s2HP * \\\n HP_per_RPM_to_FT_LBF / Nmech\n J['trq', BN_frac_W] = -W_in * (1.0 - frac_work) * (\n ht_in - ht_out) * BTU_s2HP * HP_per_RPM_to_FT_LBF / Nmech\n J['trq', BN_frac_work] = W_in * frac_W * (ht_in - ht_out) * \\\n BTU_s2HP * HP_per_RPM_to_FT_LBF / Nmech\n dtrq_dNmech -= -W_in * frac_W * (1.0 - frac_work) * (\n ht_in - ht_out) * BTU_s2HP * HP_per_RPM_to_FT_LBF * Nmech**-2\n\n J['W_out', 'W_in'] = dW_out_dW_in\n J['power', 'W_in'] = dpower_dW_in\n J['power', 'ht_in'] = dpower_dht_in\n J['power', 'ht_out'] = dpower_dht_out\n J['trq', 'W_in'] = dtrq_dW_in\n J['trq', 'ht_in'] = dtrq_dht_in\n J['trq', 'ht_out'] = dtrq_dht_out\n J['trq', 'Nmech'] = dtrq_dNmech\n\nclass EnthalpyRise(om.ExplicitComponent):\n \"\"\"Calculates enthalpy rise across a compressor\"\"\"\n\n def setup(self):\n\n self.add_input('ideal_ht', val=2.0, units='Btu/lbm',\n desc='ideal exit total enthalpy')\n self.add_input('inlet_ht', val=1.0, units='Btu/lbm',\n desc='entrance total enthalpy')\n self.add_input('eff', val=0.5, desc='design efficiency')\n\n self.add_output('ht_out', shape=1, units='Btu/lbm',\n desc='exit total enthalpy')\n\n self.declare_partials('ht_out', '*')\n\n def compute(self, inputs, outputs):\n inlet_ht = inputs['inlet_ht']\n outputs['ht_out'] = (inputs['ideal_ht'] - inlet_ht) / inputs['eff'] + inlet_ht\n\n def compute_partials(self, inputs, J):\n eff = inputs['eff']\n\n J['ht_out', 'ideal_ht'] = 1. / eff\n J['ht_out', 'inlet_ht'] = 1 - 1. / eff\n J['ht_out', 'eff'] = - (inputs['ideal_ht'] -\n inputs['inlet_ht']) * eff**(-2)\n\n\nclass PressureRise(om.ExplicitComponent):\n \"\"\"A Component that calculates ...\"\"\"\n\n def setup(self):\n self.add_input('PR', 3.0, desc=\"design pressure ratio\")\n self.add_input('Pt_in', 5.0, units='lbf/inch**2',\n desc=\"incomming total pressure\")\n\n self.add_output('Pt_out', shape=1, lower=1e-5,\n units='lbf/inch**2', desc=\"exit total pressure\")\n\n self.declare_partials('Pt_out', '*')\n\n def compute(self, inputs, outputs):\n outputs['Pt_out'] = inputs['PR'] * inputs['Pt_in']\n\n def compute_partials(self, inputs, J):\n J['Pt_out', 'Pt_in'] = inputs['PR']\n J['Pt_out', 'PR'] = inputs['Pt_in']\n\n\nclass Compressor(om.Group):\n \"\"\"\n Calculates pressure and temperature rise of a flow through a non-ideal compressors,\n using turbomachinery performance maps.\n\n --------------\n Flow Stations\n --------------\n Fl_I\n Fl_O\n\n -------------\n Design\n -------------\n inputs\n --------\n map.PRdes\n map.effDes\n map.RlineMap\n alphaMap\n MN\n\n outputs\n --------\n s_PRdes\n s_WcDes\n s_effDes\n s_NcDes\n\n -------------\n Off-Design\n -------------\n inputs\n --------\n s_PRdes\n s_WcDes\n s_effDes\n s_NcDes\n\n outputs\n --------\n Wc\n PR\n eff_poly\n Nc\n power\n map.RlineMap\n map.readmap.NcMap\n \"\"\"\n\n def initialize(self):\n self.options.declare('map_data', default=NCP01,\n desc='data container for raw compressor map data')\n self.options.declare('thermo_data', default=species_data.janaf,\n desc='thermodynamic data set', recordable=False)\n self.options.declare('elements', default=AIR_ELEMENTS,\n desc='set of elements present in the flow')\n self.options.declare('statics', default=True,\n desc='If True, calculate static properties.')\n self.options.declare('design', default=True,\n desc='Switch between on-design and off-design calculation.')\n self.options.declare('bleed_names', types=(list,tuple), desc='list of names for the bleed ports',\n default=[])\n self.options.declare('map_interp_method', default='slinear',\n desc='Method to use for map interpolation. \\\n Options are `slinear`, `cubic`, `quintic`.')\n self.options.declare('map_extrap', default=False, desc='Switch to allow extrapoloation off map')\n\n self.default_des_od_conns = [\n # (design src, off-design target)\n ('s_Wc', 's_Wc'),\n ('s_PR', 's_PR'),\n ('s_eff', 's_eff'), \n ('s_Nc', 's_Nc'), \n ('Fl_O:stat:area', 'area')\n ]\n\n\n\n def setup(self):\n #(self, mapclass=NCP01map(), design=True, thermo_data=species_data.janaf, elements=AIR_ELEMENTS, bleeds=[],statics=True):\n\n map_data = self.options['map_data']\n interp_method = self.options['map_interp_method']\n map_extrap = self.options['map_extrap']\n # self.linear_solver = ScipyGMRES()\n # self.linear_solver.options['atol'] = 2e-8\n # self.linear_solver.options['maxiter'] = 100\n # self.linear_solver.options['restart'] = 100\n\n # self.nonlinear_solver = Newton()\n # self.nonlinear_solver.options['utol'] = 1e-9\n\n design = self.options['design']\n bleeds = self.options['bleed_names']\n thermo_data = self.options['thermo_data']\n elements = self.options['elements']\n statics = self.options['statics']\n\n num_element = len(elements)\n\n # Create inlet flow station\n flow_in = FlowIn(fl_name='Fl_I')\n self.add_subsystem('flow_in', flow_in, promotes_inputs=['Fl_I:*'])\n\n self.add_subsystem('corrinputs', CorrectedInputsCalc(),\n promotes_inputs=(\n 'Nmech', ('W_in', 'Fl_I:stat:W'),\n ('Pt', 'Fl_I:tot:P'), ('Tt', 'Fl_I:tot:T')),\n promotes_outputs=('Nc', 'Wc'))\n\n map_calcs = CompressorMap(map_data=self.options['map_data'], design=design,\n interp_method=interp_method, extrap=map_extrap)\n self.add_subsystem('map', map_calcs,\n promotes=['s_Nc','s_eff','s_Wc','s_PR','Nc','Wc',\n 'PR','eff','SMN','SMW'])\n\n # Calculate pressure rise across compressor\n self.add_subsystem('press_rise', PressureRise(), promotes_inputs=[\n 'PR', ('Pt_in', 'Fl_I:tot:P')])\n\n # Calculate ideal flow station properties\n ideal_flow = Thermo(mode='total_SP', \n method='CEA', \n thermo_kwargs={'elements':elements, \n 'spec':thermo_data})\n self.add_subsystem('ideal_flow', ideal_flow,\n promotes_inputs=[('S', 'Fl_I:tot:S'),\n ('composition', 'Fl_I:tot:composition')])\n self.connect(\"press_rise.Pt_out\", \"ideal_flow.P\")\n\n # Calculate enthalpy rise across compressor\n self.add_subsystem(\"enth_rise\", EnthalpyRise(),\n promotes_inputs=['eff', ('inlet_ht', 'Fl_I:tot:h')])\n self.connect(\"ideal_flow.h\", \"enth_rise.ideal_ht\")\n\n # Calculate real flow station properties\n real_flow = Thermo(mode='total_hP', fl_name='Fl_O:tot', \n method='CEA', \n thermo_kwargs={'elements':elements, \n 'spec':thermo_data})\n self.add_subsystem('real_flow', real_flow,\n promotes_inputs=[\n ('composition', 'Fl_I:tot:composition')],\n promotes_outputs=['Fl_O:tot:*'])\n self.connect(\"enth_rise.ht_out\", \"real_flow.h\")\n self.connect(\"press_rise.Pt_out\", \"real_flow.P\")\n #clculate Polytropic Efficiency\n self.add_subsystem('eff_poly_calc', eff_poly_calc(),\n promotes_inputs=[('PR','PR'),\n ('S_in','Fl_I:tot:S'),\n ('S_out','Fl_O:tot:S'),\n # ('Cp','Fl_I:tot:Cp'),\n # ('Cv','Fl_I:tot:Cv'),\n ('Rt', 'Fl_I:tot:R')],\n promotes_outputs=['eff_poly'] )\n\n # Calculate shaft power consumption\n blds_pwr = BleedsAndPower(bleed_names=bleeds)\n bld_inputs = ['frac_W', 'frac_P', 'frac_work']\n bld_in_vars = ['{0}:{1}'.format(\n bn, in_name) for bn, in_name in itertools.product(bleeds, bld_inputs)]\n bld_out_globs = ['{}:*'.format(bn) for bn in bleeds]\n\n self.add_subsystem('blds_pwr', blds_pwr,\n promotes_inputs=['Nmech', ('W_in', 'Fl_I:stat:W'),\n ('ht_in', 'Fl_I:tot:h'),\n ('Pt_in', 'Fl_I:tot:P'),\n ('Pt_out', 'Fl_O:tot:P'), ] + bld_in_vars,\n promotes_outputs=['power', 'trq', 'W_out'] + bld_out_globs)\n self.connect('enth_rise.ht_out', 'blds_pwr.ht_out')\n\n bleed_names = []\n for BN in bleeds:\n\n bleed_names.append(BN + '_flow')\n bleed_flow = Thermo(mode='total_hP', fl_name=BN + \":tot\", \n method='CEA', \n thermo_kwargs={'elements':elements, \n 'spec':thermo_data})\n self.add_subsystem(BN + '_flow', bleed_flow,\n promotes_inputs=[\n ('composition', 'Fl_I:tot:composition')],\n promotes_outputs=['{}:tot:*'.format(BN)])\n self.connect(BN + ':ht', BN + \"_flow.h\")\n self.connect(BN + ':Pt', BN + \"_flow.P\")\n\n\n if statics:\n if design:\n # Calculate static properties\n out_stat = Thermo(mode='static_MN', fl_name='Fl_O:stat', \n method='CEA', \n thermo_kwargs={'elements':elements, \n 'spec':thermo_data})\n self.add_subsystem('out_stat', out_stat,\n promotes_inputs=[\n 'MN', ('composition', 'Fl_I:tot:composition')],\n promotes_outputs=['Fl_O:stat:*'])\n self.connect('Fl_O:tot:S', 'out_stat.S')\n self.connect('Fl_O:tot:h', 'out_stat.ht')\n self.connect('W_out', 'out_stat.W')\n self.connect('Fl_O:tot:P', 'out_stat.guess:Pt')\n self.connect('Fl_O:tot:gamma', 'out_stat.guess:gamt')\n\n else: # Calculate static properties\n out_stat = Thermo(mode='static_A', fl_name='Fl_O:stat', \n method='CEA', \n thermo_kwargs={'elements':elements, \n 'spec':thermo_data})\n self.add_subsystem('out_stat', out_stat,\n promotes_inputs=[\n 'area', ('composition', 'Fl_I:tot:composition')],\n promotes_outputs=['Fl_O:stat:*'])\n\n self.connect('Fl_O:tot:S', 'out_stat.S')\n self.connect('Fl_O:tot:h', 'out_stat.ht')\n self.connect('W_out', 'out_stat.W')\n self.connect('Fl_O:tot:P', 'out_stat.guess:Pt')\n self.connect('Fl_O:tot:gamma', 'out_stat.guess:gamt')\n\n self.set_order(['flow_in', 'corrinputs', 'map',\n 'press_rise','ideal_flow', 'enth_rise',\n 'real_flow','eff_poly_calc' ,'blds_pwr',] \n + bleed_names + ['out_stat'])\n\n else:\n self.add_subsystem('W_passthru', PassThrough('W_out',\n 'Fl_O:stat:W',\n 1.0,\n units=\"lbm/s\"),\n promotes=['*'])\n self.set_order(['flow_in', 'corrinputs', 'map',\n 'press_rise','ideal_flow', 'enth_rise',\n 'real_flow','eff_poly_calc' , 'blds_pwr'] \n + bleed_names + ['W_passthru'])\n\n\n # define the group level defaults\n self.set_input_defaults('Fl_I:FAR', val=0., units=None)\n self.set_input_defaults('PR', val=2., units=None)\n self.set_input_defaults('eff', val=0.99, units=None)\n\n # if not design: \n # self.set_input_defaults('area', val=1, units='inch**2')\n\n"
] | [
[
"numpy.log"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lichangao1826/ml-contest | [
"6c5350a0006d79b536df52215d18a989875135e1",
"6c5350a0006d79b536df52215d18a989875135e1"
] | [
"infer/data_fountain_529_ner.py",
"run/data_fountain_529_ner/predict.py"
] | [
"from paddlenlp.transformers import PretrainedTokenizer\nfrom paddlenlp.datasets import MapDataset\nfrom paddlenlp.data import Stack, Tuple, Pad\nfrom paddle import nn\nfrom dotmap import DotMap\nfrom functools import partial\nfrom utils.utils import create_data_loader, load_label_vocab\nimport numpy as np\nimport paddle\nimport os\n\n\nclass DataFountain529NerInfer(object):\n\n def __init__(self,\n model: nn.Layer,\n tokenizer: PretrainedTokenizer,\n test_ds: MapDataset,\n config: DotMap,\n model_params_path: str):\n self.model = model\n self.tokenizer = tokenizer\n self.test_ds = test_ds\n self.logger = config.logger\n self.config = config\n self._gen_data_loader(config)\n self._load_model(model_params_path)\n\n def _gen_data_loader(self, config):\n label_vocab = load_label_vocab(config.label_list)\n self.no_entity_id = label_vocab[\"O\"]\n\n # 将数据处理成模型可读入的数据格式\n trans_func = partial(\n self.convert_example,\n tokenizer=self.tokenizer,\n max_seq_len=config.max_seq_len)\n\n batchify_fn = lambda samples, fn=Tuple(\n Pad(axis=0, pad_val=self.tokenizer.pad_token_id, dtype='int32'), # input_ids\n Pad(axis=0, pad_val=self.tokenizer.pad_token_type_id, dtype='int32'), # token_type_ids\n Stack(dtype='int64'), # seq_len\n Stack(dtype='int64'), # qid\n ): [data for data in fn(samples)]\n\n self.test_data_loader = create_data_loader(\n self.test_ds,\n mode='test',\n batch_size=config.batch_size,\n batchify_fn=batchify_fn,\n trans_fn=trans_func)\n\n def _load_model(self, model_params_path):\n try:\n # 加载模型参数\n state_dict = paddle.load(model_params_path)\n self.model.set_dict(state_dict)\n self.logger.info(\"Loaded parameters from {}\".format(model_params_path))\n except Exception as e:\n raise RuntimeError(\"Loaded parameters error from {}: {}\".format(model_params_path, e))\n\n @paddle.no_grad()\n def predict(self):\n # 切换 model 模型为评估模式,关闭 dropout 等随机因素\n self.model.eval()\n\n result = []\n id2label = dict(enumerate(self.config.label_list))\n for step, batch in enumerate(self.test_data_loader):\n input_ids, token_type_ids, lens, qids = batch\n logits = self.model(input_ids, token_type_ids)\n pred = paddle.argmax(logits, axis=-1)\n\n for i, end in enumerate(lens):\n tags = [id2label[x.numpy()[0]] for x in pred[i][1:end - 1]]\n qid = qids[i].numpy()[0]\n result.append([qid, tags])\n return result\n\n @staticmethod\n def parse_decodes(input_words, id2label, decodes, lens):\n decodes = [x for batch in decodes for x in batch]\n lens = [x for batch in lens for x in batch]\n\n outputs = []\n for idx, end in enumerate(lens):\n sent = \"\".join(input_words[idx]['tokens'])\n tags = [id2label[x] for x in decodes[idx][1:end - 1]]\n outputs.append([sent, tags])\n\n return outputs\n\n @staticmethod\n def convert_example(example, tokenizer, max_seq_len):\n tokens, qid = example[\"tokens\"], example[\"qid\"]\n encoded_inputs = tokenizer(text=tokens,\n max_seq_len=max_seq_len,\n return_length=True,\n is_split_into_words=True)\n\n return tuple([np.array(x, dtype=\"int64\") for x in [encoded_inputs[\"input_ids\"],\n encoded_inputs[\"token_type_ids\"],\n encoded_inputs[\"seq_len\"],\n qid]])\n",
"from model.data_fountain_529_ner import get_model_and_tokenizer\nfrom data_process.data_fountain_529_ner import DataFountain529NerDataProcessor\nfrom dataset.data_fountain_529_ner import DataFountain529NerDataset\nfrom infer.data_fountain_529_ner import DataFountain529NerInfer\nfrom utils.config_utils import get_config, CONFIG_PATH\nfrom utils.utils import mkdir_if_not_exist\nfrom dotmap import DotMap\nfrom scipy import stats\nimport csv\nimport os\n\n\ndef predict():\n config = get_config(os.path.join(CONFIG_PATH, \"data_fountain_529_ner.json\"), \"predict\")\n\n # 原始数据预处理\n data_processor = DataFountain529NerDataProcessor(config)\n data_processor.process()\n\n # 获取全部分类标签\n config.label_list = DataFountain529NerDataset.get_labels()\n\n # 使用配置中的所有模型进行融合\n fusion_result = []\n for model_name, weight in config.model_params.items():\n\n # 计算单模型 K 折交叉验证的结果\n k_fold_result = []\n for fold in range(config.k_fold or 1):\n model_path = os.path.join(config.base_path, model_name, 'model_{}.pdparams'.format(fold))\n fold_result = single_model_predict(config, model_name, model_path)\n k_fold_result.append(fold_result)\n\n # 融合 k 折模型的预测结果\n merge_result = merge_k_fold_result(k_fold_result)\n\n # 将当前模型及对应权重保存\n fusion_result.append([merge_result, weight])\n\n # 融合所有模型的预测结果\n result = merge_fusion_result(fusion_result)\n\n # 写入预测结果\n res_dir = os.path.join(config.res_dir, config.model_name)\n mkdir_if_not_exist(res_dir)\n with open(os.path.join(res_dir, \"result.csv\"), \"w\", encoding=\"utf-8\") as f:\n writer = csv.writer(f)\n writer.writerow([\"id\", \"BIO_anno\"])\n for line in result:\n qid, tags = line\n writer.writerow([qid, \" \".join(tags)])\n\n\ndef merge_fusion_result(fusion_result):\n # TODO: 尝试不同的模型融合方法\n return fusion_result[0][0]\n\n\ndef single_model_predict(config: DotMap, model_name: str, model_path: str):\n # 获取测试集\n [test_ds] = DataFountain529NerDataset(config).load_data(splits=['test'], lazy=False)\n\n # 加载 model 和 tokenizer\n model, tokenizer, config = get_model_and_tokenizer(model_name, config)\n\n # 获取推断器\n infer = DataFountain529NerInfer(model,\n tokenizer=tokenizer,\n test_ds=test_ds,\n config=config,\n model_params_path=model_path)\n # 开始预测\n result = infer.predict()\n\n return result\n\n\ndef merge_k_fold_result(k_fold_result):\n merge_result = {}\n for fold_result in k_fold_result:\n for line in fold_result:\n qid, tags = line[0], line[1]\n if qid not in merge_result:\n merge_result[qid] = []\n merge_result[qid].append(tags)\n\n result = []\n for qid, tags in merge_result.items():\n merge_tags = stats.mode(tags)[0][0]\n result.append([qid, merge_tags])\n return result\n\n\nif __name__ == \"__main__\":\n predict()\n"
] | [
[
"numpy.array"
],
[
"scipy.stats.mode"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
PaulCzaban/Time-Travel-Rephotography.github.io | [
"5d0ce32a48dfd7156a0f8dfddf0eadbb55b0be52"
] | [
"models/gaussian_smoothing.py"
] | [
"import math\nimport numbers\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\nclass GaussianSmoothing(nn.Module):\n \"\"\"\n Apply gaussian smoothing on a\n 1d, 2d or 3d tensor. Filtering is performed seperately for each channel\n in the input using a depthwise convolution.\n Arguments:\n channels (int, sequence): Number of channels of the input tensors. Output will\n have this number of channels as well.\n kernel_size (int, sequence): Size of the gaussian kernel.\n sigma (float, sequence): Standard deviation of the gaussian kernel.\n dim (int, optional): The number of dimensions of the data.\n Default value is 2 (spatial).\n \"\"\"\n def __init__(self, channels, kernel_size, sigma, dim=2):\n super(GaussianSmoothing, self).__init__()\n if isinstance(kernel_size, numbers.Number):\n kernel_size = [kernel_size] * dim\n if isinstance(sigma, numbers.Number):\n sigma = [sigma] * dim\n\n # The gaussian kernel is the product of the\n # gaussian function of each dimension.\n kernel = 1\n meshgrids = torch.meshgrid(\n [\n torch.arange(size, dtype=torch.float32)\n for size in kernel_size\n ]\n )\n for size, std, mgrid in zip(kernel_size, sigma, meshgrids):\n mean = (size - 1) / 2\n kernel *= 1 / (std * math.sqrt(2 * math.pi)) * \\\n torch.exp(-((mgrid - mean) / (2 * std)) ** 2)\n\n # Make sure sum of values in gaussian kernel equals 1.\n kernel = kernel / torch.sum(kernel)\n\n # Reshape to depthwise convolutional weight\n kernel = kernel.view(1, 1, *kernel.size())\n kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))\n\n self.register_buffer('weight', kernel)\n self.groups = channels\n\n if dim == 1:\n self.conv = F.conv1d\n elif dim == 2:\n self.conv = F.conv2d\n elif dim == 3:\n self.conv = F.conv3d\n else:\n raise RuntimeError(\n 'Only 1, 2 and 3 dimensions are supported. Received {}.'.format(dim)\n )\n\n def forward(self, input, stride: int = 1):\n \"\"\"\n Apply gaussian filter to input.\n Arguments:\n input (torch.Tensor): Input to apply gaussian filter on.\n stride for applying conv\n Returns:\n filtered (torch.Tensor): Filtered output.\n \"\"\"\n padding = (self.weight.shape[-1] - 1) // 2\n return self.conv(input, weight=self.weight, groups=self.groups, padding=padding, stride=stride)\n\n"
] | [
[
"torch.exp",
"torch.sum",
"torch.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RoughStochVol/BFGHS17 | [
"f3221e6356c016f0bf54279efcdcbafad28ad1d0"
] | [
"code/BlackScholes.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# ------------------------------------------------------------------------------\n# BLACK-SCHOLES FRAMEWORK\n\n# ------------------------------------------------------------------------------\n# IMPORTS\n\nimport numpy as np\nfrom numpy import inf\nfrom math import sqrt, log, e, pi, isnan\nfrom scipy.stats import norm\nfrom scipy.optimize import brentq\nfrom scipy.integrate import quad\n\n# ------------------------------------------------------------------------------\n# CLASS DEFINITIONS\n\n\nclass Pricer:\n \"\"\"\n Implementation of the usual Black-Scholes Pricer.\n\n May be used to compute European call option prices and some Greeks.\n\n :param flag: either \"c\" for calls or \"p\" for puts\n :param spot_price: spot price of the underlying\n :param strike: strike price\n :param time_to_maturity: time to maturity in years\n :param vol: annualized volatility assumed constant until expiration\n :param risk_free_rate: risk-free interest rate\n :param method: computation method for CDF function: \"f\" for built-in\n formula, \"n\" for numerical integration\n\n :type flag: string\n :type spot_price: float\n :type strike: float\n :type time_to_maturity: float\n :type vol: float\n :type risk_free_rate: float\n :type method: string\n \"\"\"\n\n def __init__(self, flag, spot_price, strike, time_to_maturity, vol,\n risk_free_rate=0, method='f'):\n\n self.flag = flag\n self.S = spot_price\n self.K = strike\n self.T = time_to_maturity\n self.r = risk_free_rate\n self.vol = vol\n self.method = method\n\n self.d1 = 1/(self.vol * sqrt(self.T)) * \\\n (log(self.S) - log(self.K) + (self.r + 1/2 * self.vol**2) *\n self.T)\n\n self.d2 = self.d1 - self.vol * sqrt(self.T)\n\n # If numerical method chosen, compute all quantiles numerically.\n if method == 'n':\n\n self.num_cdf_d1 = quad(norm.pdf, -inf, self.d1)[0]\n self.num_cdf_d2 = quad(norm.pdf, -inf, self.d2)[0]\n self.num_cdf_minus_d1 = quad(norm.pdf, -inf, -self.d1)[0]\n self.num_cdf_minus_d2 = quad(norm.pdf, -inf, -self.d2)[0]\n\n def get_price(self):\n \"\"\"\n Computes the Black-Scholes price for the specified option.\n\n :return: Black-Scholes price\n :rtype: float\n \"\"\"\n\n if self.flag == 'c':\n\n if self.method == \"f\":\n\n price = self.S * norm.cdf(self.d1) - self.K * \\\n e**(-self.r * self.T) * norm.cdf(self.d2)\n\n elif self.method == 'n':\n\n price = self.S * self.num_cdf_d1 - self.K * \\\n e**(-self.r * self.T) * self.num_cdf_d2\n\n elif self.flag == 'p':\n\n if self.method == 'f':\n\n price = self.K * e**(-self.r * self.T) * \\\n norm.cdf(-self.d2) - self.S * norm.cdf(-self.d1)\n\n elif self.method == 'n':\n\n price = self.K * e**(-self.r * self.T) * \\\n self.num_cdf_minus_d2 - self.S * self.num_cdf_minus_d1\n\n return price\n\n def get_price_via_GBM(self, number_paths):\n \"\"\"\n Computes the Black-Scholes price for the specified option via\n simulation of a Geometric Brownian motion.\n\n :param number_paths: number of sample paths\n :type number_paths: int\n\n :return: Black-Scholes price\n :rtype: float\n\n :return: standard deviation of estimator\n :rtype: float\n \"\"\"\n\n W = np.random.randn(number_paths, 1)\n\n S = self.S * np.exp(-0.5 * self.vol**2 * self.T +\n self.vol * sqrt(self.T) * W)\n\n if self.flag == 'c':\n\n payoffs = np.maximum(S - self.K, 0)\n\n price = np.average(payoffs)\n\n std_price = np.std(payoffs)/sqrt(number_paths)\n\n elif self.flag == 'p':\n\n payoffs = np.maximum(self.K - S, 0)\n\n price = np.average(payoffs)\n\n std_price = np.std(payoffs)/sqrt(number_paths)\n\n return price, std_price\n\n def get_delta(self):\n \"\"\"\n Computes the Black-Scholes delta, the derivative of the option price\n with respect to the price of the underlying.\n\n :return: Black-Scholes delta\n :rtype: float\n \"\"\"\n\n if self.flag == 'c':\n\n if self.method == 'f':\n\n return norm.cdf(self.d1)\n\n if self.method == 'n':\n\n return self.num_cdf_d1\n\n elif self.flag == 'p':\n\n if self.method == 'f':\n\n return norm.cdf(self.d1) - 1\n\n if self.method == 'n':\n\n return self.num_cdf_d1 - 1\n\n def get_vega(self):\n \"\"\"\n Computes the Black-Scholes Vega, the derivative of the option price\n with respect to volatility.\n\n :return: Black-Scholes vega\n :rtype: float\n \"\"\"\n\n vega = self.S * norm.pdf(self.d1) * sqrt(self.T)\n\n return vega\n\n\nclass ImpliedVol:\n \"\"\"\n Computes the Black-Scholes implied volatility from a given market/model\n price. For the root-finding, we use Brent's method.\n\n :param flag: either \"c\" for calls or \"p\" for puts\n :param mkt_price: market/model option price to infer the implied vol from\n :param spot_price: spot price of the underlying\n :param strike: strike price\n :param time_to_maturity: time to maturity in years\n :param risk_free_rate: risk-free interest rate\n :param lower_bound: lower bound of implied volatility\n :param upper_bound: upper bound of implied volatility\n :param maxiter: maximum number of root finding iterations\n :param method: computation method for CDF function: \"f\" for built-in\n formula, \"n\" for numerical integration\n\n :type flag: string\n :type mkt_price: float\n :type spot_price: float\n :type strike: float\n :type time_to_maturity: float\n :type risk_free_rate: float\n :type lower_bound: float\n :type upper_bound: float\n :type maxiter: integer\n :type method: string\n \"\"\"\n\n def __init__(self, flag, mkt_price, spot_price, strike, time_to_maturity,\n lower_bound, upper_bound, risk_free_rate=0, maxiter=1000,\n method='f'):\n\n self.flag = flag\n self.mkt_price = mkt_price\n self.S = spot_price\n self.K = strike\n self.T = time_to_maturity\n self.r = risk_free_rate\n self.a = lower_bound\n self.b = upper_bound\n self.n = maxiter\n self.method = method\n\n def func(self, vol):\n \"\"\"\n Objective function in root-finding problem.\n \"\"\"\n\n p = Pricer(self.flag, self.S, self.K, self.T, vol, self.r, self.method)\n\n return p.get_price() - self.mkt_price\n\n def get(self):\n \"\"\"\n Computes the Black-Scholes implied volatility.\n\n :return: Black-Scholes implied volatility\n :rtype: float\n \"\"\"\n\n if self.mkt_price <= 0:\n\n implied_vol = float('NaN')\n\n else:\n\n implied_vol = brentq(self.func, self.a, self.b, maxiter=self.n)\n\n return implied_vol\n"
] | [
[
"numpy.maximum",
"scipy.stats.norm.cdf",
"scipy.stats.norm.pdf",
"numpy.std",
"numpy.random.randn",
"scipy.optimize.brentq",
"scipy.integrate.quad",
"numpy.average"
]
] | [
{
"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": []
}
] |
CBI-PITT/bil_api | [
"5be7e9d84556dcadade944f4f0c536c4b5798cfa"
] | [
"BrAinPI/old/zarrVDS.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 9 16:26:33 2021\n\n@author: alpha\n\"\"\"\n\nimport os, glob, zarr, warnings\nimport numpy as np\n\nfrom numcodecs import Blosc\ncompressor = Blosc(cname='zstd', clevel=9, shuffle=Blosc.BITSHUFFLE)\n\n# ## Open fullres fmost CH1\n# location = r\"/CBI_Hive/globus/pitt/bil/CH1\"\n# location = r\"h:/globus/pitt/bil/CH1\"\n# fileList = sorted(glob.glob(os.path.join(location,'*_CH1.tif')))\n\n# testImage = io.imread(fileList[0])\n\n# stack = [delayed(io.imread)(x) for x in fileList]\n# stack = [da.from_delayed(x,shape=testImage.shape,dtype=testImage.dtype) for x in stack]\n# imageStack = da.stack(stack)\n\nclass zarrVDS:\n \n def __init__(self, directoryStr, shape=None, dtype=None, chunks=None, compressor=None, ResolutionLevelLock=0):\n \n \n \n assert isinstance(directoryStr,str)\n assert isinstance(shape,tuple)\n assert len(shape) == 5,\"All shapes and chunks must be 5 dimentions TCZYX\"\n assert len(chunks) == 5,\"All shapes and chunks must be 5 dimentions TCZYX\"\n \n self.directoryStr = directoryStr\n self.shape = shape\n self.dtype = dtype\n self.ndim = len(self.shape)\n self.chunks = chunks\n \n # Force chunk dims 0,1 to == 1 for time and color\n if self.chunks[0] != 1:\n warnings.warn('Chunk dim 0 must be 1. Resetting to 1')\n self.chunks = list(self.chunks)\n self.chunks[0] = 1\n if self.chunks[1] != 1:\n warnings.warn('Chunk dim 1 must be 1. Resetting to 1')\n self.chunks = list(self.chunks)\n self.chunks[1] = 1\n self.chunks = tuple(self.chunks)\n \n self.compressor = compressor\n self.ResolutionLevelLock = ResolutionLevelLock\n \n \n # Set defaults\n if self.dtype is None:\n self.dtype = np.float32\n if self.compressor is None:\n self.compressor = Blosc(cname='zstd', clevel=9, shuffle=Blosc.BITSHUFFLE)\n \n # make location dir\n if os.path.exists(self.directoryStr) == False:\n os.makedirs(self.directoryStr)\n \n # Initialize the first and only required array\n self.initArray(0,0,0)\n \n \n def __getitem__(self, key):\n print(key)\n \n # res = self.ResolutionLock\n \n # if isinstance(key,tuple) and len(key) == 6 and isinstance(key[0], int):\n # res = key[0]\n # key = [x for x in key[1::]]\n \n \n # if isinstance(key, int):\n # key = [slice(key)]\n # for _ in range(self.ndim-1):\n # key.append(slice(None))\n # key = tuple(key)\n \n # if isinstance(key,tuple):\n # key = [slice(x) if isinstance(x,int) else x for x in key]\n # while len(key) < self.ndim:\n # key.append(slice(None))\n # key = tuple(key)\n \n # print(key)\n \n origionalKey = key\n res = self.ResolutionLevelLock\n \n if isinstance(key,slice) == False and isinstance(key,int) == False and len(key) == 6:\n res = key[0]\n # if res >= self.ResolutionLevels:\n # raise ValueError('Layer is larger than the number of ResolutionLevels')\n key = tuple([x for x in key[1::]])\n \n ## All slices will be converted to 5 dims and placed into a tuple\n if isinstance(key,slice):\n key = [key]\n \n if isinstance(key, int):\n key = [slice(key)]\n \n ## Convert int/slice mix to a tuple of slices\n elif isinstance(key,tuple):\n key = tuple([slice(x) if isinstance(x,int) else x for x in key])\n \n key = list(key)\n while len(key) < 5:\n key.append(slice(None))\n key = tuple(key)\n \n print(res)\n print(key)\n \n\n ## Convert slice None to int\n newKey = []\n for num, idx in enumerate(key):\n if isinstance(idx.stop, int) and idx.start is None:\n newKey.append(slice(idx.stop,idx.stop+1,idx.step))\n \n ## Need to throw errors here\n if newKey[-1].stop >= self.shape[num]:\n newKey[-1] = slice(newKey[-1].start,self.shape[num]-1,newKey[-1].step)\n \n if newKey[-1].start >= self.shape[num]:\n newKey[-1] = slice(newKey[-1].stop-1,newKey[-1].stop,newKey[-1].step)\n \n if newKey[-1].step is None:\n newKey[-1] = slice(newKey[-1].start,newKey[-1].stop,1)\n else:\n newKey.append(idx)\n \n \n key = newKey\n print(key)\n \n \n \n # if self.cache == None:\n # return getSlice(\n # self, \n # r = res if res is not None else 0,\n # t = sliceFixer(self,key[0],'t',res=res),\n # c = sliceFixer(self,key[1],'c',res=res),\n # z = sliceFixer(self,key[2],'z',res=res),\n # y = sliceFixer(self,key[3],'y',res=res), \n # x = sliceFixer(self,key[4],'x',res=res)\n # )\n # else:\n # return cache(location=self.cache_location,mem_size=self.mem_size,disk_size=self.disk_size)(getSlice)(\n # self, \n # r = res if res is not None else 0,\n # t = sliceFixer(self,key[0],'t',res=res),\n # c = sliceFixer(self,key[1],'c',res=res),\n # z = sliceFixer(self,key[2],'z',res=res),\n # y = sliceFixer(self,key[3],'y',res=res), \n # x = sliceFixer(self,key[4],'x',res=res)\n # )\n \n sliceReturned = getSlice(\n self, \n r = res if res is not None else 0, #Force ResolutionLock of None to be 0 when slicing\n t = sliceFixer(self,key[0],'t',res=res),\n c = sliceFixer(self,key[1],'c',res=res),\n z = sliceFixer(self,key[2],'z',res=res),\n y = sliceFixer(self,key[3],'y',res=res), \n x = sliceFixer(self,key[4],'x',res=res)\n )\n print('Image Slices Requested: {} / Item shape returned: {} \\n'.format(origionalKey,sliceReturned.shape))\n return sliceReturned\n # return getArray(datasetNum=self.datasetNum,res=self.ResolutionLock,key=key)\n \n \n \n \n \n \n \n\n def location(self,r,t,c):\n return os.path.join(self.directoryStr,'{}.{}.{}.zarr'.format(r,t,c))\n \n \n def initArray(self,r,t,c):\n if os.path.exists(self.location(r,t,c)) == False:\n store = zarr.ZipStore(self.location(r,t,c))\n zarr.zeros(shape=self.shape[-2::], chunks=self.chunks[-2::], store=store, dtype=np.uint16,compressor=compressor)\n store.close()\n \n\n\n\ndef getSlice(imsClass,r,t,c,z,y,x):\n \n '''\n IMS stores 3D datasets ONLY with Resolution, Time, and Color as 'directory'\n structure witing HDF5. Thus, data access can only happen accross dims XYZ\n for a specific RTC. \n '''\n \n # incomingSlices = (r,t,c,z,y,x)\n tSize = list(range(imsClass.TimePoints)[t])\n cSize = list(range(imsClass.Channels)[c])\n zSize = len(range(imsClass.metaData[(r,0,0,'shape')][-3])[z])\n ySize = len(range(imsClass.metaData[(r,0,0,'shape')][-2])[y])\n xSize = len(range(imsClass.metaData[(r,0,0,'shape')][-1])[x])\n \n outputArray = np.zeros((len(tSize),len(cSize),zSize,ySize,xSize))\n # chunkRequested = outputArray.shape\n \n with h5py.File(imsClass.filePathComplete, 'r') as hf:\n for idxt, t in enumerate(tSize):\n for idxc, c in enumerate(cSize):\n # print(t)\n # print(c)\n dSetString = locationGenerator(r,t,c,data='data')\n outputArray[idxt,idxc,:,:,:] = hf[dSetString][z,y,x]\n \n \n ''' Some issues here with the output of these arrays. Napari sometimes expects\n 3-dim arrays and sometimes 5-dim arrays which originates from the dask array input representing\n tczyx dimentions of the imaris file. When os.environ[\"NAPARI_ASYNC\"] = \"1\", squeezing\n the array to 3 dimentions works. When ASYNC is off squeese does not work.\n Napari thows an error because it did not get a 3-dim array.\n \n Am I implementing slicing wrong? or does napari have some inconsistancy with the \n dimentions of the arrays that it expects with different loading mechanisms if the \n arrays have unused single dimentions.\n \n Currently \"NAPARI_ASYNC\" = '1' is set to one in the image loader\n Currently File/Preferences/Render Images Asynchronously must be turned on for this plugin to work\n '''\n try:\n # if os.environ[\"NAPARI_ASYNC\"] == '1':\n # while outputArray.shape[0] == 1 and len(outputArray.shape) > 1:\n # outputArray = outputArray[0,:]\n # # sliceOutput = outputArray.shape\n # # print('Incoming Slices: {} / Slice Requested: {} / Slice Output {}'.format(incomingSlices,chunkRequested,sliceOutput))\n # return outputArray\n \n ## Above code only eliminates low single length dims\n ## Squeeze will eliminate ALL single length dims\n if os.environ[\"NAPARI_ASYNC\"] == '1':\n return np.squeeze(outputArray)\n except KeyError:\n pass\n \n # sliceOutput = outputArray.shape\n # print('Incoming Slices: {} / Slice Requested: {} / Slice Output {}'.format(incomingSlices,chunkRequested,sliceOutput))\n return outputArray\n\n\nz = zarrVDS(r\"Y:\\bil\", shape=(1,1,100,3000,3000), dtype=np.uint16,chunks=(2,1,1,1000,1000)) \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] | [
[
"numpy.squeeze"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
GuilhermeBaldo/segqnas | [
"5826a98f1037480e52b69a04d4f8550f2cadf920"
] | [
"evaluation.py"
] | [
"\"\"\" Copyright (c) 2020, Daniela Szwarcman and IBM Research\n * Licensed under The MIT License [see LICENSE for details]\n\n - Distribute population eval using MPI.\n\"\"\"\n\nimport time\n\nimport numpy as np\nfrom mpi4py import MPI\n\nfrom cnn import train\nfrom util import init_log\n\n\nclass EvalPopulation(object):\n def __init__(self, params, data_info, fn_dict, log_level='INFO'):\n \"\"\" Initialize EvalPopulation.\n\n Args:\n params: dictionary with parameters.\n data_info: one of input.*Info objects.\n fn_dict: dict with definitions of the functions (name and parameters);\n format --> {'fn_name': ['FNClass', {'param1': value1, 'param2': value2}]}.\n log_level: (str) one of \"INFO\", \"DEBUG\" or \"NONE\".\n \"\"\"\n\n self.train_params = params\n self.data_info = data_info\n self.fn_dict = fn_dict\n self.timeout = 9000\n self.logger = init_log(log_level, name=__name__)\n self.comm = MPI.COMM_WORLD\n self.size = self.comm.Get_size()\n self.num_workers = self.size - 1\n\n def __call__(self, decoded_params, decoded_nets, generation):\n \"\"\" Train and evaluate *decoded_nets* using the parameters defined in *decoded_params*.\n\n Args:\n decoded_params: list containing the dict of values of evolved parameters\n (size = num_individuals).\n decoded_nets: list containing the lists of network layers descriptions\n (size = num_individuals).\n generation: (int) generation number.\n\n Returns:\n numpy array containing evaluations results of each model in *net_lists*.\n \"\"\"\n\n pop_size = len(decoded_nets)\n\n assert pop_size == self.size\n\n evaluations = np.empty(shape=(pop_size,))\n\n try:\n self.send_data(decoded_params, decoded_nets, generation)\n\n # After sending tasks, Master starts its own work...\n evaluations[0] = train.fitness_calculation(id_num=f'{generation}_0',\n data_info=self.data_info,\n params={**self.train_params,\n **decoded_params[0]},\n fn_dict=self.fn_dict,\n net_list=decoded_nets[0])\n\n # Master starts receiving results...\n self.receive_data(results=evaluations)\n\n except TimeoutError:\n self.comm.Abort()\n\n return evaluations\n\n def check_timeout(self, t0, requests):\n \"\"\" Check if communication has reached self.timeout and raise an error if it did.\n\n Args:\n t0: initial time as time.time() instance.\n requests: list of MPI.Request.\n \"\"\"\n\n t1 = time.time()\n if t1 - t0 >= self.timeout:\n pending = [i + 1 for i in range(len(requests)) if requests[i] is not None]\n self.logger.error(f'Pending request operations: {pending}')\n raise TimeoutError()\n\n def send_data(self, decoded_params, decoded_nets, generation):\n \"\"\" Send data to all workers.\n\n Args:\n decoded_params: list containing the dict of values of evolved parameters\n (size = num_individuals).\n decoded_nets: list containing the lists of network layers descriptions\n (size = num_individuals).\n generation: (int) generation number.\n \"\"\"\n\n requests = [None] * self.num_workers\n\n for worker in range(1, self.size):\n id_num = f'{generation}_{worker}'\n\n args = {'id_num': id_num,\n 'data_info': self.data_info,\n 'params': {**self.train_params, **decoded_params[worker]},\n 'fn_dict': self.fn_dict,\n 'net_list': decoded_nets[worker]}\n\n requests[worker - 1] = self.comm.isend(args, dest=worker, tag=11)\n\n t0 = time.time()\n\n # Checking if all messages were sent\n while not all(r is None for r in requests):\n for i in range(self.num_workers):\n if requests[i] is not None:\n check_result = requests[i].test()\n if check_result[0]:\n self.logger.info(f'Sent message to worker {i+1}!')\n requests[i] = None\n\n self.check_timeout(t0, requests)\n\n def receive_data(self, results):\n \"\"\" Receive data from all workers.\n\n Args:\n results: ndarray that will store all results.\n\n Returns:\n modified ndarray containing the received results.\n \"\"\"\n\n requests = [self.comm.irecv(source=i, tag=10) for i in range(1, self.size)]\n\n t0 = time.time()\n\n while not all(r is None for r in requests):\n for i in range(self.num_workers):\n if requests[i] is not None:\n check_result = requests[i].test()\n if check_result[0]:\n self.logger.info(f'Received message from worker {i+1}!')\n results[i+1] = check_result[1]\n requests[i] = None\n\n self.check_timeout(t0, requests)\n\n return results\n\n"
] | [
[
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
marwahaha/QSpectra | [
"328a4f78af1473d65c011eb99b903c7f0ef1db32"
] | [
"qspectra/dynamics/liouville_space.py"
] | [
"import itertools\nimport numpy as np\nfrom scipy.sparse import lil_matrix, csr_matrix\nfrom .base import DynamicalModel, SystemOperator\nfrom ..operator_tools import (SubspaceError, n_excitations,\n full_liouville_subspace)\nfrom ..utils import memoized_property\n\ndef liouville_subspace_index(liouville_subspace, full_subspace, n_sites,\n n_vibrational_states=1):\n \"\"\"\n Returns indices of the full vectorized density operator in the given\n subspace that are included in the indicated liouville subspace\n \"\"\"\n total_states = 0\n cuts = {}\n exc_n_states = n_excitations(n_sites, n_vibrational_states)\n for excitation, n_states in zip('gef', exc_n_states):\n if excitation in full_subspace:\n cuts[excitation] = np.arange(n_states) + total_states\n total_states += n_states\n keep = np.zeros((total_states, total_states))\n for row, col in liouville_subspace.split(','):\n try:\n keep[np.ix_(cuts[row], cuts[col])] = 1\n except KeyError:\n raise SubspaceError(\"{}{} not in subspace '{}'\".format(\n row, col, full_subspace))\n return matrix_to_ket_vec(keep).nonzero()[0]\n\n\ndef all_liouville_subspaces(hilbert_subspace):\n \"\"\"\n Given a Hilbert subspace, return a comma separated list with all included\n Liouville subspaces\n\n Example\n -------\n >>> all_liouville_subspaces('ge')\n 'gg,ge,eg,ee'\n \"\"\"\n return ','.join(''.join(s) for s\n in itertools.product(hilbert_subspace, repeat=2))\n\n\ndef matrix_to_ket_vec(matrix):\n \"\"\"\n Transform an operator from matrix to vectorized (stacked column) form\n \"\"\"\n return matrix.reshape((-1), order='F')\n\n\ndef ket_vec_to_matrix(ket_vec):\n \"\"\"\n Transform an operator vectorized (stacked column) form into a matrix\n \"\"\"\n N = int(np.sqrt(np.prod(ket_vec.shape)))\n return ket_vec.reshape((N, N), order='F')\n\n\ndef matrix_to_bra_vec(matrix):\n \"\"\"\n Transform an operator from matrix to vectorized (stacked row) form\n \"\"\"\n return matrix.reshape((-1), order='C')\n\n\ndef tensor_to_super(tensor_operator):\n \"\"\"\n Transform a linear operator on density matrices from tensor to super-\n operator form\n\n Parameters\n ----------\n tensor_operator : np.ndarray\n Four dimensional tensor describing the linear operator on a density\n matrix.\n\n Returns\n -------\n super_operator : np.ndarray\n Two dimensional super-operator giving the equivalent linear operator\n that acts on liouville state vectors.\n \"\"\"\n N = tensor_operator.shape[0]\n super_operator = np.empty((N ** 2, N ** 2), dtype=tensor_operator.dtype)\n for i in xrange(N):\n for j in xrange(N):\n super_operator[i::N, j::N] = tensor_operator[i, :, j, :]\n return super_operator\n\n\ndef super_commutator_matrix(operator):\n \"\"\"\n Returns the super-operator that when applied to a vectorized density\n operator is equivalent to the commutator of the operator and the density\n matrix\n \"\"\"\n return super_left_matrix(operator) - super_right_matrix(operator)\n\n\ndef super_left_matrix(operator):\n \"\"\"\n Returns the super-operator that when applied to a vectorized density\n operator is equivalent to the matrix product of the operator times the\n density matrix\n\n Reference\n ---------\n Havel, T. F. Robust procedures for converting among Lindblad, Kraus and\n matrix representations of quantum dynamical semigroups. J Math. Phys.\n 44, 534-557 (2003).\n \"\"\"\n I = np.identity(len(operator))\n return np.kron(I, operator)\n\n\ndef super_right_matrix(operator):\n \"\"\"\n Returns the super-operator that when applied to a vectorized density\n operator is equivalent to the matrix product of the density matrix times the\n operator\n\n Reference\n ---------\n Havel, T. F. Robust procedures for converting among Lindblad, Kraus and\n matrix representations of quantum dynamical semigroups. J Math. Phys.\n 44, 534-557 (2003).\n \"\"\"\n I = np.identity(len(operator))\n return np.kron(operator.T, I)\n\n\ndef make_sparse(make_super_op):\n def make_sparse_super_op(op):\n return lil_matrix(make_super_op(op))\n return make_sparse_super_op\n\n@make_sparse\ndef super_right_sparse_matrix(operator):\n return super_right_matrix(operator)\n\n@make_sparse\ndef super_left_sparse_matrix(operator):\n return super_left_matrix(operator)\n\n@make_sparse\ndef super_commutator_sparse_matrix(operator):\n return super_commutator_matrix(operator)\n\nclass LiouvilleSpaceOperator(SystemOperator):\n \"\"\"\n Parameters\n ----------\n operator : np.ndarray\n Matrix representation of the operator in the Hilbert subspace of\n `dynamical_model`.\n liouv_subspace_map : string\n String in the form 'eg,fe->gg,ee' indicating the mapping between\n Liouville subspaces on which the operator should act. Optionally,\n only one Liouville subspace may be provided (e.g., a string of the\n form 'eg,fe'), in which case the super operator is assumed to map\n from and to the same subspace.\n dynamical_model : LiouvilleSpaceModel\n The dynamical model on which this operator acts.\n \"\"\"\n def __init__(self, operator, liouv_subspace_map, dynamical_model):\n self.operator = operator\n liouv_subspaces = (liouv_subspace_map.split('->')\n if '->' in liouv_subspace_map\n else [liouv_subspace_map, liouv_subspace_map])\n self.from_indices, self.to_indices = \\\n map(dynamical_model.liouville_subspace_index, liouv_subspaces)\n self.super_op_mesh = np.ix_(self.to_indices, self.from_indices)\n\n @property\n def bra_vector(self):\n # cast the operator to a complex vector so integrate methods handle it\n # properly\n operator = np.asanyarray(self.operator, dtype=complex)\n return matrix_to_bra_vec(operator)[self.from_indices]\n\n @memoized_property\n def _super_left_matrix(self):\n # save the matrix for left multiplication so it can be used by both the\n # left_multply and expectation_value methods\n return super_left_matrix(self.operator)[self.super_op_mesh]\n\n @property\n def left_multiply(self):\n return self._super_left_matrix.dot\n\n @memoized_property\n def right_multiply(self):\n return super_right_matrix(self.operator)[self.super_op_mesh].dot\n\n @memoized_property\n def commutator(self):\n return super_commutator_matrix(self.operator)[self.super_op_mesh].dot\n\n @memoized_property\n def expectation_value(self):\n # Derivation:\n # tr M rho = tr super_left(M) vec(rho)\n # = tr_M vec(rho)\n # = sum_{ij} vec(I)_i S_ij v_j\n # => (tr_M)_j = sum_i vec(I)_i S_ij\n tr = np.identity(len(self.operator)).reshape(-1)[self.to_indices]\n return tr.dot(self._super_left_matrix).dot\n\n\nclass LiouvilleSpaceModel(DynamicalModel):\n \"\"\"\n DynamicalModel for Liouville space dynamics\n\n Subclasses must override the `evolution_super_operator` property or the\n `equation_of_motion` method.\n\n Parameters\n ----------\n evolve_basis : string, optional\n Either 'site' or 'eigen'. Specifies whether to calculate\n dynamics in the site basis or the system eigenstate basis.\n sparse_matrix : bool or func, optional\n Specifies whether csr_matrix should be used to speed up the\n dynamics calculation for sufficinently sparse matrices. Use\n this in conjunction with evolve_basis='eigen'. (The site basis\n tends to be a dense matrix).\n If a function is passed, it should act on a matrix and determine\n whether it is sparse enough to use csr_matrix.\n\n def func(matrix):\n if matrix is sparse:\n return True\n else:\n return False\n\n If sparse_matrix is True, it will by default only use csr_matrix\n if the matrix is at least 0.99 sparse.\n \"\"\"\n system_operator = LiouvilleSpaceOperator\n\n def __init__(self, hamiltonian, rw_freq=None, hilbert_subspace='gef',\n unit_convert=1, evolve_basis='site', sparse_matrix=False):\n super(LiouvilleSpaceModel, self).__init__(hamiltonian, rw_freq,\n hilbert_subspace,\n unit_convert)\n self.evolve_basis = evolve_basis\n self.sparse_matrix = sparse_matrix\n\n def density_matrix_to_state_vector(self, rho0, liouville_subspace):\n \"\"\"\n turn a density matrix into a state vector to use as the\n diff eq initial condition\n \"\"\"\n state0 = matrix_to_ket_vec(rho0)\n state0 = self.map_between_subspaces(\n state0, full_liouville_subspace(liouville_subspace),\n liouville_subspace)\n return state0\n\n def state_vector_to_density_matrix(self, rho):\n \"\"\"\n turn the diff eq trajectory (list of state vectors) into a\n list of density matrices\n \"\"\"\n N = int(np.sqrt(rho.shape[-1]))\n return rho.reshape(-1, N, N, order='F')\n\n @property\n def evolve_basis(self):\n return self._evolve_basis\n\n @evolve_basis.setter\n def evolve_basis(self, val):\n if val == 'site' or val == 'eigen':\n self._evolve_basis = val\n else:\n raise ValueError('invalid basis')\n\n def dipole_operator(self, liouv_subspace_map, polarization,\n transitions='-+'):\n \"\"\"\n Return a dipole operator that follows the SystemOperator API for the\n given liouville_subspace_map, polarization and requested transitions.\n The operator will be defined in the same basis as self.evolve_basis\n \"\"\"\n operator = self.hamiltonian.dipole_operator(self.hilbert_subspace,\n polarization, transitions)\n if self.evolve_basis == 'eigen':\n operator = self.hamiltonian.transform_operator_to_eigenbasis(\n operator, self.hilbert_subspace)\n return self.system_operator(operator, liouv_subspace_map, self)\n\n def liouville_subspace_index(self, subspace):\n return liouville_subspace_index(subspace, self.hilbert_subspace,\n self.hamiltonian.n_sites,\n self.hamiltonian.n_vibrational_states)\n\n def thermal_state(self, liouville_subspace):\n rho0 = self.hamiltonian.thermal_state(liouville_subspace)\n state0 = matrix_to_ket_vec(rho0)\n rho = self.map_between_subspaces(\n state0, full_liouville_subspace(liouville_subspace),\n liouville_subspace)\n if self.evolve_basis == 'eigen':\n rho = self.hamiltonian.transform_vector_to_eigenbasis(\n rho, liouville_subspace)\n return rho\n\n @property\n def evolution_super_operator(self):\n raise NotImplementedError('subclass must implement the property '\n '`evolution_super_operator`')\n\n def equation_of_motion(self, liouville_subspace, heisenberg_picture=False):\n \"\"\"\n Return the equation of motion for this dynamical model in the given\n subspace, a function which takes a state vector and returns its first\n time derivative, for use in a numerical integration routine\n \"\"\"\n index = self.liouville_subspace_index(liouville_subspace)\n mesh = np.ix_(index, index)\n evolve_matrix = self.evolution_super_operator[mesh]\n if heisenberg_picture:\n # This works because these two equations of motion are equivalent:\n # rho.reshape(-1, 1).dot(L)\n # and:\n # L.T.dot(rho)\n evolve_matrix = evolve_matrix.T\n if self.sparse_matrix is not False:\n if self.sparse_matrix is True:\n def sparse_check(mat):\n return np.mean(mat == 0) >= 0.99\n else:\n sparse_check = self.sparse_matrix\n if sparse_check(evolve_matrix):\n evolve_matrix = csr_matrix(evolve_matrix)\n def eom(t, rho):\n return evolve_matrix.dot(rho)\n return eom\n\n def map_between_subspaces(self, state, from_subspace, to_subspace):\n from_indices, to_indices = map(self.liouville_subspace_index,\n [from_subspace, to_subspace])\n N = self.hamiltonian.n_states(self.hilbert_subspace)\n new_state = matrix_to_ket_vec(np.zeros((N, N), dtype=complex))\n new_state[from_indices] = state\n return new_state[to_indices]\n"
] | [
[
"numpy.ix_",
"numpy.sqrt",
"numpy.arange",
"numpy.kron",
"scipy.sparse.csr_matrix",
"numpy.asanyarray",
"numpy.mean",
"numpy.prod",
"numpy.zeros",
"numpy.empty"
]
] | [
{
"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": []
}
] |
VitusP/Fair-SMOTE | [
"046c82936af08d9041b3d7fe9f575273a110dc82"
] | [
"Fair-SMOTE/Adult_Sex_Race.py"
] | [
"\n# coding: utf-8\n\n# In[ ]:\n\n\nimport pandas as pd\nimport random,time,csv\nimport numpy as np\nimport math,copy,os\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\nfrom sklearn import tree\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nimport sklearn.metrics as metrics\n\n\nimport sys\nsys.path.append(os.path.abspath('..'))\n\nfrom SMOTE import smote\nfrom Measure import measure_final_score,calculate_recall,calculate_far,calculate_precision,calculate_accuracy\nfrom Generate_Samples import generate_samples\n\n\n# # Load Dataset\n\n# In[ ]:\n\n\n## Load dataset\nfrom sklearn import preprocessing\ndataset_orig = pd.read_csv('../data/adult.data.csv')\n\n## Drop NULL values\ndataset_orig = dataset_orig.dropna()\n\n## Drop categorical features\ndataset_orig = dataset_orig.drop(['workclass','fnlwgt','education','marital-status','occupation','relationship','native-country'],axis=1)\n\n## Change symbolics to numerics\ndataset_orig['sex'] = np.where(dataset_orig['sex'] == ' Male', 1, 0)\ndataset_orig['race'] = np.where(dataset_orig['race'] != ' White', 0, 1)\ndataset_orig['Probability'] = np.where(dataset_orig['Probability'] == ' <=50K', 0, 1)\n\n\n## Discretize age\ndataset_orig['age'] = np.where(dataset_orig['age'] >= 70, 70, dataset_orig['age'])\ndataset_orig['age'] = np.where((dataset_orig['age'] >= 60 ) & (dataset_orig['age'] < 70), 60, dataset_orig['age'])\ndataset_orig['age'] = np.where((dataset_orig['age'] >= 50 ) & (dataset_orig['age'] < 60), 50, dataset_orig['age'])\ndataset_orig['age'] = np.where((dataset_orig['age'] >= 40 ) & (dataset_orig['age'] < 50), 40, dataset_orig['age'])\ndataset_orig['age'] = np.where((dataset_orig['age'] >= 30 ) & (dataset_orig['age'] < 40), 30, dataset_orig['age'])\ndataset_orig['age'] = np.where((dataset_orig['age'] >= 20 ) & (dataset_orig['age'] < 30), 20, dataset_orig['age'])\ndataset_orig['age'] = np.where((dataset_orig['age'] >= 10 ) & (dataset_orig['age'] < 10), 10, dataset_orig['age'])\ndataset_orig['age'] = np.where(dataset_orig['age'] < 10, 0, dataset_orig['age'])\n\nprotected_attribute1 = 'sex'\nprotected_attribute2 = 'race'\n\nfrom sklearn.preprocessing import MinMaxScaler\n\nscaler = MinMaxScaler()\ndataset_orig = pd.DataFrame(scaler.fit_transform(dataset_orig),columns = dataset_orig.columns)\n\n\ndataset_orig_train, dataset_orig_test = train_test_split(dataset_orig, test_size=0.2, shuffle = True)\n# dataset_orig\n\n\n# # Check Original Score - Sex\n\n# In[ ]:\n\n\nX_train, y_train = dataset_orig_train.loc[:, dataset_orig_train.columns != 'Probability'], dataset_orig_train['Probability']\nX_test , y_test = dataset_orig_test.loc[:, dataset_orig_test.columns != 'Probability'], dataset_orig_test['Probability']\n\nclf = LogisticRegression(C=1.0, penalty='l2', solver='liblinear', max_iter=100) # LSR\n\nprint(\"recall :\", measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'recall'))\nprint(\"far :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'far'))\nprint(\"precision :\", measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'precision'))\nprint(\"accuracy :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'accuracy'))\nprint(\"F1 Score :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'F1'))\nprint(\"aod :\"+protected_attribute1,measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'aod'))\nprint(\"eod :\"+protected_attribute1,measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'eod'))\n\nprint(\"SPD:\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'SPD'))\nprint(\"DI:\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'DI'))\n\n\n# # Check Original Score - Race\n\n# In[ ]:\n\n\nX_train, y_train = dataset_orig_train.loc[:, dataset_orig_train.columns != 'Probability'], dataset_orig_train['Probability']\nX_test , y_test = dataset_orig_test.loc[:, dataset_orig_test.columns != 'Probability'], dataset_orig_test['Probability']\n\nclf = LogisticRegression(C=1.0, penalty='l2', solver='liblinear', max_iter=100) # LSR\n\nprint(\"recall :\", measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'recall'))\nprint(\"far :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'far'))\nprint(\"precision :\", measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'precision'))\nprint(\"accuracy :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'accuracy'))\nprint(\"F1 Score :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'F1'))\nprint(\"aod :\"+protected_attribute2,measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'aod'))\nprint(\"eod :\"+protected_attribute2,measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'eod'))\n\nprint(\"SPD:\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'SPD'))\nprint(\"DI:\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'DI'))\n\n\n# # Find Class & Protected attribute Distribution\n\n# In[ ]:\n\n\n# first one is class value and second one is 'sex' and third one is 'race'\nzero_zero_zero = len(dataset_orig_train[(dataset_orig_train['Probability'] == 0) & (dataset_orig_train[protected_attribute1] == 0)\n & (dataset_orig_train[protected_attribute2] == 0)])\nzero_zero_one = len(dataset_orig_train[(dataset_orig_train['Probability'] == 0) & (dataset_orig_train[protected_attribute1] == 0)\n & (dataset_orig_train[protected_attribute2] == 1)])\nzero_one_zero = len(dataset_orig_train[(dataset_orig_train['Probability'] == 0) & (dataset_orig_train[protected_attribute1] == 1)\n & (dataset_orig_train[protected_attribute2] == 0)])\nzero_one_one = len(dataset_orig_train[(dataset_orig_train['Probability'] == 0) & (dataset_orig_train[protected_attribute1] == 1)\n & (dataset_orig_train[protected_attribute2] == 1)])\none_zero_zero = len(dataset_orig_train[(dataset_orig_train['Probability'] == 1) & (dataset_orig_train[protected_attribute1] == 0)\n & (dataset_orig_train[protected_attribute2] == 0)])\none_zero_one = len(dataset_orig_train[(dataset_orig_train['Probability'] == 1) & (dataset_orig_train[protected_attribute1] == 0)\n & (dataset_orig_train[protected_attribute2] == 1)])\none_one_zero = len(dataset_orig_train[(dataset_orig_train['Probability'] == 1) & (dataset_orig_train[protected_attribute1] == 1)\n & (dataset_orig_train[protected_attribute2] == 0)])\none_one_one = len(dataset_orig_train[(dataset_orig_train['Probability'] == 1) & (dataset_orig_train[protected_attribute1] == 1)\n & (dataset_orig_train[protected_attribute2] == 1)])\n\n\nprint(zero_zero_zero,zero_zero_one,zero_one_zero,zero_one_one,one_zero_zero,one_zero_one,one_one_zero,one_one_one)\n\n\n# # Sort these four\n\n# In[ ]:\n\n\nmaximum = max(zero_zero_zero,zero_zero_one,zero_one_zero,zero_one_one,one_zero_zero,one_zero_one,one_one_zero,one_one_one)\nif maximum == zero_zero_zero:\n print(\"zero_zero_zero is maximum\")\nif maximum == zero_zero_one:\n print(\"zero_zero_one is maximum\")\nif maximum == zero_one_zero:\n print(\"zero_one_zero is maximum\")\nif maximum == zero_one_one:\n print(\"zero_one_one is maximum\")\nif maximum == one_zero_zero:\n print(\"one_zero_zero is maximum\")\nif maximum == one_zero_one:\n print(\"one_zero_one is maximum\")\nif maximum == one_one_zero:\n print(\"one_one_zero is maximum\")\nif maximum == one_one_one:\n print(\"one_one_one is maximum\")\n\n\n# In[ ]:\n\n\nzero_zero_zero_to_be_incresed = maximum - zero_zero_zero\nzero_zero_one_to_be_incresed = maximum - zero_zero_one\nzero_one_zero_to_be_incresed = maximum - zero_one_zero\nzero_one_one_to_be_incresed = maximum - zero_one_one\none_zero_zero_to_be_incresed = maximum - one_zero_zero\none_zero_one_to_be_incresed = maximum - one_zero_one\none_one_zero_to_be_incresed = maximum - one_one_zero\none_one_one_to_be_incresed = maximum - one_one_one\n\nprint(zero_zero_zero_to_be_incresed,zero_zero_one_to_be_incresed,zero_one_zero_to_be_incresed,zero_one_one_to_be_incresed,\n one_zero_zero_to_be_incresed,one_zero_one_to_be_incresed,one_one_zero_to_be_incresed,one_one_one_to_be_incresed)\n\n\n# In[ ]:\n\n\ndf_zero_zero_zero = dataset_orig_train[(dataset_orig_train['Probability'] == 0) & (dataset_orig_train[protected_attribute1] == 0)\n & (dataset_orig_train[protected_attribute2] == 0)]\ndf_zero_zero_one = dataset_orig_train[(dataset_orig_train['Probability'] == 0) & (dataset_orig_train[protected_attribute1] == 0)\n & (dataset_orig_train[protected_attribute2] == 1)]\ndf_zero_one_zero = dataset_orig_train[(dataset_orig_train['Probability'] == 0) & (dataset_orig_train[protected_attribute1] == 1)\n & (dataset_orig_train[protected_attribute2] == 0)]\ndf_zero_one_one = dataset_orig_train[(dataset_orig_train['Probability'] == 0) & (dataset_orig_train[protected_attribute1] == 1)\n & (dataset_orig_train[protected_attribute2] == 1)]\ndf_one_zero_zero = dataset_orig_train[(dataset_orig_train['Probability'] == 1) & (dataset_orig_train[protected_attribute1] == 0)\n & (dataset_orig_train[protected_attribute2] == 0)]\ndf_one_zero_one = dataset_orig_train[(dataset_orig_train['Probability'] == 1) & (dataset_orig_train[protected_attribute1] == 0)\n & (dataset_orig_train[protected_attribute2] == 1)]\ndf_one_one_zero = dataset_orig_train[(dataset_orig_train['Probability'] == 1) & (dataset_orig_train[protected_attribute1] == 1)\n & (dataset_orig_train[protected_attribute2] == 0)]\ndf_one_one_one = dataset_orig_train[(dataset_orig_train['Probability'] == 1) & (dataset_orig_train[protected_attribute1] == 1)\n & (dataset_orig_train[protected_attribute2] == 1)]\n\n\ndf_zero_zero_zero['race'] = df_zero_zero_zero['race'].astype(str)\ndf_zero_zero_zero['sex'] = df_zero_zero_zero['sex'].astype(str)\n\ndf_zero_zero_one['race'] = df_zero_zero_one['race'].astype(str)\ndf_zero_zero_one['sex'] = df_zero_zero_one['sex'].astype(str)\n\ndf_zero_one_zero['race'] = df_zero_one_zero['race'].astype(str)\ndf_zero_one_zero['sex'] = df_zero_one_zero['sex'].astype(str)\n\ndf_zero_one_one['race'] = df_zero_one_one['race'].astype(str)\ndf_zero_one_one['sex'] = df_zero_one_one['sex'].astype(str)\n\ndf_one_zero_zero['race'] = df_one_zero_zero['race'].astype(str)\ndf_one_zero_zero['sex'] = df_one_zero_zero['sex'].astype(str)\n\ndf_one_zero_one['race'] = df_one_zero_one['race'].astype(str)\ndf_one_zero_one['sex'] = df_one_zero_one['sex'].astype(str)\n\ndf_one_one_zero['race'] = df_one_one_zero['race'].astype(str)\ndf_one_one_zero['sex'] = df_one_one_zero['sex'].astype(str)\n\ndf_one_one_one['race'] = df_one_one_one['race'].astype(str)\ndf_one_one_one['sex'] = df_one_one_one['sex'].astype(str)\n\n\ndf_zero_zero_zero = generate_samples(zero_zero_zero_to_be_incresed,df_zero_zero_zero,'Adult')\ndf_zero_zero_one = generate_samples(zero_zero_one_to_be_incresed,df_zero_zero_one,'Adult')\ndf_zero_one_zero = generate_samples(zero_one_zero_to_be_incresed,df_zero_one_zero,'Adult')\ndf_zero_one_one = generate_samples(zero_one_one_to_be_incresed,df_zero_one_one,'Adult')\ndf_one_zero_zero = generate_samples(one_zero_zero_to_be_incresed,df_one_zero_zero,'Adult')\ndf_one_zero_one = generate_samples(one_zero_one_to_be_incresed,df_one_zero_one,'Adult')\ndf_one_one_zero = generate_samples(one_one_zero_to_be_incresed,df_one_one_zero,'Adult')\ndf_one_one_one = generate_samples(one_one_one_to_be_incresed,df_one_one_one,'Adult')\n\n\n# # Append the dataframes\n\n# In[ ]:\n\n\ndf = pd.concat([df_zero_zero_zero,df_zero_zero_one,df_zero_one_zero,df_zero_one_one,\ndf_one_zero_zero,df_one_zero_one,df_one_one_zero,df_one_one_one])\ndf\n\n\n# # Check Score after oversampling\n\n# In[ ]:\n\n\nX_train, y_train = df.loc[:, df.columns != 'Probability'], df['Probability']\nX_test , y_test = dataset_orig_test.loc[:, dataset_orig_test.columns != 'Probability'], dataset_orig_test['Probability']\n\nclf = LogisticRegression(C=1.0, penalty='l2', solver='liblinear', max_iter=100) # LSR\n\n\nprint(\"recall :\", measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'recall'))\nprint(\"far :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'far'))\nprint(\"precision :\", measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'precision'))\nprint(\"accuracy :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'accuracy'))\nprint(\"F1 Score :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'F1'))\nprint(\"aod :\"+protected_attribute1,measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'aod'))\nprint(\"eod :\"+protected_attribute1,measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'eod'))\n\nprint(\"SPD:\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'SPD'))\nprint(\"DI:\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute1, 'DI'))\n\nprint(\"-------------\")\n\nprint(\"recall :\", measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'recall'))\nprint(\"far :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'far'))\nprint(\"precision :\", measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'precision'))\nprint(\"accuracy :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'accuracy'))\nprint(\"F1 Score :\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'F1'))\nprint(\"aod :\"+protected_attribute2,measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'aod'))\nprint(\"eod :\"+protected_attribute2,measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'eod'))\n\nprint(\"SPD:\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'SPD'))\nprint(\"DI:\",measure_final_score(dataset_orig_test, clf, X_train, y_train, X_test, y_test, protected_attribute2, 'DI'))\n\n\n# # Verification \n\n# In[ ]:\n\n\nzero_zero_zero = len(df[(df['Probability'] == 0) & (df[protected_attribute1] == '0.0')\n & (df[protected_attribute2] == '0.0')])\nzero_zero_one = len(df[(df['Probability'] == 0) & (df[protected_attribute1] == '0.0')\n & (df[protected_attribute2] == '1.0')])\nzero_one_zero = len(df[(df['Probability'] == 0) & (df[protected_attribute1] == '1.0')\n & (df[protected_attribute2] == '0.0')])\nzero_one_one = len(df[(df['Probability'] == 0) & (df[protected_attribute1] == '1.0')\n & (df[protected_attribute2] == '1.0')])\none_zero_zero = len(df[(df['Probability'] == 1) & (df[protected_attribute1] == '0.0')\n & (df[protected_attribute2] == '0.0')])\none_zero_one = len(df[(df['Probability'] == 1) & (df[protected_attribute1] == '0.0')\n & (df[protected_attribute2] == '1.0')])\none_one_zero = len(df[(df['Probability'] == 1) & (df[protected_attribute1] == '1.0')\n & (df[protected_attribute2] == '0.0')])\none_one_one = len(df[(df['Probability'] == 1) & (df[protected_attribute1] == '1.0')\n & (df[protected_attribute2] == '1.0')])\n\n\nprint(zero_zero_zero,zero_zero_one,zero_one_zero,zero_one_one,one_zero_zero,one_zero_one,one_one_zero,one_one_one)\n\n"
] | [
[
"pandas.concat",
"pandas.read_csv",
"sklearn.linear_model.LogisticRegression",
"sklearn.model_selection.train_test_split",
"numpy.where",
"sklearn.preprocessing.MinMaxScaler"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
chiragyadav/char_cnn | [
"e891aebbd7a6abf1e2c141f444eebfa63738b81c"
] | [
"model.py"
] | [
"import tensorflow as tf\nimport numpy as np\n\n\nclass TextCNN(object):\n \"\"\"\n A CNN for text classification.\n Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.\n \"\"\"\n\n def __init__(\n self, sequence_length, num_classes, vocab_size,\n embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0):\n # Placeholders for input, output and dropout\n self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name=\"input_x\")\n self.input_y = tf.placeholder(tf.float32, [None, num_classes], name=\"input_y\")\n self.dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\n\n # Keeping track of l2 regularization loss (optional)\n l2_loss = tf.constant(0.0)\n\n # Embedding layer\n with tf.device('/cpu:0'), tf.name_scope(\"embedding\"):\n self.W = tf.Variable(\n tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),\n name=\"W\")\n self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)\n self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)\n\n # Create a convolution + maxpool layer for each filter size\n pooled_outputs = []\n for i, filter_size in enumerate(filter_sizes):\n with tf.name_scope(\"conv-maxpool-%s\" % filter_size):\n # Convolution Layer\n filter_shape = [filter_size, embedding_size, 1, num_filters]\n W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=\"W\")\n b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name=\"b\")\n conv = tf.nn.conv2d(\n self.embedded_chars_expanded,\n W,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n name=\"conv\")\n # Apply nonlinearity\n h = tf.nn.relu(tf.nn.bias_add(conv, b), name=\"relu\")\n # Maxpooling over the outputs\n pooled = tf.nn.max_pool(\n h,\n ksize=[1, sequence_length - filter_size + 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding='VALID',\n name=\"pool\")\n pooled_outputs.append(pooled)\n\n # Combine all the pooled features\n num_filters_total = num_filters * len(filter_sizes)\n self.h_pool = tf.concat(pooled_outputs, 3)\n self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])\n\n # Add dropout\n with tf.name_scope(\"dropout\"):\n self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)\n\n # Final (unnormalized) scores and predictions\n with tf.name_scope(\"output\"):\n W = tf.get_variable(\n \"W\",\n shape=[num_filters_total, num_classes],\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name=\"b\")\n l2_loss += tf.nn.l2_loss(W)\n l2_loss += tf.nn.l2_loss(b)\n self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name=\"scores\")\n self.predictions = tf.argmax(self.scores, 1, name=\"predictions\")\n\n # CalculateMean cross-entropy loss\n with tf.name_scope(\"loss\"):\n losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)\n self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss\n\n # Accuracy\n with tf.name_scope(\"accuracy\"):\n correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\n\n with tf.name_scope('num_correct'):\n correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))\n self.num_correct = tf.reduce_sum(tf.cast(correct_predictions, 'float'), name='num_correct')\n\n"
] | [
[
"tensorflow.device",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.concat",
"tensorflow.nn.max_pool",
"tensorflow.cast",
"tensorflow.nn.l2_loss",
"tensorflow.nn.conv2d",
"tensorflow.name_scope",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.argmax",
"tensorflow.nn.dropout",
"tensorflow.nn.xw_plus_b",
"tensorflow.truncated_normal",
"tensorflow.placeholder",
"tensorflow.nn.embedding_lookup",
"tensorflow.nn.bias_add",
"tensorflow.constant",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.random_uniform"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
scottstanie/apertools | [
"f959d03038e77444204c1ff224ddd8357db3fc04"
] | [
"apertools/utils.py"
] | [
"#! /usr/bin/env python\n\"\"\"Author: Scott Staniewicz\nutils.py: Miscellaneous helper functions\nEmail: [email protected]\n\"\"\"\nfrom __future__ import division, print_function\nimport contextlib\nimport datetime\nimport copy\nimport errno\nimport sys\nimport os\nimport subprocess\nimport numpy as np\nimport itertools\n\nfrom apertools.log import get_log\n\nlogger = get_log()\n\n\ndef get_file_ext(filename):\n \"\"\"Extracts the file extension, including the '.' (e.g.: .slc)\n\n Examples:\n >>> print(get_file_ext('radarimage.slc'))\n .slc\n >>> print(get_file_ext('unwrapped.lowpass.unw'))\n .unw\n\n \"\"\"\n return os.path.splitext(filename)[1]\n\n\ndef to_datetime(dates, tzinfo=datetime.timezone.utc):\n \"\"\"Convert a single (or list of) `datetime.date` to `datetime.datetime`\"\"\"\n if isinstance(dates, datetime.datetime):\n return dates\n try:\n iter(dates)\n if len(dates) == 0:\n return dates\n try: # Check if its a list of tuples (an ifglist)\n iter(dates[0])\n return [to_datetime(tup) for tup in dates]\n except TypeError:\n return [datetime.datetime(*d.timetuple()[:6], tzinfo=tzinfo) for d in dates]\n # Or if it's just one sigle date\n except TypeError:\n return datetime.datetime(*dates.timetuple()[:6], tzinfo=tzinfo)\n\n\ndef mkdir_p(path):\n \"\"\"Emulates bash `mkdir -p`, in python style\n Used for igrams directory creation\n \"\"\"\n try:\n os.makedirs(path)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\n\ndef which(program):\n \"\"\"Mimics UNIX which\n\n Used from https://stackoverflow.com/a/377028\"\"\"\n\n def is_exe(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n fpath, fname = os.path.split(program)\n if fpath:\n if is_exe(program):\n return program\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n exe_file = os.path.join(path, program)\n if is_exe(exe_file):\n return exe_file\n\n return None\n\n\n# NOTE: now possible in numpy 1.20:\n# def take_looks(x, rl, cl, func=np.mean):\n# from numpy.lib.stride_tricks import sliding_window_view\n# views = sliding_window_view(x, (rl, cl))\n# return func(views[::rl, ::cl], axis=(2, 3))\n\n\ndef take_looks(arr, row_looks, col_looks, separate_complex=False, **kwargs):\n \"\"\"Downsample a numpy matrix by summing blocks of (row_looks, col_looks)\n\n Cuts off values if the size isn't divisible by num looks\n\n NOTE: For complex data, looks on the magnitude are done separately\n from looks on the phase\n\n Args:\n arr (ndarray) 2D array of an image\n row_looks (int) the reduction rate in row direction\n col_looks (int) the reduction rate in col direction\n separate_complex (bool): take looks on magnitude and phase separately\n Better to preserve the look of the magnitude\n\n Returns:\n ndarray, size = ceil(rows / row_looks, cols / col_looks)\n \"\"\"\n if row_looks == 1 and col_looks == 1:\n return arr\n if isinstance(arr, dict):\n return take_looks_rsc(arr, row_looks, col_looks)\n if np.iscomplexobj(arr) and separate_complex:\n mag_looked = take_looks(np.abs(arr), row_looks, col_looks)\n phase_looked = take_looks(np.angle(arr), row_looks, col_looks)\n return mag_looked * np.exp(1j * phase_looked)\n\n rows, cols = arr.shape\n new_rows = rows // row_looks\n new_cols = cols // col_looks\n\n row_cutoff = rows % row_looks\n col_cutoff = cols % col_looks\n\n if row_cutoff != 0:\n arr = arr[:-row_cutoff, :]\n if col_cutoff != 0:\n arr = arr[:, :-col_cutoff]\n # For taking the mean, treat integers as floats\n if np.issubdtype(arr.dtype, np.integer):\n arr = arr.astype(\"float\")\n\n return np.mean(arr.reshape(new_rows, row_looks, new_cols, col_looks), axis=(3, 1))\n\n\ndef take_looks_rsc(rsc_data, row_looks, col_looks):\n nrows, ncols = rsc_data[\"file_length\"], rsc_data[\"width\"]\n\n out_rsc = rsc_data.copy()\n out_rsc[\"x_step\"] = rsc_data[\"x_step\"] * col_looks\n out_rsc[\"y_step\"] = rsc_data[\"y_step\"] * row_looks\n out_rsc[\"file_length\"] = nrows // row_looks\n out_rsc[\"width\"] = ncols // col_looks\n return out_rsc\n\n\ndef get_looks_rdr(filename: str):\n \"\"\"Get the row/col looks of a radar coordinates file from the transform\"\"\"\n import rasterio as rio\n\n with rio.open(filename) as src:\n x_step, _, _, _, y_step, _ = tuple(src.transform)[:6]\n # x_step is column looks, y_step is row looks\n return y_step, x_step\n\n\ndef scale_dset(filename, dset, scale):\n import h5py\n\n with h5py.File(filename, \"r+\") as f:\n data = f[dset]\n data[...] *= scale\n\n\ndef slclist_from_igrams(igram_list):\n \"\"\"Takes a list of [(reference, secondary),...] igram date pairs\n and returns the list of unique dates of SAR images used to form them\n \"\"\"\n return sorted(list(set(itertools.chain(*igram_list))))\n\n\ndef full_igram_list(slclist):\n \"\"\"Create the list of all possible igram pairs from slclist\"\"\"\n return [\n (early, late)\n for (idx, early) in enumerate(slclist[:-1])\n for late in slclist[idx + 1 :]\n ]\n\n\ndef filter_min_max_date(ifg_list, min_date=None, max_date=None, verbose=False):\n \"\"\"Filters from an iterable of (date1, date1) ifg pairs by min/max date\"\"\"\n # Coerce all dates to datetimes\n if min_date:\n md = to_datetime(min_date)\n len_before = len(ifg_list)\n ifg_list = [ifg for ifg in ifg_list if (ifg[0] >= md and ifg[1] >= md)]\n if verbose:\n logger.info(\n f\"Ignoring {len_before - len(ifg_list)} igrams before {min_date}\"\n )\n if max_date:\n md = to_datetime(max_date)\n len_before = len(ifg_list)\n ifg_list = [ifg for ifg in ifg_list if (ifg[0] <= md and ifg[1] <= md)]\n if verbose:\n logger.info(\n f\"Ignoring {len_before - len(ifg_list)} igrams after {max_date}\"\n )\n return ifg_list\n\n\ndef filter_slclist_ifglist(\n ifg_date_list,\n min_date=None,\n max_date=None,\n max_temporal_baseline=None,\n min_bandwidth=None,\n max_bandwidth=None,\n include_annual=False,\n slclist_ignore_file=None,\n verbose=False,\n):\n # Make sure it's a list of tuples\n ifg_date_list = [tuple(ifg) for ifg in ifg_date_list]\n # Dont alter the original so we can find the indices at the end\n valid_ifg_pairs = copy.copy(ifg_date_list)\n if slclist_ignore_file is not None:\n _, valid_ifg_pairs = ignore_slc_dates(\n ifg_date_list=valid_ifg_pairs, slclist_ignore_file=slclist_ignore_file\n )\n\n valid_ifg_pairs = filter_min_max_date(\n valid_ifg_pairs, min_date, max_date, verbose=verbose\n )\n # Check for 1 year interferograms before cutting down\n if include_annual:\n annual_ifgs = find_annual_ifgs(valid_ifg_pairs)\n else:\n annual_ifgs = []\n\n # Now filter the rest by temp baseline or by \"bandwidth\" aka index distance\n if max_temporal_baseline is not None and max_bandwidth is not None:\n raise ValueError(\"Only can filter by one of bandwith or temp. baseline\")\n if max_temporal_baseline is not None:\n # TODO: handle min and max both\n ll = len(valid_ifg_pairs)\n valid_ifg_pairs = [\n ifg\n for ifg in valid_ifg_pairs\n if abs((ifg[1] - ifg[0]).days) <= max_temporal_baseline\n ]\n if verbose:\n logger.info(\n f\"Ignoring {ll - len(valid_ifg_pairs)} longer than {max_temporal_baseline}\"\n )\n elif max_bandwidth is not None or min_bandwidth is not None:\n valid_ifg_pairs = limit_ifg_bandwidth(\n valid_ifg_pairs, max_bandwidth=max_bandwidth, min_bandwidth=min_bandwidth\n )\n valid_ifg_pairs = list(sorted(valid_ifg_pairs + annual_ifgs))\n\n if verbose:\n logger.info(\n f\"Ignoring {len(ifg_date_list) - len(valid_ifg_pairs)} igrams total\"\n )\n\n # Now just use the ones remaining to reform the unique SAR dates\n valid_sar_dates = list(sorted(set(itertools.chain.from_iterable(valid_ifg_pairs))))\n # Does the same as np.searchsorted, but works on a list[tuple]\n valid_ifg_idxs = [ifg_date_list.index(tup) for tup in valid_ifg_pairs]\n return valid_sar_dates, valid_ifg_pairs, valid_ifg_idxs\n\n\ndef ignore_slc_dates(\n slc_date_list=[],\n ifg_date_list=[],\n slclist_ignore_file=\"slclist_ignore.txt\",\n parse=True,\n):\n \"\"\"Read extra file to ignore certain dates of interferograms\"\"\"\n import apertools.sario\n\n ignore_slcs = set(\n to_datetime(\n apertools.sario.find_slcs(filename=slclist_ignore_file, parse=parse)\n )\n )\n logger.info(\"Ignoring the following slc dates:\")\n logger.info(sorted(ignore_slcs))\n valid_slcs = [g for g in slc_date_list if g not in ignore_slcs]\n valid_igrams = [\n i for i in ifg_date_list if i[0] not in ignore_slcs and i[1] not in ignore_slcs\n ]\n logger.info(\n f\"Ignoring {len(ifg_date_list) - len(valid_igrams)} igrams listed in {slclist_ignore_file}\"\n )\n return valid_slcs, valid_igrams\n\n\ndef limit_ifg_bandwidth(valid_ifg_dates, max_bandwidth=None, min_bandwidth=None):\n \"\"\"Limit the total interferograms to just nearest `max_bandwidth` connections\n Alternative to a temportal baseline.\n \"\"\"\n if not max_bandwidth:\n max_bandwidth = np.inf\n if not min_bandwidth:\n min_bandwidth = 1\n cur_early = None\n cur_bw = 1\n ifg_used = []\n for early, late in valid_ifg_dates:\n if early != cur_early:\n cur_bw = 1\n cur_early = early\n else:\n cur_bw += 1\n if cur_bw <= max_bandwidth and cur_bw >= min_bandwidth:\n ifg_used.append((early, late))\n return ifg_used\n\n\ndef _temp_baseline(ifg_pair):\n return (ifg_pair[1] - ifg_pair[0]).days\n\n\ndef find_annual_ifgs(ifg_pairs, buffer_days=30, num_years=1):\n \"\"\"Pick out interferograms which are closest to 1 year in span \"\"\"\n # We only want to pick 1 ifg per date, closest to a year, but skip a date if it\n # doesn't have an ifg of baseline 365 +/- `buffer_days`\n # sar_dates = list(sorted(set(itertools.chain.from_iterable(ifg_pairs))))\n date_to_ifg = {}\n # Used to keep track how far into ifg_list the last sar date was (avoid iterations)\n for ifg in ifg_pairs:\n early = ifg[0]\n tb = _temp_baseline(ifg)\n if abs(tb - 365) > buffer_days:\n continue\n cur_ifg = date_to_ifg.get(early)\n # Use this ifg as the annual if none exist, or if it's closer to 365\n if cur_ifg is None or abs(tb - 365) < _temp_baseline(cur_ifg):\n date_to_ifg[early] = ifg\n return list(sorted(date_to_ifg.values()))\n\n\ndef take_looks_gdal(outname, src_filename, row_looks, col_looks, format=\"ROI_PAC\"):\n \"\"\"Downsample an array on disk using gdal_translate\n\n Cuts off values if the size isn't divisible by num looks\n\n NOTE: For complex data, looks on the magnitude are done separately\n from looks on the phase\n\n See https://github.com/OSGeo/gdal/blob/master/gdal/swig/python/osgeo/gdal.py#L328\n for options\n\n Args:\n outname (string): output/destination filename\n filename (string) Name of gdal-compatible input raster file\n row_looks (int) the reduction rate in row direction\n col_looks (int) the reduction rate in col direction\n\n Returns:\n ndarray, size = ceil(rows / row_looks, cols / col_looks)\n values at each pixel are averaged from input array\n \"\"\"\n from osgeo import gdal\n from osgeo import gdalconst\n\n if row_looks == 1 and col_looks == 1:\n raise ValueError(\"Must take looks for file on disk\")\n in_ds = gdal.Open(src_filename)\n shape = (in_ds.RasterYSize, in_ds.RasterXSize) # (rows, cols)\n new_rows, new_cols = shape[0] // row_looks, shape[1] // col_looks\n return gdal.Translate(\n outname,\n in_ds,\n height=new_rows,\n width=new_cols,\n format=format,\n resampleAlg=gdalconst.GRIORA_Average,\n )\n\n\ndef take_looks_gdal2(\n infile,\n outfile,\n fmt=\"GTiff\",\n xlooks=None,\n ylooks=None,\n noData=None,\n method=\"average\",\n):\n \"\"\"\n infile - Input file to multilook\n outfile - Output file to multilook\n fmt - Output format\n xlooks - Number of looks in x/range direction\n ylooks - Number of looks in y/azimuth direction\n \"\"\"\n from osgeo import gdal\n\n ds = gdal.Open(infile, gdal.GA_ReadOnly)\n\n # Input file dimensions\n xSize = ds.RasterXSize\n ySize = ds.RasterYSize\n\n # Output file dimensions\n outXSize = xSize // xlooks\n outYSize = ySize // ylooks\n\n # Set up options for translation\n gdalTranslateOpts = gdal.TranslateOptions(\n format=fmt,\n width=outXSize,\n height=outYSize,\n srcWin=[0, 0, outXSize * xlooks, outYSize * ylooks],\n noData=noData,\n resampleAlg=method,\n )\n\n # Call gdal_translate\n gdal.Translate(outfile, ds, options=gdalTranslateOpts)\n ds = None\n\n\ndef crossmul_gdal(outfile, file1, file2, row_looks, col_looks, format=\"ROI_PAC\"):\n \"\"\"Uses gdal_calc.py to multiply, then gdal_translate for looks\"\"\"\n tmp = \"tmp.tif\"\n cmd = \"\"\"gdal_calc.py -A {f1} -B {f1} --outfile={tmp} \\\n --calc=\"A * conj(B)\" --NoDataValue=0 \"\"\".format(\n f1=file1, f2=file2, tmp=tmp\n )\n subprocess.check_call(cmd, shell=True)\n take_looks_gdal(outfile, tmp, row_looks, col_looks, format=format)\n os.remove(tmp)\n\n\ndef clip(image):\n \"\"\"Convert float image to only range 0 to 1 (clips)\"\"\"\n return np.clip(np.abs(image), 0, 1)\n\n\ndef log(image):\n \"\"\"Converts magnitude amplitude image to log scale\"\"\"\n if np.iscomplexobj(image):\n image = np.abs(image)\n return 20 * np.log10(image)\n\n\n# Alias: convert\ndb = log\n\n\ndef mag(db_image):\n \"\"\"Reverse of log/db: decibel to magnitude\"\"\"\n return 10 ** (db_image / 20)\n\n\ndef mask_zeros(image):\n \"\"\"Turn image into masked array, 0s masked\"\"\"\n return np.ma.masked_equal(image, 0)\n\n\ndef force_column(arr):\n \"\"\"Turns 1d numpy array into an (N, 1) shaped column\"\"\"\n return arr.reshape((len(arr), 1))\n\n\ndef atleast_2d(*arys):\n \"\"\"column version of numpy's atleast_2d\n\n Reshapes to be (N, 1) if 1d\n \"\"\"\n res = []\n for ary in arys:\n ary = np.asanyarray(ary)\n if ary.ndim == 0:\n result = ary.reshape(1, 1)\n elif ary.ndim == 1:\n result = ary[:, np.newaxis]\n else:\n result = ary\n res.append(result)\n if len(res) == 1:\n return res[0]\n else:\n return res\n\n\ndef percent_zero(arr=None):\n \"\"\"Function to give the percentage of a file that is exactly zero\n\n Used as a quality assessment check\n\n Args:\n arr (ndarray): pre-loaded array to check\n\n Returns:\n float: decimal from 0 to 1, ratio of zeros to total entries\n\n Example:\n >>> a = np.array([[1 + 1j, 0.0], [1, 0.0001]])\n >>> print(percent_zero(arr=a))\n 0.25\n \"\"\"\n return np.sum(arr == 0) / arr.size\n\n\ndef sliding_window_view(x, shape, step=None):\n \"\"\"\n Create sliding window views of the N dimensions array with the given window\n shape. Window slides across each dimension of `x` and provides subsets of `x`\n at any window position.\n\n Adapted from https://github.com/numpy/numpy/pull/10771\n\n Args:\n x (ndarray): Array to create sliding window views.\n shape (sequence of int): The shape of the window.\n Must have same length as number of input array dimensions.\n step: (sequence of int), optional\n The steps of window shifts for each dimension on input array at a time.\n If given, must have same length as number of input array dimensions.\n Defaults to 1 on all dimensions.\n Returns:\n ndarray: Sliding window views (or copies) of `x`.\n view.shape = (x.shape - shape) // step + 1\n\n Notes\n -----\n ``sliding_window_view`` create sliding window views of the N dimensions array\n with the given window shape and its implementation based on ``as_strided``.\n The returned views are *readonly* due to the numpy sliding tricks.\n Examples\n --------\n >>> i, j = np.ogrid[:3,:4]\n >>> x = 10*i + j\n >>> shape = (2,2)\n >>> sliding_window_view(x, shape)[0, 0]\n array([[ 0, 1],\n [10, 11]])\n >>> sliding_window_view(x, shape)[1, 2]\n array([[12, 13],\n [22, 23]])\n \"\"\"\n # first convert input to array, possibly keeping subclass\n x = np.array(x, copy=False)\n\n try:\n shape = np.array(shape, np.int)\n except ValueError:\n raise TypeError(\"`shape` must be a sequence of integer\")\n else:\n if shape.ndim > 1:\n raise ValueError(\"`shape` must be one-dimensional sequence of integer\")\n if len(x.shape) != len(shape):\n raise ValueError(\"`shape` length doesn't match with input array dimensions\")\n if np.any(shape <= 0):\n raise ValueError(\"`shape` cannot contain non-positive value\")\n\n if step is None:\n step = np.ones(len(x.shape), np.intp)\n else:\n try:\n step = np.array(step, np.intp)\n except ValueError:\n raise TypeError(\"`step` must be a sequence of integer\")\n else:\n if step.ndim > 1:\n raise ValueError(\"`step` must be one-dimensional sequence of integer\")\n if len(x.shape) != len(step):\n raise ValueError(\n \"`step` length doesn't match with input array dimensions\"\n )\n if np.any(step <= 0):\n raise ValueError(\"`step` cannot contain non-positive value\")\n\n o = (np.array(x.shape) - shape) // step + 1 # output shape\n if np.any(o <= 0):\n raise ValueError(\"window shape cannot larger than input array shape\")\n\n strides = x.strides\n view_strides = strides * step\n\n view_shape = np.concatenate((o, shape), axis=0)\n view_strides = np.concatenate((view_strides, strides), axis=0)\n view = np.lib.stride_tricks.as_strided(x, view_shape, view_strides, writeable=False)\n\n return view\n\n\ndef window_stack(stack, row, col, window_size=3, func=np.mean):\n \"\"\"Combines square around (row, col) in 3D stack to a 1D array\n\n Used to average around a pixel in a stack and produce a timeseries\n\n Args:\n stack (ndarray): 3D array of images, stacked along axis=0\n row (int): row index of the reference pixel to subtract\n col (int): col index of the reference pixel to subtract\n window_size (int): size of the group around ref pixel to avg for reference.\n if window_size=1 or None, only the single pixel location used for output\n func (str): default=np.mean, numpy function to use on window.\n\n Raises:\n ValueError: if window_size is not a positive int, or if ref pixel out of bounds\n \"\"\"\n window_size = window_size or 1\n if not isinstance(window_size, int) or window_size < 1:\n raise ValueError(\n \"Invalid window_size %s: must be odd positive int\" % window_size\n )\n elif row > stack.shape[1] or col > stack.shape[2]:\n raise ValueError(\n \"(%s, %s) out of bounds reference for stack size %s\"\n % (row, col, stack.shape)\n )\n\n if window_size % 2 == 0:\n window_size -= 1\n print(\"Making window_size an odd number (%s) to get square\" % window_size)\n\n half_win = window_size // 2\n row_slice = slice(row - half_win, row + half_win + 1)\n col_slice = slice(col - half_win, col + half_win + 1)\n subset = stack[..., row_slice, col_slice]\n return func(subset, axis=(-2, -1))\n\n\ndef window_stack_xr(\n da,\n lon=None,\n lat=None,\n row=None,\n col=None,\n window_size=5,\n lon_name=\"lon\",\n lat_name=\"lat\",\n func=np.mean,\n):\n \"\"\"Combines square around (row, col) in 3D DataArray to a 1D array\n\n Used to average around a pixel in a stack and produce a timeseries\n \"\"\"\n is_2d_latlon = getattr(da, lon_name).ndim\n if row is None or col is None:\n if is_2d_latlon == 2:\n # It wont be in the indices in this case, just a 2d data array\n from apertools import latlon\n\n row, col = latlon.latlon_to_rowcol_rdr(\n lat,\n lon,\n lat_arr=getattr(da, lat_name).data,\n lon_arr=getattr(da, lon_name).data,\n )\n if col is None or row is None:\n # out of bounds (could be on a diagonal corner of the bbox)\n raise ValueError(f\"({lon}, {lat}) is out of bounds for {da}\")\n else:\n col = da.indexes[lon_name].get_loc(lon, method=\"nearest\")\n row = da.indexes[lat_name].get_loc(lat, method=\"nearest\")\n\n return window_stack(da, row, col, window_size=window_size, func=func)\n\n\n# Randoms using the sentinelapi\ndef find_slc_products(api, gj_obj, date_start, date_end, area_relation=\"contains\"):\n \"\"\"Query for Sentinel 1 SCL products with common options\n\n from sentinelsat import SentinelAPI, read_geojson, geojson_to_wkt\n api = api = SentinelAPI(user, pw)\n pecosgeo = geojson_to_wkt(geojson.read_json('pecosBig.geojson'))\n find_slc_products(pecosgeo, '20150101', '20171230')\n\n Returns:\n OrderedDict: key = '528c0630-bbbf-4a95-8415-c55aa5ce915a', the sentinel\n \"\"\"\n # area_relation : 'Intersection', 'Contains', 'IsWithin'\n # contains means that the Sentinel footprint completely contains your geojson object\n return api.query(\n gj_obj,\n date=(date_start, date_end),\n platformname=\"Sentinel-1\",\n producttype=\"SLC\",\n area_relation=area_relation,\n )\n\n\ndef show_titles(products):\n return [p[\"title\"] for p in products.values()]\n\n\ndef fullpath(path):\n \"\"\"Expands ~ and returns an absolute path\"\"\"\n return os.path.abspath(os.path.expanduser(path))\n\n\ndef force_symlink(src, dest):\n \"\"\"python equivalent to 'ln -f -s': force overwrite \"\"\"\n if os.path.exists(fullpath(dest)) and os.path.islink(fullpath(dest)):\n os.remove(fullpath(dest))\n\n try:\n os.symlink(fullpath(src), fullpath(dest))\n except OSError as e:\n if e.errno == errno.EEXIST:\n raise ValueError(\"Non-symlink file exists: %s\" % fullpath(dest))\n else:\n raise\n # os.remove(fullpath(dest))\n # os.symlink(fullpath(src), fullpath(dest))\n\n\ndef rm_if_exists(filename):\n # os.path.islink(path) # Test for symlink\n try:\n os.remove(filename)\n except OSError as e:\n if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory\n raise # re-raise if different error\n\n\ndef get_parent_dir(filepath):\n \"\"\"Shortcut to get the parent directory\n\n Works on directories or files, so\n \"/home/scott/\" -> \"/home\"\n \"/home/scott/file.txt\" -> \"/home\"\n\n Used, e.g. for when .geos should be 1 directory up from igrams\n\n Examples:\n >>> import tempfile, sys\n >>> if sys.version_info[0] == 2: from backports import tempfile\n >>> temp_dir = tempfile.TemporaryDirectory()\n >>> nested = os.path.join(temp_dir.name, 'dir2')\n >>> os.mkdir(nested)\n >>> get_parent_dir(nested) == temp_dir.name\n True\n >>> open(os.path.join(nested, \"emptyfile\"), \"a\").close()\n >>> get_parent_dir(os.path.join(nested, \"emptyfile\")) == temp_dir.name\n True\n \"\"\"\n if os.path.isdir(filepath):\n return os.path.dirname(os.path.abspath(os.path.normpath(filepath)))\n else:\n return os.path.dirname(os.path.split(os.path.abspath(filepath))[0])\n\n\ndef get_cache_dir(force_posix=False, app_name=\"apertools\"):\n \"\"\"Returns the config folder for the application. The default behavior\n is to return whatever is most appropriate for the operating system.\n\n This is used to store gps timeseries data\n\n the following folders could be returned:\n Mac OS X:\n ``~/Library/Application Support/apertools``\n Mac OS X (POSIX):\n ``~/.apertools``\n Unix:\n ``~/.cache/apertools``\n Unix (POSIX):\n ``~/.apertools``\n\n Args:\n force_posix: if this is set to `True` then on any POSIX system the\n folder will be stored in the home folder with a leading\n dot instead of the XDG config home or darwin's\n application support folder.\n\n Source: https://github.com/pallets/click/blob/master/click/utils.py#L368\n \"\"\"\n if force_posix:\n path = os.path.join(os.path.expanduser(\"~/.\" + app_name))\n if sys.platform == \"darwin\":\n path = os.path.join(\n os.path.expanduser(\"~/Library/Application Support\"), app_name\n )\n path = os.path.join(\n os.environ.get(\"XDG_CONFIG_HOME\", os.path.expanduser(\"~/.cache\")),\n app_name,\n )\n if not os.path.exists(path):\n os.makedirs(path)\n return path\n\n\ndef az_inc_to_enu(\n infile=\"los.rdr\",\n outfile=\"los_enu.tif\",\n do_geocode=True,\n latlon_step=0.001,\n invert=True,\n nodata=0,\n):\n \"\"\"Convert a 2 band azimuth/inclindation line of sight file to 3 band east/north/up\n\n Source: http://earthdef.caltech.edu/boards/4/topics/327\n Args:\n infile (str, optional): 2-band los file. Defaults to \"los.rdr\".\n outfile (str, optional): output ENU file. Defaults to \"los_enu.tif\".\n do_geocode (bool, optional): If the `infile` is in radar coordinates (e.g.\n ISCE's geometry folder has \"los.rdr\"). Defaults to True.\n latlon_step (float, optional): if geocoding, lat/lon spacing. Defaults to 0.001.\n invert (bool, optional): Reverse the LOS convention in the output. Defaults to True.\n E.g. ISCE uses \"from ground toward satellite\" line of sight vector convention,\n so the \"up\" component is positive\".\n `invert=True` makes the output use \"satellite-to-ground\" convention, and \"up\" is\n negative.\n nodata (float): value to use for nodata if geocoding. Defaults to 0.\n \"\"\"\n cmd = f'gdal_calc.py --quiet -A {infile} -B {infile} --A_band=1 --B_band=2 --outfile tmp_los_east.tif --calc=\"sin(deg2rad(A)) * cos(deg2rad(B+90))\" '\n print(cmd)\n subprocess.run(cmd, check=True, shell=True)\n\n cmd = f'gdal_calc.py --quiet -A {infile} -B {infile} --A_band=1 --B_band=2 --outfile tmp_los_north.tif --calc=\"sin(deg2rad(A)) * sin(deg2rad(B+90))\" '\n print(cmd)\n subprocess.run(cmd, check=True, shell=True)\n\n cmd = f'gdal_calc.py --quiet -A {infile} -B {infile} --A_band=1 --B_band=2 --outfile tmp_los_up.tif --calc=\"cos(deg2rad(A))\" '\n print(cmd)\n subprocess.run(cmd, check=True, shell=True)\n\n cmd = f\"gdal_merge.py -separate -o {outfile} tmp_los_east.tif tmp_los_north.tif tmp_los_up.tif \"\n print(cmd)\n subprocess.run(cmd, check=True, shell=True)\n subprocess.run(\n \"rm -f tmp_los_east.tif tmp_los_north.tif tmp_los_up.tif\",\n shell=True,\n check=True,\n )\n temp_enu = \"temp_los_enu.tif\"\n if do_geocode:\n from apertools import geocode\n\n logger.info(\"Geocoding LOS file\")\n os.rename(outfile, temp_enu)\n # Assume the infile is in a geom dir...\n geom_dir = os.path.dirname(infile)\n lon_file = os.path.join(geom_dir, \"lon.rdr\")\n lat_file = os.path.join(geom_dir, \"lat.rdr\")\n geocode.geocode(\n infile=temp_enu,\n outfile=outfile,\n lat=lat_file,\n lon=lon_file,\n lat_step=latlon_step,\n lon_step=latlon_step,\n nodata=nodata,\n )\n os.remove(temp_enu)\n if invert:\n logger.info(\"Inverting LOS direction\")\n cmd = (\n f\"gdal_calc.py --quiet --NoDataValue={nodata} --allBands=A -A {outfile} \"\n f' --outfile={temp_enu} --calc \"-1 * A\" '\n )\n logger.info(cmd)\n subprocess.run(cmd, check=True, shell=True)\n os.rename(temp_enu, outfile)\n\n\ndef enu_to_az_inc(infile, outfile=\"los_az_inc.tif\"):\n \"\"\"Convert 3-band ENU LOS to ISCE convention of azimuth-elevation\n\n Here, LOS points FROM ground, TO satellite (reveresed from our other convention).\n Channel 1: Incidence angle measured from vertical at target (always positive)\n Channel 2: Azimuth angle is measured from North in the anti-clockwise direction.\n\n References:\n http://earthdef.caltech.edu/boards/4/topics/1915?r=1919#message-1919\n http://earthdef.caltech.edu/boards/4/topics/327\n \"\"\"\n # Note: A = xEast, B = yNorth, C = zUp\n # inc = atan2(sqrt(x**2 + y**2), abs(z))\n tmp_inc = \"tmp_los_inc.tif\"\n cmd = (\n f\"gdal_calc.py --quiet -A {infile} -B {infile} -C {infile} --A_band=1 --B_band=2 --C_band=3 \"\n f'--outfile {tmp_inc} --calc=\"rad2deg(arctan2(sqrt(A **2 + B**2), abs(C)))\" '\n )\n subprocess.run(cmd, check=True, shell=True)\n # -90 + rad2deg(arctan2( -yNorth, -xEast ))\n tmp_az = \"tmp_los_az.tif\"\n cmd = (\n f\"gdal_calc.py --quiet -A {infile} -B {infile} --A_band=1 --B_band=2 \"\n f'--outfile {tmp_az} --calc=\" -90 + rad2deg(arctan2(-B, -A ))\" '\n )\n subprocess.run(cmd, check=True, shell=True)\n cmd = f\"gdal_merge.py -separate -o {outfile} {tmp_inc} {tmp_az} \"\n subprocess.run(cmd, check=True, shell=True)\n subprocess.run(f\"rm -f {tmp_inc} {tmp_az}\", shell=True, check=True)\n\n\ndef velo_to_cumulative_scale(slclist):\n ndays = (slclist[-1] - slclist[0]).days\n # input is MM/year\n # (mm/year) * (1 yr / 365 days) * (1 cm / 10 mm) * ndays => [cm]\n return ndays / 365 / 10\n\n\ndef find_largest_component_idxs(binimg, strel_size=2):\n from skimage.morphology import disk, closing\n from skimage import measure\n from collections import Counter\n\n selem = disk(strel_size)\n img = closing(binimg, selem)\n labels, num = measure.label(img, return_num=True, connectivity=2)\n counts = Counter(labels.reshape(-1))\n # Get the top label which is not 0, the background\n top2 = sorted(counts.items(), key=lambda x: x[1], reverse=True)[:2]\n fg_label, fg_count = top2[0] if top2[0][0] != 0 else top2[1]\n return labels == fg_label\n\n\ndef pprint_lon_lat(lon, lat, decimals=0):\n \"\"\"Pretty print a lat and and lon\n\n Examples:\n >>> pprint_lon_lat(-104.52, 31.123)\n 'N31W105'\n >>> pprint_lon_lat(-104.52, 31.123, decimals=1)\n 'N31.1W104.5'\n \"\"\"\n # Note: strings must be formatted twice:\n # ff = f\"{{:02.1f}}\" ; f\"{hemi_ew}{ff}\".format(32.123)\n # 'E32.1\n hemi_ns = \"N\" if lat >= 0 else \"S\"\n format_lat = \"{:02.\" + str(decimals) + \"f}\"\n lat_str = f\"{hemi_ns}{format_lat}\".format(abs(lat))\n\n hemi_ew = \"E\" if lon >= 0 else \"W\"\n format_lon = \"{:03.\" + str(decimals) + \"f}\"\n lon_str = f\"{hemi_ew}{format_lon}\".format(abs(lon))\n return f\"{lat_str}{lon_str}\"\n\n\ndef block_iterator(arr_shape, block_shape, overlaps=(0, 0), start_offsets=(0, 0)):\n \"\"\"Iterator to get indexes for accessing blocks of a raster\n\n Args:\n arr_shape = (num_rows, num_cols), full size of array to access\n block_shape = (height, width), size of accessing blocks\n overlaps = (row_overlap, col_overlap), number of pixels to re-include\n after sliding the block (default (0, 0))\n start_offset = (row_offset, col_offset) starting location (default (0,0))\n Yields:\n iterator: ((row_start, row_end), (col_start, col_end))\n\n Notes:\n If the block_shape/overlaps don't evenly divide the full arr_shape,\n It will return the edges as smaller blocks, rather than skip them\n\n Examples:\n >>> list(block_iterator((180, 250), (100, 100)))\n [((0, 100), (0, 100)), ((0, 100), (100, 200)), ((0, 100), (200, 250)), \\\n((100, 180), (0, 100)), ((100, 180), (100, 200)), ((100, 180), (200, 250))]\n >>> list(block_iterator((180, 250), (100, 100), overlaps=(10, 10)))\n [((0, 100), (0, 100)), ((0, 100), (90, 190)), ((0, 100), (180, 250)), \\\n((90, 180), (0, 100)), ((90, 180), (90, 190)), ((90, 180), (180, 250))]\n \"\"\"\n rows, cols = arr_shape\n row_off, col_off = start_offsets\n row_overlap, col_overlap = overlaps\n height, width = block_shape\n\n if height is None:\n height = rows\n if width is None:\n width = cols\n\n # Check we're not moving backwards with the overlap:\n if row_overlap >= height:\n raise ValueError(f\"{row_overlap = } must be less than {height = }\")\n if col_overlap >= width:\n raise ValueError(f\"{col_overlap = } must be less than {width = }\")\n while row_off < rows:\n while col_off < cols:\n row_end = min(row_off + height, rows) # Dont yield something OOB\n col_end = min(col_off + width, cols)\n yield ((row_off, row_end), (col_off, col_end))\n\n col_off += width\n if col_off < cols: # dont bring back if already at edge\n col_off -= col_overlap\n\n row_off += height\n if row_off < rows:\n row_off -= row_overlap\n col_off = 0\n\n\ndef read_blocks(\n filename, band=1, window_shape=(None, None), overlaps=(0, 0), start_offsets=(0, 0)\n):\n from rasterio.windows import Window\n import rasterio as rio\n\n with rio.open(filename) as src:\n block_iter = block_iterator(\n src.shape,\n window_shape,\n overlaps=overlaps,\n start_offsets=start_offsets,\n )\n for win_slice in block_iter:\n window = Window.from_slices(*win_slice)\n yield src.read(band, window=window)\n\n\ndef memmap_blocks(\n filename, full_shape, block_rows, dtype, overlaps=(0, 0), start_offsets=(0, 0)\n):\n total_rows, total_cols = full_shape\n block_iter = block_iterator(\n full_shape,\n (block_rows, total_cols),\n overlaps=overlaps,\n start_offsets=start_offsets,\n )\n dtype = np.dtype(dtype)\n for block_idxs in block_iter:\n row_start = block_idxs[0][0]\n offset = total_cols * row_start * dtype.itemsize\n cur_block = np.memmap(\n filename,\n mode=\"r\",\n dtype=dtype,\n offset=offset,\n shape=(block_rows, total_cols),\n )\n yield cur_block\n\n\ndef get_stack_block_shape(\n h5_stack_file, dset, target_block_size=100e6, default_chunk_size=(None, 10, 10)\n):\n \"\"\"Find a shape of blocks to load from `h5_stack_file` with memory size < `target_block_size`\n\n Args:\n h5_stack_file (str): HDF5 file name containing 3D dataset\n dset (str): name of 3D dataset within `h5_stack_file`\n target_block_size (float, optional): target size of memory for blocks. Defaults to 100e6.\n default_chunk_size (tuple/list, optional): If `dset` is not chunked, size to use as chunks.\n Defaults to (None, 10, 10).\n\n Returns:\n [type]: [description]\n \"\"\"\n import h5py\n\n with h5py.File(h5_stack_file) as hf:\n full_shape = hf[dset].shape\n nstack = full_shape[0]\n # Use the HDF5 chunk size, if the dataset is chunked.\n chunk_size = list(hf[dset].chunks) or default_chunk_size\n chunk_size[0] = nstack # always load a full depth slice at once\n\n nbytes = hf[dset].dtype.itemsize\n\n # Figure out how much to load at 1 time, staying at ~`target_block_size` bytes of RAM\n chunks_per_block = target_block_size / (np.prod(chunk_size) * nbytes)\n row_chunks, col_chunks = 1, 1\n cur_block_shape = list(copy.copy(chunk_size))\n while chunks_per_block > 1:\n # First keep incrementing the number of rows we grab at once time\n if row_chunks * chunk_size[1] < full_shape[1]:\n row_chunks += 1\n cur_block_shape[1] = min(row_chunks * chunk_size[1], full_shape[1])\n # Then increase the column size if still haven't hit `target_block_size`\n elif col_chunks * chunk_size[2] < full_shape[2]:\n col_chunks += 1\n cur_block_shape[2] = min(col_chunks * chunk_size[2], full_shape[2])\n else:\n break\n chunks_per_block = target_block_size / (np.prod(cur_block_shape) * nbytes)\n return cur_block_shape\n\n\ndef ifg_to_mag_phase(filename, outname=None, driver=None):\n \"\"\"Convert a complex float interferogram into a 2-band raster of magnitude/phase\"\"\"\n import rasterio as rio\n from copy import deepcopy\n\n if not outname:\n _, ext = os.path.splitext(filename)\n outname = filename.replace(ext, ext + \".mph\")\n driver = \"ENVI\"\n print(\"saving to\", outname, \"with driver\", driver)\n\n with rio.open(filename) as src:\n arr = src.read(1)\n out_meta = deepcopy(src.meta)\n out_meta[\"count\"] = 2\n out_meta[\"dtype\"] = \"float32\"\n allowed_drivers = (\"isce\", \"envi\", \"gtiff\")\n if driver:\n if driver.lower() not in allowed_drivers:\n raise ValueError(\"Driver must be in {}\".format(allowed_drivers))\n out_meta[\"driver\"] = driver\n if out_meta[\"driver\"].lower() == \"envi\":\n # make sure the .hdr is appended after everything\n # -of ENVI -co SUFFIX=ADD\n out_meta[\"SUFFIX\"] = \"ADD\"\n print(out_meta)\n with rio.open(outname, \"w\", **out_meta) as dst:\n dst.write(np.abs(arr), 1)\n dst.write(np.angle(arr), 2)\n\n\[email protected]\ndef chdir_then_revert(path):\n \"\"\"Temporarily change directory to `path`, then go back to original working dir\n\n with chdir_then_revert('temp_dir'):\n #...do stuff\n # now back in original\n \"\"\"\n orig_path = os.getcwd()\n try:\n os.chdir(path)\n yield\n finally:\n os.chdir(orig_path)\n"
] | [
[
"numpy.abs",
"numpy.issubdtype",
"numpy.memmap",
"numpy.dtype",
"numpy.concatenate",
"numpy.lib.stride_tricks.as_strided",
"numpy.ma.masked_equal",
"numpy.log10",
"numpy.asanyarray",
"numpy.any",
"numpy.prod",
"numpy.iscomplexobj",
"numpy.exp",
"numpy.angle",
"numpy.array",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dreamingleo/glow | [
"8f9649bf1e1244692f2e14bdf57720f683d82618"
] | [
"torch_glow/tests/nodes/quantized_conv2d_test.py"
] | [
"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport torch\n\nfrom tests.utils import jitVsGlow\nimport pytest\n\n\ndef test_quantized_conv2d():\n \"\"\"Basic test of the PyTorch quantized onv2d Node on Glow.\"\"\"\n\n def test_f(a, w, b):\n qu = torch.nn.quantized.Quantize(1/16, 0, torch.quint8)\n qi = torch.nn.quantized.Quantize(1/16, 0, torch.qint8)\n dq = torch.nn.quantized.DeQuantize()\n conv = torch.nn.quantized.functional.conv2d\n return dq(conv(qu(a), qi(w), b))\n\n # TODO\n # Due to the quantization error between\n # PyTorch and Glow, we would like to use some\n # determined test data instead of random ones\n # x = torch.randn([3, 3, 3, 3])\n # w = torch.randn([3, 3, 3, 3])\n # b = torch.randn([3])\n\n x = torch.tensor([[[[5., 6.], [7., 8.]]]])\n w = torch.tensor([[[[1., 2.], [3., 4.]]]])\n b_zero = torch.zeros(1)\n b = torch.randn(1)\n\n jitVsGlow(test_f, x, w, b, expected_fused_ops={\"aten::quantize_per_tensor\",\n \"glow::unpacked_quantized_conv2d\",\n \"aten::dequantize\"})\n\n jitVsGlow(test_f, x, w, b_zero, expected_fused_ops={\"aten::quantize_per_tensor\",\n \"glow::unpacked_quantized_conv2d\",\n \"aten::dequantize\"})\n\n\[email protected](reason=\"accuracy between glow & pytorch\")\ndef test_quantized_conv2d_nonfunctional():\n \"\"\"Basic test of the PyTorch quantized conv2d Node with external quantized\n input on Glow.\"\"\"\n\n def test_f(a):\n q = torch.nn.quantized.Quantize(1/16, 0, torch.quint8)\n dq = torch.nn.quantized.DeQuantize()\n conv = torch.nn.quantized.Conv2d(1, 1, [2, 2])\n return dq(conv(q(a)))\n\n x = torch.tensor([[[[5., 6.], [7., 8.]]]])\n\n jitVsGlow(test_f, x, expected_fused_ops={\"aten::quantize_per_tensor\",\n \"glow::unpacked_quantized_conv2d\",\n \"aten::dequantize\"})\n"
] | [
[
"torch.nn.quantized.Conv2d",
"torch.nn.quantized.DeQuantize",
"torch.zeros",
"torch.randn",
"torch.tensor",
"torch.nn.quantized.Quantize"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SmartWarehouse-UAntwerpen/habitat-api | [
"c4e86bbb945060254355a0c70a25ecf5246a1a12"
] | [
"habitat_baselines/eval_habitat_agent_in_ros.py"
] | [
"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# LICENSE file in the root directory of this source tree.\n\n# this script is a prototype implementation of transferring Habitat trained agent to the real world/physics enabled environment.\n# in summary, this script does the following:\n# 1. import habitat trained model\n# 2. subscribe to topic that contain sensor readings related to habitat trained model\n# 3. obtain an action_id from trained model and command agent to perform that action. Then stop subscribing to the topic\n# 4. Wait until agent finishes that action command or some time has passed\n# 5. Repeat steps 2-4 until agent reaches the goal\n\n\n# To run:\n# 1. start roscore\n# 2. source your ros related setup.bash files\n# 3. run this script with python (not rosrun!)\n# 4. If testing in physics enabled habitat environment, run hab_ros_interface.py. Important! depth camera need resolution 256x256\n# 4.1 If testing in a gazebo environment, first roslaunch habitat_interface trained_agent_in_gazebo.launch, then rosrun habitat_interface get_pointnav_depth_obs.py\n# 5. run roslaunch habitat_interface default.launch to visualize what the agent is doing\n\nimport sys\nimport os\n\nPKG = \"numpy_tutorial\"\nimport roslib\n\nroslib.load_manifest(PKG)\n\nimport rospy\nfrom rospy.numpy_msg import numpy_msg\nfrom rospy_tutorials.msg import Floats\nfrom geometry_msgs.msg import Twist\nimport numpy as np\n\n\ninitial_sys_path = sys.path\nsys.path = [b for b in sys.path if \"2.7\" not in b]\nsys.path.insert(0, os.getcwd())\n\n\nimport argparse\nimport torch\nimport habitat\nfrom habitat.config.default import get_config\nfrom config.default import get_config as cfg_baseline\n\nfrom train_ppo import make_env_fn\nfrom rl.ppo import PPO, Policy\nfrom rl.ppo.utils import batch_obs\nimport time\n\n\nsys.path = initial_sys_path\n\n\npub_vel = rospy.Publisher(\"cmd_vel\", Twist, queue_size=1)\nrospy.init_node(\"controller_nn\", anonymous=True)\n\n# define some useful global variables\nflag = 2\nobservation = {}\nt_prev_update = time.time()\n\n\ndef pol2cart(rho, phi):\n x = rho * np.cos(phi)\n y = rho * np.sin(phi)\n return (x, y)\n\n\ndef main():\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model-path\", type=str, required=True)\n parser.add_argument(\"--sim-gpu-id\", type=int, required=True)\n parser.add_argument(\"--pth-gpu-id\", type=int, required=True)\n parser.add_argument(\"--num-processes\", type=int, required=True)\n parser.add_argument(\"--hidden-size\", type=int, default=512)\n parser.add_argument(\"--count-test-episodes\", type=int, default=100)\n parser.add_argument(\n \"--sensors\",\n type=str,\n default=\"DEPTH_SENSOR\",\n help=\"comma separated string containing different\"\n \"sensors to use, currently 'RGB_SENSOR' and\"\n \"'DEPTH_SENSOR' are supported\",\n )\n parser.add_argument(\n \"--task-config\",\n type=str,\n default=\"configs/tasks/pointnav.yaml\",\n help=\"path to config yaml containing information about task\",\n )\n\n cmd_line_inputs = [\n \"--model-path\",\n \"/home/bruce/NSERC_2019/habitat-api/data/checkpoints/depth.pth\",\n \"--sim-gpu-id\",\n \"0\",\n \"--pth-gpu-id\",\n \"0\",\n \"--num-processes\",\n \"1\",\n \"--count-test-episodes\",\n \"100\",\n \"--task-config\",\n \"configs/tasks/pointnav.yaml\",\n ]\n args = parser.parse_args(cmd_line_inputs)\n\n device = torch.device(\"cuda:{}\".format(args.pth_gpu_id))\n\n env_configs = []\n baseline_configs = []\n\n for _ in range(args.num_processes):\n config_env = get_config(config_paths=args.task_config)\n config_env.defrost()\n config_env.DATASET.SPLIT = \"val\"\n\n agent_sensors = args.sensors.strip().split(\",\")\n for sensor in agent_sensors:\n assert sensor in [\"RGB_SENSOR\", \"DEPTH_SENSOR\"]\n config_env.SIMULATOR.AGENT_0.SENSORS = agent_sensors\n config_env.freeze()\n env_configs.append(config_env)\n\n config_baseline = cfg_baseline()\n baseline_configs.append(config_baseline)\n\n assert len(baseline_configs) > 0, \"empty list of datasets\"\n\n envs = habitat.VectorEnv(\n make_env_fn=make_env_fn,\n env_fn_args=tuple(\n tuple(zip(env_configs, baseline_configs, range(args.num_processes)))\n ),\n )\n\n ckpt = torch.load(args.model_path, map_location=device)\n\n actor_critic = Policy(\n observation_space=envs.observation_spaces[0],\n action_space=envs.action_spaces[0],\n hidden_size=512,\n goal_sensor_uuid=\"pointgoal\",\n )\n actor_critic.to(device)\n\n ppo = PPO(\n actor_critic=actor_critic,\n clip_param=0.1,\n ppo_epoch=4,\n num_mini_batch=32,\n value_loss_coef=0.5,\n entropy_coef=0.01,\n lr=2.5e-4,\n eps=1e-5,\n max_grad_norm=0.5,\n )\n\n ppo.load_state_dict(ckpt[\"state_dict\"])\n\n actor_critic = ppo.actor_critic\n\n observations = envs.reset()\n batch = batch_obs(observations)\n for sensor in batch:\n batch[sensor] = batch[sensor].to(device)\n\n test_recurrent_hidden_states = torch.zeros(\n args.num_processes, args.hidden_size, device=device\n )\n not_done_masks = torch.zeros(args.num_processes, 1, device=device)\n\n def transform_callback(data):\n nonlocal actor_critic\n nonlocal batch\n nonlocal not_done_masks\n nonlocal test_recurrent_hidden_states\n global flag\n global t_prev_update\n global observation\n\n if flag == 2:\n observation[\"depth\"] = np.reshape(data.data[0:-2], (256, 256, 1))\n observation[\"pointgoal\"] = data.data[-2:]\n flag = 1\n return\n\n pointgoal_received = data.data[-2:]\n translate_amount = 0.25 # meters\n rotate_amount = 0.174533 # radians\n\n isrotated = (\n rotate_amount * 0.95\n <= abs(pointgoal_received[1] - observation[\"pointgoal\"][1])\n <= rotate_amount * 1.05\n )\n istimeup = (time.time() - t_prev_update) >= 4\n\n # print('istranslated is '+ str(istranslated))\n # print('isrotated is '+ str(isrotated))\n # print('istimeup is '+ str(istimeup))\n\n if isrotated or istimeup:\n vel_msg = Twist()\n vel_msg.linear.x = 0\n vel_msg.linear.y = 0\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n pub_vel.publish(vel_msg)\n time.sleep(0.2)\n print(\"entered update step\")\n\n # cv2.imshow(\"Depth\", observation['depth'])\n # cv2.waitKey(100)\n\n observation[\"depth\"] = np.reshape(data.data[0:-2], (256, 256, 1))\n observation[\"pointgoal\"] = data.data[-2:]\n\n batch = batch_obs([observation])\n for sensor in batch:\n batch[sensor] = batch[sensor].to(device)\n if flag == 1:\n not_done_masks = torch.tensor([0.0], dtype=torch.float, device=device)\n flag = 0\n else:\n not_done_masks = torch.tensor([1.0], dtype=torch.float, device=device)\n\n _, actions, _, test_recurrent_hidden_states = actor_critic.act(\n batch, test_recurrent_hidden_states, not_done_masks, deterministic=True\n )\n\n action_id = actions.item()\n print(\n \"observation received to produce action_id is \"\n + str(observation[\"pointgoal\"])\n )\n print(\"action_id from net is \" + str(actions.item()))\n\n t_prev_update = time.time()\n vel_msg = Twist()\n vel_msg.linear.x = 0\n vel_msg.linear.y = 0\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n if action_id == 0:\n vel_msg.linear.x = 0.25 / 4\n pub_vel.publish(vel_msg)\n elif action_id == 1:\n vel_msg.angular.z = 10 / 180 * 3.1415926\n pub_vel.publish(vel_msg)\n elif action_id == 2:\n vel_msg.angular.z = -10 / 180 * 3.1415926\n pub_vel.publish(vel_msg)\n else:\n pub_vel.publish(vel_msg)\n sub.unregister()\n print(\"NN finished navigation task\")\n\n sub = rospy.Subscriber(\n \"depth_and_pointgoal\", numpy_msg(Floats), transform_callback, queue_size=1\n )\n rospy.spin()\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"torch.zeros",
"numpy.reshape",
"torch.load",
"numpy.cos",
"numpy.sin",
"torch.tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
WeichenXu123/koalas | [
"224cbe4a1c7a2b12976069762379d0e77e46750b",
"224cbe4a1c7a2b12976069762379d0e77e46750b"
] | [
"databricks/koalas/tests/test_frame_plot.py",
"databricks/koalas/tests/test_etl.py"
] | [
"import base64\nfrom io import BytesIO\n\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nfrom databricks import koalas\nfrom databricks.koalas.config import set_option, reset_option\nfrom databricks.koalas.plot import TopNPlot, SampledPlot\nfrom databricks.koalas.exceptions import PandasNotImplementedError\nfrom databricks.koalas.testing.utils import ReusedSQLTestCase, TestUtils\n\n\nmatplotlib.use('agg')\n\n\nclass DataFramePlotTest(ReusedSQLTestCase, TestUtils):\n sample_ratio_default = None\n\n @classmethod\n def setUpClass(cls):\n super(DataFramePlotTest, cls).setUpClass()\n set_option('plotting.max_rows', 2000)\n set_option('plotting.sample_ratio', None)\n\n @classmethod\n def tearDownClass(cls):\n reset_option('plotting.max_rows')\n reset_option('plotting.sample_ratio')\n super(DataFramePlotTest, cls).tearDownClass()\n\n @property\n def pdf1(self):\n return pd.DataFrame({\n 'a': [1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 50],\n 'b': [2, 3, 4, 5, 7, 9, 10, 15, 34, 45, 49]\n }, index=[0, 1, 3, 5, 6, 8, 9, 9, 9, 10, 10])\n\n @property\n def kdf1(self):\n return koalas.from_pandas(self.pdf1)\n\n @staticmethod\n def plot_to_base64(ax):\n bytes_data = BytesIO()\n ax.figure.savefig(bytes_data, format='png')\n bytes_data.seek(0)\n b64_data = base64.b64encode(bytes_data.read())\n plt.close(ax.figure)\n return b64_data\n\n def compare_plots(self, ax1, ax2):\n self.assert_eq(self.plot_to_base64(ax1), self.plot_to_base64(ax2))\n\n def test_line_plot(self):\n pdf = self.pdf1\n kdf = self.kdf1\n\n ax1 = pdf.plot(kind=\"line\", colormap='Paired')\n ax2 = kdf.plot(kind=\"line\", colormap='Paired')\n self.compare_plots(ax1, ax2)\n\n ax3 = pdf.plot.line(colormap='Paired')\n ax4 = kdf.plot.line(colormap='Paired')\n self.compare_plots(ax3, ax4)\n\n def test_area_plot(self):\n pdf = self.pdf1\n kdf = self.kdf1\n\n ax1 = pdf.plot(kind=\"area\", colormap='Paired')\n ax2 = kdf.plot(kind=\"area\", colormap='Paired')\n self.compare_plots(ax1, ax2)\n\n ax3 = pdf.plot.area(colormap='Paired')\n ax4 = kdf.plot.area(colormap='Paired')\n self.compare_plots(ax3, ax4)\n\n def test_area_plot_stacked_false(self):\n # test if frame area plot is correct when stacked=False because default is True\n pdf = pd.DataFrame({\n 'sales': [3, 2, 3, 9, 10, 6],\n 'signups': [5, 5, 6, 12, 14, 13],\n 'visits': [20, 42, 28, 62, 81, 50],\n }, index=pd.date_range(start='2018/01/01', end='2018/07/01', freq='M'))\n kdf = koalas.from_pandas(pdf)\n\n ax1 = pdf.plot.area(stacked=False)\n ax2 = kdf.plot.area(stacked=False)\n self.compare_plots(ax1, ax2)\n\n def test_area_plot_y(self):\n # test if frame area plot is correct when y is specified\n pdf = pd.DataFrame({\n 'sales': [3, 2, 3, 9, 10, 6],\n 'signups': [5, 5, 6, 12, 14, 13],\n 'visits': [20, 42, 28, 62, 81, 50],\n }, index=pd.date_range(start='2018/01/01', end='2018/07/01', freq='M'))\n kdf = koalas.from_pandas(pdf)\n\n ax1 = pdf.plot.area(y='sales')\n ax2 = kdf.plot.area(y='sales')\n self.compare_plots(ax1, ax2)\n\n def test_barh_plot_with_x_y(self):\n # this is testing plot with specified x and y\n pdf = pd.DataFrame({'lab': ['A', 'B', 'C'], 'val': [10, 30, 20]})\n kdf = koalas.from_pandas(pdf)\n\n ax1 = pdf.plot(kind=\"barh\", x='lab', y='val', colormap='Paired')\n ax2 = kdf.plot(kind=\"barh\", x='lab', y='val', colormap='Paired')\n self.compare_plots(ax1, ax2)\n\n ax3 = pdf.plot.barh(x='lab', y='val', colormap='Paired')\n ax4 = kdf.plot.barh(x='lab', y='val', colormap='Paired')\n self.compare_plots(ax3, ax4)\n\n def test_barh_plot(self):\n # this is testing when x or y is not assigned\n pdf = pd.DataFrame({'lab': ['A', 'B', 'C'], 'val': [10, 30, 20]})\n kdf = koalas.from_pandas(pdf)\n\n ax1 = pdf.plot(kind=\"barh\", colormap='Paired')\n ax2 = kdf.plot(kind=\"barh\", colormap='Paired')\n self.compare_plots(ax1, ax2)\n\n ax3 = pdf.plot.barh(colormap='Paired')\n ax4 = kdf.plot.barh(colormap='Paired')\n self.compare_plots(ax3, ax4)\n\n def test_bar_plot(self):\n pdf = self.pdf1\n kdf = self.kdf1\n\n ax1 = pdf.plot(kind='bar', colormap='Paired')\n ax2 = kdf.plot(kind='bar', colormap='Paired')\n self.compare_plots(ax1, ax2)\n\n ax3 = pdf.plot.bar(colormap='Paired')\n ax4 = kdf.plot.bar(colormap='Paired')\n self.compare_plots(ax3, ax4)\n\n def test_bar_with_x_y(self):\n # this is testing plot with specified x and y\n pdf = pd.DataFrame({'lab': ['A', 'B', 'C'], 'val': [10, 30, 20]})\n kdf = koalas.from_pandas(pdf)\n\n ax1 = pdf.plot(kind=\"bar\", x='lab', y='val', colormap='Paired')\n ax2 = kdf.plot(kind=\"bar\", x='lab', y='val', colormap='Paired')\n self.compare_plots(ax1, ax2)\n\n ax3 = pdf.plot.bar(x='lab', y='val', colormap='Paired')\n ax4 = kdf.plot.bar(x='lab', y='val', colormap='Paired')\n self.compare_plots(ax3, ax4)\n\n def test_pie_plot(self):\n pdf = pd.DataFrame({'mass': [0.330, 4.87, 5.97], 'radius': [2439.7, 6051.8, 6378.1]},\n index=['Mercury', 'Venus', 'Earth'])\n kdf = koalas.from_pandas(pdf)\n\n ax1 = pdf.plot.pie(y='mass', figsize=(5, 5), colormap='Paired')\n ax2 = kdf.plot.pie(y='mass', figsize=(5, 5), colormap='Paired')\n self.compare_plots(ax1, ax2)\n\n ax1 = pdf.plot(kind=\"pie\", y='mass', figsize=(5, 5), colormap='Paired')\n ax2 = kdf.plot(kind=\"pie\", y='mass', figsize=(5, 5), colormap='Paired')\n self.compare_plots(ax1, ax2)\n\n ax11, ax12 = pdf.plot.pie(figsize=(5, 5), subplots=True, colormap='Paired')\n ax21, ax22 = kdf.plot.pie(figsize=(5, 5), subplots=True, colormap='Paired')\n self.compare_plots(ax11, ax21)\n self.compare_plots(ax12, ax22)\n\n ax11, ax12 = pdf.plot(kind=\"pie\", figsize=(5, 5), subplots=True, colormap='Paired')\n ax21, ax22 = kdf.plot(kind=\"pie\", figsize=(5, 5), subplots=True, colormap='Paired')\n self.compare_plots(ax11, ax21)\n self.compare_plots(ax12, ax22)\n\n def test_pie_plot_error_message(self):\n # this is to test if error is correctly raising when y is not specified\n # and subplots is not set to True\n pdf = pd.DataFrame({'mass': [0.330, 4.87, 5.97], 'radius': [2439.7, 6051.8, 6378.1]},\n index=['Mercury', 'Venus', 'Earth'])\n kdf = koalas.from_pandas(pdf)\n\n with self.assertRaises(ValueError) as context:\n kdf.plot.pie(figsize=(5, 5), colormap='Paired')\n error_message = \"pie requires either y column or 'subplots=True'\"\n self.assertTrue(error_message in str(context.exception))\n\n def test_scatter_plot(self):\n # Use pandas scatter plot example\n pdf = pd.DataFrame(np.random.rand(50, 4), columns=['a', 'b', 'c', 'd'])\n kdf = koalas.from_pandas(pdf)\n\n ax1 = pdf.plot.scatter(x='a', y='b')\n ax2 = kdf.plot.scatter(x='a', y='b')\n self.compare_plots(ax1, ax2)\n\n ax1 = pdf.plot(kind='scatter', x='a', y='b')\n ax2 = kdf.plot(kind='scatter', x='a', y='b')\n self.compare_plots(ax1, ax2)\n\n # check when keyword c is given as name of a column\n ax1 = pdf.plot.scatter(x='a', y='b', c='c', s=50)\n ax2 = kdf.plot.scatter(x='a', y='b', c='c', s=50)\n self.compare_plots(ax1, ax2)\n\n def test_missing(self):\n ks = self.kdf1\n\n unsupported_functions = ['box', 'density', 'hexbin', 'hist', 'kde']\n\n for name in unsupported_functions:\n with self.assertRaisesRegex(PandasNotImplementedError,\n \"method.*DataFrame.*{}.*not implemented\".format(name)):\n getattr(ks.plot, name)()\n\n def test_topn_max_rows(self):\n\n pdf = pd.DataFrame(np.random.rand(2500, 4), columns=['a', 'b', 'c', 'd'])\n kdf = koalas.from_pandas(pdf)\n\n data = TopNPlot().get_top_n(kdf)\n self.assertEqual(len(data), 2000)\n\n def test_sampled_plot_with_ratio(self):\n set_option('plotting.sample_ratio', 0.5)\n try:\n pdf = pd.DataFrame(np.random.rand(2500, 4), columns=['a', 'b', 'c', 'd'])\n kdf = koalas.from_pandas(pdf)\n data = SampledPlot().get_sampled(kdf)\n self.assertEqual(round(len(data) / 2500, 1), 0.5)\n finally:\n set_option('plotting.sample_ratio', DataFramePlotTest.sample_ratio_default)\n\n def test_sampled_plot_with_max_rows(self):\n # 'plotting.max_rows' is 2000\n pdf = pd.DataFrame(np.random.rand(2000, 4), columns=['a', 'b', 'c', 'd'])\n kdf = koalas.from_pandas(pdf)\n data = SampledPlot().get_sampled(kdf)\n self.assertEqual(round(len(data) / 2000, 1), 1)\n",
"#\n# Copyright (C) 2019 Databricks, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os\n\nimport pandas as pd\n\nfrom databricks.koalas.testing.utils import ComparisonTestBase, compare_both\n\n\nclass EtlTest(ComparisonTestBase):\n\n @property\n def pdf(self):\n test_dir = os.path.dirname(os.path.realpath(__file__))\n return pd.read_csv('%s/../../../data/sample_stocks.csv' % test_dir)\n\n @compare_both\n def test_etl(self, df):\n df1 = df.loc[:, 'Symbol Date Open High Low Close'.split()]\n yield df1\n\n df2 = df1.sort_values(by=[\"Symbol\", \"Date\"])\n yield df2\n\n df3 = df2.groupby(by=\"Symbol\").agg({\n 'Open': 'first',\n 'High': 'max',\n 'Low': 'min',\n 'Close': 'last'\n })\n yield df3\n\n df4 = df2.copy()\n\n df4.loc[:, 'signal_1'] = df4.Close - df4.Open\n df4.loc[:, 'signal_2'] = df4.High - df4.Low\n\n # df4.loc[:, 'signal_3'] = (df4.signal_2 - df4.signal_2.mean()) / df4.signal_2.std()\n yield df4\n\n df5 = df4.loc[df4.signal_1 > 0, ['Symbol', 'Date']]\n yield df5\n\n df6 = df4.loc[df4.signal_2 > 0, ['Symbol', 'Date']]\n yield df6\n\n # df7 = df4.loc[df4.signal_3 > 0, ['Symbol', 'Date']]\n # yield df7\n"
] | [
[
"matplotlib.use",
"pandas.DataFrame",
"numpy.random.rand",
"matplotlib.pyplot.close",
"pandas.date_range"
],
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
raybellwaves/geopandas | [
"592abf7f596ef4cf9b78c2706f69e83d8005821f",
"592abf7f596ef4cf9b78c2706f69e83d8005821f",
"592abf7f596ef4cf9b78c2706f69e83d8005821f"
] | [
"geopandas/base.py",
"geopandas/io/tests/test_pickle.py",
"geopandas/tests/test_geoseries.py"
] | [
"from warnings import warn\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame, Series\n\nfrom shapely.geometry import box\nfrom shapely.geometry.base import BaseGeometry\nfrom shapely.ops import cascaded_union\n\nfrom .array import GeometryArray, GeometryDtype\n\n\ndef is_geometry_type(data):\n \"\"\"\n Check if the data is of geometry dtype.\n\n Does not include object array of shapely scalars.\n \"\"\"\n if isinstance(getattr(data, \"dtype\", None), GeometryDtype):\n # GeometryArray, GeoSeries and Series[GeometryArray]\n return True\n else:\n return False\n\n\ndef _delegate_binary_method(op, this, other, align, *args, **kwargs):\n # type: (str, GeoSeries, GeoSeries) -> GeoSeries/Series\n this = this.geometry\n if isinstance(other, GeoPandasBase):\n if align and not this.index.equals(other.index):\n warn(\"The indices of the two GeoSeries are different.\")\n this, other = this.align(other.geometry)\n else:\n other = other.geometry\n\n a_this = GeometryArray(this.values)\n other = GeometryArray(other.values)\n elif isinstance(other, BaseGeometry):\n a_this = GeometryArray(this.values)\n else:\n raise TypeError(type(this), type(other))\n\n data = getattr(a_this, op)(other, *args, **kwargs)\n return data, this.index\n\n\ndef _binary_geo(op, this, other, align):\n # type: (str, GeoSeries, GeoSeries) -> GeoSeries\n \"\"\"Binary operation on GeoSeries objects that returns a GeoSeries\"\"\"\n from .geoseries import GeoSeries\n\n geoms, index = _delegate_binary_method(op, this, other, align)\n return GeoSeries(geoms.data, index=index, crs=this.crs)\n\n\ndef _binary_op(op, this, other, align, *args, **kwargs):\n # type: (str, GeoSeries, GeoSeries, args/kwargs) -> Series[bool/float]\n \"\"\"Binary operation on GeoSeries objects that returns a Series\"\"\"\n data, index = _delegate_binary_method(op, this, other, align, *args, **kwargs)\n return Series(data, index=index)\n\n\ndef _delegate_property(op, this):\n # type: (str, GeoSeries) -> GeoSeries/Series\n a_this = GeometryArray(this.geometry.values)\n data = getattr(a_this, op)\n if isinstance(data, GeometryArray):\n from .geoseries import GeoSeries\n\n return GeoSeries(data.data, index=this.index, crs=this.crs)\n else:\n return Series(data, index=this.index)\n\n\ndef _delegate_geo_method(op, this, *args, **kwargs):\n # type: (str, GeoSeries) -> GeoSeries\n \"\"\"Unary operation that returns a GeoSeries\"\"\"\n from .geoseries import GeoSeries\n\n a_this = GeometryArray(this.geometry.values)\n data = getattr(a_this, op)(*args, **kwargs).data\n return GeoSeries(data, index=this.index, crs=this.crs)\n\n\nclass GeoPandasBase(object):\n @property\n def area(self):\n \"\"\"Returns a ``Series`` containing the area of each geometry in the\n ``GeoSeries`` expressed in the units of the CRS.\n\n Examples\n --------\n\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... Polygon([(10, 0), (10, 5), (0, 0)]),\n ... Polygon([(0, 0), (2, 2), (2, 0)]),\n ... LineString([(0, 0), (1, 1), (0, 1)]),\n ... Point(0, 1)\n ... ]\n ... )\n >>> s\n 0 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 1 POLYGON ((10.00000 0.00000, 10.00000 5.00000, ...\n 2 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 2....\n 3 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s.area\n 0 0.5\n 1 25.0\n 2 2.0\n 3 0.0\n 4 0.0\n dtype: float64\n\n See also\n --------\n GeoSeries.length : measure length\n\n Notes\n -----\n Area may be invalid for a geographic CRS using degrees as units;\n use :meth:`GeoSeries.to_crs` to project geometries to a planar\n CRS before using this function.\n\n Every operation in GeoPandas is planar, i.e. the potential third\n dimension is not taken into account.\n \"\"\"\n return _delegate_property(\"area\", self)\n\n @property\n def crs(self):\n \"\"\"\n The Coordinate Reference System (CRS) represented as a ``pyproj.CRS``\n object.\n\n Returns None if the CRS is not set, and to set the value it\n :getter: Returns a ``pyproj.CRS`` or None. When setting, the value\n can be anything accepted by\n :meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`,\n such as an authority string (eg \"EPSG:4326\") or a WKT string.\n\n Examples\n --------\n\n >>> s.crs # doctest: +SKIP\n <Geographic 2D CRS: EPSG:4326>\n Name: WGS 84\n Axis Info [ellipsoidal]:\n - Lat[north]: Geodetic latitude (degree)\n - Lon[east]: Geodetic longitude (degree)\n Area of Use:\n - name: World\n - bounds: (-180.0, -90.0, 180.0, 90.0)\n Datum: World Geodetic System 1984\n - Ellipsoid: WGS 84\n - Prime Meridian: Greenwich\n\n See also\n --------\n GeoSeries.set_crs : assign CRS\n GeoSeries.to_crs : re-project to another CRS\n \"\"\"\n return self.geometry.values.crs\n\n @crs.setter\n def crs(self, value):\n \"\"\"Sets the value of the crs\"\"\"\n self.geometry.values.crs = value\n\n @property\n def geom_type(self):\n \"\"\"\n Returns a ``Series`` of strings specifying the `Geometry Type` of each\n object.\n\n Examples\n --------\n >>> from shapely.geometry import Point, Polygon, LineString\n >>> d = {'geometry': [Point(2, 1), Polygon([(0, 0), (1, 1), (1, 0)]),\n ... LineString([(0, 0), (1, 1)])]}\n >>> gdf = geopandas.GeoDataFrame(d, crs=\"EPSG:4326\")\n >>> gdf.geom_type\n 0 Point\n 1 Polygon\n 2 LineString\n dtype: object\n \"\"\"\n return _delegate_property(\"geom_type\", self)\n\n @property\n def type(self):\n \"\"\"Return the geometry type of each geometry in the GeoSeries\"\"\"\n return self.geom_type\n\n @property\n def length(self):\n \"\"\"Returns a ``Series`` containing the length of each geometry\n expressed in the units of the CRS.\n\n In the case of a (Multi)Polygon it measures the length\n of its exterior (i.e. perimeter).\n\n Examples\n --------\n\n >>> from shapely.geometry import Polygon, LineString, MultiLineString, Point, \\\nGeometryCollection\n >>> s = geopandas.GeoSeries(\n ... [\n ... LineString([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(10, 0), (10, 5), (0, 0)]),\n ... MultiLineString([((0, 0), (1, 0)), ((-1, 0), (1, 0))]),\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... Point(0, 1),\n ... GeometryCollection([Point(1, 0), LineString([(10, 0), (10, 5), (0,\\\n 0)])])\n ... ]\n ... )\n >>> s\n 0 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 1 LINESTRING (10.00000 0.00000, 10.00000 5.00000...\n 2 MULTILINESTRING ((0.00000 0.00000, 1.00000 0.0...\n 3 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 4 POINT (0.00000 1.00000)\n 5 GEOMETRYCOLLECTION (POINT (1.00000 0.00000), L...\n dtype: geometry\n\n >>> s.length\n 0 2.414214\n 1 16.180340\n 2 3.000000\n 3 3.414214\n 4 0.000000\n 5 16.180340\n dtype: float64\n\n See also\n --------\n GeoSeries.area : measure area of a polygon\n\n Notes\n -----\n Length may be invalid for a geographic CRS using degrees as units;\n use :meth:`GeoSeries.to_crs` to project geometries to a planar\n CRS before using this function.\n\n Every operation in GeoPandas is planar, i.e. the potential third\n dimension is not taken into account.\n\n \"\"\"\n return _delegate_property(\"length\", self)\n\n @property\n def is_valid(self):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n geometries that are valid.\n\n Examples\n --------\n\n An example with one invalid polygon (a bowtie geometry crossing itself)\n and one missing geometry:\n\n >>> from shapely.geometry import Polygon\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... Polygon([(0,0), (1, 1), (1, 0), (0, 1)]), # bowtie geometry\n ... Polygon([(0, 0), (2, 2), (2, 0)]),\n ... None\n ... ]\n ... )\n >>> s\n 0 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 1....\n 2 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 2....\n 3 None\n dtype: geometry\n\n >>> s.is_valid\n 0 True\n 1 False\n 2 True\n 3 False\n dtype: bool\n\n \"\"\"\n return _delegate_property(\"is_valid\", self)\n\n @property\n def is_empty(self):\n \"\"\"\n Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n empty geometries.\n\n Examples\n --------\n An example of a GeoDataFrame with one empty point, one point and one missing\n value:\n\n >>> from shapely.geometry import Point\n >>> d = {'geometry': [Point(), Point(2, 1), None]}\n >>> gdf = geopandas.GeoDataFrame(d, crs=\"EPSG:4326\")\n >>> gdf\n geometry\n 0 GEOMETRYCOLLECTION EMPTY\n 1 POINT (2.00000 1.00000)\n 2 None\n >>> gdf.is_empty\n 0 True\n 1 False\n 2 False\n dtype: bool\n\n See Also\n --------\n GeoSeries.isna : detect missing values\n \"\"\"\n return _delegate_property(\"is_empty\", self)\n\n @property\n def is_simple(self):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n geometries that do not cross themselves.\n\n This is meaningful only for `LineStrings` and `LinearRings`.\n\n Examples\n --------\n >>> from shapely.geometry import LineString\n >>> s = geopandas.GeoSeries(\n ... [\n ... LineString([(0, 0), (1, 1), (1, -1), (0, 1)]),\n ... LineString([(0, 0), (1, 1), (1, -1)]),\n ... ]\n ... )\n >>> s\n 0 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 1 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n dtype: geometry\n\n >>> s.is_simple\n 0 False\n 1 True\n dtype: bool\n \"\"\"\n return _delegate_property(\"is_simple\", self)\n\n @property\n def is_ring(self):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n features that are closed.\n\n When constructing a LinearRing, the sequence of coordinates may be\n explicitly closed by passing identical values in the first and last indices.\n Otherwise, the sequence will be implicitly closed by copying the first tuple\n to the last index.\n\n Examples\n --------\n >>> from shapely.geometry import LineString, LinearRing\n >>> s = geopandas.GeoSeries(\n ... [\n ... LineString([(0, 0), (1, 1), (1, -1)]),\n ... LineString([(0, 0), (1, 1), (1, -1), (0, 0)]),\n ... LinearRing([(0, 0), (1, 1), (1, -1)]),\n ... ]\n ... )\n >>> s\n 0 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 1 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 2 LINEARRING (0.00000 0.00000, 1.00000 1.00000, ...\n dtype: geometry\n\n >>> s.is_ring\n 0 False\n 1 True\n 2 True\n dtype: bool\n\n \"\"\"\n return _delegate_property(\"is_ring\", self)\n\n @property\n def has_z(self):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n features that have a z-component.\n\n Notes\n ------\n Every operation in GeoPandas is planar, i.e. the potential third\n dimension is not taken into account.\n\n Examples\n --------\n >>> from shapely.geometry import Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Point(0, 1),\n ... Point(0, 1, 2),\n ... ]\n ... )\n >>> s\n 0 POINT (0.00000 1.00000)\n 1 POINT Z (0.00000 1.00000 2.00000)\n dtype: geometry\n\n >>> s.has_z\n 0 False\n 1 True\n dtype: bool\n \"\"\"\n return _delegate_property(\"has_z\", self)\n\n #\n # Unary operations that return a GeoSeries\n #\n\n @property\n def boundary(self):\n \"\"\"Returns a ``GeoSeries`` of lower dimensional objects representing\n each geometries's set-theoretic `boundary`.\n\n Examples\n --------\n\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(0, 0), (1, 1), (1, 0)]),\n ... Point(0, 0),\n ... ]\n ... )\n >>> s\n 0 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 1 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 2 POINT (0.00000 0.00000)\n dtype: geometry\n\n >>> s.boundary\n 0 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 1 MULTIPOINT (0.00000 0.00000, 1.00000 0.00000)\n 2 GEOMETRYCOLLECTION EMPTY\n dtype: geometry\n\n See also\n --------\n GeoSeries.exterior : outer boundary (without interior rings)\n\n \"\"\"\n return _delegate_property(\"boundary\", self)\n\n @property\n def centroid(self):\n \"\"\"Returns a ``GeoSeries`` of points representing the centroid of each\n geometry.\n\n Note that centroid does not have to be on or within original geometry.\n\n Examples\n --------\n\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(0, 0), (1, 1), (1, 0)]),\n ... Point(0, 0),\n ... ]\n ... )\n >>> s\n 0 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 1 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 2 POINT (0.00000 0.00000)\n dtype: geometry\n\n >>> s.centroid\n 0 POINT (0.33333 0.66667)\n 1 POINT (0.70711 0.50000)\n 2 POINT (0.00000 0.00000)\n dtype: geometry\n\n See also\n --------\n GeoSeries.representative_point : point guaranteed to be within each geometry\n \"\"\"\n return _delegate_property(\"centroid\", self)\n\n @property\n def convex_hull(self):\n \"\"\"Returns a ``GeoSeries`` of geometries representing the convex hull\n of each geometry.\n\n The convex hull of a geometry is the smallest convex `Polygon`\n containing all the points in each geometry, unless the number of points\n in the geometric object is less than three. For two points, the convex\n hull collapses to a `LineString`; for 1, a `Point`.\n\n Examples\n --------\n\n >>> from shapely.geometry import Polygon, LineString, Point, MultiPoint\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(0, 0), (1, 1), (1, 0)]),\n ... MultiPoint([(0, 0), (1, 1), (0, 1), (1, 0), (0.5, 0.5)]),\n ... MultiPoint([(0, 0), (1, 1)]),\n ... Point(0, 0),\n ... ]\n ... )\n >>> s\n 0 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 1 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 2 MULTIPOINT (0.00000 0.00000, 1.00000 1.00000, ...\n 3 MULTIPOINT (0.00000 0.00000, 1.00000 1.00000)\n 4 POINT (0.00000 0.00000)\n dtype: geometry\n\n >>> s.convex_hull\n 0 POLYGON ((0.00000 0.00000, 0.00000 1.00000, 1....\n 1 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 1....\n 2 POLYGON ((0.00000 0.00000, 0.00000 1.00000, 1....\n 3 LINESTRING (0.00000 0.00000, 1.00000 1.00000)\n 4 POINT (0.00000 0.00000)\n dtype: geometry\n\n See also\n --------\n GeoSeries.envelope : bounding rectangle geometry\n\n \"\"\"\n return _delegate_property(\"convex_hull\", self)\n\n @property\n def envelope(self):\n \"\"\"Returns a ``GeoSeries`` of geometries representing the envelope of\n each geometry.\n\n The envelope of a geometry is the bounding rectangle. That is, the\n point or smallest rectangular polygon (with sides parallel to the\n coordinate axes) that contains the geometry.\n\n Examples\n --------\n\n >>> from shapely.geometry import Polygon, LineString, Point, MultiPoint\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(0, 0), (1, 1), (1, 0)]),\n ... MultiPoint([(0, 0), (1, 1)]),\n ... Point(0, 0),\n ... ]\n ... )\n >>> s\n 0 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 1 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 2 MULTIPOINT (0.00000 0.00000, 1.00000 1.00000)\n 3 POINT (0.00000 0.00000)\n dtype: geometry\n\n >>> s.envelope\n 0 POLYGON ((0.00000 0.00000, 1.00000 0.00000, 1....\n 1 POLYGON ((0.00000 0.00000, 1.00000 0.00000, 1....\n 2 POLYGON ((0.00000 0.00000, 1.00000 0.00000, 1....\n 3 POINT (0.00000 0.00000)\n dtype: geometry\n\n See also\n --------\n GeoSeries.convex_hull : convex hull geometry\n \"\"\"\n return _delegate_property(\"envelope\", self)\n\n @property\n def exterior(self):\n \"\"\"Returns a ``GeoSeries`` of LinearRings representing the outer\n boundary of each polygon in the GeoSeries.\n\n Applies to GeoSeries containing only Polygons. Returns ``None``` for\n other geometry types.\n\n Examples\n --------\n\n >>> from shapely.geometry import Polygon, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... Polygon([(1, 0), (2, 1), (0, 0)]),\n ... Point(0, 1)\n ... ]\n ... )\n >>> s\n 0 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 1 POLYGON ((1.00000 0.00000, 2.00000 1.00000, 0....\n 2 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s.exterior\n 0 LINEARRING (0.00000 0.00000, 1.00000 1.00000, ...\n 1 LINEARRING (1.00000 0.00000, 2.00000 1.00000, ...\n 2 None\n dtype: geometry\n\n See also\n --------\n GeoSeries.boundary : complete set-theoretic boundary\n GeoSeries.interiors : list of inner rings of each polygon\n \"\"\"\n # TODO: return empty geometry for non-polygons\n return _delegate_property(\"exterior\", self)\n\n @property\n def interiors(self):\n \"\"\"Returns a ``Series`` of List representing the\n inner rings of each polygon in the GeoSeries.\n\n Applies to GeoSeries containing only Polygons.\n\n Returns\n ----------\n inner_rings: Series of List\n Inner rings of each polygon in the GeoSeries.\n\n Examples\n --------\n\n >>> from shapely.geometry import Polygon\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon(\n ... [(0, 0), (0, 5), (5, 5), (5, 0)],\n ... [[(1, 1), (2, 1), (1, 2)], [(1, 4), (2, 4), (2, 3)]],\n ... ),\n ... Polygon([(1, 0), (2, 1), (0, 0)]),\n ... ]\n ... )\n >>> s\n 0 POLYGON ((0.00000 0.00000, 0.00000 5.00000, 5....\n 1 POLYGON ((1.00000 0.00000, 2.00000 1.00000, 0....\n dtype: geometry\n\n >>> s.interiors\n 0 [LINEARRING (1 1, 2 1, 1 2, 1 1), LINEARRING (...\n 1 []\n dtype: object\n\n See also\n --------\n GeoSeries.exterior : outer boundary\n \"\"\"\n return _delegate_property(\"interiors\", self)\n\n def representative_point(self):\n \"\"\"Returns a ``GeoSeries`` of (cheaply computed) points that are\n guaranteed to be within each geometry.\n\n Examples\n --------\n\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(0, 0), (1, 1), (1, 0)]),\n ... Point(0, 0),\n ... ]\n ... )\n >>> s\n 0 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 1 LINESTRING (0.00000 0.00000, 1.00000 1.00000, ...\n 2 POINT (0.00000 0.00000)\n dtype: geometry\n\n >>> s.representative_point()\n 0 POINT (0.25000 0.50000)\n 1 POINT (1.00000 1.00000)\n 2 POINT (0.00000 0.00000)\n dtype: geometry\n\n See also\n --------\n GeoSeries.centroid : geometric centroid\n \"\"\"\n return _delegate_geo_method(\"representative_point\", self)\n\n #\n # Reduction operations that return a Shapely geometry\n #\n\n @property\n def cascaded_union(self):\n \"\"\"Deprecated: Return the unary_union of all geometries\"\"\"\n return cascaded_union(np.asarray(self.geometry.values))\n\n @property\n def unary_union(self):\n \"\"\"Returns a geometry containing the union of all geometries in the\n ``GeoSeries``.\n\n Examples\n --------\n\n >>> from shapely.geometry import box\n >>> s = geopandas.GeoSeries([box(0,0,1,1), box(0,0,2,2)])\n >>> s\n 0 POLYGON ((1.00000 0.00000, 1.00000 1.00000, 0....\n 1 POLYGON ((2.00000 0.00000, 2.00000 2.00000, 0....\n dtype: geometry\n\n >>> union = s.unary_union\n >>> print(union)\n POLYGON ((0 1, 0 2, 2 2, 2 0, 1 0, 0 0, 0 1))\n \"\"\"\n return self.geometry.values.unary_union()\n\n #\n # Binary operations that return a pandas Series\n #\n\n def contains(self, other, align=True):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each aligned geometry that contains `other`.\n\n An object is said to contain `other` if its `interior` contains the\n `boundary` and `interior` of the other object and their boundaries do\n not touch at all.\n\n This is the inverse of :meth:`within` in the sense that the expression\n ``a.contains(b) == b.within(a)`` always evaluates to ``True``.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if is\n contained.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(0, 0), (0, 2)]),\n ... LineString([(0, 0), (0, 1)]),\n ... Point(0, 1),\n ... ],\n ... index=range(0, 4),\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (1, 2), (0, 2)]),\n ... LineString([(0, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 5),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 1 LINESTRING (0.00000 0.00000, 0.00000 2.00000)\n 2 LINESTRING (0.00000 0.00000, 0.00000 1.00000)\n 3 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 2 POLYGON ((0.00000 0.00000, 1.00000 2.00000, 0....\n 3 LINESTRING (0.00000 0.00000, 0.00000 2.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can check if each geometry of GeoSeries contains a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> point = Point(0, 1)\n >>> s.contains(point)\n 0 False\n 1 True\n 2 False\n 3 True\n dtype: bool\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s2.contains(s, align=True)\n 0 False\n 1 False\n 2 False\n 3 True\n 4 False\n dtype: bool\n\n >>> s2.contains(s, align=False)\n 1 True\n 2 False\n 3 True\n 4 True\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries ``contains`` *any* element of the other one.\n\n See also\n --------\n GeoSeries.within\n \"\"\"\n return _binary_op(\"contains\", self, other, align)\n\n def geom_equals(self, other, align=True):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each aligned geometry equal to `other`.\n\n An object is said to be equal to `other` if its set-theoretic\n `boundary`, `interior`, and `exterior` coincides with those of the\n other.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test for\n equality.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (1, 2), (0, 2)]),\n ... LineString([(0, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (1, 2), (0, 2)]),\n ... Point(0, 1),\n ... LineString([(0, 0), (0, 2)]),\n ... ],\n ... index=range(1, 5),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 1.00000 2.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 0.00000 2.00000)\n 3 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 2 POLYGON ((0.00000 0.00000, 1.00000 2.00000, 0....\n 3 POINT (0.00000 1.00000)\n 4 LINESTRING (0.00000 0.00000, 0.00000 2.00000)\n dtype: geometry\n\n We can check if each geometry of GeoSeries contains a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> polygon = Polygon([(0, 0), (2, 2), (0, 2)])\n >>> s.geom_equals(polygon)\n 0 True\n 1 False\n 2 False\n 3 False\n dtype: bool\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.geom_equals(s2)\n 0 False\n 1 False\n 2 False\n 3 True\n 4 False\n dtype: bool\n\n >>> s.geom_equals(s2, align=False)\n 0 True\n 1 True\n 2 False\n 3 False\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries is equal to *any* element of the other one.\n\n See also\n --------\n GeoSeries.geom_almost_equals\n GeoSeries.geom_equals_exact\n\n \"\"\"\n return _binary_op(\"geom_equals\", self, other, align)\n\n def geom_almost_equals(self, other, decimal=6, align=True):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` if\n each aligned geometry is approximately equal to `other`.\n\n Approximate equality is tested at all points to the specified `decimal`\n place precision.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to compare to.\n decimal : int\n Decimal place presion used when testing for approximate equality.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Point(0, 1.1),\n ... Point(0, 1.01),\n ... Point(0, 1.001),\n ... ],\n ... )\n\n >>> s\n 0 POINT (0.00000 1.10000)\n 1 POINT (0.00000 1.01000)\n 2 POINT (0.00000 1.00100)\n dtype: geometry\n\n\n >>> s.geom_almost_equals(Point(0, 1), decimal=2)\n 0 False\n 1 False\n 2 True\n dtype: bool\n\n >>> s.geom_almost_equals(Point(0, 1), decimal=1)\n 0 False\n 1 True\n 2 True\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries is equal to *any* element of the other one.\n\n See also\n --------\n GeoSeries.geom_equals\n GeoSeries.geom_equals_exact\n\n \"\"\"\n return _binary_op(\n \"geom_almost_equals\", self, other, decimal=decimal, align=align\n )\n\n def geom_equals_exact(self, other, tolerance, align=True):\n \"\"\"Return True for all geometries that equal aligned *other* to a given\n tolerance, else False.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to compare to.\n tolerance : float\n Decimal place presion used when testing for approximate equality.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Point(0, 1.1),\n ... Point(0, 1.0),\n ... Point(0, 1.2),\n ... ]\n ... )\n\n >>> s\n 0 POINT (0.00000 1.10000)\n 1 POINT (0.00000 1.00000)\n 2 POINT (0.00000 1.20000)\n dtype: geometry\n\n\n >>> s.geom_equals_exact(Point(0, 1), tolerance=0.1)\n 0 False\n 1 True\n 2 False\n dtype: bool\n\n >>> s.geom_equals_exact(Point(0, 1), tolerance=0.15)\n 0 True\n 1 True\n 2 False\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries is equal to *any* element of the other one.\n\n See also\n --------\n GeoSeries.geom_equals\n GeoSeries.geom_almost_equals\n \"\"\"\n return _binary_op(\n \"geom_equals_exact\", self, other, tolerance=tolerance, align=align\n )\n\n def crosses(self, other, align=True):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each aligned geometry that cross `other`.\n\n An object is said to cross `other` if its `interior` intersects the\n `interior` of the other but does not contain it, and the dimension of\n the intersection is less than the dimension of the one or the other.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if is\n crossed.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... LineString([(1, 0), (1, 3)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(1, 1),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 5),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 2 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 3 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 LINESTRING (1.00000 0.00000, 1.00000 3.00000)\n 2 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 3 POINT (1.00000 1.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can check if each geometry of GeoSeries crosses a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> line = LineString([(-1, 1), (3, 1)])\n >>> s.crosses(line)\n 0 True\n 1 True\n 2 True\n 3 False\n dtype: bool\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.crosses(s2, align=True)\n 0 False\n 1 True\n 2 False\n 3 False\n 4 False\n dtype: bool\n\n >>> s.crosses(s2, align=False)\n 0 True\n 1 True\n 2 False\n 3 False\n dtype: bool\n\n Notice that a line does not cross a point that it contains.\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries ``crosses`` *any* element of the other one.\n\n See also\n --------\n GeoSeries.disjoint\n GeoSeries.intersects\n\n \"\"\"\n return _binary_op(\"crosses\", self, other, align)\n\n def disjoint(self, other, align=True):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each aligned geometry disjoint to `other`.\n\n An object is said to be disjoint to `other` if its `boundary` and\n `interior` does not intersect at all with those of the other.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if is\n disjoint.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(-1, 0), (-1, 2), (0, -2)]),\n ... LineString([(0, 0), (0, 1)]),\n ... Point(1, 1),\n ... Point(0, 0),\n ... ],\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 2 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 3 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 0 POLYGON ((-1.00000 0.00000, -1.00000 2.00000, ...\n 1 LINESTRING (0.00000 0.00000, 0.00000 1.00000)\n 2 POINT (1.00000 1.00000)\n 3 POINT (0.00000 0.00000)\n dtype: geometry\n\n We can check each geometry of GeoSeries to a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> line = LineString([(0, 0), (2, 0)])\n >>> s.disjoint(line)\n 0 False\n 1 False\n 2 False\n 3 True\n dtype: bool\n\n We can also check two GeoSeries against each other, row by row.\n We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.disjoint(s2)\n 0 True\n 1 False\n 2 False\n 3 True\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries is equal to *any* element of the other one.\n\n See also\n --------\n GeoSeries.intersects\n GeoSeries.touches\n\n \"\"\"\n return _binary_op(\"disjoint\", self, other, align)\n\n def intersects(self, other, align=True):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each aligned geometry that intersects `other`.\n\n An object is said to intersect `other` if its `boundary` and `interior`\n intersects in any way with those of the other.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if is\n intersected.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... LineString([(1, 0), (1, 3)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(1, 1),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 5),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 2 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 3 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 LINESTRING (1.00000 0.00000, 1.00000 3.00000)\n 2 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 3 POINT (1.00000 1.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can check if each geometry of GeoSeries crosses a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> line = LineString([(-1, 1), (3, 1)])\n >>> s.intersects(line)\n 0 True\n 1 True\n 2 True\n 3 True\n dtype: bool\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.intersects(s2, align=True)\n 0 False\n 1 True\n 2 True\n 3 False\n 4 False\n dtype: bool\n\n >>> s.intersects(s2, align=False)\n 0 True\n 1 True\n 2 True\n 3 True\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries ``crosses`` *any* element of the other one.\n\n See also\n --------\n GeoSeries.disjoint\n GeoSeries.crosses\n GeoSeries.touches\n GeoSeries.intersection\n \"\"\"\n return _binary_op(\"intersects\", self, other, align)\n\n def overlaps(self, other, align=True):\n \"\"\"Returns True for all aligned geometries that overlap *other*, else False.\n\n Geometries overlaps if they have more than one but not all\n points in common, have the same dimension, and the intersection of the\n interiors of the geometries has the same dimension as the geometries\n themselves.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if\n overlaps.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, MultiPoint, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... MultiPoint([(0, 0), (0, 1)]),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 0), (0, 2)]),\n ... LineString([(0, 1), (1, 1)]),\n ... LineString([(1, 1), (3, 3)]),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 5),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 3 MULTIPOINT (0.00000 0.00000, 0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, 2.00000 0.00000, 0....\n 2 LINESTRING (0.00000 1.00000, 1.00000 1.00000)\n 3 LINESTRING (1.00000 1.00000, 3.00000 3.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can check if each geometry of GeoSeries overlaps a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> polygon = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n >>> s.overlaps(polygon)\n 0 True\n 1 True\n 2 False\n 3 False\n dtype: bool\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.overlaps(s2)\n 0 False\n 1 True\n 2 False\n 3 False\n 4 False\n dtype: bool\n\n >>> s.overlaps(s2, align=False)\n 0 True\n 1 False\n 2 True\n 3 False\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries ``overlaps`` *any* element of the other one.\n\n See also\n --------\n GeoSeries.crosses\n GeoSeries.intersects\n\n \"\"\"\n return _binary_op(\"overlaps\", self, other, align)\n\n def touches(self, other, align=True):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each aligned geometry that touches `other`.\n\n An object is said to touch `other` if it has at least one point in\n common with `other` and its interior does not intersect with any part\n of the other. Overlapping features therefore do not touch.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if is\n touched.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, MultiPoint, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... MultiPoint([(0, 0), (0, 1)]),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (-2, 0), (0, -2)]),\n ... LineString([(0, 1), (1, 1)]),\n ... LineString([(1, 1), (3, 0)]),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 5),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 3 MULTIPOINT (0.00000 0.00000, 0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, -2.00000 0.00000, 0...\n 2 LINESTRING (0.00000 1.00000, 1.00000 1.00000)\n 3 LINESTRING (1.00000 1.00000, 3.00000 0.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can check if each geometry of GeoSeries touches a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n\n >>> line = LineString([(0, 0), (-1, -2)])\n >>> s.touches(line)\n 0 True\n 1 True\n 2 True\n 3 True\n dtype: bool\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.touches(s2, align=True)\n 0 False\n 1 True\n 2 True\n 3 False\n 4 False\n dtype: bool\n\n >>> s.touches(s2, align=False)\n 0 True\n 1 False\n 2 True\n 3 False\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries ``touches`` *any* element of the other one.\n\n See also\n --------\n GeoSeries.overlaps\n GeoSeries.intersects\n\n \"\"\"\n return _binary_op(\"touches\", self, other, align)\n\n def within(self, other, align=True):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each aligned geometry that is within `other`.\n\n An object is said to be within `other` if its `boundary` and `interior`\n intersects only with the `interior` of the other (not its `boundary` or\n `exterior`).\n\n This is the inverse of :meth:`contains` in the sense that the\n expression ``a.within(b) == b.contains(a)`` always evaluates to\n ``True``.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if each\n geometry is within.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (1, 2), (0, 2)]),\n ... LineString([(0, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(0, 0), (0, 2)]),\n ... LineString([(0, 0), (0, 1)]),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 5),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 1.00000 2.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 0.00000 2.00000)\n 3 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 0.00000 2.00000)\n 3 LINESTRING (0.00000 0.00000, 0.00000 1.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can check if each geometry of GeoSeries is within a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> polygon = Polygon([(0, 0), (2, 2), (0, 2)])\n >>> s.within(polygon)\n 0 True\n 1 True\n 2 False\n 3 False\n dtype: bool\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s2.within(s)\n 0 False\n 1 False\n 2 True\n 3 False\n 4 False\n dtype: bool\n\n >>> s2.within(s, align=False)\n 1 True\n 2 False\n 3 True\n 4 True\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries is ``within`` *any* element of the other one.\n\n See also\n --------\n GeoSeries.contains\n \"\"\"\n return _binary_op(\"within\", self, other, align)\n\n def covers(self, other, align=True):\n \"\"\"\n Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each aligned geometry that is entirely covering `other`.\n\n An object A is said to cover another object B if no points of B lie\n in the exterior of A.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n See\n https://lin-ear-th-inking.blogspot.com/2007/06/subtleties-of-ogc-covers-spatial.html\n for reference.\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to check is being covered.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... Point(0, 0),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0.5, 0.5), (1.5, 0.5), (1.5, 1.5), (0.5, 1.5)]),\n ... Polygon([(0, 0), (2, 0), (2, 2), (0, 2)]),\n ... LineString([(1, 1), (1.5, 1.5)]),\n ... Point(0, 0),\n ... ],\n ... index=range(1, 5),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 0.00000, 2....\n 1 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 3 POINT (0.00000 0.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.50000 0.50000, 1.50000 0.50000, 1....\n 2 POLYGON ((0.00000 0.00000, 2.00000 0.00000, 2....\n 3 LINESTRING (1.00000 1.00000, 1.50000 1.50000)\n 4 POINT (0.00000 0.00000)\n dtype: geometry\n\n We can check if each geometry of GeoSeries covers a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> poly = Polygon([(0, 0), (2, 0), (2, 2), (0, 2)])\n >>> s.covers(poly)\n 0 True\n 1 False\n 2 False\n 3 False\n dtype: bool\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.covers(s2, align=True)\n 0 False\n 1 False\n 2 False\n 3 False\n 4 False\n dtype: bool\n\n >>> s.covers(s2, align=False)\n 0 True\n 1 False\n 2 True\n 3 True\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries ``covers`` *any* element of the other one.\n\n See also\n --------\n GeoSeries.covered_by\n GeoSeries.overlaps\n \"\"\"\n return _binary_op(\"covers\", self, other, align)\n\n def covered_by(self, other, align=True):\n \"\"\"\n Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each aligned geometry that is entirely covered by `other`.\n\n An object A is said to cover another object B if no points of B lie\n in the exterior of A.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n See\n https://lin-ear-th-inking.blogspot.com/2007/06/subtleties-of-ogc-covers-spatial.html\n for reference.\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to check is being covered.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series (bool)\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0.5, 0.5), (1.5, 0.5), (1.5, 1.5), (0.5, 1.5)]),\n ... Polygon([(0, 0), (2, 0), (2, 2), (0, 2)]),\n ... LineString([(1, 1), (1.5, 1.5)]),\n ... Point(0, 0),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... Point(0, 0),\n ... ],\n ... index=range(1, 5),\n ... )\n\n >>> s\n 0 POLYGON ((0.50000 0.50000, 1.50000 0.50000, 1....\n 1 POLYGON ((0.00000 0.00000, 2.00000 0.00000, 2....\n 2 LINESTRING (1.00000 1.00000, 1.50000 1.50000)\n 3 POINT (0.00000 0.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, 2.00000 0.00000, 2....\n 2 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 3 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 4 POINT (0.00000 0.00000)\n dtype: geometry\n\n We can check if each geometry of GeoSeries is covered by a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> poly = Polygon([(0, 0), (2, 0), (2, 2), (0, 2)])\n >>> s.covered_by(poly)\n 0 True\n 1 True\n 2 True\n 3 True\n dtype: bool\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.covered_by(s2, align=True)\n 0 False\n 1 True\n 2 True\n 3 True\n 4 False\n dtype: bool\n\n >>> s.covered_by(s2, align=False)\n 0 True\n 1 False\n 2 True\n 3 True\n dtype: bool\n\n Notes\n -----\n This method works in a row-wise manner. It does not check if an element\n of one GeoSeries is ``covered_by`` *any* element of the other one.\n\n See also\n --------\n GeoSeries.covers\n GeoSeries.overlaps\n \"\"\"\n return _binary_op(\"covered_by\", self, other, align)\n\n def distance(self, other, align=True):\n \"\"\"Returns a ``Series`` containing the distance to aligned `other`.\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to find the\n distance to.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n\n Returns\n -------\n Series (float)\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 0), (1, 1)]),\n ... Polygon([(0, 0), (-1, 0), (-1, 1)]),\n ... LineString([(1, 1), (0, 0)]),\n ... Point(0, 0),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0.5, 0.5), (1.5, 0.5), (1.5, 1.5), (0.5, 1.5)]),\n ... Point(3, 1),\n ... LineString([(1, 0), (2, 0)]),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 5),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 1.00000 0.00000, 1....\n 1 POLYGON ((0.00000 0.00000, -1.00000 0.00000, -...\n 2 LINESTRING (1.00000 1.00000, 0.00000 0.00000)\n 3 POINT (0.00000 0.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.50000 0.50000, 1.50000 0.50000, 1....\n 2 POINT (3.00000 1.00000)\n 3 LINESTRING (1.00000 0.00000, 2.00000 0.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can check the distance of each geometry of GeoSeries to a single\n geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> point = Point(-1, 0)\n >>> s.distance(point)\n 0 1.0\n 1 0.0\n 2 1.0\n 3 1.0\n dtype: float64\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and use elements with the same index using\n ``align=True`` or ignore index and use elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.distance(s2, align=True)\n 0 NaN\n 1 0.707107\n 2 2.000000\n 3 1.000000\n 4 NaN\n dtype: float64\n\n >>> s.distance(s2, align=False)\n 0 0.000000\n 1 3.162278\n 2 0.707107\n 3 1.000000\n dtype: float64\n \"\"\"\n return _binary_op(\"distance\", self, other, align)\n\n #\n # Binary operations that return a GeoSeries\n #\n\n def difference(self, other, align=True):\n \"\"\"Returns a ``GeoSeries`` of the points in each aligned geometry that\n are not in `other`.\n\n .. image:: ../../../_static/binary_geo-difference.svg\n :align: center\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to find the\n difference to.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n GeoSeries\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(1, 0), (1, 3)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(1, 1),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 6),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 2 LINESTRING (1.00000 0.00000, 1.00000 3.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (1.00000 1.00000)\n 5 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can do difference of each geometry and a single\n shapely geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> s.difference(Polygon([(0, 0), (1, 1), (0, 1)]))\n 0 POLYGON ((0.00000 2.00000, 2.00000 2.00000, 1....\n 1 POLYGON ((0.00000 2.00000, 2.00000 2.00000, 1....\n 2 LINESTRING (1.00000 1.00000, 2.00000 2.00000)\n 3 MULTILINESTRING ((2.00000 0.00000, 1.00000 1.0...\n 4 POINT EMPTY\n dtype: geometry\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.difference(s2, align=True)\n 0 None\n 1 POLYGON ((0.00000 2.00000, 2.00000 2.00000, 1....\n 2 MULTILINESTRING ((0.00000 0.00000, 1.00000 1.0...\n 3 LINESTRING EMPTY\n 4 POINT (0.00000 1.00000)\n 5 None\n dtype: geometry\n\n >>> s.difference(s2, align=False)\n 0 POLYGON ((0.00000 2.00000, 2.00000 2.00000, 1....\n 1 POLYGON ((0.00000 0.00000, 0.00000 2.00000, 1....\n 2 MULTILINESTRING ((0.00000 0.00000, 1.00000 1.0...\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT EMPTY\n dtype: geometry\n\n See Also\n --------\n GeoSeries.symmetric_difference\n GeoSeries.union\n GeoSeries.intersection\n \"\"\"\n return _binary_geo(\"difference\", self, other, align)\n\n def symmetric_difference(self, other, align=True):\n \"\"\"Returns a ``GeoSeries`` of the symmetric difference of points in\n each aligned geometry with `other`.\n\n For each geometry, the symmetric difference consists of points in the\n geometry not in `other`, and points in `other` not in the geometry.\n\n .. image:: ../../../_static/binary_geo-symm_diff.svg\n :align: center\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to find the\n symmetric difference to.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n GeoSeries\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(1, 0), (1, 3)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(1, 1),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 6),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 2 LINESTRING (1.00000 0.00000, 1.00000 3.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (1.00000 1.00000)\n 5 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can do symmetric difference of each geometry and a single\n shapely geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> s.symmetric_difference(Polygon([(0, 0), (1, 1), (0, 1)]))\n 0 POLYGON ((0.00000 2.00000, 2.00000 2.00000, 1....\n 1 POLYGON ((0.00000 2.00000, 2.00000 2.00000, 1....\n 2 GEOMETRYCOLLECTION (POLYGON ((0.00000 0.00000,...\n 3 GEOMETRYCOLLECTION (POLYGON ((0.00000 0.00000,...\n 4 POLYGON ((0.00000 1.00000, 1.00000 1.00000, 0....\n dtype: geometry\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.symmetric_difference(s2, align=True)\n 0 None\n 1 POLYGON ((0.00000 2.00000, 2.00000 2.00000, 1....\n 2 MULTILINESTRING ((0.00000 0.00000, 1.00000 1.0...\n 3 LINESTRING EMPTY\n 4 MULTIPOINT (0.00000 1.00000, 1.00000 1.00000)\n 5 None\n dtype: geometry\n\n >>> s.symmetric_difference(s2, align=False)\n 0 POLYGON ((0.00000 2.00000, 2.00000 2.00000, 1....\n 1 GEOMETRYCOLLECTION (POLYGON ((0.00000 0.00000,...\n 2 MULTILINESTRING ((0.00000 0.00000, 1.00000 1.0...\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT EMPTY\n dtype: geometry\n\n See Also\n --------\n GeoSeries.difference\n GeoSeries.union\n GeoSeries.intersection\n \"\"\"\n return _binary_geo(\"symmetric_difference\", self, other, align)\n\n def union(self, other, align=True):\n \"\"\"Returns a ``GeoSeries`` of the union of points in each aligned geometry with\n `other`.\n\n .. image:: ../../../_static/binary_geo-union.svg\n :align: center\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to find the union\n with.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n GeoSeries\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(1, 0), (1, 3)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(1, 1),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 6),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 2 LINESTRING (1.00000 0.00000, 1.00000 3.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (1.00000 1.00000)\n 5 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can do union of each geometry and a single\n shapely geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> s.union(Polygon([(0, 0), (1, 1), (0, 1)]))\n 0 POLYGON ((0.00000 0.00000, 0.00000 1.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 0.00000 1.00000, 0....\n 2 GEOMETRYCOLLECTION (POLYGON ((0.00000 0.00000,...\n 3 GEOMETRYCOLLECTION (POLYGON ((0.00000 0.00000,...\n 4 POLYGON ((0.00000 1.00000, 1.00000 1.00000, 0....\n dtype: geometry\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.union(s2, align=True)\n 0 None\n 1 POLYGON ((0.00000 0.00000, 0.00000 1.00000, 0....\n 2 MULTILINESTRING ((0.00000 0.00000, 1.00000 1.0...\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 MULTIPOINT (0.00000 1.00000, 1.00000 1.00000)\n 5 None\n dtype: geometry\n\n >>> s.union(s2, align=False)\n 0 POLYGON ((0.00000 0.00000, 0.00000 1.00000, 0....\n 1 GEOMETRYCOLLECTION (POLYGON ((0.00000 0.00000,...\n 2 MULTILINESTRING ((0.00000 0.00000, 1.00000 1.0...\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n\n See Also\n --------\n GeoSeries.symmetric_difference\n GeoSeries.difference\n GeoSeries.intersection\n \"\"\"\n return _binary_geo(\"union\", self, other, align)\n\n def intersection(self, other, align=True):\n \"\"\"Returns a ``GeoSeries`` of the intersection of points in each\n aligned geometry with `other`.\n\n .. image:: ../../../_static/binary_geo-intersection.svg\n :align: center\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to find the\n intersection with.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n GeoSeries\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(1, 0), (1, 3)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(1, 1),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 6),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 2 LINESTRING (1.00000 0.00000, 1.00000 3.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (1.00000 1.00000)\n 5 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can also do intersection of each geometry and a single\n shapely geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> s.intersection(Polygon([(0, 0), (1, 1), (0, 1)]))\n 0 POLYGON ((0.00000 0.00000, 0.00000 1.00000, 1....\n 1 POLYGON ((0.00000 0.00000, 0.00000 1.00000, 1....\n 2 LINESTRING (0.00000 0.00000, 1.00000 1.00000)\n 3 POINT (1.00000 1.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.intersection(s2, align=True)\n 0 None\n 1 POLYGON ((0.00000 0.00000, 0.00000 1.00000, 1....\n 2 POINT (1.00000 1.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT EMPTY\n 5 None\n dtype: geometry\n\n >>> s.intersection(s2, align=False)\n 0 POLYGON ((0.00000 0.00000, 0.00000 1.00000, 1....\n 1 LINESTRING (1.00000 1.00000, 1.00000 2.00000)\n 2 POINT (1.00000 1.00000)\n 3 POINT (1.00000 1.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n\n See Also\n --------\n GeoSeries.difference\n GeoSeries.symmetric_difference\n GeoSeries.union\n \"\"\"\n return _binary_geo(\"intersection\", self, other, align)\n\n #\n # Other operations\n #\n\n @property\n def bounds(self):\n \"\"\"Returns a ``DataFrame`` with columns ``minx``, ``miny``, ``maxx``,\n ``maxy`` values containing the bounds for each geometry.\n\n See ``GeoSeries.total_bounds`` for the limits of the entire series.\n\n Examples\n --------\n >>> from shapely.geometry import Point, Polygon, LineString\n >>> d = {'geometry': [Point(2, 1), Polygon([(0, 0), (1, 1), (1, 0)]),\n ... LineString([(0, 1), (1, 2)])]}\n >>> gdf = geopandas.GeoDataFrame(d, crs=\"EPSG:4326\")\n >>> gdf.bounds\n minx miny maxx maxy\n 0 2.0 1.0 2.0 1.0\n 1 0.0 0.0 1.0 1.0\n 2 0.0 1.0 1.0 2.0\n \"\"\"\n bounds = GeometryArray(self.geometry.values).bounds\n return DataFrame(\n bounds, columns=[\"minx\", \"miny\", \"maxx\", \"maxy\"], index=self.index\n )\n\n @property\n def total_bounds(self):\n \"\"\"Returns a tuple containing ``minx``, ``miny``, ``maxx``, ``maxy``\n values for the bounds of the series as a whole.\n\n See ``GeoSeries.bounds`` for the bounds of the geometries contained in\n the series.\n\n Examples\n --------\n >>> from shapely.geometry import Point, Polygon, LineString\n >>> d = {'geometry': [Point(3, -1), Polygon([(0, 0), (1, 1), (1, 0)]),\n ... LineString([(0, 1), (1, 2)])]}\n >>> gdf = geopandas.GeoDataFrame(d, crs=\"EPSG:4326\")\n >>> gdf.total_bounds\n array([ 0., -1., 3., 2.])\n \"\"\"\n return GeometryArray(self.geometry.values).total_bounds\n\n @property\n def sindex(self):\n \"\"\"Generate the spatial index\n\n Creates R-tree spatial index based on ``pygeos.STRtree`` or\n ``rtree.index.Index``.\n\n Note that the spatial index may not be fully\n initialized until the first use.\n\n Examples\n --------\n >>> from shapely.geometry import box\n >>> s = geopandas.GeoSeries(geopandas.points_from_xy(range(5), range(5)))\n >>> s\n 0 POINT (0.00000 0.00000)\n 1 POINT (1.00000 1.00000)\n 2 POINT (2.00000 2.00000)\n 3 POINT (3.00000 3.00000)\n 4 POINT (4.00000 4.00000)\n dtype: geometry\n\n Query the spatial index with a single geometry based on the bounding box:\n\n >>> s.sindex.query(box(1, 1, 3, 3))\n array([1, 2, 3])\n\n Query the spatial index with a single geometry based on the predicate:\n\n >>> s.sindex.query(box(1, 1, 3, 3), predicate=\"contains\")\n array([2])\n\n Query the spatial index with an array of geometries based on the bounding\n box:\n\n >>> s2 = geopandas.GeoSeries([box(1, 1, 3, 3), box(4, 4, 5, 5)])\n >>> s2\n 0 POLYGON ((3.00000 1.00000, 3.00000 3.00000, 1....\n 1 POLYGON ((5.00000 4.00000, 5.00000 5.00000, 4....\n dtype: geometry\n\n >>> s.sindex.query_bulk(s2)\n array([[0, 0, 0, 1],\n [1, 2, 3, 4]])\n\n Query the spatial index with an array of geometries based on the predicate:\n\n >>> s.sindex.query_bulk(s2, predicate=\"contains\")\n array([[0],\n [2]])\n \"\"\"\n return self.geometry.values.sindex\n\n @property\n def has_sindex(self):\n \"\"\"Check the existence of the spatial index without generating it.\n\n Use the `.sindex` attribute on a GeoDataFrame or GeoSeries\n to generate a spatial index if it does not yet exist,\n which may take considerable time based on the underlying index\n implementation.\n\n Note that the underlying spatial index may not be fully\n initialized until the first use.\n\n Examples\n --------\n\n >>> from shapely.geometry import Point\n >>> d = {'geometry': [Point(1, 2), Point(2, 1)]}\n >>> gdf = geopandas.GeoDataFrame(d)\n >>> gdf.has_sindex\n False\n >>> index = gdf.sindex\n >>> gdf.has_sindex\n True\n\n Returns\n -------\n bool\n `True` if the spatial index has been generated or\n `False` if not.\n \"\"\"\n return self.geometry.values.has_sindex\n\n def buffer(self, distance, resolution=16, **kwargs):\n \"\"\"Returns a ``GeoSeries`` of geometries representing all points within\n a given ``distance`` of each geometric object.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#object.buffer\n for details.\n\n Parameters\n ----------\n distance : float, np.array, pd.Series\n The radius of the buffer. If np.array or pd.Series are used\n then it must have same length as the GeoSeries.\n resolution : int (optional, default 16)\n The resolution of the buffer around each vertex.\n\n Examples\n --------\n >>> from shapely.geometry import Point, LineString, Polygon\n >>> s = geopandas.GeoSeries(\n ... [\n ... Point(0, 0),\n ... LineString([(1, -1), (1, 0), (2, 0), (2, 1)]),\n ... Polygon([(3, -1), (4, 0), (3, 1)]),\n ... ]\n ... )\n >>> s\n 0 POINT (0.00000 0.00000)\n 1 LINESTRING (1.00000 -1.00000, 1.00000 0.00000,...\n 2 POLYGON ((3.00000 -1.00000, 4.00000 0.00000, 3...\n dtype: geometry\n\n >>> s.buffer(0.2)\n 0 POLYGON ((0.20000 0.00000, 0.19904 -0.01960, 0...\n 1 POLYGON ((0.80000 0.00000, 0.80096 0.01960, 0....\n 2 POLYGON ((2.80000 -1.00000, 2.80000 1.00000, 2...\n dtype: geometry\n\n ``**kwargs`` accept further specification as ``join_style`` and ``cap_style``.\n See the following illustration of different options.\n\n .. plot:: _static/code/buffer.py\n\n \"\"\"\n # TODO: update docstring based on pygeos after shapely 2.0\n if isinstance(distance, pd.Series):\n if not self.index.equals(distance.index):\n raise ValueError(\n \"Index values of distance sequence does \"\n \"not match index values of the GeoSeries\"\n )\n distance = np.asarray(distance)\n\n return _delegate_geo_method(\n \"buffer\", self, distance, resolution=resolution, **kwargs\n )\n\n def simplify(self, *args, **kwargs):\n \"\"\"Returns a ``GeoSeries`` containing a simplified representation of\n each geometry.\n\n The algorithm (Douglas-Peucker) recursively splits the original line\n into smaller parts and connects these parts’ endpoints\n by a straight line. Then, it removes all points whose distance\n to the straight line is smaller than `tolerance`. It does not\n move any points and it always preserves endpoints of\n the original line or polygon.\n See http://shapely.readthedocs.io/en/latest/manual.html#object.simplify\n for details\n\n Parameters\n ----------\n tolerance : float\n All parts of a simplified geometry will be no more than\n `tolerance` distance from the original. It has the same units\n as the coordinate reference system of the GeoSeries.\n For example, using `tolerance=100` in a projected CRS with meters\n as units means a distance of 100 meters in reality.\n preserve_topology: bool (default True)\n False uses a quicker algorithm, but may produce self-intersecting\n or otherwise invalid geometries.\n\n Notes\n -----\n Invalid geometric objects may result from simplification that does not\n preserve topology and simplification may be sensitive to the order of\n coordinates: two geometries differing only in order of coordinates may be\n simplified differently.\n\n Examples\n --------\n >>> from shapely.geometry import Point, LineString\n >>> s = geopandas.GeoSeries(\n ... [Point(0, 0).buffer(1), LineString([(0, 0), (1, 10), (0, 20)])]\n ... )\n >>> s\n 0 POLYGON ((1.00000 0.00000, 0.99518 -0.09802, 0...\n 1 LINESTRING (0.00000 0.00000, 1.00000 10.00000,...\n dtype: geometry\n\n >>> s.simplify(1)\n 0 POLYGON ((1.00000 0.00000, 0.00000 -1.00000, -...\n 1 LINESTRING (0.00000 0.00000, 0.00000 20.00000)\n dtype: geometry\n \"\"\"\n return _delegate_geo_method(\"simplify\", self, *args, **kwargs)\n\n def relate(self, other, align=True):\n \"\"\"\n Returns the DE-9IM intersection matrices for the geometries\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n Parameters\n ----------\n other : BaseGeometry or GeoSeries\n The other geometry to computed\n the DE-9IM intersection matrices from.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n ----------\n spatial_relations: Series of strings\n The DE-9IM intersection matrices which describe\n the spatial relations of the other geometry.\n\n Examples\n --------\n >>> from shapely.geometry import Polygon, LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... Polygon([(0, 0), (2, 2), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(0, 1),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Polygon([(0, 0), (1, 1), (0, 1)]),\n ... LineString([(1, 0), (1, 3)]),\n ... LineString([(2, 0), (0, 2)]),\n ... Point(1, 1),\n ... Point(0, 1),\n ... ],\n ... index=range(1, 6),\n ... )\n\n >>> s\n 0 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 1 POLYGON ((0.00000 0.00000, 2.00000 2.00000, 0....\n 2 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (0.00000 1.00000)\n dtype: geometry\n\n >>> s2\n 1 POLYGON ((0.00000 0.00000, 1.00000 1.00000, 0....\n 2 LINESTRING (1.00000 0.00000, 1.00000 3.00000)\n 3 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n 4 POINT (1.00000 1.00000)\n 5 POINT (0.00000 1.00000)\n dtype: geometry\n\n We can relate each geometry and a single\n shapely geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> s.relate(Polygon([(0, 0), (1, 1), (0, 1)]))\n 0 212F11FF2\n 1 212F11FF2\n 2 F11F00212\n 3 F01FF0212\n 4 F0FFFF212\n dtype: object\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and compare elements with the same index using\n ``align=True`` or ignore index and compare elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.relate(s2, align=True)\n 0 None\n 1 212F11FF2\n 2 0F1FF0102\n 3 1FFF0FFF2\n 4 FF0FFF0F2\n 5 None\n dtype: object\n\n >>> s.relate(s2, align=False)\n 0 212F11FF2\n 1 1F20F1102\n 2 0F1FF0102\n 3 0F1FF0FF2\n 4 0FFFFFFF2\n dtype: object\n\n \"\"\"\n return _binary_op(\"relate\", self, other, align)\n\n def project(self, other, normalized=False, align=True):\n \"\"\"\n Return the distance along each geometry nearest to *other*\n\n The operation works on a 1-to-1 row-wise manner:\n\n .. image:: ../../../_static/binary_op-01.svg\n :align: center\n\n The project method is the inverse of interpolate.\n\n\n Parameters\n ----------\n other : BaseGeometry or GeoSeries\n The *other* geometry to computed projected point from.\n normalized : boolean\n If normalized is True, return the distance normalized to\n the length of the object.\n align : bool (default True)\n If True, automatically aligns GeoSeries based on their indices.\n If False, the order of elements is preserved.\n\n Returns\n -------\n Series\n\n Examples\n --------\n >>> from shapely.geometry import LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [\n ... LineString([(0, 0), (2, 0), (0, 2)]),\n ... LineString([(0, 0), (2, 2)]),\n ... LineString([(2, 0), (0, 2)]),\n ... ],\n ... )\n >>> s2 = geopandas.GeoSeries(\n ... [\n ... Point(1, 0),\n ... Point(1, 0),\n ... Point(2, 1),\n ... ],\n ... index=range(1, 4),\n ... )\n\n >>> s\n 0 LINESTRING (0.00000 0.00000, 2.00000 0.00000, ...\n 1 LINESTRING (0.00000 0.00000, 2.00000 2.00000)\n 2 LINESTRING (2.00000 0.00000, 0.00000 2.00000)\n dtype: geometry\n\n >>> s2\n 1 POINT (1.00000 0.00000)\n 2 POINT (1.00000 0.00000)\n 3 POINT (2.00000 1.00000)\n dtype: geometry\n\n We can project each geometry on a single\n shapely geometry:\n\n .. image:: ../../../_static/binary_op-03.svg\n :align: center\n\n >>> s.project(Point(1, 0))\n 0 1.000000\n 1 0.707107\n 2 0.707107\n dtype: float64\n\n We can also check two GeoSeries against each other, row by row.\n The GeoSeries above have different indices. We can either align both GeoSeries\n based on index values and project elements with the same index using\n ``align=True`` or ignore index and project elements based on their matching\n order using ``align=False``:\n\n .. image:: ../../../_static/binary_op-02.svg\n\n >>> s.project(s2, align=True)\n 0 NaN\n 1 0.707107\n 2 0.707107\n 3 NaN\n dtype: float64\n\n >>> s.project(s2, align=False)\n 0 1.000000\n 1 0.707107\n 2 0.707107\n dtype: float64\n\n See also\n --------\n GeoSeries.interpolate\n \"\"\"\n return _binary_op(\"project\", self, other, normalized=normalized, align=align)\n\n def interpolate(self, distance, normalized=False):\n \"\"\"\n Return a point at the specified distance along each geometry\n\n Parameters\n ----------\n distance : float or Series of floats\n Distance(s) along the geometries at which a point should be\n returned. If np.array or pd.Series are used then it must have\n same length as the GeoSeries.\n normalized : boolean\n If normalized is True, distance will be interpreted as a fraction\n of the geometric object's length.\n \"\"\"\n if isinstance(distance, pd.Series):\n if not self.index.equals(distance.index):\n raise ValueError(\n \"Index values of distance sequence does \"\n \"not match index values of the GeoSeries\"\n )\n distance = np.asarray(distance)\n return _delegate_geo_method(\n \"interpolate\", self, distance, normalized=normalized\n )\n\n def affine_transform(self, matrix):\n \"\"\"Return a ``GeoSeries`` with translated geometries.\n\n See http://shapely.readthedocs.io/en/stable/manual.html#shapely.affinity.affine_transform\n for details.\n\n Parameters\n ----------\n matrix: List or tuple\n 6 or 12 items for 2D or 3D transformations respectively.\n\n For 2D affine transformations,\n the 6 parameter matrix is ``[a, b, d, e, xoff, yoff]``\n\n For 3D affine transformations,\n the 12 parameter matrix is ``[a, b, c, d, e, f, g, h, i, xoff, yoff, zoff]``\n\n Examples\n --------\n >>> from shapely.geometry import Point, LineString, Polygon\n >>> s = geopandas.GeoSeries(\n ... [\n ... Point(1, 1),\n ... LineString([(1, -1), (1, 0)]),\n ... Polygon([(3, -1), (4, 0), (3, 1)]),\n ... ]\n ... )\n >>> s\n 0 POINT (1.00000 1.00000)\n 1 LINESTRING (1.00000 -1.00000, 1.00000 0.00000)\n 2 POLYGON ((3.00000 -1.00000, 4.00000 0.00000, 3...\n dtype: geometry\n\n >>> s.affine_transform([2, 3, 2, 4, 5, 2])\n 0 POINT (10.00000 8.00000)\n 1 LINESTRING (4.00000 0.00000, 7.00000 4.00000)\n 2 POLYGON ((8.00000 4.00000, 13.00000 10.00000, ...\n dtype: geometry\n\n \"\"\" # noqa (E501 link is longer than max line length)\n return _delegate_geo_method(\"affine_transform\", self, matrix)\n\n def translate(self, xoff=0.0, yoff=0.0, zoff=0.0):\n \"\"\"Returns a ``GeoSeries`` with translated geometries.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#shapely.affinity.translate\n for details.\n\n Parameters\n ----------\n xoff, yoff, zoff : float, float, float\n Amount of offset along each dimension.\n xoff, yoff, and zoff for translation along the x, y, and z\n dimensions respectively.\n\n Examples\n --------\n >>> from shapely.geometry import Point, LineString, Polygon\n >>> s = geopandas.GeoSeries(\n ... [\n ... Point(1, 1),\n ... LineString([(1, -1), (1, 0)]),\n ... Polygon([(3, -1), (4, 0), (3, 1)]),\n ... ]\n ... )\n >>> s\n 0 POINT (1.00000 1.00000)\n 1 LINESTRING (1.00000 -1.00000, 1.00000 0.00000)\n 2 POLYGON ((3.00000 -1.00000, 4.00000 0.00000, 3...\n dtype: geometry\n\n >>> s.translate(2, 3)\n 0 POINT (3.00000 4.00000)\n 1 LINESTRING (3.00000 2.00000, 3.00000 3.00000)\n 2 POLYGON ((5.00000 2.00000, 6.00000 3.00000, 5....\n dtype: geometry\n\n \"\"\" # noqa (E501 link is longer than max line length)\n return _delegate_geo_method(\"translate\", self, xoff, yoff, zoff)\n\n def rotate(self, angle, origin=\"center\", use_radians=False):\n \"\"\"Returns a ``GeoSeries`` with rotated geometries.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#shapely.affinity.rotate\n for details.\n\n Parameters\n ----------\n angle : float\n The angle of rotation can be specified in either degrees (default)\n or radians by setting use_radians=True. Positive angles are\n counter-clockwise and negative are clockwise rotations.\n origin : string, Point, or tuple (x, y)\n The point of origin can be a keyword 'center' for the bounding box\n center (default), 'centroid' for the geometry's centroid, a Point\n object or a coordinate tuple (x, y).\n use_radians : boolean\n Whether to interpret the angle of rotation as degrees or radians\n\n Examples\n --------\n >>> from shapely.geometry import Point, LineString, Polygon\n >>> s = geopandas.GeoSeries(\n ... [\n ... Point(1, 1),\n ... LineString([(1, -1), (1, 0)]),\n ... Polygon([(3, -1), (4, 0), (3, 1)]),\n ... ]\n ... )\n >>> s\n 0 POINT (1.00000 1.00000)\n 1 LINESTRING (1.00000 -1.00000, 1.00000 0.00000)\n 2 POLYGON ((3.00000 -1.00000, 4.00000 0.00000, 3...\n dtype: geometry\n\n >>> s.rotate(90)\n 0 POINT (1.00000 1.00000)\n 1 LINESTRING (1.50000 -0.50000, 0.50000 -0.50000)\n 2 POLYGON ((4.50000 -0.50000, 3.50000 0.50000, 2...\n dtype: geometry\n\n >>> s.rotate(90, origin=(0, 0))\n 0 POINT (-1.00000 1.00000)\n 1 LINESTRING (1.00000 1.00000, 0.00000 1.00000)\n 2 POLYGON ((1.00000 3.00000, 0.00000 4.00000, -1...\n dtype: geometry\n\n \"\"\"\n return _delegate_geo_method(\n \"rotate\", self, angle, origin=origin, use_radians=use_radians\n )\n\n def scale(self, xfact=1.0, yfact=1.0, zfact=1.0, origin=\"center\"):\n \"\"\"Returns a ``GeoSeries`` with scaled geometries.\n\n The geometries can be scaled by different factors along each\n dimension. Negative scale factors will mirror or reflect coordinates.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#shapely.affinity.scale\n for details.\n\n Parameters\n ----------\n xfact, yfact, zfact : float, float, float\n Scaling factors for the x, y, and z dimensions respectively.\n origin : string, Point, or tuple\n The point of origin can be a keyword 'center' for the 2D bounding\n box center (default), 'centroid' for the geometry's 2D centroid, a\n Point object or a coordinate tuple (x, y, z).\n\n Examples\n --------\n >>> from shapely.geometry import Point, LineString, Polygon\n >>> s = geopandas.GeoSeries(\n ... [\n ... Point(1, 1),\n ... LineString([(1, -1), (1, 0)]),\n ... Polygon([(3, -1), (4, 0), (3, 1)]),\n ... ]\n ... )\n >>> s\n 0 POINT (1.00000 1.00000)\n 1 LINESTRING (1.00000 -1.00000, 1.00000 0.00000)\n 2 POLYGON ((3.00000 -1.00000, 4.00000 0.00000, 3...\n dtype: geometry\n\n >>> s.scale(2, 3)\n 0 POINT (1.00000 1.00000)\n 1 LINESTRING (1.00000 -2.00000, 1.00000 1.00000)\n 2 POLYGON ((2.50000 -3.00000, 4.50000 0.00000, 2...\n dtype: geometry\n\n >>> s.scale(2, 3, origin=(0, 0))\n 0 POINT (2.00000 3.00000)\n 1 LINESTRING (2.00000 -3.00000, 2.00000 0.00000)\n 2 POLYGON ((6.00000 -3.00000, 8.00000 0.00000, 6...\n dtype: geometry\n \"\"\"\n return _delegate_geo_method(\"scale\", self, xfact, yfact, zfact, origin=origin)\n\n def skew(self, xs=0.0, ys=0.0, origin=\"center\", use_radians=False):\n \"\"\"Returns a ``GeoSeries`` with skewed geometries.\n\n The geometries are sheared by angles along the x and y dimensions.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#shapely.affinity.skew\n for details.\n\n Parameters\n ----------\n xs, ys : float, float\n The shear angle(s) for the x and y axes respectively. These can be\n specified in either degrees (default) or radians by setting\n use_radians=True.\n origin : string, Point, or tuple (x, y)\n The point of origin can be a keyword 'center' for the bounding box\n center (default), 'centroid' for the geometry's centroid, a Point\n object or a coordinate tuple (x, y).\n use_radians : boolean\n Whether to interpret the shear angle(s) as degrees or radians\n\n Examples\n --------\n >>> from shapely.geometry import Point, LineString, Polygon\n >>> s = geopandas.GeoSeries(\n ... [\n ... Point(1, 1),\n ... LineString([(1, -1), (1, 0)]),\n ... Polygon([(3, -1), (4, 0), (3, 1)]),\n ... ]\n ... )\n >>> s\n 0 POINT (1.00000 1.00000)\n 1 LINESTRING (1.00000 -1.00000, 1.00000 0.00000)\n 2 POLYGON ((3.00000 -1.00000, 4.00000 0.00000, 3...\n dtype: geometry\n\n >>> s.skew(45, 30)\n 0 POINT (1.00000 1.00000)\n 1 LINESTRING (0.50000 -1.00000, 1.50000 0.00000)\n 2 POLYGON ((2.00000 -1.28868, 4.00000 0.28868, 4...\n dtype: geometry\n\n >>> s.skew(45, 30, origin=(0, 0))\n 0 POINT (2.00000 1.57735)\n 1 LINESTRING (0.00000 -0.42265, 1.00000 0.57735)\n 2 POLYGON ((2.00000 0.73205, 4.00000 2.30940, 4....\n dtype: geometry\n \"\"\"\n return _delegate_geo_method(\n \"skew\", self, xs, ys, origin=origin, use_radians=use_radians\n )\n\n @property\n def cx(self):\n \"\"\"\n Coordinate based indexer to select by intersection with bounding box.\n\n Format of input should be ``.cx[xmin:xmax, ymin:ymax]``. Any of\n ``xmin``, ``xmax``, ``ymin``, and ``ymax`` can be provided, but input\n must include a comma separating x and y slices. That is, ``.cx[:, :]``\n will return the full series/frame, but ``.cx[:]`` is not implemented.\n\n Examples\n --------\n >>> from shapely.geometry import LineString, Point\n >>> s = geopandas.GeoSeries(\n ... [Point(0, 0), Point(1, 2), Point(3, 3), LineString([(0, 0), (3, 3)])]\n ... )\n >>> s\n 0 POINT (0.00000 0.00000)\n 1 POINT (1.00000 2.00000)\n 2 POINT (3.00000 3.00000)\n 3 LINESTRING (0.00000 0.00000, 3.00000 3.00000)\n dtype: geometry\n\n >>> s.cx[0:1, 0:1]\n 0 POINT (0.00000 0.00000)\n 3 LINESTRING (0.00000 0.00000, 3.00000 3.00000)\n dtype: geometry\n\n >>> s.cx[:, 1:]\n 1 POINT (1.00000 2.00000)\n 2 POINT (3.00000 3.00000)\n 3 LINESTRING (0.00000 0.00000, 3.00000 3.00000)\n dtype: geometry\n\n \"\"\"\n return _CoordinateIndexer(self)\n\n def equals(self, other):\n \"\"\"\n Test whether two objects contain the same elements.\n\n This function allows two GeoSeries or GeoDataFrames to be compared\n against each other to see if they have the same shape and elements.\n Missing values in the same location are considered equal. The\n row/column index do not need to have the same type (as long as the\n values are still considered equal), but the dtypes of the respective\n columns must be the same.\n\n Parameters\n ----------\n other : GeoSeries or GeoDataFrame\n The other GeoSeries or GeoDataFrame to be compared with the first.\n\n Returns\n -------\n bool\n True if all elements are the same in both objects, False\n otherwise.\n \"\"\"\n # we override this because pandas is using `self._constructor` in the\n # isinstance check (https://github.com/geopandas/geopandas/issues/1420)\n if not isinstance(other, type(self)):\n return False\n return self._data.equals(other._data)\n\n\nclass _CoordinateIndexer(object):\n # see docstring GeoPandasBase.cx property above\n\n def __init__(self, obj):\n self.obj = obj\n\n def __getitem__(self, key):\n obj = self.obj\n xs, ys = key\n # handle numeric values as x and/or y coordinate index\n if type(xs) is not slice:\n xs = slice(xs, xs)\n if type(ys) is not slice:\n ys = slice(ys, ys)\n # don't know how to handle step; should this raise?\n if xs.step is not None or ys.step is not None:\n warn(\"Ignoring step - full interval is used.\")\n if xs.start is None or xs.stop is None or ys.start is None or ys.stop is None:\n xmin, ymin, xmax, ymax = obj.total_bounds\n bbox = box(\n xs.start if xs.start is not None else xmin,\n ys.start if ys.start is not None else ymin,\n xs.stop if xs.stop is not None else xmax,\n ys.stop if ys.stop is not None else ymax,\n )\n idx = obj.intersects(bbox)\n return obj[idx]\n",
"\"\"\"\nSee generate_legacy_storage_files.py for the creation of the legacy files.\n\n\"\"\"\nfrom distutils.version import LooseVersion\nimport glob\nimport os\nimport pathlib\n\nimport pandas as pd\n\nimport pyproj\n\nimport pytest\nfrom geopandas.testing import assert_geodataframe_equal\nfrom geopandas import _compat as compat\nimport geopandas\nfrom shapely.geometry import Point\n\nDATA_PATH = pathlib.Path(os.path.dirname(__file__)) / \"data\"\n\n\[email protected](scope=\"module\")\ndef current_pickle_data():\n # our current version pickle data\n from .generate_legacy_storage_files import create_pickle_data\n\n return create_pickle_data()\n\n\nfiles = glob.glob(str(DATA_PATH / \"pickle\" / \"*.pickle\"))\n\n\[email protected](params=files, ids=[p.split(\"/\")[-1] for p in files])\ndef legacy_pickle(request):\n return request.param\n\n\[email protected]\ndef with_use_pygeos_false():\n orig = geopandas.options.use_pygeos\n geopandas.options.use_pygeos = not orig\n yield\n geopandas.options.use_pygeos = orig\n\n\[email protected](\n compat.USE_PYGEOS or (str(pyproj.__version__) < LooseVersion(\"2.4\")),\n reason=(\n \"pygeos-based unpickling currently only works for pygeos-written files; \"\n \"old pyproj versions can't read pickles from newer pyproj versions\"\n ),\n)\ndef test_legacy_pickles(current_pickle_data, legacy_pickle):\n result = pd.read_pickle(legacy_pickle)\n\n for name, value in result.items():\n expected = current_pickle_data[name]\n assert_geodataframe_equal(value, expected)\n\n\ndef test_round_trip_current(tmpdir, current_pickle_data):\n data = current_pickle_data\n\n for name, value in data.items():\n path = str(tmpdir / \"{}.pickle\".format(name))\n value.to_pickle(path)\n result = pd.read_pickle(path)\n assert_geodataframe_equal(result, value)\n assert isinstance(result.has_sindex, bool)\n\n\[email protected](not compat.HAS_PYGEOS, reason=\"requires pygeos to test #1745\")\ndef test_pygeos_switch(tmpdir, with_use_pygeos_false):\n gdf_crs = geopandas.GeoDataFrame(\n {\"a\": [0.1, 0.2, 0.3], \"geometry\": [Point(1, 1), Point(2, 2), Point(3, 3)]},\n crs=\"EPSG:4326\",\n )\n path = str(tmpdir / \"gdf_crs.pickle\")\n gdf_crs.to_pickle(path)\n result = pd.read_pickle(path)\n assert_geodataframe_equal(result, gdf_crs)\n",
"import json\nimport os\nimport random\nimport shutil\nimport tempfile\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nimport pandas as pd\n\nfrom pyproj import CRS\nfrom shapely.geometry import (\n LineString,\n MultiLineString,\n MultiPoint,\n MultiPolygon,\n Point,\n Polygon,\n)\nfrom shapely.geometry.base import BaseGeometry\n\nfrom geopandas import GeoSeries, GeoDataFrame\nfrom geopandas._compat import PYPROJ_LT_3\nfrom geopandas.array import GeometryArray, GeometryDtype\nfrom geopandas.testing import assert_geoseries_equal\n\nfrom geopandas.tests.util import geom_equals\nfrom pandas.testing import assert_series_equal\nimport pytest\n\n\nclass TestSeries:\n def setup_method(self):\n self.tempdir = tempfile.mkdtemp()\n self.t1 = Polygon([(0, 0), (1, 0), (1, 1)])\n self.t2 = Polygon([(0, 0), (1, 1), (0, 1)])\n self.sq = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n self.g1 = GeoSeries([self.t1, self.sq])\n self.g2 = GeoSeries([self.sq, self.t1])\n self.g3 = GeoSeries([self.t1, self.t2])\n self.g3.crs = \"epsg:4326\"\n self.g4 = GeoSeries([self.t2, self.t1])\n self.na = GeoSeries([self.t1, self.t2, Polygon()])\n self.na_none = GeoSeries([self.t1, self.t2, None])\n self.a1 = self.g1.copy()\n self.a1.index = [\"A\", \"B\"]\n self.a2 = self.g2.copy()\n self.a2.index = [\"B\", \"C\"]\n self.esb = Point(-73.9847, 40.7484)\n self.sol = Point(-74.0446, 40.6893)\n self.landmarks = GeoSeries([self.esb, self.sol], crs=\"epsg:4326\")\n self.l1 = LineString([(0, 0), (0, 1), (1, 1)])\n self.l2 = LineString([(0, 0), (1, 0), (1, 1), (0, 1)])\n self.g5 = GeoSeries([self.l1, self.l2])\n\n def teardown_method(self):\n shutil.rmtree(self.tempdir)\n\n def test_copy(self):\n gc = self.g3.copy()\n assert type(gc) is GeoSeries\n assert self.g3.name == gc.name\n assert self.g3.crs == gc.crs\n\n def test_in(self):\n assert self.t1 in self.g1\n assert self.sq in self.g1\n assert self.t1 in self.a1\n assert self.t2 in self.g3\n assert self.sq not in self.g3\n assert 5 not in self.g3\n\n def test_align(self):\n a1, a2 = self.a1.align(self.a2)\n assert isinstance(a1, GeoSeries)\n assert isinstance(a2, GeoSeries)\n assert a2[\"A\"] is None\n assert a1[\"B\"].equals(a2[\"B\"])\n assert a1[\"C\"] is None\n\n def test_align_crs(self):\n a1 = self.a1\n a1.crs = \"epsg:4326\"\n a2 = self.a2\n a2.crs = \"epsg:31370\"\n\n res1, res2 = a1.align(a2)\n assert res1.crs == \"epsg:4326\"\n assert res2.crs == \"epsg:31370\"\n\n a2.crs = None\n res1, res2 = a1.align(a2)\n assert res1.crs == \"epsg:4326\"\n assert res2.crs is None\n\n def test_align_mixed(self):\n a1 = self.a1\n s2 = pd.Series([1, 2], index=[\"B\", \"C\"])\n res1, res2 = a1.align(s2)\n\n exp2 = pd.Series([np.nan, 1, 2], index=[\"A\", \"B\", \"C\"])\n assert_series_equal(res2, exp2)\n\n def test_warning_if_not_aligned(self):\n # GH-816\n # Test that warning is issued when operating on non-aligned series\n\n # _series_op\n with pytest.warns(UserWarning, match=\"The indices .+ different\"):\n self.a1.contains(self.a2)\n\n # _geo_op\n with pytest.warns(UserWarning, match=\"The indices .+ different\"):\n self.a1.union(self.a2)\n\n def test_no_warning_if_aligned(self):\n # GH-816\n # Test that warning is not issued when operating on aligned series\n a1, a2 = self.a1.align(self.a2)\n\n with pytest.warns(None) as warnings:\n a1.contains(a2) # _series_op, explicitly aligned\n self.g1.intersects(self.g2) # _series_op, implicitly aligned\n a2.union(a1) # _geo_op, explicitly aligned\n self.g2.intersection(self.g1) # _geo_op, implicitly aligned\n\n user_warnings = [w for w in warnings if w.category is UserWarning]\n assert not user_warnings, user_warnings[0].message\n\n def test_geom_equals(self):\n assert np.all(self.g1.geom_equals(self.g1))\n assert_array_equal(self.g1.geom_equals(self.sq), [False, True])\n\n def test_geom_equals_align(self):\n with pytest.warns(UserWarning, match=\"The indices .+ different\"):\n a = self.a1.geom_equals(self.a2, align=True)\n exp = pd.Series([False, True, False], index=[\"A\", \"B\", \"C\"])\n assert_series_equal(a, exp)\n\n a = self.a1.geom_equals(self.a2, align=False)\n exp = pd.Series([False, False], index=[\"A\", \"B\"])\n assert_series_equal(a, exp)\n\n def test_geom_almost_equals(self):\n # TODO: test decimal parameter\n assert np.all(self.g1.geom_almost_equals(self.g1))\n assert_array_equal(self.g1.geom_almost_equals(self.sq), [False, True])\n\n assert_array_equal(\n self.a1.geom_almost_equals(self.a2, align=True), [False, True, False]\n )\n assert_array_equal(\n self.a1.geom_almost_equals(self.a2, align=False), [False, False]\n )\n\n def test_geom_equals_exact(self):\n # TODO: test tolerance parameter\n assert np.all(self.g1.geom_equals_exact(self.g1, 0.001))\n assert_array_equal(self.g1.geom_equals_exact(self.sq, 0.001), [False, True])\n\n assert_array_equal(\n self.a1.geom_equals_exact(self.a2, 0.001, align=True), [False, True, False]\n )\n assert_array_equal(\n self.a1.geom_equals_exact(self.a2, 0.001, align=False), [False, False]\n )\n\n def test_equal_comp_op(self):\n s = GeoSeries([Point(x, x) for x in range(3)])\n res = s == Point(1, 1)\n exp = pd.Series([False, True, False])\n assert_series_equal(res, exp)\n\n def test_to_file(self):\n \"\"\" Test to_file and from_file \"\"\"\n tempfilename = os.path.join(self.tempdir, \"test.shp\")\n self.g3.to_file(tempfilename)\n # Read layer back in?\n s = GeoSeries.from_file(tempfilename)\n assert all(self.g3.geom_equals(s))\n # TODO: compare crs\n\n def test_to_json(self):\n \"\"\"\n Test whether GeoSeries.to_json works and returns an actual json file.\n \"\"\"\n json_str = self.g3.to_json()\n json.loads(json_str)\n # TODO : verify the output is a valid GeoJSON.\n\n def test_representative_point(self):\n assert np.all(self.g1.contains(self.g1.representative_point()))\n assert np.all(self.g2.contains(self.g2.representative_point()))\n assert np.all(self.g3.contains(self.g3.representative_point()))\n assert np.all(self.g4.contains(self.g4.representative_point()))\n\n def test_transform(self):\n utm18n = self.landmarks.to_crs(epsg=26918)\n lonlat = utm18n.to_crs(epsg=4326)\n assert np.all(self.landmarks.geom_almost_equals(lonlat))\n with pytest.raises(ValueError):\n self.g1.to_crs(epsg=4326)\n with pytest.raises(ValueError):\n self.landmarks.to_crs(crs=None, epsg=None)\n\n def test_estimate_utm_crs__geographic(self):\n if PYPROJ_LT_3:\n with pytest.raises(RuntimeError, match=r\"pyproj 3\\+ required\"):\n self.landmarks.estimate_utm_crs()\n else:\n assert self.landmarks.estimate_utm_crs() == CRS(\"EPSG:32618\")\n assert self.landmarks.estimate_utm_crs(\"NAD83\") == CRS(\"EPSG:26918\")\n\n @pytest.mark.skipif(PYPROJ_LT_3, reason=\"requires pyproj 3 or higher\")\n def test_estimate_utm_crs__projected(self):\n assert self.landmarks.to_crs(\"EPSG:3857\").estimate_utm_crs() == CRS(\n \"EPSG:32618\"\n )\n\n @pytest.mark.skipif(PYPROJ_LT_3, reason=\"requires pyproj 3 or higher\")\n def test_estimate_utm_crs__out_of_bounds(self):\n with pytest.raises(RuntimeError, match=\"Unable to determine UTM CRS\"):\n GeoSeries(\n [Polygon([(0, 90), (1, 90), (2, 90)])], crs=\"EPSG:4326\"\n ).estimate_utm_crs()\n\n @pytest.mark.skipif(PYPROJ_LT_3, reason=\"requires pyproj 3 or higher\")\n def test_estimate_utm_crs__missing_crs(self):\n with pytest.raises(RuntimeError, match=\"crs must be set\"):\n GeoSeries([Polygon([(0, 90), (1, 90), (2, 90)])]).estimate_utm_crs()\n\n def test_fillna(self):\n # default is to fill with empty geometry\n na = self.na_none.fillna()\n assert isinstance(na[2], BaseGeometry)\n assert na[2].is_empty\n assert geom_equals(self.na_none[:2], na[:2])\n # XXX: method works inconsistently for different pandas versions\n # self.na_none.fillna(method='backfill')\n\n def test_coord_slice(self):\n \"\"\" Test CoordinateSlicer \"\"\"\n # need some better test cases\n assert geom_equals(self.g3, self.g3.cx[:, :])\n assert geom_equals(self.g3[[True, False]], self.g3.cx[0.9:, :0.1])\n assert geom_equals(self.g3[[False, True]], self.g3.cx[0:0.1, 0.9:1.0])\n\n def test_coord_slice_with_zero(self):\n # Test that CoordinateSlice correctly handles zero slice (#GH477).\n\n gs = GeoSeries([Point(x, x) for x in range(-3, 4)])\n assert geom_equals(gs.cx[:0, :0], gs.loc[:3])\n assert geom_equals(gs.cx[:, :0], gs.loc[:3])\n assert geom_equals(gs.cx[:0, :], gs.loc[:3])\n assert geom_equals(gs.cx[0:, 0:], gs.loc[3:])\n assert geom_equals(gs.cx[0:, :], gs.loc[3:])\n assert geom_equals(gs.cx[:, 0:], gs.loc[3:])\n\n def test_geoseries_geointerface(self):\n assert self.g1.__geo_interface__[\"type\"] == \"FeatureCollection\"\n assert len(self.g1.__geo_interface__[\"features\"]) == self.g1.shape[0]\n\n def test_proj4strings(self):\n # As string\n reprojected = self.g3.to_crs(\"+proj=utm +zone=30\")\n reprojected_back = reprojected.to_crs(epsg=4326)\n assert np.all(self.g3.geom_almost_equals(reprojected_back))\n\n # As dict\n reprojected = self.g3.to_crs({\"proj\": \"utm\", \"zone\": \"30\"})\n reprojected_back = reprojected.to_crs(epsg=4326)\n assert np.all(self.g3.geom_almost_equals(reprojected_back))\n\n # Set to equivalent string, convert, compare to original\n copy = self.g3.copy()\n copy.crs = \"epsg:4326\"\n reprojected = copy.to_crs({\"proj\": \"utm\", \"zone\": \"30\"})\n reprojected_back = reprojected.to_crs(epsg=4326)\n assert np.all(self.g3.geom_almost_equals(reprojected_back))\n\n # Conversions by different format\n reprojected_string = self.g3.to_crs(\"+proj=utm +zone=30\")\n reprojected_dict = self.g3.to_crs({\"proj\": \"utm\", \"zone\": \"30\"})\n assert np.all(reprojected_string.geom_almost_equals(reprojected_dict))\n\n def test_from_wkb(self):\n assert_geoseries_equal(self.g1, GeoSeries.from_wkb([self.t1.wkb, self.sq.wkb]))\n\n def test_from_wkb_series(self):\n s = pd.Series([self.t1.wkb, self.sq.wkb], index=[1, 2])\n expected = self.g1.copy()\n expected.index = pd.Index([1, 2])\n assert_geoseries_equal(expected, GeoSeries.from_wkb(s))\n\n def test_from_wkb_series_with_index(self):\n index = [0]\n s = pd.Series([self.t1.wkb, self.sq.wkb], index=[0, 2])\n expected = self.g1.reindex(index)\n assert_geoseries_equal(expected, GeoSeries.from_wkb(s, index=index))\n\n def test_from_wkt(self):\n assert_geoseries_equal(self.g1, GeoSeries.from_wkt([self.t1.wkt, self.sq.wkt]))\n\n def test_from_wkt_series(self):\n s = pd.Series([self.t1.wkt, self.sq.wkt], index=[1, 2])\n expected = self.g1.copy()\n expected.index = pd.Index([1, 2])\n assert_geoseries_equal(expected, GeoSeries.from_wkt(s))\n\n def test_from_wkt_series_with_index(self):\n index = [0]\n s = pd.Series([self.t1.wkt, self.sq.wkt], index=[0, 2])\n expected = self.g1.reindex(index)\n assert_geoseries_equal(expected, GeoSeries.from_wkt(s, index=index))\n\n def test_to_wkb(self):\n assert_series_equal(pd.Series([self.t1.wkb, self.sq.wkb]), self.g1.to_wkb())\n assert_series_equal(\n pd.Series([self.t1.wkb_hex, self.sq.wkb_hex]), self.g1.to_wkb(hex=True)\n )\n\n def test_to_wkt(self):\n assert_series_equal(pd.Series([self.t1.wkt, self.sq.wkt]), self.g1.to_wkt())\n\n\ndef test_missing_values_empty_warning():\n s = GeoSeries([Point(1, 1), None, np.nan, BaseGeometry(), Polygon()])\n with pytest.warns(UserWarning):\n s.isna()\n\n with pytest.warns(UserWarning):\n s.notna()\n\n\[email protected](\"ignore::UserWarning\")\ndef test_missing_values():\n s = GeoSeries([Point(1, 1), None, np.nan, BaseGeometry(), Polygon()])\n\n # construction -> missing values get normalized to None\n assert s[1] is None\n assert s[2] is None\n assert s[3].is_empty\n assert s[4].is_empty\n\n # isna / is_empty\n assert s.isna().tolist() == [False, True, True, False, False]\n assert s.is_empty.tolist() == [False, False, False, True, True]\n assert s.notna().tolist() == [True, False, False, True, True]\n\n # fillna defaults to fill with empty geometry -> no missing values anymore\n assert not s.fillna().isna().any()\n\n # dropna drops the missing values\n assert not s.dropna().isna().any()\n assert len(s.dropna()) == 3\n\n\ndef test_geoseries_crs():\n gs = GeoSeries()\n gs.crs = \"IGNF:ETRS89UTM28\"\n assert gs.crs.to_authority() == (\"IGNF\", \"ETRS89UTM28\")\n\n\n# -----------------------------------------------------------------------------\n# # Constructor tests\n# -----------------------------------------------------------------------------\n\n\ndef check_geoseries(s):\n assert isinstance(s, GeoSeries)\n assert isinstance(s.geometry, GeoSeries)\n assert isinstance(s.dtype, GeometryDtype)\n assert isinstance(s.values, GeometryArray)\n\n\nclass TestConstructor:\n def test_constructor(self):\n s = GeoSeries([Point(x, x) for x in range(3)])\n check_geoseries(s)\n\n def test_single_geom_constructor(self):\n p = Point(1, 2)\n line = LineString([(2, 3), (4, 5), (5, 6)])\n poly = Polygon(\n [(0, 0), (1, 0), (1, 1), (0, 1)], [[(0.1, 0.1), (0.9, 0.1), (0.9, 0.9)]]\n )\n mp = MultiPoint([(1, 2), (3, 4), (5, 6)])\n mline = MultiLineString([[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10)]])\n\n poly2 = Polygon(\n [(0, 0), (0, -1), (-1, -1), (-1, 0)],\n [[(-0.1, -0.1), (-0.1, -0.5), (-0.5, -0.5), (-0.5, -0.1)]],\n )\n mpoly = MultiPolygon([poly, poly2])\n\n geoms = [p, line, poly, mp, mline, mpoly]\n index = [\"a\", \"b\", \"c\", \"d\"]\n\n for g in geoms:\n gs = GeoSeries(g)\n assert len(gs) == 1\n # accessing elements no longer give identical objects\n assert gs.iloc[0].equals(g)\n\n gs = GeoSeries(g, index=index)\n assert len(gs) == len(index)\n for x in gs:\n assert x.equals(g)\n\n def test_no_geometries_fallback(self):\n with pytest.warns(FutureWarning):\n s = GeoSeries([True, False, True])\n assert not isinstance(s, GeoSeries)\n assert type(s) == pd.Series\n\n with pytest.warns(FutureWarning):\n s = GeoSeries([\"a\", \"b\", \"c\"])\n assert not isinstance(s, GeoSeries)\n assert type(s) == pd.Series\n\n with pytest.warns(FutureWarning):\n s = GeoSeries([[1, 2], [3, 4]])\n assert not isinstance(s, GeoSeries)\n assert type(s) == pd.Series\n\n def test_empty(self):\n s = GeoSeries([])\n check_geoseries(s)\n\n s = GeoSeries()\n check_geoseries(s)\n\n def test_data_is_none(self):\n s = GeoSeries(index=range(3))\n check_geoseries(s)\n\n def test_from_series(self):\n shapes = [\n Polygon([(random.random(), random.random()) for _ in range(3)])\n for _ in range(10)\n ]\n s = pd.Series(shapes, index=list(\"abcdefghij\"), name=\"foo\")\n g = GeoSeries(s)\n check_geoseries(g)\n\n assert [a.equals(b) for a, b in zip(s, g)]\n assert s.name == g.name\n assert s.index is g.index\n\n # GH 1216\n def test_expanddim(self):\n s = GeoSeries(\n [MultiPoint([(0, 0), (1, 1)]), MultiPoint([(2, 2), (3, 3), (4, 4)])]\n )\n s = s.explode()\n df = s.reset_index()\n assert type(df) == GeoDataFrame\n"
] | [
[
"numpy.asarray",
"pandas.Series",
"pandas.DataFrame"
],
[
"pandas.read_pickle"
],
[
"pandas.Index",
"pandas.testing.assert_series_equal",
"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": []
},
{
"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.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
kongjy/pycroscopy | [
"fd02ac735a1194d2a5687183fafe00368ed8a3ca",
"fd02ac735a1194d2a5687183fafe00368ed8a3ca",
"fd02ac735a1194d2a5687183fafe00368ed8a3ca"
] | [
"pycroscopy/io/translators/time_series.py",
"pycroscopy/io/translators/igor_ibw.py",
"pycroscopy/io/translators/labview_h5_patcher.py"
] | [
"\"\"\"\nCreated on Feb 9, 2016\n\n@author: Chris Smith\n\"\"\"\n\nfrom __future__ import division, print_function, absolute_import, unicode_literals\n\nimport os\n\nimport numpy as np\nfrom skimage.measure import block_reduce\nimport h5py\n\nfrom .df_utils.dm_utils import read_dm3\nfrom pyUSID.io.image import read_image\nfrom pyUSID.io.translator import Translator\nfrom pyUSID.io.write_utils import Dimension, calc_chunks\nfrom pyUSID.io.hdf_utils import get_h5_obj_refs, link_as_main, write_main_dataset, \\\n write_simple_attrs, create_indexed_group\n\n\nclass MovieTranslator(Translator):\n \"\"\"\n Translate Pytchography data from a set of images to an HDF5 file\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(MovieTranslator, self).__init__(*args, **kwargs)\n\n self.rebin = False\n self.bin_factor = 1\n self.h5_file = None\n self.binning_func = self.__no_bin\n self.bin_func = None\n self.image_ext = None\n\n def translate(self, h5_path, image_path, bin_factor=None, bin_func=np.mean, start_image=0, image_type='.tif'):\n \"\"\"\n Basic method that adds Movie data to existing hdf5 file\n\n Parameters\n ----------------\n h5_path : str\n Absolute path to where the HDF5 file should be located\n image_path : str\n Absolute path to folder holding the image files\n bin_factor : array_like of uint, optional\n Downsampling factor for each dimension. Default is None.\n bin_func : callable, optional\n Function which will be called to calculate the return value\n of each block. Function must implement an axis parameter,\n i.e. numpy.mean. Ignored if bin_factor is None. Default is\n numpy.mean.\n start_image : int, optional\n Integer denoting which image in the file path should be considered the starting\n point. Default is 0, start with the first image on the list.\n image_type : str, optional\n File extension of images to load. Used to filter out other files in the same\n directory. Default .tif\n\n Returns\n ----------\n h5_main : h5py.Dataset\n HDF5 Dataset object that contains the flattened images\n\n \"\"\"\n self.image_ext = image_type\n\n image_path = os.path.abspath(image_path)\n h5_path = os.path.abspath(h5_path)\n \n if os.path.exists(h5_path):\n os.remove(h5_path)\n\n self.h5_file = h5py.File(h5_path, 'w')\n \n '''\n Get the list of all files with the provided extension and the number of files in the list\n '''\n if os.path.isfile(image_path):\n file_list, image_parms = read_dm3(image_path)\n usize = image_parms['SuperScan-Height']\n vsize = image_parms['SuperScan-Width']\n data_type = file_list.dtype.type\n num_images = file_list.shape[0] - start_image\n\n else:\n file_list = self._parse_file_path(image_path, image_type)\n\n # Set up the basic parameters associated with this set of images\n (usize, vsize), data_type, image_parms = self._getimagesize(os.path.join(image_path, file_list[0]))\n\n num_images = len(file_list) - start_image\n\n '''\n Check if a bin_factor is given. Set up binning objects if it is.\n '''\n if bin_factor is not None:\n self.rebin = True\n if isinstance(bin_factor, int):\n self.bin_factor = (bin_factor, bin_factor)\n elif len(bin_factor) == 2:\n self.bin_factor = tuple(bin_factor)\n else:\n raise ValueError('Input parameter `bin_factor` must be a length 2 array_like or an integer.\\n' +\n '{} was given.'.format(bin_factor))\n usize = int(usize / self.bin_factor[0])\n vsize = int(vsize / self.bin_factor[1])\n self.binning_func = block_reduce\n self.bin_func = bin_func\n data_type = np.float32\n\n h5_main, h5_mean_spec, h5_ronch = self._setupH5(usize, vsize, np.float32, num_images, image_parms)\n\n self._read_data(file_list[start_image:],\n h5_main, h5_mean_spec, h5_ronch, image_path)\n\n return h5_main\n\n def _read_data(self, image_stack, h5_main, h5_mean_spec, h5_ronch, image_path):\n \"\"\"\n Iterates over the images in `file_list`, reading each image and downsampling if\n reqeusted, and writes the flattened image to file. Also builds the Mean_Ronchigram\n and the Spectroscopic_Mean datasets at the same time.\n\n Parameters\n ----------\n image_stack : list of str\n List of all files in `image_path` that will be read\n h5_main : h5py.Dataset\n Dataset which will hold the Ronchigrams\n h5_mean_spec : h5py.Dataset\n Dataset which will hold the Spectroscopic Mean\n h5_ronch : h5py.Dataset\n Dataset which will hold the Mean Ronchigram\n image_path : str\n Absolute file path to the directory which hold the images\n\n Returns\n -------\n None\n \"\"\"\n\n mean_ronch = np.zeros(h5_ronch.shape, dtype=np.float32)\n\n num_files = len(image_stack)\n\n if os.path.isfile(image_path):\n self.__save_dm3_frames(image_stack, h5_main, h5_mean_spec, h5_ronch, mean_ronch, num_files)\n else:\n self.__read_image_files(image_stack, h5_main, h5_mean_spec, h5_ronch, image_path, mean_ronch, num_files)\n\n def __save_dm3_frames(self, image_stack, h5_main, h5_mean_spec, h5_ronch, mean_ronch, num_frames):\n \"\"\"\n\n :param image_stack:\n :param h5_main:\n :param h5_mean_spec:\n :param h5_ronch:\n :param mean_ronch:\n :param num_frames:\n :return:\n \"\"\"\n for iframe, thisframe in enumerate(image_stack):\n selected = (iframe + 1) % round(num_frames / 16) == 0\n if selected:\n print('Processing file...{}% - reading: {}'.format(round(100 * iframe / num_frames), iframe))\n image = self.binning_func(thisframe, self.bin_factor, self.bin_func).flatten()\n h5_main[:, iframe] = image\n\n h5_mean_spec[iframe] = np.mean(image)\n\n mean_ronch += image\n\n self.h5_file.flush()\n\n h5_ronch[:] = mean_ronch / num_frames\n self.h5_file.flush()\n\n def __read_image_files(self, image_stack, h5_main, h5_mean_spec, h5_ronch, image_path, mean_ronch, num_files):\n \"\"\"\n Read each image from `file_list` and save it in `h5_main`.\n\n Parameters\n ----------\n image_stack:\n :param h5_main:\n :param h5_mean_spec:\n :param h5_ronch:\n :param image_path:\n :param mean_ronch:\n :param num_files:\n :return:\n \"\"\"\n for ifile, thisfile in enumerate(image_stack):\n\n selected = (ifile + 1) % round(num_files / 16) == 0\n if selected:\n print('Processing file...{}% - reading: {}'.format(round(100 * ifile / num_files), thisfile))\n\n image = read_image(os.path.join(image_path, thisfile), greyscale=True)\n image = self.binning_func(image, self.bin_factor, self.bin_func)\n image = image.flatten()\n h5_main[:, ifile] = image\n\n h5_mean_spec[ifile] = np.mean(image)\n\n mean_ronch += image\n\n self.h5_file.flush()\n h5_ronch[:] = mean_ronch / num_files\n self.h5_file.flush()\n\n @staticmethod\n def downSampRoncVec(ronch_vec, binning_factor):\n \"\"\"\n Downsample the image by taking the mean over nearby values\n\n Parameters\n ----------\n ronch_vec : ndarray\n Image data\n binning_factor : int\n factor to reduce the size of the image by\n\n Returns\n -------\n ronc_mat3_mean : ndarray\n Flattened downsampled image\n \"\"\"\n ccd_pix = int(np.sqrt(ronch_vec.size))\n ronc_mat = ronch_vec.reshape(ccd_pix, ccd_pix)\n ronc_mat2 = ronc_mat.reshape(ccd_pix, ccd_pix / binning_factor, binning_factor)\n ronc_mat2_mean = ronc_mat2.mean(2) # take the mean along the 3rd dimension\n ronc_mat3 = ronc_mat2_mean.reshape(ccd_pix / binning_factor, binning_factor, -1)\n ronc_mat3_mean = ronc_mat3.mean(1)\n\n return ronc_mat3_mean.reshape(-1)\n\n @staticmethod\n def _parse_file_path(path, ftype='all'):\n \"\"\"\n Returns a list of all files in the directory given by path\n \n Parameters\n ---------------\n path : string / unicode\n absolute path to directory containing files\n ftype : this file types to return in file_list. (optional. Default is all) \n \n Returns\n ----------\n file_list : list of strings\n names of all files in directory located at path\n numfiles : unsigned int\n number of files in file_list\n \"\"\"\n\n # Get all files in directory\n file_list = os.listdir(path)\n\n # If no file type specified, return full list\n if ftype == 'all':\n return file_list\n\n # Remove files of type other than the request ftype from the list\n new_file_list = []\n for this_thing in file_list:\n # Make sure it's really a file\n if not os.path.isfile(os.path.join(path, this_thing)):\n continue\n\n split = os.path.splitext(this_thing)\n ext = split[1]\n if ext == ftype:\n new_file_list.append(os.path.join(path, this_thing))\n\n return new_file_list\n\n @staticmethod\n def _getimagesize(image):\n \"\"\"\n Returns the x and y size of the image in pixels\n \n Parameters\n ------------\n image : string / unicode\n absolute path to the image file\n \n Returns\n -----------\n (size, tmp.dtype) : Tuple \n \n size : unsigned integer\n x and y dimenstions of image\n dtype : data type\n Datatype of the image\n \"\"\"\n tmp, parms = read_image(image, get_parms=True)\n size = tmp.shape\n\n return size, tmp.dtype.type, parms\n\n def _setupH5(self, usize, vsize, data_type, num_images, main_parms):\n \"\"\"\n Setup the HDF5 file in which to store the data including creating\n the Position and Spectroscopic datasets\n\n Parameters\n ----------\n usize : int\n Number of pixel columns in the images\n vsize : int\n Number of pixel rows in the images\n data_type : type\n Data type to save image as\n num_images : int\n Number of images in the movie\n main_parms : dict\n\n\n Returns\n -------\n h5_main : h5py.Dataset\n HDF5 Dataset that the images will be written into\n h5_mean_spec : h5py.Dataset\n HDF5 Dataset that the mean over all positions will be written\n into\n h5_ronch : h5py.Dataset\n HDF5 Dateset that the mean over all Spectroscopic steps will be\n written into\n \"\"\"\n num_pixels = usize * vsize\n\n root_parms = dict()\n root_parms['data_type'] = 'PtychographyData'\n\n main_parms['num_images'] = num_images\n main_parms['image_size_u'] = usize\n main_parms['image_size_v'] = vsize\n main_parms['num_pixels'] = num_pixels\n main_parms['translator'] = 'Movie'\n\n # Create the hdf5 data Group\n write_simple_attrs(self.h5_file, root_parms)\n meas_grp = create_indexed_group(self.h5_file, 'Measurement')\n write_simple_attrs(meas_grp, main_parms)\n chan_grp = create_indexed_group(meas_grp, 'Channel')\n\n # Build the Position and Spectroscopic Datasets\n spec_dim = Dimension('Time', 's', np.arange(num_images))\n pos_dims = [Dimension('X', 'a.u.', np.arange(usize)), Dimension('Y', 'a.u.', np.arange(vsize))]\n\n ds_chunking = calc_chunks([num_pixels, num_images],\n data_type(0).itemsize,\n unit_chunks=(num_pixels, 1))\n\n # Allocate space for Main_Data and Pixel averaged Data\n h5_main = write_main_dataset(chan_grp, (num_pixels, num_images), 'Raw_Data',\n 'Intensity', 'a.u.',\n pos_dims, spec_dim,\n chunks=ds_chunking, dtype=data_type)\n h5_ronch = meas_grp.create_dataset('Mean_Ronchigram',\n data=np.zeros(num_pixels, dtype=np.float32),\n dtype=np.float32)\n h5_mean_spec = meas_grp.create_dataset('Spectroscopic_Mean',\n data=np.zeros(num_images, dtype=np.float32),\n dtype=np.float32)\n\n self.h5_file.flush()\n\n return h5_main, h5_mean_spec, h5_ronch\n\n @staticmethod\n def __no_bin(image, *args, **kwargs):\n \"\"\"\n Does absolutely nothing to the image. Exists so that we can have\n a bin function to call whether we actually rebin the image or not.\n\n Parameters\n ----------\n image : ndarray\n Image\n args:\n Argument list\n kwargs:\n Keyword argument list\n\n Returns\n -------\n image : ndarray\n The input image\n \"\"\"\n return image\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 07 16:04:34 2016\n\n@author: Suhas Somnath, Chris R. Smith, Raj Giri\n\"\"\"\n\nfrom __future__ import division, print_function, absolute_import, unicode_literals\nimport sys\nfrom os import path, remove # File Path formatting\nimport numpy as np # For array operations\nimport h5py\nfrom igor import binarywave as bw\n\nfrom pyUSID.io.translator import Translator # Because this class extends the abstract Translator class\nfrom pyUSID.io.write_utils import VALUES_DTYPE, Dimension\nfrom pyUSID.io.hdf_utils import create_indexed_group, write_main_dataset, write_simple_attrs, write_ind_val_dsets\n\nif sys.version_info.major == 3:\n unicode = str\n\n\nclass IgorIBWTranslator(Translator):\n \"\"\"\n Translates Igor Binary Wave (.ibw) files containing images or force curves to .h5\n \"\"\"\n\n @staticmethod\n def is_valid_file(file_path):\n \"\"\"\n Checks whether the provided file can be read by this translator\n\n Parameters\n ----------\n file_path : str\n Path to raw data file\n\n Returns\n -------\n obj : str\n Path to file that will be accepted by the translate() function if\n this translator is indeed capable of translating the provided file.\n Otherwise, None will be returned\n \"\"\"\n if not isinstance(file_path, (str, unicode)):\n raise TypeError('file_path should be a string object')\n if not path.isfile(file_path):\n return None\n file_path = path.abspath(file_path)\n extension = path.splitext(file_path)[1][1:]\n if extension == 'ibw':\n # This should be sufficient I think.\n return file_path\n else:\n return None\n\n def translate(self, file_path, verbose=False, append_path='', \n grp_name='Measurement', parm_encoding='utf-8'):\n \"\"\"\n Translates the provided file to .h5\n\n Parameters\n ----------\n file_path : String / unicode\n Absolute path of the .ibw file\n verbose : Boolean (Optional)\n Whether or not to show print statements for debugging\n append_path : string (Optional)\n h5_file to add these data to, must be a path to the h5_file on disk\n grp_name : string (Optional)\n Change from default \"Measurement\" name to something specific\n parm_encoding : str, optional\n Codec to be used to decode the bytestrings into Python strings if needed.\n Default 'utf-8'\n\n Returns\n -------\n h5_path : String / unicode\n Absolute path of the .h5 file\n \"\"\"\n file_path = path.abspath(file_path)\n # Prepare the .h5 file:\n folder_path, base_name = path.split(file_path)\n base_name = base_name[:-4]\n \n if not append_path:\n h5_path = path.join(folder_path, base_name + '.h5')\n if path.exists(h5_path):\n remove(h5_path)\n h5_file = h5py.File(h5_path, 'w')\n else:\n h5_path = append_path\n if not path.exists(append_path):\n raise Exception('File does not exist. Check pathname.')\n h5_file = h5py.File(h5_path, 'r+')\n \n\n # Load the ibw file first\n ibw_obj = bw.load(file_path)\n ibw_wave = ibw_obj.get('wave')\n parm_dict = self._read_parms(ibw_wave, parm_encoding)\n chan_labels, chan_units = self._get_chan_labels(ibw_wave, parm_encoding)\n\n if verbose:\n print('Channels and units found:')\n print(chan_labels)\n print(chan_units)\n\n # Get the data to figure out if this is an image or a force curve\n images = ibw_wave.get('wData')\n\n if images.shape[-1] != len(chan_labels):\n chan_labels = chan_labels[1:] # for layer 0 null set errors in older AR software\n\n if images.ndim == 3: # Image stack\n if verbose:\n print('Found image stack of size {}'.format(images.shape))\n type_suffix = 'Image'\n\n num_rows = parm_dict['ScanLines']\n num_cols = parm_dict['ScanPoints']\n\n images = images.transpose(2, 1, 0) # now ordered as [chan, Y, X] image\n images = np.reshape(images, (images.shape[0], -1, 1)) # 3D [chan, Y*X points,1]\n\n pos_desc = [Dimension('X', 'm', np.linspace(0, parm_dict['FastScanSize'], num_cols)),\n Dimension('Y', 'm', np.linspace(0, parm_dict['SlowScanSize'], num_rows))]\n\n spec_desc = Dimension('arb', 'a.u.', [1])\n\n else: # single force curve\n if verbose:\n print('Found force curve of size {}'.format(images.shape))\n\n type_suffix = 'ForceCurve'\n images = np.atleast_3d(images) # now [Z, chan, 1]\n images = images.transpose((1, 2, 0)) # [chan ,1, Z] force curve\n\n # The data generated above varies linearly. Override.\n # For now, we'll shove the Z sensor data into the spectroscopic values.\n\n # Find the channel that corresponds to either Z sensor or Raw:\n try:\n chan_ind = chan_labels.index('ZSnsr')\n spec_data = VALUES_DTYPE(images[chan_ind]).squeeze()\n except ValueError:\n try:\n chan_ind = chan_labels.index('Raw')\n spec_data = VALUES_DTYPE(images[chan_ind]).squeeze()\n except ValueError:\n # We don't expect to come here. If we do, spectroscopic values remains as is\n spec_data = np.arange(images.shape[2])\n\n pos_desc = Dimension('X', 'm', [1])\n spec_desc = Dimension('Z', 'm', spec_data)\n\n # Create measurement group\n meas_grp = create_indexed_group(h5_file, grp_name)\n\n # Write file and measurement level parameters\n global_parms = dict()\n global_parms['data_type'] = 'IgorIBW_' + type_suffix\n global_parms['translator'] = 'IgorIBW'\n write_simple_attrs(h5_file, global_parms)\n\n write_simple_attrs(meas_grp, parm_dict)\n\n # Create Position and spectroscopic datasets\n h5_pos_inds, h5_pos_vals = write_ind_val_dsets(meas_grp, pos_desc, is_spectral=False)\n h5_spec_inds, h5_spec_vals = write_ind_val_dsets(meas_grp, spec_desc, is_spectral=True)\n\n # Prepare the list of raw_data datasets\n for chan_data, chan_name, chan_unit in zip(images, chan_labels, chan_units):\n if verbose:\n print('channel', chan_name)\n print('unit', chan_unit)\n chan_grp = create_indexed_group(meas_grp, 'Channel')\n\n write_main_dataset(chan_grp, np.atleast_2d(chan_data), 'Raw_Data',\n chan_name, chan_unit,\n None, None,\n h5_pos_inds=h5_pos_inds, h5_pos_vals=h5_pos_vals,\n h5_spec_inds=h5_spec_inds, h5_spec_vals=h5_spec_vals,\n dtype=np.float32)\n\n if verbose:\n print('Finished preparing raw datasets')\n\n h5_file.close()\n return h5_path\n\n @staticmethod\n def _read_parms(ibw_wave, codec='utf-8'):\n \"\"\"\n Parses the parameters in the provided dictionary\n\n Parameters\n ----------\n ibw_wave : dictionary\n Wave entry in the dictionary obtained from loading the ibw file\n codec : str, optional\n Codec to be used to decode the bytestrings into Python strings if needed.\n Default 'utf-8'\n\n Returns\n -------\n parm_dict : dictionary\n Dictionary containing parameters\n \"\"\"\n parm_string = ibw_wave.get('note')\n if type(parm_string) == bytes:\n try:\n parm_string = parm_string.decode(codec)\n except:\n parm_string = parm_string.decode('ISO-8859-1') # for older AR software\n parm_string = parm_string.rstrip('\\r')\n parm_list = parm_string.split('\\r')\n parm_dict = dict()\n for pair_string in parm_list:\n temp = pair_string.split(':')\n if len(temp) == 2:\n temp = [item.strip() for item in temp]\n try:\n num = float(temp[1])\n parm_dict[temp[0]] = num\n try:\n if num == int(num):\n parm_dict[temp[0]] = int(num)\n except OverflowError:\n pass\n except ValueError:\n parm_dict[temp[0]] = temp[1]\n\n # Grab the creation and modification times:\n other_parms = ibw_wave.get('wave_header')\n for key in ['creationDate', 'modDate', 'bname']:\n try:\n parm_dict[key] = other_parms[key]\n except KeyError:\n pass\n return parm_dict\n\n @staticmethod\n def _get_chan_labels(ibw_wave, codec='utf-8'):\n \"\"\"\n Retrieves the names of the data channels and default units\n\n Parameters\n ----------\n ibw_wave : dictionary\n Wave entry in the dictionary obtained from loading the ibw file\n codec : str, optional\n Codec to be used to decode the bytestrings into Python strings if needed.\n Default 'utf-8'\n\n Returns\n -------\n labels : list of strings\n List of the names of the data channels\n default_units : list of strings\n List of units for the measurement in each channel\n \"\"\"\n temp = ibw_wave.get('labels')\n labels = []\n for item in temp:\n if len(item) > 0:\n labels += item\n for item in labels:\n if item == '':\n labels.remove(item)\n\n default_units = list()\n for chan_ind, chan in enumerate(labels):\n # clean up channel names\n if type(chan) == bytes:\n chan = chan.decode(codec)\n if chan.lower().rfind('trace') > 0:\n labels[chan_ind] = chan[:chan.lower().rfind('trace') + 5]\n else:\n labels[chan_ind] = chan\n # Figure out (default) units\n if chan.startswith('Phase'):\n default_units.append('deg')\n elif chan.startswith('Current'):\n default_units.append('A')\n else:\n default_units.append('m')\n\n return labels, default_units\n\n def _parse_file_path(self, input_path):\n pass\n\n def _read_data(self):\n pass\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 3 15:24:12 2015\n\n@author: Chris R. Smith\n\"\"\"\n\nfrom __future__ import division, print_function, absolute_import, unicode_literals\nfrom warnings import warn\nimport sys\nimport h5py\nimport os\nimport numpy as np\nfrom pyUSID.io.translator import Translator\nfrom pyUSID.io.hdf_utils import get_attr, link_as_main, check_and_link_ancillary, find_results_groups, find_dataset\nfrom pyUSID.io.write_utils import create_spec_inds_from_vals\n\nif sys.version_info.major == 3:\n unicode = str\n\n\nclass LabViewH5Patcher(Translator):\n \"\"\"\n Patches the hdf5 files from the LabView V3 data aquisition software to meet the\n standards of the Pycroscopy data format.\n\n \"\"\"\n\n def __init__(self):\n super(LabViewH5Patcher, self).__init__()\n\n def _parse_file_path(self, input_path):\n pass\n\n def _read_data(self):\n pass\n\n @staticmethod\n def is_valid_file(file_path):\n \"\"\"\n Checks whether the provided file can be read by this translator\n\n Parameters\n ----------\n file_path : str\n Path to raw data file\n\n Returns\n -------\n obj : str\n Path to file that will be accepted by the translate() function if\n this translator is indeed capable of translating the provided file.\n Otherwise, None will be returned\n \"\"\"\n if not isinstance(file_path, (str, unicode)):\n raise TypeError('file_path should be a string object')\n if not os.path.isfile(file_path):\n return None\n\n file_path = os.path.abspath(file_path)\n extension = os.path.splitext(file_path)[1][1:]\n if extension not in ['h5', 'hdf5']:\n return None\n try:\n h5_f = h5py.File(file_path, 'r+')\n except:\n return None\n\n # TODO: Make this check as lot stronger. Currently brittle\n if 'DAQ_software_version_name' not in h5_f.attrs.keys():\n return None\n\n if len(find_dataset(h5_f, 'Raw_Data')) < 1:\n return None\n return file_path\n\n def translate(self, h5_path, force_patch=False, **kwargs):\n \"\"\"\n Add the needed references and attributes to the h5 file that are not created by the\n LabView data aquisition program.\n\n Parameters\n ----------\n h5_path : str\n path to the h5 file\n force_patch : bool, optional\n Should the check to see if the file has already been patched be ignored.\n Default False.\n\n Returns\n -------\n h5_file : str\n path to the patched dataset\n\n \"\"\"\n # Open the file and check if a patch is needed\n h5_file = h5py.File(os.path.abspath(h5_path), 'r+')\n if h5_file.attrs.get('translator') is not None and not force_patch:\n print('File is already Pycroscopy ready.')\n h5_file.close()\n return h5_path\n\n '''\n Get the list of all Raw_Data Datasets\n Loop over the list and update the needed attributes\n '''\n raw_list = find_dataset(h5_file, 'Raw_Data')\n for h5_raw in raw_list:\n if 'quantity' not in h5_raw.attrs:\n h5_raw.attrs['quantity'] = 'quantity'\n if 'units' not in h5_raw.attrs:\n h5_raw.attrs['units'] = 'a.u.'\n\n # Grab the channel and measurement group of the data to check some needed attributes\n h5_chan = h5_raw.parent\n try:\n c_type = get_attr(h5_chan, 'channel_type')\n\n except KeyError:\n warn_str = \"'channel_type' was not found as an attribute of {}.\\n\".format(h5_chan.name)\n warn_str += \"If this is BEPS or BELine data from the LabView aquisition software, \" + \\\n \"please run the following piece of code. Afterwards, run this function again.\\n\" + \\\n \"CODE: \" \\\n \"hdf.file['{}'].attrs['channel_type'] = 'BE'\".format(h5_chan.name)\n warn(warn_str)\n h5_file.close()\n return h5_path\n\n except:\n raise\n\n if c_type != 'BE':\n continue\n\n h5_meas = h5_chan.parent\n h5_meas.attrs['num_UDVS_steps'] = h5_meas.attrs['num_steps']\n\n # Get the object handles for the Indices and Values datasets\n h5_pos_inds = h5_chan['Position_Indices']\n h5_pos_vals = h5_chan['Position_Values']\n h5_spec_inds = h5_chan['Spectroscopic_Indices']\n h5_spec_vals = h5_chan['Spectroscopic_Values']\n\n # Make sure we have correct spectroscopic indices for the given values\n ds_spec_inds = create_spec_inds_from_vals(h5_spec_vals[()])\n if not np.allclose(ds_spec_inds, h5_spec_inds[()]):\n h5_spec_inds[:, :] = ds_spec_inds[:, :]\n h5_file.flush()\n\n # Get the labels and units for the Spectroscopic datasets\n h5_spec_labels = h5_spec_inds.attrs['labels']\n inds_and_vals = [h5_pos_inds, h5_pos_vals, h5_spec_inds, h5_spec_vals]\n for dset in inds_and_vals:\n spec_labels = dset.attrs['labels']\n try:\n spec_units = dset.attrs['units']\n\n if len(spec_units) != len(spec_labels):\n raise KeyError\n\n except KeyError:\n dset['units'] = ['' for _ in spec_labels]\n except:\n raise\n\n for ilabel, label in enumerate(h5_spec_labels):\n label_slice = (slice(ilabel, ilabel + 1), slice(None))\n if label == '':\n label = 'Step'\n h5_spec_inds.attrs[label] = h5_spec_inds.regionref[label_slice]\n h5_spec_vals.attrs[label] = h5_spec_vals.regionref[label_slice]\n\n # Link the references to the Indices and Values datasets to the Raw_Data\n link_as_main(h5_raw, h5_pos_inds, h5_pos_vals, h5_spec_inds, h5_spec_vals)\n\n # Also link the Bin_Frequencies and Bin_Wfm_Type datasets\n h5_freqs = h5_chan['Bin_Frequencies']\n aux_dset_names = ['Bin_Frequencies']\n aux_dset_refs = [h5_freqs.ref]\n check_and_link_ancillary(h5_raw, aux_dset_names, anc_refs=aux_dset_refs)\n\n '''\n Get all SHO_Fit groups for the Raw_Data and loop over them\n Get the Guess and Spectroscopic Datasets for each SHO_Fit group\n '''\n sho_list = find_results_groups(h5_raw, 'SHO_Fit')\n for h5_sho in sho_list:\n h5_sho_guess = h5_sho['Guess']\n h5_sho_spec_inds = h5_sho['Spectroscopic_Indices']\n h5_sho_spec_vals = h5_sho['Spectroscopic_Values']\n\n # Make sure we have correct spectroscopic indices for the given values\n ds_sho_spec_inds = create_spec_inds_from_vals(h5_sho_spec_inds[()])\n if not np.allclose(ds_sho_spec_inds, h5_sho_spec_inds[()]):\n h5_sho_spec_inds[:, :] = ds_sho_spec_inds[:, :]\n\n # Get the labels and units for the Spectroscopic datasets\n h5_sho_spec_labels = get_attr(h5_sho_spec_inds, 'labels')\n link_as_main(h5_sho_guess, h5_pos_inds, h5_pos_vals, h5_sho_spec_inds, h5_sho_spec_vals)\n sho_inds_and_vals = [h5_sho_spec_inds, h5_sho_spec_vals]\n\n for dset in sho_inds_and_vals:\n spec_labels = get_attr(dset, 'labels')\n try:\n spec_units = get_attr(dset, 'units')\n\n if len(spec_units) != len(spec_labels):\n raise KeyError\n\n except KeyError:\n spec_units = [''.encode('utf-8') for _ in spec_labels]\n dset.attrs['units'] = spec_units\n\n except:\n raise\n\n # Make region references in the\n for ilabel, label in enumerate(h5_sho_spec_labels):\n label_slice = (slice(ilabel, ilabel + 1), slice(None))\n if label == '':\n label = 'Step'.encode('utf-8')\n h5_sho_spec_inds.attrs[label] = h5_sho_spec_inds.regionref[label_slice]\n h5_sho_spec_vals.attrs[label] = h5_sho_spec_vals.regionref[label_slice]\n\n h5_file.flush()\n\n h5_file.attrs['translator'] = 'V3patcher'.encode('utf-8')\n\n h5_file.close()\n\n return h5_path\n"
] | [
[
"numpy.arange",
"numpy.sqrt",
"numpy.zeros",
"numpy.mean"
],
[
"numpy.linspace",
"numpy.reshape",
"numpy.arange",
"numpy.atleast_2d",
"numpy.atleast_3d"
],
[
"numpy.allclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ddoron9/deepface | [
"3b6dd0628cb4b0a32d1ccd836e2d765e187c1485"
] | [
"deepface/commons/realtime.py"
] | [
"import os\nfrom tqdm import tqdm\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport time\nimport re\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nfrom deepface import DeepFace\nfrom deepface.extendedmodels import Age\nfrom deepface.commons import functions, realtime, distance as dst\n\ndef analysis(db_path = '', model_name ='VGG-Face', distance_metric = 'cosine', enable_face_analysis = True\n\t\t\t\t, source = 0):\n\n\tinput_shape = (224, 224); input_shape_x = input_shape[0]; input_shape_y = input_shape[1]\n\n\ttext_color = (255,255,255)\n\n\temployees = []\n\t#check passed db folder exists\n\tif os.path.isdir(db_path) == True:\n\t\tfor r, d, f in os.walk(db_path): # r=root, d=directories, f = files\n\t\t\tfor file in f:\n\t\t\t\tif ('.jpg' in file):\n\t\t\t\t\t#exact_path = os.path.join(r, file)\n\t\t\t\t\texact_path = r + \"/\" + file\n\t\t\t\t\t#print(exact_path)\n\t\t\t\t\temployees.append(exact_path)\n\n\tif len(employees) == 0:\n\t\tprint(\"WARNING: There is no image in this path ( \", db_path,\") . Face recognition will not be performed.\")\n\n\t#------------------------\n\n\tif len(employees) > 0:\n\n\t\tmodel = DeepFace.build_model(model_name)\n\t\tprint(model_name,\" is built\")\n\n\t\t#------------------------\n\n\t\tinput_shape = functions.find_input_shape(model)\n\t\tinput_shape_x = input_shape[0]\n\t\tinput_shape_y = input_shape[1]\n\n\t\t#tuned thresholds for model and metric pair\n\t\tthreshold = dst.findThreshold(model_name, distance_metric)\n\n\t#------------------------\n\t#facial attribute analysis models\n\n\tif enable_face_analysis == True:\n\n\t\ttic = time.time()\n\n\t\temotion_model = DeepFace.build_model('Emotion')\n\t\tprint(\"Emotion model loaded\")\n\n\t\tage_model = DeepFace.build_model('Age')\n\t\tprint(\"Age model loaded\")\n\n\t\tgender_model = DeepFace.build_model('Gender')\n\t\tprint(\"Gender model loaded\")\n\n\t\ttoc = time.time()\n\n\t\tprint(\"Facial attibute analysis models loaded in \",toc-tic,\" seconds\")\n\n\t#------------------------\n\n\t#find embeddings for employee list\n\n\ttic = time.time()\n\n\tpbar = tqdm(range(0, len(employees)), desc='Finding embeddings')\n\n\tembeddings = []\n\t#for employee in employees:\n\tfor index in pbar:\n\t\temployee = employees[index]\n\t\tpbar.set_description(\"Finding embedding for %s\" % (employee.split(\"/\")[-1]))\n\t\tembedding = []\n\t\timg = functions.preprocess_face(img = employee, target_size = (input_shape_y, input_shape_x), enforce_detection = False)\n\t\timg_representation = model.predict(img)[0,:]\n\n\t\tembedding.append(employee)\n\t\tembedding.append(img_representation)\n\t\tembeddings.append(embedding)\n\n\tdf = pd.DataFrame(embeddings, columns = ['employee', 'embedding'])\n\tdf['distance_metric'] = distance_metric\n\n\ttoc = time.time()\n\n\tprint(\"Embeddings found for given data set in \", toc-tic,\" seconds\")\n\n\t#-----------------------\n\n\tpivot_img_size = 112 #face recognition result image\n\n\t#-----------------------\n\n\topencv_path = functions.get_opencv_path()\n\tface_detector_path = opencv_path+\"haarcascade_frontalface_default.xml\"\n\tface_cascade = cv2.CascadeClassifier(face_detector_path)\n\n\t#----------------------- \n\ttic = time.time()\n\n\tcap = cv2.VideoCapture(source) #webcam \n\n\tpeople = 0\n\twhile(True):\n\t\tret, img = cap.read()\n\n\t\tif img is None: \n\t\t\tbreak\n\n\t\t#cv2.namedWindow('img', cv2.WINDOW_FREERATIO)\n\t\t#cv2.setWindowProperty('img', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)\n\n\t\traw_img = img.copy()\n\t\tresolution = img.shape\n\n\t\tresolution_x = img.shape[1]; resolution_y = img.shape[0]\n \n\t\tfaces = face_cascade.detectMultiScale(img, 1.3, 5)\n\t\t\n\t\tif len(faces) == 0: \n\t\t\tcontinue \n\t\t# print(f'faces num : {len(faces)}')\n\t\tdetected_faces = [] \n\t\tfor (x,y,w,h) in faces:\n\t\t\tif w > 130: #discard small detected faces\n \n\t\t\t\tcv2.rectangle(img, (x,y), (x+w,y+h), (67,67,67), 1) #draw rectangle to main image\n\n\t\t\t\t# cv2.putText(img, str(frame_threshold - face_included_frames), (int(x+w/4),int(y+h/1.5)), cv2.FONT_HERSHEY_SIMPLEX, 4, (255, 255, 255), 2)\n\n\t\t\t\tdetected_face = img[int(y):int(y+h), int(x):int(x+w)] #crop detected face\n\n\t\t\t\t#-------------------------------------\n\t\t\t\t#chk 변경 필요\n\t\t\t\tdetected_faces.append((x,y,w,h)) \n\n\t\t\t\t#-------------------------------------\n\n\t\t#base_img = img.copy()\n\t\tbase_img = raw_img.copy()\n\t\tdetected_faces_final = detected_faces.copy()\n\t\ttry:\n\n\t\t\tfreeze_img = base_img.copy()\n\t\t\t#freeze_img = np.zeros(resolution, np.uint8) #here, np.uint8 handles showing white area issue\n\n\t\t\tfor detected_face in detected_faces_final:\n\t\t\t\tx = detected_face[0]; y = detected_face[1]\n\t\t\t\tw = detected_face[2]; h = detected_face[3]\n\n\t\t\t\tcv2.rectangle(freeze_img, (x,y), (x+w,y+h), (67,67,67), 1) #draw rectangle to main image\n\n\t\t\t\t#-------------------------------\n\n\t\t\t\t#apply deep learning for custom_face\n\n\t\t\t\tcustom_face = base_img[y:y+h, x:x+w]\n\n\t\t\t\t#-------------------------------\n\t\t\t\t#facial attribute analysis\n\n\t\t\t\tif enable_face_analysis == True:\n\n\t\t\t\t\tgray_img = functions.preprocess_face(img = custom_face, target_size = (48, 48), grayscale = True, enforce_detection = False)\n\t\t\t\t\temotion_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']\n\t\t\t\t\temotion_predictions = emotion_model.predict(gray_img)[0,:]\n\t\t\t\t\tsum_of_predictions = emotion_predictions.sum()\n\n\t\t\t\t\tmood_items = []\n\t\t\t\t\tfor i in range(0, len(emotion_labels)):\n\t\t\t\t\t\tmood_item = []\n\t\t\t\t\t\temotion_label = emotion_labels[i]\n\t\t\t\t\t\temotion_prediction = 100 * emotion_predictions[i] / sum_of_predictions\n\t\t\t\t\t\tmood_item.append(emotion_label)\n\t\t\t\t\t\tmood_item.append(emotion_prediction)\n\t\t\t\t\t\tmood_items.append(mood_item)\n\n\t\t\t\t\temotion_df = pd.DataFrame(mood_items, columns = [\"emotion\", \"score\"])\n\t\t\t\t\temotion_df = emotion_df.sort_values(by = [\"score\"], ascending=False).reset_index(drop=True)\n\n\t\t\t\t\t#background of mood box\n\n\t\t\t\t\t#transparency\n\t\t\t\t\toverlay = freeze_img.copy()\n\t\t\t\t\topacity = 0.4\n\n\t\t\t\t\tif x+w+pivot_img_size < resolution_x:\n\t\t\t\t\t\t#right\n\t\t\t\t\t\tcv2.rectangle(freeze_img\n\t\t\t\t\t\t\t#, (x+w,y+20)\n\t\t\t\t\t\t\t, (x+w,y)\n\t\t\t\t\t\t\t, (x+w+pivot_img_size, y+h)\n\t\t\t\t\t\t\t, (64,64,64),cv2.FILLED)\n\n\t\t\t\t\t\tcv2.addWeighted(overlay, opacity, freeze_img, 1 - opacity, 0, freeze_img)\n\n\t\t\t\t\telif x-pivot_img_size > 0:\n\t\t\t\t\t\t#left\n\t\t\t\t\t\tcv2.rectangle(freeze_img\n\t\t\t\t\t\t\t#, (x-pivot_img_size,y+20)\n\t\t\t\t\t\t\t, (x-pivot_img_size,y)\n\t\t\t\t\t\t\t, (x, y+h)\n\t\t\t\t\t\t\t, (64,64,64),cv2.FILLED)\n\n\t\t\t\t\t\tcv2.addWeighted(overlay, opacity, freeze_img, 1 - opacity, 0, freeze_img)\n\n\t\t\t\t\tfor index, instance in emotion_df.iterrows():\n\t\t\t\t\t\temotion_label = \"%s \" % (instance['emotion'])\n\t\t\t\t\t\temotion_score = instance['score']/100\n\n\t\t\t\t\t\tbar_x = 35 #this is the size if an emotion is 100%\n\t\t\t\t\t\tbar_x = int(bar_x * emotion_score)\n\n\t\t\t\t\t\tif x+w+pivot_img_size < resolution_x:\n\n\t\t\t\t\t\t\ttext_location_y = y + 20 + (index+1) * 20\n\t\t\t\t\t\t\ttext_location_x = x+w\n\n\t\t\t\t\t\t\tif text_location_y < y + h:\n\t\t\t\t\t\t\t\tcv2.putText(freeze_img, emotion_label, (text_location_x, text_location_y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)\n\n\t\t\t\t\t\t\t\tcv2.rectangle(freeze_img\n\t\t\t\t\t\t\t\t\t, (x+w+70, y + 13 + (index+1) * 20)\n\t\t\t\t\t\t\t\t\t, (x+w+70+bar_x, y + 13 + (index+1) * 20 + 5)\n\t\t\t\t\t\t\t\t\t, (255,255,255), cv2.FILLED)\n\n\t\t\t\t\t\telif x-pivot_img_size > 0:\n\n\t\t\t\t\t\t\ttext_location_y = y + 20 + (index+1) * 20\n\t\t\t\t\t\t\ttext_location_x = x-pivot_img_size\n\n\t\t\t\t\t\t\tif text_location_y <= y+h:\n\t\t\t\t\t\t\t\tcv2.putText(freeze_img, emotion_label, (text_location_x, text_location_y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)\n\n\t\t\t\t\t\t\t\tcv2.rectangle(freeze_img\n\t\t\t\t\t\t\t\t\t, (x-pivot_img_size+70, y + 13 + (index+1) * 20)\n\t\t\t\t\t\t\t\t\t, (x-pivot_img_size+70+bar_x, y + 13 + (index+1) * 20 + 5)\n\t\t\t\t\t\t\t\t\t, (255,255,255), cv2.FILLED)\n\n\t\t\t\t\t#-------------------------------\n\n\t\t\t\t\tface_224 = functions.preprocess_face(img = custom_face, target_size = (224, 224), grayscale = False, enforce_detection = False)\n\n\t\t\t\t\tage_predictions = age_model.predict(face_224)[0,:]\n\t\t\t\t\tapparent_age = Age.findApparentAge(age_predictions)\n\n\t\t\t\t\t#-------------------------------\n\n\t\t\t\t\tgender_prediction = gender_model.predict(face_224)[0,:]\n\n\t\t\t\t\tif np.argmax(gender_prediction) == 0:\n\t\t\t\t\t\tgender = \"W\"\n\t\t\t\t\telif np.argmax(gender_prediction) == 1:\n\t\t\t\t\t\tgender = \"M\"\n\n\t\t\t\t\t#print(str(int(apparent_age)),\" years old \", dominant_emotion, \" \", gender)\n\n\t\t\t\t\tanalysis_report = str(int(apparent_age))+\" \"+gender\n\n\t\t\t\t\t#-------------------------------\n\n\t\t\t\t\tinfo_box_color = (46,200,255)\n\n\t\t\t\t\t#top\n\t\t\t\t\tif y - pivot_img_size + int(pivot_img_size/5) > 0:\n\n\t\t\t\t\t\ttriangle_coordinates = np.array( [\n\t\t\t\t\t\t\t(x+int(w/2), y)\n\t\t\t\t\t\t\t, (x+int(w/2)-int(w/10), y-int(pivot_img_size/3))\n\t\t\t\t\t\t\t, (x+int(w/2)+int(w/10), y-int(pivot_img_size/3))\n\t\t\t\t\t\t] )\n\n\t\t\t\t\t\tcv2.drawContours(freeze_img, [triangle_coordinates], 0, info_box_color, -1)\n\n\t\t\t\t\t\tcv2.rectangle(freeze_img, (x+int(w/5), y-pivot_img_size+int(pivot_img_size/5)), (x+w-int(w/5), y-int(pivot_img_size/3)), info_box_color, cv2.FILLED)\n\n\t\t\t\t\t\tcv2.putText(freeze_img, analysis_report, (x+int(w/3.5), y - int(pivot_img_size/2.1)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 111, 255), 2)\n\n\t\t\t\t\t#bottom\n\t\t\t\t\telif y + h + pivot_img_size - int(pivot_img_size/5) < resolution_y:\n\n\t\t\t\t\t\ttriangle_coordinates = np.array( [\n\t\t\t\t\t\t\t(x+int(w/2), y+h)\n\t\t\t\t\t\t\t, (x+int(w/2)-int(w/10), y+h+int(pivot_img_size/3))\n\t\t\t\t\t\t\t, (x+int(w/2)+int(w/10), y+h+int(pivot_img_size/3))\n\t\t\t\t\t\t] )\n\n\t\t\t\t\t\tcv2.drawContours(freeze_img, [triangle_coordinates], 0, info_box_color, -1)\n\n\t\t\t\t\t\tcv2.rectangle(freeze_img, (x+int(w/5), y + h + int(pivot_img_size/3)), (x+w-int(w/5), y+h+pivot_img_size-int(pivot_img_size/5)), info_box_color, cv2.FILLED)\n\n\t\t\t\t\t\tcv2.putText(freeze_img, analysis_report, (x+int(w/3.5), y + h + int(pivot_img_size/1.5)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 111, 255), 2)\n\n\t\t\t\t#-------------------------------\n\t\t\t\t#face recognition\n\n\t\t\t\tcustom_face = np.array(functions.preprocess_face(img = custom_face, target_size = (input_shape_y, input_shape_x), enforce_detection = False))\n\t\t\t\tnp.squeeze(custom_face,axis=1)\n\t\t\t\t#check preprocess_face function handled\n\t\t\t\tif custom_face.shape[1:3] == input_shape:\n\t\t\t\t\tif df.shape[0] > 0: #if there are images to verify, apply face recognition\n\t\t\t\t\t\timg1_representation = model.predict(custom_face)[0,:]\n\n\n\t\t\t\t\t\tdef findDistance(row):\n\t\t\t\t\t\t\tdistance_metric = row['distance_metric']\n\t\t\t\t\t\t\timg2_representation = row['embedding']\n\n\t\t\t\t\t\t\tdistance = 1000 #initialize very large value\n\t\t\t\t\t\t\tif distance_metric == 'cosine':\n\t\t\t\t\t\t\t\tdistance = dst.findCosineDistance(img1_representation, img2_representation)\n\t\t\t\t\t\t\telif distance_metric == 'euclidean':\n\t\t\t\t\t\t\t\tdistance = dst.findEuclideanDistance(img1_representation, img2_representation)\n\t\t\t\t\t\t\telif distance_metric == 'euclidean_l2':\n\t\t\t\t\t\t\t\tdistance = dst.findEuclideanDistance(dst.l2_normalize(img1_representation), dst.l2_normalize(img2_representation))\n\n\t\t\t\t\t\t\treturn distance\n\n\t\t\t\t\t\tdf['distance'] = df.apply(findDistance, axis = 1)\n\t\t\t\t\t\tdf = df.sort_values(by = [\"distance\"])\n\n\t\t\t\t\t\tcandidate = df.iloc[0]\n\t\t\t\t\t\temployee_name = candidate['employee']\n\t\t\t\t\t\tbest_distance = candidate['distance']\n\n\t\t\t\t\t\t#print(candidate[['employee', 'distance']].values)\n\n\t\t\t\t\t\t#if True:\n\t\t\t\t\t\tif best_distance <= threshold:\n\t\t\t\t\t\t\t#print(employee_name)\n\t\t\t\t\t\t\tdisplay_img = cv2.imread(employee_name)\n\n\t\t\t\t\t\t\tdisplay_img = cv2.resize(display_img, (pivot_img_size, pivot_img_size))\n\n\t\t\t\t\t\t\tlabel = employee_name.split(\"/\")[-1].replace(\".jpg\", \"\")\n\t\t\t\t\t\t\tlabel = re.sub('[0-9]', '', label)\n\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tif y - pivot_img_size > 0 and x + w + pivot_img_size < resolution_x:\n\t\t\t\t\t\t\t\t\t#top right\n\t\t\t\t\t\t\t\t\tfreeze_img[y - pivot_img_size:y, x+w:x+w+pivot_img_size] = display_img\n\n\t\t\t\t\t\t\t\t\toverlay = freeze_img.copy(); opacity = 0.4\n\t\t\t\t\t\t\t\t\tcv2.rectangle(freeze_img,(x+w,y),(x+w+pivot_img_size, y+20),(46,200,255),cv2.FILLED)\n\t\t\t\t\t\t\t\t\tcv2.addWeighted(overlay, opacity, freeze_img, 1 - opacity, 0, freeze_img)\n\n\t\t\t\t\t\t\t\t\tcv2.putText(freeze_img, label, (x+w, y+10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 1)\n\n\t\t\t\t\t\t\t\t\t#connect face and text\n\t\t\t\t\t\t\t\t\tcv2.line(freeze_img,(x+int(w/2), y), (x+3*int(w/4), y-int(pivot_img_size/2)),(67,67,67),1)\n\t\t\t\t\t\t\t\t\tcv2.line(freeze_img, (x+3*int(w/4), y-int(pivot_img_size/2)), (x+w, y - int(pivot_img_size/2)), (67,67,67),1)\n\n\t\t\t\t\t\t\t\telif y + h + pivot_img_size < resolution_y and x - pivot_img_size > 0:\n\t\t\t\t\t\t\t\t\t#bottom left\n\t\t\t\t\t\t\t\t\tfreeze_img[y+h:y+h+pivot_img_size, x-pivot_img_size:x] = display_img\n\n\t\t\t\t\t\t\t\t\toverlay = freeze_img.copy(); opacity = 0.4\n\t\t\t\t\t\t\t\t\tcv2.rectangle(freeze_img,(x-pivot_img_size,y+h-20),(x, y+h),(46,200,255),cv2.FILLED)\n\t\t\t\t\t\t\t\t\tcv2.addWeighted(overlay, opacity, freeze_img, 1 - opacity, 0, freeze_img)\n\n\t\t\t\t\t\t\t\t\tcv2.putText(freeze_img, label, (x - pivot_img_size, y+h-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 1)\n\n\t\t\t\t\t\t\t\t\t#connect face and text\n\t\t\t\t\t\t\t\t\tcv2.line(freeze_img,(x+int(w/2), y+h), (x+int(w/2)-int(w/4), y+h+int(pivot_img_size/2)),(67,67,67),1)\n\t\t\t\t\t\t\t\t\tcv2.line(freeze_img, (x+int(w/2)-int(w/4), y+h+int(pivot_img_size/2)), (x, y+h+int(pivot_img_size/2)), (67,67,67),1)\n\n\t\t\t\t\t\t\t\telif y - pivot_img_size > 0 and x - pivot_img_size > 0:\n\t\t\t\t\t\t\t\t\t#top left\n\t\t\t\t\t\t\t\t\tfreeze_img[y-pivot_img_size:y, x-pivot_img_size:x] = display_img\n\n\t\t\t\t\t\t\t\t\toverlay = freeze_img.copy(); opacity = 0.4\n\t\t\t\t\t\t\t\t\tcv2.rectangle(freeze_img,(x- pivot_img_size,y),(x, y+20),(46,200,255),cv2.FILLED)\n\t\t\t\t\t\t\t\t\tcv2.addWeighted(overlay, opacity, freeze_img, 1 - opacity, 0, freeze_img)\n\n\t\t\t\t\t\t\t\t\tcv2.putText(freeze_img, label, (x - pivot_img_size, y+10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 1)\n\n\t\t\t\t\t\t\t\t\t#connect face and text\n\t\t\t\t\t\t\t\t\tcv2.line(freeze_img,(x+int(w/2), y), (x+int(w/2)-int(w/4), y-int(pivot_img_size/2)),(67,67,67),1)\n\t\t\t\t\t\t\t\t\tcv2.line(freeze_img, (x+int(w/2)-int(w/4), y-int(pivot_img_size/2)), (x, y - int(pivot_img_size/2)), (67,67,67),1)\n\n\t\t\t\t\t\t\t\telif x+w+pivot_img_size < resolution_x and y + h + pivot_img_size < resolution_y:\n\t\t\t\t\t\t\t\t\t#bottom righ\n\t\t\t\t\t\t\t\t\tfreeze_img[y+h:y+h+pivot_img_size, x+w:x+w+pivot_img_size] = display_img\n\n\t\t\t\t\t\t\t\t\toverlay = freeze_img.copy(); opacity = 0.4\n\t\t\t\t\t\t\t\t\tcv2.rectangle(freeze_img,(x+w,y+h-20),(x+w+pivot_img_size, y+h),(46,200,255),cv2.FILLED)\n\t\t\t\t\t\t\t\t\tcv2.addWeighted(overlay, opacity, freeze_img, 1 - opacity, 0, freeze_img)\n\n\t\t\t\t\t\t\t\t\tcv2.putText(freeze_img, label, (x+w, y+h-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, text_color, 1)\n\n\t\t\t\t\t\t\t\t\t#connect face and text\n\t\t\t\t\t\t\t\t\tcv2.line(freeze_img,(x+int(w/2), y+h), (x+int(w/2)+int(w/4), y+h+int(pivot_img_size/2)),(67,67,67),1)\n\t\t\t\t\t\t\t\t\tcv2.line(freeze_img, (x+int(w/2)+int(w/4), y+h+int(pivot_img_size/2)), (x+w, y+h+int(pivot_img_size/2)), (67,67,67),1)\n\t\t\t\t\t\t\texcept Exception as err:\n\t\t\t\t\t\t\t\tprint(str(err))\n\n\t\t\t\ttic = time.time() #in this way, freezed image can show 5 seconds\n\n\t\t\t\t\t#-------------------------------\n\n\n\t\t\tcv2.rectangle(freeze_img, (10, 10), (90, 50), (67,67,67), -10)\n\t\t\t# cv2.putText(freeze_img, str(time_left), (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1)\n\n\t\t\tif len(faces) != people:\n\t\t\t\tpeople = len(faces)\n\t\t\tcv2.putText(freeze_img, f'number of human detected : {len(faces)}', (20,25), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1)\n\n\t\t\t\n\t\t\tcv2.imshow('img', freeze_img) \n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tcv2.imshow('img',img)\n\n\t\tif cv2.waitKey(1) & 0xFF == ord('q'): #press q to quit\n\t\t\tbreak\n\n\t#kill open cv things\n\tcap.release()\n\tcv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n\tanalysis(enable_face_analysis = True)"
] | [
[
"numpy.squeeze",
"numpy.argmax",
"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": []
}
] |
laekov/akg | [
"5316b8cb2340bbf71bdc724dc9d81513a67b3104",
"5316b8cb2340bbf71bdc724dc9d81513a67b3104",
"5316b8cb2340bbf71bdc724dc9d81513a67b3104",
"5316b8cb2340bbf71bdc724dc9d81513a67b3104",
"5316b8cb2340bbf71bdc724dc9d81513a67b3104",
"5316b8cb2340bbf71bdc724dc9d81513a67b3104",
"5316b8cb2340bbf71bdc724dc9d81513a67b3104",
"5316b8cb2340bbf71bdc724dc9d81513a67b3104",
"5316b8cb2340bbf71bdc724dc9d81513a67b3104",
"5316b8cb2340bbf71bdc724dc9d81513a67b3104",
"5316b8cb2340bbf71bdc724dc9d81513a67b3104"
] | [
"tests/common/test_run/avgpool_run.py",
"tests/common/test_run/topk_run.py",
"tests/common/test_run/abs_sum_run.py",
"tests/common/test_run/equal_run.py",
"tests/common/test_run/elemwise_sum_run.py",
"tests/common/test_run/fused_mean_mul_run.py",
"tests/common/test_run/cross_run.py",
"tests/common/test_run/pad_run.py",
"tests/common/test_run/distr_bernoulli_logprob_run.py",
"tests/common/test_run/sparse_softmax_cross_entropy_with_logits_run.py",
"tests/common/test_run/truncatemod_run.py"
] | [
"# Copyright 2019 Huawei Technologies Co., Ltd\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\nfrom tensorio import compare_tensor\r\nimport numpy as np\r\nfrom akg.utils import kernel_exec as utils\r\nfrom akg.ops.nn import avgpool\r\nfrom akg.utils.dsl_create import cal_pad_shapes_by_strategy\r\nfrom gen_random import random_gaussian\r\n\r\ndef benchmark(input, kernel, stride, pad):\r\n sh, sw = stride\r\n N, C1, H, W, C0 = input.shape\r\n KH, KW = kernel\r\n\r\n [ph_h, ph_t, pw_h, pw_t], [out_size_h, out_size_w] = cal_pad_shapes_by_strategy(input.shape, kernel, stride, pad)\r\n out_shape = (N, C1, out_size_h, out_size_w, C0)\r\n\r\n out = np.zeros(out_shape)\r\n\r\n inputpad = np.zeros((N, C1, H + ph_h + ph_t, W + pw_h + pw_t, C0))\r\n inputpad[:, :, ph_h:ph_h + H, pw_h:pw_h + W, :] = input\r\n\r\n for i in range(out_size_h):\r\n for j in range(out_size_w):\r\n out[:, :, i, j, :] = np.mean(inputpad[:, :, i * sh:i * sh + KH, j * sw:j * sw + KW, :], axis=(2, 3))\r\n return out\r\n\r\n\r\ndef avgpool_run(shape, kernel, stride, strategy, dtype, attrs):\r\n if 'tuning' in attrs.keys():\r\n t = attrs.get(\"tuning\", False)\r\n kernel_name = attrs.get(\"kernel_name\", False)\r\n mod = utils.op_build_test(avgpool.avgpool, [shape], [dtype], op_attrs=[kernel, stride, strategy],\r\n kernel_name=kernel_name, attrs=attrs, tuning=t)\r\n if t:\r\n expect, input, output = gen_data(dtype, kernel, shape, strategy, stride)\r\n return mod, expect, (input, output)\r\n else:\r\n return mod\r\n else:\r\n mod = utils.op_build_test(avgpool.avgpool, [shape], [dtype], op_attrs=[kernel, stride, strategy],\r\n kernel_name='avgpool', attrs=attrs)\r\n expect, input, output = gen_data(dtype, kernel, shape, strategy, stride)\r\n output = utils.mod_launch(mod, [input, output], expect=expect)\r\n return input, output, expect, compare_tensor(output, expect, rtol=5e-03, atol=5e-03, equal_nan=True)\r\n\r\n\r\ndef gen_data(dtype, kernel, shape, strategy, stride):\r\n support_list = {\"float16\": np.float16, \"float32\": np.float32}\r\n input = random_gaussian(shape, miu=1, sigma=0.1).astype(support_list[dtype])\r\n expect = benchmark(input, kernel, stride, strategy)\r\n out_shape = expect.shape\r\n output = np.full(out_shape, 0, dtype)\r\n return expect, input, output\r\n",
"# Copyright 2019 Huawei Technologies Co., Ltd\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\nimport numpy as np\r\nfrom akg.utils import kernel_exec as utils\r\nfrom test_op import topk\r\nfrom tensorio import compare_tensor\r\n\r\n\r\ndef less_than(a, b):\r\n return a[0] < b[0] or (a[0] == b[0] and a[1] > b[1])\r\n\r\n\r\ndef cal_topk(A, k):\r\n if k > A.shape[-1]:\r\n raise RuntimeError(\"k should not be greater than shape[-1]\")\r\n out_shape = A.shape[:-1] + (k,)\r\n\r\n last_dim = A.shape[-1]\r\n loop_cnt = 1\r\n for x in A.shape[:-1]:\r\n loop_cnt *= x\r\n\r\n in_len = loop_cnt * last_dim\r\n out_len = loop_cnt * k\r\n\r\n out_value = np.zeros((out_len,), dtype=A.dtype)\r\n out_index = np.zeros((out_len,), dtype=\"int32\")\r\n\r\n A = A.flatten()\r\n\r\n arr_idx = np.zeros((last_dim,), dtype=\"int32\")\r\n arr_val = np.zeros((last_dim,), dtype=A.dtype)\r\n for i in range(loop_cnt):\r\n base_in = i * last_dim\r\n base_out = i * k\r\n for j in range(last_dim):\r\n arr_idx[j] = j\r\n arr_val[j] = A[base_in + j]\r\n # get topk values by selection sort\r\n for x in range(k):\r\n p = x\r\n for y in range(x + 1, last_dim):\r\n if less_than((arr_val[p], arr_idx[p]), (arr_val[y], arr_idx[y])):\r\n p = y\r\n out_value[base_out + x] = arr_val[p]\r\n out_index[base_out + x] = arr_idx[p]\r\n if x != p:\r\n arr_val[p] = arr_val[x]\r\n arr_idx[p] = arr_idx[x]\r\n\r\n return out_value.reshape(out_shape), out_index.reshape(out_shape)\r\n\r\n\r\ndef topk_run(shape, k, dtype, attrs):\r\n if 'tuning' in attrs.keys():\r\n t = attrs.get(\"tuning\", False)\r\n kernel_name = attrs.get(\"kernel_name\", False)\r\n mod = utils.op_build_test(topk.topk, [shape], [dtype], [k],\r\n kernel_name=kernel_name, attrs=attrs, tuning=t)\r\n if t:\r\n expect_index, expect_value, input, output_value = gen_data(dtype, k, shape)\r\n return mod, (expect_index, expect_value), (input, output_value)\r\n else:\r\n return mod\r\n else:\r\n mod = topk.topk(shape, k, dtype, \"topk\", attrs)\r\n expect_index, expect_value, input, output_value = gen_data(dtype, k, shape)\r\n output_index = np.full(expect_index.shape, np.nan, dtype)\r\n\r\n #output_value, output_index = utils.mod_launch(mod, (input, output_value, output_index))\r\n output_value = utils.mod_launch(mod, (input, output_value), expect=(expect_value, expect_index))\r\n result = compare_tensor(output_value, expect_value, rtol=5e-03, equal_nan=True) and \\\r\n compare_tensor(output_index, expect_index, rtol=5e-03, equal_nan=True)\r\n return input, (output_value, output_index), (expect_value, expect_index), result\r\n\r\n\r\ndef gen_data(dtype, k, shape):\r\n input = np.random.randint(100, size=shape).astype(dtype)\r\n out_shape = shape[:-1] + (k,)\r\n expect_value, expect_index = cal_topk(input, k)\r\n output_value = np.full(expect_value.shape, np.nan, dtype)\r\n return expect_index, expect_value, input, output_value\r\n",
"# Copyright 2019 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nfrom tensorio import compare_tensor\nfrom akg.utils import kernel_exec as utils\nfrom test_op import abs_sum\nfrom akg.utils.dsl_create import get_reduce_out_shape\nfrom gen_random import random_gaussian\n\ndef abs_sum_run(shape, reduce_axis, keepdims, dtype, attrs):\n op_attrs = [reduce_axis, keepdims]\n\n if 'tuning' in attrs.keys():\n t = attrs.get(\"tuning\", False)\n kernel_name = attrs.get(\"kernel_name\", False)\n mod = utils.op_build_test(abs_sum.abs_sum, [shape], [dtype], op_attrs, kernel_name=kernel_name, attrs=attrs, tuning=t)\n if t:\n expect, input1, output = gen_data(dtype, keepdims, reduce_axis, shape)\n return mod, expect, (input1, output)\n else:\n return mod\n else:\n expect, input1, output = gen_data(dtype, keepdims, reduce_axis, shape)\n mod = utils.op_build_test(abs_sum.abs_sum, [shape], [dtype], op_attrs, kernel_name=\"abs_sum\", attrs=attrs)\n output = utils.mod_launch(mod, (input1, output), expect=expect)\n return input1, output, expect, compare_tensor(output, expect, rtol=5e-03, atol=5e-3, equal_nan=True)\n\n\ndef gen_data(dtype, keepdims, reduce_axis, shape):\n input1 = random_gaussian(shape, miu=1, sigma=0.1)\n input1 = input1.astype(dtype)\n input1_abs = np.abs(input1)\n expect = np.sum(input1_abs, axis=reduce_axis, keepdims=keepdims)\n out_shape = get_reduce_out_shape(shape, axis=reduce_axis, keepdims=keepdims)\n output = np.full(out_shape, np.nan, dtype)\n return expect, input1, output\n",
"# Copyright 2019 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nfrom akg.utils import kernel_exec as utils\nfrom akg.ops.math import equal\nfrom gen_random import random_gaussian\n\n\ndef equal_run(shapes, dtype, kernel_name, attrs, cce_path=\"./\"):\n if 'tuning' in attrs.keys():\n t = attrs.get(\"tuning\", False)\n kernel_name = attrs.get(\"kernel_name\", False)\n mod = utils.op_build_test(equal.equal, shapes, [dtype, dtype], kernel_name=kernel_name, attrs=attrs, tuning=t)\n if t:\n benchMark1, inputs1, output1 = gen_data(dtype, shapes)\n return mod, benchMark1, inputs1 + [output1]\n else:\n return mod\n else:\n mod = utils.op_build_test(equal.equal, shapes, [dtype, dtype], kernel_name=kernel_name, attrs=attrs)\n benchMark1, inputs1, output1 = gen_data(dtype, shapes)\n output1 = utils.mod_launch(mod, inputs1 + [output1], expect=benchMark1)\n\n # Also test the case where the inputs are equal\n if shapes[0] == shapes[1]:\n inputs2 = []\n inputs2.append(inputs1[0])\n inputs2.append(inputs1[0])\n benchMark2 = np.equal(inputs2[0], inputs2[1])\n output2 = np.full(benchMark2.shape, 0, bool)\n output2 = utils.mod_launch(mod, inputs2 + [output2], expect=benchMark1)\n testPass = (np.array_equal(output1, benchMark1) and np.array_equal(output2, benchMark2))\n return (inputs1, inputs2), (output1, output2), (benchMark1, benchMark2), testPass\n else:\n return inputs1, output1, benchMark1, np.array_equal(output1, benchMark1)\n\n\ndef gen_data(dtype, shapes):\n support_list = {\"float16\": np.float16, \"float32\": np.float32, \"int32\": np.int32, \"int8\": np.int8, \"uint8\": np.uint8}\n inputs1 = []\n for i in range(len(shapes)):\n shape = shapes[i]\n input = random_gaussian(shape, miu=1, sigma=100).astype(support_list[dtype.lower()])\n inputs1.append(input)\n \"\"\"\n inputs.append(np.ones(shapes[0], dtype=np.float16))\n for i in range(16):\n inputs[0][i]=0\n inputs.append(np.zeros(shapes[0], dtype=np.float16))\n \"\"\"\n if len(inputs1) != 2:\n raise RuntimeError(\"inputs num should be 2\")\n benchMark1 = np.equal(inputs1[0], inputs1[1])\n output1 = np.full(benchMark1.shape, 0, bool)\n return benchMark1, inputs1, output1\n",
"# Copyright 2019 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nfrom akg.utils import kernel_exec as utils\nfrom test_op.elemwise_sum import elemwise_sum\nfrom test_op.elemwise_sum import elemwise_sum_manual_schedule\nfrom tensorio import compare_tensor\nfrom gen_random import random_gaussian\n\ndef elemwise_sum_run(shape, dtype, attrs, polyhedral=True):\n if 'tuning' in attrs.keys():\n t = attrs.get(\"tuning\", False)\n kernel_name = attrs.get(\"kernel_name\", False)\n mod = utils.op_build_test(elemwise_sum, [shape, shape, shape], [dtype, dtype, dtype],\n kernel_name='elemwise_sum', attrs=attrs, tuning=t)\n if t:\n expect, head_np, input1, input2, output = gen_data(dtype, shape)\n return mod, expect, (head_np, input1, input2, output)\n else:\n return mod\n else:\n expect, input1, input2, output = gen_data(dtype, shape)\n if polyhedral:\n mod = utils.op_build_test(elemwise_sum, [shape, shape], [dtype, dtype],\n kernel_name='elemwise_sum', polyhedral=polyhedral, attrs=attrs)\n output = utils.mod_launch(mod, (input1, input2, output), expect=expect)\n else:\n mod = elemwise_sum_manual_schedule(shape, polyhedral=polyhedral, attrs=attrs)\n output = utils.mod_launch(mod, [input1, input2, output], expect=expect)\n \n return (input1, input2), output, expect, compare_tensor(output, expect, rtol=5e-03, atol=5e-03, equal_nan=True)\n\n\ndef gen_data(dtype, shape):\n input1 = random_gaussian(shape, miu=1, sigma=0.1).astype(dtype)\n input2 = random_gaussian(shape, miu=1, sigma=0.1).astype(dtype)\n expect = input1+input2\n output = np.full(shape, np.nan, dtype)\n return expect, input1, input2, output\n",
"# Copyright 2019 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nfrom tensorio import compare_tensor\nfrom akg.utils import kernel_exec as utils\nfrom akg.ops.math import mul, mean\nfrom gen_random import random_gaussian\n\ndef mean_mul(first_input, second_input, axis=None, keepdims=False):\n temp, _ = mean.mean(first_input, axis, keepdims)\n output = mul.mul(temp, second_input)\n return output\n\n\ndef fused_mean_mul_execute(shape1, shape2, dtype, axis, keepdims, kernel_name, attrs):\n if 'tuning' in attrs.keys():\n t = attrs.get(\"tuning\", False)\n kernel_name = attrs.get(\"kernel_name\", False)\n mod = fused_mean_mul_compile(shape1, shape2, dtype, axis, keepdims, kernel_name, attrs, tuning=t)\n if t:\n expect, input1, input2, output = gen_data(shape1, shape2, dtype, axis, keepdims)\n return mod, expect, (input1, input2, output)\n else:\n return mod\n else:\n expect, input1, input2, output = gen_data(shape1, shape2, dtype, axis, keepdims)\n mod = fused_mean_mul_compile(shape1, shape2, dtype, axis, keepdims, kernel_name, attrs)\n output = utils.mod_launch(mod, (input1, input2, output), expect=expect)\n return (input1, input2), output, expect, compare_tensor(output, expect, rtol=5e-03, equal_nan=True)\n\n\ndef fused_mean_mul_compile(shape1, shape2, dtype, axis, keepdims, kernel_name, attrs, tuning=False):\n op_attrs = [axis, keepdims]\n return utils.op_build_test(mean_mul, [shape1, shape2], [dtype, dtype], op_attrs, kernel_name=kernel_name, attrs=attrs, tuning=tuning)\n\n\ndef gen_data(shape1, shape2, dtype, axis=None, keepdims=False):\n support_list = {\"float16\": np.float16, \"float32\": np.float32}\n input1 = random_gaussian(shape1, miu=1, sigma=0.1).astype(support_list[dtype])\n input2 = random_gaussian(shape2, miu=1, sigma=0.1).astype(support_list[dtype])\n temp = np.mean(input1, axis=axis, keepdims=keepdims)\n expect = np.multiply(temp, input2)\n out_shape = expect.shape\n output = np.full(out_shape, np.nan, dtype)\n return expect, input1, input2, output\n",
"# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"run test function for cross\"\"\"\n\nimport numpy as np\n\nfrom akg.utils import kernel_exec as utils\nfrom tensorio import compare_tensor\nfrom base import get_rtol_atol\nfrom test_op import cross\nfrom gen_random import random_gaussian\n\n\ndef cross_run(shape1, dtype1, shape2, dtype2, attrs):\n \"\"\"run function for cross\"\"\"\n mod = utils.op_build_test(cross.cross,\n [shape1, shape2], [dtype1, dtype2],\n kernel_name=\"cross\",\n attrs=attrs)\n expect, inputs, out_buf = gen_data(dtype1, dtype2, shape1, shape2)\n output = utils.mod_launch(mod, (*inputs, out_buf), expect=expect)\n rtol, atol = get_rtol_atol(\"cross\", dtype1)\n cmp_res = compare_tensor(output, expect, rtol=rtol, atol=atol)\n return inputs, output, expect, cmp_res\n\ndef gen_data(dtype1, dtype2, shape1, shape2):\n \"\"\"generate valid test data for cross\"\"\"\n input1 = random_gaussian(shape1).astype(dtype1)\n input2 = random_gaussian(shape2).astype(dtype2)\n\n if dtype1 in (\"int8\", \"uint8\", \"int32\"):\n # for overflow case, numpy will truncate the result, but davinci will\n # make it maximum or minimuam value.\n expect = np.cross(input1.astype(\"float32\"), input2.astype(\"float32\"),\n axisa=0, axisb=0, axisc=0)\n expect = np.maximum(expect, np.ones_like(expect) * np.iinfo(dtype1).min)\n expect = np.minimum(expect, np.ones_like(expect) * np.iinfo(dtype1).max)\n expect = expect.astype(dtype1)\n else:\n expect = np.cross(input1, input2, axisa=0, axisb=0, axisc=0)\n\n out_buf = np.full(expect.shape, np.nan, dtype1)\n return expect, (input1, input2), out_buf\n",
"# Copyright 2019 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nsqrt run define\n\"\"\"\n\nimport numpy as np\nfrom akg.utils import kernel_exec as utils\nfrom test_op import pad\nfrom tensorio import compare_tensor\nfrom gen_random import random_gaussian\n\ndef pad_run(shape, paddings, dtype, padtype, kernel_name, attrs):\n if 'tuning' in attrs.keys():\n t = attrs.get(\"tuning\", False)\n kernel_name = attrs.get(\"kernel_name\", False)\n if len(paddings) == 0:\n ops_attrs = []\n mod = utils.op_build_test(pad.auto_pad, [shape], [dtype], ops_attrs, kernel_name=kernel_name, attrs=attrs, tuning=t)\n else:\n ops_attrs = [paddings, padtype]\n mod = utils.op_build_test(pad.pad, [shape], [dtype], ops_attrs, kernel_name=kernel_name, attrs=attrs, tuning=t)\n if t:\n expect, input, output = gen_data(dtype, paddings, padtype, shape)\n return mod, expect, (input, output)\n else:\n return mod\n else:\n if len(paddings) == 0:\n ops_attrs = []\n mod = utils.op_build_test(pad.auto_pad, [shape], [dtype], ops_attrs, kernel_name=kernel_name, attrs=attrs)\n else:\n ops_attrs = [paddings, padtype]\n mod = utils.op_build_test(pad.pad, [shape], [dtype], ops_attrs, kernel_name=kernel_name, attrs=attrs)\n expect, input, output = gen_data(dtype, paddings, padtype, shape)\n output = utils.mod_launch(mod, (input, output), expect=expect)\n\n return input, output, expect, compare_tensor(output, expect, rtol=5e-03, equal_nan=True)\n\n\ndef gen_data(dtype, paddings, padtype, shape):\n # Generate data for testing the op\n input = random_gaussian(shape, miu=1, sigma=0.1).astype(dtype)\n if len(paddings) == 0:\n # auto pad to 16x\n pad_shape = [(x + 15) // 16 * 16 for x in shape]\n new_paddings = [[0, pad_shape[i] - shape[i]] for i in range(len(shape))]\n expect = np.pad(input, new_paddings, padtype)\n else:\n expect = np.pad(input, paddings, padtype)\n out_shape = expect.shape\n output = np.full(out_shape, np.nan, dtype)\n return expect, input, output\n",
"# Copyright 2019 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nfrom tensorio import compare_tensor\nfrom akg.utils import kernel_exec as utils\nfrom test_op.prob_program.distribution import bernoulli as akg_bernoulli\nfrom scipy.stats import bernoulli, uniform\nfrom numpy.random import seed\nimport sys\n#np.set_printoptions(threshold=sys.maxsize)\n\ndef log_prob_op(x, probs):\n return akg_bernoulli.bernoulli(probs).log_prob(x)\n\ndef log_prob_run(shape, dtype, kernelname=\"\", attrs = None):\n expect, x, probs, output = gen_data(dtype, shape)\n\n mod = utils.op_build_test(log_prob_op, [x.shape, probs.shape],\n [dtype, dtype], kernel_name=kernelname,\n op_attrs=[], attrs=None, log_cce=True, dump_code=True, polyhedral=True)\n output = utils.mod_launch(mod, [x, probs, output], expect=expect)\n return (x, probs), output, expect, compare_tensor(output, expect, rtol=1e-03, atol=1e-03, equal_nan=True)\n\ndef gen_data(dtype, shape):\n support_list = {\"float16\": np.float16, \"float32\": np.float32}\n seed(0)\n m, k = shape\n x = bernoulli.rvs(0.5, size=(m, k)).astype(support_list[dtype])\n eps = 1e-3\n # generate probabilities in the range [eps, 1 - eps], to avoid mismatch between np.inf and computed\n # inf = -65500.0, due to taking log\n probs = uniform(eps, 1.0 - 2.0 * eps).rvs(size=(m, k)).astype(support_list[dtype])\n expect = bernoulli.logpmf(x, probs)\n output = np.full((m, k), 0.0, dtype)\n\n return expect, x, probs, output\n",
"# Copyright 2019 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nfrom tensorio import compare_tensor\nfrom akg.utils import kernel_exec as utils\nfrom akg.ops.nn import sparse_softmax_cross_entropy_with_logits\nfrom gen_random import random_gaussian\nfrom base import get_rtol_atol\n\n\ndef np_sparse_softmax_cross_entropy_with_logits(shape1, dtype1, shape2, dtype2, reduction=\"mean\", scale=1.0):\n logits = random_gaussian(shape2, miu=0, sigma=1).astype(dtype2)\n num_class = logits.shape[1]\n labels = np.random.randint(low=0, high=num_class, size=shape1).astype(dtype1)\n batch_dim = 0\n class_dim = 1\n batch_size = logits.shape[batch_dim]\n e = np.exp(logits - np.reshape(\n np.amax(\n logits, axis=class_dim), [batch_size, 1]))\n probs = e / np.reshape(np.sum(e, axis=class_dim), [batch_size, 1])\n labels_one_hot = np.zeros_like(probs).astype(probs.dtype)\n labels_one_hot[np.arange(batch_size), labels] = 1.0\n bp = (probs - labels_one_hot)\n cost = -np.sum(labels_one_hot * np.log(probs + 1.0e-20), axis=1)\n if not reduction or reduction.lower() == \"none\":\n loss = cost\n elif reduction.lower() == \"mean\":\n loss = np.mean(cost)\n cost_num = 1\n for i in range(len(cost.shape)):\n cost_num *= cost.shape[i]\n bp = np.divide(bp, cost_num)\n elif reduction.lower() == \"sum\":\n loss = np.sum(cost)\n else:\n raise ValueError(\"reduction method for {} is not supported\")\n # loss_res = np.reshape(loss, labels.shape)\n bp = np.multiply(bp, scale)\n return labels, logits, loss, bp\n\n\ndef sparse_softmax_cross_entropy_with_logits_run(shape1, dtype1, shape2, dtype2, reduction, kernel_name, attrs):\n op_attrs = [reduction]\n\n if 'tuning' in attrs.keys():\n t = attrs.get(\"tuning\", False)\n kernel_name = attrs.get(\"kernel_name\", False)\n mod = utils.op_build_test(sparse_softmax_cross_entropy_with_logits.sparse_softmax_cross_entropy_with_logits,\n [shape1, shape2], [dtype1, dtype2], op_attrs=op_attrs,\n kernel_name=kernel_name, attrs=attrs, tuning=t)\n if t:\n expect, labels, logits, output = gen_data(dtype1, dtype2, reduction, shape1, shape2)\n return mod, expect, (labels, logits, output)\n else:\n return mod\n else:\n mod = utils.op_build_test(sparse_softmax_cross_entropy_with_logits.sparse_softmax_cross_entropy_with_logits,\n [shape1, shape2], [dtype1, dtype2], op_attrs=op_attrs,\n kernel_name=kernel_name, attrs=attrs)\n expect, labels, logits, output = gen_data(dtype1, dtype2, reduction, shape1, shape2)\n output = utils.mod_launch(mod, (labels, logits, output), expect=expect)\n rtol, atol = get_rtol_atol(\"sparse_softmax_cross_entropy_with_logits\", dtype2)\n compare_res = compare_tensor(output, expect, rtol=rtol, atol=atol)\n return (labels, logits), output, expect, compare_res\n\n\ndef gen_data(dtype1, dtype2, reduction, shape1, shape2):\n labels, logits, loss_res, bp_res = np_sparse_softmax_cross_entropy_with_logits(shape1, dtype1, shape2, dtype2,\n reduction)\n expect = loss_res\n output_shape = expect.shape\n if reduction and reduction.lower() != \"none\":\n output_shape = (1,)\n expect = [expect]\n output = np.full(output_shape, np.nan, dtype2)\n return expect, labels, logits, output\n",
"# Copyright 2019 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom akg.utils import kernel_exec as utils\nfrom tensorio import compare_tensor\nimport numpy as np\nfrom gen_random import random_gaussian\n\nfrom test_op import truncatemod\nfrom base import get_rtol_atol\n\n\ndef truncatemod_run(shape1, shape2, dtype, attrs):\n if 'tuning' in attrs.keys():\n t = attrs.get(\"tuning\", False)\n kernel_name = attrs.get(\"kernel_name\", False)\n mod = utils.op_build_test(truncatemod.truncatemod, [shape1, shape2], [dtype, dtype], kernel_name=kernel_name,\n attrs=attrs, dump_code=True, tuning=t)\n if t:\n expect, input1, input2, output = gen_data(dtype, shape1, shape2)\n return mod, expect, (input1, input2, output)\n else:\n return mod\n else:\n expect, input1, input2, output = gen_data(dtype, shape1, shape2)\n mod = utils.op_build_test(truncatemod.truncatemod, [shape1, shape2], [dtype, dtype], kernel_name=\"truncatemod\",\n attrs=attrs, dump_code=True)\n output = utils.mod_launch(mod, (input1, input2, output), expect=expect)\n rtol, atol = get_rtol_atol(\"truncatemod\", dtype)\n res = compare_tensor(output, expect, rtol=rtol, atol=atol, equal_nan=True)\n return (input1, input2), output, expect, res\n\n\ndef truncatemod_compute(x, y):\n dtype = x.dtype\n if dtype != \"float32\":\n x = x.astype(\"float32\")\n y = y.astype(\"float32\")\n expect = (x - y*np.trunc(x/y))\n\n if expect.dtype != dtype:\n expect = expect.astype(dtype)\n\n return expect\n\n\ndef gen_data(dtype, shape1, shape2):\n input1 = random_gaussian(shape1).astype(dtype)\n input2 = random_gaussian(shape2).astype(dtype)\n # mod 0 is undefined\n input2 = np.select(input2 == 0, np.ones_like(input2), input2)\n if utils.product_is_mini():\n # If the value of input2 is too small, input1/input2 will be some overflow\n lower_bound = 1e-3\n input2 = np.select([input2 >= 0, input2 < 0], [np.maximum(input2, lower_bound),\n np.minimum(input2, -lower_bound)])\n expect = truncatemod_compute(input1, input2)\n output = np.full(expect.shape, np.nan, dtype)\n return expect, input1, input2, output\n"
] | [
[
"numpy.zeros",
"numpy.mean",
"numpy.full"
],
[
"numpy.random.randint",
"numpy.zeros",
"numpy.full"
],
[
"numpy.sum",
"numpy.abs",
"numpy.full"
],
[
"numpy.equal",
"numpy.array_equal",
"numpy.full"
],
[
"numpy.full"
],
[
"numpy.mean",
"numpy.multiply",
"numpy.full"
],
[
"numpy.cross",
"numpy.ones_like",
"numpy.iinfo",
"numpy.full"
],
[
"numpy.pad",
"numpy.full"
],
[
"scipy.stats.bernoulli.logpmf",
"numpy.random.seed",
"numpy.full",
"scipy.stats.uniform",
"scipy.stats.bernoulli.rvs"
],
[
"numpy.amax",
"numpy.log",
"numpy.multiply",
"numpy.arange",
"numpy.full",
"numpy.zeros_like",
"numpy.mean",
"numpy.sum",
"numpy.divide",
"numpy.random.randint"
],
[
"numpy.trunc",
"numpy.ones_like",
"numpy.maximum",
"numpy.minimum",
"numpy.full"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
billbrod/spatial-frequency-preferences | [
"4a83fe209bbbf8130f297bcc6e17cb79b36006c2",
"4a83fe209bbbf8130f297bcc6e17cb79b36006c2"
] | [
"sfp/plotting.py",
"sfp/tuning_curves.py"
] | [
"#!/usr/bin/python\n\"\"\"high-level functions to make relevant plots\n\"\"\"\nimport matplotlib as mpl\n# we do this because sometimes we run this without an X-server, and this backend doesn't need\n# one. We set warn=False because the notebook uses a different backend and will spout out a big\n# warning to that effect; that's unnecessarily alarming, so we hide it.\nmpl.use('svg', warn=False)\nimport argparse\nimport itertools\nfrom . import utils\nimport warnings\nimport os\nfrom . import tuning_curves\nfrom . import stimuli as sfp_stimuli\nfrom . import model as sfp_model\nfrom . import first_level_analysis\nfrom . import analyze_model\nimport numpy as np\nimport seaborn as sns\nimport neuropythy as ny\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport scipy as sp\nfrom sklearn import linear_model\n\nLOGPOLAR_SUPERCLASS_ORDER = ['radial', 'forward spiral', 'angular', 'reverse spiral', 'mixtures']\nCONSTANT_SUPERCLASS_ORDER = ['vertical', 'forward diagonal', 'horizontal', 'reverse diagonal',\n 'off-diagonal']\n# radial and angular are ambiguous labels -- do they refer to the direction of\n# the oscillation or the stripes? annulus and pinwheel are less ambiguous in\n# this regard, so we use them in the paper.\nSUPERCLASS_PLOT_LABELS = {'radial': 'annulus', 'angular': 'pinwheel'}\nORIG_PARAM_ORDER = (['sigma', 'sf_ecc_slope', 'sf_ecc_intercept'] +\n ['%s_%s_%s' % (i, j, k) for j, i, k in\n itertools.product(['mode', 'amplitude'], ['abs', 'rel'],\n ['cardinals', 'obliques'])])\nPLOT_PARAM_ORDER = [r'$\\sigma$', r'$a$', r'$b$', r'$p_1$', r'$p_2$', r'$p_3$', r'$p_4$', r'$A_1$',\n r'$A_2$', r'$A_3$', r'$A_4$']\nMODEL_ORDER = ['constant_donut_period-iso_amps-iso', 'scaling_donut_period-iso_amps-iso',\n 'full_donut_period-iso_amps-iso', 'full_donut_period-absolute_amps-iso',\n 'full_donut_period-relative_amps-iso', 'full_donut_period-full_amps-iso',\n 'full_donut_period-iso_amps-absolute', 'full_donut_period-iso_amps-relative',\n 'full_donut_period-iso_amps-full', 'full_donut_period-absolute_amps-absolute',\n 'full_donut_period-relative_amps-relative', 'full_donut_period-full_amps-absolute',\n 'full_donut_period-full_amps-relative', 'full_donut_period-full_amps-full']\n# these are the 'prettier names' for plotting\nMODEL_PLOT_ORDER_FULL = (['constant iso', 'scaling iso', 'full iso'] +\n [i.replace('_donut', '').replace('_', ' ') for i in MODEL_ORDER[3:]])\n# using the numbers instead of names, since names aren't that helpful\nMODEL_PLOT_ORDER = list(range(1, len(MODEL_ORDER)+1))\n# \"doubles-up\" the model types, so that numbers are unique for parameters\n# excluding A3/A4 (so if two models have the same number, they're identical\n# except for those two parameters)\nMODEL_PLOT_ORDER_DOUBLEUP = MODEL_PLOT_ORDER[:7] + [3, 7, 10, 5, 12, 6, 12]\n# the subjects that end up in our final analysis\nSUBJECT_ORDER = ['sub-wlsubj001', 'sub-wlsubj006', 'sub-wlsubj007', 'sub-wlsubj045',\n 'sub-wlsubj046', 'sub-wlsubj062', 'sub-wlsubj064', 'sub-wlsubj081',\n 'sub-wlsubj095', 'sub-wlsubj114', 'sub-wlsubj115', 'sub-wlsubj121']\n# use numbers since names aren't helpful for plots\nSUBJECT_PLOT_ORDER = [f'sub-{i:02d}' for i in range(1, len(SUBJECT_ORDER)+1)]\n\n\ndef get_order(col, reference_frame=None, col_unique=None):\n \"\"\"get order for column\n \"\"\"\n if col == 'stimulus_type':\n return stimulus_type_order(reference_frame)\n elif col == 'fit_model_type':\n if any([i in col_unique for i in MODEL_PLOT_ORDER]):\n return [i for i in MODEL_PLOT_ORDER if i in col_unique]\n elif any([i in col_unique for i in MODEL_PLOT_ORDER_FULL]):\n return [i for i in MODEL_PLOT_ORDER_FULL if i in col_unique]\n else:\n return [i for i in MODEL_ORDER if i in col_unique]\n elif col == 'model_parameter':\n if col_unique is not None and 'sigma' in col_unique:\n return ORIG_PARAM_ORDER\n else:\n return PLOT_PARAM_ORDER\n elif col == 'subject':\n if col_unique is None:\n return SUBJECT_PLOT_ORDER\n elif any([sub in col_unique for sub in SUBJECT_PLOT_ORDER]):\n return [sub for sub in SUBJECT_PLOT_ORDER if sub in col_unique]\n elif any([sub in col_unique for sub in SUBJECT_ORDER]):\n return [sub for sub in SUBJECT_ORDER if sub in col_unique]\n else:\n return sorted(col_unique)\n\n\ndef get_palette(col, reference_frame=None, col_unique=None, as_dict=False,\n doubleup=False):\n \"\"\"get palette for column\n\n Parameters\n ----------\n col : {'stimulus_type', 'subject', 'fit_model_type', 'model_parameter'}\n The column to return the palette for\n reference_frame : {'absolute', 'relative', None}, optional\n The reference frame (ignored if col!='stimulus_type')\n col_unique : list or None, optional\n The list of unique values in col, in order to determine how many\n elements in the palette. If None, we use seaborn's default\n as_dict : bool, optional\n Whether to return the palette as a dictionary or not. if True, then we\n also find the order for this column (using get_order), and return a\n dictionary matching between the elements of this col and the colors in\n the palette (this can still be passed as the palette argument to most\n seaborn plots).\n doubleup: bool, optional\n Whether to return the doubleup palette for fit_model_type (8 unique\n colors and then 6 versions with lower alpha). Ignored if\n col!='fit_model_type'\n\n \"\"\"\n if col == 'stimulus_type':\n pal = stimulus_type_palette(reference_frame)\n pal = dict((k, v) for k, v in pal.items() if k in col_unique)\n if not as_dict:\n raise Exception(\"palette is always a dictionary if col is stimulus_type!\")\n elif col == 'subject':\n # it's hard to find a qualitative color palette with 12 colors that all\n # look fairly distinct. ColorBrewer Set3 has 12 values, but some of\n # them are really light and so hard to see. here I'm using the colors\n # from https://tsitsul.in/blog/coloropt/, but reordered slightly\n pal = [(235, 172, 35), (0, 187, 173), (184, 0, 88), (0, 140, 249),\n (0, 110, 0), (209, 99, 230), (178, 69, 2), (135, 133, 0),\n (89, 84, 214), (255, 146, 135), (0, 198, 248), (0, 167, 108),\n (189, 189, 189)]\n # expects RGB triplets to lie between 0 and 1, not 0 and 255\n pal = sns.color_palette(np.array(pal) / 255, len(col_unique))\n elif col == 'fit_model_type':\n if not doubleup:\n pal = sns.color_palette('deep', len(col_unique))\n else:\n if len(col_unique) != len(MODEL_PLOT_ORDER):\n raise Exception(\"Can only return doubleup model type palette \"\n \"if plotting all models!\")\n # can't set the alpha channel of palettes for seaborn functions, so\n # we use this workaround. fortunately, we only need 5 pairs of\n # colors, because that's all that Paired contains!\n pal = np.concatenate([sns.color_palette('Paired', 10),\n sns.color_palette('deep')[-5:-1]])\n pal = pal[[-1, -2, 1, -3, 3, 5, 7, 0, 6, -4, 2, 9, 4, 8]]\n elif col == 'model_parameter':\n # I don't think we actually need distinct colors for model parameter,\n # so we plot them all black\n pal = ['k'] * len(col_unique)\n elif col == 'freq_space_distance':\n pal = sns.color_palette('gray', len(col_unique))\n else:\n pal = sns.color_palette('Blues', len(col_unique))\n # if col=='stimulus_type', this is already a dict\n if as_dict and col != 'stimulus_type':\n order = get_order(col, reference_frame, col_unique)\n pal = dict(zip(order, pal))\n return pal\n\n\ndef stimulus_type_palette(reference_frame):\n palette = {}\n if isinstance(reference_frame, str):\n reference_frame = [reference_frame]\n if 'relative' in reference_frame:\n pal = sns.color_palette('deep', 5)\n palette.update(dict(zip(LOGPOLAR_SUPERCLASS_ORDER, pal)))\n if 'absolute' in reference_frame:\n pal = sns.color_palette('cubehelix', 5)\n palette.update(dict(zip(CONSTANT_SUPERCLASS_ORDER, pal)))\n return palette\n\n\ndef stimulus_type_order(reference_frame):\n order = []\n if isinstance(reference_frame, str):\n reference_frame = [reference_frame]\n for t in reference_frame:\n order.extend({'relative': LOGPOLAR_SUPERCLASS_ORDER,\n 'absolute': CONSTANT_SUPERCLASS_ORDER}[t])\n return order\n\n\ndef is_numeric(s):\n \"\"\"check whether data s is numeric\n\n s should be something that can be converted to an array: list,\n Series, array, column from a DataFrame, etc\n\n this is based on the function\n seaborn.categorical._CategoricalPlotter.infer_orient.is_not_numeric\n\n Parameters\n ----------\n s :\n data to check\n\n Returns\n -------\n is_numeric : bool\n whether s is numeric or not\n \"\"\"\n try:\n np.asarray(s, dtype=np.float)\n except ValueError:\n return False\n return True\n\n\ndef draw_arrow(ax, xy, xytext, text=\"\", arrowprops={}, **kwargs):\n kwargs.setdefault('xycoords', 'data')\n kwargs.setdefault('textcoords', 'data')\n ax.annotate(text, xy=xy, xytext=xytext, arrowprops=arrowprops, **kwargs)\n\n\nclass MidpointNormalize(mpl.colors.Normalize):\n def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):\n self.midpoint = midpoint\n mpl.colors.Normalize.__init__(self, vmin, vmax, clip)\n\n def __call__(self, value, clip=None):\n # I'm ignoring masked values and all kinds of edge cases to make a\n # simple example...\n x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]\n return np.ma.masked_array(np.interp(value, x, y))\n\n\ndef myLogFormat(y, pos):\n \"\"\"formatter that only shows the required number of decimal points\n\n this is for use with log-scaled axes, and so assumes that everything greater than 1 is an\n integer and so has no decimal points\n\n to use (or equivalently, with `axis.xaxis`):\n ```\n from matplotlib import ticker\n axis.yaxis.set_major_formatter(ticker.FuncFormatter(myLogFormat))\n ```\n\n modified from https://stackoverflow.com/a/33213196/4659293\n \"\"\"\n # Find the number of decimal places required\n if y < 1:\n # because the string representation of a float always starts \"0.\"\n decimalplaces = len(str(y)) - 2\n else:\n decimalplaces = 0\n # Insert that number into a format string\n formatstring = '{{:.{:1d}f}}'.format(decimalplaces)\n # Return the formatted tick label\n return formatstring.format(y)\n\n\ndef _jitter_data(data, jitter):\n \"\"\"optionally jitter data some amount\n\n jitter can be None / False (in which case no jittering is done), a number (in which case we add\n uniform noise with a min of -jitter, max of jitter), or True (in which case we do the uniform\n thing with min/max of -.1/.1)\n\n based on seaborn.linearmodels._RegressionPlotter.scatter_data\n \"\"\"\n if jitter is None or jitter is False:\n return data\n else:\n if jitter is True:\n jitter = .1\n return data + np.random.uniform(-jitter, jitter, len(data))\n\n\ndef im_plot(im, **kwargs):\n try:\n cmap = kwargs.pop('cmap')\n except KeyError:\n cmap = 'gray'\n try:\n ax = kwargs.pop('ax')\n ax.imshow(im, cmap=cmap, **kwargs)\n except KeyError:\n ax = plt.imshow(im, cmap=cmap, **kwargs)\n ax.axes.xaxis.set_visible(False)\n ax.axes.yaxis.set_visible(False)\n\n\ndef plot_median(x, y, plot_func=plt.plot, **kwargs):\n \"\"\"plot the median points, for use with seaborn's map_dataframe\n\n plot_func specifies what plotting function to call on the median points (e.g., plt.plot,\n plt.scatter)\n \"\"\"\n data = kwargs.pop('data')\n x_data, plot_data, _, _ = _map_dataframe_prep(data, x, y, np.median, None, None, None, 68)\n plot_func(x_data, plot_data.values, **kwargs)\n\n\ndef plot_ci(x, y, ci_vals=[16, 84], **kwargs):\n \"\"\"fill between the specified CIs, for use with seaborn's map_dataframe\n \"\"\"\n data = kwargs.pop('data')\n alpha = kwargs.pop('alpha', .2)\n plot_data = data.groupby(x)[y].apply(np.percentile, ci_vals)\n plot_values = np.vstack(plot_data.values)\n plt.fill_between(plot_data.index, plot_values[:, 0], plot_values[:, 1], alpha=alpha, **kwargs)\n\n\ndef scatter_ci_col(x, y, ci, x_order=None, x_jitter=None, **kwargs):\n \"\"\"plot center points and specified CIs, for use with seaborn's map_dataframe\n\n based on seaborn.linearmodels.scatterplot. CIs are taken from a column in this function.\n \"\"\"\n data = kwargs.pop('data')\n ax = plt.gca()\n plot_data = data.groupby(x)[y].median()\n plot_cis = data.groupby(x)[ci].median()\n if x_order is not None:\n plot_data = plot_data.reindex(x_order)\n plot_cis = plot_cis.reindex(x_order)\n for i, ((x_data, group_data), (_, group_cis)) in enumerate(zip(plot_data.items(), plot_cis.items())):\n try:\n x_data = _jitter_data(x_data, x_jitter)\n except TypeError:\n x_data = np.ones(1) * i\n x_data = _jitter_data(x_data, x_jitter)\n ax.scatter(x_data, group_data, **kwargs)\n ax.plot([x_data, x_data], [group_data+group_cis, group_data-group_cis], **kwargs)\n ax.set(xticks=range(len(plot_data)), xticklabels=plot_data.index.values)\n\n\ndef _map_dataframe_prep(data, x, y, estimator, x_jitter, x_dodge, x_order, ci=68):\n \"\"\"prepare dataframe for plotting\n\n Several of the plotting functions are called by map_dataframe and\n need a bit of prep work before plotting. These include:\n - computing the central trend\n - computing the CIs\n - jittering, dodging, or ordering the x values\n\n Parameters\n ----------\n data : pd.DataFrame\n The dataframe containing the info to plot\n x : str\n which column of data to plot on the x-axis\n y : str\n which column of data to plot on the y-axis\n estimator : callable, optional\n what function to use for estimating central trend of the data\n x_jitter : float, bool, or None, optional\n whether to jitter the data along the x-axis. if None or False,\n don't jitter. if a float, add uniform noise (drawn from\n -x_jitter to x_jitter) to each point's x value. if True, act as\n if x_jitter=.1\n x_dodge : float, None, or bool, optional\n to improve visibility with many points that have the same\n x-values (or are categorical), we can jitter the data along the\n x-axis, but we can also \"dodge\" it, which operates\n deterministically. x_dodge should be either a single float or an\n array of the same shape as x (we will dodge by calling `x_data =\n x_data + x_dodge`). if None, we don't dodge at all. If True, we\n dodge as if x_dodge=.01\n x_order: np.array or None, optional\n the order to plot x-values in. If None, don't reorder\n ci : int, optinoal\n The width fo the CI to draw (in percentiles)\n\n Returns\n -------\n x_data : np.array\n the x data to plot\n plot_data : np.array\n the y data of the central trend\n plot_cis : np.array\n the y data of the CIs\n x_numeric : bool\n whether the x data is numeric or not (used to determine if/how\n we should update the x-ticks)\n\n \"\"\"\n plot_data = data.groupby(x)[y].agg(estimator)\n ci_vals = [50 - ci/2, 50 + ci/2]\n plot_cis = [data.groupby(x)[y].agg(np.percentile, val) for val in ci_vals]\n if x_order is not None:\n plot_data = plot_data.reindex(x_order)\n plot_cis = [p.reindex(x_order) for p in plot_cis]\n x_data = plot_data.index\n # we have to check here because below we'll end up making things\n # numeric\n x_numeric = is_numeric(x_data)\n if not x_numeric:\n x_data = np.arange(len(x_data))\n x_data = _jitter_data(x_data, x_jitter)\n # at this point, x_data could be an array or the index of a\n # dataframe. we want it to be an array for all the following calls,\n # and this try/except forces that\n try:\n x_data = x_data.values\n except AttributeError:\n pass\n if x_dodge is not None:\n if x_dodge is True:\n x_dodge = .01\n x_data = x_data + x_dodge\n return x_data, plot_data, plot_cis, x_numeric\n\n\ndef scatter_ci_dist(x, y, ci=68, x_jitter=None, join=False, estimator=np.median,\n draw_ctr_pts=True, ci_mode='lines', ci_alpha=.2, size=5, x_dodge=None,\n **kwargs):\n \"\"\"plot center points and specified CIs, for use with seaborn's map_dataframe\n\n based on seaborn.linearmodels.scatterplot. CIs are taken from a\n distribution in this function. Therefore, it's assumed that the\n values being passed to it are values from a bootstrap distribution.\n\n by default, this draws the 68% confidence interval. to change this,\n change the ci argument. for instance, if you only want to draw the\n estimator point, pass ci=0\n\n Parameters\n ----------\n x : str\n which column of data to plot on the x-axis\n y : str\n which column of data to plot on the y-axis\n ci : int, optinoal\n The width fo the CI to draw (in percentiles)\n x_jitter : float, bool, or None, optional\n whether to jitter the data along the x-axis. if None or False,\n don't jitter. if a float, add uniform noise (drawn from\n -x_jitter to x_jitter) to each point's x value. if True, act as\n if x_jitter=.1\n join : bool, optional\n whether to connect the central trend of the data with a line or\n not.\n estimator : callable, optional\n what function to use for estimating central trend of the data,\n as plotted if either draw_ctr_pts or join is True.\n draw_ctr_pts : bool, optional\n whether to draw the center points (as given by estimator).\n ci_mode : {'lines', 'fill'}, optional\n how to draw the CI. If 'lines', we draw lines for the CI. If\n 'fill', we shade the region of the CI, with alpha given by\n ci_alpha\n ci_alpha : float, optional\n the alpha value for the CI, if ci_mode=='fill'\n size : float, optional\n Diameter of the markers, in points. (Although plt.scatter is\n used to draw the points, the size argument here takes a \"normal\"\n markersize and not size^2 like plt.scatter, following how it's\n done by seaborn.stripplot).\n x_dodge : float, None, or bool, optional\n to improve visibility with many points that have the same\n x-values (or are categorical), we can jitter the data along the\n x-axis, but we can also \"dodge\" it, which operates\n deterministically. x_dodge should be either a single float or an\n array of the same shape as x (we will dodge by calling `x_data =\n x_data + x_dodge`). if None, we don't dodge at all. If True, we\n dodge as if x_dodge=.01\n kwargs :\n must contain data. Other expected keys:\n - ax: the axis to draw on (otherwise, we grab current axis)\n - x_order: the order to plot x-values in. Otherwise, don't\n reorder\n everything else will be passed to the scatter, plot, and\n fill_between functions called (except label, which will not be\n passed to the plot or fill_between function call that draws the\n CI, in order to make any legend created after this prettier)\n\n Returns\n -------\n dots, lines, cis :\n The handles for the center points, lines connecting them (if\n join=True), and CI lines/fill. this is returned for better\n control over what shows up in the legend.\n\n \"\"\"\n data = kwargs.pop('data')\n ax = kwargs.pop('ax', plt.gca())\n x_order = kwargs.pop('x_order', None)\n x_data, plot_data, plot_cis, x_numeric = _map_dataframe_prep(data, x, y, estimator, x_jitter,\n x_dodge, x_order, ci)\n if draw_ctr_pts:\n # scatter expects s to be the size in pts**2, whereas we expect\n # size to be the diameter, so we convert that (following how\n # it's handled by seaborn's stripplot)\n dots = ax.scatter(x_data, plot_data.values, s=size**2, **kwargs)\n else:\n dots = None\n if join is True:\n lines = ax.plot(x_data, plot_data.values, **kwargs)\n else:\n lines = None\n # if we attach label to the CI, then the legend may use the CI\n # artist, which we don't want\n kwargs.pop('label', None)\n if ci_mode == 'lines':\n for x, (ci_low, ci_high) in zip(x_data, zip(*plot_cis)):\n cis = ax.plot([x, x], [ci_low, ci_high], **kwargs)\n elif ci_mode == 'fill':\n cis = ax.fill_between(x_data, plot_cis[0].values, plot_cis[1].values, alpha=ci_alpha,\n **kwargs)\n else:\n raise Exception(f\"Don't know how to handle ci_mode {ci_mode}!\")\n # if we do the following when x is numeric, things get messed up.\n if (x_jitter is not None or x_dodge is not None) and not x_numeric:\n ax.set(xticks=range(len(plot_data)), xticklabels=plot_data.index.values)\n return dots, lines, cis\n\n\ndef plot_noise_ceiling(x, y, ci=68, x_extent=.5, estimator=np.median, ci_alpha=.2,\n orient='v', **kwargs):\n \"\"\"plot the noise ceiling\n\n this is similar to scatter_ci_dist except that we want to plot each\n x value as a separate line, to make it clear there's no connection\n between them, and we always show the CIs using fill.\n\n Parameters\n ----------\n x : str\n which column of data to plot on the x-axis\n y : str\n which column of data to plot on the y-axis\n ci : int, optinoal\n The width fo the CI to draw (in percentiles)\n x_extent : float, optional\n we want to show the noise ceiling as a flat line, so we need it\n to extend beyond the exact x-value (which would just result in a\n point). to do that, x_extent controls the size of this line; we\n plot from `x-x_extent` to `x+x_extent` for each x.\n estimator : callable, optional\n what function to use for estimating central trend of the data,\n as plotted if either draw_ctr_pts or join is True.\n ci_alpha : float, optional\n the alpha value for the CI, if ci_mode=='fill'\n orient : {'h', 'v'}, optional\n orientation of plot (horizontal or vertical)\n kwargs :\n must contain data. Other expected keys:\n - ax: the axis to draw on (otherwise, we grab current axis)\n - x_order: the order to plot x-values in. Otherwise, don't\n reorder\n everything else will be passed to the scatter, plot, and\n fill_between functions called (except label, which will not be\n passed to the plot or fill_between function call that draws the\n CI, in order to make any legend created after this prettier)\n\n Returns\n -------\n lines, cis :\n The handles for the lines showing the noise level and the CI\n fill. this is returned for better control over what shows up in\n the legend. all lines have `label='noise_ceiling'`, the CIs have\n no label\n\n \"\"\"\n data = kwargs.pop('data')\n ax = kwargs.pop('ax', plt.gca())\n x_order = kwargs.pop('x_order', None)\n x_data, plot_data, plot_cis, _ = _map_dataframe_prep(data, x, y, estimator, None, None, None,\n ci)\n if is_numeric(x_data):\n warnings.warn(\"With numeric x_data, there's a confusion between the integer values and \"\n f\"the categorical labels -- we're subtracting off the min value, {min(x_data)},\"\n \" to avoid this situation\")\n x_data -= min(x_data)\n y_extent = 0\n # then flip everything\n if orient == 'h':\n x_tmp = x_data\n x_data = plot_data\n plot_data = x_tmp\n y_extent = x_extent\n x_extent = 0\n lines = []\n cis = []\n for x, d, ci_low, ci_high in zip(x_data, plot_data, *plot_cis):\n lines.append(ax.plot([x-x_extent, x+x_extent], [d-y_extent, d+y_extent],\n label='noise ceiling', **kwargs))\n cis.append(ax.fill_between([x-x_extent, x+x_extent], ci_low, ci_high, alpha=ci_alpha,\n **kwargs))\n return lines, cis\n\n\ndef plot_median_fit(x, y, model=linear_model.LinearRegression(), x_vals=None, **kwargs):\n \"\"\"plot a model fit to the median points, for use with seaborn's map_dataframe\n\n we first find the median values of y when grouped by x and then fit model to them and plot\n *only* the model's predictions (thus you'll need to call another function if you want to see\n the actual data). we don't cross-validate or do anything fancy.\n\n model should be an (already-initialized) class that has a fit (which accepts X and y) and a\n predict method (which accepts X; for instance, anything from sklearn). It should expect X to be\n 2d; we reshape our 1d data to be 2d (since this is what the sklearn models expect)\n \"\"\"\n data = kwargs.pop('data')\n if 'exclude' in kwargs['label']:\n # we don't plot anything with exclude in the label\n return\n plot_data = data.groupby(x)[y].median()\n model.fit(plot_data.index.values.reshape(-1, 1), plot_data.values)\n if x_vals is None:\n x_vals = plot_data.index\n x_vals = np.array(x_vals).reshape(-1, 1)\n plt.plot(x_vals, model.predict(x_vals), **kwargs)\n\n\ndef stimuli_properties(df, save_path=None):\n \"\"\"plot some summaries of the stimuli properties\n\n this plots three pieces stimulus properties as a function of their position in frequency space\n (either w_x / w_y or w_r / w_a): superclass (radial, angular, etc / horizontal, vertical,\n etc), distance from the origin in frequency space, and angle in the frequency space. these\n various properties of the stimuli will be used to summarize results later on and so are\n important to have a handle on.\n\n df: pandas DataFrame containing stimulus information. should be either the stimulus description\n dataframe or the first level results dataframe.\n \"\"\"\n if 'voxel' in df.columns:\n df = df[df.voxel == df.voxel.unique()[0]]\n else:\n df = df.dropna()\n df.class_idx = df.class_idx.astype(int)\n df = df.drop_duplicates('class_idx').set_index('class_idx')\n df = df.rename(columns={'index': 'stimulus_index'})\n df = first_level_analysis._add_freq_metainfo(df)\n if 'baseline' in df.stimulus_superclass.unique():\n df = df[df.stimulus_superclass != 'baseline']\n figsize = (19, 5)\n cmaps = [None, sns.cubehelix_palette(as_cmap=True),\n sns.diverging_palette(10, 220, as_cmap=True)]\n try:\n df['w_a']\n freq_names = ['w_r', 'w_a']\n if 181 in df['w_a'].unique():\n # then this is the pilot data, which goes out further in frequency space\n if df['freq_space_angle'].max() > 2:\n # then this is the first pilot, which has a bit different angles\n ylim, xlim = [-75, 200], [-150, 250]\n figsize = (20, 6)\n else:\n ylim, xlim = [-176, 212], [-28, 311]\n else:\n ylim, xlim = [-125, 150], [-20, 220]\n cmaps[0] = stimulus_type_palette('relative')\n except KeyError:\n freq_names = ['w_x', 'w_y']\n ylim, xlim = [-.098, .118], [-.0157, .173]\n cmaps[0] = stimulus_type_palette('absolute')\n norms = [None, None, MidpointNormalize(df.freq_space_angle.min(),\n df.freq_space_angle.max(), midpoint=0)]\n titles = ['Frequency superclass', 'Frequency distance', \"Frequency angle\"]\n color_prop = ['stimulus_superclass', 'freq_space_distance', 'freq_space_angle']\n with sns.axes_style('white'):\n fig, axes = plt.subplots(1, 3, figsize=figsize)\n for i, ax in enumerate(axes.flatten()):\n # zorder ensures that the lines are plotted before the points in the scatterplot\n ax.plot(xlim, [0, 0], 'k--', alpha=.5, zorder=1)\n ax.plot([0, 0], ylim, 'k--', alpha=.5, zorder=2)\n if i == 0:\n handles = []\n labels = []\n for lab, g in df.groupby(color_prop[i]):\n pts = ax.scatter(g[freq_names[0]].values, g[freq_names[1]].values,\n c=cmaps[i][lab], edgecolors='k', zorder=3)\n handles.append(pts)\n labels.append(lab)\n ax.legend(handles, labels)\n elif 0 < i < 3:\n pts = ax.scatter(df[freq_names[0]].values, df[freq_names[1]].values,\n c=df[color_prop[i]].values, cmap=cmaps[i], edgecolors='k',\n norm=norms[i], zorder=3)\n fig.colorbar(pts, ax=ax, fraction=.046, pad=.1)\n else:\n ax.set_visible(False)\n continue\n ax.set_aspect('equal')\n ax.set_xlim(xlim)\n ax.set_ylim(ylim)\n ax.set_title(titles[i], fontsize=15)\n ax.set_xlabel(\"$\\omega_%s$\" % freq_names[0][-1], fontsize=20)\n ax.set_ylabel(\"$\\omega_%s$\" % freq_names[1][-1], fontsize=20)\n sns.despine()\n if save_path is not None:\n fig.savefig(save_path, bbox_inches='tight')\n return fig\n\n\ndef local_spatial_frequency(df, save_path=None, **kwargs):\n \"\"\"plot the local spatial frequency for all stimuli\n\n df: first_level_analysis results dataframe.\n\n all kwargs get passed to plt.plot\n \"\"\"\n if 'rounded_freq_space_distance' in df.columns:\n hue_label = 'rounded_freq_space_distance'\n col_order = LOGPOLAR_SUPERCLASS_ORDER\n else:\n hue_label = 'freq_space_distance'\n col_order = CONSTANT_SUPERCLASS_ORDER\n\n def mini_plot(x, y, **kwargs):\n # this function converts the stringified floats of eccentricity to floats and correctly\n # orders them for plotting.\n x = [np.mean([float(j) for j in i.split('-')]) for i in x.values]\n plot_vals = sorted(zip(x, y.values), key=lambda pair: pair[0])\n plt.plot([i for i, _ in plot_vals], [j for _, j in plot_vals], **kwargs)\n\n with sns.axes_style('white'):\n g = sns.FacetGrid(df, hue=hue_label, col='stimulus_superclass', palette='Reds', col_wrap=3,\n col_order=col_order)\n g.map(mini_plot, 'eccen', 'local_sf_magnitude', **kwargs)\n g.add_legend()\n plt.subplots_adjust(top=.9)\n g.fig.suptitle(\"Local spatial frequencies across eccentricities for all stimuli\",\n fontsize=15)\n if save_path is not None:\n g.fig.savefig(save_path, bbox_inches='tight')\n return g\n\n\ndef plot_data(df, x_col='freq_space_distance', median_only=False, ci=68,\n save_path=None, row='varea', **kwargs):\n \"\"\"plot the raw amplitude estimates, either with or without confidence intervals\n\n if df is the summary dataframe, we'll use the amplitude_estimate_std_error column as the\n confidence intervals (in this case, ci is ignored). otherwise, we'll estimate them\n directly from the bootstrapped data using np.percentile; in this case, ci determines what\n percentile to plot (by default, the 68% confidence interval)\n\n x_col determines what to have on the x-axis 'freq_space_distance' or\n 'rounded_freq_space_distance' will probably work best. you can try 'freq_space_angle' or 'Local\n spatial frequency (cpd)', but there's no guarantee those will plot well.\n\n if median_only is True, will not plot confidence intervals.\n\n kwargs will get passed to plt.scatter and plt.plot, via scatter_ci_dist / scatter_ci_col\n \"\"\"\n if 'rounded_freq_space_distance' in df.columns:\n col_order = [i for i in LOGPOLAR_SUPERCLASS_ORDER if i in df.stimulus_superclass.unique()]\n else:\n col_order = [i for i in CONSTANT_SUPERCLASS_ORDER if i in df.stimulus_superclass.unique()]\n\n ylim = kwargs.pop('ylim', None)\n xlim = kwargs.pop('xlim', None)\n aspect = kwargs.pop('aspect', 1)\n g = sns.FacetGrid(df, hue='eccen', palette='Reds', height=5, row=row, col_order=col_order,\n hue_order=sorted(df.eccen.unique()), col='stimulus_superclass', ylim=ylim,\n xlim=xlim, aspect=aspect, row_order=sorted(df[row].unique()))\n if 'amplitude_estimate_std_error' in df.columns:\n g.map_dataframe(plot_median, x_col, 'amplitude_estimate_median')\n if not median_only:\n g.map_dataframe(scatter_ci_col, x_col, 'amplitude_estimate_median',\n 'amplitude_estimate_std_error', **kwargs)\n else:\n g.map_dataframe(plot_median, x_col, 'amplitude_estimate')\n if not median_only:\n g.map_dataframe(scatter_ci_dist, x_col, 'amplitude_estimate', ci=ci, **kwargs)\n g.map_dataframe(plot_median, x_col, 'baseline', linestyle='--')\n for ax in g.axes.flatten():\n ax.set_xscale('log', basex=2)\n g.add_legend()\n g.fig.suptitle(\"Amplitude estimates as a function of frequency\")\n plt.subplots_adjust(top=.9)\n if save_path is not None:\n g.fig.savefig(save_path, bbox_inches='tight')\n return g\n\n\ndef _plot_grating_approx_and_save(grating, grating_type, save_path, **kwargs):\n figsize = kwargs.pop('figsize', (5, 5))\n fig, axes = plt.subplots(1, 1, figsize=figsize)\n im_plot(grating, ax=axes, **kwargs)\n if grating_type == 'grating':\n axes.set_title(\"Windowed view of actual grating\")\n elif grating_type == 'approx':\n axes.set_title(\"Windowed view of linear approximation\")\n if save_path is not None:\n try:\n fig.savefig(save_path % grating_type, bbox_inches='tight')\n except TypeError:\n save_path = os.path.splitext(save_path)[0] + \"_\" + grating_type + os.path.splitext(save_path)[1]\n fig.savefig(save_path, bbox_inches='tight')\n\n\ndef plot_grating_approximation(grating, dx, dy, num_windows=10, phase=0, w_r=None, w_a=None,\n origin=None, stim_type='logpolar', save_path=None, **kwargs):\n \"\"\"plot the \"windowed approximation\" of a grating\n\n note that this will not create the grating or its gradients (dx/dy), it only plots them. For\n this to work, dx and dy must be in cycles / pixel\n\n this will work for either regular 2d gratings or the log polar gratings we use as stimuli,\n though it will look slightly different depending on which you do. In the regular case, the\n space between windows will be mid-gray, while for the log polar gratings, it will be\n black. This allows for a creation of a neat illusion for some regular gratings (use\n grating=sfp.utils.create_sin_cpp(1080, .005, .005) to see an example)!\n\n if `grating` is one of our log polar gratings, then w_r and w_a also need to be set. if it's a\n regular 2d grating, then they should both be None.\n\n num_windows: int, the number of windows in each direction that we'll use. as this gets larger,\n the approximation will look better and better (and this will take a longer time to run)\n\n save_path: str, optional. If set, will save plots. in order to make comparison easier, will save\n two separate plots (one of the windowed grating, one of the linear approximation). if save_path\n does not include %s, will append _grating and _approx (respectively) to filename\n\n kwargs will be past to im_plot.\n \"\"\"\n size = grating.shape[0]\n # we need to window the gradients dx and dy so they only have values where the grating does\n # (since they're derived analytically, they'll have values everywhere)\n mid_val = {'pilot': 127}.get(stim_type, 128)\n dx = utils.mask_array_like_grating(grating, dx, mid_val)\n dy = utils.mask_array_like_grating(grating, dy, mid_val)\n mask_spacing = int(np.round(size / num_windows))\n # for this to work, the gratings must be non-overlapping\n mask_size = int(np.round(mask_spacing / 2) - 1)\n masked_grating = np.zeros((size, size))\n masked_approx = np.zeros((size, size))\n masks = np.zeros((size, size))\n for i in range(mask_size, size, mask_spacing):\n for j in range(mask_size, size, mask_spacing):\n loc_x, loc_y = i, j\n mask = utils.create_circle_mask(loc_x, loc_y, mask_size, size)\n masks += mask\n masked_grating += mask * grating\n masked_approx += mask * utils.local_grad_sin(dx, dy, loc_x, loc_y, w_r, w_a, phase,\n origin, stim_type)\n # in order to make the space between the masks black, that area should have the minimum\n # value, -1. but for the above to all work, that area needs to be 0, so this corrects that.\n masked_approx[~masks.astype(bool)] -= 1\n masked_grating[~masks.astype(bool)] -= 1\n _plot_grating_approx_and_save(masked_grating, 'grating', save_path, **kwargs)\n _plot_grating_approx_and_save(masked_approx, 'approx', save_path, **kwargs)\n return masked_grating, masked_approx\n\n\ndef add_img_to_xaxis(fig, ax, img, rel_position, size=.1, **kwargs):\n \"\"\"add image to x-axis\n\n after calling this, you probably want to make your x axis invisible:\n `ax.xaxis.set_visible(False)` or things will look confusing\n\n rel_position: float between 0 and 1, specifies where on the x axis you want to place the\n image. You'll need to play arond with this, I don't have a good way of doing this automatically\n (for instance, lining up with existing tick marks). This interacts with size. if you want the\n left edge to line up with the beginning of the x-axis, this should be 0, but if you want the\n right edge to line up with the end of the x-axis, this should be around 1-size\n\n size: float between 0 and 1, size of image, relative to overall plot size. it appears that\n around .1 or .2 is a good size.\n \"\"\"\n xl, yl, xh, yh = np.array(ax.get_position()).ravel()\n w = xh - xl\n\n ax1 = fig.add_axes([xl + w*rel_position, yl-size, size, size])\n ax1.axison = False\n im_plot(img, ax=ax1, **kwargs)\n\n\ndef stimuli_linear_approximation(stim, stim_df, stim_type, num_windows=11, stim_idx=None, phi=None,\n freq_space_distance=None, freq_space_angle=None,\n stimulus_superclass=None, save_path=None, **kwargs):\n \"\"\"plot the linear approximation of specific stimulus\n \"\"\"\n if stim_idx is None:\n stim_idx = utils.find_stim_idx(stim_df, stimulus_superclass=stimulus_superclass, phi=phi,\n freq_space_distance=freq_space_distance,\n freq_space_angle=freq_space_angle)\n props = stim_df.loc[stim_idx]\n freqs = {}\n for f in ['w_r', 'w_a', 'w_x', 'w_y']:\n try:\n freqs[f] = props[f]\n except KeyError:\n freqs[f] = None\n stim = stim[stim_idx]\n dx, dy, _, _ = sfp_stimuli.create_sf_maps_cpp(props.res, stim_type=stim_type, **freqs)\n return plot_grating_approximation(stim, dx, dy, num_windows, props.phi, w_r=freqs['w_r'],\n w_a=freqs['w_a'], stim_type=stim_type,\n save_path=save_path, **kwargs)\n\n\ndef stimuli(stim, stim_df, save_path=None, **kwargs):\n \"\"\"plot a bunch of stimuli with specific properties, pulled out of stim_df\n\n possible keys for kwargs: {'w_r'/'w_x', 'w_a'/'w_y', 'phi', 'res', 'alpha', 'stimulus_index',\n 'class_idx', 'stimulus_superclass', 'freq_space_angle', 'freq_space_distance'}. The values\n should be either a list or a single value. if a single value, will assume that all stimuli\n share that property. all lists should be the same length. if a property isn't set, then we\n assume it's not important and so will grab the lowest stimuli with the lowest index that\n matches all specified properties.\n \"\"\"\n stim_props = {}\n stim_num = None\n figsize = kwargs.pop('figsize', None)\n for k, v in kwargs.items():\n if hasattr(v, \"__iter__\") and not isinstance(v, str):\n if stim_num is None:\n stim_num = len(v)\n else:\n if stim_num != len(v) and len(v) != 1:\n raise Exception(\"All stimulus properties must have the same length!\")\n stim_props[k] = v\n else:\n stim_props[k] = [v]\n if stim_num is None:\n stim_num = 1\n for k, v in stim_props.items():\n if len(v) == 1:\n stim_props[k] = stim_num * v\n stim_idx = []\n for i in range(stim_num):\n stim_idx.append(utils.find_stim_idx(stim_df,\n **dict((k, v[i]) for k, v in stim_props.items())))\n if figsize is None:\n figsize = (5 * min(stim_num, 4), 5 * np.ceil(stim_num / 4.))\n fig = plt.figure(figsize=figsize)\n # ADD DESCRIPTIVE TITLES\n for i, idx in enumerate(stim_idx):\n ax = fig.add_subplot(np.ceil(stim_num / 4.).astype(int), min(stim_num, 4), i+1)\n im_plot(stim[idx, :, :], ax=ax)\n plt.tight_layout()\n if save_path is not None:\n fig.savefig(save_path)\n\n\ndef plot_tuning_curve(ci_vals=[16, 84], norm=False, xlim=None, style=None,\n dashes_dict={}, **kwargs):\n data = kwargs.pop('data')\n color = kwargs.pop('color')\n ax = kwargs.pop('ax', plt.gca())\n if xlim is not None:\n if xlim == 'data':\n xlim = (data.frequency_value.min(), data.frequency_value.max())\n xlim = np.logspace(np.log10(xlim[0]), np.log10(xlim[1]))\n if style is not None:\n data = data.groupby(style)\n else:\n data = [(None, data)]\n for m, d in data:\n dashes = dashes_dict.get(m, '')\n if 'bootstrap_num' in d.columns and d.bootstrap_num.nunique() > 1:\n xs, ys = [], []\n for n, g in d.groupby('bootstrap_num'):\n x, y = tuning_curves.get_tuning_curve_xy_from_df(g, norm=norm, x=xlim)\n xs.append(x)\n ys.append(y)\n xs = np.array(xs)\n if (xs != xs[0]).any():\n raise Exception(\"Somehow we got different xs for the tuning curves of some \"\n \"bootstraps!\")\n ys = np.array(ys)\n y_median = np.median(ys, 0)\n y_cis = np.percentile(ys, ci_vals, 0)\n ax.fill_between(xs[0], y_cis[0], y_cis[1], alpha=.2, facecolor=color)\n ax.semilogx(xs[0], y_median, basex=2, color=color, dashes=dashes, **kwargs)\n else:\n x, y = tuning_curves.get_tuning_curve_xy_from_df(d, norm=norm, x=xlim)\n ax.semilogx(x, y, basex=2, color=color, dashes=dashes, **kwargs)\n\n\ndef _restrict_df(df, **kwargs):\n for k, v in kwargs.items():\n try:\n df = df[df[k].isin(v)]\n except TypeError:\n df = df[df[k] == v]\n return df\n\n\ndef check_tuning_curves(tuning_df, save_path_template, **kwargs):\n \"\"\"create all the tuning curve plots\n\n this takes the dataframe containing the tuning curves and creates plots of all of them, so they\n can be visibly checked. note that this will take a while and create *many* plots, especially\n when run on the full dataframes. It is thus *not* meant to be run from a notebook and it will\n close the plots as it creates and saves them.\n\n kwargs can contain columns in the tuning_df and values to limit them to.\n \"\"\"\n tuning_df = _restrict_df(tuning_df, **kwargs)\n gb_cols = ['varea']\n title_template = 'varea={}'\n if 'bootstrap_num' in tuning_df.columns:\n gb_cols += ['bootstrap_num']\n title_template += ', bootstrap={:02d}'\n mode_bounds = (tuning_df.mode_bound_lower.unique()[0], tuning_df.mode_bound_upper.unique()[0])\n for n, g in tuning_df.groupby(gb_cols):\n f = sns.FacetGrid(g, row='eccen', col='stimulus_superclass', hue='frequency_type',\n xlim=mode_bounds, aspect=.7, height=5)\n f.map(plt.scatter, 'frequency_value', 'amplitude_estimate')\n f.map_dataframe(plot_tuning_curve)\n f.map_dataframe(plot_median, 'frequency_value', 'baseline', linestyle='--')\n f.add_legend()\n f.set_titles(\"eccen={row_name} | {col_name}\")\n if len(gb_cols) == 1:\n # then there's only one value in n (and thus, in gb_cols)\n suptitle = title_template.format(n)\n else:\n suptitle = title_template.format(*n)\n f.fig.suptitle(suptitle)\n plt.subplots_adjust(top=.95)\n f.savefig(save_path_template % (suptitle.replace(', ', '_')))\n plt.close(f.fig)\n\n\ndef check_hypotheses(tuning_df, save_path_template=None, norm=False, ci_vals=[16, 84],\n plot_data=True, **kwargs):\n tuning_df = _restrict_df(tuning_df, **kwargs)\n gb_cols = ['varea']\n title_template = 'varea={}'\n col_order = [i for i in LOGPOLAR_SUPERCLASS_ORDER+CONSTANT_SUPERCLASS_ORDER\n if i in tuning_df.stimulus_superclass.unique()]\n for n, g in tuning_df.groupby(gb_cols):\n f = sns.FacetGrid(g, hue='eccen', palette='Reds', height=5, row='frequency_type',\n col='stimulus_superclass', col_order=col_order)\n if plot_data:\n f.map_dataframe(plot_median, 'frequency_value', 'amplitude_estimate',\n plot_func=plt.scatter)\n f.map_dataframe(plot_tuning_curve, norm=norm, ci_vals=ci_vals)\n for ax in f.axes.flatten():\n ax.set_xscale('log', basex=2)\n ax.set_xlim((2**-5, 2**10))\n if norm:\n ax.set_ylim((0, 1.2))\n f.add_legend()\n suptitle = title_template.format(n)\n f.fig.suptitle(\"Median amplitude estimates with tuning curves, %s\" % suptitle)\n plt.subplots_adjust(top=.93)\n f.set_titles(\"{row_name} | {col_name}\")\n if save_path_template is not None:\n f.fig.savefig(save_path_template % suptitle, bbox_inches='tight')\n\n\ndef check_hypotheses_with_data(tuning_df, save_path_template=None, ci_vals=[16, 84], **kwargs):\n check_hypotheses(tuning_df, save_path_template, False, ci_vals, True, **kwargs)\n\n\ndef check_hypotheses_normalized(tuning_df, save_path_template=None, ci_vals=[16, 84], **kwargs):\n check_hypotheses(tuning_df, save_path_template, True, ci_vals, False, **kwargs)\n\n\ndef tuning_params(tuning_df, save_path=None, **kwargs):\n tuning_df = _restrict_df(tuning_df, **kwargs)\n tuning_df = tuning_df[['frequency_type', 'tuning_curve_amplitude', 'tuning_curve_sigma',\n 'tuning_curve_peak', 'tuning_curve_bandwidth']]\n tuning_df['tuning_curve_peak'] = np.log2(tuning_df.tuning_curve_peak)\n g = sns.PairGrid(tuning_df, hue='frequency_type', aspect=1)\n g.map_offdiag(plt.scatter)\n g.map_diag(sns.distplot)\n g.add_legend()\n if save_path is not None:\n g.fig.savefig(save_path)\n\n\ndef period_summary_plot(df, pRF_size_slope=.25394, pRF_size_offset=.100698,\n model=linear_model.LinearRegression(), n_windows=4, size=1080,\n max_visual_angle=24, plot_view='full', center_spot_rad=2,\n stimulus_superclass=None, save_path=None):\n \"\"\"make plot that shows the optimal number of periods per receptive field\n\n df: dataframe containing the summarized preferred periods. should contain three columns:\n stimulus_superclass, eccen, and preferred_period. will fit model separately to each\n stimulus_superclass (by default, linear regression, fitting the intercept) and then, at each\n eccentricity, show the appropriate period (from the fitted line). because we allow the\n intercept to be non-zero\n\n this works by using the coefficients of the linear fits (with zero intercept) relating\n eccentricity to the period of the optimal grating stimulus (from measurements for both radial\n and angular stimuli) and to V1 receptive field size. We show the views of the radial stimuli\n along the vertical axis and the views of the angular along the horizontal axis.\n\n pRF_size_slope should be for the diameter of what you want to display. for example, the default\n is 4 * stddev, or the diameter of two standard deviations.\n\n n_windows: int, the number of windows on each side of the origin to show\n\n plot_view: {'full', 'quarter', 'aligned'}. whether to plot a full, quarter, or aligned view. if\n aligned, can only plot one stimulus superclass and will do always do so along the horizontal\n meridian (for combining by hand afterwards).\n\n stimulus_superclass: which stimulus superclasses to plot. if None, will plot all that are in\n the dataframe. note that we don't re-adjust spacing to make it look good for fewer than 4\n superclasses, so that's on you.\n \"\"\"\n def get_logpolar_freq(slope, intercept, ecc):\n coeff = (slope*ecc + intercept) / ecc\n return np.round((2 * np.pi) / coeff)\n\n def fit_model(data, model=linear_model.LinearRegression()):\n x = data.eccen.values\n y = data.preferred_period.values\n model.fit(x.reshape(-1, 1), y)\n return pd.Series({'coeff': model.coef_[0], 'intercept': model.intercept_})\n\n def logpolar_solve_for_global_phase(x, y, w_r, w_a, local_phase=0):\n origin = ((size+1) / 2., (size+1) / 2.)\n x_orig, y_orig = np.meshgrid(np.array(range(1, size+1))-origin[0],\n np.array(range(1, size+1))-origin[1])\n local_x = x_orig[y, x]\n local_y = y_orig[y, x]\n return np.mod(local_phase - (((w_r*np.log(2))/2.)*np.log2(local_x**2+local_y**2) +\n w_a*np.arctan2(local_y, local_x)), 2*np.pi)\n\n if stimulus_superclass is None:\n stimulus_superclass = df.stimulus_superclass.unique()\n if plot_view == 'aligned' and len(stimulus_superclass) != 1:\n raise Exception(\"Can only plot aligned view if plotting 1 stimulus_superclass\")\n df = df.groupby('stimulus_superclass').apply(fit_model)\n windowed_plot = np.zeros((size, size))\n R = sfp_stimuli.mkR(size) * (float(max_visual_angle) / size)\n ecc_to_pix = pRF_size_slope * (float(size) / max_visual_angle) + pRF_size_offset\n masks = np.zeros((size, size))\n meridian = int(size / 2)\n # we put this into masks so it doesn't get adjusted at the end and we set it to -1 so it\n # appears black.\n masks[meridian-center_spot_rad:meridian+center_spot_rad,\n meridian-center_spot_rad:meridian+center_spot_rad] = 1\n windowed_plot[masks.astype(bool)] = -1\n view_range = range(meridian, size, int(meridian / (n_windows+1)))[1:]\n for loc in view_range:\n # we do x and y separately because there's a chance a rounding issue will mean they differ\n # slightly\n if plot_view == 'full':\n diag_value_1 = (loc - meridian) * np.sin(np.pi / 4)\n diag_value_2 = (loc - meridian) * -np.sin(np.pi / 4)\n window_locs = [(loc, meridian, 'radial'), (meridian, loc, 'angular'),\n (size-loc, meridian, 'radial'), (meridian, size-loc, 'angular'),\n (meridian+diag_value_1, meridian+diag_value_1, 'forward spiral'),\n (meridian+diag_value_1, meridian+diag_value_2, 'reverse spiral'),\n (meridian+diag_value_2, meridian+diag_value_2, 'forward spiral'),\n (meridian+diag_value_2, meridian+diag_value_1, 'reverse spiral')]\n elif plot_view == 'quarter':\n diag_value_1 = (loc - meridian) * np.sin(np.pi / 6)\n diag_value_2 = (loc - meridian) * np.sin(np.pi / 3)\n window_locs = [(size-loc, meridian, 'radial'), (meridian, loc, 'angular'),\n (meridian-diag_value_1, meridian+diag_value_2, 'forward spiral'),\n (meridian-diag_value_2, meridian+diag_value_1, 'reverse spiral')]\n elif plot_view == 'aligned':\n window_locs = [(meridian, loc, stimulus_superclass[0])]\n for loc_y, loc_x, stim_class in window_locs:\n if stim_class not in stimulus_superclass:\n continue\n loc_x, loc_y = int(loc_x), int(loc_y)\n ecc = R[loc_y, loc_x]\n # ecc * ecc_to_pix gives you the diameter, but we want the radius\n mask = utils.create_circle_mask(loc_x, loc_y, (ecc * ecc_to_pix) / 2, size)\n masks += mask\n opt_w = get_logpolar_freq(df.loc[stim_class].coeff, df.loc[stim_class].intercept, ecc)\n if stim_class == 'angular':\n phase = logpolar_solve_for_global_phase(loc_x, loc_y, 0, opt_w)\n windowed_plot += mask * sfp_stimuli.log_polar_grating(size, w_a=opt_w, phi=phase)\n elif stim_class == 'radial':\n phase = logpolar_solve_for_global_phase(loc_x, loc_y, opt_w, 0)\n windowed_plot += mask * sfp_stimuli.log_polar_grating(size, w_r=opt_w, phi=phase)\n elif stim_class == 'forward spiral':\n opt_w = np.round(opt_w / np.sqrt(2))\n phase = logpolar_solve_for_global_phase(loc_x, loc_y, opt_w, opt_w)\n windowed_plot += mask * sfp_stimuli.log_polar_grating(size, w_r=opt_w, w_a=opt_w,\n phi=phase)\n elif stim_class == 'reverse spiral':\n opt_w = np.round(opt_w / np.sqrt(2))\n phase = logpolar_solve_for_global_phase(loc_x, loc_y, opt_w, -opt_w)\n windowed_plot += mask * sfp_stimuli.log_polar_grating(size, w_r=opt_w, w_a=-opt_w,\n phi=phase)\n windowed_plot[~masks.astype(bool)] += 1\n fig, ax = plt.subplots(1, 1, figsize=(8, 8))\n im_plot(windowed_plot, ax=ax)\n if save_path is not None:\n fig.savefig(save_path)\n return windowed_plot\n\n\ndef model_schematic(model, axes=None, ylims=None, title=True,\n orientation=np.linspace(0, np.pi, 4, endpoint=False)):\n \"\"\"Examine model predictions, intended for example models (not ones fit to data)\n\n In order to better understand the model, it's helpful to examine the\n predictions for several toy models to see the effect of changing\n parameters and get an intuition for what's going on. This plot is an\n attempt to help with that by creating two plots next to each other,\n showing the preferred period as a function of eccentricity and\n retinotopic angle (in separate plots, each showing one slice of the\n other; both in relative reference frame).\n\n This function is intended to be called by figures.model_schematic().\n\n It's recommended that each axis have size (5, 5).\n\n NOTE: we remove the legend from each plot, because otherwise there's\n one per plot and they take up too much space. It's recommended that\n you create your own by grabbing the handles and labels from the\n returned axes and placing on its own set of axes:\n\n ```\n fig = plt.figure(figsize=(15, 5))\n axes = []\n for i in range(4):\n ax = fig.add_subplot(1, 3, i+1,\n projection=['rectilinear', 'polar', 'rectilinear'][i])\n axes.append(ax)\n axes = model_schematic(model, axes)\n # relative reference frame legend\n axes[-1].legend(*axes[0].get_legend_handles_labels(), loc='upper left')\n ```\n\n Parameters\n ----------\n model : sfp.model.LogGaussianDonut\n Instantiated model that you want to generate the predictions for\n axes : list or None, optional\n A list of axes to create the plots on. There must be at least\n two of them, the first must have a rectilinear projection (the\n default), and the second must have polar projections (any\n further axes will be ignored). If None, we create two axes in a\n row with figsize=(10, 5).\n ylims : list or None, optional\n A list of three tuples, the ylim value to use for each plot\n (ylim corresponds to rlim for polar plots). If None, we use the\n default. Used for making the same limits across multiple\n calls to this function.\n title : bool, optional\n whether to add a title or not\n\n Returns\n -------\n axes : list\n The axes with the plots\n\n \"\"\"\n if axes is None:\n fig = plt.figure(figsize=(10, 5))\n axes = []\n for i in range(2):\n ax = fig.add_subplot(1, 2, i+1, projection=['rectilinear', 'polar'][i])\n axes.append(ax)\n single_ret_angle = 0\n single_ecc = 6\n ecc = np.arange(12)\n pref_period = analyze_model.create_preferred_period_df(model, reference_frame='relative',\n retinotopic_angle=[single_ret_angle],\n eccentricity=ecc,\n orientation=orientation)\n ret_angle = np.linspace(0, 2*np.pi, 49)\n rel_contour = analyze_model.create_preferred_period_df(model, reference_frame='relative',\n eccentricity=[single_ecc],\n retinotopic_angle=ret_angle,\n orientation=orientation)\n titles = [f'Preferred period at retinotopic angle {single_ret_angle}',\n f'Preferred period at eccentricity {single_ecc}']\n dfs = [pref_period, rel_contour]\n projs = ['rectilinear', 'polar']\n if len(axes) == 1:\n if axes[0].name == 'rectilinear':\n dfs = [dfs[0]]\n projs = [projs[0]]\n titles = [titles[0]]\n elif axes[0].name == 'polar':\n dfs = [dfs[1]]\n projs = [projs[1]]\n titles = [titles[1]]\n for i, (df, ax, proj, t) in enumerate(zip(dfs, axes, projs, titles)):\n if ax.name != proj:\n raise Exception(f\"Axes must have projection {proj}, not {ax.name}!\")\n if proj == 'rectilinear':\n x = 'Eccentricity (deg)'\n single_x = single_ecc\n else:\n x = 'Retinotopic angle (rad)'\n single_x = single_ret_angle\n order = [k for k in stimulus_type_order(df.reference_frame.unique()[0])\n if k in df['Stimulus type'].unique()]\n pal = get_palette('stimulus_type', df.reference_frame.unique()[0],\n df['Stimulus type'].unique(), True)\n sns.lineplot(x, 'Preferred period (deg)', 'Stimulus type', data=df, ax=ax, hue_order=order,\n palette=pal, estimator=np.median, ci=68)\n ax.legend_.remove()\n if i > 0:\n ax.set_ylabel('')\n if title:\n ax.set_title(t, y=[1.1, 1.1][i])\n if ylims is not None:\n ax.set_ylim(ylims[i])\n restricted = df[df['Eccentricity (deg)'] == single_ecc]['Preferred period (deg)']\n if proj == 'rectilinear':\n ax.axhline(color='gray', linestyle='--')\n ax.axvline(color='gray', linestyle='--')\n else:\n ax.set(yticklabels=[0, '', 1, '', 2, '', 3], yticks=[0, .5, 1, 1.5, 2, 2.5, 3])\n if len(axes) > 1:\n # only want this if we're plotting both the linear and polar plots\n ax.vlines(single_x, restricted.min()-.5, restricted.max()+.5, 'r', '--')\n return axes\n\n\ndef feature_df_plot(feature_df, hue=\"Stimulus type\", col='Retinotopic angle (rad)', row=None,\n plot_func=sns.lineplot, x='Eccentricity (deg)', y='Preferred period (deg)',\n yticks=[0, 1, 2], xticks=[0, 2, 4, 6, 8, 10], height=4, aspect=1,\n title='Preferred period', top=.85, pal=None, col_order=None, row_order=None,\n ylim=None, xlim=None, ci=68, col_wrap=None, pre_boot_gb_func=None,\n pre_boot_gb_cols=['subject', 'reference_frame', 'Stimulus type',\n 'bootstrap_num', 'Eccentricity (deg)'],\n facetgrid_legend=True, hue_kws={}, **kwargs):\n \"\"\"Create plot from feature_df\n\n This function takes the feature_df created by\n sfp.analyze_model.create_feature_df and makes summary plots. The\n default should do more or less what you want it to, but there's a\n lot of customizability.\n\n Note that this makes a non-polar plot (it plots y as a function of\n x), and so the intended use is for the preferred_period\n feature_df. For the preferred period and max amplitude contours, use\n feature_df_polar_plot\n\n The majority of the arguments are passed right to sns.FacetGrid\n\n There are two major choices for `plot_func`: `sns.lineplot` and\n `sfp.plotting.scatter_ci_dist`. The major difference is how they\n draw CIs:\n\n 1. `sns.lineplot` draws CIs by drawing its own bootstraps from the\n data present in the df. So if your df contains 12 independent\n subjects and you want to draw your CIs summarizing how these\n predictions differ across subjects, use this.\n\n 2. `sfp.plotting.scatter_ci_dist` draws CIs based on a distribution\n already in the df. That is, we assume you've already generated\n your bootstrapped distribution and want the plotting function to\n create the CIs based on the percentiles of the data already in\n the df. For example, we get 100 bootstrapped estimates of each\n voxels' response to the stimuli, and fit a model to each of these\n bootstraps separately. These bootstraps are *not* independent\n (they're generated by sampling from runs, which are), and so\n using `sns.lineplot` above to resample from them is\n inappropriate. Instead, `scatter_ci_dist` will create the CIs\n from the df directly.\n\n If you're using `scatter_ci_dist` for the intended purpose above,\n you probably want to add the following kwargs (which will get passed\n directly to `scatter_ci_dist`): `draw_ctr_pts=False, ci_mode='fill',\n join=True`.\n\n Parameters\n ----------\n feature_df : pd.DataFrame\n The feature dataframe, containing the preferred period as a\n function of eccentricity, at multiple stimulus orientation and\n retinotopic angles\n hue : str, optional\n a column in feature_df, which feature to use for the hue of plot\n col : str, optional\n a column in feature_df, which feature to facet on the columns\n row : str, optional\n a column in feature_df, which feature to facet on the rows\n plot_func : callable, optional\n The plot function to map on the FacetGrid. First two args should\n be x and y, should accept ci kwarg. Will call using\n map_dataframe. Note that different choices here will affects how\n we raw CIs, see above for more details\n x : str, optional\n a column in feature_df, which feature to plot on the x-axis\n y : str, optional\n a column in feature_df, which feature to plot on the y-axis\n {y, x}ticks : list, optional\n list of floats, which y- and x-ticks to include on the plot\n height : float, optional\n The height of each individual subplot\n aspect : float, optional\n The aspect ratio of each individual subplot\n title : str or None, optional\n The super-title of the plot. If None, we don't add a\n super-title, and we will not adjust the subplot spacing\n top : float, optional\n The amount to adjust the subplot spacing at the top so the title\n is above the subplots (with a call to\n g.fig.subplots_adjust(top=top)). If title is None, this is\n ignored.\n pal : palette name, list, dict, or None, optional\n palette to pass to sns.FacetGrid for specifying the colors to\n use. if None and hue==\"Stimulus type\", we use the defaults given\n by sfp.plotting.stimulus_type_palette.\n {col, row}_order : list or None, optional\n the order for the columns and rows. If None, we use the default\n {y, x}lim : tuples or None, optional\n if not None, the limits for the y- and x-axes for all subplots.\n ci : int, optional\n the size of the confidence intervals to plot. see the docstring\n of plot_func for more details\n col_wrap : int or None, optional\n 'wrap' the column variable at this width, so that the column\n facets span multiple rows. will throw an exception if col_wrap\n and row are both not None\n pre_boot_gb_func : str,, callable or None, optional\n feature_df contains a lot of info, and you may want to collapse\n over some of those dimensions. In order to make sure those\n dimensions are collapsed over appropriately, this function can\n perform an (optional) groupby before creating the FacetGrid. If\n this is not None, we will create the plot with\n feature_df.groupby(pre_boot_gb_cols).agg(pre_boot_gb_func).reset_index(). The\n intended use case is for, e.g., averaging over all retinotopic\n angles by setting this to 'mean'. See the docstring of\n pandas.groupby.agg for more info on possible arguments\n pre_boot_gb_cols : list, optional\n The columns to use for the optional groupby. See above for more\n details\n facetgrid_legend : bool, optional\n whether to use the `FacetGrid.add_legend` method to add a\n legend. if False, will not add a legend (and so you must do it\n yourself)\n hue_kws : dict, optional\n Other keyword arguments to insert into the plotting call to let other\n plot attributes vary across levels of the hue variable (e.g. the\n markers in a scatterplot).\n kwargs :\n passed to plot_func\n\n Returns\n -------\n g : sns.FacetGrid\n The FacetGrid containing the plot\n\n \"\"\"\n if pal is None and hue == 'Stimulus type':\n pal = stimulus_type_palette(feature_df.reference_frame.unique())\n if col_order is None and col == 'Stimulus type':\n col_order = stimulus_type_order(feature_df.reference_frame.unique())\n if row_order is None and row == 'Stimulus type':\n row_order = stimulus_type_order(feature_df.reference_frame.unique())\n if pre_boot_gb_func is not None:\n feature_df = feature_df.groupby(pre_boot_gb_cols).agg(pre_boot_gb_func).reset_index()\n # facetgrid seems to ignore the defaults for these, but we want to use them\n # so its consistent with other figures\n gridspec_kws = {k: mpl.rcParams[f'figure.subplot.{k}']\n for k in ['top', 'bottom', 'left', 'right']}\n g = sns.FacetGrid(feature_df, hue=hue, col=col, row=row, height=height, aspect=aspect,\n palette=pal, xlim=xlim, ylim=ylim, col_wrap=col_wrap, col_order=col_order,\n row_order=row_order, gridspec_kws=gridspec_kws, hue_kws=hue_kws)\n g.map_dataframe(plot_func, x, y, ci=ci, estimator=np.median, **kwargs)\n if col_wrap is not None:\n g_axes = g.axes\n # if col_wrap is not None, g.axes will be a single list of axes. we\n # want it to be a list of lists, where the i-th entry contains a list\n # with all axes in the i-th column\n g_axes = [g_axes[col_wrap*i:col_wrap*(i+1)] for i in range(len(g_axes)//col_wrap+1)]\n # drop any empty lists\n g_axes = [ax for ax in g_axes if len(ax) > 0]\n g._axes = np.array(g_axes)\n if facetgrid_legend:\n g.add_legend()\n for ax in g.axes.flatten():\n if ax.get_ylim()[0] < 0:\n ax.axhline(color='gray', linestyle='--')\n if ax.get_xlim()[0] < 0:\n ax.axvline(color='gray', linestyle='--')\n if yticks is not None:\n ax.set_yticks(yticks)\n if xticks is not None:\n ax.set_xticks(xticks)\n if title is not None:\n g.fig.suptitle(title)\n g.fig.subplots_adjust(top=top)\n if col == 'subject' and feature_df[col].nunique() == 1:\n g.set(title='')\n return g\n\n\ndef feature_df_polar_plot(feature_df, hue=\"Stimulus type\", col='Preferred period (deg)', row=None,\n plot_func=sns.lineplot, theta='Retinotopic angle (rad)',\n r='Eccentricity (deg)', r_ticks=None, theta_ticks=None, r_ticklabels=None,\n theta_ticklabels=None, all_tick_labels=[], height=4, aspect=1, title='Preferred period contours',\n top=.76, hspace=.3, wspace=.1, pal=None, col_order=None, row_order=None,\n title_position=[.5, 1.15], ylabelpad=30, legend_position=None, ylim=None,\n xlim=None, ci=68, col_wrap=None, pre_boot_gb_func=None,\n pre_boot_gb_cols=['subject', 'reference_frame', 'Stimulus type',\n 'Eccentricity (deg)'],\n facetgrid_legend=True, **kwargs):\n \"\"\"Create polar plot from feature_df\n\n This function takes the feature_df created by\n sfp.analyze_model.create_feature_df and makes summary plots. The\n default should do more or less what you want it to, but there's a\n lot of customizability.\n\n Note that this makes a polar plot (it plots r as a function of\n theta), and so the intended use is for the preferred period and max\n amplitude contours feature_df. For the preferred period, use\n feature_df_plot\n\n The majority of the arguments are passed right to sns.FacetGrid\n\n There are two major choices for `plot_func`: `sns.lineplot` and\n `sfp.plotting.scatter_ci_dist`. The major difference is how they\n draw CIs:\n\n 1. `sns.lineplot` draws CIs by drawing its own bootstraps from the\n data present in the df. So if your df contains 12 independent\n subjects and you want to draw your CIs summarizing how these\n predictions differ across subjects, use this.\n\n 2. `sfp.plotting.scatter_ci_dist` draws CIs based on a distribution\n already in the df. That is, we assume you've already generated\n your bootstrapped distribution and want the plotting function to\n create the CIs based on the percentiles of the data already in\n the df. For example, we get 100 bootstrapped estimates of each\n voxels' response to the stimuli, and fit a model to each of these\n bootstraps separately. These bootstraps are *not* independent\n (they're generated by sampling from runs, which are), and so\n using `sns.lineplot` above to resample from them is\n inappropriate. Instead, `scatter_ci_dist` will create the CIs\n from the df directly.\n\n Parameters\n ----------\n feature_df : pd.DataFrame\n The feature dataframe, containing the preferred period as a\n function of eccentricity, at multiple stimulus orientation and\n retinotopic angles\n hue : str, optional\n a column in feature_df, which feature to use for the hue of plot\n col : str, optional\n a column in feature_df, which feature to facet on the columns\n row : str, optional\n a column in feature_df, which feature to facet on the rows\n plot_func : callable, optional\n The plot function to map on the FacetGrid. First two args should\n be x and y, should accept ci kwarg. Will call using\n map_dataframe. Note that different choices here will affect how\n we create CIs, see above for more details\n theta : str, optional\n a column in feature_df, which feature to plot as polar angle\n r : str, optional\n a column in feature_df, which feature to plot as distance from\n the origin\n {r, theta}_ticks : list, optional\n list of floats, which r- and theta-ticks to include on the plot\n {r, theta}_ticklabels : list, optional\n list of floats/strs, which r- and theta-tick labels to include\n on the plot\n all_tick_labels : list, optional\n by default, sns.FacetGrid only puts tick labels on the bottom-\n and left-most facets. this works well for cartesian plots, but\n less well for polar ones. If you want to make sure that the tick\n labels are shown on each facet, include the axis here. possible\n values are: 'r', 'theta'. If list is empty, then we don't change\n anything\n height : float, optional\n The height of each individual subplot\n aspect : float, optional\n The aspect ratio of each individual subplot\n title : str or None, optional\n The super-title of the plot. If None, we don't add a\n super-title, and we will not adjust the subplot spacing\n top : float, optional\n The amount to adjust the subplot spacing at the top so the title\n is above the subplots (with a call to\n g.fig.subplots_adjust(top=top)). If title is None, this is\n ignored.\n hspace : float, optional\n the amount of height reserved for space between subplots,\n expressed as a fraction of the average axis width\n wspace : float, optional\n the amount of width reserved for space between subplots,\n expressed as a fraction of the average axis width\n pal : palette name, list, dict, or None, optional\n palette to pass to sns.FacetGrid for specifying the colors to\n use. if None and hue==\"Stimulus type\", we use the defaults given\n by sfp.plotting.stimulus_type_palette.\n {col, row}_order : list or None, optional\n the order for the columns and rows. If None, we use the default\n title_position : 2-tuple, optional\n The position (in x, y) of each subplots' title (not the\n super-title)\n ylabelpad : int\n number of pixels to \"pad\" the y-label by, so that it doesn't\n overlap with the polar plot\n legend_position : 2-tuple or None, optional\n if not None, the x, y position of the legend. if None, use\n default position\n {y, x}lim : tuples or None, optional\n if not None, the limits for the y- and x-axes for all subplots.\n ci : int, optional\n the size of the confidence intervals to plot. see the docstring\n of plot_func for more details\n col_wrap : int or None, optional\n 'wrap' the column variable at this width, so that the column\n facets span multiple rows. will throw an exception if col_wrap\n and row are both not None\n pre_boot_gb_func : callable or None, optional\n feature_df contains a lot of info, and you may want to collapse\n over some of those dimensions. In order to make sure those\n dimensions are collapsed over appropriately, this function can\n perform an (optional) groupby before creating the FacetGrid. If\n this is not None, we will create the plot with\n feature_df.groupby(pre_boot_gb_cols).agg(pre_boot_gb_func).reset_index(). The\n intended use case is for, e.g., averaging over all retinotopic\n angles by setting this to 'mean'. See the docstring of\n pandas.groupby.agg for more info on possible arguments\n pre_boot_gb_cols : list, optional\n The columns to use for the optional groupby. See above for more\n details\n facetgrid_legend : bool, optional\n whether to use the `FacetGrid.add_legend` method to add a\n legend. if False, will not add a legend (and so you must do it\n yourself)\n kwargs :\n passed to plot_func\n\n Returns\n -------\n g : sns.FacetGrid\n The FacetGrid containing the plot\n\n \"\"\"\n if pal is None and hue == 'Stimulus type':\n pal = stimulus_type_palette(feature_df.reference_frame.unique())\n if col_order is None and col == 'Stimulus type':\n col_order = stimulus_type_order(feature_df.reference_frame.unique())\n if row_order is None and row == 'Stimulus type':\n row_order = stimulus_type_order(feature_df.reference_frame.unique())\n if pre_boot_gb_func is not None:\n feature_df = feature_df.groupby(pre_boot_gb_cols).agg(pre_boot_gb_func).reset_index()\n # facetgrid seems to ignore the defaults for these, but we want to use them\n # so its consistent with other figures\n gridspec_kws = {k: mpl.rcParams[f'figure.subplot.{k}']\n for k in ['top', 'bottom', 'left', 'right']}\n g = sns.FacetGrid(feature_df, col=col, hue=hue, row=row, subplot_kws={'projection': 'polar'},\n despine=False, height=height, aspect=aspect, palette=pal, xlim=xlim,\n ylim=ylim, col_wrap=col_wrap, col_order=col_order, row_order=row_order,\n gridspec_kws=gridspec_kws)\n g.map_dataframe(plot_func, theta, r, ci=ci, estimator=np.median, **kwargs)\n if col_wrap is not None:\n g_axes = g.axes\n # if col_wrap is not None, g.axes will be a single list of axes. we\n # want it to be a list of lists, where the i-th entry contains a list\n # with all axes in the i-th column\n g_axes = [g_axes[col_wrap*i:col_wrap*(i+1)] for i in range(len(g_axes)//col_wrap+1)]\n # drop any empty lists\n g_axes = [ax for ax in g_axes if len(ax) > 0]\n g._axes = np.array(g_axes)\n for i, axes in enumerate(g.axes):\n for j, ax in enumerate(axes):\n ax.title.set_position(title_position)\n # we do this for all axes in the first column\n if j == 0:\n ax.yaxis.labelpad = ylabelpad\n if r_ticks is not None:\n ax.set_yticks(r_ticks)\n if r_ticklabels is not None:\n ax.set_yticklabels(r_ticklabels)\n if 'r' in all_tick_labels:\n ax.tick_params(labelleft=True)\n if theta_ticks is not None:\n ax.set_xticks(theta_ticks)\n if theta_ticklabels is not None:\n ax.set_xticklabels(theta_ticklabels)\n if 'theta' in all_tick_labels:\n ax.tick_params(labelbottom=True)\n if facetgrid_legend:\n if legend_position is not None:\n g.add_legend(bbox_to_anchor=legend_position)\n else:\n g.add_legend()\n if title is not None:\n g.fig.suptitle(title)\n g.fig.subplots_adjust(top=top)\n g.fig.subplots_adjust(hspace=hspace, wspace=wspace)\n return g\n\n\ndef flat_cortex_plot(freesurfer_sub, plot_property, output_path=None, mask=None):\n \"\"\"Create a plot of a property on a flattened view of the cortical surface\n\n I'm not aware of an easy scriptable way to create 3d plots of the\n cortex from a consistent viewpoint, but, since we only care about\n primary visual cortex, a flattened view of the cortical surface\n works pretty well. This function uses Noah Benson's neuropythy\n library to plot a property on top of the cortical surface of both\n hemispheres, flattened to a circle, from both posterior and anterior\n views.\n\n Parameters\n ----------\n freesurfer_sub : str\n The freesurfer subject to use. This can be either the name\n (e.g., wlsubj045; in which case the environmental variable\n SUBJECTS_DIR must be set) or a path to the freesurfer folder. It\n will be passed directly to neuropythy.freesurfer_subject, so see\n the docstring of that function for more details\n plot_property : str or dict\n The property to plot as an overlay on the flattened cortical\n surface. This can either be a str, in which case it's a property\n of the subject, coming from surfaces already found in the\n freesurfer folder, or a dictionary of arrays (with keys lh, rh)\n containing the labels of the property.\n output_path : str or None, optional\n if not None, the path to save the resulting figure at. If None,\n will not save\n mask : tuple or None, optional\n a mask to restrict the values of the property plotted. it should\n be a 2-tuple, where the first value is a str giving the property\n to restrict, and the second is a list giving the values to\n restrict to (e.g., `('varea', [1,2,3])`). see\n neuropythy.cortex_plot's docstring for more details. If None,\n will plot everything\n\n \"\"\"\n sub = ny.freesurfer_subject(freesurfer_sub)\n if isinstance(plot_property, dict):\n if len(plot_property) != 2:\n raise Exception(\"plot_property must either be a str or a dict with left and right \"\n \"hemis, but plot_property has %s items!\" % len(plot_property))\n property_data = plot_property\n plot_property = 'plot_property'\n lh = sub.lh.with_prop(plot_property=property_data['lh'])\n rh = sub.rh.with_prop(plot_property=property_data['rh'])\n else:\n lh = sub.lh\n rh = sub.rh\n\n # prepare to create a flat map of the posterior and anterior views\n # of the brain\n map_projs_post = {h: ny.map_projection('occipital_pole', h, radius=np.pi/2)\n for h in ['lh', 'rh']}\n map_projs_ante = {h: mp.copy(center=-mp.center, center_right=-mp.center_right)\n for h, mp in map_projs_post.items()}\n # flatten the surfaces\n flat_maps = [map_projs_post['lh'](lh), map_projs_post['rh'](rh),\n map_projs_ante['lh'](lh), map_projs_ante['rh'](rh)]\n\n fig, axes = plt.subplots(2, 2, figsize=(7.5, 7.5), dpi=72*4)\n for ax, m in zip(axes.flatten(), flat_maps):\n ny.cortex_plot(m, axes=ax, color=plot_property, cmap='hot', mask=mask)\n ax.axis('off')\n fig.subplots_adjust(0, 0, 1, 1, 0, 0)\n if output_path is not None:\n fig.savefig(output_path)\n return fig\n\n\ndef voxel_property_plot(first_level_df, plot_property='precision', figsize=(10, 10),\n df_filter_string='drop_voxels_with_any_negative_amplitudes,drop_voxels_near_border'):\n \"\"\"Plot a voxel property (as size and color) on polar plot.\n\n Must be a property that each voxel has a unique value for (like precision);\n if it's a property that voxel shav emultiple values for (like\n amplitude_estimate), this plot will be misleading, because we drop all rows\n that have duplicate values for voxel\n\n df_filter_string can be used to filter the voxels we examine, so\n that we look only at those voxels that the model was fit to\n\n Parameters\n ----------\n first_level_df : pd.DataFrame\n DataFrame containing the outputs of first level analysis. Contains\n voxels with their angle, eccentricity, and several properties\n plot_property : str, optional\n str with the voxel property to plot. must be a column in first_level_df\n figsize : tuple, optional\n size of the plot to create\n df_filter_string : str or None, optional\n a str specifying how to filter the voxels in the dataset. see\n the docstrings for sfp.model.FirstLevelDataset and\n sfp.model.construct_df_filter for more details. If None, we\n won't filter. Should probably use the default, which is what all\n models are trained using.\n\n Returns\n -------\n fig : plt.figure\n matplotlib figure containing thhe plot\n\n \"\"\"\n if df_filter_string is not None:\n df_filter = sfp_model.construct_df_filter(df_filter_string)\n first_level_df = df_filter(first_level_df).reset_index()\n voxels = first_level_df.drop_duplicates('voxel')\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111, projection='polar')\n size = voxels[plot_property].values.copy()\n while size.max() < 50:\n size *= 10\n c = ax.scatter(voxels.angle.values, voxels.eccen.values,\n c=voxels[plot_property].values,\n alpha=.75, s=size)\n ax.set(ylim=(0, 12.5))\n plt.colorbar(c)\n return fig\n\n\ndef voxel_property_joint(first_level_df, plot_kind='hex',\n plot_properties=['eccen', 'precision'],\n df_filter_string='drop_voxels_with_any_negative_amplitudes,drop_voxels_near_border',\n **kwargs):\n \"\"\"Plot a joint distribution plot (sns.jointplot) of two voxel properties.\n\n Must be a property that each voxel has a unique value for (like precision);\n if it's a property that voxel shav emultiple values for (like\n amplitude_estimate), this plot will be misleading, because we drop all rows\n that have duplicate values for voxel\n\n df_filter_string can be used to filter the voxels we examine, so\n that we look only at those voxels that the model was fit to\n\n Parameters\n ----------\n first_level_df : pd.DataFrame\n DataFrame containing the outputs of first level analysis. Contains\n voxels with their angle, eccentricity, and several properties\n plot_properties : list, optional\n list of strs, each of which is a the voxel property to plot and thus\n must be a column in first_level_df\n plot_kind : str, optional\n type of plot to use for joint plot. see sns.jointplot docstring for\n details\n df_filter_string : str or None, optional\n a str specifying how to filter the voxels in the dataset. see\n the docstrings for sfp.model.FirstLevelDataset and\n sfp.model.construct_df_filter for more details. If None, we\n won't filter. Should probably use the default, which is what all\n models are trained using.\n kwargs :\n passed to sns.jointplot\n\n Returns\n -------\n g : sns.JointGrid\n JointGrid containing the figure with the plot\n\n \"\"\"\n if df_filter_string is not None:\n df_filter = sfp_model.construct_df_filter(df_filter_string)\n first_level_df = df_filter(first_level_df).reset_index()\n voxels = first_level_df.drop_duplicates('voxel')\n g = sns.jointplot(x=plot_properties[0], y=plot_properties[1], data=voxels,\n kind=plot_kind, **kwargs)\n return g\n\n\ndef _parse_save_path_for_kwargs(save_path):\n kwargs = dict(i.split('=') for i in save_path.split('_'))\n # we know all are ints\n return dict(({'bootstrap': 'bootstrap_num'}.get(k, k), int(v)) for k, v in kwargs.items())\n\n\nif __name__ == '__main__':\n class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter):\n pass\n parser = argparse.ArgumentParser(\n formatter_class=CustomFormatter,\n description=(\"Creates the descriptive plots for one first level results dataframe\")\n )\n parser.add_argument(\"dataframe_path\",\n help=(\"path to first level results or tuning curves dataframe. we'll \"\n \"attempt to find the other dataframe as well.\"))\n parser.add_argument(\"stim_dir\", help=\"path to directory containing stimuli\")\n parser.add_argument(\"--plot_to_make\", default=None, nargs='*',\n help=(\"Which plots to create. If none, will create all. Possible options: \"\n \"localsf (plotting.local_spatial_frequency), stim_prop (plotting.\"\n \"stimuli_properties), data (plotting.plot_data), \"\n \"tuning_curves_check_varea={v}[_bootstrap={b:02d}] (plotting.\"\n \"check_tuning_curves; requires tuning curve dataframe), \"\n \"hypotheses_data_varea={v} (plotting.check_hypotheses_with_data; \"\n \"requires tuning curve dataframe), or tuning_params \"\n \"(plotting.tuning_params; requires tuning curve dataframe)\"))\n args = vars(parser.parse_args())\n d = utils.create_data_dict(args['dataframe_path'], args['stim_dir'])\n first_level_save_stem = d['df_filename'].replace('.csv', '')\n if 'tuning_df' in d.keys():\n tuning_save_stem = d['tuning_df_filename'].replace('.csv', '')\n tuning_df_present = True\n else:\n tuning_df_present = False\n if args['plot_to_make'] is None:\n local_spatial_frequency(d['df'], first_level_save_stem+\"_localsf.svg\")\n stimuli_properties(d['df'], first_level_save_stem+\"_stim_prop.svg\")\n plot_data(d['df'], save_path=first_level_save_stem+'_data.svg')\n if tuning_df_present:\n check_tuning_curves(d['tuning_df'], tuning_save_stem+\"_tuning_curves_check_%s.svg\")\n check_hypotheses_with_data(d['tuning_df'], tuning_save_stem+\"_hypotheses_data_%s.svg\")\n tuning_params(d['tuning_df'], tuning_save_stem+\"_tuning_params.svg\")\n else:\n warnings.warn(\"Unable to create tuning curves, hypotheses check, or tuning param plots\"\n \" because tuning curve df hasn't been created!\")\n else:\n for p in args['plot_to_make']:\n if 'localsf' == p:\n local_spatial_frequency(d['df'], first_level_save_stem+\"_localsf.svg\")\n elif 'stim_prop' == p:\n stimuli_properties(d['df'], first_level_save_stem+\"_stim_prop.svg\")\n elif 'tuning_curves_check' in p:\n if tuning_df_present:\n p_kwargs = _parse_save_path_for_kwargs(p.replace('tuning_curves_check_', ''))\n check_tuning_curves(d['tuning_df'], tuning_save_stem+\"_tuning_curves_check_%s.svg\",\n **p_kwargs)\n else:\n raise Exception(\"Unable to create tuning curves plot because tuning curve df \"\n \"hasn't been created!\")\n elif 'data' == p:\n plot_data(d['df'], save_path=first_level_save_stem+'_data.svg')\n elif 'hypotheses_data' in p:\n if tuning_df_present:\n p_kwargs = _parse_save_path_for_kwargs(p.replace('hypotheses_data_', ''))\n check_hypotheses_with_data(d['tuning_df'], tuning_save_stem+\"_hypotheses_data_%s.svg\",\n **p_kwargs)\n else:\n raise Exception(\"Unable to create hypotheses check with data plot because \"\n \"tuning curve df hasn't been created!\")\n elif 'tuning_params' == p:\n if tuning_df_present:\n tuning_params(d['tuning_df'], tuning_save_stem+\"_tuning_params.svg\")\n else:\n raise Exception(\"Unable to create tuning params plot because \"\n \"tuning curve df hasn't been created!\")\n else:\n raise Exception(\"Don't know how to make plot %s!\" % p)\n",
"#!/usr/bin/python\n\"\"\"fit tuning curves to first level results\n\"\"\"\nimport matplotlib as mpl\n# we do this because sometimes we run this without an X-server, and this backend doesn't need\n# one. We set warn=False because the notebook uses a different backend and will spout out a big\n# warning to that effect; that's unnecessarily alarming, so we hide it.\nmpl.use('svg', warn=False)\nimport argparse\nimport warnings\nimport os\nimport json\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom scipy import optimize\nimport numpy as np\n\n\ndef log_norm_pdf(x, a, mode, sigma):\n \"\"\"the pdf of the log normal distribution, with a scale factor\n \"\"\"\n # note that mode here is the actual mode, for us, the peak spatial frequency. this differs from\n # the 2d version we have, where we we have np.log2(x)+np.log2(p), so that p is the inverse of\n # the preferred period, the ivnerse of the mode / the peak spatial frequency.\n pdf = a * np.exp(-(np.log2(x)-np.log2(mode))**2/(2*sigma**2))\n return pdf\n\n\ndef get_tuning_curve_xy(a, mode, sigma, x=None, norm=False):\n if x is None:\n x = np.logspace(-20, 20, 20000, base=2)\n y = log_norm_pdf(x, a, mode, sigma)\n if norm:\n y /= y.max()\n return x, y\n\n\ndef get_tuning_curve_xy_from_df(df, x=None, norm=False):\n \"\"\"given a dataframe with one associated tuning curve, return x and y of that tuning curve\n \"\"\"\n params = {'x': x}\n for param, param_label in [('a', 'tuning_curve_amplitude'), ('mode', 'tuning_curve_peak'),\n ('sigma', 'tuning_curve_sigma')]:\n if df[param_label].nunique() > 1:\n raise Exception(\"Only one tuning curve can be described in df \\n%s!\" % df)\n params[param] = df[param_label].unique()[0]\n return get_tuning_curve_xy(norm=norm, **params)\n\n\ndef log_norm_describe_full(a, mode, sigma):\n \"\"\"calculate and return many descriptions of the log normal distribution\n\n returns the bandwidth (in octaves), low and high half max values of log normal\n curve, inf_warning, x and y.\n\n inf_warning is a boolean which indicates whether we calculate the variance to be infinite. this\n happens when the mode is really small as the result of an overflow and so you should probably\n examine this curve to make sure things are okay\n\n x and y are arrays of floats so you can plot the tuning curve over a reasonable range.\n \"\"\"\n mu = np.log(mode) + sigma**2\n # we compute this because the std dev is always larger than the bandwidth, so we can use this\n # to make sure we grab the right patch of x values\n var = (np.exp(sigma**2) - 1) * (np.exp(2*mu + sigma**2))\n inf_warning = False\n if np.isinf(var):\n # if the peak of the curve would be at a *really* low or *really* high value, the variance\n # will be infinite (not really, but because of computational issues) and so we need to\n # handle it separately. this really shouldn't happen anymore, since I've constrained the\n # bounds of the mode\n if np.log2(mode) < 0:\n x = np.logspace(-300, 100, 100000, base=2)\n else:\n x = np.logspace(-100, 300, 100000, base=2)\n inf_warning = True\n else:\n xmin, xmax = np.floor(np.log2(mode) - 5*sigma), np.ceil(np.log2(mode) + 5*sigma)\n x = np.logspace(xmin, xmax, 1000*(xmax - xmin), base=2)\n x, y = get_tuning_curve_xy(a, mode, sigma, x)\n half_max_idx = abs(y - (y.max() / 2.)).argsort()\n if (not (x[half_max_idx[0]] > mode and x[half_max_idx[1]] < mode) and\n not (x[half_max_idx[0]] < mode and x[half_max_idx[1]] > mode)):\n print(a, mode, sigma)\n raise Exception(\"Something went wrong with bandwidth calculation! halfmax x values %s and\"\n \" %s must lie on either side of max %s!\" % (x[half_max_idx[0]],\n x[half_max_idx[1]], mode))\n low_half_max = np.min(x[half_max_idx[:2]])\n high_half_max = np.max(x[half_max_idx[:2]])\n bandwidth = np.log2(high_half_max) - np.log2(low_half_max)\n return bandwidth, low_half_max, high_half_max, inf_warning, x, y\n\n\ndef create_problems_report(fit_problems, inf_problems, save_path):\n \"\"\"create html report showing problem cases\n \"\"\"\n plots_save_path = os.path.join(save_path.replace('.html', '') + \"_report_plots\", \"plot%03d.svg\")\n if not os.path.isdir(os.path.dirname(plots_save_path)):\n os.makedirs(os.path.dirname(plots_save_path))\n with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'report_templates.json')) as f:\n report_template_strs = json.load(f)\n report_text = report_template_strs['HEAD']\n for title, problems in zip([\"fitting curves\", \"finding bandwidths\"],\n [fit_problems, inf_problems]):\n report_text += \"<h2>Those cases that had problems %s</h2>\" % title\n for i, (labels, (x, y), (datax, datay)) in enumerate(problems):\n report_text += labels.style.render()\n plt.scatter(datax, datay)\n plt.semilogx(x, y, basex=2)\n plt.savefig(plots_save_path % i)\n plt.close()\n report_text += report_template_strs['FIGURE'] % (plots_save_path % i)\n report_text += report_template_strs['TAIL']\n with open(save_path, 'w') as f:\n f.write(report_text)\n\n\n# add bounds to the command line?\ndef main(df, save_path=None, mode_bounds=(2**(-5), 2**11), ampl_bounds=(0, 10),\n sigma_bounds=(0, 10)):\n \"\"\"fit tuning curve to first level results dataframe\n\n note that your mode_bounds are stimuli dependent. for the log-normal stimuli (for either the\n pilot or regular stimuli), the default value above works well. for the constant stimuli,\n (2**(-15), 2**8) seems to work\n \"\"\"\n if 'bootstrap_num' in df.columns:\n additional_cols = ['bootstrap_num']\n else:\n additional_cols = []\n df = df.rename(columns={'amplitude_estimate_median': 'amplitude_estimate'})\n melt_cols = ['varea', 'eccen', 'amplitude_estimate', 'stimulus_superclass',\n 'freq_space_angle', 'baseline'] + additional_cols\n df = df[['freq_space_distance', 'local_sf_magnitude'] + melt_cols]\n df = pd.melt(df, melt_cols, var_name='frequency_type', value_name='frequency_value')\n gb_columns = ['varea', 'eccen', 'stimulus_superclass', 'frequency_type'] + additional_cols\n gb = df.groupby(gb_columns)\n tuning_df = []\n fit_problems, inf_problems = [], []\n for n, g in gb:\n # we want a sense of where this is, in order to figure out if it stalled out.\n str_labels = \", \".join(\"%s: %s\" % i for i in zip(gb_columns, n))\n print(\"\\nCreating tuning curves for: %s\" % str_labels)\n fit_warning = False\n if 'mixtures' in n or 'off-diagonal' in n or 'baseline' in n:\n # then these points all have the same frequency and so we can't fit a frequency tuning\n # curve to them\n continue\n values_to_fit = zip(g.frequency_value.values, g.amplitude_estimate.values)\n # in python2, zip returned a list. in python3, it returns an iterable. we don't actually\n # want to iterate through it here, just index into it, so we convert it to a list\n values_to_fit = list(zip(*sorted(values_to_fit, key=lambda pair: pair[0])))\n fit_success = False\n maxfev = 100000\n tol = 1.5e-08\n while not fit_success:\n try:\n mode_guess = np.log(np.mean(values_to_fit[0]))\n if mode_guess < mode_bounds[0]:\n mode_guess = 1\n popt, _ = optimize.curve_fit(log_norm_pdf, values_to_fit[0], values_to_fit[1],\n maxfev=maxfev, ftol=tol, xtol=tol,\n p0=[1, mode_guess, 1],\n # optimize.curve_fit needs to be able to take the\n # len(bounds), and zips have no length\n bounds=list(zip(ampl_bounds, mode_bounds, sigma_bounds)))\n fit_success = True\n except RuntimeError:\n fit_warning = True\n maxfev *= 10\n tol /= np.sqrt(10)\n # popt contains a, mode, and sigma, in that order\n bandwidth, lhm, hhm, inf_warning, x, y = log_norm_describe_full(popt[0], popt[1], popt[2])\n tuning_df.append(g.assign(tuning_curve_amplitude=popt[0], tuning_curve_peak=popt[1],\n tuning_curve_sigma=popt[2], preferred_period=1./popt[1],\n tuning_curve_bandwidth=bandwidth, high_half_max=hhm, low_half_max=lhm,\n fit_warning=fit_warning, inf_warning=inf_warning, tol=tol, maxfev=maxfev,\n mode_bound_lower=mode_bounds[0], mode_bound_upper=mode_bounds[1]))\n warning_cols = gb_columns + ['tol', 'maxfev', 'tuning_curve_amplitude',\n 'tuning_curve_sigma', 'tuning_curve_peak',\n 'tuning_curve_bandwidth']\n if fit_warning:\n warnings.warn('Fit not great for:\\n%s' % str_labels.replace(', ', '\\n'))\n fit_problems.append((pd.DataFrame(tuning_df[-1][warning_cols].iloc[0]).T, (x, y),\n (g.frequency_value.values, g.amplitude_estimate.values)))\n if inf_warning:\n inf_problems.append((pd.DataFrame(tuning_df[-1][warning_cols].iloc[0]).T, (x, y),\n (g.frequency_value.values, g.amplitude_estimate.values)))\n tuning_df = pd.concat(tuning_df).reset_index(drop=True)\n if save_path is not None:\n tuning_df.to_csv(save_path, index=False)\n report_save_path = save_path.replace('.csv', '_problems.html')\n else:\n report_save_path = \"tuning_curve_problems.html\"\n if len(fit_problems) > 0 or len(inf_problems) > 0:\n create_problems_report(fit_problems, inf_problems, report_save_path)\n return tuning_df\n\n\nif __name__ == '__main__':\n class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter):\n pass\n parser = argparse.ArgumentParser(\n description=(\"Load in first level results DataFrame and create the tuning curves that \"\n \"summarize them, saving the resulting parameters in a new dataframe that can \"\n \"be used to easily plot the results. Will also create an html report showing \"\n \"any curves that had problems fitting.\"),\n formatter_class=CustomFormatter)\n parser.add_argument(\"first_level_results_path\",\n help=(\"Path to the first level results dataframe containing the data to \"\n \"fit.\"))\n parser.add_argument(\"save_path\",\n help=(\"Path to save the resulting tuning dataframe at. The problems report\"\n \", if created, will be at the same path, with '.csv' replaced by \"\n \"'_problems.html\"))\n args = vars(parser.parse_args())\n df = pd.read_csv(args.pop('first_level_results_path'))\n # bounds should be task-dependent, task-sfp and task-sfprescaled have the same frequency\n # information\n if ('task-sfp' in args['save_path'].split('_') or\n 'task-sfprescaled' in args['save_path'].split('_')):\n bounds = (2**(-5), 2**11)\n elif 'task-sfpconstant' in args['save_path'].split('_'):\n bounds = (2**(-15), 2**8)\n main(df, args['save_path'], mode_bounds=bounds)\n"
] | [
[
"matplotlib.pyplot.imshow",
"pandas.Series",
"numpy.linspace",
"numpy.sqrt",
"numpy.asarray",
"matplotlib.pyplot.plot",
"numpy.round",
"numpy.arctan2",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.tight_layout",
"numpy.arange",
"numpy.sin",
"numpy.ceil",
"numpy.interp",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots_adjust",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.log",
"numpy.median",
"numpy.log10",
"matplotlib.pyplot.fill_between",
"numpy.array",
"numpy.log2",
"matplotlib.colors.Normalize.__init__",
"matplotlib.use",
"matplotlib.pyplot.subplots",
"numpy.percentile",
"numpy.ones",
"matplotlib.pyplot.colorbar",
"sklearn.linear_model.LinearRegression",
"numpy.vstack"
],
[
"numpy.log",
"numpy.log2",
"pandas.concat",
"numpy.sqrt",
"matplotlib.pyplot.scatter",
"numpy.min",
"numpy.logspace",
"matplotlib.use",
"matplotlib.pyplot.semilogx",
"matplotlib.pyplot.savefig",
"pandas.DataFrame",
"numpy.max",
"numpy.mean",
"pandas.melt",
"matplotlib.pyplot.close",
"numpy.exp",
"numpy.isinf"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
dkurt/nncf | [
"1329d9b13cab84e45064a064e59b8f2c7e52d140",
"1329d9b13cab84e45064a064e59b8f2c7e52d140"
] | [
"examples/tensorflow/common/object_detection/architecture/darknet.py",
"nncf/tensorflow/pruning/filter_pruning/algorithm.py"
] | [
"\"\"\"\n Copyright (c) 2022 Intel Corporation\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nfrom examples.tensorflow.common.object_detection.architecture import nn_ops\n\n\nclass CSPDarknet53:\n \"\"\"Class to build CSPDarknet53\"\"\"\n\n def mish(self, x):\n return x * K.tanh(K.softplus(x))\n\n def DarknetConv2D_BN_Mish(self, *args, **kwargs):\n \"\"\"Darknet Convolution2D followed by SyncBatchNormalization and Mish.\"\"\"\n no_bias_kwargs = {'use_bias': False}\n no_bias_kwargs.update(kwargs)\n return nn_ops.compose(\n nn_ops.DarknetConv2D(*args, **no_bias_kwargs),\n tf.keras.layers.experimental.SyncBatchNormalization(),\n tf.keras.layers.Activation(self.mish))\n\n def csp_resblock_body(self, x, num_filters, num_blocks, all_narrow=True):\n \"\"\"A series of resblocks starting with a downsampling Convolution2D\"\"\"\n # Darknet uses left and top padding instead of 'same' mode\n x = tf.keras.layers.ZeroPadding2D(((1,0),(1,0)))(x)\n x = self.DarknetConv2D_BN_Mish(num_filters, (3,3), strides=(2,2))(x)\n\n res_connection = self.DarknetConv2D_BN_Mish(num_filters//2 if all_narrow else num_filters, (1,1))(x)\n x = self.DarknetConv2D_BN_Mish(num_filters//2 if all_narrow else num_filters, (1,1))(x)\n\n for _ in range(num_blocks):\n y = nn_ops.compose(\n self.DarknetConv2D_BN_Mish(num_filters//2, (1,1)),\n self.DarknetConv2D_BN_Mish(num_filters//2 if all_narrow else num_filters, (3,3)))(x)\n x = tf.keras.layers.Add()([x,y])\n\n x = self.DarknetConv2D_BN_Mish(num_filters//2 if all_narrow else num_filters, (1,1))(x)\n x = tf.keras.layers.Concatenate()([x , res_connection])\n\n return self.DarknetConv2D_BN_Mish(num_filters, (1,1))(x)\n\n def __call__(self, x):\n \"\"\"CSPDarknet53 body having 52 Convolution2D layers\"\"\"\n x = self.DarknetConv2D_BN_Mish(32, (3,3))(x)\n x = self.csp_resblock_body(x, 64, 1, False)\n x = self.csp_resblock_body(x, 128, 2)\n x = self.csp_resblock_body(x, 256, 8)\n x = self.csp_resblock_body(x, 512, 8)\n x = self.csp_resblock_body(x, 1024, 4)\n return x\n",
"\"\"\"\n Copyright (c) 2022 Intel Corporation\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nfrom math import floor\nfrom typing import Dict, List, Set\n\nimport tensorflow as tf\n\nfrom nncf import NNCFConfig\nfrom nncf.api.compression import CompressionLoss\nfrom nncf.common.graph import NNCFGraph\nfrom nncf.common.graph import NNCFNodeName\nfrom nncf.common.initialization.batchnorm_adaptation import BatchnormAdaptationAlgorithm\nfrom nncf.common.pruning.clusterization import Cluster\nfrom nncf.common.pruning.clusterization import Clusterization\nfrom nncf.common.pruning.mask_propagation import MaskPropagationAlgorithm\nfrom nncf.common.pruning.schedulers import PRUNING_SCHEDULERS\nfrom nncf.common.pruning.schedulers import PruningScheduler\nfrom nncf.common.pruning.statistics import FilterPruningStatistics\nfrom nncf.common.pruning.statistics import PrunedModelStatistics\nfrom nncf.common.pruning.utils import calculate_in_out_channels_in_uniformly_pruned_model\nfrom nncf.common.pruning.utils import calculate_in_out_channels_by_masks\nfrom nncf.common.pruning.utils import count_filters_num\nfrom nncf.common.pruning.utils import count_flops_and_weights\nfrom nncf.common.pruning.utils import count_flops_and_weights_per_node\nfrom nncf.common.pruning.utils import get_cluster_next_nodes\nfrom nncf.common.pruning.utils import get_conv_in_out_channels\nfrom nncf.common.pruning.utils import get_rounded_pruned_element_number\nfrom nncf.common.statistics import NNCFStatistics\nfrom nncf.common.pruning.statistics import PrunedModelTheoreticalBorderline\nfrom nncf.common.utils.debug import is_debug\nfrom nncf.common.utils.logger import logger as nncf_logger\nfrom nncf.common.schedulers import StubCompressionScheduler\nfrom nncf.common.accuracy_aware_training.training_loop import ADAPTIVE_COMPRESSION_CONTROLLERS\nfrom nncf.config.extractors import extract_bn_adaptation_init_params\nfrom nncf.tensorflow.algorithm_selector import TF_COMPRESSION_ALGORITHMS\nfrom nncf.tensorflow.graph.metatypes.common import GENERAL_CONV_LAYER_METATYPES\nfrom nncf.tensorflow.graph.metatypes.common import LINEAR_LAYER_METATYPES\nfrom nncf.tensorflow.graph.metatypes.matcher import get_keras_layer_metatype\nfrom nncf.tensorflow.graph.utils import collect_wrapped_layers\nfrom nncf.tensorflow.graph.utils import get_original_name_and_instance_idx\nfrom nncf.tensorflow.graph.utils import unwrap_layer\nfrom nncf.tensorflow.tensor import TFNNCFTensor\nfrom nncf.tensorflow.pruning.tensor_processor import TFNNCFPruningTensorProcessor\nfrom nncf.tensorflow.layers.data_layout import get_input_channel_axis\nfrom nncf.tensorflow.layers.wrapper import NNCFWrapper\nfrom nncf.tensorflow.loss import TFZeroCompressionLoss\nfrom nncf.tensorflow.tensor_statistics.collectors import TFNNCFCollectorTensorProcessor\nfrom nncf.tensorflow.pruning.base_algorithm import BasePruningAlgoBuilder\nfrom nncf.tensorflow.pruning.base_algorithm import BasePruningAlgoController\nfrom nncf.tensorflow.pruning.base_algorithm import PrunedLayerInfo\nfrom nncf.tensorflow.pruning.operations import TF_PRUNING_OPERATOR_METATYPES\nfrom nncf.tensorflow.pruning.operations import TFConvolutionPruningOp\nfrom nncf.tensorflow.pruning.operations import TFElementwisePruningOp\nfrom nncf.tensorflow.pruning.operations import TFTransposeConvolutionPruningOp\nfrom nncf.tensorflow.pruning.filter_pruning.functions import calculate_binary_mask\nfrom nncf.tensorflow.pruning.filter_pruning.functions import FILTER_IMPORTANCE_FUNCTIONS\nfrom nncf.tensorflow.pruning.filter_pruning.functions import tensor_l2_normalizer\nfrom nncf.tensorflow.pruning.utils import broadcast_filter_mask\nfrom nncf.tensorflow.pruning.utils import get_filter_axis\nfrom nncf.tensorflow.pruning.utils import get_filters_num\nfrom nncf.tensorflow.pruning.utils import is_valid_shape\nfrom nncf.tensorflow.sparsity.magnitude.operation import BinaryMask\n\n\n@TF_COMPRESSION_ALGORITHMS.register('filter_pruning')\nclass FilterPruningBuilder(BasePruningAlgoBuilder):\n \"\"\"\n Determines which modifications should be made to the original model in\n order to enable filter pruning during fine-tuning.\n \"\"\"\n\n def _build_controller(self, model: tf.keras.Model):\n return FilterPruningController(model,\n self._graph,\n self._op_names,\n self._prunable_types,\n self._pruned_layer_groups_info,\n self.config)\n\n def _is_pruned_layer(self, layer: tf.keras.layers.Layer) -> bool:\n # Currently prune only Convolutions\n return layer.__class__.__name__ in self._prunable_types\n\n def _get_op_types_of_pruned_layers(self) -> List[str]:\n return [op_name for meta_op in [TFConvolutionPruningOp, TFTransposeConvolutionPruningOp]\n for op_name in meta_op.get_all_op_aliases()]\n\n def _get_types_of_grouping_ops(self) -> List[str]:\n return TFElementwisePruningOp.get_all_op_aliases()\n\n\n@ADAPTIVE_COMPRESSION_CONTROLLERS.register('tf_filter_pruning')\nclass FilterPruningController(BasePruningAlgoController):\n \"\"\"\n Serves as a handle to the additional modules, parameters and hooks inserted\n into the original uncompressed model to enable filter pruning.\n \"\"\"\n\n def __init__(self,\n target_model: tf.keras.Model,\n graph: NNCFGraph,\n op_names: List[str],\n prunable_types: List[str],\n pruned_layer_groups: Clusterization[PrunedLayerInfo],\n config: NNCFConfig):\n super().__init__(target_model, op_names, prunable_types, pruned_layer_groups, config)\n self._original_graph = graph\n params = self.pruning_config.get('params', {})\n self.frozen = False\n self.pruning_quota = 0.9\n\n self._nodes_flops = {} # type: Dict[NNCFNodeName, int]\n self._nodes_params_num = {} # type: Dict[NNCFNodeName, int]\n self._layers_in_channels = {}\n self._layers_out_channels = {}\n self._layers_in_shapes = {}\n self._layers_out_shapes = {}\n self._pruning_quotas = {}\n self._next_nodes = {}\n self._init_pruned_layers_params()\n self._flops_count_init()\n self.full_flops = sum(self._nodes_flops.values())\n self.current_flops = self.full_flops\n self.full_params_num = sum(self._nodes_params_num.values())\n self.current_params_num = self.full_params_num\n self.full_filters_num = count_filters_num(self._original_graph, GENERAL_CONV_LAYER_METATYPES)\n self.current_filters_num = self.full_filters_num\n self._pruned_layers_num = len(self._pruned_layer_groups_info.get_all_nodes())\n self._prunable_layers_num = len(self._original_graph.get_nodes_by_types(self._prunable_types))\n self._max_prunable_flops, self._max_prunable_params = \\\n self._calculate_flops_and_weights_in_uniformly_pruned_model(1.)\n\n self._weights_normalizer = tensor_l2_normalizer # for all weights in common case\n self._filter_importance = FILTER_IMPORTANCE_FUNCTIONS.get(params.get('filter_importance', 'L2'))\n self.all_weights = params.get('all_weights', False)\n scheduler_cls = PRUNING_SCHEDULERS.get(params.get('schedule', 'exponential'))\n self._scheduler = scheduler_cls(self, params)\n self._bn_adaptation = None\n self.set_pruning_level(self.pruning_init)\n self._loss = TFZeroCompressionLoss()\n\n @property\n def scheduler(self) -> PruningScheduler:\n return self._scheduler\n\n @property\n def loss(self) -> CompressionLoss:\n return self._loss\n\n @property\n def compression_rate(self) -> float:\n if self.prune_flops:\n return 1 - self.current_flops / self.full_flops\n return self.pruning_rate\n\n @compression_rate.setter\n def compression_rate(self, compression_rate: float) -> None:\n is_pruning_controller_frozen = self.frozen\n self.freeze(False)\n self.set_pruning_level(compression_rate)\n self.freeze(is_pruning_controller_frozen)\n\n def disable_scheduler(self):\n self._scheduler = StubCompressionScheduler()\n self._scheduler.current_pruning_level = 0.0\n\n def statistics(self, quickly_collected_only: bool = False) -> NNCFStatistics:\n if not quickly_collected_only and is_debug():\n stats = PrunedModelTheoreticalBorderline(\n self._pruned_layers_num, self._prunable_layers_num, self._max_prunable_flops,\n self._max_prunable_params, self.full_flops, self.full_params_num)\n\n nncf_logger.debug(stats.to_str())\n\n pruned_layers_summary = self._calculate_pruned_layers_summary()\n self._update_benchmark_statistics()\n model_statistics = PrunedModelStatistics(self.full_flops, self.current_flops,\n self.full_params_num, self.current_params_num,\n self.full_filters_num, self.current_filters_num,\n pruned_layers_summary)\n\n stats = FilterPruningStatistics(model_statistics,\n self.scheduler.current_pruning_level,\n self.scheduler.target_level,\n self.prune_flops)\n\n nncf_stats = NNCFStatistics()\n nncf_stats.register('filter_pruning', stats)\n return nncf_stats\n\n def freeze(self, freeze: bool = True):\n self.frozen = freeze\n\n def set_pruning_level(self, pruning_level: float,\n run_batchnorm_adaptation: bool = False):\n \"\"\"\n Setup pruning masks in accordance to provided pruning rate\n :param pruning_level: pruning ration\n :return:\n \"\"\"\n # Pruning rate from scheduler can be percentage of params that should be pruned\n self.pruning_rate = pruning_level\n if not self.frozen:\n nncf_logger.info('Computing filter importance scores and binary masks...')\n if self.all_weights:\n if self.prune_flops:\n self._set_binary_masks_for_pruned_modules_globally_by_flops_target(pruning_level)\n else:\n self._set_binary_masks_for_pruned_layers_globally(pruning_level)\n else:\n if self.prune_flops:\n # Looking for a layerwise pruning rate needed for the required flops pruning rate\n pruning_level = self._find_uniform_pruning_level_for_target_flops(pruning_level)\n self._set_binary_masks_for_pruned_layers_groupwise(pruning_level)\n\n if run_batchnorm_adaptation:\n self._run_batchnorm_adaptation()\n\n def _init_pruned_layers_params(self):\n # 1. Initialize in/out channels for potentially prunable layers\n self._layers_in_channels, self._layers_out_channels = get_conv_in_out_channels(self._original_graph)\n\n # 2. Initialize next_nodes for each pruning cluster\n self._next_nodes = get_cluster_next_nodes(self._original_graph, self._pruned_layer_groups_info,\n self._prunable_types)\n\n # 3. Initialize pruning quotas\n for cluster in self._pruned_layer_groups_info.get_all_clusters():\n self._pruning_quotas[cluster.id] = floor(self._layers_out_channels[cluster.elements[0].node_name]\n * self.pruning_quota)\n\n def _flops_count_init(self):\n \"\"\"\n Collects input/output shapes of convolutional and dense layers,\n calculates corresponding layerwise FLOPs\n \"\"\"\n for node in self._original_graph.get_nodes_by_metatypes(GENERAL_CONV_LAYER_METATYPES):\n node_name, node_index = get_original_name_and_instance_idx(node.node_name)\n layer = self._model.get_layer(node_name)\n layer_ = unwrap_layer(layer)\n\n channel_axis = get_input_channel_axis(layer)\n dims_slice = slice(channel_axis - layer_.rank, channel_axis) \\\n if layer.data_format == 'channels_last' else slice(channel_axis + 1, None)\n in_shape = layer.get_input_shape_at(node_index)[dims_slice]\n out_shape = layer.get_output_shape_at(node_index)[dims_slice]\n\n if not is_valid_shape(in_shape) or not is_valid_shape(out_shape):\n raise RuntimeError(f'Input/output shape is not defined for layer `{layer.name}` ')\n\n self._layers_in_shapes[node.node_name] = in_shape\n self._layers_out_shapes[node.node_name] = out_shape\n\n for node in self._original_graph.get_nodes_by_metatypes(LINEAR_LAYER_METATYPES):\n node_name, node_index = get_original_name_and_instance_idx(node.node_name)\n layer = self._model.get_layer(node_name)\n\n in_shape = layer.get_input_shape_at(node_index)[1:]\n out_shape = layer.get_output_shape_at(node_index)[1:]\n\n if not is_valid_shape(in_shape) or not is_valid_shape(out_shape):\n raise RuntimeError(f'Input/output shape is not defined for layer `{layer.name}` ')\n\n self._layers_in_shapes[node.node_name] = in_shape\n self._layers_out_shapes[node.node_name] = out_shape\n\n self._nodes_flops, self._nodes_params_num = \\\n count_flops_and_weights_per_node(self._original_graph,\n self._layers_in_shapes,\n self._layers_out_shapes,\n conv_op_metatypes=GENERAL_CONV_LAYER_METATYPES,\n linear_op_metatypes=LINEAR_LAYER_METATYPES)\n\n def _set_binary_masks_for_pruned_layers_groupwise(self, pruning_level: float):\n nncf_logger.debug('Setting new binary masks for pruned layers.')\n wrapped_layers = collect_wrapped_layers(self._model)\n\n # 0. Removing masks at the elements of the NNCFGraph\n for node in self._original_graph.topological_sort():\n node.data.pop('output_mask', None)\n\n # 1. Calculate masks\n for group in self._pruned_layer_groups_info.get_all_clusters():\n # a. Calculate the cumulative importance for all filters in the group\n cumulative_filters_importance = self._calculate_filters_importance_in_group(group)\n filters_num = len(cumulative_filters_importance)\n\n # b. Calculate threshold\n num_of_sparse_elems = get_rounded_pruned_element_number(cumulative_filters_importance.shape[0],\n pruning_level)\n threshold = sorted(cumulative_filters_importance)[min(num_of_sparse_elems, filters_num - 1)]\n\n # c. Initialize masks\n filter_mask = calculate_binary_mask(cumulative_filters_importance, threshold)\n for node in group.elements:\n nncf_node = self._original_graph.get_node_by_id(node.nncf_node_id)\n nncf_node.data['output_mask'] = TFNNCFTensor(filter_mask)\n\n # 2. Propagating masks across the graph\n mask_propagator = MaskPropagationAlgorithm(self._original_graph, TF_PRUNING_OPERATOR_METATYPES,\n TFNNCFPruningTensorProcessor)\n mask_propagator.mask_propagation()\n\n # 3. Apply masks to the model\n nncf_sorted_nodes = self._original_graph.topological_sort()\n for layer in wrapped_layers:\n nncf_node = [n for n in nncf_sorted_nodes\n if layer.name == n.layer_name][0]\n if nncf_node.data['output_mask'] is not None:\n self._set_operation_masks([layer], nncf_node.data['output_mask'].tensor)\n\n # Calculate actual flops and weights number with new masks\n self._update_benchmark_statistics()\n\n def _set_binary_masks_for_pruned_layers_globally(self, pruning_level: float):\n \"\"\"\n Sets the binary mask values for layer groups according to the global pruning level.\n Filter importance scores in each group are merged into a single global list and a\n threshold value separating the pruning_level proportion of the least important filters\n in the model is calculated. Filters are pruned globally according to the threshold value.\n \"\"\"\n nncf_logger.debug('Setting new binary masks for all pruned modules together.')\n filter_importances = {}\n wrapped_layers = collect_wrapped_layers(self._model)\n\n # 0. Remove masks at the elements of the NNCFGraph\n for node in self._original_graph.topological_sort():\n node.data.pop('output_mask', None)\n\n # 1. Calculate masks\n # a. Calculate importances for all groups of filters\n for group in self._pruned_layer_groups_info.get_all_clusters():\n cumulative_filters_importance = self._calculate_filters_importance_in_group(group)\n filter_importances[group.id] = cumulative_filters_importance\n\n # b. Calculate one threshold for all weights\n importances = tf.concat(list(filter_importances.values()), 0)\n threshold = sorted(importances)[int(pruning_level * importances.shape[0])]\n\n # c. Initialize masks\n for group in self._pruned_layer_groups_info.get_all_clusters():\n filter_mask = calculate_binary_mask(filter_importances[group.id], threshold)\n for node in group.elements:\n nncf_node = self._original_graph.get_node_by_id(node.nncf_node_id)\n nncf_node.data['output_mask'] = TFNNCFTensor(filter_mask)\n\n # 2. Propagate masks across the graph\n mask_propagator = MaskPropagationAlgorithm(self._original_graph, TF_PRUNING_OPERATOR_METATYPES,\n TFNNCFPruningTensorProcessor)\n mask_propagator.mask_propagation()\n\n # 3. Apply masks to the model\n nncf_sorted_nodes = self._original_graph.topological_sort()\n for layer in wrapped_layers:\n nncf_node = [n for n in nncf_sorted_nodes\n if layer.name == n.layer_name][0]\n if nncf_node.data['output_mask'] is not None:\n self._set_operation_masks([layer], nncf_node.data['output_mask'].tensor)\n\n # Calculate actual flops with new masks\n self._update_benchmark_statistics()\n\n def _set_binary_masks_for_pruned_modules_globally_by_flops_target(self,\n target_flops_pruning_level: float):\n \"\"\"\n Prunes least important filters one-by-one until target FLOPs pruning level is achieved.\n Filters are sorted by filter importance score.\n \"\"\"\n nncf_logger.debug('Setting new binary masks for pruned layers.')\n target_flops = self.full_flops * (1 - target_flops_pruning_level)\n wrapped_layers = collect_wrapped_layers(self._model)\n masks = {}\n\n nncf_sorted_nodes = self._original_graph.topological_sort()\n for layer in wrapped_layers:\n nncf_node = [n for n in nncf_sorted_nodes\n if layer.name == n.layer_name][0]\n nncf_node.data['output_mask'] = TFNNCFTensor(tf.ones(get_filters_num(layer)))\n\n # 1. Calculate importances for all groups of filters. Initialize masks.\n filter_importances = []\n group_indexes = []\n filter_indexes = []\n for group in self._pruned_layer_groups_info.get_all_clusters():\n cumulative_filters_importance = self._calculate_filters_importance_in_group(group)\n filter_importances.extend(cumulative_filters_importance)\n filters_num = len(cumulative_filters_importance)\n group_indexes.extend([group.id] * filters_num)\n filter_indexes.extend(range(filters_num))\n masks[group.id] = tf.ones(filters_num)\n\n # 2.\n tmp_in_channels = self._layers_in_channels.copy()\n tmp_out_channels = self._layers_out_channels.copy()\n sorted_importances = sorted(zip(filter_importances, group_indexes, filter_indexes),\n key=lambda x: x[0])\n for _, group_id, filter_index in sorted_importances:\n if self._pruning_quotas[group_id] == 0:\n continue\n masks[group_id] = tf.tensor_scatter_nd_update(masks[group_id], [[filter_index]], [0])\n self._pruning_quotas[group_id] -= 1\n\n # Update input/output shapes of pruned elements\n group = self._pruned_layer_groups_info.get_cluster_by_id(group_id)\n for node in group.elements:\n tmp_out_channels[node.node_name] -= 1\n if node.is_depthwise:\n tmp_in_channels[node.node_name] -= 1\n\n for node_name in self._next_nodes[group_id]:\n tmp_in_channels[node_name] -= 1\n\n flops, params_num = count_flops_and_weights(self._original_graph,\n self._layers_in_shapes,\n self._layers_out_shapes,\n input_channels=tmp_in_channels,\n output_channels=tmp_out_channels,\n conv_op_metatypes=GENERAL_CONV_LAYER_METATYPES,\n linear_op_metatypes=LINEAR_LAYER_METATYPES)\n if flops <= target_flops:\n # 3. Add masks to the graph and propagate them\n for group in self._pruned_layer_groups_info.get_all_clusters():\n for node in group.elements:\n nncf_node = self._original_graph.get_node_by_id(node.nncf_node_id)\n nncf_node.data['output_mask'] = TFNNCFTensor(masks[group.id])\n\n mask_propagator = MaskPropagationAlgorithm(self._original_graph, TF_PRUNING_OPERATOR_METATYPES,\n TFNNCFPruningTensorProcessor)\n mask_propagator.mask_propagation()\n\n # 4. Set binary masks to the model\n self.current_flops = flops\n self.current_params_num = params_num\n nncf_sorted_nodes = self._original_graph.topological_sort()\n for layer in wrapped_layers:\n nncf_node = [n for n in nncf_sorted_nodes\n if layer.name == n.layer_name][0]\n if nncf_node.data['output_mask'] is not None:\n self._set_operation_masks([layer], nncf_node.data['output_mask'].tensor)\n return\n raise RuntimeError(f'Unable to prune model to required flops pruning level:'\n f' {target_flops_pruning_level}')\n\n def _set_operation_masks(self, layers: List[NNCFWrapper], filter_mask):\n for layer in layers:\n for weight_attr, ops in layer.weights_attr_ops.items():\n weight_shape = layer.layer_weights[weight_attr].shape\n for op_name, op in ops.items():\n if isinstance(op, BinaryMask):\n filter_axis = get_filter_axis(layer, weight_attr)\n broadcasted_mask = broadcast_filter_mask(filter_mask, weight_shape, filter_axis)\n layer.ops_weights[op_name]['mask'].assign(broadcasted_mask)\n\n def _find_uniform_pruning_level_for_target_flops(self, target_flops_pruning_level):\n error = 0.01\n target_flops = self.full_flops * (1 - target_flops_pruning_level)\n left, right = 0.0, 1.0\n while abs(right - left) > error:\n middle = (left + right) / 2\n flops, params_num = self._calculate_flops_and_weights_in_uniformly_pruned_model(middle)\n if flops < target_flops:\n right = middle\n else:\n left = middle\n flops, params_num = self._calculate_flops_and_weights_in_uniformly_pruned_model(right)\n if flops < target_flops:\n self.current_flops = flops\n self.current_params_num = params_num\n return right\n raise RuntimeError(f'Unable to prune the model to get the required '\n f'pruning level in flops = {target_flops_pruning_level}')\n\n def _calculate_flops_and_weights_in_uniformly_pruned_model(self, pruning_level):\n tmp_in_channels, tmp_out_channels = \\\n calculate_in_out_channels_in_uniformly_pruned_model(\n pruning_groups=self._pruned_layer_groups_info.get_all_clusters(),\n pruning_level=pruning_level,\n full_input_channels=self._layers_in_channels,\n full_output_channels=self._layers_out_channels,\n pruning_groups_next_nodes=self._next_nodes)\n\n return count_flops_and_weights(self._original_graph,\n self._layers_in_shapes,\n self._layers_out_shapes,\n input_channels=tmp_in_channels,\n output_channels=tmp_out_channels,\n conv_op_metatypes=GENERAL_CONV_LAYER_METATYPES,\n linear_op_metatypes=LINEAR_LAYER_METATYPES)\n\n def _calculate_filters_importance_in_group(self, group: Cluster[PrunedLayerInfo]):\n \"\"\"\n Calculates cumulative filters importance in the group.\n :param group: Nodes cluster\n :return a list of filter importance scores\n \"\"\"\n group_layers = [self._model.get_layer(node.layer_name) for node in group.elements]\n group_filters_num = tf.constant([get_filters_num(layer) for layer in group_layers])\n filters_num = group_filters_num[0]\n assert tf.reduce_all(group_filters_num == filters_num)\n\n cumulative_filters_importance = tf.zeros(filters_num)\n # Calculate cumulative importance for all filters in this group\n shared_nodes = set() # type: Set[str]\n for minfo in group.elements:\n layer_name = minfo.layer_name\n if layer_name in shared_nodes:\n continue\n nncf_node = self._original_graph.get_node_by_id(minfo.nncf_node_id)\n if nncf_node.is_shared():\n shared_nodes.add(layer_name)\n filters_importance = self._layer_filter_importance(self._model.get_layer(layer_name))\n cumulative_filters_importance += filters_importance\n\n return cumulative_filters_importance\n\n def _collect_pruning_masks(self) -> Dict[str, TFNNCFTensor]:\n retval = {}\n for group in self._pruned_layer_groups_info.get_all_clusters():\n for node in group.elements:\n retval[node.node_name] = self._original_graph.get_node_by_name(node.node_name).data['output_mask']\n return retval\n\n def _update_benchmark_statistics(self):\n tmp_in_channels, tmp_out_channels = calculate_in_out_channels_by_masks(\n pruning_groups=self._pruned_layer_groups_info.get_all_clusters(),\n masks=self._collect_pruning_masks(),\n tensor_processor=TFNNCFCollectorTensorProcessor,\n full_input_channels=self._layers_in_channels,\n full_output_channels=self._layers_out_channels,\n pruning_groups_next_nodes=self._next_nodes)\n\n self.current_filters_num = count_filters_num(self._original_graph,\n op_metatypes=GENERAL_CONV_LAYER_METATYPES,\n output_channels=tmp_out_channels)\n\n self.current_flops, self.current_params_num = \\\n count_flops_and_weights(self._original_graph,\n self._layers_in_shapes,\n self._layers_out_shapes,\n input_channels=tmp_in_channels,\n output_channels=tmp_out_channels,\n conv_op_metatypes=GENERAL_CONV_LAYER_METATYPES,\n linear_op_metatypes=LINEAR_LAYER_METATYPES)\n\n def _layer_filter_importance(self, layer: NNCFWrapper):\n layer_metatype = get_keras_layer_metatype(layer)\n if len(layer_metatype.weight_definitions) != 1:\n raise RuntimeError(f'The layer {layer.layer.name} does not support by the pruning '\n f'algorithm because it contains several weight attributes.')\n weight_attr = layer_metatype.weight_definitions[0].weight_attr_name\n weight = layer.layer_weights[weight_attr]\n if self.all_weights:\n weight = self._weights_normalizer(weight)\n target_weight_dim_for_compression = get_filter_axis(layer, weight_attr)\n filters_importance = self._filter_importance(weight, target_weight_dim_for_compression)\n return filters_importance\n\n def _run_batchnorm_adaptation(self):\n if self._bn_adaptation is None:\n self._bn_adaptation = BatchnormAdaptationAlgorithm(**extract_bn_adaptation_init_params(self.config,\n 'filter_pruning'))\n self._bn_adaptation.run(self.model)\n"
] | [
[
"tensorflow.keras.layers.Concatenate",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.layers.experimental.SyncBatchNormalization",
"tensorflow.keras.backend.softplus",
"tensorflow.keras.layers.ZeroPadding2D",
"tensorflow.keras.layers.Add"
],
[
"tensorflow.reduce_all",
"tensorflow.ones",
"tensorflow.tensor_scatter_nd_update",
"tensorflow.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"2.7",
"2.4",
"2.9",
"2.5",
"2.6",
"2.10"
]
}
] |
Ch-V3nU/Projects | [
"a0e737c1b3fe0cae48f2a42ee388e8f7c8e39817"
] | [
"Sudoku Solver/Recognizer.py"
] | [
"import cv2\nimport numpy as np\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.image import img_to_array\n\n\n\nclass OCR():\n\tdef __init__(self):\n\t\tself.loaded_model = None\n\t\tself.load_models()\n\t\t\n\tdef load_models(self):\n\n\t\tself.loaded_model = load_model(\"digits.h5\")\n\n\t\treturn\n\n\n\tdef prediction(self,image):\n\n\t\timage = cv2.resize(image, (28, 28))\n\t\timage = image.astype(\"float\") / 255.0\n\t\timage = img_to_array(image)\n\t\timage = np.expand_dims(image, axis=0)\n\n\t\tpredicted_val = self.loaded_model.predict(image,verbose=0).argmax(axis=1)[0]\n\n\t\treturn predicted_val\n"
] | [
[
"tensorflow.keras.models.load_model",
"numpy.expand_dims",
"tensorflow.keras.preprocessing.image.img_to_array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
nbiederbeck/pyirf | [
"87abc94fed4f078e185cf930f92198fd40f6f571"
] | [
"pyirf/statistics.py"
] | [
"import numpy as np\n\nfrom .utils import is_scalar\n\n\ndef li_ma_significance(n_on, n_off, alpha=0.2):\n \"\"\"\n Calculate the Li & Ma significance.\n\n Formula (17) doi.org/10.1086/161295\n\n This functions returns 0 significance when n_on < alpha * n_off\n instead of the negative sensitivities that would result from naively\n evaluating the formula.\n\n Parameters\n ----------\n n_on: integer or array like\n Number of events for the on observations\n n_off: integer of array like\n Number of events for the off observations\n alpha: float\n Ratio between the on region and the off region size or obstime.\n\n Returns\n -------\n s_lima: float or array\n The calculated significance\n \"\"\"\n\n scalar = is_scalar(n_on)\n\n n_on = np.array(n_on, copy=False, ndmin=1)\n n_off = np.array(n_off, copy=False, ndmin=1)\n\n with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n p_on = n_on / (n_on + n_off)\n p_off = n_off / (n_on + n_off)\n\n t1 = n_on * np.log(((1 + alpha) / alpha) * p_on)\n t2 = n_off * np.log((1 + alpha) * p_off)\n\n ts = t1 + t2\n significance = np.sqrt(ts * 2)\n\n significance[np.isnan(significance)] = 0\n significance[n_on < alpha * n_off] = 0\n\n if scalar:\n return significance[0]\n\n return significance\n"
] | [
[
"numpy.log",
"numpy.sqrt",
"numpy.isnan",
"numpy.errstate",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Mbompr/deepr | [
"1fb28e15aeeac6ef2d8e5b678feb380f2b1951f2",
"1fb28e15aeeac6ef2d8e5b678feb380f2b1951f2"
] | [
"deepr/hooks/num_params.py",
"deepr/metrics/mean.py"
] | [
"\"\"\"Log Number of Parameters after session creation\"\"\"\n\nfrom typing import Tuple, List\nimport logging\n\nimport tensorflow as tf\n\nfrom deepr.utils import mlflow\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass NumParamsHook(tf.train.SessionRunHook):\n \"\"\"Log Number of Parameters after session creation\"\"\"\n\n def __init__(self, use_mlflow: bool):\n self.use_mlflow = use_mlflow\n\n def after_create_session(self, session, coord):\n super().after_create_session(session, coord)\n num_global, num_trainable = get_num_params()\n LOGGER.info(f\"Number of parameters (global) = {num_global}\")\n LOGGER.info(f\"Number of parameters (trainable) = {num_trainable}\")\n if self.use_mlflow:\n mlflow.log_metrics({\"num_params_global\": num_global, \"num_params_trainable\": num_trainable})\n\n\ndef get_num_params() -> Tuple[int, int]:\n \"\"\"Get number of global and trainable parameters\n\n Returns\n -------\n Tuple[int, int]\n num_global, num_trainable\n \"\"\"\n\n def _count(variables: List):\n total = 0\n for var in variables:\n shape = var.get_shape()\n var_params = 1\n for dim in shape:\n var_params *= dim.value\n total += var_params\n return total\n\n num_global = _count(tf.global_variables())\n num_trainable = _count(tf.trainable_variables())\n return num_global, num_trainable\n",
"\"\"\"Mean Metrics\"\"\"\n\nfrom typing import Dict, List, Tuple\n\nimport tensorflow as tf\n\nfrom deepr.metrics import base\n\n\nclass Mean(base.Metric):\n \"\"\"Finite Mean Metric\"\"\"\n\n def __init__(self, tensors: List[str] = None):\n self.tensors = tensors\n\n def __call__(self, tensors: Dict[str, tf.Tensor]) -> Dict[str, Tuple]:\n if self.tensors is None:\n tensors = {key: tensor for key, tensor in tensors.items() if len(tensor.shape) == 0}\n else:\n tensors = {name: tensors[name] for name in self.tensors}\n return {name: tf.metrics.mean(value) for name, value in tensors.items()}\n\n\nclass FiniteMean(base.Metric):\n \"\"\"Finite Mean Metric\"\"\"\n\n def __init__(self, tensors: List[str] = None):\n self.tensors = tensors\n\n def __call__(self, tensors: Dict[str, tf.Tensor]) -> Dict[str, Tuple]:\n if self.tensors is None:\n tensors = {key: tensor for key, tensor in tensors.items() if len(tensor.shape) == 0}\n else:\n tensors = {name: tensors[name] for name in self.tensors}\n return {name: finite_mean_metric(value, name) for name, value in tensors.items()}\n\n\ndef finite_mean_metric(value, name):\n \"\"\"Compute Mean Metric\"\"\"\n # Variables\n acc = base.get_metric_variable(name=f\"{name}_acc\", shape=(), dtype=tf.float32)\n num = base.get_metric_variable(name=f\"{name}_num\", shape=(), dtype=tf.int64)\n\n # New Variables Values\n is_finite = tf.is_finite(value)\n new_acc = tf.cond(is_finite, lambda: acc + value, lambda: acc)\n new_num = tf.cond(is_finite, lambda: num + 1, lambda: num)\n\n # Return value and update op\n update_op = tf.group(tf.assign(acc, new_acc), tf.assign(num, new_num))\n val = tf.div_no_nan(acc, tf.to_float(num))\n return (val, update_op)\n\n\nclass DecayMean(base.Metric):\n \"\"\"Decay Mean Metric\"\"\"\n\n def __init__(self, decay: float = 0.99, tensors: List[str] = None):\n self.decay = decay\n self.tensors = tensors\n\n if decay > 1 or decay < 0:\n raise ValueError(f\"decay must be between 0 and 1, but got {decay}\")\n\n def __call__(self, tensors: Dict[str, tf.Tensor]) -> Dict[str, Tuple]:\n if self.tensors is None:\n tensors = {key: tensor for key, tensor in tensors.items() if len(tensor.shape) == 0}\n else:\n tensors = {name: tensors[name] for name in self.tensors}\n return {name: decay_mean_metric(value, self.decay, name) for name, value in tensors.items()}\n\n\ndef decay_mean_metric(value, decay: float, name: str):\n last = base.get_metric_variable(name=f\"{name}_decayed_mean\", shape=(), dtype=value.dtype)\n new_value = tf.cond(tf.equal(last, 0), lambda: value, lambda: decay * last + (1.0 - decay) * value)\n update_op = tf.assign(last, new_value)\n return (last, update_op)\n"
] | [
[
"tensorflow.trainable_variables",
"tensorflow.global_variables"
],
[
"tensorflow.cond",
"tensorflow.metrics.mean",
"tensorflow.is_finite",
"tensorflow.assign",
"tensorflow.equal",
"tensorflow.to_float"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
diego-mazon/statsmodels | [
"af8b5b5dc78acb600ffd08cda6bd9b1ca5200e10",
"af8b5b5dc78acb600ffd08cda6bd9b1ca5200e10",
"9271ced806b807a4dd325238df38b60f1aa363e2",
"9271ced806b807a4dd325238df38b60f1aa363e2"
] | [
"statsmodels/tsa/tests/test_arima.py",
"statsmodels/tsa/x13.py",
"statsmodels/imputation/bayes_mi.py",
"statsmodels/gam/smooth_basis.py"
] | [
"from statsmodels.compat.python import lrange\nfrom statsmodels.compat.platform import PLATFORM_OSX, PLATFORM_WIN\n\nfrom io import BytesIO\nimport pickle\nimport os\nimport warnings\n\nimport numpy as np\nfrom numpy.testing import (assert_almost_equal, assert_, assert_allclose,\n assert_raises)\nimport pandas as pd\nfrom pandas import DatetimeIndex, date_range, period_range\nimport pytest\n\nfrom statsmodels.datasets.macrodata import load_pandas as load_macrodata_pandas\nimport statsmodels.sandbox.tsa.fftarma as fa\nfrom statsmodels.tools.testing import assert_equal\nfrom statsmodels.tools.sm_exceptions import (\n ValueWarning, HessianInversionWarning)\nfrom statsmodels.tsa.arma_mle import Arma\nfrom statsmodels.tsa.arima_model import AR, ARMA, ARIMA\nfrom statsmodels.regression.linear_model import OLS\nfrom statsmodels.tsa.tests.results import results_arma, results_arima\nfrom statsmodels.tsa.arima_process import arma_generate_sample\n\nDECIMAL_4 = 4\nDECIMAL_3 = 3\nDECIMAL_2 = 2\nDECIMAL_1 = 1\n\ncurrent_path = os.path.dirname(os.path.abspath(__file__))\nydata_path = os.path.join(current_path, 'results', 'y_arma_data.csv')\nwith open(ydata_path, \"rb\") as fd:\n y_arma = np.genfromtxt(fd, delimiter=\",\", skip_header=1, dtype=float)\n\ncpi_dates = period_range(start='1959q1', end='2009q3', freq='Q')\nsun_dates = period_range(start='1700', end='2008', freq='A')\ncpi_predict_dates = period_range(start='2009q3', end='2015q4', freq='Q')\nsun_predict_dates = period_range(start='2008', end='2033', freq='A')\n\n\ndef test_compare_arma():\n #this is a preliminary test to compare arma_kf, arma_cond_ls and arma_cond_mle\n #the results returned by the fit methods are incomplete\n #for now without random.seed\n\n np.random.seed(9876565)\n x = fa.ArmaFft([1, -0.5], [1., 0.4], 40).generate_sample(nsample=200,\n burnin=1000)\n\n # this used kalman filter through descriptive\n #d = ARMA(x)\n #d.fit((1,1), trend='nc')\n #dres = d.res\n\n modkf = ARMA(x, (1,1))\n ##rkf = mkf.fit((1,1))\n ##rkf.params\n reskf = modkf.fit(trend='nc', disp=-1)\n dres = reskf\n\n modc = Arma(x)\n resls = modc.fit(order=(1,1))\n rescm = modc.fit_mle(order=(1,1), start_params=[0.4,0.4, 1.], disp=0)\n\n #decimal 1 corresponds to threshold of 5% difference\n #still different sign corrcted\n #assert_almost_equal(np.abs(resls[0] / d.params), np.ones(d.params.shape), decimal=1)\n assert_almost_equal(resls[0] / dres.params, np.ones(dres.params.shape),\n decimal=1)\n #rescm also contains variance estimate as last element of params\n\n #assert_almost_equal(np.abs(rescm.params[:-1] / d.params), np.ones(d.params.shape), decimal=1)\n assert_almost_equal(rescm.params[:-1] / dres.params,\n np.ones(dres.params.shape), decimal=1)\n #return resls[0], d.params, rescm.params\n\n\nclass CheckArmaResultsMixin(object):\n \"\"\"\n res2 are the results from gretl. They are in results/results_arma.\n res1 are from statsmodels\n \"\"\"\n decimal_params = DECIMAL_4\n\n def test_params(self):\n assert_almost_equal(self.res1.params, self.res2.params,\n self.decimal_params)\n\n decimal_aic = DECIMAL_4\n\n def test_aic(self):\n assert_almost_equal(self.res1.aic, self.res2.aic, self.decimal_aic)\n\n decimal_bic = DECIMAL_4\n\n def test_bic(self):\n assert_almost_equal(self.res1.bic, self.res2.bic, self.decimal_bic)\n\n decimal_arroots = DECIMAL_4\n\n def test_arroots(self):\n assert_almost_equal(self.res1.arroots, self.res2.arroots,\n self.decimal_arroots)\n\n decimal_maroots = DECIMAL_4\n\n def test_maroots(self):\n assert_almost_equal(self.res1.maroots, self.res2.maroots,\n self.decimal_maroots)\n\n decimal_bse = DECIMAL_2\n\n def test_bse(self):\n assert_almost_equal(self.res1.bse, self.res2.bse, self.decimal_bse)\n\n decimal_cov_params = DECIMAL_4\n\n def test_covparams(self):\n assert_almost_equal(self.res1.cov_params(), self.res2.cov_params,\n self.decimal_cov_params)\n\n decimal_hqic = DECIMAL_4\n\n def test_hqic(self):\n assert_almost_equal(self.res1.hqic, self.res2.hqic, self.decimal_hqic)\n\n decimal_llf = DECIMAL_4\n\n def test_llf(self):\n assert_almost_equal(self.res1.llf, self.res2.llf, self.decimal_llf)\n\n decimal_resid = DECIMAL_4\n\n def test_resid(self):\n assert_almost_equal(self.res1.resid, self.res2.resid,\n self.decimal_resid)\n\n decimal_fittedvalues = DECIMAL_4\n\n def test_fittedvalues(self):\n assert_almost_equal(self.res1.fittedvalues, self.res2.fittedvalues,\n self.decimal_fittedvalues)\n\n decimal_pvalues = DECIMAL_2\n\n def test_pvalues(self):\n assert_almost_equal(self.res1.pvalues, self.res2.pvalues,\n self.decimal_pvalues)\n\n decimal_t = DECIMAL_2 # only 2 decimal places in gretl output\n\n def test_tvalues(self):\n assert_almost_equal(self.res1.tvalues, self.res2.tvalues,\n self.decimal_t)\n\n decimal_sigma2 = DECIMAL_4\n\n def test_sigma2(self):\n assert_almost_equal(self.res1.sigma2, self.res2.sigma2,\n self.decimal_sigma2)\n\n @pytest.mark.smoke\n def test_summary(self):\n self.res1.summary()\n\n\nclass CheckForecastMixin(object):\n decimal_forecast = DECIMAL_4\n\n def test_forecast(self):\n assert_almost_equal(self.res1.forecast_res, self.res2.forecast,\n self.decimal_forecast)\n\n decimal_forecasterr = DECIMAL_4\n\n def test_forecasterr(self):\n assert_almost_equal(self.res1.forecast_err, self.res2.forecasterr,\n self.decimal_forecasterr)\n\n\nclass CheckDynamicForecastMixin(object):\n decimal_forecast_dyn = 4\n\n def test_dynamic_forecast(self):\n assert_almost_equal(self.res1.forecast_res_dyn, self.res2.forecast_dyn,\n self.decimal_forecast_dyn)\n\n def test_forecasterr(self):\n assert_almost_equal(self.res1.forecast_err_dyn,\n self.res2.forecasterr_dyn,\n DECIMAL_4)\n\n\nclass CheckArimaResultsMixin(CheckArmaResultsMixin):\n def test_order(self):\n assert self.res1.k_diff == self.res2.k_diff\n assert self.res1.k_ar == self.res2.k_ar\n assert self.res1.k_ma == self.res2.k_ma\n\n decimal_predict_levels = DECIMAL_4\n\n def test_predict_levels(self):\n assert_almost_equal(self.res1.predict(typ='levels'), self.res2.linear,\n self.decimal_predict_levels)\n\n\nclass Test_Y_ARMA11_NoConst(CheckArmaResultsMixin, CheckForecastMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,0]\n cls.res1 = ARMA(endog, order=(1,1)).fit(trend='nc', disp=-1)\n (cls.res1.forecast_res, cls.res1.forecast_err,\n confint) = cls.res1.forecast(10)\n cls.res2 = results_arma.Y_arma11()\n\n def test_pickle(self):\n fh = BytesIO()\n #test wrapped results load save pickle\n self.res1.save(fh)\n fh.seek(0,0)\n res_unpickled = self.res1.__class__.load(fh)\n assert type(res_unpickled) is type(self.res1) # noqa: E721\n\n\nclass Test_Y_ARMA14_NoConst(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,1]\n cls.res1 = ARMA(endog, order=(1,4)).fit(trend='nc', disp=-1)\n cls.res2 = results_arma.Y_arma14()\n\n\[email protected]\nclass Test_Y_ARMA41_NoConst(CheckArmaResultsMixin, CheckForecastMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,2]\n cls.res1 = ARMA(endog, order=(4,1)).fit(trend='nc', disp=-1)\n (cls.res1.forecast_res, cls.res1.forecast_err,\n confint) = cls.res1.forecast(10)\n cls.res2 = results_arma.Y_arma41()\n cls.decimal_maroots = DECIMAL_3\n\n\nclass Test_Y_ARMA22_NoConst(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,3]\n cls.res1 = ARMA(endog, order=(2,2)).fit(trend='nc', disp=-1)\n cls.res2 = results_arma.Y_arma22()\n\n\nclass Test_Y_ARMA50_NoConst(CheckArmaResultsMixin, CheckForecastMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,4]\n cls.res1 = ARMA(endog, order=(5,0)).fit(trend='nc', disp=-1)\n (cls.res1.forecast_res, cls.res1.forecast_err,\n confint) = cls.res1.forecast(10)\n cls.res2 = results_arma.Y_arma50()\n\n\nclass Test_Y_ARMA02_NoConst(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,5]\n cls.res1 = ARMA(endog, order=(0,2)).fit(trend='nc', disp=-1)\n cls.res2 = results_arma.Y_arma02()\n\n\nclass Test_Y_ARMA11_Const(CheckArmaResultsMixin, CheckForecastMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,6]\n cls.res1 = ARMA(endog, order=(1,1)).fit(trend=\"c\", disp=-1)\n (cls.res1.forecast_res, cls.res1.forecast_err,\n confint) = cls.res1.forecast(10)\n cls.res2 = results_arma.Y_arma11c()\n\n\nclass Test_Y_ARMA14_Const(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,7]\n cls.res1 = ARMA(endog, order=(1,4)).fit(trend=\"c\", disp=-1)\n cls.res2 = results_arma.Y_arma14c()\n\n\nclass Test_Y_ARMA41_Const(CheckArmaResultsMixin, CheckForecastMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,8]\n cls.res2 = results_arma.Y_arma41c()\n cls.res1 = ARMA(endog, order=(4,1)).fit(trend=\"c\", disp=-1,\n start_params=cls.res2.params)\n (cls.res1.forecast_res, cls.res1.forecast_err,\n confint) = cls.res1.forecast(10)\n cls.decimal_cov_params = DECIMAL_3\n cls.decimal_fittedvalues = DECIMAL_3\n cls.decimal_resid = DECIMAL_3\n cls.decimal_params = DECIMAL_3\n\n\nclass Test_Y_ARMA22_Const(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,9]\n cls.res1 = ARMA(endog, order=(2,2)).fit(trend=\"c\", disp=-1)\n cls.res2 = results_arma.Y_arma22c()\n\n def test_summary(self):\n # regression test for html of roots table #4434\n # we ignore whitespace in the assert\n summ = self.res1.summary()\n summ_roots = \"\"\"\\\n <tableclass=\"simpletable\">\n <caption>Roots</caption>\n <tr>\n <td></td><th>Real</th><th>Imaginary</th><th>Modulus</th><th>Frequency</th>\n </tr>\n <tr>\n <th>AR.1</th><td>1.0991</td><td>-1.2571j</td><td>1.6698</td><td>-0.1357</td>\n </tr>\n <tr>\n <th>AR.2</th><td>1.0991</td><td>+1.2571j</td><td>1.6698</td><td>0.1357</td>\n </tr>\n <tr>\n <th>MA.1</th><td>-1.1702</td><td>+0.0000j</td><td>1.1702</td><td>0.5000</td>\n </tr>\n <tr>\n <th>MA.2</th><td>1.2215</td><td>+0.0000j</td><td>1.2215</td><td>0.0000</td>\n </tr>\n </table>\"\"\"\n assert_equal(summ.tables[2]._repr_html_().replace(' ', ''),\n summ_roots.replace(' ', ''))\n\n\nclass Test_Y_ARMA50_Const(CheckArmaResultsMixin, CheckForecastMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,10]\n cls.res1 = ARMA(endog, order=(5,0)).fit(trend=\"c\", disp=-1)\n (cls.res1.forecast_res, cls.res1.forecast_err,\n confint) = cls.res1.forecast(10)\n cls.res2 = results_arma.Y_arma50c()\n\n\nclass Test_Y_ARMA02_Const(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,11]\n cls.res1 = ARMA(endog, order=(0,2)).fit(trend=\"c\", disp=-1)\n cls.res2 = results_arma.Y_arma02c()\n\n\n# cov_params and tvalues are off still but not as much vs. R\nclass Test_Y_ARMA11_NoConst_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,0]\n cls.res1 = ARMA(endog, order=(1,1)).fit(method=\"css\", trend='nc',\n disp=-1)\n cls.res2 = results_arma.Y_arma11(\"css\")\n cls.decimal_t = DECIMAL_1\n\n\n# better vs. R\nclass Test_Y_ARMA14_NoConst_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,1]\n cls.res1 = ARMA(endog, order=(1,4)).fit(method=\"css\", trend='nc',\n disp=-1)\n cls.res2 = results_arma.Y_arma14(\"css\")\n cls.decimal_fittedvalues = DECIMAL_3\n cls.decimal_resid = DECIMAL_3\n cls.decimal_t = DECIMAL_1\n\n\n# bse, etc. better vs. R\n# maroot is off because maparams is off a bit (adjust tolerance?)\nclass Test_Y_ARMA41_NoConst_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,2]\n cls.res1 = ARMA(endog, order=(4,1)).fit(method=\"css\", trend='nc',\n disp=-1)\n cls.res2 = results_arma.Y_arma41(\"css\")\n cls.decimal_t = DECIMAL_1\n cls.decimal_pvalues = 0\n cls.decimal_cov_params = DECIMAL_3\n cls.decimal_maroots = DECIMAL_1\n\n\n#same notes as above\nclass Test_Y_ARMA22_NoConst_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,3]\n cls.res1 = ARMA(endog, order=(2,2)).fit(method=\"css\", trend='nc',\n disp=-1)\n cls.res2 = results_arma.Y_arma22(\"css\")\n cls.decimal_t = DECIMAL_1\n cls.decimal_resid = DECIMAL_3\n cls.decimal_pvalues = DECIMAL_1\n cls.decimal_fittedvalues = DECIMAL_3\n\n\n#NOTE: gretl just uses least squares for AR CSS\n# so BIC, etc. is\n# -2*res1.llf + np.log(nobs)*(res1.q+res1.p+res1.k)\n# with no adjustment for p and no extra sigma estimate\n#NOTE: so our tests use x-12 arima results which agree with us and are\n# consistent with the rest of the models\nclass Test_Y_ARMA50_NoConst_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,4]\n cls.res1 = ARMA(endog, order=(5,0)).fit(method=\"css\", trend='nc',\n disp=-1)\n cls.res2 = results_arma.Y_arma50(\"css\")\n cls.decimal_t = 0\n cls.decimal_llf = DECIMAL_1 # looks like rounding error?\n\n\nclass Test_Y_ARMA02_NoConst_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,5]\n cls.res1 = ARMA(endog, order=(0,2)).fit(method=\"css\", trend='nc',\n disp=-1)\n cls.res2 = results_arma.Y_arma02(\"css\")\n\n\n#NOTE: our results are close to --x-12-arima option and R\nclass Test_Y_ARMA11_Const_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,6]\n cls.res1 = ARMA(endog, order=(1,1)).fit(trend=\"c\", method=\"css\",\n disp=-1)\n cls.res2 = results_arma.Y_arma11c(\"css\")\n cls.decimal_params = DECIMAL_3\n cls.decimal_cov_params = DECIMAL_3\n cls.decimal_t = DECIMAL_1\n\n\nclass Test_Y_ARMA14_Const_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,7]\n cls.res1 = ARMA(endog, order=(1,4)).fit(trend=\"c\", method=\"css\",\n disp=-1)\n cls.res2 = results_arma.Y_arma14c(\"css\")\n cls.decimal_t = DECIMAL_1\n cls.decimal_pvalues = DECIMAL_1\n\n\nclass Test_Y_ARMA41_Const_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,8]\n cls.res1 = ARMA(endog, order=(4,1)).fit(trend=\"c\", method=\"css\",\n disp=-1)\n cls.res2 = results_arma.Y_arma41c(\"css\")\n cls.decimal_t = DECIMAL_1\n cls.decimal_cov_params = DECIMAL_1\n cls.decimal_maroots = DECIMAL_3\n cls.decimal_bse = DECIMAL_1\n\n\nclass Test_Y_ARMA22_Const_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,9]\n cls.res1 = ARMA(endog, order=(2,2)).fit(trend=\"c\", method=\"css\",\n disp=-1)\n cls.res2 = results_arma.Y_arma22c(\"css\")\n cls.decimal_t = 0\n cls.decimal_pvalues = DECIMAL_1\n\n\nclass Test_Y_ARMA50_Const_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,10]\n cls.res1 = ARMA(endog, order=(5,0)).fit(trend=\"c\", method=\"css\",\n disp=-1)\n cls.res2 = results_arma.Y_arma50c(\"css\")\n cls.decimal_t = DECIMAL_1\n cls.decimal_params = DECIMAL_3\n cls.decimal_cov_params = DECIMAL_2\n\n\nclass Test_Y_ARMA02_Const_CSS(CheckArmaResultsMixin):\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,11]\n cls.res1 = ARMA(endog, order=(0,2)).fit(trend=\"c\", method=\"css\",\n disp=-1)\n cls.res2 = results_arma.Y_arma02c(\"css\")\n\n\ndef test_reset_trend():\n endog = y_arma[:,0]\n mod = ARMA(endog, order=(1,1))\n res1 = mod.fit(trend=\"c\", disp=-1)\n res2 = mod.fit(trend=\"nc\", disp=-1)\n assert_equal(len(res1.params), len(res2.params)+1)\n\n\[email protected]\ndef test_start_params_bug():\n data = np.array([1368., 1187, 1090, 1439, 2362, 2783, 2869, 2512, 1804,\n 1544, 1028, 869, 1737, 2055, 1947, 1618, 1196, 867, 997, 1862, 2525,\n 3250, 4023, 4018, 3585, 3004, 2500, 2441, 2749, 2466, 2157, 1847, 1463,\n 1146, 851, 993, 1448, 1719, 1709, 1455, 1950, 1763, 2075, 2343, 3570,\n 4690, 3700, 2339, 1679, 1466, 998, 853, 835, 922, 851, 1125, 1299, 1105,\n 860, 701, 689, 774, 582, 419, 846, 1132, 902, 1058, 1341, 1551, 1167,\n 975, 786, 759, 751, 649, 876, 720, 498, 553, 459, 543, 447, 415, 377,\n 373, 324, 320, 306, 259, 220, 342, 558, 825, 994, 1267, 1473, 1601,\n 1896, 1890, 2012, 2198, 2393, 2825, 3411, 3406, 2464, 2891, 3685, 3638,\n 3746, 3373, 3190, 2681, 2846, 4129, 5054, 5002, 4801, 4934, 4903, 4713,\n 4745, 4736, 4622, 4642, 4478, 4510, 4758, 4457, 4356, 4170, 4658, 4546,\n 4402, 4183, 3574, 2586, 3326, 3948, 3983, 3997, 4422, 4496, 4276, 3467,\n 2753, 2582, 2921, 2768, 2789, 2824, 2482, 2773, 3005, 3641, 3699, 3774,\n 3698, 3628, 3180, 3306, 2841, 2014, 1910, 2560, 2980, 3012, 3210, 3457,\n 3158, 3344, 3609, 3327, 2913, 2264, 2326, 2596, 2225, 1767, 1190, 792,\n 669, 589, 496, 354, 246, 250, 323, 495, 924, 1536, 2081, 2660, 2814, 2992,\n 3115, 2962, 2272, 2151, 1889, 1481, 955, 631, 288, 103, 60, 82, 107, 185,\n 618, 1526, 2046, 2348, 2584, 2600, 2515, 2345, 2351, 2355, 2409, 2449,\n 2645, 2918, 3187, 2888, 2610, 2740, 2526, 2383, 2936, 2968, 2635, 2617,\n 2790, 3906, 4018, 4797, 4919, 4942, 4656, 4444, 3898, 3908, 3678, 3605,\n 3186, 2139, 2002, 1559, 1235, 1183, 1096, 673, 389, 223, 352, 308, 365,\n 525, 779, 894, 901, 1025, 1047, 981, 902, 759, 569, 519, 408, 263, 156,\n 72, 49, 31, 41, 192, 423, 492, 552, 564, 723, 921, 1525, 2768, 3531, 3824,\n 3835, 4294, 4533, 4173, 4221, 4064, 4641, 4685, 4026, 4323, 4585, 4836,\n 4822, 4631, 4614, 4326, 4790, 4736, 4104, 5099, 5154, 5121, 5384, 5274,\n 5225, 4899, 5382, 5295, 5349, 4977, 4597, 4069, 3733, 3439, 3052, 2626,\n 1939, 1064, 713, 916, 832, 658, 817, 921, 772, 764, 824, 967, 1127, 1153,\n 824, 912, 957, 990, 1218, 1684, 2030, 2119, 2233, 2657, 2652, 2682, 2498,\n 2429, 2346, 2298, 2129, 1829, 1816, 1225, 1010, 748, 627, 469, 576, 532,\n 475, 582, 641, 605, 699, 680, 714, 670, 666, 636, 672, 679, 446, 248, 134,\n 160, 178, 286, 413, 676, 1025, 1159, 952, 1398, 1833, 2045, 2072, 1798,\n 1799, 1358, 727, 353, 347, 844, 1377, 1829, 2118, 2272, 2745, 4263, 4314,\n 4530, 4354, 4645, 4547, 5391, 4855, 4739, 4520, 4573, 4305, 4196, 3773,\n 3368, 2596, 2596, 2305, 2756, 3747, 4078, 3415, 2369, 2210, 2316, 2263,\n 2672, 3571, 4131, 4167, 4077, 3924, 3738, 3712, 3510, 3182, 3179, 2951,\n 2453, 2078, 1999, 2486, 2581, 1891, 1997, 1366, 1294, 1536, 2794, 3211,\n 3242, 3406, 3121, 2425, 2016, 1787, 1508, 1304, 1060, 1342, 1589, 2361,\n 3452, 2659, 2857, 3255, 3322, 2852, 2964, 3132, 3033, 2931, 2636, 2818,\n 3310, 3396, 3179, 3232, 3543, 3759, 3503, 3758, 3658, 3425, 3053, 2620,\n 1837, 923, 712, 1054, 1376, 1556, 1498, 1523, 1088, 728, 890, 1413, 2524,\n 3295, 4097, 3993, 4116, 3874, 4074, 4142, 3975, 3908, 3907, 3918, 3755,\n 3648, 3778, 4293, 4385, 4360, 4352, 4528, 4365, 3846, 4098, 3860, 3230,\n 2820, 2916, 3201, 3721, 3397, 3055, 2141, 1623, 1825, 1716, 2232, 2939,\n 3735, 4838, 4560, 4307, 4975, 5173, 4859, 5268, 4992, 5100, 5070, 5270,\n 4760, 5135, 5059, 4682, 4492, 4933, 4737, 4611, 4634, 4789, 4811, 4379,\n 4689, 4284, 4191, 3313, 2770, 2543, 3105, 2967, 2420, 1996, 2247, 2564,\n 2726, 3021, 3427, 3509, 3759, 3324, 2988, 2849, 2340, 2443, 2364, 1252,\n 623, 742, 867, 684, 488, 348, 241, 187, 279, 355, 423, 678, 1375, 1497,\n 1434, 2116, 2411, 1929, 1628, 1635, 1609, 1757, 2090, 2085, 1790, 1846,\n 2038, 2360, 2342, 2401, 2920, 3030, 3132, 4385, 5483, 5865, 5595, 5485,\n 5727, 5553, 5560, 5233, 5478, 5159, 5155, 5312, 5079, 4510, 4628, 4535,\n 3656, 3698, 3443, 3146, 2562, 2304, 2181, 2293, 1950, 1930, 2197, 2796,\n 3441, 3649, 3815, 2850, 4005, 5305, 5550, 5641, 4717, 5131, 2831, 3518,\n 3354, 3115, 3515, 3552, 3244, 3658, 4407, 4935, 4299, 3166, 3335, 2728,\n 2488, 2573, 2002, 1717, 1645, 1977, 2049, 2125, 2376, 2551, 2578, 2629,\n 2750, 3150, 3699, 4062, 3959, 3264, 2671, 2205, 2128, 2133, 2095, 1964,\n 2006, 2074, 2201, 2506, 2449, 2465, 2064, 1446, 1382, 983, 898, 489, 319,\n 383, 332, 276, 224, 144, 101, 232, 429, 597, 750, 908, 960, 1076, 951,\n 1062, 1183, 1404, 1391, 1419, 1497, 1267, 963, 682, 777, 906, 1149, 1439,\n 1600, 1876, 1885, 1962, 2280, 2711, 2591, 2411])\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n res = ARMA(data, order=(4,1)).fit(start_ar_lags=5, disp=-1)\n\n\nclass Test_ARIMA101(CheckArmaResultsMixin):\n # just make sure this works\n @classmethod\n def setup_class(cls):\n endog = y_arma[:,6]\n cls.res1 = ARIMA(endog, (1,0,1)).fit(trend=\"c\", disp=-1)\n (cls.res1.forecast_res, cls.res1.forecast_err,\n confint) = cls.res1.forecast(10)\n cls.res2 = results_arma.Y_arma11c()\n cls.res2.k_diff = 0\n cls.res2.k_ar = 1\n cls.res2.k_ma = 1\n\n\nclass Test_ARIMA111(CheckArimaResultsMixin, CheckForecastMixin,\n CheckDynamicForecastMixin):\n @classmethod\n def setup_class(cls):\n cpi = load_macrodata_pandas().data['cpi'].values\n cls.res1 = ARIMA(cpi, (1,1,1)).fit(disp=-1)\n cls.res2 = results_arima.ARIMA111()\n # make sure endog names changes to D.cpi\n cls.decimal_llf = 3\n cls.decimal_aic = 3\n cls.decimal_bic = 3\n cls.decimal_cov_params = 2 # this used to be better?\n cls.decimal_t = 0\n (cls.res1.forecast_res,\n cls.res1.forecast_err,\n conf_int) = cls.res1.forecast(25)\n #cls.res1.forecast_res_dyn = cls.res1.predict(start=164, end=226, typ='levels', dynamic=True)\n #TODO: fix the indexing for the end here, I do not think this is right\n # if we're going to treat it like indexing\n # the forecast from 2005Q1 through 2009Q4 is indices\n # 184 through 227 not 226\n # note that the first one counts in the count so 164 + 64 is 65\n # predictions\n cls.res1.forecast_res_dyn = cls.res1.predict(start=164, end=164+63,\n typ='levels', dynamic=True)\n\n def test_freq(self):\n assert_almost_equal(self.res1.arfreq, [0.0000], 4)\n assert_almost_equal(self.res1.mafreq, [0.0000], 4)\n\n\nclass Test_ARIMA111CSS(CheckArimaResultsMixin, CheckForecastMixin,\n CheckDynamicForecastMixin):\n @classmethod\n def setup_class(cls):\n cpi = load_macrodata_pandas().data['cpi'].values\n cls.res1 = ARIMA(cpi, (1,1,1)).fit(disp=-1, method='css')\n cls.res2 = results_arima.ARIMA111(method='css')\n cls.res2.fittedvalues = - cpi[1:-1] + cls.res2.linear\n # make sure endog names changes to D.cpi\n (cls.res1.forecast_res,\n cls.res1.forecast_err,\n conf_int) = cls.res1.forecast(25)\n cls.decimal_forecast = 2\n cls.decimal_forecast_dyn = 2\n cls.decimal_forecasterr = 3\n cls.res1.forecast_res_dyn = cls.res1.predict(start=164, end=164+63,\n typ='levels', dynamic=True)\n\n # precisions\n cls.decimal_arroots = 3\n cls.decimal_cov_params = 3\n cls.decimal_hqic = 3\n cls.decimal_maroots = 3\n cls.decimal_t = 1\n cls.decimal_fittedvalues = 2 # because of rounding when copying\n cls.decimal_resid = 2\n #cls.decimal_llf = 3\n #cls.decimal_aic = 3\n #cls.decimal_bic = 3\n cls.decimal_predict_levels = DECIMAL_2\n\n\nclass Test_ARIMA112CSS(CheckArimaResultsMixin):\n @classmethod\n def setup_class(cls):\n cpi = load_macrodata_pandas().data['cpi'].values\n cls.res1 = ARIMA(cpi, (1,1,2)).fit(disp=-1, method='css',\n start_params = [.905322, -.692425, 1.07366,\n 0.172024])\n cls.res2 = results_arima.ARIMA112(method='css')\n cls.res2.fittedvalues = - cpi[1:-1] + cls.res2.linear\n # make sure endog names changes to D.cpi\n cls.decimal_llf = 3\n cls.decimal_aic = 3\n cls.decimal_bic = 3\n #(cls.res1.forecast_res,\n # cls.res1.forecast_err,\n # conf_int) = cls.res1.forecast(25)\n #cls.res1.forecast_res_dyn = cls.res1.predict(start=164, end=226, typ='levels', dynamic=True)\n #TODO: fix the indexing for the end here, I do not think this is right\n # if we're going to treat it like indexing\n # the forecast from 2005Q1 through 2009Q4 is indices\n # 184 through 227 not 226\n # note that the first one counts in the count so 164 + 64 is 65\n # predictions\n #cls.res1.forecast_res_dyn = self.predict(start=164, end=164+63,\n # typ='levels', dynamic=True)\n # since we got from gretl do not have linear prediction in differences\n cls.decimal_arroots = 3\n cls.decimal_maroots = 2\n cls.decimal_t = 1\n cls.decimal_resid = 2\n cls.decimal_fittedvalues = 3\n cls.decimal_predict_levels = DECIMAL_3\n\n def test_freq(self):\n assert_almost_equal(self.res1.arfreq, [0.5000], 4)\n assert_almost_equal(self.res1.mafreq, [0.5000, 0.5000], 4)\n\n#class Test_ARIMADates(CheckArmaResults, CheckForecast, CheckDynamicForecast):\n# @classmethod\n# def setup_class(cls):\n# cpi = load_macrodata_pandas().data['cpi'].values\n# dates = pd.date_range('1959', periods=203, freq='Q')\n# cls.res1 = ARIMA(cpi, dates=dates, freq='Q').fit(order=(1,1,1), disp=-1)\n# cls.res2 = results_arima.ARIMA111()\n# # make sure endog names changes to D.cpi\n# cls.decimal_llf = 3\n# cls.decimal_aic = 3\n# cls.decimal_bic = 3\n# (cls.res1.forecast_res,\n# cls.res1.forecast_err,\n# conf_int) = cls.res1.forecast(25)\n\n\ndef test_arima_predict_mle_dates():\n cpi = load_macrodata_pandas().data['cpi'].values\n res1 = ARIMA(cpi, (4,1,1), dates=cpi_dates, freq='Q').fit(disp=-1)\n\n with open(current_path + '/results/results_arima_forecasts_all_mle.csv', \"rb\") as test_data:\n arima_forecasts = np.genfromtxt(test_data, delimiter=\",\", skip_header=1, dtype=float)\n\n fc = arima_forecasts[:,0]\n fcdyn = arima_forecasts[:,1]\n fcdyn2 = arima_forecasts[:,2]\n\n start, end = 2, 51\n fv = res1.predict('1959Q3', '1971Q4', typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n assert_equal(res1.data.predict_dates, cpi_dates[start:end+1])\n\n start, end = 202, 227\n fv = res1.predict('2009Q3', '2015Q4', typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n assert_equal(res1.data.predict_dates, cpi_predict_dates)\n\n # make sure dynamic works\n\n start, end = '1960q2', '1971q4'\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn[5:51+1], DECIMAL_4)\n\n start, end = '1965q1', '2015q4'\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn2[24:227+1], DECIMAL_4)\n\n\ndef test_arma_predict_mle_dates():\n from statsmodels.datasets.sunspots import load_pandas\n sunspots = load_pandas().data['SUNACTIVITY'].values\n mod = ARMA(sunspots, (9,0), dates=sun_dates, freq='A')\n mod.method = 'mle'\n\n assert_raises(ValueError, mod._get_prediction_index, *('1701', '1751', True))\n\n start, end = 2, 51\n _, _, _, _ = mod._get_prediction_index('1702', '1751', False)\n assert_equal(mod.data.predict_dates, sun_dates[start:end+1])\n\n start, end = 308, 333\n _, _, _, _ = mod._get_prediction_index('2008', '2033', False)\n assert_equal(mod.data.predict_dates, sun_predict_dates)\n\n\ndef test_arima_predict_css_dates():\n cpi = load_macrodata_pandas().data['cpi'].values\n res1 = ARIMA(cpi, (4,1,1), dates=cpi_dates, freq='Q').fit(disp=-1,\n method='css', trend='nc')\n\n params = np.array([ 1.231272508473910,\n -0.282516097759915,\n 0.170052755782440,\n -0.118203728504945,\n -0.938783134717947])\n\n with open(current_path + '/results/results_arima_forecasts_all_css.csv', \"rb\") as test_data:\n arima_forecasts = np.genfromtxt(test_data, delimiter=\",\", skip_header=1, dtype=float)\n\n fc = arima_forecasts[:,0]\n fcdyn = arima_forecasts[:,1]\n fcdyn2 = arima_forecasts[:,2]\n\n start, end = 5, 51\n fv = res1.model.predict(params, '1960Q2', '1971Q4', typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n assert_equal(res1.data.predict_dates, cpi_dates[start:end+1])\n\n start, end = 202, 227\n fv = res1.model.predict(params, '2009Q3', '2015Q4', typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n assert_equal(res1.data.predict_dates, cpi_predict_dates)\n\n # make sure dynamic works\n start, end = 5, 51\n fv = res1.model.predict(params, '1960Q2', '1971Q4', typ='levels',\n dynamic=True)\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n\n start, end = '1965q1', '2015q4'\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn2[24:227+1], DECIMAL_4)\n\n\ndef test_arma_predict_css_dates():\n from statsmodels.datasets.sunspots import load_pandas\n sunspots = load_pandas().data['SUNACTIVITY'].values\n mod = ARMA(sunspots, (9,0), dates=sun_dates, freq='A')\n mod.method = 'css'\n assert_raises(ValueError, mod._get_prediction_index, *('1701', '1751', False))\n\n\ndef test_arima_predict_mle():\n cpi = load_macrodata_pandas().data['cpi'].values\n res1 = ARIMA(cpi, (4,1,1)).fit(disp=-1)\n # fit the model so that we get correct endog length but use\n with open(current_path + '/results/results_arima_forecasts_all_mle.csv', \"rb\") as test_data:\n arima_forecasts = np.genfromtxt(test_data, delimiter=\",\", skip_header=1, dtype=float)\n fc = arima_forecasts[:,0]\n fcdyn = arima_forecasts[:,1]\n fcdyn2 = arima_forecasts[:,2]\n fcdyn3 = arima_forecasts[:,3]\n fcdyn4 = arima_forecasts[:,4]\n\n # 0 indicates the first sample-observation below\n # ie., the index after the pre-sample, these are also differenced once\n # so the indices are moved back once from the cpi in levels\n # start < p, end <p 1959q2 - 1959q4\n start, end = 1,3\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start < p, end 0 1959q3 - 1960q1\n start, end = 2, 4\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start < p, end >0 1959q3 - 1971q4\n start, end = 2, 51\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start < p, end nobs 1959q3 - 2009q3\n start, end = 2, 202\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start < p, end >nobs 1959q3 - 2015q4\n start, end = 2, 227\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start 0, end >0 1960q1 - 1971q4\n start, end = 4, 51\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start 0, end nobs 1960q1 - 2009q3\n start, end = 4, 202\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start 0, end >nobs 1960q1 - 2015q4\n start, end = 4, 227\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end >0 1965q1 - 1971q4\n start, end = 24, 51\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end nobs 1965q1 - 2009q3\n start, end = 24, 202\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end >nobs 1965q1 - 2015q4\n start, end = 24, 227\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start nobs, end nobs 2009q3 - 2009q3\n #NOTE: raises\n #start, end = 202, 202\n #fv = res1.predict(start, end, typ='levels')\n #assert_almost_equal(fv, [])\n # start nobs, end >nobs 2009q3 - 2015q4\n start, end = 202, 227\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_3)\n # start >nobs, end >nobs 2009q4 - 2015q4\n #NOTE: this raises but should not, dynamic forecasts could start\n #one period out\n start, end = 203, 227\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # defaults\n start, end = None, None\n fv = res1.predict(start, end, typ='levels')\n assert_almost_equal(fv, fc[1:203], DECIMAL_4)\n\n #### Dynamic #####\n\n # start < p, end <p 1959q2 - 1959q4\n #NOTE: should raise\n #start, end = 1,3\n #fv = res1.predict(start, end, dynamic=True, typ='levels')\n #assert_almost_equal(fv, arima_forecasts[:,15])\n # start < p, end 0 1959q3 - 1960q1\n\n #NOTE: below should raise an error\n #start, end = 2, 4\n #fv = res1.predict(start, end, dynamic=True, typ='levels')\n #assert_almost_equal(fv, fcdyn[5:end+1], DECIMAL_4)\n # start < p, end >0 1959q3 - 1971q4\n #start, end = 2, 51\n #fv = res1.predict(start, end, dynamic=True, typ='levels')\n #assert_almost_equal(fv, fcdyn[5:end+1], DECIMAL_4)\n ## start < p, end nobs 1959q3 - 2009q3\n #start, end = 2, 202\n #fv = res1.predict(start, end, dynamic=True, typ='levels')\n #assert_almost_equal(fv, fcdyn[5:end+1], DECIMAL_4)\n ## start < p, end >nobs 1959q3 - 2015q4\n #start, end = 2, 227\n #fv = res1.predict(start, end, dynamic=True, typ='levels')\n #assert_almost_equal(fv, fcdyn[5:end+1], DECIMAL_4)\n # start 0, end >0 1960q1 - 1971q4\n start, end = 5, 51\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start 0, end nobs 1960q1 - 2009q3\n start, end = 5, 202\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start 0, end >nobs 1960q1 - 2015q4\n start, end = 5, 227\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start >p, end >0 1965q1 - 1971q4\n start, end = 24, 51\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start >p, end nobs 1965q1 - 2009q3\n start, end = 24, 202\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start >p, end >nobs 1965q1 - 2015q4\n start, end = 24, 227\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start nobs, end nobs 2009q3 - 2009q3\n start, end = 202, 202\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn3[start:end+1], DECIMAL_4)\n # start nobs, end >nobs 2009q3 - 2015q4\n start, end = 202, 227\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn3[start:end+1], DECIMAL_4)\n # start >nobs, end >nobs 2009q4 - 2015q4\n start, end = 203, 227\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn4[start:end+1], DECIMAL_4)\n # defaults\n start, end = None, None\n fv = res1.predict(start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn[5:203], DECIMAL_4)\n\n\ndef _check_start(model, given, expected, dynamic):\n start, _, _, _ = model._get_prediction_index(given, None, dynamic)\n assert_equal(start, expected)\n\n\ndef _check_end(model, given, end_expect, out_of_sample_expect):\n _, end, out_of_sample, _ = model._get_prediction_index(None, given, False)\n assert_equal((end, out_of_sample), (end_expect, out_of_sample_expect))\n\n\ndef test_arma_predict_indices():\n from statsmodels.datasets.sunspots import load_pandas\n sunspots = load_pandas().data['SUNACTIVITY'].values\n model = ARMA(sunspots, (9,0), dates=sun_dates, freq='A')\n model.method = 'mle'\n\n # raises - pre-sample + dynamic\n assert_raises(ValueError, model._get_prediction_index, *(0, None, True))\n assert_raises(ValueError, model._get_prediction_index, *(8, None, True))\n assert_raises(ValueError, model._get_prediction_index, *('1700', None, True))\n assert_raises(ValueError, model._get_prediction_index, *('1708', None, True))\n\n # raises - start out of sample\n # TODO: remove these, start out of sample now allowed\n # assert_raises(ValueError, model._get_prediction_index, *(311, None, True))\n # assert_raises(ValueError, model._get_prediction_index, *(311, None, False))\n # assert_raises(ValueError, model._get_prediction_index, *('2010', None, True))\n # assert_raises(ValueError, model._get_prediction_index, *('2010', None, False))\n\n # works - in-sample\n # None\n start_test_cases = [\n # given, expected, dynamic\n (None, 9, True),\n # all start get moved back by k_diff\n (9, 9, True),\n (10, 10, True),\n # what about end of sample start - last value is first\n # forecast\n (309, 309, True),\n (308, 308, True),\n (0, 0, False),\n (1, 1, False),\n (4, 4, False),\n\n # all start get moved back by k_diff\n ('1709', 9, True),\n ('1710', 10, True),\n # what about end of sample start - last value is first\n # forecast\n ('2008', 308, True),\n ('2009', 309, True),\n ('1700', 0, False),\n ('1708', 8, False),\n ('1709', 9, False),\n ]\n\n for case in start_test_cases:\n _check_start(*((model,) + case))\n\n # the length of sunspot is 309, so last index is 208\n end_test_cases = [(None, 308, 0),\n (307, 307, 0),\n (308, 308, 0),\n (309, 308, 1),\n (312, 308, 4),\n (51, 51, 0),\n (333, 308, 25),\n\n ('2007', 307, 0),\n ('2008', 308, 0),\n ('2009', 308, 1),\n ('2012', 308, 4),\n ('1815', 115, 0),\n ('2033', 308, 25),\n ]\n\n for case in end_test_cases:\n _check_end(*((model,)+case))\n\n\ndef test_arima_predict_indices():\n cpi = load_macrodata_pandas().data['cpi'].values\n model = ARIMA(cpi, (4,1,1), dates=cpi_dates, freq='Q')\n model.method = 'mle'\n\n # starting indices\n\n # raises - pre-sample + dynamic\n assert_raises(ValueError, model._get_prediction_index, *(0, None, True))\n assert_raises(ValueError, model._get_prediction_index, *(4, None, True))\n assert_raises(KeyError, model._get_prediction_index, *('1959Q1', None, True))\n assert_raises(ValueError, model._get_prediction_index, *('1960Q1', None, True))\n\n # raises - index differenced away\n assert_raises(ValueError, model._get_prediction_index, *(0, None, False))\n assert_raises(KeyError, model._get_prediction_index, *('1959Q1', None, False))\n\n # raises - start out of sample\n # TODO: start out of sample is now allowed; remove this code\n # assert_raises(ValueError, model._get_prediction_index, *(204, None, True))\n # assert_raises(ValueError, model._get_prediction_index, *(204, None, False))\n # assert_raises(ValueError, model._get_prediction_index, *('2010Q1', None, True))\n # assert_raises(ValueError, model._get_prediction_index, *('2010Q1', None, False))\n\n # works - in-sample\n # None\n start_test_cases = [\n # given, expected, dynamic\n (None, 4, True),\n # all start get moved back by k_diff\n (5, 4, True),\n (6, 5, True),\n # what about end of sample start - last value is first\n # forecast\n (203, 202, True),\n (1, 0, False),\n (4, 3, False),\n (5, 4, False),\n # all start get moved back by k_diff\n ('1960Q2', 4, True),\n ('1960Q3', 5, True),\n # what about end of sample start - last value is first\n # forecast\n ('2009Q4', 202, True),\n ('1959Q2', 0, False),\n ('1960Q1', 3, False),\n ('1960Q2', 4, False),\n ]\n\n for case in start_test_cases:\n _check_start(*((model,) + case))\n\n # check raises\n #TODO: make sure dates are passing through unmolested\n #assert_raises(ValueError, model._get_predict_end, (\"2001-1-1\",))\n\n # the length of diff(cpi) is 202, so last index is 201\n end_test_cases = [(None, 201, 0),\n (201, 200, 0),\n (202, 201, 0),\n (203, 201, 1),\n (204, 201, 2),\n (51, 50, 0),\n (164+63, 201, 25),\n\n ('2009Q2', 200, 0),\n ('2009Q3', 201, 0),\n ('2009Q4', 201, 1),\n ('2010Q1', 201, 2),\n ('1971Q4', 50, 0),\n ('2015Q4', 201, 25),\n ]\n\n for case in end_test_cases:\n _check_end(*((model,)+case))\n\n # check higher k_diff\n # model.k_diff = 2\n model = ARIMA(cpi, (4,2,1), dates=cpi_dates, freq='Q')\n model.method = 'mle'\n\n # raises - pre-sample + dynamic\n assert_raises(ValueError, model._get_prediction_index, *(0, None, True))\n assert_raises(ValueError, model._get_prediction_index, *(5, None, True))\n assert_raises(KeyError, model._get_prediction_index, *('1959Q1', None, True))\n assert_raises(ValueError, model._get_prediction_index, *('1960Q1', None, True))\n\n # raises - index differenced away\n assert_raises(ValueError, model._get_prediction_index, *(1, None, False))\n assert_raises(KeyError, model._get_prediction_index, *('1959Q2', None, False))\n\n start_test_cases = [(None, 4, True),\n # all start get moved back by k_diff\n (6, 4, True),\n # what about end of sample start - last value is first\n # forecast\n (203, 201, True),\n (2, 0, False),\n (4, 2, False),\n (5, 3, False),\n ('1960Q3', 4, True),\n # what about end of sample start - last value is first\n # forecast\n ('2009Q4', 201, True),\n ('2009Q4', 201, True),\n ('1959Q3', 0, False),\n ('1960Q1', 2, False),\n ('1960Q2', 3, False),\n ]\n\n for case in start_test_cases:\n _check_start(*((model,)+case))\n\n end_test_cases = [(None, 200, 0),\n (201, 199, 0),\n (202, 200, 0),\n (203, 200, 1),\n (204, 200, 2),\n (51, 49, 0),\n (164+63, 200, 25),\n\n ('2009Q2', 199, 0),\n ('2009Q3', 200, 0),\n ('2009Q4', 200, 1),\n ('2010Q1', 200, 2),\n ('1971Q4', 49, 0),\n ('2015Q4', 200, 25),\n ]\n\n for case in end_test_cases:\n _check_end(*((model,)+case))\n\n\ndef test_arima_predict_indices_css():\n cpi = load_macrodata_pandas().data['cpi'].values\n #NOTE: Doing no-constant for now to kick the conditional exogenous\n #issue 274 down the road\n # go ahead and git the model to set up necessary variables\n model = ARIMA(cpi, (4,1,1))\n model.method = 'css'\n\n assert_raises(ValueError, model._get_prediction_index, *(0, None, False))\n assert_raises(ValueError, model._get_prediction_index, *(0, None, True))\n assert_raises(ValueError, model._get_prediction_index, *(2, None, False))\n assert_raises(ValueError, model._get_prediction_index, *(2, None, True))\n\n\ndef test_arima_predict_css():\n cpi = load_macrodata_pandas().data['cpi'].values\n #NOTE: Doing no-constant for now to kick the conditional exogenous\n #issue 274 down the road\n # go ahead and git the model to set up necessary variables\n res1 = ARIMA(cpi, (4,1,1)).fit(disp=-1, method=\"css\",\n trend=\"nc\")\n # but use gretl parameters to predict to avoid precision problems\n params = np.array([ 1.231272508473910,\n -0.282516097759915,\n 0.170052755782440,\n -0.118203728504945,\n -0.938783134717947])\n\n with open(current_path + '/results/results_arima_forecasts_all_css.csv', \"rb\") as test_data:\n arima_forecasts = np.genfromtxt(test_data, delimiter=\",\", skip_header=1, dtype=float)\n fc = arima_forecasts[:,0]\n fcdyn = arima_forecasts[:,1]\n fcdyn2 = arima_forecasts[:,2]\n fcdyn3 = arima_forecasts[:,3]\n fcdyn4 = arima_forecasts[:,4]\n\n #NOTE: should raise\n #start, end = 1,3\n #fv = res1.model.predict(params, start, end)\n ## start < p, end 0 1959q3 - 1960q1\n #start, end = 2, 4\n #fv = res1.model.predict(params, start, end)\n ## start < p, end >0 1959q3 - 1971q4\n #start, end = 2, 51\n #fv = res1.model.predict(params, start, end)\n ## start < p, end nobs 1959q3 - 2009q3\n #start, end = 2, 202\n #fv = res1.model.predict(params, start, end)\n ## start < p, end >nobs 1959q3 - 2015q4\n #start, end = 2, 227\n #fv = res1.model.predict(params, start, end)\n # start 0, end >0 1960q1 - 1971q4\n start, end = 5, 51\n fv = res1.model.predict(params, start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start 0, end nobs 1960q1 - 2009q3\n start, end = 5, 202\n fv = res1.model.predict(params, start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start 0, end >nobs 1960q1 - 2015q4\n #TODO: why detoriating precision?\n fv = res1.model.predict(params, start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end >0 1965q1 - 1971q4\n start, end = 24, 51\n fv = res1.model.predict(params, start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end nobs 1965q1 - 2009q3\n start, end = 24, 202\n fv = res1.model.predict(params, start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end >nobs 1965q1 - 2015q4\n start, end = 24, 227\n fv = res1.model.predict(params, start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start nobs, end nobs 2009q3 - 2009q3\n start, end = 202, 202\n fv = res1.model.predict(params, start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start nobs, end >nobs 2009q3 - 2015q4\n start, end = 202, 227\n fv = res1.model.predict(params, start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >nobs, end >nobs 2009q4 - 2015q4\n start, end = 203, 227\n fv = res1.model.predict(params, start, end, typ='levels')\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # defaults\n start, end = None, None\n fv = res1.model.predict(params, start, end, typ='levels')\n assert_almost_equal(fv, fc[5:203], DECIMAL_4)\n\n #### Dynamic #####\n\n #NOTE: should raise\n # start < p, end <p 1959q2 - 1959q4\n #start, end = 1,3\n #fv = res1.predict(start, end, dynamic=True)\n # start < p, end 0 1959q3 - 1960q1\n #start, end = 2, 4\n #fv = res1.predict(start, end, dynamic=True)\n ## start < p, end >0 1959q3 - 1971q4\n #start, end = 2, 51\n #fv = res1.predict(start, end, dynamic=True)\n ## start < p, end nobs 1959q3 - 2009q3\n #start, end = 2, 202\n #fv = res1.predict(start, end, dynamic=True)\n ## start < p, end >nobs 1959q3 - 2015q4\n #start, end = 2, 227\n #fv = res1.predict(start, end, dynamic=True)\n # start 0, end >0 1960q1 - 1971q4\n start, end = 5, 51\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start 0, end nobs 1960q1 - 2009q3\n start, end = 5, 202\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start 0, end >nobs 1960q1 - 2015q4\n start, end = 5, 227\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start >p, end >0 1965q1 - 1971q4\n start, end = 24, 51\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start >p, end nobs 1965q1 - 2009q3\n start, end = 24, 202\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start >p, end >nobs 1965q1 - 2015q4\n start, end = 24, 227\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start nobs, end nobs 2009q3 - 2009q3\n start, end = 202, 202\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn3[start:end+1], DECIMAL_4)\n # start nobs, end >nobs 2009q3 - 2015q4\n start, end = 202, 227\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n # start >nobs, end >nobs 2009q4 - 2015q4\n start, end = 203, 227\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn4[start:end+1], DECIMAL_4)\n # defaults\n start, end = None, None\n fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')\n assert_almost_equal(fv, fcdyn[5:203], DECIMAL_4)\n\n\ndef test_arima_predict_css_diffs():\n\n cpi = load_macrodata_pandas().data['cpi'].values\n #NOTE: Doing no-constant for now to kick the conditional exogenous\n #issue 274 down the road\n # go ahead and git the model to set up necessary variables\n res1 = ARIMA(cpi, (4,1,1)).fit(disp=-1, method=\"css\",\n trend=\"c\")\n # but use gretl parameters to predict to avoid precision problems\n params = np.array([0.78349893861244,\n -0.533444105973324,\n 0.321103691668809,\n 0.264012463189186,\n 0.107888256920655,\n 0.920132542916995])\n # we report mean, should we report constant?\n params[0] = params[0] / (1 - params[1:5].sum())\n\n with open(current_path + '/results/results_arima_forecasts_all_css_diff.csv', \"rb\") as test_data:\n arima_forecasts = np.genfromtxt(test_data, delimiter=\",\", skip_header=1, dtype=float)\n fc = arima_forecasts[:,0]\n fcdyn = arima_forecasts[:,1]\n fcdyn2 = arima_forecasts[:,2]\n fcdyn3 = arima_forecasts[:,3]\n fcdyn4 = arima_forecasts[:,4]\n\n #NOTE: should raise\n #start, end = 1,3\n #fv = res1.model.predict(params, start, end)\n ## start < p, end 0 1959q3 - 1960q1\n #start, end = 2, 4\n #fv = res1.model.predict(params, start, end)\n ## start < p, end >0 1959q3 - 1971q4\n #start, end = 2, 51\n #fv = res1.model.predict(params, start, end)\n ## start < p, end nobs 1959q3 - 2009q3\n #start, end = 2, 202\n #fv = res1.model.predict(params, start, end)\n ## start < p, end >nobs 1959q3 - 2015q4\n #start, end = 2, 227\n #fv = res1.model.predict(params, start, end)\n # start 0, end >0 1960q1 - 1971q4\n start, end = 5, 51\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start 0, end nobs 1960q1 - 2009q3\n start, end = 5, 202\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start 0, end >nobs 1960q1 - 2015q4\n #TODO: why detoriating precision?\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end >0 1965q1 - 1971q4\n start, end = 24, 51\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end nobs 1965q1 - 2009q3\n start, end = 24, 202\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end >nobs 1965q1 - 2015q4\n start, end = 24, 227\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start nobs, end nobs 2009q3 - 2009q3\n start, end = 202, 202\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start nobs, end >nobs 2009q3 - 2015q4\n start, end = 202, 227\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >nobs, end >nobs 2009q4 - 2015q4\n start, end = 203, 227\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # defaults\n start, end = None, None\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[5:203], DECIMAL_4)\n\n #### Dynamic #####\n\n #NOTE: should raise\n # start < p, end <p 1959q2 - 1959q4\n #start, end = 1,3\n #fv = res1.predict(start, end, dynamic=True)\n # start < p, end 0 1959q3 - 1960q1\n #start, end = 2, 4\n #fv = res1.predict(start, end, dynamic=True)\n ## start < p, end >0 1959q3 - 1971q4\n #start, end = 2, 51\n #fv = res1.predict(start, end, dynamic=True)\n ## start < p, end nobs 1959q3 - 2009q3\n #start, end = 2, 202\n #fv = res1.predict(start, end, dynamic=True)\n ## start < p, end >nobs 1959q3 - 2015q4\n #start, end = 2, 227\n #fv = res1.predict(start, end, dynamic=True)\n # start 0, end >0 1960q1 - 1971q4\n start, end = 5, 51\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start 0, end nobs 1960q1 - 2009q3\n start, end = 5, 202\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start 0, end >nobs 1960q1 - 2015q4\n start, end = 5, 227\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start >p, end >0 1965q1 - 1971q4\n start, end = 24, 51\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start >p, end nobs 1965q1 - 2009q3\n start, end = 24, 202\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start >p, end >nobs 1965q1 - 2015q4\n start, end = 24, 227\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start nobs, end nobs 2009q3 - 2009q3\n start, end = 202, 202\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn3[start:end+1], DECIMAL_4)\n # start nobs, end >nobs 2009q3 - 2015q4\n start, end = 202, 227\n fv = res1.model.predict(params, start, end, dynamic=True)\n # start >nobs, end >nobs 2009q4 - 2015q4\n start, end = 203, 227\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn4[start:end+1], DECIMAL_4)\n # defaults\n start, end = None, None\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn[5:203], DECIMAL_4)\n\n\ndef test_arima_predict_mle_diffs():\n\n cpi = load_macrodata_pandas().data['cpi'].values\n #NOTE: Doing no-constant for now to kick the conditional exogenous\n #issue 274 down the road\n # go ahead and git the model to set up necessary variables\n res1 = ARIMA(cpi, (4,1,1)).fit(disp=-1, trend=\"c\")\n # but use gretl parameters to predict to avoid precision problems\n params = np.array([0.926875951549299,\n -0.555862621524846,\n 0.320865492764400,\n 0.252253019082800,\n 0.113624958031799,\n 0.939144026934634])\n\n with open(current_path + '/results/results_arima_forecasts_all_mle_diff.csv', \"rb\") as test_data:\n arima_forecasts = np.genfromtxt(test_data, delimiter=\",\", skip_header=1, dtype=float)\n fc = arima_forecasts[:,0]\n fcdyn = arima_forecasts[:,1]\n fcdyn2 = arima_forecasts[:,2]\n fcdyn3 = arima_forecasts[:,3]\n fcdyn4 = arima_forecasts[:,4]\n\n #NOTE: should raise\n start, end = 1,3\n fv = res1.model.predict(params, start, end)\n ## start < p, end 0 1959q3 - 1960q1\n start, end = 2, 4\n fv = res1.model.predict(params, start, end)\n ## start < p, end >0 1959q3 - 1971q4\n start, end = 2, 51\n fv = res1.model.predict(params, start, end)\n ## start < p, end nobs 1959q3 - 2009q3\n start, end = 2, 202\n fv = res1.model.predict(params, start, end)\n ## start < p, end >nobs 1959q3 - 2015q4\n start, end = 2, 227\n fv = res1.model.predict(params, start, end)\n # start 0, end >0 1960q1 - 1971q4\n start, end = 5, 51\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start 0, end nobs 1960q1 - 2009q3\n start, end = 5, 202\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start 0, end >nobs 1960q1 - 2015q4\n #TODO: why detoriating precision?\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end >0 1965q1 - 1971q4\n start, end = 24, 51\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end nobs 1965q1 - 2009q3\n start, end = 24, 202\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >p, end >nobs 1965q1 - 2015q4\n start, end = 24, 227\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start nobs, end nobs 2009q3 - 2009q3\n start, end = 202, 202\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start nobs, end >nobs 2009q3 - 2015q4\n start, end = 202, 227\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # start >nobs, end >nobs 2009q4 - 2015q4\n start, end = 203, 227\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[start:end+1], DECIMAL_4)\n # defaults\n start, end = None, None\n fv = res1.model.predict(params, start, end)\n assert_almost_equal(fv, fc[1:203], DECIMAL_4)\n\n #### Dynamic #####\n\n #NOTE: should raise\n # start < p, end <p 1959q2 - 1959q4\n #start, end = 1,3\n #fv = res1.predict(start, end, dynamic=True)\n # start < p, end 0 1959q3 - 1960q1\n #start, end = 2, 4\n #fv = res1.predict(start, end, dynamic=True)\n ## start < p, end >0 1959q3 - 1971q4\n #start, end = 2, 51\n #fv = res1.predict(start, end, dynamic=True)\n ## start < p, end nobs 1959q3 - 2009q3\n #start, end = 2, 202\n #fv = res1.predict(start, end, dynamic=True)\n ## start < p, end >nobs 1959q3 - 2015q4\n #start, end = 2, 227\n #fv = res1.predict(start, end, dynamic=True)\n # start 0, end >0 1960q1 - 1971q4\n start, end = 5, 51\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start 0, end nobs 1960q1 - 2009q3\n start, end = 5, 202\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start 0, end >nobs 1960q1 - 2015q4\n start, end = 5, 227\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn[start:end+1], DECIMAL_4)\n # start >p, end >0 1965q1 - 1971q4\n start, end = 24, 51\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start >p, end nobs 1965q1 - 2009q3\n start, end = 24, 202\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start >p, end >nobs 1965q1 - 2015q4\n start, end = 24, 227\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn2[start:end+1], DECIMAL_4)\n # start nobs, end nobs 2009q3 - 2009q3\n start, end = 202, 202\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn3[start:end+1], DECIMAL_4)\n # start nobs, end >nobs 2009q3 - 2015q4\n start, end = 202, 227\n fv = res1.model.predict(params, start, end, dynamic=True)\n # start >nobs, end >nobs 2009q4 - 2015q4\n start, end = 203, 227\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn4[start:end+1], DECIMAL_4)\n # defaults\n start, end = None, None\n fv = res1.model.predict(params, start, end, dynamic=True)\n assert_almost_equal(fv, fcdyn[5:203], DECIMAL_4)\n\n\ndef test_arima_wrapper():\n cpi = load_macrodata_pandas().data['cpi']\n cpi.index = pd.Index(cpi_dates)\n res = ARIMA(cpi, (4,1,1), freq='Q').fit(disp=-1)\n assert_equal(res.params.index, pd.Index(['const', 'ar.L1.D.cpi', 'ar.L2.D.cpi',\n 'ar.L3.D.cpi', 'ar.L4.D.cpi',\n 'ma.L1.D.cpi']))\n assert_equal(res.model.endog_names, 'D.cpi')\n\n\[email protected]\ndef test_1dexog():\n # smoke test, this will raise an error if broken\n dta = load_macrodata_pandas().data\n endog = dta['realcons'].values\n exog = dta['m1'].values.squeeze()\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n mod = ARMA(endog, (1,1), exog).fit(disp=-1)\n mod.predict(193, 203, exog[-10:])\n\n # check for dynamic is true and pandas Series see #2589\n mod.predict(193, 202, exog[-10:], dynamic=True)\n\n dta.index = pd.Index(cpi_dates)\n mod = ARMA(dta['realcons'], (1,1), dta['m1']).fit(disp=-1)\n mod.predict(dta.index[-10], dta.index[-1], exog=dta['m1'][-10:], dynamic=True)\n\n mod = ARMA(dta['realcons'], (1,1), dta['m1']).fit(trend='nc', disp=-1)\n mod.predict(dta.index[-10], dta.index[-1], exog=dta['m1'][-10:], dynamic=True)\n\n\ndef test_arima_predict_bug():\n #predict_start_date was not getting set on start = None\n from statsmodels.datasets import sunspots\n dta = sunspots.load_pandas().data.SUNACTIVITY\n dta.index = pd.date_range(start='1700', end='2009', freq='A')[:309]\n arma_mod20 = ARMA(dta, (2,0)).fit(disp=-1)\n arma_mod20.predict(None, None)\n\n # test prediction with time stamp, see #2587\n predict = arma_mod20.predict(dta.index[-20], dta.index[-1])\n assert_(predict.index.equals(dta.index[-20:]))\n predict = arma_mod20.predict(dta.index[-20], dta.index[-1], dynamic=True)\n assert_(predict.index.equals(dta.index[-20:]))\n # partially out of sample\n predict_dates = pd.date_range(start='2000', end='2015', freq='A')\n predict = arma_mod20.predict(predict_dates[0], predict_dates[-1])\n assert_(predict.index.equals(predict_dates))\n #assert_(1 == 0)\n\n\ndef test_arima_predict_q2():\n # bug with q > 1 for arima predict\n inv = load_macrodata_pandas().data['realinv'].values\n arima_mod = ARIMA(np.log(inv), (1,1,2)).fit(start_params=[0,0,0,0], disp=-1)\n fc, stderr, conf_int = arima_mod.forecast(5)\n # values copy-pasted from gretl\n assert_almost_equal(fc,\n [7.306320, 7.313825, 7.321749, 7.329827, 7.337962],\n 5)\n\n\ndef test_arima_predict_pandas_nofreq():\n # this is issue 712\n dates = [\"2010-01-04\", \"2010-01-05\", \"2010-01-06\", \"2010-01-07\",\n \"2010-01-08\", \"2010-01-11\", \"2010-01-12\", \"2010-01-11\",\n \"2010-01-12\", \"2010-01-13\", \"2010-01-17\"]\n close = [626.75, 623.99, 608.26, 594.1, 602.02, 601.11, 590.48, 587.09,\n 589.85, 580.0,587.62]\n data = pd.DataFrame(close, index=DatetimeIndex(dates), columns=[\"close\"])\n\n # TODO: fix this names bug for non-string names names\n with pytest.warns(ValueWarning, match=\"it has no associated frequency\"):\n arma = ARMA(data, order=(1, 0)).fit(disp=-1)\n\n # first check that in-sample prediction works\n predict = arma.predict()\n\n assert_(predict.index.equals(data.index))\n\n # check that this raises an exception when date not on index\n assert_raises(KeyError, arma.predict, start=\"2010-1-9\", end=10)\n assert_raises(KeyError, arma.predict, start=\"2010-1-9\", end=\"2010-1-17\")\n\n # raise because end not on index\n assert_raises(KeyError, arma.predict, start=\"2010-1-4\", end=\"2010-1-10\")\n # raise because end not on index\n assert_raises(KeyError, arma.predict, start=3, end=\"2010-1-10\")\n\n predict = arma.predict(start=\"2010-1-7\", end=10) # should be of length 10\n assert_(len(predict) == 8)\n assert_(predict.index.equals(data.index[3:10+1]))\n\n with pytest.warns(ValueWarning, match=\"No supported index is available\"):\n predict = arma.predict(start=\"2010-1-7\", end=14)\n\n assert_(predict.index.equals(pd.Index(lrange(3, 15))))\n\n with pytest.warns(ValueWarning, match=\"No supported index is available\"):\n predict = arma.predict(start=3, end=14)\n\n assert_(predict.index.equals(pd.Index(lrange(3, 15))))\n\n # end can be a date if it's in the sample and on the index\n # predict dates is just a slice of the dates index then\n predict = arma.predict(start=\"2010-1-6\", end=\"2010-1-13\")\n assert_(predict.index.equals(data.index[2:10]))\n predict = arma.predict(start=2, end=\"2010-1-13\")\n assert_(predict.index.equals(data.index[2:10]))\n\n\ndef test_arima_predict_exog():\n # check 625 and 626\n #from statsmodels.tsa.arima_process import arma_generate_sample\n #arparams = np.array([1, -.45, .25])\n #maparams = np.array([1, .15])\n #nobs = 100\n #np.random.seed(123)\n #y = arma_generate_sample(arparams, maparams, nobs, burnin=100)\n\n ## make an exogenous trend\n #X = np.array(lrange(nobs)) / 20.0\n ## add a constant\n #y += 2.5\n\n from pandas import read_csv\n arima_forecasts = read_csv(current_path + \"/results/\"\n \"results_arima_exog_forecasts_mle.csv\")\n y = arima_forecasts[\"y\"].dropna()\n X = np.arange(len(y) + 25)/20.\n predict_expected = arima_forecasts[\"predict\"]\n arma_res = ARMA(y.values, order=(2,1), exog=X[:100]).fit(trend=\"c\",\n disp=-1)\n # params from gretl\n params = np.array([2.786912485145725, -0.122650190196475,\n 0.533223846028938, -0.319344321763337,\n 0.132883233000064])\n assert_almost_equal(arma_res.params, params, 5)\n # no exog for in-sample\n predict = arma_res.predict()\n assert_almost_equal(predict, predict_expected.values[:100], 5)\n\n # check 626\n assert_(len(arma_res.model.exog_names) == 5)\n\n # exog for out-of-sample and in-sample dynamic\n predict = arma_res.model.predict(params, end=124, exog=X[100:])\n assert_almost_equal(predict, predict_expected.values, 6)\n\n # conditional sum of squares\n #arima_forecasts = read_csv(current_path + \"/results/\"\n # \"results_arima_exog_forecasts_css.csv\")\n #predict_expected = arima_forecasts[\"predict\"].dropna()\n #arma_res = ARMA(y.values, order=(2,1), exog=X[:100]).fit(trend=\"c\",\n # method=\"css\",\n # disp=-1)\n\n #params = np.array([2.152350033809826, -0.103602399018814,\n # 0.566716580421188, -0.326208009247944,\n # 0.102142932143421])\n #predict = arma_res.model.predict(params)\n ## in-sample\n #assert_almost_equal(predict, predict_expected.values[:98], 6)\n\n #predict = arma_res.model.predict(params, end=124, exog=X[100:])\n ## exog for out-of-sample and in-sample dynamic\n #assert_almost_equal(predict, predict_expected.values, 3)\n\n\[email protected]\ndef test_arima_no_diff():\n # GH#736\n # smoke test, predict will break if we have ARIMAResults but\n # ARMA model, need ARIMA(p, 0, q) to return an ARMA in init.\n ar = [1, -.75, .15, .35]\n ma = [1, .25, .9]\n np.random.seed(12345)\n y = arma_generate_sample(ar, ma, 100)\n mod = ARIMA(y, (3, 0, 2))\n assert_(type(mod) is ARMA)\n res = mod.fit(disp=-1)\n # smoke test just to be sure\n res.predict()\n\n\[email protected]\ndef test_arima_predict_noma():\n # GH#657\n ar = [1, .75]\n ma = [1]\n np.random.seed(12345)\n data = arma_generate_sample(ar, ma, 100)\n arma = ARMA(data, order=(0,1))\n arma_res = arma.fit(disp=-1)\n arma_res.forecast(1)\n\n\ndef test_arimax():\n dta = load_macrodata_pandas().data\n dates = pd.date_range(\"1959\", periods=len(dta), freq='Q')\n dta.index = cpi_dates\n dta = dta[[\"realdpi\", \"m1\", \"realgdp\"]]\n y = dta.pop(\"realdpi\")\n\n # 1 exog\n #X = dta.iloc[1:][\"m1\"]\n #res = ARIMA(y, (2, 1, 1), X).fit(disp=-1)\n #params = [23.902305009084373, 0.024650911502790, -0.162140641341602,\n # 0.165262136028113, -0.066667022903974]\n #assert_almost_equal(res.params.values, params, 6)\n\n # 2 exog\n X = dta\n res = ARIMA(y, (2, 1, 1), X).fit(disp=False, solver=\"nm\", maxiter=1000,\n ftol=1e-12, xtol=1e-12)\n\n # from gretl\n #params = [13.113976653926638, -0.003792125069387, 0.004123504809217,\n # -0.199213760940898, 0.151563643588008, -0.033088661096699]\n # from stata using double\n stata_llf = -1076.108614859121\n params = [13.1259220104, -0.00376814509403812, 0.00411970083135622,\n -0.19921477896158524, 0.15154396192855729, -0.03308400760360837]\n # we can get close\n assert_almost_equal(res.params.values, params, 4)\n\n # This shows that it's an optimizer problem and not a problem in the code\n assert_almost_equal(res.model.loglike(np.array(params)), stata_llf, 6)\n\n X = dta.diff()\n X.iloc[0] = 0\n res = ARIMA(y, (2, 1, 1), X).fit(disp=False)\n\n # gretl will not estimate this - looks like maybe a bug on their part,\n # but we can just fine, we're close to Stata's answer\n # from Stata\n params = [19.5656863783347, 0.32653841355833396198,\n 0.36286527042965188716, -1.01133792126884,\n -0.15722368379307766206, 0.69359822544092153418]\n\n assert_almost_equal(res.params.values, params, 3)\n\n\ndef test_bad_start_params():\n endog = np.array([\n 820.69093, 781.0103028, 785.8786988, 767.64282267,\n 778.9837648, 824.6595702, 813.01877867, 751.65598567,\n 753.431091, 746.920813, 795.6201904, 772.65732833,\n 793.4486454, 868.8457766, 823.07226547, 783.09067747,\n 791.50723847, 770.93086347, 835.34157333, 810.64147947,\n 738.36071367, 776.49038513, 822.93272333, 815.26461227,\n 773.70552987, 777.3726522, 811.83444853, 840.95489133,\n 777.51031933, 745.90077307, 806.95113093, 805.77521973,\n 756.70927733, 749.89091773, 1694.2266924, 2398.4802244,\n 1434.6728516, 909.73940427, 929.01291907, 769.07561453,\n 801.1112548, 796.16163313, 817.2496376, 857.73046447,\n 838.849345, 761.92338873, 731.7842242, 770.4641844])\n\n mod = ARMA(endog, (15, 0))\n with pytest.raises(ValueError, match=\"pass your own start_params\"):\n with pytest.warns(RuntimeWarning, match=\"encountered in sqrt\"):\n # numpy warns \"invalid value encountered in sqrt\"\n mod.fit()\n\n inv = load_macrodata_pandas().data['realinv'].values\n arima_mod = ARIMA(np.log(inv), (1, 1, 2))\n with pytest.raises(ValueError):\n arima_mod.fit()\n\n\ndef test_arima_small_data_bug():\n # Issue 1038, too few observations with given order\n import statsmodels.api as sm\n\n vals = [96.2, 98.3, 99.1, 95.5, 94.0, 87.1, 87.9, 86.7402777504474]\n\n dr = pd.date_range(\"1990\", periods=len(vals), freq='Q')\n ts = pd.Series(vals, index=dr)\n df = pd.DataFrame(ts)\n mod = sm.tsa.ARIMA(df, (2, 0, 2))\n assert_raises(ValueError, mod.fit)\n\n\[email protected]\ndef test_arima_dataframe_integer_name():\n # Smoke Test for Issue GH#1038\n import statsmodels.api as sm\n\n vals = [96.2, 98.3, 99.1, 95.5, 94.0, 87.1, 87.9, 86.7402777504474,\n 94.0, 96.5, 93.3, 97.5, 96.3, 92.]\n\n dr = pd.date_range(\"1990\", periods=len(vals), freq='Q')\n ts = pd.Series(vals, index=dr)\n df = pd.DataFrame(ts)\n mod = sm.tsa.ARIMA(df, (2, 0, 2))\n\n\ndef test_arima_exog_predict_1d():\n # test 1067\n np.random.seed(12345)\n y = np.random.random(100)\n x = np.random.random(100)\n mod = ARMA(y, (2, 1), x).fit(disp=-1)\n newx = np.random.random(10)\n mod.forecast(steps=10, alpha=0.05, exog=newx)\n\n with pytest.raises(ValueError):\n mod.forecast(steps=10, alpha=0.05, exog=newx[:5])\n\n with pytest.raises(ValueError):\n mod.forecast(steps=10, alpha=0.05)\n\n too_many = pd.DataFrame(np.zeros((10, 2)),\n columns=['x1', 'x2'])\n with pytest.raises(ValueError):\n mod.forecast(steps=10, alpha=0.05, exog=too_many)\n\n\ndef test_arima_1123():\n # test ARMAX predict when trend is none\n np.random.seed(12345)\n arparams = np.array([.75, -.25])\n maparams = np.array([.65, .35])\n\n arparam = np.r_[1, -arparams]\n maparam = np.r_[1, maparams]\n\n nobs = 20\n\n dates = pd.date_range(start='1980', periods=nobs, freq='A')\n\n np.random.seed(12345)\n y = arma_generate_sample(arparams, maparams, nobs)\n\n X = np.random.randn(nobs)\n y += 5*X\n mod = ARMA(y[:-1], order=(1,0), exog=X[:-1])\n res = mod.fit(trend='nc', disp=False)\n fc = res.forecast(exog=X[-1:])\n # results from gretl\n assert_almost_equal(fc[0], 2.200393, 6)\n assert_almost_equal(fc[1], 1.030743, 6)\n assert_almost_equal(fc[2][0,0], 0.180175, 6)\n assert_almost_equal(fc[2][0,1], 4.220611, 6)\n\n mod = ARMA(y[:-1], order=(1,1), exog=X[:-1])\n res = mod.fit(trend='nc', disp=False)\n fc = res.forecast(exog=X[-1:])\n assert_almost_equal(fc[0], 2.765688, 6)\n assert_almost_equal(fc[1], 0.835048, 6)\n assert_almost_equal(fc[2][0,0], 1.129023, 6)\n assert_almost_equal(fc[2][0,1], 4.402353, 6)\n\n # make sure this works to. code looked fishy.\n mod = ARMA(y[:-1], order=(1,0), exog=X[:-1])\n res = mod.fit(trend='c', disp=False)\n fc = res.forecast(exog=X[-1:])\n assert_almost_equal(fc[0], 2.481219, 6)\n assert_almost_equal(fc[1], 0.968759, 6)\n assert_almost_equal(fc[2][0], [0.582485, 4.379952], 6)\n\n\ndef test_small_data():\n # 1146\n y = [-1214.360173, -1848.209905, -2100.918158, -3647.483678, -4711.186773]\n\n # refuse to estimate these\n assert_raises(ValueError, ARIMA, y, (2, 0, 3))\n assert_raises(ValueError, ARIMA, y, (1, 1, 3))\n mod = ARIMA(y, (1, 0, 3))\n assert_raises(ValueError, mod.fit, trend=\"c\")\n\n # try to estimate these...leave it up to the user to check for garbage\n # and be clear, these are garbage parameters.\n # X-12 arima will estimate, gretl refuses to estimate likely a problem\n # in start params regression.\n res = mod.fit(trend=\"nc\", disp=0, start_params=[.1,.1,.1,.1])\n mod = ARIMA(y, (1, 0, 2))\n import warnings\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n res = mod.fit(disp=0, start_params=[np.mean(y), .1, .1, .1])\n\n\nclass TestARMA00(object):\n\n @classmethod\n def setup_class(cls):\n from statsmodels.datasets.sunspots import load_pandas\n\n sunspots = load_pandas().data['SUNACTIVITY'].values\n cls.y = y = sunspots\n cls.arma_00_model = ARMA(y, order=(0, 0))\n cls.arma_00_res = cls.arma_00_model.fit(disp=-1)\n\n def test_parameters(self):\n params = self.arma_00_res.params\n assert_almost_equal(self.y.mean(), params)\n\n def test_predictions(self):\n predictions = self.arma_00_res.predict()\n assert_almost_equal(self.y.mean() * np.ones_like(predictions), predictions)\n\n def test_arroots(self):\n # regression test; older implementation of arroots returned None\n # instead of en empty array\n roots = self.arma_00_res.arroots\n assert_equal(roots.size, 0)\n\n def test_maroots(self):\n # regression test; older implementation of arroots returned None\n # instead of en empty array\n roots = self.arma_00_res.maroots\n assert_equal(roots.size, 0)\n\n @pytest.mark.skip(\"This test is invalid since the ICs differ due to \"\n \"df_model differences between OLS and ARIMA\")\n def test_information_criteria(self):\n res = self.arma_00_res\n y = self.y\n ols_res = OLS(y, np.ones_like(y)).fit(disp=-1)\n ols_ic = np.array([ols_res.aic, ols_res.bic])\n arma_ic = np.array([res.aic, res.bic])\n assert_almost_equal(ols_ic, arma_ic, DECIMAL_4)\n\n def test_arma_00_nc(self):\n arma_00 = ARMA(self.y, order=(0, 0))\n assert_raises(ValueError, arma_00.fit, trend='nc', disp=-1)\n\n def test_css(self):\n arma = ARMA(self.y, order=(0, 0))\n fit = arma.fit(method='css', disp=-1)\n predictions = fit.predict()\n assert_almost_equal(self.y.mean() * np.ones_like(predictions), predictions)\n\n def test_arima(self):\n yi = np.cumsum(self.y)\n arima = ARIMA(yi, order=(0, 1, 0))\n fit = arima.fit(disp=-1)\n assert_almost_equal(np.diff(yi).mean(), fit.params, DECIMAL_4)\n\n def test_arma_ols(self):\n y = self.y\n y_lead = y[1:]\n y_lag = y[:-1]\n T = y_lag.shape[0]\n X = np.hstack((np.ones((T,1)), y_lag[:,None]))\n ols_res = OLS(y_lead, X).fit()\n arma_res = ARMA(y_lead,order=(0,0),exog=y_lag).fit(trend='c', disp=-1)\n assert_almost_equal(ols_res.params, arma_res.params)\n\n def test_arma_exog_no_constant(self):\n y = self.y\n y_lead = y[1:]\n y_lag = y[:-1]\n X = y_lag[:,None]\n ols_res = OLS(y_lead, X).fit()\n arma_res = ARMA(y_lead,order=(0,0),exog=y_lag).fit(trend='nc', disp=-1)\n assert_almost_equal(ols_res.params, arma_res.params)\n\n\ndef test_arima_dates_startatend():\n # bug\n np.random.seed(18)\n x = pd.Series(np.random.random(36),\n index=pd.date_range(start='1/1/1990',\n periods=36, freq='M'))\n res = ARIMA(x, (1, 0, 0)).fit(disp=0)\n pred = res.predict(start=len(x), end=len(x))\n assert_(pred.index[0] == x.index.shift(1)[-1])\n fc = res.forecast()[0]\n assert_almost_equal(pred.values[0], fc)\n\n\ndef test_arma_missing():\n from statsmodels.tools.sm_exceptions import MissingDataError\n # bug 1343\n y = np.random.random(40)\n y[-1] = np.nan\n assert_raises(MissingDataError, ARMA, y, (1, 0), missing='raise')\n\n\[email protected]\ndef test_plot_predict(close_figures):\n from statsmodels.datasets.sunspots import load_pandas\n\n dta = load_pandas().data[['SUNACTIVITY']]\n dta.index = date_range(start='1700', end='2009', freq='A')[:309]\n res = ARMA(dta, (3, 0)).fit(disp=-1)\n fig = res.plot_predict('1990', '2012', dynamic=True, plot_insample=False)\n\n res = ARIMA(dta, (3, 1, 0)).fit(disp=-1)\n fig = res.plot_predict('1990', '2012', dynamic=True, plot_insample=False)\n\n\ndef test_arima_diff2():\n dta = load_macrodata_pandas().data['cpi']\n dates = pd.date_range(\"1959\", periods=len(dta), freq='Q')\n dta.index = cpi_dates\n mod = ARIMA(dta, (3, 2, 1)).fit(disp=-1)\n fc, fcerr, conf_int = mod.forecast(10)\n # forecasts from gretl\n conf_int_res = [ (216.139, 219.231),\n (216.472, 221.520),\n (217.064, 223.649),\n (217.586, 225.727),\n (218.119, 227.770),\n (218.703, 229.784),\n (219.306, 231.777),\n (219.924, 233.759),\n (220.559, 235.735),\n (221.206, 237.709)]\n\n fc_res = [217.685, 218.996, 220.356, 221.656, 222.945, 224.243, 225.541,\n 226.841, 228.147, 229.457]\n fcerr_res = [0.7888, 1.2878, 1.6798, 2.0768, 2.4620, 2.8269, 3.1816,\n 3.52950, 3.8715, 4.2099]\n\n assert_almost_equal(fc, fc_res, 3)\n assert_almost_equal(fcerr, fcerr_res, 3)\n assert_almost_equal(conf_int, conf_int_res, 3)\n\n predicted = mod.predict('2008Q1', '2012Q1', typ='levels')\n\n predicted_res = [214.464, 215.478, 221.277, 217.453, 212.419, 213.530,\n 215.087, 217.685 , 218.996 , 220.356 , 221.656 ,\n 222.945 , 224.243 , 225.541 , 226.841 , 228.147 ,\n 229.457]\n assert_almost_equal(predicted, predicted_res, 3)\n\n\ndef test_arima111_predict_exog_2127():\n # regression test for issue #2127\n ef = [0.03005, 0.03917, 0.02828, 0.03644, 0.03379, 0.02744,\n 0.03343, 0.02621, 0.03050, 0.02455, 0.03261, 0.03507,\n 0.02734, 0.05373, 0.02677, 0.03443, 0.03331, 0.02741,\n 0.03709, 0.02113, 0.03343, 0.02011, 0.03675, 0.03077,\n 0.02201, 0.04844, 0.05518, 0.03765, 0.05433, 0.03049,\n 0.04829, 0.02936, 0.04421, 0.02457, 0.04007, 0.03009,\n 0.04504, 0.05041, 0.03651, 0.02719, 0.04383, 0.02887,\n 0.03440, 0.03348, 0.02364, 0.03496, 0.02549, 0.03284,\n 0.03523, 0.02579, 0.03080, 0.01784, 0.03237, 0.02078,\n 0.03508, 0.03062, 0.02006, 0.02341, 0.02223, 0.03145,\n 0.03081, 0.02520, 0.02683, 0.01720, 0.02225, 0.01579,\n 0.02237, 0.02295, 0.01830, 0.02356, 0.02051, 0.02932,\n 0.03025, 0.02390, 0.02635, 0.01863, 0.02994, 0.01762,\n 0.02837, 0.02421, 0.01951, 0.02149, 0.02079, 0.02528,\n 0.02575, 0.01634, 0.02563, 0.01719, 0.02915, 0.01724,\n 0.02804, 0.02750, 0.02099, 0.02522, 0.02422, 0.03254,\n 0.02095, 0.03241, 0.01867, 0.03998, 0.02212, 0.03034,\n 0.03419, 0.01866, 0.02623, 0.02052]\n ue = [4.9, 5.0, 5.0, 5.0, 4.9, 4.7, 4.8, 4.7, 4.7,\n 4.6, 4.6, 4.7, 4.7, 4.5, 4.4, 4.5, 4.4, 4.6,\n 4.5, 4.4, 4.5, 4.4, 4.6, 4.7, 4.6, 4.7, 4.7,\n 4.7, 5.0, 5.0, 4.9, 5.1, 5.0, 5.4, 5.6, 5.8,\n 6.1, 6.1, 6.5, 6.8, 7.3, 7.8, 8.3, 8.7, 9.0,\n 9.4, 9.5, 9.5, 9.6, 9.8, 10., 9.9, 9.9, 9.7,\n 9.8, 9.9, 9.9, 9.6, 9.4, 9.5, 9.5, 9.5, 9.5,\n 9.8, 9.4, 9.1, 9.0, 9.0, 9.1, 9.0, 9.1, 9.0,\n 9.0, 9.0, 8.8, 8.6, 8.5, 8.2, 8.3, 8.2, 8.2,\n 8.2, 8.2, 8.2, 8.1, 7.8, 7.8, 7.8, 7.9, 7.9,\n 7.7, 7.5, 7.5, 7.5, 7.5, 7.3, 7.2, 7.2, 7.2,\n 7.0, 6.7, 6.6, 6.7, 6.7, 6.3, 6.3]\n\n ue = np.array(ue) / 100\n model = ARIMA(ef, (1, 1, 1), exog=ue)\n res = model.fit(transparams=False, pgtol=1e-8, iprint=0, disp=0)\n assert_equal(res.mle_retvals['warnflag'], 0)\n predicts = res.predict(start=len(ef), end=len(ef) + 10,\n exog=ue[-11:], typ='levels')\n\n # regression test, not verified numbers\n predicts_res = np.array([\n 0.02591095, 0.02321325, 0.02436579, 0.02368759, 0.02389753,\n 0.02372, 0.0237481, 0.0236738, 0.023644, 0.0236283,\n 0.02362267])\n\n assert_allclose(predicts, predicts_res, atol=5e-6)\n\n # Smoke check of forecast with exog in ARIMA\n res.forecast(steps=10, exog=np.empty(10))\n\n with pytest.raises(ValueError):\n res.forecast(steps=10)\n with pytest.raises(ValueError):\n res.forecast(steps=10, exog=np.empty((10, 2)))\n with pytest.raises(ValueError):\n res.forecast(steps=10, exog=np.empty(100))\n\n\ndef test_arima_exog_predict():\n # test forecasting and dynamic prediction with exog against Stata\n\n dta = load_macrodata_pandas().data\n dates = pd.date_range(\"1959\", periods=len(dta), freq='Q')\n cpi_dates = period_range(start='1959Q1', end='2009Q3', freq='Q')\n dta.index = cpi_dates\n\n data = dta\n data['loginv'] = np.log(data['realinv'])\n data['loggdp'] = np.log(data['realgdp'])\n data['logcons'] = np.log(data['realcons'])\n\n forecast_period = period_range(start='2008Q2', end='2009Q4', freq='Q')\n end = forecast_period[0]\n data_sample = data.loc[dta.index < end]\n\n exog_full = data[['loggdp', 'logcons']]\n\n # pandas\n\n mod = ARIMA(data_sample['loginv'], (1, 0, 1),\n exog=data_sample[['loggdp', 'logcons']])\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n res = mod.fit(disp=0, solver='bfgs', maxiter=5000)\n\n predicted_arma_fp = res.predict(start=197, end=202,\n exog=exog_full.values[197:]).values\n predicted_arma_dp = res.predict(start=193, end=202,\n exog=exog_full[197:], dynamic=True)\n\n # numpy\n mod2 = ARIMA(np.asarray(data_sample['loginv']), (1, 0, 1),\n exog=np.asarray(data_sample[['loggdp', 'logcons']]))\n res2 = mod2.fit(start_params=res.params, disp=0,\n solver='bfgs', maxiter=5000)\n\n exog_full = data[['loggdp', 'logcons']]\n predicted_arma_f = res2.predict(start=197, end=202,\n exog=exog_full.values[197:])\n predicted_arma_d = res2.predict(start=193, end=202,\n exog=exog_full[197:], dynamic=True)\n\n endog_scale = 100\n ex_scale = 1000\n # ARIMA(1, 1, 1)\n ex = ex_scale * np.asarray(data_sample[['loggdp', 'logcons']].diff())\n # The first obsevation is not (supposed to be) used, but I get a Lapack problem\n # Intel MKL ERROR: Parameter 5 was incorrect on entry to DLASCL.\n ex[0] = 0\n mod111 = ARIMA(100 * np.asarray(data_sample['loginv']), (1, 1, 1),\n # Stata differences also the exog\n exog=ex)\n sv = [-0.94771574, 0.5869353, -0.32651653, 0.78066562, -0.68747501]\n res111 = mod111.fit(start_params=sv, disp=0, solver='bfgs', maxiter=5000)\n exog_full_d = ex_scale * data[['loggdp', 'logcons']].diff()\n res111.predict(start=197, end=202, exog=exog_full_d.values[197:])\n\n predicted_arima_f = res111.predict(start=196, end=202,\n exog=exog_full_d.values[197:],\n typ='levels')\n predicted_arima_d = res111.predict(start=193, end=202,\n exog=exog_full_d.values[197:],\n typ='levels', dynamic=True)\n\n res_f101 = np.array(\n [7.73975859954, 7.71660108543, 7.69808978329, 7.70872117504,\n 7.65183927580, 7.69784279784, 7.70290907856, 7.69237782644,\n 7.65017785174, 7.66061689028, 7.65980022857, 7.61505314129,\n 7.51697158428, 7.51657606630, 7.5271053284])\n res_f111 = np.array(\n [7.74460013693, 7.71958207517, 7.69629561172, 7.71208186737,\n 7.65758850178, 7.69223472572, 7.70411775588, 7.68896109499,\n 7.64016249001, 7.64871881901, 7.62550283402, 7.55814609462,\n 7.44431310053, 7.42963968062, 7.43554675427])\n res_d111 = np.array(\n [7.74460013693, 7.71958207517, 7.69629561172, 7.71208186737,\n 7.65758850178, 7.69223472572, 7.71870821151, 7.72994302150,\n 7.71439447355, 7.72544001101, 7.70521902623, 7.64020040524,\n 7.52819271910, 7.51494426940, 7.52196378005])\n res_d101 = np.array(\n [7.73975859954, 7.71660108543, 7.69808978329, 7.70872117504,\n 7.65183927580, 7.69784279784, 7.72522142662, 7.73962377858,\n 7.73245950636, 7.74935432862, 7.74449584691, 7.69589103679,\n 7.59412746880, 7.59021764836, 7.59739267775])\n\n # Relax tolerance on OSX due to frequent small failures\n # GH 4657\n tol = 1e-3 if PLATFORM_OSX or PLATFORM_WIN else 1e-4\n assert_allclose(predicted_arma_dp,\n res_d101[-len(predicted_arma_d):], rtol=tol, atol=tol)\n assert_allclose(predicted_arma_fp,\n res_f101[-len(predicted_arma_f):], rtol=tol, atol=tol)\n assert_allclose(predicted_arma_d,\n res_d101[-len(predicted_arma_d):], rtol=tol, atol=tol)\n assert_allclose(predicted_arma_f,\n res_f101[-len(predicted_arma_f):], rtol=tol, atol=tol)\n assert_allclose(predicted_arima_d / endog_scale,\n res_d111[-len(predicted_arima_d):], rtol=tol, atol=tol)\n assert_allclose(predicted_arima_f / endog_scale,\n res_f111[-len(predicted_arima_f):], rtol=tol, atol=tol)\n\n # test for forecast with 0 ar fix in #2457 numbers again from Stata\n\n res_f002 = np.array(\n [7.70178181209, 7.67445481224, 7.67153737650, 7.67729153190,\n 7.61173201163, 7.67913499878, 7.67276092120, 7.66275451925,\n 7.65199799315, 7.65149983741, 7.65554131408, 7.62213286298,\n 7.53795983357, 7.53626130154, 7.54539963934])\n res_d002 = np.array(\n [7.70178181209, 7.67445481224, 7.67153737650, 7.67729153190,\n 7.61173201163, 7.67913499878, 7.67306697759, 7.65287924998,\n 7.64904451605, 7.66580449603, 7.66252081172, 7.62213286298,\n 7.53795983357, 7.53626130154, 7.54539963934])\n\n mod_002 = ARIMA(np.asarray(data_sample['loginv']), (0, 0, 2),\n exog=np.asarray(data_sample[['loggdp', 'logcons']]))\n\n # does not converge with default starting values\n start_params = np.concatenate((res.params[[0, 1, 2, 4]], [0]))\n res_002 = mod_002.fit(start_params=start_params, disp=0,\n solver='bfgs', maxiter=5000)\n\n # forecast\n fpredict_002 = res_002.predict(start=197, end=202,\n exog=exog_full.values[197:])\n forecast_002 = res_002.forecast(steps=len(exog_full.values[197:]),\n exog=exog_full.values[197:])\n # TODO: Checking other results\n forecast_002 = forecast_002[0]\n assert_allclose(fpredict_002, res_f002[-len(fpredict_002):],\n rtol=tol, atol=tol / 100.0)\n assert_allclose(forecast_002, res_f002[-len(forecast_002):],\n rtol=tol, atol=tol / 100.0)\n\n # dynamic predict\n dpredict_002 = res_002.predict(start=193, end=202,\n exog=exog_full.values[197:], dynamic=True)\n assert_allclose(dpredict_002, res_d002[-len(dpredict_002):],\n rtol=tol, atol=tol / 100.0)\n\n # in-sample dynamic predict should not need exog, #2982\n predict_3a = res_002.predict(start=100, end=120, dynamic=True)\n predict_3b = res_002.predict(start=100, end=120,\n exog=exog_full.values[100:120], dynamic=True)\n assert_allclose(predict_3a, predict_3b, rtol=1e-10)\n\n h = len(exog_full.values[197:])\n with pytest.raises(ValueError):\n res_002.forecast(steps=h)\n with pytest.raises(ValueError):\n res_002.forecast(steps=h, exog=np.empty((h, 20)))\n with pytest.raises(ValueError):\n res_002.forecast(steps=h, exog=np.empty(20))\n\n\ndef test_arima_fit_multiple_calls():\n y = [-1214.360173, -1848.209905, -2100.918158, -3647.483678, -4711.186773]\n mod = ARIMA(y, (1, 0, 2))\n # Make multiple calls to fit\n with pytest.warns(HessianInversionWarning, match=\"no bse or cov\"):\n mod.fit(disp=0, start_params=[np.mean(y), .1, .1, .1])\n assert_equal(mod.exog_names, ['const', 'ar.L1.y', 'ma.L1.y', 'ma.L2.y'])\n\n mod.exog = None # FIXME: this should not be necessary\n with pytest.warns(HessianInversionWarning, match=\"no bse or cov\"):\n res = mod.fit(disp=0, start_params=[np.mean(y), .1, .1, .1])\n assert_equal(mod.exog_names, ['const', 'ar.L1.y', 'ma.L1.y', 'ma.L2.y'])\n\n # ensure summary() works # TODO: separate and pytest.mark.smoke\n res.summary()\n\n # test multiple calls when there is only a constant term\n mod = ARIMA(y, (0, 0, 0))\n # Make multiple calls to fit\n mod.fit(disp=0, start_params=[np.mean(y)])\n assert_equal(mod.exog_names, ['const'])\n\n mod.exog = None # FIXME: this should not be necessary\n res = mod.fit(disp=0, start_params=[np.mean(y)])\n assert_equal(mod.exog_names, ['const'])\n\n # ensure summary() works # TODO: separate and pytest.mark.smoke\n res.summary()\n\n\ndef test_long_ar_start_params():\n np.random.seed(12345)\n arparams = np.array([1, -.75, .25])\n maparams = np.array([1, .65, .35])\n\n nobs = 30\n\n np.random.seed(12345)\n y = arma_generate_sample(arparams, maparams, nobs)\n\n model = ARMA(y, order=(2, 2))\n\n model.fit(method='css',start_ar_lags=10, disp=0)\n\n model.exog = None # FIXME: should not be necessary\n model.fit(method='css-mle',start_ar_lags=10, disp=0)\n\n model.exog = None # FIXME: should not be necessary\n model.fit(method='mle',start_ar_lags=10, disp=0)\n assert_raises(ValueError, model.fit, start_ar_lags=nobs+5, disp=0)\n\n\ndef test_arma_pickle():\n np.random.seed(9876565)\n x = fa.ArmaFft([1, -0.5], [1., 0.4], 40).generate_sample(nsample=200,\n burnin=1000)\n mod = ARMA(x, (1, 1))\n pkl_mod = pickle.loads(pickle.dumps(mod))\n\n res = mod.fit(trend=\"c\", disp=-1, solver='newton')\n pkl_res = pkl_mod.fit(trend=\"c\", disp=-1, solver='newton')\n\n assert_allclose(res.params, pkl_res.params)\n assert_allclose(res.llf, pkl_res.llf)\n assert_almost_equal(res.resid, pkl_res.resid)\n assert_almost_equal(res.fittedvalues, pkl_res.fittedvalues)\n assert_almost_equal(res.pvalues, pkl_res.pvalues)\n\n\ndef test_arima_pickle():\n endog = y_arma[:, 6]\n mod = ARIMA(endog, (1, 1, 1))\n pkl_mod = pickle.loads(pickle.dumps(mod))\n\n res = mod.fit(trend=\"c\", disp=-1, solver='newton')\n pkl_res = pkl_mod.fit(trend=\"c\", disp=-1, solver='newton')\n\n assert_allclose(res.params, pkl_res.params)\n assert_allclose(res.llf, pkl_res.llf)\n assert_almost_equal(res.resid, pkl_res.resid)\n assert_almost_equal(res.fittedvalues, pkl_res.fittedvalues)\n assert_almost_equal(res.pvalues, pkl_res.pvalues)\n\n\ndef test_arima_not_implemented():\n formula = ' WUE ~ 1 + SFO3 '\n data = [-1214.360173, -1848.209905, -2100.918158]\n assert_raises(NotImplementedError, ARIMA.from_formula, formula, data)\n\n\ndef test_endog_int():\n # int endog should produce same result as float, #3504\n\n np.random.seed(123987)\n y = np.random.randint(0, 16, size=100)\n yf = y.astype(np.float64)\n\n res = AR(y).fit(5)\n resf = AR(yf).fit(5)\n assert_allclose(res.params, resf.params, atol=1e-5)\n assert_allclose(res.bse, resf.bse, atol=1e-5)\n\n res = ARMA(y, order=(2, 1)).fit(disp=0)\n resf = ARMA(yf, order=(2, 1)).fit(disp=0)\n assert_allclose(res.params, resf.params, atol=1e-5)\n assert_allclose(res.bse, resf.bse, atol=1e-5)\n\n res = ARIMA(y.cumsum(), order=(1, 1, 1)).fit(disp=0)\n resf = ARIMA(yf.cumsum(), order=(1, 1, 1)).fit(disp=0)\n assert_allclose(res.params, resf.params, rtol=1e-6, atol=1e-5)\n assert_allclose(res.bse, resf.bse, rtol=1e-6, atol=1e-5)\n\n\ndef test_multidim_endog(reset_randomstate):\n y = np.random.randn(1000, 2)\n with pytest.raises(ValueError):\n ARMA(y, order=(1, 1))\n\n y = np.random.randn(1000, 1, 2)\n with pytest.raises(ValueError):\n ARMA(y, order=(1, 1))\n\n y = np.random.randn(1, 1, 1000)\n with pytest.raises(ValueError):\n ARMA(y, order=(1, 1))\n\n\ndef test_arima_no_full_output():\n # GH 2752\n endog = y_arma[:, 6]\n mod = ARIMA(endog, (1, 0, 1))\n res = mod.fit(trend=\"c\", disp=-1, full_output=False)\n assert res.mle_retvals is None\n\n\ndef test_arima_summary_no_lags(reset_randomstate):\n y_train = pd.Series(np.random.randn(1000), name='y_train')\n x_train = pd.DataFrame(np.random.randn(1000, 2), columns=['x1', 'x2'])\n res = ARIMA(endog=y_train.values, exog=x_train,\n order=(0, 1, 0)).fit(disp=-1)\n summ = res.summary().as_text()\n assert 'const ' in summ\n assert 'x1 ' in summ\n assert 'x2 ' in summ\n\n\ndef test_constant_column_trend():\n # GH#3343 analogous to GH#5258 for AR, when the user passes a constant exog\n # and also passes trend=\"c\", raise instead _make_arma_exog used to\n # silently drop a column and return an inconsistenct k_trend value.\n\n exog = np.array([0.5, 0.5, 0.5, 0.5, 0.5])\n endog = np.array([-0.011866, 0.003380, 0.015357, 0.004451, -0.020889])\n\n model = ARIMA(endog=endog, order=(1, 1, 0), exog=exog)\n\n # Fitting with a constant and constant exog raises because of colinearity\n with pytest.raises(ValueError, match=\"x contains a constant\"):\n model.fit(trend=\"c\")\n\n # FIXME: calling model.fit(trend=\"nc\") raises for orthogonal reasons\n",
"\"\"\"\nRun x12/x13-arima specs in a subprocess from Python and curry results back\ninto python.\n\nNotes\n-----\nMany of the functions are called x12. However, they are also intended to work\nfor x13. If this is not the case, it's a bug.\n\"\"\"\nimport os\nimport subprocess\nimport tempfile\nimport re\nfrom warnings import warn\n\nimport pandas as pd\n\nfrom statsmodels.compat.python import iteritems\nfrom statsmodels.tools.tools import Bunch\nfrom statsmodels.tools.sm_exceptions import (X13NotFoundError,\n IOWarning, X13Error,\n X13Warning)\n\n__all__ = [\"x13_arima_select_order\", \"x13_arima_analysis\"]\n\n_binary_names = ('x13as.exe', 'x13as', 'x12a.exe', 'x12a')\n\n\nclass _freq_to_period:\n def __getitem__(self, key):\n if key.startswith('M'):\n return 12\n elif key.startswith('Q'):\n return 4\n elif key.startswith('W'):\n return 52\n\n\n_freq_to_period = _freq_to_period()\n\n_period_to_freq = {12: 'M', 4: 'Q'}\n_log_to_x12 = {True: 'log', False: 'none', None: 'auto'}\n_bool_to_yes_no = lambda x: 'yes' if x else 'no' # noqa:E731\n\n\ndef _find_x12(x12path=None, prefer_x13=True):\n \"\"\"\n If x12path is not given, then either x13as[.exe] or x12a[.exe] must\n be found on the PATH. Otherwise, the environmental variable X12PATH or\n X13PATH must be defined. If prefer_x13 is True, only X13PATH is searched\n for. If it is false, only X12PATH is searched for.\n \"\"\"\n global _binary_names\n if x12path is not None and x12path.endswith(_binary_names):\n # remove binary from path if given\n x12path = os.path.dirname(x12path)\n\n if not prefer_x13: # search for x12 first\n _binary_names = _binary_names[::-1]\n if x12path is None:\n x12path = os.getenv(\"X12PATH\", \"\")\n if not x12path:\n x12path = os.getenv(\"X13PATH\", \"\")\n elif x12path is None:\n x12path = os.getenv(\"X13PATH\", \"\")\n if not x12path:\n x12path = os.getenv(\"X12PATH\", \"\")\n\n for binary in _binary_names:\n x12 = os.path.join(x12path, binary)\n try:\n subprocess.check_call(x12, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n return x12\n except OSError:\n pass\n\n else:\n return False\n\n\ndef _check_x12(x12path=None):\n x12path = _find_x12(x12path)\n if not x12path:\n raise X13NotFoundError(\"x12a and x13as not found on path. Give the \"\n \"path, put them on PATH, or set the \"\n \"X12PATH or X13PATH environmental variable.\")\n return x12path\n\n\ndef _clean_order(order):\n \"\"\"\n Takes something like (1 1 0)(0 1 1) and returns a arma order, sarma\n order tuple. Also accepts (1 1 0) and return arma order and (0, 0, 0)\n \"\"\"\n order = re.findall(r\"\\([0-9 ]*?\\)\", order)\n\n def clean(x):\n return tuple(map(int, re.sub(\"[()]\", \"\", x).split(\" \")))\n\n if len(order) > 1:\n order, sorder = map(clean, order)\n else:\n order = clean(order[0])\n sorder = (0, 0, 0)\n\n return order, sorder\n\n\ndef run_spec(x12path, specpath, outname=None, meta=False, datameta=False):\n\n if meta and datameta:\n raise ValueError(\"Cannot specify both meta and datameta.\")\n if meta:\n args = [x12path, \"-m \" + specpath]\n elif datameta:\n args = [x12path, \"-d \" + specpath]\n else:\n args = [x12path, specpath]\n\n if outname:\n args += [outname]\n\n return subprocess.Popen(args, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n\n\ndef _make_automdl_options(maxorder, maxdiff, diff):\n options = \"\\n\"\n options += \"maxorder = ({0} {1})\\n\".format(maxorder[0], maxorder[1])\n if maxdiff is not None: # maxdiff always takes precedence\n options += \"maxdiff = ({0} {1})\\n\".format(maxdiff[0], maxdiff[1])\n else:\n options += \"diff = ({0} {1})\\n\".format(diff[0], diff[1])\n return options\n\n\ndef _make_var_names(exog):\n if hasattr(exog, \"name\"):\n var_names = exog.name\n elif hasattr(exog, \"columns\"):\n var_names = exog.columns\n else:\n raise ValueError(\"exog is not a Series or DataFrame or is unnamed.\")\n try:\n var_names = \" \".join(var_names)\n except TypeError: # cannot have names that are numbers, pandas default\n from statsmodels.base.data import _make_exog_names\n if exog.ndim == 1:\n var_names = \"x1\"\n else:\n var_names = \" \".join(_make_exog_names(exog))\n return var_names\n\n\ndef _make_regression_options(trading, exog):\n if not trading and exog is None: # start regression spec\n return \"\"\n\n reg_spec = \"regression{\\n\"\n if trading:\n reg_spec += \" variables = (td)\\n\"\n if exog is not None:\n var_names = _make_var_names(exog)\n reg_spec += \" user = ({0})\\n\".format(var_names)\n reg_spec += \" data = ({0})\\n\".format(\"\\n\".join(map(str,\n exog.values.ravel().tolist())))\n\n reg_spec += \"}\\n\" # close out regression spec\n return reg_spec\n\n\ndef _make_forecast_options(forecast_years):\n if forecast_years is None:\n return \"\"\n forecast_spec = \"forecast{\\n\"\n forecast_spec += \"maxlead = ({0})\\n}}\\n\".format(forecast_years)\n return forecast_spec\n\n\ndef _check_errors(errors):\n errors = errors[errors.find(\"spc:\")+4:].strip()\n if errors and 'ERROR' in errors:\n raise X13Error(errors)\n elif errors and 'WARNING' in errors:\n warn(errors, X13Warning)\n\n\ndef _convert_out_to_series(x, dates, name):\n \"\"\"\n Convert x to a DataFrame where x is a string in the format given by\n x-13arima-seats output.\n \"\"\"\n from io import StringIO\n from pandas import read_csv\n out = read_csv(StringIO(x), skiprows=2,\n header=None, sep='\\t', engine='python')\n return out.set_index(dates).rename(columns={1: name})[name]\n\n\ndef _open_and_read(fname):\n # opens a file, reads it, and make sure it's closed\n with open(fname, 'r') as fin:\n fout = fin.read()\n return fout\n\n\nclass Spec(object):\n @property\n def spec_name(self):\n return self.__class__.__name__.replace(\"Spec\", \"\")\n\n def create_spec(self, **kwargs):\n spec = \"\"\"{name} {{\n {options}\n }}\n \"\"\"\n return spec.format(name=self.spec_name,\n options=self.options)\n\n def set_options(self, **kwargs):\n options = \"\"\n for key, value in iteritems(kwargs):\n options += \"{0}={1}\\n\".format(key, value)\n self.__dict__.update({key: value})\n self.options = options\n\n\nclass SeriesSpec(Spec):\n \"\"\"\n Parameters\n ----------\n data\n appendbcst : bool\n appendfcst : bool\n comptype\n compwt\n decimals\n modelspan\n name\n period\n precision\n to_print\n to_save\n span\n start\n title\n type\n\n Notes\n -----\n Rarely used arguments\n\n divpower\n missingcode\n missingval\n saveprecision\n trimzero\n\n \"\"\"\n def __init__(self, data, name='Unnamed Series', appendbcst=False,\n appendfcst=False,\n comptype=None, compwt=1, decimals=0, modelspan=(),\n period=12, precision=0, to_print=[], to_save=[], span=(),\n start=(1, 1), title='', series_type=None, divpower=None,\n missingcode=-99999, missingval=1000000000):\n\n appendbcst, appendfcst = map(_bool_to_yes_no, [appendbcst,\n appendfcst,\n ])\n\n series_name = \"\\\"{0}\\\"\".format(name[:64]) # trim to 64 characters\n title = \"\\\"{0}\\\"\".format(title[:79]) # trim to 79 characters\n self.set_options(data=data, appendbcst=appendbcst,\n appendfcst=appendfcst, period=period, start=start,\n title=title, name=series_name,\n )\n\n\ndef pandas_to_series_spec(x):\n # from statsmodels.tools.data import _check_period_index\n # check_period_index(x)\n if hasattr(x, 'columns'): # convert to series\n if len(x.columns) > 1:\n raise ValueError(\"Does not handle DataFrame with more than one \"\n \"column\")\n x = x[x.columns[0]]\n\n data = \"({0})\".format(\"\\n\".join(map(str, x.values.tolist())))\n\n # get periodicity\n # get start / first data\n # give it a title\n try:\n period = _freq_to_period[x.index.freqstr]\n except (AttributeError, ValueError):\n from pandas.tseries.api import infer_freq\n period = _freq_to_period[infer_freq(x.index)]\n start_date = x.index[0]\n if period == 12:\n year, stperiod = start_date.year, start_date.month\n elif period == 4:\n year, stperiod = start_date.year, start_date.quarter\n else: # pragma: no cover\n raise ValueError(\"Only monthly and quarterly periods are supported.\"\n \" Please report or send a pull request if you want \"\n \"this extended.\")\n\n if hasattr(x, 'name'):\n name = x.name or \"Unnamed Series\"\n else:\n name = 'Unnamed Series'\n series_spec = SeriesSpec(data=data, name=name, period=period,\n title=name, start=\"{0}.{1}\".format(year,\n stperiod))\n return series_spec\n\n\ndef x13_arima_analysis(endog, maxorder=(2, 1), maxdiff=(2, 1), diff=None,\n exog=None, log=None, outlier=True, trading=False,\n forecast_years=None, retspec=False,\n speconly=False, start=None, freq=None,\n print_stdout=False, x12path=None, prefer_x13=True):\n \"\"\"\n Perform x13-arima analysis for monthly or quarterly data.\n\n Parameters\n ----------\n endog : array_like, pandas.Series\n The series to model. It is best to use a pandas object with a\n DatetimeIndex or PeriodIndex. However, you can pass an array-like\n object. If your object does not have a dates index then ``start`` and\n ``freq`` are not optional.\n maxorder : tuple\n The maximum order of the regular and seasonal ARMA polynomials to\n examine during the model identification. The order for the regular\n polynomial must be greater than zero and no larger than 4. The\n order for the seasonal polynomial may be 1 or 2.\n maxdiff : tuple\n The maximum orders for regular and seasonal differencing in the\n automatic differencing procedure. Acceptable inputs for regular\n differencing are 1 and 2. The maximum order for seasonal differencing\n is 1. If ``diff`` is specified then ``maxdiff`` should be None.\n Otherwise, ``diff`` will be ignored. See also ``diff``.\n diff : tuple\n Fixes the orders of differencing for the regular and seasonal\n differencing. Regular differencing may be 0, 1, or 2. Seasonal\n differencing may be 0 or 1. ``maxdiff`` must be None, otherwise\n ``diff`` is ignored.\n exog : array_like\n Exogenous variables.\n log : bool or None\n If None, it is automatically determined whether to log the series or\n not. If False, logs are not taken. If True, logs are taken.\n outlier : bool\n Whether or not outliers are tested for and corrected, if detected.\n trading : bool\n Whether or not trading day effects are tested for.\n forecast_years : int\n Number of forecasts produced. The default is one year.\n retspec : bool\n Whether to return the created specification file. Can be useful for\n debugging.\n speconly : bool\n Whether to create the specification file and then return it without\n performing the analysis. Can be useful for debugging.\n start : str, datetime\n Must be given if ``endog`` does not have date information in its index.\n Anything accepted by pandas.DatetimeIndex for the start value.\n freq : str\n Must be givein if ``endog`` does not have date information in its\n index. Anything accepted by pandas.DatetimeIndex for the freq value.\n print_stdout : bool\n The stdout from X12/X13 is suppressed. To print it out, set this\n to True. Default is False.\n x12path : str or None\n The path to x12 or x13 binary. If None, the program will attempt\n to find x13as or x12a on the PATH or by looking at X13PATH or\n X12PATH depending on the value of prefer_x13.\n prefer_x13 : bool\n If True, will look for x13as first and will fallback to the X13PATH\n environmental variable. If False, will look for x12a first and will\n fallback to the X12PATH environmental variable. If x12path points\n to the path for the X12/X13 binary, it does nothing.\n\n\n Returns\n -------\n res : Bunch\n A bunch object with the following attributes:\n\n - results : str\n The full output from the X12/X13 run.\n - seasadj : pandas.Series\n The final seasonally adjusted ``endog``\n - trend : pandas.Series\n The trend-cycle component of ``endog``\n - irregular : pandas.Series\n The final irregular component of ``endog``\n - stdout : str\n The captured stdout produced by x12/x13.\n - spec : str, optional\n Returned if ``retspec`` is True. The only thing returned if\n ``speconly`` is True.\n\n Notes\n -----\n This works by creating a specification file, writing it to a temporary\n directory, invoking X12/X13 in a subprocess, and reading the output\n directory, invoking exog12/X13 in a subprocess, and reading the output\n back in.\n \"\"\"\n x12path = _check_x12(x12path)\n\n if not isinstance(endog, (pd.DataFrame, pd.Series)):\n if start is None or freq is None:\n raise ValueError(\"start and freq cannot be none if endog is not \"\n \"a pandas object\")\n endog = pd.Series(endog, index=pd.DatetimeIndex(start=start,\n periods=len(endog),\n freq=freq))\n spec_obj = pandas_to_series_spec(endog)\n spec = spec_obj.create_spec()\n spec += \"transform{{function={0}}}\\n\".format(_log_to_x12[log])\n if outlier:\n spec += \"outlier{}\\n\"\n options = _make_automdl_options(maxorder, maxdiff, diff)\n spec += \"automdl{{{0}}}\\n\".format(options)\n spec += _make_regression_options(trading, exog)\n spec += _make_forecast_options(forecast_years)\n spec += \"x11{ save=(d11 d12 d13) }\"\n if speconly:\n return spec\n # write it to a tempfile\n # TODO: make this more robust - give the user some control?\n ftempin = tempfile.NamedTemporaryFile(delete=False, suffix='.spc')\n ftempout = tempfile.NamedTemporaryFile(delete=False)\n try:\n ftempin.write(spec.encode('utf8'))\n ftempin.close()\n ftempout.close()\n # call x12 arima\n p = run_spec(x12path, ftempin.name[:-4], ftempout.name)\n p.wait()\n stdout = p.stdout.read()\n if print_stdout:\n print(p.stdout.read())\n # check for errors\n errors = _open_and_read(ftempout.name + '.err')\n _check_errors(errors)\n\n # read in results\n results = _open_and_read(ftempout.name + '.out')\n seasadj = _open_and_read(ftempout.name + '.d11')\n trend = _open_and_read(ftempout.name + '.d12')\n irregular = _open_and_read(ftempout.name + '.d13')\n finally:\n try: # sometimes this gives a permission denied error?\n # not sure why. no process should have these open\n os.remove(ftempin.name)\n os.remove(ftempout.name)\n except OSError:\n if os.path.exists(ftempin.name):\n warn(\"Failed to delete resource {0}\".format(ftempin.name),\n IOWarning)\n if os.path.exists(ftempout.name):\n warn(\"Failed to delete resource {0}\".format(ftempout.name),\n IOWarning)\n\n seasadj = _convert_out_to_series(seasadj, endog.index, 'seasadj')\n trend = _convert_out_to_series(trend, endog.index, 'trend')\n irregular = _convert_out_to_series(irregular, endog.index, 'irregular')\n\n # NOTE: there is not likely anything in stdout that's not in results\n # so may be safe to just suppress and remove it\n if not retspec:\n res = X13ArimaAnalysisResult(observed=endog, results=results,\n seasadj=seasadj, trend=trend,\n irregular=irregular, stdout=stdout)\n else:\n res = X13ArimaAnalysisResult(observed=endog, results=results,\n seasadj=seasadj, trend=trend,\n irregular=irregular, stdout=stdout,\n spec=spec)\n return res\n\n\ndef x13_arima_select_order(endog, maxorder=(2, 1), maxdiff=(2, 1), diff=None,\n exog=None, log=None, outlier=True, trading=False,\n forecast_years=None,\n start=None, freq=None, print_stdout=False,\n x12path=None, prefer_x13=True):\n \"\"\"\n Perform automatic seasonal ARIMA order identification using x12/x13 ARIMA.\n\n Parameters\n ----------\n endog : array_like, pandas.Series\n The series to model. It is best to use a pandas object with a\n DatetimeIndex or PeriodIndex. However, you can pass an array-like\n object. If your object does not have a dates index then ``start`` and\n ``freq`` are not optional.\n maxorder : tuple\n The maximum order of the regular and seasonal ARMA polynomials to\n examine during the model identification. The order for the regular\n polynomial must be greater than zero and no larger than 4. The\n order for the seasonal polynomial may be 1 or 2.\n maxdiff : tuple\n The maximum orders for regular and seasonal differencing in the\n automatic differencing procedure. Acceptable inputs for regular\n differencing are 1 and 2. The maximum order for seasonal differencing\n is 1. If ``diff`` is specified then ``maxdiff`` should be None.\n Otherwise, ``diff`` will be ignored. See also ``diff``.\n diff : tuple\n Fixes the orders of differencing for the regular and seasonal\n differencing. Regular differencing may be 0, 1, or 2. Seasonal\n differencing may be 0 or 1. ``maxdiff`` must be None, otherwise\n ``diff`` is ignored.\n exog : array_like\n Exogenous variables.\n log : bool or None\n If None, it is automatically determined whether to log the series or\n not. If False, logs are not taken. If True, logs are taken.\n outlier : bool\n Whether or not outliers are tested for and corrected, if detected.\n trading : bool\n Whether or not trading day effects are tested for.\n forecast_years : int\n Number of forecasts produced. The default is one year.\n start : str, datetime\n Must be given if ``endog`` does not have date information in its index.\n Anything accepted by pandas.DatetimeIndex for the start value.\n freq : str\n Must be givein if ``endog`` does not have date information in its\n index. Anything accepted by pandas.DatetimeIndex for the freq value.\n print_stdout : bool\n The stdout from X12/X13 is suppressed. To print it out, set this\n to True. Default is False.\n x12path : str or None\n The path to x12 or x13 binary. If None, the program will attempt\n to find x13as or x12a on the PATH or by looking at X13PATH or X12PATH\n depending on the value of prefer_x13.\n prefer_x13 : bool\n If True, will look for x13as first and will fallback to the X13PATH\n environmental variable. If False, will look for x12a first and will\n fallback to the X12PATH environmental variable. If x12path points\n to the path for the X12/X13 binary, it does nothing.\n\n Returns\n -------\n results : Bunch\n A bunch object that has the following attributes:\n\n - order : tuple\n The regular order\n - sorder : tuple\n The seasonal order\n - include_mean : bool\n Whether to include a mean or not\n - results : str\n The full results from the X12/X13 analysis\n - stdout : str\n The captured stdout from the X12/X13 analysis\n\n Notes\n -----\n This works by creating a specification file, writing it to a temporary\n directory, invoking X12/X13 in a subprocess, and reading the output back\n in.\n \"\"\"\n results = x13_arima_analysis(endog, x12path=x12path, exog=exog, log=log,\n outlier=outlier, trading=trading,\n forecast_years=forecast_years,\n maxorder=maxorder, maxdiff=maxdiff, diff=diff,\n start=start, freq=freq, prefer_x13=prefer_x13)\n model = re.search(\"(?<=Final automatic model choice : ).*\",\n results.results)\n order = model.group()\n if re.search(\"Mean is not significant\", results.results):\n include_mean = False\n elif re.search(\"Constant\", results.results):\n include_mean = True\n else:\n include_mean = False\n order, sorder = _clean_order(order)\n res = Bunch(order=order, sorder=sorder, include_mean=include_mean,\n results=results.results, stdout=results.stdout)\n return res\n\n\nclass X13ArimaAnalysisResult(object):\n def __init__(self, **kwargs):\n for key, value in iteritems(kwargs):\n setattr(self, key, value)\n\n def plot(self):\n from statsmodels.graphics.utils import _import_mpl\n plt = _import_mpl()\n fig, axes = plt.subplots(4, 1, sharex=True)\n self.observed.plot(ax=axes[0], legend=False)\n axes[0].set_ylabel('Observed')\n self.seasadj.plot(ax=axes[1], legend=False)\n axes[1].set_ylabel('Seas. Adjusted')\n self.trend.plot(ax=axes[2], legend=False)\n axes[2].set_ylabel('Trend')\n self.irregular.plot(ax=axes[3], legend=False)\n axes[3].set_ylabel('Irregular')\n\n fig.tight_layout()\n return fig\n",
"import numpy as np\nimport pandas as pd\nfrom collections import OrderedDict\nfrom statsmodels.base.model import LikelihoodModelResults\n\n\nclass BayesGaussMI(object):\n \"\"\"\n BayesGaussMI uses a Gaussian model to impute multivariate data.\n\n The approach is Bayesian. The goal is to sample from the joint\n distribution of the mean vector, covariance matrix, and missing\n data values given the observed data values. Conjugate priors for\n the population mean and covariance matrix are used. Gibbs\n sampling is used to update the mean vector, covariance matrix, and\n missing data values in turn. After burn-in, the imputed complete\n data sets from the Gibbs chain can be used in multiple imputation\n analyses (MI).\n\n Parameters\n ----------\n data : ndarray\n The array of data to be imputed. Values in the array equal to\n NaN are imputed.\n mean_prior : ndarray, optional\n The covariance matrix of the Gaussian prior distribution for\n the mean vector. If not provided, the identity matrix is\n used.\n cov_prior : ndarray, optional\n The center matrix for the inverse Wishart prior distribution\n for the covariance matrix. If not provided, the identity\n matrix is used.\n cov_prior_df : positive float\n The degrees of freedom of the inverse Wishart prior\n distribution for the covariance matrix. Defaults to 1.\n\n Returns:\n -------\n BayesGaussMI object\n\n Examples:\n ---------\n A basic example with OLS:\n\n >> def model_args_fn(x):\n # Return endog, exog from x\n return (x[:, 0], x[:, 1:])\n >> imp = BayesGaussMI(x)\n >> mi = MI(imp, sm.OLS, model_args_fn)\n \"\"\"\n\n def __init__(self, data, mean_prior=None, cov_prior=None, cov_prior_df=1):\n\n self.exog_names = None\n if type(data) is pd.DataFrame:\n self.exog_names = data.columns\n\n data = np.asarray(data)\n self.data = data\n self._data = data\n self.mask = np.isnan(data)\n self.nobs = self.mask.shape[0]\n self.nvar = self.mask.shape[1]\n\n # Identify all distinct missing data patterns\n z = 1 + np.log(1 + np.arange(self.mask.shape[1]))\n c = np.dot(self.mask, z)\n rowmap = OrderedDict()\n for i, v in enumerate(c):\n if v == 0:\n # No missing values\n continue\n if v not in rowmap:\n rowmap[v] = []\n rowmap[v].append(i)\n self.patterns = [np.asarray(v) for v in rowmap.values()]\n\n # Simple starting values for mean and covariance\n p = self._data.shape[1]\n self.cov = np.eye(p)\n mean = []\n for i in range(p):\n v = self._data[:, i]\n v = v[np.isfinite(v)]\n if len(v) == 0:\n msg = \"Column %d has no observed values\" % i\n raise ValueError(msg)\n mean.append(v.mean())\n self.mean = np.asarray(mean)\n\n # Default covariance matrix of the (Gaussian) mean prior\n if mean_prior is None:\n mean_prior = np.eye(p)\n self.mean_prior = mean_prior\n\n # Default center matrix of the (inverse Wishart) covariance prior\n if cov_prior is None:\n cov_prior = np.eye(p)\n self.cov_prior = cov_prior\n\n # Degrees of freedom for the (inverse Wishart) covariance prior\n self.cov_prior_df = cov_prior_df\n\n def update(self):\n \"\"\"\n Cycle through all Gibbs updates.\n \"\"\"\n\n self.update_data()\n\n # Need to update data first\n self.update_mean()\n self.update_cov()\n\n def update_data(self):\n \"\"\"\n Gibbs update of the missing data values.\n \"\"\"\n\n for ix in self.patterns:\n\n i = ix[0]\n ix_miss = np.flatnonzero(self.mask[i, :])\n ix_obs = np.flatnonzero(~self.mask[i, :])\n\n mm = self.mean[ix_miss]\n mo = self.mean[ix_obs]\n\n voo = self.cov[ix_obs, :][:, ix_obs]\n vmm = self.cov[ix_miss, :][:, ix_miss]\n vmo = self.cov[ix_miss, :][:, ix_obs]\n\n r = self._data[ix, :][:, ix_obs] - mo\n cm = mm + np.dot(vmo, np.linalg.solve(voo, r.T)).T\n cv = vmm - np.dot(vmo, np.linalg.solve(voo, vmo.T))\n\n cs = np.linalg.cholesky(cv)\n u = np.random.normal(size=(len(ix), len(ix_miss)))\n self._data[np.ix_(ix, ix_miss)] = cm + np.dot(u, cs.T)\n\n # Set the user-visible data set.\n if self.exog_names is not None:\n self.data = pd.DataFrame(\n self._data,\n columns=self.exog_names,\n copy=False)\n else:\n self.data = self._data\n\n def update_mean(self):\n \"\"\"\n Gibbs update of the mean vector.\n\n Do not call until update_data has been called once.\n \"\"\"\n # https://stats.stackexchange.com/questions/28744/multivariate-normal-posterior\n\n # Posterior covariance matrix of the mean\n cm = np.linalg.solve(self.cov/self.nobs + self.mean_prior,\n self.mean_prior / self.nobs)\n cm = np.dot(self.cov, cm)\n\n # Posterior mean of the mean\n vm = np.linalg.solve(self.cov, self._data.sum(0))\n vm = np.dot(cm, vm)\n\n # Sample\n r = np.linalg.cholesky(cm)\n self.mean = vm + np.dot(r, np.random.normal(0, 1, self.nvar))\n\n def update_cov(self):\n \"\"\"\n Gibbs update of the covariance matrix.\n\n Do not call until update_data has been called once.\n \"\"\"\n # https://stats.stackexchange.com/questions/50844/estimating-the-covariance-posterior-distribution-of-a-multivariate-gaussian\n\n r = self._data - self.mean\n gr = np.dot(r.T, r)\n a = gr + self.cov_prior\n df = int(np.ceil(self.nobs + self.cov_prior_df))\n\n r = np.linalg.cholesky(np.linalg.inv(a))\n x = np.dot(np.random.normal(size=(df, self.nvar)), r.T)\n ma = np.dot(x.T, x)\n self.cov = np.linalg.inv(ma)\n\n\nclass MI(object):\n \"\"\"\n MI performs multiple imputation using a provided imputer object.\n\n Parameters\n ----------\n imp : object\n An imputer class, such as BayesGaussMI.\n model : model class\n Any statsmodels model class.\n model_args_fn : function\n A function taking an imputed dataset as input and returning\n endog, exog. If the model is fit using a formula, returns\n a Dataframe used to build the model. Optional when a formula\n is used.\n model_kwds_fn : function, optional\n A function taking an imputed dataset as input and returning\n a dictionary of model keyword arguments.\n formula : string, optional\n If provided, the model is constructed using the `from_formula`\n class method, otherwise the `__init__` method is used.\n fit_args : list-like, optional\n List of arguments to be passed to the fit method\n fit_kwds : dict-like, optional\n Keyword arguments to be passed to the fit method\n xfunc : function mapping ndarray to ndarray\n A function that is applied to the complete data matrix\n prior to fitting the model\n burn : int\n Number of burn-in iterations\n nrep : int\n Number of imputed data sets to use in the analysis\n skip : int\n Number of Gibbs iterations to skip between successive\n mutiple imputation fits.\n\n Notes\n -----\n The imputer object must have an 'update' method, and a 'data'\n attribute that contains the current imputed dataset.\n\n xfunc can be used to introduce domain constraints, e.g. when\n imputing binary data the imputed continuous values can be rounded\n to 0/1.\n \"\"\"\n\n def __init__(self, imp, model, model_args_fn=None, model_kwds_fn=None,\n formula=None, fit_args=None, fit_kwds=None, xfunc=None,\n burn=100, nrep=20, skip=10):\n\n # The imputer\n self.imp = imp\n\n # The number of imputed data sets to skip between each imputed\n # data set tha that is used in the analysis.\n self.skip = skip\n\n # The model class\n self.model = model\n self.formula = formula\n\n if model_args_fn is None:\n def f(x):\n return []\n model_args_fn = f\n self.model_args_fn = model_args_fn\n\n if model_kwds_fn is None:\n def f(x):\n return {}\n model_kwds_fn = f\n self.model_kwds_fn = model_kwds_fn\n\n if fit_args is None:\n def f(x):\n return []\n fit_args = f\n self.fit_args = fit_args\n\n if fit_kwds is None:\n def f(x):\n return {}\n fit_kwds = f\n self.fit_kwds = fit_kwds\n\n self.xfunc = xfunc\n self.nrep = nrep\n self.skip = skip\n\n # Burn-in\n for k in range(burn):\n imp.update()\n\n def fit(self, results_cb=None):\n \"\"\"\n Impute datasets, fit models, and pool results.\n\n Parameters\n ----------\n results_cb : function, optional\n If provided, each results instance r is passed through `results_cb`,\n then appended to the `results` attribute of the MIResults object.\n To save complete results, use `results_cb=lambda x: x`. The default\n behavior is to save no results.\n\n Returns\n -------\n A MIResults object.\n \"\"\"\n\n par, cov = [], []\n all_results = []\n\n for k in range(self.nrep):\n\n for k in range(self.skip+1):\n self.imp.update()\n\n da = self.imp.data\n\n if self.xfunc is not None:\n da = self.xfunc(da)\n\n if self.formula is None:\n model = self.model(*self.model_args_fn(da),\n **self.model_kwds_fn(da))\n else:\n model = self.model.from_formula(\n self.formula, *self.model_args_fn(da),\n **self.model_kwds_fn(da))\n\n result = model.fit(*self.fit_args(da), **self.fit_kwds(da))\n\n if results_cb is not None:\n all_results.append(results_cb(result))\n\n par.append(np.asarray(result.params.copy()))\n cov.append(np.asarray(result.cov_params().copy()))\n\n params, cov_params, fmi = self._combine(par, cov)\n\n r = MIResults(self, model, params, cov_params)\n r.fmi = fmi\n\n r.results = all_results\n\n return r\n\n def _combine(self, par, cov):\n # Helper function to apply \"Rubin's combining rule\"\n\n par = np.asarray(par)\n\n # Number of imputations\n m = par.shape[0]\n\n # Point estimate\n params = par.mean(0)\n\n # Within-imputation covariance\n wcov = sum(cov) / len(cov)\n\n # Between-imputation covariance\n bcov = np.cov(par.T)\n bcov = np.atleast_2d(bcov)\n\n # Overall covariance\n covp = wcov + (1 + 1/float(m))*bcov\n\n # Fraction of missing information\n fmi = (1 + 1/float(m)) * np.diag(bcov) / np.diag(covp)\n\n return params, covp, fmi\n\n\nclass MIResults(LikelihoodModelResults):\n \"\"\"\n A results class for multiple imputation (MI).\n\n Parameters\n ----------\n mi : MI instance\n The MI object that produced the results\n model : instance of statsmodels model class\n This can be any instance from the multiple imputation runs.\n It is used to get class information, the specific parameter\n and data values are not used.\n params : array_like\n The overall multiple imputation parameter estimates.\n normalized_cov_params : array_like (2d)\n The overall variance covariance matrix of the estimates.\n \"\"\"\n\n def __init__(self, mi, model, params, normalized_cov_params):\n\n super(MIResults, self).__init__(model, params, normalized_cov_params)\n self.mi = mi\n self._model = model\n\n def summary(self, title=None, alpha=.05):\n \"\"\"\n Summarize the results of running multiple imputation.\n\n Parameters\n ----------\n title : str, optional\n Title for the top table. If not None, then this replaces\n the default title\n alpha : float\n Significance level for the confidence intervals\n\n Returns\n -------\n smry : Summary instance\n This holds the summary tables and text, which can be\n printed or converted to various output formats.\n \"\"\"\n\n from statsmodels.iolib import summary2\n\n smry = summary2.Summary()\n float_format = \"%8.3f\"\n\n info = OrderedDict()\n info[\"Method:\"] = \"MI\"\n info[\"Model:\"] = self.mi.model.__name__\n info[\"Dependent variable:\"] = self._model.endog_names\n info[\"Sample size:\"] = \"%d\" % self.mi.imp.data.shape[0]\n info[\"Num. imputations\"] = \"%d\" % self.mi.nrep\n\n smry.add_dict(info, align='l', float_format=float_format)\n\n param = summary2.summary_params(self, alpha=alpha)\n param[\"FMI\"] = self.fmi\n\n smry.add_df(param, float_format=float_format)\n smry.add_title(title=title, results=self)\n\n return smry\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nSpline and other smoother classes for Generalized Additive Models\n\nAuthor: Luca Puggini\nAuthor: Josef Perktold\n\nCreated on Fri Jun 5 16:32:00 2015\n\"\"\"\n\n# import useful only for development\nfrom abc import ABCMeta, abstractmethod\nfrom statsmodels.compat.python import with_metaclass\n\nimport numpy as np\nimport pandas as pd\nfrom patsy import dmatrix\nfrom patsy.mgcv_cubic_splines import _get_all_sorted_knots\n\nfrom statsmodels.tools.linalg import transf_constraints\n\n\n# Obtain b splines from patsy\n\ndef _equally_spaced_knots(x, df):\n n_knots = df - 2\n x_min = x.min()\n x_max = x.max()\n knots = np.linspace(x_min, x_max, n_knots)\n return knots\n\n\ndef _R_compat_quantile(x, probs):\n # return np.percentile(x, 100 * np.asarray(probs))\n probs = np.asarray(probs)\n quantiles = np.asarray([np.percentile(x, 100 * prob)\n for prob in probs.ravel(order=\"C\")])\n return quantiles.reshape(probs.shape, order=\"C\")\n\n\n# FIXME: is this copy/pasted? If so, why do we need it? If not, get\n# rid of the try/except for scipy import\n# from patsy splines.py\ndef _eval_bspline_basis(x, knots, degree, deriv='all', include_intercept=True):\n try:\n from scipy.interpolate import splev\n except ImportError:\n raise ImportError(\"spline functionality requires scipy\")\n # 'knots' are assumed to be already pre-processed. E.g. usually you\n # want to include duplicate copies of boundary knots; you should do\n # that *before* calling this constructor.\n knots = np.atleast_1d(np.asarray(knots, dtype=float))\n assert knots.ndim == 1\n knots.sort()\n degree = int(degree)\n x = np.atleast_1d(x)\n if x.ndim == 2 and x.shape[1] == 1:\n x = x[:, 0]\n assert x.ndim == 1\n # XX FIXME: when points fall outside of the boundaries, splev and R seem\n # to handle them differently. I do not know why yet. So until we understand\n # this and decide what to do with it, I'm going to play it safe and\n # disallow such points.\n if np.min(x) < np.min(knots) or np.max(x) > np.max(knots):\n raise NotImplementedError(\"some data points fall outside the \"\n \"outermost knots, and I'm not sure how \"\n \"to handle them. (Patches accepted!)\")\n # Thanks to Charles Harris for explaining splev. It's not well\n # documented, but basically it computes an arbitrary b-spline basis\n # given knots and degree on some specificed points (or derivatives\n # thereof, but we do not use that functionality), and then returns some\n # linear combination of these basis functions. To get out the basis\n # functions themselves, we use linear combinations like [1, 0, 0], [0,\n # 1, 0], [0, 0, 1].\n # NB: This probably makes it rather inefficient (though I have not checked\n # to be sure -- maybe the fortran code actually skips computing the basis\n # function for coefficients that are zero).\n # Note: the order of a spline is the same as its degree + 1.\n # Note: there are (len(knots) - order) basis functions.\n\n k_const = 1 - int(include_intercept)\n n_bases = len(knots) - (degree + 1) - k_const\n if deriv in ['all', 0]:\n basis = np.empty((x.shape[0], n_bases), dtype=float)\n ret = basis\n if deriv in ['all', 1]:\n der1_basis = np.empty((x.shape[0], n_bases), dtype=float)\n ret = der1_basis\n if deriv in ['all', 2]:\n der2_basis = np.empty((x.shape[0], n_bases), dtype=float)\n ret = der2_basis\n\n for i in range(n_bases):\n coefs = np.zeros((n_bases + k_const,))\n # we are skipping the first column of the basis to drop constant\n coefs[i + k_const] = 1\n ii = i\n if deriv in ['all', 0]:\n basis[:, ii] = splev(x, (knots, coefs, degree))\n if deriv in ['all', 1]:\n der1_basis[:, ii] = splev(x, (knots, coefs, degree), der=1)\n if deriv in ['all', 2]:\n der2_basis[:, ii] = splev(x, (knots, coefs, degree), der=2)\n\n if deriv == 'all':\n return basis, der1_basis, der2_basis\n else:\n return ret\n\n\ndef compute_all_knots(x, df, degree):\n order = degree + 1\n n_inner_knots = df - order\n lower_bound = np.min(x)\n upper_bound = np.max(x)\n knot_quantiles = np.linspace(0, 1, n_inner_knots + 2)[1:-1]\n inner_knots = _R_compat_quantile(x, knot_quantiles)\n all_knots = np.concatenate(([lower_bound, upper_bound] * order,\n inner_knots))\n return all_knots, lower_bound, upper_bound, inner_knots\n\n\ndef make_bsplines_basis(x, df, degree):\n ''' make a spline basis for x '''\n\n all_knots, _, _, _ = compute_all_knots(x, df, degree)\n basis, der_basis, der2_basis = _eval_bspline_basis(x, all_knots, degree)\n return basis, der_basis, der2_basis\n\n\ndef get_knots_bsplines(x=None, df=None, knots=None, degree=3,\n spacing='quantile', lower_bound=None,\n upper_bound=None, all_knots=None):\n \"\"\"knots for use in B-splines\n\n There are two main options for the knot placement\n\n - quantile spacing with multiplicity of boundary knots\n - equal spacing extended to boundary or exterior knots\n\n The first corresponds to splines as used by patsy. the second is the\n knot spacing for P-Splines.\n\n \"\"\"\n # based on patsy memorize_finish\n if all_knots is not None:\n return all_knots\n\n x_min = x.min()\n x_max = x.max()\n\n if degree < 0:\n raise ValueError(\"degree must be greater than 0 (not %r)\"\n % (degree,))\n if int(degree) != degree:\n raise ValueError(\"degree must be an integer (not %r)\"\n % (degree,))\n\n # These are guaranteed to all be 1d vectors by the code above\n # x = np.concatenate(tmp[\"xs\"])\n if df is None and knots is None:\n raise ValueError(\"must specify either df or knots\")\n order = degree + 1\n if df is not None:\n n_inner_knots = df - order\n if n_inner_knots < 0:\n raise ValueError(\"df=%r is too small for degree=%r; must be >= %s\"\n % (df, degree,\n # We know that n_inner_knots is negative;\n # if df were that much larger, it would\n # have been zero, and things would work.\n df - n_inner_knots))\n if knots is not None:\n if len(knots) != n_inner_knots:\n raise ValueError(\"df=%s with degree=%r implies %s knots, \"\n \"but %s knots were provided\"\n % (df, degree,\n n_inner_knots, len(knots)))\n elif spacing == 'quantile':\n # Need to compute inner knots\n knot_quantiles = np.linspace(0, 1, n_inner_knots + 2)[1:-1]\n inner_knots = _R_compat_quantile(x, knot_quantiles)\n elif spacing == 'equal':\n # Need to compute inner knots\n grid = np.linspace(0, 1, n_inner_knots + 2)[1:-1]\n inner_knots = x_min + grid * (x_max - x_min)\n diff_knots = inner_knots[1] - inner_knots[0]\n else:\n raise ValueError(\"incorrect option for spacing\")\n if knots is not None:\n inner_knots = knots\n if lower_bound is None:\n lower_bound = np.min(x)\n if upper_bound is None:\n upper_bound = np.max(x)\n\n if lower_bound > upper_bound:\n raise ValueError(\"lower_bound > upper_bound (%r > %r)\"\n % (lower_bound, upper_bound))\n inner_knots = np.asarray(inner_knots)\n if inner_knots.ndim > 1:\n raise ValueError(\"knots must be 1 dimensional\")\n if np.any(inner_knots < lower_bound):\n raise ValueError(\"some knot values (%s) fall below lower bound \"\n \"(%r)\"\n % (inner_knots[inner_knots < lower_bound],\n lower_bound))\n if np.any(inner_knots > upper_bound):\n raise ValueError(\"some knot values (%s) fall above upper bound \"\n \"(%r)\"\n % (inner_knots[inner_knots > upper_bound],\n upper_bound))\n\n if spacing == \"equal\":\n diffs = np.arange(1, order + 1) * diff_knots\n lower_knots = inner_knots[0] - diffs[::-1]\n upper_knots = inner_knots[-1] + diffs\n all_knots = np.concatenate((lower_knots, inner_knots, upper_knots))\n else:\n all_knots = np.concatenate(([lower_bound, upper_bound] * order,\n inner_knots))\n all_knots.sort()\n\n return all_knots\n\n\ndef _get_integration_points(knots, k_points=3):\n \"\"\"add points to each subinterval defined by knots\n\n inserts k_points between each two consecutive knots\n \"\"\"\n k_points = k_points + 1\n knots = np.unique(knots)\n dxi = np.arange(k_points) / k_points\n dxk = np.diff(knots)\n dx = dxk[:, None] * dxi\n x = np.concatenate(((knots[:-1, None] + dx).ravel(), [knots[-1]]))\n return x\n\n\ndef get_covder2(smoother, k_points=4, integration_points=None,\n skip_ctransf=False, deriv=2):\n \"\"\"\n Approximate integral of cross product of second derivative of smoother\n\n This uses scipy.integrate simps to compute an approximation to the\n integral of the smoother derivative cross-product at knots plus k_points\n in between knots.\n \"\"\"\n from scipy.integrate import simps\n knots = smoother.knots\n x = _get_integration_points(knots, k_points=3)\n if integration_points is None:\n d2 = smoother.transform(x, deriv=deriv, skip_ctransf=skip_ctransf)\n else:\n x = integration_points\n covd2 = simps(d2[:, :, None] * d2[:, None, :], x, axis=0)\n return covd2\n\n\n# TODO: this function should be deleted\ndef make_poly_basis(x, degree, intercept=True):\n '''\n given a vector x returns poly=(1, x, x^2, ..., x^degree)\n and its first and second derivative\n '''\n\n if intercept:\n start = 0\n else:\n start = 1\n\n nobs = len(x)\n basis = np.zeros(shape=(nobs, degree + 1 - start))\n der_basis = np.zeros(shape=(nobs, degree + 1 - start))\n der2_basis = np.zeros(shape=(nobs, degree + 1 - start))\n\n for i in range(start, degree + 1):\n basis[:, i - start] = x ** i\n der_basis[:, i - start] = i * x ** (i - 1)\n der2_basis[:, i - start] = i * (i - 1) * x ** (i - 2)\n\n return basis, der_basis, der2_basis\n\n\n# TODO: try to include other kinds of splines from patsy\n# x = np.linspace(0, 1, 30)\n# df = 10\n# degree = 3\n# from patsy.mgcv_cubic_splines import cc, cr, te\n# all_knots, lower, upper, inner = compute_all_knots(x, df, degree)\n# result = cc(x, df=df, knots=all_knots, lower_bound=lower, upper_bound=upper,\n# constraints=None)\n#\n# import matplotlib.pyplot as plt\n#\n# result = np.array(result)\n# print(result.shape)\n# plt.plot(result.T)\n# plt.show()\n\nclass UnivariateGamSmoother(with_metaclass(ABCMeta)):\n \"\"\"Base Class for single smooth component\n \"\"\"\n def __init__(self, x, constraints=None, variable_name='x'):\n self.x = x\n self.constraints = constraints\n self.variable_name = variable_name\n self.nobs, self.k_variables = len(x), 1\n\n base4 = self._smooth_basis_for_single_variable()\n if constraints == 'center':\n constraints = base4[0].mean(0)[None, :]\n\n if constraints is not None and not isinstance(constraints, str):\n ctransf = transf_constraints(constraints)\n self.ctransf = ctransf\n else:\n # subclasses might set ctransf directly\n # only used if constraints is None\n if not hasattr(self, 'ctransf'):\n self.ctransf = None\n\n self.basis, self.der_basis, self.der2_basis, self.cov_der2 = base4\n if self.ctransf is not None:\n ctransf = self.ctransf\n # transform attributes that are not None\n if base4[0] is not None:\n self.basis = base4[0].dot(ctransf)\n if base4[1] is not None:\n self.der_basis = base4[1].dot(ctransf)\n if base4[2] is not None:\n self.der2_basis = base4[2].dot(ctransf)\n if base4[3] is not None:\n self.cov_der2 = ctransf.T.dot(base4[3]).dot(ctransf)\n\n self.dim_basis = self.basis.shape[1]\n self.col_names = [self.variable_name + \"_s\" + str(i)\n for i in range(self.dim_basis)]\n\n @abstractmethod\n def _smooth_basis_for_single_variable(self):\n return\n\n\nclass UnivariateGenericSmoother(UnivariateGamSmoother):\n \"\"\"Generic single smooth component\n \"\"\"\n def __init__(self, x, basis, der_basis, der2_basis, cov_der2,\n variable_name='x'):\n self.basis = basis\n self.der_basis = der_basis\n self.der2_basis = der2_basis\n self.cov_der2 = cov_der2\n\n super(UnivariateGenericSmoother, self).__init__(\n x, variable_name=variable_name)\n\n def _smooth_basis_for_single_variable(self):\n return self.basis, self.der_basis, self.der2_basis, self.cov_der2\n\n\nclass UnivariatePolynomialSmoother(UnivariateGamSmoother):\n \"\"\"polynomial single smooth component\n \"\"\"\n def __init__(self, x, degree, variable_name='x'):\n self.degree = degree\n super(UnivariatePolynomialSmoother, self).__init__(\n x, variable_name=variable_name)\n\n def _smooth_basis_for_single_variable(self):\n # TODO: unclear description\n \"\"\"\n given a vector x returns poly=(1, x, x^2, ..., x^degree)\n and its first and second derivative\n \"\"\"\n\n basis = np.zeros(shape=(self.nobs, self.degree))\n der_basis = np.zeros(shape=(self.nobs, self.degree))\n der2_basis = np.zeros(shape=(self.nobs, self.degree))\n for i in range(self.degree):\n dg = i + 1\n basis[:, i] = self.x ** dg\n der_basis[:, i] = dg * self.x ** (dg - 1)\n if dg > 1:\n der2_basis[:, i] = dg * (dg - 1) * self.x ** (dg - 2)\n else:\n der2_basis[:, i] = 0\n\n cov_der2 = np.dot(der2_basis.T, der2_basis)\n\n return basis, der_basis, der2_basis, cov_der2\n\n\nclass UnivariateBSplines(UnivariateGamSmoother):\n \"\"\"B-Spline single smooth component\n\n This creates and holds the B-Spline basis function for one\n component.\n\n Parameters\n ----------\n x : array, 1-D\n underlying explanatory variable for smooth terms.\n df : int\n numer of basis functions or degrees of freedom\n degree : int\n degree of the spline\n include_intercept : bool\n If False, then the basis functions are transformed so that they\n do not include a constant. This avoids perfect collinearity if\n a constant or several components are included in the model.\n constraints : None, string or array\n Constraints are used to transform the basis functions to satisfy\n those constraints.\n `constraints = 'center'` applies a linear transform to remove the\n constant and center the basis functions.\n variable_name : None or str\n The name for the underlying explanatory variable, x, used in for\n creating the column and parameter names for the basis functions.\n covder2_kwds : None or dict\n options for computing the penalty matrix from the second derivative\n of the spline.\n knot_kwds : None or list of dict\n option for the knot selection.\n By default knots are selected in the same way as in patsy, however the\n number of knots is independent of keeping or removing the constant.\n Interior knot selection is based on quantiles of the data and is the\n same in patsy and mgcv. Boundary points are at the limits of the data\n range.\n The available options use with `get_knots_bsplines` are\n\n - knots : None or array\n interior knots\n - spacing : 'quantile' or 'equal'\n - lower_bound : None or float\n location of lower boundary knots, all boundary knots are at the same\n point\n - upper_bound : None or float\n location of upper boundary knots, all boundary knots are at the same\n point\n - all_knots : None or array\n If all knots are provided, then those will be taken as given and\n all other options will be ignored.\n\n \"\"\"\n def __init__(self, x, df, degree=3, include_intercept=False,\n constraints=None, variable_name='x',\n covder2_kwds=None, **knot_kwds):\n self.degree = degree\n self.df = df\n self.include_intercept = include_intercept\n self.knots = get_knots_bsplines(x, degree=degree, df=df, **knot_kwds)\n self.covder2_kwds = (covder2_kwds if covder2_kwds is not None\n else {})\n super(UnivariateBSplines, self).__init__(\n x, constraints=constraints, variable_name=variable_name)\n\n def _smooth_basis_for_single_variable(self):\n basis, der_basis, der2_basis = _eval_bspline_basis(\n self.x, self.knots, self.degree,\n include_intercept=self.include_intercept)\n # cov_der2 = np.dot(der2_basis.T, der2_basis)\n\n cov_der2 = get_covder2(self, skip_ctransf=True,\n **self.covder2_kwds)\n\n return basis, der_basis, der2_basis, cov_der2\n\n def transform(self, x_new, deriv=0, skip_ctransf=False):\n \"\"\"create the spline basis for new observations\n\n The main use of this stateful transformation is for prediction\n using the same specification of the spline basis.\n\n Parameters\n ----------\n x_new : array\n observations of the underlying explanatory variable\n deriv : int\n which derivative of the spline basis to compute\n This is an options for internal computation.\n skip_ctransf : bool\n whether to skip the constraint transform\n This is an options for internal computation.\n\n Returns\n -------\n basis : ndarray\n design matrix for the spline basis for given ``x_new``\n \"\"\"\n\n if x_new is None:\n x_new = self.x\n exog = _eval_bspline_basis(x_new, self.knots, self.degree,\n deriv=deriv,\n include_intercept=self.include_intercept)\n\n # ctransf does not exist yet when cov_der2 is computed\n ctransf = getattr(self, 'ctransf', None)\n if ctransf is not None and not skip_ctransf:\n exog = exog.dot(self.ctransf)\n return exog\n\n\nclass UnivariateCubicSplines(UnivariateGamSmoother):\n \"\"\"Cubic Spline single smooth component\n\n Cubic splines as described in the wood's book in chapter 3\n \"\"\"\n\n def __init__(self, x, df, constraints=None, transform='domain',\n variable_name='x'):\n\n self.degree = 3\n self.df = df\n self.transform_data_method = transform\n\n self.x = x = self.transform_data(x, initialize=True)\n self.knots = _equally_spaced_knots(x, df)\n super(UnivariateCubicSplines, self).__init__(\n x, constraints=constraints, variable_name=variable_name)\n\n def transform_data(self, x, initialize=False):\n tm = self.transform_data_method\n if tm is None:\n return x\n\n if initialize is True:\n if tm == 'domain':\n self.domain_low = x.min(0)\n self.domain_upp = x.max(0)\n elif isinstance(tm, tuple):\n self.domain_low = tm[0]\n self.domain_upp = tm[1]\n self.transform_data_method = 'domain'\n else:\n raise ValueError(\"transform should be None, 'domain' \"\n \"or a tuple\")\n self.domain_diff = self.domain_upp - self.domain_low\n\n if self.transform_data_method == 'domain':\n x = (x - self.domain_low) / self.domain_diff\n return x\n else:\n raise ValueError(\"incorrect transform_data_method\")\n\n def _smooth_basis_for_single_variable(self):\n\n basis = self._splines_x()[:, :-1]\n # demean except for constant, does not affect derivatives\n if not self.constraints == 'none':\n self.transf_mean = basis[:, 1:].mean(0)\n basis[:, 1:] -= self.transf_mean\n else:\n self.transf_mean = np.zeros(basis.shape[1])\n s = self._splines_s()[:-1, :-1]\n if not self.constraints == 'none':\n ctransf = np.diag(1/np.max(np.abs(basis), axis=0))\n else:\n ctransf = np.eye(basis.shape[1])\n # use np.eye to avoid rescaling\n # ctransf = np.eye(basis.shape[1])\n\n if self.constraints == 'no-const':\n ctransf = ctransf[1:]\n\n self.ctransf = ctransf\n\n return basis, None, None, s\n\n def _rk(self, x, z):\n p1 = ((z - 1 / 2) ** 2 - 1 / 12) * ((x - 1 / 2) ** 2 - 1 / 12) / 4\n p2 = ((np.abs(z - x) - 1 / 2) ** 4 -\n 1 / 2 * (np.abs(z - x) - 1 / 2) ** 2 +\n 7 / 240) / 24.\n return p1 - p2\n\n def _splines_x(self, x=None):\n if x is None:\n x = self.x\n n_columns = len(self.knots) + 2\n nobs = x.shape[0]\n basis = np.ones(shape=(nobs, n_columns))\n basis[:, 1] = x\n # for loop equivalent to outer(x, xk, fun=rk)\n for i, xi in enumerate(x):\n for j, xkj in enumerate(self.knots):\n s_ij = self._rk(xi, xkj)\n basis[i, j + 2] = s_ij\n return basis\n\n def _splines_s(self):\n q = len(self.knots) + 2\n s = np.zeros(shape=(q, q))\n for i, x1 in enumerate(self.knots):\n for j, x2 in enumerate(self.knots):\n s[i + 2, j + 2] = self._rk(x1, x2)\n return s\n\n def transform(self, x_new):\n x_new = self.transform_data(x_new, initialize=False)\n exog = self._splines_x(x_new)\n exog[:, 1:] -= self.transf_mean\n if self.ctransf is not None:\n exog = exog.dot(self.ctransf)\n return exog\n\n\nclass UnivariateCubicCyclicSplines(UnivariateGamSmoother):\n \"\"\"cyclic cubic regression spline single smooth component\n\n This creates and holds the Cyclic CubicSpline basis function for one\n component.\n\n Parameters\n ----------\n x : array, 1-D\n underlying explanatory variable for smooth terms.\n df : int\n numer of basis functions or degrees of freedom\n degree : int\n degree of the spline\n include_intercept : bool\n If False, then the basis functions are transformed so that they\n do not include a constant. This avoids perfect collinearity if\n a constant or several components are included in the model.\n constraints : None, string or array\n Constraints are used to transform the basis functions to satisfy\n those constraints.\n `constraints = 'center'` applies a linear transform to remove the\n constant and center the basis functions.\n variable_name : None or str\n The name for the underlying explanatory variable, x, used in for\n creating the column and parameter names for the basis functions.\n \"\"\"\n def __init__(self, x, df, constraints=None, variable_name='x'):\n self.degree = 3\n self.df = df\n self.x = x\n self.knots = _equally_spaced_knots(x, df)\n super(UnivariateCubicCyclicSplines, self).__init__(\n x, constraints=constraints, variable_name=variable_name)\n\n def _smooth_basis_for_single_variable(self):\n basis = dmatrix(\"cc(x, df=\" + str(self.df) + \") - 1\", {\"x\": self.x})\n self.design_info = basis.design_info\n n_inner_knots = self.df - 2 + 1 # +n_constraints\n # TODO: from CubicRegressionSplines class\n all_knots = _get_all_sorted_knots(self.x, n_inner_knots=n_inner_knots,\n inner_knots=None,\n lower_bound=None, upper_bound=None)\n\n b, d = self._get_b_and_d(all_knots)\n s = self._get_s(b, d)\n\n return basis, None, None, s\n\n def _get_b_and_d(self, knots):\n \"\"\"Returns mapping of cyclic cubic spline values to 2nd derivatives.\n\n .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006,\n pp 146-147\n\n Parameters\n ----------\n knots : ndarray\n The 1-d array knots used for cubic spline parametrization,\n must be sorted in ascending order.\n\n Returns\n -------\n b, d: ndarrays\n arrays for mapping cyclic cubic spline values at knots to\n second derivatives.\n penalty matrix is equal to ``s = d.T.dot(b^-1).dot(d)``\n \"\"\"\n h = knots[1:] - knots[:-1]\n n = knots.size - 1\n\n # b and d are defined such that the penalty matrix is equivalent to:\n # s = d.T.dot(b^-1).dot(d)\n # reference in particular to pag 146 of Wood's book\n b = np.zeros((n, n)) # the b matrix on page 146 of Wood's book\n d = np.zeros((n, n)) # the d matrix on page 146 of Wood's book\n\n b[0, 0] = (h[n - 1] + h[0]) / 3.\n b[0, n - 1] = h[n - 1] / 6.\n b[n - 1, 0] = h[n - 1] / 6.\n\n d[0, 0] = -1. / h[0] - 1. / h[n - 1]\n d[0, n - 1] = 1. / h[n - 1]\n d[n - 1, 0] = 1. / h[n - 1]\n\n for i in range(1, n):\n b[i, i] = (h[i - 1] + h[i]) / 3.\n b[i, i - 1] = h[i - 1] / 6.\n b[i - 1, i] = h[i - 1] / 6.\n\n d[i, i] = -1. / h[i - 1] - 1. / h[i]\n d[i, i - 1] = 1. / h[i - 1]\n d[i - 1, i] = 1. / h[i - 1]\n\n return b, d\n\n def _get_s(self, b, d):\n return d.T.dot(np.linalg.inv(b)).dot(d)\n\n def transform(self, x_new):\n exog = dmatrix(self.design_info, {\"x\": x_new})\n if self.ctransf is not None:\n exog = exog.dot(self.ctransf)\n return exog\n\n\nclass AdditiveGamSmoother(with_metaclass(ABCMeta)):\n \"\"\"Base class for additive smooth components\n \"\"\"\n def __init__(self, x, variable_names=None, include_intercept=False,\n **kwargs):\n\n # get pandas names before using asarray\n if isinstance(x, pd.DataFrame):\n data_names = x.columns.tolist()\n elif isinstance(x, pd.Series):\n data_names = [x.name]\n else:\n data_names = None\n\n x = np.asarray(x)\n\n if x.ndim == 1:\n self.x = x.copy()\n self.x.shape = (len(x), 1)\n else:\n self.x = x\n\n self.nobs, self.k_variables = self.x.shape\n if isinstance(include_intercept, bool):\n self.include_intercept = [include_intercept] * self.k_variables\n else:\n self.include_intercept = include_intercept\n\n if variable_names is None:\n if data_names is not None:\n self.variable_names = data_names\n else:\n self.variable_names = ['x' + str(i)\n for i in range(self.k_variables)]\n else:\n self.variable_names = variable_names\n\n self.smoothers = self._make_smoothers_list()\n self.basis = np.hstack(list(smoother.basis\n for smoother in self.smoothers))\n self.dim_basis = self.basis.shape[1]\n self.penalty_matrices = [smoother.cov_der2\n for smoother in self.smoothers]\n self.col_names = []\n for smoother in self.smoothers:\n self.col_names.extend(smoother.col_names)\n\n self.mask = []\n last_column = 0\n for smoother in self.smoothers:\n mask = np.array([False] * self.dim_basis)\n mask[last_column:smoother.dim_basis + last_column] = True\n last_column = last_column + smoother.dim_basis\n self.mask.append(mask)\n\n @abstractmethod\n def _make_smoothers_list(self):\n pass\n\n def transform(self, x_new):\n \"\"\"create the spline basis for new observations\n\n The main use of this stateful transformation is for prediction\n using the same specification of the spline basis.\n\n Parameters\n ----------\n x_new: array\n observations of the underlying explanatory variable\n\n Returns\n -------\n basis : ndarray\n design matrix for the spline basis for given ``x_new``.\n\n \"\"\"\n exog = np.hstack(list(self.smoothers[i].transform(x_new[:, i])\n for i in range(self.k_variables)))\n return exog\n\n\nclass GenericSmoothers(AdditiveGamSmoother):\n \"\"\"generic class for additive smooth components for GAM\n \"\"\"\n def __init__(self, x, smoothers):\n self.smoothers = smoothers\n super(GenericSmoothers, self).__init__(x, variable_names=None)\n\n def _make_smoothers_list(self):\n return self.smoothers\n\n\nclass PolynomialSmoother(AdditiveGamSmoother):\n \"\"\"additive polynomial components for GAM\n \"\"\"\n def __init__(self, x, degrees, variable_names=None):\n self.degrees = degrees\n super(PolynomialSmoother, self).__init__(x,\n variable_names=variable_names)\n\n def _make_smoothers_list(self):\n smoothers = []\n for v in range(self.k_variables):\n uv_smoother = UnivariatePolynomialSmoother(\n self.x[:, v],\n degree=self.degrees[v],\n variable_name=self.variable_names[v])\n smoothers.append(uv_smoother)\n return smoothers\n\n\nclass BSplines(AdditiveGamSmoother):\n \"\"\"additive smooth components using B-Splines\n\n This creates and holds the B-Spline basis function for several\n components.\n\n Parameters\n ----------\n x : array_like, 1-D or 2-D\n underlying explanatory variable for smooth terms.\n If 2-dimensional, then observations should be in rows and\n explanatory variables in columns.\n df : int\n numer of basis functions or degrees of freedom\n degree : int\n degree of the spline\n include_intercept : bool\n If False, then the basis functions are transformed so that they\n do not include a constant. This avoids perfect collinearity if\n a constant or several components are included in the model.\n constraints : None, string or array\n Constraints are used to transform the basis functions to satisfy\n those constraints.\n `constraints = 'center'` applies a linear transform to remove the\n constant and center the basis functions.\n variable_names : None or list of strings\n The names for the underlying explanatory variables, x used in for\n creating the column and parameter names for the basis functions.\n If ``x`` is a pandas object, then the names will be taken from it.\n knot_kwds : None or list of dict\n option for the knot selection.\n By default knots are selected in the same way as in patsy, however the\n number of knots is independent of keeping or removing the constant.\n Interior knot selection is based on quantiles of the data and is the\n same in patsy and mgcv. Boundary points are at the limits of the data\n range.\n The available options use with `get_knots_bsplines` are\n\n - knots : None or array\n interior knots\n - spacing : 'quantile' or 'equal'\n - lower_bound : None or float\n location of lower boundary knots, all boundary knots are at the same\n point\n - upper_bound : None or float\n location of upper boundary knots, all boundary knots are at the same\n point\n - all_knots : None or array\n If all knots are provided, then those will be taken as given and\n all other options will be ignored.\n\n\n Attributes\n ----------\n smoothers : list of univariate smooth component instances\n basis : design matrix, array of spline bases columns for all components\n penalty_matrices : list of penalty matrices, one for each smooth term\n dim_basis : number of columns in the basis\n k_variables : number of smooth components\n col_names : created names for the basis columns\n\n There are additional attributes about the specification of the splines\n and some attributes mainly for internal use.\n\n Notes\n -----\n A constant in the spline basis function can be removed in two different\n ways.\n The first is by dropping one basis column and normalizing the\n remaining columns. This is obtained by the default\n ``include_intercept=False, constraints=None``\n The second option is by using the centering transform which is a linear\n transformation of all basis functions. As a consequence of the\n transformation, the B-spline basis functions do not have locally bounded\n support anymore. This is obtained ``constraints='center'``. In this case\n ``include_intercept`` will be automatically set to True to avoid\n dropping an additional column.\n\n\n \"\"\"\n def __init__(self, x, df, degree, include_intercept=False,\n constraints=None, variable_names=None, knot_kwds=None):\n self.degrees = degree\n self.dfs = df\n self.knot_kwds = knot_kwds\n # TODO: move attaching constraints to super call\n self.constraints = constraints\n if constraints == 'center':\n include_intercept = True\n\n super(BSplines, self).__init__(x, include_intercept=include_intercept,\n variable_names=variable_names)\n\n def _make_smoothers_list(self):\n smoothers = []\n for v in range(self.k_variables):\n kwds = self.knot_kwds[v] if self.knot_kwds else {}\n uv_smoother = UnivariateBSplines(\n self.x[:, v],\n df=self.dfs[v], degree=self.degrees[v],\n include_intercept=self.include_intercept[v],\n constraints=self.constraints,\n variable_name=self.variable_names[v], **kwds)\n smoothers.append(uv_smoother)\n\n return smoothers\n\n\nclass CubicSplines(AdditiveGamSmoother):\n \"\"\"additive smooth components using cubic splines as in Wood 2006.\n\n Note, these splines do NOT use the same spline basis as\n ``Cubic Regression Splines``.\n\n \"\"\"\n def __init__(self, x, df, constraints='center', transform='domain',\n variable_names=None):\n self.dfs = df\n self.constraints = constraints\n self.transform = transform\n super(CubicSplines, self).__init__(x, constraints=constraints,\n variable_names=variable_names)\n\n def _make_smoothers_list(self):\n smoothers = []\n for v in range(self.k_variables):\n uv_smoother = UnivariateCubicSplines(\n self.x[:, v], df=self.dfs[v],\n constraints=self.constraints,\n transform=self.transform,\n variable_name=self.variable_names[v])\n smoothers.append(uv_smoother)\n\n return smoothers\n\n\nclass CyclicCubicSplines(AdditiveGamSmoother):\n \"\"\"additive smooth components using cyclic cubic regression splines\n\n This spline basis is the same as in patsy.\n\n Parameters\n ----------\n x : array_like, 1-D or 2-D\n underlying explanatory variable for smooth terms.\n If 2-dimensional, then observations should be in rows and\n explanatory variables in columns.\n df : int\n numer of basis functions or degrees of freedom\n constraints : None, string or array\n Constraints are used to transform the basis functions to satisfy\n those constraints.\n variable_names : None or list of strings\n The names for the underlying explanatory variables, x used in for\n creating the column and parameter names for the basis functions.\n If ``x`` is a pandas object, then the names will be taken from it.\n\n \"\"\"\n def __init__(self, x, df, constraints=None, variable_names=None):\n self.dfs = df\n # TODO: move attaching constraints to super call\n self.constraints = constraints\n super(CyclicCubicSplines, self).__init__(x,\n variable_names=variable_names)\n\n def _make_smoothers_list(self):\n smoothers = []\n for v in range(self.k_variables):\n uv_smoother = UnivariateCubicCyclicSplines(\n self.x[:, v],\n df=self.dfs[v], constraints=self.constraints,\n variable_name=self.variable_names[v])\n smoothers.append(uv_smoother)\n\n return smoothers\n\n# class CubicRegressionSplines(BaseCubicSplines):\n# # TODO: this class is still not tested\n#\n# def __init__(self, x, df=10):\n# import warnings\n# warnings.warn(\"This class is still not tested and it is probably\"\n# \" not working properly. \"\n# \"I suggest to use another smoother\", Warning)\n#\n# super(CubicRegressionSplines, self).__init__(x, df)\n#\n# self.basis = dmatrix(\"cc(x, df=\" + str(df) + \") - 1\", {\"x\": x})\n# n_inner_knots = df - 2 + 1 # +n_constraints\n# # TODO: ACcording to CubicRegressionSplines class this should be\n# # n_inner_knots = df - 2\n# all_knots = _get_all_sorted_knots(x, n_inner_knots=n_inner_knots,\n# inner_knots=None,\n# lower_bound=None, upper_bound=None)\n#\n# b, d = self._get_b_and_d(all_knots)\n# self.s = self._get_s(b, d)\n#\n# self.dim_basis = self.basis.shape[1]\n#\n# def _get_b_and_d(self, knots):\n#\n# h = knots[1:] - knots[:-1]\n# n = knots.size - 1\n#\n# # b and d are defined such that the penalty matrix is equivalent to:\n# # s = d.T.dot(b^-1).dot(d)\n# # reference in particular to pag 146 of Wood's book\n# b = np.zeros((n, n)) # the b matrix on page 146 of Wood's book\n# d = np.zeros((n, n)) # the d matrix on page 146 of Wood's book\n#\n# for i in range(n-2):\n# d[i, i] = 1/h[i]\n# d[i, i+1] = -1/h[i] - 1/h[i+1]\n# d[i, i+2] = 1/h[i+1]\n#\n# b[i, i] = (h[i] + h[i+1])/3\n#\n# for i in range(n-3):\n# b[i, i+1] = h[i+1]/6\n# b[i+1, i] = h[i+1]/6\n#\n# return b, d\n#\n# def _get_s(self, b, d):\n#\n# return d.T.dot(np.linalg.pinv(b)).dot(d)\n"
] | [
[
"pandas.Series",
"numpy.asarray",
"numpy.cumsum",
"pandas.DataFrame",
"numpy.concatenate",
"numpy.random.randn",
"numpy.mean",
"numpy.random.randint",
"pandas.read_csv",
"numpy.ones_like",
"pandas.Index",
"pandas.DatetimeIndex",
"numpy.testing.assert_almost_equal",
"numpy.diff",
"numpy.zeros",
"numpy.log",
"numpy.genfromtxt",
"numpy.testing.assert_raises",
"pandas.date_range",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.random.random",
"numpy.random.seed",
"pandas.period_range",
"numpy.ones",
"numpy.empty"
],
[
"pandas.tseries.api.infer_freq"
],
[
"numpy.diag",
"numpy.dot",
"numpy.ix_",
"numpy.linalg.solve",
"numpy.isfinite",
"numpy.asarray",
"numpy.isnan",
"numpy.eye",
"numpy.linalg.inv",
"numpy.arange",
"pandas.DataFrame",
"numpy.flatnonzero",
"numpy.atleast_2d",
"numpy.ceil",
"numpy.cov",
"numpy.random.normal",
"numpy.linalg.cholesky"
],
[
"numpy.dot",
"numpy.linspace",
"numpy.asarray",
"numpy.concatenate",
"numpy.max",
"numpy.any",
"numpy.unique",
"numpy.arange",
"numpy.eye",
"numpy.atleast_1d",
"numpy.diff",
"numpy.zeros",
"numpy.min",
"numpy.linalg.inv",
"scipy.interpolate.splev",
"scipy.integrate.simps",
"numpy.array",
"numpy.abs",
"numpy.percentile",
"numpy.ones",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [
"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": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"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": []
}
] |
hmmmq/BreastTumorIdentificationSystem | [
"ccb80ba11308ba14d92060f54a1d524c9e8561fd"
] | [
"faster_rcnn/backbone/resnet50_fpn_model.py"
] | [
"import os\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\nfrom torch.jit.annotations import List, Dict\nfrom torchvision.ops.misc import FrozenBatchNorm2d\n\nfrom .feature_pyramid_network import FeaturePyramidNetwork, LastLevelMaxPool\n\n\nclass Bottleneck(nn.Module): # conv block 和 identity block\n expansion = 4\n\n def __init__(self, in_channel, out_channel, stride=1, downsample=None, norm_layer=None):\n super(Bottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n\n self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,\n kernel_size=1, stride=1, bias=False) # squeeze channels\n self.bn1 = norm_layer(out_channel)\n # -----------------------------------------\n self.conv2 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel,\n kernel_size=3, stride=stride, bias=False, padding=1)\n self.bn2 = norm_layer(out_channel)\n # -----------------------------------------\n self.conv3 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel * self.expansion,\n kernel_size=1, stride=1, bias=False) # unsqueeze channels\n self.bn3 = norm_layer(out_channel * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n\n def forward(self, x):\n identity = x\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, blocks_num, num_classes=1000, include_top=True, norm_layer=None):\n super(ResNet, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self._norm_layer = norm_layer\n\n self.include_top = include_top\n self.in_channel = 64\n\n self.conv1 = nn.Conv2d(3, self.in_channel, kernel_size=7, stride=2,\n padding=3, bias=False)\n self.bn1 = norm_layer(self.in_channel)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, blocks_num[0])\n self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)\n self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)\n self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)\n if self.include_top:\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) # output size = (1, 1)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n\n def _make_layer(self, block, channel, block_num, stride=1):\n norm_layer = self._norm_layer\n downsample = None\n if stride != 1 or self.in_channel != channel * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.in_channel, channel * block.expansion, kernel_size=1, stride=stride, bias=False),\n norm_layer(channel * block.expansion))\n\n layers = []\n layers.append(block(self.in_channel, channel, downsample=downsample,\n stride=stride, norm_layer=norm_layer))\n self.in_channel = channel * block.expansion\n\n for _ in range(1, block_num):\n layers.append(block(self.in_channel, channel, norm_layer=norm_layer))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n if self.include_top:\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n x = self.fc(x)\n\n return x\n\n\ndef overwrite_eps(model, eps):\n \"\"\"\n This method overwrites the default eps values of all the\n FrozenBatchNorm2d layers of the model with the provided value.\n This is necessary to address the BC-breaking change introduced\n by the bug-fix at pytorch/vision#2933. The overwrite is applied\n only when the pretrained weights are loaded to maintain compatibility\n with previous versions.\n\n Args:\n model (nn.Module): The model on which we perform the overwrite.\n eps (float): The new value of eps.\n \"\"\"\n for module in model.modules():\n if isinstance(module, FrozenBatchNorm2d):\n module.eps = eps\n\n\nclass IntermediateLayerGetter(nn.ModuleDict):\n \"\"\"\n Module wrapper that returns intermediate layers from a model\n It has a strong assumption that the modules have been registered\n into the model in the same order as they are used.\n This means that one should **not** reuse the same nn.Module\n twice in the forward if you want this to work.\n Additionally, it is only able to query submodules that are directly\n assigned to the model. So if `model` is passed, `model.feature1` can\n be returned, but not `model.feature1.layer2`.\n Arguments:\n model (nn.Module): model on which we will extract the features\n return_layers (Dict[name, new_name]): a dict containing the names\n of the modules for which the activations will be returned as\n the key of the dict, and the value of the dict is the name\n of the returned activation (which the user can specify).\n \"\"\"\n __annotations__ = {\n \"return_layers\": Dict[str, str],\n }\n\n def __init__(self, model, return_layers):\n if not set(return_layers).issubset([name for name, _ in model.named_children()]):\n raise ValueError(\"return_layers are not present in model\")\n\n orig_return_layers = return_layers\n return_layers = {str(k): str(v) for k, v in return_layers.items()}\n layers = OrderedDict()\n\n # 遍历模型子模块按顺序存入有序字典\n # 只保存layer4及其之前的结构,舍去之后不用的结构\n for name, module in model.named_children():\n layers[name] = module\n if name in return_layers:\n del return_layers[name]\n if not return_layers:\n break\n\n super(IntermediateLayerGetter, self).__init__(layers)\n self.return_layers = orig_return_layers\n\n def forward(self, x):\n out = OrderedDict()\n # 依次遍历模型的所有子模块,并进行正向传播,\n # 收集layer1, layer2, layer3, layer4的输出\n for name, module in self.items():\n x = module(x)\n if name in self.return_layers:\n out_name = self.return_layers[name]\n out[out_name] = x\n return out\n\n\nclass BackboneWithFPN(nn.Module):\n \"\"\"\n Adds a FPN on top of a model.\n Internally, it uses torchvision.models._utils.IntermediateLayerGetter to\n extract a submodel that returns the feature maps specified in return_layers.\n The same limitations of IntermediatLayerGetter apply here.\n Arguments:\n backbone (nn.Module)\n return_layers (Dict[name, new_name]): a dict containing the names\n of the modules for which the activations will be returned as\n the key of the dict, and the value of the dict is the name\n of the returned activation (which the user can specify).\n in_channels_list (List[int]): number of channels for each feature map\n that is returned, in the order they are present in the OrderedDict\n out_channels (int): number of channels in the FPN.\n extra_blocks: ExtraFPNBlock\n Attributes:\n out_channels (int): the number of channels in the FPN\n \"\"\"\n\n def __init__(self, backbone, return_layers, in_channels_list, out_channels, extra_blocks=None):\n super(BackboneWithFPN, self).__init__()\n\n if extra_blocks is None:\n extra_blocks = LastLevelMaxPool()\n\n self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)\n self.fpn = FeaturePyramidNetwork(\n in_channels_list=in_channels_list,\n out_channels=out_channels,\n extra_blocks=extra_blocks,\n )\n\n self.out_channels = out_channels\n\n def forward(self, x):\n x = self.body(x)\n x = self.fpn(x)\n return x\n\n\ndef resnet50_fpn_backbone(pretrain_path=\"\",\n norm_layer=FrozenBatchNorm2d, # FrozenBatchNorm2d的功能与BatchNorm2d类似,但参数无法更新\n trainable_layers=3,\n returned_layers=None,\n extra_blocks=None):\n \"\"\"\n 搭建resnet50_fpn——backbone\n Args:\n pretrain_path: resnet50的预训练权重,如果不使用就默认为空\n norm_layer: 官方默认的是FrozenBatchNorm2d,即不会更新参数的bn层(因为如果batch_size设置的很小会导致效果更差,还不如不用bn层)\n 如果自己的GPU显存很大可以设置很大的batch_size,那么自己可以传入正常的BatchNorm2d层\n (https://github.com/facebookresearch/maskrcnn-benchmark/issues/267)\n trainable_layers: 指定训练哪些层结构\n returned_layers: 指定哪些层的输出需要返回\n extra_blocks: 在输出的特征层基础上额外添加的层结构\n\n Returns:\n\n \"\"\"\n resnet_backbone = ResNet(Bottleneck, [3, 4, 6, 3],\n include_top=False,\n norm_layer=norm_layer)\n\n if isinstance(norm_layer, FrozenBatchNorm2d):\n overwrite_eps(resnet_backbone, 0.0)\n\n if pretrain_path != \"\":\n assert os.path.exists(pretrain_path), \"{} is not exist.\".format(pretrain_path)\n # 载入预训练权重\n print(resnet_backbone.load_state_dict(torch.load(pretrain_path), strict=False))\n\n # select layers that wont be frozen\n assert 0 <= trainable_layers <= 5\n layers_to_train = ['layer4', 'layer3', 'layer2', 'layer1', 'conv1'][:trainable_layers]\n\n # 如果要训练所有层结构的话,不要忘了conv1后还有一个bn1\n if trainable_layers == 5:\n layers_to_train.append(\"bn1\")\n\n # freeze layers\n for name, parameter in resnet_backbone.named_parameters():\n # 只训练不在layers_to_train列表中的层结构\n if all([not name.startswith(layer) for layer in layers_to_train]):\n parameter.requires_grad_(False)\n\n if extra_blocks is None:\n extra_blocks = LastLevelMaxPool()\n\n if returned_layers is None:\n returned_layers = [1, 2, 3, 4]\n # 返回的特征层个数肯定大于0小于5\n assert min(returned_layers) > 0 and max(returned_layers) < 5\n\n # return_layers = {'layer1': '0', 'layer2': '1', 'layer3': '2', 'layer4': '3'}\n return_layers = {f'layer{k}': str(v) for v, k in enumerate(returned_layers)}\n\n # in_channel 为layer4的输出特征矩阵channel = 2048\n in_channels_stage2 = resnet_backbone.in_channel // 8 # 256\n # 记录resnet50提供给fpn的每个特征层channel\n in_channels_list = [in_channels_stage2 * 2 ** (i - 1) for i in returned_layers]\n # 通过fpn后得到的每个特征层的channel\n out_channels = 256\n return BackboneWithFPN(resnet_backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks)\n"
] | [
[
"torch.nn.Sequential",
"torch.load",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.Linear",
"torch.nn.AdaptiveAvgPool2d",
"torch.flatten",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lilhope/odnl | [
"e302a800a98a31309de0e8a0ee97a2351bea35de"
] | [
"rcnn/symbol/proposal_target.py"
] | [
"\"\"\"\nProposal Target Operator selects foreground and background roi and assigns label, bbox_transform to them.\n\"\"\"\n\nfrom __future__ import print_function\nimport mxnet as mx\nimport numpy as np\nfrom distutils.util import strtobool\n\nfrom rcnn.io.rcnn import sample_rois\n\nDEBUG = False\n\n\nclass ProposalTargetOperator(mx.operator.CustomOp):\n def __init__(self, num_classes, batch_images, batch_rois, fg_fraction):\n super(ProposalTargetOperator, self).__init__()\n self._num_classes = num_classes\n self._batch_images = batch_images\n self._batch_rois = batch_rois\n self._fg_fraction = fg_fraction\n\n if DEBUG:\n self._count = 0\n self._fg_num = 0\n self._bg_num = 0\n\n def forward(self, is_train, req, in_data, out_data, aux):\n assert self._batch_rois % self._batch_images == 0, \\\n 'BATCHIMAGES {} must devide BATCH_ROIS {}'.format(self._batch_images, self._batch_rois)\n rois_per_image = self._batch_rois / self._batch_images\n fg_rois_per_image = np.round(self._fg_fraction * rois_per_image).astype(int)\n\n all_rois = in_data[0].asnumpy()\n gt_boxes = in_data[1].asnumpy()\n\n # Include ground-truth boxes in the set of candidate rois\n zeros = np.zeros((gt_boxes.shape[0], 1), dtype=gt_boxes.dtype)\n all_rois = np.vstack((all_rois, np.hstack((zeros, gt_boxes[:, :-1]))))\n # Sanity check: single batch only\n assert np.all(all_rois[:, 0] == 0), 'Only single item batches are supported'\n\n rois, labels, bbox_targets, bbox_weights = \\\n sample_rois(all_rois, fg_rois_per_image, rois_per_image, self._num_classes, gt_boxes=gt_boxes)\n\n if DEBUG:\n print(\"labels=\", labels)\n print('num pos: {}'.format((labels ==1 ).sum()))\n print('num pos: {}'.format((labels == 2).sum()))\n self._count += 1\n self._fg_num += (labels > 0).sum()\n self._bg_num += (labels == 0).sum()\n print(\"self._count=\", self._count)\n print('num fg avg: {}'.format(self._fg_num / self._count))\n print('num bg avg: {}'.format(self._bg_num / self._count))\n print('ratio: {:.3f}'.format(float(self._fg_num) / float(self._bg_num)))\n\n for ind, val in enumerate([rois, labels, bbox_targets, bbox_weights]):\n self.assign(out_data[ind], req[ind], val)\n\n def backward(self, req, out_grad, in_data, out_data, in_grad, aux):\n self.assign(in_grad[0], req[0], 0)\n self.assign(in_grad[1], req[1], 0)\n\n\[email protected]('proposal_target')\nclass ProposalTargetProp(mx.operator.CustomOpProp):\n def __init__(self, num_classes, batch_images, batch_rois, fg_fraction='0.25'):\n super(ProposalTargetProp, self).__init__(need_top_grad=False)\n self._num_classes = int(num_classes)\n self._batch_images = int(batch_images)\n self._batch_rois = int(batch_rois)\n self._fg_fraction = float(fg_fraction)\n\n def list_arguments(self):\n return ['rois', 'gt_boxes']\n\n def list_outputs(self):\n return ['rois_output', 'label', 'bbox_target', 'bbox_weight']\n\n def infer_shape(self, in_shape):\n rpn_rois_shape = in_shape[0]\n gt_boxes_shape = in_shape[1]\n\n output_rois_shape = (self._batch_rois, 5)\n label_shape = (self._batch_rois, )\n bbox_target_shape = (self._batch_rois, self._num_classes * 4)\n bbox_weight_shape = (self._batch_rois, self._num_classes * 4)\n\n return [rpn_rois_shape, gt_boxes_shape], \\\n [output_rois_shape, label_shape, bbox_target_shape, bbox_weight_shape]\n\n def create_operator(self, ctx, shapes, dtypes):\n return ProposalTargetOperator(self._num_classes, self._batch_images, self._batch_rois, self._fg_fraction)\n\n def declare_backward_dependency(self, out_grad, in_data, out_data):\n return []\n"
] | [
[
"numpy.all",
"numpy.round",
"numpy.zeros",
"numpy.hstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gecrooks/quantumflow | [
"9d521afdec54898f52f504cf805bd994ba09b61b"
] | [
"quantumflow/circuits.py"
] | [
"# Copyright 2016-2018, Rigetti Computing\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n\"\"\"\n.. contents:: :local:\n.. currentmodule:: quantumflow\n\n\nCircuit objects\n###############\n.. autoclass:: Circuit\n :members:\n\n.. autoclass:: DAGCircuit\n :members:\n\n\nStandard circuits\n#################\n\n\n.. autofunction:: control_circuit\n.. autofunction:: zyz_circuit\n.. autofunction:: euler_circuit\n.. autofunction:: phase_estimation_circuit\n.. autofunction:: addition_circuit\n.. autofunction:: ghz_circuit\n.. autofunction:: graph_circuit\n.. autofunction:: graph_circuit_params\n\nVisualizations\n##############\n\n.. autofunction:: circuit_to_diagram\n.. autofunction:: circuit_to_image\n.. autofunction:: circuit_to_latex\n.. autofunction:: latex_to_image\n\"\"\"\n\nimport textwrap\nfrom collections import defaultdict\nfrom itertools import chain\nfrom typing import (\n Any,\n Dict,\n Iterable,\n Iterator,\n Mapping,\n Optional,\n Sequence,\n Tuple,\n Type,\n Union,\n overload,\n)\n\nimport networkx as nx\nimport numpy as np\n\nfrom .config import CIRCUIT_INDENT\nfrom .ops import Channel, Gate, Operation\nfrom .qubits import Qubit, Qubits, sorted_qubits\nfrom .states import Density, State, zero_state\nfrom .stdgates import CZ, ZZ, CCNot, CNot, H, X, XPow, YPow, ZPow\nfrom .var import Variable\n\n__all__ = [\n \"Circuit\",\n \"count_operations\",\n \"map_gate\",\n \"control_circuit\",\n \"euler_circuit\",\n \"zyz_circuit\",\n \"phase_estimation_circuit\",\n \"addition_circuit\",\n \"ghz_circuit\",\n \"graph_circuit\",\n \"graph_circuit_params\",\n \"graph_state_circuit\",\n]\n\n\nclass Circuit(Sequence, Operation):\n \"\"\"A quantum Circuit contains a sequences of circuit elements.\n These can be any quantum Operation, including other circuits.\n \"\"\"\n\n def __init__(\n self, *elements: Union[Iterable[Operation], Operation], qubits: Qubits = None\n ) -> None:\n\n elements = tuple(elements)\n\n if len(elements) == 1 and isinstance(elements[0], Iterable):\n # Legacy interface\n elements = tuple(elements[0]) # type: ignore\n\n qbs = [q for elem in elements for q in elem.qubits] # type: ignore\n\n if qubits is None:\n qubits = sorted_qubits(list(set(qbs))) # unique and sort\n else:\n if not set(qbs).issubset(qubits):\n raise ValueError(\n f\"Incommensurate qubits: Expected {list(qubits)}\"\n \"but received {list(qbs)}\"\n )\n\n super().__init__(qubits=qubits)\n self._elements: Tuple[Operation, ...] = elements # type: ignore\n\n # Methods for Sequence\n @overload\n def __getitem__(self, key: int) -> Operation:\n ... # pragma: no cover\n\n @overload # noqa: F811\n def __getitem__(self, key: slice) -> \"Circuit\":\n ... # pragma: no cover\n\n def __getitem__(self, key: Union[int, slice]) -> Operation: # noqa: F811s\n if isinstance(key, slice):\n return Circuit(self._elements[key])\n return self._elements[key]\n\n def __len__(self) -> int:\n return len(self._elements)\n\n def add(self, other: Iterable[Operation]) -> \"Circuit\":\n \"\"\"Concatenate operations and return new circuit\"\"\"\n return Circuit(chain(self, other))\n\n def __add__(self, other: \"Circuit\") -> \"Circuit\":\n return self.add(other)\n\n def __iadd__(self, other: Iterable[Any]) -> \"Circuit\":\n return self.add(other)\n\n def __iter__(self) -> Iterator[Operation]:\n yield from self._elements\n\n # End methods for Sequence\n\n def flat(self) -> Iterator[Operation]:\n \"\"\"Iterate over all elementary elements of Circuit,\n recursively flattening composite elements such as\n sub-Circuit's, DAGCircuit's, and Moment's\"\"\"\n for elem in self:\n if hasattr(elem, \"flat\"):\n yield from elem.flat() # type: ignore\n else:\n yield from elem\n\n def size(self) -> int:\n \"\"\"Return the number of operations in this circuit\"\"\"\n return len(self._elements)\n\n def on(self, *qubits: Qubit) -> \"Circuit\":\n if len(qubits) != self.qubit_nb:\n raise ValueError(\"Wrong number of qubits\")\n labels = dict(zip(self.qubits, qubits))\n\n return self.rewire(labels)\n\n def rewire(self, labels: Dict[Qubit, Qubit]) -> \"Circuit\":\n return Circuit(\n [elem.rewire(labels) for elem in self], qubits=list(labels.values())\n )\n\n def run(self, ket: State = None) -> State:\n \"\"\"\n Apply the action of this circuit upon a state.\n\n If no initial state provided an initial zero state will be created.\n \"\"\"\n if ket is None:\n qubits = self.qubits\n ket = zero_state(qubits=qubits)\n\n for elem in self:\n ket = elem.run(ket)\n return ket\n\n def evolve(self, rho: Density = None) -> Density:\n if rho is None:\n qubits = self.qubits\n rho = zero_state(qubits=qubits).asdensity()\n\n for elem in self:\n rho = elem.evolve(rho)\n return rho\n\n def asgate(self) -> Gate:\n from .gates import IdentityGate\n\n gate: Gate = IdentityGate(self.qubits)\n for elem in self:\n gate = elem.asgate() @ gate\n return gate\n\n def aschannel(self) -> Channel:\n from .gates import IdentityGate\n\n chan = IdentityGate(self.qubits).aschannel()\n for elem in self:\n chan = elem.aschannel() @ chan\n return chan\n\n @property\n def H(self) -> \"Circuit\":\n \"\"\"Returns the Hermitian conjugate of this circuit.\n If all the subsidiary gates are unitary, returns the circuit inverse.\n \"\"\"\n return Circuit([elem.H for elem in reversed(self)], qubits=self.qubits)\n\n def __str__(self) -> str:\n circ_str = \"\\n\".join([str(elem) for elem in self])\n circ_str = textwrap.indent(circ_str, \" \" * CIRCUIT_INDENT)\n return \"\\n\".join([self.name, circ_str])\n\n # TESTME\n def resolve(self, subs: Mapping[str, float]) -> \"Circuit\":\n \"\"\"Resolve the parameters of all of the elements of this circuit\"\"\"\n return Circuit(*[op.resolve(subs) for op in self], qubits=self.qubits)\n\n @property\n def params(self) -> Tuple[Variable, ...]:\n return tuple(item for elem in self for item in elem.params)\n\n def param(self, name: str) -> Variable:\n raise ValueError(\"Cannot lookup parameters by name for composite operations\")\n\n # TESTME\n def specialize(self) -> \"Circuit\":\n \"\"\"Specialize all of the elements of this circuit\"\"\"\n return Circuit([elem.specialize() for elem in self], qubits=self.qubits)\n\n # TESTME\n def decompose(self) -> Iterator[\"Operation\"]:\n from .translate import circuit_translate\n\n yield from circuit_translate(self)\n\n def _repr_png_(self) -> Optional[bytes]: # pragma: no cover\n \"\"\"Jupyter/IPython rich display\"\"\"\n from .visualization import circuit_to_image\n\n try:\n return circuit_to_image(self)._repr_png_()\n except (ValueError, IOError):\n return None\n\n def _repr_html_(self) -> Optional[str]: # pragma: no cover\n \"\"\"Jupyter/IPython rich display\"\"\"\n from .visualization import circuit_to_diagram\n\n diag = circuit_to_diagram(self)\n return '<pre style=\"line-height: 90%\">' + diag + \"</pre>\"\n\n\n# End class Circuit\n\n\ndef count_operations(elements: Iterable[Operation]) -> Dict[Type[Operation], int]:\n \"\"\"Return a count of different operation types given a collection of\n operations, such as a Circuit or DAGCircuit\n \"\"\"\n op_count: Dict[Type[Operation], int] = defaultdict(int)\n for elem in elements:\n op_count[type(elem)] += 1\n return dict(op_count)\n\n\n# TODO: MapGate? # TODO: Rename map_gate_circuit\ndef map_gate(gate: Gate, args: Sequence[Qubits]) -> Circuit:\n \"\"\"Applies the same gate to all input qubits in the argument list.\n\n >>> circ = qf.map_gate(qf.H(), [[0], [1], [2]])\n >>> print(circ)\n Circuit\n H(0)\n H(1)\n H(2)\n\n \"\"\"\n circ = Circuit()\n\n for qubits in args:\n circ += gate.on(*qubits)\n\n return circ\n\n\ndef control_circuit(controls: Qubits, gate: Gate) -> Circuit:\n \"\"\"\n Returns a circuit for a target gate controlled by\n a collection of control qubits. [Barenco1995]_\n\n Uses a number of gates quadratic in the number of control qubits.\n\n .. [Barenco1995] A. Barenco, C. Bennett, R. Cleve (1995) Elementary Gates\n for Quantum Computation`<https://arxiv.org/abs/quant-ph/9503016>`_\n Sec 7.2\n \"\"\"\n # Kudos: Adapted from Rigetti Grove's utility_programs.py\n # grove/utils/utility_programs.py::ControlledProgramBuilder\n\n from .gates import ControlGate\n\n circ = Circuit()\n if len(controls) == 1:\n q0 = controls[0]\n if isinstance(gate, X):\n circ += CNot(q0, gate.qubits[0])\n else:\n cgate = ControlGate(gate, [q0])\n circ += cgate\n else:\n circ += control_circuit(controls[-1:], gate**0.5)\n circ += control_circuit(controls[0:-1], X(controls[-1]))\n circ += control_circuit(controls[-1:], gate**-0.5)\n circ += control_circuit(controls[0:-1], X(controls[-1]))\n circ += control_circuit(controls[0:-1], gate**0.5)\n return circ\n\n\ndef zyz_circuit(t0: Variable, t1: Variable, t2: Variable, q0: Qubit) -> Circuit:\n \"\"\"A circuit of ZPow, XPow, ZPow gates on the same qubit\"\"\"\n return euler_circuit(t0, t1, t2, q0, \"ZYZ\")\n\n\ndef euler_circuit(\n t0: Variable,\n t1: Variable,\n t2: Variable,\n q0: Qubit,\n euler: str = \"ZYZ\",\n) -> Circuit:\n \"\"\"\n A Euler decomposition of a 1-qubit gate.\n\n The 'euler' argument can be used to specify any of the 6 Euler\n decompositions: 'XYX', 'XZX', 'YXY', 'YZY', 'ZXZ', 'ZYZ' (Default)\n \"\"\"\n euler_circ = {\n \"XYX\": (XPow, YPow, XPow),\n \"XZX\": (XPow, ZPow, XPow),\n \"YXY\": (YPow, XPow, YPow),\n \"YZY\": (YPow, ZPow, YPow),\n \"ZXZ\": (ZPow, XPow, ZPow),\n \"ZYZ\": (ZPow, YPow, ZPow),\n }\n\n gate0, gate1, gate2 = euler_circ[euler]\n circ = Circuit()\n circ += gate0(t0, q0)\n circ += gate1(t1, q0)\n circ += gate2(t2, q0)\n return circ\n\n\ndef phase_estimation_circuit(gate: Gate, outputs: Qubits) -> Circuit:\n \"\"\"Returns a circuit for quantum phase estimation.\n\n The gate has an eigenvector with eigenvalue e^(i 2 pi phase). To\n run the circuit, the eigenvector should be set on the gate qubits,\n and the output qubits should be in the zero state. After evolution and\n measurement, the output qubits will be (approximately) a binary fraction\n representation of the phase.\n\n The output registers can be converted with the aid of the\n quantumflow.utils.bitlist_to_int() method.\n\n >>> import numpy as np\n >>> import quantumflow as qf\n >>> N = 8\n >>> phase = 1/4\n >>> gate = qf.Rz(-4*np.pi*phase, N)\n >>> circ = qf.phase_estimation_circuit(gate, range(N))\n >>> res = circ.run().measure()[0:N]\n >>> est_phase = int(''.join([str(d) for d in res]), 2) / 2**N # To float\n >>> print(phase, est_phase)\n 0.25 0.25\n\n \"\"\"\n from .gates import ControlGate\n\n circ = Circuit()\n circ += map_gate(H(0), list(zip(outputs))) # Hadamard on all output qubits\n\n for cq in reversed(outputs):\n cgate = ControlGate(gate, [cq])\n circ += cgate\n gate = gate @ gate\n\n from .gates import InvQFTGate\n\n circ += InvQFTGate(outputs).decompose()\n\n return circ\n\n\ndef addition_circuit(addend0: Qubits, addend1: Qubits, carry: Qubits) -> Circuit:\n \"\"\"Returns a quantum circuit for ripple-carry addition. [Cuccaro2004]_\n\n Requires two carry qubit (input and output). The result is returned in\n addend1.\n\n .. [Cuccaro2004]\n A new quantum ripple-carry addition circuit, Steven A. Cuccaro,\n Thomas G. Draper, Samuel A. Kutin, David Petrie Moulton\n arXiv:quant-ph/0410184 (2004)\n \"\"\"\n\n if len(addend0) != len(addend1):\n raise ValueError(\"Number of addend qubits must be equal\")\n\n if len(carry) != 2:\n raise ValueError(\"Expected 2 carry qubits\")\n\n def _maj(qubits: Qubits) -> Circuit:\n q0, q1, q2 = qubits\n circ = Circuit()\n circ += CNot(q2, q1)\n circ += CNot(q2, q0)\n circ += CCNot(q0, q1, q2)\n return circ\n\n def _uma(qubits: Qubits) -> Circuit:\n q0, q1, q2 = qubits\n circ = Circuit()\n circ += CCNot(q0, q1, q2)\n circ += CNot(q2, q0)\n circ += CNot(q0, q1)\n return circ\n\n qubits = (\n [carry[0]]\n + list(chain.from_iterable(zip(reversed(addend1), reversed(addend0))))\n + [carry[1]]\n )\n\n circ = Circuit()\n\n for n in range(0, len(qubits) - 3, 2):\n circ += _maj(qubits[n : n + 3])\n\n circ += CNot(qubits[-2], qubits[-1])\n\n for n in reversed(range(0, len(qubits) - 3, 2)):\n circ += _uma(qubits[n : n + 3])\n\n return circ\n\n\ndef ghz_circuit(qubits: Qubits) -> Circuit:\n \"\"\"Returns a circuit that prepares a multi-qubit Bell state from the zero\n state.\n \"\"\"\n circ = Circuit()\n\n circ += H(qubits[0])\n for q0 in range(0, len(qubits) - 1):\n circ += CNot(qubits[q0], qubits[q0 + 1])\n\n return circ\n\n\ndef graph_circuit_params(\n topology: nx.Graph, steps: int, init_bias: float = 0.0, init_scale: float = 0.01\n) -> Sequence[float]:\n \"\"\"Return a set of initial parameters for graph_circuit()\"\"\"\n N = len(topology.nodes())\n K = len(topology.edges())\n total = N + N * 2 * (steps + 1) + K * steps\n params = np.random.normal(loc=init_bias, scale=init_scale, size=[total])\n\n return tuple(params)\n\n\ndef graph_circuit(\n topology: nx.Graph,\n steps: int,\n params: Sequence[float],\n) -> Circuit:\n \"\"\"\n Create a multilayer parameterized circuit given a graph of connected\n qubits.\n\n We alternate between applying a sublayer of arbitrary 1-qubit gates to all\n qubits, and a sublayer of ZZ gates between all connected qubits.\n\n In practice the pattern is ZPow, XPow, ZPow, (ZZ, XPow, ZPow )*, where ZPow are\n 1-qubit Z rotations, and XPow and 1-qubits X rotations. Since a Z rotation\n commutes across a ZZ, we only need one Z sublayer per layer.\n\n Our fundamental 2-qubit interaction is the Ising like ZZ gate. We could\n apply a more general gate, such as the universal Canonical gate. But ZZ\n gates commute with each other, whereas other choice of gate would not,\n which would necessitate specifying the order of all 2-qubit gates within\n the layer.\n \"\"\"\n\n def tx_layer(topology: nx.Graph, layer_params: Sequence[float]) -> Circuit:\n circ = Circuit()\n for p, q0 in zip(layer_params, topology.nodes()):\n circ += XPow(p, q0)\n return circ\n\n def tz_layer(topology: nx.Graph, layer_params: Sequence[float]) -> Circuit:\n circ = Circuit()\n for p, q0 in zip(layer_params, topology.nodes()):\n circ += ZPow(p, q0)\n return circ\n\n def zz_layer(topology: nx.Graph, layer_params: Sequence[float]) -> Circuit:\n circ = Circuit()\n for p, (q0, q1) in zip(layer_params, topology.edges()):\n circ += ZZ(p, q0, q1)\n return circ\n\n N = len(topology.nodes())\n K = len(topology.edges())\n\n circ = Circuit()\n\n n = 0\n circ += tz_layer(topology, params[n : n + N])\n n += N\n circ += tx_layer(topology, params[n : n + N])\n n += N\n circ += tz_layer(topology, params[n : n + N])\n n += N\n\n for _ in range(steps):\n circ += zz_layer(topology, params[n : n + K])\n n += K\n circ += tx_layer(topology, params[n : n + N])\n n += N\n circ += tz_layer(topology, params[n : n + N])\n n += N\n\n return circ\n\n\ndef graph_state_circuit(topology: nx.Graph) -> Circuit:\n \"\"\"\n Return a circuit to create a graph state, given a\n particular graph topology.\n\n Refs:\n - [Wikipedia: Graph State](https://en.wikipedia.org/wiki/Graph_state)\n \"\"\"\n circ = Circuit()\n\n for q in topology.nodes:\n circ += H(q)\n\n for q0, q1 in topology.edges:\n circ += CZ(q0, q1)\n\n return circ\n\n\n# Fin\n"
] | [
[
"numpy.random.normal"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hazevedosa/human-trust-transfer | [
"eaf96f3a4410d011af6557eb6c03560372fd2959"
] | [
"code/BidirectionalTrustModel.py"
] | [
"# imports\nimport torch\nfrom torch.autograd import Variable\nfrom torch import nn\nfrom torch.nn import Parameter\n\nimport numpy as np\nfrom numpy.linalg import norm\n\nimport scipy.io as sio\n\nimport pickle\n\nusecuda = True\nusecuda = usecuda and torch.cuda.is_available()\n\ndtype = torch.FloatTensor\n\nif usecuda:\n dtype = torch.cuda.FloatTensor\n\nclass BidirectionalTrustModel(torch.nn.Module):\n\n # Init Method (define parameters)\n def __init__(\n self, \n modelname, \n inpsize, \n obsseqlen,\n taskrepsize,\n capabilityRepresentationSize\n ):\n super(BidirectionalTrustModel, self).__init__()\n\n\n self.modelname = modelname # modelname\n\n self.capabilityRepresentationSize = capabilityRepresentationSize # how many capabilities are represented\n self.capabilityEdges = Variable(dtype(np.ones((self.capabilityRepresentationSize,2)) * [0.0, 1.0]), requires_grad=False) # initialized as zeros and ones\n\n self.discretizationBins = 10 # how many bins in each dimension\n self.updateProbabilityDistribution() # probability distribution tensor\n\n\n self.betas = Parameter(dtype(20.0 * np.random.rand( self.capabilityRepresentationSize ))) # parameters to be optimized\n self.zetas = Parameter(dtype(np.random.rand( self.capabilityRepresentationSize ))) # parameters to be optimized\n # self.zetas = dtype(np.ones( self.capabilityRepresentationSize )) # or only ones\n\n self.optimizedCapabilitiesMatrix = Parameter(dtype(np.random.rand(1, 12))) # parameters to be optimized\n\n self.counter = 0\n\n\n\n # Forward Method (model process)\n def forward(self, inptasksobs, inptasksperf, inptaskspred, num_obs_tasks, tasksobsids, taskspredids, \\\n obs_task_sens_cap_seq, pred_task_sens_cap, obs_task_proc_cap_seq, pred_task_proc_cap):\n\n # parameters\n\n tasksPerObservationSequence = inptasksobs.shape[0] # 3 for our dataset // 2 for Soh's\n observationSequencesNumber = inptasksobs.shape[1] # 49 or 63 or N for our dataset // 192 or 186 for Soh's\n trustPredictionsNumber = 1 # adequate to the dataset format... // (both)\n predictedTrust = Variable(dtype(np.zeros((observationSequencesNumber, trustPredictionsNumber))), requires_grad=False) \n # (49, 1) for our dataset // (both)\n\n\n # for each (of the 49 * 3) observations sequence prior to trust predictions\n for i in range(observationSequencesNumber):\n \n # re-initialize the capability edges\n self.capabilityEdges = Variable(dtype(np.ones((self.capabilityRepresentationSize,2)) * [0.0, 1.0]), requires_grad=False)\n self.updateProbabilityDistribution()\n\n\n ## Capabilities estimation loop\n # checks each task on the observation sequence\n for j in range(tasksPerObservationSequence):\n self.capabilityUpdate(inptasksobs[j,i,:], inptasksperf[j,i,:], tasksobsids[j,i,0], \\\n obs_task_sens_cap_seq[j, i], obs_task_proc_cap_seq[j, i])\n # difficulties_obs[j, i, 0])\n\n\n ## Trust computation loop\n # computes trust for each input task... But in our dataset we consider only 1\n for j in range(trustPredictionsNumber):\n predictedTrust[i, j] = self.computeTrust(taskspredids[i, 0], \\\n pred_task_sens_cap[i, 0], pred_task_proc_cap[i, 0])\n # difficulties_pred[i, 0])\n\n\n trust = predictedTrust\n\n return dtype(trust)\n\n\n\n # Auxiliary Methods\n def capabilityUpdate(self, observedTask, observedTaskPerformance, observedTaskID,\n observedTaskSensingCap, observedTaskProcessingCap):\n\n observedCapability = dtype((observedTaskSensingCap, observedTaskProcessingCap))\n\n taskIsNonZero, taskSuccess = self.getSuccessOrFailBools(observedTaskPerformance)\n\n capabilityEdgesChanged = False\n\n if taskIsNonZero:\n if taskSuccess:\n for i in range(self.capabilityRepresentationSize):\n if observedCapability[i] > self.capabilityEdges[i, 1]:\n self.capabilityEdges[i, 1] = observedCapability[i]\n capabilityEdgesChanged = True\n elif observedCapability[i] > self.capabilityEdges[i, 0]:\n self.capabilityEdges[i, 0] = observedCapability[i]\n capabilityEdgesChanged = True\n\n else:\n for i in range(self.capabilityRepresentationSize):\n if observedCapability[i] < self.capabilityEdges[i, 0]:\n self.capabilityEdges[i, 0] = observedCapability[i]\n capabilityEdgesChanged = True\n elif observedCapability[i] < self.capabilityEdges[i, 1]:\n self.capabilityEdges[i, 1] = observedCapability[i]\n capabilityEdgesChanged = True\n\n for i in range(self.capabilityRepresentationSize):\n if self.capabilityEdges[i, 0] == self.capabilityEdges[i, 1]:\n if self.capabilityEdges[i, 1] == 0.0:\n self.capabilityEdges[i, 1] = 1 / self.discretizationBins\n else:\n self.capabilityEdges[i, 0] = self.capabilityEdges[i, 1] - 1 / self.discretizationBins\n\n if capabilityEdgesChanged == True:\n self.updateProbabilityDistribution()\n\n return\n\n\n def getSuccessOrFailBools(self, observedTaskPerformance):\n \n if not(observedTaskPerformance[0]) and not(observedTaskPerformance[1]):\n taskIsNonZero = False\n taskSuccess = False\n elif not(observedTaskPerformance[0]) and observedTaskPerformance[1]:\n taskIsNonZero = True\n taskSuccess = True\n elif observedTaskPerformance[0] and not(observedTaskPerformance[1]):\n taskIsNonZero = True\n taskSuccess = False\n else:\n print(\"Error: performance indicators = [1, 1]\")\n raise SystemExit(0)\n\n return taskIsNonZero, taskSuccess\n\n\n def sigm(self, x):\n return 1 / (1 + torch.exp(-x))\n\n def computeTrust(self, inptaskspredID, predictionTaskSensingCap, predictionTaskProcessingCap):\n\n requiredCapability = dtype((predictionTaskSensingCap, predictionTaskProcessingCap))\n\n trust = 0.0\n\n if self.capabilityRepresentationSize == 1:\n for j in range(self.discretizationBins):\n stepInDim_j = (j + 0.5) / self.discretizationBins\n trust = trust + self.trustGivenCapability([stepInDim_j], requiredCapability) * self.probabilityDistribution[j]\n\n elif self.capabilityRepresentationSize == 2:\n for k in range(self.discretizationBins):\n stepInDim_k = (k + 0.5) / self.discretizationBins\n for j in range(self.discretizationBins):\n stepInDim_j = (j + 0.5) / self.discretizationBins\n trust = trust + self.trustGivenCapability([stepInDim_j, stepInDim_k], \n requiredCapability) * self.probabilityDistribution[j, k]\n\n elif self.capabilityRepresentationSize == 3:\n for l in range(self.discretizationBins):\n stepInDim_l = (l + 0.5) / self.discretizationBins\n for k in range(self.discretizationBins):\n stepInDim_k = (k + 0.5) / self.discretizationBins\n for j in range(self.discretizationBins):\n stepInDim_j = (j + 0.5) / self.discretizationBins\n trust = trust + self.trustGivenCapability([stepInDim_j, stepInDim_k, stepInDim_l], \n requiredCapability) * self.probabilityDistribution[j, k, l]\n\n # print(\"capEdges: \", self.capabilityEdges)\n # print(\"reqCap: \", requiredCapability)\n # print(\"Trust: \", trust)\n # print(\"------\")\n\n return trust\n\n\n def trustGivenCapability(self, capability, requiredCapability):\n\n trust = 1.0\n for i in range(self.capabilityRepresentationSize):\n\n p_i = self.betas[i] * (requiredCapability[i] - capability[i])\n d_i = ( 1 + torch.exp(p_i) ) ** ( - self.zetas[i] * self.zetas[i] )\n\n trust = trust * d_i\n\n return trust\n\n\n def updateProbabilityDistribution(self):\n\n # Tuple to start the distribution tensor\n probabilityStarter = tuple(self.discretizationBins * np.ones((self.capabilityRepresentationSize), dtype = int))\n\n # Distribution tensors\n probabilityDistribution = torch.ones(probabilityStarter, dtype = torch.int8)\n # zeroProbability = torch.ones(probabilityStarter, dtype = torch.int8)\n\n\n # hardcoded solution: for 1 dim\n if self.capabilityRepresentationSize == 1:\n for j in range(self.discretizationBins):\n step = (j + 0.5) / self.discretizationBins\n if step < self.capabilityEdges[0, 0]:\n probabilityDistribution[j] = 0\n if step > self.capabilityEdges[0, 1]:\n probabilityDistribution[j] = 0\n \n probabilityDistribution = probabilityDistribution.float()\n if usecuda:\n probabilityDistribution = probabilityDistribution.cuda()\n probabilityDistribution = dtype(probabilityDistribution)\n probabilityDistribution = probabilityDistribution / torch.sum(probabilityDistribution)\n\n # hardcoded solution: for 2 dim\n if self.capabilityRepresentationSize == 2:\n\n for j in range(self.discretizationBins):\n step = (j + 0.5) / self.discretizationBins\n\n if step < self.capabilityEdges[0, 0]:\n probabilityDistribution[j,:] = 0\n if step > self.capabilityEdges[0, 1]:\n probabilityDistribution[j,:] = 0\n if step < self.capabilityEdges[1, 0]:\n probabilityDistribution[:,j] = 0\n if step > self.capabilityEdges[1, 1]:\n probabilityDistribution[:,j] = 0\n \n probabilityDistribution = probabilityDistribution.float()\n if usecuda:\n probabilityDistribution = probabilityDistribution.cuda()\n probabilityDistribution = dtype(probabilityDistribution)\n probabilityDistribution = probabilityDistribution / torch.sum(probabilityDistribution)\n\n self.probabilityDistribution = probabilityDistribution\n return"
] | [
[
"torch.ones",
"torch.sum",
"numpy.ones",
"torch.exp",
"numpy.random.rand",
"torch.cuda.is_available",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JonWiggins/pandas | [
"951239398789b077689371d30906cab5b9248f4e"
] | [
"pandas/tests/extension/test_sparse.py"
] | [
"\"\"\"\nThis file contains a minimal set of tests for compliance with the extension\narray interface test suite, and should contain no other tests.\nThe test suite for the full functionality of the array is located in\n`pandas/tests/arrays/`.\n\nThe tests in this file are inherited from the BaseExtensionTests, and only\nminimal tweaks should be applied to get the tests passing (by overwriting a\nparent method).\n\nAdditional tests should either be added to one of the BaseExtensionTests\nclasses (if they are relevant for the extension interface for all dtypes), or\nbe added to the array-specific tests in `pandas/tests/arrays/`.\n\n\"\"\"\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import np_version_under1p20\nfrom pandas.errors import PerformanceWarning\n\nfrom pandas.core.dtypes.common import is_object_dtype\n\nimport pandas as pd\nfrom pandas import SparseDtype\nimport pandas._testing as tm\nfrom pandas.arrays import SparseArray\nfrom pandas.tests.extension import base\n\n\ndef make_data(fill_value):\n if np.isnan(fill_value):\n data = np.random.uniform(size=100)\n else:\n data = np.random.randint(1, 100, size=100)\n if data[0] == data[1]:\n data[0] += 1\n\n data[2::3] = fill_value\n return data\n\n\[email protected]\ndef dtype():\n return SparseDtype()\n\n\[email protected](params=[0, np.nan])\ndef data(request):\n \"\"\"Length-100 PeriodArray for semantics test.\"\"\"\n res = SparseArray(make_data(request.param), fill_value=request.param)\n return res\n\n\[email protected]\ndef data_for_twos(request):\n return SparseArray(np.ones(100) * 2)\n\n\[email protected](params=[0, np.nan])\ndef data_missing(request):\n \"\"\"Length 2 array with [NA, Valid]\"\"\"\n return SparseArray([np.nan, 1], fill_value=request.param)\n\n\[email protected](params=[0, np.nan])\ndef data_repeated(request):\n \"\"\"Return different versions of data for count times\"\"\"\n\n def gen(count):\n for _ in range(count):\n yield SparseArray(make_data(request.param), fill_value=request.param)\n\n yield gen\n\n\[email protected](params=[0, np.nan])\ndef data_for_sorting(request):\n return SparseArray([2, 3, 1], fill_value=request.param)\n\n\[email protected](params=[0, np.nan])\ndef data_missing_for_sorting(request):\n return SparseArray([2, np.nan, 1], fill_value=request.param)\n\n\[email protected]\ndef na_value():\n return np.nan\n\n\[email protected]\ndef na_cmp():\n return lambda left, right: pd.isna(left) and pd.isna(right)\n\n\[email protected](params=[0, np.nan])\ndef data_for_grouping(request):\n return SparseArray([1, 1, np.nan, np.nan, 2, 2, 1, 3], fill_value=request.param)\n\n\nclass BaseSparseTests:\n def _check_unsupported(self, data):\n if data.dtype == SparseDtype(int, 0):\n pytest.skip(\"Can't store nan in int array.\")\n\n @pytest.mark.xfail(reason=\"SparseArray does not support setitem\")\n def test_ravel(self, data):\n super().test_ravel(data)\n\n\nclass TestDtype(BaseSparseTests, base.BaseDtypeTests):\n def test_array_type_with_arg(self, data, dtype):\n assert dtype.construct_array_type() is SparseArray\n\n\nclass TestInterface(BaseSparseTests, base.BaseInterfaceTests):\n def test_copy(self, data):\n # __setitem__ does not work, so we only have a smoke-test\n data.copy()\n\n def test_view(self, data):\n # __setitem__ does not work, so we only have a smoke-test\n data.view()\n\n\nclass TestConstructors(BaseSparseTests, base.BaseConstructorsTests):\n pass\n\n\nclass TestReshaping(BaseSparseTests, base.BaseReshapingTests):\n def test_concat_mixed_dtypes(self, data):\n # https://github.com/pandas-dev/pandas/issues/20762\n # This should be the same, aside from concat([sparse, float])\n df1 = pd.DataFrame({\"A\": data[:3]})\n df2 = pd.DataFrame({\"A\": [1, 2, 3]})\n df3 = pd.DataFrame({\"A\": [\"a\", \"b\", \"c\"]}).astype(\"category\")\n dfs = [df1, df2, df3]\n\n # dataframes\n result = pd.concat(dfs)\n expected = pd.concat(\n [x.apply(lambda s: np.asarray(s).astype(object)) for x in dfs]\n )\n self.assert_frame_equal(result, expected)\n\n def test_concat_columns(self, data, na_value):\n self._check_unsupported(data)\n super().test_concat_columns(data, na_value)\n\n def test_concat_extension_arrays_copy_false(self, data, na_value):\n self._check_unsupported(data)\n super().test_concat_extension_arrays_copy_false(data, na_value)\n\n def test_align(self, data, na_value):\n self._check_unsupported(data)\n super().test_align(data, na_value)\n\n def test_align_frame(self, data, na_value):\n self._check_unsupported(data)\n super().test_align_frame(data, na_value)\n\n def test_align_series_frame(self, data, na_value):\n self._check_unsupported(data)\n super().test_align_series_frame(data, na_value)\n\n def test_merge(self, data, na_value):\n self._check_unsupported(data)\n super().test_merge(data, na_value)\n\n @pytest.mark.xfail(reason=\"SparseArray does not support setitem\")\n def test_transpose(self, data):\n super().test_transpose(data)\n\n\nclass TestGetitem(BaseSparseTests, base.BaseGetitemTests):\n def test_get(self, data):\n ser = pd.Series(data, index=[2 * i for i in range(len(data))])\n if np.isnan(ser.values.fill_value):\n assert np.isnan(ser.get(4)) and np.isnan(ser.iloc[2])\n else:\n assert ser.get(4) == ser.iloc[2]\n assert ser.get(2) == ser.iloc[1]\n\n def test_reindex(self, data, na_value):\n self._check_unsupported(data)\n super().test_reindex(data, na_value)\n\n\n# Skipping TestSetitem, since we don't implement it.\n\n\nclass TestMissing(BaseSparseTests, base.BaseMissingTests):\n def test_isna(self, data_missing):\n sarr = SparseArray(data_missing)\n expected_dtype = SparseDtype(bool, pd.isna(data_missing.dtype.fill_value))\n expected = SparseArray([True, False], dtype=expected_dtype)\n result = sarr.isna()\n tm.assert_sp_array_equal(result, expected)\n\n # test isna for arr without na\n sarr = sarr.fillna(0)\n expected_dtype = SparseDtype(bool, pd.isna(data_missing.dtype.fill_value))\n expected = SparseArray([False, False], fill_value=False, dtype=expected_dtype)\n self.assert_equal(sarr.isna(), expected)\n\n def test_fillna_limit_pad(self, data_missing):\n with tm.assert_produces_warning(PerformanceWarning):\n super().test_fillna_limit_pad(data_missing)\n\n def test_fillna_limit_backfill(self, data_missing):\n with tm.assert_produces_warning(PerformanceWarning):\n super().test_fillna_limit_backfill(data_missing)\n\n def test_fillna_no_op_returns_copy(self, data, request):\n if np.isnan(data.fill_value):\n request.node.add_marker(\n pytest.mark.xfail(reason=\"returns array with different fill value\")\n )\n with tm.assert_produces_warning(PerformanceWarning):\n super().test_fillna_no_op_returns_copy(data)\n\n def test_fillna_series_method(self, data_missing):\n with tm.assert_produces_warning(PerformanceWarning):\n super().test_fillna_limit_backfill(data_missing)\n\n @pytest.mark.skip(reason=\"Unsupported\")\n def test_fillna_series(self):\n # this one looks doable.\n pass\n\n def test_fillna_frame(self, data_missing):\n # Have to override to specify that fill_value will change.\n fill_value = data_missing[1]\n\n result = pd.DataFrame({\"A\": data_missing, \"B\": [1, 2]}).fillna(fill_value)\n\n if pd.isna(data_missing.fill_value):\n dtype = SparseDtype(data_missing.dtype, fill_value)\n else:\n dtype = data_missing.dtype\n\n expected = pd.DataFrame(\n {\n \"A\": data_missing._from_sequence([fill_value, fill_value], dtype=dtype),\n \"B\": [1, 2],\n }\n )\n\n self.assert_frame_equal(result, expected)\n\n\nclass TestMethods(BaseSparseTests, base.BaseMethodsTests):\n def test_combine_le(self, data_repeated):\n # We return a Series[SparseArray].__le__ returns a\n # Series[Sparse[bool]]\n # rather than Series[bool]\n orig_data1, orig_data2 = data_repeated(2)\n s1 = pd.Series(orig_data1)\n s2 = pd.Series(orig_data2)\n result = s1.combine(s2, lambda x1, x2: x1 <= x2)\n expected = pd.Series(\n SparseArray(\n [a <= b for (a, b) in zip(list(orig_data1), list(orig_data2))],\n fill_value=False,\n )\n )\n self.assert_series_equal(result, expected)\n\n val = s1.iloc[0]\n result = s1.combine(val, lambda x1, x2: x1 <= x2)\n expected = pd.Series(\n SparseArray([a <= val for a in list(orig_data1)], fill_value=False)\n )\n self.assert_series_equal(result, expected)\n\n def test_fillna_copy_frame(self, data_missing):\n arr = data_missing.take([1, 1])\n df = pd.DataFrame({\"A\": arr}, copy=False)\n\n filled_val = df.iloc[0, 0]\n result = df.fillna(filled_val)\n\n if hasattr(df._mgr, \"blocks\"):\n assert df.values.base is not result.values.base\n assert df.A._values.to_dense() is arr.to_dense()\n\n def test_fillna_copy_series(self, data_missing):\n arr = data_missing.take([1, 1])\n ser = pd.Series(arr)\n\n filled_val = ser[0]\n result = ser.fillna(filled_val)\n\n assert ser._values is not result._values\n assert ser._values.to_dense() is arr.to_dense()\n\n @pytest.mark.skip(reason=\"Not Applicable\")\n def test_fillna_length_mismatch(self, data_missing):\n pass\n\n def test_where_series(self, data, na_value):\n assert data[0] != data[1]\n cls = type(data)\n a, b = data[:2]\n\n ser = pd.Series(cls._from_sequence([a, a, b, b], dtype=data.dtype))\n\n cond = np.array([True, True, False, False])\n result = ser.where(cond)\n\n new_dtype = SparseDtype(\"float\", 0.0)\n expected = pd.Series(\n cls._from_sequence([a, a, na_value, na_value], dtype=new_dtype)\n )\n self.assert_series_equal(result, expected)\n\n other = cls._from_sequence([a, b, a, b], dtype=data.dtype)\n cond = np.array([True, False, True, True])\n result = ser.where(cond, other)\n expected = pd.Series(cls._from_sequence([a, b, b, b], dtype=data.dtype))\n self.assert_series_equal(result, expected)\n\n def test_combine_first(self, data, request):\n if data.dtype.subtype == \"int\":\n # Right now this is upcasted to float, just like combine_first\n # for Series[int]\n mark = pytest.mark.xfail(\n reason=\"TODO(SparseArray.__setitem__) will preserve dtype.\"\n )\n request.node.add_marker(mark)\n super().test_combine_first(data)\n\n def test_searchsorted(self, data_for_sorting, as_series):\n with tm.assert_produces_warning(PerformanceWarning):\n super().test_searchsorted(data_for_sorting, as_series)\n\n def test_shift_0_periods(self, data):\n # GH#33856 shifting with periods=0 should return a copy, not same obj\n result = data.shift(0)\n\n data._sparse_values[0] = data._sparse_values[1]\n assert result._sparse_values[0] != result._sparse_values[1]\n\n @pytest.mark.parametrize(\"method\", [\"argmax\", \"argmin\"])\n def test_argmin_argmax_all_na(self, method, data, na_value):\n # overriding because Sparse[int64, 0] cannot handle na_value\n self._check_unsupported(data)\n super().test_argmin_argmax_all_na(method, data, na_value)\n\n @pytest.mark.parametrize(\"box\", [pd.array, pd.Series, pd.DataFrame])\n def test_equals(self, data, na_value, as_series, box):\n self._check_unsupported(data)\n super().test_equals(data, na_value, as_series, box)\n\n\nclass TestCasting(BaseSparseTests, base.BaseCastingTests):\n def test_astype_object_series(self, all_data):\n # Unlike the base class, we do not expect the resulting Block\n # to be ObjectBlock / resulting array to be np.dtype(\"object\")\n ser = pd.Series(all_data, name=\"A\")\n result = ser.astype(object)\n assert is_object_dtype(result.dtype)\n assert is_object_dtype(result._mgr.array.dtype)\n\n def test_astype_object_frame(self, all_data):\n # Unlike the base class, we do not expect the resulting Block\n # to be ObjectBlock / resulting array to be np.dtype(\"object\")\n df = pd.DataFrame({\"A\": all_data})\n\n result = df.astype(object)\n assert is_object_dtype(result._mgr.arrays[0].dtype)\n\n # earlier numpy raises TypeError on e.g. np.dtype(np.int64) == \"Int64\"\n # instead of returning False\n if not np_version_under1p20:\n # check that we can compare the dtypes\n comp = result.dtypes == df.dtypes\n assert not comp.any()\n\n def test_astype_str(self, data):\n result = pd.Series(data[:5]).astype(str)\n expected_dtype = SparseDtype(str, str(data.fill_value))\n expected = pd.Series([str(x) for x in data[:5]], dtype=expected_dtype)\n self.assert_series_equal(result, expected)\n\n @pytest.mark.xfail(raises=TypeError, reason=\"no sparse StringDtype\")\n def test_astype_string(self, data):\n super().test_astype_string(data)\n\n\nclass TestArithmeticOps(BaseSparseTests, base.BaseArithmeticOpsTests):\n series_scalar_exc = None\n frame_scalar_exc = None\n divmod_exc = None\n series_array_exc = None\n\n def _skip_if_different_combine(self, data):\n if data.fill_value == 0:\n # arith ops call on dtype.fill_value so that the sparsity\n # is maintained. Combine can't be called on a dtype in\n # general, so we can't make the expected. This is tested elsewhere\n raise pytest.skip(\"Incorrected expected from Series.combine\")\n\n def test_arith_series_with_scalar(self, data, all_arithmetic_operators):\n self._skip_if_different_combine(data)\n super().test_arith_series_with_scalar(data, all_arithmetic_operators)\n\n def test_arith_series_with_array(self, data, all_arithmetic_operators):\n self._skip_if_different_combine(data)\n super().test_arith_series_with_array(data, all_arithmetic_operators)\n\n def test_arith_frame_with_scalar(self, data, all_arithmetic_operators, request):\n if data.dtype.fill_value != 0:\n pass\n elif all_arithmetic_operators.strip(\"_\") not in [\n \"mul\",\n \"rmul\",\n \"floordiv\",\n \"rfloordiv\",\n \"pow\",\n \"mod\",\n \"rmod\",\n ]:\n mark = pytest.mark.xfail(reason=\"result dtype.fill_value mismatch\")\n request.node.add_marker(mark)\n super().test_arith_frame_with_scalar(data, all_arithmetic_operators)\n\n def _check_divmod_op(self, ser, op, other, exc=NotImplementedError):\n # We implement divmod\n super()._check_divmod_op(ser, op, other, exc=None)\n\n\nclass TestComparisonOps(BaseSparseTests, base.BaseComparisonOpsTests):\n def _compare_other(self, s, data, comparison_op, other):\n op = comparison_op\n\n # array\n result = pd.Series(op(data, other))\n # hard to test the fill value, since we don't know what expected\n # is in general.\n # Rely on tests in `tests/sparse` to validate that.\n assert isinstance(result.dtype, SparseDtype)\n assert result.dtype.subtype == np.dtype(\"bool\")\n\n with np.errstate(all=\"ignore\"):\n expected = pd.Series(\n SparseArray(\n op(np.asarray(data), np.asarray(other)),\n fill_value=result.values.fill_value,\n )\n )\n\n tm.assert_series_equal(result, expected)\n\n # series\n ser = pd.Series(data)\n result = op(ser, other)\n tm.assert_series_equal(result, expected)\n\n\nclass TestPrinting(BaseSparseTests, base.BasePrintingTests):\n @pytest.mark.xfail(reason=\"Different repr\")\n def test_array_repr(self, data, size):\n super().test_array_repr(data, size)\n\n\nclass TestParsing(BaseSparseTests, base.BaseParsingTests):\n @pytest.mark.parametrize(\"engine\", [\"c\", \"python\"])\n def test_EA_types(self, engine, data):\n expected_msg = r\".*must implement _from_sequence_of_strings.*\"\n with pytest.raises(NotImplementedError, match=expected_msg):\n super().test_EA_types(engine, data)\n"
] | [
[
"numpy.array",
"pandas.concat",
"pandas._testing.assert_produces_warning",
"pandas._testing.assert_sp_array_equal",
"pandas.Series",
"pandas.arrays.SparseArray",
"numpy.isnan",
"numpy.asarray",
"pandas.DataFrame",
"numpy.ones",
"pandas._testing.assert_series_equal",
"numpy.dtype",
"pandas.core.dtypes.common.is_object_dtype",
"numpy.errstate",
"numpy.random.uniform",
"pandas.isna",
"pandas.SparseDtype",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"0.24",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
online-ml/creme | [
"60872844e6052b5ef20e4075aea30f9031377136",
"60872844e6052b5ef20e4075aea30f9031377136",
"60872844e6052b5ef20e4075aea30f9031377136"
] | [
"river/drift/kswin.py",
"river/facto/fm.py",
"river/optim/initializers.py"
] | [
"import collections\nimport itertools\nimport random\nimport typing\n\nfrom scipy import stats\n\nfrom river.base import DriftDetector\n\n\nclass KSWIN(DriftDetector):\n r\"\"\"Kolmogorov-Smirnov Windowing method for concept drift detection.\n\n Parameters\n ----------\n alpha\n Probability for the test statistic of the Kolmogorov-Smirnov-Test. The alpha parameter is\n very sensitive, therefore should be set below 0.01.\n window_size\n Size of the sliding window.\n stat_size\n Size of the statistic window.\n window\n Already collected data to avoid cold start.\n seed\n Random seed for reproducibility.\n\n Notes\n -----\n KSWIN (Kolmogorov-Smirnov Windowing) is a concept change detection method based\n on the Kolmogorov-Smirnov (KS) statistical test. KS-test is a statistical test with\n no assumption of underlying data distribution. KSWIN can monitor data or performance\n distributions. Note that the detector accepts one dimensional input as array.\n\n KSWIN maintains a sliding window $\\Psi$ of fixed size $n$ (window_size). The\n last $r$ (stat_size) samples of $\\Psi$ are assumed to represent the last\n concept considered as $R$. From the first $n-r$ samples of $\\Psi$,\n $r$ samples are uniformly drawn, representing an approximated last concept $W$.\n\n The KS-test is performed on the windows $R$ and $W$ of the same size. KS\n -test compares the distance of the empirical cumulative data distribution $dist(R,W)$.\n\n A concept drift is detected by KSWIN if:\n\n $$\n dist(R,W) > \\sqrt{-\\frac{ln\\alpha}{r}}\n $$\n\n The difference in empirical data distributions between the windows $R$ and $W$ is too large\n since $R$ and $W$ come from the same distribution.\n\n Examples\n --------\n >>> import random\n >>> from river import drift\n\n >>> rng = random.Random(12345)\n >>> kswin = drift.KSWIN(alpha=0.0001, seed=42)\n\n >>> # Simulate a data stream composed by two data distributions\n >>> data_stream = rng.choices([0, 1], k=1000) + rng.choices(range(4, 8), k=1000)\n\n >>> # Update drift detector and verify if change is detected\n >>> for i, val in enumerate(data_stream):\n ... in_drift, _ = kswin.update(val)\n ... if in_drift:\n ... print(f\"Change detected at index {i}, input value: {val}\")\n ... kswin.reset() # Good practice\n Change detected at index 1016, input value: 6\n\n References\n ----------\n [^1]: Christoph Raab, Moritz Heusinger, Frank-Michael Schleif, Reactive Soft Prototype Computing for\n Concept Drift Streams, Neurocomputing, 2020,\n\n \"\"\"\n\n def __init__(\n self,\n alpha: float = 0.005,\n window_size: int = 100,\n stat_size: int = 30,\n seed: int = None,\n window: typing.Iterable = None,\n ):\n super().__init__()\n self.alpha = alpha\n self.window_size = window_size\n self.stat_size = stat_size\n self.seed = seed\n\n self.p_value = 0\n self.n = 0\n if self.alpha < 0 or self.alpha > 1:\n raise ValueError(\"Alpha must be between 0 and 1.\")\n\n if self.window_size < 0:\n raise ValueError(\"window_size must be greater than 0.\")\n\n if self.window_size < self.stat_size:\n raise ValueError(\"stat_size must be smaller than window_size.\")\n\n if window is None:\n self.window = collections.deque(maxlen=self.window_size)\n else:\n self.window = collections.deque(window, maxlen=self.window_size)\n\n self._rng = random.Random(self.seed)\n\n def update(self, value):\n \"\"\"Update the change detector with a single data point.\n\n Adds an element on top of the sliding window and removes the oldest one from the window.\n Afterwards, the KS-test is performed.\n\n Parameters\n ----------\n value\n New data sample the sliding window should add.\n\n Returns\n -------\n A tuple (drift, warning) where its elements indicate if a drift or a warning is detected.\n\n \"\"\"\n self.n += 1\n\n self.window.append(value)\n if len(self.window) >= self.window_size:\n rnd_window = [\n self.window[r]\n for r in self._rng.sample(\n range(self.window_size - self.stat_size), self.stat_size\n )\n ]\n most_recent = list(\n itertools.islice(\n self.window, self.window_size - self.stat_size, self.window_size\n )\n )\n\n st, self.p_value = stats.ks_2samp(rnd_window, most_recent)\n\n if self.p_value <= self.alpha and st > 0.1:\n self._in_concept_change = True\n self.window = collections.deque(most_recent, maxlen=self.window_size)\n else:\n self._in_concept_change = False\n else: # Not enough samples in the sliding window for a valid test\n self._in_concept_change = False\n\n return self._in_concept_change, False\n\n @classmethod\n def _unit_test_params(cls):\n yield {\"seed\": 1}\n",
"import collections\nimport functools\nimport itertools\nimport typing\n\nimport numpy as np\n\nfrom river import base, optim, utils\n\nfrom .base import BaseFM\n\n__all__ = [\"FMClassifier\", \"FMRegressor\"]\n\n\nclass FM(BaseFM):\n \"\"\"Factorization machine base class.\"\"\"\n\n def __init__(\n self,\n n_factors,\n weight_optimizer,\n latent_optimizer,\n loss,\n sample_normalization,\n l1_weight,\n l2_weight,\n l1_latent,\n l2_latent,\n intercept,\n intercept_lr,\n weight_initializer,\n latent_initializer,\n clip_gradient,\n seed,\n ):\n super().__init__(\n n_factors=n_factors,\n weight_optimizer=weight_optimizer,\n latent_optimizer=latent_optimizer,\n loss=loss,\n sample_normalization=sample_normalization,\n l1_weight=l1_weight,\n l2_weight=l2_weight,\n l1_latent=l1_latent,\n l2_latent=l2_latent,\n intercept=intercept,\n intercept_lr=intercept_lr,\n weight_initializer=weight_initializer,\n latent_initializer=latent_initializer,\n clip_gradient=clip_gradient,\n seed=seed,\n )\n\n def _init_latents(self):\n random_latents = functools.partial(\n self.latent_initializer, shape=self.n_factors\n )\n return collections.defaultdict(random_latents)\n\n def _interaction_names(self, x):\n return [f\"{j1} - {j2}\" for j1, j2 in itertools.combinations(x.keys(), 2)]\n\n def _interaction_combination_keys(self, x):\n return itertools.combinations(x.keys(), 2)\n\n def _interaction_val(self, x, combination):\n return functools.reduce(lambda x, y: x * y, (x[j] for j in combination))\n\n def _interaction_coefficient(self, combination):\n j1, j2 = combination\n return np.dot(self.latents[j1], self.latents[j2])\n\n def _calculate_weights_gradients(self, x, g_loss):\n\n # For notational convenience\n w, l1, l2, sign = self.weights, self.l1_weight, self.l2_weight, utils.math.sign\n\n return {j: g_loss * xj + l1 * sign(w[j]) + l2 * w[j] for j, xj in x.items()}\n\n def _update_latents(self, x, g_loss):\n\n # For notational convenience\n v, l1, l2, sign = self.latents, self.l1_latent, self.l2_latent, utils.math.sign\n\n # Precompute feature independent sum for time efficiency\n precomputed_sum = {\n f: sum(v[j][f] * xj for j, xj in x.items()) for f in range(self.n_factors)\n }\n\n # Calculate each latent factor gradient before updating any\n gradients = {}\n for j, xj in x.items():\n gradients[j] = {\n f: g_loss * (xj * precomputed_sum[f] - v[j][f] * xj**2)\n + l1 * sign(v[j][f])\n + l2 * v[j][f]\n for f in range(self.n_factors)\n }\n\n # Finally update the latent weights\n for j in x.keys():\n self.latents[j] = self.latent_optimizer.step(w=v[j], g=gradients[j])\n\n\nclass FMRegressor(FM, base.Regressor):\n \"\"\"Factorization Machine for regression.\n\n The model equation is defined as:\n\n $$\\\\hat{y}(x) = w_{0} + \\\\sum_{j=1}^{p} w_{j} x_{j} + \\\\sum_{j=1}^{p} \\\\sum_{j'=j+1}^{p} \\\\langle \\\\mathbf{v}_j, \\\\mathbf{v}_{j'} \\\\rangle x_{j} x_{j'}$$\n\n Where $\\\\mathbf{v}_j$ and $\\\\mathbf{v}_{j'}$ are $j$ and $j'$ latent vectors, respectively.\n\n For more efficiency, this model automatically one-hot encodes strings features considering them\n as categorical variables.\n\n Parameters\n ----------\n n_factors\n Dimensionality of the factorization or number of latent factors.\n weight_optimizer\n The sequential optimizer used for updating the feature weights. Note that\n the intercept is handled separately.\n latent_optimizer\n The sequential optimizer used for updating the latent factors.\n loss\n The loss function to optimize for.\n sample_normalization\n Whether to divide each element of `x` by `x`'s L2-norm.\n l1_weight\n Amount of L1 regularization used to push weights towards 0.\n l2_weight\n Amount of L2 regularization used to push weights towards 0.\n l1_latent\n Amount of L1 regularization used to push latent weights towards 0.\n l2_latent\n Amount of L2 regularization used to push latent weights towards 0.\n intercept\n Initial intercept value.\n intercept_lr\n Learning rate scheduler used for updating the intercept. An instance of\n `optim.schedulers.Constant` is used if a `float` is passed. No intercept will be used\n if this is set to 0.\n weight_initializer\n Weights initialization scheme. Defaults to `optim.initializers.Zeros()`.\n latent_initializer\n Latent factors initialization scheme. Defaults to\n `optim.initializers.Normal(mu=.0, sigma=.1, random_state=self.random_state)`.\n clip_gradient\n Clips the absolute value of each gradient value.\n seed\n Randomization seed used for reproducibility.\n\n Attributes\n ----------\n weights\n The current weights assigned to the features.\n latents\n The current latent weights assigned to the features.\n\n Examples\n --------\n\n >>> from river import facto\n\n >>> dataset = (\n ... ({'user': 'Alice', 'item': 'Superman'}, 8),\n ... ({'user': 'Alice', 'item': 'Terminator'}, 9),\n ... ({'user': 'Alice', 'item': 'Star Wars'}, 8),\n ... ({'user': 'Alice', 'item': 'Notting Hill'}, 2),\n ... ({'user': 'Alice', 'item': 'Harry Potter '}, 5),\n ... ({'user': 'Bob', 'item': 'Superman'}, 8),\n ... ({'user': 'Bob', 'item': 'Terminator'}, 9),\n ... ({'user': 'Bob', 'item': 'Star Wars'}, 8),\n ... ({'user': 'Bob', 'item': 'Notting Hill'}, 2)\n ... )\n\n >>> model = facto.FMRegressor(\n ... n_factors=10,\n ... intercept=5,\n ... seed=42,\n ... )\n\n >>> for x, y in dataset:\n ... _ = model.learn_one(x, y)\n\n >>> model.predict_one({'Bob': 1, 'Harry Potter': 1})\n 5.236504\n\n >>> report = model.debug_one({'Bob': 1, 'Harry Potter': 1})\n\n >>> print(report)\n Name Value Weight Contribution\n Intercept 1.00000 5.23426 5.23426\n Bob - Harry Potter 1.00000 0.00224 0.00224\n Harry Potter 1.00000 0.00000 0.00000\n Bob 1.00000 0.00000 0.00000\n\n References\n ----------\n [^1]: [Rendle, S., 2010, December. Factorization machines. In 2010 IEEE International Conference on Data Mining (pp. 995-1000). IEEE.](https://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf)\n [^2]: [Rendle, S., 2012, May. Factorization Machines with libFM. In ACM Transactions on Intelligent Systems and Technology 3, 3, Article 57, 22 pages.](https://analyticsconsultores.com.mx/wp-content/uploads/2019/03/Factorization-Machines-with-libFM-Steffen-Rendle-University-of-Konstanz2012-.pdf)\n\n \"\"\"\n\n def __init__(\n self,\n n_factors=10,\n weight_optimizer: optim.base.Optimizer = None,\n latent_optimizer: optim.base.Optimizer = None,\n loss: optim.losses.RegressionLoss = None,\n sample_normalization=False,\n l1_weight=0.0,\n l2_weight=0.0,\n l1_latent=0.0,\n l2_latent=0.0,\n intercept=0.0,\n intercept_lr: typing.Union[optim.base.Scheduler, float] = 0.01,\n weight_initializer: optim.initializers.Initializer = None,\n latent_initializer: optim.initializers.Initializer = None,\n clip_gradient=1e12,\n seed: int = None,\n ):\n\n super().__init__(\n n_factors=n_factors,\n weight_optimizer=weight_optimizer,\n latent_optimizer=latent_optimizer,\n loss=optim.losses.Squared() if loss is None else loss,\n sample_normalization=sample_normalization,\n l1_weight=l1_weight,\n l2_weight=l2_weight,\n l1_latent=l1_latent,\n l2_latent=l2_latent,\n intercept=intercept,\n intercept_lr=intercept_lr,\n weight_initializer=weight_initializer,\n latent_initializer=latent_initializer,\n clip_gradient=clip_gradient,\n seed=seed,\n )\n\n def predict_one(self, x):\n x = self._ohe_cat_features(x)\n return self._raw_dot(x)\n\n\nclass FMClassifier(FM, base.Classifier):\n \"\"\"Factorization Machine for binary classification.\n\n The model equation is defined as:\n\n $$\\\\hat{y}(x) = w_{0} + \\\\sum_{j=1}^{p} w_{j} x_{j} + \\\\sum_{j=1}^{p} \\\\sum_{j'=j+1}^{p} \\\\langle \\\\mathbf{v}_j, \\\\mathbf{v}_{j'} \\\\rangle x_{j} x_{j'}$$\n\n Where $\\\\mathbf{v}_j$ and $\\\\mathbf{v}_{j'}$ are $j$ and $j'$ latent vectors, respectively.\n\n For more efficiency, this model automatically one-hot encodes strings features considering them\n as categorical variables.\n\n Parameters\n ----------\n n_factors\n Dimensionality of the factorization or number of latent factors.\n weight_optimizer\n The sequential optimizer used for updating the feature weights. Note that the intercept is\n handled separately.\n latent_optimizer\n The sequential optimizer used for updating the latent factors.\n loss\n The loss function to optimize for.\n sample_normalization\n Whether to divide each element of `x` by `x`'s L2-norm.\n l1_weight\n Amount of L1 regularization used to push weights towards 0.\n l2_weight\n Amount of L2 regularization used to push weights towards 0.\n l1_latent\n Amount of L1 regularization used to push latent weights towards 0.\n l2_latent\n Amount of L2 regularization used to push latent weights towards 0.\n intercept\n Initial intercept value.\n intercept_lr\n Learning rate scheduler used for updating the intercept. An instance of\n `optim.schedulers.Constant` is used if a `float` is passed. No intercept will be used\n if this is set to 0.\n weight_initializer\n Weights initialization scheme. Defaults to `optim.initializers.Zeros()`.\n latent_initializer\n Latent factors initialization scheme. Defaults to\n `optim.initializers.Normal(mu=.0, sigma=.1, random_state=self.random_state)`.\n clip_gradient\n Clips the absolute value of each gradient value.\n seed\n Randomization seed used for reproducibility.\n\n Attributes\n ----------\n weights\n The current weights assigned to the features.\n latents\n The current latent weights assigned to the features.\n\n Examples\n --------\n\n >>> from river import facto\n\n >>> dataset = (\n ... ({'user': 'Alice', 'item': 'Superman'}, True),\n ... ({'user': 'Alice', 'item': 'Terminator'}, True),\n ... ({'user': 'Alice', 'item': 'Star Wars'}, True),\n ... ({'user': 'Alice', 'item': 'Notting Hill'}, False),\n ... ({'user': 'Alice', 'item': 'Harry Potter '}, True),\n ... ({'user': 'Bob', 'item': 'Superman'}, True),\n ... ({'user': 'Bob', 'item': 'Terminator'}, True),\n ... ({'user': 'Bob', 'item': 'Star Wars'}, True),\n ... ({'user': 'Bob', 'item': 'Notting Hill'}, False)\n ... )\n\n >>> model = facto.FMClassifier(\n ... n_factors=10,\n ... seed=42,\n ... )\n\n >>> for x, y in dataset:\n ... _ = model.learn_one(x, y)\n\n >>> model.predict_one({'Bob': 1, 'Harry Potter': 1})\n True\n\n References\n ----------\n [^1]: [Rendle, S., 2010, December. Factorization machines. In 2010 IEEE International Conference on Data Mining (pp. 995-1000). IEEE.](https://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf)\n [^2]: [Rendle, S., 2012, May. Factorization Machines with libFM. In ACM Transactions on Intelligent Systems and Technology 3, 3, Article 57, 22 pages.](https://analyticsconsultores.com.mx/wp-content/uploads/2019/03/Factorization-Machines-with-libFM-Steffen-Rendle-University-of-Konstanz2012-.pdf)\n\n \"\"\"\n\n def __init__(\n self,\n n_factors=10,\n weight_optimizer: optim.base.Optimizer = None,\n latent_optimizer: optim.base.Optimizer = None,\n loss: optim.losses.BinaryLoss = None,\n sample_normalization=False,\n l1_weight=0.0,\n l2_weight=0.0,\n l1_latent=0.0,\n l2_latent=0.0,\n intercept=0.0,\n intercept_lr: typing.Union[optim.base.Scheduler, float] = 0.01,\n weight_initializer: optim.initializers.Initializer = None,\n latent_initializer: optim.initializers.Initializer = None,\n clip_gradient=1e12,\n seed: int = None,\n ):\n\n super().__init__(\n n_factors=n_factors,\n weight_optimizer=weight_optimizer,\n latent_optimizer=latent_optimizer,\n loss=optim.losses.Log() if loss is None else loss,\n sample_normalization=sample_normalization,\n l1_weight=l1_weight,\n l2_weight=l2_weight,\n l1_latent=l1_latent,\n l2_latent=l2_latent,\n intercept=intercept,\n intercept_lr=intercept_lr,\n weight_initializer=weight_initializer,\n latent_initializer=latent_initializer,\n clip_gradient=clip_gradient,\n seed=seed,\n )\n\n def predict_proba_one(self, x):\n x = self._ohe_cat_features(x)\n p = utils.math.sigmoid(self._raw_dot(x)) # Convert logit to probability\n return {False: 1.0 - p, True: p}\n",
"\"\"\"Weight initializers.\"\"\"\r\nimport numpy as np\r\n\r\nfrom river.optim.base import Initializer\r\n\r\n__all__ = [\"Constant\", \"Normal\", \"Zeros\"]\r\n\r\n\r\nclass Constant(Initializer):\r\n \"\"\"Constant initializer which always returns the same value.\r\n\r\n Parameters\r\n ----------\r\n value\r\n\r\n Examples\r\n --------\r\n\r\n >>> from river import optim\r\n\r\n >>> init = optim.initializers.Constant(value=3.14)\r\n\r\n >>> init(shape=1)\r\n 3.14\r\n\r\n >>> init(shape=2)\r\n array([3.14, 3.14])\r\n\r\n \"\"\"\r\n\r\n def __init__(self, value: float):\r\n self.value = value\r\n\r\n def __call__(self, shape=1):\r\n return np.full(shape, self.value, dtype=float) if shape != 1 else self.value\r\n\r\n\r\nclass Zeros(Constant):\r\n \"\"\"Constant initializer which always returns zeros.\r\n\r\n Examples\r\n --------\r\n\r\n >>> from river import optim\r\n\r\n >>> init = optim.initializers.Zeros()\r\n\r\n >>> init(shape=1)\r\n 0.0\r\n\r\n >>> init(shape=2)\r\n array([0., 0.])\r\n\r\n \"\"\"\r\n\r\n def __init__(self):\r\n super().__init__(value=0.0)\r\n\r\n\r\nclass Normal(Initializer):\r\n \"\"\"Random normal initializer which simulate a normal distribution with specified parameters.\r\n\r\n Parameters\r\n ----------\r\n mu\r\n The mean of the normal distribution\r\n sigma\r\n The standard deviation of the normal distribution\r\n seed\r\n Random number generation seed that can be set for reproducibility.\r\n\r\n Examples\r\n --------\r\n\r\n >>> from river import optim\r\n\r\n >>> init = optim.initializers.Normal(mu=0, sigma=1, seed=42)\r\n\r\n >>> init(shape=1)\r\n 0.496714\r\n\r\n >>> init(shape=2)\r\n array([-0.1382643 , 0.64768854])\r\n\r\n \"\"\"\r\n\r\n def __init__(self, mu=0.0, sigma=1.0, seed=None):\r\n self.mu = mu\r\n self.sigma = sigma\r\n self.seed = seed\r\n self._rng = np.random.RandomState(seed)\r\n\r\n def __call__(self, shape=1):\r\n weights = self._rng.normal(loc=self.mu, scale=self.sigma, size=shape)\r\n if shape == 1:\r\n return weights[0]\r\n return weights\r\n"
] | [
[
"scipy.stats.ks_2samp"
],
[
"numpy.dot"
],
[
"numpy.random.RandomState",
"numpy.full"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
KarlKangYu/dcnn-pos-deps-head | [
"2ac6c16ea217517e4af79a84a4b0e223b2f62cd0"
] | [
"vdcnn.py"
] | [
"import tensorflow as tf\r\nimport numpy as np\r\nimport math\r\n\r\n# weights initializers\r\nhe_normal = tf.contrib.keras.initializers.he_normal()\r\n#he_normal = tf.contrib.layers.variance_scaling_initializer()\r\nregularizer = tf.contrib.layers.l2_regularizer(1e-4)\r\n\r\ndef Convolutional_Block(inputs, shortcut, num_filters, name, is_training):\r\n print(\"-\"*20)\r\n print(\"Convolutional Block\", str(num_filters), name)\r\n print(\"-\"*20)\r\n with tf.variable_scope(\"conv_block_\" + str(num_filters) + \"_\" + name):\r\n for i in range(2):\r\n with tf.variable_scope(\"conv1d_%s\" % str(i)):\r\n filter_shape = [3, inputs.get_shape()[2], num_filters]\r\n W = tf.get_variable(name='W', shape=filter_shape, \r\n initializer=he_normal,\r\n regularizer=regularizer)\r\n inputs = tf.nn.conv1d(inputs, W, stride=1, padding=\"SAME\")\r\n inputs = tf.layers.batch_normalization(inputs=inputs, momentum=0.997, epsilon=1e-5, \r\n center=True, scale=True, training=is_training)\r\n inputs = tf.nn.relu(inputs)\r\n print(\"Conv1D:\", inputs.get_shape())\r\n print(\"-\"*20)\r\n if shortcut is not None:\r\n print(\"-\"*5)\r\n print(\"Optional Shortcut:\", shortcut.get_shape())\r\n print(\"-\"*5)\r\n return inputs + shortcut\r\n return inputs\r\n\r\n# Three types of downsampling methods described by paper\r\ndef downsampling(inputs, downsampling_type, name, optional_shortcut=False, shortcut=None):\r\n # k-maxpooling\r\n if downsampling_type=='k-maxpool':\r\n k = math.ceil(int(inputs.get_shape()[1]) / 2)\r\n pool = tf.nn.top_k(tf.transpose(inputs, [0,2,1]), k=k, name=name, sorted=False)[0]\r\n pool = tf.transpose(pool, [0,2,1])\r\n # Linear\r\n elif downsampling_type=='linear':\r\n pool = tf.layers.conv1d(inputs=inputs, filters=inputs.get_shape()[2], kernel_size=3,\r\n strides=2, padding='same', use_bias=False)\r\n # Maxpooling\r\n else:\r\n pool = tf.layers.max_pooling1d(inputs=inputs, pool_size=3, strides=2, padding='same', name=name)\r\n if optional_shortcut:\r\n shortcut = tf.layers.conv1d(inputs=shortcut, filters=shortcut.get_shape()[2], kernel_size=1,\r\n strides=2, padding='same', use_bias=False)\r\n print(\"-\"*5)\r\n print(\"Optional Downsampling Shortcut:\", shortcut.get_shape())\r\n print(\"-\"*5)\r\n pool += shortcut\r\n pool = fixed_padding(inputs=pool)\r\n return tf.layers.conv1d(inputs=pool, filters=pool.get_shape()[2]*2, kernel_size=1,\r\n strides=1, padding='valid', use_bias=False)\r\n\r\ndef fixed_padding(inputs, kernel_size=3):\r\n pad_total = kernel_size - 1\r\n pad_beg = pad_total // 2\r\n pad_end = pad_total - pad_beg\r\n padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end], [0, 0]])\r\n return padded_inputs\r\n\r\nclass VDCNN():\r\n def __init__(self, num_classes, sequence_max_length=20, num_quantized_chars=50000, tags_vocab_size=44,\r\n deps_vocab_size=47, embedding_size=300,\r\n depth=9, downsampling_type='maxpool', use_he_uniform=True, optional_shortcut=False):\r\n\r\n # Depth to No. Layers\r\n if depth == 9:\r\n num_layers = [2,2,2,2]\r\n elif depth == 5:\r\n num_layers = [1,1,1,1]\r\n elif depth == 17:\r\n num_layers = [4,4,4,4]\r\n elif depth == 29:\r\n num_layers = [10,10,4,4]\r\n elif depth == 49:\r\n num_layers = [16,16,10,6]\r\n else:\r\n raise ValueError('depth=%g is a not a valid setting!' % depth)\r\n\r\n # input tensors\r\n self.input_x = tf.placeholder(tf.int32, [None, sequence_max_length], name=\"input_x\")\r\n self.input_tags = tf.placeholder(tf.int32, [None, sequence_max_length], name=\"input_tags\")\r\n self.input_deps = tf.placeholder(tf.int32, [None, sequence_max_length], name=\"input_dependency\")\r\n self.input_head = tf.placeholder(tf.int32, [None, sequence_max_length], name=\"input_head\")\r\n self.input_y = tf.placeholder(tf.float32, [None, num_classes], name=\"input_y\")\r\n self.is_training = tf.placeholder(tf.bool)\r\n\r\n initializer = tf.contrib.layers.variance_scaling_initializer()\r\n\r\n # Embedding Lookup 16\r\n with tf.device('/cpu:0'), tf.name_scope(\"embedding\"):\r\n if use_he_uniform:\r\n self.embedding_W = tf.get_variable(name='lookup_W', shape=[num_quantized_chars, embedding_size],\r\n initializer=tf.contrib.layers.variance_scaling_initializer())\r\n else:\r\n self.embedding_W = tf.Variable(tf.random_uniform([num_quantized_chars, embedding_size], -1.0, 1.0),name=\"embedding_W\")\r\n self.embedded_characters = tf.nn.embedding_lookup(self.embedding_W, self.input_x)\r\n embedded_text_expand = tf.expand_dims(self.embedded_characters, -1)\r\n\r\n with tf.device('/cpu:0'), tf.name_scope(\"embedding_tags\"):\r\n W_tags = tf.get_variable(\"embed_W_tags\", [tags_vocab_size, embedding_size], initializer=initializer)\r\n embedded_tags = tf.nn.embedding_lookup(W_tags, self.input_tags)\r\n embedded_tags_expanded = tf.expand_dims(embedded_tags, -1)\r\n\r\n with tf.device('/cpu:0'), tf.name_scope(\"embedding_deps\"):\r\n W_deps = tf.get_variable(\"embed_W_deps\", [deps_vocab_size, embedding_size], initializer=initializer)\r\n embedded_deps = tf.nn.embedding_lookup(W_deps, self.input_deps)\r\n embedded_deps_expanded = tf.expand_dims(embedded_deps, -1)\r\n\r\n with tf.device('/cpu:0'), tf.name_scope(\"embedding_head\"):\r\n W_head = tf.get_variable(\"embed_W_head\", [num_quantized_chars, embedding_size], initializer=initializer)\r\n embedded_head = tf.nn.embedding_lookup(W_head, self.input_head)\r\n embedded_head_expanded = tf.expand_dims(embedded_head, -1)\r\n\r\n cnn_inputs = tf.concat(\r\n [embedded_text_expand, embedded_tags_expanded, embedded_deps_expanded, embedded_head_expanded], -1)\r\n\r\n print(\"-\" * 20)\r\n print(\"Embedded Lookup:\", cnn_inputs.get_shape())\r\n print(\"-\" * 20)\r\n\r\n self.layers = []\r\n\r\n # Temp(First) Conv Layer\r\n with tf.variable_scope(\"temp_conv\") as scope: \r\n filter_shape = [3, embedding_size, 4, 64]\r\n W = tf.get_variable(name='W_1', shape=filter_shape, \r\n initializer=he_normal,\r\n regularizer=regularizer)\r\n paddings = [[0, 0], [1, 1], [0, 0], [0, 0]]\r\n cnn_inputs = tf.pad(cnn_inputs, paddings, \"CONSTANT\")\r\n #print(\"cnn_inputs shape:\", cnn_inputs.shape)\r\n inputs = tf.nn.conv2d(cnn_inputs, W, strides=[1, 1, 1, 1], padding=\"VALID\", name=\"first_conv\")\r\n inputs = tf.layers.batch_normalization(inputs, axis=-1, training=self.is_training)\r\n inputs = tf.nn.relu(inputs, name=\"first_relu\")\r\n #print(\"temp cnn output shape:\", inputs.shape)\r\n inputs = tf.squeeze(inputs, axis=2)\r\n #print(\"squeeze shape\", inputs.shape)\r\n #inputs = tf.nn.relu(inputs)\r\n print(\"Temp Conv\", inputs.get_shape())\r\n self.layers.append(inputs)\r\n\r\n # Conv Block 64\r\n for i in range(num_layers[0]):\r\n if i < num_layers[0] - 1 and optional_shortcut:\r\n shortcut = self.layers[-1]\r\n else:\r\n shortcut = None\r\n conv_block = Convolutional_Block(inputs=self.layers[-1], shortcut=shortcut, num_filters=64, is_training=self.is_training, name=str(i+1))\r\n self.layers.append(conv_block)\r\n pool1 = downsampling(self.layers[-1], downsampling_type=downsampling_type, name='pool1', optional_shortcut=optional_shortcut, shortcut=self.layers[-2])\r\n self.layers.append(pool1)\r\n print(\"Pooling:\", pool1.get_shape())\r\n\r\n # Conv Block 128\r\n for i in range(num_layers[1]):\r\n if i < num_layers[1] - 1 and optional_shortcut:\r\n shortcut = self.layers[-1]\r\n else:\r\n shortcut = None\r\n conv_block = Convolutional_Block(inputs=self.layers[-1], shortcut=shortcut, num_filters=128, is_training=self.is_training, name=str(i+1))\r\n self.layers.append(conv_block)\r\n pool2 = downsampling(self.layers[-1], downsampling_type=downsampling_type, name='pool2', optional_shortcut=optional_shortcut, shortcut=self.layers[-2])\r\n self.layers.append(pool2)\r\n print(\"Pooling:\", pool2.get_shape())\r\n\r\n # Conv Block 256\r\n for i in range(num_layers[2]):\r\n if i < num_layers[2] - 1 and optional_shortcut:\r\n shortcut = self.layers[-1]\r\n else:\r\n shortcut = None\r\n conv_block = Convolutional_Block(inputs=self.layers[-1], shortcut=shortcut, num_filters=256, is_training=self.is_training, name=str(i+1))\r\n self.layers.append(conv_block)\r\n pool3 = downsampling(self.layers[-1], downsampling_type=downsampling_type, name='pool3', optional_shortcut=optional_shortcut, shortcut=self.layers[-2])\r\n self.layers.append(pool3)\r\n print(\"Pooling:\", pool3.get_shape())\r\n\r\n # Conv Block 512\r\n for i in range(num_layers[3]):\r\n if i < num_layers[3] - 1 and optional_shortcut:\r\n shortcut = self.layers[-1]\r\n else:\r\n shortcut = None\r\n conv_block = Convolutional_Block(inputs=self.layers[-1], shortcut=shortcut, num_filters=512, is_training=self.is_training, name=str(i+1))\r\n self.layers.append(conv_block)\r\n\r\n # Extract 8 most features as mentioned in paper\r\n self.k_pooled = tf.nn.top_k(tf.transpose(self.layers[-1], [0,2,1]), k=8, name='k_pool', sorted=False)[0]\r\n print(\"8-maxpooling:\", self.k_pooled.get_shape())\r\n self.flatten = tf.reshape(self.k_pooled, (-1, 512*8))\r\n\r\n # fc1\r\n with tf.variable_scope('fc1'):\r\n w = tf.get_variable('w', [self.flatten.get_shape()[1], 2048], initializer=he_normal,\r\n regularizer=regularizer)\r\n b = tf.get_variable('b', [2048], initializer=tf.constant_initializer(1.0))\r\n out = tf.matmul(self.flatten, w) + b\r\n self.fc1 = tf.nn.relu(out)\r\n\r\n # fc2\r\n with tf.variable_scope('fc2'):\r\n w = tf.get_variable('w', [self.fc1.get_shape()[1], 2048], initializer=he_normal,\r\n regularizer=regularizer)\r\n b = tf.get_variable('b', [2048], initializer=tf.constant_initializer(1.0))\r\n out = tf.matmul(self.fc1, w) + b\r\n self.fc2 = tf.nn.relu(out)\r\n\r\n # fc3\r\n with tf.variable_scope('fc3'):\r\n w = tf.get_variable('w', [self.fc2.get_shape()[1], num_classes], initializer=initializer,\r\n regularizer=regularizer)\r\n b = tf.get_variable('b', [num_classes], initializer=tf.constant_initializer(1.0))\r\n self.fc3 = tf.matmul(self.fc2, w) + b\r\n\r\n # Calculate Mean cross-entropy loss\r\n with tf.name_scope(\"loss\"):\r\n self.predictions = tf.argmax(self.fc3, 1, name=\"predictions\")\r\n losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.fc3, labels=self.input_y)\r\n regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\r\n self.loss = tf.reduce_mean(losses) + sum(regularization_losses)\r\n\r\n # Accuracy\r\n with tf.name_scope(\"accuracy\"):\r\n correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))\r\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\r\n"
] | [
[
"tensorflow.device",
"tensorflow.get_variable",
"tensorflow.concat",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.contrib.keras.initializers.he_normal",
"tensorflow.cast",
"tensorflow.pad",
"tensorflow.nn.conv1d",
"tensorflow.nn.conv2d",
"tensorflow.layers.max_pooling1d",
"tensorflow.layers.batch_normalization",
"tensorflow.contrib.layers.variance_scaling_initializer",
"tensorflow.get_collection",
"tensorflow.squeeze",
"tensorflow.name_scope",
"tensorflow.argmax",
"tensorflow.matmul",
"tensorflow.placeholder",
"tensorflow.nn.embedding_lookup",
"tensorflow.nn.relu",
"tensorflow.transpose",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.constant_initializer",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.variable_scope",
"tensorflow.random_uniform"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
waikato-datamining/cntk | [
"1b626407ef750dfbd4ad66fe9aed28487f2a4441",
"1b626407ef750dfbd4ad66fe9aed28487f2a4441"
] | [
"2.6/faster_rcnn/FasterRCNN/FasterRCNN_eval.py",
"2.6/faster_rcnn/utils/config_helpers.py"
] | [
"# Copyright (c) Microsoft. All rights reserved.\n\n# Licensed under the MIT license. See LICENSE.md file in the project root\n# for full license information.\n# ==============================================================================\n\nimport os\nimport numpy as np\nimport cntk\nfrom cntk import input_variable, Axis\nfrom utils.map_helpers import evaluate_detections\nfrom utils.plot_helpers import load_resize_and_pad\nfrom utils.rpn.bbox_transform import regress_rois\nfrom utils.od_mb_source import ObjectDetectionMinibatchSource\nfrom utils.nms_wrapper import apply_nms_to_single_image_results\n\nclass FasterRCNN_Evaluator:\n def __init__(self, eval_model, cfg):\n # load model once in constructor and push images through the model in 'process_image()'\n self._img_shape = (cfg.NUM_CHANNELS, cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH)\n image_input = input_variable(shape=self._img_shape,\n dynamic_axes=[Axis.default_batch_axis()],\n name=cfg[\"MODEL\"].FEATURE_NODE_NAME)\n dims_input = input_variable((1,6), dynamic_axes=[Axis.default_batch_axis()], name='dims_input')\n self._eval_model = eval_model(image_input, dims_input)\n\n def process_image(self, img_path):\n out_cls_pred, out_rpn_rois, out_bbox_regr, dims = self.process_image_detailed(img_path)\n labels = out_cls_pred.argmax(axis=1)\n regressed_rois = regress_rois(out_rpn_rois, out_bbox_regr, labels, dims)\n\n return regressed_rois, out_cls_pred\n\n def process_image_detailed(self, img_path):\n _, cntk_img_input, dims = load_resize_and_pad(img_path, self._img_shape[2], self._img_shape[1])\n\n cntk_dims_input = np.array(dims, dtype=np.float32)\n cntk_dims_input.shape = (1,) + cntk_dims_input.shape\n output = self._eval_model.eval({self._eval_model.arguments[0]: [cntk_img_input],\n self._eval_model.arguments[1]: cntk_dims_input})\n\n out_dict = dict([(k.name, k) for k in output])\n out_cls_pred = output[out_dict['cls_pred']][0]\n out_rpn_rois = output[out_dict['rpn_rois']][0]\n out_bbox_regr = output[out_dict['bbox_regr']][0]\n\n return out_cls_pred, out_rpn_rois, out_bbox_regr, dims\n\ndef compute_test_set_aps(eval_model, cfg):\n results_base_path = os.path.join(cfg.OUTPUT_PATH, cfg[\"DATA\"].DATASET)\n # get image paths\n with open(cfg[\"DATA\"].TEST_MAP_FILE) as f:\n content = f.readlines()\n img_base_path = os.path.dirname(os.path.abspath(cfg[\"DATA\"].TEST_MAP_FILE))\n img_file_names = [os.path.join(img_base_path, x.split('\\t')[1]) for x in content]\n num_test_images = cfg[\"DATA\"].NUM_TEST_IMAGES\n classes = cfg[\"DATA\"].CLASSES\n str_labels = load_class_labels(cfg[\"DATA\"].CLASS_MAP_FILE)\n image_input = input_variable(shape=(cfg.NUM_CHANNELS, cfg.IMAGE_HEIGHT, cfg.IMAGE_WIDTH),\n dynamic_axes=[Axis.default_batch_axis()],\n name=cfg[\"MODEL\"].FEATURE_NODE_NAME)\n roi_input = input_variable((cfg.INPUT_ROIS_PER_IMAGE, 5), dynamic_axes=[Axis.default_batch_axis()])\n dims_input = input_variable((6), dynamic_axes=[Axis.default_batch_axis()])\n frcn_eval = eval_model(image_input, dims_input)\n\n # Create the minibatch source\n minibatch_source = ObjectDetectionMinibatchSource(\n cfg[\"DATA\"].TEST_MAP_FILE,\n cfg[\"DATA\"].TEST_ROI_FILE,\n max_annotations_per_image=cfg.INPUT_ROIS_PER_IMAGE,\n pad_width=cfg.IMAGE_WIDTH,\n pad_height=cfg.IMAGE_HEIGHT,\n pad_value=cfg[\"MODEL\"].IMG_PAD_COLOR,\n randomize=False, use_flipping=False,\n max_images=cfg[\"DATA\"].NUM_TEST_IMAGES,\n num_classes=cfg[\"DATA\"].NUM_CLASSES,\n proposal_provider=None)\n\n # define mapping from reader streams to network inputs\n input_map = {\n minibatch_source.image_si: image_input,\n minibatch_source.roi_si: roi_input,\n minibatch_source.dims_si: dims_input\n }\n\n # all detections are collected into:\n # all_boxes[cls][image] = N x 5 array of detections in (x1, y1, x2, y2, score)\n all_boxes = [[[] for _ in range(num_test_images)] for _ in range(cfg[\"DATA\"].NUM_CLASSES)]\n\n # evaluate test images and write netwrok output to file\n print(\"Evaluating Faster R-CNN model for %s images.\" % num_test_images)\n all_gt_infos = {key: [] for key in classes}\n for img_i in range(0, num_test_images):\n mb_data = minibatch_source.next_minibatch(1, input_map=input_map)\n\n gt_row = mb_data[roi_input].asarray()\n gt_row = gt_row.reshape((cfg.INPUT_ROIS_PER_IMAGE, 5))\n all_gt_boxes = gt_row[np.where(gt_row[:,-1] > 0)]\n\n for cls_index, cls_name in enumerate(classes):\n if cls_index == 0: continue\n cls_gt_boxes = all_gt_boxes[np.where(all_gt_boxes[:,-1] == cls_index)]\n all_gt_infos[cls_name].append({'bbox': np.array(cls_gt_boxes),\n 'difficult': [False] * len(cls_gt_boxes),\n 'det': [False] * len(cls_gt_boxes)})\n\n output = frcn_eval.eval({image_input: mb_data[image_input], dims_input: mb_data[dims_input]})\n out_dict = dict([(k.name, k) for k in output])\n out_cls_pred = output[out_dict['cls_pred']][0]\n out_rpn_rois = output[out_dict['rpn_rois']][0]\n out_bbox_regr = output[out_dict['bbox_regr']][0]\n\n labels = out_cls_pred.argmax(axis=1)\n scores = out_cls_pred.max(axis=1)\n regressed_rois = regress_rois(out_rpn_rois, out_bbox_regr, labels, mb_data[dims_input].asarray())\n nms_keep_indices = apply_nms_to_single_image_results(regressed_rois, labels, scores.tolist(),\n use_gpu_nms = cfg.USE_GPU_NMS,\n device_id = cfg.GPU_ID,\n nms_threshold=cfg.RESULTS_NMS_THRESHOLD,\n conf_threshold=cfg.RESULTS_NMS_CONF_THRESHOLD)\n \n img_path = img_file_names[img_i]\n _, cntk_img_input, dims = load_resize_and_pad(img_path, cfg.IMAGE_WIDTH, cfg.IMAGE_HEIGHT)\n save_rois_to_file(regressed_rois, nms_keep_indices, labels, str_labels, scores.tolist(),\n results_base_path, img_path, headers=True, output_width_height=False,\n suppressed_labels=(), dims=dims)\n\n labels.shape = labels.shape + (1,)\n scores.shape = scores.shape + (1,)\n coords_score_label = np.hstack((regressed_rois, scores, labels))\n\n # shape of all_boxes: e.g. 21 classes x 4952 images x 58 rois x 5 coords+score\n for cls_j in range(1, cfg[\"DATA\"].NUM_CLASSES):\n coords_score_label_for_cls = coords_score_label[np.where(coords_score_label[:,-1] == cls_j)]\n all_boxes[cls_j][img_i] = coords_score_label_for_cls[:,:-1].astype(np.float32, copy=False)\n\n if (img_i+1) % 100 == 0:\n print(\"Processed {} samples\".format(img_i+1))\n\n # calculate mAP\n aps = evaluate_detections(all_boxes, all_gt_infos, classes,\n use_gpu_nms = cfg.USE_GPU_NMS,\n device_id = cfg.GPU_ID,\n nms_threshold=cfg.RESULTS_NMS_THRESHOLD,\n conf_threshold = cfg.RESULTS_NMS_CONF_THRESHOLD)\n\n return aps\n\ndef save_rois_to_file(regressed_rois, nms_keep_indices, labels, str_labels, scores, results_base_path, img_path,\n headers=True, output_width_height=False, suppressed_labels=(), dims=None):\n \"\"\"\n Stores the ROIs in a CSV file.\n\n :param regressed_rois: the ROIs to store\n :param nms_keep_indices: the indices to keep\n :param labels: the labels\n :param str_labels: the string labels\n :param scores: the scores\n :param results_base_path: the base output directory\n :param img_path: the image file\n :param headers: whether to output the headers\n :param output_width_height: whether to output x/y/width/height or x0/y0/x1/y1\n :param suppressed_labels: the labels to keep from being output\n :param dims: the image dimensions, as returned by \"load_resize_and_pad\":\n cntk_width, cntk_height, actual_cntk_width, actual_cntk_height, original_width, original_height\n :return:\n \"\"\"\n roi_path = \"{}/{}-rois.csv\".format(results_base_path, os.path.splitext(os.path.basename(img_path))[0])\n with open(roi_path, \"w\") as roi_file:\n # headers?\n if headers:\n if output_width_height:\n roi_file.write(\"file,x,y,w,h,label,label_str,score\\n\")\n else:\n roi_file.write(\"file,x0,y0,x1,y1,label,label_str,score\\n\")\n # rois\n for index in nms_keep_indices:\n if str_labels[labels[index]] in suppressed_labels:\n continue\n\n # get coordinates\n x0 = regressed_rois[index][0]\n y0 = regressed_rois[index][1]\n x1 = regressed_rois[index][2]\n y1 = regressed_rois[index][3]\n w = x1 - x0 + 1\n h = y1 - y0 + 1\n\n # translate into realworld coordinates again\n if dims is not None:\n cntk_w, cntk_h, _, _, orig_w, orig_h = dims\n aspect = orig_w / orig_h\n cntk_act_h = round(cntk_w / aspect)\n cntk_trans_w = 0\n cntk_trans_h = -round((cntk_h - cntk_act_h) / 2)\n cntk_scale = orig_w / cntk_w\n # translate\n x0 = x0 + cntk_trans_w\n y0 = y0 + cntk_trans_h\n x1 = x1 + cntk_trans_w\n y1 = y1 + cntk_trans_h\n # scale\n x0 = x0 * cntk_scale\n y0 = y0 * cntk_scale\n x1 = x1 * cntk_scale\n y1 = y1 * cntk_scale\n w = w * cntk_scale\n h = h * cntk_scale\n\n # output\n if output_width_height:\n roi_file.write(\"{},{},{},{},{},{},{},{}\\n\".format(\n os.path.basename(img_path),\n x0, y0, w, h,\n labels[index], str_labels[labels[index]], scores[index]))\n else:\n roi_file.write(\"{},{},{},{},{},{},{},{}\\n\".format(\n os.path.basename(img_path),\n x0, y0, x1, y1,\n labels[index], str_labels[labels[index]], scores[index]))\n\ndef load_class_labels(class_map_file):\n \"\"\"\n Loads the labels from the class map file and stores them\n in a dictionary with their label index as the key.\n\n :param class_map_file: the file with the class map (label<TAB>index)\n :type class_map_file: str\n :return: the label dictionary\n :rtype: dict\n \"\"\"\n result = {}\n with open(class_map_file, 'r') as map:\n for line in map.readlines():\n label, num = line.split(\"\\t\")\n result[int(num)] = label\n return result",
"from easydict import EasyDict\nimport numpy as np\n\ndef merge_configs(config_list):\n if config_list == None or len(config_list) == 0:\n return None\n\n base_config = config_list[0]\n if type(base_config) is dict:\n base_config = EasyDict(base_config)\n\n if type(base_config) is not EasyDict:\n print(\"The argument given to 'merge_configs' have to be of type dict or EasyDict.\")\n return None\n\n for i in range(len(config_list) - 1):\n config_to_merge = config_list[i+1]\n if type(config_to_merge) is dict:\n config_to_merge = EasyDict(config_to_merge)\n _merge_add_a_into_b(config_to_merge, base_config)\n return base_config\n\n\ndef _merge_add_a_into_b(a, b):\n \"\"\"\n Merge config dictionary a into config dictionary b,\n clobbering the options in b whenever they are also specified in a.\n New options that are only in a will be added to b.\n \"\"\"\n if type(a) is not EasyDict:\n return\n\n for k, v in a.items():\n # if the key from a is new to b simply add it\n if not k in b:\n b[k] = v\n continue\n\n # the types must match\n old_type = type(b[k])\n if old_type is not type(v):\n if isinstance(b[k], np.ndarray):\n v = np.array(v, dtype=b[k].dtype)\n else:\n raise ValueError(('Type mismatch ({} vs. {}) for config key: {}').format(type(b[k]), type(v), k))\n\n # recursively merge dicts\n if type(v) is EasyDict:\n try:\n _merge_add_a_into_b(a[k], b[k])\n except:\n print('Error under config key: {}'.format(k))\n raise\n else:\n b[k] = v\n"
] | [
[
"numpy.hstack",
"numpy.array",
"numpy.where"
],
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
boyuruan/Anomaly-ReactionRL | [
"590fbc89dfa761be324c35e0dcf5d08f6086df77"
] | [
"estimators/A3C/estimators.py"
] | [
"import tensorflow as tf\n\ndef build_shared_network(X, add_summaries=False):\n \"\"\"\n \n Args:\n X: Inputs\n add_summaries: If true, add layer summaries to Tensorboard.\n \n Returns:\n Final layer activations.\n \"\"\"\n\n # Three convolutional layers\n in_layer = tf.contrib.layers.fully_connected(\n inputs=X,\n num_outputs=256,\n activation_fn=tf.nn.relu,\n scope=\"In_layer\")\n hidd_layer1 = tf.contrib.layers.fully_connected(\n inputs=in_layer,\n num_outputs=256,\n activation_fn=tf.nn.relu, \n scope=\"hidden1\")\n hidd_layer2 = tf.contrib.layers.fully_connected(\n inputs=hidd_layer1,\n num_outputs=256,\n activation_fn=tf.nn.relu, \n scope=\"hidden2\")\n \n out = tf.contrib.layers.fully_connected(\n inputs=hidd_layer2,\n num_outputs=256,\n scope=\"out\")\n \n if add_summaries:\n tf.contrib.layers.summarize_activation(in_layer)\n tf.contrib.layers.summarize_activation(hidd_layer1)\n tf.contrib.layers.summarize_activation(hidd_layer2)\n tf.contrib.layers.summarize_activation(out)\n \n return out\n\nclass PolicyEstimator():\n \"\"\"\n Policy Function approximator. Given a observation, returns probabilities\n over all possible actions.\n \n Args:\n num_outputs: Size of the action space.\n reuse: If true, an existing shared network will be re-used.\n trainable: If true we add train ops to the network.\n Actor threads that don't update their local models and don't need\n train ops would set this to false.\n \"\"\"\n\n def __init__(self, num_outputs,observation_space, reuse=False, trainable=True):\n self.num_outputs = num_outputs\n self.observation_space = observation_space\n \n # Placeholders for our input\n self.states = tf.placeholder(shape=[None, self.observation_space], \n dtype=tf.float32, name=\"X\")\n # The TD target value\n self.targets = tf.placeholder(shape=[None], dtype=tf.float32, name=\"y\")\n # Integer id of which action was selected\n self.actions = tf.placeholder(shape=[None], dtype=tf.int32, name=\"actions\")\n \n # Normalize\n #X = tf.to_float(self.states) / 255.0\n X = tf.to_float(self.states)\n batch_size = tf.shape(self.states)[0]\n \n # Graph shared with Value Net\n with tf.variable_scope(\"shared\", reuse=reuse):\n out = build_shared_network(X, add_summaries=(not reuse))\n \n \n with tf.variable_scope(\"policy_net\"):\n self.logits = tf.contrib.layers.fully_connected(out, num_outputs, activation_fn=None)\n self.probs = tf.nn.softmax(self.logits) + 1e-8\n \n self.predictions = {\n \"logits\": self.logits,\n \"probs\": self.probs\n }\n \n # We add entropy to the loss to encourage exploration\n self.entropy = -tf.reduce_sum(self.probs * tf.log(self.probs), 1, name=\"entropy\")\n self.entropy_mean = tf.reduce_mean(self.entropy, name=\"entropy_mean\")\n \n # Get the predictions for the chosen actions only\n gather_indices = tf.range(batch_size) * tf.shape(self.probs)[1] + self.actions\n self.picked_action_probs = tf.gather(tf.reshape(self.probs, [-1]), gather_indices)\n \n # Exploratory parameter beta\n beta = 0.01\n \n self.losses = - (tf.log(self.picked_action_probs) * self.targets + beta * self.entropy)\n self.loss = tf.reduce_sum(self.losses, name=\"loss\")\n \n tf.summary.scalar(self.loss.op.name, self.loss)\n tf.summary.scalar(self.entropy_mean.op.name, self.entropy_mean)\n tf.summary.histogram(self.entropy.op.name, self.entropy)\n \n if trainable:\n self.optimizer = tf.train.AdamOptimizer(0.0002)\n# self.optimizer = tf.train.RMSPropOptimizer(0.00025, 0.99, 0.0, 1e-6)\n self.grads_and_vars = self.optimizer.compute_gradients(self.loss)\n self.grads_and_vars = [[grad, var] for grad, var in self.grads_and_vars if grad is not None]\n self.train_op = self.optimizer.apply_gradients(self.grads_and_vars,\n global_step=tf.train.get_global_step())\n\n # Merge summaries from this network and the shared network (but not the value net)\n var_scope_name = tf.get_variable_scope().name\n summary_ops = tf.get_collection(tf.GraphKeys.SUMMARIES)\n sumaries = [s for s in summary_ops if \"policy_net\" in s.name or \"shared\" in s.name]\n sumaries = [s for s in summary_ops if var_scope_name in s.name]\n self.summaries = tf.summary.merge(sumaries)\n\n\nclass ValueEstimator():\n \"\"\"\n Value Function approximator. Returns a value estimator for a batch of observations.\n \n Args:\n reuse: If true, an existing shared network will be re-used.\n trainable: If true we add train ops to the network.\n Actor threads that don't update their local models and don't need\n train ops would set this to false.\n \"\"\"\n\n def __init__(self,observation_space, reuse=False, trainable=True):\n \n self.observation_space = observation_space\n\n # Placeholders for our input\n self.states = tf.placeholder(shape=[None, observation_space], dtype=tf.float32, name=\"X\")\n # The TD target value\n self.targets = tf.placeholder(shape=[None], dtype=tf.float32, name=\"y\")\n \n X = tf.to_float(self.states)\n \n # Graph shared with Value Net\n with tf.variable_scope(\"shared\", reuse=reuse):\n out = build_shared_network(X, add_summaries=(not reuse))\n \n with tf.variable_scope(\"value_net\"):\n self.logits = tf.contrib.layers.fully_connected(\n inputs=out,\n num_outputs=1,\n activation_fn=None)\n self.logits = tf.squeeze(self.logits, squeeze_dims=[1], name=\"logits\")\n \n self.losses = tf.squared_difference(self.logits, self.targets)\n self.loss = tf.reduce_sum(self.losses, name=\"loss\")\n \n self.predictions = {\"logits\": self.logits}\n \n # Summaries\n prefix = tf.get_variable_scope().name\n tf.summary.scalar(self.loss.name, self.loss)\n tf.summary.scalar(\"{}/max_value\".format(prefix), tf.reduce_max(self.logits))\n tf.summary.scalar(\"{}/min_value\".format(prefix), tf.reduce_min(self.logits))\n tf.summary.scalar(\"{}/mean_value\".format(prefix), tf.reduce_mean(self.logits))\n tf.summary.scalar(\"{}/reward_max\".format(prefix), tf.reduce_max(self.targets))\n tf.summary.scalar(\"{}/reward_min\".format(prefix), tf.reduce_min(self.targets))\n tf.summary.scalar(\"{}/reward_mean\".format(prefix), tf.reduce_mean(self.targets))\n tf.summary.histogram(\"{}/reward_targets\".format(prefix), self.targets)\n tf.summary.histogram(\"{}/values\".format(prefix), self.logits)\n \n if trainable:\n self.optimizer = tf.train.AdamOptimizer(0.0002)\n# self.optimizer = tf.train.RMSPropOptimizer(0.00025, 0.99, 0.0, 1e-6)\n self.grads_and_vars = self.optimizer.compute_gradients(self.loss)\n self.grads_and_vars = [[grad, var] for grad, var in self.grads_and_vars if grad is not None]\n self.train_op = self.optimizer.apply_gradients(\n self.grads_and_vars,\n global_step=tf.train.get_global_step())\n \n var_scope_name = tf.get_variable_scope().name\n summary_ops = tf.get_collection(tf.GraphKeys.SUMMARIES)\n sumaries = [s for s in summary_ops if \"policy_net\" in s.name or \"shared\" in s.name]\n sumaries = [s for s in summary_ops if var_scope_name in s.name]\n self.summaries = tf.summary.merge(sumaries)\n"
] | [
[
"tensorflow.reduce_sum",
"tensorflow.train.AdamOptimizer",
"tensorflow.summary.scalar",
"tensorflow.get_collection",
"tensorflow.squeeze",
"tensorflow.train.get_global_step",
"tensorflow.to_float",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.summary.merge",
"tensorflow.summary.histogram",
"tensorflow.reduce_max",
"tensorflow.nn.softmax",
"tensorflow.range",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.contrib.layers.fully_connected",
"tensorflow.reduce_min",
"tensorflow.log",
"tensorflow.variable_scope",
"tensorflow.contrib.layers.summarize_activation",
"tensorflow.get_variable_scope",
"tensorflow.squared_difference"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
meierw/hackathon-2020-01 | [
"0b80b5ae336759a8fa7af2f8a98520cd7e9c0ee4"
] | [
"01-rotation_correction/train_paper_rotation.py"
] | [
"'''Training the page orientation model'''\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\nfrom tensorflow import keras\nfrom datetime import datetime\n\nimport cv2\nimport numpy as np\nimport helper\n\n# TODO:\n# - Train to identify rotation of found pieces of paper\n\nDATA_DIR = os.path.dirname(__file__) + '/data'\nIMAGE_SIZE = 300\n\nprint('Loading data')\nTRAIN_IMAGES, TRAIN_LABELS = helper.load_samples(DATA_DIR + '/train', IMAGE_SIZE, paper_type='paper')\nTEST_IMAGES, TEST_LABELS = helper.load_samples(DATA_DIR + '/test', IMAGE_SIZE, paper_type='paper')\nprint('Data loaded')\n\nFIRST_LAYER_SIZE = 4000\nLAYER_SIZE = 500\nDROPOUT_SIZE = 0.1\nMODEL = keras.Sequential([\n keras.layers.Flatten(input_shape=(IMAGE_SIZE, IMAGE_SIZE)),\n keras.layers.Dense(FIRST_LAYER_SIZE, activation='relu'),\n keras.layers.Dense(LAYER_SIZE, activation='relu'),\n keras.layers.Dense(LAYER_SIZE, activation='relu'),\n keras.layers.Dense(LAYER_SIZE, activation='relu'),\n keras.layers.Dense(LAYER_SIZE, activation='relu'),\n keras.layers.Dense(4, activation='softmax')\n])\nMODEL.compile(\n optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy']\n)\n\nMODEL.fit(TRAIN_IMAGES, TRAIN_LABELS[:, 1], epochs=15)\n\nTEST_LOSS, TEST_ACCURACY = MODEL.evaluate(TEST_IMAGES, TEST_LABELS[:, 1], verbose=2)\n\nPREDICTIONS = MODEL.predict(TEST_IMAGES)\n\nif TEST_ACCURACY > 0.7:\n ACC = str(TEST_ACCURACY).split('.')[1]\n MODEL.save(f'predict_paper_rotation_{ACC}.h5')\n\nprint('Done')\n"
] | [
[
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Flatten"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
henriqueribeiro/pandas | [
"996f361f8e6986ea1c65ccb164a4c585e1f4a027",
"996f361f8e6986ea1c65ccb164a4c585e1f4a027",
"996f361f8e6986ea1c65ccb164a4c585e1f4a027",
"996f361f8e6986ea1c65ccb164a4c585e1f4a027",
"996f361f8e6986ea1c65ccb164a4c585e1f4a027",
"996f361f8e6986ea1c65ccb164a4c585e1f4a027",
"996f361f8e6986ea1c65ccb164a4c585e1f4a027"
] | [
"pandas/core/indexes/datetimes.py",
"pandas/core/reshape/tile.py",
"pandas/tests/extension/base/reshaping.py",
"pandas/tests/arrays/categorical/test_api.py",
"pandas/io/json/normalize.py",
"pandas/core/reshape/util.py",
"pandas/tests/indexes/multi/test_duplicates.py"
] | [
"# pylint: disable=E1101\nfrom __future__ import division\nimport operator\nimport warnings\nfrom datetime import time, datetime, timedelta\n\nimport numpy as np\nfrom pytz import utc\n\nfrom pandas.core.base import _shared_docs\n\nfrom pandas.core.dtypes.common import (\n _INT64_DTYPE,\n _NS_DTYPE,\n is_datetime64_dtype,\n is_datetimetz,\n is_dtype_equal,\n is_integer,\n is_float,\n is_integer_dtype,\n is_datetime64_ns_dtype,\n is_period_dtype,\n is_bool_dtype,\n is_string_like,\n is_list_like,\n is_scalar,\n pandas_dtype,\n ensure_int64)\nfrom pandas.core.dtypes.generic import ABCSeries\nfrom pandas.core.dtypes.missing import isna\n\nimport pandas.core.dtypes.concat as _concat\nfrom pandas.core.arrays.datetimes import DatetimeArrayMixin, _to_m8\nfrom pandas.core.arrays import datetimelike as dtl\n\nfrom pandas.core.indexes.base import Index, _index_shared_docs\nfrom pandas.core.indexes.numeric import Int64Index, Float64Index\nimport pandas.compat as compat\nfrom pandas.tseries.frequencies import to_offset, get_period_alias, Resolution\nfrom pandas.core.indexes.datetimelike import (\n DatelikeOps, TimelikeOps, DatetimeIndexOpsMixin)\nfrom pandas.tseries.offsets import (\n generate_range, CDay, prefix_mapping)\n\nfrom pandas.core.tools.timedeltas import to_timedelta\nfrom pandas.util._decorators import (\n Appender, cache_readonly, deprecate_kwarg, Substitution)\nimport pandas.core.common as com\nimport pandas.tseries.offsets as offsets\nimport pandas.core.tools.datetimes as tools\n\nfrom pandas._libs import (lib, index as libindex, tslib as libts,\n join as libjoin, Timestamp)\nfrom pandas._libs.tslibs import (timezones, conversion, fields, parsing,\n ccalendar)\n\n# -------- some conversion wrapper functions\n\n\ndef _wrap_field_accessor(name):\n fget = getattr(DatetimeArrayMixin, name).fget\n\n def f(self):\n result = fget(self)\n if is_bool_dtype(result):\n return result\n return Index(result, name=self.name)\n\n f.__name__ = name\n f.__doc__ = fget.__doc__\n return property(f)\n\n\ndef _wrap_in_index(name):\n meth = getattr(DatetimeArrayMixin, name)\n\n def func(self, *args, **kwargs):\n result = meth(self, *args, **kwargs)\n return Index(result, name=self.name)\n\n func.__doc__ = meth.__doc__\n func.__name__ = name\n return func\n\n\ndef _dt_index_cmp(cls, op):\n \"\"\"\n Wrap comparison operations to convert datetime-like to datetime64\n \"\"\"\n opname = '__{name}__'.format(name=op.__name__)\n\n def wrapper(self, other):\n result = getattr(DatetimeArrayMixin, opname)(self, other)\n if is_bool_dtype(result):\n return result\n return Index(result)\n\n return compat.set_function_name(wrapper, opname, cls)\n\n\ndef _new_DatetimeIndex(cls, d):\n \"\"\" This is called upon unpickling, rather than the default which doesn't\n have arguments and breaks __new__ \"\"\"\n\n # data are already in UTC\n # so need to localize\n tz = d.pop('tz', None)\n\n result = cls.__new__(cls, verify_integrity=False, **d)\n if tz is not None:\n result = result.tz_localize('UTC').tz_convert(tz)\n return result\n\n\nclass DatetimeIndex(DatetimeArrayMixin, DatelikeOps, TimelikeOps,\n DatetimeIndexOpsMixin, Int64Index):\n \"\"\"\n Immutable ndarray of datetime64 data, represented internally as int64, and\n which can be boxed to Timestamp objects that are subclasses of datetime and\n carry metadata such as frequency information.\n\n Parameters\n ----------\n data : array-like (1-dimensional), optional\n Optional datetime-like data to construct index with\n copy : bool\n Make a copy of input ndarray\n freq : string or pandas offset object, optional\n One of pandas date offset strings or corresponding objects. The string\n 'infer' can be passed in order to set the frequency of the index as the\n inferred frequency upon creation\n\n start : starting value, datetime-like, optional\n If data is None, start is used as the start point in generating regular\n timestamp data.\n periods : int, optional, > 0\n Number of periods to generate, if generating index. Takes precedence\n over end argument\n end : end time, datetime-like, optional\n If periods is none, generated index will extend to first conforming\n time on or just past end argument\n closed : string or None, default None\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None)\n tz : pytz.timezone or dateutil.tz.tzfile\n ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise'\n - 'infer' will attempt to infer fall dst-transition hours based on\n order\n - bool-ndarray where True signifies a DST time, False signifies a\n non-DST time (note that this flag is only applicable for ambiguous\n times)\n - 'NaT' will return NaT where there are ambiguous times\n - 'raise' will raise an AmbiguousTimeError if there are ambiguous times\n name : object\n Name to be stored in the index\n dayfirst : bool, default False\n If True, parse dates in `data` with the day first order\n yearfirst : bool, default False\n If True parse dates in `data` with the year first order\n\n Attributes\n ----------\n year\n month\n day\n hour\n minute\n second\n microsecond\n nanosecond\n date\n time\n timetz\n dayofyear\n weekofyear\n week\n dayofweek\n weekday\n quarter\n tz\n freq\n freqstr\n is_month_start\n is_month_end\n is_quarter_start\n is_quarter_end\n is_year_start\n is_year_end\n is_leap_year\n inferred_freq\n\n Methods\n -------\n normalize\n strftime\n snap\n tz_convert\n tz_localize\n round\n floor\n ceil\n to_period\n to_perioddelta\n to_pydatetime\n to_series\n to_frame\n month_name\n day_name\n\n Notes\n -----\n To learn more about the frequency strings, please see `this link\n <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.\n\n See Also\n ---------\n Index : The base pandas Index type\n TimedeltaIndex : Index of timedelta64 data\n PeriodIndex : Index of Period data\n pandas.to_datetime : Convert argument to datetime\n \"\"\"\n _resolution = cache_readonly(DatetimeArrayMixin._resolution.fget)\n\n _typ = 'datetimeindex'\n _join_precedence = 10\n\n def _join_i8_wrapper(joinf, **kwargs):\n return DatetimeIndexOpsMixin._join_i8_wrapper(joinf, dtype='M8[ns]',\n **kwargs)\n\n _inner_indexer = _join_i8_wrapper(libjoin.inner_join_indexer_int64)\n _outer_indexer = _join_i8_wrapper(libjoin.outer_join_indexer_int64)\n _left_indexer = _join_i8_wrapper(libjoin.left_join_indexer_int64)\n _left_indexer_unique = _join_i8_wrapper(\n libjoin.left_join_indexer_unique_int64, with_indexers=False)\n\n @classmethod\n def _add_comparison_methods(cls):\n \"\"\" add in comparison methods \"\"\"\n cls.__eq__ = _dt_index_cmp(cls, operator.eq)\n cls.__ne__ = _dt_index_cmp(cls, operator.ne)\n cls.__lt__ = _dt_index_cmp(cls, operator.lt)\n cls.__gt__ = _dt_index_cmp(cls, operator.gt)\n cls.__le__ = _dt_index_cmp(cls, operator.le)\n cls.__ge__ = _dt_index_cmp(cls, operator.ge)\n\n _engine_type = libindex.DatetimeEngine\n\n tz = None\n _freq = None\n _comparables = ['name', 'freqstr', 'tz']\n _attributes = ['name', 'freq', 'tz']\n\n # define my properties & methods for delegation\n _bool_ops = ['is_month_start', 'is_month_end',\n 'is_quarter_start', 'is_quarter_end', 'is_year_start',\n 'is_year_end', 'is_leap_year']\n _object_ops = ['weekday_name', 'freq', 'tz']\n _field_ops = ['year', 'month', 'day', 'hour', 'minute', 'second',\n 'weekofyear', 'week', 'weekday', 'dayofweek',\n 'dayofyear', 'quarter', 'days_in_month',\n 'daysinmonth', 'microsecond',\n 'nanosecond']\n _other_ops = ['date', 'time', 'timetz']\n _datetimelike_ops = _field_ops + _object_ops + _bool_ops + _other_ops\n _datetimelike_methods = ['to_period', 'tz_localize',\n 'tz_convert',\n 'normalize', 'strftime', 'round', 'floor',\n 'ceil', 'month_name', 'day_name']\n\n _is_numeric_dtype = False\n _infer_as_myclass = True\n _timezone = cache_readonly(DatetimeArrayMixin._timezone.fget)\n is_normalized = cache_readonly(DatetimeArrayMixin.is_normalized.fget)\n\n def __new__(cls, data=None,\n freq=None, start=None, end=None, periods=None, tz=None,\n normalize=False, closed=None, ambiguous='raise',\n dayfirst=False, yearfirst=False, dtype=None,\n copy=False, name=None, verify_integrity=True):\n\n # This allows to later ensure that the 'copy' parameter is honored:\n if isinstance(data, Index):\n ref_to_data = data._data\n else:\n ref_to_data = data\n\n if name is None and hasattr(data, 'name'):\n name = data.name\n\n freq, freq_infer = dtl.maybe_infer_freq(freq)\n\n # if dtype has an embedded tz, capture it\n tz = dtl.validate_tz_from_dtype(dtype, tz)\n\n if data is None:\n # TODO: Remove this block and associated kwargs; GH#20535\n if freq is None and com._any_none(periods, start, end):\n raise ValueError('Must provide freq argument if no data is '\n 'supplied')\n periods = dtl.validate_periods(periods)\n return cls._generate_range(start, end, periods, name, freq,\n tz=tz, normalize=normalize,\n closed=closed, ambiguous=ambiguous)\n\n if not isinstance(data, (np.ndarray, Index, ABCSeries)):\n if is_scalar(data):\n raise ValueError('DatetimeIndex() must be called with a '\n 'collection of some kind, %s was passed'\n % repr(data))\n # other iterable of some kind\n if not isinstance(data, (list, tuple)):\n data = list(data)\n data = np.asarray(data, dtype='O')\n elif isinstance(data, ABCSeries):\n data = data._values\n\n # data must be Index or np.ndarray here\n if not (is_datetime64_dtype(data) or is_datetimetz(data) or\n is_integer_dtype(data) or lib.infer_dtype(data) == 'integer'):\n data = tools.to_datetime(data, dayfirst=dayfirst,\n yearfirst=yearfirst)\n\n if isinstance(data, DatetimeArrayMixin):\n if tz is None:\n tz = data.tz\n elif data.tz is None:\n data = data.tz_localize(tz, ambiguous=ambiguous)\n else:\n # the tz's must match\n if str(tz) != str(data.tz):\n msg = ('data is already tz-aware {0}, unable to '\n 'set specified tz: {1}')\n raise TypeError(msg.format(data.tz, tz))\n\n subarr = data.values\n\n if freq is None:\n freq = data.freq\n verify_integrity = False\n elif issubclass(data.dtype.type, np.datetime64):\n if data.dtype != _NS_DTYPE:\n data = conversion.ensure_datetime64ns(data)\n if tz is not None:\n # Convert tz-naive to UTC\n tz = timezones.maybe_get_tz(tz)\n data = conversion.tz_localize_to_utc(data.view('i8'), tz,\n ambiguous=ambiguous)\n subarr = data.view(_NS_DTYPE)\n else:\n # must be integer dtype otherwise\n # assume this data are epoch timestamps\n if data.dtype != _INT64_DTYPE:\n data = data.astype(np.int64, copy=False)\n subarr = data.view(_NS_DTYPE)\n\n subarr = cls._simple_new(subarr, name=name, freq=freq, tz=tz)\n if dtype is not None:\n if not is_dtype_equal(subarr.dtype, dtype):\n # dtype must be coerced to DatetimeTZDtype above\n if subarr.tz is not None:\n raise ValueError(\"cannot localize from non-UTC data\")\n\n if verify_integrity and len(subarr) > 0:\n if freq is not None and not freq_infer:\n cls._validate_frequency(subarr, freq, ambiguous=ambiguous)\n\n if freq_infer:\n inferred = subarr.inferred_freq\n if inferred:\n subarr.freq = to_offset(inferred)\n\n return subarr._deepcopy_if_needed(ref_to_data, copy)\n\n @classmethod\n @Appender(DatetimeArrayMixin._generate_range.__doc__)\n def _generate_range(cls, start, end, periods, name=None, freq=None,\n tz=None, normalize=False, ambiguous='raise',\n closed=None):\n out = super(DatetimeIndex, cls)._generate_range(\n start, end, periods, freq,\n tz=tz, normalize=normalize, ambiguous=ambiguous, closed=closed)\n out.name = name\n return out\n\n @classmethod\n def _use_cached_range(cls, freq, _normalized, start, end):\n # Note: This always returns False\n return (freq._should_cache() and\n not (freq._normalize_cache and not _normalized) and\n _naive_in_cache_range(start, end))\n\n def _convert_for_op(self, value):\n \"\"\" Convert value to be insertable to ndarray \"\"\"\n if self._has_same_tz(value):\n return _to_m8(value)\n raise ValueError('Passed item and index have different timezone')\n\n @classmethod\n def _simple_new(cls, values, name=None, freq=None, tz=None,\n dtype=None, **kwargs):\n \"\"\"\n we require the we have a dtype compat for the values\n if we are passed a non-dtype compat, then coerce using the constructor\n \"\"\"\n\n if getattr(values, 'dtype', None) is None:\n # empty, but with dtype compat\n if values is None:\n values = np.empty(0, dtype=_NS_DTYPE)\n return cls(values, name=name, freq=freq, tz=tz,\n dtype=dtype, **kwargs)\n values = np.array(values, copy=False)\n\n if not is_datetime64_dtype(values):\n values = ensure_int64(values).view(_NS_DTYPE)\n\n values = getattr(values, 'values', values)\n\n assert isinstance(values, np.ndarray), \"values is not an np.ndarray\"\n assert is_datetime64_dtype(values)\n\n result = super(DatetimeIndex, cls)._simple_new(values, freq, tz,\n **kwargs)\n result.name = name\n result._reset_identity()\n return result\n\n @property\n def _values(self):\n # tz-naive -> ndarray\n # tz-aware -> DatetimeIndex\n if self.tz is not None:\n return self\n else:\n return self.values\n\n @property\n def tz(self):\n # GH 18595\n return self._tz\n\n @tz.setter\n def tz(self, value):\n # GH 3746: Prevent localizing or converting the index by setting tz\n raise AttributeError(\"Cannot directly set timezone. Use tz_localize() \"\n \"or tz_convert() as appropriate\")\n\n @property\n def size(self):\n # TODO: Remove this when we have a DatetimeTZArray\n # Necessary to avoid recursion error since DTI._values is a DTI\n # for TZ-aware\n return self._ndarray_values.size\n\n @property\n def shape(self):\n # TODO: Remove this when we have a DatetimeTZArray\n # Necessary to avoid recursion error since DTI._values is a DTI\n # for TZ-aware\n return self._ndarray_values.shape\n\n @property\n def nbytes(self):\n # TODO: Remove this when we have a DatetimeTZArray\n # Necessary to avoid recursion error since DTI._values is a DTI\n # for TZ-aware\n return self._ndarray_values.nbytes\n\n @classmethod\n def _cached_range(cls, start=None, end=None, periods=None, freq=None,\n name=None):\n if start is None and end is None:\n # I somewhat believe this should never be raised externally\n raise TypeError('Must specify either start or end.')\n if start is not None:\n start = Timestamp(start)\n if end is not None:\n end = Timestamp(end)\n if (start is None or end is None) and periods is None:\n raise TypeError(\n 'Must either specify period or provide both start and end.')\n\n if freq is None:\n # This can't happen with external-facing code\n raise TypeError('Must provide freq.')\n\n drc = _daterange_cache\n if freq not in _daterange_cache:\n xdr = generate_range(offset=freq, start=_CACHE_START,\n end=_CACHE_END)\n\n arr = tools.to_datetime(list(xdr), box=False)\n\n cachedRange = DatetimeIndex._simple_new(arr)\n cachedRange.freq = freq\n cachedRange = cachedRange.tz_localize(None)\n cachedRange.name = None\n drc[freq] = cachedRange\n else:\n cachedRange = drc[freq]\n\n if start is None:\n if not isinstance(end, Timestamp):\n raise AssertionError('end must be an instance of Timestamp')\n\n end = freq.rollback(end)\n\n endLoc = cachedRange.get_loc(end) + 1\n startLoc = endLoc - periods\n elif end is None:\n if not isinstance(start, Timestamp):\n raise AssertionError('start must be an instance of Timestamp')\n\n start = freq.rollforward(start)\n\n startLoc = cachedRange.get_loc(start)\n endLoc = startLoc + periods\n else:\n if not freq.onOffset(start):\n start = freq.rollforward(start)\n\n if not freq.onOffset(end):\n end = freq.rollback(end)\n\n startLoc = cachedRange.get_loc(start)\n endLoc = cachedRange.get_loc(end) + 1\n\n indexSlice = cachedRange[startLoc:endLoc]\n indexSlice.name = name\n indexSlice.freq = freq\n\n return indexSlice\n\n def _mpl_repr(self):\n # how to represent ourselves to matplotlib\n return libts.ints_to_pydatetime(self.asi8, self.tz)\n\n @cache_readonly\n def _is_dates_only(self):\n \"\"\"Return a boolean if we are only dates (and don't have a timezone)\"\"\"\n from pandas.io.formats.format import _is_dates_only\n return _is_dates_only(self.values) and self.tz is None\n\n @property\n def _formatter_func(self):\n from pandas.io.formats.format import _get_format_datetime64\n formatter = _get_format_datetime64(is_dates_only=self._is_dates_only)\n return lambda x: \"'%s'\" % formatter(x, tz=self.tz)\n\n def __reduce__(self):\n\n # we use a special reudce here because we need\n # to simply set the .tz (and not reinterpret it)\n\n d = dict(data=self._data)\n d.update(self._get_attributes_dict())\n return _new_DatetimeIndex, (self.__class__, d), None\n\n def __setstate__(self, state):\n \"\"\"Necessary for making this object picklable\"\"\"\n if isinstance(state, dict):\n super(DatetimeIndex, self).__setstate__(state)\n\n elif isinstance(state, tuple):\n\n # < 0.15 compat\n if len(state) == 2:\n nd_state, own_state = state\n data = np.empty(nd_state[1], dtype=nd_state[2])\n np.ndarray.__setstate__(data, nd_state)\n\n self.name = own_state[0]\n self._freq = own_state[1]\n self._tz = timezones.tz_standardize(own_state[2])\n\n # provide numpy < 1.7 compat\n if nd_state[2] == 'M8[us]':\n new_state = np.ndarray.__reduce__(data.astype('M8[ns]'))\n np.ndarray.__setstate__(data, new_state[2])\n\n else: # pragma: no cover\n data = np.empty(state)\n np.ndarray.__setstate__(data, state)\n\n self._data = data\n self._reset_identity()\n\n else:\n raise Exception(\"invalid pickle state\")\n _unpickle_compat = __setstate__\n\n def _maybe_update_attributes(self, attrs):\n \"\"\" Update Index attributes (e.g. freq) depending on op \"\"\"\n freq = attrs.get('freq', None)\n if freq is not None:\n # no need to infer if freq is None\n attrs['freq'] = 'infer'\n return attrs\n\n def _format_native_types(self, na_rep='NaT', date_format=None, **kwargs):\n from pandas.io.formats.format import _get_format_datetime64_from_values\n format = _get_format_datetime64_from_values(self, date_format)\n\n return libts.format_array_from_datetime(self.asi8,\n tz=self.tz,\n format=format,\n na_rep=na_rep)\n\n @Appender(_index_shared_docs['astype'])\n def astype(self, dtype, copy=True):\n dtype = pandas_dtype(dtype)\n if (is_datetime64_ns_dtype(dtype) and\n not is_dtype_equal(dtype, self.dtype)):\n # GH 18951: datetime64_ns dtype but not equal means different tz\n new_tz = getattr(dtype, 'tz', None)\n if getattr(self.dtype, 'tz', None) is None:\n return self.tz_localize(new_tz)\n return self.tz_convert(new_tz)\n elif is_period_dtype(dtype):\n return self.to_period(freq=dtype.freq)\n return super(DatetimeIndex, self).astype(dtype, copy=copy)\n\n def _get_time_micros(self):\n values = self.asi8\n if self.tz is not None and self.tz is not utc:\n values = self._local_timestamps()\n return fields.get_time_micros(values)\n\n def to_series(self, keep_tz=False, index=None, name=None):\n \"\"\"\n Create a Series with both index and values equal to the index keys\n useful with map for returning an indexer based on an index\n\n Parameters\n ----------\n keep_tz : optional, defaults False.\n return the data keeping the timezone.\n\n If keep_tz is True:\n\n If the timezone is not set, the resulting\n Series will have a datetime64[ns] dtype.\n\n Otherwise the Series will have an datetime64[ns, tz] dtype; the\n tz will be preserved.\n\n If keep_tz is False:\n\n Series will have a datetime64[ns] dtype. TZ aware\n objects will have the tz removed.\n index : Index, optional\n index of resulting Series. If None, defaults to original index\n name : string, optional\n name of resulting Series. If None, defaults to name of original\n index\n\n Returns\n -------\n Series\n \"\"\"\n from pandas import Series\n\n if index is None:\n index = self._shallow_copy()\n if name is None:\n name = self.name\n\n return Series(self._to_embed(keep_tz), index=index, name=name)\n\n def _to_embed(self, keep_tz=False, dtype=None):\n \"\"\"\n return an array repr of this object, potentially casting to object\n\n This is for internal compat\n \"\"\"\n if dtype is not None:\n return self.astype(dtype)._to_embed(keep_tz=keep_tz)\n\n if keep_tz and self.tz is not None:\n\n # preserve the tz & copy\n return self.copy(deep=True)\n\n return self.values.copy()\n\n def to_period(self, freq=None):\n \"\"\"\n Cast to PeriodIndex at a particular frequency.\n\n Converts DatetimeIndex to PeriodIndex.\n\n Parameters\n ----------\n freq : string or Offset, optional\n One of pandas' :ref:`offset strings <timeseries.offset_aliases>`\n or an Offset object. Will be inferred by default.\n\n Returns\n -------\n PeriodIndex\n\n Raises\n ------\n ValueError\n When converting a DatetimeIndex with non-regular values, so that a\n frequency cannot be inferred.\n\n Examples\n --------\n >>> df = pd.DataFrame({\"y\": [1,2,3]},\n ... index=pd.to_datetime([\"2000-03-31 00:00:00\",\n ... \"2000-05-31 00:00:00\",\n ... \"2000-08-31 00:00:00\"]))\n >>> df.index.to_period(\"M\")\n PeriodIndex(['2000-03', '2000-05', '2000-08'],\n dtype='period[M]', freq='M')\n\n Infer the daily frequency\n\n >>> idx = pd.date_range(\"2017-01-01\", periods=2)\n >>> idx.to_period()\n PeriodIndex(['2017-01-01', '2017-01-02'],\n dtype='period[D]', freq='D')\n\n See also\n --------\n pandas.PeriodIndex: Immutable ndarray holding ordinal values\n pandas.DatetimeIndex.to_pydatetime: Return DatetimeIndex as object\n \"\"\"\n from pandas.core.indexes.period import PeriodIndex\n\n if self.tz is not None:\n warnings.warn(\"Converting to PeriodIndex representation will \"\n \"drop timezone information.\", UserWarning)\n\n if freq is None:\n freq = self.freqstr or self.inferred_freq\n\n if freq is None:\n msg = (\"You must pass a freq argument as \"\n \"current index has none.\")\n raise ValueError(msg)\n\n freq = get_period_alias(freq)\n\n return PeriodIndex(self.values, name=self.name, freq=freq)\n\n def snap(self, freq='S'):\n \"\"\"\n Snap time stamps to nearest occurring frequency\n\n \"\"\"\n # Superdumb, punting on any optimizing\n freq = to_offset(freq)\n\n snapped = np.empty(len(self), dtype=_NS_DTYPE)\n\n for i, v in enumerate(self):\n s = v\n if not freq.onOffset(s):\n t0 = freq.rollback(s)\n t1 = freq.rollforward(s)\n if abs(s - t0) < abs(t1 - s):\n s = t0\n else:\n s = t1\n snapped[i] = s\n\n # we know it conforms; skip check\n return DatetimeIndex(snapped, freq=freq, verify_integrity=False)\n\n def unique(self, level=None):\n # Override here since IndexOpsMixin.unique uses self._values.unique\n # For DatetimeIndex with TZ, that's a DatetimeIndex -> recursion error\n # So we extract the tz-naive DatetimeIndex, unique that, and wrap the\n # result with out TZ.\n if self.tz is not None:\n naive = type(self)(self._ndarray_values, copy=False)\n else:\n naive = self\n result = super(DatetimeIndex, naive).unique(level=level)\n return self._simple_new(result.values, name=self.name, tz=self.tz,\n freq=self.freq)\n\n def union(self, other):\n \"\"\"\n Specialized union for DatetimeIndex objects. If combine\n overlapping ranges with the same DateOffset, will be much\n faster than Index.union\n\n Parameters\n ----------\n other : DatetimeIndex or array-like\n\n Returns\n -------\n y : Index or DatetimeIndex\n \"\"\"\n self._assert_can_do_setop(other)\n if not isinstance(other, DatetimeIndex):\n try:\n other = DatetimeIndex(other)\n except TypeError:\n pass\n\n this, other = self._maybe_utc_convert(other)\n\n if this._can_fast_union(other):\n return this._fast_union(other)\n else:\n result = Index.union(this, other)\n if isinstance(result, DatetimeIndex):\n result._tz = timezones.tz_standardize(this.tz)\n if (result.freq is None and\n (this.freq is not None or other.freq is not None)):\n result.freq = to_offset(result.inferred_freq)\n return result\n\n def to_perioddelta(self, freq):\n \"\"\"\n Calculate TimedeltaIndex of difference between index\n values and index converted to periodIndex at specified\n freq. Used for vectorized offsets\n\n Parameters\n ----------\n freq: Period frequency\n\n Returns\n -------\n y: TimedeltaIndex\n \"\"\"\n return to_timedelta(self.asi8 - self.to_period(freq)\n .to_timestamp().asi8)\n\n def union_many(self, others):\n \"\"\"\n A bit of a hack to accelerate unioning a collection of indexes\n \"\"\"\n this = self\n\n for other in others:\n if not isinstance(this, DatetimeIndex):\n this = Index.union(this, other)\n continue\n\n if not isinstance(other, DatetimeIndex):\n try:\n other = DatetimeIndex(other)\n except TypeError:\n pass\n\n this, other = this._maybe_utc_convert(other)\n\n if this._can_fast_union(other):\n this = this._fast_union(other)\n else:\n tz = this.tz\n this = Index.union(this, other)\n if isinstance(this, DatetimeIndex):\n this._tz = timezones.tz_standardize(tz)\n\n if this.freq is None:\n this.freq = to_offset(this.inferred_freq)\n return this\n\n def join(self, other, how='left', level=None, return_indexers=False,\n sort=False):\n \"\"\"\n See Index.join\n \"\"\"\n if (not isinstance(other, DatetimeIndex) and len(other) > 0 and\n other.inferred_type not in ('floating', 'integer', 'mixed-integer',\n 'mixed-integer-float', 'mixed')):\n try:\n other = DatetimeIndex(other)\n except (TypeError, ValueError):\n pass\n\n this, other = self._maybe_utc_convert(other)\n return Index.join(this, other, how=how, level=level,\n return_indexers=return_indexers, sort=sort)\n\n def _maybe_utc_convert(self, other):\n this = self\n if isinstance(other, DatetimeIndex):\n if self.tz is not None:\n if other.tz is None:\n raise TypeError('Cannot join tz-naive with tz-aware '\n 'DatetimeIndex')\n elif other.tz is not None:\n raise TypeError('Cannot join tz-naive with tz-aware '\n 'DatetimeIndex')\n\n if not timezones.tz_compare(self.tz, other.tz):\n this = self.tz_convert('UTC')\n other = other.tz_convert('UTC')\n return this, other\n\n def _wrap_joined_index(self, joined, other):\n name = self.name if self.name == other.name else None\n if (isinstance(other, DatetimeIndex) and\n self.freq == other.freq and\n self._can_fast_union(other)):\n joined = self._shallow_copy(joined)\n joined.name = name\n return joined\n else:\n tz = getattr(other, 'tz', None)\n return self._simple_new(joined, name, tz=tz)\n\n def _can_fast_union(self, other):\n if not isinstance(other, DatetimeIndex):\n return False\n\n freq = self.freq\n\n if freq is None or freq != other.freq:\n return False\n\n if not self.is_monotonic or not other.is_monotonic:\n return False\n\n if len(self) == 0 or len(other) == 0:\n return True\n\n # to make our life easier, \"sort\" the two ranges\n if self[0] <= other[0]:\n left, right = self, other\n else:\n left, right = other, self\n\n right_start = right[0]\n left_end = left[-1]\n\n # Only need to \"adjoin\", not overlap\n try:\n return (right_start == left_end + freq) or right_start in left\n except (ValueError):\n\n # if we are comparing a freq that does not propagate timezones\n # this will raise\n return False\n\n def _fast_union(self, other):\n if len(other) == 0:\n return self.view(type(self))\n\n if len(self) == 0:\n return other.view(type(self))\n\n # to make our life easier, \"sort\" the two ranges\n if self[0] <= other[0]:\n left, right = self, other\n else:\n left, right = other, self\n\n left_start, left_end = left[0], left[-1]\n right_end = right[-1]\n\n if not self.freq._should_cache():\n # concatenate dates\n if left_end < right_end:\n loc = right.searchsorted(left_end, side='right')\n right_chunk = right.values[loc:]\n dates = _concat._concat_compat((left.values, right_chunk))\n return self._shallow_copy(dates)\n else:\n return left\n else:\n return type(self)(start=left_start,\n end=max(left_end, right_end),\n freq=left.freq)\n\n def _wrap_union_result(self, other, result):\n name = self.name if self.name == other.name else None\n if not timezones.tz_compare(self.tz, other.tz):\n raise ValueError('Passed item and index have different timezone')\n return self._simple_new(result, name=name, freq=None, tz=self.tz)\n\n def intersection(self, other):\n \"\"\"\n Specialized intersection for DatetimeIndex objects. May be much faster\n than Index.intersection\n\n Parameters\n ----------\n other : DatetimeIndex or array-like\n\n Returns\n -------\n y : Index or DatetimeIndex\n \"\"\"\n self._assert_can_do_setop(other)\n if not isinstance(other, DatetimeIndex):\n try:\n other = DatetimeIndex(other)\n except (TypeError, ValueError):\n pass\n result = Index.intersection(self, other)\n if isinstance(result, DatetimeIndex):\n if result.freq is None:\n result.freq = to_offset(result.inferred_freq)\n return result\n\n elif (other.freq is None or self.freq is None or\n other.freq != self.freq or\n not other.freq.isAnchored() or\n (not self.is_monotonic or not other.is_monotonic)):\n result = Index.intersection(self, other)\n result = self._shallow_copy(result._values, name=result.name,\n tz=result.tz, freq=None)\n if result.freq is None:\n result.freq = to_offset(result.inferred_freq)\n return result\n\n if len(self) == 0:\n return self\n if len(other) == 0:\n return other\n # to make our life easier, \"sort\" the two ranges\n if self[0] <= other[0]:\n left, right = self, other\n else:\n left, right = other, self\n\n end = min(left[-1], right[-1])\n start = right[0]\n\n if end < start:\n return type(self)(data=[])\n else:\n lslice = slice(*left.slice_locs(start, end))\n left_chunk = left.values[lslice]\n return self._shallow_copy(left_chunk)\n\n def _parsed_string_to_bounds(self, reso, parsed):\n \"\"\"\n Calculate datetime bounds for parsed time string and its resolution.\n\n Parameters\n ----------\n reso : Resolution\n Resolution provided by parsed string.\n parsed : datetime\n Datetime from parsed string.\n\n Returns\n -------\n lower, upper: pd.Timestamp\n\n \"\"\"\n if reso == 'year':\n return (Timestamp(datetime(parsed.year, 1, 1), tz=self.tz),\n Timestamp(datetime(parsed.year, 12, 31, 23,\n 59, 59, 999999), tz=self.tz))\n elif reso == 'month':\n d = ccalendar.get_days_in_month(parsed.year, parsed.month)\n return (Timestamp(datetime(parsed.year, parsed.month, 1),\n tz=self.tz),\n Timestamp(datetime(parsed.year, parsed.month, d, 23,\n 59, 59, 999999), tz=self.tz))\n elif reso == 'quarter':\n qe = (((parsed.month - 1) + 2) % 12) + 1 # two months ahead\n d = ccalendar.get_days_in_month(parsed.year, qe) # at end of month\n return (Timestamp(datetime(parsed.year, parsed.month, 1),\n tz=self.tz),\n Timestamp(datetime(parsed.year, qe, d, 23, 59,\n 59, 999999), tz=self.tz))\n elif reso == 'day':\n st = datetime(parsed.year, parsed.month, parsed.day)\n return (Timestamp(st, tz=self.tz),\n Timestamp(Timestamp(st + offsets.Day(),\n tz=self.tz).value - 1))\n elif reso == 'hour':\n st = datetime(parsed.year, parsed.month, parsed.day,\n hour=parsed.hour)\n return (Timestamp(st, tz=self.tz),\n Timestamp(Timestamp(st + offsets.Hour(),\n tz=self.tz).value - 1))\n elif reso == 'minute':\n st = datetime(parsed.year, parsed.month, parsed.day,\n hour=parsed.hour, minute=parsed.minute)\n return (Timestamp(st, tz=self.tz),\n Timestamp(Timestamp(st + offsets.Minute(),\n tz=self.tz).value - 1))\n elif reso == 'second':\n st = datetime(parsed.year, parsed.month, parsed.day,\n hour=parsed.hour, minute=parsed.minute,\n second=parsed.second)\n return (Timestamp(st, tz=self.tz),\n Timestamp(Timestamp(st + offsets.Second(),\n tz=self.tz).value - 1))\n elif reso == 'microsecond':\n st = datetime(parsed.year, parsed.month, parsed.day,\n parsed.hour, parsed.minute, parsed.second,\n parsed.microsecond)\n return (Timestamp(st, tz=self.tz), Timestamp(st, tz=self.tz))\n else:\n raise KeyError\n\n def _partial_date_slice(self, reso, parsed, use_lhs=True, use_rhs=True):\n is_monotonic = self.is_monotonic\n if (is_monotonic and reso in ['day', 'hour', 'minute', 'second'] and\n self._resolution >= Resolution.get_reso(reso)):\n # These resolution/monotonicity validations came from GH3931,\n # GH3452 and GH2369.\n\n # See also GH14826\n raise KeyError\n\n if reso == 'microsecond':\n # _partial_date_slice doesn't allow microsecond resolution, but\n # _parsed_string_to_bounds allows it.\n raise KeyError\n\n t1, t2 = self._parsed_string_to_bounds(reso, parsed)\n stamps = self.asi8\n\n if is_monotonic:\n\n # we are out of range\n if (len(stamps) and ((use_lhs and t1.value < stamps[0] and\n t2.value < stamps[0]) or\n ((use_rhs and t1.value > stamps[-1] and\n t2.value > stamps[-1])))):\n raise KeyError\n\n # a monotonic (sorted) series can be sliced\n left = stamps.searchsorted(\n t1.value, side='left') if use_lhs else None\n right = stamps.searchsorted(\n t2.value, side='right') if use_rhs else None\n\n return slice(left, right)\n\n lhs_mask = (stamps >= t1.value) if use_lhs else True\n rhs_mask = (stamps <= t2.value) if use_rhs else True\n\n # try to find a the dates\n return (lhs_mask & rhs_mask).nonzero()[0]\n\n def _maybe_promote(self, other):\n if other.inferred_type == 'date':\n other = DatetimeIndex(other)\n return self, other\n\n def get_value(self, series, key):\n \"\"\"\n Fast lookup of value from 1-dimensional ndarray. Only use this if you\n know what you're doing\n \"\"\"\n\n if isinstance(key, datetime):\n\n # needed to localize naive datetimes\n if self.tz is not None:\n key = Timestamp(key, tz=self.tz)\n\n return self.get_value_maybe_box(series, key)\n\n if isinstance(key, time):\n locs = self.indexer_at_time(key)\n return series.take(locs)\n\n try:\n return com.maybe_box(self, Index.get_value(self, series, key),\n series, key)\n except KeyError:\n try:\n loc = self._get_string_slice(key)\n return series[loc]\n except (TypeError, ValueError, KeyError):\n pass\n\n try:\n return self.get_value_maybe_box(series, key)\n except (TypeError, ValueError, KeyError):\n raise KeyError(key)\n\n def get_value_maybe_box(self, series, key):\n # needed to localize naive datetimes\n if self.tz is not None:\n key = Timestamp(key, tz=self.tz)\n elif not isinstance(key, Timestamp):\n key = Timestamp(key)\n values = self._engine.get_value(com.values_from_object(series),\n key, tz=self.tz)\n return com.maybe_box(self, values, series, key)\n\n def get_loc(self, key, method=None, tolerance=None):\n \"\"\"\n Get integer location for requested label\n\n Returns\n -------\n loc : int\n \"\"\"\n\n if tolerance is not None:\n # try converting tolerance now, so errors don't get swallowed by\n # the try/except clauses below\n tolerance = self._convert_tolerance(tolerance, np.asarray(key))\n\n if isinstance(key, datetime):\n # needed to localize naive datetimes\n key = Timestamp(key, tz=self.tz)\n return Index.get_loc(self, key, method, tolerance)\n\n elif isinstance(key, timedelta):\n # GH#20464\n raise TypeError(\"Cannot index {cls} with {other}\"\n .format(cls=type(self).__name__,\n other=type(key).__name__))\n\n if isinstance(key, time):\n if method is not None:\n raise NotImplementedError('cannot yet lookup inexact labels '\n 'when key is a time object')\n return self.indexer_at_time(key)\n\n try:\n return Index.get_loc(self, key, method, tolerance)\n except (KeyError, ValueError, TypeError):\n try:\n return self._get_string_slice(key)\n except (TypeError, KeyError, ValueError):\n pass\n\n try:\n stamp = Timestamp(key, tz=self.tz)\n return Index.get_loc(self, stamp, method, tolerance)\n except KeyError:\n raise KeyError(key)\n except ValueError as e:\n # list-like tolerance size must match target index size\n if 'list-like' in str(e):\n raise e\n raise KeyError(key)\n\n def _maybe_cast_slice_bound(self, label, side, kind):\n \"\"\"\n If label is a string, cast it to datetime according to resolution.\n\n Parameters\n ----------\n label : object\n side : {'left', 'right'}\n kind : {'ix', 'loc', 'getitem'}\n\n Returns\n -------\n label : object\n\n Notes\n -----\n Value of `side` parameter should be validated in caller.\n\n \"\"\"\n assert kind in ['ix', 'loc', 'getitem', None]\n\n if is_float(label) or isinstance(label, time) or is_integer(label):\n self._invalid_indexer('slice', label)\n\n if isinstance(label, compat.string_types):\n freq = getattr(self, 'freqstr',\n getattr(self, 'inferred_freq', None))\n _, parsed, reso = parsing.parse_time_string(label, freq)\n lower, upper = self._parsed_string_to_bounds(reso, parsed)\n # lower, upper form the half-open interval:\n # [parsed, parsed + 1 freq)\n # because label may be passed to searchsorted\n # the bounds need swapped if index is reverse sorted and has a\n # length > 1 (is_monotonic_decreasing gives True for empty\n # and length 1 index)\n if self._is_strictly_monotonic_decreasing and len(self) > 1:\n return upper if side == 'left' else lower\n return lower if side == 'left' else upper\n else:\n return label\n\n def _get_string_slice(self, key, use_lhs=True, use_rhs=True):\n freq = getattr(self, 'freqstr',\n getattr(self, 'inferred_freq', None))\n _, parsed, reso = parsing.parse_time_string(key, freq)\n loc = self._partial_date_slice(reso, parsed, use_lhs=use_lhs,\n use_rhs=use_rhs)\n return loc\n\n def slice_indexer(self, start=None, end=None, step=None, kind=None):\n \"\"\"\n Return indexer for specified label slice.\n Index.slice_indexer, customized to handle time slicing.\n\n In addition to functionality provided by Index.slice_indexer, does the\n following:\n\n - if both `start` and `end` are instances of `datetime.time`, it\n invokes `indexer_between_time`\n - if `start` and `end` are both either string or None perform\n value-based selection in non-monotonic cases.\n\n \"\"\"\n # For historical reasons DatetimeIndex supports slices between two\n # instances of datetime.time as if it were applying a slice mask to\n # an array of (self.hour, self.minute, self.seconds, self.microsecond).\n if isinstance(start, time) and isinstance(end, time):\n if step is not None and step != 1:\n raise ValueError('Must have step size of 1 with time slices')\n return self.indexer_between_time(start, end)\n\n if isinstance(start, time) or isinstance(end, time):\n raise KeyError('Cannot mix time and non-time slice keys')\n\n try:\n return Index.slice_indexer(self, start, end, step, kind=kind)\n except KeyError:\n # For historical reasons DatetimeIndex by default supports\n # value-based partial (aka string) slices on non-monotonic arrays,\n # let's try that.\n if ((start is None or isinstance(start, compat.string_types)) and\n (end is None or isinstance(end, compat.string_types))):\n mask = True\n if start is not None:\n start_casted = self._maybe_cast_slice_bound(\n start, 'left', kind)\n mask = start_casted <= self\n\n if end is not None:\n end_casted = self._maybe_cast_slice_bound(\n end, 'right', kind)\n mask = (self <= end_casted) & mask\n\n indexer = mask.nonzero()[0][::step]\n if len(indexer) == len(self):\n return slice(None)\n else:\n return indexer\n else:\n raise\n\n year = _wrap_field_accessor('year')\n month = _wrap_field_accessor('month')\n day = _wrap_field_accessor('day')\n hour = _wrap_field_accessor('hour')\n minute = _wrap_field_accessor('minute')\n second = _wrap_field_accessor('second')\n microsecond = _wrap_field_accessor('microsecond')\n nanosecond = _wrap_field_accessor('nanosecond')\n weekofyear = _wrap_field_accessor('weekofyear')\n week = weekofyear\n dayofweek = _wrap_field_accessor('dayofweek')\n weekday = dayofweek\n\n weekday_name = _wrap_field_accessor('weekday_name')\n\n dayofyear = _wrap_field_accessor('dayofyear')\n quarter = _wrap_field_accessor('quarter')\n days_in_month = _wrap_field_accessor('days_in_month')\n daysinmonth = days_in_month\n is_month_start = _wrap_field_accessor('is_month_start')\n is_month_end = _wrap_field_accessor('is_month_end')\n is_quarter_start = _wrap_field_accessor('is_quarter_start')\n is_quarter_end = _wrap_field_accessor('is_quarter_end')\n is_year_start = _wrap_field_accessor('is_year_start')\n is_year_end = _wrap_field_accessor('is_year_end')\n is_leap_year = _wrap_field_accessor('is_leap_year')\n\n @Appender(DatetimeArrayMixin.normalize.__doc__)\n def normalize(self):\n result = DatetimeArrayMixin.normalize(self)\n result.name = self.name\n return result\n\n @Substitution(klass='DatetimeIndex')\n @Appender(_shared_docs['searchsorted'])\n @deprecate_kwarg(old_arg_name='key', new_arg_name='value')\n def searchsorted(self, value, side='left', sorter=None):\n if isinstance(value, (np.ndarray, Index)):\n value = np.array(value, dtype=_NS_DTYPE, copy=False)\n else:\n value = _to_m8(value, tz=self.tz)\n\n return self.values.searchsorted(value, side=side)\n\n def is_type_compatible(self, typ):\n return typ == self.inferred_type or typ == 'datetime'\n\n @property\n def inferred_type(self):\n # b/c datetime is represented as microseconds since the epoch, make\n # sure we can't have ambiguous indexing\n return 'datetime64'\n\n @property\n def is_all_dates(self):\n return True\n\n def insert(self, loc, item):\n \"\"\"\n Make new Index inserting new item at location\n\n Parameters\n ----------\n loc : int\n item : object\n if not either a Python datetime or a numpy integer-like, returned\n Index dtype will be object rather than datetime.\n\n Returns\n -------\n new_index : Index\n \"\"\"\n if is_scalar(item) and isna(item):\n # GH 18295\n item = self._na_value\n\n freq = None\n\n if isinstance(item, (datetime, np.datetime64)):\n self._assert_can_do_op(item)\n if not self._has_same_tz(item) and not isna(item):\n raise ValueError(\n 'Passed item and index have different timezone')\n # check freq can be preserved on edge cases\n if self.size and self.freq is not None:\n if ((loc == 0 or loc == -len(self)) and\n item + self.freq == self[0]):\n freq = self.freq\n elif (loc == len(self)) and item - self.freq == self[-1]:\n freq = self.freq\n item = _to_m8(item, tz=self.tz)\n\n try:\n new_dates = np.concatenate((self[:loc].asi8, [item.view(np.int64)],\n self[loc:].asi8))\n return DatetimeIndex(new_dates, name=self.name, freq=freq,\n tz=self.tz)\n except (AttributeError, TypeError):\n\n # fall back to object index\n if isinstance(item, compat.string_types):\n return self.astype(object).insert(loc, item)\n raise TypeError(\n \"cannot insert DatetimeIndex with incompatible label\")\n\n def delete(self, loc):\n \"\"\"\n Make a new DatetimeIndex with passed location(s) deleted.\n\n Parameters\n ----------\n loc: int, slice or array of ints\n Indicate which sub-arrays to remove.\n\n Returns\n -------\n new_index : DatetimeIndex\n \"\"\"\n new_dates = np.delete(self.asi8, loc)\n\n freq = None\n if is_integer(loc):\n if loc in (0, -len(self), -1, len(self) - 1):\n freq = self.freq\n else:\n if is_list_like(loc):\n loc = lib.maybe_indices_to_slice(\n ensure_int64(np.array(loc)), len(self))\n if isinstance(loc, slice) and loc.step in (1, None):\n if (loc.start in (0, None) or loc.stop in (len(self), None)):\n freq = self.freq\n\n return DatetimeIndex(new_dates, name=self.name, freq=freq, tz=self.tz)\n\n def indexer_at_time(self, time, asof=False):\n \"\"\"\n Returns index locations of index values at particular time of day\n (e.g. 9:30AM).\n\n Parameters\n ----------\n time : datetime.time or string\n datetime.time or string in appropriate format (\"%H:%M\", \"%H%M\",\n \"%I:%M%p\", \"%I%M%p\", \"%H:%M:%S\", \"%H%M%S\", \"%I:%M:%S%p\",\n \"%I%M%S%p\").\n\n Returns\n -------\n values_at_time : array of integers\n\n See Also\n --------\n indexer_between_time, DataFrame.at_time\n \"\"\"\n from dateutil.parser import parse\n\n if asof:\n raise NotImplementedError(\"'asof' argument is not supported\")\n\n if isinstance(time, compat.string_types):\n time = parse(time).time()\n\n if time.tzinfo:\n # TODO\n raise NotImplementedError(\"argument 'time' with timezone info is \"\n \"not supported\")\n\n time_micros = self._get_time_micros()\n micros = _time_to_micros(time)\n return (micros == time_micros).nonzero()[0]\n\n def indexer_between_time(self, start_time, end_time, include_start=True,\n include_end=True):\n \"\"\"\n Return index locations of values between particular times of day\n (e.g., 9:00-9:30AM).\n\n Parameters\n ----------\n start_time, end_time : datetime.time, str\n datetime.time or string in appropriate format (\"%H:%M\", \"%H%M\",\n \"%I:%M%p\", \"%I%M%p\", \"%H:%M:%S\", \"%H%M%S\", \"%I:%M:%S%p\",\n \"%I%M%S%p\").\n include_start : boolean, default True\n include_end : boolean, default True\n\n Returns\n -------\n values_between_time : array of integers\n\n See Also\n --------\n indexer_at_time, DataFrame.between_time\n \"\"\"\n start_time = tools.to_time(start_time)\n end_time = tools.to_time(end_time)\n time_micros = self._get_time_micros()\n start_micros = _time_to_micros(start_time)\n end_micros = _time_to_micros(end_time)\n\n if include_start and include_end:\n lop = rop = operator.le\n elif include_start:\n lop = operator.le\n rop = operator.lt\n elif include_end:\n lop = operator.lt\n rop = operator.le\n else:\n lop = rop = operator.lt\n\n if start_time <= end_time:\n join_op = operator.and_\n else:\n join_op = operator.or_\n\n mask = join_op(lop(start_micros, time_micros),\n rop(time_micros, end_micros))\n\n return mask.nonzero()[0]\n\n def to_julian_date(self):\n \"\"\"\n Convert DatetimeIndex to Float64Index of Julian Dates.\n 0 Julian date is noon January 1, 4713 BC.\n http://en.wikipedia.org/wiki/Julian_day\n \"\"\"\n result = DatetimeArrayMixin.to_julian_date(self)\n return Float64Index(result)\n\n month_name = _wrap_in_index(\"month_name\")\n day_name = _wrap_in_index(\"day_name\")\n\n\nDatetimeIndex._add_comparison_methods()\nDatetimeIndex._add_numeric_methods_disabled()\nDatetimeIndex._add_logical_methods_disabled()\nDatetimeIndex._add_datetimelike_methods()\n\n\ndef date_range(start=None, end=None, periods=None, freq=None, tz=None,\n normalize=False, name=None, closed=None, **kwargs):\n \"\"\"\n Return a fixed frequency DatetimeIndex.\n\n Parameters\n ----------\n start : str or datetime-like, optional\n Left bound for generating dates.\n end : str or datetime-like, optional\n Right bound for generating dates.\n periods : integer, optional\n Number of periods to generate.\n freq : str or DateOffset, default 'D'\n Frequency strings can have multiples, e.g. '5H'. See\n :ref:`here <timeseries.offset_aliases>` for a list of\n frequency aliases.\n tz : str or tzinfo, optional\n Time zone name for returning localized DatetimeIndex, for example\n 'Asia/Hong_Kong'. By default, the resulting DatetimeIndex is\n timezone-naive.\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range.\n name : str, default None\n Name of the resulting DatetimeIndex.\n closed : {None, 'left', 'right'}, optional\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None, the default).\n **kwargs\n For compatibility. Has no effect on the result.\n\n Returns\n -------\n rng : DatetimeIndex\n\n See Also\n --------\n pandas.DatetimeIndex : An immutable container for datetimes.\n pandas.timedelta_range : Return a fixed frequency TimedeltaIndex.\n pandas.period_range : Return a fixed frequency PeriodIndex.\n pandas.interval_range : Return a fixed frequency IntervalIndex.\n\n Notes\n -----\n Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. If ``freq`` is omitted, the resulting\n ``DatetimeIndex`` will have ``periods`` linearly spaced elements between\n ``start`` and ``end`` (closed on both sides).\n\n To learn more about the frequency strings, please see `this link\n <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.\n\n Examples\n --------\n **Specifying the values**\n\n The next four examples generate the same `DatetimeIndex`, but vary\n the combination of `start`, `end` and `periods`.\n\n Specify `start` and `end`, with the default daily frequency.\n\n >>> pd.date_range(start='1/1/2018', end='1/08/2018')\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `start` and `periods`, the number of periods (days).\n\n >>> pd.date_range(start='1/1/2018', periods=8)\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `end` and `periods`, the number of periods (days).\n\n >>> pd.date_range(end='1/1/2018', periods=8)\n DatetimeIndex(['2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28',\n '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `start`, `end`, and `periods`; the frequency is generated\n automatically (linearly spaced).\n\n >>> pd.date_range(start='2018-04-24', end='2018-04-27', periods=3)\n DatetimeIndex(['2018-04-24 00:00:00', '2018-04-25 12:00:00',\n '2018-04-27 00:00:00'], freq=None)\n\n **Other Parameters**\n\n Changed the `freq` (frequency) to ``'M'`` (month end frequency).\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq='M')\n DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30',\n '2018-05-31'],\n dtype='datetime64[ns]', freq='M')\n\n Multiples are allowed\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq='3M')\n DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n '2019-01-31'],\n dtype='datetime64[ns]', freq='3M')\n\n `freq` can also be specified as an Offset object.\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq=pd.offsets.MonthEnd(3))\n DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n '2019-01-31'],\n dtype='datetime64[ns]', freq='3M')\n\n Specify `tz` to set the timezone.\n\n >>> pd.date_range(start='1/1/2018', periods=5, tz='Asia/Tokyo')\n DatetimeIndex(['2018-01-01 00:00:00+09:00', '2018-01-02 00:00:00+09:00',\n '2018-01-03 00:00:00+09:00', '2018-01-04 00:00:00+09:00',\n '2018-01-05 00:00:00+09:00'],\n dtype='datetime64[ns, Asia/Tokyo]', freq='D')\n\n `closed` controls whether to include `start` and `end` that are on the\n boundary. The default includes boundary points on either end.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed=None)\n DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'],\n dtype='datetime64[ns]', freq='D')\n\n Use ``closed='left'`` to exclude `end` if it falls on the boundary.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='left')\n DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03'],\n dtype='datetime64[ns]', freq='D')\n\n Use ``closed='right'`` to exclude `start` if it falls on the boundary.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='right')\n DatetimeIndex(['2017-01-02', '2017-01-03', '2017-01-04'],\n dtype='datetime64[ns]', freq='D')\n \"\"\"\n\n if freq is None and com._any_none(periods, start, end):\n freq = 'D'\n\n return DatetimeIndex(start=start, end=end, periods=periods,\n freq=freq, tz=tz, normalize=normalize, name=name,\n closed=closed, **kwargs)\n\n\ndef bdate_range(start=None, end=None, periods=None, freq='B', tz=None,\n normalize=True, name=None, weekmask=None, holidays=None,\n closed=None, **kwargs):\n \"\"\"\n Return a fixed frequency DatetimeIndex, with business day as the default\n frequency\n\n Parameters\n ----------\n start : string or datetime-like, default None\n Left bound for generating dates\n end : string or datetime-like, default None\n Right bound for generating dates\n periods : integer, default None\n Number of periods to generate\n freq : string or DateOffset, default 'B' (business daily)\n Frequency strings can have multiples, e.g. '5H'\n tz : string or None\n Time zone name for returning localized DatetimeIndex, for example\n Asia/Beijing\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range\n name : string, default None\n Name of the resulting DatetimeIndex\n weekmask : string or None, default None\n Weekmask of valid business days, passed to ``numpy.busdaycalendar``,\n only used when custom frequency strings are passed. The default\n value None is equivalent to 'Mon Tue Wed Thu Fri'\n\n .. versionadded:: 0.21.0\n\n holidays : list-like or None, default None\n Dates to exclude from the set of valid business days, passed to\n ``numpy.busdaycalendar``, only used when custom frequency strings\n are passed\n\n .. versionadded:: 0.21.0\n\n closed : string, default None\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None)\n\n Notes\n -----\n Of the four parameters: ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. Specifying ``freq`` is a requirement\n for ``bdate_range``. Use ``date_range`` if specifying ``freq`` is not\n desired.\n\n To learn more about the frequency strings, please see `this link\n <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.\n\n Returns\n -------\n rng : DatetimeIndex\n \"\"\"\n if freq is None:\n msg = 'freq must be specified for bdate_range; use date_range instead'\n raise TypeError(msg)\n\n if is_string_like(freq) and freq.startswith('C'):\n try:\n weekmask = weekmask or 'Mon Tue Wed Thu Fri'\n freq = prefix_mapping[freq](holidays=holidays, weekmask=weekmask)\n except (KeyError, TypeError):\n msg = 'invalid custom frequency string: {freq}'.format(freq=freq)\n raise ValueError(msg)\n elif holidays or weekmask:\n msg = ('a custom frequency string is required when holidays or '\n 'weekmask are passed, got frequency {freq}').format(freq=freq)\n raise ValueError(msg)\n\n return DatetimeIndex(start=start, end=end, periods=periods,\n freq=freq, tz=tz, normalize=normalize, name=name,\n closed=closed, **kwargs)\n\n\ndef cdate_range(start=None, end=None, periods=None, freq='C', tz=None,\n normalize=True, name=None, closed=None, **kwargs):\n \"\"\"\n Return a fixed frequency DatetimeIndex, with CustomBusinessDay as the\n default frequency\n\n .. deprecated:: 0.21.0\n\n Parameters\n ----------\n start : string or datetime-like, default None\n Left bound for generating dates\n end : string or datetime-like, default None\n Right bound for generating dates\n periods : integer, default None\n Number of periods to generate\n freq : string or DateOffset, default 'C' (CustomBusinessDay)\n Frequency strings can have multiples, e.g. '5H'\n tz : string, default None\n Time zone name for returning localized DatetimeIndex, for example\n Asia/Beijing\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range\n name : string, default None\n Name of the resulting DatetimeIndex\n weekmask : string, Default 'Mon Tue Wed Thu Fri'\n weekmask of valid business days, passed to ``numpy.busdaycalendar``\n holidays : list\n list/array of dates to exclude from the set of valid business days,\n passed to ``numpy.busdaycalendar``\n closed : string, default None\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None)\n\n Notes\n -----\n Of the three parameters: ``start``, ``end``, and ``periods``, exactly two\n must be specified.\n\n To learn more about the frequency strings, please see `this link\n <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.\n\n Returns\n -------\n rng : DatetimeIndex\n \"\"\"\n warnings.warn(\"cdate_range is deprecated and will be removed in a future \"\n \"version, instead use pd.bdate_range(..., freq='{freq}')\"\n .format(freq=freq), FutureWarning, stacklevel=2)\n\n if freq == 'C':\n holidays = kwargs.pop('holidays', [])\n weekmask = kwargs.pop('weekmask', 'Mon Tue Wed Thu Fri')\n freq = CDay(holidays=holidays, weekmask=weekmask)\n return DatetimeIndex(start=start, end=end, periods=periods, freq=freq,\n tz=tz, normalize=normalize, name=name,\n closed=closed, **kwargs)\n\n\n_CACHE_START = Timestamp(datetime(1950, 1, 1))\n_CACHE_END = Timestamp(datetime(2030, 1, 1))\n\n_daterange_cache = {}\n\n\ndef _naive_in_cache_range(start, end):\n if start is None or end is None:\n return False\n else:\n if start.tzinfo is not None or end.tzinfo is not None:\n return False\n return start > _CACHE_START and end < _CACHE_END\n\n\ndef _time_to_micros(time):\n seconds = time.hour * 60 * 60 + 60 * time.minute + time.second\n return 1000000 * seconds + time.microsecond\n",
"\"\"\"\nQuantilization functions and related stuff\n\"\"\"\nfrom functools import partial\n\nfrom pandas.core.dtypes.missing import isna\nfrom pandas.core.dtypes.common import (\n is_integer,\n is_scalar,\n is_categorical_dtype,\n is_datetime64_dtype,\n is_timedelta64_dtype,\n is_datetime64tz_dtype,\n is_datetime_or_timedelta_dtype,\n ensure_int64)\n\nimport pandas.core.algorithms as algos\nimport pandas.core.nanops as nanops\nfrom pandas._libs.lib import infer_dtype\nfrom pandas import (to_timedelta, to_datetime,\n Categorical, Timestamp, Timedelta,\n Series, Index, Interval, IntervalIndex)\n\nimport numpy as np\n\n\ndef cut(x, bins, right=True, labels=None, retbins=False, precision=3,\n include_lowest=False, duplicates='raise'):\n \"\"\"\n Bin values into discrete intervals.\n\n Use `cut` when you need to segment and sort data values into bins. This\n function is also useful for going from a continuous variable to a\n categorical variable. For example, `cut` could convert ages to groups of\n age ranges. Supports binning into an equal number of bins, or a\n pre-specified array of bins.\n\n Parameters\n ----------\n x : array-like\n The input array to be binned. Must be 1-dimensional.\n bins : int, sequence of scalars, or pandas.IntervalIndex\n The criteria to bin by.\n\n * int : Defines the number of equal-width bins in the range of `x`. The\n range of `x` is extended by .1% on each side to include the minimum\n and maximum values of `x`.\n * sequence of scalars : Defines the bin edges allowing for non-uniform\n width. No extension of the range of `x` is done.\n * IntervalIndex : Defines the exact bins to be used.\n\n right : bool, default True\n Indicates whether `bins` includes the rightmost edge or not. If\n ``right == True`` (the default), then the `bins` ``[1, 2, 3, 4]``\n indicate (1,2], (2,3], (3,4]. This argument is ignored when\n `bins` is an IntervalIndex.\n labels : array or bool, optional\n Specifies the labels for the returned bins. Must be the same length as\n the resulting bins. If False, returns only integer indicators of the\n bins. This affects the type of the output container (see below).\n This argument is ignored when `bins` is an IntervalIndex.\n retbins : bool, default False\n Whether to return the bins or not. Useful when bins is provided\n as a scalar.\n precision : int, default 3\n The precision at which to store and display the bins labels.\n include_lowest : bool, default False\n Whether the first interval should be left-inclusive or not.\n duplicates : {default 'raise', 'drop'}, optional\n If bin edges are not unique, raise ValueError or drop non-uniques.\n\n .. versionadded:: 0.23.0\n\n Returns\n -------\n out : pandas.Categorical, Series, or ndarray\n An array-like object representing the respective bin for each value\n of `x`. The type depends on the value of `labels`.\n\n * True (default) : returns a Series for Series `x` or a\n pandas.Categorical for all other inputs. The values stored within\n are Interval dtype.\n\n * sequence of scalars : returns a Series for Series `x` or a\n pandas.Categorical for all other inputs. The values stored within\n are whatever the type in the sequence is.\n\n * False : returns an ndarray of integers.\n\n bins : numpy.ndarray or IntervalIndex.\n The computed or specified bins. Only returned when `retbins=True`.\n For scalar or sequence `bins`, this is an ndarray with the computed\n bins. If set `duplicates=drop`, `bins` will drop non-unique bin. For\n an IntervalIndex `bins`, this is equal to `bins`.\n\n See Also\n --------\n qcut : Discretize variable into equal-sized buckets based on rank\n or based on sample quantiles.\n pandas.Categorical : Array type for storing data that come from a\n fixed set of values.\n Series : One-dimensional array with axis labels (including time series).\n pandas.IntervalIndex : Immutable Index implementing an ordered,\n sliceable set.\n\n Notes\n -----\n Any NA values will be NA in the result. Out of bounds values will be NA in\n the resulting Series or pandas.Categorical object.\n\n Examples\n --------\n Discretize into three equal-sized bins.\n\n >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3)\n ... # doctest: +ELLIPSIS\n [(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...\n Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ...\n\n >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True)\n ... # doctest: +ELLIPSIS\n ([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...\n Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ...\n array([0.994, 3. , 5. , 7. ]))\n\n Discovers the same bins, but assign them specific labels. Notice that\n the returned Categorical's categories are `labels` and is ordered.\n\n >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]),\n ... 3, labels=[\"bad\", \"medium\", \"good\"])\n [bad, good, medium, medium, good, bad]\n Categories (3, object): [bad < medium < good]\n\n ``labels=False`` implies you just want the bins back.\n\n >>> pd.cut([0, 1, 1, 2], bins=4, labels=False)\n array([0, 1, 1, 3])\n\n Passing a Series as an input returns a Series with categorical dtype:\n\n >>> s = pd.Series(np.array([2, 4, 6, 8, 10]),\n ... index=['a', 'b', 'c', 'd', 'e'])\n >>> pd.cut(s, 3)\n ... # doctest: +ELLIPSIS\n a (1.992, 4.667]\n b (1.992, 4.667]\n c (4.667, 7.333]\n d (7.333, 10.0]\n e (7.333, 10.0]\n dtype: category\n Categories (3, interval[float64]): [(1.992, 4.667] < (4.667, ...\n\n Passing a Series as an input returns a Series with mapping value.\n It is used to map numerically to intervals based on bins.\n\n >>> s = pd.Series(np.array([2, 4, 6, 8, 10]),\n ... index=['a', 'b', 'c', 'd', 'e'])\n >>> pd.cut(s, [0, 2, 4, 6, 8, 10], labels=False, retbins=True, right=False)\n ... # doctest: +ELLIPSIS\n (a 0.0\n b 1.0\n c 2.0\n d 3.0\n e 4.0\n dtype: float64, array([0, 2, 4, 6, 8]))\n\n Use `drop` optional when bins is not unique\n\n >>> pd.cut(s, [0, 2, 4, 6, 10, 10], labels=False, retbins=True,\n ... right=False, duplicates='drop')\n ... # doctest: +ELLIPSIS\n (a 0.0\n b 1.0\n c 2.0\n d 3.0\n e 3.0\n dtype: float64, array([0, 2, 4, 6, 8]))\n\n Passing an IntervalIndex for `bins` results in those categories exactly.\n Notice that values not covered by the IntervalIndex are set to NaN. 0\n is to the left of the first bin (which is closed on the right), and 1.5\n falls between two bins.\n\n >>> bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)])\n >>> pd.cut([0, 0.5, 1.5, 2.5, 4.5], bins)\n [NaN, (0, 1], NaN, (2, 3], (4, 5]]\n Categories (3, interval[int64]): [(0, 1] < (2, 3] < (4, 5]]\n \"\"\"\n # NOTE: this binning code is changed a bit from histogram for var(x) == 0\n\n # for handling the cut for datetime and timedelta objects\n x_is_series, series_index, name, x = _preprocess_for_cut(x)\n x, dtype = _coerce_to_type(x)\n\n if not np.iterable(bins):\n if is_scalar(bins) and bins < 1:\n raise ValueError(\"`bins` should be a positive integer.\")\n\n try: # for array-like\n sz = x.size\n except AttributeError:\n x = np.asarray(x)\n sz = x.size\n\n if sz == 0:\n raise ValueError('Cannot cut empty array')\n\n rng = (nanops.nanmin(x), nanops.nanmax(x))\n mn, mx = [mi + 0.0 for mi in rng]\n\n if mn == mx: # adjust end points before binning\n mn -= .001 * abs(mn) if mn != 0 else .001\n mx += .001 * abs(mx) if mx != 0 else .001\n bins = np.linspace(mn, mx, bins + 1, endpoint=True)\n else: # adjust end points after binning\n bins = np.linspace(mn, mx, bins + 1, endpoint=True)\n adj = (mx - mn) * 0.001 # 0.1% of the range\n if right:\n bins[0] -= adj\n else:\n bins[-1] += adj\n\n elif isinstance(bins, IntervalIndex):\n pass\n else:\n bins = np.asarray(bins)\n bins = _convert_bin_to_numeric_type(bins, dtype)\n if (np.diff(bins) < 0).any():\n raise ValueError('bins must increase monotonically.')\n\n fac, bins = _bins_to_cuts(x, bins, right=right, labels=labels,\n precision=precision,\n include_lowest=include_lowest,\n dtype=dtype,\n duplicates=duplicates)\n\n return _postprocess_for_cut(fac, bins, retbins, x_is_series,\n series_index, name, dtype)\n\n\ndef qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise'):\n \"\"\"\n Quantile-based discretization function. Discretize variable into\n equal-sized buckets based on rank or based on sample quantiles. For example\n 1000 values for 10 quantiles would produce a Categorical object indicating\n quantile membership for each data point.\n\n Parameters\n ----------\n x : 1d ndarray or Series\n q : integer or array of quantiles\n Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately\n array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles\n labels : array or boolean, default None\n Used as labels for the resulting bins. Must be of the same length as\n the resulting bins. If False, return only integer indicators of the\n bins.\n retbins : bool, optional\n Whether to return the (bins, labels) or not. Can be useful if bins\n is given as a scalar.\n precision : int, optional\n The precision at which to store and display the bins labels\n duplicates : {default 'raise', 'drop'}, optional\n If bin edges are not unique, raise ValueError or drop non-uniques.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n out : Categorical or Series or array of integers if labels is False\n The return type (Categorical or Series) depends on the input: a Series\n of type category if input is a Series else Categorical. Bins are\n represented as categories when categorical data is returned.\n bins : ndarray of floats\n Returned only if `retbins` is True.\n\n Notes\n -----\n Out of bounds values will be NA in the resulting Categorical object\n\n Examples\n --------\n >>> pd.qcut(range(5), 4)\n ... # doctest: +ELLIPSIS\n [(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]]\n Categories (4, interval[float64]): [(-0.001, 1.0] < (1.0, 2.0] ...\n\n >>> pd.qcut(range(5), 3, labels=[\"good\", \"medium\", \"bad\"])\n ... # doctest: +SKIP\n [good, good, medium, bad, bad]\n Categories (3, object): [good < medium < bad]\n\n >>> pd.qcut(range(5), 4, labels=False)\n array([0, 0, 1, 2, 3])\n \"\"\"\n x_is_series, series_index, name, x = _preprocess_for_cut(x)\n\n x, dtype = _coerce_to_type(x)\n\n if is_integer(q):\n quantiles = np.linspace(0, 1, q + 1)\n else:\n quantiles = q\n bins = algos.quantile(x, quantiles)\n fac, bins = _bins_to_cuts(x, bins, labels=labels,\n precision=precision, include_lowest=True,\n dtype=dtype, duplicates=duplicates)\n\n return _postprocess_for_cut(fac, bins, retbins, x_is_series,\n series_index, name, dtype)\n\n\ndef _bins_to_cuts(x, bins, right=True, labels=None,\n precision=3, include_lowest=False,\n dtype=None, duplicates='raise'):\n\n if duplicates not in ['raise', 'drop']:\n raise ValueError(\"invalid value for 'duplicates' parameter, \"\n \"valid options are: raise, drop\")\n\n if isinstance(bins, IntervalIndex):\n # we have a fast-path here\n ids = bins.get_indexer(x)\n result = algos.take_nd(bins, ids)\n result = Categorical(result, categories=bins, ordered=True)\n return result, bins\n\n unique_bins = algos.unique(bins)\n if len(unique_bins) < len(bins) and len(bins) != 2:\n if duplicates == 'raise':\n raise ValueError(\"Bin edges must be unique: {bins!r}.\\nYou \"\n \"can drop duplicate edges by setting \"\n \"the 'duplicates' kwarg\".format(bins=bins))\n else:\n bins = unique_bins\n\n side = 'left' if right else 'right'\n ids = ensure_int64(bins.searchsorted(x, side=side))\n\n if include_lowest:\n # Numpy 1.9 support: ensure this mask is a Numpy array\n ids[np.asarray(x == bins[0])] = 1\n\n na_mask = isna(x) | (ids == len(bins)) | (ids == 0)\n has_nas = na_mask.any()\n\n if labels is not False:\n if labels is None:\n labels = _format_labels(bins, precision, right=right,\n include_lowest=include_lowest,\n dtype=dtype)\n else:\n if len(labels) != len(bins) - 1:\n raise ValueError('Bin labels must be one fewer than '\n 'the number of bin edges')\n if not is_categorical_dtype(labels):\n labels = Categorical(labels, categories=labels, ordered=True)\n\n np.putmask(ids, na_mask, 0)\n result = algos.take_nd(labels, ids - 1)\n\n else:\n result = ids - 1\n if has_nas:\n result = result.astype(np.float64)\n np.putmask(result, na_mask, np.nan)\n\n return result, bins\n\n\ndef _trim_zeros(x):\n while len(x) > 1 and x[-1] == '0':\n x = x[:-1]\n if len(x) > 1 and x[-1] == '.':\n x = x[:-1]\n return x\n\n\ndef _coerce_to_type(x):\n \"\"\"\n if the passed data is of datetime/timedelta type,\n this method converts it to numeric so that cut method can\n handle it\n \"\"\"\n dtype = None\n\n if is_datetime64tz_dtype(x):\n dtype = x.dtype\n elif is_datetime64_dtype(x):\n x = to_datetime(x)\n dtype = np.datetime64\n elif is_timedelta64_dtype(x):\n x = to_timedelta(x)\n dtype = np.timedelta64\n\n if dtype is not None:\n # GH 19768: force NaT to NaN during integer conversion\n x = np.where(x.notna(), x.view(np.int64), np.nan)\n\n return x, dtype\n\n\ndef _convert_bin_to_numeric_type(bins, dtype):\n \"\"\"\n if the passed bin is of datetime/timedelta type,\n this method converts it to integer\n\n Parameters\n ----------\n bins : list-like of bins\n dtype : dtype of data\n\n Raises\n ------\n ValueError if bins are not of a compat dtype to dtype\n \"\"\"\n bins_dtype = infer_dtype(bins)\n if is_timedelta64_dtype(dtype):\n if bins_dtype in ['timedelta', 'timedelta64']:\n bins = to_timedelta(bins).view(np.int64)\n else:\n raise ValueError(\"bins must be of timedelta64 dtype\")\n elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):\n if bins_dtype in ['datetime', 'datetime64']:\n bins = to_datetime(bins).view(np.int64)\n else:\n raise ValueError(\"bins must be of datetime64 dtype\")\n\n return bins\n\n\ndef _convert_bin_to_datelike_type(bins, dtype):\n \"\"\"\n Convert bins to a DatetimeIndex or TimedeltaIndex if the orginal dtype is\n datelike\n\n Parameters\n ----------\n bins : list-like of bins\n dtype : dtype of data\n\n Returns\n -------\n bins : Array-like of bins, DatetimeIndex or TimedeltaIndex if dtype is\n datelike\n \"\"\"\n if is_datetime64tz_dtype(dtype) or is_datetime_or_timedelta_dtype(dtype):\n bins = Index(bins.astype(np.int64), dtype=dtype)\n return bins\n\n\ndef _format_labels(bins, precision, right=True,\n include_lowest=False, dtype=None):\n \"\"\" based on the dtype, return our labels \"\"\"\n\n closed = 'right' if right else 'left'\n\n if is_datetime64tz_dtype(dtype):\n formatter = partial(Timestamp, tz=dtype.tz)\n adjust = lambda x: x - Timedelta('1ns')\n elif is_datetime64_dtype(dtype):\n formatter = Timestamp\n adjust = lambda x: x - Timedelta('1ns')\n elif is_timedelta64_dtype(dtype):\n formatter = Timedelta\n adjust = lambda x: x - Timedelta('1ns')\n else:\n precision = _infer_precision(precision, bins)\n formatter = lambda x: _round_frac(x, precision)\n adjust = lambda x: x - 10 ** (-precision)\n\n breaks = [formatter(b) for b in bins]\n labels = IntervalIndex.from_breaks(breaks, closed=closed)\n\n if right and include_lowest:\n # we will adjust the left hand side by precision to\n # account that we are all right closed\n v = adjust(labels[0].left)\n\n i = IntervalIndex([Interval(v, labels[0].right, closed='right')])\n labels = i.append(labels[1:])\n\n return labels\n\n\ndef _preprocess_for_cut(x):\n \"\"\"\n handles preprocessing for cut where we convert passed\n input to array, strip the index information and store it\n separately\n \"\"\"\n x_is_series = isinstance(x, Series)\n series_index = None\n name = None\n\n if x_is_series:\n series_index = x.index\n name = x.name\n\n # Check that the passed array is a Pandas or Numpy object\n # We don't want to strip away a Pandas data-type here (e.g. datetimetz)\n ndim = getattr(x, 'ndim', None)\n if ndim is None:\n x = np.asarray(x)\n if x.ndim != 1:\n raise ValueError(\"Input array must be 1 dimensional\")\n\n return x_is_series, series_index, name, x\n\n\ndef _postprocess_for_cut(fac, bins, retbins, x_is_series,\n series_index, name, dtype):\n \"\"\"\n handles post processing for the cut method where\n we combine the index information if the originally passed\n datatype was a series\n \"\"\"\n if x_is_series:\n fac = Series(fac, index=series_index, name=name)\n\n if not retbins:\n return fac\n\n bins = _convert_bin_to_datelike_type(bins, dtype)\n\n return fac, bins\n\n\ndef _round_frac(x, precision):\n \"\"\"\n Round the fractional part of the given number\n \"\"\"\n if not np.isfinite(x) or x == 0:\n return x\n else:\n frac, whole = np.modf(x)\n if whole == 0:\n digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision\n else:\n digits = precision\n return np.around(x, digits)\n\n\ndef _infer_precision(base_precision, bins):\n \"\"\"Infer an appropriate precision for _round_frac\n \"\"\"\n for precision in range(base_precision, 20):\n levels = [_round_frac(b, precision) for b in bins]\n if algos.unique(levels).size == bins.size:\n return precision\n return base_precision # default\n",
"import pytest\nimport numpy as np\n\nimport pandas as pd\nfrom pandas.core.internals import ExtensionBlock\n\nfrom .base import BaseExtensionTests\n\n\nclass BaseReshapingTests(BaseExtensionTests):\n \"\"\"Tests for reshaping and concatenation.\"\"\"\n @pytest.mark.parametrize('in_frame', [True, False])\n def test_concat(self, data, in_frame):\n wrapped = pd.Series(data)\n if in_frame:\n wrapped = pd.DataFrame(wrapped)\n result = pd.concat([wrapped, wrapped], ignore_index=True)\n\n assert len(result) == len(data) * 2\n\n if in_frame:\n dtype = result.dtypes[0]\n else:\n dtype = result.dtype\n\n assert dtype == data.dtype\n assert isinstance(result._data.blocks[0], ExtensionBlock)\n\n @pytest.mark.parametrize('in_frame', [True, False])\n def test_concat_all_na_block(self, data_missing, in_frame):\n valid_block = pd.Series(data_missing.take([1, 1]), index=[0, 1])\n na_block = pd.Series(data_missing.take([0, 0]), index=[2, 3])\n if in_frame:\n valid_block = pd.DataFrame({\"a\": valid_block})\n na_block = pd.DataFrame({\"a\": na_block})\n result = pd.concat([valid_block, na_block])\n if in_frame:\n expected = pd.DataFrame({\"a\": data_missing.take([1, 1, 0, 0])})\n self.assert_frame_equal(result, expected)\n else:\n expected = pd.Series(data_missing.take([1, 1, 0, 0]))\n self.assert_series_equal(result, expected)\n\n def test_concat_mixed_dtypes(self, data):\n # https://github.com/pandas-dev/pandas/issues/20762\n df1 = pd.DataFrame({'A': data[:3]})\n df2 = pd.DataFrame({\"A\": [1, 2, 3]})\n df3 = pd.DataFrame({\"A\": ['a', 'b', 'c']}).astype('category')\n df4 = pd.DataFrame({\"A\": pd.SparseArray([1, 2, 3])})\n dfs = [df1, df2, df3, df4]\n\n # dataframes\n result = pd.concat(dfs)\n expected = pd.concat([x.astype(object) for x in dfs])\n self.assert_frame_equal(result, expected)\n\n # series\n result = pd.concat([x['A'] for x in dfs])\n expected = pd.concat([x['A'].astype(object) for x in dfs])\n self.assert_series_equal(result, expected)\n\n # simple test for just EA and one other\n result = pd.concat([df1, df2])\n expected = pd.concat([df1.astype('object'), df2.astype('object')])\n self.assert_frame_equal(result, expected)\n\n result = pd.concat([df1['A'], df2['A']])\n expected = pd.concat([df1['A'].astype('object'),\n df2['A'].astype('object')])\n self.assert_series_equal(result, expected)\n\n def test_concat_columns(self, data, na_value):\n df1 = pd.DataFrame({'A': data[:3]})\n df2 = pd.DataFrame({'B': [1, 2, 3]})\n\n expected = pd.DataFrame({'A': data[:3], 'B': [1, 2, 3]})\n result = pd.concat([df1, df2], axis=1)\n self.assert_frame_equal(result, expected)\n result = pd.concat([df1['A'], df2['B']], axis=1)\n self.assert_frame_equal(result, expected)\n\n # non-aligned\n df2 = pd.DataFrame({'B': [1, 2, 3]}, index=[1, 2, 3])\n expected = pd.DataFrame({\n 'A': data._from_sequence(list(data[:3]) + [na_value],\n dtype=data.dtype),\n 'B': [np.nan, 1, 2, 3]})\n\n result = pd.concat([df1, df2], axis=1)\n self.assert_frame_equal(result, expected)\n result = pd.concat([df1['A'], df2['B']], axis=1)\n self.assert_frame_equal(result, expected)\n\n def test_align(self, data, na_value):\n a = data[:3]\n b = data[2:5]\n r1, r2 = pd.Series(a).align(pd.Series(b, index=[1, 2, 3]))\n\n # Assumes that the ctor can take a list of scalars of the type\n e1 = pd.Series(data._from_sequence(list(a) + [na_value],\n dtype=data.dtype))\n e2 = pd.Series(data._from_sequence([na_value] + list(b),\n dtype=data.dtype))\n self.assert_series_equal(r1, e1)\n self.assert_series_equal(r2, e2)\n\n def test_align_frame(self, data, na_value):\n a = data[:3]\n b = data[2:5]\n r1, r2 = pd.DataFrame({'A': a}).align(\n pd.DataFrame({'A': b}, index=[1, 2, 3])\n )\n\n # Assumes that the ctor can take a list of scalars of the type\n e1 = pd.DataFrame({'A': data._from_sequence(list(a) + [na_value],\n dtype=data.dtype)})\n e2 = pd.DataFrame({'A': data._from_sequence([na_value] + list(b),\n dtype=data.dtype)})\n self.assert_frame_equal(r1, e1)\n self.assert_frame_equal(r2, e2)\n\n def test_align_series_frame(self, data, na_value):\n # https://github.com/pandas-dev/pandas/issues/20576\n ser = pd.Series(data, name='a')\n df = pd.DataFrame({\"col\": np.arange(len(ser) + 1)})\n r1, r2 = ser.align(df)\n\n e1 = pd.Series(data._from_sequence(list(data) + [na_value],\n dtype=data.dtype),\n name=ser.name)\n\n self.assert_series_equal(r1, e1)\n self.assert_frame_equal(r2, df)\n\n def test_set_frame_expand_regular_with_extension(self, data):\n df = pd.DataFrame({\"A\": [1] * len(data)})\n df['B'] = data\n expected = pd.DataFrame({\"A\": [1] * len(data), \"B\": data})\n self.assert_frame_equal(df, expected)\n\n def test_set_frame_expand_extension_with_regular(self, data):\n df = pd.DataFrame({'A': data})\n df['B'] = [1] * len(data)\n expected = pd.DataFrame({\"A\": data, \"B\": [1] * len(data)})\n self.assert_frame_equal(df, expected)\n\n def test_set_frame_overwrite_object(self, data):\n # https://github.com/pandas-dev/pandas/issues/20555\n df = pd.DataFrame({\"A\": [1] * len(data)}, dtype=object)\n df['A'] = data\n assert df.dtypes['A'] == data.dtype\n\n def test_merge(self, data, na_value):\n # GH-20743\n df1 = pd.DataFrame({'ext': data[:3], 'int1': [1, 2, 3],\n 'key': [0, 1, 2]})\n df2 = pd.DataFrame({'int2': [1, 2, 3, 4], 'key': [0, 0, 1, 3]})\n\n res = pd.merge(df1, df2)\n exp = pd.DataFrame(\n {'int1': [1, 1, 2], 'int2': [1, 2, 3], 'key': [0, 0, 1],\n 'ext': data._from_sequence([data[0], data[0], data[1]],\n dtype=data.dtype)})\n self.assert_frame_equal(res, exp[['ext', 'int1', 'key', 'int2']])\n\n res = pd.merge(df1, df2, how='outer')\n exp = pd.DataFrame(\n {'int1': [1, 1, 2, 3, np.nan], 'int2': [1, 2, 3, np.nan, 4],\n 'key': [0, 0, 1, 2, 3],\n 'ext': data._from_sequence(\n [data[0], data[0], data[1], data[2], na_value],\n dtype=data.dtype)})\n self.assert_frame_equal(res, exp[['ext', 'int1', 'key', 'int2']])\n",
"# -*- coding: utf-8 -*-\n\nimport pytest\n\nimport numpy as np\n\nimport pandas.util.testing as tm\nfrom pandas import Categorical, CategoricalIndex, Index, Series, DataFrame\n\nfrom pandas.core.arrays.categorical import _recode_for_categories\nfrom pandas.tests.arrays.categorical.common import TestCategorical\n\n\nclass TestCategoricalAPI(object):\n\n def test_ordered_api(self):\n # GH 9347\n cat1 = Categorical(list('acb'), ordered=False)\n tm.assert_index_equal(cat1.categories, Index(['a', 'b', 'c']))\n assert not cat1.ordered\n\n cat2 = Categorical(list('acb'), categories=list('bca'), ordered=False)\n tm.assert_index_equal(cat2.categories, Index(['b', 'c', 'a']))\n assert not cat2.ordered\n\n cat3 = Categorical(list('acb'), ordered=True)\n tm.assert_index_equal(cat3.categories, Index(['a', 'b', 'c']))\n assert cat3.ordered\n\n cat4 = Categorical(list('acb'), categories=list('bca'), ordered=True)\n tm.assert_index_equal(cat4.categories, Index(['b', 'c', 'a']))\n assert cat4.ordered\n\n def test_set_ordered(self):\n\n cat = Categorical([\"a\", \"b\", \"c\", \"a\"], ordered=True)\n cat2 = cat.as_unordered()\n assert not cat2.ordered\n cat2 = cat.as_ordered()\n assert cat2.ordered\n cat2.as_unordered(inplace=True)\n assert not cat2.ordered\n cat2.as_ordered(inplace=True)\n assert cat2.ordered\n\n assert cat2.set_ordered(True).ordered\n assert not cat2.set_ordered(False).ordered\n cat2.set_ordered(True, inplace=True)\n assert cat2.ordered\n cat2.set_ordered(False, inplace=True)\n assert not cat2.ordered\n\n # removed in 0.19.0\n msg = \"can\\'t set attribute\"\n with tm.assert_raises_regex(AttributeError, msg):\n cat.ordered = True\n with tm.assert_raises_regex(AttributeError, msg):\n cat.ordered = False\n\n def test_rename_categories(self):\n cat = Categorical([\"a\", \"b\", \"c\", \"a\"])\n\n # inplace=False: the old one must not be changed\n res = cat.rename_categories([1, 2, 3])\n tm.assert_numpy_array_equal(res.__array__(), np.array([1, 2, 3, 1],\n dtype=np.int64))\n tm.assert_index_equal(res.categories, Index([1, 2, 3]))\n\n exp_cat = np.array([\"a\", \"b\", \"c\", \"a\"], dtype=np.object_)\n tm.assert_numpy_array_equal(cat.__array__(), exp_cat)\n\n exp_cat = Index([\"a\", \"b\", \"c\"])\n tm.assert_index_equal(cat.categories, exp_cat)\n\n # GH18862 (let rename_categories take callables)\n result = cat.rename_categories(lambda x: x.upper())\n expected = Categorical([\"A\", \"B\", \"C\", \"A\"])\n tm.assert_categorical_equal(result, expected)\n\n # and now inplace\n res = cat.rename_categories([1, 2, 3], inplace=True)\n assert res is None\n tm.assert_numpy_array_equal(cat.__array__(), np.array([1, 2, 3, 1],\n dtype=np.int64))\n tm.assert_index_equal(cat.categories, Index([1, 2, 3]))\n\n # Lengthen\n with pytest.raises(ValueError):\n cat.rename_categories([1, 2, 3, 4])\n\n # Shorten\n with pytest.raises(ValueError):\n cat.rename_categories([1, 2])\n\n def test_rename_categories_series(self):\n # https://github.com/pandas-dev/pandas/issues/17981\n c = Categorical(['a', 'b'])\n xpr = \"Treating Series 'new_categories' as a list-like \"\n with tm.assert_produces_warning(FutureWarning) as rec:\n result = c.rename_categories(Series([0, 1]))\n\n assert len(rec) == 1\n assert xpr in str(rec[0].message)\n expected = Categorical([0, 1])\n tm.assert_categorical_equal(result, expected)\n\n def test_rename_categories_dict(self):\n # GH 17336\n cat = Categorical(['a', 'b', 'c', 'd'])\n res = cat.rename_categories({'a': 4, 'b': 3, 'c': 2, 'd': 1})\n expected = Index([4, 3, 2, 1])\n tm.assert_index_equal(res.categories, expected)\n\n # Test for inplace\n res = cat.rename_categories({'a': 4, 'b': 3, 'c': 2, 'd': 1},\n inplace=True)\n assert res is None\n tm.assert_index_equal(cat.categories, expected)\n\n # Test for dicts of smaller length\n cat = Categorical(['a', 'b', 'c', 'd'])\n res = cat.rename_categories({'a': 1, 'c': 3})\n\n expected = Index([1, 'b', 3, 'd'])\n tm.assert_index_equal(res.categories, expected)\n\n # Test for dicts with bigger length\n cat = Categorical(['a', 'b', 'c', 'd'])\n res = cat.rename_categories({'a': 1, 'b': 2, 'c': 3,\n 'd': 4, 'e': 5, 'f': 6})\n expected = Index([1, 2, 3, 4])\n tm.assert_index_equal(res.categories, expected)\n\n # Test for dicts with no items from old categories\n cat = Categorical(['a', 'b', 'c', 'd'])\n res = cat.rename_categories({'f': 1, 'g': 3})\n\n expected = Index(['a', 'b', 'c', 'd'])\n tm.assert_index_equal(res.categories, expected)\n\n def test_reorder_categories(self):\n cat = Categorical([\"a\", \"b\", \"c\", \"a\"], ordered=True)\n old = cat.copy()\n new = Categorical([\"a\", \"b\", \"c\", \"a\"], categories=[\"c\", \"b\", \"a\"],\n ordered=True)\n\n # first inplace == False\n res = cat.reorder_categories([\"c\", \"b\", \"a\"])\n # cat must be the same as before\n tm.assert_categorical_equal(cat, old)\n # only res is changed\n tm.assert_categorical_equal(res, new)\n\n # inplace == True\n res = cat.reorder_categories([\"c\", \"b\", \"a\"], inplace=True)\n assert res is None\n tm.assert_categorical_equal(cat, new)\n\n # not all \"old\" included in \"new\"\n cat = Categorical([\"a\", \"b\", \"c\", \"a\"], ordered=True)\n\n def f():\n cat.reorder_categories([\"a\"])\n\n pytest.raises(ValueError, f)\n\n # still not all \"old\" in \"new\"\n def f():\n cat.reorder_categories([\"a\", \"b\", \"d\"])\n\n pytest.raises(ValueError, f)\n\n # all \"old\" included in \"new\", but too long\n def f():\n cat.reorder_categories([\"a\", \"b\", \"c\", \"d\"])\n\n pytest.raises(ValueError, f)\n\n def test_add_categories(self):\n cat = Categorical([\"a\", \"b\", \"c\", \"a\"], ordered=True)\n old = cat.copy()\n new = Categorical([\"a\", \"b\", \"c\", \"a\"],\n categories=[\"a\", \"b\", \"c\", \"d\"], ordered=True)\n\n # first inplace == False\n res = cat.add_categories(\"d\")\n tm.assert_categorical_equal(cat, old)\n tm.assert_categorical_equal(res, new)\n\n res = cat.add_categories([\"d\"])\n tm.assert_categorical_equal(cat, old)\n tm.assert_categorical_equal(res, new)\n\n # inplace == True\n res = cat.add_categories(\"d\", inplace=True)\n tm.assert_categorical_equal(cat, new)\n assert res is None\n\n # new is in old categories\n def f():\n cat.add_categories([\"d\"])\n\n pytest.raises(ValueError, f)\n\n # GH 9927\n cat = Categorical(list(\"abc\"), ordered=True)\n expected = Categorical(\n list(\"abc\"), categories=list(\"abcde\"), ordered=True)\n # test with Series, np.array, index, list\n res = cat.add_categories(Series([\"d\", \"e\"]))\n tm.assert_categorical_equal(res, expected)\n res = cat.add_categories(np.array([\"d\", \"e\"]))\n tm.assert_categorical_equal(res, expected)\n res = cat.add_categories(Index([\"d\", \"e\"]))\n tm.assert_categorical_equal(res, expected)\n res = cat.add_categories([\"d\", \"e\"])\n tm.assert_categorical_equal(res, expected)\n\n def test_set_categories(self):\n cat = Categorical([\"a\", \"b\", \"c\", \"a\"], ordered=True)\n exp_categories = Index([\"c\", \"b\", \"a\"])\n exp_values = np.array([\"a\", \"b\", \"c\", \"a\"], dtype=np.object_)\n\n res = cat.set_categories([\"c\", \"b\", \"a\"], inplace=True)\n tm.assert_index_equal(cat.categories, exp_categories)\n tm.assert_numpy_array_equal(cat.__array__(), exp_values)\n assert res is None\n\n res = cat.set_categories([\"a\", \"b\", \"c\"])\n # cat must be the same as before\n tm.assert_index_equal(cat.categories, exp_categories)\n tm.assert_numpy_array_equal(cat.__array__(), exp_values)\n # only res is changed\n exp_categories_back = Index([\"a\", \"b\", \"c\"])\n tm.assert_index_equal(res.categories, exp_categories_back)\n tm.assert_numpy_array_equal(res.__array__(), exp_values)\n\n # not all \"old\" included in \"new\" -> all not included ones are now\n # np.nan\n cat = Categorical([\"a\", \"b\", \"c\", \"a\"], ordered=True)\n res = cat.set_categories([\"a\"])\n tm.assert_numpy_array_equal(res.codes, np.array([0, -1, -1, 0],\n dtype=np.int8))\n\n # still not all \"old\" in \"new\"\n res = cat.set_categories([\"a\", \"b\", \"d\"])\n tm.assert_numpy_array_equal(res.codes, np.array([0, 1, -1, 0],\n dtype=np.int8))\n tm.assert_index_equal(res.categories, Index([\"a\", \"b\", \"d\"]))\n\n # all \"old\" included in \"new\"\n cat = cat.set_categories([\"a\", \"b\", \"c\", \"d\"])\n exp_categories = Index([\"a\", \"b\", \"c\", \"d\"])\n tm.assert_index_equal(cat.categories, exp_categories)\n\n # internals...\n c = Categorical([1, 2, 3, 4, 1], categories=[1, 2, 3, 4], ordered=True)\n tm.assert_numpy_array_equal(c._codes, np.array([0, 1, 2, 3, 0],\n dtype=np.int8))\n tm.assert_index_equal(c.categories, Index([1, 2, 3, 4]))\n\n exp = np.array([1, 2, 3, 4, 1], dtype=np.int64)\n tm.assert_numpy_array_equal(c.get_values(), exp)\n\n # all \"pointers\" to '4' must be changed from 3 to 0,...\n c = c.set_categories([4, 3, 2, 1])\n\n # positions are changed\n tm.assert_numpy_array_equal(c._codes, np.array([3, 2, 1, 0, 3],\n dtype=np.int8))\n\n # categories are now in new order\n tm.assert_index_equal(c.categories, Index([4, 3, 2, 1]))\n\n # output is the same\n exp = np.array([1, 2, 3, 4, 1], dtype=np.int64)\n tm.assert_numpy_array_equal(c.get_values(), exp)\n assert c.min() == 4\n assert c.max() == 1\n\n # set_categories should set the ordering if specified\n c2 = c.set_categories([4, 3, 2, 1], ordered=False)\n assert not c2.ordered\n\n tm.assert_numpy_array_equal(c.get_values(), c2.get_values())\n\n # set_categories should pass thru the ordering\n c2 = c.set_ordered(False).set_categories([4, 3, 2, 1])\n assert not c2.ordered\n\n tm.assert_numpy_array_equal(c.get_values(), c2.get_values())\n\n @pytest.mark.parametrize('values, categories, new_categories', [\n # No NaNs, same cats, same order\n (['a', 'b', 'a'], ['a', 'b'], ['a', 'b'],),\n # No NaNs, same cats, different order\n (['a', 'b', 'a'], ['a', 'b'], ['b', 'a'],),\n # Same, unsorted\n (['b', 'a', 'a'], ['a', 'b'], ['a', 'b'],),\n # No NaNs, same cats, different order\n (['b', 'a', 'a'], ['a', 'b'], ['b', 'a'],),\n # NaNs\n (['a', 'b', 'c'], ['a', 'b'], ['a', 'b']),\n (['a', 'b', 'c'], ['a', 'b'], ['b', 'a']),\n (['b', 'a', 'c'], ['a', 'b'], ['a', 'b']),\n (['b', 'a', 'c'], ['a', 'b'], ['a', 'b']),\n # Introduce NaNs\n (['a', 'b', 'c'], ['a', 'b'], ['a']),\n (['a', 'b', 'c'], ['a', 'b'], ['b']),\n (['b', 'a', 'c'], ['a', 'b'], ['a']),\n (['b', 'a', 'c'], ['a', 'b'], ['a']),\n # No overlap\n (['a', 'b', 'c'], ['a', 'b'], ['d', 'e']),\n ])\n @pytest.mark.parametrize('ordered', [True, False])\n def test_set_categories_many(self, values, categories, new_categories,\n ordered):\n c = Categorical(values, categories)\n expected = Categorical(values, new_categories, ordered)\n result = c.set_categories(new_categories, ordered=ordered)\n tm.assert_categorical_equal(result, expected)\n\n def test_set_categories_private(self):\n cat = Categorical(['a', 'b', 'c'], categories=['a', 'b', 'c', 'd'])\n cat._set_categories(['a', 'c', 'd', 'e'])\n expected = Categorical(['a', 'c', 'd'], categories=list('acde'))\n tm.assert_categorical_equal(cat, expected)\n\n # fastpath\n cat = Categorical(['a', 'b', 'c'], categories=['a', 'b', 'c', 'd'])\n cat._set_categories(['a', 'c', 'd', 'e'], fastpath=True)\n expected = Categorical(['a', 'c', 'd'], categories=list('acde'))\n tm.assert_categorical_equal(cat, expected)\n\n def test_remove_categories(self):\n cat = Categorical([\"a\", \"b\", \"c\", \"a\"], ordered=True)\n old = cat.copy()\n new = Categorical([\"a\", \"b\", np.nan, \"a\"], categories=[\"a\", \"b\"],\n ordered=True)\n\n # first inplace == False\n res = cat.remove_categories(\"c\")\n tm.assert_categorical_equal(cat, old)\n tm.assert_categorical_equal(res, new)\n\n res = cat.remove_categories([\"c\"])\n tm.assert_categorical_equal(cat, old)\n tm.assert_categorical_equal(res, new)\n\n # inplace == True\n res = cat.remove_categories(\"c\", inplace=True)\n tm.assert_categorical_equal(cat, new)\n assert res is None\n\n # removal is not in categories\n def f():\n cat.remove_categories([\"c\"])\n\n pytest.raises(ValueError, f)\n\n def test_remove_unused_categories(self):\n c = Categorical([\"a\", \"b\", \"c\", \"d\", \"a\"],\n categories=[\"a\", \"b\", \"c\", \"d\", \"e\"])\n exp_categories_all = Index([\"a\", \"b\", \"c\", \"d\", \"e\"])\n exp_categories_dropped = Index([\"a\", \"b\", \"c\", \"d\"])\n\n tm.assert_index_equal(c.categories, exp_categories_all)\n\n res = c.remove_unused_categories()\n tm.assert_index_equal(res.categories, exp_categories_dropped)\n tm.assert_index_equal(c.categories, exp_categories_all)\n\n res = c.remove_unused_categories(inplace=True)\n tm.assert_index_equal(c.categories, exp_categories_dropped)\n assert res is None\n\n # with NaN values (GH11599)\n c = Categorical([\"a\", \"b\", \"c\", np.nan],\n categories=[\"a\", \"b\", \"c\", \"d\", \"e\"])\n res = c.remove_unused_categories()\n tm.assert_index_equal(res.categories,\n Index(np.array([\"a\", \"b\", \"c\"])))\n exp_codes = np.array([0, 1, 2, -1], dtype=np.int8)\n tm.assert_numpy_array_equal(res.codes, exp_codes)\n tm.assert_index_equal(c.categories, exp_categories_all)\n\n val = ['F', np.nan, 'D', 'B', 'D', 'F', np.nan]\n cat = Categorical(values=val, categories=list('ABCDEFG'))\n out = cat.remove_unused_categories()\n tm.assert_index_equal(out.categories, Index(['B', 'D', 'F']))\n exp_codes = np.array([2, -1, 1, 0, 1, 2, -1], dtype=np.int8)\n tm.assert_numpy_array_equal(out.codes, exp_codes)\n assert out.get_values().tolist() == val\n\n alpha = list('abcdefghijklmnopqrstuvwxyz')\n val = np.random.choice(alpha[::2], 10000).astype('object')\n val[np.random.choice(len(val), 100)] = np.nan\n\n cat = Categorical(values=val, categories=alpha)\n out = cat.remove_unused_categories()\n assert out.get_values().tolist() == val.tolist()\n\n\nclass TestCategoricalAPIWithFactor(TestCategorical):\n\n def test_describe(self):\n # string type\n desc = self.factor.describe()\n assert self.factor.ordered\n exp_index = CategoricalIndex(['a', 'b', 'c'], name='categories',\n ordered=self.factor.ordered)\n expected = DataFrame({'counts': [3, 2, 3],\n 'freqs': [3 / 8., 2 / 8., 3 / 8.]},\n index=exp_index)\n tm.assert_frame_equal(desc, expected)\n\n # check unused categories\n cat = self.factor.copy()\n cat.set_categories([\"a\", \"b\", \"c\", \"d\"], inplace=True)\n desc = cat.describe()\n\n exp_index = CategoricalIndex(\n list('abcd'), ordered=self.factor.ordered, name='categories')\n expected = DataFrame({'counts': [3, 2, 3, 0],\n 'freqs': [3 / 8., 2 / 8., 3 / 8., 0]},\n index=exp_index)\n tm.assert_frame_equal(desc, expected)\n\n # check an integer one\n cat = Categorical([1, 2, 3, 1, 2, 3, 3, 2, 1, 1, 1])\n desc = cat.describe()\n exp_index = CategoricalIndex([1, 2, 3], ordered=cat.ordered,\n name='categories')\n expected = DataFrame({'counts': [5, 3, 3],\n 'freqs': [5 / 11., 3 / 11., 3 / 11.]},\n index=exp_index)\n tm.assert_frame_equal(desc, expected)\n\n # https://github.com/pandas-dev/pandas/issues/3678\n # describe should work with NaN\n cat = Categorical([np.nan, 1, 2, 2])\n desc = cat.describe()\n expected = DataFrame({'counts': [1, 2, 1],\n 'freqs': [1 / 4., 2 / 4., 1 / 4.]},\n index=CategoricalIndex([1, 2, np.nan],\n categories=[1, 2],\n name='categories'))\n tm.assert_frame_equal(desc, expected)\n\n def test_set_categories_inplace(self):\n cat = self.factor.copy()\n cat.set_categories(['a', 'b', 'c', 'd'], inplace=True)\n tm.assert_index_equal(cat.categories, Index(['a', 'b', 'c', 'd']))\n\n\nclass TestPrivateCategoricalAPI(object):\n\n def test_codes_immutable(self):\n\n # Codes should be read only\n c = Categorical([\"a\", \"b\", \"c\", \"a\", np.nan])\n exp = np.array([0, 1, 2, 0, -1], dtype='int8')\n tm.assert_numpy_array_equal(c.codes, exp)\n\n # Assignments to codes should raise\n def f():\n c.codes = np.array([0, 1, 2, 0, 1], dtype='int8')\n\n pytest.raises(ValueError, f)\n\n # changes in the codes array should raise\n # np 1.6.1 raises RuntimeError rather than ValueError\n codes = c.codes\n\n def f():\n codes[4] = 1\n\n pytest.raises(ValueError, f)\n\n # But even after getting the codes, the original array should still be\n # writeable!\n c[4] = \"a\"\n exp = np.array([0, 1, 2, 0, 0], dtype='int8')\n tm.assert_numpy_array_equal(c.codes, exp)\n c._codes[4] = 2\n exp = np.array([0, 1, 2, 0, 2], dtype='int8')\n tm.assert_numpy_array_equal(c.codes, exp)\n\n @pytest.mark.parametrize('codes, old, new, expected', [\n ([0, 1], ['a', 'b'], ['a', 'b'], [0, 1]),\n ([0, 1], ['b', 'a'], ['b', 'a'], [0, 1]),\n ([0, 1], ['a', 'b'], ['b', 'a'], [1, 0]),\n ([0, 1], ['b', 'a'], ['a', 'b'], [1, 0]),\n ([0, 1, 0, 1], ['a', 'b'], ['a', 'b', 'c'], [0, 1, 0, 1]),\n ([0, 1, 2, 2], ['a', 'b', 'c'], ['a', 'b'], [0, 1, -1, -1]),\n ([0, 1, -1], ['a', 'b', 'c'], ['a', 'b', 'c'], [0, 1, -1]),\n ([0, 1, -1], ['a', 'b', 'c'], ['b'], [-1, 0, -1]),\n ([0, 1, -1], ['a', 'b', 'c'], ['d'], [-1, -1, -1]),\n ([0, 1, -1], ['a', 'b', 'c'], [], [-1, -1, -1]),\n ([-1, -1], [], ['a', 'b'], [-1, -1]),\n ([1, 0], ['b', 'a'], ['a', 'b'], [0, 1]),\n ])\n def test_recode_to_categories(self, codes, old, new, expected):\n codes = np.asanyarray(codes, dtype=np.int8)\n expected = np.asanyarray(expected, dtype=np.int8)\n old = Index(old)\n new = Index(new)\n result = _recode_for_categories(codes, old, new)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_recode_to_categories_large(self):\n N = 1000\n codes = np.arange(N)\n old = Index(codes)\n expected = np.arange(N - 1, -1, -1, dtype=np.int16)\n new = Index(expected)\n result = _recode_for_categories(codes, old, new)\n tm.assert_numpy_array_equal(result, expected)\n",
"# ---------------------------------------------------------------------\n# JSON normalization routines\n\nimport copy\nfrom collections import defaultdict\nimport numpy as np\n\nfrom pandas._libs.writers import convert_json_to_lines\nfrom pandas import compat, DataFrame\n\n\ndef _convert_to_line_delimits(s):\n \"\"\"Helper function that converts json lists to line delimited json.\"\"\"\n\n # Determine we have a JSON list to turn to lines otherwise just return the\n # json object, only lists can\n if not s[0] == '[' and s[-1] == ']':\n return s\n s = s[1:-1]\n\n return convert_json_to_lines(s)\n\n\ndef nested_to_record(ds, prefix=\"\", sep=\".\", level=0):\n \"\"\"a simplified json_normalize\n\n converts a nested dict into a flat dict (\"record\"), unlike json_normalize,\n it does not attempt to extract a subset of the data.\n\n Parameters\n ----------\n ds : dict or list of dicts\n prefix: the prefix, optional, default: \"\"\n sep : string, default '.'\n Nested records will generate names separated by sep,\n e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar\n\n .. versionadded:: 0.20.0\n\n level: the number of levels in the jason string, optional, default: 0\n\n Returns\n -------\n d - dict or list of dicts, matching `ds`\n\n Examples\n --------\n\n IN[52]: nested_to_record(dict(flat1=1,dict1=dict(c=1,d=2),\n nested=dict(e=dict(c=1,d=2),d=2)))\n Out[52]:\n {'dict1.c': 1,\n 'dict1.d': 2,\n 'flat1': 1,\n 'nested.d': 2,\n 'nested.e.c': 1,\n 'nested.e.d': 2}\n \"\"\"\n singleton = False\n if isinstance(ds, dict):\n ds = [ds]\n singleton = True\n\n new_ds = []\n for d in ds:\n\n new_d = copy.deepcopy(d)\n for k, v in d.items():\n # each key gets renamed with prefix\n if not isinstance(k, compat.string_types):\n k = str(k)\n if level == 0:\n newkey = k\n else:\n newkey = prefix + sep + k\n\n # only dicts gets recurse-flattend\n # only at level>1 do we rename the rest of the keys\n if not isinstance(v, dict):\n if level != 0: # so we skip copying for top level, common case\n v = new_d.pop(k)\n new_d[newkey] = v\n continue\n else:\n v = new_d.pop(k)\n new_d.update(nested_to_record(v, newkey, sep, level + 1))\n new_ds.append(new_d)\n\n if singleton:\n return new_ds[0]\n return new_ds\n\n\ndef json_normalize(data, record_path=None, meta=None,\n meta_prefix=None,\n record_prefix=None,\n errors='raise',\n sep='.'):\n \"\"\"\n \"Normalize\" semi-structured JSON data into a flat table\n\n Parameters\n ----------\n data : dict or list of dicts\n Unserialized JSON objects\n record_path : string or list of strings, default None\n Path in each object to list of records. If not passed, data will be\n assumed to be an array of records\n meta : list of paths (string or list of strings), default None\n Fields to use as metadata for each record in resulting table\n record_prefix : string, default None\n If True, prefix records with dotted (?) path, e.g. foo.bar.field if\n path to records is ['foo', 'bar']\n meta_prefix : string, default None\n errors : {'raise', 'ignore'}, default 'raise'\n\n * 'ignore' : will ignore KeyError if keys listed in meta are not\n always present\n * 'raise' : will raise KeyError if keys listed in meta are not\n always present\n\n .. versionadded:: 0.20.0\n\n sep : string, default '.'\n Nested records will generate names separated by sep,\n e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar\n\n .. versionadded:: 0.20.0\n\n\n Returns\n -------\n frame : DataFrame\n\n Examples\n --------\n\n >>> from pandas.io.json import json_normalize\n >>> data = [{'id': 1, 'name': {'first': 'Coleen', 'last': 'Volk'}},\n ... {'name': {'given': 'Mose', 'family': 'Regner'}},\n ... {'id': 2, 'name': 'Faye Raker'}]\n >>> json_normalize(data)\n id name name.family name.first name.given name.last\n 0 1.0 NaN NaN Coleen NaN Volk\n 1 NaN NaN Regner NaN Mose NaN\n 2 2.0 Faye Raker NaN NaN NaN NaN\n\n >>> data = [{'state': 'Florida',\n ... 'shortname': 'FL',\n ... 'info': {\n ... 'governor': 'Rick Scott'\n ... },\n ... 'counties': [{'name': 'Dade', 'population': 12345},\n ... {'name': 'Broward', 'population': 40000},\n ... {'name': 'Palm Beach', 'population': 60000}]},\n ... {'state': 'Ohio',\n ... 'shortname': 'OH',\n ... 'info': {\n ... 'governor': 'John Kasich'\n ... },\n ... 'counties': [{'name': 'Summit', 'population': 1234},\n ... {'name': 'Cuyahoga', 'population': 1337}]}]\n >>> result = json_normalize(data, 'counties', ['state', 'shortname',\n ... ['info', 'governor']])\n >>> result\n name population info.governor state shortname\n 0 Dade 12345 Rick Scott Florida FL\n 1 Broward 40000 Rick Scott Florida FL\n 2 Palm Beach 60000 Rick Scott Florida FL\n 3 Summit 1234 John Kasich Ohio OH\n 4 Cuyahoga 1337 John Kasich Ohio OH\n\n >>> data = {'A': [1, 2]}\n >>> json_normalize(data, 'A', record_prefix='Prefix.')\n Prefix.0\n 0 1\n 1 2\n \"\"\"\n def _pull_field(js, spec):\n result = js\n if isinstance(spec, list):\n for field in spec:\n result = result[field]\n else:\n result = result[spec]\n\n return result\n\n if isinstance(data, list) and not data:\n return DataFrame()\n\n # A bit of a hackjob\n if isinstance(data, dict):\n data = [data]\n\n if record_path is None:\n if any([isinstance(x, dict)\n for x in compat.itervalues(y)] for y in data):\n # naive normalization, this is idempotent for flat records\n # and potentially will inflate the data considerably for\n # deeply nested structures:\n # {VeryLong: { b: 1,c:2}} -> {VeryLong.b:1 ,VeryLong.c:@}\n #\n # TODO: handle record value which are lists, at least error\n # reasonably\n data = nested_to_record(data, sep=sep)\n return DataFrame(data)\n elif not isinstance(record_path, list):\n record_path = [record_path]\n\n if meta is None:\n meta = []\n elif not isinstance(meta, list):\n meta = [meta]\n\n meta = [m if isinstance(m, list) else [m] for m in meta]\n\n # Disastrously inefficient for now\n records = []\n lengths = []\n\n meta_vals = defaultdict(list)\n if not isinstance(sep, compat.string_types):\n sep = str(sep)\n meta_keys = [sep.join(val) for val in meta]\n\n def _recursive_extract(data, path, seen_meta, level=0):\n if len(path) > 1:\n for obj in data:\n for val, key in zip(meta, meta_keys):\n if level + 1 == len(val):\n seen_meta[key] = _pull_field(obj, val[-1])\n\n _recursive_extract(obj[path[0]], path[1:],\n seen_meta, level=level + 1)\n else:\n for obj in data:\n recs = _pull_field(obj, path[0])\n\n # For repeating the metadata later\n lengths.append(len(recs))\n\n for val, key in zip(meta, meta_keys):\n if level + 1 > len(val):\n meta_val = seen_meta[key]\n else:\n try:\n meta_val = _pull_field(obj, val[level:])\n except KeyError as e:\n if errors == 'ignore':\n meta_val = np.nan\n else:\n raise \\\n KeyError(\"Try running with \"\n \"errors='ignore' as key \"\n \"{err} is not always present\"\n .format(err=e))\n meta_vals[key].append(meta_val)\n\n records.extend(recs)\n\n _recursive_extract(data, record_path, {}, level=0)\n\n result = DataFrame(records)\n\n if record_prefix is not None:\n result = result.rename(\n columns=lambda x: \"{p}{c}\".format(p=record_prefix, c=x))\n\n # Data types, a problem\n for k, v in compat.iteritems(meta_vals):\n if meta_prefix is not None:\n k = meta_prefix + k\n\n if k in result:\n raise ValueError('Conflicting metadata name {name}, '\n 'need distinguishing prefix '.format(name=k))\n\n result[k] = np.array(v).repeat(lengths)\n\n return result\n",
"import numpy as np\n\nfrom pandas.core.dtypes.common import is_list_like\n\nfrom pandas.compat import reduce\nfrom pandas.core import common as com\n\n\ndef cartesian_product(X):\n \"\"\"\n Numpy version of itertools.product or pandas.compat.product.\n Sometimes faster (for large inputs)...\n\n Parameters\n ----------\n X : list-like of list-likes\n\n Returns\n -------\n product : list of ndarrays\n\n Examples\n --------\n >>> cartesian_product([list('ABC'), [1, 2]])\n [array(['A', 'A', 'B', 'B', 'C', 'C'], dtype='|S1'),\n array([1, 2, 1, 2, 1, 2])]\n\n See also\n --------\n itertools.product : Cartesian product of input iterables. Equivalent to\n nested for-loops.\n pandas.compat.product : An alias for itertools.product.\n \"\"\"\n msg = \"Input must be a list-like of list-likes\"\n if not is_list_like(X):\n raise TypeError(msg)\n for x in X:\n if not is_list_like(x):\n raise TypeError(msg)\n\n if len(X) == 0:\n return []\n\n lenX = np.fromiter((len(x) for x in X), dtype=np.intp)\n cumprodX = np.cumproduct(lenX)\n\n a = np.roll(cumprodX, 1)\n a[0] = 1\n\n if cumprodX[-1] != 0:\n b = cumprodX[-1] / cumprodX\n else:\n # if any factor is empty, the cartesian product is empty\n b = np.zeros_like(cumprodX)\n\n return [np.tile(np.repeat(np.asarray(com.values_from_object(x)), b[i]),\n np.product(a[i]))\n for i, x in enumerate(X)]\n\n\ndef _compose2(f, g):\n \"\"\"Compose 2 callables\"\"\"\n return lambda *args, **kwargs: f(g(*args, **kwargs))\n\n\ndef compose(*funcs):\n \"\"\"Compose 2 or more callables\"\"\"\n assert len(funcs) > 1, 'At least 2 callables must be passed to compose'\n return reduce(_compose2, funcs)\n",
"# -*- coding: utf-8 -*-\n\nimport warnings\nfrom itertools import product\nimport pytest\n\nimport numpy as np\n\nfrom pandas.compat import range, u\nfrom pandas import MultiIndex, DatetimeIndex\nfrom pandas._libs import hashtable\nimport pandas.util.testing as tm\n\n\[email protected]('names', [None, ['first', 'second']])\ndef test_unique(names):\n mi = MultiIndex.from_arrays([[1, 2, 1, 2], [1, 1, 1, 2]], names=names)\n\n res = mi.unique()\n exp = MultiIndex.from_arrays([[1, 2, 2], [1, 1, 2]], names=mi.names)\n tm.assert_index_equal(res, exp)\n\n mi = MultiIndex.from_arrays([list('aaaa'), list('abab')],\n names=names)\n res = mi.unique()\n exp = MultiIndex.from_arrays([list('aa'), list('ab')], names=mi.names)\n tm.assert_index_equal(res, exp)\n\n mi = MultiIndex.from_arrays([list('aaaa'), list('aaaa')], names=names)\n res = mi.unique()\n exp = MultiIndex.from_arrays([['a'], ['a']], names=mi.names)\n tm.assert_index_equal(res, exp)\n\n # GH #20568 - empty MI\n mi = MultiIndex.from_arrays([[], []], names=names)\n res = mi.unique()\n tm.assert_index_equal(mi, res)\n\n\ndef test_unique_datetimelike():\n idx1 = DatetimeIndex(['2015-01-01', '2015-01-01', '2015-01-01',\n '2015-01-01', 'NaT', 'NaT'])\n idx2 = DatetimeIndex(['2015-01-01', '2015-01-01', '2015-01-02',\n '2015-01-02', 'NaT', '2015-01-01'],\n tz='Asia/Tokyo')\n result = MultiIndex.from_arrays([idx1, idx2]).unique()\n\n eidx1 = DatetimeIndex(['2015-01-01', '2015-01-01', 'NaT', 'NaT'])\n eidx2 = DatetimeIndex(['2015-01-01', '2015-01-02',\n 'NaT', '2015-01-01'],\n tz='Asia/Tokyo')\n exp = MultiIndex.from_arrays([eidx1, eidx2])\n tm.assert_index_equal(result, exp)\n\n\[email protected]('level', [0, 'first', 1, 'second'])\ndef test_unique_level(idx, level):\n # GH #17896 - with level= argument\n result = idx.unique(level=level)\n expected = idx.get_level_values(level).unique()\n tm.assert_index_equal(result, expected)\n\n # With already unique level\n mi = MultiIndex.from_arrays([[1, 3, 2, 4], [1, 3, 2, 5]],\n names=['first', 'second'])\n result = mi.unique(level=level)\n expected = mi.get_level_values(level)\n tm.assert_index_equal(result, expected)\n\n # With empty MI\n mi = MultiIndex.from_arrays([[], []], names=['first', 'second'])\n result = mi.unique(level=level)\n expected = mi.get_level_values(level)\n\n\[email protected]('dropna', [True, False])\ndef test_get_unique_index(idx, dropna):\n mi = idx[[0, 1, 0, 1, 1, 0, 0]]\n expected = mi._shallow_copy(mi[[0, 1]])\n\n result = mi._get_unique_index(dropna=dropna)\n assert result.unique\n tm.assert_index_equal(result, expected)\n\n\ndef test_duplicate_multiindex_labels():\n # GH 17464\n # Make sure that a MultiIndex with duplicate levels throws a ValueError\n with pytest.raises(ValueError):\n mi = MultiIndex([['A'] * 10, range(10)], [[0] * 10, range(10)])\n\n # And that using set_levels with duplicate levels fails\n mi = MultiIndex.from_arrays([['A', 'A', 'B', 'B', 'B'],\n [1, 2, 1, 2, 3]])\n with pytest.raises(ValueError):\n mi.set_levels([['A', 'B', 'A', 'A', 'B'], [2, 1, 3, -2, 5]],\n inplace=True)\n\n\[email protected]('names', [['a', 'b', 'a'], [1, 1, 2],\n [1, 'a', 1]])\ndef test_duplicate_level_names(names):\n # GH18872, GH19029\n mi = MultiIndex.from_product([[0, 1]] * 3, names=names)\n assert mi.names == names\n\n # With .rename()\n mi = MultiIndex.from_product([[0, 1]] * 3)\n mi = mi.rename(names)\n assert mi.names == names\n\n # With .rename(., level=)\n mi.rename(names[1], level=1, inplace=True)\n mi = mi.rename([names[0], names[2]], level=[0, 2])\n assert mi.names == names\n\n\ndef test_duplicate_meta_data():\n # GH 10115\n mi = MultiIndex(\n levels=[[0, 1], [0, 1, 2]],\n labels=[[0, 0, 0, 0, 1, 1, 1],\n [0, 1, 2, 0, 0, 1, 2]])\n\n for idx in [mi,\n mi.set_names([None, None]),\n mi.set_names([None, 'Num']),\n mi.set_names(['Upper', 'Num']), ]:\n assert idx.has_duplicates\n assert idx.drop_duplicates().names == idx.names\n\n\ndef test_has_duplicates(idx, idx_dup):\n # see fixtures\n assert idx.is_unique\n assert not idx.has_duplicates\n assert not idx_dup.is_unique\n assert idx_dup.has_duplicates\n\n mi = MultiIndex(levels=[[0, 1], [0, 1, 2]],\n labels=[[0, 0, 0, 0, 1, 1, 1],\n [0, 1, 2, 0, 0, 1, 2]])\n assert not mi.is_unique\n assert mi.has_duplicates\n\n\ndef test_has_duplicates_from_tuples():\n # GH 9075\n t = [(u('x'), u('out'), u('z'), 5, u('y'), u('in'), u('z'), 169),\n (u('x'), u('out'), u('z'), 7, u('y'), u('in'), u('z'), 119),\n (u('x'), u('out'), u('z'), 9, u('y'), u('in'), u('z'), 135),\n (u('x'), u('out'), u('z'), 13, u('y'), u('in'), u('z'), 145),\n (u('x'), u('out'), u('z'), 14, u('y'), u('in'), u('z'), 158),\n (u('x'), u('out'), u('z'), 16, u('y'), u('in'), u('z'), 122),\n (u('x'), u('out'), u('z'), 17, u('y'), u('in'), u('z'), 160),\n (u('x'), u('out'), u('z'), 18, u('y'), u('in'), u('z'), 180),\n (u('x'), u('out'), u('z'), 20, u('y'), u('in'), u('z'), 143),\n (u('x'), u('out'), u('z'), 21, u('y'), u('in'), u('z'), 128),\n (u('x'), u('out'), u('z'), 22, u('y'), u('in'), u('z'), 129),\n (u('x'), u('out'), u('z'), 25, u('y'), u('in'), u('z'), 111),\n (u('x'), u('out'), u('z'), 28, u('y'), u('in'), u('z'), 114),\n (u('x'), u('out'), u('z'), 29, u('y'), u('in'), u('z'), 121),\n (u('x'), u('out'), u('z'), 31, u('y'), u('in'), u('z'), 126),\n (u('x'), u('out'), u('z'), 32, u('y'), u('in'), u('z'), 155),\n (u('x'), u('out'), u('z'), 33, u('y'), u('in'), u('z'), 123),\n (u('x'), u('out'), u('z'), 12, u('y'), u('in'), u('z'), 144)]\n\n mi = MultiIndex.from_tuples(t)\n assert not mi.has_duplicates\n\n\ndef test_has_duplicates_overflow():\n # handle int64 overflow if possible\n def check(nlevels, with_nulls):\n labels = np.tile(np.arange(500), 2)\n level = np.arange(500)\n\n if with_nulls: # inject some null values\n labels[500] = -1 # common nan value\n labels = [labels.copy() for i in range(nlevels)]\n for i in range(nlevels):\n labels[i][500 + i - nlevels // 2] = -1\n\n labels += [np.array([-1, 1]).repeat(500)]\n else:\n labels = [labels] * nlevels + [np.arange(2).repeat(500)]\n\n levels = [level] * nlevels + [[0, 1]]\n\n # no dups\n mi = MultiIndex(levels=levels, labels=labels)\n assert not mi.has_duplicates\n\n # with a dup\n if with_nulls:\n def f(a):\n return np.insert(a, 1000, a[0])\n labels = list(map(f, labels))\n mi = MultiIndex(levels=levels, labels=labels)\n else:\n values = mi.values.tolist()\n mi = MultiIndex.from_tuples(values + [values[0]])\n\n assert mi.has_duplicates\n\n # no overflow\n check(4, False)\n check(4, True)\n\n # overflow possible\n check(8, False)\n check(8, True)\n\n\[email protected]('keep, expected', [\n ('first', np.array([False, False, False, True, True, False])),\n ('last', np.array([False, True, True, False, False, False])),\n (False, np.array([False, True, True, True, True, False]))\n])\ndef test_duplicated(idx_dup, keep, expected):\n result = idx_dup.duplicated(keep=keep)\n tm.assert_numpy_array_equal(result, expected)\n\n\[email protected]('keep', ['first', 'last', False])\ndef test_duplicated_large(keep):\n # GH 9125\n n, k = 200, 5000\n levels = [np.arange(n), tm.makeStringIndex(n), 1000 + np.arange(n)]\n labels = [np.random.choice(n, k * n) for lev in levels]\n mi = MultiIndex(levels=levels, labels=labels)\n\n result = mi.duplicated(keep=keep)\n expected = hashtable.duplicated_object(mi.values, keep=keep)\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_get_duplicates():\n # GH5873\n for a in [101, 102]:\n mi = MultiIndex.from_arrays([[101, a], [3.5, np.nan]])\n assert not mi.has_duplicates\n\n with warnings.catch_warnings(record=True):\n # Deprecated - see GH20239\n assert mi.get_duplicates().equals(MultiIndex.from_arrays([[], []]))\n\n tm.assert_numpy_array_equal(mi.duplicated(),\n np.zeros(2, dtype='bool'))\n\n for n in range(1, 6): # 1st level shape\n for m in range(1, 5): # 2nd level shape\n # all possible unique combinations, including nan\n lab = product(range(-1, n), range(-1, m))\n mi = MultiIndex(levels=[list('abcde')[:n], list('WXYZ')[:m]],\n labels=np.random.permutation(list(lab)).T)\n assert len(mi) == (n + 1) * (m + 1)\n assert not mi.has_duplicates\n\n with warnings.catch_warnings(record=True):\n # Deprecated - see GH20239\n assert mi.get_duplicates().equals(MultiIndex.from_arrays(\n [[], []]))\n\n tm.assert_numpy_array_equal(mi.duplicated(),\n np.zeros(len(mi), dtype='bool'))\n"
] | [
[
"pandas.tseries.offsets.Hour",
"pandas.tseries.offsets.Day",
"pandas.tseries.frequencies.to_offset",
"pandas.core.dtypes.common.is_datetime64_ns_dtype",
"pandas.util._decorators.deprecate_kwarg",
"pandas.core.arrays.datetimes.DatetimeArrayMixin.to_julian_date",
"pandas._libs.tslibs.timezones.maybe_get_tz",
"numpy.asarray",
"pandas.core.arrays.datetimes.DatetimeArrayMixin.normalize",
"pandas.core.dtypes.common.is_dtype_equal",
"pandas.io.formats.format._is_dates_only",
"pandas.core.indexes.base.Index",
"pandas.core.indexes.numeric.Float64Index",
"pandas.tseries.offsets.Second",
"pandas._libs.tslibs.conversion.ensure_datetime64ns",
"pandas.core.dtypes.common.is_datetime64_dtype",
"pandas._libs.tslib.ints_to_pydatetime",
"pandas.core.common.values_from_object",
"pandas.core.indexes.period.PeriodIndex",
"pandas.util._decorators.Substitution",
"pandas.core.dtypes.common.is_string_like",
"pandas.core.indexes.base.Index.slice_indexer",
"pandas.tseries.frequencies.get_period_alias",
"pandas.core.indexes.base.Index.join",
"pandas.core.common.maybe_box",
"pandas._libs.lib.infer_dtype",
"pandas.core.dtypes.common.ensure_int64",
"pandas.tseries.offsets.Minute",
"pandas.compat.set_function_name",
"pandas.core.arrays.datetimes._to_m8",
"pandas._libs.tslibs.timezones.tz_compare",
"pandas.core.dtypes.common.is_float",
"pandas.core.dtypes.common.is_datetimetz",
"pandas.core.arrays.datetimelike.maybe_infer_freq",
"pandas.core.indexes.base.Index.get_value",
"pandas.core.indexes.base.Index.union",
"pandas.core.dtypes.common.is_list_like",
"pandas.core.dtypes.common.is_integer_dtype",
"pandas.util._decorators.Appender",
"pandas.core.dtypes.common.pandas_dtype",
"pandas._libs.tslib.format_array_from_datetime",
"pandas._libs.Timestamp",
"pandas.core.dtypes.common.is_period_dtype",
"pandas.core.indexes.base.Index.intersection",
"pandas._libs.tslibs.timezones.tz_standardize",
"pandas.core.common._any_none",
"numpy.delete",
"pandas.tseries.offsets.generate_range",
"pandas.core.tools.datetimes.to_datetime",
"numpy.array",
"pandas.core.indexes.datetimelike.DatetimeIndexOpsMixin._join_i8_wrapper",
"pandas.core.dtypes.common.is_bool_dtype",
"pandas.tseries.frequencies.Resolution.get_reso",
"pandas.io.formats.format._get_format_datetime64_from_values",
"pandas.core.dtypes.common.is_scalar",
"pandas._libs.tslibs.parsing.parse_time_string",
"pandas._libs.tslibs.fields.get_time_micros",
"pandas.core.dtypes.common.is_integer",
"pandas.tseries.offsets.CDay",
"pandas.core.indexes.base.Index.get_loc",
"pandas._libs.tslibs.ccalendar.get_days_in_month",
"pandas.core.arrays.datetimelike.validate_tz_from_dtype",
"pandas.core.dtypes.concat._concat_compat",
"pandas.io.formats.format._get_format_datetime64",
"pandas.util._decorators.cache_readonly",
"pandas.core.tools.datetimes.to_time",
"pandas.core.dtypes.missing.isna",
"numpy.ndarray.__setstate__",
"pandas.core.arrays.datetimelike.validate_periods",
"numpy.empty"
],
[
"pandas.to_datetime",
"pandas.Series",
"numpy.linspace",
"numpy.asarray",
"numpy.around",
"pandas.core.dtypes.common.is_datetime64tz_dtype",
"pandas.core.dtypes.common.is_datetime64_dtype",
"pandas.core.nanops.nanmin",
"pandas.core.algorithms.unique",
"numpy.diff",
"pandas.core.algorithms.take_nd",
"pandas.core.dtypes.common.is_categorical_dtype",
"numpy.putmask",
"pandas.core.algorithms.quantile",
"pandas.core.dtypes.common.is_timedelta64_dtype",
"pandas.Categorical",
"pandas.Timedelta",
"numpy.modf",
"pandas.Interval",
"numpy.iterable",
"numpy.isfinite",
"pandas.core.dtypes.common.is_scalar",
"pandas.core.dtypes.common.is_integer",
"pandas.IntervalIndex.from_breaks",
"pandas.core.dtypes.common.is_datetime_or_timedelta_dtype",
"pandas.core.dtypes.missing.isna",
"pandas.to_timedelta",
"pandas._libs.lib.infer_dtype",
"pandas.core.nanops.nanmax"
],
[
"pandas.concat",
"pandas.merge",
"pandas.SparseArray",
"pandas.Series",
"pandas.DataFrame"
],
[
"pandas.CategoricalIndex",
"pandas.core.arrays.categorical._recode_for_categories",
"pandas.util.testing.assert_numpy_array_equal",
"pandas.Series",
"pandas.util.testing.assert_categorical_equal",
"numpy.random.choice",
"pandas.Categorical",
"numpy.arange",
"pandas.util.testing.assert_raises_regex",
"pandas.util.testing.assert_produces_warning",
"pandas.Index",
"pandas.DataFrame",
"pandas.util.testing.assert_frame_equal",
"pandas.util.testing.assert_index_equal",
"numpy.asanyarray",
"numpy.array"
],
[
"pandas._libs.writers.convert_json_to_lines",
"pandas.DataFrame",
"pandas.compat.iteritems",
"pandas.compat.itervalues",
"numpy.array"
],
[
"pandas.core.dtypes.common.is_list_like",
"numpy.product",
"numpy.cumproduct",
"pandas.compat.reduce",
"numpy.zeros_like",
"pandas.core.common.values_from_object",
"numpy.roll"
],
[
"pandas.util.testing.assert_numpy_array_equal",
"pandas.compat.u",
"pandas.MultiIndex",
"numpy.random.choice",
"numpy.arange",
"pandas.MultiIndex.from_tuples",
"pandas.DatetimeIndex",
"pandas.MultiIndex.from_arrays",
"pandas.util.testing.makeStringIndex",
"pandas.util.testing.assert_index_equal",
"pandas.MultiIndex.from_product",
"numpy.insert",
"pandas._libs.hashtable.duplicated_object",
"numpy.array",
"numpy.zeros",
"pandas.compat.range"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"1.4",
"1.3",
"1.1",
"1.5",
"0.24",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"0.19",
"0.24",
"0.20",
"0.25"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"0.24",
"0.20",
"0.25"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"0.19",
"0.24",
"0.20"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
anleva/CliffordAttractorWithNumba | [
"f51b9472754b602b7c4f33ffc7c34d443fe23954"
] | [
"src/clifford_attractor_numpy.py"
] | [
"import numpy as np\r\n\r\n\r\n\"\"\"\r\nCLIFFORD ATTRACTORS\r\nEach new point (x_n+1, y_n+1) is determined based on the preceding point (x_n, y_n), and the parameters a, b, c and d. \r\nx_n+1 = sin(a * y_n) + c * cos(a x_n)\r\ny_n+1 = sin(b * x_n) + d * cos(b y_n)\r\n\"\"\"\r\n\r\n\r\ndef sample_histogram(a=0.98, b=1.7, c=1.48, d=1.57, h=None, dim=2000, samples=1e9, randomize=1000):\r\n \"\"\"\r\n Samples a number of points for a Clifford Attractor.\r\n\r\n :param a: Attractor Parameter. Defaults to 0.98.\r\n :param b: Attractor Parameter. Defaults to 1.70.\r\n :param c: Attractor Parameter. Defaults to 1.48.\r\n :param d: Attractor Parameter. Defaults to 1.57.\r\n :param h: Optional. A sample histogram from a previous sampling. Defaults to None, and initiates a zero-valued array\r\n :param dim: The output histogram h will have the dimension (dim, dim).\r\n :param samples: Number of samples generated. Defaults to 1e9.\r\n :param randomize: The number of samples between each random shock.\r\n :return: h, updated NumPy array of dimension (dim, dim).\r\n \"\"\"\r\n\r\n # Initialize\r\n x, y = 0, 0\r\n c_abs = np.abs(c)\r\n d_abs = np.abs(d)\r\n\r\n if h is None:\r\n h = np.zeros((dim, dim))\r\n\r\n # Split sample in batches if too big\r\n while samples > 1e9:\r\n h = sample_histogram(a, b, c, d, h, dim, 1e9, randomize)\r\n samples -= 1e9\r\n\r\n # Run samples\r\n for i in range(int(samples)):\r\n\r\n # Randomize sometimes to avoid numerical issues\r\n if i % randomize == 0:\r\n x += 0.1 * np.random.normal()\r\n y += 0.1 * np.random.normal()\r\n\r\n # Get new data\r\n x_ = np.sin(a * y) + c * np.cos(a * x)\r\n y = np.sin(b * x) + d * np.cos(b * y)\r\n x = x_\r\n\r\n # Get buckets\r\n bx = np.floor(dim * (0.03 + 0.94 * (1 + c_abs + x) / (2 + 2 * c_abs))).astype(np.int)\r\n by = np.floor(dim * (0.03 + 0.94 * (1 + d_abs + y) / (2 + 2 * d_abs))).astype(np.int)\r\n\r\n # Update histogram\r\n h[bx, by] += 1\r\n\r\n return h\r\n\r\n\r\n# h = sample_histogram()\r\n\r\n\r\n"
] | [
[
"numpy.abs",
"numpy.cos",
"numpy.sin",
"numpy.random.normal",
"numpy.floor",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RishabhMaheshwary/unilm | [
"fecf168c067e2c6f8f344f09a076b7557cba9452"
] | [
"layoutlmft/examples/run_funsd.py"
] | [
"#!/usr/bin/env python\n# coding=utf-8\n\nimport logging\nimport os\nimport math\nimport sys\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nimport torch\nimport numpy as np\nfrom datasets import ClassLabel, load_dataset, load_metric\nimport torch\nfrom PIL import Image, ImageDraw, ImageFont\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom detectron2.structures import ImageList\nfrom matplotlib.colors import ListedColormap\nimport layoutlmft.data.datasets.funsd\nimport transformers\nfrom layoutlmft import AutoModelForRelationExtraction\nfrom layoutlmft import AutoModelForTokenClassification\n#from layoutlm import LayoutLMForTokenClassification\nfrom layoutlmft.data import DataCollatorForKeyValueExtraction\nfrom layoutlmft.data.data_args import DataTrainingArguments\nfrom layoutlmft.models.model_args import ModelArguments\nfrom layoutlmft.trainers import FunsdTrainer as Trainer\nfrom transformers import (\n AutoConfig,\n AutoModelForTokenClassification,\n AutoTokenizer,\n HfArgumentParser,\n PreTrainedTokenizerFast,\n TrainingArguments,\n set_seed,\n)\nfrom transformers.trainer_utils import get_last_checkpoint, is_main_process\nfrom transformers.utils import check_min_version\nfrom pathlib import Path\n\n# Will error if the minimal version of Transformers is not installed. Remove at your own risks.\ncheck_min_version(\"4.5.0\")\n\nlogger = logging.getLogger(__name__)\n\ndef plot_boxes(inputs, predictions, attentions, test_set, tokenizer, label_list, dir):\n #breakpoint()\n Path(str(dir)+\"/attn_images/\").mkdir(parents=True, exist_ok=True)\n Path(str(dir)+\"/images/\").mkdir(parents=True, exist_ok=True)\n #attentions = np.mean(attentions, axis = 0)\n for sample_idx in range(len(inputs[\"bbox\"])):\n bbox = inputs[\"bbox\"][sample_idx]\n input_ids = inputs[\"input_ids\"][sample_idx]\n true_labels = inputs[\"labels\"][sample_idx]\n predicted_labels = predictions[sample_idx]\n cur_idx = 0\n final_boxes, final_true_labels, final_predicted_labels = [], [], []\n attention_indices = []\n for id in input_ids:\n if (tokenizer.decode([id]).startswith(\"##\")) or (id in [tokenizer.cls_token_id, tokenizer.sep_token_id, tokenizer.pad_token_id]):\n cur_idx+=1\n continue\n else:\n attention_indices.append(cur_idx)\n final_predicted_labels.append(predicted_labels[cur_idx])\n final_boxes.append(bbox[cur_idx])\n final_true_labels.append(true_labels[cur_idx])\n cur_idx+=1\n #print(final_true_labels)\n #print(final_predicted_labels)\n assert len(final_true_labels) == len(final_predicted_labels)\n\n image = Image.open(inputs[\"image_paths\"][sample_idx])\n image = image.convert(\"RGB\")\n draw = ImageDraw.Draw(image)\n fnt = ImageFont.truetype(\"Pillow/Tests/fonts/FreeMono.ttf\", 30)\n #attns = attentions[sample_idx]\n #attns = np.mean(attns, axis=0)\n\n for i in range(len(final_boxes)):\n if int(final_true_labels[i]) == -100:\n continue\n\n #image1 = Image.open(inputs[\"image_paths\"][sample_idx])\n #image1 = image1.convert(\"RGB\")\n #draw1 = ImageDraw.Draw(image1)\n #attn_scores = []\n\n #for j in range(len(attention_indices)):\n # if i == j:\n # continue\n # attn_scores.append((attns[i][attention_indices[j]], final_boxes[j]))\n #attn_scores.sort()\n #attn_scores.reverse()\n #draw1.rectangle(final_boxes[i], outline='green', width=3)\n\n #for j in range(10):\n # if j <= 5:\n # draw1.rectangle(attn_scores[j][1], outline='red', width=3)\n # else:\n # draw1.rectangle(attn_scores[j][1], outline='red', width=2)\n #attn_path = str(dir)+\"/attn_images/\"+str(sample_idx)+\"_\"+str(i)+\".png\"\n #image1.save(attn_path)\n if final_true_labels[i] == final_predicted_labels[i]:\n draw.rectangle([final_boxes[i][0]-100,final_boxes[i][1], final_boxes[i][2]-100, final_boxes[i][3]], outline='green', width=3)\n else:\n orig_label = label_list[final_true_labels[i]]\n pred_label = label_list[final_predicted_labels[i]]\n if len(orig_label) > 1:\n text_mark = orig_label[2]\n else:\n text_mark = \"F\"\n if len(pred_label) > 1:\n text_mark1 = pred_label[2]\n else:\n text_mark1 = \"F\"\n #draw.text((final_boxes[i][0], final_boxes[i][1]-15), text_mark, fill=\"black\", font=fnt)\n #draw.text((final_boxes[i][2], final_boxes[i][1]-15), text_mark1, fill=\"black\", font=fnt)\n draw.rectangle([final_boxes[i][0]-100,final_boxes[i][1], final_boxes[i][2]-100, final_boxes[i][3]], outline='red', width=3)\n\n boxes_path = str(dir)+\"/images/\"+str(sample_idx)+\".png\"\n image.save(boxes_path)\n\ndef get_attention_scores(attentions, inputs, tokenizer, layer):\n #breakpoint()\n final_euc_dist, final_attn_score, final_far = [], [], []\n for sample_idx in range(17):\n avg_attn_score = 0\n label_map = {}\n #token_predictions = outputs[sample_idx].logits.argmax(-1).squeeze().tolist() # the predictions are at the token level\n words_indices = []\n labels = inputs[\"labels\"][sample_idx]\n input_ids = inputs[\"input_ids\"][sample_idx]\n bboxes = inputs[\"bbox\"][sample_idx]\n #breakpoint()\n attns = attentions[layer][sample_idx]\n attns = np.mean(attns, axis=0)\n #attns = attns.tolist()\n cur_idx = 0\n final_labels = []\n for id in input_ids:\n if (tokenizer.decode([id]).startswith(\"##\")) or (id in [tokenizer.cls_token_id, tokenizer.sep_token_id, tokenizer.pad_token_id]):\n # skip prediction + bounding box\n #if id == tokenizer.pad_token_id:\n # print(id)\n continue\n else:\n words_indices.append(cur_idx)\n final_labels.append(labels[cur_idx])\n cur_idx+=1\n attention_scores = []\n x_distance = []\n y_distance = []\n euc_distance = []\n label_pairs = []\n far = []\n total_cnt = 0\n for i in range(512):\n for j in range(i+1, 512):\n if i in words_indices and j in words_indices and final_labels[i] !=-100 and final_labels[j]!=-100:\n if abs(bboxes[i][0] - bboxes[j][0])<= 50 and abs(bboxes[i][1] - bboxes[j][1]) <= 50:\n far.append(0)\n else:\n far.append(1)\n attention_scores.append(attns[i][j])\n total_cnt+=1\n avg_attn_score += attns[i][j]\n x_distance.append(abs(bboxes[i][0] - bboxes[j][0]))\n y_distance.append(abs(bboxes[i][1] - bboxes[j][1]))\n euc_distance.append(int(math.sqrt((bboxes[i][0]-bboxes[j][0])**2 + (bboxes[i][1] - bboxes[j][1])**2)))\n label_pairs.append((labels[i],labels[j]))\n label_map[(labels[i], labels[j])] = 1\n #breakpoint()\n avg_attn_score = avg_attn_score / total_cnt\n #final_euc_dist, final_attn_score, final_far = [], [], []\n for k in range(len(attention_scores)):\n if attention_scores[k] <= avg_attn_score:\n continue\n final_attn_score.append(attention_scores[k])\n final_euc_dist.append(euc_distance[k])\n final_far.append(far[k])\n classes = ['Near','Far']\n colors = ListedColormap(['r','b'])\n plt.figure()\n scatter = plt.scatter(final_attn_score, final_euc_dist, s = 1, c = final_far, cmap=colors)\n plt.xlabel(\"Attention Scores\")\n plt.ylabel(\"Euclidean distance\")\n plt.title(\"LayoutLM\")\n plt.legend(handles=scatter.legend_elements()[0], labels=classes)\n plt.savefig('plots/plot_all_'+str(layer)+'.jpg')\n plt.close()\n\n\ndef main():\n # See all possible arguments in layoutlmft/transformers/training_args.py\n # or by passing the --help flag to this script.\n # We now keep distinct sets of args, for a cleaner separation of concerns.\n\n parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))\n if len(sys.argv) == 2 and sys.argv[1].endswith(\".json\"):\n # If we pass only one argument to the script and it's the path to a json file,\n # let's parse it to get our arguments.\n model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))\n else:\n model_args, data_args, training_args = parser.parse_args_into_dataclasses()\n\n # Detecting last checkpoint.\n last_checkpoint = None\n if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:\n last_checkpoint = get_last_checkpoint(training_args.output_dir)\n if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:\n raise ValueError(\n f\"Output directory ({training_args.output_dir}) already exists and is not empty. \"\n \"Use --overwrite_output_dir to overcome.\"\n )\n elif last_checkpoint is not None:\n logger.info(\n f\"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change \"\n \"the `--output_dir` or add `--overwrite_output_dir` to train from scratch.\"\n )\n\n # Setup logging\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n handlers=[logging.StreamHandler(sys.stdout)],\n )\n logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)\n\n # Log on each process the small summary:\n logger.warning(\n f\"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}\"\n + f\"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}\"\n )\n # Set the verbosity to info of the Transformers logger (on main process only):\n if is_main_process(training_args.local_rank):\n transformers.utils.logging.set_verbosity_info()\n transformers.utils.logging.enable_default_handler()\n transformers.utils.logging.enable_explicit_format()\n logger.info(f\"Training/evaluation parameters {training_args}\")\n\n # Set seed before initializing model.\n set_seed(training_args.seed)\n\n datasets = load_dataset(os.path.abspath(layoutlmft.data.datasets.funsd.__file__))\n\n if training_args.do_train:\n column_names = datasets[\"train\"].column_names\n features = datasets[\"train\"].features\n else:\n column_names = datasets[\"validation\"].column_names\n features = datasets[\"validation\"].features\n text_column_name = \"tokens\" if \"tokens\" in column_names else column_names[0]\n label_column_name = (\n f\"{data_args.task_name}_tags\" if f\"{data_args.task_name}_tags\" in column_names else column_names[1]\n )\n\n remove_columns = column_names\n\n # In the event the labels are not a `Sequence[ClassLabel]`, we will need to go through the dataset to get the\n # unique labels.\n def get_label_list(labels):\n unique_labels = set()\n for label in labels:\n unique_labels = unique_labels | set(label)\n label_list = list(unique_labels)\n label_list.sort()\n return label_list\n\n if isinstance(features[label_column_name].feature, ClassLabel):\n label_list = features[label_column_name].feature.names\n # No need to convert the labels since they are already ints.\n label_to_id = {i: i for i in range(len(label_list))}\n else:\n label_list = get_label_list(datasets[\"train\"][label_column_name])\n label_to_id = {l: i for i, l in enumerate(label_list)}\n num_labels = len(label_list)\n\n # Load pretrained model and tokenizer\n #\n # Distributed training:\n # The .from_pretrained methods guarantee that only one local process can concurrently\n # download model & vocab.\n config = AutoConfig.from_pretrained(\n model_args.config_name if model_args.config_name else model_args.model_name_or_path,\n num_labels=num_labels,\n finetuning_task=data_args.task_name,\n cache_dir=model_args.cache_dir,\n revision=model_args.model_revision,\n use_auth_token=True if model_args.use_auth_token else None,\n )\n tokenizer = AutoTokenizer.from_pretrained(\n model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,\n cache_dir=model_args.cache_dir,\n use_fast=True,\n revision=model_args.model_revision,\n use_auth_token=True if model_args.use_auth_token else None,\n )\n model = AutoModelForTokenClassification.from_pretrained(\n model_args.model_name_or_path,\n from_tf=bool(\".ckpt\" in model_args.model_name_or_path),\n config=config,\n cache_dir=model_args.cache_dir,\n revision=model_args.model_revision,\n use_auth_token=True if model_args.use_auth_token else None,\n )\n\n # Tokenizer check: this script requires a fast tokenizer.\n if not isinstance(tokenizer, PreTrainedTokenizerFast):\n raise ValueError(\n \"This example script only works for models that have a fast tokenizer. Checkout the big table of models \"\n \"at https://huggingface.co/transformers/index.html#bigtable to find the model types that meet this \"\n \"requirement\"\n )\n\n # Preprocessing the dataset\n # Padding strategy\n padding = \"max_length\" if data_args.pad_to_max_length else False\n\n # Tokenize all texts and align the labels with them.\n def tokenize_and_align_labels(examples):\n #breakpoint()\n tokenized_inputs = tokenizer(\n examples[text_column_name],\n padding=padding,\n truncation=True,\n return_overflowing_tokens=True,\n # We use this argument because the texts in our dataset are lists of words (with a label for each word).\n is_split_into_words=True,\n )\n #breakpoint()\n labels = []\n bboxes = []\n images = []\n img_paths = []\n data_args.label_all_tokens = True\n for batch_index in range(len(tokenized_inputs[\"input_ids\"])):\n word_ids = tokenized_inputs.word_ids(batch_index=batch_index)\n org_batch_index = tokenized_inputs[\"overflow_to_sample_mapping\"][batch_index]\n\n label = examples[label_column_name][org_batch_index]\n bbox = examples[\"bboxes\"][org_batch_index]\n #bbox = torch.clamp(bbox, min=0, max=1000)\n image = examples[\"image\"][org_batch_index]\n previous_word_idx = None\n label_ids = []\n bbox_inputs = []\n for word_idx in word_ids:\n # Special tokens have a word id that is None. We set the label to -100 so they are automatically\n # ignored in the loss function.\n if word_idx is None:\n label_ids.append(-100)\n bbox_inputs.append([0, 0, 0, 0])\n # We set the label for the first token of each word.\n elif word_idx != previous_word_idx:\n label_ids.append(label_to_id[label[word_idx]])\n bbox_inputs.append(bbox[word_idx])\n # For the other tokens in a word, we set the label to either the current label or -100, depending on\n # the label_all_tokens flag.\n else:\n label_ids.append(label_to_id[label[word_idx]] if data_args.label_all_tokens else -100)\n bbox_inputs.append(bbox[word_idx])\n previous_word_idx = word_idx\n labels.append(label_ids)\n bboxes.append(bbox_inputs)\n images.append(image)\n img_paths.append(examples[\"image_path\"][org_batch_index])\n tokenized_inputs[\"labels\"] = labels\n tokenized_inputs[\"bbox\"] = bboxes\n tokenized_inputs[\"image\"] = images\n tokenized_inputs[\"image_paths\"] = img_paths\n #breakpoint()\n return tokenized_inputs\n\n if training_args.do_train:\n if \"train\" not in datasets:\n raise ValueError(\"--do_train requires a train dataset\")\n train_dataset = datasets[\"train\"]\n if data_args.max_train_samples is not None:\n train_dataset = train_dataset.select(range(data_args.max_train_samples))\n train_dataset = train_dataset.map(\n tokenize_and_align_labels,\n batched=True,\n remove_columns=remove_columns,\n num_proc=data_args.preprocessing_num_workers,\n load_from_cache_file=not data_args.overwrite_cache,\n )\n\n if training_args.do_eval:\n if \"validation\" not in datasets:\n raise ValueError(\"--do_eval requires a validation dataset\")\n eval_dataset = datasets[\"validation\"]\n if data_args.max_val_samples is not None:\n eval_dataset = eval_dataset.select(range(data_args.max_val_samples))\n eval_dataset = eval_dataset.map(\n tokenize_and_align_labels,\n batched=True,\n remove_columns=remove_columns,\n num_proc=data_args.preprocessing_num_workers,\n load_from_cache_file=not data_args.overwrite_cache,\n )\n\n if training_args.do_predict:\n if \"test\" not in datasets:\n raise ValueError(\"--do_predict requires a test dataset\")\n test_dataset = datasets[\"test\"]\n exs = tokenize_and_align_labels(test_dataset)\n if data_args.max_test_samples is not None:\n test_dataset = test_dataset.select(range(data_args.max_test_samples))\n test_dataset = test_dataset.map(\n tokenize_and_align_labels,\n batched=True,\n remove_columns=remove_columns,\n num_proc=data_args.preprocessing_num_workers,\n load_from_cache_file=not data_args.overwrite_cache,\n )\n #breakpoint()\n\n # Data collator\n data_collator = DataCollatorForKeyValueExtraction(\n tokenizer,\n pad_to_multiple_of=8 if training_args.fp16 else None,\n padding=padding,\n max_length=512,\n )\n\n # Metrics\n metric = load_metric(\"seqeval\")\n\n def compute_metrics(p):\n predictions, labels = p\n predictions = np.argmax(predictions, axis=2)\n\n # Remove ignored index (special tokens)\n true_predictions = [\n [label_list[p] for (p, l) in zip(prediction, label) if l != -100]\n for prediction, label in zip(predictions, labels)\n ]\n true_labels = [\n [label_list[l] for (p, l) in zip(prediction, label) if l != -100]\n for prediction, label in zip(predictions, labels)\n ]\n\n results = metric.compute(predictions=true_predictions, references=true_labels)\n if data_args.return_entity_level_metrics:\n # Unpack nested dictionaries\n final_results = {}\n for key, value in results.items():\n if isinstance(value, dict):\n for n, v in value.items():\n final_results[f\"{key}_{n}\"] = v\n else:\n final_results[key] = value\n return final_results\n else:\n return {\n \"precision\": results[\"overall_precision\"],\n \"recall\": results[\"overall_recall\"],\n \"f1\": results[\"overall_f1\"],\n \"accuracy\": results[\"overall_accuracy\"],\n }\n\n # Initialize our Trainer\n #breakpoint()\n trainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=train_dataset if training_args.do_train else None,\n eval_dataset=eval_dataset if training_args.do_eval else None,\n tokenizer=tokenizer,\n data_collator=data_collator,\n compute_metrics=compute_metrics,\n )\n\n # Training\n if training_args.do_train:\n checkpoint = last_checkpoint if last_checkpoint else None\n train_result = trainer.train(resume_from_checkpoint=checkpoint)\n metrics = train_result.metrics\n trainer.save_model() # Saves the tokenizer too for easy upload\n\n max_train_samples = (\n data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)\n )\n metrics[\"train_samples\"] = min(max_train_samples, len(train_dataset))\n\n trainer.log_metrics(\"train\", metrics)\n trainer.save_metrics(\"train\", metrics)\n trainer.save_state()\n\n # Evaluation\n if training_args.do_eval:\n logger.info(\"*** Evaluate ***\")\n\n #metrics = trainer.evaluate()\n\n #max_val_samples = data_args.max_val_samples if data_args.max_val_samples is not None else len(eval_dataset)\n #metrics[\"eval_samples\"] = min(max_val_samples, len(eval_dataset))\n\n #trainer.log_metrics(\"eval\", metrics)\n #trainer.save_metrics(\"eval\", metrics)\n\n # Predict\n if training_args.do_predict:\n logger.info(\"*** Predict ***\")\n breakpoint()\n predictions, labels, metrics, attns = trainer.predict(test_dataset)\n cur_preds = predictions\n breakpoint()\n predictions = np.argmax(predictions, axis=2)\n trainer.log_metrics(\"test\", metrics)\n # Remove ignored index (special tokens)\n true_predictions = [\n [label_list[p] for (p, l) in zip(prediction, label) if l != -100]\n for prediction, label in zip(predictions, labels)\n ]\n orig_predictions = [\n [label_list[l] for (p, l) in zip(prediction, label) if l != -100]\n for prediction, label in zip(predictions, labels)\n ]\n #breakpoint()\n #true_preds = []\n #input_ids = exs[\"input_ids\"]\n #cntr = 0\n #docs = []\n #all_hidden_states = []\n #for prediction, label in zip(cur_preds, labels):\n # arr = []\n # words = []\n # h_states = []\n # input_id = input_ids[cntr]\n # tok_cntr = 0\n # for (p, l) in zip(prediction, label):\n # if l !=-100:\n # h_states.append(hidden_states[11][cntr][tok_cntr])\n # words.append(tokenizer.decode([input_id[tok_cntr]]))\n # arr.append(p)\n # tok_cntr+=1\n # cntr+=1\n # true_preds.append(arr)\n # docs.append(words)\n # all_hidden_states.append(h_states)\n #true_preds = [\n # [p for (p, l) in zip(prediction, label) if l != -100]\n # for prediction, label in zip(cur_preds, labels)\n #]\n img = []\n for img_path in exs[\"image_paths\"]:\n iddx = img_path.rfind(\"/\")\n img.append(img_path[iddx+1:])\n with open(\"image_prediction_sequence_train.txt\", \"w\") as ff:\n ff.write(\"\\n\".join(img))\n trainer.log_metrics(\"test\", metrics)\n trainer.save_metrics(\"test\", metrics)\n\n # Save predictions\n output_test_predictions_file = os.path.join(training_args.output_dir, \"test_predictions.txt\")\n if trainer.is_world_process_zero():\n with open(output_test_predictions_file, \"w\") as writer:\n for prediction in true_predictions:\n writer.write(\" \".join(prediction) + \"\\n\")\n\n #with open(\"original_predictions.txt\", \"w\") as wrt:\n # for prediction in orig_predictions:\n # wrt.write(\" \".join(prediction) + \"\\n\")\n\n #np.save(\"confidence_train.npy\", np.asarray(true_preds))\n #np.save(\"words_train.npy\", np.asarray(docs))\n #np.save(\"all_hidden_states_train.npy\", np.asarray(all_hidden_states))\n plot_boxes(exs, predictions, attns ,datasets[\"test\"], tokenizer, label_list, training_args.output_dir)\n #np.save(\"attention_original/part1.npy\", attns)\n #np.save(\"hidden_states_original/part1.npy\", hidden_states)\n #device = torch.device(\"cpu\")\n #model.to(device)\n #model.eval()\n #breakpoint()\n #preds = model(input_ids=torch.tensor(exs[\"input_ids\"], device=device),\\\n # attention_mask=torch.tensor(exs[\"attention_mask\"], device=device),\\\n # token_type_ids=torch.tensor(exs[\"token_type_ids\"], device=device),\\\n # labels=torch.tensor(exs[\"labels\"], device=device), output_attentions=True, output_hidden_states=True)\n #attns, hidden_states = [], []\n #for i in range(12):\n #attns.append(preds.attentions[i].detach().numpy())\n #hidden_states.append(preds.hidden_states[i].detach().numpy())\n # np.save(\"attention_pre/test.npy\", preds.attentions[i].detach().numpy())\n # np.save(\"hidden_states_pre/test.npy\", preds.hidden_states[i].detach().numpy())\n #device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n #trainer.log_metrics(\"test\", metrics)\n #breakpoint()\n #test_embeddings = []\n #num_categories = 12\n #cmap = cm.get_cmap('tab20')\n #layers = []\n #for i in range(12):\n # embeddings = preds.hidden_states[i]\n # embeddings = torch.mean(embeddings, axis = 1)\n # for j in range(52):\n # doc_embeddings = embeddings[j]\n # layers.append(i)\n # test_embeddings.append(doc_embeddings.detach().numpy())\n\n #tsne = TSNE(2, verbose=1)\n #fig, ax = plt.subplots(figsize=(8,8))\n #tsne_proj = tsne.fit_transform(test_embeddings)\n #for lab in range(num_categories):\n # indices = np.asarray(layers) == lab\n # ax.scatter(tsne_proj[indices,0], tsne_proj[indices,1], c=np.array(cmap(lab)).reshape(1,4), label = lab ,alpha=0.5)\n #ax.legend(fontsize='large', markerscale=2)\n #plt.savefig('plots/test_embeddings_original_1.jpg')\n #plt.close()\n #for i in range(12):\n #get_attention_scores(attns, exs, tokenizer, i)\n\ndef _mp_fn(index):\n # For xla_spawn (TPUs)\n main()\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"numpy.argmax",
"matplotlib.colors.ListedColormap",
"numpy.mean",
"matplotlib.pyplot.close",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Vishu26/Hydrological-Cycle | [
"b6db5f1526340cf1a79e27d185559b75a191b260"
] | [
"Mac/graph2.py"
] | [
"from grap2 import Ui_Form\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom sys import argv\nfrom PyQt5.QtWidgets import *\nimport matplotlib as mpl\n\nmpl.use('Qt5Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass mas2(QWidget, Ui_Form):\n\n def __init__(self):\n\n super(mas2, self).__init__()\n self.setupUi(self)\n self.step = 2\n self.seax = [1990]\n self.seay = [30]\n self.cy = [0]\n self.conc = 0\n self.usage = 0.2\n self.lo = 0.02\n self.ppm.valueChanged.connect(self.se)\n self.forward.clicked.connect(self.go)\n self.time.currentIndexChanged.connect(self.t)\n self.use.currentIndexChanged.connect(self.u)\n self.loss.currentIndexChanged.connect(self.l)\n self.reset.clicked.connect(self.re)\n self.expo.clicked.connect(self.exp)\n\n\n fig, self.ax1 = plt.subplots()\n self.ax1.plot(self.seax, self.seay, '*', color='r')\n self.ax1.axis([1980, 2110, 15, 40])\n self.ax1.xaxis.grid()\n self.ax1.yaxis.grid()\n self.ax1.set_facecolor('gray')\n self.ax1.set_ylabel('Ground Water Level (in metres)')\n self.ax1.yaxis.label.set_color('red')\n self.ax1.tick_params(axis='y', colors='red')\n\n self.ax2 = self.ax1.twinx()\n self.ax2.plot(self.seax, self.cy, '^', color='b')\n self.ax2.axis([1980, 2110, 0, 2800])\n self.ax2.xaxis.grid()\n self.ax2.set_ylabel('Rainfall (in mm)')\n self.ax2.yaxis.label.set_color('blue')\n self.ax2.tick_params(axis='y', colors='blue')\n\n self.ax1.set_xlabel('Date (Year)')\n\n plt.savefig('fig.png')\n self.graph.setPixmap(QPixmap('fig.png'))\n self.show()\n\n def u(self):\n self.usage = float(self.use.currentText().split()[0])\n\n def l(self):\n self.lo = float(self.loss.currentText().split()[0])\n\n def exp(self):\n with open('graph.txt', 'w') as f:\n f.write('Date, Rainfall, Water\\n')\n for i in range(len(self.cy)):\n f.write(str(self.seax[i])+', '+str(self.cy[i])+', '+str(self.seay[i])+'\\n')\n def t(self):\n self.step = int(self.time.currentText().split()[0])\n def re(self):\n self.hide()\n self.__init__()\n\n\n def se(self):\n self.conc = self.ppm.value()\n self.val.setText(str(self.conc)+' mm')\n\n def go(self):\n self.cy.append(self.conc*10)\n self.seax.append(self.seax[-1] + self.step)\n if self.seax[-1] >= 2110:\n self.forward.setDisabled(True)\n return\n x = 25*np.log(self.conc + 1) + 20\n\n self.seay.append(((self.seay[-1]+x/1000)*(100-self.usage)/100)*(100-self.lo)/100)\n\n self.ax1.plot(self.seax, self.seay, '*', color='r')\n self.ax2.plot(self.seax, self.cy, '^', color='b')\n\n plt.savefig('fig.png')\n self.graph.setPixmap(QPixmap('fig.png'))\n\n\nif __name__ =='__main__':\n app = QApplication(argv)\n m = mas2()\n app.exec_()"
] | [
[
"matplotlib.use",
"numpy.log",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
stefanrer/bot-emotion2 | [
"a09a51bb3355eec29c9fc09d1080877a64ef89fb"
] | [
"response_selectors/rule_based_response_selector/server.py"
] | [
"#!/usr/bin/env python\n\nimport logging\nimport numpy as np\nimport time\n\nfrom flask import Flask, request, jsonify\nfrom os import getenv\nimport sentry_sdk\n\n\nsentry_sdk.init(getenv(\"SENTRY_DSN\"))\n\nlogging.basicConfig(format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\napp = Flask(__name__)\n\n\[email protected](\"/respond\", methods=[\"POST\"])\ndef respond():\n st_time = time.time()\n\n dialogs = request.json[\"dialogs\"]\n response_candidates = [dialog[\"utterances\"][-1][\"hypotheses\"] for dialog in dialogs]\n logger.error(dialogs)\n logger.error(response_candidates)\n selected_skill_names = []\n selected_responses = []\n selected_confidences = []\n selected_human_attributes = []\n selected_bot_attributes = []\n\n for i, dialog in enumerate(dialogs):\n confidences = []\n responses = []\n skill_names = []\n human_attributes = []\n bot_attributes = []\n\n for skill_data in response_candidates[i]:\n if skill_data[\"text\"] and skill_data[\"confidence\"]:\n logger.info(f\"Skill {skill_data['skill_name']} returned non-empty hypothesis with non-zero confidence.\")\n\n confidences += [skill_data[\"confidence\"]]\n responses += [skill_data[\"text\"]]\n skill_names += [skill_data[\"skill_name\"]]\n human_attributes += [skill_data.get(\"human_attributes\", {})]\n bot_attributes += [skill_data.get(\"bot_attributes\", {})]\n\n if skill_data[\"skill_name\"] == \"dff_bot_persona_2_skill\" and skill_data[\"confidence\"] == 1.0:\n confidences[-1] = 100.0\n logger.info(\"DFF Persona was superpowered!\")\n logger.error(confidences)\n best_id = np.argmax(confidences)\n\n selected_skill_names.append(skill_names[best_id])\n selected_responses.append(responses[best_id])\n selected_confidences.append(confidences[best_id])\n selected_human_attributes.append(human_attributes[best_id])\n selected_bot_attributes.append(bot_attributes[best_id])\n\n total_time = time.time() - st_time\n logger.info(f\"rule_based_response_selector exec time = {total_time:.3f}s\")\n return jsonify(list(zip(selected_skill_names, selected_responses, selected_confidences, selected_human_attributes, selected_bot_attributes)))\n\n\nif __name__ == \"__main__\":\n app.run(debug=False, host=\"0.0.0.0\", port=3003)\n"
] | [
[
"numpy.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kdop-dev/ipysheet | [
"997377df6ab5d1c5cfcca66f164ec0931fceec1c"
] | [
"ipysheet/test_all.py"
] | [
"import numpy as np\nimport pandas as pd\nimport ipysheet\nimport pytest\nfrom ipysheet.utils import transpose\nimport ipywidgets as widgets\nimport ipykernel.kernelbase\nfrom .utils import adapt_value\n\n\nclass _KernelMock(ipykernel.kernelbase.Kernel):\n @property\n def session(self):\n return self\n\n def send(self, *args, **kwargs):\n pass\n\n\[email protected]\ndef kernel():\n return _KernelMock()\n\n\ndef test_transpose():\n assert transpose([[1, 2]]) == [[1], [2]]\n assert transpose([[1, 2], [3, 4]]) == [[1, 3], [2, 4]]\n assert transpose([[1], [2]]) == [[1, 2]]\n\n\ndef test_current_sheet():\n sheet1 = ipysheet.sheet()\n assert sheet1 is ipysheet.current()\n sheet2 = ipysheet.sheet()\n assert sheet2 is ipysheet.current()\n assert sheet1 is ipysheet.sheet(sheet1)\n assert sheet1 is ipysheet.current()\n\n sheet3 = ipysheet.sheet('key3')\n assert sheet3 is ipysheet.current()\n sheet4 = ipysheet.sheet('key4')\n assert sheet4 is ipysheet.current()\n assert sheet3 is ipysheet.sheet('key3')\n assert sheet3 is ipysheet.current()\n assert sheet4 is ipysheet.sheet('key4')\n assert sheet4 is ipysheet.current()\n\n\ndef test_cell_add():\n sheet1 = ipysheet.sheet()\n sheet2 = ipysheet.sheet()\n ipysheet.cell(0, 0, value='1')\n assert len(sheet1.cells) == 0\n assert len(sheet2.cells) == 1\n ipysheet.sheet(sheet1)\n ipysheet.cell(0, 0, value='2')\n ipysheet.cell(0, 1, value='2')\n assert len(sheet1.cells) == 2\n assert len(sheet2.cells) == 1\n\n with ipysheet.hold_cells():\n ipysheet.cell(1, 0, value='3')\n ipysheet.cell(1, 1, value='4')\n assert len(sheet1.cells) == 2\n assert len(sheet2.cells) == 1\n assert len(sheet1.cells) == 4\n assert len(sheet2.cells) == 1\n\n # nested hold cells\n sheet1 = ipysheet.sheet()\n with ipysheet.hold_cells():\n with ipysheet.hold_cells():\n ipysheet.cell(1, 0, value='3')\n ipysheet.cell(1, 1, value='4')\n assert len(sheet1.cells) == 0\n assert len(sheet1.cells) == 0\n assert len(sheet1.cells) == 2\n\n\ndef test_calculation():\n ipysheet.sheet()\n a = ipysheet.cell(0, 0, value=1)\n b = ipysheet.cell(0, 0, value=2)\n c = ipysheet.cell(0, 0, value=0)\n\n @ipysheet.calculation(inputs=[a, (b, 'value')], output=c)\n def add(a, b): # pylint: disable=unused-variable\n return a + b\n\n assert c.value == 3\n a.value = 10\n assert c.value == 10 + 2\n b.value = 20\n assert c.value == 10 + 20\n\n a.value = 1\n b.value = 2\n assert c.row_start == 0\n\n @ipysheet.calculation(inputs=[a, b], output=(c, 'type'))\n def add2(a, b): # pylint: disable=unused-variable\n return 'abcdefg'[a + b]\n\n assert c.type == 'd'\n b.value = 1\n assert c.type == 'c'\n\n ipysheet.sheet()\n a = ipysheet.cell(0, 0, value=1)\n b = ipysheet.cell(0, 0, value=widgets.IntSlider(value=2))\n c = widgets.IntSlider(max=0)\n d = ipysheet.cell(0, 0, value=1)\n\n @ipysheet.calculation(inputs=[a, (b, 'value'), (c, 'max')], output=d)\n def add3(a, b, c): # pylint: disable=unused-variable\n return a + b + c\n\n assert d.value == 3\n a.value = 10\n assert d.value == 10+2\n b.value.value = 20\n assert d.value == 10+20\n c.max = 30\n assert d.value == 10+20+30\n\n b.value = widgets.IntSlider(value=2)\n assert d.value == 10+2+30\n b.value = 20\n assert d.value == 10+20+30\n\n a.value = widgets.IntSlider(value=100)\n assert d.value == 100+20+30\n a.value.value = 10\n assert d.value == 10+20+30\n\n\ndef test_getitem():\n sheet = ipysheet.sheet()\n cell00 = ipysheet.cell(0, 0, value='0_0')\n cell10 = ipysheet.cell(1, 0, value='1_0')\n cell21 = ipysheet.cell(2, 1, value='2_1')\n assert sheet[0, 0] is cell00\n assert sheet[1, 0] is cell10\n assert sheet[2, 1] is cell21\n with pytest.raises(IndexError):\n sheet[1, 1]\n # TODO: what do we do with copies.. ? now we return the first values\n ipysheet.cell(0, 0, value='0_0')\n assert sheet[0, 0] is cell00\n\n\ndef test_row_and_column():\n ipysheet.sheet(rows=3, columns=4)\n ipysheet.row(0, [0, 1, 2, 3])\n ipysheet.row(0, [0, 1, 2])\n ipysheet.row(0, [0, 1, 2], column_end=2)\n ipysheet.row(0, [0, 1, 2], column_start=1)\n with pytest.raises(ValueError):\n ipysheet.row(0, [0, 1, 2, 4, 5])\n with pytest.raises(ValueError):\n ipysheet.row(0, [0, 1], column_end=3)\n with pytest.raises(ValueError):\n ipysheet.row(0, [0, 1, 2, 4], column_start=1)\n\n row = ipysheet.row(0, [0, 1, 2, 3])\n with pytest.raises(ValueError):\n row.value = [0, 1, 2]\n with pytest.raises(ValueError):\n row.value = 1\n row.value = [0, 1, 2, 4]\n assert row.value == [0, 1, 2, 4]\n\n ipysheet.column(0, [0, 1, 2])\n ipysheet.column(0, [0, 1])\n ipysheet.column(0, [0, 1], row_end=1)\n ipysheet.column(0, [0, 1], row_start=1)\n with pytest.raises(ValueError):\n ipysheet.column(0, [0, 1, 2, 3])\n with pytest.raises(ValueError):\n ipysheet.column(0, [0, 1], row_end=0)\n with pytest.raises(ValueError):\n ipysheet.column(0, [0, 1, 2, 4], row_start=1)\n\n col = ipysheet.column(0, [0, 1, 2])\n with pytest.raises(ValueError):\n col.value = [0, 1]\n with pytest.raises(ValueError):\n col.value = 1\n col.value = [0, 1, 3]\n assert col.value == [0, 1, 3]\n\n\ndef test_cell_range():\n ipysheet.sheet(rows=3, columns=4)\n # [row][column]\n ipysheet.cell_range([[0, 1]]) # 1 row, 2 columns\n ipysheet.cell_range([[0], [2]]) # 2 rows, 1 columns\n ipysheet.cell_range([[0, 1], [2, 3]]) # 2 rows, 2 columns\n ipysheet.cell_range([[0, 1], [2, 3], [4, 5]]) # 3 rows, 2 columns\n ipysheet.cell_range([[0, 1, 9], [2, 3, 9], [4, 5, 9]]) # 3 rows, 3 columns\n ipysheet.cell_range([[0, 1, 9]], column_end=2) # 3 rows, 3 columns\n ipysheet.cell_range([[0, 1, 9]], column_start=1) # 1 rows, 3 columns\n with pytest.raises(ValueError):\n ipysheet.cell_range([[0, 1], [2, 3], [4, 5], [6, 7]]) # 4 rows, 2 columns\n with pytest.raises(ValueError):\n ipysheet.cell_range([[0, 1, 2, 3, 4], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]) # 3 rows, 5 columns\n with pytest.raises(ValueError):\n ipysheet.cell_range([[0, 1, 2, 3, 4], [2], [3, 4, 5, 6, 7]]) # not well shaped\n with pytest.raises(ValueError):\n ipysheet.cell_range([]) # empty rows\n with pytest.raises(ValueError):\n ipysheet.cell_range([[], []]) # empty columns\n\n value = [[0, 1], [2, 3], [4, 5]]\n valueT = [[0, 2, 4], [1, 3, 5]] # it's transpose\n assert value == transpose(valueT)\n r = ipysheet.cell_range(value) # 3 rows, 2 columns\n with pytest.raises(ValueError):\n r.value = 1\n with pytest.raises(ValueError):\n r.value = [1, 2, 3]\n with pytest.raises(ValueError):\n r.value = [[1, 2]]\n assert r.value == transpose(valueT)\n\n rT = ipysheet.cell_range(valueT, transpose=True) # 3 rows, 2 columns\n with pytest.raises(ValueError):\n rT.value = 1\n with pytest.raises(ValueError):\n rT.value = [1, 2, 3]\n with pytest.raises(ValueError):\n rT.value = [[1, 2]]\n rT.value = transpose(value)\n assert rT.value == transpose(value)\n\n sheet = ipysheet.sheet(rows=3, columns=4)\n assert len(sheet.cells) == 0\n with ipysheet.hold_cells():\n ipysheet.cell_range(value)\n ipysheet.cell_range(value)\n assert len(sheet.cells) == 0\n assert len(sheet.cells) == 2\n\n # sheet = ipysheet.sheet(rows=3, columns=4)\n # range1, cells = ipysheet.cell_range([[0, 1], [2, 3]], return_cells=True)\n # assert range1.value == [[0, 1], [2, 3]]\n\n # sheet = ipysheet.sheet(rows=3, columns=4)\n # range1, cells = ipysheet.cell_range([[0, 1], [2, 3]], return_cells=True)\n # cells[1][0].value = 99\n # assert range1.value == [[0, 1], [99, 3]]\n # print('now we reset it')\n # range1.value = [[0, 1], [2, 8]]\n # print('now we reset it...')\n # assert cells[1][0].value == 2\n\n # sheet = ipysheet.sheet(rows=3, columns=4)\n # range2, cells = ipysheet.cell_range([[0, 1], [2, 3]], return_cells=True, transpose=True)\n # cells[1][0].value = 99\n # assert range2.value == [[0, 99], [1, 3]]\n # range2.value = [[0, 1], [2, 3]]\n # assert cells[1][0].value == 2\n\n # sheet = ipysheet.sheet(rows=2, columns=1)\n # range2 = ipysheet.cell_range([[0, 1]], transpose=True)\n # #range2.\n\n # sheet = ipysheet.sheet(rows=1, columns=2)\n # range2 = ipysheet.cell_range([[0], [2]], transpose=True)\n\n\ndef test_cell_values():\n cell = ipysheet.cell(0, 0, value=True)\n assert cell.value is True\n assert cell.type == 'checkbox'\n\n cell = ipysheet.cell(0, 0, value=1.2)\n assert cell.value == 1.2\n assert cell.type == 'numeric'\n cell = ipysheet.cell(0, 0, value=1)\n assert cell.value == 1\n assert cell.type == 'numeric'\n\n cell = ipysheet.Cell(value='1.2')\n assert cell.value == '1.2'\n assert cell.type is None\n\n cell = ipysheet.row(0, [True, False])\n assert cell.value == [True, False]\n assert cell.type == 'checkbox'\n\n cell = ipysheet.row(0, [0, 1.2])\n assert cell.value == [0, 1.2]\n assert cell.type == 'numeric'\n\n cell = ipysheet.row(0, [0, 1])\n assert cell.value == [0, 1]\n assert cell.type == 'numeric'\n\n cell = ipysheet.row(0, ['a', 'b'])\n assert cell.value == ['a', 'b']\n assert cell.type == 'text'\n\n cell = ipysheet.row(0, [True, 0])\n assert cell.type == 'numeric'\n\n cell = ipysheet.row(0, [True, 'bla'])\n assert cell.type is None\n\n cell = ipysheet.cell(0, 0, choice=['a', 'b'])\n assert cell.type == 'dropdown'\n\n\ndef test_cell_style():\n cell = ipysheet.cell(0, 0, color='red')\n assert cell.style['color'] == 'red'\n cell = ipysheet.cell(0, 0, background_color='blue')\n assert cell.style['backgroundColor'] == 'blue'\n cell = ipysheet.cell(0, 0, font_style='nice')\n assert cell.style['fontStyle'] == 'nice'\n cell = ipysheet.cell(0, 0, font_weight='bold')\n assert cell.style['fontWeight'] == 'bold'\n\n\ndef test_cell_range_style():\n values = [[1]]\n cell = ipysheet.cell_range(values, color='red')\n assert cell.style['color'] == 'red'\n cell = ipysheet.cell_range(values, background_color='blue')\n assert cell.style['backgroundColor'] == 'blue'\n cell = ipysheet.cell_range(values, font_style='nice')\n assert cell.style['fontStyle'] == 'nice'\n cell = ipysheet.cell_range(values, font_weight='bold')\n assert cell.style['fontWeight'] == 'bold'\n\n\ndef test_cell_label():\n sheet = ipysheet.sheet()\n ipysheet.cell(0, 1, label_left='hi')\n assert sheet.cells[-1].value == 'hi'\n with pytest.raises(IndexError):\n ipysheet.cell(0, 0, label_left='hi')\n\n\ndef test_renderer():\n ipysheet.sheet()\n renderer = ipysheet.renderer('code', 'name')\n assert renderer.code == 'code'\n assert renderer.name == 'name'\n\n def somefunction(x):\n pass\n\n def f(x):\n somefunction(x)\n\n f(1) # for coverage\n\n renderer = ipysheet.renderer(f, 'name2')\n assert \"somefunction\" in renderer.code\n assert renderer.name == 'name2'\n\n\ndef _format_date(date):\n import pandas as pd\n\n return pd.to_datetime(str(date)).strftime('%Y/%m/%d')\n\n\ndef test_to_dataframe():\n sheet = ipysheet.sheet(rows=5, columns=4)\n ipysheet.cell(0, 0, value=True)\n ipysheet.row(1, value=[2, 34, 543, 23])\n ipysheet.column(3, value=[1.2, 1.3, 1.4, 1.5, 1.6])\n\n df = ipysheet.to_dataframe(sheet)\n assert np.all(df['A'].tolist() == [True, 2, None, None, None])\n assert np.all(df['B'].tolist() == [None, 34, None, None, None])\n assert np.all(df['C'].tolist() == [None, 543, None, None, None])\n assert np.all(df['D'].tolist() == [1.2, 1.3, 1.4, 1.5, 1.6])\n\n sheet = ipysheet.sheet(rows=4, columns=4, column_headers=['c0', 'c1', 'c2', 'c3'], row_headers=['r0', 'r1', 'r2', 'r3'])\n ipysheet.cell_range(\n [\n [2, 34, 543, 23],\n [1, 1, 1, 1],\n [2, 2, 222, 22],\n [2, 0, 111, 11],\n ],\n row_start=0, column_start=0,\n transpose=True\n )\n\n df = ipysheet.to_dataframe(sheet)\n assert np.all(df['c0'].tolist() == [2, 34, 543, 23])\n assert np.all(df['c1'].tolist() == [1, 1, 1, 1])\n assert np.all(df['c2'].tolist() == [2, 2, 222, 22])\n assert np.all(df['c3'].tolist() == [2, 0, 111, 11])\n\n sheet = ipysheet.sheet(rows=4, columns=4, column_headers=['t0', 't1', 't2', 't3'])\n ipysheet.cell_range(\n [\n [2, 34, 543, 23],\n [1, 1, 1, 1],\n [2, 2, 222, 22],\n [2, 0, 111, 11],\n ],\n row_start=0, column_start=0,\n transpose=False\n )\n\n df = ipysheet.to_dataframe(sheet)\n assert np.all(df['t0'].tolist() == [2, 1, 2, 2])\n assert np.all(df['t1'].tolist() == [34, 1, 2, 0])\n assert np.all(df['t2'].tolist() == [543, 1, 222, 111])\n assert np.all(df['t3'].tolist() == [23, 1, 22, 11])\n\n sheet = ipysheet.sheet(rows=0, columns=0)\n\n df = ipysheet.to_dataframe(sheet)\n assert np.all(df == pd.DataFrame())\n\n sheet = ipysheet.sheet(rows=4, columns=1)\n ipysheet.column(0, ['2019/02/28', '2019/02/27', '2019/02/26', '2019/02/25'], type='date')\n\n df = ipysheet.to_dataframe(sheet)\n assert [_format_date(x) for x in df['A'].tolist()] == ['2019/02/28', '2019/02/27', '2019/02/26', '2019/02/25']\n\n\ndef test_from_dataframe():\n df = pd.DataFrame({\n 'A': 1.,\n 'B': pd.Timestamp('20130102'),\n 'C': pd.Series(1, index=list(range(4)), dtype='float32'),\n 'D': np.array([False, True, False, False], dtype='bool'),\n 'S': pd.Categorical([\"test\", \"train\", \"test\", \"train\"]),\n 'T': 'foo',\n 'X': np.array([0, 3, 9, 18])})\n\n df.loc[[0, 2], ['B']] = np.nan\n\n sheet = ipysheet.from_dataframe(df)\n assert len(sheet.cells) == 7\n assert sheet.cells[0].value == [1., 1., 1., 1.]\n assert sheet.cells[0].type == 'numeric'\n assert sheet.cells[1].value == [None, '2013/01/02', None, '2013/01/02']\n assert sheet.cells[1].type == 'date'\n assert sheet.cells[2].value == [1., 1., 1., 1.]\n assert sheet.cells[2].type == 'numeric'\n assert sheet.cells[2].numeric_format == '0.000'\n assert sheet.cells[3].value == [False, True, False, False]\n assert sheet.cells[3].type == 'checkbox'\n assert sheet.cells[4].value == ['test', 'train', 'test', 'train']\n assert sheet.cells[4].type == 'text'\n assert sheet.cells[5].value == ['foo', 'foo', 'foo', 'foo']\n assert sheet.cells[5].type == 'text'\n assert sheet.cells[6].value == [0, 3, 9, 18]\n assert sheet.cells[6].type == 'numeric'\n assert sheet.cells[6].numeric_format == '0[.]0'\n\n\ndef test_from_to_dataframe():\n df = pd.DataFrame({\n 'A': 1.,\n 'B': pd.Timestamp('20130102'),\n 'C': pd.Series(1, index=list(range(4)), dtype='float32'),\n 'D': np.array([False, True, False, False], dtype='bool'),\n 'S': pd.Categorical([\"test\", \"train\", \"test\", \"train\"]),\n 'T': 'foo'})\n\n df.loc[[0, 2], ['B']] = np.nan\n\n sheet = ipysheet.from_dataframe(df)\n df2 = ipysheet.to_dataframe(sheet)\n\n a = np.array(df.values)\n b = np.array(df2.values)\n assert ((a == b) | (pd.isna(a) & pd.isna(b))).all()\n\n\ndef test_to_array():\n sheet = ipysheet.sheet(rows=5, columns=4)\n ipysheet.cell(0, 0, value=True)\n ipysheet.row(1, value=[2, 34, 543, 23])\n ipysheet.column(3, value=[1.2, 1.3, 1.4, 1.5, 1.6])\n\n arr = ipysheet.to_array(sheet)\n expected = np.array([\n [True, None, None, 1.2],\n [2, 34, 543, 1.3],\n [None, None, None, 1.4],\n [None, None, None, 1.5],\n [None, None, None, 1.6]\n ])\n assert np.all(arr == expected)\n\n\ndef test_from_array():\n arr = np.random.randn(6, 10, 2)\n with pytest.raises(RuntimeError):\n ipysheet.from_array(arr)\n\n arr = np.random.randn(6, 10)\n sheet = ipysheet.from_array(arr)\n assert len(sheet.cells) == 1\n assert sheet.cells[0].type == 'numeric'\n assert sheet.cells[0].value is arr\n assert sheet.rows == 6\n assert sheet.columns == 10\n\n arr = np.array([True, False, True])\n sheet = ipysheet.from_array(arr)\n assert len(sheet.cells) == 1\n assert sheet.cells[0].type == 'checkbox'\n assert sheet.cells[0].value is arr\n assert sheet.rows == 3\n assert sheet.columns == 1\n\n\ndef test_value_types_serialize(kernel):\n # test scalars, list, ndarray and pandas series\n # this test duplicates a bit from test_cell_range and test_row_and_column\n x = np.arange(3)\n y = x**2\n xr = x[::-1]\n x_list = x.tolist()\n xr_list = xr.tolist()\n matrix = np.array([x, y]).T\n matrix_list = matrix.tolist()\n matrix_r = matrix[::, ::-1]\n matrix_list_r = matrix_r.tolist()\n df = pd.DataFrame({'x': x})\n df['y'] = y\n assert not isinstance(df.x, np.ndarray)\n\n cell_scalar = ipysheet.Cell()\n cell_vector = ipysheet.Cell(row_start=0, row_end=2, squeeze_row=False)\n cell_matrix = ipysheet.Cell(row_start=0, row_end=2, column_start=0, column_end=1,\n squeeze_row=False, squeeze_column=False)\n cell_scalar.comm.kernel = kernel\n cell_vector.comm.kernel = kernel\n cell_matrix.comm.kernel = kernel\n\n # scalar\n\n cell_scalar.value = 1\n assert cell_scalar.value == 1\n\n cell_scalar.value = 1.1\n assert cell_scalar.value == 1.1\n\n cell_scalar.value = True\n assert cell_scalar.value is True\n\n cell_scalar.value = 'voila'\n assert cell_scalar.value == 'voila'\n\n cell_scalar.value = np.int64(1)\n assert cell_scalar.value == 1\n\n # vector\n cell_vector.value = x_list\n assert cell_vector.value == x_list\n\n cell_vector.set_state({'value': xr_list})\n assert cell_vector.value == xr_list\n\n # vector+numpy\n cell_vector.value = x\n assert isinstance(cell_vector.value, np.ndarray)\n assert cell_vector.value.tolist() == x.tolist()\n\n # we'd like it to stay a ndarray\n cell_vector.set_state({'value': xr_list})\n assert isinstance(cell_vector.value, np.ndarray)\n assert cell_vector.value.tolist() == xr_list\n\n # vector+series\n cell_vector.value = df.x\n assert cell_vector.value.tolist() == df.x.tolist()\n assert isinstance(cell_vector.value, pd.Series)\n\n # we'd like it to stay a series\n cell_vector.set_state({'value': x_list})\n assert isinstance(cell_vector.value, pd.Series)\n assert cell_vector.value.tolist() == x_list\n\n with pytest.raises(ValueError):\n cell_vector.value = 1\n\n # matrix\n cell_matrix.value = matrix_list\n assert cell_matrix.value == matrix_list\n\n # matrix+numpy\n cell_matrix.value = matrix\n assert isinstance(cell_matrix.value, np.ndarray)\n assert cell_matrix.value.tolist() == matrix_list\n\n # we'd like it to stay a ndarray\n cell_matrix.set_state({'value': matrix_list_r})\n assert isinstance(cell_matrix.value, np.ndarray)\n assert cell_matrix.value.tolist() == matrix_list_r\n\n # matrix+dataframe\n cell_matrix.value = df # pandas to_numpy->tolist() gives the transposed result\n assert adapt_value(cell_matrix.value) == matrix_list\n assert isinstance(cell_matrix.value, pd.DataFrame)\n\n # we'd like it to stay a dataframe\n cell_matrix.set_state({'value': matrix_list})\n assert isinstance(cell_matrix.value, pd.DataFrame)\n assert adapt_value(cell_matrix.value) == matrix_list\n\n with pytest.raises(ValueError):\n cell_matrix.value = 1\n with pytest.raises(ValueError):\n cell_matrix.value = x\n\n # make sure we can still set the widgets, and they serialize\n\n button = widgets.Button()\n slider = widgets.FloatSlider()\n cell_scalar.value = button\n\n cell_vector.value = [slider, button, button]\n cell_vector.set_state(\n {'value': ['IPY_MODEL_' + button.model_id, 'IPY_MODEL_' + slider.model_id, 'IPY_MODEL_' + slider.model_id]})\n assert cell_vector.value == [button, slider, slider]\n\n # even when originally a ndarray\n cell_vector.value = x\n cell_vector.set_state(\n {'value': ['IPY_MODEL_' + button.model_id, 'IPY_MODEL_' + button.model_id, 'IPY_MODEL_' + slider.model_id]})\n assert cell_vector.value == [button, button, slider]\n\n # or series\n # TODO: this code path fails, we can consider it not supported\n # * you cannot change a cell's value from the frontend from to a different type when it's a pandas series\n # cell_vector.value = df.x\n # cell_vector.set_state(\n # {'value': ['IPY_MODEL_' + slider.model_id, 'IPY_MODEL_' + button.model_id, 'IPY_MODEL_' + slider.model_id]})\n # assert cell_vector.value == [slider, button, slider]\n"
] | [
[
"pandas.Timestamp",
"numpy.arange",
"pandas.Categorical",
"pandas.DataFrame",
"numpy.all",
"numpy.int64",
"numpy.random.randn",
"pandas.isna",
"numpy.array"
]
] | [
{
"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": []
}
] |
papamarkou/bnn_mcmc_examples | [
"297cdb1e74335860989bebdb4ff6f6322b6adc06",
"297cdb1e74335860989bebdb4ff6f6322b6adc06",
"297cdb1e74335860989bebdb4ff6f6322b6adc06"
] | [
"bnn_mcmc_examples/examples/mlp/hawks/prior/benchmark_pred_accuracy_via_mean.py",
"bnn_mcmc_examples/examples/mlp/hawks/metropolis_hastings/benchmark_numerical_summary.py",
"bnn_mcmc_examples/examples/mlp/penguins/metropolis_hastings/benchmark_pred_posterior_vals_on_test.py"
] | [
"# %% Load packages\n\nimport numpy as np\nimport torch\n\nfrom sklearn.metrics import accuracy_score\n\nfrom bnn_mcmc_examples.examples.mlp.hawks.constants import num_chains\nfrom bnn_mcmc_examples.examples.mlp.hawks.dataloaders import test_dataloader\nfrom bnn_mcmc_examples.examples.mlp.hawks.prior.constants import sampler_output_path, sampler_output_run_paths\n\n# %% Load test data and labels\n\n_, test_labels = next(iter(test_dataloader))\n\n# %% Compute predictive accuracies\n\naccuracies = np.empty(num_chains)\n\nfor i in range(num_chains):\n test_preds = np.loadtxt(sampler_output_run_paths[i].joinpath('preds_via_mean.txt'), skiprows=0)\n\n accuracies[i] = accuracy_score(test_preds, torch.argmax(test_labels, 1))\n\n# %% Save predictive accuracies\n\nnp.savetxt(sampler_output_path.joinpath('accuracies_via_mean.txt'), accuracies)\n",
"# %% Load packages\n\nimport numpy as np\n\nfrom kanga.chains import ChainArrays\n\nfrom bnn_mcmc_examples.examples.mlp.hawks.constants import diagnostic_iter_thres, num_chains\nfrom bnn_mcmc_examples.examples.mlp.hawks.metropolis_hastings.constants import sampler_output_path, sampler_output_run_paths\n\n# %% Load chain arrays, covariance matrices and runtimes\n\nchain_arrays = ChainArrays.from_file(sampler_output_run_paths, keys=['sample'])\n\nmc_cov_mats = []\nfor i in range(num_chains):\n mc_cov_mats.append(np.loadtxt(sampler_output_run_paths[i].joinpath('mc_cov.csv'), delimiter=',', skiprows=0))\nmc_cov_mats = np.stack(mc_cov_mats)\n\nruntimes = []\nfor i in range(num_chains):\n with open(sampler_output_run_paths[i].joinpath('runtime.txt'), 'r') as file:\n runtimes.append(float(file.readline().rstrip()))\nruntimes = np.array(runtimes)\n\n# %% Drop burn-in samples\n\nchain_arrays.vals['sample'] = chain_arrays.vals['sample'][:, diagnostic_iter_thres:, :]\n\n# %% Compute multivariate rhat\n\nrhat_val, _, _, _, _ = chain_arrays.multi_rhat(mc_cov_mat=mc_cov_mats)\n\n# %% Save rhat_val\n\nwith open(sampler_output_path.joinpath('multi_rhat.txt'), 'w') as file:\n file.write('{}\\n'.format(rhat_val))\n\n# %% Compute multivariate ESS\n\ness_vals = np.array(chain_arrays.multi_ess(mc_cov_mat=mc_cov_mats))\n\n# %% Save multivariate ESSs\n\nfor i in range(num_chains):\n with open(sampler_output_run_paths[i].joinpath('multi_ess.txt'), 'w') as file:\n file.write('{}\\n'.format(ess_vals[i]))\n\n# %% Save mean of multivariate ESSs\n\nwith open(sampler_output_path.joinpath('mean_multi_ess.txt'), 'w') as file:\n file.write('{}\\n'.format(ess_vals.mean()))\n\n# %% Save mean runtime\n\nwith open(sampler_output_path.joinpath('mean_runtime.txt'), 'w') as file:\n file.write('{}\\n'.format(runtimes.mean()))\n",
"# %% Load packages\n\nimport numpy as np\nimport torch\n\nfrom eeyore.chains import ChainLists\n\nfrom bnn_mcmc_examples.examples.mlp.penguins.constants import dtype, num_chains, num_classes, pred_iter_thres\nfrom bnn_mcmc_examples.examples.mlp.penguins.datascanners import test_dataloader\nfrom bnn_mcmc_examples.examples.mlp.penguins.metropolis_hastings.constants import sampler_output_run_paths\nfrom bnn_mcmc_examples.examples.mlp.penguins.model import model\n\n# %% Load chain lists\n\nchain_lists = ChainLists.from_file(sampler_output_run_paths, keys=['sample'], dtype=dtype)\n\n# %% Drop burn-in samples\n\nfor i in range(num_chains):\n chain_lists.vals['sample'][i] = chain_lists.vals['sample'][i][pred_iter_thres:]\n\n# %% Compute and save predictive posteriors\n\nverbose_msg = 'Evaluating predictive posterior based on chain {:' \\\n + str(len(str(num_chains))) \\\n + '} out of ' \\\n + str(num_chains) \\\n + ' at test point {:' \\\n + str(len(str(len(test_dataloader)))) \\\n + '} out of ' \\\n + str(len(test_dataloader)) \\\n + '...'\n\nfor k in range(num_chains):\n test_pred_probs = np.empty([len(test_dataloader), num_classes])\n nums_dropped_samples = np.empty([len(test_dataloader), num_classes], dtype=np.int64)\n\n for i, (x, _) in enumerate(test_dataloader):\n print(verbose_msg.format(k+1, i+1))\n\n for j in range(num_classes):\n y = torch.zeros([1, num_classes], dtype=dtype)\n y[0, j] = 1.\n integral, num_dropped_samples = model.predictive_posterior(chain_lists.vals['sample'][k], x, y)\n test_pred_probs[i, j] = integral.item()\n nums_dropped_samples[i, j] = num_dropped_samples\n\n np.savetxt(sampler_output_run_paths[k].joinpath('pred_posterior_on_test.csv'), test_pred_probs, delimiter=',')\n np.savetxt(\n sampler_output_run_paths[k].joinpath('pred_posterior_on_test_num_dropped_samples.csv'),\n nums_dropped_samples,\n fmt='%d',\n delimiter=','\n )\n"
] | [
[
"numpy.empty",
"torch.argmax"
],
[
"numpy.array",
"numpy.stack"
],
[
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mdovgialo/mne-python | [
"8ccc3999da6c15efa03840230c13aeb7bab5618d",
"8ccc3999da6c15efa03840230c13aeb7bab5618d",
"8ccc3999da6c15efa03840230c13aeb7bab5618d",
"8ccc3999da6c15efa03840230c13aeb7bab5618d",
"8ccc3999da6c15efa03840230c13aeb7bab5618d",
"8ccc3999da6c15efa03840230c13aeb7bab5618d"
] | [
"mne/stats/tests/test_permutations.py",
"mne/beamformer/tests/test_dics.py",
"mne/viz/raw.py",
"tutorials/raw/20_event_arrays.py",
"mne/tests/test_morph_map.py",
"mne/viz/_3d.py"
] | [
"# Authors: Alexandre Gramfort <[email protected]>\n#\n# License: BSD (3-clause)\n\nfrom numpy.testing import assert_array_equal, assert_allclose\nimport numpy as np\nfrom scipy import stats, sparse\n\nfrom mne.stats import permutation_cluster_1samp_test\nfrom mne.stats.permutations import (permutation_t_test, _ci,\n bootstrap_confidence_interval)\nfrom mne.utils import check_version\n\n\ndef test_permutation_t_test():\n \"\"\"Test T-test based on permutations.\"\"\"\n # 1 sample t-test\n np.random.seed(10)\n n_samples, n_tests = 30, 5\n X = np.random.randn(n_samples, n_tests)\n X[:, :2] += 1\n\n t_obs, p_values, H0 = permutation_t_test(\n X, n_permutations=999, tail=0, seed=0)\n assert (p_values > 0).all()\n assert len(H0) == 999\n is_significant = p_values < 0.05\n assert_array_equal(is_significant, [True, True, False, False, False])\n\n t_obs, p_values, H0 = permutation_t_test(\n X, n_permutations=999, tail=1, seed=0)\n assert (p_values > 0).all()\n assert len(H0) == 999\n is_significant = p_values < 0.05\n assert_array_equal(is_significant, [True, True, False, False, False])\n\n t_obs, p_values, H0 = permutation_t_test(\n X, n_permutations=999, tail=-1, seed=0)\n is_significant = p_values < 0.05\n assert_array_equal(is_significant, [False, False, False, False, False])\n\n X *= -1\n t_obs, p_values, H0 = permutation_t_test(\n X, n_permutations=999, tail=-1, seed=0)\n assert (p_values > 0).all()\n assert len(H0) == 999\n is_significant = p_values < 0.05\n assert_array_equal(is_significant, [True, True, False, False, False])\n\n # check equivalence with spatio_temporal_cluster_test\n for adjacency in (sparse.eye(n_tests), False):\n t_obs_clust, _, p_values_clust, _ = permutation_cluster_1samp_test(\n X, n_permutations=999, seed=0, adjacency=adjacency,\n out_type='mask')\n # the cluster tests drop any clusters that don't get thresholded\n keep = p_values < 1\n assert_allclose(t_obs_clust, t_obs)\n assert_allclose(p_values_clust, p_values[keep], atol=1e-2)\n\n X = np.random.randn(18, 1)\n t_obs, p_values, H0 = permutation_t_test(X, n_permutations='all')\n t_obs_scipy, p_values_scipy = stats.ttest_1samp(X[:, 0], 0)\n assert_allclose(t_obs[0], t_obs_scipy, 8)\n assert_allclose(p_values[0], p_values_scipy, rtol=1e-2)\n\n\ndef test_ci():\n \"\"\"Test confidence intervals.\"\"\"\n # isolated test of CI functions\n arr = np.linspace(0, 1, 1000)[..., np.newaxis]\n assert_allclose(_ci(arr, method=\"parametric\"),\n _ci(arr, method=\"bootstrap\"), rtol=.005)\n assert_allclose(bootstrap_confidence_interval(arr, stat_fun=\"median\",\n random_state=0),\n bootstrap_confidence_interval(arr, stat_fun=\"mean\",\n random_state=0),\n rtol=.1)\n # smoke test for new API\n if check_version('numpy', '1.17'):\n random_state = np.random.default_rng(0)\n bootstrap_confidence_interval(arr, random_state=random_state)\n",
"# Authors: Marijn van Vliet <[email protected]>\n# Britta Westner <[email protected]>\n#\n# License: BSD 3 clause\n\nimport copy as cp\nimport os.path as op\n\nimport pytest\nfrom numpy.testing import assert_array_equal, assert_allclose\nimport numpy as np\n\nimport mne\nfrom mne.datasets import testing\nfrom mne.beamformer import (make_dics, apply_dics, apply_dics_epochs,\n apply_dics_csd, read_beamformer, Beamformer)\nfrom mne.beamformer._compute_beamformer import _prepare_beamformer_input\nfrom mne.beamformer._dics import _prepare_noise_csd\nfrom mne.time_frequency import csd_morlet\nfrom mne.utils import object_diff, requires_h5py, catch_logging\nfrom mne.proj import compute_proj_evoked, make_projector\nfrom mne.surface import _compute_nearest\nfrom mne.beamformer.tests.test_lcmv import _assert_weight_norm\nfrom mne.time_frequency import CrossSpectralDensity\nfrom mne.time_frequency.csd import _sym_mat_to_vector\n\ndata_path = testing.data_path(download=False)\nfname_raw = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc_raw.fif')\nfname_fwd = op.join(data_path, 'MEG', 'sample',\n 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif')\nfname_fwd_vol = op.join(data_path, 'MEG', 'sample',\n 'sample_audvis_trunc-meg-vol-7-fwd.fif')\nfname_event = op.join(data_path, 'MEG', 'sample',\n 'sample_audvis_trunc_raw-eve.fif')\n\nsubjects_dir = op.join(data_path, 'subjects')\n\n\[email protected](scope='module', params=[testing._pytest_param()])\ndef _load_forward():\n \"\"\"Load forward models.\"\"\"\n fwd_free = mne.read_forward_solution(fname_fwd)\n fwd_free = mne.pick_types_forward(fwd_free, meg=True, eeg=False)\n fwd_free = mne.convert_forward_solution(fwd_free, surf_ori=False)\n fwd_surf = mne.convert_forward_solution(fwd_free, surf_ori=True,\n use_cps=False)\n fwd_fixed = mne.convert_forward_solution(fwd_free, force_fixed=True,\n use_cps=False)\n fwd_vol = mne.read_forward_solution(fname_fwd_vol)\n return fwd_free, fwd_surf, fwd_fixed, fwd_vol\n\n\ndef _simulate_data(fwd, idx): # Somewhere on the frontal lobe by default\n \"\"\"Simulate an oscillator on the cortex.\"\"\"\n source_vertno = fwd['src'][0]['vertno'][idx]\n\n sfreq = 50. # Hz.\n times = np.arange(10 * sfreq) / sfreq # 10 seconds of data\n signal = np.sin(20 * 2 * np.pi * times) # 20 Hz oscillator\n signal[:len(times) // 2] *= 2 # Make signal louder at the beginning\n signal *= 1e-9 # Scale to be in the ballpark of MEG data\n\n # Construct a SourceEstimate object that describes the signal at the\n # cortical level.\n stc = mne.SourceEstimate(\n signal[np.newaxis, :],\n vertices=[[source_vertno], []],\n tmin=0,\n tstep=1 / sfreq,\n subject='sample',\n )\n\n # Create an info object that holds information about the sensors\n info = mne.create_info(fwd['info']['ch_names'], sfreq, ch_types='grad')\n info.update(fwd['info']) # Merge in sensor position information\n # heavily decimate sensors to make it much faster\n info = mne.pick_info(info, np.arange(info['nchan'])[::5])\n fwd = mne.pick_channels_forward(fwd, info['ch_names'])\n\n # Run the simulated signal through the forward model, obtaining\n # simulated sensor data.\n raw = mne.apply_forward_raw(fwd, stc, info)\n\n # Add a little noise\n random = np.random.RandomState(42)\n noise = random.randn(*raw._data.shape) * 1e-14\n raw._data += noise\n\n # Define a single epoch (weird baseline but shouldn't matter)\n epochs = mne.Epochs(raw, [[0, 0, 1]], event_id=1, tmin=0,\n tmax=raw.times[-1], baseline=(0., 0.), preload=True)\n evoked = epochs.average()\n\n # Compute the cross-spectral density matrix\n csd = csd_morlet(epochs, frequencies=[10, 20], n_cycles=[5, 10], decim=5)\n\n labels = mne.read_labels_from_annot(\n 'sample', hemi='lh', subjects_dir=subjects_dir)\n label = [\n label for label in labels if np.in1d(source_vertno, label.vertices)[0]]\n assert len(label) == 1\n label = label[0]\n vertices = np.intersect1d(label.vertices, fwd['src'][0]['vertno'])\n source_ind = vertices.tolist().index(source_vertno)\n assert vertices[source_ind] == source_vertno\n return epochs, evoked, csd, source_vertno, label, vertices, source_ind\n\n\nidx_param = pytest.mark.parametrize('idx', [\n 0,\n pytest.param(100, marks=pytest.mark.slowtest),\n 200,\n pytest.param(233, marks=pytest.mark.slowtest),\n])\n\n\ndef _rand_csd(rng, info):\n scales = mne.make_ad_hoc_cov(info).data\n n = scales.size\n # Some random complex correlation structure (with channel scalings)\n data = rng.randn(n, n) + 1j * rng.randn(n, n)\n data = data @ data.conj().T\n data *= scales\n data *= scales[:, np.newaxis]\n data.flat[::n + 1] = scales\n return data\n\n\ndef _make_rand_csd(info, csd):\n rng = np.random.RandomState(0)\n data = _rand_csd(rng, info)\n # now we need to have the same null space as the data csd\n s, u = np.linalg.eigh(csd.get_data(csd.frequencies[0]))\n mask = np.abs(s) >= s[-1] * 1e-7\n rank = mask.sum()\n assert rank == len(data) == len(info['ch_names'])\n noise_csd = CrossSpectralDensity(\n _sym_mat_to_vector(data), info['ch_names'], 0., csd.n_fft)\n return noise_csd, rank\n\n\[email protected]\[email protected]_testing_data\n@requires_h5py\n@idx_param\[email protected]('whiten', [\n pytest.param(False, marks=pytest.mark.slowtest),\n True,\n])\ndef test_make_dics(tmpdir, _load_forward, idx, whiten):\n \"\"\"Test making DICS beamformer filters.\"\"\"\n # We only test proper handling of parameters here. Testing the results is\n # done in test_apply_dics_timeseries and test_apply_dics_csd.\n\n fwd_free, fwd_surf, fwd_fixed, fwd_vol = _load_forward\n epochs, _, csd, _, label, vertices, source_ind = \\\n _simulate_data(fwd_fixed, idx)\n with pytest.raises(ValueError, match='several sensor types'):\n make_dics(epochs.info, fwd_surf, csd, label=label, pick_ori=None)\n if whiten:\n noise_csd, rank = _make_rand_csd(epochs.info, csd)\n assert rank == len(epochs.info['ch_names']) == 62\n else:\n noise_csd = None\n epochs.pick_types(meg='grad')\n\n with pytest.raises(ValueError, match=\"Invalid value for the 'pick_ori'\"):\n make_dics(epochs.info, fwd_fixed, csd, pick_ori=\"notexistent\",\n noise_csd=noise_csd)\n with pytest.raises(ValueError, match='rank, if str'):\n make_dics(epochs.info, fwd_fixed, csd, rank='foo', noise_csd=noise_csd)\n with pytest.raises(TypeError, match='rank must be'):\n make_dics(epochs.info, fwd_fixed, csd, rank=1., noise_csd=noise_csd)\n\n # Test if fixed forward operator is detected when picking normal\n # orientation\n with pytest.raises(ValueError, match='forward operator with free ori'):\n make_dics(epochs.info, fwd_fixed, csd, pick_ori=\"normal\",\n noise_csd=noise_csd)\n\n # Test if non-surface oriented forward operator is detected when picking\n # normal orientation\n with pytest.raises(ValueError, match='oriented in surface coordinates'):\n make_dics(epochs.info, fwd_free, csd, pick_ori=\"normal\",\n noise_csd=noise_csd)\n\n # Test if volume forward operator is detected when picking normal\n # orientation\n with pytest.raises(ValueError, match='oriented in surface coordinates'):\n make_dics(epochs.info, fwd_vol, csd, pick_ori=\"normal\",\n noise_csd=noise_csd)\n\n # Test invalid combinations of parameters\n with pytest.raises(ValueError, match='reduce_rank cannot be used with'):\n make_dics(epochs.info, fwd_free, csd, inversion='single',\n reduce_rank=True, noise_csd=noise_csd)\n # TODO: Restore this?\n # with pytest.raises(ValueError, match='not stable with depth'):\n # make_dics(epochs.info, fwd_free, csd, weight_norm='unit-noise-gain',\n # inversion='single', depth=None)\n\n # Sanity checks on the returned filters\n n_freq = len(csd.frequencies)\n vertices = np.intersect1d(label.vertices, fwd_free['src'][0]['vertno'])\n n_verts = len(vertices)\n n_orient = 3\n\n n_channels = len(epochs.ch_names)\n # Test return values\n weight_norm = 'unit-noise-gain'\n inversion = 'single'\n filters = make_dics(epochs.info, fwd_surf, csd, label=label, pick_ori=None,\n weight_norm=weight_norm, depth=None, real_filter=False,\n noise_csd=noise_csd, inversion=inversion)\n assert filters['weights'].shape == (n_freq, n_verts * n_orient, n_channels)\n assert np.iscomplexobj(filters['weights'])\n assert filters['csd'].ch_names == epochs.ch_names\n assert isinstance(filters['csd'], CrossSpectralDensity)\n assert filters['ch_names'] == epochs.ch_names\n assert_array_equal(filters['proj'], np.eye(n_channels))\n assert_array_equal(filters['vertices'][0], vertices)\n assert_array_equal(filters['vertices'][1], []) # Label was on the LH\n assert filters['subject'] == fwd_free['src']._subject\n assert filters['pick_ori'] is None\n assert filters['is_free_ori']\n assert filters['inversion'] == inversion\n assert filters['weight_norm'] == weight_norm\n assert 'DICS' in repr(filters)\n assert 'subject \"sample\"' in repr(filters)\n assert str(len(vertices)) in repr(filters)\n assert str(n_channels) in repr(filters)\n assert 'rank' not in repr(filters)\n _, noise_cov = _prepare_noise_csd(csd, noise_csd, real_filter=False)\n _, _, _, _, G, _, _, _ = _prepare_beamformer_input(\n epochs.info, fwd_surf, label, 'vector', combine_xyz=False, exp=None,\n noise_cov=noise_cov)\n G.shape = (n_channels, n_verts, n_orient)\n G = G.transpose(1, 2, 0).conj() # verts, orient, ch\n _assert_weight_norm(filters, G)\n\n inversion = 'matrix'\n filters = make_dics(epochs.info, fwd_surf, csd, label=label, pick_ori=None,\n weight_norm=weight_norm, depth=None,\n noise_csd=noise_csd, inversion=inversion)\n _assert_weight_norm(filters, G)\n\n weight_norm = 'unit-noise-gain-invariant'\n inversion = 'single'\n filters = make_dics(epochs.info, fwd_surf, csd, label=label, pick_ori=None,\n weight_norm=weight_norm, depth=None,\n noise_csd=noise_csd, inversion=inversion)\n _assert_weight_norm(filters, G)\n\n # Test picking orientations. Also test weight norming under these different\n # conditions.\n weight_norm = 'unit-noise-gain'\n filters = make_dics(epochs.info, fwd_surf, csd, label=label,\n pick_ori='normal', weight_norm=weight_norm,\n depth=None, noise_csd=noise_csd, inversion=inversion)\n n_orient = 1\n assert filters['weights'].shape == (n_freq, n_verts * n_orient, n_channels)\n assert not filters['is_free_ori']\n _assert_weight_norm(filters, G)\n\n filters = make_dics(epochs.info, fwd_surf, csd, label=label,\n pick_ori='max-power', weight_norm=weight_norm,\n depth=None, noise_csd=noise_csd, inversion=inversion)\n n_orient = 1\n assert filters['weights'].shape == (n_freq, n_verts * n_orient, n_channels)\n assert not filters['is_free_ori']\n _assert_weight_norm(filters, G)\n\n # From here on, only work on a single frequency\n csd = csd[0]\n\n # Test using a real-valued filter\n filters = make_dics(epochs.info, fwd_surf, csd, label=label,\n pick_ori='normal', real_filter=True,\n noise_csd=noise_csd)\n assert not np.iscomplexobj(filters['weights'])\n\n # Test forward normalization. When inversion='single', the power of a\n # unit-noise CSD should be 1, even without weight normalization.\n if not whiten:\n csd_noise = csd.copy()\n inds = np.triu_indices(csd.n_channels)\n # Using [:, :] syntax for in-place broadcasting\n csd_noise._data[:, :] = np.eye(csd.n_channels)[inds][:, np.newaxis]\n filters = make_dics(epochs.info, fwd_surf, csd_noise, label=label,\n weight_norm=None, depth=1., noise_csd=noise_csd,\n inversion='single')\n w = filters['weights'][0][:3]\n assert_allclose(np.diag(w.dot(w.conjugate().T)), 1.0, rtol=1e-6,\n atol=0)\n\n # Test turning off both forward and weight normalization\n filters = make_dics(epochs.info, fwd_surf, csd, label=label,\n weight_norm=None, depth=None, noise_csd=noise_csd)\n w = filters['weights'][0][:3]\n assert not np.allclose(np.diag(w.dot(w.conjugate().T)), 1.0,\n rtol=1e-2, atol=0)\n\n # Test neural-activity-index weight normalization. It should be a scaled\n # version of the unit-noise-gain beamformer.\n filters_nai = make_dics(\n epochs.info, fwd_surf, csd, label=label, pick_ori='max-power',\n weight_norm='nai', depth=None, noise_csd=noise_csd)\n w_nai = filters_nai['weights'][0]\n filters_ung = make_dics(\n epochs.info, fwd_surf, csd, label=label, pick_ori='max-power',\n weight_norm='unit-noise-gain', depth=None, noise_csd=noise_csd)\n w_ung = filters_ung['weights'][0]\n assert_allclose(np.corrcoef(np.abs(w_nai).ravel(),\n np.abs(w_ung).ravel()), 1, atol=1e-7)\n\n # Test whether spatial filter contains src_type\n assert 'src_type' in filters\n\n fname = op.join(str(tmpdir), 'filters-dics.h5')\n filters.save(fname)\n filters_read = read_beamformer(fname)\n assert isinstance(filters, Beamformer)\n assert isinstance(filters_read, Beamformer)\n for key in ['tmin', 'tmax']: # deal with strictness of object_diff\n setattr(filters['csd'], key, np.float64(getattr(filters['csd'], key)))\n assert object_diff(filters, filters_read) == ''\n\n\ndef _fwd_dist(power, fwd, vertices, source_ind, tidx=1):\n idx = np.argmax(power.data[:, tidx])\n rr_got = fwd['src'][0]['rr'][vertices[idx]]\n rr_want = fwd['src'][0]['rr'][vertices[source_ind]]\n return np.linalg.norm(rr_got - rr_want)\n\n\n@idx_param\[email protected]('inversion, weight_norm', [\n ('single', None),\n ('matrix', 'unit-noise-gain'),\n])\ndef test_apply_dics_csd(_load_forward, idx, inversion, weight_norm):\n \"\"\"Test applying a DICS beamformer to a CSD matrix.\"\"\"\n fwd_free, fwd_surf, fwd_fixed, _ = _load_forward\n epochs, _, csd, source_vertno, label, vertices, source_ind = \\\n _simulate_data(fwd_fixed, idx)\n reg = 1 # Lots of regularization for our toy dataset\n\n with pytest.raises(ValueError, match='several sensor types'):\n make_dics(epochs.info, fwd_free, csd)\n epochs.pick_types(meg='grad')\n\n # Try different types of forward models\n assert label.hemi == 'lh'\n for fwd in [fwd_free, fwd_surf, fwd_fixed]:\n filters = make_dics(epochs.info, fwd, csd, label=label, reg=reg,\n inversion=inversion, weight_norm=weight_norm)\n power, f = apply_dics_csd(csd, filters)\n assert f == [10, 20]\n\n # Did we find the true source at 20 Hz?\n dist = _fwd_dist(power, fwd_free, vertices, source_ind)\n assert dist == 0.\n\n # Is the signal stronger at 20 Hz than 10?\n assert power.data[source_ind, 1] > power.data[source_ind, 0]\n\n\[email protected]('pick_ori', [None, 'normal', 'max-power'])\[email protected]('inversion', ['single', 'matrix'])\n@idx_param\ndef test_apply_dics_ori_inv(_load_forward, pick_ori, inversion, idx):\n \"\"\"Test picking different orientations and inversion modes.\"\"\"\n fwd_free, fwd_surf, fwd_fixed, fwd_vol = _load_forward\n epochs, _, csd, source_vertno, label, vertices, source_ind = \\\n _simulate_data(fwd_fixed, idx)\n epochs.pick_types(meg='grad')\n\n reg_ = 5 if inversion == 'matrix' else 1\n filters = make_dics(epochs.info, fwd_surf, csd, label=label,\n reg=reg_, pick_ori=pick_ori,\n inversion=inversion, depth=None,\n weight_norm='unit-noise-gain')\n power, f = apply_dics_csd(csd, filters)\n assert f == [10, 20]\n dist = _fwd_dist(power, fwd_surf, vertices, source_ind)\n # This is 0. for unit-noise-gain-invariant:\n assert dist <= (0.02 if inversion == 'matrix' else 0.)\n assert power.data[source_ind, 1] > power.data[source_ind, 0]\n\n # Test unit-noise-gain weighting\n csd_noise = csd.copy()\n inds = np.triu_indices(csd.n_channels)\n csd_noise._data[...] = np.eye(csd.n_channels)[inds][:, np.newaxis]\n noise_power, f = apply_dics_csd(csd_noise, filters)\n want_norm = 3 if pick_ori is None else 1.\n assert_allclose(noise_power.data, want_norm, atol=1e-7)\n\n # Test filter with forward normalization instead of weight\n # normalization\n filters = make_dics(epochs.info, fwd_surf, csd, label=label,\n reg=reg_, pick_ori=pick_ori,\n inversion=inversion, weight_norm=None,\n depth=1.)\n power, f = apply_dics_csd(csd, filters)\n assert f == [10, 20]\n dist = _fwd_dist(power, fwd_surf, vertices, source_ind)\n mat_tol = {0: 0.055, 100: 0.20, 200: 0.015, 233: 0.035}[idx]\n max_ = (mat_tol if inversion == 'matrix' else 0.)\n assert 0 <= dist <= max_\n assert power.data[source_ind, 1] > power.data[source_ind, 0]\n\n\ndef _nearest_vol_ind(fwd_vol, fwd, vertices, source_ind):\n return _compute_nearest(\n fwd_vol['source_rr'],\n fwd['src'][0]['rr'][vertices][source_ind][np.newaxis])[0]\n\n\n@idx_param\ndef test_real(_load_forward, idx):\n \"\"\"Test using a real-valued filter.\"\"\"\n fwd_free, fwd_surf, fwd_fixed, fwd_vol = _load_forward\n epochs, _, csd, source_vertno, label, vertices, source_ind = \\\n _simulate_data(fwd_fixed, idx)\n epochs.pick_types(meg='grad')\n reg = 1 # Lots of regularization for our toy dataset\n filters_real = make_dics(epochs.info, fwd_surf, csd, label=label, reg=reg,\n real_filter=True, inversion='single')\n # Also test here that no warings are thrown - implemented to check whether\n # src should not be None warning occurs:\n with pytest.warns(None) as w:\n power, f = apply_dics_csd(csd, filters_real)\n assert len(w) == 0\n\n assert f == [10, 20]\n dist = _fwd_dist(power, fwd_surf, vertices, source_ind)\n assert dist == 0\n assert power.data[source_ind, 1] > power.data[source_ind, 0]\n\n # Test rank reduction\n filters_real = make_dics(epochs.info, fwd_surf, csd, label=label, reg=5,\n pick_ori='max-power', inversion='matrix',\n reduce_rank=True)\n power, f = apply_dics_csd(csd, filters_real)\n assert f == [10, 20]\n dist = _fwd_dist(power, fwd_surf, vertices, source_ind)\n assert dist == 0\n assert power.data[source_ind, 1] > power.data[source_ind, 0]\n\n # Test computing source power on a volume source space\n filters_vol = make_dics(epochs.info, fwd_vol, csd, reg=reg,\n inversion='single')\n power, f = apply_dics_csd(csd, filters_vol)\n vol_source_ind = _nearest_vol_ind(fwd_vol, fwd_surf, vertices, source_ind)\n assert f == [10, 20]\n dist = _fwd_dist(\n power, fwd_vol, fwd_vol['src'][0]['vertno'], vol_source_ind)\n vol_tols = {100: 0.008, 200: 0.008}\n assert dist <= vol_tols.get(idx, 0.)\n assert power.data[vol_source_ind, 1] > power.data[vol_source_ind, 0]\n\n # check whether a filters object without src_type throws expected warning\n del filters_vol['src_type'] # emulate 0.16 behaviour to cause warning\n with pytest.warns(RuntimeWarning, match='spatial filter does not contain '\n 'src_type'):\n apply_dics_csd(csd, filters_vol)\n\n\[email protected](\"ignore:The use of several sensor types with the\"\n \":RuntimeWarning\")\n@idx_param\ndef test_apply_dics_timeseries(_load_forward, idx):\n \"\"\"Test DICS applied to timeseries data.\"\"\"\n fwd_free, fwd_surf, fwd_fixed, fwd_vol = _load_forward\n epochs, evoked, csd, source_vertno, label, vertices, source_ind = \\\n _simulate_data(fwd_fixed, idx)\n reg = 5 # Lots of regularization for our toy dataset\n\n with pytest.raises(ValueError, match='several sensor types'):\n make_dics(evoked.info, fwd_surf, csd)\n evoked.pick_types(meg='grad')\n\n multiple_filters = make_dics(evoked.info, fwd_surf, csd, label=label,\n reg=reg)\n\n # Sanity checks on the resulting STC after applying DICS on evoked\n stcs = apply_dics(evoked, multiple_filters)\n assert isinstance(stcs, list)\n assert len(stcs) == len(multiple_filters['weights'])\n assert_array_equal(stcs[0].vertices[0], multiple_filters['vertices'][0])\n assert_array_equal(stcs[0].vertices[1], multiple_filters['vertices'][1])\n assert_allclose(stcs[0].times, evoked.times)\n\n # Applying filters for multiple frequencies on epoch data should fail\n with pytest.raises(ValueError, match='computed for a single frequency'):\n apply_dics_epochs(epochs, multiple_filters)\n\n # From now on, only apply filters with a single frequency (20 Hz).\n csd20 = csd.pick_frequency(20)\n filters = make_dics(evoked.info, fwd_surf, csd20, label=label, reg=reg,\n inversion='single')\n\n # Sanity checks on the resulting STC after applying DICS on epochs.\n # Also test here that no warnings are thrown - implemented to check whether\n # src should not be None warning occurs\n with pytest.warns(None) as w:\n stcs = apply_dics_epochs(epochs, filters)\n assert len(w) == 0\n\n assert isinstance(stcs, list)\n assert len(stcs) == 1\n assert_array_equal(stcs[0].vertices[0], filters['vertices'][0])\n assert_array_equal(stcs[0].vertices[1], filters['vertices'][1])\n assert_allclose(stcs[0].times, epochs.times)\n\n # Did we find the source?\n stc = (stcs[0] ** 2).mean()\n dist = _fwd_dist(stc, fwd_surf, vertices, source_ind, tidx=0)\n assert dist == 0\n\n # Apply filters to evoked\n stc = apply_dics(evoked, filters)\n stc = (stc ** 2).mean()\n dist = _fwd_dist(stc, fwd_surf, vertices, source_ind, tidx=0)\n assert dist == 0\n\n # Test if wrong channel selection is detected in application of filter\n evoked_ch = cp.deepcopy(evoked)\n evoked_ch.pick_channels(evoked_ch.ch_names[:-1])\n with pytest.raises(ValueError, match='MEG 2633 which is not present'):\n apply_dics(evoked_ch, filters)\n\n # Test whether projections are applied, by adding a custom projection\n filters_noproj = make_dics(evoked.info, fwd_surf, csd20, label=label)\n stc_noproj = apply_dics(evoked, filters_noproj)\n evoked_proj = evoked.copy()\n p = compute_proj_evoked(evoked_proj, n_grad=1, n_mag=0, n_eeg=0)\n proj_matrix = make_projector(p, evoked_proj.ch_names)[0]\n evoked_proj.info['projs'] += p\n filters_proj = make_dics(evoked_proj.info, fwd_surf, csd20, label=label)\n assert_array_equal(filters_proj['proj'], proj_matrix)\n stc_proj = apply_dics(evoked_proj, filters_proj)\n assert np.any(np.not_equal(stc_noproj.data, stc_proj.data))\n\n # Test detecting incompatible projections\n filters_proj['proj'] = filters_proj['proj'][:-1, :-1]\n with pytest.raises(ValueError, match='operands could not be broadcast'):\n apply_dics(evoked_proj, filters_proj)\n\n # Test returning a generator\n stcs = apply_dics_epochs(epochs, filters, return_generator=False)\n stcs_gen = apply_dics_epochs(epochs, filters, return_generator=True)\n assert_array_equal(stcs[0].data, next(stcs_gen).data)\n\n # Test computing timecourses on a volume source space\n filters_vol = make_dics(evoked.info, fwd_vol, csd20, reg=reg,\n inversion='single')\n stc = apply_dics(evoked, filters_vol)\n stc = (stc ** 2).mean()\n assert stc.data.shape[1] == 1\n vol_source_ind = _nearest_vol_ind(fwd_vol, fwd_surf, vertices, source_ind)\n dist = _fwd_dist(stc, fwd_vol, fwd_vol['src'][0]['vertno'], vol_source_ind,\n tidx=0)\n vol_tols = {100: 0.008, 200: 0.015}\n vol_tol = vol_tols.get(idx, 0.)\n assert dist <= vol_tol\n\n # check whether a filters object without src_type throws expected warning\n del filters_vol['src_type'] # emulate 0.16 behaviour to cause warning\n with pytest.warns(RuntimeWarning, match='filter does not contain src_typ'):\n apply_dics_epochs(epochs, filters_vol)\n\n\ndef _cov_as_csd(cov, info):\n rng = np.random.RandomState(0)\n assert cov['data'].ndim == 2\n assert len(cov['data']) == len(cov['names'])\n # we need to make this have at least some complex structure\n data = cov['data'] + 1e-1 * _rand_csd(rng, info)\n assert data.dtype == np.complex128\n return CrossSpectralDensity(_sym_mat_to_vector(data), cov['names'], 0., 16)\n\n\n# Just test free ori here (assume fixed is same as LCMV if these are)\n# Changes here should be synced with test_lcmv.py\[email protected]\[email protected](\n 'reg, pick_ori, weight_norm, use_cov, depth, lower, upper, real_filter', [\n (0.05, None, 'unit-noise-gain-invariant', False, None, 26, 28, False),\n (0.05, None, 'unit-noise-gain-invariant', True, None, 40, 42, False),\n (0.05, None, 'unit-noise-gain-invariant', True, None, 40, 42, True),\n (0.05, None, 'unit-noise-gain', False, None, 13, 14, False),\n (0.05, None, 'unit-noise-gain', True, None, 35, 37, False),\n (0.05, None, 'nai', True, None, 35, 37, False),\n (0.05, None, None, True, None, 12, 14, False),\n (0.05, None, None, True, 0.8, 39, 43, False),\n (0.05, 'max-power', 'unit-noise-gain-invariant', False, None, 17, 20,\n False),\n (0.05, 'max-power', 'unit-noise-gain', False, None, 17, 20, False),\n (0.05, 'max-power', 'unit-noise-gain', False, None, 17, 20, True),\n (0.05, 'max-power', 'nai', True, None, 21, 24, False),\n (0.05, 'max-power', None, True, None, 7, 10, False),\n (0.05, 'max-power', None, True, 0.8, 15, 18, False),\n # skip most no-reg tests, assume others are equal to LCMV if these are\n (0.00, None, None, True, None, 21, 32, False),\n (0.00, 'max-power', None, True, None, 13, 19, False),\n ])\ndef test_localization_bias_free(bias_params_free, reg, pick_ori, weight_norm,\n use_cov, depth, lower, upper, real_filter):\n \"\"\"Test localization bias for free-orientation DICS.\"\"\"\n evoked, fwd, noise_cov, data_cov, want = bias_params_free\n noise_csd = _cov_as_csd(noise_cov, evoked.info)\n data_csd = _cov_as_csd(data_cov, evoked.info)\n del noise_cov, data_cov\n if not use_cov:\n evoked.pick_types(meg='grad')\n noise_csd = None\n loc = apply_dics(evoked, make_dics(\n evoked.info, fwd, data_csd, reg, noise_csd, pick_ori=pick_ori,\n weight_norm=weight_norm, depth=depth, real_filter=real_filter)).data\n loc = np.linalg.norm(loc, axis=1) if pick_ori == 'vector' else np.abs(loc)\n # Compute the percentage of sources for which there is no loc bias:\n perc = (want == np.argmax(loc, axis=0)).mean() * 100\n assert lower <= perc <= upper\n\n\[email protected]_testing_data\n@idx_param\[email protected]('whiten', (False, True))\ndef test_make_dics_rank(_load_forward, idx, whiten):\n \"\"\"Test making DICS beamformer filters with rank param.\"\"\"\n _, fwd_surf, fwd_fixed, _ = _load_forward\n epochs, _, csd, _, label, _, _ = _simulate_data(fwd_fixed, idx)\n if whiten:\n noise_csd, want_rank = _make_rand_csd(epochs.info, csd)\n kind = 'mag + grad'\n else:\n noise_csd = None\n epochs.pick_types(meg='grad')\n want_rank = len(epochs.ch_names)\n assert want_rank == 41\n kind = 'grad'\n\n with catch_logging() as log:\n filters = make_dics(\n epochs.info, fwd_surf, csd, label=label, noise_csd=noise_csd,\n verbose=True)\n log = log.getvalue()\n assert f'Estimated rank ({kind}): {want_rank}' in log, log\n stc, _ = apply_dics_csd(csd, filters)\n other_rank = want_rank - 1 # shouldn't make a huge difference\n use_rank = dict(meg=other_rank)\n if not whiten:\n # XXX it's a bug that our rank functions don't treat \"meg\"\n # properly here...\n use_rank['grad'] = use_rank.pop('meg')\n with catch_logging() as log:\n filters_2 = make_dics(\n epochs.info, fwd_surf, csd, label=label, noise_csd=noise_csd,\n rank=use_rank, verbose=True)\n log = log.getvalue()\n assert f'Computing rank from covariance with rank={use_rank}' in log, log\n stc_2, _ = apply_dics_csd(csd, filters_2)\n corr = np.corrcoef(stc_2.data.ravel(), stc.data.ravel())[0, 1]\n assert 0.8 < corr < 0.99999\n\n # degenerate conditions\n if whiten:\n # make rank deficient\n data = noise_csd.get_data(0.)\n data[0] = data[:0] = 0\n noise_csd._data[:, 0] = _sym_mat_to_vector(data)\n with pytest.raises(ValueError, match='meg data rank.*the noise rank'):\n filters = make_dics(\n epochs.info, fwd_surf, csd, label=label, noise_csd=noise_csd,\n verbose=True)\n",
"\"\"\"Functions to plot raw M/EEG data.\"\"\"\n\n# Authors: Eric Larson <[email protected]>\n# Jaakko Leppakangas <[email protected]>\n# Daniel McCloy <[email protected]>\n#\n# License: Simplified BSD\n\nfrom functools import partial\nfrom collections import OrderedDict\n\nimport numpy as np\n\nfrom ..annotations import _annotations_starts_stops\nfrom ..filter import create_filter\nfrom ..io.pick import pick_types, _pick_data_channels, pick_info, pick_channels\nfrom ..utils import verbose, _validate_type, _check_option\nfrom ..time_frequency import psd_welch\nfrom ..defaults import _handle_default\nfrom .topo import _plot_topo, _plot_timeseries, _plot_timeseries_unified\nfrom .utils import (plt_show, _compute_scalings, _handle_decim, _check_cov,\n _shorten_path_from_middle,\n _get_channel_plotting_order, _make_event_color_dict)\n\n_RAW_CLIP_DEF = 1.5\n\n\n@verbose\ndef plot_raw(raw, events=None, duration=10.0, start=0.0, n_channels=20,\n bgcolor='w', color=None, bad_color=(0.8, 0.8, 0.8),\n event_color='cyan', scalings=None, remove_dc=True, order=None,\n show_options=False, title=None, show=True, block=False,\n highpass=None, lowpass=None, filtorder=4,\n clipping=_RAW_CLIP_DEF,\n show_first_samp=False, proj=True, group_by='type',\n butterfly=False, decim='auto', noise_cov=None, event_id=None,\n show_scrollbars=True, show_scalebars=True, verbose=None):\n \"\"\"Plot raw data.\n\n Parameters\n ----------\n raw : instance of Raw\n The raw data to plot.\n events : array | None\n Events to show with vertical bars.\n duration : float\n Time window (s) to plot. The lesser of this value and the duration\n of the raw file will be used.\n start : float\n Initial time to show (can be changed dynamically once plotted). If\n show_first_samp is True, then it is taken relative to\n ``raw.first_samp``.\n n_channels : int\n Number of channels to plot at once. Defaults to 20. The lesser of\n ``n_channels`` and ``len(raw.ch_names)`` will be shown.\n Has no effect if ``order`` is 'position', 'selection' or 'butterfly'.\n bgcolor : color object\n Color of the background.\n color : dict | color object | None\n Color for the data traces. If None, defaults to::\n\n dict(mag='darkblue', grad='b', eeg='k', eog='k', ecg='m',\n emg='k', ref_meg='steelblue', misc='k', stim='k',\n resp='k', chpi='k')\n\n bad_color : color object\n Color to make bad channels.\n %(event_color)s\n Defaults to ``'cyan'``.\n scalings : 'auto' | dict | None\n Scaling factors for the traces. If any fields in scalings are 'auto',\n the scaling factor is set to match the 99.5th percentile of a subset of\n the corresponding data. If scalings == 'auto', all scalings fields are\n set to 'auto'. If any fields are 'auto' and data is not preloaded, a\n subset of times up to 100mb will be loaded. If None, defaults to::\n\n dict(mag=1e-12, grad=4e-11, eeg=20e-6, eog=150e-6, ecg=5e-4,\n emg=1e-3, ref_meg=1e-12, misc=1e-3, stim=1,\n resp=1, chpi=1e-4, whitened=1e2)\n\n remove_dc : bool\n If True remove DC component when plotting data.\n order : array of int | None\n Order in which to plot data. If the array is shorter than the number of\n channels, only the given channels are plotted. If None (default), all\n channels are plotted. If ``group_by`` is ``'position'`` or\n ``'selection'``, the ``order`` parameter is used only for selecting the\n channels to be plotted.\n show_options : bool\n If True, a dialog for options related to projection is shown.\n title : str | None\n The title of the window. If None, and either the filename of the\n raw object or '<unknown>' will be displayed as title.\n show : bool\n Show figure if True.\n block : bool\n Whether to halt program execution until the figure is closed.\n Useful for setting bad channels on the fly by clicking on a line.\n May not work on all systems / platforms.\n highpass : float | None\n Highpass to apply when displaying data.\n lowpass : float | None\n Lowpass to apply when displaying data.\n If highpass > lowpass, a bandstop rather than bandpass filter\n will be applied.\n filtorder : int\n Filtering order. 0 will use FIR filtering with MNE defaults.\n Other values will construct an IIR filter of the given order\n and apply it with :func:`~scipy.signal.filtfilt` (making the effective\n order twice ``filtorder``). Filtering may produce some edge artifacts\n (at the left and right edges) of the signals during display.\n\n .. versionchanged:: 0.18\n Support for ``filtorder=0`` to use FIR filtering.\n clipping : str | float | None\n If None, channels are allowed to exceed their designated bounds in\n the plot. If \"clamp\", then values are clamped to the appropriate\n range for display, creating step-like artifacts. If \"transparent\",\n then excessive values are not shown, creating gaps in the traces.\n If float, clipping occurs for values beyond the ``clipping`` multiple\n of their dedicated range, so ``clipping=1.`` is an alias for\n ``clipping='transparent'``.\n\n .. versionchanged:: 0.21\n Support for float, and default changed from None to 1.5.\n show_first_samp : bool\n If True, show time axis relative to the ``raw.first_samp``.\n proj : bool\n Whether to apply projectors prior to plotting (default is ``True``).\n Individual projectors can be enabled/disabled interactively (see\n Notes). This argument only affects the plot; use ``raw.apply_proj()``\n to modify the data stored in the Raw object.\n %(browse_group_by)s\n butterfly : bool\n Whether to start in butterfly mode. Defaults to False.\n decim : int | 'auto'\n Amount to decimate the data during display for speed purposes.\n You should only decimate if the data are sufficiently low-passed,\n otherwise aliasing can occur. The 'auto' mode (default) uses\n the decimation that results in a sampling rate least three times\n larger than ``min(info['lowpass'], lowpass)`` (e.g., a 40 Hz lowpass\n will result in at least a 120 Hz displayed sample rate).\n noise_cov : instance of Covariance | str | None\n Noise covariance used to whiten the data while plotting.\n Whitened data channels are scaled by ``scalings['whitened']``,\n and their channel names are shown in italic.\n Can be a string to load a covariance from disk.\n See also :meth:`mne.Evoked.plot_white` for additional inspection\n of noise covariance properties when whitening evoked data.\n For data processed with SSS, the effective dependence between\n magnetometers and gradiometers may introduce differences in scaling,\n consider using :meth:`mne.Evoked.plot_white`.\n\n .. versionadded:: 0.16.0\n event_id : dict | None\n Event IDs used to show at event markers (default None shows\n the event numbers).\n\n .. versionadded:: 0.16.0\n %(show_scrollbars)s\n show_scalebars : bool\n Whether or not to show the scale bars. Defaults to True.\n\n .. versionadded:: 0.20.0\n %(verbose)s\n\n Returns\n -------\n fig : instance of matplotlib.figure.Figure\n Raw traces.\n\n Notes\n -----\n The arrow keys (up/down/left/right) can typically be used to navigate\n between channels and time ranges, but this depends on the backend\n matplotlib is configured to use (e.g., mpl.use('TkAgg') should work). The\n left/right arrows will scroll by 25%% of ``duration``, whereas\n shift+left/shift+right will scroll by 100%% of ``duration``. The scaling\n can be adjusted with - and + (or =) keys. The viewport dimensions can be\n adjusted with page up/page down and home/end keys. Full screen mode can be\n toggled with the F11 key, and scrollbars can be hidden/shown by pressing\n 'z'. Right-click a channel label to view its location. To mark or un-mark a\n channel as bad, click on a channel label or a channel trace. The changes\n will be reflected immediately in the raw object's ``raw.info['bads']``\n entry.\n\n If projectors are present, a button labelled \"Prj\" in the lower right\n corner of the plot window opens a secondary control window, which allows\n enabling/disabling specific projectors individually. This provides a means\n of interactively observing how each projector would affect the raw data if\n it were applied.\n\n Annotation mode is toggled by pressing 'a', butterfly mode by pressing\n 'b', and whitening mode (when ``noise_cov is not None``) by pressing 'w'.\n By default, the channel means are removed when ``remove_dc`` is set to\n ``True``. This flag can be toggled by pressing 'd'.\n \"\"\"\n from ..io.base import BaseRaw\n from ._figure import _browse_figure\n\n info = raw.info.copy()\n sfreq = info['sfreq']\n projs = info['projs']\n # this will be an attr for which projectors are currently \"on\" in the plot\n projs_on = np.full_like(projs, proj, dtype=bool)\n # disable projs in info if user doesn't want to see them right away\n if not proj:\n info['projs'] = list()\n\n # handle defaults / check arg validity\n color = _handle_default('color', color)\n scalings = _compute_scalings(scalings, raw, remove_dc=remove_dc,\n duration=duration)\n if scalings['whitened'] == 'auto':\n scalings['whitened'] = 1.\n _validate_type(raw, BaseRaw, 'raw', 'Raw')\n decim, picks_data = _handle_decim(info, decim, lowpass)\n noise_cov = _check_cov(noise_cov, info)\n units = _handle_default('units', None)\n unit_scalings = _handle_default('scalings', None)\n _check_option('group_by', group_by,\n ('selection', 'position', 'original', 'type'))\n\n # clipping\n _validate_type(clipping, (None, 'numeric', str), 'clipping')\n if isinstance(clipping, str):\n _check_option('clipping', clipping, ('clamp', 'transparent'),\n extra='when a string')\n clipping = 1. if clipping == 'transparent' else clipping\n elif clipping is not None:\n clipping = float(clipping)\n\n # be forgiving if user asks for too much time\n duration = min(raw.times[-1], float(duration))\n\n # determine IIR filtering parameters\n if highpass is not None and highpass <= 0:\n raise ValueError(f'highpass must be > 0, got {highpass}')\n if highpass is None and lowpass is None:\n ba = filt_bounds = None\n else:\n filtorder = int(filtorder)\n if filtorder == 0:\n method = 'fir'\n iir_params = None\n else:\n method = 'iir'\n iir_params = dict(order=filtorder, output='sos', ftype='butter')\n ba = create_filter(np.zeros((1, int(round(duration * sfreq)))),\n sfreq, highpass, lowpass, method=method,\n iir_params=iir_params)\n filt_bounds = _annotations_starts_stops(\n raw, ('edge', 'bad_acq_skip'), invert=True)\n\n # compute event times in seconds\n if events is not None:\n event_times = (events[:, 0] - raw.first_samp).astype(float)\n event_times /= sfreq\n event_nums = events[:, 2]\n else:\n event_times = event_nums = None\n\n # determine trace order\n ch_names = np.array(raw.ch_names)\n ch_types = np.array(raw.get_channel_types())\n order = _get_channel_plotting_order(order, ch_types)\n n_channels = min(info['nchan'], n_channels, len(order))\n # adjust order based on channel selection, if needed\n selections = None\n if group_by in ('selection', 'position'):\n selections = _setup_channel_selections(raw, group_by, order)\n order = np.concatenate(list(selections.values()))\n default_selection = list(selections)[0]\n n_channels = len(selections[default_selection])\n\n # handle event colors\n event_color_dict = _make_event_color_dict(event_color, events, event_id)\n\n # handle first_samp\n first_time = raw._first_time if show_first_samp else 0\n start += first_time\n event_id_rev = {v: k for k, v in (event_id or {}).items()}\n\n # generate window title; allow instances without a filename (e.g., ICA)\n if title is None:\n title = '<unknown>'\n fnames = raw._filenames.copy()\n if len(fnames):\n title = fnames.pop(0)\n extra = f' ... (+ {len(fnames)} more)' if len(fnames) else ''\n title = f'{title}{extra}'\n if len(title) > 60:\n title = _shorten_path_from_middle(title)\n elif not isinstance(title, str):\n raise TypeError(f'title must be None or a string, got a {type(title)}')\n\n # gather parameters and initialize figure\n params = dict(inst=raw,\n info=info,\n # channels and channel order\n ch_names=ch_names,\n ch_types=ch_types,\n ch_order=order,\n picks=order[:n_channels],\n n_channels=n_channels,\n picks_data=picks_data,\n group_by=group_by,\n ch_selections=selections,\n # time\n t_start=start,\n duration=duration,\n n_times=raw.n_times,\n first_time=first_time,\n decim=decim,\n # events\n event_color_dict=event_color_dict,\n event_times=event_times,\n event_nums=event_nums,\n event_id_rev=event_id_rev,\n # preprocessing\n projs=projs,\n projs_on=projs_on,\n apply_proj=proj,\n remove_dc=remove_dc,\n filter_coefs=ba,\n filter_bounds=filt_bounds,\n noise_cov=noise_cov,\n # scalings\n scalings=scalings,\n units=units,\n unit_scalings=unit_scalings,\n # colors\n ch_color_bad=bad_color,\n ch_color_dict=color,\n # display\n butterfly=butterfly,\n clipping=clipping,\n scrollbars_visible=show_scrollbars,\n scalebars_visible=show_scalebars,\n window_title=title)\n\n fig = _browse_figure(**params)\n fig._update_picks()\n\n # make channel selection dialog, if requested (doesn't work well in init)\n if group_by in ('selection', 'position'):\n fig._create_selection_fig()\n\n # update projector and data, and plot\n fig._update_projector()\n fig._update_trace_offsets()\n fig._update_data()\n fig._draw_traces()\n\n # plot annotations (if any)\n fig._setup_annotation_colors()\n fig._draw_annotations()\n\n # start with projectors dialog open, if requested\n if show_options:\n fig._toggle_proj_fig()\n\n plt_show(show, block=block)\n return fig\n\n\n@verbose\ndef plot_raw_psd(raw, fmin=0, fmax=np.inf, tmin=None, tmax=None, proj=False,\n n_fft=None, n_overlap=0, reject_by_annotation=True,\n picks=None, ax=None, color='black', xscale='linear',\n area_mode='std', area_alpha=0.33, dB=True, estimate='auto',\n show=True, n_jobs=1, average=False, line_alpha=None,\n spatial_colors=True, sphere=None, window='hamming',\n verbose=None):\n \"\"\"%(plot_psd_doc)s.\n\n Parameters\n ----------\n raw : instance of Raw\n The raw object.\n fmin : float\n Start frequency to consider.\n fmax : float\n End frequency to consider.\n tmin : float | None\n Start time to consider.\n tmax : float | None\n End time to consider.\n proj : bool\n Apply projection.\n n_fft : int | None\n Number of points to use in Welch FFT calculations.\n Default is None, which uses the minimum of 2048 and the\n number of time points.\n n_overlap : int\n The number of points of overlap between blocks. The default value\n is 0 (no overlap).\n %(reject_by_annotation_raw)s\n %(plot_psd_picks_good_data)s\n ax : instance of Axes | None\n Axes to plot into. If None, axes will be created.\n %(plot_psd_color)s\n %(plot_psd_xscale)s\n %(plot_psd_area_mode)s\n %(plot_psd_area_alpha)s\n %(plot_psd_dB)s\n %(plot_psd_estimate)s\n %(show)s\n %(n_jobs)s\n %(plot_psd_average)s\n %(plot_psd_line_alpha)s\n %(plot_psd_spatial_colors)s\n %(topomap_sphere_auto)s\n %(window-psd)s\n\n .. versionadded:: 0.22.0\n %(verbose)s\n\n Returns\n -------\n fig : instance of Figure\n Figure with frequency spectra of the data channels.\n \"\"\"\n from ._figure import _psd_figure\n # handle FFT\n if n_fft is None:\n if tmax is None or not np.isfinite(tmax):\n tmax = raw.times[-1]\n tmin = 0. if tmin is None else tmin\n n_fft = min(np.diff(raw.time_as_index([tmin, tmax]))[0] + 1, 2048)\n # generate figure\n fig = _psd_figure(\n inst=raw, proj=proj, picks=picks, axes=ax, tmin=tmin, tmax=tmax,\n fmin=fmin, fmax=fmax, sphere=sphere, xscale=xscale, dB=dB,\n average=average, estimate=estimate, area_mode=area_mode,\n line_alpha=line_alpha, area_alpha=area_alpha, color=color,\n spatial_colors=spatial_colors, n_jobs=n_jobs, n_fft=n_fft,\n n_overlap=n_overlap, reject_by_annotation=reject_by_annotation,\n window=window)\n plt_show(show)\n return fig\n\n\n@verbose\ndef plot_raw_psd_topo(raw, tmin=0., tmax=None, fmin=0., fmax=100., proj=False,\n n_fft=2048, n_overlap=0, layout=None, color='w',\n fig_facecolor='k', axis_facecolor='k', dB=True,\n show=True, block=False, n_jobs=1, axes=None,\n verbose=None):\n \"\"\"Plot channel-wise frequency spectra as topography.\n\n Parameters\n ----------\n raw : instance of io.Raw\n The raw instance to use.\n tmin : float\n Start time for calculations. Defaults to zero.\n tmax : float | None\n End time for calculations. If None (default), the end of data is used.\n fmin : float\n Start frequency to consider. Defaults to zero.\n fmax : float\n End frequency to consider. Defaults to 100.\n proj : bool\n Apply projection. Defaults to False.\n n_fft : int\n Number of points to use in Welch FFT calculations. Defaults to 2048.\n n_overlap : int\n The number of points of overlap between blocks. Defaults to 0\n (no overlap).\n layout : instance of Layout | None\n Layout instance specifying sensor positions (does not need to be\n specified for Neuromag data). If None (default), the correct layout is\n inferred from the data.\n color : str | tuple\n A matplotlib-compatible color to use for the curves. Defaults to white.\n fig_facecolor : str | tuple\n A matplotlib-compatible color to use for the figure background.\n Defaults to black.\n axis_facecolor : str | tuple\n A matplotlib-compatible color to use for the axis background.\n Defaults to black.\n dB : bool\n If True, transform data to decibels. Defaults to True.\n show : bool\n Show figure if True. Defaults to True.\n block : bool\n Whether to halt program execution until the figure is closed.\n May not work on all systems / platforms. Defaults to False.\n %(n_jobs)s\n axes : instance of matplotlib Axes | None\n Axes to plot into. If None, axes will be created.\n %(verbose)s\n\n Returns\n -------\n fig : instance of matplotlib.figure.Figure\n Figure distributing one image per channel across sensor topography.\n \"\"\"\n if layout is None:\n from ..channels.layout import find_layout\n layout = find_layout(raw.info)\n\n psds, freqs = psd_welch(raw, tmin=tmin, tmax=tmax, fmin=fmin,\n fmax=fmax, proj=proj, n_fft=n_fft,\n n_overlap=n_overlap, n_jobs=n_jobs)\n if dB:\n psds = 10 * np.log10(psds)\n y_label = 'dB'\n else:\n y_label = 'Power'\n show_func = partial(_plot_timeseries_unified, data=[psds], color=color,\n times=[freqs])\n click_func = partial(_plot_timeseries, data=[psds], color=color,\n times=[freqs])\n picks = _pick_data_channels(raw.info)\n info = pick_info(raw.info, picks)\n\n fig = _plot_topo(info, times=freqs, show_func=show_func,\n click_func=click_func, layout=layout,\n axis_facecolor=axis_facecolor,\n fig_facecolor=fig_facecolor, x_label='Frequency (Hz)',\n unified=True, y_label=y_label, axes=axes)\n\n try:\n plt_show(show, block=block)\n except TypeError: # not all versions have this\n plt_show(show)\n return fig\n\n\ndef _setup_channel_selections(raw, kind, order):\n \"\"\"Get dictionary of channel groupings.\"\"\"\n from ..channels import (read_vectorview_selection, _SELECTIONS,\n _EEG_SELECTIONS, _divide_to_regions)\n from ..utils import _get_stim_channel\n _check_option('group_by', kind, ('position', 'selection'))\n if kind == 'position':\n selections_dict = _divide_to_regions(raw.info)\n keys = _SELECTIONS[1:] # omit 'Vertex'\n else: # kind == 'selection'\n from ..channels.channels import _get_ch_info\n (has_vv_mag, has_vv_grad, *_, has_neuromag_122_grad, has_csd_coils\n ) = _get_ch_info(raw.info)\n if not (has_vv_grad or has_vv_mag or has_neuromag_122_grad):\n raise ValueError(\"order='selection' only works for Neuromag \"\n \"data. Use order='position' instead.\")\n selections_dict = OrderedDict()\n # get stim channel (if any)\n stim_ch = _get_stim_channel(None, raw.info, raise_error=False)\n stim_ch = stim_ch if len(stim_ch) else ['']\n stim_ch = pick_channels(raw.ch_names, stim_ch)\n # loop over regions\n keys = np.concatenate([_SELECTIONS, _EEG_SELECTIONS])\n for key in keys:\n channels = read_vectorview_selection(key, info=raw.info)\n picks = pick_channels(raw.ch_names, channels)\n picks = np.intersect1d(picks, order)\n if not len(picks):\n continue # omit empty selections\n selections_dict[key] = np.concatenate([picks, stim_ch])\n # add misc channels\n misc = pick_types(raw.info, meg=False, eeg=False, stim=True, eog=True,\n ecg=True, emg=True, ref_meg=False, misc=True,\n resp=True, chpi=True, exci=True, ias=True, syst=True,\n seeg=False, bio=True, ecog=False, fnirs=False, dbs=False,\n exclude=())\n if len(misc) and np.in1d(misc, order).any():\n selections_dict['Misc'] = misc\n return selections_dict\n",
"# -*- coding: utf-8 -*-\n\"\"\"\n.. _tut-event-arrays:\n\nWorking with events\n===================\n\nThis tutorial describes event representation and how event arrays are used to\nsubselect data.\n\nAs usual we'll start by importing the modules we need, loading some\n:ref:`example data <sample-dataset>`, and cropping the :class:`~mne.io.Raw`\nobject to just 60 seconds before loading it into RAM to save memory:\n\"\"\"\n\nimport os\nimport numpy as np\nimport mne\n\nsample_data_folder = mne.datasets.sample.data_path()\nsample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n 'sample_audvis_raw.fif')\nraw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)\nraw.crop(tmax=60).load_data()\n\n###############################################################################\n# The tutorial :ref:`tut-events-vs-annotations` describes in detail the\n# different ways of obtaining an :term:`Events array <events>` from a\n# :class:`~mne.io.Raw` object (see the section\n# :ref:`overview-tut-events-section` for details). Since the :ref:`sample\n# dataset <sample-dataset>` includes experimental events recorded on\n# :term:`stim channel` ``STI 014``, we'll start this tutorial by parsing the\n# events from that channel using :func:`mne.find_events`:\n\nevents = mne.find_events(raw, stim_channel='STI 014')\n\n###############################################################################\n# .. _tut-section-events-io:\n#\n# Reading and writing events from/to a file\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# Event arrays are :class:`NumPy array <numpy.ndarray>` objects, so they could\n# be saved to disk as binary :file:`.npy` files using :func:`numpy.save`.\n# However, MNE-Python provides convenience functions :func:`mne.read_events`\n# and :func:`mne.write_events` for reading and writing event arrays as either\n# text files (common file extensions are :file:`.eve`, :file:`.lst`, and\n# :file:`.txt`) or binary :file:`.fif` files. The example dataset includes the\n# results of ``mne.find_events(raw)`` in a :file:`.fif` file. Since we've\n# truncated our :class:`~mne.io.Raw` object, it will have fewer events than the\n# events file loaded from disk (which contains events for the entire\n# recording), but the events should match for the first 60 seconds anyway:\n\nsample_data_events_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n 'sample_audvis_raw-eve.fif')\nevents_from_file = mne.read_events(sample_data_events_file)\nassert np.array_equal(events, events_from_file[:len(events)])\n\n###############################################################################\n# When writing event arrays to disk, the format will be inferred from the file\n# extension you provide. By convention, MNE-Python expects events files to\n# either have an :file:`.eve` extension or to have a file basename ending in\n# ``-eve`` or ``_eve`` (e.g., :file:`{my_experiment}_eve.fif`), and will issue\n# a warning if this convention is not respected.\n#\n#\n# Subselecting and combining events\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# The output of :func:`~mne.find_events` above (repeated here) told us the\n# number of events that were found, and the unique integer event IDs present:\n\nmne.find_events(raw, stim_channel='STI 014')\n\n###############################################################################\n# .. sidebar:: Including/excluding events\n#\n# Just like `~mne.pick_events`, `~mne.read_events` also has ``include``\n# and ``exclude`` parameters.\n#\n# If some of those events are not of interest, you can easily subselect events\n# using :func:`mne.pick_events`, which has parameters ``include`` and\n# ``exclude``. For example, in the sample data Event ID 32 corresponds to a\n# subject button press, which could be excluded as:\n\nevents_no_button = mne.pick_events(events, exclude=32)\n\n###############################################################################\n# It is also possible to combine two Event IDs using :func:`mne.merge_events`;\n# the following example will combine Event IDs 1, 2 and 3 into a single event\n# labelled ``1``:\n\nmerged_events = mne.merge_events(events, [1, 2, 3], 1)\nprint(np.unique(merged_events[:, -1]))\n\n###############################################################################\n# Note, however, that merging events is not necessary if you simply want to\n# pool trial types for analysis; the next section describes how MNE-Python uses\n# *event dictionaries* to map integer Event IDs to more descriptive label\n# strings.\n#\n#\n# Mapping Event IDs to trial descriptors\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# So far in this tutorial we've only been dealing with integer Event IDs, which\n# were assigned based on DC voltage pulse magnitude (which is ultimately\n# determined by the experimenter's choices about what signals to send to the\n# STIM channels). Keeping track of which Event ID corresponds to which\n# experimental condition can be cumbersome, and it is often desirable to pool\n# experimental conditions during analysis. You may recall that the mapping of\n# integer Event IDs to meaningful descriptions for the :ref:`sample dataset\n# <sample-dataset>` is given in :ref:`this table\n# <sample-data-event-dict-table>` in the :ref:`introductory tutorial\n# <tut-overview>`. Here we simply reproduce that mapping as an\n# *event dictionary*:\n\nevent_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,\n 'visual/right': 4, 'smiley': 5, 'buttonpress': 32}\n\n###############################################################################\n# Event dictionaries like this one are used when extracting epochs from\n# continuous data, and the resulting :class:`~mne.Epochs` object allows pooling\n# by requesting partial trial descriptors. For example, if we wanted to pool\n# all auditory trials, instead of merging Event IDs 1 and 2 using the\n# :func:`~mne.merge_events` function, we can make use of the fact that the keys\n# of ``event_dict`` contain multiple trial descriptors separated by ``/``\n# characters: requesting ``'auditory'`` trials will select all epochs with\n# Event IDs 1 and 2; requesting ``'left'`` trials will select all epochs with\n# Event IDs 1 and 3. An example of this is shown later, in the\n# :ref:`tut-section-subselect-epochs` section of the tutorial\n# :ref:`tut-epochs-class`.\n#\n#\n# Plotting events\n# ^^^^^^^^^^^^^^^\n#\n# Another use of event dictionaries is when plotting events, which can serve as\n# a useful check that your event signals were properly sent to the STIM\n# channel(s) and that MNE-Python has successfully found them. The function\n# :func:`mne.viz.plot_events` will plot each event versus its sample number\n# (or, if you provide the sampling frequency, it will plot them versus time in\n# seconds). It can also account for the offset between sample number and sample\n# index in Neuromag systems, with the ``first_samp`` parameter. If an event\n# dictionary is provided, it will be used to generate a legend:\n\nfig = mne.viz.plot_events(events, sfreq=raw.info['sfreq'],\n first_samp=raw.first_samp, event_id=event_dict)\nfig.subplots_adjust(right=0.7) # make room for legend\n\n###############################################################################\n# Plotting events and raw data together\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Events can also be plotted alongside the :class:`~mne.io.Raw` object they\n# were extracted from, by passing the Event array as the ``events`` parameter\n# of :meth:`raw.plot <mne.io.Raw.plot>`:\n\nraw.plot(events=events, start=5, duration=10, color='gray',\n event_color={1: 'r', 2: 'g', 3: 'b', 4: 'm', 5: 'y', 32: 'k'})\n\n###############################################################################\n# .. _`fixed-length-events`:\n#\n# Making equally-spaced Events arrays\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n#\n# For some experiments (such as those intending to analyze resting-state\n# activity) there may not be any experimental events included in the raw\n# recording. In such cases, an Events array of equally-spaced events can be\n# generated using :func:`mne.make_fixed_length_events`:\n\nnew_events = mne.make_fixed_length_events(raw, start=5, stop=50, duration=2.)\n\n###############################################################################\n# By default, the events will all be given the integer Event ID of ``1``, but\n# you can change that with the ``id`` parameter. It is also possible to specify\n# an ``overlap`` duration — i.e., if you ultimately want :term:`epochs` that\n# are 2.5 seconds long, but you want them to overlap by 0.5 seconds, you can\n# specify ``duration=2.5, overlap=0.5`` in the call to\n# :func:`~mne.make_fixed_length_events` (this will yield the same spacing of\n# events as ``duration=2, overlap=0)``.\n",
"# Authors: Alexandre Gramfort <[email protected]>\n#\n# License: BSD 3 clause\n\nimport os\nimport os.path as op\nfrom shutil import copyfile\n\nimport pytest\nimport numpy as np\nfrom numpy.testing import assert_allclose\nfrom scipy import sparse\n\nfrom mne.datasets import testing\nfrom mne.utils import catch_logging\nfrom mne import read_morph_map\n\ndata_path = testing.data_path(download=False)\nsubjects_dir = op.join(data_path, 'subjects')\n\n\[email protected]\[email protected]_testing_data\ndef test_make_morph_maps(tmpdir):\n \"\"\"Test reading and creating morph maps.\"\"\"\n # make a new fake subjects_dir\n tempdir = str(tmpdir)\n for subject in ('sample', 'sample_ds', 'fsaverage_ds'):\n os.mkdir(op.join(tempdir, subject))\n os.mkdir(op.join(tempdir, subject, 'surf'))\n regs = ('reg', 'left_right') if subject == 'fsaverage_ds' else ('reg',)\n for hemi in ['lh', 'rh']:\n for reg in regs:\n args = [subject, 'surf', hemi + '.sphere.' + reg]\n copyfile(op.join(subjects_dir, *args),\n op.join(tempdir, *args))\n\n for subject_from, subject_to, xhemi in (\n ('fsaverage_ds', 'sample_ds', False),\n ('fsaverage_ds', 'fsaverage_ds', True)):\n # trigger the creation of morph-maps dir and create the map\n with catch_logging() as log:\n mmap = read_morph_map(subject_from, subject_to, tempdir,\n xhemi=xhemi, verbose=True)\n log = log.getvalue()\n assert 'does not exist' in log\n assert 'Creating' in log\n mmap2 = read_morph_map(subject_from, subject_to, subjects_dir,\n xhemi=xhemi)\n assert len(mmap) == len(mmap2)\n for m1, m2 in zip(mmap, mmap2):\n # deal with sparse matrix stuff\n diff = (m1 - m2).data\n assert_allclose(diff, np.zeros_like(diff), atol=1e-3, rtol=0)\n\n # This will also trigger creation, but it's trivial\n with pytest.warns(None):\n mmap = read_morph_map('sample', 'sample', subjects_dir=tempdir)\n for mm in mmap:\n assert (mm - sparse.eye(mm.shape[0], mm.shape[0])).sum() == 0\n",
"# -*- coding: utf-8 -*-\n\"\"\"Functions to make 3D plots with M/EEG data.\"\"\"\n\n# Authors: Alexandre Gramfort <[email protected]>\n# Denis Engemann <[email protected]>\n# Martin Luessi <[email protected]>\n# Eric Larson <[email protected]>\n# Mainak Jas <[email protected]>\n# Mark Wronkiewicz <[email protected]>\n#\n# License: Simplified BSD\n\nfrom itertools import cycle\nimport os.path as op\nimport sys\nimport warnings\nfrom collections.abc import Iterable\nfrom functools import partial\n\nimport numpy as np\n\nfrom ..defaults import DEFAULTS\nfrom ..fixes import _crop_colorbar, _get_img_fdata, _get_args\nfrom ..io import _loc_to_coil_trans\nfrom ..io.pick import pick_types, _picks_to_idx\nfrom ..io.constants import FIFF\nfrom ..io.meas_info import read_fiducials, create_info\nfrom ..source_space import (_ensure_src, _create_surf_spacing, _check_spacing,\n _read_mri_info, SourceSpaces, read_freesurfer_lut)\n\nfrom ..surface import (get_meg_helmet_surf, _read_mri_surface, _DistanceQuery,\n transform_surface_to, _project_onto_surface,\n _reorder_ccw)\nfrom ..transforms import (_find_trans, apply_trans, rot_to_quat,\n combine_transforms, _get_trans, _ensure_trans,\n invert_transform, Transform, rotation,\n read_ras_mni_t, _print_coord_trans)\nfrom ..utils import (get_subjects_dir, logger, _check_subject, verbose, warn,\n has_nibabel, check_version, fill_doc, _pl, get_config,\n _ensure_int, _validate_type, _check_option)\nfrom .utils import (mne_analyze_colormap, _get_color_list,\n plt_show, tight_layout, figure_nobar, _check_time_unit)\nfrom .misc import _check_mri\nfrom ..bem import (ConductorModel, _bem_find_surface,\n read_bem_surfaces, _ensure_bem_surfaces)\n\n\nverbose_dec = verbose\nFIDUCIAL_ORDER = (FIFF.FIFFV_POINT_LPA, FIFF.FIFFV_POINT_NASION,\n FIFF.FIFFV_POINT_RPA)\n\n\n# XXX: to unify with digitization\ndef _fiducial_coords(points, coord_frame=None):\n \"\"\"Generate 3x3 array of fiducial coordinates.\"\"\"\n points = points or [] # None -> list\n if coord_frame is not None:\n points = [p for p in points if p['coord_frame'] == coord_frame]\n points_ = {p['ident']: p for p in points if\n p['kind'] == FIFF.FIFFV_POINT_CARDINAL}\n if points_:\n return np.array([points_[i]['r'] for i in FIDUCIAL_ORDER])\n else:\n # XXX eventually this should probably live in montage.py\n if coord_frame is None or coord_frame == FIFF.FIFFV_COORD_HEAD:\n # Try converting CTF HPI coils to fiducials\n out = np.empty((3, 3))\n out.fill(np.nan)\n for p in points:\n if p['kind'] == FIFF.FIFFV_POINT_HPI:\n if np.isclose(p['r'][1:], 0, atol=1e-6).all():\n out[0 if p['r'][0] < 0 else 2] = p['r']\n elif np.isclose(p['r'][::2], 0, atol=1e-6).all():\n out[1] = p['r']\n if np.isfinite(out).all():\n return out\n return np.array([])\n\n\ndef plot_head_positions(pos, mode='traces', cmap='viridis', direction='z',\n show=True, destination=None, info=None, color='k',\n axes=None):\n \"\"\"Plot head positions.\n\n Parameters\n ----------\n pos : ndarray, shape (n_pos, 10) | list of ndarray\n The head position data. Can also be a list to treat as a\n concatenation of runs.\n mode : str\n Can be 'traces' (default) to show position and quaternion traces,\n or 'field' to show the position as a vector field over time.\n cmap : colormap\n Colormap to use for the trace plot, default is \"viridis\".\n direction : str\n Can be any combination of \"x\", \"y\", or \"z\" (default: \"z\") to show\n directional axes in \"field\" mode.\n show : bool\n Show figure if True. Defaults to True.\n destination : str | array-like, shape (3,) | None\n The destination location for the head, assumed to be in head\n coordinates. See :func:`mne.preprocessing.maxwell_filter` for\n details.\n\n .. versionadded:: 0.16\n info : instance of mne.Info | None\n Measurement information. If provided, will be used to show the\n destination position when ``destination is None``, and for\n showing the MEG sensors.\n\n .. versionadded:: 0.16\n color : color object\n The color to use for lines in ``mode == 'traces'`` and quiver\n arrows in ``mode == 'field'``.\n\n .. versionadded:: 0.16\n axes : array-like, shape (3, 2)\n The matplotlib axes to use. Only used for ``mode == 'traces'``.\n\n .. versionadded:: 0.16\n\n Returns\n -------\n fig : instance of matplotlib.figure.Figure\n The figure.\n \"\"\"\n from ..chpi import head_pos_to_trans_rot_t\n from ..preprocessing.maxwell import _check_destination\n import matplotlib.pyplot as plt\n _check_option('mode', mode, ['traces', 'field'])\n dest_info = dict(dev_head_t=None) if info is None else info\n destination = _check_destination(destination, dest_info, head_frame=True)\n if destination is not None:\n destination = _ensure_trans(destination, 'head', 'meg') # probably inv\n destination = destination['trans'][:3].copy()\n destination[:, 3] *= 1000\n\n if not isinstance(pos, (list, tuple)):\n pos = [pos]\n for ii, p in enumerate(pos):\n p = np.array(p, float)\n if p.ndim != 2 or p.shape[1] != 10:\n raise ValueError('pos (or each entry in pos if a list) must be '\n 'dimension (N, 10), got %s' % (p.shape,))\n if ii > 0: # concatenation\n p[:, 0] += pos[ii - 1][-1, 0] - p[0, 0]\n pos[ii] = p\n borders = np.cumsum([len(pp) for pp in pos])\n pos = np.concatenate(pos, axis=0)\n trans, rot, t = head_pos_to_trans_rot_t(pos) # also ensures pos is okay\n # trans, rot, and t are for dev_head_t, but what we really want\n # is head_dev_t (i.e., where the head origin is in device coords)\n use_trans = np.einsum('ijk,ik->ij', rot[:, :3, :3].transpose([0, 2, 1]),\n -trans) * 1000\n use_rot = rot.transpose([0, 2, 1])\n use_quats = -pos[:, 1:4] # inverse (like doing rot.T)\n surf = rrs = lims = None\n if info is not None:\n meg_picks = pick_types(info, meg=True, ref_meg=False, exclude=())\n if len(meg_picks) > 0:\n rrs = 1000 * np.array([info['chs'][pick]['loc'][:3]\n for pick in meg_picks], float)\n if mode == 'traces':\n lims = np.array((rrs.min(0), rrs.max(0))).T\n else: # mode == 'field'\n surf = get_meg_helmet_surf(info)\n transform_surface_to(surf, 'meg', info['dev_head_t'],\n copy=False)\n surf['rr'] *= 1000.\n helmet_color = (0.0, 0.0, 0.6)\n if mode == 'traces':\n if axes is None:\n axes = plt.subplots(3, 2, sharex=True)[1]\n else:\n axes = np.array(axes)\n if axes.shape != (3, 2):\n raise ValueError('axes must have shape (3, 2), got %s'\n % (axes.shape,))\n fig = axes[0, 0].figure\n\n labels = ['xyz', ('$q_1$', '$q_2$', '$q_3$')]\n for ii, (quat, coord) in enumerate(zip(use_quats.T, use_trans.T)):\n axes[ii, 0].plot(t, coord, color, lw=1., zorder=3)\n axes[ii, 0].set(ylabel=labels[0][ii], xlim=t[[0, -1]])\n axes[ii, 1].plot(t, quat, color, lw=1., zorder=3)\n axes[ii, 1].set(ylabel=labels[1][ii], xlim=t[[0, -1]])\n for b in borders[:-1]:\n for jj in range(2):\n axes[ii, jj].axvline(t[b], color='r')\n for ii, title in enumerate(('Position (mm)', 'Rotation (quat)')):\n axes[0, ii].set(title=title)\n axes[-1, ii].set(xlabel='Time (s)')\n if rrs is not None:\n pos_bads = np.any([(use_trans[:, ii] <= lims[ii, 0]) |\n (use_trans[:, ii] >= lims[ii, 1])\n for ii in range(3)], axis=0)\n for ii in range(3):\n oidx = list(range(ii)) + list(range(ii + 1, 3))\n # knowing it will generally be spherical, we can approximate\n # how far away we are along the axis line by taking the\n # point to the left and right with the smallest distance\n from scipy.spatial.distance import cdist\n dists = cdist(rrs[:, oidx], use_trans[:, oidx])\n left = rrs[:, [ii]] < use_trans[:, ii]\n left_dists_all = dists.copy()\n left_dists_all[~left] = np.inf\n # Don't show negative Z direction\n if ii != 2 and np.isfinite(left_dists_all).any():\n idx = np.argmin(left_dists_all, axis=0)\n left_dists = rrs[idx, ii]\n bads = ~np.isfinite(\n left_dists_all[idx, np.arange(len(idx))]) | pos_bads\n left_dists[bads] = np.nan\n axes[ii, 0].plot(t, left_dists, color=helmet_color,\n ls='-', lw=0.5, zorder=2)\n else:\n axes[ii, 0].axhline(lims[ii][0], color=helmet_color,\n ls='-', lw=0.5, zorder=2)\n right_dists_all = dists\n right_dists_all[left] = np.inf\n if np.isfinite(right_dists_all).any():\n idx = np.argmin(right_dists_all, axis=0)\n right_dists = rrs[idx, ii]\n bads = ~np.isfinite(\n right_dists_all[idx, np.arange(len(idx))]) | pos_bads\n right_dists[bads] = np.nan\n axes[ii, 0].plot(t, right_dists, color=helmet_color,\n ls='-', lw=0.5, zorder=2)\n else:\n axes[ii, 0].axhline(lims[ii][1], color=helmet_color,\n ls='-', lw=0.5, zorder=2)\n\n for ii in range(3):\n axes[ii, 1].set(ylim=[-1, 1])\n\n if destination is not None:\n vals = np.array([destination[:, 3],\n rot_to_quat(destination[:, :3])]).T.ravel()\n for ax, val in zip(fig.axes, vals):\n ax.axhline(val, color='r', ls=':', zorder=2, lw=1.)\n\n else: # mode == 'field':\n from matplotlib.colors import Normalize\n from mpl_toolkits.mplot3d.art3d import Line3DCollection\n from mpl_toolkits.mplot3d import Axes3D # noqa: F401, analysis:ignore\n fig, ax = plt.subplots(1, subplot_kw=dict(projection='3d'))\n\n # First plot the trajectory as a colormap:\n # http://matplotlib.org/examples/pylab_examples/multicolored_line.html\n pts = use_trans[:, np.newaxis]\n segments = np.concatenate([pts[:-1], pts[1:]], axis=1)\n norm = Normalize(t[0], t[-2])\n lc = Line3DCollection(segments, cmap=cmap, norm=norm)\n lc.set_array(t[:-1])\n ax.add_collection(lc)\n # now plot the head directions as a quiver\n dir_idx = dict(x=0, y=1, z=2)\n kwargs = dict(pivot='tail')\n for d, length in zip(direction, [5., 2.5, 1.]):\n use_dir = use_rot[:, :, dir_idx[d]]\n # draws stems, then heads\n array = np.concatenate((t, np.repeat(t, 2)))\n ax.quiver(use_trans[:, 0], use_trans[:, 1], use_trans[:, 2],\n use_dir[:, 0], use_dir[:, 1], use_dir[:, 2], norm=norm,\n cmap=cmap, array=array, length=length, **kwargs)\n if destination is not None:\n ax.quiver(destination[0, 3],\n destination[1, 3],\n destination[2, 3],\n destination[dir_idx[d], 0],\n destination[dir_idx[d], 1],\n destination[dir_idx[d], 2], color=color,\n length=length, **kwargs)\n mins = use_trans.min(0)\n maxs = use_trans.max(0)\n if surf is not None:\n ax.plot_trisurf(*surf['rr'].T, triangles=surf['tris'],\n color=helmet_color, alpha=0.1, shade=False)\n ax.scatter(*rrs.T, s=1, color=helmet_color)\n mins = np.minimum(mins, rrs.min(0))\n maxs = np.maximum(maxs, rrs.max(0))\n scale = (maxs - mins).max() / 2.\n xlim, ylim, zlim = (maxs + mins)[:, np.newaxis] / 2. + [-scale, scale]\n ax.set(xlabel='x', ylabel='y', zlabel='z',\n xlim=xlim, ylim=ylim, zlim=zlim)\n _set_aspect_equal(ax)\n ax.view_init(30, 45)\n tight_layout(fig=fig)\n plt_show(show)\n return fig\n\n\ndef _set_aspect_equal(ax):\n # XXX recent MPL throws an error for 3D axis aspect setting, not much\n # we can do about it at this point\n try:\n ax.set_aspect('equal')\n except NotImplementedError:\n pass\n\n\n@verbose\ndef plot_evoked_field(evoked, surf_maps, time=None, time_label='t = %0.0f ms',\n n_jobs=1, fig=None, vmax=None, n_contours=21,\n verbose=None):\n \"\"\"Plot MEG/EEG fields on head surface and helmet in 3D.\n\n Parameters\n ----------\n evoked : instance of mne.Evoked\n The evoked object.\n surf_maps : list\n The surface mapping information obtained with make_field_map.\n time : float | None\n The time point at which the field map shall be displayed. If None,\n the average peak latency (across sensor types) is used.\n time_label : str | None\n How to print info about the time instant visualized.\n %(n_jobs)s\n fig : instance of mayavi.core.api.Scene | None\n If None (default), a new figure will be created, otherwise it will\n plot into the given figure.\n\n .. versionadded:: 0.20\n vmax : float | None\n Maximum intensity. Can be None to use the max(abs(data)).\n\n .. versionadded:: 0.21\n n_contours : int\n The number of contours.\n\n .. versionadded:: 0.21\n %(verbose)s\n\n Returns\n -------\n fig : instance of mayavi.mlab.Figure\n The mayavi figure.\n \"\"\"\n # Update the backend\n from .backends.renderer import _get_renderer\n types = [t for t in ['eeg', 'grad', 'mag'] if t in evoked]\n _validate_type(vmax, (None, 'numeric'), 'vmax')\n n_contours = _ensure_int(n_contours, 'n_contours')\n\n time_idx = None\n if time is None:\n time = np.mean([evoked.get_peak(ch_type=t)[1] for t in types])\n del types\n\n if not evoked.times[0] <= time <= evoked.times[-1]:\n raise ValueError('`time` (%0.3f) must be inside `evoked.times`' % time)\n time_idx = np.argmin(np.abs(evoked.times - time))\n\n # Plot them\n alphas = [1.0, 0.5]\n colors = [(0.6, 0.6, 0.6), (1.0, 1.0, 1.0)]\n colormap = mne_analyze_colormap(format='mayavi')\n colormap_lines = np.concatenate([np.tile([0., 0., 255., 255.], (127, 1)),\n np.tile([0., 0., 0., 255.], (2, 1)),\n np.tile([255., 0., 0., 255.], (127, 1))])\n\n renderer = _get_renderer(fig, bgcolor=(0.0, 0.0, 0.0), size=(600, 600))\n\n for ii, this_map in enumerate(surf_maps):\n surf = this_map['surf']\n map_data = this_map['data']\n map_type = this_map['kind']\n map_ch_names = this_map['ch_names']\n\n if map_type == 'eeg':\n pick = pick_types(evoked.info, meg=False, eeg=True)\n else:\n pick = pick_types(evoked.info, meg=True, eeg=False, ref_meg=False)\n\n ch_names = [evoked.ch_names[k] for k in pick]\n\n set_ch_names = set(ch_names)\n set_map_ch_names = set(map_ch_names)\n if set_ch_names != set_map_ch_names:\n message = ['Channels in map and data do not match.']\n diff = set_map_ch_names - set_ch_names\n if len(diff):\n message += ['%s not in data file. ' % list(diff)]\n diff = set_ch_names - set_map_ch_names\n if len(diff):\n message += ['%s not in map file.' % list(diff)]\n raise RuntimeError(' '.join(message))\n\n data = np.dot(map_data, evoked.data[pick, time_idx])\n\n # Make a solid surface\n if vmax is None:\n vmax = np.max(np.abs(data))\n vmax = float(vmax)\n alpha = alphas[ii]\n renderer.surface(surface=surf, color=colors[ii],\n opacity=alpha)\n\n # Now show our field pattern\n renderer.surface(surface=surf, vmin=-vmax, vmax=vmax,\n scalars=data, colormap=colormap,\n polygon_offset=-1)\n\n # And the field lines on top\n renderer.contour(surface=surf, scalars=data, contours=n_contours,\n vmin=-vmax, vmax=vmax, opacity=alpha,\n colormap=colormap_lines)\n\n if time_label is not None:\n if '%' in time_label:\n time_label %= (1e3 * evoked.times[time_idx])\n renderer.text2d(x_window=0.01, y_window=0.01, text=time_label)\n renderer.set_camera(azimuth=10, elevation=60)\n renderer.show()\n return renderer.scene()\n\n\n@verbose\ndef plot_alignment(info=None, trans=None, subject=None, subjects_dir=None,\n surfaces='auto', coord_frame='head',\n meg=None, eeg='original', fwd=None,\n dig=False, ecog=True, src=None, mri_fiducials=False,\n bem=None, seeg=True, fnirs=True, show_axes=False, dbs=True,\n fig=None, interaction='trackball', verbose=None):\n \"\"\"Plot head, sensor, and source space alignment in 3D.\n\n Parameters\n ----------\n info : dict | None\n The measurement info.\n If None (default), no sensor information will be shown.\n %(trans)s\n subject : str | None\n The subject name corresponding to FreeSurfer environment\n variable SUBJECT. Can be omitted if ``src`` is provided.\n %(subjects_dir)s\n surfaces : str | list | dict\n Surfaces to plot. Supported values:\n\n * scalp: one of 'head', 'outer_skin' (alias for 'head'),\n 'head-dense', or 'seghead' (alias for 'head-dense')\n * skull: 'outer_skull', 'inner_skull', 'brain' (alias for\n 'inner_skull')\n * brain: one of 'pial', 'white', 'inflated', or 'brain'\n (alias for 'pial').\n\n Can be dict to specify alpha values for each surface. Use None\n to specify default value. Specified values must be between 0 and 1.\n for example::\n\n surfaces=dict(brain=0.4, outer_skull=0.6, head=None)\n\n Defaults to 'auto', which will look for a head surface and plot\n it if found.\n\n .. note:: For single layer BEMs it is recommended to use 'brain'.\n coord_frame : str\n Coordinate frame to use, 'head', 'meg', or 'mri'.\n meg : str | list | bool | None\n Can be \"helmet\", \"sensors\" or \"ref\" to show the MEG helmet, sensors or\n reference sensors respectively, or a combination like\n ``('helmet', 'sensors')`` (same as None, default). True translates to\n ``('helmet', 'sensors', 'ref')``.\n eeg : bool | str | list\n String options are:\n\n - \"original\" (default; equivalent to ``True``)\n Shows EEG sensors using their digitized locations (after\n transformation to the chosen ``coord_frame``)\n - \"projected\"\n The EEG locations projected onto the scalp, as is done in forward\n modeling\n\n Can also be a list of these options, or an empty list (``[]``,\n equivalent of ``False``).\n fwd : instance of Forward\n The forward solution. If present, the orientations of the dipoles\n present in the forward solution are displayed.\n dig : bool | 'fiducials'\n If True, plot the digitization points; 'fiducials' to plot fiducial\n points only.\n ecog : bool\n If True (default), show ECoG sensors.\n src : instance of SourceSpaces | None\n If not None, also plot the source space points.\n mri_fiducials : bool | str\n Plot MRI fiducials (default False). If ``True``, look for a file with\n the canonical name (``bem/{subject}-fiducials.fif``). If ``str``,\n it can be ``'estimated'`` to use :func:`mne.coreg.get_mni_fiducials`,\n otherwise it should provide the full path to the fiducials file.\n\n .. versionadded:: 0.22\n Support for ``'estimated'``.\n bem : list of dict | instance of ConductorModel | None\n Can be either the BEM surfaces (list of dict), a BEM solution or a\n sphere model. If None, we first try loading\n ``'$SUBJECTS_DIR/$SUBJECT/bem/$SUBJECT-$SOURCE.fif'``, and then look\n for ``'$SUBJECT*$SOURCE.fif'`` in the same directory. For\n ``'outer_skin'``, the subjects bem and bem/flash folders are searched.\n Defaults to None.\n seeg : bool\n If True (default), show sEEG electrodes.\n fnirs : str | list | bool | None\n Can be \"channels\", \"pairs\", \"detectors\", and/or \"sources\" to show the\n fNIRS channel locations, optode locations, or line between\n source-detector pairs, or a combination like ``('pairs', 'channels')``.\n True translates to ``('pairs',)``.\n\n .. versionadded:: 0.20\n show_axes : bool\n If True (default False), coordinate frame axis indicators will be\n shown:\n\n * head in pink.\n * MRI in gray (if ``trans is not None``).\n * MEG in blue (if MEG sensors are present).\n\n .. versionadded:: 0.16\n dbs : bool\n If True (default), show DBS (deep brain stimulation) electrodes.\n fig : mayavi.mlab.Figure | None\n Mayavi Scene in which to plot the alignment.\n If ``None``, creates a new 600x600 pixel figure with black background.\n\n .. versionadded:: 0.16\n interaction : str\n Can be \"trackball\" (default) or \"terrain\", i.e. a turntable-style\n camera.\n\n .. versionadded:: 0.16\n %(verbose)s\n\n Returns\n -------\n fig : instance of mayavi.mlab.Figure\n The mayavi figure.\n\n See Also\n --------\n mne.viz.plot_bem\n\n Notes\n -----\n This function serves the purpose of checking the validity of the many\n different steps of source reconstruction:\n\n - Transform matrix (keywords ``trans``, ``meg`` and ``mri_fiducials``),\n - BEM surfaces (keywords ``bem`` and ``surfaces``),\n - sphere conductor model (keywords ``bem`` and ``surfaces``) and\n - source space (keywords ``surfaces`` and ``src``).\n\n .. versionadded:: 0.15\n \"\"\"\n from ..forward import _create_meg_coils, Forward\n from ..coreg import get_mni_fiducials\n # Update the backend\n from .backends.renderer import _get_renderer\n\n if eeg is False:\n eeg = list()\n elif eeg is True:\n eeg = 'original'\n if meg is None:\n meg = ('helmet', 'sensors')\n # only consider warning if the value is explicit\n warn_meg = False\n else:\n warn_meg = True\n\n if meg is True:\n meg = ('helmet', 'sensors', 'ref')\n elif meg is False:\n meg = list()\n elif isinstance(meg, str):\n meg = [meg]\n if isinstance(eeg, str):\n eeg = [eeg]\n\n if fnirs is True:\n fnirs = ['pairs']\n elif fnirs is False:\n fnirs = list()\n elif isinstance(fnirs, str):\n fnirs = [fnirs]\n\n _check_option('interaction', interaction, ['trackball', 'terrain'])\n for kind, var in zip(('eeg', 'meg', 'fnirs'), (eeg, meg, fnirs)):\n if not isinstance(var, (list, tuple)) or \\\n not all(isinstance(x, str) for x in var):\n raise TypeError('%s must be list or tuple of str, got %s'\n % (kind, type(var)))\n for xi, x in enumerate(meg):\n _check_option('meg[%d]' % xi, x, ('helmet', 'sensors', 'ref'))\n for xi, x in enumerate(eeg):\n _check_option('eeg[%d]' % xi, x, ('original', 'projected'))\n for xi, x in enumerate(fnirs):\n _check_option('fnirs[%d]' % xi, x, ('channels', 'pairs',\n 'sources', 'detectors'))\n\n info = create_info(1, 1000., 'misc') if info is None else info\n _validate_type(info, \"info\")\n\n if isinstance(surfaces, str):\n surfaces = [surfaces]\n if isinstance(surfaces, dict):\n user_alpha = surfaces.copy()\n for key, val in user_alpha.items():\n _validate_type(key, \"str\", f\"surfaces key {repr(key)}\")\n _validate_type(val, (None, \"numeric\"), f\"surfaces[{repr(key)}]\")\n if val is not None:\n user_alpha[key] = float(val)\n if not 0 <= user_alpha[key] <= 1:\n raise ValueError(\n f'surfaces[{repr(key)}] ({val}) must be'\n ' between 0 and 1'\n )\n else:\n user_alpha = {}\n surfaces = list(surfaces)\n for si, s in enumerate(surfaces):\n _validate_type(s, \"str\", f\"surfaces[{si}]\")\n brain = sorted(\n set(surfaces) & set(['brain', 'pial', 'white', 'inflated']))\n\n bem = _ensure_bem_surfaces(bem, extra_allow=(ConductorModel, None))\n assert isinstance(bem, ConductorModel) or bem is None\n\n _check_option('coord_frame', coord_frame, ['head', 'meg', 'mri'])\n if src is not None:\n src = _ensure_src(src)\n src_subject = src._subject\n subject = src_subject if subject is None else subject\n if src_subject is not None and subject != src_subject:\n raise ValueError('subject (\"%s\") did not match the subject name '\n ' in src (\"%s\")' % (subject, src_subject))\n\n if fwd is not None:\n _validate_type(fwd, [Forward])\n fwd_rr = fwd['source_rr']\n if fwd['source_ori'] == FIFF.FIFFV_MNE_FIXED_ORI:\n fwd_nn = fwd['source_nn'].reshape(-1, 1, 3)\n else:\n fwd_nn = fwd['source_nn'].reshape(-1, 3, 3)\n\n ref_meg = 'ref' in meg\n meg_picks = pick_types(info, meg=True, ref_meg=ref_meg)\n eeg_picks = pick_types(info, meg=False, eeg=True, ref_meg=False)\n fnirs_picks = pick_types(info, meg=False, eeg=False, ref_meg=False,\n fnirs=True)\n other_bools = dict(ecog=ecog, seeg=seeg, dbs=dbs,\n fnirs=(('channels' in fnirs) |\n ('sources' in fnirs) |\n ('detectors' in fnirs)))\n del ecog, seeg, dbs\n other_keys = sorted(other_bools.keys())\n other_picks = {key: pick_types(info, meg=False, ref_meg=False,\n **{key: True}) for key in other_keys}\n\n if trans == 'auto':\n # let's try to do this in MRI coordinates so they're easy to plot\n subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)\n trans = _find_trans(subject, subjects_dir)\n head_mri_t, _ = _get_trans(trans, 'head', 'mri')\n dev_head_t, _ = _get_trans(info['dev_head_t'], 'meg', 'head')\n del trans\n\n # Figure out our transformations\n if coord_frame == 'meg':\n head_trans = invert_transform(dev_head_t)\n meg_trans = Transform('meg', 'meg')\n mri_trans = invert_transform(combine_transforms(\n dev_head_t, head_mri_t, 'meg', 'mri'))\n elif coord_frame == 'mri':\n head_trans = head_mri_t\n meg_trans = combine_transforms(dev_head_t, head_mri_t, 'meg', 'mri')\n mri_trans = Transform('mri', 'mri')\n else: # coord_frame == 'head'\n head_trans = Transform('head', 'head')\n meg_trans = dev_head_t\n mri_trans = invert_transform(head_mri_t)\n\n # both the head and helmet will be in MRI coordinates after this\n surfs = dict()\n\n # Head:\n head = False\n for s in surfaces:\n if s in ('auto', 'head', 'outer_skin', 'head-dense', 'seghead'):\n if head:\n raise ValueError('Can only supply one head-like surface name')\n surfaces.pop(surfaces.index(s))\n head = True\n head_surf = None\n # Try the BEM if applicable\n if s in ('auto', 'head', 'outer_skin'):\n if bem is not None:\n head_missing = (\n 'Could not find the surface for '\n 'head in the provided BEM model, '\n 'looking in the subject directory.')\n try:\n head_surf = _bem_find_surface(bem, 'head')\n except RuntimeError:\n logger.info(head_missing)\n if head_surf is None:\n if subject is None:\n if s == 'auto':\n # ignore\n continue\n raise ValueError('To plot the head surface, the BEM/sphere'\n ' model must contain a head surface '\n 'or \"subject\" must be provided (got '\n 'None)')\n subject_dir = op.join(\n get_subjects_dir(subjects_dir, raise_error=True), subject)\n if s in ('head-dense', 'seghead'):\n try_fnames = [\n op.join(subject_dir, 'bem', '%s-head-dense.fif'\n % subject),\n op.join(subject_dir, 'surf', 'lh.seghead'),\n ]\n else:\n try_fnames = [\n op.join(subject_dir, 'bem', 'outer_skin.surf'),\n op.join(subject_dir, 'bem', 'flash',\n 'outer_skin.surf'),\n op.join(subject_dir, 'bem', '%s-head.fif'\n % subject),\n ]\n for fname in try_fnames:\n if op.exists(fname):\n logger.info('Using %s for head surface.'\n % (op.basename(fname),))\n if op.splitext(fname)[-1] == '.fif':\n head_surf = read_bem_surfaces(fname)[0]\n else:\n head_surf = _read_mri_surface(fname)\n break\n else:\n raise IOError('No head surface found for subject '\n '%s after trying:\\n%s'\n % (subject, '\\n'.join(try_fnames)))\n surfs['head'] = head_surf\n\n # Skull:\n skull = list()\n for name in ('outer_skull', 'inner_skull'):\n if name in surfaces:\n surfaces.pop(surfaces.index(name))\n if bem is None:\n fname = op.join(\n get_subjects_dir(subjects_dir, raise_error=True),\n subject, 'bem', name + '.surf')\n if not op.isfile(fname):\n raise ValueError('bem is None and the the %s file cannot '\n 'be found:\\n%s' % (name, fname))\n surf = _read_mri_surface(fname)\n else:\n surf = _bem_find_surface(bem, name).copy()\n surf['name'] = name\n skull.append(surf)\n assert all(isinstance(s, dict) for s in skull)\n\n if mri_fiducials:\n if mri_fiducials is True:\n subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)\n if subject is None:\n raise ValueError(\"Subject needs to be specified to \"\n \"automatically find the fiducials file.\")\n mri_fiducials = op.join(subjects_dir, subject, 'bem',\n subject + '-fiducials.fif')\n if isinstance(mri_fiducials, str):\n if mri_fiducials == 'estimated':\n mri_fiducials = get_mni_fiducials(subject, subjects_dir)\n else:\n mri_fiducials, cf = read_fiducials(mri_fiducials)\n if cf != FIFF.FIFFV_COORD_MRI:\n raise ValueError(\"Fiducials are not in MRI space\")\n fid_loc = _fiducial_coords(mri_fiducials, FIFF.FIFFV_COORD_MRI)\n fid_loc = apply_trans(mri_trans, fid_loc)\n else:\n fid_loc = []\n\n if 'helmet' in meg and len(meg_picks) > 0:\n surfs['helmet'] = get_meg_helmet_surf(info, head_mri_t)\n assert surfs['helmet']['coord_frame'] == FIFF.FIFFV_COORD_MRI\n\n # Brain:\n if len(brain) > 1:\n raise ValueError('Only one brain surface can be plotted. '\n 'Got %s.' % brain)\n elif len(brain) == 0:\n brain = False\n else: # exactly 1\n brain = brain[0]\n surfaces.pop(surfaces.index(brain))\n if brain in user_alpha:\n user_alpha['lh'] = user_alpha['rh'] = user_alpha.pop(brain)\n if bem is not None and bem['is_sphere'] and brain == 'brain':\n surfs['lh'] = _bem_find_surface(bem, 'brain')\n else:\n brain = 'pial' if brain == 'brain' else brain\n subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)\n for hemi in ['lh', 'rh']:\n fname = op.join(subjects_dir, subject, 'surf',\n '%s.%s' % (hemi, brain))\n surfs[hemi] = _read_mri_surface(fname)\n brain = True\n\n # we've looked through all of them, raise if some remain\n if len(surfaces) > 0:\n raise ValueError('Unknown surface type%s: %s'\n % (_pl(surfaces), surfaces,))\n\n skull_alpha = dict()\n skull_colors = dict()\n hemi_val = 0.5\n no_deep = all(len(other_picks[key]) == 0 for key in ('dbs', 'seeg'))\n max_alpha = 1.0 if no_deep else 0.75\n if src is None or (brain and any(s['type'] == 'surf' for s in src)):\n hemi_val = max_alpha\n alphas = np.linspace(max_alpha / 2., 0, 5)[:len(skull) + 1]\n\n for idx, this_skull in enumerate(skull):\n name = this_skull['name']\n skull_alpha[name] = alphas[idx + 1]\n skull_colors[name] = (0.95 - idx * 0.2, 0.85, 0.95 - idx * 0.2)\n surfs[name] = this_skull\n\n if src is None and brain is False and len(skull) == 0 and not show_axes:\n head_alpha = max_alpha\n else:\n head_alpha = alphas[0]\n\n for key in surfs:\n # Surfs can sometimes be in head coords (e.g., if coming from sphere)\n surf = surfs[key]\n assert isinstance(surf, dict), f'{key}: {type(surf)}'\n surfs[key] = transform_surface_to(surfs[key], coord_frame,\n [mri_trans, head_trans], copy=True)\n\n if fwd is not None:\n fwd_rr, fwd_nn = _update_coord_frame(fwd, fwd_rr, fwd_nn,\n mri_trans, head_trans)\n\n # determine points\n meg_rrs, meg_tris = list(), list()\n hpi_loc = list()\n ext_loc = list()\n car_loc = list()\n eeg_loc = list()\n eegp_loc = list()\n other_loc = dict()\n if len(eeg) > 0:\n eeg_loc = np.array([info['chs'][k]['loc'][:3] for k in eeg_picks])\n if len(eeg_loc) > 0:\n eeg_loc = apply_trans(head_trans, eeg_loc)\n # XXX do projections here if necessary\n if 'projected' in eeg:\n eegp_loc, eegp_nn = _project_onto_surface(\n eeg_loc, surfs['head'], project_rrs=True,\n return_nn=True)[2:4]\n if 'original' not in eeg:\n eeg_loc = list()\n del eeg\n if 'sensors' in meg:\n coil_transs = [_loc_to_coil_trans(info['chs'][pick]['loc'])\n for pick in meg_picks]\n coils = _create_meg_coils([info['chs'][pick] for pick in meg_picks],\n acc='normal')\n offset = 0\n for coil, coil_trans in zip(coils, coil_transs):\n rrs, tris = _sensor_shape(coil)\n rrs = apply_trans(coil_trans, rrs)\n meg_rrs.append(rrs)\n meg_tris.append(tris + offset)\n offset += len(meg_rrs[-1])\n if len(meg_rrs) == 0:\n if warn_meg:\n warn('MEG sensors not found. Cannot plot MEG locations.')\n else:\n meg_rrs = apply_trans(meg_trans, np.concatenate(meg_rrs, axis=0))\n meg_tris = np.concatenate(meg_tris, axis=0)\n del meg\n if dig:\n if dig == 'fiducials':\n hpi_loc = ext_loc = []\n elif dig is not True:\n raise ValueError(\"dig needs to be True, False or 'fiducials', \"\n \"not %s\" % repr(dig))\n else:\n hpi_loc = np.array([\n d['r'] for d in (info['dig'] or [])\n if (d['kind'] == FIFF.FIFFV_POINT_HPI and\n d['coord_frame'] == FIFF.FIFFV_COORD_HEAD)])\n ext_loc = np.array([\n d['r'] for d in (info['dig'] or [])\n if (d['kind'] == FIFF.FIFFV_POINT_EXTRA and\n d['coord_frame'] == FIFF.FIFFV_COORD_HEAD)])\n car_loc = _fiducial_coords(info['dig'], FIFF.FIFFV_COORD_HEAD)\n # Transform from head coords if necessary\n if coord_frame == 'meg':\n for loc in (hpi_loc, ext_loc, car_loc):\n loc[:] = apply_trans(invert_transform(info['dev_head_t']), loc)\n elif coord_frame == 'mri':\n for loc in (hpi_loc, ext_loc, car_loc):\n loc[:] = apply_trans(head_mri_t, loc)\n if len(car_loc) == len(ext_loc) == len(hpi_loc) == 0:\n warn('Digitization points not found. Cannot plot digitization.')\n del dig\n for key, picks in other_picks.items():\n if other_bools[key] and len(picks):\n title = DEFAULTS[\"titles\"][key] if key != 'fnirs' else 'fNIRS'\n if key != 'fnirs' or 'channels' in fnirs:\n other_loc[key] = [\n info['chs'][pick]['loc'][:3] for pick in picks\n ]\n # deal with NaN\n other_loc[key] = np.array([loc for loc in other_loc[key]\n if np.isfinite(loc).all()], float)\n logger.info(\n f'Plotting {len(other_loc[key])} {title}'\n f' location{_pl(other_loc[key])}')\n if key == 'fnirs':\n if 'sources' in fnirs:\n other_loc['source'] = np.array(\n [info['chs'][pick]['loc'][3:6]\n for pick in picks])\n logger.info('Plotting %d %s source%s'\n % (len(other_loc['source']),\n title, _pl(other_loc['source'])))\n if 'detectors' in fnirs:\n other_loc['detector'] = np.array(\n [info['chs'][pick]['loc'][6:9]\n for pick in picks])\n logger.info('Plotting %d %s detector%s'\n % (len(other_loc['detector']),\n title, _pl(other_loc['detector'])))\n for v in other_loc.values():\n v[:] = apply_trans(head_trans, v)\n other_keys = sorted(other_loc) # re-sort and only keep non-empty\n del other_bools\n\n # initialize figure\n renderer = _get_renderer(fig, bgcolor=(0.5, 0.5, 0.5), size=(800, 800))\n if interaction == 'terrain':\n renderer.set_interaction('terrain')\n\n # plot surfaces\n alphas = dict(head=head_alpha, helmet=0.25, lh=hemi_val, rh=hemi_val)\n alphas.update(skull_alpha)\n # replace default alphas with specified user_alpha\n for k, v in user_alpha.items():\n if v is not None:\n alphas[k] = v\n colors = dict(head=DEFAULTS['coreg']['head_color'],\n helmet=(0.0, 0.0, 0.6), lh=(0.5,) * 3,\n rh=(0.5,) * 3)\n colors.update(skull_colors)\n for key, surf in surfs.items():\n renderer.surface(surface=surf, color=colors[key],\n opacity=alphas[key],\n backface_culling=(key != 'helmet'))\n if brain and 'lh' not in surfs: # one layer sphere\n assert bem['coord_frame'] == FIFF.FIFFV_COORD_HEAD\n center = bem['r0'].copy()\n center = apply_trans(head_trans, center)\n renderer.sphere(center, scale=0.01, color=colors['lh'],\n opacity=alphas['lh'])\n if show_axes:\n axes = [(head_trans, (0.9, 0.3, 0.3))] # always show head\n if not np.allclose(head_mri_t['trans'], np.eye(4)): # Show MRI\n axes.append((mri_trans, (0.6, 0.6, 0.6)))\n if len(meg_picks) > 0: # Show MEG\n axes.append((meg_trans, (0., 0.6, 0.6)))\n for ax in axes:\n x, y, z = np.tile(ax[0]['trans'][:3, 3], 3).reshape((3, 3)).T\n u, v, w = ax[0]['trans'][:3, :3]\n renderer.sphere(center=np.column_stack((x[0], y[0], z[0])),\n color=ax[1], scale=3e-3)\n renderer.quiver3d(x=x, y=y, z=z, u=u, v=v, w=w, mode='arrow',\n scale=2e-2, color=ax[1],\n scale_mode='scalar', resolution=20,\n scalars=[0.33, 0.66, 1.0])\n\n # plot points\n defaults = DEFAULTS['coreg']\n datas = [eeg_loc,\n hpi_loc,\n ext_loc] + list(other_loc[key] for key in other_keys)\n colors = [defaults['eeg_color'],\n defaults['hpi_color'],\n defaults['extra_color']\n ] + [defaults[key + '_color'] for key in other_keys]\n alphas = [0.8,\n 0.5,\n 0.25] + [0.8] * len(other_keys)\n scales = [defaults['eeg_scale'],\n defaults['hpi_scale'],\n defaults['extra_scale']\n ] + [defaults[key + '_scale'] for key in other_keys]\n assert len(datas) == len(colors) == len(alphas) == len(scales)\n fid_colors = tuple(\n defaults[f'{key}_color'] for key in ('lpa', 'nasion', 'rpa'))\n glyphs = ['sphere'] * len(datas)\n for kind, loc in (('dig', car_loc), ('mri', fid_loc)):\n if len(loc) > 0:\n datas.extend(loc[:, np.newaxis])\n colors.extend(fid_colors)\n alphas.extend(3 * (defaults[f'{kind}_fid_opacity'],))\n scales.extend(3 * (defaults[f'{kind}_fid_scale'],))\n glyphs.extend(3 * (('oct' if kind == 'mri' else 'sphere'),))\n for data, color, alpha, scale, glyph in zip(\n datas, colors, alphas, scales, glyphs):\n if len(data) > 0:\n if glyph == 'oct':\n transform = np.eye(4)\n transform[:3, :3] = mri_trans['trans'][:3, :3] * scale\n # rotate around Z axis 45 deg first\n transform = transform @ rotation(0, 0, np.pi / 4)\n renderer.quiver3d(\n x=data[:, 0], y=data[:, 1], z=data[:, 2],\n u=1., v=0., w=0., color=color, mode='oct',\n scale=1., opacity=alpha, backface_culling=True,\n solid_transform=transform)\n else:\n assert glyph == 'sphere'\n assert data.ndim == 2 and data.shape[1] == 3, data.shape\n renderer.sphere(center=data, color=color, scale=scale,\n opacity=alpha, backface_culling=True)\n if len(eegp_loc) > 0:\n renderer.quiver3d(\n x=eegp_loc[:, 0], y=eegp_loc[:, 1], z=eegp_loc[:, 2],\n u=eegp_nn[:, 0], v=eegp_nn[:, 1], w=eegp_nn[:, 2],\n color=defaults['eegp_color'], mode='cylinder',\n scale=defaults['eegp_scale'], opacity=0.6,\n glyph_height=defaults['eegp_height'],\n glyph_center=(0., -defaults['eegp_height'], 0),\n glyph_resolution=20,\n backface_culling=True)\n if len(meg_rrs) > 0:\n color, alpha = (0., 0.25, 0.5), 0.25\n surf = dict(rr=meg_rrs, tris=meg_tris)\n renderer.surface(surface=surf, color=color,\n opacity=alpha, backface_culling=True)\n\n if src is not None:\n atlas_ids, colors = read_freesurfer_lut()\n for ss in src:\n src_rr = ss['rr'][ss['inuse'].astype(bool)]\n src_nn = ss['nn'][ss['inuse'].astype(bool)]\n\n src_rr, src_nn = _update_coord_frame(src[0], src_rr, src_nn,\n mri_trans, head_trans)\n # volume sources\n if ss['type'] == 'vol':\n if ss['seg_name'] in colors.keys():\n color = colors[ss['seg_name']][:3]\n color = tuple(i / 256. for i in color)\n else:\n color = (1., 1., 0.)\n\n # surface and discrete sources\n else:\n color = (1., 1., 0.)\n\n if len(src_rr) > 0:\n renderer.quiver3d(\n x=src_rr[:, 0], y=src_rr[:, 1], z=src_rr[:, 2],\n u=src_nn[:, 0], v=src_nn[:, 1], w=src_nn[:, 2],\n color=color, mode='cylinder', scale=3e-3,\n opacity=0.75, glyph_height=0.25,\n glyph_center=(0., 0., 0.), glyph_resolution=20,\n backface_culling=True)\n\n if fwd is not None:\n red = (1.0, 0.0, 0.0)\n green = (0.0, 1.0, 0.0)\n blue = (0.0, 0.0, 1.0)\n for ori, color in zip(range(fwd_nn.shape[1]), (red, green, blue)):\n renderer.quiver3d(fwd_rr[:, 0],\n fwd_rr[:, 1],\n fwd_rr[:, 2],\n fwd_nn[:, ori, 0],\n fwd_nn[:, ori, 1],\n fwd_nn[:, ori, 2],\n color=color, mode='arrow', scale=1.5e-3)\n if 'pairs' in fnirs and len(fnirs_picks) > 0:\n origin = apply_trans(head_trans, np.array(\n [info['chs'][k]['loc'][3:6] for k in fnirs_picks]))\n destination = apply_trans(head_trans, np.array(\n [info['chs'][k]['loc'][6:9] for k in fnirs_picks]))\n logger.info(f'Plotting {origin.shape[0]} fNIRS pair{_pl(origin)}')\n renderer.tube(origin=origin, destination=destination)\n\n renderer.set_camera(azimuth=90, elevation=90,\n distance=0.6, focalpoint=(0., 0., 0.))\n renderer.show()\n return renderer.scene()\n\n\ndef _make_tris_fan(n_vert):\n \"\"\"Make tris given a number of vertices of a circle-like obj.\"\"\"\n tris = np.zeros((n_vert - 2, 3), int)\n tris[:, 2] = np.arange(2, n_vert)\n tris[:, 1] = tris[:, 2] - 1\n return tris\n\n\ndef _sensor_shape(coil):\n \"\"\"Get the sensor shape vertices.\"\"\"\n from scipy.spatial import ConvexHull\n id_ = coil['type'] & 0xFFFF\n pad = True\n # Square figure eight\n if id_ in (FIFF.FIFFV_COIL_NM_122,\n FIFF.FIFFV_COIL_VV_PLANAR_W,\n FIFF.FIFFV_COIL_VV_PLANAR_T1,\n FIFF.FIFFV_COIL_VV_PLANAR_T2,\n ):\n # wound by right hand rule such that +x side is \"up\" (+z)\n long_side = coil['size'] # length of long side (meters)\n offset = 0.0025 # offset of the center portion of planar grad coil\n rrs = np.array([\n [offset, -long_side / 2.],\n [long_side / 2., -long_side / 2.],\n [long_side / 2., long_side / 2.],\n [offset, long_side / 2.],\n [-offset, -long_side / 2.],\n [-long_side / 2., -long_side / 2.],\n [-long_side / 2., long_side / 2.],\n [-offset, long_side / 2.]])\n tris = np.concatenate((_make_tris_fan(4),\n _make_tris_fan(4)[:, ::-1] + 4), axis=0)\n # Square\n elif id_ in (FIFF.FIFFV_COIL_POINT_MAGNETOMETER,\n FIFF.FIFFV_COIL_VV_MAG_T1,\n FIFF.FIFFV_COIL_VV_MAG_T2,\n FIFF.FIFFV_COIL_VV_MAG_T3,\n FIFF.FIFFV_COIL_KIT_REF_MAG,\n ):\n # square magnetometer (potentially point-type)\n size = 0.001 if id_ == 2000 else (coil['size'] / 2.)\n rrs = np.array([[-1., 1.], [1., 1.], [1., -1.], [-1., -1.]]) * size\n tris = _make_tris_fan(4)\n # Circle\n elif id_ in (FIFF.FIFFV_COIL_MAGNES_MAG,\n FIFF.FIFFV_COIL_MAGNES_REF_MAG,\n FIFF.FIFFV_COIL_CTF_REF_MAG,\n FIFF.FIFFV_COIL_BABY_MAG,\n FIFF.FIFFV_COIL_BABY_REF_MAG,\n FIFF.FIFFV_COIL_ARTEMIS123_REF_MAG,\n ):\n n_pts = 15 # number of points for circle\n circle = np.exp(2j * np.pi * np.arange(n_pts) / float(n_pts))\n circle = np.concatenate(([0.], circle))\n circle *= coil['size'] / 2. # radius of coil\n rrs = np.array([circle.real, circle.imag]).T\n tris = _make_tris_fan(n_pts + 1)\n # Circle\n elif id_ in (FIFF.FIFFV_COIL_MAGNES_GRAD,\n FIFF.FIFFV_COIL_CTF_GRAD,\n FIFF.FIFFV_COIL_CTF_REF_GRAD,\n FIFF.FIFFV_COIL_CTF_OFFDIAG_REF_GRAD,\n FIFF.FIFFV_COIL_MAGNES_REF_GRAD,\n FIFF.FIFFV_COIL_MAGNES_OFFDIAG_REF_GRAD,\n FIFF.FIFFV_COIL_KIT_GRAD,\n FIFF.FIFFV_COIL_BABY_GRAD,\n FIFF.FIFFV_COIL_ARTEMIS123_GRAD,\n FIFF.FIFFV_COIL_ARTEMIS123_REF_GRAD,\n ):\n # round coil 1st order (off-diagonal) gradiometer\n baseline = coil['base'] if id_ in (5004, 4005) else 0.\n n_pts = 16 # number of points for circle\n # This time, go all the way around circle to close it fully\n circle = np.exp(2j * np.pi * np.arange(-1, n_pts) / float(n_pts - 1))\n circle[0] = 0 # center pt for triangulation\n circle *= coil['size'] / 2.\n rrs = np.array([ # first, second coil\n np.concatenate([circle.real + baseline / 2.,\n circle.real - baseline / 2.]),\n np.concatenate([circle.imag, -circle.imag])]).T\n tris = np.concatenate([_make_tris_fan(n_pts + 1),\n _make_tris_fan(n_pts + 1) + n_pts + 1])\n # 3D convex hull (will fail for 2D geometry, can extend later if needed)\n else:\n rrs = coil['rmag_orig'].copy()\n pad = False\n tris = _reorder_ccw(rrs, ConvexHull(rrs).simplices)\n\n # Go from (x,y) -> (x,y,z)\n if pad:\n rrs = np.pad(rrs, ((0, 0), (0, 1)), mode='constant')\n assert rrs.ndim == 2 and rrs.shape[1] == 3\n return rrs, tris\n\n\ndef _get_cmap(colormap):\n import matplotlib.pyplot as plt\n if isinstance(colormap, str) and colormap in ('mne', 'mne_analyze'):\n colormap = mne_analyze_colormap([0, 1, 2], format='matplotlib')\n else:\n colormap = plt.get_cmap(colormap)\n return colormap\n\n\ndef _process_clim(clim, colormap, transparent, data=0., allow_pos_lims=True):\n \"\"\"Convert colormap/clim options to dict.\n\n This fills in any \"auto\" entries properly such that round-trip\n calling gives the same results.\n \"\"\"\n # Based on type of limits specified, get cmap control points\n from matplotlib.colors import Colormap\n _validate_type(colormap, (str, Colormap), 'colormap')\n data = np.asarray(data)\n if isinstance(colormap, str):\n if colormap == 'auto':\n if clim == 'auto':\n if allow_pos_lims and (data < 0).any():\n colormap = 'mne'\n else:\n colormap = 'hot'\n else:\n if 'lims' in clim:\n colormap = 'hot'\n else: # 'pos_lims' in clim\n colormap = 'mne'\n colormap = _get_cmap(colormap)\n assert isinstance(colormap, Colormap)\n diverging_maps = ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',\n 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr',\n 'seismic']\n diverging_maps += [d + '_r' for d in diverging_maps]\n diverging_maps += ['mne', 'mne_analyze']\n if clim == 'auto':\n # this is merely a heuristic!\n if allow_pos_lims and colormap.name in diverging_maps:\n key = 'pos_lims'\n else:\n key = 'lims'\n clim = {'kind': 'percent', key: [96, 97.5, 99.95]}\n if not isinstance(clim, dict):\n raise ValueError('\"clim\" must be \"auto\" or dict, got %s' % (clim,))\n\n if ('lims' in clim) + ('pos_lims' in clim) != 1:\n raise ValueError('Exactly one of lims and pos_lims must be specified '\n 'in clim, got %s' % (clim,))\n if 'pos_lims' in clim and not allow_pos_lims:\n raise ValueError('Cannot use \"pos_lims\" for clim, use \"lims\" '\n 'instead')\n diverging = 'pos_lims' in clim\n ctrl_pts = np.array(clim['pos_lims' if diverging else 'lims'], float)\n ctrl_pts = np.array(ctrl_pts, float)\n if ctrl_pts.shape != (3,):\n raise ValueError('clim has shape %s, it must be (3,)'\n % (ctrl_pts.shape,))\n if (np.diff(ctrl_pts) < 0).any():\n raise ValueError('colormap limits must be monotonically '\n 'increasing, got %s' % (ctrl_pts,))\n clim_kind = clim.get('kind', 'percent')\n _check_option(\"clim['kind']\", clim_kind, ['value', 'values', 'percent'])\n if clim_kind == 'percent':\n perc_data = np.abs(data) if diverging else data\n ctrl_pts = np.percentile(perc_data, ctrl_pts)\n logger.info('Using control points %s' % (ctrl_pts,))\n assert len(ctrl_pts) == 3\n clim = dict(kind='value')\n clim['pos_lims' if diverging else 'lims'] = ctrl_pts\n mapdata = dict(clim=clim, colormap=colormap, transparent=transparent)\n return mapdata\n\n\ndef _separate_map(mapdata):\n \"\"\"Help plotters that cannot handle limit equality.\"\"\"\n diverging = 'pos_lims' in mapdata['clim']\n key = 'pos_lims' if diverging else 'lims'\n ctrl_pts = np.array(mapdata['clim'][key])\n assert ctrl_pts.shape == (3,)\n if len(set(ctrl_pts)) == 1: # three points match\n if ctrl_pts[0] == 0: # all are zero\n warn('All data were zero')\n ctrl_pts = np.arange(3, dtype=float)\n else:\n ctrl_pts *= [0., 0.5, 1] # all nonzero pts == max\n elif len(set(ctrl_pts)) == 2: # two points match\n # if points one and two are identical, add a tiny bit to the\n # control point two; if points two and three are identical,\n # subtract a tiny bit from point two.\n bump = 1e-5 if ctrl_pts[0] == ctrl_pts[1] else -1e-5\n ctrl_pts[1] = ctrl_pts[0] + bump * (ctrl_pts[2] - ctrl_pts[0])\n mapdata['clim'][key] = ctrl_pts\n\n\ndef _linearize_map(mapdata):\n from matplotlib.colors import ListedColormap\n diverging = 'pos_lims' in mapdata['clim']\n scale_pts = mapdata['clim']['pos_lims' if diverging else 'lims']\n if diverging:\n lims = [-scale_pts[2], scale_pts[2]]\n ctrl_norm = np.concatenate([-scale_pts[::-1] / scale_pts[2], [0],\n scale_pts / scale_pts[2]]) / 2 + 0.5\n linear_norm = [0, 0.25, 0.5, 0.5, 0.5, 0.75, 1]\n trans_norm = [1, 1, 0, 0, 0, 1, 1]\n else:\n lims = [scale_pts[0], scale_pts[2]]\n range_ = scale_pts[2] - scale_pts[0]\n mid = (scale_pts[1] - scale_pts[0]) / range_ if range_ > 0 else 0.5\n ctrl_norm = [0, mid, 1]\n linear_norm = [0, 0.5, 1]\n trans_norm = [0, 1, 1]\n # do the piecewise linear transformation\n interp_to = np.linspace(0, 1, 256)\n colormap = np.array(mapdata['colormap'](\n np.interp(interp_to, ctrl_norm, linear_norm)))\n if mapdata['transparent']:\n colormap[:, 3] = np.interp(interp_to, ctrl_norm, trans_norm)\n lims = np.array([lims[0], np.mean(lims), lims[1]])\n colormap = ListedColormap(colormap)\n return colormap, lims\n\n\ndef _get_map_ticks(mapdata):\n diverging = 'pos_lims' in mapdata['clim']\n ticks = mapdata['clim']['pos_lims' if diverging else 'lims']\n delta = 1e-2 * (ticks[2] - ticks[0])\n if ticks[1] <= ticks[0] + delta: # Only two worth showing\n ticks = ticks[::2]\n if ticks[1] <= ticks[0] + delta: # Actually only one\n ticks = ticks[::2]\n if diverging:\n idx = int(ticks[0] == 0)\n ticks = list(-np.array(ticks[idx:])[::-1]) + [0] + list(ticks[idx:])\n return np.array(ticks)\n\n\ndef _handle_time(time_label, time_unit, times):\n \"\"\"Handle time label string and units.\"\"\"\n _validate_type(time_label, (None, str, 'callable'), 'time_label')\n if time_label == 'auto':\n if times is not None and len(times) > 1:\n if time_unit == 's':\n time_label = 'time=%0.3fs'\n elif time_unit == 'ms':\n time_label = 'time=%0.1fms'\n else:\n time_label = None\n # convert to callable\n if isinstance(time_label, str):\n time_label_fmt = time_label\n\n def time_label(x):\n try:\n return time_label_fmt % x\n except Exception:\n return time_label # in case it's static\n assert time_label is None or callable(time_label)\n if times is not None:\n _, times = _check_time_unit(time_unit, times)\n return time_label, times\n\n\ndef _key_pressed_slider(event, params):\n \"\"\"Handle key presses for time_viewer slider.\"\"\"\n step = 1\n if event.key.startswith('ctrl'):\n step = 5\n event.key = event.key.split('+')[-1]\n if event.key not in ['left', 'right']:\n return\n time_viewer = event.canvas.figure\n value = time_viewer.slider.val\n times = params['stc'].times\n if params['time_unit'] == 'ms':\n times = times * 1000.\n time_idx = np.argmin(np.abs(times - value))\n if event.key == 'left':\n time_idx = np.max((0, time_idx - step))\n elif event.key == 'right':\n time_idx = np.min((len(times) - 1, time_idx + step))\n this_time = times[time_idx]\n time_viewer.slider.set_val(this_time)\n\n\ndef _smooth_plot(this_time, params):\n \"\"\"Smooth source estimate data and plot with mpl.\"\"\"\n from ..morph import _hemi_morph\n ax = params['ax']\n stc = params['stc']\n ax.clear()\n times = stc.times\n scaler = 1000. if params['time_unit'] == 'ms' else 1.\n if this_time is None:\n time_idx = 0\n else:\n time_idx = np.argmin(np.abs(times - this_time / scaler))\n\n if params['hemi_idx'] == 0:\n data = stc.data[:len(stc.vertices[0]), time_idx:time_idx + 1]\n else:\n data = stc.data[len(stc.vertices[0]):, time_idx:time_idx + 1]\n\n morph = _hemi_morph(\n params['tris'], params['inuse'], params['vertices'],\n params['smoothing_steps'], maps=None, warn=True)\n array_plot = morph @ data\n\n range_ = params['scale_pts'][2] - params['scale_pts'][0]\n colors = (array_plot - params['scale_pts'][0]) / range_\n\n faces = params['faces']\n greymap = params['greymap']\n cmap = params['cmap']\n polyc = ax.plot_trisurf(*params['coords'].T, triangles=faces,\n antialiased=False, vmin=0, vmax=1)\n color_ave = np.mean(colors[faces], axis=1).flatten()\n curv_ave = np.mean(params['curv'][faces], axis=1).flatten()\n colors = cmap(color_ave)\n # alpha blend\n colors[:, :3] *= colors[:, [3]]\n colors[:, :3] += greymap(curv_ave)[:, :3] * (1. - colors[:, [3]])\n colors[:, 3] = 1.\n polyc.set_facecolor(colors)\n if params['time_label'] is not None:\n ax.set_title(params['time_label'](times[time_idx] * scaler,),\n color='w')\n _set_aspect_equal(ax)\n ax.axis('off')\n ax.set(xlim=[-80, 80], ylim=(-80, 80), zlim=[-80, 80])\n ax.figure.canvas.draw()\n\n\ndef _plot_mpl_stc(stc, subject=None, surface='inflated', hemi='lh',\n colormap='auto', time_label='auto', smoothing_steps=10,\n subjects_dir=None, views='lat', clim='auto', figure=None,\n initial_time=None, time_unit='s', background='black',\n spacing='oct6', time_viewer=False, colorbar=True,\n transparent=True):\n \"\"\"Plot source estimate using mpl.\"\"\"\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n from matplotlib import cm\n from matplotlib.widgets import Slider\n import nibabel as nib\n from scipy import stats\n from ..morph import _get_subject_sphere_tris\n if hemi not in ['lh', 'rh']:\n raise ValueError(\"hemi must be 'lh' or 'rh' when using matplotlib. \"\n \"Got %s.\" % hemi)\n lh_kwargs = {'lat': {'elev': 0, 'azim': 180},\n 'med': {'elev': 0, 'azim': 0},\n 'ros': {'elev': 0, 'azim': 90},\n 'cau': {'elev': 0, 'azim': -90},\n 'dor': {'elev': 90, 'azim': -90},\n 'ven': {'elev': -90, 'azim': -90},\n 'fro': {'elev': 0, 'azim': 106.739},\n 'par': {'elev': 30, 'azim': -120}}\n rh_kwargs = {'lat': {'elev': 0, 'azim': 0},\n 'med': {'elev': 0, 'azim': 180},\n 'ros': {'elev': 0, 'azim': 90},\n 'cau': {'elev': 0, 'azim': -90},\n 'dor': {'elev': 90, 'azim': -90},\n 'ven': {'elev': -90, 'azim': -90},\n 'fro': {'elev': 16.739, 'azim': 60},\n 'par': {'elev': 30, 'azim': -60}}\n time_viewer = False if time_viewer == 'auto' else time_viewer\n kwargs = dict(lh=lh_kwargs, rh=rh_kwargs)\n views = 'lat' if views == 'auto' else views\n _check_option('views', views, sorted(lh_kwargs.keys()))\n mapdata = _process_clim(clim, colormap, transparent, stc.data)\n _separate_map(mapdata)\n colormap, scale_pts = _linearize_map(mapdata)\n del transparent, mapdata\n\n time_label, times = _handle_time(time_label, time_unit, stc.times)\n fig = plt.figure(figsize=(6, 6)) if figure is None else figure\n try:\n ax = Axes3D(fig, auto_add_to_figure=False)\n except Exception: # old mpl\n ax = Axes3D(fig)\n else:\n fig.add_axes(ax)\n hemi_idx = 0 if hemi == 'lh' else 1\n surf = op.join(subjects_dir, subject, 'surf', '%s.%s' % (hemi, surface))\n if spacing == 'all':\n coords, faces = nib.freesurfer.read_geometry(surf)\n inuse = slice(None)\n else:\n stype, sval, ico_surf, src_type_str = _check_spacing(spacing)\n surf = _create_surf_spacing(surf, hemi, subject, stype, ico_surf,\n subjects_dir)\n inuse = surf['vertno']\n faces = surf['use_tris']\n coords = surf['rr'][inuse]\n shape = faces.shape\n faces = stats.rankdata(faces, 'dense').reshape(shape) - 1\n faces = np.round(faces).astype(int) # should really be int-like anyway\n del surf\n vertices = stc.vertices[hemi_idx]\n n_verts = len(vertices)\n tris = _get_subject_sphere_tris(subject, subjects_dir)[hemi_idx]\n cmap = cm.get_cmap(colormap)\n greymap = cm.get_cmap('Greys')\n\n curv = nib.freesurfer.read_morph_data(\n op.join(subjects_dir, subject, 'surf', '%s.curv' % hemi))[inuse]\n curv = np.clip(np.array(curv > 0, np.int64), 0.33, 0.66)\n params = dict(ax=ax, stc=stc, coords=coords, faces=faces,\n hemi_idx=hemi_idx, vertices=vertices, tris=tris,\n smoothing_steps=smoothing_steps, n_verts=n_verts,\n inuse=inuse, cmap=cmap, curv=curv,\n scale_pts=scale_pts, greymap=greymap, time_label=time_label,\n time_unit=time_unit)\n _smooth_plot(initial_time, params)\n\n ax.view_init(**kwargs[hemi][views])\n\n try:\n ax.set_facecolor(background)\n except AttributeError:\n ax.set_axis_bgcolor(background)\n\n if time_viewer:\n time_viewer = figure_nobar(figsize=(4.5, .25))\n fig.time_viewer = time_viewer\n ax_time = plt.axes()\n if initial_time is None:\n initial_time = 0\n slider = Slider(ax=ax_time, label='Time', valmin=times[0],\n valmax=times[-1], valinit=initial_time)\n time_viewer.slider = slider\n callback_slider = partial(_smooth_plot, params=params)\n slider.on_changed(callback_slider)\n callback_key = partial(_key_pressed_slider, params=params)\n time_viewer.canvas.mpl_connect('key_press_event', callback_key)\n\n time_viewer.subplots_adjust(left=0.12, bottom=0.05, right=0.75,\n top=0.95)\n fig.subplots_adjust(left=0., bottom=0., right=1., top=1.)\n\n # add colorbar\n from mpl_toolkits.axes_grid1.inset_locator import inset_axes\n sm = plt.cm.ScalarMappable(cmap=cmap,\n norm=plt.Normalize(scale_pts[0], scale_pts[2]))\n cax = inset_axes(ax, width=\"80%\", height=\"5%\", loc=8, borderpad=3.)\n plt.setp(plt.getp(cax, 'xticklabels'), color='w')\n sm.set_array(np.linspace(scale_pts[0], scale_pts[2], 256))\n if colorbar:\n cb = plt.colorbar(sm, cax=cax, orientation='horizontal')\n cb_yticks = plt.getp(cax, 'yticklabels')\n plt.setp(cb_yticks, color='w')\n cax.tick_params(labelsize=16)\n cb.patch.set_facecolor('0.5')\n cax.set(xlim=(scale_pts[0], scale_pts[2]))\n plt_show(True)\n return fig\n\n\ndef link_brains(brains, time=True, camera=False, colorbar=True,\n picking=False):\n \"\"\"Plot multiple SourceEstimate objects with PyVista.\n\n Parameters\n ----------\n brains : list, tuple or np.ndarray\n The collection of brains to plot.\n time : bool\n If True, link the time controllers. Defaults to True.\n camera : bool\n If True, link the camera controls. Defaults to False.\n colorbar : bool\n If True, link the colorbar controllers. Defaults to True.\n picking : bool\n If True, link the vertices picked with the mouse. Defaults to False.\n \"\"\"\n from .backends.renderer import _get_3d_backend\n if _get_3d_backend() != 'pyvista':\n raise NotImplementedError(\"Expected 3d backend is pyvista but\"\n \" {} was given.\".format(_get_3d_backend()))\n from ._brain import Brain, _LinkViewer\n if not isinstance(brains, Iterable):\n brains = [brains]\n if len(brains) == 0:\n raise ValueError(\"The collection of brains is empty.\")\n for brain in brains:\n if not isinstance(brain, Brain):\n raise TypeError(\"Expected type is Brain but\"\n \" {} was given.\".format(type(brain)))\n # enable time viewer if necessary\n brain.setup_time_viewer()\n subjects = [brain._subject_id for brain in brains]\n if subjects.count(subjects[0]) != len(subjects):\n raise RuntimeError(\"Cannot link brains from different subjects.\")\n\n # link brains properties\n _LinkViewer(\n brains=brains,\n time=time,\n camera=camera,\n colorbar=colorbar,\n picking=picking,\n )\n\n\ndef _check_volume(stc, src, surface, backend_name):\n from ..source_estimate import (\n _BaseSurfaceSourceEstimate, _BaseMixedSourceEstimate)\n if isinstance(stc, _BaseSurfaceSourceEstimate):\n return False\n else:\n if backend_name == 'mayavi':\n raise RuntimeError(\n 'Must use the PyVista 3D backend to plot a mixed or volume '\n 'source estimate')\n _validate_type(src, SourceSpaces, 'src',\n 'src when stc is a mixed or volume source estimate')\n if isinstance(stc, _BaseMixedSourceEstimate):\n # When showing subvolumes, surfaces that preserve geometry must\n # be used (i.e., no inflated)\n _check_option(\n 'surface', surface, ('white', 'pial'),\n extra='when plotting a mixed source estimate')\n return True\n\n\n@verbose\ndef plot_source_estimates(stc, subject=None, surface='inflated', hemi='lh',\n colormap='auto', time_label='auto',\n smoothing_steps=10, transparent=True, alpha=1.0,\n time_viewer='auto', subjects_dir=None, figure=None,\n views='auto', colorbar=True, clim='auto',\n cortex=\"classic\", size=800, background=\"black\",\n foreground=None, initial_time=None,\n time_unit='s', backend='auto', spacing='oct6',\n title=None, show_traces='auto',\n src=None, volume_options=1., view_layout='vertical',\n add_data_kwargs=None, brain_kwargs=None,\n verbose=None):\n \"\"\"Plot SourceEstimate.\n\n Parameters\n ----------\n stc : SourceEstimate\n The source estimates to plot.\n subject : str | None\n The subject name corresponding to FreeSurfer environment\n variable SUBJECT. If None stc.subject will be used. If that\n is None, the environment will be used.\n surface : str\n The type of surface (inflated, white etc.).\n hemi : str\n Hemisphere id (ie 'lh', 'rh', 'both', or 'split'). In the case\n of 'both', both hemispheres are shown in the same window.\n In the case of 'split' hemispheres are displayed side-by-side\n in different viewing panes.\n %(colormap)s\n The default ('auto') uses 'hot' for one-sided data and\n 'mne' for two-sided data.\n %(time_label)s\n smoothing_steps : int\n The amount of smoothing.\n %(transparent)s\n alpha : float\n Alpha value to apply globally to the overlay. Has no effect with mpl\n backend.\n time_viewer : bool | str\n Display time viewer GUI. Can also be 'auto', which will mean True\n for the PyVista backend and False otherwise.\n\n .. versionchanged:: 0.20.0\n \"auto\" mode added.\n %(subjects_dir)s\n figure : instance of mayavi.core.api.Scene | instance of matplotlib.figure.Figure | list | int | None\n If None, a new figure will be created. If multiple views or a\n split view is requested, this must be a list of the appropriate\n length. If int is provided it will be used to identify the Mayavi\n figure by it's id or create a new figure with the given id. If an\n instance of matplotlib figure, mpl backend is used for plotting.\n %(views)s\n\n When plotting a standard SourceEstimate (not volume, mixed, or vector)\n and using the PyVista backend, ``views='flat'`` is also supported to\n plot cortex as a flatmap.\n\n .. versionchanged:: 0.21.0\n Support for flatmaps.\n colorbar : bool\n If True, display colorbar on scene.\n %(clim)s\n cortex : str or tuple\n Specifies how binarized curvature values are rendered.\n Either the name of a preset PySurfer cortex colorscheme (one of\n 'classic', 'bone', 'low_contrast', or 'high_contrast'), or the name of\n mayavi colormap, or a tuple with values (colormap, min, max, reverse)\n to fully specify the curvature colors. Has no effect with mpl backend.\n size : float or tuple of float\n The size of the window, in pixels. can be one number to specify\n a square window, or the (width, height) of a rectangular window.\n Has no effect with mpl backend.\n background : matplotlib color\n Color of the background of the display window.\n foreground : matplotlib color | None\n Color of the foreground of the display window. Has no effect with mpl\n backend. None will choose white or black based on the background color.\n initial_time : float | None\n The time to display on the plot initially. ``None`` to display the\n first time sample (default).\n time_unit : 's' | 'ms'\n Whether time is represented in seconds (\"s\", default) or\n milliseconds (\"ms\").\n backend : 'auto' | 'mayavi' | 'pyvista' | 'matplotlib'\n Which backend to use. If ``'auto'`` (default), tries to plot with\n pyvista, but resorts to matplotlib if no 3d backend is available.\n\n .. versionadded:: 0.15.0\n spacing : str\n The spacing to use for the source space. Can be ``'ico#'`` for a\n recursively subdivided icosahedron, ``'oct#'`` for a recursively\n subdivided octahedron, or ``'all'`` for all points. In general, you can\n speed up the plotting by selecting a sparser source space. Has no\n effect with mayavi backend. Defaults to 'oct6'.\n\n .. versionadded:: 0.15.0\n title : str | None\n Title for the figure. If None, the subject name will be used.\n\n .. versionadded:: 0.17.0\n %(show_traces)s\n %(src_volume_options)s\n %(view_layout)s\n %(add_data_kwargs)s\n %(brain_kwargs)s\n %(verbose)s\n\n Returns\n -------\n figure : instance of mne.viz.Brain | matplotlib.figure.Figure\n An instance of :class:`mne.viz.Brain` or matplotlib figure.\n\n Notes\n -----\n Flatmaps are available by default for ``fsaverage`` but not for other\n subjects reconstructed by FreeSurfer. We recommend using\n :func:`mne.compute_source_morph` to morph source estimates to ``fsaverage``\n for flatmap plotting. If you want to construct your own flatmap for a given\n subject, these links might help:\n\n - https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferOccipitalFlattenedPatch\n - https://openwetware.org/wiki/Beauchamp:FreeSurfer\n \"\"\" # noqa: E501\n from .backends.renderer import _get_3d_backend, use_3d_backend\n from ..source_estimate import _BaseSourceEstimate, _check_stc_src\n _check_stc_src(stc, src)\n _validate_type(stc, _BaseSourceEstimate, 'stc', 'source estimate')\n subjects_dir = get_subjects_dir(subjects_dir=subjects_dir,\n raise_error=True)\n subject = _check_subject(stc.subject, subject)\n _check_option('backend', backend,\n ['auto', 'matplotlib', 'mayavi', 'pyvista', 'notebook'])\n plot_mpl = backend == 'matplotlib'\n if not plot_mpl:\n if backend == 'auto':\n try:\n backend = _get_3d_backend()\n except (ImportError, ModuleNotFoundError):\n warn('No 3D backend found. Resorting to matplotlib 3d.')\n plot_mpl = True\n kwargs = dict(\n subject=subject, surface=surface, hemi=hemi, colormap=colormap,\n time_label=time_label, smoothing_steps=smoothing_steps,\n subjects_dir=subjects_dir, views=views, clim=clim,\n figure=figure, initial_time=initial_time, time_unit=time_unit,\n background=background, time_viewer=time_viewer, colorbar=colorbar,\n transparent=transparent)\n if plot_mpl:\n return _plot_mpl_stc(stc, spacing=spacing, **kwargs)\n else:\n with use_3d_backend(backend):\n return _plot_stc(\n stc, overlay_alpha=alpha, brain_alpha=alpha,\n vector_alpha=alpha, cortex=cortex, foreground=foreground,\n size=size, scale_factor=None, show_traces=show_traces,\n src=src, volume_options=volume_options,\n view_layout=view_layout, add_data_kwargs=add_data_kwargs,\n brain_kwargs=brain_kwargs, **kwargs)\n\n\ndef _plot_stc(stc, subject, surface, hemi, colormap, time_label,\n smoothing_steps, subjects_dir, views, clim, figure, initial_time,\n time_unit, background, time_viewer, colorbar, transparent,\n brain_alpha, overlay_alpha, vector_alpha, cortex, foreground,\n size, scale_factor, show_traces, src, volume_options,\n view_layout, add_data_kwargs, brain_kwargs):\n from .backends.renderer import _get_3d_backend, get_brain_class\n from ..source_estimate import _BaseVolSourceEstimate\n vec = stc._data_ndim == 3\n subjects_dir = get_subjects_dir(subjects_dir=subjects_dir,\n raise_error=True)\n subject = _check_subject(stc.subject, subject)\n\n backend = _get_3d_backend()\n del _get_3d_backend\n using_mayavi = backend == \"mayavi\"\n Brain = get_brain_class()\n views = _check_views(surface, views, hemi, stc, backend)\n _check_option('hemi', hemi, ['lh', 'rh', 'split', 'both'])\n _check_option('view_layout', view_layout, ('vertical', 'horizontal'))\n time_label, times = _handle_time(time_label, time_unit, stc.times)\n show_traces, time_viewer = _check_st_tv(\n show_traces, time_viewer, using_mayavi, times)\n\n # convert control points to locations in colormap\n use = stc.magnitude().data if vec else stc.data\n mapdata = _process_clim(clim, colormap, transparent, use,\n allow_pos_lims=not vec)\n\n volume = _check_volume(stc, src, surface, backend)\n\n # XXX we should only need to do this for PySurfer/Mayavi, the PyVista\n # plotter should be smart enough to do this separation in the cmap-to-ctab\n # conversion. But this will need to be another refactoring that will\n # hopefully restore this line:\n #\n # if using_mayavi:\n _separate_map(mapdata)\n colormap = mapdata['colormap']\n diverging = 'pos_lims' in mapdata['clim']\n scale_pts = mapdata['clim']['pos_lims' if diverging else 'lims']\n transparent = mapdata['transparent']\n del mapdata\n\n if hemi in ['both', 'split']:\n hemis = ['lh', 'rh']\n else:\n hemis = [hemi]\n\n if overlay_alpha is None:\n overlay_alpha = brain_alpha\n if overlay_alpha == 0:\n smoothing_steps = 1 # Disable smoothing to save time.\n\n title = subject if len(hemis) > 1 else '%s - %s' % (subject, hemis[0])\n kwargs = {\n \"subject_id\": subject, \"hemi\": hemi, \"surf\": surface,\n \"title\": title, \"cortex\": cortex, \"size\": size,\n \"background\": background, \"foreground\": foreground,\n \"figure\": figure, \"subjects_dir\": subjects_dir,\n \"views\": views, \"alpha\": brain_alpha,\n }\n if brain_kwargs is not None:\n kwargs.update(brain_kwargs)\n if backend in ['pyvista', 'notebook']:\n kwargs[\"show\"] = False\n kwargs[\"view_layout\"] = view_layout\n else:\n kwargs.update(_check_pysurfer_antialias(Brain))\n if view_layout != 'vertical':\n raise ValueError('view_layout must be \"vertical\" when using the '\n 'mayavi backend')\n with warnings.catch_warnings(record=True): # traits warnings\n brain = Brain(**kwargs)\n del kwargs\n\n if using_mayavi:\n # Here we patch to avoid segfault:\n # https://github.com/mne-tools/mne-python/pull/8828\n brain.close = lambda *args, **kwargs: brain._close(False)\n\n if scale_factor is None:\n # Configure the glyphs scale directly\n width = np.mean([np.ptp(brain.geo[hemi].coords[:, 1])\n for hemi in hemis if hemi in brain.geo])\n scale_factor = 0.025 * width / scale_pts[-1]\n\n if transparent is None:\n transparent = True\n center = 0. if diverging else None\n sd_kwargs = dict(transparent=transparent, center=center, verbose=False)\n kwargs = {\n \"array\": stc,\n \"colormap\": colormap,\n \"smoothing_steps\": smoothing_steps,\n \"time\": times, \"time_label\": time_label,\n \"alpha\": overlay_alpha,\n \"colorbar\": colorbar,\n \"vector_alpha\": vector_alpha,\n \"scale_factor\": scale_factor,\n \"verbose\": False,\n \"initial_time\": initial_time,\n \"transparent\": transparent,\n \"center\": center,\n \"fmin\": scale_pts[0],\n \"fmid\": scale_pts[1],\n \"fmax\": scale_pts[2],\n \"clim\": clim,\n \"src\": src,\n \"volume_options\": volume_options,\n \"verbose\": False,\n }\n if add_data_kwargs is not None:\n kwargs.update(add_data_kwargs)\n for hemi in hemis:\n if isinstance(stc, _BaseVolSourceEstimate): # no surf data\n break\n vertices = stc.vertices[0 if hemi == 'lh' else 1]\n if len(vertices) == 0: # no surf data for the given hemi\n continue # no data\n use_kwargs = kwargs.copy()\n use_kwargs.update(hemi=hemi)\n if using_mayavi:\n del use_kwargs['clim'], use_kwargs['src']\n del use_kwargs['volume_options']\n use_kwargs.update(\n min=use_kwargs.pop('fmin'), mid=use_kwargs.pop('fmid'),\n max=use_kwargs.pop('fmax'), array=getattr(stc, hemi + '_data'),\n vertices=vertices)\n with warnings.catch_warnings(record=True): # traits warnings\n brain.add_data(**use_kwargs)\n if using_mayavi:\n brain.scale_data_colormap(fmin=scale_pts[0], fmid=scale_pts[1],\n fmax=scale_pts[2], **sd_kwargs)\n\n if volume:\n use_kwargs = kwargs.copy()\n use_kwargs.update(hemi='vol')\n brain.add_data(**use_kwargs)\n del kwargs\n\n need_peeling = (brain_alpha < 1.0 and\n sys.platform != 'darwin' and\n vec)\n if using_mayavi:\n for hemi in hemis:\n for b in brain._brain_list:\n for layer in b['brain'].data.values():\n glyphs = layer['glyphs']\n if glyphs is None:\n continue\n glyphs.glyph.glyph.scale_factor = scale_factor\n glyphs.glyph.glyph.clamping = False\n glyphs.glyph.glyph.range = (0., 1.)\n\n # depth peeling patch\n if need_peeling:\n for ff in brain._figures:\n for f in ff:\n if f.scene is not None and sys.platform != 'darwin':\n f.scene.renderer.use_depth_peeling = True\n elif need_peeling:\n brain.enable_depth_peeling()\n\n if time_viewer:\n if using_mayavi:\n from surfer import TimeViewer\n TimeViewer(brain)\n else: # PyVista\n brain.setup_time_viewer(time_viewer=time_viewer,\n show_traces=show_traces)\n else:\n if not using_mayavi:\n brain.show()\n\n return brain\n\n\ndef _check_st_tv(show_traces, time_viewer, using_mayavi, times):\n # time_viewer and show_traces\n _check_option('time_viewer', time_viewer, (True, False, 'auto'))\n _validate_type(show_traces, (str, bool, 'numeric'), 'show_traces')\n if isinstance(show_traces, str):\n _check_option('show_traces', show_traces,\n ('auto', 'separate', 'vertex', 'label'),\n extra='when a string')\n if time_viewer == 'auto':\n time_viewer = not using_mayavi\n if show_traces == 'auto':\n show_traces = (\n not using_mayavi and\n time_viewer and\n times is not None and\n len(times) > 1\n )\n if show_traces and not time_viewer:\n raise ValueError('show_traces cannot be used when time_viewer=False')\n if using_mayavi and show_traces:\n raise NotImplementedError(\"show_traces=True is not available \"\n \"for the mayavi 3d backend.\")\n return show_traces, time_viewer\n\n\ndef _glass_brain_crosshairs(params, x, y, z):\n for ax, a, b in ((params['ax_y'], x, z),\n (params['ax_x'], y, z),\n (params['ax_z'], x, y)):\n ax.axvline(a, color='0.75')\n ax.axhline(b, color='0.75')\n\n\ndef _cut_coords_to_ijk(cut_coords, img):\n ijk = apply_trans(np.linalg.inv(img.affine), cut_coords)\n ijk = np.clip(np.round(ijk).astype(int), 0, np.array(img.shape[:3]) - 1)\n return ijk\n\n\ndef _ijk_to_cut_coords(ijk, img):\n return apply_trans(img.affine, ijk)\n\n\ndef _load_subject_mri(mri, stc, subject, subjects_dir, name):\n import nibabel as nib\n from nibabel.spatialimages import SpatialImage\n _validate_type(mri, ('path-like', SpatialImage), name)\n if isinstance(mri, str):\n subject = _check_subject(stc.subject, subject)\n mri = nib.load(_check_mri(mri, subject, subjects_dir))\n return mri\n\n\n@verbose\ndef plot_volume_source_estimates(stc, src, subject=None, subjects_dir=None,\n mode='stat_map', bg_img='T1.mgz',\n colorbar=True, colormap='auto', clim='auto',\n transparent=None, show=True,\n initial_time=None, initial_pos=None,\n verbose=None):\n \"\"\"Plot Nutmeg style volumetric source estimates using nilearn.\n\n Parameters\n ----------\n stc : VectorSourceEstimate\n The vector source estimate to plot.\n src : instance of SourceSpaces | instance of SourceMorph\n The source space. Can also be a SourceMorph to morph the STC to\n a new subject (see Examples).\n\n .. versionchanged:: 0.18\n Support for :class:`~nibabel.spatialimages.SpatialImage`.\n subject : str | None\n The subject name corresponding to FreeSurfer environment\n variable SUBJECT. If None stc.subject will be used. If that\n is None, the environment will be used.\n %(subjects_dir)s\n mode : str\n The plotting mode to use. Either 'stat_map' (default) or 'glass_brain'.\n For \"glass_brain\", activation absolute values are displayed\n after being transformed to a standard MNI brain.\n bg_img : instance of SpatialImage | str\n The background image used in the nilearn plotting function.\n Can also be a string to use the ``bg_img`` file in the subject's\n MRI directory (default is ``'T1.mgz'``).\n Not used in \"glass brain\" plotting.\n colorbar : bool, optional\n If True, display a colorbar on the right of the plots.\n %(colormap)s\n %(clim)s\n %(transparent)s\n show : bool\n Show figures if True. Defaults to True.\n initial_time : float | None\n The initial time to plot. Can be None (default) to use the time point\n with the maximal absolute value activation across all voxels\n or the ``initial_pos`` voxel (if ``initial_pos is None`` or not,\n respectively).\n\n .. versionadded:: 0.19\n initial_pos : ndarray, shape (3,) | None\n The initial position to use (in m). Can be None (default) to use the\n voxel with the maximum absolute value activation across all time points\n or at ``initial_time`` (if ``initial_time is None`` or not,\n respectively).\n\n .. versionadded:: 0.19\n %(verbose)s\n\n Returns\n -------\n fig : instance of Figure\n The figure.\n\n Notes\n -----\n Click on any of the anatomical slices to explore the time series.\n Clicking on any time point will bring up the corresponding anatomical map.\n\n The left and right arrow keys can be used to navigate in time.\n To move in time by larger steps, use shift+left and shift+right.\n\n In ``'glass_brain'`` mode, values are transformed to the standard MNI\n brain using the FreeSurfer Talairach transformation\n ``$SUBJECTS_DIR/$SUBJECT/mri/transforms/talairach.xfm``.\n\n .. versionadded:: 0.17\n\n .. versionchanged:: 0.19\n MRI volumes are automatically transformed to MNI space in\n ``'glass_brain'`` mode.\n\n Examples\n --------\n Passing a :class:`mne.SourceMorph` as the ``src``\n parameter can be useful for plotting in a different subject's space\n (here, a ``'sample'`` STC in ``'fsaverage'``'s space)::\n\n >>> morph = mne.compute_source_morph(src_sample, subject_to='fsaverage') # doctest: +SKIP\n >>> fig = stc_vol_sample.plot(morph) # doctest: +SKIP\n \"\"\" # noqa: E501\n from matplotlib import pyplot as plt, colors\n from matplotlib.cbook import mplDeprecation\n import nibabel as nib\n from ..source_estimate import VolSourceEstimate\n from ..morph import SourceMorph\n\n if not check_version('nilearn', '0.4'):\n raise RuntimeError('This function requires nilearn >= 0.4')\n\n from nilearn.plotting import plot_stat_map, plot_glass_brain\n from nilearn.image import index_img\n\n _check_option('mode', mode, ('stat_map', 'glass_brain'))\n plot_func = dict(stat_map=plot_stat_map,\n glass_brain=plot_glass_brain)[mode]\n _validate_type(stc, VolSourceEstimate, 'stc')\n if isinstance(src, SourceMorph):\n img = src.apply(stc, 'nifti1', mri_resolution=False, mri_space=False)\n stc = src.apply(stc, mri_resolution=False, mri_space=False)\n kind, src_subject = 'morph.subject_to', src.subject_to\n else:\n src = _ensure_src(src, kind='volume', extra=' or SourceMorph')\n img = stc.as_volume(src, mri_resolution=False)\n kind, src_subject = 'src subject', src._subject\n del src\n _print_coord_trans(Transform('mri_voxel', 'ras', img.affine),\n prefix='Image affine ', units='mm', level='debug')\n subject = _check_subject(src_subject, subject, first_kind=kind)\n stc_ijk = np.array(\n np.unravel_index(stc.vertices[0], img.shape[:3], order='F')).T\n assert stc_ijk.shape == (len(stc.vertices[0]), 3)\n del kind\n\n # XXX this assumes zooms are uniform, should probably mult by zooms...\n dist_to_verts = _DistanceQuery(stc_ijk, allow_kdtree=True)\n\n def _cut_coords_to_idx(cut_coords, img):\n \"\"\"Convert voxel coordinates to index in stc.data.\"\"\"\n ijk = _cut_coords_to_ijk(cut_coords, img)\n del cut_coords\n logger.debug(' Affine remapped cut coords to [%d, %d, %d] idx'\n % tuple(ijk))\n dist, loc_idx = dist_to_verts.query(ijk[np.newaxis])\n dist, loc_idx = dist[0], loc_idx[0]\n logger.debug(' Using vertex %d at a distance of %d voxels'\n % (stc.vertices[0][loc_idx], dist))\n return loc_idx\n\n ax_name = dict(x='X (saggital)', y='Y (coronal)', z='Z (axial)')\n\n def _click_to_cut_coords(event, params):\n \"\"\"Get voxel coordinates from mouse click.\"\"\"\n if event.inaxes is params['ax_x']:\n ax = 'x'\n x = params['ax_z'].lines[0].get_xdata()[0]\n y, z = event.xdata, event.ydata\n elif event.inaxes is params['ax_y']:\n ax = 'y'\n y = params['ax_x'].lines[0].get_xdata()[0]\n x, z = event.xdata, event.ydata\n elif event.inaxes is params['ax_z']:\n ax = 'z'\n x, y = event.xdata, event.ydata\n z = params['ax_x'].lines[1].get_ydata()[0]\n else:\n logger.debug(' Click outside axes')\n return None\n cut_coords = np.array((x, y, z))\n logger.debug('')\n\n if params['mode'] == 'glass_brain': # find idx for MIP\n # Figure out what XYZ in world coordinates is in our voxel data\n codes = ''.join(nib.aff2axcodes(params['img_idx'].affine))\n assert len(codes) == 3\n # We don't care about directionality, just which is which dim\n codes = codes.replace('L', 'R').replace('P', 'A').replace('I', 'S')\n idx = codes.index(dict(x='R', y='A', z='S')[ax])\n img_data = np.abs(_get_img_fdata(params['img_idx']))\n ijk = _cut_coords_to_ijk(cut_coords, params['img_idx'])\n if idx == 0:\n ijk[0] = np.argmax(img_data[:, ijk[1], ijk[2]])\n logger.debug(' MIP: i = %d idx' % (ijk[0],))\n elif idx == 1:\n ijk[1] = np.argmax(img_data[ijk[0], :, ijk[2]])\n logger.debug(' MIP: j = %d idx' % (ijk[1],))\n else:\n ijk[2] = np.argmax(img_data[ijk[0], ijk[1], :])\n logger.debug(' MIP: k = %d idx' % (ijk[2],))\n cut_coords = _ijk_to_cut_coords(ijk, params['img_idx'])\n\n logger.debug(' Cut coords for %s: (%0.1f, %0.1f, %0.1f) mm'\n % ((ax_name[ax],) + tuple(cut_coords)))\n return cut_coords\n\n def _press(event, params):\n \"\"\"Manage keypress on the plot.\"\"\"\n pos = params['lx'].get_xdata()\n idx = params['stc'].time_as_index(pos)[0]\n if event.key == 'left':\n idx = max(0, idx - 2)\n elif event.key == 'shift+left':\n idx = max(0, idx - 10)\n elif event.key == 'right':\n idx = min(params['stc'].shape[1] - 1, idx + 2)\n elif event.key == 'shift+right':\n idx = min(params['stc'].shape[1] - 1, idx + 10)\n _update_timeslice(idx, params)\n params['fig'].canvas.draw()\n\n def _update_timeslice(idx, params):\n params['lx'].set_xdata(idx / params['stc'].sfreq +\n params['stc'].tmin)\n ax_x, ax_y, ax_z = params['ax_x'], params['ax_y'], params['ax_z']\n plot_map_callback = params['plot_func']\n # Crosshairs are the first thing plotted in stat_map, and the last\n # in glass_brain\n idxs = [0, 0, 1] if mode == 'stat_map' else [-2, -2, -1]\n cut_coords = (\n ax_y.lines[idxs[0]].get_xdata()[0],\n ax_x.lines[idxs[1]].get_xdata()[0],\n ax_x.lines[idxs[2]].get_ydata()[0])\n ax_x.clear()\n ax_y.clear()\n ax_z.clear()\n params.update({'img_idx': index_img(img, idx)})\n params.update({'title': 'Activation (t=%.3f s.)'\n % params['stc'].times[idx]})\n plot_map_callback(\n params['img_idx'], title='', cut_coords=cut_coords)\n\n @verbose_dec\n def _onclick(event, params, verbose=None):\n \"\"\"Manage clicks on the plot.\"\"\"\n ax_x, ax_y, ax_z = params['ax_x'], params['ax_y'], params['ax_z']\n plot_map_callback = params['plot_func']\n if event.inaxes is params['ax_time']:\n idx = params['stc'].time_as_index(\n event.xdata, use_rounding=True)[0]\n _update_timeslice(idx, params)\n\n cut_coords = _click_to_cut_coords(event, params)\n if cut_coords is None:\n return # not in any axes\n\n ax_x.clear()\n ax_y.clear()\n ax_z.clear()\n plot_map_callback(params['img_idx'], title='',\n cut_coords=cut_coords)\n loc_idx = _cut_coords_to_idx(cut_coords, params['img_idx'])\n ydata = stc.data[loc_idx]\n if loc_idx is not None:\n ax_time.lines[0].set_ydata(ydata)\n else:\n ax_time.lines[0].set_ydata(0.)\n params['fig'].canvas.draw()\n\n if mode == 'glass_brain':\n subject = _check_subject(stc.subject, subject)\n ras_mni_t = read_ras_mni_t(subject, subjects_dir)\n if not np.allclose(ras_mni_t['trans'], np.eye(4)):\n _print_coord_trans(\n ras_mni_t, prefix='Transforming subject ', units='mm')\n logger.info('')\n # To get from voxel coords to world coords (i.e., define affine)\n # we would apply img.affine, then also apply ras_mni_t, which\n # transforms from the subject's RAS to MNI RAS. So we left-multiply\n # these.\n img = nib.Nifti1Image(\n img.dataobj, np.dot(ras_mni_t['trans'], img.affine))\n bg_img = None # not used\n else: # stat_map\n if bg_img is None:\n bg_img = 'T1.mgz'\n bg_img = _load_subject_mri(\n bg_img, stc, subject, subjects_dir, 'bg_img')\n\n if initial_time is None:\n time_sl = slice(0, None)\n else:\n initial_time = float(initial_time)\n logger.info('Fixing initial time: %s sec' % (initial_time,))\n initial_time = np.argmin(np.abs(stc.times - initial_time))\n time_sl = slice(initial_time, initial_time + 1)\n if initial_pos is None: # find max pos and (maybe) time\n loc_idx, time_idx = np.unravel_index(\n np.abs(stc.data[:, time_sl]).argmax(), stc.data[:, time_sl].shape)\n time_idx += time_sl.start\n else: # position specified\n initial_pos = np.array(initial_pos, float)\n if initial_pos.shape != (3,):\n raise ValueError('initial_pos must be float ndarray with shape '\n '(3,), got shape %s' % (initial_pos.shape,))\n initial_pos *= 1000\n logger.info('Fixing initial position: %s mm'\n % (initial_pos.tolist(),))\n loc_idx = _cut_coords_to_idx(initial_pos, img)\n if initial_time is not None: # time also specified\n time_idx = time_sl.start\n else: # find the max\n time_idx = np.argmax(np.abs(stc.data[loc_idx]))\n img_idx = index_img(img, time_idx)\n assert img_idx.shape == img.shape[:3]\n del initial_time, initial_pos\n ijk = stc_ijk[loc_idx]\n cut_coords = _ijk_to_cut_coords(ijk, img_idx)\n np.testing.assert_allclose(_cut_coords_to_ijk(cut_coords, img_idx), ijk)\n logger.info('Showing: t = %0.3f s, (%0.1f, %0.1f, %0.1f) mm, '\n '[%d, %d, %d] vox, %d vertex'\n % ((stc.times[time_idx],) + tuple(cut_coords) + tuple(ijk) +\n (stc.vertices[0][loc_idx],)))\n del ijk\n\n # Plot initial figure\n fig, (axes, ax_time) = plt.subplots(2)\n axes.set(xticks=[], yticks=[])\n marker = 'o' if len(stc.times) == 1 else None\n ydata = stc.data[loc_idx]\n ax_time.plot(stc.times, ydata, color='k', marker=marker)\n if len(stc.times) > 1:\n ax_time.set(xlim=stc.times[[0, -1]])\n ax_time.set(xlabel='Time (s)', ylabel='Activation')\n lx = ax_time.axvline(stc.times[time_idx], color='g')\n fig.tight_layout()\n\n allow_pos_lims = (mode != 'glass_brain')\n mapdata = _process_clim(clim, colormap, transparent, stc.data,\n allow_pos_lims)\n _separate_map(mapdata)\n diverging = 'pos_lims' in mapdata['clim']\n ticks = _get_map_ticks(mapdata)\n colormap, scale_pts = _linearize_map(mapdata)\n del mapdata\n\n ylim = [min((scale_pts[0], ydata.min())),\n max((scale_pts[-1], ydata.max()))]\n ylim = np.array(ylim) + np.array([-1, 1]) * 0.05 * np.diff(ylim)[0]\n dup_neg = False\n if stc.data.min() < 0:\n ax_time.axhline(0., color='0.5', ls='-', lw=0.5, zorder=2)\n dup_neg = not diverging # glass brain with signed data\n yticks = list(ticks)\n if dup_neg:\n yticks += [0] + list(-np.array(ticks))\n yticks = np.unique(yticks)\n ax_time.set(yticks=yticks)\n ax_time.set(ylim=ylim)\n del yticks\n\n if not diverging: # set eq above iff one-sided\n # there is a bug in nilearn where this messes w/transparency\n # Need to double the colormap\n if (scale_pts < 0).any():\n # XXX We should fix this, but it's hard to get nilearn to\n # use arbitrary bounds :(\n # Should get them to support non-mirrored colorbars, or\n # at least a proper `vmin` for one-sided things.\n # Hopefully this is a sufficiently rare use case!\n raise ValueError('Negative colormap limits for sequential '\n 'control points clim[\"lims\"] not supported '\n 'currently, consider shifting or flipping the '\n 'sign of your data for visualization purposes')\n # due to nilearn plotting weirdness, extend this to go\n # -scale_pts[2]->scale_pts[2] instead of scale_pts[0]->scale_pts[2]\n colormap = plt.get_cmap(colormap)\n colormap = colormap(\n np.interp(np.linspace(-1, 1, 256),\n scale_pts / scale_pts[2],\n [0, 0.5, 1]))\n colormap = colors.ListedColormap(colormap)\n vmax = scale_pts[-1]\n\n # black_bg = True is needed because of some matplotlib\n # peculiarity. See: https://stackoverflow.com/a/34730204\n # Otherwise, event.inaxes does not work for ax_x and ax_z\n plot_kwargs = dict(\n threshold=None, axes=axes,\n resampling_interpolation='nearest', vmax=vmax, figure=fig,\n colorbar=colorbar, bg_img=bg_img, cmap=colormap, black_bg=True,\n symmetric_cbar=True)\n\n def plot_and_correct(*args, **kwargs):\n axes.clear()\n if params.get('fig_anat') is not None and plot_kwargs['colorbar']:\n params['fig_anat']._cbar.ax.clear()\n with warnings.catch_warnings(record=True): # nilearn bug; ax recreated\n warnings.simplefilter('ignore', mplDeprecation)\n params['fig_anat'] = partial(\n plot_func, **plot_kwargs)(*args, **kwargs)\n params['fig_anat']._cbar.outline.set_visible(False)\n for key in 'xyz':\n params.update({'ax_' + key: params['fig_anat'].axes[key].ax})\n # Fix nilearn bug w/cbar background being white\n if plot_kwargs['colorbar']:\n params['fig_anat']._cbar.patch.set_facecolor('0.5')\n # adjust one-sided colorbars\n if not diverging:\n _crop_colorbar(params['fig_anat']._cbar, *scale_pts[[0, -1]])\n params['fig_anat']._cbar.set_ticks(params['cbar_ticks'])\n if mode == 'glass_brain':\n _glass_brain_crosshairs(params, *kwargs['cut_coords'])\n\n params = dict(stc=stc, ax_time=ax_time, plot_func=plot_and_correct,\n img_idx=img_idx, fig=fig, lx=lx, mode=mode, cbar_ticks=ticks)\n\n plot_and_correct(stat_map_img=params['img_idx'], title='',\n cut_coords=cut_coords)\n\n if show:\n plt.show()\n fig.canvas.mpl_connect('button_press_event',\n partial(_onclick, params=params, verbose=verbose))\n fig.canvas.mpl_connect('key_press_event',\n partial(_press, params=params))\n\n return fig\n\n\ndef _check_pysurfer_antialias(Brain):\n antialias = _get_3d_option('antialias')\n kwargs = dict()\n if not antialias:\n if 'antialias' not in _get_args(Brain):\n raise ValueError('To turn off antialiasing, PySurfer needs to be '\n 'updated to version 0.11+')\n kwargs['antialias'] = antialias\n return kwargs\n\n\ndef _check_views(surf, views, hemi, stc=None, backend=None):\n from ..source_estimate import SourceEstimate\n _validate_type(views, (list, tuple, str), 'views')\n views = [views] if isinstance(views, str) else list(views)\n if surf == 'flat':\n _check_option('views', views, (['auto'], ['flat']))\n views = ['flat']\n elif len(views) == 1 and views[0] == 'auto':\n views = ['lateral']\n if views == ['flat']:\n if stc is not None:\n _validate_type(stc, SourceEstimate, 'stc',\n 'SourceEstimate when a flatmap is used')\n if backend is not None:\n if backend not in ('pyvista', 'notebook'):\n raise RuntimeError('The PyVista 3D backend must be used to '\n 'plot a flatmap')\n if (views == ['flat']) ^ (surf == 'flat'): # exactly only one of the two\n raise ValueError('surface=\"flat\" must be used with views=\"flat\", got '\n f'surface={repr(surf)} and views={repr(views)}')\n return views\n\n\n@verbose\ndef plot_vector_source_estimates(stc, subject=None, hemi='lh', colormap='hot',\n time_label='auto', smoothing_steps=10,\n transparent=None, brain_alpha=0.4,\n overlay_alpha=None, vector_alpha=1.0,\n scale_factor=None, time_viewer='auto',\n subjects_dir=None, figure=None,\n views='lateral',\n colorbar=True, clim='auto', cortex='classic',\n size=800, background='black',\n foreground=None, initial_time=None,\n time_unit='s', show_traces='auto',\n src=None, volume_options=1.,\n view_layout='vertical',\n add_data_kwargs=None, brain_kwargs=None,\n verbose=None):\n \"\"\"Plot VectorSourceEstimate with PySurfer.\n\n A \"glass brain\" is drawn and all dipoles defined in the source estimate\n are shown using arrows, depicting the direction and magnitude of the\n current moment at the dipole. Additionally, an overlay is plotted on top of\n the cortex with the magnitude of the current.\n\n Parameters\n ----------\n stc : VectorSourceEstimate | MixedVectorSourceEstimate\n The vector source estimate to plot.\n subject : str | None\n The subject name corresponding to FreeSurfer environment\n variable SUBJECT. If None stc.subject will be used. If that\n is None, the environment will be used.\n hemi : str, 'lh' | 'rh' | 'split' | 'both'\n The hemisphere to display.\n %(colormap)s\n This should be a sequential colormap.\n %(time_label)s\n smoothing_steps : int\n The amount of smoothing.\n %(transparent)s\n brain_alpha : float\n Alpha value to apply globally to the surface meshes. Defaults to 0.4.\n overlay_alpha : float\n Alpha value to apply globally to the overlay. Defaults to\n ``brain_alpha``.\n vector_alpha : float\n Alpha value to apply globally to the vector glyphs. Defaults to 1.\n scale_factor : float | None\n Scaling factor for the vector glyphs. By default, an attempt is made to\n automatically determine a sane value.\n time_viewer : bool | str\n Display time viewer GUI. Can be \"auto\", which is True for the PyVista\n backend and False otherwise.\n\n .. versionchanged:: 0.20\n Added \"auto\" option and default.\n subjects_dir : str\n The path to the freesurfer subjects reconstructions.\n It corresponds to Freesurfer environment variable SUBJECTS_DIR.\n figure : instance of mayavi.core.api.Scene | list | int | None\n If None, a new figure will be created. If multiple views or a\n split view is requested, this must be a list of the appropriate\n length. If int is provided it will be used to identify the Mayavi\n figure by it's id or create a new figure with the given id.\n %(views)s\n colorbar : bool\n If True, display colorbar on scene.\n %(clim_onesided)s\n cortex : str or tuple\n Specifies how binarized curvature values are rendered.\n either the name of a preset PySurfer cortex colorscheme (one of\n 'classic', 'bone', 'low_contrast', or 'high_contrast'), or the\n name of mayavi colormap, or a tuple with values (colormap, min,\n max, reverse) to fully specify the curvature colors.\n size : float or tuple of float\n The size of the window, in pixels. can be one number to specify\n a square window, or the (width, height) of a rectangular window.\n background : matplotlib color\n Color of the background of the display window.\n foreground : matplotlib color | None\n Color of the foreground of the display window.\n None will choose black or white based on the background color.\n initial_time : float | None\n The time to display on the plot initially. ``None`` to display the\n first time sample (default).\n time_unit : 's' | 'ms'\n Whether time is represented in seconds (\"s\", default) or\n milliseconds (\"ms\").\n %(show_traces)s\n %(src_volume_options)s\n %(view_layout)s\n %(add_data_kwargs)s\n %(brain_kwargs)s\n %(verbose)s\n\n Returns\n -------\n brain : mne.viz.Brain\n A instance of :class:`mne.viz.Brain`.\n\n Notes\n -----\n .. versionadded:: 0.15\n\n If the current magnitude overlay is not desired, set ``overlay_alpha=0``\n and ``smoothing_steps=1``.\n \"\"\"\n from ..source_estimate import _BaseVectorSourceEstimate\n _validate_type(\n stc, _BaseVectorSourceEstimate, 'stc', 'vector source estimate')\n return _plot_stc(\n stc, subject=subject, surface='white', hemi=hemi, colormap=colormap,\n time_label=time_label, smoothing_steps=smoothing_steps,\n subjects_dir=subjects_dir, views=views, clim=clim, figure=figure,\n initial_time=initial_time, time_unit=time_unit, background=background,\n time_viewer=time_viewer, colorbar=colorbar, transparent=transparent,\n brain_alpha=brain_alpha, overlay_alpha=overlay_alpha,\n vector_alpha=vector_alpha, cortex=cortex, foreground=foreground,\n size=size, scale_factor=scale_factor, show_traces=show_traces,\n src=src, volume_options=volume_options, view_layout=view_layout,\n add_data_kwargs=add_data_kwargs, brain_kwargs=brain_kwargs)\n\n\n@verbose\ndef plot_sparse_source_estimates(src, stcs, colors=None, linewidth=2,\n fontsize=18, bgcolor=(.05, 0, .1),\n opacity=0.2, brain_color=(0.7,) * 3,\n show=True, high_resolution=False,\n fig_name=None, fig_number=None, labels=None,\n modes=('cone', 'sphere'),\n scale_factors=(1, 0.6),\n verbose=None, **kwargs):\n \"\"\"Plot source estimates obtained with sparse solver.\n\n Active dipoles are represented in a \"Glass\" brain.\n If the same source is active in multiple source estimates it is\n displayed with a sphere otherwise with a cone in 3D.\n\n Parameters\n ----------\n src : dict\n The source space.\n stcs : instance of SourceEstimate or list of instances of SourceEstimate\n The source estimates (up to 3).\n colors : list\n List of colors.\n linewidth : int\n Line width in 2D plot.\n fontsize : int\n Font size.\n bgcolor : tuple of length 3\n Background color in 3D.\n opacity : float in [0, 1]\n Opacity of brain mesh.\n brain_color : tuple of length 3\n Brain color.\n show : bool\n Show figures if True.\n high_resolution : bool\n If True, plot on the original (non-downsampled) cortical mesh.\n fig_name : str\n Mayavi figure name.\n fig_number : int\n Matplotlib figure number.\n labels : ndarray or list of ndarray\n Labels to show sources in clusters. Sources with the same\n label and the waveforms within each cluster are presented in\n the same color. labels should be a list of ndarrays when\n stcs is a list ie. one label for each stc.\n modes : list\n Should be a list, with each entry being ``'cone'`` or ``'sphere'``\n to specify how the dipoles should be shown.\n The pivot for the glyphs in ``'cone'`` mode is always the tail\n whereas the pivot in ``'sphere'`` mode is the center.\n scale_factors : list\n List of floating point scale factors for the markers.\n %(verbose)s\n **kwargs : kwargs\n Keyword arguments to pass to mlab.triangular_mesh.\n\n Returns\n -------\n surface : instance of mayavi.mlab.pipeline.surface\n The triangular mesh surface.\n \"\"\"\n import matplotlib.pyplot as plt\n from matplotlib.colors import ColorConverter\n # Update the backend\n from .backends.renderer import _get_renderer\n\n known_modes = ['cone', 'sphere']\n if not isinstance(modes, (list, tuple)) or \\\n not all(mode in known_modes for mode in modes):\n raise ValueError('mode must be a list containing only '\n '\"cone\" or \"sphere\"')\n if not isinstance(stcs, list):\n stcs = [stcs]\n if labels is not None and not isinstance(labels, list):\n labels = [labels]\n\n if colors is None:\n colors = _get_color_list()\n\n linestyles = ['-', '--', ':']\n\n # Show 3D\n lh_points = src[0]['rr']\n rh_points = src[1]['rr']\n points = np.r_[lh_points, rh_points]\n\n lh_normals = src[0]['nn']\n rh_normals = src[1]['nn']\n normals = np.r_[lh_normals, rh_normals]\n\n if high_resolution:\n use_lh_faces = src[0]['tris']\n use_rh_faces = src[1]['tris']\n else:\n use_lh_faces = src[0]['use_tris']\n use_rh_faces = src[1]['use_tris']\n\n use_faces = np.r_[use_lh_faces, lh_points.shape[0] + use_rh_faces]\n\n points *= 170\n\n vertnos = [np.r_[stc.lh_vertno, lh_points.shape[0] + stc.rh_vertno]\n for stc in stcs]\n unique_vertnos = np.unique(np.concatenate(vertnos).ravel())\n\n color_converter = ColorConverter()\n\n renderer = _get_renderer(bgcolor=bgcolor, size=(600, 600), name=fig_name)\n surface = renderer.mesh(x=points[:, 0], y=points[:, 1],\n z=points[:, 2], triangles=use_faces,\n color=brain_color, opacity=opacity,\n backface_culling=True, shading=True,\n normals=normals, **kwargs)\n\n # Show time courses\n fig = plt.figure(fig_number)\n fig.clf()\n ax = fig.add_subplot(111)\n\n colors = cycle(colors)\n\n logger.info(\"Total number of active sources: %d\" % len(unique_vertnos))\n\n if labels is not None:\n colors = [next(colors) for _ in\n range(np.unique(np.concatenate(labels).ravel()).size)]\n\n for idx, v in enumerate(unique_vertnos):\n # get indices of stcs it belongs to\n ind = [k for k, vertno in enumerate(vertnos) if v in vertno]\n is_common = len(ind) > 1\n\n if labels is None:\n c = next(colors)\n else:\n # if vertex is in different stcs than take label from first one\n c = colors[labels[ind[0]][vertnos[ind[0]] == v]]\n\n mode = modes[1] if is_common else modes[0]\n scale_factor = scale_factors[1] if is_common else scale_factors[0]\n\n if (isinstance(scale_factor, (np.ndarray, list, tuple)) and\n len(unique_vertnos) == len(scale_factor)):\n scale_factor = scale_factor[idx]\n\n x, y, z = points[v]\n nx, ny, nz = normals[v]\n renderer.quiver3d(x=x, y=y, z=z, u=nx, v=ny, w=nz,\n color=color_converter.to_rgb(c),\n mode=mode, scale=scale_factor)\n\n for k in ind:\n vertno = vertnos[k]\n mask = (vertno == v)\n assert np.sum(mask) == 1\n linestyle = linestyles[k]\n ax.plot(1e3 * stcs[k].times, 1e9 * stcs[k].data[mask].ravel(),\n c=c, linewidth=linewidth, linestyle=linestyle)\n\n ax.set_xlabel('Time (ms)', fontsize=18)\n ax.set_ylabel('Source amplitude (nAm)', fontsize=18)\n\n if fig_name is not None:\n ax.set_title(fig_name)\n plt_show(show)\n\n renderer.show()\n return surface\n\n\n@verbose\ndef plot_dipole_locations(dipoles, trans=None, subject=None, subjects_dir=None,\n mode='orthoview', coord_frame='mri', idx='gof',\n show_all=True, ax=None, block=False, show=True,\n scale=5e-3, color=None, highlight_color='r',\n fig=None, verbose=None, title=None):\n \"\"\"Plot dipole locations.\n\n If mode is set to 'arrow' or 'sphere', only the location of the first\n time point of each dipole is shown else use the show_all parameter.\n\n The option mode='orthoview' was added in version 0.14.\n\n Parameters\n ----------\n dipoles : list of instances of Dipole | Dipole\n The dipoles to plot.\n trans : dict | None\n The mri to head trans.\n Can be None with mode set to '3d'.\n subject : str | None\n The subject name corresponding to FreeSurfer environment\n variable SUBJECT.\n Can be None with mode set to '3d'.\n subjects_dir : None | str\n The path to the freesurfer subjects reconstructions.\n It corresponds to Freesurfer environment variable SUBJECTS_DIR.\n The default is None.\n mode : str\n Can be ``'arrow'``, ``'sphere'`` or ``'orthoview'``.\n\n .. versionadded:: 0.19.0\n coord_frame : str\n Coordinate frame to use, 'head' or 'mri'. Defaults to 'mri'.\n\n .. versionadded:: 0.14.0\n idx : int | 'gof' | 'amplitude'\n Index of the initially plotted dipole. Can also be 'gof' to plot the\n dipole with highest goodness of fit value or 'amplitude' to plot the\n dipole with the highest amplitude. The dipoles can also be browsed\n through using up/down arrow keys or mouse scroll. Defaults to 'gof'.\n Only used if mode equals 'orthoview'.\n\n .. versionadded:: 0.14.0\n show_all : bool\n Whether to always plot all the dipoles. If ``True`` (default), the\n active dipole is plotted as a red dot and its location determines the\n shown MRI slices. The non-active dipoles are plotted as small blue\n dots. If ``False``, only the active dipole is plotted.\n Only used if ``mode='orthoview'``.\n\n .. versionadded:: 0.14.0\n ax : instance of matplotlib Axes3D | None\n Axes to plot into. If None (default), axes will be created.\n Only used if mode equals 'orthoview'.\n\n .. versionadded:: 0.14.0\n block : bool\n Whether to halt program execution until the figure is closed. Defaults\n to False.\n Only used if mode equals 'orthoview'.\n\n .. versionadded:: 0.14.0\n show : bool\n Show figure if True. Defaults to True.\n Only used if mode equals 'orthoview'.\n scale : float\n The scale of the dipoles if ``mode`` is 'arrow' or 'sphere'.\n color : tuple\n The color of the dipoles.\n The default (None) will use ``'y'`` if mode is ``'orthoview'`` and\n ``show_all`` is True, else 'r'.\n\n .. versionchanged:: 0.19.0\n Color is now passed in orthoview mode.\n highlight_color : color\n The highlight color. Only used in orthoview mode with\n ``show_all=True``.\n\n .. versionadded:: 0.19.0\n fig : mayavi.mlab.Figure | None\n 3D Scene in which to plot the alignment.\n If ``None``, creates a new 600x600 pixel figure with black background.\n\n .. versionadded:: 0.19.0\n %(verbose)s\n %(dipole_locs_fig_title)s\n\n .. versionadded:: 0.21.0\n\n Returns\n -------\n fig : instance of mayavi.mlab.Figure or matplotlib.figure.Figure\n The mayavi figure or matplotlib Figure.\n\n Notes\n -----\n .. versionadded:: 0.9.0\n \"\"\"\n if mode == 'orthoview':\n fig = _plot_dipole_mri_orthoview(\n dipoles, trans=trans, subject=subject, subjects_dir=subjects_dir,\n coord_frame=coord_frame, idx=idx, show_all=show_all,\n ax=ax, block=block, show=show, color=color,\n highlight_color=highlight_color, title=title)\n elif mode in ['arrow', 'sphere']:\n from .backends.renderer import _get_renderer\n color = (1., 0., 0.) if color is None else color\n renderer = _get_renderer(fig=fig, size=(600, 600))\n pos = dipoles.pos\n ori = dipoles.ori\n if coord_frame != 'head':\n trans = _get_trans(trans, fro='head', to=coord_frame)[0]\n pos = apply_trans(trans, pos)\n ori = apply_trans(trans, ori)\n\n renderer.sphere(center=pos, color=color, scale=scale)\n if mode == 'arrow':\n x, y, z = pos.T\n u, v, w = ori.T\n renderer.quiver3d(x, y, z, u, v, w, scale=3 * scale,\n color=color, mode='arrow')\n renderer.show()\n fig = renderer.scene()\n else:\n raise ValueError('Mode must be \"cone\", \"arrow\" or orthoview\", '\n 'got %s.' % (mode,))\n\n return fig\n\n\ndef snapshot_brain_montage(fig, montage, hide_sensors=True):\n \"\"\"Take a snapshot of a Mayavi Scene and project channels onto 2d coords.\n\n Note that this will take the raw values for 3d coordinates of each channel,\n without applying any transforms. If brain images are flipped up/dn upon\n using `~matplotlib.pyplot.imshow`, check your matplotlib backend as this\n behavior changes.\n\n Parameters\n ----------\n fig : instance of ~mayavi.core.api.Scene\n The figure on which you've plotted electrodes using\n :func:`mne.viz.plot_alignment`.\n montage : instance of DigMontage or Info | dict\n The digital montage for the electrodes plotted in the scene. If\n :class:`~mne.Info`, channel positions will be pulled from the ``loc``\n field of ``chs``. dict should have ch:xyz mappings.\n hide_sensors : bool\n Whether to remove the spheres in the scene before taking a snapshot.\n\n Returns\n -------\n xy : array, shape (n_channels, 2)\n The 2d location of each channel on the image of the current scene view.\n im : array, shape (m, n, 3)\n The screenshot of the current scene view.\n \"\"\"\n from ..channels import DigMontage\n from .. import Info\n # Update the backend\n from .backends.renderer import _get_renderer\n\n if fig is None:\n raise ValueError('The figure must have a scene')\n if isinstance(montage, DigMontage):\n chs = montage._get_ch_pos()\n ch_names, xyz = zip(*[(ich, ixyz) for ich, ixyz in chs.items()])\n elif isinstance(montage, Info):\n xyz = [ich['loc'][:3] for ich in montage['chs']]\n ch_names = [ich['ch_name'] for ich in montage['chs']]\n elif isinstance(montage, dict):\n if not all(len(ii) == 3 for ii in montage.values()):\n raise ValueError('All electrode positions must be length 3')\n ch_names, xyz = zip(*[(ich, ixyz) for ich, ixyz in montage.items()])\n else:\n raise TypeError('montage must be an instance of `DigMontage`, `Info`,'\n ' or `dict`')\n\n # initialize figure\n renderer = _get_renderer(fig, show=True)\n\n xyz = np.vstack(xyz)\n proj = renderer.project(xyz=xyz, ch_names=ch_names)\n if hide_sensors is True:\n proj.visible(False)\n\n im = renderer.screenshot()\n proj.visible(True)\n return proj.xy, im\n\n\n@fill_doc\ndef plot_sensors_connectivity(info, con, picks=None,\n cbar_label='Connectivity'):\n \"\"\"Visualize the sensor connectivity in 3D.\n\n Parameters\n ----------\n info : dict | None\n The measurement info.\n con : array, shape (n_channels, n_channels)\n The computed connectivity measure(s).\n %(picks_good_data)s\n Indices of selected channels.\n cbar_label : str\n Label for the colorbar.\n\n Returns\n -------\n fig : instance of mayavi.mlab.Figure\n The mayavi figure.\n \"\"\"\n _validate_type(info, \"info\")\n\n from .backends.renderer import _get_renderer\n\n renderer = _get_renderer(size=(600, 600), bgcolor=(0.5, 0.5, 0.5))\n\n picks = _picks_to_idx(info, picks)\n if len(picks) != len(con):\n raise ValueError('The number of channels picked (%s) does not '\n 'correspond to the size of the connectivity data '\n '(%s)' % (len(picks), len(con)))\n\n # Plot the sensor locations\n sens_loc = [info['chs'][k]['loc'][:3] for k in picks]\n sens_loc = np.array(sens_loc)\n\n renderer.sphere(np.c_[sens_loc[:, 0], sens_loc[:, 1], sens_loc[:, 2]],\n color=(1, 1, 1), opacity=1, scale=0.005)\n\n # Get the strongest connections\n n_con = 20 # show up to 20 connections\n min_dist = 0.05 # exclude sensors that are less than 5cm apart\n threshold = np.sort(con, axis=None)[-n_con]\n ii, jj = np.where(con >= threshold)\n\n # Remove close connections\n con_nodes = list()\n con_val = list()\n for i, j in zip(ii, jj):\n if np.linalg.norm(sens_loc[i] - sens_loc[j]) > min_dist:\n con_nodes.append((i, j))\n con_val.append(con[i, j])\n\n con_val = np.array(con_val)\n\n # Show the connections as tubes between sensors\n vmax = np.max(con_val)\n vmin = np.min(con_val)\n for val, nodes in zip(con_val, con_nodes):\n x1, y1, z1 = sens_loc[nodes[0]]\n x2, y2, z2 = sens_loc[nodes[1]]\n tube = renderer.tube(origin=np.c_[x1, y1, z1],\n destination=np.c_[x2, y2, z2],\n scalars=np.c_[val, val],\n vmin=vmin, vmax=vmax,\n reverse_lut=True)\n\n renderer.scalarbar(source=tube, title=cbar_label)\n\n # Add the sensor names for the connections shown\n nodes_shown = list(set([n[0] for n in con_nodes] +\n [n[1] for n in con_nodes]))\n\n for node in nodes_shown:\n x, y, z = sens_loc[node]\n renderer.text3d(x, y, z, text=info['ch_names'][picks[node]],\n scale=0.005,\n color=(0, 0, 0))\n\n renderer.set_camera(azimuth=-88.7, elevation=40.8,\n distance=0.76,\n focalpoint=np.array([-3.9e-4, -8.5e-3, -1e-2]))\n renderer.show()\n return renderer.scene()\n\n\ndef _plot_dipole_mri_orthoview(dipole, trans, subject, subjects_dir=None,\n coord_frame='head', idx='gof', show_all=True,\n ax=None, block=False, show=True, color=None,\n highlight_color='r', title=None):\n \"\"\"Plot dipoles on top of MRI slices in 3-D.\"\"\"\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n from .. import Dipole\n if not has_nibabel():\n raise ImportError('This function requires nibabel.')\n\n _check_option('coord_frame', coord_frame, ['head', 'mri'])\n\n if not isinstance(dipole, Dipole):\n from ..dipole import _concatenate_dipoles\n dipole = _concatenate_dipoles(dipole)\n if idx == 'gof':\n idx = np.argmax(dipole.gof)\n elif idx == 'amplitude':\n idx = np.argmax(np.abs(dipole.amplitude))\n else:\n idx = _ensure_int(idx, 'idx', 'an int or one of [\"gof\", \"amplitude\"]')\n\n vox, ori, pos, data = _get_dipole_loc(\n dipole, trans, subject, subjects_dir, coord_frame)\n\n dims = len(data) # Symmetric size assumed.\n dd = dims // 2\n if ax is None:\n fig, ax = plt.subplots(1, subplot_kw=dict(projection='3d'))\n else:\n _validate_type(ax, Axes3D, \"ax\", \"Axes3D\")\n fig = ax.get_figure()\n\n gridx, gridy = np.meshgrid(np.linspace(-dd, dd, dims),\n np.linspace(-dd, dd, dims), indexing='ij')\n params = {'ax': ax, 'data': data, 'idx': idx, 'dipole': dipole,\n 'vox': vox, 'gridx': gridx, 'gridy': gridy,\n 'ori': ori, 'coord_frame': coord_frame,\n 'show_all': show_all, 'pos': pos,\n 'color': color, 'highlight_color': highlight_color,\n 'title': title}\n _plot_dipole(**params)\n ax.view_init(elev=30, azim=-140)\n\n callback_func = partial(_dipole_changed, params=params)\n fig.canvas.mpl_connect('scroll_event', callback_func)\n fig.canvas.mpl_connect('key_press_event', callback_func)\n\n plt_show(show, block=block)\n return fig\n\n\nRAS_AFFINE = np.eye(4)\nRAS_AFFINE[:3, 3] = [-128] * 3\nRAS_SHAPE = (256, 256, 256)\n\n\ndef _get_dipole_loc(dipole, trans, subject, subjects_dir, coord_frame):\n \"\"\"Get the dipole locations and orientations.\"\"\"\n import nibabel as nib\n from nibabel.processing import resample_from_to\n _check_option('coord_frame', coord_frame, ['head', 'mri'])\n\n subjects_dir = get_subjects_dir(subjects_dir=subjects_dir,\n raise_error=True)\n t1_fname = op.join(subjects_dir, subject, 'mri', 'T1.mgz')\n t1 = nib.load(t1_fname)\n # Do everything in mm here to make life slightly easier\n vox_ras_t, _, mri_ras_t, _, _ = _read_mri_info(\n t1_fname, units='mm')\n head_mri_t = _get_trans(trans, fro='head', to='mri')[0].copy()\n head_mri_t['trans'][:3, 3] *= 1000 # m→mm\n del trans\n pos = dipole.pos * 1e3 # m→mm\n ori = dipole.ori\n # Figure out how to always resample to an identity, 256x256x256 RAS:\n #\n # 1. Resample to head or MRI surface RAS (the conditional), but also\n # 2. Resample to what will work for the standard 1mm** RAS_AFFINE (resamp)\n #\n # We could do this with two resample_from_to calls, but it's cleaner,\n # faster, and we get fewer boundary artifacts if we do it in one shot.\n # So first olve usamp s.t. ``upsamp @ vox_ras_t == RAS_AFFINE`` (2):\n upsamp = np.linalg.solve(vox_ras_t['trans'].T, RAS_AFFINE.T).T\n # Now figure out how we would resample from RAS to head or MRI coords:\n if coord_frame == 'head':\n dest_ras_t = combine_transforms(\n head_mri_t, mri_ras_t, 'head', 'ras')['trans']\n else:\n pos = apply_trans(head_mri_t, pos)\n ori = apply_trans(head_mri_t, dipole.ori, move=False)\n dest_ras_t = mri_ras_t['trans']\n # The order here is wacky because we need `resample_from_to` to operate\n # in a reverse order\n affine = np.dot(np.dot(dest_ras_t, upsamp), vox_ras_t['trans'])\n t1 = resample_from_to(t1, (RAS_SHAPE, affine), order=0)\n # Now we could do:\n #\n # t1 = SpatialImage(t1.dataobj, RAS_AFFINE)\n #\n # And t1 would be in our destination (mri or head) space. But we don't\n # need to construct the image -- let's just get our voxel coords and data:\n vox = apply_trans(np.linalg.inv(RAS_AFFINE), pos)\n t1_data = _get_img_fdata(t1)\n return vox, ori, pos, t1_data\n\n\ndef _plot_dipole(ax, data, vox, idx, dipole, gridx, gridy, ori, coord_frame,\n show_all, pos, color, highlight_color, title):\n \"\"\"Plot dipoles.\"\"\"\n import matplotlib.pyplot as plt\n from matplotlib.colors import ColorConverter\n color_converter = ColorConverter()\n xidx, yidx, zidx = np.round(vox[idx]).astype(int)\n xslice = data[xidx]\n yslice = data[:, yidx]\n zslice = data[:, :, zidx]\n\n ori = ori[idx]\n if color is None:\n color = 'y' if show_all else 'r'\n color = np.array(color_converter.to_rgba(color))\n highlight_color = np.array(color_converter.to_rgba(highlight_color))\n if show_all:\n colors = np.repeat(color[np.newaxis], len(vox), axis=0)\n colors[idx] = highlight_color\n size = np.repeat(5, len(vox))\n size[idx] = 20\n visible = np.arange(len(vox))\n else:\n colors = color\n size = 20\n visible = idx\n\n offset = np.min(gridx)\n xyz = pos\n ax.scatter(xs=xyz[visible, 0], ys=xyz[visible, 1],\n zs=xyz[visible, 2], zorder=2, s=size, facecolor=colors)\n xx = np.linspace(offset, xyz[idx, 0], xidx)\n yy = np.linspace(offset, xyz[idx, 1], yidx)\n zz = np.linspace(offset, xyz[idx, 2], zidx)\n ax.plot(xx, np.repeat(xyz[idx, 1], len(xx)), zs=xyz[idx, 2], zorder=1,\n linestyle='-', color=highlight_color)\n ax.plot(np.repeat(xyz[idx, 0], len(yy)), yy, zs=xyz[idx, 2], zorder=1,\n linestyle='-', color=highlight_color)\n ax.plot(np.repeat(xyz[idx, 0], len(zz)),\n np.repeat(xyz[idx, 1], len(zz)), zs=zz, zorder=1,\n linestyle='-', color=highlight_color)\n q_kwargs = dict(length=50, color=highlight_color, pivot='tail')\n ax.quiver(xyz[idx, 0], xyz[idx, 1], xyz[idx, 2], ori[0], ori[1], ori[2],\n **q_kwargs)\n dims = np.array([(len(data) / -2.), (len(data) / 2.)])\n ax.set(xlim=-dims, ylim=-dims, zlim=dims)\n\n # Plot slices\n ax.contourf(xslice, gridx, gridy, offset=offset, zdir='x',\n cmap='gray', zorder=0, alpha=.5)\n ax.contourf(gridx, yslice, gridy, offset=offset, zdir='y',\n cmap='gray', zorder=0, alpha=.5)\n ax.contourf(gridx, gridy, zslice, offset=offset, zdir='z',\n cmap='gray', zorder=0, alpha=.5)\n\n # Plot orientations\n args = np.array([list(xyz[idx]) + list(ori)] * 3)\n for ii in range(3):\n args[ii, [ii, ii + 3]] = [offset + 0.5, 0] # half a mm inward (z ord)\n ax.quiver(*args.T, alpha=.75, **q_kwargs)\n\n # These are the only two options\n coord_frame_name = 'Head' if coord_frame == 'head' else 'MRI'\n\n if title is None:\n title = ('Dipole #%s / %s @ %.3fs, GOF: %.1f%%, %.1fnAm\\n%s: ' % (\n idx + 1, len(dipole.times), dipole.times[idx], dipole.gof[idx],\n dipole.amplitude[idx] * 1e9, coord_frame_name) +\n '(%0.1f, %0.1f, %0.1f) mm' % tuple(xyz[idx]))\n\n ax.get_figure().suptitle(title)\n\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n\n plt.draw()\n\n\ndef _dipole_changed(event, params):\n \"\"\"Handle dipole plotter scroll/key event.\"\"\"\n if event.key is not None:\n if event.key == 'up':\n params['idx'] += 1\n elif event.key == 'down':\n params['idx'] -= 1\n else: # some other key\n return\n elif event.step > 0: # scroll event\n params['idx'] += 1\n else:\n params['idx'] -= 1\n params['idx'] = min(max(0, params['idx']), len(params['dipole'].pos) - 1)\n params['ax'].clear()\n _plot_dipole(**params)\n\n\ndef _update_coord_frame(obj, rr, nn, mri_trans, head_trans):\n if obj['coord_frame'] == FIFF.FIFFV_COORD_MRI:\n rr = apply_trans(mri_trans, rr)\n nn = apply_trans(mri_trans, nn, move=False)\n elif obj['coord_frame'] == FIFF.FIFFV_COORD_HEAD:\n rr = apply_trans(head_trans, rr)\n nn = apply_trans(head_trans, nn, move=False)\n return rr, nn\n\n\n@fill_doc\ndef plot_brain_colorbar(ax, clim, colormap='auto', transparent=True,\n orientation='vertical', label='Activation',\n bgcolor='0.5'):\n \"\"\"Plot a colorbar that corresponds to a brain activation map.\n\n Parameters\n ----------\n ax : instance of Axes\n The Axes to plot into.\n %(clim)s\n %(colormap)s\n %(transparent)s\n orientation : str\n Orientation of the colorbar, can be \"vertical\" or \"horizontal\".\n label : str\n The colorbar label.\n bgcolor : color\n The color behind the colorbar (for alpha blending).\n\n Returns\n -------\n cbar : instance of ColorbarBase\n The colorbar.\n\n Notes\n -----\n .. versionadded:: 0.19\n \"\"\"\n from matplotlib.colorbar import ColorbarBase\n from matplotlib.colors import Normalize\n mapdata = _process_clim(clim, colormap, transparent)\n ticks = _get_map_ticks(mapdata)\n colormap, lims = _linearize_map(mapdata)\n del mapdata\n norm = Normalize(vmin=lims[0], vmax=lims[2])\n cbar = ColorbarBase(ax, cmap=colormap, norm=norm, ticks=ticks,\n label=label, orientation=orientation)\n # make the colorbar background match the brain color\n cbar.patch.set(facecolor=bgcolor)\n # remove the colorbar frame except for the line containing the ticks\n cbar.outline.set_visible(False)\n cbar.ax.set_frame_on(True)\n for key in ('left', 'top',\n 'bottom' if orientation == 'vertical' else 'right'):\n ax.spines[key].set_visible(False)\n return cbar\n\n\n_3d_options = dict()\n_3d_default = dict(antialias='true')\n\n\ndef set_3d_options(antialias=None):\n \"\"\"Set 3D rendering options.\n\n Parameters\n ----------\n antialias : bool | None\n If not None, set the default full-screen anti-aliasing setting.\n False is useful when renderers have problems (such as software\n MESA renderers). This option can also be controlled using an\n environment variable, e.g., ``MNE_3D_OPTION_ANTIALIAS=false``.\n\n Notes\n -----\n .. versionadded:: 0.21.0\n \"\"\"\n if antialias is not None:\n _3d_options['antialias'] = str(bool(antialias)).lower()\n\n\ndef _get_3d_option(key):\n try:\n opt = _3d_options[key]\n except KeyError:\n opt = get_config(f'MNE_3D_OPTION_{key.upper()}', _3d_default[key])\n opt = opt.lower()\n _check_option(f'3D option {key}', opt, ('true', 'false'))\n return opt == 'true'\n"
] | [
[
"scipy.stats.ttest_1samp",
"numpy.random.seed",
"numpy.linspace",
"scipy.sparse.eye",
"numpy.testing.assert_array_equal",
"numpy.random.randn",
"numpy.testing.assert_allclose",
"numpy.random.default_rng"
],
[
"numpy.abs",
"numpy.triu_indices",
"numpy.arange",
"numpy.eye",
"numpy.in1d",
"numpy.linalg.norm",
"numpy.sin",
"numpy.testing.assert_array_equal",
"numpy.intersect1d",
"numpy.argmax",
"numpy.iscomplexobj",
"numpy.not_equal",
"numpy.random.RandomState",
"numpy.testing.assert_allclose"
],
[
"numpy.isfinite",
"numpy.in1d",
"numpy.full_like",
"numpy.intersect1d",
"numpy.concatenate",
"numpy.log10",
"numpy.array"
],
[
"numpy.unique"
],
[
"scipy.sparse.eye",
"numpy.zeros_like"
],
[
"numpy.dot",
"numpy.linspace",
"numpy.asarray",
"numpy.ptp",
"matplotlib.pyplot.get_cmap",
"numpy.concatenate",
"numpy.max",
"matplotlib.pyplot.axes",
"numpy.round",
"numpy.mean",
"numpy.argmin",
"numpy.where",
"numpy.tile",
"numpy.pad",
"numpy.unique",
"numpy.arange",
"numpy.eye",
"matplotlib.colorbar.ColorbarBase",
"numpy.argmax",
"numpy.diff",
"numpy.interp",
"numpy.column_stack",
"numpy.repeat",
"numpy.zeros",
"numpy.unravel_index",
"matplotlib.pyplot.figure",
"numpy.isclose",
"numpy.min",
"numpy.linalg.inv",
"scipy.spatial.distance.cdist",
"matplotlib.pyplot.Normalize",
"matplotlib.pyplot.getp",
"matplotlib.colors.ListedColormap",
"scipy.spatial.ConvexHull",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.sum",
"numpy.linalg.solve",
"numpy.abs",
"numpy.isfinite",
"scipy.stats.rankdata",
"matplotlib.pyplot.subplots",
"matplotlib.colors.Normalize",
"matplotlib.pyplot.draw",
"numpy.percentile",
"matplotlib.widgets.Slider",
"matplotlib.pyplot.colorbar",
"numpy.sort",
"matplotlib.pyplot.setp",
"matplotlib.colors.ColorConverter",
"numpy.empty",
"matplotlib.cm.get_cmap",
"numpy.linalg.norm",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
mathemusician/pytorch-lightning | [
"15fa5389387b3a220bc044dd30eb0be1e8f64944",
"15fa5389387b3a220bc044dd30eb0be1e8f64944",
"15fa5389387b3a220bc044dd30eb0be1e8f64944",
"15fa5389387b3a220bc044dd30eb0be1e8f64944"
] | [
"tests/strategies/test_ddp_fully_sharded_with_full_state_dict.py",
"pytorch_lightning/tuner/lr_finder.py",
"tests/benchmarks/test_sharded_parity.py",
"pytorch_lightning/utilities/fetching.py"
] | [
"import os\nfrom typing import Any, Dict, Optional\nfrom unittest import mock\n\nimport pytest\nimport torch\n\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning.plugins import FullyShardedNativeMixedPrecisionPlugin\nfrom pytorch_lightning.strategies import DDPFullyShardedStrategy\nfrom pytorch_lightning.utilities import _FAIRSCALE_FULLY_SHARDED_AVAILABLE\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom tests.helpers.boring_model import BoringModel\nfrom tests.helpers.runif import RunIf\n\nif _FAIRSCALE_FULLY_SHARDED_AVAILABLE:\n from fairscale.nn import FullyShardedDataParallel, wrap\n\n\ndef test_invalid_on_cpu(tmpdir):\n \"\"\"Test to ensure that to raise Misconfiguration for FSDP on CPU.\"\"\"\n with pytest.raises(\n MisconfigurationException, match=\"You selected strategy to be `ddp_fully_sharded`, but GPU is not available.\"\n ):\n trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=True, strategy=\"fsdp\")\n assert isinstance(trainer.strategy, DDPFullyShardedStrategy)\n trainer.strategy.setup_environment()\n\n\[email protected](os.environ, {\"CUDA_VISIBLE_DEVICES\": \"0\"})\[email protected](\"torch.cuda.device_count\", return_value=1)\[email protected](\"torch.cuda.is_available\", return_value=True)\n@RunIf(fairscale_fully_sharded=True)\ndef test_fsdp_with_sharded_amp(device_count_mock, mock_cuda_available, tmpdir):\n \"\"\"Test to ensure that plugin native amp plugin is correctly chosen when using sharded.\"\"\"\n trainer = Trainer(\n default_root_dir=tmpdir, fast_dev_run=True, strategy=\"fsdp\", accelerator=\"gpu\", devices=1, precision=16\n )\n assert isinstance(trainer.strategy, DDPFullyShardedStrategy)\n assert isinstance(trainer.strategy.precision_plugin, FullyShardedNativeMixedPrecisionPlugin)\n\n\nclass TestFSDPModel(BoringModel):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.layer: Optional[torch.nn.Module] = None\n\n def _init_model(self) -> None:\n self.layer = torch.nn.Sequential(torch.nn.Linear(32, 32), torch.nn.ReLU(), torch.nn.Linear(32, 2))\n\n def setup(self, stage: str) -> None:\n if self.layer is None:\n self._init_model()\n\n def configure_sharded_model(self) -> None:\n # the model is already wrapped with FSDP: no need to wrap again!\n if isinstance(self.layer, FullyShardedDataParallel):\n return\n for i, layer in enumerate(self.layer):\n if i % 2 == 0:\n self.layer[i] = wrap(layer)\n self.layer = wrap(self.layer)\n\n def on_load_checkpoint(self, checkpoint: Dict[str, Any]) -> None:\n # when loading full state dict, we first need to create a new unwrapped model\n self._init_model()\n\n def configure_optimizers(self):\n return torch.optim.SGD(self.layer.parameters(), lr=0.1)\n\n def on_train_start(self) -> None:\n self._assert_layer_fsdp_instance()\n\n def on_test_start(self) -> None:\n self._assert_layer_fsdp_instance()\n\n def on_validation_start(self) -> None:\n self._assert_layer_fsdp_instance()\n\n def on_prediction_start(self) -> None:\n self._assert_layer_fsdp_instance()\n\n def _assert_layer_fsdp_instance(self) -> None:\n assert isinstance(self.layer, FullyShardedDataParallel)\n assert isinstance(self.layer.module[0], FullyShardedDataParallel)\n assert isinstance(self.layer.module[2], FullyShardedDataParallel)\n\n # Assert that the nested layers are set reshard_after_forward to True\n assert self.layer.module[0].reshard_after_forward is True\n assert self.layer.module[2].reshard_after_forward is True\n\n if isinstance(self.trainer.precision_plugin, FullyShardedNativeMixedPrecisionPlugin):\n assert self.layer.mixed_precision\n assert self.layer.module[0].mixed_precision\n assert self.layer.module[2].mixed_precision\n\n\n@RunIf(min_gpus=1, skip_windows=True, standalone=True, fairscale_fully_sharded=True)\ndef test_fully_sharded_strategy_checkpoint(tmpdir):\n \"\"\"Test to ensure that checkpoint is saved correctly when using a single GPU, and all stages can be run.\"\"\"\n\n model = TestFSDPModel()\n trainer = Trainer(\n default_root_dir=tmpdir,\n accelerator=\"gpu\",\n devices=1,\n strategy=\"fsdp\",\n precision=16,\n max_epochs=1,\n enable_progress_bar=False,\n enable_model_summary=False,\n )\n _run_multiple_stages(trainer, model, os.path.join(tmpdir, \"last.ckpt\"))\n\n\n@RunIf(min_gpus=2, skip_windows=True, standalone=True, fairscale_fully_sharded=True)\ndef test_fully_sharded_strategy_checkpoint_multi_gpus(tmpdir):\n \"\"\"Test to ensure that checkpoint is saved correctly when using multiple GPUs, and all stages can be run.\"\"\"\n\n model = TestFSDPModel()\n ck = ModelCheckpoint(save_last=True)\n trainer = Trainer(\n default_root_dir=tmpdir,\n accelerator=\"gpu\",\n devices=2,\n strategy=\"fsdp\",\n precision=16,\n max_epochs=1,\n callbacks=[ck],\n enable_progress_bar=False,\n enable_model_summary=False,\n )\n _run_multiple_stages(trainer, model)\n\n\ndef _assert_save_equality(trainer, ckpt_path, cls=TestFSDPModel):\n # Use FullySharded to get the state dict for the sake of comparison\n model_state_dict = trainer.strategy.lightning_module_state_dict()\n\n if trainer.is_global_zero:\n saved_model = cls.load_from_checkpoint(ckpt_path)\n\n # Assert model parameters are identical after loading\n for ddp_param, shard_param in zip(model_state_dict.values(), saved_model.state_dict().values()):\n assert torch.equal(ddp_param.float().cpu(), shard_param)\n\n\ndef _run_multiple_stages(trainer, model, model_path: Optional[str] = None):\n trainer.fit(model)\n\n model_path = model_path if model_path else trainer.checkpoint_callback.last_model_path\n\n trainer.save_checkpoint(model_path, weights_only=True)\n\n _assert_save_equality(trainer, model_path, cls=TestFSDPModel)\n\n # Test entry point\n trainer.test(model) # model is wrapped, will not call configure_shared_model\n\n # provide model path, will create a new unwrapped model and load and then call configure_shared_model to wrap\n trainer.test(ckpt_path=model_path)\n\n\n@RunIf(min_gpus=1, skip_windows=True, standalone=True, fairscale_fully_sharded=True)\ndef test_fsdp_gradient_clipping_raises(tmpdir):\n \"\"\"Test to ensure that an exception is raised when clipping gradients by value with FSDP.\"\"\"\n model = BoringModel()\n trainer = Trainer(\n default_root_dir=tmpdir,\n strategy=\"fsdp\",\n fast_dev_run=True,\n accelerator=\"gpu\",\n devices=1,\n precision=16,\n gradient_clip_val=1,\n gradient_clip_algorithm=\"norm\",\n enable_progress_bar=False,\n enable_model_summary=False,\n )\n with pytest.raises(\n MisconfigurationException, match=\"gradient_clip_algorithm='norm'` is currently not supported for `FullySharded\"\n ):\n trainer.fit(model)\n",
"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport importlib\nimport logging\nimport os\nimport uuid\nfrom functools import wraps\nfrom typing import Any, Dict, Optional, Sequence\n\nimport numpy as np\nimport torch\nfrom torch.optim.lr_scheduler import _LRScheduler\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks import Callback\nfrom pytorch_lightning.core.optimizer import _init_optimizers_and_lr_schedulers, _set_scheduler_opt_idx\nfrom pytorch_lightning.loggers.logger import DummyLogger\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom pytorch_lightning.utilities.parsing import lightning_hasattr, lightning_setattr\nfrom pytorch_lightning.utilities.rank_zero import rank_zero_warn\nfrom pytorch_lightning.utilities.types import LRSchedulerConfig\n\n# check if ipywidgets is installed before importing tqdm.auto\n# to ensure it won't fail and a progress bar is displayed\nif importlib.util.find_spec(\"ipywidgets\") is not None:\n from tqdm.auto import tqdm\nelse:\n from tqdm import tqdm\n\nlog = logging.getLogger(__name__)\n\n\ndef _determine_lr_attr_name(trainer: \"pl.Trainer\", model: \"pl.LightningModule\") -> str:\n if isinstance(trainer.auto_lr_find, str):\n if not lightning_hasattr(model, trainer.auto_lr_find):\n raise MisconfigurationException(\n f\"`auto_lr_find` was set to {trainer.auto_lr_find}, however\"\n \" could not find this as a field in `model` or `model.hparams`.\"\n )\n return trainer.auto_lr_find\n\n attr_options = (\"lr\", \"learning_rate\")\n for attr in attr_options:\n if lightning_hasattr(model, attr):\n return attr\n\n raise MisconfigurationException(\n \"When `auto_lr_find=True`, either `model` or `model.hparams` should\"\n f\" have one of these fields: {attr_options} overridden.\"\n )\n\n\nclass _LRFinder:\n \"\"\"LR finder object. This object stores the results of lr_find().\n\n Args:\n mode: either `linear` or `exponential`, how to increase lr after each step\n\n lr_min: lr to start search from\n\n lr_max: lr to stop search\n\n num_training: number of steps to take between lr_min and lr_max\n\n Example::\n # Run lr finder\n lr_finder = trainer.lr_find(model)\n\n # Results stored in\n lr_finder.results\n\n # Plot using\n lr_finder.plot()\n\n # Get suggestion\n lr = lr_finder.suggestion()\n \"\"\"\n\n def __init__(self, mode: str, lr_min: float, lr_max: float, num_training: int):\n assert mode in (\"linear\", \"exponential\"), \"mode should be either `linear` or `exponential`\"\n\n self.mode = mode\n self.lr_min = lr_min\n self.lr_max = lr_max\n self.num_training = num_training\n\n self.results = {}\n self._total_batch_idx = 0 # for debug purpose\n\n def _exchange_scheduler(self, trainer: \"pl.Trainer\", model: \"pl.LightningModule\"):\n \"\"\"Decorate `trainer.strategy.setup_optimizers` method such that it sets the user's originally specified\n optimizer together with a new scheduler that takes care of the learning rate search.\"\"\"\n setup_optimizers = trainer.strategy.setup_optimizers\n\n @wraps(setup_optimizers)\n def func(trainer):\n # Decide the structure of the output from _init_optimizers_and_lr_schedulers\n optimizers, _, _ = _init_optimizers_and_lr_schedulers(trainer.lightning_module)\n\n if len(optimizers) != 1:\n raise MisconfigurationException(\n f\"`model.configure_optimizers()` returned {len(optimizers)}, but\"\n \" learning rate finder only works with single optimizer\"\n )\n\n optimizer = optimizers[0]\n\n new_lrs = [self.lr_min] * len(optimizer.param_groups)\n for param_group, new_lr in zip(optimizer.param_groups, new_lrs):\n param_group[\"lr\"] = new_lr\n param_group[\"initial_lr\"] = new_lr\n\n args = (optimizer, self.lr_max, self.num_training)\n scheduler = _LinearLR(*args) if self.mode == \"linear\" else _ExponentialLR(*args)\n\n trainer.strategy.optimizers = [optimizer]\n trainer.strategy.lr_scheduler_configs = [LRSchedulerConfig(scheduler, interval=\"step\", opt_idx=0)]\n trainer.strategy.optimizer_frequencies = []\n _set_scheduler_opt_idx(trainer.optimizers, trainer.lr_scheduler_configs)\n\n return func\n\n def plot(self, suggest: bool = False, show: bool = False):\n \"\"\"Plot results from lr_find run\n Args:\n suggest: if True, will mark suggested lr to use with a red point\n\n show: if True, will show figure\n \"\"\"\n import matplotlib.pyplot as plt\n\n lrs = self.results[\"lr\"]\n losses = self.results[\"loss\"]\n\n fig, ax = plt.subplots()\n\n # Plot loss as a function of the learning rate\n ax.plot(lrs, losses)\n if self.mode == \"exponential\":\n ax.set_xscale(\"log\")\n ax.set_xlabel(\"Learning rate\")\n ax.set_ylabel(\"Loss\")\n\n if suggest:\n _ = self.suggestion()\n if self._optimal_idx:\n ax.plot(lrs[self._optimal_idx], losses[self._optimal_idx], markersize=10, marker=\"o\", color=\"red\")\n\n if show:\n plt.show()\n\n return fig\n\n def suggestion(self, skip_begin: int = 10, skip_end: int = 1):\n \"\"\"This will propose a suggestion for choice of initial learning rate as the point with the steepest\n negative gradient.\n\n Returns:\n lr: suggested initial learning rate to use\n skip_begin: how many samples to skip in the beginning. Prevent too naive estimates\n skip_end: how many samples to skip in the end. Prevent too optimistic estimates\n \"\"\"\n try:\n loss = np.array(self.results[\"loss\"][skip_begin:-skip_end])\n loss = loss[np.isfinite(loss)]\n min_grad = np.gradient(loss).argmin()\n self._optimal_idx = min_grad + skip_begin\n return self.results[\"lr\"][self._optimal_idx]\n # todo: specify the possible exception\n except Exception:\n log.exception(\"Failed to compute suggesting for `lr`. There might not be enough points.\")\n self._optimal_idx = None\n\n\ndef lr_find(\n trainer: \"pl.Trainer\",\n model: \"pl.LightningModule\",\n min_lr: float = 1e-8,\n max_lr: float = 1,\n num_training: int = 100,\n mode: str = \"exponential\",\n early_stop_threshold: float = 4.0,\n update_attr: bool = False,\n) -> Optional[_LRFinder]:\n \"\"\"See :meth:`~pytorch_lightning.tuner.tuning.Tuner.lr_find`\"\"\"\n if trainer.fast_dev_run:\n rank_zero_warn(\"Skipping learning rate finder since fast_dev_run is enabled.\")\n return\n\n # Determine lr attr\n if update_attr:\n lr_attr_name = _determine_lr_attr_name(trainer, model)\n\n # Save initial model, that is loaded after learning rate is found\n ckpt_path = os.path.join(trainer.default_root_dir, f\".lr_find_{uuid.uuid4()}.ckpt\")\n trainer.save_checkpoint(ckpt_path)\n params = __lr_finder_dump_params(trainer)\n\n # Set to values that are required by the algorithm\n __lr_finder_reset_params(trainer, num_training, early_stop_threshold)\n\n # Initialize lr finder object (stores results)\n lr_finder = _LRFinder(mode, min_lr, max_lr, num_training)\n\n # Disable standard progress bar for fit\n if trainer.progress_bar_callback:\n trainer.progress_bar_callback.disable()\n\n # Configure optimizer and scheduler\n trainer.strategy.setup_optimizers = lr_finder._exchange_scheduler(trainer, model)\n\n # Fit, lr & loss logged in callback\n trainer.tuner._run(model)\n\n # Prompt if we stopped early\n if trainer.global_step != num_training:\n log.info(f\"LR finder stopped early after {trainer.global_step} steps due to diverging loss.\")\n\n # Transfer results from callback to lr finder object\n lr_finder.results.update({\"lr\": trainer.callbacks[0].lrs, \"loss\": trainer.callbacks[0].losses})\n lr_finder._total_batch_idx = trainer.fit_loop.total_batch_idx # for debug purpose\n\n # Restore initial state of model\n trainer._checkpoint_connector.restore(ckpt_path)\n trainer.strategy.remove_checkpoint(ckpt_path)\n __lr_finder_restore_params(trainer, params)\n\n if trainer.progress_bar_callback:\n trainer.progress_bar_callback.enable()\n\n # Update lr attr if required\n if update_attr:\n lr = lr_finder.suggestion()\n\n # TODO: log lr.results to self.logger\n lightning_setattr(model, lr_attr_name, lr)\n log.info(f\"Learning rate set to {lr}\")\n\n return lr_finder\n\n\ndef __lr_finder_dump_params(trainer: \"pl.Trainer\") -> Dict[str, Any]:\n return {\n \"auto_lr_find\": trainer.auto_lr_find,\n \"callbacks\": trainer.callbacks,\n \"logger\": trainer.logger,\n \"max_steps\": trainer.fit_loop.max_steps,\n }\n\n\ndef __lr_finder_reset_params(trainer: \"pl.Trainer\", num_training: int, early_stop_threshold: float) -> None:\n # avoid lr find being called multiple times\n trainer.auto_lr_find = False\n # Use special lr logger callback\n trainer.callbacks = [_LRCallback(num_training, early_stop_threshold, progress_bar_refresh_rate=1)]\n # No logging\n trainer.loggers = [DummyLogger()] if trainer.loggers else []\n # Max step set to number of iterations\n trainer.fit_loop.max_steps = num_training\n\n\ndef __lr_finder_restore_params(trainer: \"pl.Trainer\", params: Dict[str, Any]) -> None:\n trainer.auto_lr_find = params[\"auto_lr_find\"]\n trainer.callbacks = params[\"callbacks\"]\n trainer.logger = params[\"logger\"]\n trainer.fit_loop.max_steps = params[\"max_steps\"]\n\n\nclass _LRCallback(Callback):\n \"\"\"Special callback used by the learning rate finder. This callbacks log the learning rate before each batch\n and log the corresponding loss after each batch.\n\n Args:\n num_training: number of iterations done by the learning rate finder\n early_stop_threshold: threshold for stopping the search. If the\n loss at any point is larger than ``early_stop_threshold*best_loss``\n then the search is stopped. To disable, set to ``None``.\n progress_bar_refresh_rate: rate to refresh the progress bar for\n the learning rate finder\n beta: smoothing value, the loss being logged is a running average of\n loss values logged until now. ``beta`` controls the forget rate i.e.\n if ``beta=0`` all past information is ignored.\n \"\"\"\n\n def __init__(\n self,\n num_training: int,\n early_stop_threshold: float = 4.0,\n progress_bar_refresh_rate: int = 0,\n beta: float = 0.98,\n ):\n self.num_training = num_training\n self.early_stop_threshold = early_stop_threshold\n self.beta = beta\n self.losses = []\n self.lrs = []\n self.avg_loss = 0.0\n self.best_loss = 0.0\n self.progress_bar_refresh_rate = progress_bar_refresh_rate\n self.progress_bar = None\n\n def on_train_batch_start(self, trainer, pl_module, batch, batch_idx):\n \"\"\"Called before each training batch, logs the lr that will be used.\"\"\"\n if (trainer.fit_loop.batch_idx + 1) % trainer.accumulate_grad_batches != 0:\n return\n\n if self.progress_bar_refresh_rate and self.progress_bar is None:\n self.progress_bar = tqdm(desc=\"Finding best initial lr\", total=self.num_training)\n\n self.lrs.append(trainer.lr_scheduler_configs[0].scheduler.lr[0])\n\n def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):\n \"\"\"Called when the training batch ends, logs the calculated loss.\"\"\"\n if (trainer.fit_loop.batch_idx + 1) % trainer.accumulate_grad_batches != 0:\n return\n\n if self.progress_bar:\n self.progress_bar.update()\n\n current_loss = trainer.fit_loop.running_loss.last().item()\n current_step = trainer.global_step\n\n # Avg loss (loss with momentum) + smoothing\n self.avg_loss = self.beta * self.avg_loss + (1 - self.beta) * current_loss\n smoothed_loss = self.avg_loss / (1 - self.beta ** (current_step + 1))\n\n # Check if we diverging\n if self.early_stop_threshold is not None:\n if current_step > 1 and smoothed_loss > self.early_stop_threshold * self.best_loss:\n trainer.fit_loop.max_steps = current_step # stop signal\n if self.progress_bar:\n self.progress_bar.close()\n\n # Save best loss for diverging checking\n if smoothed_loss < self.best_loss or current_step == 1:\n self.best_loss = smoothed_loss\n\n self.losses.append(smoothed_loss)\n\n\nclass _LinearLR(_LRScheduler):\n \"\"\"Linearly increases the learning rate between two boundaries over a number of iterations.\n\n Args:\n\n optimizer: wrapped optimizer.\n\n end_lr: the final learning rate.\n\n num_iter: the number of iterations over which the test occurs.\n\n last_epoch: the index of last epoch. Default: -1.\n \"\"\"\n\n last_epoch: int\n base_lrs: Sequence\n\n def __init__(self, optimizer: torch.optim.Optimizer, end_lr: float, num_iter: int, last_epoch: int = -1):\n self.end_lr = end_lr\n self.num_iter = num_iter\n super().__init__(optimizer, last_epoch)\n\n def get_lr(self):\n curr_iter = self.last_epoch + 1\n r = curr_iter / self.num_iter\n\n if self.last_epoch > 0:\n val = [base_lr + r * (self.end_lr - base_lr) for base_lr in self.base_lrs]\n else:\n val = [base_lr for base_lr in self.base_lrs]\n self._lr = val\n return val\n\n @property\n def lr(self):\n return self._lr\n\n\nclass _ExponentialLR(_LRScheduler):\n \"\"\"Exponentially increases the learning rate between two boundaries over a number of iterations.\n\n Arguments:\n\n optimizer: wrapped optimizer.\n\n end_lr: the final learning rate.\n\n num_iter: the number of iterations over which the test occurs.\n\n last_epoch: the index of last epoch. Default: -1.\n \"\"\"\n\n last_epoch: int\n base_lrs: Sequence\n\n def __init__(self, optimizer: torch.optim.Optimizer, end_lr: float, num_iter: int, last_epoch: int = -1):\n self.end_lr = end_lr\n self.num_iter = num_iter\n super().__init__(optimizer, last_epoch)\n\n def get_lr(self):\n curr_iter = self.last_epoch + 1\n r = curr_iter / self.num_iter\n\n if self.last_epoch > 0:\n val = [base_lr * (self.end_lr / base_lr) ** r for base_lr in self.base_lrs]\n else:\n val = [base_lr for base_lr in self.base_lrs]\n self._lr = val\n return val\n\n @property\n def lr(self):\n return self._lr\n",
"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport time\nfrom typing import Type\n\nimport pytest\nimport torch\n\nfrom pytorch_lightning import seed_everything, Trainer\nfrom pytorch_lightning.strategies import DDPSpawnShardedStrategy\nfrom tests.helpers.boring_model import BoringModel, RandomDataset\nfrom tests.helpers.runif import RunIf\n\n\nclass SeedTrainLoaderModel(BoringModel):\n \"\"\"Overrides training loader to ensure we enforce the same seed for all DDP processes.\"\"\"\n\n def train_dataloader(self):\n seed_everything(42)\n return torch.utils.data.DataLoader(RandomDataset(32, 64))\n\n\nclass SeedTrainLoaderManualModel(SeedTrainLoaderModel):\n def training_step(self, batch, batch_idx, optimizer_idx):\n # manual\n # access your optimizers with use_pl_optimizer=False. Default is True\n (opt_a, opt_b) = self.optimizers(use_pl_optimizer=True)\n loss_1 = self.step(batch)\n\n self.manual_backward(loss_1)\n opt_a.step()\n\n # fake discriminator\n loss_2 = self.step(batch[0])\n\n # ensure we forward the correct params to the optimizer\n # without retain_graph we can't do multiple backward passes\n self.manual_backward(loss_2)\n # todo: understand why synchronization breaks there.\n # self.manual_backward(loss_2, retain_graph=True)\n opt_b.step()\n\n assert self.layer.weight.grad is None or torch.all(self.layer.weight.grad == 0)\n\n def training_epoch_end(self, outputs) -> None:\n # outputs should be an array with an entry per optimizer\n assert len(outputs) == 2\n\n def configure_optimizers(self):\n optimizer = torch.optim.SGD(self.layer.parameters(), lr=0.1)\n optimizer_2 = torch.optim.SGD(self.layer.parameters(), lr=0.1)\n return optimizer, optimizer_2\n\n @property\n def automatic_optimization(self) -> bool:\n return False\n\n\nclass SeedTrainLoaderMultipleOptimizersModel(SeedTrainLoaderModel):\n def training_step(self, batch, batch_idx, optimizer_idx):\n output = self.layer(batch)\n loss = self.loss(batch, output)\n return {\"loss\": loss}\n\n def training_epoch_end(self, outputs) -> None:\n # outputs should be an array with an entry per optimizer\n assert len(outputs) == 2\n\n def configure_optimizers(self):\n optimizer = torch.optim.SGD(self.layer.parameters(), lr=0.1)\n optimizer_2 = torch.optim.SGD(self.layer.parameters(), lr=0.1)\n return optimizer, optimizer_2\n\n\ndef record_ddp_fit_model_stats(trainer, model, use_cuda):\n \"\"\"Helper to calculate wall clock time for fit + max allocated memory.\n\n Args:\n trainer: The trainer object.\n model: The model to fit.\n use_cuda: Whether to sync CUDA kernels.\n\n Returns:\n Max Memory if using GPUs, and total wall clock time.\n \"\"\"\n max_memory = None\n\n time_start = time.perf_counter()\n if use_cuda:\n torch.cuda.reset_peak_memory_stats()\n torch.cuda.synchronize()\n\n trainer.fit(model)\n\n if use_cuda:\n torch.cuda.synchronize()\n max_memory = torch.cuda.max_memory_allocated() / 2**20\n\n total_time = time.perf_counter() - time_start\n\n return max_memory, total_time\n\n\ndef plugin_parity_test(\n model_cls: Type[SeedTrainLoaderModel],\n seed: int = 42,\n gpus: int = 0,\n precision: int = 32,\n max_percent_speed_diff: float = 0.1,\n):\n \"\"\"Ensures that the trained model is identical to the standard DDP implementation. Also checks for speed/memory\n regressions, we should expect always less memory but performance to fluctuate.\n\n Args:\n model_cls: Model class to use for test.\n seed: Seed for generators. Note that this does not handle the seed for data-loading on multi-process.\n gpus: Number of GPUS to enable.\n precision: Whether to use AMP or normal FP32 training.\n max_percent_speed_diff: The maximum speed difference compared to normal DDP training.\n This is more a safety net for variability in CI which can vary in speed, not for benchmarking.\n \"\"\"\n\n # Train normal DDP\n seed_everything(seed)\n ddp_model = model_cls()\n use_cuda = gpus > 0\n\n trainer = Trainer(\n fast_dev_run=True, max_epochs=1, accelerator=\"gpu\", devices=gpus, precision=precision, strategy=\"ddp_spawn\"\n )\n\n max_memory_ddp, ddp_time = record_ddp_fit_model_stats(trainer=trainer, model=ddp_model, use_cuda=use_cuda)\n\n # Reset and train Custom DDP\n seed_everything(seed)\n custom_plugin_model = model_cls()\n\n trainer = Trainer(\n fast_dev_run=True,\n max_epochs=1,\n accelerator=\"gpu\",\n devices=gpus,\n precision=precision,\n strategy=\"ddp_sharded_spawn\",\n )\n assert isinstance(trainer.strategy, DDPSpawnShardedStrategy)\n\n max_memory_custom, custom_model_time = record_ddp_fit_model_stats(\n trainer=trainer, model=custom_plugin_model, use_cuda=use_cuda\n )\n\n # Assert model parameters are identical after fit\n for ddp_param, custom_param in zip(ddp_model.parameters(), custom_plugin_model.parameters()):\n assert torch.equal(ddp_param, custom_param), \"Model parameters are different between DDP and Custom plugin\"\n\n # Assert speed parity by ensuring percentage difference between custom/ddp is below threshold\n percent_diff = (custom_model_time - ddp_time) / custom_model_time\n\n assert (\n percent_diff <= max_percent_speed_diff\n ), f\"Custom DDP was too slow compared to regular DDP, Custom Plugin Time: {custom_model_time}, DDP Time: {ddp_time}\"\n\n if use_cuda:\n # Assert CUDA memory parity\n assert max_memory_custom <= max_memory_ddp, (\n \"Custom plugin used too much memory compared to DDP, \"\n f\"Custom Mem: {max_memory_custom}, DDP Mem: {max_memory_ddp}\"\n )\n\n\n@RunIf(skip_windows=True, fairscale=True)\[email protected](\n \"kwargs\",\n [\n pytest.param(dict(gpus=1, model_cls=SeedTrainLoaderModel), marks=RunIf(min_gpus=1)),\n pytest.param(\n dict(gpus=1, precision=16, model_cls=SeedTrainLoaderModel), marks=RunIf(min_gpus=1, amp_native=True)\n ),\n pytest.param(dict(gpus=2, model_cls=SeedTrainLoaderModel), marks=RunIf(min_gpus=2)),\n pytest.param(\n dict(gpus=2, precision=16, model_cls=SeedTrainLoaderModel), marks=RunIf(min_gpus=2, amp_native=True)\n ),\n pytest.param(\n dict(gpus=2, model_cls=SeedTrainLoaderMultipleOptimizersModel),\n marks=[\n RunIf(min_gpus=2),\n pytest.mark.skip(reason=\"TODO: Current issue with multiple optimizers and FairScale.\"),\n ],\n ),\n pytest.param(\n dict(gpus=2, model_cls=SeedTrainLoaderManualModel),\n marks=[\n RunIf(min_gpus=2),\n pytest.mark.skip(reason=\"TODO: Current issue with multiple optimizers and FairScale.\"),\n ],\n ),\n ],\n)\ndef test_ddp_spawn_sharded_strategy(kwargs):\n if kwargs[\"gpus\"] > 1:\n # TODO: decrease speed diff since only 2 GPUs sharding 2 optimizers\n kwargs[\"max_percent_speed_diff\"] = 0.25\n plugin_parity_test(**kwargs)\n",
"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom abc import ABC, abstractmethod\nfrom collections.abc import Iterable, Iterator\nfrom copy import deepcopy\nfrom typing import Any, Callable, List, Optional, Sized, Tuple\n\nimport torch\nfrom torch.utils.data.dataloader import DataLoader\n\nfrom pytorch_lightning.trainer.supporters import CombinedLoader, CycleIterator\nfrom pytorch_lightning.utilities.apply_func import apply_to_collection, apply_to_collections\nfrom pytorch_lightning.utilities.auto_restart import (\n _add_capture_metadata_collate,\n _patch_dataloader_get_iterators,\n _teardown_dataloader_get_iterators,\n IteratorState,\n MergedIteratorState,\n patch_dataloader_iterator,\n)\nfrom pytorch_lightning.utilities.data import has_len\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom pytorch_lightning.utilities.imports import _fault_tolerant_training\n\n\ndef _profile_nothing() -> None:\n pass\n\n\nclass AbstractDataFetcher(ABC):\n\n \"\"\"This base class should be used to implement a fault tolerant ``DataFetcher``. It is required to override the\n ``fetching_function`` with fetching logic.\n\n Example::\n\n class SimpleDataFetcher(AbstractDataFetcher):\n def fetching_function(self):\n while True:\n try:\n return next(self.dataloader_iter), False\n except StopIteration:\n return None, True\n \"\"\"\n\n @abstractmethod\n def fetching_function(self) -> Any:\n \"\"\"Override with your own fetching logic.\"\"\"\n\n @abstractmethod\n def prefetching(self) -> None:\n \"\"\"Override with your own pre-fetching logic.\"\"\"\n\n def on_fetch_start(self) -> Any:\n \"\"\"Hook to override to handle the logic before fetching a batch.\"\"\"\n\n def on_fetch_end(self, batch: Any, start_output: Any) -> None:\n \"\"\"Hook to extend which handles the logic after fetching a batch.\"\"\"\n\n def wait(self) -> None:\n \"\"\"Hook to override to indicate the `DataFetcher` to wait for an event.\"\"\"\n\n def __init__(self, prefetch_batches: int = 0) -> None:\n if prefetch_batches < 0:\n raise MisconfigurationException(\"`prefetch_batches` should at least be 0.\")\n self.prefetch_batches = prefetch_batches\n self._dataloader: Optional[Iterable] = None\n self.dataloader_iter: Optional[Iterator] = None\n self.fetched: int = 0\n self.done: bool = False\n self._start_profiler = _profile_nothing\n self._stop_profiler = _profile_nothing\n\n def setup(self, dataloader: Iterable, **kwargs: Any) -> None:\n self._add_capture_metadata_collate(dataloader)\n self._dataloader = dataloader\n _patch_dataloader_get_iterators()\n self._attach_data_fetcher()\n\n @property\n def dataloader(self) -> Iterable:\n if self._dataloader is None:\n raise MisconfigurationException(\n f\"`{self.__class__.__name__}` should have been `setup` with a dataloader iterable.\"\n )\n return self._dataloader\n\n @staticmethod\n def _add_capture_metadata_collate(dataloader: Iterable) -> None:\n if not isinstance(dataloader, (DataLoader, CombinedLoader)):\n return\n\n if isinstance(dataloader, CombinedLoader):\n dataloader = dataloader.loaders\n\n apply_to_collection(dataloader, DataLoader, _add_capture_metadata_collate)\n\n def _apply_patch(self) -> None:\n def _apply_patch_fn(loader: DataLoader, iterator: Iterator) -> None:\n if isinstance(loader, CycleIterator):\n loader = loader.loader\n # cycle_iterator = iterator\n iterator = iterator._loader_iter\n\n if isinstance(loader, DataLoader) and _fault_tolerant_training():\n loader._lightning_fetcher = self\n patch_dataloader_iterator(loader, iterator, self)\n\n apply_to_collections(self.loaders, self.loader_iters, (Iterator, DataLoader), _apply_patch_fn)\n\n def _store_dataloader_iter_state(\n self, dataloader_iter: Iterator, dataloader_iter_states: List[IteratorState]\n ) -> None:\n if getattr(dataloader_iter, \"cache_states\", None) is None:\n dataloader_iter.cache_states = {}\n\n if getattr(dataloader_iter, \"state\", None) is None:\n dataloader_iter.state = MergedIteratorState()\n\n for iter_state in dataloader_iter_states:\n iter_name = iter_state.name\n if iter_name not in dataloader_iter.cache_states:\n dataloader_iter.cache_states[iter_name] = []\n dataloader_iter.cache_states[iter_name].append(iter_state)\n\n if self.fetched >= self.prefetch_batches:\n for iter_state in dataloader_iter_states:\n if len(dataloader_iter.state):\n dataloader_iter.previous_state = deepcopy(dataloader_iter.state)\n iter_name = iter_state.name\n state = dataloader_iter.cache_states[iter_name].pop(0)\n dataloader_iter.state.update(iter_name, state)\n\n @property\n def loaders(self) -> List[DataLoader]:\n if isinstance(self.dataloader, CombinedLoader):\n loaders = self.dataloader.loaders\n else:\n loaders = [self.dataloader]\n return loaders\n\n @property\n def loader_iters(self) -> List[Iterator]:\n if self.dataloader_iter is None:\n raise MisconfigurationException(\"The `dataloader_iter` isn't available outside the __iter__ context.\")\n\n if isinstance(self.dataloader, CombinedLoader):\n loader_iters = self.dataloader_iter.loader_iters\n else:\n loader_iters = [self.dataloader_iter]\n return loader_iters\n\n @property\n def state(self) -> List[MergedIteratorState]:\n def collect_state(iterator: Iterator) -> MergedIteratorState:\n return iterator.state\n\n return apply_to_collection(self.loader_iters, Iterator, collect_state)\n\n def _attach_data_fetcher(self) -> None:\n def _attach_data_fetcher_fn(loader: DataLoader) -> None:\n if isinstance(loader, CycleIterator):\n loader = loader.loader\n\n if isinstance(loader, DataLoader) and _fault_tolerant_training():\n loader._lightning_fetcher = self\n\n apply_to_collection(self.loaders, (DataLoader, CycleIterator), _attach_data_fetcher_fn)\n\n def __iter__(self) -> \"AbstractDataFetcher\":\n self.reset()\n self.dataloader_iter = iter(self.dataloader)\n self._apply_patch()\n self.prefetching()\n return self\n\n def __next__(self) -> Any:\n return self.fetching_function()\n\n def reset(self) -> None:\n self.fetched = 0\n self.done = False\n\n def teardown(self) -> None:\n self.reset()\n if isinstance(self._dataloader, CombinedLoader):\n self._dataloader.reset()\n if isinstance(self._dataloader, DataLoader):\n CombinedLoader._shutdown_workers_and_reset_iterator(self._dataloader)\n self.dataloader_iter = None\n _teardown_dataloader_get_iterators()\n\n\ndef _no_op_batch_to_device(batch: Any) -> Any:\n return batch\n\n\nclass DataFetcher(AbstractDataFetcher):\n \"\"\"This class is used to control batch fetching flow.\n\n Args:\n prefetch_batches: Number of batches to pre-fetch. Pre-fetching at least 1 batch is necessary to properly track\n whether a batch is the last one (available with :attr:`self.done`) under any training setup.\n store_on_device: Whether to store the pre-fetched batches on device.\n \"\"\"\n\n def __init__(self, prefetch_batches: int = 1, store_on_device: bool = True) -> None:\n super().__init__(prefetch_batches=prefetch_batches)\n self.store_on_device = store_on_device\n self.batch_to_device: Callable[[Any], Any] = _no_op_batch_to_device\n self.batches: List[Any] = []\n self._has_len = False\n\n def setup( # type: ignore[override]\n self, dataloader: Iterable, batch_to_device: Optional[Callable[[Any], Any]] = None\n ) -> None:\n super().setup(dataloader)\n self._has_len = has_len(dataloader)\n if batch_to_device is not None:\n self.batch_to_device = batch_to_device\n\n def on_fetch_start(self) -> Any:\n self._start_profiler()\n\n def on_fetch_end(self, batch: Any, start_output: Any) -> None:\n \"\"\"Hook to extend which handles the logic after fetching a batch.\"\"\"\n self._stop_profiler()\n self.batches.append(batch)\n\n def prefetching(self) -> None:\n iterator = self.dataloader_iter\n assert iterator is not None\n for _ in range(self.prefetch_batches):\n try:\n self._fetch_next_batch(iterator)\n except StopIteration:\n # this would only happen when prefetch_batches > the number of batches available and makes\n # `fetching_function` jump directly to the empty iterator case without trying to fetch again\n self.done = True\n break\n\n def fetching_function(self) -> Any:\n assert self.dataloader_iter is not None\n if self.batches:\n # there are pre-fetched batches already from a previous `prefetching` call.\n # consume one\n batch = self.batches.pop(0)\n try:\n # refill the consumed batch\n self._fetch_next_batch(self.dataloader_iter)\n except StopIteration:\n # no more batches to fetch. we are done only if all pre-fetched batches were returned\n self.done = not self.batches\n elif not self.done:\n # this will run only when no pre-fetching was done.\n try:\n self._fetch_next_batch(self.dataloader_iter)\n # consume the batch we just fetched\n batch = self.batches.pop(0)\n except StopIteration as e:\n self.done = True\n raise e\n else:\n # the iterator is empty\n raise StopIteration\n self.wait()\n return self.move_to_device(batch)\n\n def _fetch_next_batch(self, iterator: Iterator) -> None:\n start_output = self.on_fetch_start()\n batch = next(iterator)\n self.fetched += 1\n if not self.prefetch_batches and self._has_len:\n # when we don't prefetch but the dataloader is sized, we use the length for `done`\n dataloader = self.dataloader\n assert isinstance(dataloader, Sized) # `_has_len` is True\n self.done = self.fetched >= len(dataloader)\n self.on_fetch_end(batch, start_output)\n\n def move_to_device(self, batch: Any) -> Any:\n if self.store_on_device:\n batch = self.batch_to_device(batch)\n return batch\n\n def reset(self) -> None:\n super().reset()\n self.batches = []\n\n\nclass InterBatchParallelDataFetcher(DataFetcher):\n\n \"\"\"This class implements inter-batch parallelism, which aims at hiding the latency of host-to-device copy of\n input batches behind computationally intensive operations.\n\n code-block::\n\n Without parallelization:\n\n batch 0: [HtoD][forward][backward]\n batch 1: [HtoD][forward][backward]\n batch 2: [HtoD][forward][backward]\n\n With parallelization, the latency of HtoD copy can be hidden:\n\n batch 0: [HtoD][forward][backward]\n batch 1: [HtoD] [forward][backward]\n batch 2: [HtoD] [forward][backward]\n \"\"\"\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n self.cuda_stream = torch.cuda.Stream()\n self.events: List[torch.cuda.Event] = []\n\n def move_to_device(self, batch: Any) -> Any:\n with torch.cuda.stream(self.cuda_stream):\n return super().move_to_device(batch)\n\n def on_fetch_start(self) -> \"torch.cuda.Event\":\n # create a cuda event used to record the async stream of data to device.\n event = torch.cuda.Event()\n self._start_profiler()\n return event\n\n def on_fetch_end(self, batch: Any, event: torch.cuda.Event) -> None:\n self._stop_profiler()\n self.batches.append(batch)\n event.record()\n self.events.append(event)\n\n def wait(self) -> None:\n # pop first event from the queue and wait for the batch to be available on device.\n event = self.events.pop(0)\n event.wait()\n\n\nclass StepFuncDataLoaderIter(Iterator):\n\n \"\"\"This class is a wrapper to keep track of dataloader iterator fetching event while left entirely to user\n control.\"\"\"\n\n def __init__(self, iterator: Iterator, data_fetcher: AbstractDataFetcher) -> None:\n self.iterator = iterator\n self.data_fetcher = data_fetcher\n\n def __next__(self) -> Any:\n try:\n self.data_fetcher._start_profiler()\n data = next(self.iterator)\n self.data_fetcher._stop_profiler()\n self.data_fetcher.fetched += 1\n return data\n except StopIteration as e:\n self.data_fetcher.done = True\n raise e\n\n\nclass DataLoaderIterDataFetcher(AbstractDataFetcher):\n\n \"\"\"This class is used to return directly the `dataloader_iter` to the ``LightningModule`` training_step for\n users to implement their own pre-fetching logic. This feature can be activated as follows:\n\n Example::\n\n Class MyModel(LightningModule):\n\n def __init__(self):\n self.automatic_optimization = False\n\n def training_step(self, dataloader_iter: Iterator, batch_idx: int) -> None:\n # it is the user responsibility to fetch and move the batch to the right device.\n batch = next(dataloader_iter)\n batch = batch.to(self.device)\n ...\n \"\"\"\n\n def __init__(self, prefetch_batches: int = 0) -> None:\n # prefetch batches is not used for this class\n super().__init__()\n self.store_on_device = False\n\n def prefetching(self) -> None:\n iterator = self.dataloader_iter\n assert iterator is not None\n self.iterator = iter(StepFuncDataLoaderIter(iterator, self))\n\n def fetching_function(self) -> Tuple[int, Iterator]:\n if not self.done:\n return self.fetched, self.iterator\n raise StopIteration\n"
] | [
[
"torch.nn.Linear",
"torch.nn.ReLU"
],
[
"numpy.isfinite",
"numpy.gradient",
"matplotlib.pyplot.subplots",
"numpy.array",
"matplotlib.pyplot.show"
],
[
"torch.all",
"torch.cuda.synchronize",
"torch.equal",
"torch.cuda.max_memory_allocated",
"torch.cuda.reset_peak_memory_stats"
],
[
"torch.cuda.Event",
"torch.cuda.Stream",
"torch.cuda.stream"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
christopherlovell/hyperion | [
"f65c253abf0bdf174a9302666bc2fec57f7ae7da",
"f65c253abf0bdf174a9302666bc2fec57f7ae7da"
] | [
"hyperion/dust/tests/test_mean_opacities.py",
"hyperion/util/nans.py"
] | [
"from __future__ import print_function, division\n\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport pytest\n\nfrom ..optical_properties import OpticalProperties\nfrom ..mean_opacities import MeanOpacities\nfrom ...util.functions import virtual_file, B_nu\nfrom ...util.constants import sigma, c\n\n\nclass TestMeanOpacities(object):\n\n def setup_class(self):\n self.o = OpticalProperties()\n self.o.nu = np.array([1.e8, 1.e16])\n self.o.chi = np.array([1.e-2, 1])\n self.o.albedo = np.array([0., 0.5])\n\n def test_init(self):\n MeanOpacities()\n\n def test_compute(self):\n\n m = MeanOpacities()\n m.compute(self.o, n_temp=10, temp_min=1., temp_max=1000.)\n\n assert_allclose(m.temperature[0], 1.)\n assert_allclose(m.temperature[-1], 1000.)\n\n assert_allclose(m.specific_energy,\n 4. * sigma * m.temperature ** 4. * m.kappa_planck)\n\n def test_io(self):\n\n m = MeanOpacities()\n m.compute(self.o, n_temp=10, temp_min=1., temp_max=1000.)\n\n f = virtual_file()\n m.to_hdf5_group(f)\n m_new = MeanOpacities()\n m_new.from_hdf5_group(f)\n\n assert_allclose(m.temperature, m_new.temperature)\n assert_allclose(m.specific_energy, m_new.specific_energy)\n assert_allclose(m.chi_planck, m_new.chi_planck)\n assert_allclose(m.kappa_planck, m_new.kappa_planck)\n assert_allclose(m.chi_inv_planck, m_new.chi_inv_planck)\n assert_allclose(m.kappa_inv_planck, m_new.kappa_inv_planck)\n assert_allclose(m.chi_rosseland, m_new.chi_rosseland)\n assert_allclose(m.kappa_rosseland, m_new.kappa_rosseland)\n assert m.hash() == m_new.hash()\n\n def test_plot(self):\n\n # Just check that plot runs without crashing\n\n fig = plt.figure()\n\n m = MeanOpacities()\n m.compute(self.o, n_temp=10, temp_min=1., temp_max=1000.)\n m.plot(fig, 111)\n\n plt.close(fig)\n\n\ndef test_zero_emissivities():\n\n wav = np.array([2.0, 0.5])\n nu = c / (wav * 1.e-4)\n\n o = OpticalProperties()\n o.nu = nu\n o.chi = np.array([1.e-2, 1])\n o.albedo = np.array([0., 0.5])\n\n m = MeanOpacities()\n m.compute(o)\n",
"import warnings\n\nimport h5py\nimport numpy as np\n\n\nclass NaNWarning(UserWarning):\n pass\n\n\ndef number_nan(array):\n if (np.isscalar(array) and np.isreal(array)) or array.dtype.kind in ['i', 'f']:\n return np.sum(np.isnan(array))\n else:\n return 0\n\n\ndef check_for_nans(handle):\n \"\"\"\n Check for NaNs anywhere in an HDF5 group\n \"\"\"\n\n # List datasets and groups\n datasets = []\n groups = []\n\n def func(name, obj):\n if isinstance(obj, h5py.Dataset):\n datasets.append(name)\n elif isinstance(obj, h5py.Group):\n groups.append(name)\n handle.visititems(func)\n\n # Visit order is not guaranteed, so sort\n datasets.sort()\n groups.sort()\n\n # Loop over datasets to check for NaN values\n for d in datasets:\n array = np.array(handle[d])\n if array.dtype.kind == 'V': # structured array\n for col in array.dtype.fields:\n n_nan = number_nan(array[col])\n if n_nan > 0:\n warnings.warn(\"{0} NaN value(s) encountered in field {1} of dataset '{2}'\".format(n_nan, col, d), NaNWarning)\n else:\n n_nan = number_nan(array)\n if n_nan > 0:\n warnings.warn(\"{0} NaN value(s) encountered in dataset '{1}'\".format(n_nan, d), NaNWarning)\n\n # Loop over all groups and datasets to check attributes\n for item in ['/'] + datasets + groups:\n\n # Find all attributes\n attributes = list(handle[item].attrs.keys())\n attributes.sort()\n\n for a in attributes:\n n_nan = number_nan(handle[item].attrs[a])\n if n_nan > 0:\n warnings.warn(\"{0} NaN value(s) encountered in attribute '{1}' of object '{2}'\".format(n_nan, a, item), NaNWarning)\n"
] | [
[
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.close",
"numpy.testing.assert_allclose"
],
[
"numpy.isnan",
"numpy.array",
"numpy.isreal",
"numpy.isscalar"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ThomasRot/rational_activations | [
"1fa26d1ee5f3c916eda00c899afa96eccb960143"
] | [
"rational/utils/histograms_numpy.py"
] | [
"import numpy as np\n\n\nclass Histogram():\n \"\"\"\n Input Histograms, used to retrieve the input of Rational Activations\n \"\"\"\n def __init__(self, bin_size=0.001, random_select=False):\n self.bins = np.array([])\n self.weights = np.array([], dtype=np.uint32)\n self.bin_size = bin_size\n self._empty = True\n self._rd = int(np.log10(1./bin_size).item())\n self._verbose = False\n\n def fill_n(self, input):\n self._update_hist(input.detach().numpy())\n\n def _update_hist(self, new_input):\n range_ext = np.around(new_input.min() - self.bin_size / 2, 1), \\\n np.around(new_input.max() + self.bin_size / 2, 1)\n bins_array = np.arange(range_ext[0], range_ext[1] + self.bin_size,\n self.bin_size)\n weights, bins = np.histogram(new_input, bins_array)\n if self._empty:\n self.weights, self.bins = weights, bins[:-1]\n self._empty = False\n else: # update the hist\n self.weights, self.bins = concat_hists(self.weights, self.bins,\n weights, bins[:-1],\n self.bin_size, self._rd)\n\n @property\n def is_empty(self):\n return self._empty\n\n def __repr__(self):\n if self._empty:\n rtrn = \"Empty Histogram\"\n else:\n rtrn = f\"Histogram on range {self.bins[0]}, {self.bins[-1]}, of \" + \\\n f\"bin_size {self.bin_size}, with {self.weights.sum()} total\" + \\\n f\"elements\"\n if self._verbose:\n rtrn += f\" {hex(id(self))}\"\n return rtrn\n\n @property\n def total(self):\n return self.weights.sum()\n\n def normalize(self, numpy=True, nb_output=100):\n \"\"\"\n\n \"\"\"\n if nb_output is not None and nb_output < len(self.bins):\n div = len(self.bins) // nb_output\n if len(self.bins) % div == 0:\n weights = np.nanmean(self.weights.reshape(-1, div), axis=1)\n last = self.bins[-1]\n else:\n import ipdb; ipdb.set_trace()\n to_add = div - self.weights.size % div\n padded = np.pad(self.weights, (0, to_add), mode='constant',\n constant_values=np.NaN).reshape(-1, div)\n weights = np.nanmean(padded, axis=1)\n last = self.bins[-1] + self.bin_size * to_add\n bins = np.linspace(self.bins[0], last, len(weights),\n endpoint=False)\n return weights / weights.sum(), bins\n else:\n return self.weights / self.weights.sum(), self.bins\n\n def _from_physt(self, phystogram):\n if (phystogram.bin_sizes == phystogram.bin_sizes[0]).all():\n self.bin_size = phystogram.bin_sizes[0]\n self.bins = np.array(phystogram.bin_left_edges)\n self.weights = np.array(phystogram.frequencies)\n return self\n\n\ndef concat_hists(weights1, bins1, weights2, bins2, bin_size, rd):\n min1, max1 = np.around(bins1[0], rd), np.around(bins1[-1], rd)\n min2, max2 = np.around(bins2[0], rd), np.around(bins2[-1], rd)\n mini, maxi = min(min1, min2), max(max1, max2)\n new_bins = np.arange(mini, maxi + bin_size*0.9, bin_size) # * 0.9 to avoid unexpected random inclusion of last element\n if min1 - mini != 0 and maxi - max1 != 0:\n ext1 = np.pad(weights1, (np.int(np.around((min1 - mini) / bin_size)),\n np.int(np.around((maxi - max1) / bin_size))),\n 'constant', constant_values=0)\n elif min1 - mini != 0:\n ext1 = np.pad(weights1, (np.int(np.around((min1 - mini) / bin_size)),\n 0), 'constant', constant_values=0)\n elif maxi - max1 != 0:\n ext1 = np.pad(weights1, (0,\n np.int(np.around((maxi - max1) / bin_size))),\n 'constant', constant_values=0)\n else:\n ext1 = weights1\n if min2 - mini != 0 and maxi - max2 != 0:\n ext2 = np.pad(weights2, (np.int(np.around((min2 - mini) / bin_size)),\n np.int(np.around((maxi - max2) / bin_size))),\n 'constant', constant_values=0)\n elif min2 - mini != 0:\n ext2 = np.pad(weights2, (np.int(np.around((min2 - mini) / bin_size)),\n 0), 'constant', constant_values=0)\n elif maxi - max2 != 0:\n ext2 = np.pad(weights2, (0,\n np.int(np.around((maxi - max2) / bin_size))),\n 'constant', constant_values=0)\n else:\n ext2 = weights2\n new_ext = ext1 + ext2\n return new_ext, new_bins\n"
] | [
[
"numpy.pad",
"numpy.arange",
"numpy.around",
"numpy.log10",
"numpy.nanmean",
"numpy.array",
"numpy.histogram"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nthndy/BayesianTracker | [
"443f984ce830373e140f744a27179debdf34ae58"
] | [
"btrack/models.py"
] | [
"from typing import List, Optional\n\nimport numpy as np\nfrom pydantic import BaseModel, root_validator, validator\n\nfrom . import constants\nfrom .optimise.hypothesis import H_TYPES, PyHypothesisParams\n\n__all__ = [\"MotionModel\", \"ObjectModel\", \"HypothesisModel\"]\n\n\ndef _check_symmetric(\n x: np.ndarray, rtol: float = 1e-5, atol: float = 1e-8\n) -> bool:\n \"\"\"Check that a matrix is symmetric by comparing with it's own transpose.\"\"\"\n return np.allclose(x, x.T, rtol=rtol, atol=atol)\n\n\nclass MotionModel(BaseModel):\n r\"\"\"The `btrack` motion model.\n\n Parameters\n ----------\n name : str\n A name identifier for the model.\n measurements : int\n The number of measurements of the system (e.g. 3 for x, y, z).\n states : int\n The number of states of the system (typically >= measurements). The\n standard states for a constant velocity model are (x, y, z, dx, dy, dz),\n i.e. 6 in total for 3 measurements.\n A : array (states, states)\n State transition matrix.\n H : array (measurements, states)\n Observation matrix.\n P : array (states, states)\n Initial covariance estimate.\n G : array (1, states), optional\n Simplified estimated error in process. Is used to calculate Q using\n Q = G.T @ G. Either G or Q must be defined.\n Q : array (states, states), optional\n Full estimated error in process. Either G or Q must be defined.\n R : array (measurements, measurements)\n Estimated error in measurements.\n dt : float\n Time difference (always 1).\n accuracy : float\n Integration limits for calculating the probabilities.\n max_lost : int\n Number of frames without observation before marking as lost.\n prob_not_assign : float\n The default probability to not assign a track.\n\n Notes\n -----\n Uses a Kalman filter [1]_:\n\n 'Is an algorithm which uses a series of measurements observed over time,\n containing noise (random variations) and other inaccuracies, and produces\n estimates of unknown variables that tend to be more precise than those that\n would be based on a single measurement alone.'\n\n Predicted estimate of state:\n\n .. math:: \\hat{x}_{t\\vert~t-1} = A_t \\hat{x}_{t-1\\vert~t-1}\n\n Predicted estimate of covariance:\n\n .. math:: P_{t\\vert~t-1} = A_t P_{t-1\\vert~t-1} A_t^{\\top} + Q_t\n\n This is just a wrapper for the data with a few convenience functions\n thrown in. Matrices must be stored Fortran style, because Eigen uses\n column major and Numpy uses row major storage.\n\n References\n ----------\n .. [1] 'A new approach to linear filtering and prediction problems.'\n Kalman RE, 1960 Journal of Basic Engineering\n \"\"\"\n\n measurements: int\n states: int\n A: np.ndarray\n H: np.ndarray\n P: np.ndarray\n R: np.ndarray\n G: Optional[np.ndarray] = None\n Q: Optional[np.ndarray] = None\n dt: float = 1.0\n accuracy: float = 2.0\n max_lost: int = constants.MAX_LOST\n prob_not_assign: float = constants.PROB_NOT_ASSIGN\n name: str = \"Default\"\n\n @validator(\"A\", \"H\", \"P\", \"R\", \"G\", \"Q\", pre=True)\n def parse_arrays(cls, v):\n if isinstance(v, dict):\n m = v.get(\"matrix\", None)\n s = v.get(\"sigma\", 1.0)\n return np.asarray(m, dtype=float) * s\n return np.asarray(v, dtype=float)\n\n @validator(\"A\")\n def reshape_A(cls, a, values):\n shape = (values[\"states\"], values[\"states\"])\n return np.reshape(a, shape)\n\n @validator(\"H\")\n def reshape_H(cls, h, values):\n shape = (values[\"measurements\"], values[\"states\"])\n return np.reshape(h, shape)\n\n @validator(\"P\")\n def reshape_P(cls, p, values):\n shape = (values[\"states\"], values[\"states\"])\n p = np.reshape(p, shape)\n if not _check_symmetric(p):\n raise ValueError(\"Matrix `P` is not symmetric.\")\n return p\n\n @validator(\"R\")\n def reshape_R(cls, r, values):\n shape = (values[\"measurements\"], values[\"measurements\"])\n r = np.reshape(r, shape)\n if not _check_symmetric(r):\n raise ValueError(\"Matrix `R` is not symmetric.\")\n return r\n\n @validator(\"G\")\n def reshape_G(cls, g, values):\n shape = (1, values[\"states\"])\n return np.reshape(g, shape)\n\n @validator(\"Q\")\n def reshape_Q(cls, q, values):\n shape = (values[\"states\"], values[\"states\"])\n q = np.reshape(q, shape)\n if not _check_symmetric(q):\n raise ValueError(\"Matrix `Q` is not symmetric.\")\n return q\n\n @root_validator\n def validate_motion_model(cls, values):\n if values[\"Q\"] is None:\n G = values.get(\"G\", None)\n if G is None:\n raise ValueError(\"Either a `G` or `Q` matrix is required.\")\n values[\"Q\"] = G.T @ G\n return values\n\n class Config:\n arbitrary_types_allowed = True\n validate_assignment = True\n\n\nclass ObjectModel(BaseModel):\n \"\"\"The `btrack` object model.\n\n This is a class to deal with state transitions in the object, essentially\n a Hidden Markov Model. Makes an assumption that the states are all\n observable, but with noise.\n\n Parameters\n ----------\n name : str\n A name identifier for the model.\n emission : array\n The emission probability matrix.\n transition : array\n Transition probabilities.\n start : array\n Initial probabilities.\n states : int\n Number of observable states.\n \"\"\"\n\n states: int\n emission: np.ndarray\n transition: np.ndarray\n start: np.ndarray\n name: str = \"Default\"\n\n @validator(\"emission\", \"transition\", \"start\", pre=True)\n def parse_array(cls, v, values):\n return np.asarray(v, dtype=float)\n\n @validator(\"emission\", \"transition\", \"start\", pre=True)\n def reshape_emission_transition(cls, v, values):\n shape = (values[\"states\"], values[\"states\"])\n return np.reshape(v, shape)\n\n @validator(\"emission\", \"transition\", \"start\", pre=True)\n def reshape_start(cls, v, values):\n shape = (1, values[\"states\"])\n return np.reshape(v, shape)\n\n class Config:\n arbitrary_types_allowed = True\n validate_assignment = True\n\n\nclass HypothesisModel(BaseModel):\n r\"\"\"The `btrack` hypothesis model.\n\n This is a class to deal with hypothesis generation in the optimization step\n of the tracking algorithm.\n\n Parameters\n ----------\n name : str\n A name identifier for the model.\n hypotheses : list[str]\n A list of hypotheses to be generated. See `optimise.hypothesis.H_TYPES`.\n lambda_time : float\n A scaling factor for the influence of time when determining\n initialization or termination hypotheses. See notes.\n lambda_dist : float\n A a scaling factor for the influence of distance at the border when\n determining initialization or termination hypotheses. See notes.\n lambda_link : float\n A scaling factor for the influence of track-to-track distance on linking\n probability. See notes.\n lambda_branch : float\n A scaling factor for the influence of cell state and position on\n division (mitosis/branching) probability. See notes.\n eta : float\n Default value for a low probability event (e.g. 1E-10) to prevent\n divide-by-zero.\n theta_dist : float\n A threshold distance from the edge of the FOV to add an initialization\n or termination hypothesis.\n theta_time : float\n A threshold time from the beginning or end of movie to add an\n initialization or termination hypothesis.\n dist_thresh : float\n Isotropic spatial bin size for considering hypotheses. Larger bin sizes\n generate more hypothesese for each tracklet.\n time_thresh : float\n Temporal bin size for considering hypotheses. Larger bin sizes generate\n more hypothesese for each tracklet.\n apop_thresh : int\n Number of apoptotic detections, counted consecutively from the back of\n the track, to be considered a real apoptosis.\n segmentation_miss_rate : float\n Miss rate for the segmentation, e.g. 1/100 segmentations incorrect gives\n a segmentation miss rate or 0.01.\n apoptosis_rate : float\n Rate of apoptosis detections.\n relax : bool\n Disables the `theta_dist` and `theta_time` thresholds when creating\n termination and initialization hypotheses. This means that tracks can\n initialize or terminate anywhere (or time) in the dataset.\n\n Notes\n -----\n The `lambda` (:math:`\\lambda`) factors scale the probability according to\n the following function:\n\n .. math:: e^{(-d / \\lambda)}\n \"\"\"\n\n hypotheses: List[str]\n lambda_time: float\n lambda_dist: float\n lambda_link: float\n lambda_branch: float\n eta: float\n theta_dist: float\n theta_time: float\n dist_thresh: float\n time_thresh: float\n apop_thresh: int\n segmentation_miss_rate: float\n apoptosis_rate: float\n relax: bool\n name: str = \"Default\"\n\n @validator(\"hypotheses\", pre=True)\n def parse_hypotheses(cls, hypotheses):\n if not all(h in H_TYPES for h in hypotheses):\n raise ValueError(\"Unknown hypothesis type in `hypotheses`.\")\n return hypotheses\n\n def hypotheses_to_generate(self) -> int:\n \"\"\"Return an integer representation of the hypotheses to generate.\"\"\"\n h_bin = \"\".join(\n [str(int(h)) for h in [h in self.hypotheses for h in H_TYPES]]\n )\n return int(h_bin[::-1], 2)\n\n def as_ctype(self) -> PyHypothesisParams:\n \"\"\"Return the ctypes representation of the `HypothesisModel`.\"\"\"\n h_params = PyHypothesisParams()\n fields = [f[0] for f in h_params._fields_]\n\n for k, v in self.dict().items():\n if k in fields:\n setattr(h_params, k, v)\n\n # set the hypotheses to generate\n h_params.hypotheses_to_generate = self.hypotheses_to_generate()\n return h_params\n\n class Config:\n validate_assignment = True\n"
] | [
[
"numpy.asarray",
"numpy.allclose",
"numpy.reshape"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NowacekLab/Duke-Whale-TagDataVis | [
"89f5f1af5fa558ddfec41ac6dad6e7239be4b3be"
] | [
"src/app/scripts_dev/dives.py"
] | [
"\"\"\"\nFind dives\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\n\ndef plotDives(calc_file_path, new_file_path, is_export, min_length = 60, required_depth = None, max_depth = None, interest_variables = [], shading = 'deep'):\n \"\"\"\n This function pulls individual dives from the data that meet defined criteria.\n It then plots these dives next to each other starting from a shared zeroed start time.\n The dives can be colorscaled based on \"interest variables\"\n\n Inputs:\n min_length : type int or float, sets the minimum length of a dive in seconds before a dive is recorded (Default is 60 seconds)\n required_depth : type int or float, a dive must reach this depth (same units as file) in order to be recorded (Defualt is None)\n max_depth : type int or float, dives over that reach a depth greater than this will not be recorded (Default is None)\n interest_variables : tpye list of string, each string is the name of a variable to coloscale dives, creates a subplot for each\n shading : type string, choose any PlotLy colorscale to set the color (Default is 'deep')\n\n Tips:\n For cyclical data like Pitch, Roll, or Heading try setting 'shading' to 'icefire' one of PlotLy's cyclical colorscales\n Though not technically cyclical, 'balance' provides a similar effect\n \"\"\"\n # Pull in Data\n data = pd.read_csv(calc_file_path) \n\n # Pull Specific Variables : \n fs = data['fs'].tolist()[0]\n depth = np.array(data[\"Depth\"])\n\n # Calculate time in terms of hours\n numData = len(depth)\n t = np.array([x/fs/3600 for x in range(numData)])\n\n # Deifne the surface\n sigma = np.std(depth[0:fs*2])\n surface = (depth*[depth < 6*sigma])[0]\n\n # Section the data into all dives\n diveIndexes = np.where(surface == 0)[0]\n lstDives = np.split(diveIndexes, np.where(np.diff(diveIndexes)!=1)[0]+1)\n\n # Create a dictionary to record dives\n dives = {}\n\n # Loop through dives and check that they meet requirements\n for d in lstDives:\n # Set a variable to the depth data\n diveDepth = depth[d]\n # Check Requirements\n if len(d) >= fs*min_length and (True if required_depth == None else np.max(diveDepth) >= required_depth) and (True if max_depth == None else np.max(diveDepth) <= max_depth):\n num = len(dives) + 1\n # Create a dictionary for specific dive\n dive = {}\n dive[\"name\"] = \"Dive \" + str(num) # Name is used for title of trace, sequential order\n dive[\"depth\"] = diveDepth # Dive path \n dive[\"time\"] = t[:len(d)] # Time of dive starting at 0\n dive[\"idx\"] = d # Indexes of the dive in full data set\n # Record dive to dives dictionay\n dives[num-1] = dive\n \n # Create Figure\n # Check to see if interest variables declared \n if not interest_variables:\n fig = go.Figure()\n # If interest variables declared, make subplots for each\n else:\n fig = go.Figure(\n make_subplots(\n rows = (len(interest_variables)),\n cols = 1,\n specs = [[{}]]*(len(interest_variables)),\n subplot_titles = [\"Colorscale based on \" + name for name in interest_variables],\n shared_xaxes = True\n )\n )\n\n # Plot Dives\n if not interest_variables:\n # Loop through dives and plot a trace for each\n for i in range(len(dives)):\n d = dives[i]\n fig.add_trace(go.Scattergl(x = d[\"time\"], y = d[\"depth\"], name = d[\"name\"], mode = \"markers\"))\n \n # Update x-axis, with range slider\n fig.update_xaxes(title = \"Time (hr)\", rangeslider = dict(visible = True))\n # If interest variables declared plot traces with colorscale\n else:\n numVars = len(interest_variables) # Ease of access varible for number of interest variables\n\n # Determine loactions for color bars\n clocSpacing = 1/numVars/2 # spacing variable for color bar placement\n cbarlocs = [1 - (clocSpacing * (1 + 2*i)) for i in range(numVars)] # List of y-axis locations for colorbars\n\n # Loop through Interest Variables\n for k in range(len(interest_variables)):\n # Set current variable and associated data\n var = interest_variables[k]\n varData = np.array(data[var])\n\n # Loop through Dives\n for i in range(len(dives)):\n d = dives[i]\n # Add trace\n fig.add_trace(go.Scattergl(x = d[\"time\"], \n y = d[\"depth\"],\n name = d[\"name\"],\n # Group legends of each dive across subplots\n legendgroup = str(i),\n showlegend = (True if k == 0 else False),\n mode = \"markers\",\n # Set colorscale\n marker = dict(color = varData[d[\"idx\"]],\n cmax = np.max(varData),\n cmin = np.min(varData),\n colorbar = dict(title = var, len = clocSpacing*2, x = -0.15, y = cbarlocs[k]),\n colorscale = shading),\n ), \n row = k+1,\n col = 1,\n )\n\n # Update x-axis\n fig.update_xaxes(title = \"Time (hr)\", rangeslider = dict(visible = True), col = 1, row = numVars)\n\n \n # Update y-axis\n fig.update_yaxes(title = \"Depth (m)\", autorange = \"reversed\")\n \n # Update Title of plot\n fig.update_layout(\n title = \"Dives\"\n )\n \n if len(dives) == 0:\n raise Exception(\"No dives found.\")\n \n if is_export:\n fig.write_html(new_file_path)\n else:\n fig.show()\n \ndef main(cmdLineArgs: dict):\n try: \n calc_file_path = cmdLineArgs['calcFilePath']\n new_file_path = cmdLineArgs['newFilePath']\n is_export = cmdLineArgs['isExport']\n min_length = cmdLineArgs['minLength']\n required_depth = cmdLineArgs['requiredDepth']\n max_depth = cmdLineArgs['maxDepth']\n interest_vars = cmdLineArgs['interestVars']\n interest_vars = interest_vars.split(\"ARRAYSEP\")\n \n try:\n min_length = float(min_length)\n except:\n min_length = None \n \n try: \n required_depth = float(required_depth)\n except:\n required_depth = None \n \n try:\n max_depth = float(max_depth)\n except:\n max_depth = None \n \n is_export = True if is_export == \"True\" else False \n \n plotDives(calc_file_path, new_file_path, is_export, min_length, required_depth, max_depth, interest_vars)\n \n \n return \"SUCCESS\" \n except Exception as e:\n raise Exception(e)"
] | [
[
"pandas.read_csv",
"numpy.min",
"numpy.max",
"numpy.std",
"numpy.diff",
"numpy.array",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Linyou/maskrcnn-benchmark | [
"5b26da7e56018dc27d0d2d8ab131d140e00c2a64"
] | [
"maskrcnn_benchmark/structures/bbox_4_point.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 29 18:56:23 2019\n\n@author: pengming\n\"\"\"\n\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nimport torch\n\n# transpose\nFLIP_LEFT_RIGHT = 0\nFLIP_TOP_BOTTOM = 1\n\nfrom .bounding_box import BoxList as bbox2\nfrom maskrcnn_benchmark.data.datasets.DOTA_devkit.dota_utils import dots4ToRec4\n\n\n\ndef _dots8ToRec4(poly):\n poly = poly.view(poly.size(0), 4, 2)\n xmin, xmax, ymin, ymax = torch.min(poly[:,0,0], torch.min(poly[:,1,0], torch.min(poly[:,2,0], poly[:,3,0]))), \\\n torch.max(poly[:,0,0], torch.max(poly[:,1,0], torch.max(poly[:,2,0], poly[:,3,0]))), \\\n torch.min(poly[:,0,1], torch.min(poly[:,1,1], torch.min(poly[:,2,1], poly[:,3,1]))), \\\n torch.max(poly[:,0,1], torch.max(poly[:,1,1], torch.max(poly[:,2,1], poly[:,3,1])))\n poly_box = torch.cat([xmin.unsqueeze(1), ymin.unsqueeze(1), xmax.unsqueeze(1) - xmin.unsqueeze(1), ymax.unsqueeze(1) - ymin.unsqueeze(1)], dim=1)\n return poly_box\n\n\n\nclass BoxList(object):\n \"\"\"\n This class represents a set of bounding boxes.\n The bounding boxes are represented as a Nx4 Tensor.\n In order to uniquely determine the bounding boxes with respect\n to an image, we also store the corresponding image dimensions.\n They can contain extra information that is specific to each bounding box, such as\n labels.\n \"\"\"\n\n def __init__(self, bbox, image_size, mode=\"xyxy\"):\n device = bbox.device if isinstance(bbox, torch.Tensor) else torch.device(\"cpu\")\n bbox = torch.as_tensor(bbox, dtype=torch.float32, device=device)\n if bbox.ndimension() != 2:\n raise ValueError(\n \"bbox should have 2 dimensions, got {}\".format(bbox.ndimension())\n )\n if bbox.size(-1) != 8 and bbox.size(-1) != 4:\n raise ValueError(\n \"last dimension of bbox should have a \"\n \"size of 10 or 4, got {}\".format(bbox.size(-1))\n )\n if mode not in (\"xyxy\", \"xywh\", \"xxyy\", \"xxyy_\", \"xyxy_\"):\n raise ValueError(\"mode should be 'xyxy' \")\n\n self.bbox = bbox\n #self.temp_bbox = self._dots8ToRec4(self.bbox)\n self.size = image_size # (image_width, image_height)\n self.mode = mode\n self.extra_fields = {}\n \n\n def add_field(self, field, field_data):\n self.extra_fields[field] = field_data\n\n def get_field(self, field):\n return self.extra_fields[field]\n\n def has_field(self, field):\n return field in self.extra_fields\n\n def fields(self):\n return list(self.extra_fields.keys())\n\n def _copy_extra_fields(self, bbox):\n for k, v in bbox.extra_fields.items():\n self.extra_fields[k] = v\n \n def center(self):\n x1, y1, x2, y2, x3, y3, x4, y4 = self._split_into_xyxy()\n minx = torch.stack([x1, x2, x3, x4], dim=1).min(dim=1)[0]\n maxx = torch.stack([x1, x2, x3, x4], dim=1).max(dim=1)[0]\n miny = torch.stack([y1, y2, y3, y4], dim=1).min(dim=1)[0]\n maxy = torch.stack([y1, y2, y3, y4], dim=1).max(dim=1)[0]\n centerx = (minx + maxx)/2\n centery = (miny + maxy)/2\n center = torch.stack([centerx, centery],dim=1)\n return center\n\n def convert(self, mode):\n if mode not in (\"xyxy\", \"xywh\", \"xxyy\", \"xyxy_\", \"xxyy_\"):\n raise ValueError(\"mode should be 'xyxy' or 'xywh'\")\n# if mode == self.mode:\n# return self\n # we only have two modes, so don't need to check\n # self.mode\n \n #if mode == \"xyxy_\":\n temp = self.bbox\n tempbbox = _dots8ToRec4(temp)\n return BoxList(tempbbox, self.size, mode=\"xyxy_\")\n\n def _split_into_xyxy(self):\n if self.mode == \"xyxy\":\n #xmin, ymin, xmax, ymax = self.bbox.split(1, dim=-1)\n x1, y1, x2, y2, x3, y3, x4, y4 = (self.bbox[:,0], self.bbox[:,1], \n self.bbox[:,2], self.bbox[:,3],\n self.bbox[:,4], self.bbox[:,5], \n self.bbox[:,6], self.bbox[:,7])\n \n return x1, y1, x2, y2, x3, y3, x4, y4\n else:\n raise RuntimeError(\"xywh Should not be here\")\n \n def _dots8ToRec4_(self, poly):\n poly = poly.view(poly.size(0), 4, 2)\n xmin, xmax, ymin, ymax = torch.min(poly[:,0,0], torch.min(poly[:,1,0], torch.min(poly[:,2,0], poly[:,3,0]))), \\\n torch.max(poly[:,0,0], torch.max(poly[:,1,0], torch.max(poly[:,2,0], poly[:,3,0]))), \\\n torch.min(poly[:,0,1], torch.min(poly[:,1,1], torch.min(poly[:,2,1], poly[:,3,1]))), \\\n torch.max(poly[:,0,1], torch.max(poly[:,1,1], torch.max(poly[:,2,1], poly[:,3,1])))\n poly_box = torch.cat([xmin.unsqueeze(1), xmax.unsqueeze(1), ymin.unsqueeze(1), ymax.unsqueeze(1)], dim=1)\n #poly_box = torch.cat([xmin.unsqueeze(1), ymin.unsqueeze(1), xmax.unsqueeze(1) - xmin.unsqueeze(1), ymax.unsqueeze(1) - ymin.unsqueeze(1)], dim=1)\n bbox = BoxList(poly_box, self.size, mode=\"xyxy\")\n # bbox._copy_extra_fields(self)\n for k, v in self.extra_fields.items():\n if not isinstance(v, torch.Tensor):\n v = v._dots8ToRec4(poly)\n bbox.add_field(k, v)\n\n return bbox\n\n def resize(self, size, *args, **kwargs):\n \"\"\"\n Returns a resized copy of this bounding box\n\n :param size: The requested size in pixels, as a 2-tuple:\n (width, height).\n \"\"\"\n\n ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(size, self.size))\n if ratios[0] == ratios[1]:\n ratio = ratios[0]\n scaled_box = self.bbox * ratio\n bbox = BoxList(scaled_box, size, mode=self.mode)\n # bbox._copy_extra_fields(self)\n for k, v in self.extra_fields.items():\n if not isinstance(v, torch.Tensor):\n v = v.resize(size, *args, **kwargs)\n bbox.add_field(k, v)\n return bbox\n\n ratio_width, ratio_height = ratios\n x1, y1, x2, y2, x3, y3, x4, y4 = self._split_into_xyxy()\n num_boxs = x4.size(0)\n scaled_x1 = x1 * ratio_width\n scaled_y1 = y1 * ratio_height\n scaled_x2 = x2 * ratio_width\n scaled_y2 = y2 * ratio_height\n scaled_x3 = x3 * ratio_width\n scaled_y3 = y3 * ratio_height\n scaled_x4 = x4 * ratio_width\n scaled_y4 = y4 * ratio_height\n# scaled_box = torch.cat(\n# (scaled_xmin, scaled_ymin, scaled_xmax, scaled_ymax), dim=-1\n# )\n# x1y1 = torch.cat((scaled_x1.view(x1.size(0),-1), scaled_y1.view(y1.size(0),-1)), dim=1)\n# x2y2 = torch.cat((scaled_x2.view(x2.size(0),-1), scaled_y2.view(y2.size(0),-1)), dim=1)\n# x3y3 = torch.cat((scaled_x3.view(x3.size(0),-1), scaled_y3.view(y3.size(0),-1)), dim=1)\n# x4y4 = torch.cat((scaled_x4.view(x4.size(0),-1), scaled_y4.view(y4.size(0),-1)), dim=1)\n# \n# cat_xy = torch.cat((x1y1, x2y2, x3y3, x4y4), dim=-1)\n# scaled_box = cat_xy.view(cat_xy.size(0), 4, 2)\n scaled_box = torch.cat((scaled_x1.view(num_boxs,-1), \n scaled_y1.view(num_boxs,-1), \n scaled_x2.view(num_boxs,-1), \n scaled_y2.view(num_boxs,-1), \n scaled_x3.view(num_boxs,-1), \n scaled_y3.view(num_boxs,-1), \n scaled_x4.view(num_boxs,-1), \n scaled_y4.view(num_boxs,-1)), dim=1)\n bbox = BoxList(scaled_box, size, mode=\"xyxy\")\n # bbox._copy_extra_fields(self)\n for k, v in self.extra_fields.items():\n if not isinstance(v, torch.Tensor):\n v = v.resize(size, *args, **kwargs)\n bbox.add_field(k, v)\n\n return bbox\n\n def transpose(self, method):\n \"\"\"\n Transpose bounding box (flip or rotate in 90 degree steps)\n :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,\n :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,\n :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`,\n :py:attr:`PIL.Image.TRANSPOSE` or :py:attr:`PIL.Image.TRANSVERSE`.\n \"\"\"\n if method not in (FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM):\n raise NotImplementedError(\n \"Only FLIP_LEFT_RIGHT and FLIP_TOP_BOTTOM implemented\"\n )\n\n image_width, image_height = self.size\n x1, y1, x2, y2, x3, y3, x4, y4 = self._split_into_xyxy()\n if method == FLIP_LEFT_RIGHT:\n TO_REMOVE = 0\n transposed_x1 = image_width - x1 - TO_REMOVE\n transposed_x2 = image_width - x2 - TO_REMOVE\n transposed_x3 = image_width - x3 - TO_REMOVE\n transposed_x4 = image_width - x4 - TO_REMOVE\n transposed_y1 = y1\n transposed_y2 = y2\n transposed_y3 = y3\n transposed_y4 = y4\n elif method == FLIP_TOP_BOTTOM:\n transposed_x1 = x1\n transposed_x2 = x2\n transposed_x3 = x3\n transposed_x4 = x4\n transposed_y1 = image_height - y1\n transposed_y2 = image_height - y2\n transposed_y3 = image_height - y3\n transposed_y4 = image_height - y4\n\n\n num_boxs = x4.size(0)\n# transposed_boxes = torch.cat(\n# (transposed_xmin, transposed_ymin, transposed_xmax, transposed_ymax), dim=-1\n# )\n# x1y1 = torch.cat((transposed_x1.view(x1.size(0),-1), transposed_y1.view(y1.size(0),-1)), dim=1)\n# x2y2 = torch.cat((transposed_x2.view(x2.size(0),-1), transposed_y2.view(y2.size(0),-1)), dim=1)\n# x3y3 = torch.cat((transposed_x3.view(x3.size(0),-1), transposed_y3.view(y3.size(0),-1)), dim=1)\n# x4y4 = torch.cat((transposed_x4.view(x4.size(0),-1), transposed_y4.view(y4.size(0),-1)), dim=1)\n \n transposed_boxes = torch.cat((transposed_x1.view(num_boxs,-1), \n transposed_y1.view(num_boxs,-1), \n transposed_x2.view(num_boxs,-1), \n transposed_y2.view(num_boxs,-1), \n transposed_x3.view(num_boxs,-1), \n transposed_y3.view(num_boxs,-1), \n transposed_x4.view(num_boxs,-1), \n transposed_y4.view(num_boxs,-1)), dim=1)\n \n# cat_xy = torch.cat((x1y1, x2y2, x3y3, x4y4), dim=-1)\n #transposed_boxes = cat_xy.view(cat_xy.size(0), 4, 2)\n bbox = BoxList(transposed_boxes, self.size, mode=\"xyxy\")\n # bbox._copy_extra_fields(self)\n for k, v in self.extra_fields.items():\n if not isinstance(v, torch.Tensor):\n v = v.transpose(method)\n bbox.add_field(k, v)\n return bbox\n\n# def crop(self, box):\n# \"\"\"\n# Cropss a rectangular region from this bounding box. The box is a\n# 4-tuple defining the left, upper, right, and lower pixel\n# coordinate.\n# \"\"\"\n# x1, y1, x2, y2, x3, y3, x4, y4 = self._split_into_xyxy()\n# w, h = box[2] - box[0], box[3] - box[1]\n# cropped_xmin = (xmin - box[0]).clamp(min=0, max=w)\n# cropped_ymin = (ymin - box[1]).clamp(min=0, max=h)\n# cropped_xmax = (xmax - box[0]).clamp(min=0, max=w)\n# cropped_ymax = (ymax - box[1]).clamp(min=0, max=h)\n#\n# # TODO should I filter empty boxes here?\n# if False:\n# is_empty = (cropped_xmin == cropped_xmax) | (cropped_ymin == cropped_ymax)\n#\n# cropped_box = torch.cat(\n# (cropped_xmin, cropped_ymin, cropped_xmax, cropped_ymax), dim=-1\n# )\n# bbox = BoxList(cropped_box, (w, h), mode=\"xyxy\")\n# # bbox._copy_extra_fields(self)\n# for k, v in self.extra_fields.items():\n# if not isinstance(v, torch.Tensor):\n# v = v.crop(box)\n# bbox.add_field(k, v)\n# print(\"don't use!! crop\")\n# return bbox.convert(self.mode)\n\n # Tensor-like methods\n\n def to(self, device):\n bbox = BoxList(self.bbox.to(device), self.size, self.mode)\n for k, v in self.extra_fields.items():\n if hasattr(v, \"to\"):\n v = v.to(device)\n bbox.add_field(k, v)\n return bbox\n\n def __getitem__(self, item):\n bbox = BoxList(self.bbox[item], self.size, self.mode)\n for k, v in self.extra_fields.items():\n bbox.add_field(k, v[item])\n return bbox\n\n def __len__(self):\n return self.bbox.shape[0]\n\n def clip_to_image(self, remove_empty=True):\n TO_REMOVE = 1\n self.bbox[:,0].clamp_(min=0, max=self.size[0] - TO_REMOVE)\n self.bbox[:,1].clamp_(min=0, max=self.size[1] - TO_REMOVE)\n self.bbox[:,2].clamp_(min=0, max=self.size[0] - TO_REMOVE)\n self.bbox[:,3].clamp_(min=0, max=self.size[1] - TO_REMOVE)\n self.bbox[:,4].clamp_(min=0, max=self.size[0] - TO_REMOVE)\n self.bbox[:,5].clamp_(min=0, max=self.size[1] - TO_REMOVE)\n self.bbox[:,6].clamp_(min=0, max=self.size[0] - TO_REMOVE)\n self.bbox[:,7].clamp_(min=0, max=self.size[1] - TO_REMOVE)\n# if remove_empty:\n# box = self.bbox\n# #keep = (box[:, 3] > box[:, 1]) & (box[:, 2] > box[:, 0])\n# keep = (box[:,2,0] > box[:,0,0]) & (\n# box[:,3,1] > box[:,1,1]) & (\n# return self[keep]\n return self\n\n def area(self):\n box = self.bbox\n if self.mode == \"xyxy\":\n area = self.extra_fields['areas']\n else:\n raise RuntimeError(\"Should not be here\")\n\n return area\n\n def copy_with_fields(self, fields, skip_missing=False):\n bbox = BoxList(self.bbox, self.size, self.mode)\n if not isinstance(fields, (list, tuple)):\n fields = [fields]\n for field in fields:\n if self.has_field(field):\n bbox.add_field(field, self.get_field(field))\n elif not skip_missing:\n raise KeyError(\"Field '{}' not found in {}\".format(field, self))\n return bbox\n\n def __repr__(self):\n s = self.__class__.__name__ + \"(\"\n s += \"num_boxes={}, \".format(len(self))\n s += \"image_width={}, \".format(self.size[0])\n s += \"image_height={}, \".format(self.size[1])\n s += \"mode={})\".format(self.mode)\n return s\n\n\nif __name__ == \"__main__\":\n bbox = BoxList([[0, 0, 10, 10], [0, 0, 5, 5]], (10, 10))\n s_bbox = bbox.resize((5, 5))\n print(s_bbox)\n print(s_bbox.bbox)\n\n t_bbox = bbox.transpose(0)\n print(t_bbox)\n print(t_bbox.bbox)\n"
] | [
[
"torch.max",
"torch.min",
"torch.stack",
"torch.device",
"torch.as_tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
i-jones/captum | [
"567ec6fc67ab85ce07d075b25428be22bb65e31b",
"567ec6fc67ab85ce07d075b25428be22bb65e31b"
] | [
"captum/influence/_core/similarity_influence.py",
"captum/attr/_utils/attribution.py"
] | [
"#!/usr/bin/env python3\n\nimport warnings\nfrom functools import partial\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nimport captum._utils.common as common\nimport torch\nfrom captum._utils.av import AV\nfrom captum.attr import LayerActivation\nfrom captum.influence._core.influence import DataInfluence\nfrom torch import Tensor\nfrom torch.nn import Module\nfrom torch.utils.data import DataLoader, Dataset\n\nr\"\"\"\nAdditional helper functions to calculate similarity metrics.\n\"\"\"\n\n\ndef euclidean_distance(test, train) -> Tensor:\n r\"\"\"\n Calculates the pairwise euclidean distance for batches of feature vectors.\n Tensors test and train have shape (batch_size_1, *), and (batch_size_2, *).\n Returns pairwise euclidean distance Tensor of shape (batch_size_1, batch_size_2).\n \"\"\"\n similarity = torch.cdist(\n test.view(test.shape[0], -1).unsqueeze(0),\n train.view(train.shape[0], -1).unsqueeze(0),\n ).squeeze(0)\n return similarity\n\n\ndef cosine_similarity(test, train, replace_nan=0) -> Tensor:\n r\"\"\"\n Calculates the pairwise cosine similarity for batches of feature vectors.\n Tensors test and train have shape (batch_size_1, *), and (batch_size_2, *).\n Returns pairwise cosine similarity Tensor of shape (batch_size_1, batch_size_2).\n \"\"\"\n test = test.view(test.shape[0], -1)\n train = train.view(train.shape[0], -1)\n\n if torch.__version__ <= \"1.6.0\":\n test_norm = torch.norm(test, p=None, dim=1, keepdim=True)\n train_norm = torch.norm(train, p=None, dim=1, keepdim=True)\n else:\n test_norm = torch.linalg.norm(test, ord=2, dim=1, keepdim=True)\n train_norm = torch.linalg.norm(train, ord=2, dim=1, keepdim=True)\n\n test = torch.where(test_norm != 0.0, test / test_norm, Tensor([replace_nan]))\n train = torch.where(train_norm != 0.0, train / train_norm, Tensor([replace_nan])).T\n\n similarity = torch.mm(test, train)\n return similarity\n\n\nr\"\"\"\nImplements abstract DataInfluence class and provides implementation details for\nsimilarity metric-based influence computation. Similarity metrics can be used to compare\nintermediate or final activation vectors of a model for different sets of input. Then,\nthese can be used to draw conclusions about influential instances.\n\nSome standard similarity metrics such as dot product similarity or euclidean distance\nare provided, but the user can provide any custom similarity metric as well.\n\"\"\"\n\n\nclass SimilarityInfluence(DataInfluence):\n def __init__(\n self,\n module: Module,\n layers: Union[str, List[str]],\n influence_src_dataset: Dataset,\n activation_dir: str,\n model_id: str = \"\",\n similarity_metric: Callable = cosine_similarity,\n similarity_direction: str = \"max\",\n batch_size: int = 1,\n **kwargs: Any,\n ):\n r\"\"\"\n Args:\n module (torch.nn.Module): An instance of pytorch model. This model should\n define all of its layers as attributes of the model.\n layers (str or List of str): The fully qualified layer(s) for which the\n activation vectors are computed.\n influence_src_dataset (torch.utils.data.Dataset): PyTorch Dataset that is\n used to create a PyTorch Dataloader to iterate over the dataset and\n its labels. This is the dataset for which we will be seeking for\n influential instances. In most cases this is the training dataset.\n activation_dir (str): The directory of the path to store\n and retrieve activation computations. Best practice would be to use\n an absolute path.\n model_id (str): The name/version of the model for which layer\n activations are being computed. Activations will be stored and\n loaded under the subdirectory with this name if provided.\n similarity_metric (Callable): This is a callable function that computes a\n similarity metric between two representations. For example, the\n representations pair could be from the training and test sets.\n\n This function must adhere to certain standards. The inputs should be\n torch Tensors with shape (batch_size_i/j, feature dimensions). The\n output Tensor should have shape (batch_size_i, batch_size_j) with\n scalar values corresponding to the similarity metric used for each\n pairwise combination from the two batches.\n\n For example, suppose we use `batch_size_1 = 16` for iterating\n through `influence_src_dataset`, and for the `inputs` argument\n we pass in a Tensor with 3 examples, i.e. batch_size_2 = 3. Also,\n suppose that our inputs and intermediate activations throughout the\n model will have dimension (N, C, H, W). Then, the feature dimensions\n should be flattened within this function. For example::\n\n >>> av_test.shape\n torch.Size([3, N, C, H, W])\n >>> av_src.shape\n torch.Size([16, N, C, H, W])\n >>> av_test = torch.view(av_test.shape[0], -1)\n >>> av_test.shape\n torch.Size([3, N x C x H x W])\n\n and similarly for av_src. The similarity_metric should then use\n these flattened tensors to return the pairwise similarity matrix.\n For example, `similarity_metric(av_test, av_src)` should return a\n tensor of shape (3, 16).\n\n batch_size (int): Batch size for iterating through `influence_src_dataset`.\n **kwargs: Additional key-value arguments that are necessary for specific\n implementation of `DataInfluence` abstract class.\n \"\"\"\n self.module = module\n self.layers = [layers] if isinstance(layers, str) else layers\n self.influence_src_dataset = influence_src_dataset\n self.activation_dir = activation_dir\n self.model_id = model_id\n self.batch_size = batch_size\n\n if similarity_direction == \"max\" or similarity_direction == \"min\":\n self.similarity_direction = similarity_direction\n else:\n raise ValueError(\n f\"{similarity_direction} is not a valid value. \"\n \"Must be either 'max' or 'min'\"\n )\n\n if similarity_metric is cosine_similarity:\n if \"replace_nan\" in kwargs:\n self.replace_nan = kwargs[\"replace_nan\"]\n else:\n self.replace_nan = -2 if self.similarity_direction == \"max\" else 2\n similarity_metric = partial(cosine_similarity, replace_nan=self.replace_nan)\n\n self.similarity_metric = similarity_metric\n\n self.influence_src_dataloader = DataLoader(\n influence_src_dataset, batch_size, shuffle=False\n )\n\n def influence( # type: ignore[override]\n self,\n inputs: Union[Tensor, Tuple[Tensor, ...]],\n top_k: int = 1,\n additional_forward_args: Optional[Any] = None,\n load_src_from_disk: bool = True,\n **kwargs: Any,\n ) -> Dict:\n r\"\"\"\n Args:\n inputs (tensor or tuple of tensors): Batch of examples for which influential\n instances are computed. They are passed to the forward_func. The\n first dimension in `inputs` tensor or tuple of tensors corresponds\n to the batch size. A tuple of tensors is only passed in if this\n is the input form that `module` accepts.\n top_k (int): The number of top-matching activations to return\n additional_forward_args (optional): Additional arguments that will be\n passed to forward_func after inputs.\n load_src_from_disk (bool): Loads activations for `influence_src_dataset`\n where possible. Setting to False would force regeneration of\n activations.\n load_input_from_disk (bool): Regenerates activations for inputs by default\n and removes previous `inputs` activations that are flagged with\n `inputs_id`. Setting to True will load prior matching inputs\n activations. Note that this could lead to unexpected behavior if\n `inputs_id` is not configured properly and activations are loaded\n for a different, prior `inputs`.\n inputs_id (str): Used to identify inputs for loading activations.\n\n **kwargs: Additional key-value arguments that are necessary for specific\n implementation of `DataInfluence` abstract class.\n\n Returns:\n\n influences (dict): Returns the influential instances retrieved from\n `influence_src_dataset` for each test example represented through a\n tensor or a tuple of tensor in `inputs`. Returned influential\n examples are represented as dict, with keys corresponding to\n the layer names passed in `layers`. Each value in the dict is a\n tuple containing the indices and values for the top k similarities\n from `influence_src_dataset` by the chosen metric. The first value\n in the tuple corresponds to the indices corresponding to the top k\n most similar examples, and the second value is the similarity score.\n The batch dimension corresponds to the batch dimension of `inputs`.\n If inputs.shape[0] == 5, then dict[`layer_name`][0].shape[0] == 5.\n These tensors will be of shape (inputs.shape[0], top_k).\n \"\"\"\n inputs_batch_size = (\n inputs[0].shape[0] if isinstance(inputs, tuple) else inputs.shape[0]\n )\n\n influences: Dict[str, Any] = {}\n\n layer_AVDatasets = AV.generate_dataset_activations(\n self.activation_dir,\n self.module,\n self.model_id,\n self.layers,\n DataLoader(self.influence_src_dataset, self.batch_size, shuffle=False),\n identifier=\"src\",\n load_from_disk=load_src_from_disk,\n return_activations=True,\n )\n\n assert layer_AVDatasets is not None and not isinstance(\n layer_AVDatasets, AV.AVDataset\n )\n\n layer_modules = [\n common._get_module_from_name(self.module, layer) for layer in self.layers\n ]\n test_activations = LayerActivation(self.module, layer_modules).attribute(\n inputs, additional_forward_args\n )\n\n minmax = self.similarity_direction == \"max\"\n\n # av_inputs shape: (inputs_batch_size, *) e.g. (inputs_batch_size, N, C, H, W)\n # av_src shape: (self.batch_size, *) e.g. (self.batch_size, N, C, H, W)\n test_activations = (\n test_activations if len(self.layers) > 1 else [test_activations]\n )\n for i, (layer, layer_AVDataset) in enumerate(\n zip(self.layers, layer_AVDatasets)\n ):\n topk_val, topk_idx = torch.Tensor(), torch.Tensor().long()\n zero_acts = torch.Tensor().long()\n\n av_inputs = test_activations[i]\n src_loader = DataLoader(layer_AVDataset)\n for j, av_src in enumerate(src_loader):\n av_src = av_src.squeeze(0)\n\n similarity = self.similarity_metric(av_inputs, av_src)\n msg = (\n \"Output of custom similarity does not meet required dimensions. \"\n f\"Your output has shape {similarity.shape}.\\nPlease ensure the \"\n \"output shape matches (inputs_batch_size, src_dataset_batch_size), \"\n f\"which should be {(inputs_batch_size, self.batch_size)}.\"\n )\n assert similarity.shape == (inputs_batch_size, av_src.shape[0]), msg\n if hasattr(self, \"replace_nan\"):\n idx = (similarity == self.replace_nan).nonzero()\n zero_acts = torch.cat((zero_acts, idx))\n\n r\"\"\"\n TODO: For models that can have tuples as activations, we should\n allow similarity metrics to accept tuples, support topk selection.\n \"\"\"\n\n topk_batch = min(top_k, self.batch_size)\n values, indices = torch.topk(\n similarity, topk_batch, dim=1, largest=minmax\n )\n indices += int(j * self.batch_size)\n\n topk_val = torch.cat((topk_val, values), dim=1)\n topk_idx = torch.cat((topk_idx, indices), dim=1)\n\n # can modify how often to sort for efficiency? minor\n sort_idx = torch.argsort(topk_val, dim=1, descending=minmax)\n topk_val = torch.gather(topk_val, 1, sort_idx[:, :top_k])\n topk_idx = torch.gather(topk_idx, 1, sort_idx[:, :top_k])\n\n influences[layer] = (topk_idx, topk_val)\n\n if torch.numel(zero_acts != 0):\n zero_warning = (\n f\"Layer {layer} has zero-vector activations for some inputs. This \"\n \"may cause undefined behavior for cosine similarity. The indices \"\n \"for the offending inputs will be included under the key \"\n f\"'zero_acts-{layer}' in the output dictionary. Indices are \"\n \"returned as a tensor with [inputs_idx, src_dataset_idx] pairs \"\n \"which may have corrupted similarity scores.\"\n )\n warnings.warn(zero_warning, RuntimeWarning)\n key = \"-\".join([\"zero_acts\", layer])\n influences[key] = zero_acts\n\n return influences\n",
"#!/usr/bin/env python3\nfrom typing import Any, Callable, Generic, List, Tuple, Type, Union, cast\n\nimport torch\nimport torch.nn.functional as F\nfrom captum._utils.common import (\n _format_additional_forward_args,\n _format_tensor_into_tuples,\n _run_forward,\n _validate_target,\n)\nfrom captum._utils.gradient import compute_gradients\nfrom captum._utils.typing import ModuleOrModuleList, TargetType\nfrom captum.attr._utils.common import (\n _format_input_baseline,\n _sum_rows,\n _tensorize_baseline,\n _validate_input,\n)\nfrom captum.log import log_usage\nfrom torch import Tensor\nfrom torch.nn import Module\n\n\nclass Attribution:\n r\"\"\"\n All attribution algorithms extend this class. It enforces its child classes\n to extend and override core `attribute` method.\n \"\"\"\n\n def __init__(self, forward_func: Callable) -> None:\n r\"\"\"\n Args:\n forward_func (callable or torch.nn.Module): This can either be an instance\n of pytorch model or any modification of model's forward\n function.\n \"\"\"\n self.forward_func = forward_func\n\n attribute: Callable\n r\"\"\"\n This method computes and returns the attribution values for each input tensor.\n Deriving classes are responsible for implementing its logic accordingly.\n\n Specific attribution algorithms that extend this class take relevant\n arguments.\n\n Args:\n\n inputs (tensor or tuple of tensors): Input for which attribution\n is computed. It can be provided as a single tensor or\n a tuple of multiple tensors. If multiple input tensors\n are provided, the batch sizes must be aligned accross all\n tensors.\n\n\n Returns:\n\n *tensor* or tuple of *tensors* of **attributions**:\n - **attributions** (*tensor* or tuple of *tensors*):\n Attribution values for each\n input tensor. The `attributions` have the same shape and\n dimensionality as the inputs.\n If a single tensor is provided as inputs, a single tensor\n is returned. If a tuple is provided for inputs, a tuple of\n corresponding sized tensors is returned.\n\n \"\"\"\n\n @property\n def multiplies_by_inputs(self):\n return False\n\n def has_convergence_delta(self) -> bool:\n r\"\"\"\n This method informs the user whether the attribution algorithm provides\n a convergence delta (aka an approximation error) or not. Convergence\n delta may serve as a proxy of correctness of attribution algorithm's\n approximation. If deriving attribution class provides a\n `compute_convergence_delta` method, it should\n override both `compute_convergence_delta` and `has_convergence_delta` methods.\n\n Returns:\n bool:\n Returns whether the attribution algorithm\n provides a convergence delta (aka approximation error) or not.\n\n \"\"\"\n return False\n\n compute_convergence_delta: Callable\n r\"\"\"\n The attribution algorithms which derive `Attribution` class and provide\n convergence delta (aka approximation error) should implement this method.\n Convergence delta can be computed based on certain properties of the\n attribution alogrithms.\n\n Args:\n\n attributions (tensor or tuple of tensors): Attribution scores that\n are precomputed by an attribution algorithm.\n Attributions can be provided in form of a single tensor\n or a tuple of those. It is assumed that attribution\n tensor's dimension 0 corresponds to the number of\n examples, and if multiple input tensors are provided,\n the examples must be aligned appropriately.\n *args (optional): Additonal arguments that are used by the\n sub-classes depending on the specific implementation\n of `compute_convergence_delta`.\n\n Returns:\n\n *tensor* of **deltas**:\n - **deltas** (*tensor*):\n Depending on specific implementaion of\n sub-classes, convergence delta can be returned per\n sample in form of a tensor or it can be aggregated\n across multuple samples and returned in form of a\n single floating point tensor.\n \"\"\"\n\n @classmethod\n def get_name(cls: Type[\"Attribution\"]) -> str:\n r\"\"\"\n Create readable class name by inserting a space before any capital\n characters besides the very first.\n\n Returns:\n str: a readable class name\n Example:\n for a class called IntegratedGradients, we return the string\n 'Integrated Gradients'\n \"\"\"\n return \"\".join(\n [\n char if char.islower() or idx == 0 else \" \" + char\n for idx, char in enumerate(cls.__name__)\n ]\n )\n\n\nclass GradientAttribution(Attribution):\n r\"\"\"\n All gradient based attribution algorithms extend this class. It requires a\n forward function, which most commonly is the forward function of the model\n that we want to interpret or the model itself.\n \"\"\"\n\n def __init__(self, forward_func: Callable) -> None:\n r\"\"\"\n Args:\n\n forward_func (callable or torch.nn.Module): This can either be an instance\n of pytorch model or any modification of model's forward\n function.\n \"\"\"\n Attribution.__init__(self, forward_func)\n self.gradient_func = compute_gradients\n\n @log_usage()\n def compute_convergence_delta(\n self,\n attributions: Union[Tensor, Tuple[Tensor, ...]],\n start_point: Union[\n None, int, float, Tensor, Tuple[Union[int, float, Tensor], ...]\n ],\n end_point: Union[Tensor, Tuple[Tensor, ...]],\n target: TargetType = None,\n additional_forward_args: Any = None,\n ) -> Tensor:\n r\"\"\"\n Here we provide a specific implementation for `compute_convergence_delta`\n which is based on a common property among gradient-based attribution algorithms.\n In the literature sometimes it is also called completeness axiom. Completeness\n axiom states that the sum of the attribution must be equal to the differences of\n NN Models's function at its end and start points. In other words:\n sum(attributions) - (F(end_point) - F(start_point)) is close to zero.\n Returned delta of this method is defined as above stated difference.\n\n This implementation assumes that both the `start_point` and `end_point` have\n the same shape and dimensionality. It also assumes that the target must have\n the same number of examples as the `start_point` and the `end_point` in case\n it is provided in form of a list or a non-singleton tensor.\n\n Args:\n\n attributions (tensor or tuple of tensors): Precomputed attribution\n scores. The user can compute those using any attribution\n algorithm. It is assumed the the shape and the\n dimensionality of attributions must match the shape and\n the dimensionality of `start_point` and `end_point`.\n It also assumes that the attribution tensor's\n dimension 0 corresponds to the number of\n examples, and if multiple input tensors are provided,\n the examples must be aligned appropriately.\n start_point (tensor or tuple of tensors, optional): `start_point`\n is passed as an input to model's forward function. It\n is the starting point of attributions' approximation.\n It is assumed that both `start_point` and `end_point`\n have the same shape and dimensionality.\n end_point (tensor or tuple of tensors): `end_point`\n is passed as an input to model's forward function. It\n is the end point of attributions' approximation.\n It is assumed that both `start_point` and `end_point`\n have the same shape and dimensionality.\n target (int, tuple, tensor or list, optional): Output indices for\n which gradients are computed (for classification cases,\n this is usually the target class).\n If the network returns a scalar value per example,\n no target index is necessary.\n For general 2D outputs, targets can be either:\n\n - a single integer or a tensor containing a single\n integer, which is applied to all input examples\n\n - a list of integers or a 1D tensor, with length matching\n the number of examples in inputs (dim 0). Each integer\n is applied as the target for the corresponding example.\n\n For outputs with > 2 dimensions, targets can be either:\n\n - A single tuple, which contains #output_dims - 1\n elements. This target index is applied to all examples.\n\n - A list of tuples with length equal to the number of\n examples in inputs (dim 0), and each tuple containing\n #output_dims - 1 elements. Each tuple is applied as the\n target for the corresponding example.\n\n Default: None\n additional_forward_args (any, optional): If the forward function\n requires additional arguments other than the inputs for\n which attributions should not be computed, this argument\n can be provided. It must be either a single additional\n argument of a Tensor or arbitrary (non-tuple) type or a\n tuple containing multiple additional arguments including\n tensors or any arbitrary python types. These arguments\n are provided to forward_func in order following the\n arguments in inputs.\n For a tensor, the first dimension of the tensor must\n correspond to the number of examples.\n `additional_forward_args` is used both for `start_point`\n and `end_point` when computing the forward pass.\n Default: None\n\n Returns:\n\n *tensor* of **deltas**:\n - **deltas** (*tensor*):\n This implementation returns convergence delta per\n sample. Deriving sub-classes may do any type of aggregation\n of those values, if necessary.\n \"\"\"\n end_point, start_point = _format_input_baseline(end_point, start_point)\n additional_forward_args = _format_additional_forward_args(\n additional_forward_args\n )\n # tensorizing start_point in case it is a scalar or one example baseline\n # If the batch size is large we could potentially also tensorize only one\n # sample and expand the output to the rest of the elements in the batch\n start_point = _tensorize_baseline(end_point, start_point)\n\n attributions = _format_tensor_into_tuples(attributions)\n\n # verify that the attributions and end_point match on 1st dimension\n for attribution, end_point_tnsr in zip(attributions, end_point):\n assert end_point_tnsr.shape[0] == attribution.shape[0], (\n \"Attributions tensor and the end_point must match on the first\"\n \" dimension but found attribution: {} and end_point: {}\".format(\n attribution.shape[0], end_point_tnsr.shape[0]\n )\n )\n\n num_samples = end_point[0].shape[0]\n _validate_input(end_point, start_point)\n _validate_target(num_samples, target)\n\n with torch.no_grad():\n start_out_sum = _sum_rows(\n _run_forward(\n self.forward_func, start_point, target, additional_forward_args\n )\n )\n\n end_out_sum = _sum_rows(\n _run_forward(\n self.forward_func, end_point, target, additional_forward_args\n )\n )\n row_sums = [_sum_rows(attribution) for attribution in attributions]\n attr_sum = torch.stack(\n [cast(Tensor, sum(row_sum)) for row_sum in zip(*row_sums)]\n )\n _delta = attr_sum - (end_out_sum - start_out_sum)\n return _delta\n\n\nclass PerturbationAttribution(Attribution):\n r\"\"\"\n All perturbation based attribution algorithms extend this class. It requires a\n forward function, which most commonly is the forward function of the model\n that we want to interpret or the model itself.\n \"\"\"\n\n def __init__(self, forward_func: Callable) -> None:\n r\"\"\"\n Args:\n\n forward_func (callable or torch.nn.Module): This can either be an instance\n of pytorch model or any modification of model's forward\n function.\n \"\"\"\n Attribution.__init__(self, forward_func)\n\n @property\n def multiplies_by_inputs(self):\n return True\n\n\nclass InternalAttribution(Attribution, Generic[ModuleOrModuleList]):\n layer: ModuleOrModuleList\n r\"\"\"\n Shared base class for LayerAttrubution and NeuronAttribution,\n attribution types that require a model and a particular layer.\n \"\"\"\n\n def __init__(\n self,\n forward_func: Callable,\n layer: ModuleOrModuleList,\n device_ids: Union[None, List[int]] = None,\n ) -> None:\n r\"\"\"\n Args:\n\n forward_func (callable or torch.nn.Module): This can either be an instance\n of pytorch model or any modification of model's forward\n function.\n layer (torch.nn.Module): Layer for which output attributions are computed.\n Output size of attribute matches that of layer output.\n device_ids (list(int)): Device ID list, necessary only if forward_func\n applies a DataParallel model, which allows reconstruction of\n intermediate outputs from batched results across devices.\n If forward_func is given as the DataParallel model itself,\n then it is not necessary to provide this argument.\n \"\"\"\n Attribution.__init__(self, forward_func)\n self.layer = layer\n self.device_ids = device_ids\n\n\nclass LayerAttribution(InternalAttribution):\n r\"\"\"\n Layer attribution provides attribution values for the given layer, quanitfying\n the importance of each neuron within the given layer's output. The output\n attribution of calling attribute on a LayerAttribution object always matches\n the size of the layer output.\n \"\"\"\n\n def __init__(\n self,\n forward_func: Callable,\n layer: ModuleOrModuleList,\n device_ids: Union[None, List[int]] = None,\n ) -> None:\n r\"\"\"\n Args:\n\n forward_func (callable or torch.nn.Module): This can either be an instance\n of pytorch model or any modification of model's forward\n function.\n layer (torch.nn.Module): Layer for which output attributions are computed.\n Output size of attribute matches that of layer output.\n device_ids (list(int)): Device ID list, necessary only if forward_func\n applies a DataParallel model, which allows reconstruction of\n intermediate outputs from batched results across devices.\n If forward_func is given as the DataParallel model itself,\n then it is not necessary to provide this argument.\n \"\"\"\n InternalAttribution.__init__(self, forward_func, layer, device_ids)\n\n @staticmethod\n def interpolate(\n layer_attribution: Tensor,\n interpolate_dims: Union[int, Tuple[int, ...]],\n interpolate_mode: str = \"nearest\",\n ) -> Tensor:\n r\"\"\"\n Interpolates given 3D, 4D or 5D layer attribution to given dimensions.\n This is often utilized to upsample the attribution of a convolutional layer\n to the size of an input, which allows visualizing in the input space.\n\n Args:\n\n layer_attribution (torch.Tensor): Tensor of given layer attributions.\n interpolate_dims (int or tuple): Upsampled dimensions. The\n number of elements must be the number of dimensions\n of layer_attribution - 2, since the first dimension\n corresponds to number of examples and the second is\n assumed to correspond to the number of channels.\n interpolate_mode (str): Method for interpolation, which\n must be a valid input interpolation mode for\n torch.nn.functional. These methods are\n \"nearest\", \"area\", \"linear\" (3D-only), \"bilinear\"\n (4D-only), \"bicubic\" (4D-only), \"trilinear\" (5D-only)\n based on the number of dimensions of the given layer\n attribution.\n\n Returns:\n *tensor* of upsampled **attributions**:\n - **attributions** (*tensor*):\n Upsampled layer attributions with first 2 dimensions matching\n slayer_attribution and remaining dimensions given by\n interpolate_dims.\n \"\"\"\n return F.interpolate(layer_attribution, interpolate_dims, mode=interpolate_mode)\n\n\nclass NeuronAttribution(InternalAttribution):\n r\"\"\"\n Neuron attribution provides input attribution for a given neuron, quanitfying\n the importance of each input feature in the activation of a particular neuron.\n Calling attribute on a NeuronAttribution object requires also providing\n the index of the neuron in the output of the given layer for which attributions\n are required.\n The output attribution of calling attribute on a NeuronAttribution object\n always matches the size of the input.\n \"\"\"\n\n def __init__(\n self,\n forward_func: Callable,\n layer: Module,\n device_ids: Union[None, List[int]] = None,\n ) -> None:\n r\"\"\"\n Args:\n\n forward_func (callable or torch.nn.Module): This can either be an instance\n of pytorch model or any modification of model's forward\n function.\n layer (torch.nn.Module): Layer for which output attributions are computed.\n Output size of attribute matches that of layer output.\n device_ids (list(int)): Device ID list, necessary only if forward_func\n applies a DataParallel model, which allows reconstruction of\n intermediate outputs from batched results across devices.\n If forward_func is given as the DataParallel model itself,\n then it is not necessary to provide this argument.\n \"\"\"\n InternalAttribution.__init__(self, forward_func, layer, device_ids)\n\n attribute: Callable\n r\"\"\"\n This method computes and returns the neuron attribution values for each\n input tensor. Deriving classes are responsible for implementing\n its logic accordingly.\n\n Specific attribution algorithms that extend this class take relevant\n arguments.\n\n Args:\n\n inputs: A single high dimensional input tensor or a tuple of them.\n neuron_selector (int or tuple): Tuple providing index of neuron in output\n of given layer for which attribution is desired. Length of\n this tuple must be one less than the number of\n dimensions in the output of the given layer (since\n dimension 0 corresponds to number of examples).\n\n Returns:\n\n *tensor* or tuple of *tensors* of **attributions**:\n - **attributions** (*tensor* or tuple of *tensors*):\n Attribution values for\n each input vector. The `attributions` have the\n dimensionality of inputs.\n \"\"\"\n"
] | [
[
"torch.mm",
"torch.norm",
"torch.Tensor",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.gather",
"torch.linalg.norm",
"torch.numel",
"torch.topk",
"torch.argsort"
],
[
"torch.no_grad",
"torch.nn.functional.interpolate"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.