repo_name
stringlengths 8
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence |
---|---|---|---|---|
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')"
] | [
[
"numpy.meshgrid",
"matplotlib.pyplot.figure",
"numpy.std",
"numpy.arange",
"numpy.shape",
"numpy.array",
"matplotlib.colors.to_rgb",
"matplotlib.gridspec.GridSpec",
"numpy.linspace",
"matplotlib.gridspec.GridSpecFromSubplotSpec",
"numpy.mean"
]
] |
iqbal-lab-org/pandora_paper_roc | [
"bb21c76faefa8021c86c3be9d77b8b5999fe2ef5"
] | [
"pipeline/scripts/calculate_recall_per_sample_vs_nb_of_samples.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"
] | [
[
"pandas.concat"
]
] |
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.reshape",
"numpy.asarray",
"tensorflow.train.Int64List",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.train.BytesList"
]
] |
Dakror/OpenMDAO | [
"3650622e0e96bed6979991bd096186c85050738f"
] | [
"openmdao/devtools/memory.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"
] | [
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots"
]
] |
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"
]
] |
amnaabbassi/shapash | [
"6c867c8b1724f2737369557f8db056cb0027999b"
] | [
"tests/unit_tests/utils/test_explanation_metrics.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"
] | [
[
"numpy.append",
"pandas.DataFrame",
"sklearn.linear_model.LinearRegression",
"numpy.array_equal",
"numpy.array",
"numpy.random.randint"
]
] |
roizhv22/IML.HUJI | [
"b6efdf4ca21ef5cf33da222d74330a19e2177527"
] | [
"exercises/ex4/sub/decision_stump.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"
] | [
[
"numpy.ones",
"numpy.sign",
"numpy.argsort",
"numpy.abs",
"numpy.sort",
"numpy.where"
]
] |
gist-ailab/FSCE | [
"94ba3f4737d5e40af795db49b8c6914526c912b6"
] | [
"fsdet/modeling/meta_arch/rcnn.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"
] | [
[
"numpy.concatenate",
"torch.device",
"torch.Tensor"
]
] |
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"
] | [
[
"tensorflow.placeholder",
"tensorflow.logging.info",
"numpy.var",
"numpy.stack",
"numpy.reshape",
"tensorflow.variable_scope",
"tensorflow.global_variables",
"numpy.arange",
"numpy.hstack",
"tensorflow.train.Saver",
"numpy.array",
"tensorflow.GPUOptions",
"tensorflow.ConfigProto",
"numpy.mean"
]
] |
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"
] | [
[
"pandas.DataFrame",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
]
] |
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.array",
"numpy.log10",
"numpy.unique",
"numpy.argsort"
]
] |
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.Series",
"matplotlib.pyplot.xticks",
"pandas.read_csv",
"pandas.DataFrame",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
]
] |
yumaloop/predwm | [
"9cf757b5f8b13cff8da325838c8685700162754d"
] | [
"carracing/prednet/rnn.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"
] | [
[
"tensorflow.reduce_logsumexp",
"tensorflow.reshape",
"tensorflow.variable_scope",
"tensorflow.contrib.rnn.DropoutWrapper",
"tensorflow.nn.dynamic_rnn",
"numpy.copy",
"tensorflow.Variable",
"tensorflow.split",
"tensorflow.global_variables_initializer",
"tensorflow.device",
"tensorflow.Graph",
"numpy.random.rand",
"tensorflow.clip_by_value",
"numpy.round",
"numpy.zeros",
"tensorflow.nn.xw_plus_b",
"tensorflow.Session",
"numpy.random.standard_cauchy",
"numpy.array",
"tensorflow.placeholder",
"tensorflow.train.AdamOptimizer",
"tensorflow.reduce_mean",
"numpy.random.randn",
"numpy.exp",
"tensorflow.trainable_variables",
"tensorflow.exp",
"numpy.sqrt",
"numpy.concatenate",
"tensorflow.get_variable"
]
] |
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"
]
] |
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.ones_like",
"torch.as_tensor",
"torch.argsort",
"torch.zeros_like",
"numpy.argsort",
"torch.cuda.amp.autocast",
"torch.arange",
"torch.any",
"torch.meshgrid",
"torch.abs",
"torch.zeros",
"torch.unique",
"torch.cat",
"torch.mean"
]
] |
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"
]
] |
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.stack",
"torch.flatten",
"torch.tensor",
"torch.utils.data._utils.collate.default_collate"
]
] |
uc-eqgeo/rnc2-earthquakes | [
"cfa6a68ab4bb3fee7a06683683f131d6413c53d1"
] | [
"src/rsqsim_api/rsqsim_api/io/read_utils.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"
] | [
[
"numpy.load",
"numpy.fromfile",
"numpy.zeros",
"pandas.read_csv",
"pandas.DataFrame",
"numpy.hstack",
"numpy.array",
"numpy.unique",
"numpy.loadtxt"
]
] |
w1ll1am-davis/lecture0 | [
"0c1ae34c69c9ff236457f52897af14839a4839e8"
] | [
"ocr/generate_samples.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"
] | [
[
"numpy.random.uniform",
"numpy.ones",
"numpy.zeros",
"numpy.random.normal",
"numpy.array",
"numpy.random.randint"
]
] |
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.inv",
"numpy.linalg.det",
"numpy.matrix.round",
"numpy.nditer"
]
] |
STAR-Center/selfSupervisedDescriptor | [
"f1fee51aee64914faf0a0af78cf9854a7230552c"
] | [
"data/3dmatch/desc2txt.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"
] | [
[
"numpy.savetxt"
]
] |
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"
]
] |
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.sum",
"torch.empty_like",
"torch.randint",
"torch.randn",
"torch.manual_seed",
"torch.no_grad",
"numpy.random.seed",
"torch.nn.LogSoftmax",
"torch.cuda.amp.custom_fwd",
"torch.nn.Conv2d",
"torch.abs",
"torch.log_softmax",
"torch.softmax"
]
] |
cvoelcker/spn-pytorch-experiments | [
"495d1fddf00f76fe28e926f7e558b26089e5428e"
] | [
"src/models/models.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"
] | [
[
"torch.logsumexp",
"torch.nn.init.kaiming_normal_",
"torch.ones",
"torch.stack",
"torch.nn.Linear",
"torch.nn.BatchNorm1d",
"numpy.random.permutation",
"torch.nn.init.xavier_normal_",
"torch.rand",
"torch.nn.ModuleList",
"torch.device"
]
] |
tamuhey/pymatgen | [
"cf1793f0af59844ea9222d973212e3ab83e58209"
] | [
"pymatgen/analysis/structure_analyzer.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"
] | [
[
"numpy.sum",
"numpy.any",
"numpy.cross",
"numpy.fill_diagonal",
"scipy.spatial.Voronoi",
"matplotlib.pyplot.figure",
"numpy.reshape",
"matplotlib.pyplot.title",
"matplotlib.pyplot.barh",
"numpy.where",
"numpy.mean",
"numpy.ceil",
"numpy.zeros",
"numpy.max",
"numpy.linalg.norm",
"matplotlib.pyplot.grid",
"numpy.array",
"numpy.dot",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.xlabel"
]
] |
cjs220/alre_experiments | [
"bb1969e1650368357b8e76d3b4f262dedd47f752"
] | [
"util/general.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"
] | [
[
"pandas.Timestamp.now",
"numpy.random.seed",
"tensorflow.random.set_seed"
]
] |
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"
]
] |
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.MaxPool2d",
"torch.nn.ReLU",
"torch.nn.Dropout"
]
] |
mealworm/gammapy | [
"a838b2ca347dd6321f8da4e4097a33150d7b9be6"
] | [
"gammapy/utils/fits.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"
] | [
[
"numpy.arange",
"numpy.append"
]
] |
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"
]
] |
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.array",
"numpy.ones",
"numpy.append",
"numpy.insert"
],
[
"numpy.einsum",
"numpy.dot",
"numpy.random.seed",
"numpy.random.rand"
]
] |
mjseong0414/SPA_Radar_mmdet3d | [
"ae4eee101a5665b72586d3d5db06832bf45b3b33"
] | [
"tools/test.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"
] | [
[
"torch.cuda.current_device"
]
] |
Magnety/tuFramework | [
"b31cb34d476ef306b52da955021f93c91c14ddf4"
] | [
"tuframework/training/network_training/nnUNet_variants/architectural_variants/nnUNetTrainerV2_noDeepSupervision.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"
] | [
[
"torch.cuda.is_available"
]
] |
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.array",
"numpy.random.shuffle",
"numpy.random.seed",
"numpy.zeros"
]
] |
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.array",
"numpy.reshape"
]
] |
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"
]
] |
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.arctan2",
"numpy.average",
"numpy.argsort",
"numpy.column_stack",
"numpy.asarray",
"numpy.cos",
"numpy.arange",
"numpy.std",
"numpy.max",
"numpy.power",
"numpy.min",
"numpy.isnan",
"numpy.sin",
"numpy.meshgrid",
"numpy.linspace"
]
] |
frankwhzhang/Paddle | [
"131b1dc3240e53ea295cc49323bb2a7e7dcc717f"
] | [
"python/paddle/fluid/tests/unittests/test_bilinear_interp_op.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"
] | [
[
"numpy.allclose",
"numpy.ones",
"numpy.transpose",
"numpy.zeros",
"numpy.random.random",
"numpy.array",
"numpy.random.randint"
]
] |
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 "
] | [
[
"torch.no_grad",
"numpy.asarray",
"torch.cuda.is_available",
"matplotlib.pyplot.ylabel",
"numpy.transpose",
"torch.save",
"matplotlib.pyplot.title",
"matplotlib.pyplot.hist",
"torch.Tensor",
"matplotlib.pyplot.axis",
"numpy.max",
"numpy.min",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"torch.nn.MSELoss",
"matplotlib.pyplot.switch_backend",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.array",
"numpy.concatenate",
"matplotlib.pyplot.xlabel"
]
] |
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"
]
] |
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.eye",
"pandas.Series",
"pandas.DataFrame",
"numpy.linalg.det",
"numpy.abs",
"numpy.expand_dims",
"numpy.array",
"numpy.dot"
]
] |
sijunhe/tensorflow | [
"d7e858192d1de827bc03705ac62e1bd38daf06d8"
] | [
"tensorflow/python/autograph/impl/conversion_test.py"
] | [
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"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"
] | [
[
"tensorflow.python.autograph.core.config.DoNotConvert",
"tensorflow.python.autograph.impl.conversion.convert_entity_to_ast",
"tensorflow.python.autograph.impl.conversion.is_whitelisted_for_graph",
"tensorflow.python.platform.test.main",
"tensorflow.python.autograph.pyct.compiler.ast_to_source",
"tensorflow.python.autograph.core.converter.ConversionOptions",
"tensorflow.python.framework.constant_op.constant"
]
] |
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.functional.log_softmax",
"torch.nn.Linear",
"torch.nn.functional.dropout"
]
] |
quanpn90/SpeechGAN | [
"b2aa923ac40474bd7a6fa2acfd290eb2770e0972"
] | [
"onmt/models/relative_transformer.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"
] | [
[
"torch.empty",
"torch.set_printoptions",
"torch.no_grad",
"torch.arange",
"torch.nn.ModuleList",
"torch.LongTensor",
"torch.cat",
"torch.Tensor"
]
] |
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"
]
] |
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"
]
] |
Z223I/deephyper | [
"4fd1054dc22f15197567bdd93c6e7a95a614b8e2"
] | [
"deephyper/nas/space/op/op1d.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"
] | [
[
"tensorflow.keras.initializers.glorot_uniform",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.MaxPooling1D",
"tensorflow.keras.layers.Conv1D",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.layers.BatchNormalization"
]
] |
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.read_csv",
"pandas.read_excel",
"pandas.DataFrame",
"pandas.merge",
"pandas.concat"
]
] |
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"
]
] |
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.utils.data.DataLoader",
"torch.load",
"torch.autograd.Variable",
"numpy.array",
"torch.sigmoid",
"numpy.loadtxt"
]
] |
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",
"torch.cuda.get_device_name",
"numpy.zeros"
]
] |
liyi193328/warp_seq2seq | [
"e5cbed8305aa27a76eab3e4250e0d30d96058f96"
] | [
"seq2seq/features/extend_ids.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"
] | [
[
"tensorflow.equal",
"tensorflow.gather",
"tensorflow.shape",
"tensorflow.reshape",
"tensorflow.unstack",
"tensorflow.scatter_nd",
"tensorflow.range",
"tensorflow.cond",
"tensorflow.cast",
"tensorflow.while_loop",
"tensorflow.less",
"tensorflow.TensorArray",
"tensorflow.convert_to_tensor",
"tensorflow.where",
"tensorflow.Session",
"tensorflow.constant"
]
] |
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"
]
] |
lichangao1826/ml-contest | [
"6c5350a0006d79b536df52215d18a989875135e1"
] | [
"infer/data_fountain_529_ner.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"
] | [
[
"numpy.array"
]
] |
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.sum",
"torch.arange",
"torch.exp"
]
] |
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"
] | [
[
"scipy.integrate.quad",
"scipy.stats.norm.pdf",
"numpy.random.randn",
"scipy.optimize.brentq",
"numpy.maximum",
"numpy.std",
"numpy.average",
"scipy.stats.norm.cdf"
]
] |
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"
]
] |
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"
]
] |
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.empty",
"numpy.zeros",
"scipy.sparse.csr_matrix",
"numpy.asanyarray",
"numpy.arange",
"numpy.prod",
"numpy.sqrt",
"numpy.kron",
"numpy.mean"
]
] |
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.read_csv",
"sklearn.preprocessing.MinMaxScaler",
"pandas.concat",
"sklearn.linear_model.LogisticRegression",
"numpy.where",
"sklearn.model_selection.train_test_split"
]
] |
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.nn.softmax_cross_entropy_with_logits",
"tensorflow.reshape",
"tensorflow.nn.l2_loss",
"tensorflow.name_scope",
"tensorflow.concat",
"tensorflow.nn.dropout",
"tensorflow.nn.max_pool",
"tensorflow.device",
"tensorflow.constant",
"tensorflow.expand_dims",
"tensorflow.random_uniform",
"tensorflow.cast",
"tensorflow.nn.xw_plus_b",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.nn.embedding_lookup",
"tensorflow.placeholder",
"tensorflow.nn.bias_add",
"tensorflow.truncated_normal",
"tensorflow.reduce_mean",
"tensorflow.nn.conv2d",
"tensorflow.argmax"
]
] |
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.sum",
"numpy.dtype",
"numpy.ma.masked_equal",
"numpy.issubdtype",
"numpy.any",
"numpy.abs",
"numpy.asanyarray",
"numpy.exp",
"numpy.lib.stride_tricks.as_strided",
"numpy.log10",
"numpy.angle",
"numpy.prod",
"numpy.array",
"numpy.iscomplexobj",
"numpy.concatenate",
"numpy.memmap"
]
] |
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.Quantize",
"torch.nn.quantized.Conv2d",
"torch.randn",
"torch.tensor",
"torch.nn.quantized.DeQuantize",
"torch.zeros"
]
] |
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.load",
"numpy.reshape",
"torch.tensor",
"numpy.cos",
"torch.zeros",
"numpy.sin"
]
] |
WeichenXu123/koalas | [
"224cbe4a1c7a2b12976069762379d0e77e46750b"
] | [
"databricks/koalas/tests/test_frame_plot.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"
] | [
[
"pandas.date_range",
"pandas.DataFrame",
"numpy.random.rand",
"matplotlib.pyplot.close",
"matplotlib.use"
]
] |
raybellwaves/geopandas | [
"592abf7f596ef4cf9b78c2706f69e83d8005821f"
] | [
"geopandas/base.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"
] | [
[
"numpy.asarray",
"pandas.Series",
"pandas.DataFrame"
]
] |
kongjy/pycroscopy | [
"fd02ac735a1194d2a5687183fafe00368ed8a3ca"
] | [
"pycroscopy/io/translators/time_series.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"
] | [
[
"numpy.mean",
"numpy.arange",
"numpy.sqrt",
"numpy.zeros"
]
] |
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)"
] | [
[
"pandas.DataFrame",
"numpy.argmax",
"numpy.squeeze"
]
] |
laekov/akg | [
"5316b8cb2340bbf71bdc724dc9d81513a67b3104"
] | [
"tests/common/test_run/avgpool_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"
] | [
[
"numpy.mean",
"numpy.full",
"numpy.zeros"
]
] |
billbrod/spatial-frequency-preferences | [
"4a83fe209bbbf8130f297bcc6e17cb79b36006c2"
] | [
"sfp/plotting.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"
] | [
[
"numpy.ones",
"pandas.Series",
"matplotlib.pyplot.tight_layout",
"numpy.asarray",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.imshow",
"numpy.log",
"matplotlib.pyplot.plot",
"numpy.vstack",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.gca",
"sklearn.linear_model.LinearRegression",
"numpy.log10",
"matplotlib.use",
"numpy.linspace",
"numpy.sqrt",
"matplotlib.colors.Normalize.__init__",
"numpy.zeros",
"numpy.ceil",
"numpy.median",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.close",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.fill_between",
"numpy.array",
"numpy.percentile",
"numpy.log2",
"numpy.arctan2",
"numpy.interp",
"numpy.round",
"numpy.sin"
]
] |
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.backend.softplus",
"tensorflow.keras.layers.ZeroPadding2D",
"tensorflow.keras.layers.experimental.SyncBatchNormalization",
"tensorflow.keras.layers.Add"
],
[
"tensorflow.zeros",
"tensorflow.ones",
"tensorflow.tensor_scatter_nd_update",
"tensorflow.reduce_all"
]
] |
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.preprocessing.image.img_to_array",
"numpy.expand_dims",
"tensorflow.keras.models.load_model"
]
] |
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.sqrt",
"numpy.errstate",
"numpy.log",
"numpy.isnan",
"numpy.array"
]
] |
Mbompr/deepr | [
"1fb28e15aeeac6ef2d8e5b678feb380f2b1951f2"
] | [
"deepr/hooks/num_params.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"
] | [
[
"tensorflow.trainable_variables",
"tensorflow.global_variables"
]
] |
diego-mazon/statsmodels | [
"af8b5b5dc78acb600ffd08cda6bd9b1ca5200e10"
] | [
"statsmodels/tsa/tests/test_arima.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"
] | [
[
"numpy.ones",
"pandas.Series",
"numpy.diff",
"numpy.random.seed",
"numpy.asarray",
"numpy.ones_like",
"numpy.log",
"pandas.period_range",
"numpy.testing.assert_almost_equal",
"numpy.genfromtxt",
"numpy.mean",
"pandas.date_range",
"numpy.zeros",
"pandas.read_csv",
"pandas.Index",
"numpy.testing.assert_raises",
"pandas.DatetimeIndex",
"numpy.cumsum",
"numpy.empty",
"pandas.DataFrame",
"numpy.random.randn",
"numpy.random.random",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.concatenate",
"numpy.random.randint"
]
] |
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.MaxPool2d",
"torch.nn.init.kaiming_normal_",
"torch.nn.Linear",
"torch.load",
"torch.nn.AdaptiveAvgPool2d",
"torch.flatten",
"torch.nn.Conv2d",
"torch.nn.Sequential",
"torch.nn.ReLU"
]
] |
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.round",
"numpy.hstack",
"numpy.all",
"numpy.zeros"
]
] |
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"
]
] |
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.sum",
"numpy.ones",
"torch.ones",
"numpy.zeros",
"torch.exp",
"torch.cuda.is_available",
"numpy.random.rand"
]
] |
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.random.uniform",
"numpy.ones",
"pandas.Series",
"numpy.array",
"pandas._testing.assert_produces_warning",
"numpy.dtype",
"pandas.DataFrame",
"numpy.asarray",
"numpy.errstate",
"pandas.core.dtypes.common.is_object_dtype",
"pandas._testing.assert_sp_array_equal",
"pandas._testing.assert_series_equal",
"pandas.concat",
"numpy.isnan",
"pandas.SparseDtype",
"numpy.random.randint",
"pandas.arrays.SparseArray",
"pandas.isna"
]
] |
online-ml/creme | [
"60872844e6052b5ef20e4075aea30f9031377136"
] | [
"river/drift/kswin.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"
] | [
[
"scipy.stats.ks_2samp"
]
] |
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.nn.softmax_cross_entropy_with_logits",
"tensorflow.reshape",
"tensorflow.variable_scope",
"tensorflow.contrib.keras.initializers.he_normal",
"tensorflow.matmul",
"tensorflow.squeeze",
"tensorflow.name_scope",
"tensorflow.concat",
"tensorflow.contrib.layers.variance_scaling_initializer",
"tensorflow.device",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.transpose",
"tensorflow.constant_initializer",
"tensorflow.get_collection",
"tensorflow.expand_dims",
"tensorflow.layers.batch_normalization",
"tensorflow.layers.max_pooling1d",
"tensorflow.random_uniform",
"tensorflow.cast",
"tensorflow.nn.embedding_lookup",
"tensorflow.pad",
"tensorflow.placeholder",
"tensorflow.reduce_mean",
"tensorflow.nn.conv2d",
"tensorflow.nn.conv1d",
"tensorflow.argmax",
"tensorflow.nn.relu",
"tensorflow.get_variable"
]
] |
waikato-datamining/cntk | [
"1b626407ef750dfbd4ad66fe9aed28487f2a4441"
] | [
"2.6/faster_rcnn/FasterRCNN/FasterRCNN_eval.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"
] | [
[
"numpy.array",
"numpy.hstack",
"numpy.where"
]
] |
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.summary.scalar",
"tensorflow.reduce_max",
"tensorflow.reshape",
"tensorflow.variable_scope",
"tensorflow.squeeze",
"tensorflow.get_variable_scope",
"tensorflow.summary.merge",
"tensorflow.train.get_global_step",
"tensorflow.nn.softmax",
"tensorflow.reduce_sum",
"tensorflow.summary.histogram",
"tensorflow.contrib.layers.summarize_activation",
"tensorflow.reduce_min",
"tensorflow.shape",
"tensorflow.get_collection",
"tensorflow.to_float",
"tensorflow.placeholder",
"tensorflow.range",
"tensorflow.squared_difference",
"tensorflow.train.AdamOptimizer",
"tensorflow.reduce_mean",
"tensorflow.log",
"tensorflow.contrib.layers.fully_connected"
]
] |
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.Flatten",
"tensorflow.keras.layers.Dense"
]
] |
henriqueribeiro/pandas | [
"996f361f8e6986ea1c65ccb164a4c585e1f4a027"
] | [
"pandas/core/indexes/datetimes.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"
] | [
[
"pandas.core.common.values_from_object",
"pandas.core.arrays.datetimelike.validate_tz_from_dtype",
"pandas._libs.tslibs.parsing.parse_time_string",
"pandas.tseries.offsets.Hour",
"pandas.core.dtypes.concat._concat_compat",
"numpy.asarray",
"pandas.core.indexes.base.Index.join",
"pandas.core.dtypes.common.ensure_int64",
"pandas._libs.Timestamp",
"pandas.core.dtypes.common.is_integer",
"numpy.ndarray.__setstate__",
"pandas._libs.tslibs.timezones.maybe_get_tz",
"pandas.core.dtypes.common.pandas_dtype",
"pandas.core.dtypes.common.is_list_like",
"pandas.core.arrays.datetimes.DatetimeArrayMixin.normalize",
"pandas.tseries.frequencies.get_period_alias",
"pandas.core.indexes.base.Index.union",
"pandas.core.arrays.datetimelike.maybe_infer_freq",
"pandas.core.dtypes.common.is_float",
"pandas.core.indexes.base.Index.get_value",
"pandas.tseries.offsets.Minute",
"pandas.util._decorators.deprecate_kwarg",
"pandas.core.tools.datetimes.to_datetime",
"pandas.core.dtypes.common.is_datetime64_ns_dtype",
"pandas.core.indexes.base.Index.slice_indexer",
"pandas.core.indexes.base.Index.intersection",
"pandas.core.indexes.datetimelike.DatetimeIndexOpsMixin._join_i8_wrapper",
"pandas._libs.tslib.format_array_from_datetime",
"pandas.core.arrays.datetimelike.validate_periods",
"numpy.delete",
"pandas.core.dtypes.common.is_datetime64_dtype",
"pandas.io.formats.format._get_format_datetime64",
"pandas.core.indexes.numeric.Float64Index",
"pandas._libs.lib.infer_dtype",
"pandas.core.indexes.base.Index",
"pandas.core.tools.datetimes.to_time",
"pandas.tseries.offsets.Second",
"pandas.compat.set_function_name",
"pandas.core.dtypes.common.is_bool_dtype",
"pandas.tseries.frequencies.to_offset",
"pandas.core.arrays.datetimes._to_m8",
"pandas.tseries.offsets.generate_range",
"pandas.core.dtypes.common.is_period_dtype",
"pandas.core.arrays.datetimes.DatetimeArrayMixin.to_julian_date",
"pandas.io.formats.format._is_dates_only",
"pandas._libs.tslibs.timezones.tz_compare",
"pandas._libs.tslibs.timezones.tz_standardize",
"pandas.io.formats.format._get_format_datetime64_from_values",
"pandas.util._decorators.cache_readonly",
"pandas.core.common._any_none",
"pandas._libs.tslib.ints_to_pydatetime",
"pandas.core.dtypes.common.is_scalar",
"pandas.core.dtypes.missing.isna",
"pandas.tseries.offsets.Day",
"pandas.util._decorators.Substitution",
"pandas.util._decorators.Appender",
"pandas.core.common.maybe_box",
"pandas.core.indexes.base.Index.get_loc",
"numpy.empty",
"pandas.tseries.frequencies.Resolution.get_reso",
"pandas.tseries.offsets.CDay",
"pandas.core.dtypes.common.is_datetimetz",
"pandas.core.dtypes.common.is_dtype_equal",
"pandas._libs.tslibs.ccalendar.get_days_in_month",
"pandas.core.dtypes.common.is_string_like",
"pandas.core.indexes.period.PeriodIndex",
"pandas._libs.tslibs.conversion.ensure_datetime64ns",
"numpy.array",
"pandas._libs.tslibs.fields.get_time_micros",
"pandas.core.dtypes.common.is_integer_dtype"
]
] |
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.zeros",
"numpy.abs",
"numpy.cos",
"numpy.floor",
"numpy.random.normal",
"numpy.sin"
]
] |
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.colors.ListedColormap",
"matplotlib.pyplot.figure",
"numpy.argmax",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.close",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.scatter"
]
] |
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",
"matplotlib.pyplot.savefig",
"numpy.log",
"matplotlib.pyplot.subplots"
]
] |
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"
]
] |
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.DataFrame",
"numpy.random.randn",
"pandas.Categorical",
"numpy.int64",
"numpy.arange",
"numpy.all",
"numpy.array",
"pandas.Timestamp",
"pandas.isna"
]
] |
papamarkou/bnn_mcmc_examples | [
"297cdb1e74335860989bebdb4ff6f6322b6adc06"
] | [
"bnn_mcmc_examples/examples/mlp/hawks/prior/benchmark_pred_accuracy_via_mean.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"
] | [
[
"numpy.empty",
"torch.argmax"
]
] |
mdovgialo/mne-python | [
"8ccc3999da6c15efa03840230c13aeb7bab5618d"
] | [
"mne/stats/tests/test_permutations.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"
] | [
[
"scipy.stats.ttest_1samp",
"numpy.random.default_rng",
"numpy.random.randn",
"numpy.random.seed",
"numpy.testing.assert_array_equal",
"scipy.sparse.eye",
"numpy.testing.assert_allclose",
"numpy.linspace"
]
] |
mathemusician/pytorch-lightning | [
"15fa5389387b3a220bc044dd30eb0be1e8f64944"
] | [
"tests/strategies/test_ddp_fully_sharded_with_full_state_dict.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"
] | [
[
"torch.nn.ReLU",
"torch.nn.Linear"
]
] |
christopherlovell/hyperion | [
"f65c253abf0bdf174a9302666bc2fec57f7ae7da"
] | [
"hyperion/dust/tests/test_mean_opacities.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"
] | [
[
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.close",
"numpy.testing.assert_allclose"
]
] |
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.histogram",
"numpy.nanmean",
"numpy.arange",
"numpy.log10",
"numpy.array",
"numpy.around",
"numpy.pad"
]
] |
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.allclose",
"numpy.reshape",
"numpy.asarray"
]
] |
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)"
] | [
[
"numpy.diff",
"pandas.read_csv",
"numpy.max",
"numpy.min",
"numpy.array",
"numpy.std",
"numpy.where"
]
] |
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.min",
"torch.stack",
"torch.as_tensor",
"torch.max",
"torch.device"
]
] |
i-jones/captum | [
"567ec6fc67ab85ce07d075b25428be22bb65e31b"
] | [
"captum/influence/_core/similarity_influence.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"
] | [
[
"torch.utils.data.DataLoader",
"torch.linalg.norm",
"torch.argsort",
"torch.mm",
"torch.gather",
"torch.norm",
"torch.topk",
"torch.numel",
"torch.cat",
"torch.Tensor"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.