repo_name
stringlengths
8
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
mfkiwl/OpenXcvr
[ "9bea6efd03cd246f16982f0fadafed684ac5ce1c" ]
[ "firmware/audio_agc.py" ]
[ "from baremetal import *\nfrom math import log, pi\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport sys\nfrom math import log, ceil\nfrom settings import Settings\nfrom measure_magnitude import measure_magnitude\nfrom calculate_gain import calculate_gain\nfrom slow_barrel_shifter import slow_barrel_shifter\n\n\ndef audio_agc(clk, data, stb, audio_attenuation, agc_speed):\n\n #when squelch is active blank the input to the AGC, so that the\n #noise in FM mode doesn't turn down the gain\n squelch_active = (audio_attenuation == 18)\n\n #calculate magnitude and DC\n magnitude = measure_magnitude(clk, data, stb, agc_speed, reset=squelch_active)\n\n #rescale the data \n setpoint = int((2**(data.subtype.bits-1)) * 0.5)\n gain = calculate_gain(clk, magnitude, setpoint)\n gain = gain.subtype.select(gain < 1, gain, 1)\n\n #keep all the bits so we can handle overflowing values\n bits = data.subtype.bits\n data = data.resize(bits*2)\n data *= gain\n data = data.subtype.register(clk, d=data, init=0, en=stb)\n stb = stb.subtype.register(clk, d=stb)\n\n #soft clip any signals that have escaped the AGC\n maxval = setpoint\n minval = -setpoint\n positive_overflow = data > maxval\n positive_excess = (data - maxval) >> 1\n data = data.subtype.select(positive_overflow, data, positive_excess+maxval)\n negative_overflow = data < minval\n negative_excess = (data.subtype.constant(minval) - data) >> 1\n data = data.subtype.select(negative_overflow, data, -negative_excess+minval)\n data = data.subtype.register(clk, d=data, init=0, en=stb)\n stb = stb.subtype.register(clk, d=stb)\n\n #hard clamp signals that we couldn't clip\n maxval = (2**(bits-1))\n minval = -maxval\n positive_overflow = data > maxval\n data = data.subtype.select(positive_overflow, data, maxval)\n negative_overflow = data < minval\n data = data.subtype.select(negative_overflow, data, minval)\n data = data.subtype.register(clk, d=data, init=0, en=stb)\n stb = stb.subtype.register(clk, d=stb)\n\n #discard the extra bits\n data = data[bits-1:0]\n data = data.subtype.register(clk, d=data, init=0, en=stb)\n stb = stb.subtype.register(clk, d=stb)\n\n #apply additional attenuation (digital volume)\n audio_out, audio_out_stb = data, stb\n data, stb = slow_barrel_shifter(clk, data, audio_attenuation, stb, \"right\")\n\n return data, stb, audio_out, audio_out_stb, positive_overflow | negative_overflow\n\nif __name__ == \"__main__\" and \"sim\" in sys.argv:\n\n clk = Clock(\"clk\")\n audio_in = Signed(16).input(\"magnitude\")\n stb_in = Boolean().input(\"stb\")\n\n audio_out, stb_out, _ = audio_agc(clk, audio_in, stb_in, Unsigned(8).constant(0), Unsigned(8).constant(0))\n\n clk.initialise()\n response = []\n\n for i in range(100):\n audio_in.set(100)\n for i in range(100):\n stb_in.set(i==0)\n clk.tick()\n if stb_out.get():\n x = audio_out.get()\n response.append(x)\n audio_in.set(-100)\n for i in range(100):\n stb_in.set(i==0)\n clk.tick()\n if stb_out.get():\n x = audio_out.get()\n response.append(x)\n for i in range(100):\n audio_in.set(0)\n for i in range(100):\n stb_in.set(i==0)\n clk.tick()\n if stb_out.get():\n x = audio_out.get()\n response.append(x)\n for i in range(100):\n audio_in.set(100)\n for i in range(100):\n stb_in.set(i==0)\n clk.tick()\n if stb_out.get():\n x = audio_out.get()\n response.append(x)\n audio_in.set(-100)\n for i in range(100):\n stb_in.set(i==0)\n clk.tick()\n if stb_out.get():\n x = audio_out.get()\n response.append(x)\n\n plt.plot(response)\n plt.show()\n" ]
[ [ "matplotlib.pyplot.plot", "matplotlib.pyplot.show" ] ]
LocalLegend517/zenml
[ "0f9639a7a1014d893885263647bbe3b9b1a36d5f" ]
[ "src/zenml/integrations/plotly/visualizers/pipeline_lineage_visualizer.py" ]
[ "# Copyright (c) ZenML GmbH 2021. 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\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nfrom abc import abstractmethod\nfrom typing import Any\n\nimport pandas as pd\nimport plotly.express as px\nfrom plotly.graph_objs import Figure\n\nfrom zenml.logger import get_logger\nfrom zenml.post_execution import PipelineView\nfrom zenml.visualizers import BasePipelineVisualizer\n\nlogger = get_logger(__name__)\n\n# TODO [ENG-221]: This integration is working but not really doing much. We\n# should use plotly in more useful ways.\n\n\nclass PipelineLineageVisualizer(BasePipelineVisualizer):\n \"\"\"Visualize the lineage of runs in a pipeline using plotly.\"\"\"\n\n @abstractmethod\n def visualize(\n self, object: PipelineView, *args: Any, **kwargs: Any\n ) -> Figure:\n \"\"\"Creates a pipeline lineage diagram using plotly.\"\"\"\n logger.warning(\n \"This integration is not completed yet. Results might be unexpected.\"\n )\n\n category_dict = {}\n dimensions = [\"run\"]\n for run in object.runs:\n category_dict[run.name] = {\"run\": run.name}\n for step in run.steps:\n category_dict[run.name].update(\n {\n step.name: str(step.id),\n }\n )\n if step.name not in dimensions:\n dimensions.append(f\"{step.name}\")\n\n category_df = pd.DataFrame.from_dict(category_dict, orient=\"index\")\n\n category_df = category_df.reset_index()\n\n fig = px.parallel_categories(\n category_df,\n dimensions,\n color=None,\n labels=\"status\",\n )\n\n fig.show()\n return fig\n" ]
[ [ "pandas.DataFrame.from_dict" ] ]
Pakleung/Mixup-TransUnet
[ "d7d0ae264589cd46db8f5da1135e786f065c372d" ]
[ "models/encoder_layers.py" ]
[ "import tensorflow as tf\nimport tensorflow_addons as tfa\n\ntfk = tf.keras\ntfkl = tfk.layers\ntfm = tf.math\n\n\nclass AddPositionEmbs(tfkl.Layer):\n \"\"\"Adds (optionally learned) positional embeddings to the inputs.\"\"\"\n\n def __init__(self, trainable=True, **kwargs):\n super().__init__(trainable=trainable, **kwargs)\n self.trainable = trainable\n\n def build(self, input_shape):\n assert (\n len(input_shape) == 3\n ), f\"Number of dimensions should be 3, got {len(input_shape)}\"\n self.pe = tf.Variable(\n name=\"pos_embedding\",\n initial_value=tf.random_normal_initializer(stddev=0.06)(\n shape=(1, input_shape[1], input_shape[2])\n ),\n dtype=\"float32\",\n trainable=self.trainable,\n )\n\n def call(self, inputs):\n return inputs + tf.cast(self.pe, dtype=inputs.dtype)\n\n\nclass MultiHeadSelfAttention(tfkl.Layer):\n def __init__(self, *args, trainable=True, n_heads, **kwargs):\n super().__init__(trainable=trainable, *args, **kwargs)\n self.n_heads = n_heads\n\n def build(self, input_shape):\n hidden_size = input_shape[-1]\n n_heads = self.n_heads\n if hidden_size % n_heads != 0:\n raise ValueError(\n f\"embedding dimension = {hidden_size} should be divisible by number of heads = {n_heads}\"\n )\n self.hidden_size = hidden_size\n self.projection_dim = hidden_size // n_heads\n self.query_dense = tfkl.Dense(\n hidden_size, name=\"query\")\n self.key_dense = tfkl.Dense(\n hidden_size, name=\"key\")\n self.value_dense = tfkl.Dense(\n hidden_size, name=\"value\")\n self.combine_heads = tfkl.Dense(\n hidden_size, name=\"out\")\n\n # pylint: disable=no-self-use\n def attention(self, query, key, value):\n score = tf.matmul(query, key, transpose_b=True)\n dim_key = tf.cast(tf.shape(key)[-1], score.dtype)\n scaled_score = score / tf.math.sqrt(dim_key)\n weights = tf.nn.softmax(scaled_score, axis=-1)\n output = tf.matmul(weights, value)\n return output, weights\n\n def separate_heads(self, x, batch_size):\n x = tf.reshape(\n x, (batch_size, -1, self.n_heads, self.projection_dim))\n return tf.transpose(x, perm=[0, 2, 1, 3])\n\n def call(self, inputs):\n batch_size = tf.shape(inputs)[0]\n query = self.query_dense(inputs)\n key = self.key_dense(inputs)\n value = self.value_dense(inputs)\n query = self.separate_heads(query, batch_size)\n key = self.separate_heads(key, batch_size)\n value = self.separate_heads(value, batch_size)\n\n attention, weights = self.attention(query, key, value)\n attention = tf.transpose(attention, perm=[0, 2, 1, 3])\n concat_attention = tf.reshape(\n attention, (batch_size, -1, self.hidden_size))\n output = self.combine_heads(concat_attention)\n return output, weights\n\n\nclass TransformerBlock(tfkl.Layer):\n \"\"\"Implements a Transformer block.\"\"\"\n\n def __init__(self, *args, n_heads, mlp_dim, dropout, trainable=True, **kwargs):\n super().__init__(*args, trainable=trainable, **kwargs)\n self.n_heads = n_heads\n self.mlp_dim = mlp_dim\n self.dropout = dropout\n\n def build(self, input_shape):\n self.att = MultiHeadSelfAttention(\n n_heads=self.n_heads,\n name=\"MultiHeadDotProductAttention_1\",\n )\n self.mlpblock = tfk.Sequential(\n [\n tfkl.Dense(\n self.mlp_dim,\n activation=\"linear\",\n name=f\"{self.name}/Dense_0\"\n ),\n tfkl.Lambda(\n lambda x: tfk.activations.gelu(x, approximate=False)\n )\n if hasattr(tfk.activations, \"gelu\")\n else tfkl.Lambda(\n lambda x: tfa.activations.gelu(x, approximate=False)\n ),\n tfkl.Dropout(self.dropout),\n tfkl.Dense(\n input_shape[-1], name=f\"{self.name}/Dense_1\"),\n tfkl.Dropout(self.dropout),\n ],\n name=\"MlpBlock_3\",\n )\n self.layernorm1 = tfkl.LayerNormalization(\n epsilon=1e-6, name=\"LayerNorm_0\"\n )\n self.layernorm2 = tfkl.LayerNormalization(\n epsilon=1e-6, name=\"LayerNorm_2\"\n )\n self.dropout = tfkl.Dropout(self.dropout)\n\n def call(self, inputs, training):\n x = self.layernorm1(inputs)\n x, weights = self.att(x)\n x = self.dropout(x, training=training)\n x = x + inputs\n y = self.layernorm2(x)\n y = self.mlpblock(y)\n return x + y, weights\n" ]
[ [ "tensorflow.math.sqrt", "tensorflow.shape", "tensorflow.reshape", "tensorflow.nn.softmax", "tensorflow.matmul", "tensorflow.cast", "tensorflow.random_normal_initializer", "tensorflow.transpose" ] ]
rainwoodman/pandas
[ "671cf86a78e931a9c98ad72571ec65cd3c35d8a7" ]
[ "pandas/tests/strings/test_strings.py" ]
[ "from datetime import (\n datetime,\n timedelta,\n)\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n Series,\n isna,\n)\nimport pandas._testing as tm\n\n\ndef assert_series_or_index_equal(left, right):\n if isinstance(left, Series):\n tm.assert_series_equal(left, right)\n else: # Index\n tm.assert_index_equal(left, right)\n\n\ndef test_iter():\n # GH3638\n strs = \"google\", \"wikimedia\", \"wikipedia\", \"wikitravel\"\n ser = Series(strs)\n\n with tm.assert_produces_warning(FutureWarning):\n for s in ser.str:\n # iter must yield a Series\n assert isinstance(s, Series)\n\n # indices of each yielded Series should be equal to the index of\n # the original Series\n tm.assert_index_equal(s.index, ser.index)\n\n for el in s:\n # each element of the series is either a basestring/str or nan\n assert isinstance(el, str) or isna(el)\n\n # desired behavior is to iterate until everything would be nan on the\n # next iter so make sure the last element of the iterator was 'l' in\n # this case since 'wikitravel' is the longest string\n assert s.dropna().values.item() == \"l\"\n\n\ndef test_iter_empty():\n ser = Series([], dtype=object)\n\n i, s = 100, 1\n\n with tm.assert_produces_warning(FutureWarning):\n for i, s in enumerate(ser.str):\n pass\n\n # nothing to iterate over so nothing defined values should remain\n # unchanged\n assert i == 100\n assert s == 1\n\n\ndef test_iter_single_element():\n ser = Series([\"a\"])\n\n with tm.assert_produces_warning(FutureWarning):\n for i, s in enumerate(ser.str):\n pass\n\n assert not i\n tm.assert_series_equal(ser, s)\n\n\ndef test_iter_object_try_string():\n ser = Series(\n [\n slice(None, np.random.randint(10), np.random.randint(10, 20))\n for _ in range(4)\n ]\n )\n\n i, s = 100, \"h\"\n\n with tm.assert_produces_warning(FutureWarning):\n for i, s in enumerate(ser.str):\n pass\n\n assert i == 100\n assert s == \"h\"\n\n\n# test integer/float dtypes (inferred by constructor) and mixed\n\n\ndef test_count():\n ser = Series([\"foo\", \"foofoo\", np.nan, \"foooofooofommmfoo\"], dtype=np.object_)\n result = ser.str.count(\"f[o]+\")\n expected = Series([1, 2, np.nan, 4])\n tm.assert_series_equal(result, expected)\n\n\ndef test_count_mixed_object():\n ser = Series(\n [\"a\", np.nan, \"b\", True, datetime.today(), \"foo\", None, 1, 2.0],\n dtype=object,\n )\n result = ser.str.count(\"a\")\n expected = Series([1, np.nan, 0, np.nan, np.nan, 0, np.nan, np.nan, np.nan])\n tm.assert_series_equal(result, expected)\n\n\ndef test_repeat():\n ser = Series([\"a\", \"b\", np.nan, \"c\", np.nan, \"d\"])\n\n result = ser.str.repeat(3)\n expected = Series([\"aaa\", \"bbb\", np.nan, \"ccc\", np.nan, \"ddd\"])\n tm.assert_series_equal(result, expected)\n\n result = ser.str.repeat([1, 2, 3, 4, 5, 6])\n expected = Series([\"a\", \"bb\", np.nan, \"cccc\", np.nan, \"dddddd\"])\n tm.assert_series_equal(result, expected)\n\n\ndef test_repeat_mixed_object():\n ser = Series([\"a\", np.nan, \"b\", True, datetime.today(), \"foo\", None, 1, 2.0])\n result = ser.str.repeat(3)\n expected = Series(\n [\"aaa\", np.nan, \"bbb\", np.nan, np.nan, \"foofoofoo\", np.nan, np.nan, np.nan]\n )\n tm.assert_series_equal(result, expected)\n\n\ndef test_repeat_with_null(nullable_string_dtype):\n # GH: 31632\n ser = Series([\"a\", None], dtype=nullable_string_dtype)\n result = ser.str.repeat([3, 4])\n expected = Series([\"aaa\", None], dtype=nullable_string_dtype)\n tm.assert_series_equal(result, expected)\n\n ser = Series([\"a\", \"b\"], dtype=nullable_string_dtype)\n result = ser.str.repeat([3, None])\n expected = Series([\"aaa\", None], dtype=nullable_string_dtype)\n tm.assert_series_equal(result, expected)\n\n\ndef test_empty_str_methods(any_string_dtype):\n empty_str = empty = Series(dtype=any_string_dtype)\n if any_string_dtype == \"object\":\n empty_int = Series(dtype=\"int64\")\n empty_bool = Series(dtype=bool)\n else:\n empty_int = Series(dtype=\"Int64\")\n empty_bool = Series(dtype=\"boolean\")\n empty_object = Series(dtype=object)\n empty_bytes = Series(dtype=object)\n\n # GH7241\n # (extract) on empty series\n\n tm.assert_series_equal(empty_str, empty.str.cat(empty))\n assert \"\" == empty.str.cat()\n tm.assert_series_equal(empty_str, empty.str.title())\n tm.assert_series_equal(empty_int, empty.str.count(\"a\"))\n tm.assert_series_equal(empty_bool, empty.str.contains(\"a\"))\n tm.assert_series_equal(empty_bool, empty.str.startswith(\"a\"))\n tm.assert_series_equal(empty_bool, empty.str.endswith(\"a\"))\n tm.assert_series_equal(empty_str, empty.str.lower())\n tm.assert_series_equal(empty_str, empty.str.upper())\n tm.assert_series_equal(empty_str, empty.str.replace(\"a\", \"b\"))\n tm.assert_series_equal(empty_str, empty.str.repeat(3))\n tm.assert_series_equal(empty_bool, empty.str.match(\"^a\"))\n tm.assert_frame_equal(\n DataFrame(columns=[0], dtype=any_string_dtype),\n empty.str.extract(\"()\", expand=True),\n )\n tm.assert_frame_equal(\n DataFrame(columns=[0, 1], dtype=any_string_dtype),\n empty.str.extract(\"()()\", expand=True),\n )\n tm.assert_series_equal(empty_str, empty.str.extract(\"()\", expand=False))\n tm.assert_frame_equal(\n DataFrame(columns=[0, 1], dtype=any_string_dtype),\n empty.str.extract(\"()()\", expand=False),\n )\n tm.assert_frame_equal(DataFrame(), empty.str.get_dummies())\n tm.assert_series_equal(empty_str, empty_str.str.join(\"\"))\n tm.assert_series_equal(empty_int, empty.str.len())\n tm.assert_series_equal(empty_object, empty_str.str.findall(\"a\"))\n tm.assert_series_equal(empty_int, empty.str.find(\"a\"))\n tm.assert_series_equal(empty_int, empty.str.rfind(\"a\"))\n tm.assert_series_equal(empty_str, empty.str.pad(42))\n tm.assert_series_equal(empty_str, empty.str.center(42))\n tm.assert_series_equal(empty_object, empty.str.split(\"a\"))\n tm.assert_series_equal(empty_object, empty.str.rsplit(\"a\"))\n tm.assert_series_equal(empty_object, empty.str.partition(\"a\", expand=False))\n tm.assert_series_equal(empty_object, empty.str.rpartition(\"a\", expand=False))\n tm.assert_series_equal(empty_str, empty.str.slice(stop=1))\n tm.assert_series_equal(empty_str, empty.str.slice(step=1))\n tm.assert_series_equal(empty_str, empty.str.strip())\n tm.assert_series_equal(empty_str, empty.str.lstrip())\n tm.assert_series_equal(empty_str, empty.str.rstrip())\n tm.assert_series_equal(empty_str, empty.str.wrap(42))\n tm.assert_series_equal(empty_str, empty.str.get(0))\n tm.assert_series_equal(empty_object, empty_bytes.str.decode(\"ascii\"))\n tm.assert_series_equal(empty_bytes, empty.str.encode(\"ascii\"))\n # ismethods should always return boolean (GH 29624)\n tm.assert_series_equal(empty_bool, empty.str.isalnum())\n tm.assert_series_equal(empty_bool, empty.str.isalpha())\n tm.assert_series_equal(empty_bool, empty.str.isdigit())\n tm.assert_series_equal(empty_bool, empty.str.isspace())\n tm.assert_series_equal(empty_bool, empty.str.islower())\n tm.assert_series_equal(empty_bool, empty.str.isupper())\n tm.assert_series_equal(empty_bool, empty.str.istitle())\n tm.assert_series_equal(empty_bool, empty.str.isnumeric())\n tm.assert_series_equal(empty_bool, empty.str.isdecimal())\n tm.assert_series_equal(empty_str, empty.str.capitalize())\n tm.assert_series_equal(empty_str, empty.str.swapcase())\n tm.assert_series_equal(empty_str, empty.str.normalize(\"NFC\"))\n\n table = str.maketrans(\"a\", \"b\")\n tm.assert_series_equal(empty_str, empty.str.translate(table))\n\n\ndef test_empty_str_methods_to_frame():\n ser = Series(dtype=str)\n expected = DataFrame()\n\n result = ser.str.partition(\"a\")\n tm.assert_frame_equal(result, expected)\n\n result = ser.str.rpartition(\"a\")\n tm.assert_frame_equal(result, expected)\n\n\[email protected](\n \"method, expected\",\n [\n (\"isalnum\", [True, True, True, True, True, False, True, True, False, False]),\n (\"isalpha\", [True, True, True, False, False, False, True, False, False, False]),\n (\n \"isdigit\",\n [False, False, False, True, False, False, False, True, False, False],\n ),\n (\n \"isnumeric\",\n [False, False, False, True, False, False, False, True, False, False],\n ),\n (\n \"isspace\",\n [False, False, False, False, False, False, False, False, False, True],\n ),\n (\n \"islower\",\n [False, True, False, False, False, False, False, False, False, False],\n ),\n (\n \"isupper\",\n [True, False, False, False, True, False, True, False, False, False],\n ),\n (\n \"istitle\",\n [True, False, True, False, True, False, False, False, False, False],\n ),\n ],\n)\ndef test_ismethods(method, expected, any_string_dtype):\n values = [\"A\", \"b\", \"Xy\", \"4\", \"3A\", \"\", \"TT\", \"55\", \"-\", \" \"]\n ser = Series(values, dtype=any_string_dtype)\n\n expected_dtype = \"bool\" if any_string_dtype == \"object\" else \"boolean\"\n expected = Series(expected, dtype=expected_dtype)\n result = getattr(ser.str, method)()\n tm.assert_series_equal(result, expected)\n\n # compare with standard library\n expected = [getattr(v, method)() for v in values]\n result = result.tolist()\n assert result == expected\n\n\[email protected](\n \"method, expected\",\n [\n (\"isnumeric\", [False, True, True, False, True, True, False]),\n (\"isdecimal\", [False, True, False, False, False, True, False]),\n ],\n)\ndef test_isnumeric_unicode(method, expected, any_string_dtype):\n # 0x00bc: ¼ VULGAR FRACTION ONE QUARTER\n # 0x2605: ★ not number\n # 0x1378: ፸ ETHIOPIC NUMBER SEVENTY\n # 0xFF13: 3 Em 3\n values = [\"A\", \"3\", \"¼\", \"★\", \"፸\", \"3\", \"four\"]\n ser = Series(values, dtype=any_string_dtype)\n expected_dtype = \"bool\" if any_string_dtype == \"object\" else \"boolean\"\n expected = Series(expected, dtype=expected_dtype)\n result = getattr(ser.str, method)()\n tm.assert_series_equal(result, expected)\n\n # compare with standard library\n expected = [getattr(v, method)() for v in values]\n result = result.tolist()\n assert result == expected\n\n\[email protected](\n \"method, expected\",\n [\n (\"isnumeric\", [False, np.nan, True, False, np.nan, True, False]),\n (\"isdecimal\", [False, np.nan, False, False, np.nan, True, False]),\n ],\n)\ndef test_isnumeric_unicode_missing(method, expected, any_string_dtype):\n values = [\"A\", np.nan, \"¼\", \"★\", np.nan, \"3\", \"four\"]\n ser = Series(values, dtype=any_string_dtype)\n expected_dtype = \"object\" if any_string_dtype == \"object\" else \"boolean\"\n expected = Series(expected, dtype=expected_dtype)\n result = getattr(ser.str, method)()\n tm.assert_series_equal(result, expected)\n\n\ndef test_spilt_join_roundtrip():\n ser = Series([\"a_b_c\", \"c_d_e\", np.nan, \"f_g_h\"])\n result = ser.str.split(\"_\").str.join(\"_\")\n tm.assert_series_equal(result, ser)\n\n\ndef test_spilt_join_roundtrip_mixed_object():\n ser = Series(\n [\"a_b\", np.nan, \"asdf_cas_asdf\", True, datetime.today(), \"foo\", None, 1, 2.0]\n )\n result = ser.str.split(\"_\").str.join(\"_\")\n expected = Series(\n [\"a_b\", np.nan, \"asdf_cas_asdf\", np.nan, np.nan, \"foo\", np.nan, np.nan, np.nan]\n )\n tm.assert_series_equal(result, expected)\n\n\ndef test_len(any_string_dtype):\n ser = Series(\n [\"foo\", \"fooo\", \"fooooo\", np.nan, \"fooooooo\", \"foo\\n\", \"あ\"],\n dtype=any_string_dtype,\n )\n result = ser.str.len()\n expected_dtype = \"float64\" if any_string_dtype == \"object\" else \"Int64\"\n expected = Series([3, 4, 6, np.nan, 8, 4, 1], dtype=expected_dtype)\n tm.assert_series_equal(result, expected)\n\n\ndef test_len_mixed():\n ser = Series(\n [\"a_b\", np.nan, \"asdf_cas_asdf\", True, datetime.today(), \"foo\", None, 1, 2.0]\n )\n result = ser.str.len()\n expected = Series([3, np.nan, 13, np.nan, np.nan, 3, np.nan, np.nan, np.nan])\n tm.assert_series_equal(result, expected)\n\n\ndef test_index(index_or_series):\n if index_or_series is Series:\n _check = tm.assert_series_equal\n else:\n _check = tm.assert_index_equal\n\n obj = index_or_series([\"ABCDEFG\", \"BCDEFEF\", \"DEFGHIJEF\", \"EFGHEF\"])\n\n result = obj.str.index(\"EF\")\n _check(result, index_or_series([4, 3, 1, 0]))\n expected = np.array([v.index(\"EF\") for v in obj.values], dtype=np.int64)\n tm.assert_numpy_array_equal(result.values, expected)\n\n result = obj.str.rindex(\"EF\")\n _check(result, index_or_series([4, 5, 7, 4]))\n expected = np.array([v.rindex(\"EF\") for v in obj.values], dtype=np.int64)\n tm.assert_numpy_array_equal(result.values, expected)\n\n result = obj.str.index(\"EF\", 3)\n _check(result, index_or_series([4, 3, 7, 4]))\n expected = np.array([v.index(\"EF\", 3) for v in obj.values], dtype=np.int64)\n tm.assert_numpy_array_equal(result.values, expected)\n\n result = obj.str.rindex(\"EF\", 3)\n _check(result, index_or_series([4, 5, 7, 4]))\n expected = np.array([v.rindex(\"EF\", 3) for v in obj.values], dtype=np.int64)\n tm.assert_numpy_array_equal(result.values, expected)\n\n result = obj.str.index(\"E\", 4, 8)\n _check(result, index_or_series([4, 5, 7, 4]))\n expected = np.array([v.index(\"E\", 4, 8) for v in obj.values], dtype=np.int64)\n tm.assert_numpy_array_equal(result.values, expected)\n\n result = obj.str.rindex(\"E\", 0, 5)\n _check(result, index_or_series([4, 3, 1, 4]))\n expected = np.array([v.rindex(\"E\", 0, 5) for v in obj.values], dtype=np.int64)\n tm.assert_numpy_array_equal(result.values, expected)\n\n\ndef test_index_not_found(index_or_series):\n obj = index_or_series([\"ABCDEFG\", \"BCDEFEF\", \"DEFGHIJEF\", \"EFGHEF\"])\n with pytest.raises(ValueError, match=\"substring not found\"):\n obj.str.index(\"DE\")\n\n\ndef test_index_wrong_type_raises(index_or_series):\n obj = index_or_series([], dtype=object)\n msg = \"expected a string object, not int\"\n\n with pytest.raises(TypeError, match=msg):\n obj.str.index(0)\n\n with pytest.raises(TypeError, match=msg):\n obj.str.rindex(0)\n\n\ndef test_index_missing():\n ser = Series([\"abcb\", \"ab\", \"bcbe\", np.nan])\n\n result = ser.str.index(\"b\")\n expected = Series([1, 1, 0, np.nan])\n tm.assert_series_equal(result, expected)\n\n result = ser.str.rindex(\"b\")\n expected = Series([3, 1, 2, np.nan])\n tm.assert_series_equal(result, expected)\n\n\ndef test_pipe_failures():\n # #2119\n ser = Series([\"A|B|C\"])\n\n result = ser.str.split(\"|\")\n expected = Series([[\"A\", \"B\", \"C\"]])\n tm.assert_series_equal(result, expected)\n\n result = ser.str.replace(\"|\", \" \", regex=False)\n expected = Series([\"A B C\"])\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"start, stop, step, expected\",\n [\n (2, 5, None, [\"foo\", \"bar\", np.nan, \"baz\"]),\n (0, 3, -1, [\"\", \"\", np.nan, \"\"]),\n (None, None, -1, [\"owtoofaa\", \"owtrabaa\", np.nan, \"xuqzabaa\"]),\n (3, 10, 2, [\"oto\", \"ato\", np.nan, \"aqx\"]),\n (3, 0, -1, [\"ofa\", \"aba\", np.nan, \"aba\"]),\n ],\n)\ndef test_slice(start, stop, step, expected):\n ser = Series([\"aafootwo\", \"aabartwo\", np.nan, \"aabazqux\"])\n result = ser.str.slice(start, stop, step)\n expected = Series(expected)\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"start, stop, step, expected\",\n [\n (2, 5, None, [\"foo\", np.nan, \"bar\", np.nan, np.nan, np.nan, np.nan, np.nan]),\n (4, 1, -1, [\"oof\", np.nan, \"rab\", np.nan, np.nan, np.nan, np.nan, np.nan]),\n ],\n)\ndef test_slice_mixed_object(start, stop, step, expected):\n ser = Series([\"aafootwo\", np.nan, \"aabartwo\", True, datetime.today(), None, 1, 2.0])\n result = ser.str.slice(start, stop, step)\n expected = Series(expected)\n tm.assert_series_equal(result, expected)\n\n\ndef test_slice_replace():\n ser = Series([\"short\", \"a bit longer\", \"evenlongerthanthat\", \"\", np.nan])\n\n expected = Series([\"shrt\", \"a it longer\", \"evnlongerthanthat\", \"\", np.nan])\n result = ser.str.slice_replace(2, 3)\n tm.assert_series_equal(result, expected)\n\n expected = Series([\"shzrt\", \"a zit longer\", \"evznlongerthanthat\", \"z\", np.nan])\n result = ser.str.slice_replace(2, 3, \"z\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([\"shzort\", \"a zbit longer\", \"evzenlongerthanthat\", \"z\", np.nan])\n result = ser.str.slice_replace(2, 2, \"z\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([\"shzort\", \"a zbit longer\", \"evzenlongerthanthat\", \"z\", np.nan])\n result = ser.str.slice_replace(2, 1, \"z\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([\"shorz\", \"a bit longez\", \"evenlongerthanthaz\", \"z\", np.nan])\n result = ser.str.slice_replace(-1, None, \"z\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([\"zrt\", \"zer\", \"zat\", \"z\", np.nan])\n result = ser.str.slice_replace(None, -2, \"z\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([\"shortz\", \"a bit znger\", \"evenlozerthanthat\", \"z\", np.nan])\n result = ser.str.slice_replace(6, 8, \"z\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([\"zrt\", \"a zit longer\", \"evenlongzerthanthat\", \"z\", np.nan])\n result = ser.str.slice_replace(-10, 3, \"z\")\n tm.assert_series_equal(result, expected)\n\n\ndef test_strip_lstrip_rstrip(any_string_dtype):\n ser = Series([\" aa \", \" bb \\n\", np.nan, \"cc \"], dtype=any_string_dtype)\n\n result = ser.str.strip()\n expected = Series([\"aa\", \"bb\", np.nan, \"cc\"], dtype=any_string_dtype)\n tm.assert_series_equal(result, expected)\n\n result = ser.str.lstrip()\n expected = Series([\"aa \", \"bb \\n\", np.nan, \"cc \"], dtype=any_string_dtype)\n tm.assert_series_equal(result, expected)\n\n result = ser.str.rstrip()\n expected = Series([\" aa\", \" bb\", np.nan, \"cc\"], dtype=any_string_dtype)\n tm.assert_series_equal(result, expected)\n\n\ndef test_strip_lstrip_rstrip_mixed_object():\n ser = Series([\" aa \", np.nan, \" bb \\t\\n\", True, datetime.today(), None, 1, 2.0])\n\n result = ser.str.strip()\n expected = Series([\"aa\", np.nan, \"bb\", np.nan, np.nan, np.nan, np.nan, np.nan])\n tm.assert_series_equal(result, expected)\n\n result = ser.str.lstrip()\n expected = Series(\n [\"aa \", np.nan, \"bb \\t\\n\", np.nan, np.nan, np.nan, np.nan, np.nan]\n )\n tm.assert_series_equal(result, expected)\n\n result = ser.str.rstrip()\n expected = Series([\" aa\", np.nan, \" bb\", np.nan, np.nan, np.nan, np.nan, np.nan])\n tm.assert_series_equal(result, expected)\n\n\ndef test_strip_lstrip_rstrip_args(any_string_dtype):\n ser = Series([\"xxABCxx\", \"xx BNSD\", \"LDFJH xx\"], dtype=any_string_dtype)\n\n result = ser.str.strip(\"x\")\n expected = Series([\"ABC\", \" BNSD\", \"LDFJH \"], dtype=any_string_dtype)\n tm.assert_series_equal(result, expected)\n\n result = ser.str.lstrip(\"x\")\n expected = Series([\"ABCxx\", \" BNSD\", \"LDFJH xx\"], dtype=any_string_dtype)\n tm.assert_series_equal(result, expected)\n\n result = ser.str.rstrip(\"x\")\n expected = Series([\"xxABC\", \"xx BNSD\", \"LDFJH \"], dtype=any_string_dtype)\n tm.assert_series_equal(result, expected)\n\n\ndef test_string_slice_get_syntax():\n ser = Series(\n [\"YYY\", \"B\", \"C\", \"YYYYYYbYYY\", \"BYYYcYYY\", np.nan, \"CYYYBYYY\", \"dog\", \"cYYYt\"]\n )\n\n result = ser.str[0]\n expected = ser.str.get(0)\n tm.assert_series_equal(result, expected)\n\n result = ser.str[:3]\n expected = ser.str.slice(stop=3)\n tm.assert_series_equal(result, expected)\n\n result = ser.str[2::-1]\n expected = ser.str.slice(start=2, step=-1)\n tm.assert_series_equal(result, expected)\n\n\ndef test_string_slice_out_of_bounds():\n ser = Series([(1, 2), (1,), (3, 4, 5)])\n result = ser.str[1]\n expected = Series([2, np.nan, 4])\n tm.assert_series_equal(result, expected)\n\n ser = Series([\"foo\", \"b\", \"ba\"])\n result = ser.str[1]\n expected = Series([\"o\", np.nan, \"a\"])\n tm.assert_series_equal(result, expected)\n\n\ndef test_encode_decode():\n ser = Series([\"a\", \"b\", \"a\\xe4\"]).str.encode(\"utf-8\")\n result = ser.str.decode(\"utf-8\")\n expected = ser.map(lambda x: x.decode(\"utf-8\"))\n tm.assert_series_equal(result, expected)\n\n\ndef test_encode_errors_kwarg():\n ser = Series([\"a\", \"b\", \"a\\x9d\"])\n\n msg = (\n r\"'charmap' codec can't encode character '\\\\x9d' in position 1: \"\n \"character maps to <undefined>\"\n )\n with pytest.raises(UnicodeEncodeError, match=msg):\n ser.str.encode(\"cp1252\")\n\n result = ser.str.encode(\"cp1252\", \"ignore\")\n expected = ser.map(lambda x: x.encode(\"cp1252\", \"ignore\"))\n tm.assert_series_equal(result, expected)\n\n\ndef test_decode_errors_kwarg():\n ser = Series([b\"a\", b\"b\", b\"a\\x9d\"])\n\n msg = (\n \"'charmap' codec can't decode byte 0x9d in position 1: \"\n \"character maps to <undefined>\"\n )\n with pytest.raises(UnicodeDecodeError, match=msg):\n ser.str.decode(\"cp1252\")\n\n result = ser.str.decode(\"cp1252\", \"ignore\")\n expected = ser.map(lambda x: x.decode(\"cp1252\", \"ignore\"))\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"form, expected\",\n [\n (\"NFKC\", [\"ABC\", \"ABC\", \"123\", np.nan, \"アイエ\"]),\n (\"NFC\", [\"ABC\", \"ABC\", \"123\", np.nan, \"アイエ\"]),\n ],\n)\ndef test_normalize(form, expected):\n ser = Series([\"ABC\", \"ABC\", \"123\", np.nan, \"アイエ\"], index=[\"a\", \"b\", \"c\", \"d\", \"e\"])\n expected = Series(expected, index=[\"a\", \"b\", \"c\", \"d\", \"e\"])\n result = ser.str.normalize(form)\n tm.assert_series_equal(result, expected)\n\n\ndef test_normalize_bad_arg_raises():\n ser = Series([\"ABC\", \"ABC\", \"123\", np.nan, \"アイエ\"], index=[\"a\", \"b\", \"c\", \"d\", \"e\"])\n with pytest.raises(ValueError, match=\"invalid normalization form\"):\n ser.str.normalize(\"xxx\")\n\n\ndef test_normalize_index():\n idx = Index([\"ABC\", \"123\", \"アイエ\"])\n expected = Index([\"ABC\", \"123\", \"アイエ\"])\n result = idx.str.normalize(\"NFKC\")\n tm.assert_index_equal(result, expected)\n\n\[email protected](\n \"values,inferred_type\",\n [\n ([\"a\", \"b\"], \"string\"),\n ([\"a\", \"b\", 1], \"mixed-integer\"),\n ([\"a\", \"b\", 1.3], \"mixed\"),\n ([\"a\", \"b\", 1.3, 1], \"mixed-integer\"),\n ([\"aa\", datetime(2011, 1, 1)], \"mixed\"),\n ],\n)\ndef test_index_str_accessor_visibility(values, inferred_type, index_or_series):\n from pandas.core.strings import StringMethods\n\n obj = index_or_series(values)\n if index_or_series is Index:\n assert obj.inferred_type == inferred_type\n\n assert isinstance(obj.str, StringMethods)\n\n\[email protected](\n \"values,inferred_type\",\n [\n ([1, np.nan], \"floating\"),\n ([datetime(2011, 1, 1)], \"datetime64\"),\n ([timedelta(1)], \"timedelta64\"),\n ],\n)\ndef test_index_str_accessor_non_string_values_raises(\n values, inferred_type, index_or_series\n):\n obj = index_or_series(values)\n if index_or_series is Index:\n assert obj.inferred_type == inferred_type\n\n msg = \"Can only use .str accessor with string values\"\n with pytest.raises(AttributeError, match=msg):\n obj.str\n\n\ndef test_index_str_accessor_multiindex_raises():\n # MultiIndex has mixed dtype, but not allow to use accessor\n idx = MultiIndex.from_tuples([(\"a\", \"b\"), (\"a\", \"b\")])\n assert idx.inferred_type == \"mixed\"\n\n msg = \"Can only use .str accessor with Index, not MultiIndex\"\n with pytest.raises(AttributeError, match=msg):\n idx.str\n\n\ndef test_str_accessor_no_new_attributes():\n # https://github.com/pandas-dev/pandas/issues/10673\n ser = Series(list(\"aabbcde\"))\n with pytest.raises(AttributeError, match=\"You cannot add any new attribute\"):\n ser.str.xlabel = \"a\"\n\n\ndef test_cat_on_bytes_raises():\n lhs = Series(np.array(list(\"abc\"), \"S1\").astype(object))\n rhs = Series(np.array(list(\"def\"), \"S1\").astype(object))\n msg = \"Cannot use .str.cat with values of inferred dtype 'bytes'\"\n with pytest.raises(TypeError, match=msg):\n lhs.str.cat(rhs)\n\n\ndef test_str_accessor_in_apply_func():\n # https://github.com/pandas-dev/pandas/issues/38979\n df = DataFrame(zip(\"abc\", \"def\"))\n expected = Series([\"A/D\", \"B/E\", \"C/F\"])\n result = df.apply(lambda f: \"/\".join(f.str.upper()), axis=1)\n tm.assert_series_equal(result, expected)\n" ]
[ [ "pandas._testing.assert_numpy_array_equal", "pandas.Series", "pandas._testing.assert_produces_warning", "pandas.DataFrame", "pandas._testing.assert_frame_equal", "pandas._testing.assert_index_equal", "pandas._testing.assert_series_equal", "pandas.MultiIndex.from_tuples", "pandas.Index", "pandas.isna", "numpy.random.randint" ] ]
levinem/WarpX
[ "86f690e672578fb51e70493824026f3c372d5540" ]
[ "Python/pywarpx/PGroup.py" ]
[ "import numpy as np\nfrom . import _libwarpx\n\nclass PGroup(object):\n \"\"\"Implements a class that has the same API as a warp ParticleGroup instance.\n \"\"\"\n\n def __init__(self, igroup, ispecie, level=0):\n self.igroup = igroup\n self.ispecie = ispecie\n self.level = level\n self.ns = 1 # Number of species\n\n self.gallot()\n\n def name(self):\n return 'WarpXParticleGroup'\n\n def gallot(self):\n self.lebcancel_pusher = 0 # turns on/off cancellation of E+VxB within V push (logical type)\n self.lebcancel = 0 # turns on/off cancellation of E+VxB before V push (logical type)\n\n self.sm = np.zeros(self.ns) # Species mass [kg]\n self.sq = np.zeros(self.ns) # Species charge [C]\n self.sw = np.zeros(self.ns) # Species weight, (real particles per simulation particles)\n\n self.sid = np.arange(self.ns, dtype=int) # Global species index for each species\n self.ndts = np.ones(self.ns, dtype=int) # Stride for time step advance for each species\n self.ldts = np.ones(self.ns, dtype=int) # (logical type)\n self.lvdts = np.ones(self.ns, dtype=int) # (logical type)\n self.iselfb = np.zeros(self.ns, dtype=int) # Group number for particles that are affected by\n # their own magnetic field, using the 1/gamma**2\n # approximation. The correction is not applied to\n # group number -1.\n self.fselfb = np.zeros(self.ns) # The scaling factor, vz.\n self.l_maps = np.zeros(self.ns)\n self.dtscale = np.ones(self.ns) # Scale factor applied to time step size for each\n # species. Only makes sense in steaday and and\n # transverse slice modes.\n\n self.limplicit = np.zeros(self.ns, dtype=int) # Flags implicit particle species (logical type)\n self.iimplicit = np.full(self.ns, -1, dtype=int) # Group number for implicit particles\n self.ldoadvance = np.ones(self.ns, dtype=int) # Flags whether particles are time advanced (logical type)\n self.lboundaries = np.ones(self.ns, dtype=int) # Flags whether boundary conditions need to be applied (logical type)\n self.lparaxial = np.zeros(self.ns, dtype=int) # Flags to turn on/off paraxial approximation (logical type)\n\n self.zshift = np.zeros(self.ns)\n self.gamma_ebcancel_max = np.ones(self.ns) # maximum value allowed for ExB cancellation\n\n # --- Temporary fix\n gchange = gallot\n\n def allocated(self, name):\n return True\n\n def addspecies(self):\n pass\n\n def getnpid(self):\n return _libwarpx.get_nattr()\n npid = property(getnpid)\n\n def getnps(self):\n return np.array([len(self.xp)], dtype='l')\n nps = property(getnps)\n\n def getins(self):\n return np.ones(self.ns, dtype='l')\n ins = property(getins)\n\n def getipmax(self):\n return np.array([0, len(self.xp)], dtype='l')\n ipmax = property(getipmax)\n\n def getnpmax(self):\n return self.nps.sum()\n npmax = property(getnpmax)\n\n def getxp(self):\n return _libwarpx.get_particle_x(self.ispecie, self.level)[self.igroup]\n xp = property(getxp)\n\n def getyp(self):\n return _libwarpx.get_particle_y(self.ispecie, self.level)[self.igroup]\n yp = property(getyp)\n\n def getrp(self):\n return _libwarpx.get_particle_r(self.ispecie, self.level)[self.igroup]\n rp = property(getrp)\n\n def getzp(self):\n return _libwarpx.get_particle_z(self.ispecie, self.level)[self.igroup]\n zp = property(getzp)\n\n def getuxp(self):\n return _libwarpx.get_particle_ux(self.ispecie, self.level)[self.igroup]\n uxp = property(getuxp)\n\n def getuyp(self):\n return _libwarpx.get_particle_uy(self.ispecie, self.level)[self.igroup]\n uyp = property(getuyp)\n\n def getuzp(self):\n return _libwarpx.get_particle_uz(self.ispecie, self.level)[self.igroup]\n uzp = property(getuzp)\n\n def getpid(self):\n id = _libwarpx.get_particle_id(self.ispecie, self.level)[self.igroup]\n pid = np.array([id]).T\n return pid\n pid = property(getpid)\n\n def getgaminv(self):\n uxp = self.getuxp()\n uyp = self.getuyp()\n uzp = self.getuzp()\n return np.sqrt(1. - (uxp**2 + uyp**2 + uzp**2)/_libwarpx.clight**2)\n gaminv = property(getgaminv)\n\n def getex(self):\n return _libwarpx.get_particle_Ex(self.ispecie, self.level)[self.igroup]\n ex = property(getex)\n\n def getey(self):\n return _libwarpx.get_particle_Ey(self.ispecie, self.level)[self.igroup]\n ey = property(getey)\n\n def getez(self):\n return _libwarpx.get_particle_Ez(self.ispecie, self.level)[self.igroup]\n ez = property(getez)\n\n def getbx(self):\n return _libwarpx.get_particle_Bx(self.ispecie, self.level)[self.igroup]\n bx = property(getbx)\n\n def getby(self):\n return _libwarpx.get_particle_By(self.ispecie, self.level)[self.igroup]\n by = property(getby)\n\n def getbz(self):\n return _libwarpx.get_particle_Bz(self.ispecie, self.level)[self.igroup]\n bz = property(getbz)\n\n def gettheta(self):\n return _libwarpx.get_particle_theta(self.ispecie, self.level)[self.igroup]\n theta = property(gettheta)\n\nclass PGroups(object):\n def __init__(self, ispecie=0, level=0):\n self.ispecie = ispecie\n self.level = level\n\n def setuppgroups(self):\n xall = _libwarpx.get_particle_x(self.ispecie, self.level)\n self.ngroups = len(xall)\n\n self._pgroups = []\n for igroup in range(self.ngroups):\n self._pgroups.append(PGroup(igroup, self.ispecie, self.level))\n\n def __iter__(self):\n self.setuppgroups()\n for igroup in range(self.ngroups):\n yield self._pgroups[igroup]\n\n def __getitem__(self, key):\n self.setuppgroups()\n return self._pgroups[key]\n\n def __len__(self):\n self.setuppgroups()\n return len(self._pgroups)\n" ]
[ [ "numpy.ones", "numpy.zeros", "numpy.arange", "numpy.sqrt", "numpy.full", "numpy.array" ] ]
PranavKhadpe/Detecting-usefulness-of-Yelp-Reviews
[ "7a176ee01b5b1a1494321177d08dc3be0a04f589" ]
[ "pre-processing-source/time_filter/epoch_remove.py" ]
[ "from datetime import datetime\nimport pandas as pd\nimport numpy as np\nimport json\n\ndf = pd.read_csv('/home/josh/python/SNLP/src/truncate_data/epoch_rev.json')\ndf = df[df.epoch_time < 1483142400.0]\ndf = df[df.epoch_time > 1419984000.0]\nwith open('epoch_fil.json', 'w+') as f:\n f.write(out)\n" ]
[ [ "pandas.read_csv" ] ]
IMTtugraz/PyQMRI
[ "158ac75e0a86374f3eb907467660f96233260009" ]
[ "test/unittests/test_gradient_double.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 12 11:26:41 2019\n\n@author: omaier\n\"\"\"\n\nimport pyqmri\ntry:\n import unittest2 as unittest\nexcept ImportError:\n import unittest\nfrom pyqmri._helper_fun import CLProgram as Program\nfrom pkg_resources import resource_filename\nimport pyopencl.array as clarray\nimport numpy as np\n\nDTYPE = np.complex128\nDTYPE_real = np.float64\nRTOL=1e-12\nATOL=1e-14\n\nclass tmpArgs():\n pass\n\n\ndef setupPar(par):\n par[\"NScan\"] = 10\n par[\"NC\"] = 15\n par[\"NSlice\"] = 10\n par[\"dimX\"] = 128\n par[\"dimY\"] = 128\n par[\"Nproj\"] = 21\n par[\"N\"] = 256\n par[\"unknowns_TGV\"] = 2\n par[\"unknowns_H1\"] = 0\n par[\"unknowns\"] = 2\n par[\"dz\"] = 1\n par[\"weights\"] = np.array([1, 0.1])\n\n\nclass GradientTest(unittest.TestCase):\n def setUp(self):\n parser = tmpArgs()\n parser.streamed = False\n parser.devices = -1\n parser.use_GPU = True\n\n par = {}\n pyqmri.pyqmri._setupOCL(parser, par)\n setupPar(par)\n if DTYPE == np.complex128:\n file = resource_filename(\n 'pyqmri', 'kernels/OpenCL_Kernels_double.c')\n else:\n file = resource_filename(\n 'pyqmri', 'kernels/OpenCL_Kernels.c')\n\n prg = []\n for j in range(len(par[\"ctx\"])):\n with open(file) as myfile:\n prg.append(Program(\n par[\"ctx\"][j],\n myfile.read()))\n prg = prg[0]\n \n self.weights = par[\"weights\"]\n\n self.grad = pyqmri.operator.OperatorFiniteGradient(\n par, prg,\n DTYPE=DTYPE,\n DTYPE_real=DTYPE_real)\n\n self.gradin = np.random.randn(par[\"unknowns\"], par[\"NSlice\"],\n par[\"dimY\"], par[\"dimX\"]) +\\\n 1j * np.random.randn(par[\"unknowns\"], par[\"NSlice\"],\n par[\"dimY\"], par[\"dimX\"])\n self.divin = np.random.randn(par[\"unknowns\"], par[\"NSlice\"],\n par[\"dimY\"], par[\"dimX\"], 4) +\\\n 1j * np.random.randn(par[\"unknowns\"], par[\"NSlice\"],\n par[\"dimY\"], par[\"dimX\"], 4)\n self.gradin = self.gradin.astype(DTYPE)\n self.divin = self.divin.astype(DTYPE)\n self.dz = par[\"dz\"]\n self.queue = par[\"queue\"][0]\n\n def test_grad_outofplace(self):\n gradx = np.zeros_like(self.gradin)\n grady = np.zeros_like(self.gradin)\n gradz = np.zeros_like(self.gradin)\n\n gradx[..., :-1] = np.diff(self.gradin, axis=-1)\n grady[..., :-1, :] = np.diff(self.gradin, axis=-2)\n gradz[:, :-1, ...] = np.diff(self.gradin, axis=-3)*self.dz\n\n grad = np.stack((gradx,\n grady,\n gradz), axis=-1)\n \n grad *= self.weights[:, None, None, None, None]\n\n inp = clarray.to_device(self.queue, self.gradin)\n outp = self.grad.fwdoop(inp)\n outp = outp.get()\n\n np.testing.assert_allclose(outp[..., :-1], grad, rtol=RTOL, atol=ATOL)\n\n def test_grad_inplace(self):\n gradx = np.zeros_like(self.gradin)\n grady = np.zeros_like(self.gradin)\n gradz = np.zeros_like(self.gradin)\n\n gradx[..., :-1] = np.diff(self.gradin, axis=-1)\n grady[..., :-1, :] = np.diff(self.gradin, axis=-2)\n gradz[:, :-1, ...] = np.diff(self.gradin, axis=-3)*self.dz\n\n grad = np.stack((gradx,\n grady,\n gradz), axis=-1)\n \n grad *= self.weights[:, None, None, None, None]\n\n inp = clarray.to_device(self.queue, self.gradin)\n outp = clarray.to_device(self.queue, self.divin)\n outp.add_event(self.grad.fwd(outp, inp))\n outp = outp.get()\n\n np.testing.assert_allclose(outp[..., :-1], grad, rtol=RTOL, atol=ATOL)\n\n def test_adj_outofplace(self):\n inpgrad = clarray.to_device(self.queue, self.gradin)\n inpdiv = clarray.to_device(self.queue, self.divin)\n\n outgrad = self.grad.fwdoop(inpgrad)\n outdiv = self.grad.adjoop(inpdiv)\n\n outgrad = outgrad.get()\n outdiv = outdiv.get()\n\n a = np.vdot(outgrad[..., :-1].flatten(),\n self.divin[..., :-1].flatten())/self.gradin.size\n b = np.vdot(self.gradin.flatten(), -outdiv.flatten())/self.gradin.size\n\n print(\"Adjointness: %.2e +1j %.2e\" % ((a - b).real, (a - b).imag))\n\n np.testing.assert_allclose(a, b, rtol=RTOL, atol=ATOL)\n\n def test_adj_inplace(self):\n inpgrad = clarray.to_device(self.queue, self.gradin)\n inpdiv = clarray.to_device(self.queue, self.divin)\n\n outgrad = clarray.zeros_like(inpdiv)\n outdiv = clarray.zeros_like(inpgrad)\n\n outgrad.add_event(self.grad.fwd(outgrad, inpgrad))\n outgrad.add_event(self.grad.adj(outdiv, inpdiv))\n\n outgrad = outgrad.get()\n outdiv = outdiv.get()\n\n a = np.vdot(outgrad[..., :-1].flatten(),\n self.divin[..., :-1].flatten())/self.gradin.size\n b = np.vdot(self.gradin.flatten(), -outdiv.flatten())/self.gradin.size\n\n print(\"Adjointness: %.2e +1j %.2e\" % ((a - b).real, (a - b).imag))\n\n np.testing.assert_allclose(a, b, rtol=RTOL, atol=ATOL)\n\n\nclass GradientStreamedTest(unittest.TestCase):\n def setUp(self):\n parser = tmpArgs()\n parser.streamed = True\n parser.devices = -1\n parser.use_GPU = True\n\n par = {}\n pyqmri.pyqmri._setupOCL(parser, par)\n setupPar(par)\n if DTYPE == np.complex128:\n file = resource_filename(\n 'pyqmri', 'kernels/OpenCL_Kernels_double_streamed.c')\n else:\n file = resource_filename(\n 'pyqmri', 'kernels/OpenCL_Kernels_streamed.c')\n\n prg = []\n for j in range(len(par[\"ctx\"])):\n with open(file) as myfile:\n prg.append(Program(\n par[\"ctx\"][j],\n myfile.read()))\n\n par[\"par_slices\"] = 1\n self.weights = par[\"weights\"]\n\n self.grad = pyqmri.operator.OperatorFiniteGradientStreamed(\n par, prg,\n DTYPE=DTYPE,\n DTYPE_real=DTYPE_real)\n\n self.gradin = np.random.randn(par[\"NSlice\"], par[\"unknowns\"],\n par[\"dimY\"], par[\"dimX\"]) +\\\n 1j * np.random.randn(par[\"NSlice\"], par[\"unknowns\"],\n par[\"dimY\"], par[\"dimX\"])\n self.divin = np.random.randn(par[\"NSlice\"], par[\"unknowns\"],\n par[\"dimY\"], par[\"dimX\"], 4) +\\\n 1j * np.random.randn(par[\"NSlice\"], par[\"unknowns\"],\n par[\"dimY\"], par[\"dimX\"], 4)\n self.gradin = self.gradin.astype(DTYPE)\n self.divin = self.divin.astype(DTYPE)\n self.dz = par[\"dz\"]\n\n def test_grad_outofplace(self):\n gradx = np.zeros_like(self.gradin)\n grady = np.zeros_like(self.gradin)\n gradz = np.zeros_like(self.gradin)\n\n gradx[..., :-1] = np.diff(self.gradin, axis=-1)\n grady[..., :-1, :] = np.diff(self.gradin, axis=-2)\n gradz[:-1, ...] = np.diff(self.gradin, axis=0)*self.dz\n\n grad = np.stack((gradx,\n grady,\n gradz), axis=-1)\n \n grad *= self.weights[None, :, None, None, None]\n\n outp = self.grad.fwdoop([[self.gradin]])\n\n np.testing.assert_allclose(outp[..., :-1], grad, rtol=RTOL, atol=ATOL)\n\n def test_grad_inplace(self):\n gradx = np.zeros_like(self.gradin)\n grady = np.zeros_like(self.gradin)\n gradz = np.zeros_like(self.gradin)\n\n gradx[..., :-1] = np.diff(self.gradin, axis=-1)\n grady[..., :-1, :] = np.diff(self.gradin, axis=-2)\n gradz[:-1, ...] = np.diff(self.gradin, axis=0)*self.dz\n\n grad = np.stack((gradx,\n grady,\n gradz), axis=-1)\n \n grad *= self.weights[None, :, None, None, None]\n\n outp = np.zeros_like(self.divin)\n\n self.grad.fwd([outp], [[self.gradin]])\n\n np.testing.assert_allclose(outp[..., :-1], grad, rtol=RTOL, atol=ATOL)\n\n def test_adj_outofplace(self):\n\n outgrad = self.grad.fwdoop([[self.gradin]])\n outdiv = self.grad.adjoop([[self.divin]])\n\n a = np.vdot(outgrad[..., :-1].flatten(),\n self.divin[..., :-1].flatten())/self.gradin.size\n b = np.vdot(self.gradin.flatten(), -outdiv.flatten())/self.gradin.size\n\n print(\"Adjointness: %.2e +1j %.2e\" % ((a - b).real, (a - b).imag))\n\n np.testing.assert_allclose(a, b, rtol=RTOL, atol=ATOL)\n\n def test_adj_inplace(self):\n\n outgrad = np.zeros_like(self.divin)\n outdiv = np.zeros_like(self.gradin)\n\n self.grad.fwd([outgrad], [[self.gradin]])\n self.grad.adj([outdiv], [[self.divin]])\n\n a = np.vdot(outgrad[..., :-1].flatten(),\n self.divin[..., :-1].flatten())/self.gradin.size\n b = np.vdot(self.gradin.flatten(), -outdiv.flatten())/self.gradin.size\n\n print(\"Adjointness: %.2e +1j %.2e\" % ((a - b).real, (a - b).imag))\n\n np.testing.assert_allclose(a, b, rtol=RTOL, atol=ATOL)\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.zeros_like", "numpy.diff", "numpy.stack", "numpy.random.randn", "numpy.testing.assert_allclose", "numpy.array" ] ]
Challyfilio/NAIC2021
[ "11b38a920dcc902f9b798dc43ae360062862e6e4" ]
[ "project/fastreid/modeling/backbones/mobilenet.py" ]
[ "\"\"\"\nCreates a MobileNetV2 Model as defined in:\nMark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018).\nMobileNetV2: Inverted Residuals and Linear Bottlenecks\narXiv preprint arXiv:1801.04381.\nimport from https://github.com/tonylins/pytorch-mobilenet-v2\n\"\"\"\nimport logging\nimport math\n\nimport torch\nimport torch.nn as nn\n\nfrom project.fastreid.layers import get_norm\nfrom project.fastreid.utils.checkpoint import get_missing_parameters_message, get_unexpected_parameters_message\nfrom .build import BACKBONE_REGISTRY\n\nlogger = logging.getLogger(__name__)\n\n\ndef _make_divisible(v, divisor, min_value=None):\n \"\"\"\n This function is taken from the original tf repo.\n It ensures that all layers have a channel number that is divisible by 8\n It can be seen here:\n https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\n :param v:\n :param divisor:\n :param min_value:\n :return:\n \"\"\"\n if min_value is None:\n min_value = divisor\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n # Make sure that round down does not go down by more than 10%.\n if new_v < 0.9 * v:\n new_v += divisor\n return new_v\n\n\ndef conv_3x3_bn(inp, oup, stride, bn_norm):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 3, stride, 1, bias=False),\n get_norm(bn_norm, oup),\n nn.ReLU6(inplace=True)\n )\n\n\ndef conv_1x1_bn(inp, oup, bn_norm):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 1, 1, 0, bias=False),\n get_norm(bn_norm, oup),\n nn.ReLU6(inplace=True)\n )\n\n\nclass InvertedResidual(nn.Module):\n def __init__(self, inp, oup, bn_norm, stride, expand_ratio):\n super(InvertedResidual, self).__init__()\n assert stride in [1, 2]\n\n hidden_dim = round(inp * expand_ratio)\n self.identity = stride == 1 and inp == oup\n\n if expand_ratio == 1:\n self.conv = nn.Sequential(\n # dw\n nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),\n get_norm(bn_norm, hidden_dim),\n nn.ReLU6(inplace=True),\n # pw-linear\n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\n get_norm(bn_norm, oup),\n )\n else:\n self.conv = nn.Sequential(\n # pw\n nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),\n get_norm(bn_norm, hidden_dim),\n nn.ReLU6(inplace=True),\n # dw\n nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),\n get_norm(bn_norm, hidden_dim),\n nn.ReLU6(inplace=True),\n # pw-linear\n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup),\n )\n\n def forward(self, x):\n if self.identity:\n return x + self.conv(x)\n else:\n return self.conv(x)\n\n\nclass MobileNetV2(nn.Module):\n def __init__(self, bn_norm, width_mult=1.):\n super(MobileNetV2, self).__init__()\n # setting of inverted residual blocks\n self.cfgs = [\n # t, c, n, s\n [1, 16, 1, 1],\n [6, 24, 2, 2],\n [6, 32, 3, 2],\n [6, 64, 4, 2],\n [6, 96, 3, 1],\n [6, 160, 3, 2],\n [6, 320, 1, 1],\n ]\n\n # building first layer\n input_channel = _make_divisible(32 * width_mult, 4 if width_mult == 0.1 else 8)\n layers = [conv_3x3_bn(3, input_channel, 2, bn_norm)]\n # building inverted residual blocks\n block = InvertedResidual\n for t, c, n, s in self.cfgs:\n output_channel = _make_divisible(c * width_mult, 4 if width_mult == 0.1 else 8)\n for i in range(n):\n layers.append(block(input_channel, output_channel, bn_norm, s if i == 0 else 1, t))\n input_channel = output_channel\n self.features = nn.Sequential(*layers)\n # building last several layers\n output_channel = _make_divisible(1280 * width_mult, 4 if width_mult == 0.1 else 8) if width_mult > 1.0 else 1280\n self.conv = conv_1x1_bn(input_channel, output_channel, bn_norm)\n\n self._initialize_weights()\n\n def forward(self, x):\n x = self.features(x)\n x = self.conv(x)\n return x\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n\n@BACKBONE_REGISTRY.register()\ndef build_mobilenetv2_backbone(cfg):\n \"\"\"\n Create a MobileNetV2 instance from config.\n Returns:\n MobileNetV2: a :class: `MobileNetV2` instance.\n \"\"\"\n # fmt: off\n pretrain = cfg.MODEL.BACKBONE.PRETRAIN\n pretrain_path = cfg.MODEL.BACKBONE.PRETRAIN_PATH\n bn_norm = cfg.MODEL.BACKBONE.NORM\n depth = cfg.MODEL.BACKBONE.DEPTH\n # fmt: on\n\n width_mult = {\n \"1.0x\": 1.0,\n \"0.75x\": 0.75,\n \"0.5x\": 0.5,\n \"0.35x\": 0.35,\n '0.25x': 0.25,\n '0.1x': 0.1,\n }[depth]\n\n model = MobileNetV2(bn_norm, width_mult)\n\n if pretrain:\n try:\n state_dict = torch.load(pretrain_path, map_location=torch.device('cpu'))\n logger.info(f\"Loading pretrained model from {pretrain_path}\")\n except FileNotFoundError as e:\n logger.info(f'{pretrain_path} is not found! Please check this path.')\n raise e\n except KeyError as e:\n logger.info(\"State dict keys error! Please check the state dict.\")\n raise e\n\n incompatible = model.load_state_dict(state_dict, strict=False)\n if incompatible.missing_keys:\n logger.info(\n get_missing_parameters_message(incompatible.missing_keys)\n )\n if incompatible.unexpected_keys:\n logger.info(\n get_unexpected_parameters_message(incompatible.unexpected_keys)\n )\n\n return model\n" ]
[ [ "torch.nn.BatchNorm2d", "torch.nn.ReLU6", "torch.nn.Conv2d", "torch.nn.Sequential", "torch.device" ] ]
DANancy/Web-Scraper-Starter
[ "bfde0c67dd004bd065f084b57040ed644bfab2fd" ]
[ "bilibili/video_analysis.py" ]
[ "#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# env libs\nimport os\nfrom dotenv import load_dotenv\nfrom pathlib import Path\n\n# dash libs\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport plotly.graph_objs as pgo\n\n# pydata stack\nimport pandas as pd\nimport pymongo\n\n# set params\nenv_path = Path('..') / '.env'\nload_dotenv(dotenv_path=env_path)\nmyClient = pymongo.MongoClient(os.getenv(\"DBCONNECT\"))\n\n# others\nfrom datetime import datetime\n\n\n###########################\n# Data Manipulation / Model\n###########################\n\ndef fetch_data(db, table):\n df = pd.DataFrame(list(myClient[db][table].find()))\n df['pubdate_new'] = pd.to_datetime(df['pubdate']).dt.date\n return df\n\n\ndef generate_data(name):\n data = fetch_data('bilibili', 'infos')\n if name is None:\n return data\n dff = data[data.author == name]\n return dff\n\n\ndata = fetch_data('bilibili', 'infos')\nauthor_by_video = data['author'].value_counts().to_frame('y')[:10]\nopts = [{'label': i, 'value': i} for i in data.author.unique()]\nunique_dates = data['pubdate_new'].unique()\ndates = sorted([str(unique_dates[i]) for i in range(0, len(unique_dates))])\ndate_mark = {i: dates[i] for i in range(0, len(unique_dates))}\n\n#########################\n# Dashboard Layout / View\n#########################\n\napp = dash.Dash()\n\ncolors = {\n 'background': '#FFFFFF',\n 'text': 'black'\n}\n\ntrace_1 = pgo.Scatter(x=author_by_video.index, y=author_by_video['y'],\n name='Videos by time',\n line=dict(width=2,\n color='rgb(229, 151, 50)'))\nlayout = pgo.Layout(title='Time Series Plot',\n hovermode='closest')\nfig = pgo.Figure(data=[trace_1], layout=layout)\n\napp.layout = html.Div(style={'backgroundColor': colors['background']}, children=[\n # add a header\n html.H1(\n children='Bilibili Data Visualization',\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }\n ),\n # add a paragraph\n html.Div(children='Bilibili videos data visualization using Dash.', style={\n 'textAlign': 'center',\n 'color': colors['text']\n }),\n\n # add a bar plot\n dcc.Graph(\n id='top-authors-by-videos',\n figure={\n 'data': [\n {'x': author_by_video.index,\n 'y': author_by_video['y'],\n 'type': 'bar'}\n ],\n 'layout': {\n 'title': 'Top 10 Auhtors by Videos',\n 'plot_bgcolor': colors['background'],\n 'paper_bgcolor': colors['background'],\n 'font': {\n 'color': colors['text']\n }\n }\n }\n ),\n\n # adding a plot\n dcc.Graph(\n id='plot', figure=fig),\n\n # add dropdown\n html.P([\n html.Label(\"Choose a name\"),\n dcc.Dropdown(id='dropdown', options=[\n {'label': i, 'value': i} for i in data.author.unique()\n ], multi=False, placeholder='Filter by Author...'),\n ], style={'width': '400px', 'fontSize': '20px', 'padding-left': '100px', 'display': 'inline-block'}),\n\n # add range slider\n html.P([\n html.Label(\"Time Period\"),\n dcc.RangeSlider(id='slider',\n marks=date_mark,\n min=0,\n max=8,\n value=[0, 6])], style={'width': '80%',\n 'fontSize': '20px',\n 'padding-left': '100px',\n 'display': 'inline-block'})\n\n])\n\n\n#############################################\n# Interaction Between Components / Controller\n#############################################\[email protected](\n Output('plot', 'figure'),\n [Input('dropdown', 'value'),\n Input('slider', 'value')])\ndef update_figure(input1, input2):\n # filtering the data\n st1 = generate_data(input1)\n from_date = datetime.strptime(dates[input2[0]], '%Y-%m-%d').date()\n to_date = datetime.strptime(dates[input2[1]], '%Y-%m-%d').date()\n st2 = st1[(st1.pubdate_new > from_date) & (st1.pubdate_new < to_date)]\n updated_data = st2['pubdate_new'].value_counts().sort_index().to_frame('y')\n\n # update the plot\n trace_1 = pgo.Scatter(x=updated_data.index, y=updated_data['y'],\n name='Videos by Date',\n line=dict(width=2,\n color='rgb(229, 151, 50)'))\n fig = pgo.Figure(data=[trace_1], layout=layout)\n return fig\n\n\n# start Flask server\nif __name__ == \"__main__\":\n app.run_server(debug=True)\n" ]
[ [ "pandas.to_datetime" ] ]
sadamarif/Basic-50-ML
[ "4b30228cb2a30c85864683c685205c1cc8a84461" ]
[ "1 Create1DVector/CreateVector.py" ]
[ "# Load library\nimport numpy as np\n# Create a vector as a row\nvector_row = np.array([1, 2, 3])\n# Create a vector as a column\nvector_column = np.array([[1],[2],[3]])" ]
[ [ "numpy.array" ] ]
threewisemonkeys-as/myrl
[ "3e67072591027bd3314f4c85cf32ddcf547c7840" ]
[ "dqn/dqn_torch.py" ]
[ "# Deep Q Network in pytorch\n# Atharv Sonwane <[email protected]>\n\n# References -\n# https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf\n\nimport copy\nimport random\nimport time\nfrom collections import deque, namedtuple\nfrom itertools import count\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ndtype = torch.double\n\n# Hyperparameters\nTIMESTEPS = 5000\nBATCH_SIZE = 128\nNETWORK_HIDDEN_LAYERS = 32\nEPSILON = 0.1\nGAMMA = 0.9\nMAX_BUFFER_SIZE = TIMESTEPS // 2\nPOLYAK_CONST = 0.995\nLEARNING_RATE = 1e-2\nMAX_TRAJ_LENGTH = 1000\nMIN_BUFFER_SIZE = BATCH_SIZE\n\n# Transition tuple\nTransition = namedtuple(\n \"Transition\", (\"observation\", \"action\", \"reward\", \"next_observation\", \"done\")\n)\n\n# Model\nclass DQN:\n def __init__(\n self, env, network_hidden_layers=NETWORK_HIDDEN_LAYERS,\n ):\n\n self.env = env\n if self.env.unwrapped.spec is not None:\n self.env_name = self.env.unwrapped.spec.id\n else:\n self.env_name = self.env.unwrapped.__class__.__name__\n\n self.Q = self._make_network(network_hidden_layers)\n self.target_Q = copy.deepcopy(self.Q)\n for p in self.target_Q.parameters():\n p.requires_grad = False\n\n def _make_network(self, network_hidden_layers):\n return (\n nn.Sequential(\n nn.Linear(self.env.observation_space.shape[0], network_hidden_layers),\n nn.ReLU(),\n nn.Linear(network_hidden_layers, self.env.action_space.n),\n )\n .to(device)\n .to(dtype)\n )\n\n def _select_action(self, observation, eps=0):\n if np.random.random() < eps:\n action = torch.tensor(env.action_space.sample(), device=device, dtype=dtype)\n else:\n q_values = self.Q(observation)\n action = torch.argmax(q_values)\n return action.unsqueeze(0)\n\n def _update(self, replay_buffer, batch_size, optimizer, gamma, polyak_const):\n\n sample = Transition(\n *[torch.cat(i) for i in [*zip(*random.sample(replay_buffer, batch_size))]]\n )\n\n # Compute the target Q values for each state action pair in batch\n with torch.no_grad():\n target_q_vals = sample.reward + gamma * self.target_Q(\n sample.next_observation\n ).max(1).values.unsqueeze(1) * (~sample.done)\n\n # Compute the current Q values for each state action pair in batch\n q_vals = self.Q(sample.observation).gather(1, sample.action)\n\n # Compute the loss, backpropogate and update the gradients\n # loss = nn.SmoothL1Loss()(target_q_vals, q_vals)\n optimizer.zero_grad()\n loss = nn.MSELoss()(target_q_vals, q_vals)\n loss.backward()\n optimizer.step()\n\n # Update target network with polyak averaging\n with torch.no_grad():\n for p_target, p in zip(self.target_Q.parameters(), self.Q.parameters()):\n p_target.data.mul_(polyak_const)\n p_target.data.add_((1 - polyak_const) * p.data)\n\n return loss.item()\n\n def train(\n self,\n timesteps=TIMESTEPS,\n lr=LEARNING_RATE,\n gamma=GAMMA,\n eps=EPSILON,\n batch_size=BATCH_SIZE,\n polyak_const=POLYAK_CONST,\n min_buffer_size=MIN_BUFFER_SIZE,\n max_buffer_size=MAX_BUFFER_SIZE,\n max_traj_length=MAX_TRAJ_LENGTH,\n RENDER=False,\n VERBOSE=False,\n PLOT_REWARDS=False,\n SAVE_FREQUENCY=None,\n ):\n \"\"\" Trains deep q network \"\"\"\n hp = locals()\n print(\n f\"\\nTraining model on {self.env_name} | \"\n f\"Observation Space: {self.env.observation_space} | \"\n f\"Action Space: {self.env.action_space}\\n\"\n f\"Hyperparameters: \\n{hp}\\n\"\n )\n start_time = time.time()\n self.Q.train()\n optimizer = torch.optim.Adam(self.Q.parameters(), lr=lr)\n replay_buffer = deque(maxlen=max_buffer_size)\n rewards = []\n e = 0\n loss = 0.0\n step_count = 0\n\n if VERBOSE:\n print(\"Collecting experience ...\")\n for episode in count():\n # initialise tracking variables\n observation = self.env.reset()\n observation = torch.tensor(\n observation, device=device, dtype=dtype\n ).unsqueeze(0)\n done = torch.tensor([False], device=device, dtype=torch.bool).unsqueeze(0)\n episode_rewards = []\n\n # run for single trajectory\n for _ in range(max_traj_length):\n step_count += 1\n if RENDER:\n self.env.render()\n\n action = self._select_action(observation, eps).unsqueeze(0).long()\n next_observation, reward, done, _ = self.env.step(action.item())\n\n episode_rewards.append(float(reward))\n next_observation = torch.tensor(\n next_observation, device=device, dtype=dtype\n ).unsqueeze(0)\n reward = torch.tensor([reward], device=device, dtype=dtype).unsqueeze(0)\n done = torch.tensor([done], device=device, dtype=torch.bool).unsqueeze(\n 0\n )\n transition = Transition(\n observation, action, reward, next_observation, done\n )\n replay_buffer.append(transition)\n observation = next_observation\n\n # Update the Deep Q Network if sufficient transitions available\n if len(replay_buffer) >= min_buffer_size:\n loss = self._update(\n replay_buffer, batch_size, optimizer, gamma, polyak_const\n )\n\n if SAVE_FREQUENCY is not None:\n if (\n len(replay_buffer) >= min_buffer_size\n and step_count % (timesteps // SAVE_FREQUENCY) == 0\n ):\n self.save()\n\n if done or step_count == timesteps:\n break\n\n if step_count == timesteps:\n break\n\n # Log rewards and losses\n total_episode_reward = sum(episode_rewards)\n rewards.append(total_episode_reward)\n if VERBOSE:\n print(\n f\"Episode {episode+1}: Step Count = {step_count} | Reward = {total_episode_reward:.2f} | \",\n end=\"\",\n )\n if len(replay_buffer) >= min_buffer_size:\n print(f\" DNQ Loss = {loss:.2f}\")\n else:\n print(\"Collecting Experience\")\n\n self.env.close()\n print(f\"\\nTraining Completed in {(time.time() - start_time):.2f} seconds\")\n if PLOT_REWARDS:\n plt.plot(rewards)\n plt.title(f\"Training {self.__class__.__name__} on {self.env_name}\")\n plt.xlabel(\"Episodes\")\n plt.ylabel(\"Rewards\")\n plt.savefig(\n f\"./plots/{self.__class__.__name__}_{self.env_name}_reward_plot.png\"\n )\n\n def save(self, path=None):\n \"\"\" Save model parameters \"\"\"\n if path is None:\n path = f\"./models/{self.__class__.__name__}_{self.env_name}.pt\"\n torch.save(\n {f\"dqn_state_dict\": self.Q.state_dict()}, path,\n )\n print(f\"\\nSaved model parameters to {path}\")\n\n def load(self, path=None):\n \"\"\" Load model parameters \"\"\"\n if path is None:\n path = f\"./models/{self.__class__.__name__}_{self.env_name}.pt\"\n checkpoint = torch.load(path)\n self.Q.load_state_dict(checkpoint[\"dqn_state_dict\"])\n print(f\"\\nLoaded model parameters from {path}\")\n\n def eval(self, episodes, RENDER=False):\n \"\"\" Evaluates model performance \"\"\"\n\n print(f\"\\nEvaluating model for {episodes} episodes ...\\n\")\n start_time = time.time()\n self.Q.eval()\n rewards = []\n\n for episode in range(episodes):\n\n observation = self.env.reset()\n observation = torch.tensor(observation, device=device, dtype=dtype)\n done = False\n episode_rewards = []\n\n while not done:\n if RENDER:\n self.env.render()\n\n action = self._select_action(observation).long()\n next_observation, reward, done, _ = self.env.step(action.item())\n episode_rewards.append(float(reward))\n next_observation = torch.tensor(\n next_observation, device=device, dtype=dtype\n )\n observation = next_observation\n\n total_episode_reward = sum(episode_rewards)\n rewards.append(total_episode_reward)\n print(\n f\"Episode {episode+1}: Total Episode Reward = {total_episode_reward:.2f}\"\n )\n rewards.append(total_episode_reward)\n\n self.env.close()\n print(f\"\\nAverage Reward for an episode = {np.mean(rewards):.2f}\")\n print(f\"Evaluation Completed in {(time.time() - start_time):.2f} seconds\\n\")\n\n\nif __name__ == \"__main__\":\n\n # import gym\n # env = gym.make(\"CartPole-v1\")\n # env = gym.make(\"LunarLander-v2\")\n\n from pybullet_envs import bullet\n\n env = bullet.racecarGymEnv.RacecarGymEnv(renders=False, isDiscrete=True)\n\n model = DQN(env)\n model.train(VERBOSE=True, PLOT_REWARDS=True, SAVE_FREQUENCY=10)\n model.save()\n # model.load()\n model.eval(10, RENDER=True)\n" ]
[ [ "torch.nn.Linear", "torch.load", "torch.nn.MSELoss", "torch.argmax", "matplotlib.pyplot.savefig", "torch.no_grad", "torch.tensor", "numpy.random.random", "matplotlib.pyplot.title", "torch.nn.ReLU", "torch.cuda.is_available", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.plot", "torch.cat", "matplotlib.pyplot.xlabel", "numpy.mean" ] ]
a18shasa/a18shasa
[ "a6bcabac61e53b92893112f4e5361faa16547bc1" ]
[ "classifEvaluationFunctions.py" ]
[ "from sklearn.metrics import accuracy_score, precision_score, f1_score, recall_score, confusion_matrix\nimport pandas as pd\n\ndef getClassification_scores(true_classes, predicted_classes):\n acc = accuracy_score(true_classes, predicted_classes)\n prec = precision_score(true_classes, predicted_classes,average=\"macro\")\n f1 = f1_score(true_classes, predicted_classes,average=\"macro\")\n recall = recall_score(true_classes, predicted_classes,average=\"macro\")\n scores = [acc, prec, f1, recall]\n return scores\n\n\ndef evaluation_Step(mean_pred_probs):\n scores = getClassification_scores(mean_pred_probs['label'], mean_pred_probs['pred_class'])\n acc = scores[0]\n prec = scores[1]\n f1 = scores[2]\n recall = scores[3]\n \n print('Scores:')\n print('Accuracy: %f' % acc)\n print('Precision: %f' % prec)\n print('F1-score: %f' % f1)\n print('Recall: %f' % recall)\n \n\n #confusion matrix\n conf_mat_df = pd.crosstab(mean_pred_probs['label'], mean_pred_probs['pred_class'], margins=True)\n \n print('\\nConfusion matrix')\n print(conf_mat_df)\n return\n\n\n" ]
[ [ "pandas.crosstab", "sklearn.metrics.f1_score", "sklearn.metrics.accuracy_score", "sklearn.metrics.precision_score", "sklearn.metrics.recall_score" ] ]
cnheider/botorch
[ "1d90aaff64b2f1e1f49bcac233b45ba18427f6fd" ]
[ "botorch/optim/initializers.py" ]
[ "#!/usr/bin/env python3\n\nimport typing # noqa F401\nimport warnings\n\nimport torch\nfrom torch import Tensor\n\nfrom ..exceptions.warnings import BadInitialCandidatesWarning\n\n\ndef initialize_q_batch(X: Tensor, Y: Tensor, n: int, eta: float = 1.0) -> Tensor:\n r\"\"\"Heuristic for selecting initial conditions for candidate generation.\n\n This heuristic selects points from `X` (without replacement) with probability\n proportional to `exp(eta * Z)`, where `Z = (Y - mean(Y)) / std(Y)` and `eta`\n is a temperature parameter.\n\n When using an acquisiton function that is non-negative and possibly zero\n over large areas of the feature space (e.g. qEI), you should use\n `initialize_q_batch_nonneg` instead.\n\n Args:\n X: A `b x q x d` tensor of `b` samples of `q`-batches from a `d`-dim.\n feature space. Typically, these are generated using qMC sampling.\n Y: A tensor of `b` outcomes associated with the samples. Typically, this\n is the value of the batch acquisition function to be maximized.\n n: The number of initial condition to be generated. Must be less than `b`.\n eta: Temperature parameter for weighting samples.\n\n Returns:\n A `n x q x d` tensor of `n` `q`-batch initial conditions.\n\n Example:\n # To get `n=10` starting points of q-batch size `q=3` for model with `d=6`:\n >>> qUCB = qUpperConfidenceBound(model, beta=0.1)\n >>> Xrnd = torch.rand(500, 3, 6)\n >>> Xinit = initialize_q_batch(Xrnd, qUCB(Xrnd), 10)\n \"\"\"\n n_samples = X.shape[0]\n if n > n_samples:\n raise RuntimeError(\n f\"n ({n}) cannot be larger than the number of \"\n f\"provided samples ({n_samples})\"\n )\n elif n == n_samples:\n return X\n\n Ystd = Y.std()\n if Ystd == 0:\n warnings.warn(\n \"All acqusition values for raw samples points are the same. \"\n \"Choosing initial conditions at random.\",\n BadInitialCandidatesWarning,\n )\n return X[torch.randperm(n=n_samples, device=X.device)][:n]\n\n max_val, max_idx = torch.max(Y, dim=0)\n Z = Y - Y.mean() / Ystd\n weights = torch.exp(eta * Z)\n idcs = torch.multinomial(weights, n)\n # make sure we get the maximum\n if max_idx not in idcs:\n idcs[-1] = max_idx\n return X[idcs]\n\n\ndef initialize_q_batch_nonneg(\n X: Tensor, Y: Tensor, n: int, eta: float = 1.0, alpha: float = 1e-4\n) -> Tensor:\n r\"\"\"Heuristic for selecting initial conditions for non-neg. acquisition functions.\n\n This function is similar to `initialize_q_batch`, but designed specifically\n for acquisition functions that are non-negative and possibly zero over\n large areas of the feature space (e.g. qEI). All samples for which\n `Y < alpha * max(Y)` will be ignored (assuming that `Y` contains at least\n one positive value).\n\n Args:\n X: A `b x q x d` tensor of `b` samples of `q`-batches from a `d`-dim.\n feature space. Typically, these are generated using qMC.\n Y: A tensor of `b` outcomes associated with the samples. Typically, this\n is the value of the batch acquisition function to be maximized.\n n: The number of initial condition to be generated. Must be less than `b`.\n eta: Temperature parameter for weighting samples.\n alpha: The threshold (as a fraction of the maximum observed value) under\n which to ignore samples. All input samples for which\n `Y < alpha * max(Y)` will be ignored.\n\n Returns:\n A `n x q x d` tensor of `n` `q`-batch initial conditions.\n\n Example:\n # To get `n=10` starting points of q-batch size `q=3` for model with `d=6`:\n >>> qEI = qExpectedImprovement(model, best_f=0.2)\n >>> Xrnd = torch.rand(500, 3, 6)\n >>> Xinit = initialize_q_batch(Xrnd, qEI(Xrnd), 10)\n \"\"\"\n n_samples = X.shape[0]\n if n > n_samples:\n raise RuntimeError(\"n cannot be larger than the number of provided samples\")\n elif n == n_samples:\n return X\n\n max_val, max_idx = torch.max(Y, dim=0)\n if torch.any(max_val <= 0):\n warnings.warn(\n \"All acquisition values for raw sampled points are nonpositive, so \"\n \"initial conditions are being selected randomly.\",\n BadInitialCandidatesWarning,\n )\n return X[torch.randperm(n=n_samples, device=X.device)][:n]\n\n # make sure there are at least `n` points with positive acquisition values\n pos = Y > 0\n num_pos = pos.sum().item()\n if num_pos < n:\n # select all positive points and then fill remaining quota with randomly\n # selected points\n remaining_indices = (~pos).nonzero().view(-1)\n rand_indices = torch.randperm(remaining_indices.shape[0], device=Y.device)\n sampled_remaining_indices = remaining_indices[rand_indices[: n - num_pos]]\n pos[sampled_remaining_indices] = 1\n return X[pos]\n # select points within alpha of max_val, iteratively decreasing alpha by a\n # factor of 10 as necessary\n alpha_pos = Y >= alpha * max_val\n while alpha_pos.sum() < n:\n alpha = 0.1 * alpha\n alpha_pos = Y >= alpha * max_val\n alpha_pos_idcs = torch.arange(len(Y), device=Y.device)[alpha_pos]\n weights = torch.exp(eta * (Y[alpha_pos] / max_val - 1))\n idcs = alpha_pos_idcs[torch.multinomial(weights, n)]\n if max_idx not in idcs:\n idcs[-1] = max_idx\n return X[idcs]\n" ]
[ [ "torch.multinomial", "torch.exp", "torch.any", "torch.randperm", "torch.max" ] ]
srijan-deepsource/cupy
[ "f7c3d579b76b5f815fa8f4a0ddc79ef9ca2d3b02" ]
[ "tests/cupy_tests/math_tests/test_sumprod.py" ]
[ "import unittest\nimport math\n\nimport numpy\nimport pytest\n\nimport cupy\nimport cupy.core._accelerator as _acc\nfrom cupy.core import _cub_reduction\nfrom cupy import testing\n\n\[email protected]\nclass TestSumprod(unittest.TestCase):\n\n def tearDown(self):\n # Free huge memory for slow test\n cupy.get_default_memory_pool().free_all_blocks()\n cupy.get_default_pinned_memory_pool().free_all_blocks()\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_sum_all(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype)\n return a.sum()\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_sum_all_keepdims(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype)\n return a.sum(keepdims=True)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_external_sum_all(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype)\n return xp.sum(a)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_sum_all2(self, xp, dtype):\n a = testing.shaped_arange((20, 30, 40), xp, dtype)\n return a.sum()\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_sum_all_transposed(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype).transpose(2, 0, 1)\n return a.sum()\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_sum_all_transposed2(self, xp, dtype):\n a = testing.shaped_arange((20, 30, 40), xp, dtype).transpose(2, 0, 1)\n return a.sum()\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_sum_axis(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype)\n return a.sum(axis=1)\n\n @testing.slow\n @testing.numpy_cupy_allclose()\n def test_sum_axis_huge(self, xp):\n a = testing.shaped_random((2048, 1, 1024), xp, 'b')\n a = xp.broadcast_to(a, (2048, 1024, 1024))\n return a.sum(axis=2)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_external_sum_axis(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype)\n return xp.sum(a, axis=1)\n\n # float16 is omitted, since NumPy's sum on float16 arrays has more error\n # than CuPy's.\n @testing.for_all_dtypes(no_float16=True)\n @testing.numpy_cupy_allclose()\n def test_sum_axis2(self, xp, dtype):\n a = testing.shaped_arange((20, 30, 40), xp, dtype)\n return a.sum(axis=1)\n\n def test_sum_axis2_float16(self):\n # Note that the above test example overflows in float16. We use a\n # smaller array instead.\n a = testing.shaped_arange((2, 30, 4), dtype='e')\n sa = a.sum(axis=1)\n b = testing.shaped_arange((2, 30, 4), numpy, dtype='f')\n sb = b.sum(axis=1)\n testing.assert_allclose(sa, sb.astype('e'))\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(contiguous_check=False)\n def test_sum_axis_transposed(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype).transpose(2, 0, 1)\n return a.sum(axis=1)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(contiguous_check=False)\n def test_sum_axis_transposed2(self, xp, dtype):\n a = testing.shaped_arange((20, 30, 40), xp, dtype).transpose(2, 0, 1)\n return a.sum(axis=1)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_sum_axes(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4, 5), xp, dtype)\n return a.sum(axis=(1, 3))\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(rtol=1e-4)\n def test_sum_axes2(self, xp, dtype):\n a = testing.shaped_arange((20, 30, 40, 50), xp, dtype)\n return a.sum(axis=(1, 3))\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(rtol=1e-6)\n def test_sum_axes3(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4, 5), xp, dtype)\n return a.sum(axis=(0, 2, 3))\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(rtol=1e-6)\n def test_sum_axes4(self, xp, dtype):\n a = testing.shaped_arange((20, 30, 40, 50), xp, dtype)\n return a.sum(axis=(0, 2, 3))\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_sum_empty_axis(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4, 5), xp, dtype)\n return a.sum(axis=())\n\n @testing.for_all_dtypes_combination(names=['src_dtype', 'dst_dtype'])\n @testing.numpy_cupy_allclose()\n def test_sum_dtype(self, xp, src_dtype, dst_dtype):\n if not xp.can_cast(src_dtype, dst_dtype):\n pytest.skip()\n a = testing.shaped_arange((2, 3, 4), xp, src_dtype)\n return a.sum(dtype=dst_dtype)\n\n @testing.for_all_dtypes_combination(names=['src_dtype', 'dst_dtype'])\n @testing.numpy_cupy_allclose()\n def test_sum_keepdims_and_dtype(self, xp, src_dtype, dst_dtype):\n if not xp.can_cast(src_dtype, dst_dtype):\n pytest.skip()\n a = testing.shaped_arange((2, 3, 4), xp, src_dtype)\n return a.sum(axis=2, dtype=dst_dtype, keepdims=True)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_sum_keepdims_multiple_axes(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype)\n return a.sum(axis=(1, 2), keepdims=True)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_sum_out(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype)\n b = xp.empty((2, 4), dtype=dtype)\n a.sum(axis=1, out=b)\n return b\n\n def test_sum_out_wrong_shape(self):\n a = testing.shaped_arange((2, 3, 4))\n b = cupy.empty((2, 3))\n with self.assertRaises(ValueError):\n a.sum(axis=1, out=b)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_prod_all(self, xp, dtype):\n a = testing.shaped_arange((2, 3), xp, dtype)\n return a.prod()\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_external_prod_all(self, xp, dtype):\n a = testing.shaped_arange((2, 3), xp, dtype)\n return xp.prod(a)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_prod_axis(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype)\n return a.prod(axis=1)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_external_prod_axis(self, xp, dtype):\n a = testing.shaped_arange((2, 3, 4), xp, dtype)\n return xp.prod(a, axis=1)\n\n @testing.for_all_dtypes_combination(names=['src_dtype', 'dst_dtype'])\n @testing.numpy_cupy_allclose()\n def test_prod_dtype(self, xp, src_dtype, dst_dtype):\n if not xp.can_cast(src_dtype, dst_dtype):\n pytest.skip()\n a = testing.shaped_arange((2, 3), xp, src_dtype)\n return a.prod(dtype=dst_dtype)\n\n\n# This class compares CUB results against NumPy's\[email protected](*testing.product({\n 'shape': [(10,), (10, 20), (10, 20, 30), (10, 20, 30, 40)],\n 'order': ('C', 'F'),\n 'backend': ('device', 'block'),\n}))\[email protected]\[email protected](cupy.cuda.cub.available, 'The CUB routine is not enabled')\nclass TestCubReduction(unittest.TestCase):\n\n def setUp(self):\n self.old_routine_accelerators = _acc.get_routine_accelerators()\n self.old_reduction_accelerators = _acc.get_reduction_accelerators()\n if self.backend == 'device':\n _acc.set_routine_accelerators(['cub'])\n _acc.set_reduction_accelerators([])\n elif self.backend == 'block':\n _acc.set_routine_accelerators([])\n _acc.set_reduction_accelerators(['cub'])\n\n def tearDown(self):\n _acc.set_routine_accelerators(self.old_routine_accelerators)\n _acc.set_reduction_accelerators(self.old_reduction_accelerators)\n\n @testing.for_contiguous_axes()\n # sum supports less dtypes; don't test float16 as it's not as accurate?\n @testing.for_dtypes('lLfdFD')\n @testing.numpy_cupy_allclose(rtol=1E-5)\n def test_cub_sum(self, xp, dtype, axis):\n a = testing.shaped_random(self.shape, xp, dtype)\n if self.order in ('c', 'C'):\n a = xp.ascontiguousarray(a)\n elif self.order in ('f', 'F'):\n a = xp.asfortranarray(a)\n\n if xp is numpy:\n return a.sum(axis=axis)\n\n # xp is cupy, first ensure we really use CUB\n ret = cupy.empty(()) # Cython checks return type, need to fool it\n if self.backend == 'device':\n func_name = 'cupy.core._routines_math.cub.'\n if len(axis) == len(self.shape):\n func_name += 'device_reduce'\n else:\n func_name += 'device_segmented_reduce'\n with testing.AssertFunctionIsCalled(func_name, return_value=ret):\n a.sum(axis=axis)\n elif self.backend == 'block':\n # this is the only function we can mock; the rest is cdef'd\n func_name = 'cupy.core._cub_reduction.'\n func_name += '_SimpleCubReductionKernel_get_cached_function'\n func = _cub_reduction._SimpleCubReductionKernel_get_cached_function\n if len(axis) == len(self.shape):\n times_called = 2 # two passes\n else:\n times_called = 1 # one pass\n with testing.AssertFunctionIsCalled(\n func_name, wraps=func, times_called=times_called):\n a.sum(axis=axis)\n # ...then perform the actual computation\n return a.sum(axis=axis)\n\n # sum supports less dtypes; don't test float16 as it's not as accurate?\n @testing.for_dtypes('lLfdFD')\n @testing.numpy_cupy_allclose(rtol=1E-5, contiguous_check=False)\n def test_cub_sum_empty_axis(self, xp, dtype):\n a = testing.shaped_random(self.shape, xp, dtype)\n if self.order in ('c', 'C'):\n a = xp.ascontiguousarray(a)\n elif self.order in ('f', 'F'):\n a = xp.asfortranarray(a)\n return a.sum(axis=())\n\n @testing.for_contiguous_axes()\n # prod supports less dtypes; don't test float16 as it's not as accurate?\n @testing.for_dtypes('lLfdFD')\n @testing.numpy_cupy_allclose(rtol=1E-5)\n def test_cub_prod(self, xp, dtype, axis):\n a = testing.shaped_random(self.shape, xp, dtype)\n if self.order in ('c', 'C'):\n a = xp.ascontiguousarray(a)\n elif self.order in ('f', 'F'):\n a = xp.asfortranarray(a)\n\n if xp is numpy:\n return a.prod(axis=axis)\n\n # xp is cupy, first ensure we really use CUB\n ret = cupy.empty(()) # Cython checks return type, need to fool it\n if self.backend == 'device':\n func_name = 'cupy.core._routines_math.cub.'\n if len(axis) == len(self.shape):\n func_name += 'device_reduce'\n else:\n func_name += 'device_segmented_reduce'\n with testing.AssertFunctionIsCalled(func_name, return_value=ret):\n a.prod(axis=axis)\n elif self.backend == 'block':\n # this is the only function we can mock; the rest is cdef'd\n func_name = 'cupy.core._cub_reduction.'\n func_name += '_SimpleCubReductionKernel_get_cached_function'\n func = _cub_reduction._SimpleCubReductionKernel_get_cached_function\n if len(axis) == len(self.shape):\n times_called = 2 # two passes\n else:\n times_called = 1 # one pass\n with testing.AssertFunctionIsCalled(\n func_name, wraps=func, times_called=times_called):\n a.prod(axis=axis)\n # ...then perform the actual computation\n return a.prod(axis=axis)\n\n # TODO(leofang): test axis after support is added\n # don't test float16 as it's not as accurate?\n @testing.for_dtypes('bhilBHILfdF')\n @testing.numpy_cupy_allclose(rtol=1E-4)\n def test_cub_cumsum(self, xp, dtype):\n if self.backend == 'block':\n raise unittest.SkipTest('does not support')\n\n a = testing.shaped_random(self.shape, xp, dtype)\n if self.order in ('c', 'C'):\n a = xp.ascontiguousarray(a)\n elif self.order in ('f', 'F'):\n a = xp.asfortranarray(a)\n\n if xp is numpy:\n return a.cumsum()\n\n # xp is cupy, first ensure we really use CUB\n ret = cupy.empty(()) # Cython checks return type, need to fool it\n func = 'cupy.core._routines_math.cub.device_scan'\n with testing.AssertFunctionIsCalled(func, return_value=ret):\n a.cumsum()\n # ...then perform the actual computation\n return a.cumsum()\n\n # TODO(leofang): test axis after support is added\n # don't test float16 as it's not as accurate?\n @testing.for_dtypes('bhilBHILfdF')\n @testing.numpy_cupy_allclose(rtol=1E-4)\n def test_cub_cumprod(self, xp, dtype):\n if self.backend == 'block':\n raise unittest.SkipTest('does not support')\n\n a = testing.shaped_random(self.shape, xp, dtype)\n if self.order in ('c', 'C'):\n a = xp.ascontiguousarray(a)\n elif self.order in ('f', 'F'):\n a = xp.asfortranarray(a)\n\n if xp is numpy:\n result = a.cumprod()\n return self._mitigate_cumprod(xp, dtype, result)\n\n # xp is cupy, first ensure we really use CUB\n ret = cupy.empty(()) # Cython checks return type, need to fool it\n func = 'cupy.core._routines_math.cub.device_scan'\n with testing.AssertFunctionIsCalled(func, return_value=ret):\n a.cumprod()\n # ...then perform the actual computation\n result = a.cumprod()\n return self._mitigate_cumprod(xp, dtype, result)\n\n def _mitigate_cumprod(self, xp, dtype, result):\n # for testing cumprod against complex arrays, the gotcha is CuPy may\n # produce only Inf at the position where NumPy starts to give NaN. So,\n # an error would be raised during assert_allclose where the positions\n # of NaNs are examined. Since this is both algorithm and architecture\n # dependent, we have no control over this behavior and can only\n # circumvent the issue by manually converting Inf to NaN\n if dtype in (numpy.complex64, numpy.complex128):\n pos = xp.where(xp.isinf(result))\n result[pos] = xp.nan + 1j * xp.nan\n return result\n\n\n# This class compares cuTENSOR results against NumPy's\[email protected](*testing.product({\n 'shape': [(10,), (10, 20), (10, 20, 30), (10, 20, 30, 40)],\n 'order': ('C', 'F'),\n}))\[email protected]\[email protected](cupy.cuda.cutensor.available,\n 'The cuTENSOR routine is not enabled')\nclass TestCuTensorReduction(unittest.TestCase):\n\n def setUp(self):\n self.old_accelerators = cupy.core.get_routine_accelerators()\n cupy.core.set_routine_accelerators(['cutensor'])\n\n def tearDown(self):\n cupy.core.set_routine_accelerators(self.old_accelerators)\n\n @testing.for_contiguous_axes()\n # sum supports less dtypes; don't test float16 as it's not as accurate?\n @testing.for_dtypes('lLfdFD')\n @testing.numpy_cupy_allclose(rtol=1E-5, contiguous_check=False)\n def test_cutensor_sum(self, xp, dtype, axis):\n a = testing.shaped_random(self.shape, xp, dtype)\n if self.order in ('c', 'C'):\n a = xp.ascontiguousarray(a)\n elif self.order in ('f', 'F'):\n a = xp.asfortranarray(a)\n\n if xp is numpy:\n return a.sum(axis=axis)\n\n # xp is cupy, first ensure we really use cuTENSOR\n ret = cupy.empty(()) # Cython checks return type, need to fool it\n func = 'cupy.cutensor._try_reduction_routine'\n with testing.AssertFunctionIsCalled(func, return_value=ret):\n a.sum(axis=axis)\n # ...then perform the actual computation\n return a.sum(axis=axis)\n\n # sum supports less dtypes; don't test float16 as it's not as accurate?\n @testing.for_dtypes('lLfdFD')\n @testing.numpy_cupy_allclose(rtol=1E-5, contiguous_check=False)\n def test_cutensor_sum_empty_axis(self, xp, dtype):\n a = testing.shaped_random(self.shape, xp, dtype)\n if self.order in ('c', 'C'):\n a = xp.ascontiguousarray(a)\n elif self.order in ('f', 'F'):\n a = xp.asfortranarray(a)\n return a.sum(axis=())\n\n\[email protected](\n *testing.product({\n 'shape': [(2, 3, 4), (20, 30, 40)],\n 'axis': [0, 1],\n 'transpose_axes': [True, False],\n 'keepdims': [True, False],\n 'func': ['nansum', 'nanprod']\n })\n)\[email protected]\nclass TestNansumNanprodLong(unittest.TestCase):\n\n def _do_transposed_axis_test(self):\n return not self.transpose_axes and self.axis != 1\n\n def _numpy_nanprod_implemented(self):\n return (self.func == 'nanprod' and\n numpy.__version__ >= numpy.lib.NumpyVersion('1.10.0'))\n\n def _test(self, xp, dtype):\n a = testing.shaped_arange(self.shape, xp, dtype)\n if self.transpose_axes:\n a = a.transpose(2, 0, 1)\n if not issubclass(dtype, xp.integer):\n a[:, 1] = xp.nan\n func = getattr(xp, self.func)\n return func(a, axis=self.axis, keepdims=self.keepdims)\n\n @testing.for_all_dtypes(no_bool=True, no_float16=True)\n @testing.numpy_cupy_allclose()\n def test_nansum_all(self, xp, dtype):\n if (not self._numpy_nanprod_implemented() or\n not self._do_transposed_axis_test()):\n return xp.array(())\n return self._test(xp, dtype)\n\n @testing.for_all_dtypes(no_bool=True, no_float16=True)\n @testing.numpy_cupy_allclose(contiguous_check=False)\n def test_nansum_axis_transposed(self, xp, dtype):\n if (not self._numpy_nanprod_implemented() or\n not self._do_transposed_axis_test()):\n return xp.array(())\n return self._test(xp, dtype)\n\n\[email protected](\n *testing.product({\n 'shape': [(2, 3, 4), (20, 30, 40)],\n })\n)\[email protected]\nclass TestNansumNanprodExtra(unittest.TestCase):\n\n def test_nansum_axis_float16(self):\n # Note that the above test example overflows in float16. We use a\n # smaller array instead, return True if array is too large.\n if (numpy.prod(self.shape) > 24):\n return True\n a = testing.shaped_arange(self.shape, dtype='e')\n a[:, 1] = cupy.nan\n sa = cupy.nansum(a, axis=1)\n b = testing.shaped_arange(self.shape, numpy, dtype='f')\n b[:, 1] = numpy.nan\n sb = numpy.nansum(b, axis=1)\n testing.assert_allclose(sa, sb.astype('e'))\n\n @testing.for_all_dtypes(no_bool=True, no_float16=True)\n @testing.numpy_cupy_allclose()\n def test_nansum_out(self, xp, dtype):\n a = testing.shaped_arange(self.shape, xp, dtype)\n if not issubclass(dtype, xp.integer):\n a[:, 1] = xp.nan\n b = xp.empty((self.shape[0], self.shape[2]), dtype=dtype)\n xp.nansum(a, axis=1, out=b)\n return b\n\n def test_nansum_out_wrong_shape(self):\n a = testing.shaped_arange(self.shape)\n a[:, 1] = cupy.nan\n b = cupy.empty((2, 3))\n with self.assertRaises(ValueError):\n cupy.nansum(a, axis=1, out=b)\n\n\[email protected](\n *testing.product({\n 'shape': [(2, 3, 4, 5), (20, 30, 40, 50)],\n 'axis': [(1, 3), (0, 2, 3)],\n })\n)\[email protected]\nclass TestNansumNanprodAxes(unittest.TestCase):\n @testing.for_all_dtypes(no_bool=True, no_float16=True)\n @testing.numpy_cupy_allclose(rtol=1e-6)\n def test_nansum_axes(self, xp, dtype):\n a = testing.shaped_arange(self.shape, xp, dtype)\n if not issubclass(dtype, xp.integer):\n a[:, 1] = xp.nan\n return xp.nansum(a, axis=self.axis)\n\n\[email protected]\nclass TestNansumNanprodHuge(unittest.TestCase):\n def _test(self, xp, nan_slice):\n a = testing.shaped_random((2048, 1, 1024), xp, 'f')\n a[nan_slice] = xp.nan\n a = xp.broadcast_to(a, (2048, 1024, 1024))\n return xp.nansum(a, axis=2)\n\n @testing.slow\n @testing.numpy_cupy_allclose(atol=1e-1)\n def test_nansum_axis_huge(self, xp):\n return self._test(\n xp, (slice(None, None), slice(None, None), slice(1, 2)))\n\n @testing.slow\n @testing.numpy_cupy_allclose(atol=1e-2)\n def test_nansum_axis_huge_halfnan(self, xp):\n return self._test(\n xp, (slice(None, None), slice(None, None), slice(0, 512)))\n\n\naxes = [0, 1, 2]\n\n\[email protected](*testing.product({'axis': axes}))\[email protected]\nclass TestCumsum(unittest.TestCase):\n\n def _cumsum(self, xp, a, *args, **kwargs):\n b = a.copy()\n res = xp.cumsum(a, *args, **kwargs)\n testing.assert_array_equal(a, b) # Check if input array is overwritten\n return res\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumsum(self, xp, dtype):\n a = testing.shaped_arange((5,), xp, dtype)\n return self._cumsum(xp, a)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumsum_out(self, xp, dtype):\n a = testing.shaped_arange((5,), xp, dtype)\n out = xp.zeros((5,), dtype=dtype)\n self._cumsum(xp, a, out=out)\n return out\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumsum_out_noncontiguous(self, xp, dtype):\n a = testing.shaped_arange((5,), xp, dtype)\n out = xp.zeros((10,), dtype=dtype)[::2] # Non contiguous view\n self._cumsum(xp, a, out=out)\n return out\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumsum_2dim(self, xp, dtype):\n a = testing.shaped_arange((4, 5), xp, dtype)\n return self._cumsum(xp, a)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(contiguous_check=False)\n def test_cumsum_axis(self, xp, dtype):\n n = len(axes)\n a = testing.shaped_arange(tuple(range(4, 4 + n)), xp, dtype)\n return self._cumsum(xp, a, axis=self.axis)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumsum_axis_out(self, xp, dtype):\n n = len(axes)\n shape = tuple(range(4, 4 + n))\n a = testing.shaped_arange(shape, xp, dtype)\n out = xp.zeros(shape, dtype=dtype)\n self._cumsum(xp, a, axis=self.axis, out=out)\n return out\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumsum_axis_out_noncontiguous(self, xp, dtype):\n n = len(axes)\n shape = tuple(range(4, 4 + n))\n a = testing.shaped_arange(shape, xp, dtype)\n out = xp.zeros((8,)+shape[1:], dtype=dtype)[::2] # Non contiguous view\n self._cumsum(xp, a, axis=self.axis, out=out)\n return out\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(contiguous_check=False)\n def test_ndarray_cumsum_axis(self, xp, dtype):\n n = len(axes)\n a = testing.shaped_arange(tuple(range(4, 4 + n)), xp, dtype)\n return a.cumsum(axis=self.axis)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumsum_axis_empty(self, xp, dtype):\n n = len(axes)\n a = testing.shaped_arange(tuple(range(0, n)), xp, dtype)\n return self._cumsum(xp, a, axis=self.axis)\n\n @testing.for_all_dtypes()\n def test_invalid_axis_lower1(self, dtype):\n for xp in (numpy, cupy):\n a = testing.shaped_arange((4, 5), xp, dtype)\n with pytest.raises(numpy.AxisError):\n xp.cumsum(a, axis=-a.ndim - 1)\n\n @testing.for_all_dtypes()\n def test_invalid_axis_lower2(self, dtype):\n a = testing.shaped_arange((4, 5), cupy, dtype)\n with self.assertRaises(numpy.AxisError):\n return cupy.cumsum(a, axis=-a.ndim - 1)\n\n @testing.for_all_dtypes()\n def test_invalid_axis_upper1(self, dtype):\n for xp in (numpy, cupy):\n a = testing.shaped_arange((4, 5), xp, dtype)\n with pytest.raises(numpy.AxisError):\n xp.cumsum(a, axis=a.ndim + 1)\n\n @testing.for_all_dtypes()\n def test_invalid_axis_upper2(self, dtype):\n a = testing.shaped_arange((4, 5), cupy, dtype)\n with self.assertRaises(numpy.AxisError):\n return cupy.cumsum(a, axis=a.ndim + 1)\n\n def test_cumsum_arraylike(self):\n with self.assertRaises(TypeError):\n return cupy.cumsum((1, 2, 3))\n\n @testing.for_float_dtypes()\n def test_cumsum_numpy_array(self, dtype):\n a_numpy = numpy.arange(8, dtype=dtype)\n with self.assertRaises(TypeError):\n return cupy.cumsum(a_numpy)\n\n\[email protected]\nclass TestCumprod(unittest.TestCase):\n\n def _cumprod(self, xp, a, *args, **kwargs):\n b = a.copy()\n res = xp.cumprod(a, *args, **kwargs)\n testing.assert_array_equal(a, b) # Check if input array is overwritten\n return res\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumprod_1dim(self, xp, dtype):\n a = testing.shaped_arange((5,), xp, dtype)\n return self._cumprod(xp, a)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumprod_out(self, xp, dtype):\n a = testing.shaped_arange((5,), xp, dtype)\n out = xp.zeros((5,), dtype=dtype)\n self._cumprod(xp, a, out=out)\n return out\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumprod_out_noncontiguous(self, xp, dtype):\n a = testing.shaped_arange((5,), xp, dtype)\n out = xp.zeros((10,), dtype=dtype)[::2] # Non contiguous view\n self._cumprod(xp, a, out=out)\n return out\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose(rtol=1e-6)\n def test_cumprod_2dim_without_axis(self, xp, dtype):\n a = testing.shaped_arange((4, 5), xp, dtype)\n return self._cumprod(xp, a)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_cumprod_2dim_with_axis(self, xp, dtype):\n a = testing.shaped_arange((4, 5), xp, dtype)\n return self._cumprod(xp, a, axis=1)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_ndarray_cumprod_2dim_with_axis(self, xp, dtype):\n a = testing.shaped_arange((4, 5), xp, dtype)\n return a.cumprod(axis=1)\n\n @testing.slow\n def test_cumprod_huge_array(self):\n size = 2 ** 32\n # Free huge memory for slow test\n cupy.get_default_memory_pool().free_all_blocks()\n a = cupy.ones(size, 'b')\n result = cupy.cumprod(a, dtype='b')\n del a\n assert (result == 1).all()\n # Free huge memory for slow test\n del result\n cupy.get_default_memory_pool().free_all_blocks()\n\n @testing.for_all_dtypes()\n def test_invalid_axis_lower1(self, dtype):\n for xp in (numpy, cupy):\n a = testing.shaped_arange((4, 5), xp, dtype)\n with pytest.raises(numpy.AxisError):\n xp.cumprod(a, axis=-a.ndim - 1)\n\n @testing.for_all_dtypes()\n def test_invalid_axis_lower2(self, dtype):\n for xp in (numpy, cupy):\n a = testing.shaped_arange((4, 5), xp, dtype)\n with pytest.raises(numpy.AxisError):\n xp.cumprod(a, axis=-a.ndim - 1)\n\n @testing.for_all_dtypes()\n def test_invalid_axis_upper1(self, dtype):\n for xp in (numpy, cupy):\n a = testing.shaped_arange((4, 5), xp, dtype)\n with pytest.raises(numpy.AxisError):\n return xp.cumprod(a, axis=a.ndim)\n\n @testing.for_all_dtypes()\n def test_invalid_axis_upper2(self, dtype):\n a = testing.shaped_arange((4, 5), cupy, dtype)\n with self.assertRaises(numpy.AxisError):\n return cupy.cumprod(a, axis=a.ndim)\n\n def test_cumprod_arraylike(self):\n with self.assertRaises(TypeError):\n return cupy.cumprod((1, 2, 3))\n\n @testing.for_float_dtypes()\n def test_cumprod_numpy_array(self, dtype):\n a_numpy = numpy.arange(1, 6, dtype=dtype)\n with self.assertRaises(TypeError):\n return cupy.cumprod(a_numpy)\n\n\[email protected](*testing.product({\n 'shape': [(20,), (7, 6), (3, 4, 5)],\n 'axis': [None, 0, 1, 2],\n 'func': ('nancumsum', 'nancumprod'),\n}))\[email protected]\nclass TestNanCumSumProd(unittest.TestCase):\n\n zero_density = 0.25\n\n def _make_array(self, dtype):\n dtype = numpy.dtype(dtype)\n if dtype.char in 'efdFD':\n r_dtype = dtype.char.lower()\n a = testing.shaped_random(self.shape, numpy, dtype=r_dtype,\n scale=1)\n if dtype.char in 'FD':\n ai = a\n aj = testing.shaped_random(self.shape, numpy, dtype=r_dtype,\n scale=1)\n ai[ai < math.sqrt(self.zero_density)] = 0\n aj[aj < math.sqrt(self.zero_density)] = 0\n a = ai + 1j * aj\n else:\n a[a < self.zero_density] = 0\n a = a / a\n else:\n a = testing.shaped_random(self.shape, numpy, dtype=dtype)\n return a\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_nancumsumprod(self, xp, dtype):\n if self.axis is not None and self.axis >= len(self.shape):\n raise unittest.SkipTest()\n a = xp.array(self._make_array(dtype))\n out = getattr(xp, self.func)(a, axis=self.axis)\n return xp.ascontiguousarray(out)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_nancumsumprod_out(self, xp, dtype):\n dtype = numpy.dtype(dtype)\n if self.axis is not None and self.axis >= len(self.shape):\n raise unittest.SkipTest()\n if len(self.shape) > 1 and self.axis is None:\n # Skip the cases where np.nancum{sum|prod} raise AssertionError.\n raise unittest.SkipTest()\n a = xp.array(self._make_array(dtype))\n out = xp.empty(self.shape, dtype=dtype)\n getattr(xp, self.func)(a, axis=self.axis, out=out)\n return xp.ascontiguousarray(out)\n\n\[email protected]\nclass TestDiff(unittest.TestCase):\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_diff_1dim(self, xp, dtype):\n a = testing.shaped_arange((5,), xp, dtype)\n return xp.diff(a)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_diff_1dim_with_n(self, xp, dtype):\n a = testing.shaped_arange((5,), xp, dtype)\n return xp.diff(a, n=3)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_diff_2dim_without_axis(self, xp, dtype):\n a = testing.shaped_arange((4, 5), xp, dtype)\n return xp.diff(a)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_diff_2dim_with_axis(self, xp, dtype):\n a = testing.shaped_arange((4, 5), xp, dtype)\n return xp.diff(a, axis=-2)\n\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_diff_2dim_with_n_and_axis(self, xp, dtype):\n a = testing.shaped_arange((4, 5), xp, dtype)\n return xp.diff(a, 2, 1)\n\n @testing.with_requires('numpy>=1.16')\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_diff_2dim_with_prepend(self, xp, dtype):\n a = testing.shaped_arange((4, 5), xp, dtype)\n b = testing.shaped_arange((4, 1), xp, dtype)\n return xp.diff(a, axis=-1, prepend=b)\n\n @testing.with_requires('numpy>=1.16')\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_diff_2dim_with_append(self, xp, dtype):\n a = testing.shaped_arange((4, 5), xp, dtype)\n b = testing.shaped_arange((1, 5), xp, dtype)\n return xp.diff(a, axis=0, append=b, n=2)\n\n @testing.with_requires('numpy>=1.16')\n @testing.for_all_dtypes()\n @testing.numpy_cupy_allclose()\n def test_diff_2dim_with_scalar_append(self, xp, dtype):\n a = testing.shaped_arange((4, 5), xp, dtype)\n return xp.diff(a, prepend=1, append=0)\n\n @testing.with_requires('numpy>=1.16')\n def test_diff_invalid_axis(self):\n for xp in (numpy, cupy):\n a = testing.shaped_arange((2, 3, 4), xp)\n with pytest.raises(numpy.AxisError):\n xp.diff(a, axis=3)\n with pytest.raises(numpy.AxisError):\n xp.diff(a, axis=-4)\n\n\n# This class compares CUB results against NumPy's\[email protected](*testing.product_dict(\n testing.product({\n 'shape': [()],\n 'axis': [None, ()],\n 'spacing': [(), (1.2,)],\n })\n + testing.product({\n 'shape': [(33,)],\n 'axis': [None, 0, -1, (0,)],\n 'spacing': [(), (1.2,), 'sequence of int', 'arrays'],\n })\n + testing.product({\n 'shape': [(10, 20), (10, 20, 30)],\n 'axis': [None, 0, -1, (0, -1), (1, 0)],\n 'spacing': [(), (1.2,), 'sequence of int', 'arrays', 'mixed'],\n }),\n testing.product({\n 'edge_order': [1, 2],\n }),\n))\[email protected]\nclass TestGradient(unittest.TestCase):\n\n def _gradient(self, xp, dtype, shape, spacing, axis, edge_order):\n x = testing.shaped_random(shape, xp, dtype=dtype)\n if axis is None:\n normalized_axes = tuple(range(x.ndim))\n else:\n normalized_axes = axis\n if not isinstance(normalized_axes, tuple):\n normalized_axes = normalized_axes,\n normalized_axes = tuple(ax % x.ndim for ax in normalized_axes)\n if spacing == 'sequence of int':\n # one scalar per axis\n spacing = tuple((ax + 1) / x.ndim for ax in normalized_axes)\n elif spacing == 'arrays':\n # one array per axis\n spacing = tuple(\n xp.arange(x.shape[ax]) * (ax + 0.5) for ax in normalized_axes\n )\n # make at one of the arrays have non-constant spacing\n spacing[-1][5:] *= 2.0\n elif spacing == 'mixed':\n # mixture of arrays and scalars\n spacing = [xp.arange(x.shape[normalized_axes[0]])]\n spacing = spacing + [0.5] * (len(normalized_axes) - 1)\n return xp.gradient(x, *spacing, axis=axis, edge_order=edge_order)\n\n @testing.for_dtypes('fFdD')\n @testing.numpy_cupy_allclose(atol=1e-6, rtol=1e-5)\n def test_gradient_floating(self, xp, dtype):\n return self._gradient(xp, dtype, self.shape, self.spacing, self.axis,\n self.edge_order)\n\n # unsigned int behavior fixed in 1.18.1\n # https://github.com/numpy/numpy/issues/15207\n @testing.with_requires('numpy>=1.18.1')\n @testing.for_int_dtypes(no_bool=True)\n @testing.numpy_cupy_allclose(atol=1e-6, rtol=1e-5)\n def test_gradient_int(self, xp, dtype):\n return self._gradient(xp, dtype, self.shape, self.spacing, self.axis,\n self.edge_order)\n\n @testing.numpy_cupy_allclose(atol=2e-2, rtol=1e-3)\n def test_gradient_float16(self, xp):\n return self._gradient(xp, numpy.float16, self.shape, self.spacing,\n self.axis, self.edge_order)\n\n\[email protected]\nclass TestGradientErrors(unittest.TestCase):\n\n def test_gradient_invalid_spacings1(self):\n # more spacings than axes\n spacing = (1.0, 2.0, 3.0)\n for xp in [numpy, cupy]:\n x = testing.shaped_random((32, 16), xp)\n with pytest.raises(TypeError):\n xp.gradient(x, *spacing)\n\n def test_gradient_invalid_spacings2(self):\n # wrong length array in spacing\n shape = (32, 16)\n spacing = (15, cupy.arange(shape[1] + 1))\n for xp in [numpy, cupy]:\n x = testing.shaped_random(shape, xp)\n with pytest.raises(ValueError):\n xp.gradient(x, *spacing)\n\n def test_gradient_invalid_spacings3(self):\n # spacing array with ndim != 1\n shape = (32, 16)\n spacing = (15, cupy.arange(shape[0]).reshape(4, -1))\n for xp in [numpy, cupy]:\n x = testing.shaped_random(shape, xp)\n with pytest.raises(ValueError):\n xp.gradient(x, *spacing)\n\n def test_gradient_invalid_edge_order1(self):\n # unsupported edge order\n shape = (32, 16)\n for xp in [numpy, cupy]:\n x = testing.shaped_random(shape, xp)\n with pytest.raises(ValueError):\n xp.gradient(x, edge_order=3)\n\n def test_gradient_invalid_edge_order2(self):\n # shape cannot be < edge_order\n shape = (1, 16)\n for xp in [numpy, cupy]:\n x = testing.shaped_random(shape, xp)\n with pytest.raises(ValueError):\n xp.gradient(x, axis=0, edge_order=2)\n\n @testing.with_requires('numpy>=1.16')\n def test_gradient_invalid_axis(self):\n # axis out of range\n shape = (4, 16)\n for xp in [numpy, cupy]:\n x = testing.shaped_random(shape, xp)\n for axis in [-3, 2]:\n with pytest.raises(numpy.AxisError):\n xp.gradient(x, axis=axis)\n\n def test_gradient_bool_input(self):\n # axis out of range\n shape = (4, 16)\n for xp in [numpy, cupy]:\n x = testing.shaped_random(shape, xp, dtype=numpy.bool)\n with pytest.raises(TypeError):\n xp.gradient(x)\n" ]
[ [ "numpy.dtype", "numpy.lib.NumpyVersion", "numpy.arange", "numpy.nansum", "numpy.prod" ] ]
Ziggareto/cs229
[ "10b03b68b24d252dad3e3437561976d9509ebdd0" ]
[ "ps3/src/cartpole/cartpole.py" ]
[ "\"\"\"\nCS 229 Machine Learning\nQuestion: Reinforcement Learning - The Inverted Pendulum\n\"\"\"\n\nfrom __future__ import division, print_function\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom env import CartPole, Physics\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.signal import lfilter\n\n\"\"\"\nParts of the code (cart and pole dynamics, and the state\ndiscretization) are inspired from code available at the RL repository\nhttp://www-anw.cs.umass.edu/rlr/domains.html\n\nBriefly, the cart-pole system is described in `cart_pole.py`. The main\nsimulation loop in this file calls the `simulate()` function for\nsimulating the pole dynamics, `get_state()` for discretizing the\notherwise continuous state space in discrete states, and `show_cart()`\nfor display.\n\nSome useful parameters are listed below:\n\n`NUM_STATES`: Number of states in the discretized state space\nYou must assume that states are numbered 0 through `NUM_STATES` - 1. The\nstate numbered `NUM_STATES` - 1 (the last one) is a special state that\nmarks the state when the pole has been judged to have fallen (or when\nthe cart is out of bounds). However, you should NOT treat this state\nany differently in your code. Any distinctions you need to make between\nstates should come automatically from your learning algorithm.\n\nAfter each simulation cycle, you are supposed to update the transition\ncounts and rewards observed. However, you should not change either\nyour value function or the transition probability matrix at each\ncycle.\n\nWhenever the pole falls, a section of your code below will be\nexecuted. At this point, you must use the transition counts and reward\nobservations that you have gathered to generate a new model for the MDP\n(i.e. transition probabilities and state rewards). After that, you\nmust use value iteration to get the optimal value function for this MDP\nmodel.\n\n`TOLERANCE`: Controls the convergence criteria for each value iteration\nrun. In value iteration, you can assume convergence when the maximum\nabsolute change in the value function at any state in an iteration\nbecomes lower than `TOLERANCE.\n\nYou need to write code that chooses the best action according\nto your current value function, and the current model of the MDP. The\naction must be either 0 or 1 (corresponding to possible directions of\npushing the cart)\n\nFinally, we assume that the simulation has converged when\n`NO_LEARNING_THRESHOLD` consecutive value function computations all\nconverged within one value function iteration. Intuitively, it seems\nlike there will be little learning after this, so we end the simulation\nhere, and say the overall algorithm has converged.\n\n\nLearning curves can be generated by calling a code snippet at the end\n(it assumes that the learning was just executed, and the array\n`time_steps_to_failure` that records the time for which the pole was\nbalanced before each failure is in memory). `num_failures` is a variable\nthat stores the number of failures (pole drops / cart out of bounds)\ntill now.\n\nOther parameters in the code are described below:\n\n`GAMMA`: Discount factor to be used\n\nThe following parameters control the simulation display; you dont\nreally need to know about them:\n\n`pause_time`: Controls the pause between successive frames of the\ndisplay. Higher values make your simulation slower.\n`min_trial_length_to_start_display`: Allows you to start the display only\nafter the pole has been successfully balanced for at least this many\ntrials. Setting this to zero starts the display immediately. Choosing a\nreasonably high value (around 100) can allow you to rush through the\ninitial learning quickly, and start the display only after the\nperformance is reasonable.\n\"\"\"\n\ndef initialize_mdp_data(num_states):\n \"\"\"\n Return a variable that contains all the parameters/state you need for your MDP.\n Feel free to use whatever data type is most convenient for you (custom classes, tuples, dicts, etc)\n\n Assume that no transitions or rewards have been observed.\n Initialize the value function array to small random values (0 to 0.10, say).\n Initialize the transition probabilities uniformly (ie, probability of\n transitioning for state x to state y using action a is exactly\n 1/num_states).\n Initialize all state rewards to zero.\n\n Args:\n num_states: The number of states\n\n Returns: The initial MDP parameters\n \"\"\"\n transition_counts = np.zeros((num_states, num_states, 2)) # P_ijk = P_{s_i, a_k} (s_j) i.e. s_i -> s_j under a_k\n transition_probs = np.ones((num_states, num_states, 2)) / num_states # initial uniform distribution\n #Index zero is count of rewards being -1 , index 1 is count of total num state is reached\n reward_counts = np.zeros((num_states, 2)) \n reward = np.zeros(num_states)\n value = np.random.rand(num_states) * 0.1 # - 0.05 - 1/num_states\n\n return {\n 'transition_counts': transition_counts,\n 'transition_probs': transition_probs,\n 'reward_counts': reward_counts,\n 'reward': reward,\n 'value': value,\n 'num_states': num_states,\n 'state_action_history': [[]]\n }\n\ndef choose_action(state, mdp_data):\n \"\"\"\n Choose the next action (0 or 1) that is optimal according to your current\n mdp_data. When there is no optimal action, return a random action.\n\n Args:\n state: The current state in the MDP\n mdp_data: The parameters for your MDP. See initialize_mdp_data.\n\n Returns:\n 0 or 1 that is optimal according to your current MDP\n \"\"\"\n\n # *** START CODE HERE ***\n # argmax over actions a of sum_s' P_sa(s') V(s')\n # s, s', a axes. times in axis s', sum over it, argmax over a and then take state s\n expected_state_action_value = (mdp_data['transition_probs'] * mdp_data['value'].reshape(1, -1, 1)).sum(axis=1)\n optimal = expected_state_action_value.argmax(axis=1) # argmax over the 2 actions\n is_optimal = expected_state_action_value[state][int(optimal[state])] > \\\n expected_state_action_value[state][int(not optimal[state])]\n action = optimal[state] if is_optimal else np.random.randint(2)\n #print(f'state: {state}; optimal action: {action}; expected values: {expected_state_action_value[state]}')\n return optimal[state] if expected_state_action_value[state][int(optimal[state])] > expected_state_action_value[state][int(not optimal[state])] else np.random.randint(2)\n # *** END CODE HERE ***\n\ndef update_mdp_transition_counts_reward_counts(mdp_data, state, action, new_state, reward):\n \"\"\"\n Update the transition count and reward count information in your mdp_data. \n Do not change the other MDP parameters (those get changed later).\n\n Record the number of times `state, action, new_state` occurs.\n Record the rewards for every `new_state` \n (since rewards are -1 or 0, you just need to record number of times reward -1 is seen in 'reward_counts' index new_state,0)\n Record the number of time `new_state` was reached (in 'reward_counts' index new_state,1)\n\n Args:\n mdp_data: The parameters of your MDP. See initialize_mdp_data.\n state: The state that was observed at the start.\n action: The action you performed.\n new_state: The state after your action.\n reward: The reward after your action (i.e. reward corresponding to new_state).\n\n Returns:\n Nothing\n \"\"\"\n\n # *** START CODE HERE ***\n mdp_data['state_action_history'][-1].append([state, action, new_state])\n if reward == -1:\n mdp_data['reward_counts'][new_state][0] += 1\n mdp_data['reward_counts'][new_state][1] += 1 # the number of times reaching this state regardless of reward -1 or 0\n\n mdp_data['transition_counts'][state, new_state, action] += 1\n\n # *** END CODE HERE ***\n\n # This function does not return anything\n return\n\ndef update_mdp_transition_probs_reward(mdp_data):\n \"\"\"\n Update the estimated transition probabilities and reward values in your MDP.\n\n Make sure you account for the case when a state-action pair has never\n been tried before, or the state has never been visited before. In that\n case, you must not change that component (and thus keep it at the\n initialized uniform distribution).\n \n Args:\n mdp_data: The data for your MDP. See initialize_mdp_data.\n\n Returns:\n Nothing\n\n \"\"\"\n\n # *** START CODE HERE ***\n num_states = mdp_data['value'].shape[0]\n transition_counts = mdp_data['transition_counts']\n # i.e. some s' transition occured for s,a pair\n state_actions_occurred = transition_counts.sum(axis=1) > 0\n state_actions_occurred = np.tile(state_actions_occurred, (num_states, 1, 1)).transpose(1,0,2)\n # where s,a pair occured take from counts, otherwise from the previous probs\n transition_probs = np.where(state_actions_occurred, transition_counts, mdp_data['transition_probs'])\n # counts at s' for s,a pair divided by total counts for s,a is our new prob - or same as old prob if no s,a\n # pair occured\n transition_probs = transition_probs/transition_probs.sum(axis=1).reshape(num_states, 1, 2)\n mdp_data['transition_probs'] = transition_probs\n\n # number of -1 rewards divided by total number of rewards (more general would be sum rewards / number times visited)\n # rewards <-> new states, so did we ever reach this new state?\n reward_occured = transition_counts.sum(axis=(0, 2)) > 0\n reward = np.where(reward_occured, - mdp_data['reward_counts'][:, 0] / mdp_data['reward_counts'][:, 1], mdp_data['reward'])\n mdp_data['reward'] = reward\n # *** END CODE HERE ***\n\n # This function does not return anything\n return\n\ndef update_mdp_value(mdp_data, tolerance, gamma):\n \"\"\"\n Update the estimated values in your MDP.\n\n\n Perform value iteration using the new estimated model for the MDP.\n The convergence criterion should be based on `TOLERANCE` as described\n at the top of the file.\n\n Return true if it converges within one iteration.\n \n Args:\n mdp_data: The data for your MDP. See initialize_mdp_data.\n tolerance: The tolerance to use for the convergence criterion.\n gamma: Your discount factor.\n\n Returns:\n True if the value iteration converged in one iteration\n\n \"\"\"\n\n # *** START CODE HERE ***\n action_values = (mdp_data['transition_probs'] * mdp_data['value'].reshape(1, -1, 1)).sum(axis=1)\n old_value = mdp_data['value']\n mdp_data['value'] = mdp_data['reward'] + gamma * action_values.max(axis=1)\n\n max_diff = np.max(np.abs(mdp_data['value'] - old_value))\n print(f'max state value diff: {max_diff}')\n return max_diff < tolerance\n # *** END CODE HERE ***\n\ndef plot_mdp_data(mdp_data):\n plt.figure()\n plt.plot(mdp_data['value'])\n\ndef main(plot=True):\n # Seed the randomness of the simulation so this outputs the same thing each time\n np.random.seed(3)\n\n # Simulation parameters\n pause_time = 0.0001\n min_trial_length_to_start_display = 100\n display_started = min_trial_length_to_start_display == 0\n\n NUM_STATES = 163\n GAMMA = 0.995\n TOLERANCE = 0.01\n NO_LEARNING_THRESHOLD = 20\n # TOTAL_MAX_TRIALS might be useful otherwise it takes up to 300 ish iterations to converge sometimes\n\n # Time cycle of the simulation\n time = 0\n\n # These variables perform bookkeeping (how many cycles was the pole\n # balanced for before it fell). Useful for plotting learning curves.\n time_steps_to_failure = []\n num_failures = 0\n time_at_start_of_current_trial = 0\n\n # You should reach convergence well before this\n max_failures = 500\n\n # Initialize a cart pole\n cart_pole = CartPole(Physics())\n\n # Starting `state_tuple` is (0, 0, 0, 0)\n # x, x_dot, theta, theta_dot represents the actual continuous state vector\n x, x_dot, theta, theta_dot = 0.0, 0.0, 0.0, 0.0\n state_tuple = (x, x_dot, theta, theta_dot)\n\n # `state` is the number given to this state, you only need to consider\n # this representation of the state\n state = cart_pole.get_state(state_tuple)\n if min_trial_length_to_start_display == 0 or display_started == 1:\n cart_pole.show_cart(state_tuple, pause_time)\n\n mdp_data = initialize_mdp_data(NUM_STATES)\n\n # This is the criterion to end the simulation.\n # You should change it to terminate when the previous\n # 'NO_LEARNING_THRESHOLD' consecutive value function computations all\n # converged within one value function iteration. Intuitively, it seems\n # like there will be little learning after this, so end the simulation\n # here, and say the overall algorithm has converged.\n\n\n consecutive_no_learning_trials = 0\n while consecutive_no_learning_trials < NO_LEARNING_THRESHOLD:\n\n action = choose_action(state, mdp_data)\n\n # Get the next state by simulating the dynamics\n state_tuple = cart_pole.simulate(action, state_tuple)\n # x, x_dot, theta, theta_dot = state_tuple\n\n # Increment simulation time\n time = time + 1\n\n # Get the state number corresponding to new state vector\n new_state = cart_pole.get_state(state_tuple)\n # if display_started == 1:\n # cart_pole.show_cart(state_tuple, pause_time)\n\n #print(f'state transition prob: {state}, {action} -> {new_state}: {mdp_data[\"transition_probs\"][state, new_state, action]}')\n\n # reward function to use - do not change this!\n if new_state == NUM_STATES - 1:\n R = -1\n else:\n R = 0\n\n # add to transition count for s, s', a triple and to reward count for s'\n update_mdp_transition_counts_reward_counts(mdp_data, state, action, new_state, R)\n\n # Recompute MDP model whenever pole falls\n # Compute the value function V for the new model\n if new_state == NUM_STATES - 1:\n\n update_mdp_transition_probs_reward(mdp_data)\n\n converged_in_one_iteration = update_mdp_value(mdp_data, TOLERANCE, GAMMA)\n\n if converged_in_one_iteration:\n consecutive_no_learning_trials = consecutive_no_learning_trials + 1\n else:\n consecutive_no_learning_trials = 0\n\n # Do NOT change this code: Controls the simulation, and handles the case\n # when the pole fell and the state must be reinitialized.\n if new_state == NUM_STATES - 1:\n num_failures += 1\n if num_failures >= max_failures:\n break\n print('[INFO] Failure number {}'.format(num_failures))\n # plot_mdp_data(mdp_data)\n time_steps_to_failure.append(time - time_at_start_of_current_trial)\n print(f'time to failure: {time_steps_to_failure[-1]}')\n # print(f'history: {mdp_data[\"state_action_history\"][-1]}')\n mdp_data[\"state_action_history\"].append([])\n # time_steps_to_failure[num_failures] = time - time_at_start_of_current_trial\n time_at_start_of_current_trial = time\n\n if time_steps_to_failure[num_failures - 1] > min_trial_length_to_start_display:\n display_started = 1\n\n # Reinitialize state\n # x = 0.0\n x = -1.1 + np.random.uniform() * 2.2\n x_dot, theta, theta_dot = 0.0, 0.0, 0.0\n state_tuple = (x, x_dot, theta, theta_dot)\n state = cart_pole.get_state(state_tuple)\n else:\n state = new_state\n\n if plot:\n plt.figure()\n # plot the learning curve (time balanced vs. trial)\n log_tstf = np.log(np.array(time_steps_to_failure))\n plt.plot(np.arange(len(time_steps_to_failure)), log_tstf, 'k')\n window = 30\n w = np.array([1/window for _ in range(window)])\n weights = lfilter(w, 1, log_tstf)\n x = np.arange(window//2, len(log_tstf) - window//2)\n plt.plot(x, weights[window:len(log_tstf)], 'r--')\n plt.xlabel('Num failures')\n plt.ylabel('Log of num steps to failure')\n plt.savefig('./control_seed3.pdf')\n\n return np.array(time_steps_to_failure)\n \nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.random.uniform", "numpy.ones", "numpy.tile", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "numpy.random.seed", "numpy.abs", "scipy.signal.lfilter", "matplotlib.pyplot.ylabel", "numpy.random.rand", "matplotlib.use", "matplotlib.pyplot.plot", "numpy.where", "numpy.random.randint", "numpy.array", "matplotlib.pyplot.xlabel" ] ]
johnjim0816/rl-tutorials
[ "5d271a43e7b24e9b0d982636d44159e25d4ae30e" ]
[ "codes/TD3/agent.py" ]
[ "#!/usr/bin/env python\n# coding=utf-8\n'''\nAuthor: JiangJi\nEmail: [email protected]\nDate: 2021-12-22 10:40:05\nLastEditor: JiangJi\nLastEditTime: 2021-12-22 10:43:55\nDiscription: \n'''\nimport copy\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom TD3.memory import ReplayBuffer\n\nclass Actor(nn.Module):\n\t\n\tdef __init__(self, input_dim, output_dim, max_action):\n\t\t'''[summary]\n\n\t\tArgs:\n\t\t\tinput_dim (int): 输入维度,这里等于n_states\n\t\t\toutput_dim (int): 输出维度,这里等于n_actions\n\t\t\tmax_action (int): action的最大值\n\t\t'''\t\t\n\t\tsuper(Actor, self).__init__()\n\n\t\tself.l1 = nn.Linear(input_dim, 256)\n\t\tself.l2 = nn.Linear(256, 256)\n\t\tself.l3 = nn.Linear(256, output_dim)\n\t\tself.max_action = max_action\n\t\n\tdef forward(self, state):\n\t\t\n\t\ta = F.relu(self.l1(state))\n\t\ta = F.relu(self.l2(a))\n\t\treturn self.max_action * torch.tanh(self.l3(a))\n\n\nclass Critic(nn.Module):\n\tdef __init__(self, input_dim, output_dim):\n\t\tsuper(Critic, self).__init__()\n\n\t\t# Q1 architecture\n\t\tself.l1 = nn.Linear(input_dim + output_dim, 256)\n\t\tself.l2 = nn.Linear(256, 256)\n\t\tself.l3 = nn.Linear(256, 1)\n\n\t\t# Q2 architecture\n\t\tself.l4 = nn.Linear(input_dim + output_dim, 256)\n\t\tself.l5 = nn.Linear(256, 256)\n\t\tself.l6 = nn.Linear(256, 1)\n\n\n\tdef forward(self, state, action):\n\t\tsa = torch.cat([state, action], 1)\n\n\t\tq1 = F.relu(self.l1(sa))\n\t\tq1 = F.relu(self.l2(q1))\n\t\tq1 = self.l3(q1)\n\n\t\tq2 = F.relu(self.l4(sa))\n\t\tq2 = F.relu(self.l5(q2))\n\t\tq2 = self.l6(q2)\n\t\treturn q1, q2\n\n\n\tdef Q1(self, state, action):\n\t\tsa = torch.cat([state, action], 1)\n\n\t\tq1 = F.relu(self.l1(sa))\n\t\tq1 = F.relu(self.l2(q1))\n\t\tq1 = self.l3(q1)\n\t\treturn q1\n\n\nclass TD3(object):\n\tdef __init__(\n\t\tself,\n\t\tinput_dim,\n\t\toutput_dim,\n\t\tmax_action,\n\t\tcfg,\n\t):\n\t\tself.max_action = max_action\n\t\tself.gamma = cfg.gamma\n\t\tself.lr = cfg.lr\n\t\tself.policy_noise = cfg.policy_noise\n\t\tself.noise_clip = cfg.noise_clip\n\t\tself.policy_freq = cfg.policy_freq\n\t\tself.batch_size = cfg.batch_size \n\t\tself.device = cfg.device\n\t\tself.total_it = 0\n\n\t\tself.actor = Actor(input_dim, output_dim, max_action).to(self.device)\n\t\tself.actor_target = copy.deepcopy(self.actor)\n\t\tself.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=3e-4)\n\n\t\tself.critic = Critic(input_dim, output_dim).to(self.device)\n\t\tself.critic_target = copy.deepcopy(self.critic)\n\t\tself.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=3e-4)\n\t\tself.memory = ReplayBuffer(input_dim, output_dim)\n\n\tdef choose_action(self, state):\n\t\tstate = torch.FloatTensor(state.reshape(1, -1)).to(self.device)\n\t\treturn self.actor(state).cpu().data.numpy().flatten()\n\n\tdef update(self):\n\t\tself.total_it += 1\n\n\t\t# Sample replay buffer \n\t\tstate, action, next_state, reward, not_done = self.memory.sample(self.batch_size)\n\n\t\twith torch.no_grad():\n\t\t\t# Select action according to policy and add clipped noise\n\t\t\tnoise = (\n\t\t\t\ttorch.randn_like(action) * self.policy_noise\n\t\t\t).clamp(-self.noise_clip, self.noise_clip)\n\t\t\t\n\t\t\tnext_action = (\n\t\t\t\tself.actor_target(next_state) + noise\n\t\t\t).clamp(-self.max_action, self.max_action)\n\n\t\t\t# Compute the target Q value\n\t\t\ttarget_Q1, target_Q2 = self.critic_target(next_state, next_action)\n\t\t\ttarget_Q = torch.min(target_Q1, target_Q2)\n\t\t\ttarget_Q = reward + not_done * self.gamma * target_Q\n\n\t\t# Get current Q estimates\n\t\tcurrent_Q1, current_Q2 = self.critic(state, action)\n\n\t\t# Compute critic loss\n\t\tcritic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q)\n\n\t\t# Optimize the critic\n\t\tself.critic_optimizer.zero_grad()\n\t\tcritic_loss.backward()\n\t\tself.critic_optimizer.step()\n\n\t\t# Delayed policy updates\n\t\tif self.total_it % self.policy_freq == 0:\n\n\t\t\t# Compute actor losse\n\t\t\tactor_loss = -self.critic.Q1(state, self.actor(state)).mean()\n\t\t\t\n\t\t\t# Optimize the actor \n\t\t\tself.actor_optimizer.zero_grad()\n\t\t\tactor_loss.backward()\n\t\t\tself.actor_optimizer.step()\n\n\t\t\t# Update the frozen target models\n\t\t\tfor param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\n\t\t\t\ttarget_param.data.copy_(self.lr * param.data + (1 - self.lr) * target_param.data)\n\n\t\t\tfor param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\n\t\t\t\ttarget_param.data.copy_(self.lr * param.data + (1 - self.lr) * target_param.data)\n\n\n\tdef save(self, path):\n\t\ttorch.save(self.critic.state_dict(), path + \"td3_critic\")\n\t\ttorch.save(self.critic_optimizer.state_dict(), path + \"td3_critic_optimizer\")\n\t\t\n\t\ttorch.save(self.actor.state_dict(), path + \"td3_actor\")\n\t\ttorch.save(self.actor_optimizer.state_dict(), path + \"td3_actor_optimizer\")\n\n\n\tdef load(self, path):\n\t\tself.critic.load_state_dict(torch.load(path + \"td3_critic\"))\n\t\tself.critic_optimizer.load_state_dict(torch.load(path + \"td3_critic_optimizer\"))\n\t\tself.critic_target = copy.deepcopy(self.critic)\n\n\t\tself.actor.load_state_dict(torch.load(path + \"td3_actor\"))\n\t\tself.actor_optimizer.load_state_dict(torch.load(path + \"td3_actor_optimizer\"))\n\t\tself.actor_target = copy.deepcopy(self.actor)\n\t\t\n" ]
[ [ "torch.nn.functional.mse_loss", "torch.min", "torch.nn.Linear", "torch.load", "torch.randn_like", "torch.no_grad", "torch.cat" ] ]
Hellowlol/bw_plex
[ "86768d6ee89ee1c08d2f6e6468976e4c51135915" ]
[ "bw_plex/audfprint/audfprint_match.py" ]
[ "# coding=utf-8\n\"\"\"\naudfprint_match.py\n\nFingerprint matching code for audfprint\n\n2014-05-26 Dan Ellis [email protected]\n\"\"\"\nfrom __future__ import division, print_function\nimport os\nimport time\n\nimport psutil\nimport matplotlib.pyplot as plt\nimport librosa\nimport numpy as np\nimport scipy.signal\n\nfrom . import audfprint_analyze # for localtest and illustrate\nfrom . import audio_read\n\n\ndef process_info():\n rss = usrtime = 0\n p = psutil.Process(os.getpid())\n if os.name == 'nt':\n rss = p.memory_info()[0]\n usrtime = p.cpu_times()[0]\n else:\n rss = p.get_memory_info()[0]\n usrtime = p.get_cpu_times()[0]\n return rss, usrtime\n\n\ndef log(message):\n \"\"\" log info with stats \"\"\"\n print('%s physmem=%s utime=%s %s' % (time.ctime(), process_info()))\n\n\ndef encpowerof2(val):\n \"\"\" Return N s.t. 2^N >= val \"\"\"\n return int(np.ceil(np.log(max(1, val)) / np.log(2)))\n\n\ndef locmax(vec, indices=False):\n \"\"\" Return a boolean vector of which points in vec are local maxima.\n End points are peaks if larger than single neighbors.\n if indices=True, return the indices of the True values instead\n of the boolean vector. (originally from audfprint.py)\n \"\"\"\n # x[-1]-1 means last value can be a peak\n # nbr = np.greater_equal(np.r_[x, x[-1]-1], np.r_[x[0], x])\n # the np.r_ was killing us, so try an optimization...\n nbr = np.zeros(len(vec) + 1, dtype=bool)\n nbr[0] = True\n nbr[1:-1] = np.greater_equal(vec[1:], vec[:-1])\n maxmask = (nbr[:-1] & ~nbr[1:])\n if indices:\n return np.nonzero(maxmask)[0]\n else:\n return maxmask\n\n\ndef keep_local_maxes(vec):\n \"\"\" Zero out values unless they are local maxima.\"\"\"\n local_maxes = np.zeros(vec.shape)\n locmaxindices = locmax(vec, indices=True)\n local_maxes[locmaxindices] = vec[locmaxindices]\n return local_maxes\n\n\ndef find_modes(data, threshold=5, window=0):\n \"\"\" Find multiple modes in data, Report a list of (mode, count)\n pairs for every mode greater than or equal to threshold.\n Only local maxima in counts are returned.\n \"\"\"\n # TODO: Ignores window at present\n datamin = np.amin(data)\n fullvector = np.bincount(data - datamin)\n # Find local maxima\n localmaxes = np.nonzero(np.logical_and(locmax(fullvector),\n np.greater_equal(fullvector,\n threshold)))[0]\n return localmaxes + datamin, fullvector[localmaxes]\n\n\nclass Matcher(object):\n \"\"\"Provide matching for audfprint fingerprint queries to hash table\"\"\"\n\n def __init__(self):\n \"\"\"Set up default object values\"\"\"\n # Tolerance window for time differences\n self.window = 1\n # Absolute minimum number of matching hashes to count as a match\n self.threshcount = 5\n # How many hits to return?\n self.max_returns = 1\n # How deep to search in return list?\n self.search_depth = 100\n # Sort those returns by time (instead of counts)?\n self.sort_by_time = False\n # Verbose reporting?\n self.verbose = False\n # Do illustration?\n self.illustrate = False\n # Careful counts?\n self.exact_count = False\n # Search for time range?\n self.find_time_range = False\n # Quantile of time range to report.\n self.time_quantile = 0.02\n # Display pre-emphasized spectrogram in illustrate_match?\n self.illustrate_hpf = False\n # If there are a lot of matches within a single track at different\n # alignments, stop looking after a while.\n self.max_alignments_per_id = 100\n\n def _best_count_ids(self, hits, ht):\n \"\"\" Return the indexes for the ids with the best counts.\n hits is a matrix as returned by hash_table.get_hits()\n with rows of consisting of [id dtime hash otime] \"\"\"\n allids = hits[:, 0]\n ids = np.unique(allids)\n # rawcounts = np.sum(np.equal.outer(ids, allids), axis=1)\n # much faster, and doesn't explode memory\n rawcounts = np.bincount(allids)[ids]\n # Divide the raw counts by the total number of hashes stored\n # for the ref track, to downweight large numbers of chance\n # matches against longer reference tracks.\n wtdcounts = rawcounts / (ht.hashesperid[ids].astype(float))\n\n # Find all the actual hits for a the most popular ids\n bestcountsixs = np.argsort(wtdcounts)[::-1]\n # We will examine however many hits have rawcounts above threshold\n # up to a maximum of search_depth.\n maxdepth = np.minimum(np.count_nonzero(np.greater(rawcounts,\n self.threshcount)),\n self.search_depth)\n # Return the ids to check\n bestcountsixs = bestcountsixs[:maxdepth]\n return ids[bestcountsixs], rawcounts[bestcountsixs]\n\n def _unique_match_hashes(self, id, hits, mode):\n \"\"\" Return the list of unique matching hashes. Split out so\n we can recover the actual matching hashes for the best\n match if required. \"\"\"\n allids = hits[:, 0]\n alltimes = hits[:, 1]\n allhashes = hits[:, 2].astype(np.int64)\n allotimes = hits[:, 3]\n timebits = max(1, encpowerof2(np.amax(allotimes)))\n # matchhashes may include repeats because multiple\n # ref hashes may match a single query hash under window.\n # Uniqify:\n # matchhashes = sorted(list(set(matchhashes)))\n # much, much faster:\n matchix = np.nonzero(\n np.logical_and(allids == id, np.less_equal(np.abs(alltimes - mode),\n self.window)))[0]\n matchhasheshash = np.unique(allotimes[matchix]\n + (allhashes[matchix] << timebits))\n timemask = (1 << timebits) - 1\n matchhashes = np.c_[matchhasheshash & timemask,\n matchhasheshash >> timebits]\n return matchhashes\n\n def _calculate_time_ranges(self, hits, id, mode):\n \"\"\"Given the id and mode, return the actual time support.\n hits is an np.array of id, skew_time, hash, orig_time\n which must be sorted in orig_time order.\"\"\"\n minoffset = mode - self.window\n maxoffset = mode + self.window\n # match_times = sorted(hits[row, 3]\n # for row in np.nonzero(hits[:, 0]==id)[0]\n # if mode - self.window <= hits[row, 1]\n # and hits[row, 1] <= mode + self.window)\n match_times = hits[np.logical_and(hits[:, 1] >= minoffset,\n hits[:, 1] <= maxoffset), 3]\n min_time = match_times[int(len(match_times) * self.time_quantile)]\n max_time = match_times[int(len(match_times) * (1.0 - self.time_quantile)) - 1]\n # log(\"_calc_time_ranges: len(hits)={:d} id={:d} mode={:d} matches={:d} min={:d} max={:d}\".format(\n # len(hits), id, mode, np.sum(np.logical_and(hits[:, 1] >= minoffset,\n # hits[:, 1] <= maxoffset)),\n # min_time, max_time))\n return min_time, max_time\n\n def _exact_match_counts(self, hits, ids, rawcounts, hashesfor=None):\n \"\"\"Find the number of \"filtered\" (time-consistent) matching hashes\n for each of the promising ids in <ids>. Return an\n np.array whose rows are [id, filtered_count,\n modal_time_skew, unfiltered_count, original_rank,\n min_time, max_time]. Results are sorted by original rank\n (but will not in general include all the the original\n IDs). There can be multiple rows for a single ID, if\n there are several distinct time_skews giving good\n matches.\n \"\"\"\n # Sort hits into time_in_original order - needed for _calc_time_range\n sorted_hits = hits[hits[:, 3].argsort()]\n # Slower, old process for exact match counts\n allids = sorted_hits[:, 0]\n alltimes = sorted_hits[:, 1]\n allhashes = sorted_hits[:, 2]\n # allotimes = sorted_hits[:, 3]\n # Allocate enough space initially for 4 modes per hit\n maxnresults = len(ids) * 4\n results = np.zeros((maxnresults, 7), np.int32)\n nresults = 0\n min_time = 0\n max_time = 0\n for urank, (id, rawcount) in enumerate(zip(ids, rawcounts)):\n modes, counts = find_modes(alltimes[np.nonzero(allids == id)[0]],\n window=self.window,\n threshold=self.threshcount)\n for mode in modes:\n matchhashes = self._unique_match_hashes(id, sorted_hits, mode)\n # Now we get the exact count\n filtcount = len(matchhashes)\n if filtcount >= self.threshcount:\n if nresults == maxnresults:\n # Extend array\n maxnresults *= 2\n results.resize((maxnresults, results.shape[1]))\n if self.find_time_range:\n min_time, max_time = self._calculate_time_ranges(\n sorted_hits, id, mode)\n results[nresults, :] = [id, filtcount, mode, rawcount,\n urank, min_time, max_time]\n nresults += 1\n return results[:nresults, :]\n\n def _approx_match_counts(self, hits, ids, rawcounts):\n \"\"\" Quick and slightly inaccurate routine to count time-aligned hits.\n\n Only considers largest mode for reference ID match.\n\n Args:\n hits: np.array of hash matches, each row consists of\n <track_id, skew_time, hash, orig_time>.\n ids: list of the IDs to check, based on raw match count.\n rawcounts: list giving the actual raw counts for each id to try.\n\n Returns:\n Rows of [id, filt_count, time_skew, raw_count, orig_rank,\n min_time, max_time].\n Ids occur in the same order as the input list, but ordering\n of (potentially multiple) hits within each track may not be\n sorted (they are sorted by the largest single count value, not\n the total count integrated over -window:+window bins).\n \"\"\"\n # In fact, the counts should be the same as exact_match_counts\n # *but* some matches may be pruned because we don't bother to\n # apply the window (allowable drift in time alignment) unless\n # there are more than threshcount matches at the single best time skew.\n # Note: now we allow multiple matches per ID, this may need to grow\n # so it can grow inside the loop.\n results = np.zeros((len(ids), 7), np.int32)\n if not hits.size:\n # No hits found, return empty results\n return results\n # Sort hits into time_in_original order - needed for _calc_time_range\n sorted_hits = hits[hits[:, 3].argsort()]\n allids = sorted_hits[:, 0].astype(int)\n alltimes = sorted_hits[:, 1].astype(int)\n # Make sure every value in alltimes is >=0 for bincount\n mintime = np.amin(alltimes)\n alltimes -= mintime\n nresults = 0\n min_time = 0\n max_time = 0\n for urank, (id, rawcount) in enumerate(zip(ids, rawcounts)):\n # Make sure id is an int64 before shifting it up.\n id = int(id)\n # Select the subrange of bincounts corresponding to this id\n bincounts = np.bincount(alltimes[allids == id])\n still_looking = True\n # Only consider legit local maxima in bincounts.\n filtered_bincounts = keep_local_maxes(bincounts)\n found_this_id = 0\n while still_looking:\n mode = np.argmax(filtered_bincounts)\n if filtered_bincounts[mode] <= self.threshcount:\n # Too few - skip to the next id\n still_looking = False\n continue\n count = np.sum(bincounts[max(0, mode - self.window):\n (mode + self.window + 1)])\n if self.find_time_range:\n min_time, max_time = self._calculate_time_ranges(\n sorted_hits, id, mode + mintime)\n results[nresults, :] = [id, count, mode + mintime, rawcount,\n urank, min_time, max_time]\n nresults += 1\n if nresults >= results.shape[0]:\n results = np.vstack([results, np.zeros(results.shape,\n np.int32)])\n # Clear this hit to find next largest.\n filtered_bincounts[max(0, mode - self.window):\n (mode + self.window + 1)] = 0\n found_this_id += 1\n if found_this_id > self.max_alignments_per_id:\n still_looking = False\n return results[:nresults, :]\n\n def match_hashes(self, ht, hashes, hashesfor=None):\n \"\"\" Match audio against fingerprint hash table.\n Return top N matches as (id, filteredmatches, timoffs, rawmatches,\n origrank, mintime, maxtime)\n If hashesfor specified, return the actual matching hashes for that\n hit (0=top hit).\n \"\"\"\n # find the implicated id, time pairs from hash table\n # log(\"nhashes=%d\" % np.shape(hashes)[0])\n hits = ht.get_hits(hashes)\n\n bestids, rawcounts = self._best_count_ids(hits, ht)\n\n # log(\"len(rawcounts)=%d max(rawcounts)=%d\" %\n # (len(rawcounts), max(rawcounts)))\n if not self.exact_count:\n results = self._approx_match_counts(hits, bestids, rawcounts)\n else:\n results = self._exact_match_counts(hits, bestids, rawcounts,\n hashesfor)\n # Sort results by filtered count, descending\n results = results[(-results[:, 1]).argsort(),]\n # Where was our best hit in the unfiltered count ranking?\n # (4th column is rank in original list; look at top hit)\n # if np.shape(results)[0] > 0:\n # bestpos = results[0, 4]\n # print \"bestpos =\", bestpos\n # Could use to collect stats on best search-depth to use...\n\n # Now strip the final column (original raw-count-based rank)\n # results = results[:, :4]\n\n if hashesfor is None:\n return results\n else:\n id = results[hashesfor, 0]\n mode = results[hashesfor, 2]\n hashesforhashes = self._unique_match_hashes(id, hits, mode)\n return results, hashesforhashes\n\n def match_file(self, analyzer, ht, filename, number=None):\n \"\"\" Read in an audio file, calculate its landmarks, query against\n hash table. Return top N matches as (id, filterdmatchcount,\n timeoffs, rawmatchcount), also length of input file in sec,\n and count of raw query hashes extracted\n \"\"\"\n q_hashes = analyzer.wavfile2hashes(filename)\n # Fake durations as largest hash time\n if len(q_hashes) == 0:\n durd = 0.0\n else:\n durd = analyzer.n_hop * q_hashes[-1][0] / analyzer.target_sr\n if self.verbose:\n if number is not None:\n numberstring = \"#%d\" % number\n else:\n numberstring = \"\"\n print(time.ctime(), \"Analyzed\", numberstring, filename, \"of\",\n ('%.3f' % durd), \"s \"\n \"to\", len(q_hashes), \"hashes\")\n # Run query\n rslts = self.match_hashes(ht, q_hashes)\n # Post filtering\n if self.sort_by_time:\n rslts = rslts[(-rslts[:, 2]).argsort(), :]\n return rslts[:self.max_returns, :], durd, len(q_hashes)\n\n def file_match_to_msgs(self, analyzer, ht, qry, number=None):\n \"\"\" Perform a match on a single input file, return list\n of message strings \"\"\"\n rslts, dur, nhash = self.match_file(analyzer, ht, qry, number)\n t_hop = analyzer.n_hop / analyzer.target_sr\n if self.verbose:\n qrymsg = qry + (' %.1f ' % dur) + \"sec \" + str(nhash) + \" raw hashes\"\n else:\n qrymsg = qry\n\n msgrslt = []\n if len(rslts) == 0:\n # No matches returned at all\n nhashaligned = 0\n if self.verbose:\n msgrslt.append(\"NOMATCH \" + qrymsg)\n else:\n msgrslt.append(qrymsg + \"\\t\")\n else:\n for (tophitid, nhashaligned, aligntime, nhashraw, rank,\n min_time, max_time) in rslts:\n # figure the number of raw and aligned matches for top hit\n if self.verbose:\n if self.find_time_range:\n msg = (\"Matched {:6.1f} s starting at {:6.1f} s in {:s}\"\n \" to time {:6.1f} s in {:s}\").format(\n (max_time - min_time) * t_hop, min_time * t_hop, qry,\n (min_time + aligntime) * t_hop, ht.names[tophitid])\n else:\n msg = \"Matched {:s} as {:s} at {:6.1f} s\".format(\n qrymsg, ht.names[tophitid], aligntime * t_hop)\n msg += (\" with {:5d} of {:5d} common hashes\"\n \" at rank {:2d}\").format(\n nhashaligned, nhashraw, rank)\n msgrslt.append(msg)\n else:\n msgrslt.append(qrymsg + \"\\t\" + ht.names[tophitid])\n if self.illustrate:\n self.illustrate_match(analyzer, ht, qry)\n return msgrslt\n\n def illustrate_match(self, analyzer, ht, filename):\n \"\"\" Show the query fingerprints and the matching ones\n plotted over a spectrogram \"\"\"\n # Make the spectrogram\n # d, sr = librosa.load(filename, sr=analyzer.target_sr)\n d, sr = audio_read.audio_read(filename, sr=analyzer.target_sr, channels=1)\n sgram = np.abs(librosa.stft(d, n_fft=analyzer.n_fft,\n hop_length=analyzer.n_hop,\n window=np.hanning(analyzer.n_fft + 2)[1:-1]))\n sgram = 20.0 * np.log10(np.maximum(sgram, np.max(sgram) / 1e6))\n sgram = sgram - np.mean(sgram)\n # High-pass filter onset emphasis\n # [:-1,] discards top bin (nyquist) of sgram so bins fit in 8 bits\n # spectrogram enhancement\n if self.illustrate_hpf:\n HPF_POLE = 0.98\n sgram = np.array([scipy.signal.lfilter([1, -1],\n [1, -HPF_POLE], s_row)\n for s_row in sgram])[:-1, ]\n sgram = sgram - np.max(sgram)\n librosa.display.specshow(sgram, sr=sr, hop_length=analyzer.n_hop,\n y_axis='linear', x_axis='time',\n cmap='gray_r', vmin=-80.0, vmax=0)\n # Do the match?\n q_hashes = analyzer.wavfile2hashes(filename)\n # Run query, get back the hashes for match zero\n results, matchhashes = self.match_hashes(ht, q_hashes, hashesfor=0)\n if self.sort_by_time:\n results = sorted(results, key=lambda x: -x[2])\n # Convert the hashes to landmarks\n lms = audfprint_analyze.hashes2landmarks(q_hashes)\n mlms = audfprint_analyze.hashes2landmarks(matchhashes)\n # Overplot on the spectrogram\n plt.plot(np.array([[x[0], x[0] + x[3]] for x in lms]).T,\n np.array([[x[1], x[2]] for x in lms]).T,\n '.-g')\n plt.plot(np.array([[x[0], x[0] + x[3]] for x in mlms]).T,\n np.array([[x[1], x[2]] for x in mlms]).T,\n '.-r')\n # Add title\n plt.title(filename + \" : Matched as \" + ht.names[results[0][0]]\n + (\" with %d of %d hashes\" % (len(matchhashes),\n len(q_hashes))))\n # Display\n plt.show()\n # Return\n return results\n\n\ndef localtest():\n \"\"\"Function to provide quick test\"\"\"\n pat = '/Users/dpwe/projects/shazam/Nine_Lives/*mp3'\n qry = 'query.mp3'\n hash_tab = audfprint_analyze.glob2hashtable(pat)\n matcher = Matcher()\n rslts, dur, nhash = matcher.match_file(audfprint_analyze.g2h_analyzer,\n hash_tab, qry)\n t_hop = 0.02322\n print(\"Matched\", qry, \"(\", dur, \"s,\", nhash, \"hashes)\",\n \"as\", hash_tab.names[rslts[0][0]],\n \"at\", t_hop * float(rslts[0][2]), \"with\", rslts[0][1],\n \"of\", rslts[0][3], \"hashes\")\n\n\n# Run the main function if called from the command line\nif __name__ == \"__main__\":\n localtest()\n" ]
[ [ "numpy.bincount", "numpy.array", "numpy.zeros", "numpy.logical_and", "numpy.argsort", "numpy.greater", "numpy.argmax", "numpy.greater_equal", "numpy.abs", "numpy.amin", "matplotlib.pyplot.show", "numpy.max", "numpy.log", "numpy.amax", "numpy.nonzero", "numpy.unique", "numpy.mean", "numpy.hanning" ] ]
rafcy/HarpyTM
[ "e91d0b7cce4a21eada642d12e2d0604ace0c179f" ]
[ "src/kalman.py" ]
[ "import numpy as np\nfrom numpy.linalg import inv\n\n# Kalman Filter Class\nclass KalmanFilter:\n \"\"\"\n Simple Kalman filter\n \"\"\"\n\n def __init__(self, XY, B=np.array([0]), M=np.array([0])):\n stateMatrix = np.zeros((4, 1), np.float32) # [x, y, delta_x, delta_y]\n if XY != 0:\n stateMatrix = np.array([[XY[0]], [XY[1]], [0], [0]], np.float32)\n # np.array([XY[0], XY[1],0,0],np.float32)\n estimateCovariance = np.eye(stateMatrix.shape[0])\n transitionMatrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)\n processNoiseCov = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32) * 0.001\n measurementStateMatrix = np.zeros((2, 1), np.float32)\n observationMatrix = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], np.float32)\n measurementNoiseCov = np.array([[1, 0], [0, 1]], np.float32) * 13\n X=stateMatrix\n P=estimateCovariance\n F=transitionMatrix\n Q=processNoiseCov\n Z=measurementStateMatrix\n H=observationMatrix\n R=measurementNoiseCov\n \"\"\"\n Initialise the filter\n Args:\n X: State estimate\n P: Estimate covariance\n F: State transition model\n B: Control matrix\n M: Control vector\n Q: Process noise covariance\n Z: Measurement of the state X\n H: Observation model\n R: Observation noise covariance\n \"\"\"\n self.X = X\n self.P = P\n self.F = F\n self.B = B\n self.M = M\n self.Q = Q\n self.Z = Z\n self.H = H\n self.R = R\n\n def predict(self):\n \"\"\"\n Predict the future state\n Args:\n self.X: State estimate\n self.P: Estimate covariance\n self.B: Control matrix\n self.M: Control vector\n Returns:\n updated self.X\n \"\"\"\n # Project the state ahead\n self.X = self.F @ self.X + self.B @ self.M\n self.P = self.F @ self.P @ self.F.T + self.Q\n return self.X\n\n def correct(self, Z):\n \"\"\"\n Update the Kalman Filter from a measurement\n Args:\n self.X: State estimate\n self.P: Estimate covariance\n Z: State measurement\n Returns:\n updated X\n \"\"\"\n K = self.P @ self.H.T @ inv(self.H @ self.P @ self.H.T + self.R)\n self.X += K @ (Z - self.H @ self.X)\n self.P = self.P - K @ self.H @ self.P\n\n return self.X\n\n\"\"\"\nneeded variables to instantly initialize kalman with just parsing X,Y variables (x,y) \n\"\"\"\ndef init_kalman(XY):\n kalman = None\n stateMatrix = np.zeros((4, 1), np.float32) # [x, y, delta_x, delta_y]\n if XY != 0:\n stateMatrix = np.array([[XY[0]], [XY[1]],[0],[0]],np.float32)\n # np.array([XY[0], XY[1],0,0],np.float32)\n estimateCovariance = np.eye(stateMatrix.shape[0])\n transitionMatrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)\n processNoiseCov = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32) * 0.001\n measurementStateMatrix = np.zeros((2, 1), np.float32)\n observationMatrix = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], np.float32)\n measurementNoiseCov = np.array([[1, 0], [0, 1]], np.float32) * 13\n kalman = KalmanFilter(X=stateMatrix,\n P=estimateCovariance,\n F=transitionMatrix,\n Q=processNoiseCov,\n Z=measurementStateMatrix,\n H=observationMatrix,\n R=measurementNoiseCov)\n return kalman\n" ]
[ [ "numpy.array", "numpy.eye", "numpy.linalg.inv", "numpy.zeros" ] ]
chrisgans/Daisy_World
[ "29d76707101f8036300977508555619be442ae34" ]
[ "daisy_world_exc_4.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nif __name__ == \"__main__\":\n print(\"In __main__\")\n import numpy as np\n import matplotlib.pyplot as plt\n\n import model_functions as mf\n\n ### 4)\n luminosities = np.arange(0.5, 1.6, 0.002) # Stelar luminosities\n alphaw_out = np.ones(len(luminosities)) * np.nan # Output variable for white\n alphab_out = np.ones(len(luminosities)) * np.nan # Output variable for black\n temp_out = np.ones(len(luminosities)) * np.nan # Output variable for temp\n\n gamma_arr = [0.1, 0.2, 0.3, 0.5, 0.7]\n fig, axs = plt.subplots(len(gamma_arr), 1, figsize=(10, 15))\n\n for k, gamma in enumerate(gamma_arr):\n # Define constants and variables\n alphaw = mf.alphaw # Cover fraction of white daisies\n alphab = mf.alphab # Cover fraction of black daisies\n\n ### custom constants\n alphaw_min = mf.alphaw\n alphab_min = mf.alphab\n\n # Main loop for changing luminosity\n for i,L in enumerate(luminosities):\n # Set a minimum for cover fractions\n alphaw = alphaw_min if alphaw < alphaw_min else alphaw\n alphab = alphab_min if alphab < alphab_min else alphab\n alphag = mf.p - alphaw - alphab\n # Reset counters\n n = 0\n changew, changeb = 1,1\n # Run loop for daisy earth.\n while (n < mf.maxn) and (changew > mf.tol) and (changeb > mf.tol):\n # Store the initial cover fractions\n sw, sb = alphaw, alphab\n # Planetary albedo\n planet_albedo = mf.albedo(alphaw, alphab, alphag, mf.aw, mf.ab, mf.ag)\n # Planetary temperature\n T = mf.planetary_temp(mf.S, planet_albedo, L=L)\n # Local temperature\n Tw = mf.local_temp(planet_albedo, mf.aw, T)\n Tb = mf.local_temp(planet_albedo, mf.ab, T)\n # Birth rate\n betaw = mf.beta(Tw)\n betab = mf.beta(Tb)\n # Change in daisies\n dawdt = mf.daisy_replicator(alphaw, alphag, betaw, gamma)\n dabdt = mf.daisy_replicator(alphab, alphag, betab, gamma)\n # Integrate\n alphaw = mf.euler(alphaw, dawdt)\n alphab = mf.euler(alphab, dabdt)\n alphag = mf.p - alphaw - alphab\n n += 1\n # Store the output\n alphaw_out[i] = alphaw\n alphab_out[i] = alphab\n temp_out[i] = T\n\n\n\n # Plot the results\n # Cover fractions\n axs[k].plot(luminosities, alphaw_out*100, 'b', label='White')\n axs[k].plot(luminosities, alphab_out*100, 'k', label='Black')\n axs[k].set_ylabel('gamma = %s' % gamma)\n\n if (k == 0):\n axs[0].legend(loc='upper right')\n\n plt.tight_layout()\n plt.savefig('./outputs/exc_4.png', dpi=520)\n" ]
[ [ "numpy.arange", "matplotlib.pyplot.savefig", "matplotlib.pyplot.tight_layout" ] ]
TreshUp/poliastro
[ "602eb3c39d315be6dc1edaa12d72ab0e361334f6" ]
[ "src/poliastro/core/angles.py" ]
[ "import numpy as np\nfrom numba import njit as jit\n\n\n@jit\ndef _kepler_equation(E, M, ecc):\n return E_to_M(E, ecc) - M\n\n\n@jit\ndef _kepler_equation_prime(E, M, ecc):\n return 1 - ecc * np.cos(E)\n\n\n@jit\ndef _kepler_equation_hyper(F, M, ecc):\n return F_to_M(F, ecc) - M\n\n\n@jit\ndef _kepler_equation_prime_hyper(F, M, ecc):\n return ecc * np.cosh(F) - 1\n\n\ndef newton_factory(func, fprime):\n @jit\n def jit_newton_wrapper(x0, args=(), tol=1.48e-08, maxiter=50):\n p0 = float(x0)\n for _ in range(maxiter):\n fval = func(p0, *args)\n fder = fprime(p0, *args)\n newton_step = fval / fder\n p = p0 - newton_step\n if abs(p - p0) < tol:\n return p\n p0 = p\n\n return np.nan\n\n return jit_newton_wrapper\n\n\n_newton_elliptic = newton_factory(_kepler_equation, _kepler_equation_prime)\n_newton_hyperbolic = newton_factory(\n _kepler_equation_hyper, _kepler_equation_prime_hyper\n)\n\n\n@jit\ndef D_to_nu(D):\n r\"\"\"True anomaly from parabolic anomaly.\n\n Parameters\n ----------\n D : float\n Eccentric anomaly.\n\n Returns\n -------\n nu : float\n True anomaly.\n\n Notes\n -----\n From [1]_:\n\n .. math::\n\n \\nu = 2 \\arctan{D}\n\n \"\"\"\n\n return 2.0 * np.arctan(D)\n\n\n@jit\ndef nu_to_D(nu):\n r\"\"\"Parabolic anomaly from true anomaly.\n\n Parameters\n ----------\n nu : float\n True anomaly in radians.\n\n Returns\n -------\n D : float\n Parabolic anomaly.\n\n Warnings\n --------\n The parabolic anomaly will be continuous in (-∞, ∞)\n only if the true anomaly is in (-π, π].\n No validation or wrapping is performed.\n\n Notes\n -----\n The treatment of the parabolic case is heterogeneous in the literature,\n and that includes the use of an equivalent quantity to the eccentric anomaly:\n [1]_ calls it \"parabolic eccentric anomaly\" D,\n [2]_ also uses the letter D but calls it just \"parabolic anomaly\",\n [3]_ uses the letter B citing indirectly [4]_\n (which however calls it \"parabolic time argument\"),\n and [5]_ does not bother to define it.\n\n We use this definition:\n\n .. math::\n\n B = \\tan{\\frac{\\nu}{2}}\n\n References\n ----------\n .. [1] Farnocchia, Davide, Davide Bracali Cioci, and Andrea Milani.\n \"Robust resolution of Kepler’s equation in all eccentricity regimes.\"\n .. [2] Bate, Muller, White.\n .. [3] Vallado, David. \"Fundamentals of Astrodynamics and Applications\",\n 2013.\n .. [4] IAU VIth General Assembly, 1938.\n .. [5] Battin, Richard H. \"An introduction to the Mathematics and Methods\n of Astrodynamics, Revised Edition\", 1999.\n\n \"\"\"\n # TODO: Rename to B\n return np.tan(nu / 2.0)\n\n\n@jit\ndef nu_to_E(nu, ecc):\n r\"\"\"Eccentric anomaly from true anomaly.\n\n .. versionadded:: 0.4.0\n\n Parameters\n ----------\n nu : float\n True anomaly in radians.\n ecc : float\n Eccentricity.\n\n Returns\n -------\n E : float\n Eccentric anomaly, between -π and π radians.\n\n Warnings\n --------\n The eccentric anomaly will be between -π and π radians,\n no matter the value of the true anomaly.\n\n Notes\n -----\n The implementation uses the half-angle formula from [3]_:\n\n .. math::\n E = 2 \\arctan \\left ( \\sqrt{\\frac{1 - e}{1 + e}} \\tan{\\frac{\\nu}{2}} \\right)\n \\in (-\\pi, \\pi]\n\n \"\"\"\n E = 2 * np.arctan(np.sqrt((1 - ecc) / (1 + ecc)) * np.tan(nu / 2))\n return E\n\n\n@jit\ndef nu_to_F(nu, ecc):\n r\"\"\"Hyperbolic anomaly from true anomaly.\n\n Parameters\n ----------\n nu : float\n True anomaly in radians.\n ecc : float\n Eccentricity (>1).\n\n Returns\n -------\n F : float\n Hyperbolic anomaly.\n\n Warnings\n --------\n The hyperbolic anomaly will be continuous in (-∞, ∞)\n only if the true anomaly is in (-π, π],\n which should happen anyway\n because the true anomaly is limited for hyperbolic orbits.\n No validation or wrapping is performed.\n\n Notes\n -----\n The implementation uses the half-angle formula from [3]_:\n\n .. math::\n F = 2 \\operatorname{arctanh} \\left( \\sqrt{\\frac{e-1}{e+1}} \\tan{\\frac{\\nu}{2}} \\right)\n\n \"\"\"\n F = 2 * np.arctanh(np.sqrt((ecc - 1) / (ecc + 1)) * np.tan(nu / 2))\n return F\n\n\n@jit\ndef E_to_nu(E, ecc):\n r\"\"\"True anomaly from eccentric anomaly.\n\n .. versionadded:: 0.4.0\n\n Parameters\n ----------\n E : float\n Eccentric anomaly in radians.\n ecc : float\n Eccentricity.\n\n Returns\n -------\n nu : float\n True anomaly, between -π and π radians.\n\n Warnings\n --------\n The true anomaly will be between -π and π radians,\n no matter the value of the eccentric anomaly.\n\n Notes\n -----\n The implementation uses the half-angle formula from [3]_:\n\n .. math::\n \\nu = 2 \\arctan \\left( \\sqrt{\\frac{1 + e}{1 - e}} \\tan{\\frac{E}{2}} \\right)\n \\in (-\\pi, \\pi]\n\n \"\"\"\n nu = 2 * np.arctan(np.sqrt((1 + ecc) / (1 - ecc)) * np.tan(E / 2))\n return nu\n\n\n@jit\ndef F_to_nu(F, ecc):\n r\"\"\"True anomaly from hyperbolic anomaly.\n\n Parameters\n ----------\n F : float\n Hyperbolic anomaly.\n ecc : float\n Eccentricity (>1).\n\n Returns\n -------\n nu : float\n True anomaly.\n\n Notes\n -----\n The implementation uses the half-angle formula from [3]_:\n\n .. math::\n \\nu = 2 \\arctan \\left( \\sqrt{\\frac{e + 1}{e - 1}} \\tanh{\\frac{F}{2}} \\right)\n \\in (-\\pi, \\pi]\n\n \"\"\"\n nu = 2 * np.arctan(np.sqrt((ecc + 1) / (ecc - 1)) * np.tanh(F / 2))\n return nu\n\n\n@jit\ndef M_to_E(M, ecc):\n \"\"\"Eccentric anomaly from mean anomaly.\n\n .. versionadded:: 0.4.0\n\n Parameters\n ----------\n M : float\n Mean anomaly in radians.\n ecc : float\n Eccentricity.\n\n Returns\n -------\n E : float\n Eccentric anomaly.\n\n Notes\n -----\n This uses a Newton iteration on the Kepler equation.\n\n \"\"\"\n if -np.pi < M < 0 or np.pi < M:\n E0 = M - ecc\n else:\n E0 = M + ecc\n E = _newton_elliptic(E0, args=(M, ecc))\n return E\n\n\n@jit\ndef M_to_F(M, ecc):\n \"\"\"Hyperbolic anomaly from mean anomaly.\n\n Parameters\n ----------\n M : float\n Mean anomaly in radians.\n ecc : float\n Eccentricity (>1).\n\n Returns\n -------\n F : float\n Hyperbolic anomaly.\n\n Notes\n -----\n This uses a Newton iteration on the hyperbolic Kepler equation.\n\n \"\"\"\n F0 = np.arcsinh(M / ecc)\n F = _newton_hyperbolic(F0, args=(M, ecc), maxiter=100)\n return F\n\n\n@jit\ndef M_to_D(M):\n \"\"\"Parabolic anomaly from mean anomaly.\n\n Parameters\n ----------\n M : float\n Mean anomaly in radians.\n\n Returns\n -------\n D : float\n Parabolic anomaly.\n\n Notes\n -----\n This uses the analytical solution of Barker's equation from [5]_.\n\n \"\"\"\n B = 3.0 * M / 2.0\n A = (B + (1.0 + B ** 2) ** 0.5) ** (2.0 / 3.0)\n D = 2 * A * B / (1 + A + A ** 2)\n return D\n\n\n@jit\ndef E_to_M(E, ecc):\n r\"\"\"Mean anomaly from eccentric anomaly.\n\n .. versionadded:: 0.4.0\n\n Parameters\n ----------\n E : float\n Eccentric anomaly in radians.\n ecc : float\n Eccentricity.\n\n Returns\n -------\n M : float\n Mean anomaly.\n\n Warnings\n --------\n The mean anomaly will be outside of (-π, π]\n if the eccentric anomaly is.\n No validation or wrapping is performed.\n\n Notes\n -----\n The implementation uses the plain original Kepler equation:\n\n .. math::\n M = E - e \\sin{E}\n\n \"\"\"\n M = E - ecc * np.sin(E)\n return M\n\n\n@jit\ndef F_to_M(F, ecc):\n r\"\"\"Mean anomaly from eccentric anomaly.\n\n Parameters\n ----------\n F : float\n Hyperbolic anomaly.\n ecc : float\n Eccentricity (>1).\n\n Returns\n -------\n M : float\n Mean anomaly.\n\n Notes\n -----\n As noted in [5]_, by manipulating\n the parametric equations of the hyperbola\n we can derive a quantity that is equivalent\n to the eccentric anomaly in the elliptic case:\n\n .. math::\n\n M = e \\sinh{F} - F\n\n \"\"\"\n M = ecc * np.sinh(F) - F\n return M\n\n\n@jit\ndef D_to_M(D):\n r\"\"\"Mean anomaly from parabolic anomaly.\n\n Parameters\n ----------\n D : float\n Parabolic anomaly.\n\n Returns\n -------\n M : float\n Mean anomaly.\n\n Notes\n -----\n We use this definition:\n\n .. math::\n\n M = B + \\frac{B^3}{3}\n\n Notice that M < ν until ν ~ 100 degrees,\n then it reaches π when ν ~ 120 degrees,\n and grows without bounds after that.\n Therefore, it can hardly be called an \"anomaly\"\n since it is by no means an angle.\n\n \"\"\"\n M = D + D ** 3 / 3\n return M\n\n\n@jit\ndef fp_angle(nu, ecc):\n r\"\"\"Returns the flight path angle.\n\n Parameters\n ----------\n nu : float\n True anomaly in radians.\n ecc : float\n Eccentricity.\n\n Returns\n -------\n fp_angle: float\n Flight path angle\n\n Notes\n -----\n From [3]_, pp. 113:\n\n .. math::\n\n \\phi = \\arctan(\\frac {e \\sin{\\nu}}{1 + e \\cos{\\nu}})\n\n \"\"\"\n return np.arctan2(ecc * np.sin(nu), 1 + ecc * np.cos(nu))\n" ]
[ [ "numpy.cosh", "numpy.arcsinh", "numpy.arctan", "numpy.cos", "numpy.sinh", "numpy.tan", "numpy.sqrt", "numpy.sin", "numpy.tanh" ] ]
shell-done/Spongo_IHM
[ "3492c889b1d60cf50b4b2625b496fd6958309a8e" ]
[ "Services/NeuralNetwork/NeuralNetwork.py" ]
[ "import cv2\r\nimport torch\r\n\r\nfrom Services.NeuralNetwork.tool.torch_utils import do_detect\r\nfrom Services.NeuralNetwork.tool.darknet2pytorch import Darknet\r\n\r\nclass NeuralNetwork:\r\n @staticmethod\r\n def isCudaAvailable() -> bool:\r\n return torch.cuda.is_available()\r\n\r\n @staticmethod\r\n def getAvailableCalculationDevices() -> dict:\r\n devices = {}\r\n devices[\"cpu\"] = \"CPU\"\r\n\r\n if torch.cuda.is_available():\r\n for device_idx in range(torch.cuda.device_count()):\r\n devices[\"cuda:%d\" % device_idx] = \"GPU (%s)\" % torch.cuda.get_device_name(device_idx)\r\n\r\n return devices\r\n\r\n def __init__(self, cfg_file: str, weights_file: str, threshold: float, device_id: str) -> None:\r\n with torch.no_grad():\r\n self._obj_thresh = threshold\r\n self._device_id = device_id\r\n\r\n self._model = Darknet(cfg_file)\r\n \r\n if(self._model is None):\r\n return\r\n\r\n #self._model.print_network()\r\n self._model.load_weights(weights_file)\r\n\r\n self._model = self._model.to(device_id)\r\n self._model.eval()\r\n\r\n def process(self, img):\r\n with torch.no_grad():\r\n sized = cv2.resize(img, (416, 416))\r\n sized = cv2.cvtColor(sized, cv2.COLOR_BGR2RGB)\r\n\r\n if(img is None):\r\n return\r\n\r\n boxes = do_detect(self._model, sized, self._obj_thresh, 0.4, self._device_id)\r\n\r\n detections = []\r\n img_height, img_width = img.shape[:2]\r\n for box in boxes[0]:\r\n x1 = int(box[0] * img_width)\r\n y1 = int(box[1] * img_height)\r\n x2 = int(box[2] * img_width)\r\n y2 = int(box[3] * img_height)\r\n\r\n xywh = (x1, y1, x2-x1, y2-y1)\r\n conf = float(box[5])\r\n id = int(box[6])\r\n\r\n detections.append([xywh, id, conf])\r\n\r\n return detections\r\n" ]
[ [ "torch.cuda.is_available", "torch.no_grad", "torch.cuda.device_count", "torch.cuda.get_device_name" ] ]
zixiliuUSC/deep_grammar_error_corrector
[ "d18ebe1fa3b0a50fb96835d1f47c6fe1e73461ad" ]
[ "fairseq/fairseq/models/simple_lstm.py" ]
[ "import torch.nn as nn\nfrom fairseq import utils\nfrom fairseq.models import FairseqEncoder\n\nclass SimpleLSTMEncoder(FairseqEncoder):\n\n def __init__(\n self, args, dictionary, embed_dim=128, hidden_dim=128, dropout=0.1,\n ):\n super().__init__(dictionary)\n self.args = args\n\n # Our encoder will embed the inputs before feeding them to the LSTM.\n self.embed_tokens = nn.Embedding(\n num_embeddings=len(dictionary),\n embedding_dim=embed_dim,\n padding_idx=dictionary.pad(),\n )\n self.dropout = nn.Dropout(p=dropout)\n\n # We'll use a single-layer, unidirectional LSTM for simplicity.\n self.lstm = nn.LSTM(\n input_size=embed_dim,\n hidden_size=hidden_dim,\n num_layers=1,\n bidirectional=False,\n )\n\n def forward(self, src_tokens, src_lengths):\n # The inputs to the ``forward()`` function are determined by the\n # Task, and in particular the ``'net_input'`` key in each\n # mini-batch. We discuss Tasks in the next tutorial, but for now just\n # know that *src_tokens* has shape `(batch, src_len)` and *src_lengths*\n # has shape `(batch)`.\n\n # Note that the source is typically padded on the left. This can be\n # configured by adding the `--left-pad-source \"False\"` command-line\n # argument, but here we'll make the Encoder handle either kind of\n # padding by converting everything to be right-padded.\n if self.args.left_pad_source:\n # Convert left-padding to right-padding.\n src_tokens = utils.convert_padding_direction(\n src_tokens,\n padding_idx=self.dictionary.pad(),\n left_to_right=True\n )\n\n # Embed the source.\n x = self.embed_tokens(src_tokens)\n\n # Apply dropout.\n x = self.dropout(x)\n\n # Pack the sequence into a PackedSequence object to feed to the LSTM.\n x = nn.utils.rnn.pack_padded_sequence(x, src_lengths, batch_first=True)\n\n # Get the output from the LSTM.\n _outputs, (final_hidden, _final_cell) = self.lstm(x)\n\n # Return the Encoder's output. This can be any object and will be\n # passed directly to the Decoder.\n return {\n # this will have shape `(bsz, hidden_dim)`\n 'final_hidden': final_hidden.squeeze(0),\n }\n\n # Encoders are required to implement this method so that we can rearrange\n # the order of the batch elements during inference (e.g., beam search).\n def reorder_encoder_out(self, encoder_out, new_order):\n \"\"\"\n Reorder encoder output according to `new_order`.\n\n Args:\n encoder_out: output from the ``forward()`` method\n new_order (LongTensor): desired order\n\n Returns:\n `encoder_out` rearranged according to `new_order`\n \"\"\"\n final_hidden = encoder_out['final_hidden']\n return {\n 'final_hidden': final_hidden.index_select(0, new_order),\n }\n\nimport torch\nfrom fairseq.models import FairseqDecoder\n\nclass SimpleLSTMDecoder(FairseqDecoder):\n\n def __init__(\n self, dictionary, encoder_hidden_dim=128, embed_dim=128, hidden_dim=128,\n dropout=0.1,\n ):\n super().__init__(dictionary)\n\n # Our decoder will embed the inputs before feeding them to the LSTM.\n self.embed_tokens = nn.Embedding(\n num_embeddings=len(dictionary),\n embedding_dim=embed_dim,\n padding_idx=dictionary.pad(),\n )\n self.dropout = nn.Dropout(p=dropout)\n\n # We'll use a single-layer, unidirectional LSTM for simplicity.\n self.lstm = nn.LSTM(\n # For the first layer we'll concatenate the Encoder's final hidden\n # state with the embedded target tokens.\n input_size=encoder_hidden_dim + embed_dim,\n hidden_size=hidden_dim,\n num_layers=1,\n bidirectional=False,\n )\n\n # Define the output projection.\n self.output_projection = nn.Linear(hidden_dim, len(dictionary))\n\n # During training Decoders are expected to take the entire target sequence\n # (shifted right by one position) and produce logits over the vocabulary.\n # The *prev_output_tokens* tensor begins with the end-of-sentence symbol,\n # ``dictionary.eos()``, followed by the target sequence.\n def forward(self, prev_output_tokens, encoder_out):\n \"\"\"\n Args:\n prev_output_tokens (LongTensor): previous decoder outputs of shape\n `(batch, tgt_len)`, for teacher forcing\n encoder_out (Tensor, optional): output from the encoder, used for\n encoder-side attention\n\n Returns:\n tuple:\n - the last decoder layer's output of shape\n `(batch, tgt_len, vocab)`\n - the last decoder layer's attention weights of shape\n `(batch, tgt_len, src_len)`\n \"\"\"\n bsz, tgt_len = prev_output_tokens.size()\n\n # Extract the final hidden state from the Encoder.\n final_encoder_hidden = encoder_out['final_hidden']\n\n # Embed the target sequence, which has been shifted right by one\n # position and now starts with the end-of-sentence symbol.\n x = self.embed_tokens(prev_output_tokens)\n\n # Apply dropout.\n x = self.dropout(x)\n\n # Concatenate the Encoder's final hidden state to *every* embedded\n # target token.\n x = torch.cat(\n [x, final_encoder_hidden.unsqueeze(1).expand(bsz, tgt_len, -1)],\n dim=2,\n )\n\n # Using PackedSequence objects in the Decoder is harder than in the\n # Encoder, since the targets are not sorted in descending length order,\n # which is a requirement of ``pack_padded_sequence()``. Instead we'll\n # feed nn.LSTM directly.\n initial_state = (\n final_encoder_hidden.unsqueeze(0), # hidden\n torch.zeros_like(final_encoder_hidden).unsqueeze(0), # cell\n )\n output, _ = self.lstm(\n x.transpose(0, 1), # convert to shape `(tgt_len, bsz, dim)`\n initial_state,\n )\n x = output.transpose(0, 1) # convert to shape `(bsz, tgt_len, hidden)`\n\n # Project the outputs to the size of the vocabulary.\n x = self.output_projection(x)\n\n # Return the logits and ``None`` for the attention weights\n return x, None\n\nfrom fairseq.models import FairseqEncoderDecoderModel, register_model\n\n# Note: the register_model \"decorator\" should immediately precede the\n# definition of the Model class.\n\n@register_model('simple_lstm')\nclass SimpleLSTMModel(FairseqEncoderDecoderModel):\n\n @staticmethod\n def add_args(parser):\n # Models can override this method to add new command-line arguments.\n # Here we'll add some new command-line arguments to configure dropout\n # and the dimensionality of the embeddings and hidden states.\n parser.add_argument(\n '--encoder-embed-dim', type=int, metavar='N',\n help='dimensionality of the encoder embeddings',\n )\n parser.add_argument(\n '--encoder-hidden-dim', type=int, metavar='N',\n help='dimensionality of the encoder hidden state',\n )\n parser.add_argument(\n '--encoder-dropout', type=float, default=0.1,\n help='encoder dropout probability',\n )\n parser.add_argument(\n '--decoder-embed-dim', type=int, metavar='N',\n help='dimensionality of the decoder embeddings',\n )\n parser.add_argument(\n '--decoder-hidden-dim', type=int, metavar='N',\n help='dimensionality of the decoder hidden state',\n )\n parser.add_argument(\n '--decoder-dropout', type=float, default=0.1,\n help='decoder dropout probability',\n )\n\n @classmethod\n def build_model(cls, args, task):\n # Fairseq initializes models by calling the ``build_model()``\n # function. This provides more flexibility, since the returned model\n # instance can be of a different type than the one that was called.\n # In this case we'll just return a SimpleLSTMModel instance.\n\n # Initialize our Encoder and Decoder.\n encoder = SimpleLSTMEncoder(\n args=args,\n dictionary=task.source_dictionary,\n embed_dim=args.encoder_embed_dim,\n hidden_dim=args.encoder_hidden_dim,\n dropout=args.encoder_dropout,\n )\n decoder = SimpleLSTMDecoder(\n dictionary=task.target_dictionary,\n encoder_hidden_dim=args.encoder_hidden_dim,\n embed_dim=args.decoder_embed_dim,\n hidden_dim=args.decoder_hidden_dim,\n dropout=args.decoder_dropout,\n )\n model = SimpleLSTMModel(encoder, decoder)\n\n # Print the model architecture.\n print(model)\n\n return model\n\n # We could override the ``forward()`` if we wanted more control over how\n # the encoder and decoder interact, but it's not necessary for this\n # tutorial since we can inherit the default implementation provided by\n # the FairseqEncoderDecoderModel base class, which looks like:\n #\n # def forward(self, src_tokens, src_lengths, prev_output_tokens):\n # encoder_out = self.encoder(src_tokens, src_lengths)\n # decoder_out = self.decoder(prev_output_tokens, encoder_out)\n # return decoder_out\n\nfrom fairseq.models import register_model_architecture\n\n# The first argument to ``register_model_architecture()`` should be the name\n# of the model we registered above (i.e., 'simple_lstm'). The function we\n# register here should take a single argument *args* and modify it in-place\n# to match the desired architecture.\n\n@register_model_architecture('simple_lstm', 'tutorial_simple_lstm')\ndef tutorial_simple_lstm(args):\n # We use ``getattr()`` to prioritize arguments that are explicitly given\n # on the command-line, so that the defaults defined below are only used\n # when no other value has been specified.\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256)\n args.encoder_hidden_dim = getattr(args, 'encoder_hidden_dim', 256)\n args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 256)\n args.decoder_hidden_dim = getattr(args, 'decoder_hidden_dim', 256)\n\n" ]
[ [ "torch.nn.utils.rnn.pack_padded_sequence", "torch.zeros_like", "torch.nn.LSTM", "torch.nn.Dropout" ] ]
t-k-/tinynn
[ "969eb96020406885d081a961084d9328e2939622" ]
[ "test/test_utils_data_iterator.py" ]
[ "\"\"\"test unit for utils/data_iterator.py\"\"\"\n\nimport runtime_path # isort:skip\n\nimport numpy as np\n\nfrom utils.data_iterator import BatchIterator\n\n\ndef test_batch_iterator():\n batch_size = 10\n n_data = 10 * batch_size # 10 batches\n iterator = BatchIterator(batch_size=batch_size)\n x_dim, y_dim = 10, 5\n fake_x = np.random.randint(0, 100, size=(n_data, x_dim))\n fake_y = np.random.randint(0, 100, size=(n_data, y_dim))\n\n n_batches = 0\n for batch_x, batch_y in iterator(fake_x, fake_y):\n assert batch_x.shape == (batch_size, x_dim)\n assert batch_y.shape == (batch_size, y_dim)\n n_batches += 1\n\n assert n_batches == 10\n" ]
[ [ "numpy.random.randint" ] ]
AleksanderLidtke/ConjunctionDetection
[ "c21596737757d87ea5bd2353c4b128c0795632d0" ]
[ "Release/validationDataProcessing.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nParse and analyse orbital conjunctions' data.\nCreated on Wed Apr 23 15:12:47 2014\nTO be used to analyse one on all data for Envisat and compare those to STK CAT results.\n\n@author: Aleksander Lidtke\n@version 1.0.0\n@since 22/05/2014 15:42:00\n\nCHANGELOG:\n\n\"\"\"\nimport datetime, pylab, scipy.integrate, matplotlib.pyplot, matplotlib, numpy, csv, math, utilities, sys\n\ndef computeMaximumCollisionProbabilityRelative(relativePosition, collisionRadius):\n \"\"\" Compute the maximum probability of collision between the two objects given their relative position within the \n collision plane (must be in the same units) at the time of closest approach. The maximum probability as given in\n N. Berend (1999) will be computed assuming a spherical uncertainty distribution of both objects and further numerically \n optimised to ensure that the true maximum probaility is computed. This has been found to\n accurately estimate the collision risk even though it doesn't account for velocity uncertainty. Assuming a spherical\n uncertainty distribution ensures that no encounter geometries yield a higher risk than others.\\n\n @param relativePosition - relative position of objects 1 and 2 within the collision plane in the form of 1x2 numpy arrays.\\n\n @param collisionRadius - combined radius that contains extremities of the objects in the same units as position.\\n\n @return (probability, error) - 2-tuple containig the probability of collision and estimated numerical integration error.\"\"\"\n \n \"\"\" FIND THE COMBINED COVARIANCE MATRIX TO YIELD WORST-CASE COLLISION PROBABILITY \"\"\"\n covarianceScalingFactor = numpy.linalg.norm(relativePosition)/math.sqrt(2) # Standard deviation which yields the maximum collision probability for spherical uncertainty distribution.\n projectedCovarianceMatrixInPlane = numpy.array([[1.,0.],[0.,1.]])\n Pd = covarianceScalingFactor*covarianceScalingFactor*projectedCovarianceMatrixInPlane # The worst-case covariance matrix in the collision plane. \n PdInverse = numpy.linalg.inv(Pd) # And its inverse.\n \n \"\"\" COMPUTE THE COLLISION PROBABILITY \"\"\"\n def integrand(y, x):\n \"\"\" Returns the probability of a successful attempt as defined by the probability density function\n in N. Berend (1999). Based upon covariance matrix Pd. \"\"\"\n discrepancyVector = numpy.array([[x], [y]]) - relativePosition.reshape(-1,1) # Instantenous [x y] minus the mean values.\n expTerm = math.exp( -0.5*float( discrepancyVector.T.dot(PdInverse).dot(discrepancyVector) ) ) # This will always be a length-1 array.\n return expTerm/( 2*math.pi*math.sqrt( numpy.linalg.det( Pd ) ) ) # A rather lengthy expression so divide it into parts.\n \n # Numerically integrate the PDF\n probability, error = scipy.integrate.dblquad(integrand, -collisionRadius, collisionRadius, lambda x: -math.sqrt(collisionRadius**2-x**2), lambda x: math.sqrt(collisionRadius**2-x**2), epsabs=1E-40)\n \n def probabilityFunction(scalingFactor):\n Pd = scalingFactor*scalingFactor*projectedCovarianceMatrixInPlane # Covariance matrix to yield the worst-case collision probability...\n PdInverse = numpy.linalg.inv(Pd) # ...and its inverse.\n def integrand(y, x):\n \"\"\" Returns the probability of a successful attempt as defined by the probability density function\n in N. Berend (1999). Based upon covariance matrix Pd. \"\"\"\n discrepancyVector = numpy.array([[x], [y]]) - relativePosition.reshape(-1,1) # Instantenous [x y] minus the mean values.\n expTerm = math.exp( -0.5*float( discrepancyVector.T.dot(PdInverse).dot(discrepancyVector) ) ) # This will always be a length-1 array.\n return expTerm/( 2*math.pi*math.sqrt( numpy.linalg.det( Pd ) ) ) # A rather lengthy expression so divide it into parts.\n \n probability, error = scipy.integrate.dblquad(integrand, -collisionRadius, collisionRadius, lambda x: -math.sqrt(collisionRadius**2-x**2), lambda x: math.sqrt(collisionRadius**2-x**2), epsabs=1E-40)\n return -probability # Actually we're looking for a maximum.\n \n actualCovarianceScalingFactor = scipy.optimize.fmin(probabilityFunction, covarianceScalingFactor) # Actual factor that gives the true local maximum of the collison probability.\n probability = -probabilityFunction(actualCovarianceScalingFactor) # - because the optimiser has to minimise a function so it returns - probaility.\n \n if float(error)/float(probability) >= 0.1: # 10% relative error, i.e plenty.\n utilities.customPrint('Relative error when computing the collision probability exceeded 10% with actual value of: '+str(float(error)/float(probability)), utilities.RED)\n\n return probability, error\n \nclass Conjunction(object):\n __doc__=\"\"\"A class that is used to stroe data about a particular orbital conjunction.\"\"\"\n\n def __init__(self, conjunctionRecord):\n \"\"\" A class that stores information about a particular orbital conjunction.\\n\n Parameters\n ----------\n conjunctionRecord : string\n string (with the trailing end line character) that contains comma separated:\n SSC1, SSC2, TCA, Miss Distance (km), Pc, relative V at TCA (km/s), collision radius (km)\n \"\"\"\n temp = conjunctionRecord.strip(\"\\n\").split(\",\") # List of strings with all the data about the particular conjunction.\n \n if len(temp[0])==4: # Brute-force method to cope with the varying lengths of SSCs.\n self.PRIMARY_SSC = '0'+temp[0]\n elif len(temp[0])==3:\n self.PRIMARY_SSC = '00'+temp[0]\n elif len(temp[0])==2:\n self.PRIMARY_SSC = '000'+temp[0]\n elif len(temp[0])==1:\n self.PRIMARY_SSC = '0000'+temp[0]\n else:\n self.PRIMARY_SSC = temp[0]\n \n if len(temp[1])==4:\n self.SECONDARY_SSC = '0'+temp[1]\n elif len(temp[1])==3:\n self.SECONDARY_SSC = '00'+temp[1]\n elif len(temp[1])==2:\n self.SECONDARY_SSC = '000'+temp[1]\n elif len(temp[1])==1:\n self.SECONDARY_SSC = '0000'+temp[1]\n else:\n self.SECONDARY_SSC = temp[1]\n \n try:\n # N.B. need temp[2].split(\".\") as in some format of the output TCA microseconds will be included.\n self.TCA = datetime.datetime.strptime( temp[2].split(\".\")[0], \"%d/%m/%Y %H:%M:%S\" ) + datetime.timedelta(microseconds=int(temp[2].split(\".\")[1])) # Hack to handle decimal fractions of a second with a leading 0.\n except IndexError: # Sometimes there will be no microseconds information, that isn't a problem.\n self.TCA = datetime.datetime.strptime( temp[2].split(\".\")[0], \"%d/%m/%Y %H:%M:%S\" )\n except ValueError: # Sometimes the microseconds will be a very small float in exponential notation, approximate to 0.\n if temp[2].split(\".\")[0][-2:]=='60': # datetime wants seconds to be [0,60), workaround.\n self.TCA = datetime.datetime.strptime( temp[2].split(\".\")[0][:-2], \"%d/%m/%Y %H:%M:\" ) # Simply ignore seconds here.\n self.TCA = self.TCA+datetime.timedelta(minutes=1) # Manuallly increase this.\n else:\n self.TCA = datetime.datetime.strptime( temp[2].split(\".\")[0], \"%d/%m/%Y %H:%M:%S\" )\n \n self.MISS_DISTANCE = float( temp[3] )\n if 'nan' in temp[4] or '-1.#IND' in temp[4] or '1.#INF' in temp[4]:\n raise Warning(\"NaN in max probability for {} and {}.\".format(self.PRIMARY_SSC, self.SECONDARY_SSC), self.PRIMARY_SSC, self.SECONDARY_SSC)\n elif 'nan' in temp[5] or '-1.#IND' in temp[5] or '1.#INF' in temp[5]: # Set a very low true collision probability. Maximum goes unchanged as it's OK.\n self.MAX_COLLISION_PROBABILITY = float( temp[4] )\n self.NO_COLLISION_PROBABILITY_MAX = 1.0 - self.MAX_COLLISION_PROBABILITY\n self.TRUE_COLLISION_PROBABILITY = sys.float_info.min\n self.NO_COLLISION_PROBABILITY_TRUE = 1.0 - self.TRUE_COLLISION_PROBABILITY\n else:\n if float( temp[4] )>1.0:\n raise Warning(\"Maximum probability for conjunction between {} and {} is greater than 1.0\".format(self.PRIMARY_SSC, self.SECONDARY_SSC), self.PRIMARY_SSC, self.SECONDARY_SSC)\n elif float( temp[5] )>1.0:\n raise Warning(\"True probability for conjunction between {} and {} is greater than 1.0\".format(self.PRIMARY_SSC, self.SECONDARY_SSC), self.PRIMARY_SSC, self.SECONDARY_SSC)\n else:\n self.MAX_COLLISION_PROBABILITY = float( temp[4] )\n self.NO_COLLISION_PROBABILITY_MAX = 1.0 - self.MAX_COLLISION_PROBABILITY\n self.TRUE_COLLISION_PROBABILITY = float( temp[5] )\n self.NO_COLLISION_PROBABILITY_TRUE = 1.0 - self.TRUE_COLLISION_PROBABILITY\n\n self.RELATIVE_V = float( temp[6] )\n self.COLLISION_RADIUS = float( temp[7] )\n \n def __str__(self):\n return \"{},{},{},{},{},{}\\n\".format(self.PRIMARY_SSC, self.SECONDARY_SSC, self.TCA, self.MISS_DISTANCE, self.MAX_COLLISION_PROBABILITY, self.TRUE_COLLISION_PROBABILITY)\n\nclass SimpleConjunction( object ):\n def __init__(self, primarySSC, secondarySSC, TCA, MD, MaxPc, TruePc):\n \"\"\" A conjunction object created from already parsed information.\n Parameters\n ----------\n primarySSC : string\n NORAD ID of the primary object.\n secondarySSC : string\n NORAD ID of the secondary object.\n TCA : datetime.Datetime\n Time of Closest Approach of the conjunction.\n MD : float\n Miss distance in km\n MaxPc : float\n Maximum collision probability.\n TruePc : float\n True collision probability.\n \"\"\"\n \n if primarySSC.endswith(\" \"): # Deal with STK CAT output format. Go from the most to fewest whitespaces to avoid problems (something with two whitespaces at the end also endswith(\" \") ).\n self.PRIMARY_SSC = \"0000\"+primarySSC.strip(\" \") \n elif primarySSC.endswith(\" \"):\n self.PRIMARY_SSC = \"000\"+primarySSC.strip(\" \")\n elif primarySSC.endswith(\" \"):\n self.PRIMARY_SSC = \"00\"+primarySSC.strip(\" \")\n elif primarySSC.endswith(\" \"):\n self.PRIMARY_SSC = \"0\"+primarySSC.strip(\" \")\n else:\n self.PRIMARY_SSC = primarySSC\n \n\n if secondarySSC.endswith(\" \"):\n self.SECONDARY_SSC = \"0000\"+secondarySSC.strip(\" \")\n elif secondarySSC.endswith(\" \"):\n self.SECONDARY_SSC = \"000\"+secondarySSC.strip(\" \")\n elif secondarySSC.endswith(\" \"):\n self.SECONDARY_SSC = \"00\"+secondarySSC.strip(\" \")\n elif secondarySSC.endswith(\" \"):\n self.SECONDARY_SSC = \"0\"+secondarySSC.strip(\" \")\n else:\n self.SECONDARY_SSC = secondarySSC\n \n self.TCA = TCA\n self.MISS_DISTANCE = MD\n self.MAX_COLLISION_PROBABILITY = MaxPc\n self.TRUE_COLLISION_PROBABILITY = TruePc\n self.NO_COLLISION_PROBABILITY_MAX = 1.0 - self.MAX_COLLISION_PROBABILITY\n self.NO_COLLISION_PROBABILITY_TRUE = 1.0 - self.TRUE_COLLISION_PROBABILITY\n \n def __str__(self):\n return \"{},{},{},{},{},{}\\n\".format(self.PRIMARY_SSC, self.SECONDARY_SSC, self.TCA, self.MISS_DISTANCE, self.MAX_COLLISION_PROBABILITY, self.TRUE_COLLISION_PROBABILITY)\n \n\"\"\"\n============================================================================================================================\n IMPORT DATA FROM C++ FILE.\n Each file should contain conjunctions information and a header. The conjunction format is expected as a CSV file\n with the following collumns:\n SSC1, SSC2, TCA, Miss Distance (km), Max Pc, True Pc, relative V at TCA (km/s), collision radius (km)\n============================================================================================================================\n\"\"\"\ndecayEpochs = {} # Get the reentry epoch of all the objects and store accoring to the SSC.\ndecayedInSimulation = 0 # Decayed in the duration of the simulation.\ndecayedOutsideSimulation = 0\nwith open(\"decayEpochs_23Oct2013\",\"r\") as deFile:\n deLines = deFile.readlines()\n for line in deLines:\n try:\n splitLine = line.split()\n decayEpochs[ splitLine[0] ] = datetime.datetime.strptime(splitLine[1]+\" \"+splitLine[2], '%Y-%m-%d %H:%M:%S')\n if datetime.datetime.strptime(splitLine[1]+\" \"+splitLine[2], '%Y-%m-%d %H:%M:%S') <= datetime.datetime(2013, 11, 23, 3, 58, 21):\n decayedInSimulation += 1\n else:\n decayedOutsideSimulation += 1\n except IndexError: # This object hasn't decayed yet.\n decayEpochs[ splitLine[0] ] = datetime.datetime(2200,1,1,0,0,0) # Very distant future just to have something.\n\nfileName = 'envisat_1year_COV3_1kmStandardDeviations_DI'\nlines=[]; # Read lines of the datafiles, one conjunction per line.\ntotalConjunctionsLoaded=0; # Nmber of conjunctions loaded from the files.\n\nutilities.customPrint(\"Reading data from {}.\".format(fileName), utilities.GREEN)\nconjunctionsRead=0 # Initialise this\n\" Read the data. \"\nwith open(fileName,\"r\") as inFile:\n tempLines = inFile.readlines(); # Lines from the given file only.\n\n\" Split the output header and conjunctions' information of generic length. \"\nheader = [];\nfor i in range(0,len(tempLines)): # this was from 0 to len(...)+1\n try:\n int( tempLines[i][3] ) # This won't work for the header, only when applyint int to a conjunction (SSC is recorded first).\n header = tempLines[:i] # Record the header info here...\n tempLines = tempLines[i:] #...and the conjunctions info here.\n break # Found end of the header, stop now.\n except ValueError:\n if not tempLines[i].startswith(\"Conjnctions found:\"):\n pass # Will get this when trying to convert a string to int i.e. when still parsing the header.\n else: # See if this line contains info about the number of conjunctions to be found in this file.\n conjunctionsRead = int( tempLines[i][19:] )\n totalConjunctionsLoaded = totalConjunctionsLoaded + conjunctionsRead\n \n \n\" Only save the conjunctions, discard the rest. \"\nutilities.customPrint(\"Read {} conjunctions from {}.\".format(conjunctionsRead,fileName), utilities.BLUE)\nlines.extend( tempLines );\ndel header, tempLines;\n\n\"\"\"\n============================================================================================================================\n IMPORT DATA FROM STK CAT FILE.\n Each file should contain conjunctions information and a header. The conjunction format is expected as a CSV file\n with the following collumns:\n SSC1, SSC2, TCA, Miss Distance (km), Max Pc, True Pc, relative V at TCA (km/s), collision radius (km)\n============================================================================================================================\n\"\"\"\n\nSTKconjunctions = [] # Different ellipsoid size (standard deviation squared c.f. standard deviation).\nSTK_SSCs=[]; STK_TCAs=[]; STKmissDistances=[]; STKtrueProbabilities=[]; STKmaxProbabilities=[];\nwith open('sgp4ESSS verificationReport COV1.csv', 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n rows = []\n for tempRow in reader:\n rows.append(tempRow)\n for row in rows[30:-1]: # Don't go through the header and the last line.\n tempConj = SimpleConjunction(\"27386\", row[0].replace('\"',''), datetime.datetime.strptime(row[1], \"%d %b %Y %H:%M:%S.%f\"), float(row[2]), float(row[3]), float(row[5]))\n if len(tempConj.SECONDARY_SSC)==4: # Correct for the leading 0s that STK does not output.\n tempConj.SECONDARY_SSC = '0'+tempConj.SECONDARY_SSC\n elif len(tempConj.SECONDARY_SSC)==3:\n tempConj.SECONDARY_SSC = '00'+tempConj.SECONDARY_SSC\n elif len(tempConj.SECONDARY_SSC)==2:\n tempConj.SECONDARY_SSC = '000'+tempConj.SECONDARY_SSC\n elif len(tempConj.SECONDARY_SSC)==1:\n tempConj.SECONDARY_SSC = '0000'+tempConj.SECONDARY_SSC\n \n if not decayEpochs[ tempConj.PRIMARY_SSC ] <= tempConj.TCA and not decayEpochs[ tempConj.SECONDARY_SSC ] <= tempConj.TCA:\n if True: #tempConj.MISS_DISTANCE >= 5.0:\n STKconjunctions.append( tempConj )\n STK_SSCs.append( tempConj.SECONDARY_SSC )\n STK_TCAs.append( tempConj.TCA )\n STKmissDistances.append( tempConj.MISS_DISTANCE )\n STKmaxProbabilities.append( tempConj.MAX_COLLISION_PROBABILITY )\n STKtrueProbabilities.append( tempConj.TRUE_COLLISION_PROBABILITY )\n \nSTKconjunctions.sort(key=lambda x: x.TCA)\nACCUMULATED_PCs_MAX_STK = []; ACCUMULATED_PCs_TRUE_STK = []; accumulatedPcMAX_STK2 = 1.0; accumulatedPcTRUE_STK2 = 1.0;\nfor conjSTK in STKconjunctions: # Save the conjunctions' data once they've been sorted by TCA ascending.\n accumulatedPcMAX_STK2 = accumulatedPcMAX_STK2*conjSTK.NO_COLLISION_PROBABILITY_MAX\n accumulatedPcTRUE_STK2 = accumulatedPcTRUE_STK2*conjSTK.NO_COLLISION_PROBABILITY_TRUE\n \n ACCUMULATED_PCs_MAX_STK.append( 1.0-accumulatedPcMAX_STK2 )\n ACCUMULATED_PCs_TRUE_STK.append( 1.0-accumulatedPcTRUE_STK2 )\n \n\"\"\"\n============================================================================================================================\n PARSE THE CONJUNCTIONS INFORMATION TO GET GLOBAL STATISTICS ABOUT ALL OF THEM.\n============================================================================================================================\n\"\"\"\nconjunctions = []; missDistances=[]; maxProbabilities = []; trueProbabilities = []; TCAs = [];\nNO_BAD_PROBABILITY_CONJUNCTIONS = 0\nNO_NANS_IN_CONJUNCTIONS = 0\nNO_maxPC_LOWER_THAN_truePC = 0; badPCsEpochs=[]; badMaxPCs=[]; badTruePCs=[]; badPCsPrimaries=[]; badPCsSecondaries=[] # Epochs and probabilities for this case.\nNO_TOO_LOW_maxPC = 0; tooLowMaxPCsPrimaries=[]; tooLowMaxPCsSecondaries=[]; # SSCs of the objets that have conjunctions with Pc MAX less than 1.0 even though it should be 1.0.\n\nfor conjLine in lines: # Create conjunctions from the records for ease of processing\n try:\n tempConj = Conjunction(conjLine)\n if not decayEpochs[ tempConj.PRIMARY_SSC ] <= tempConj.TCA and not decayEpochs[ tempConj.SECONDARY_SSC ] <= tempConj.TCA: # Filter out the TLEs that have decayed already so this conjunction can't have taken place.\n conjunctions.append( tempConj )\n # Do consistency checks here\n if tempConj.COLLISION_RADIUS >= tempConj.MISS_DISTANCE and tempConj.MAX_COLLISION_PROBABILITY<1.0:\n utilities.customPrint(\"Miss distance lower than collision radius and Pc max less than 1.0\", utilities.RED)\n utilities.customPrint( str(tempConj), utilities.GRAY)\n NO_TOO_LOW_maxPC += 1\n tooLowMaxPCsPrimaries.append(tempConj.PRIMARY_SSC)\n tooLowMaxPCsSecondaries.append(tempConj.SECONDARY_SSC)\n \n if tempConj.MAX_COLLISION_PROBABILITY < tempConj.TRUE_COLLISION_PROBABILITY:\n utilities.customPrint(\"Maximum collision probability lower than true collision probability\", utilities.RED)\n utilities.customPrint( str(tempConj), utilities.GRAY)\n NO_maxPC_LOWER_THAN_truePC += 1\n badPCsEpochs.append(tempConj.TCA) # Store info about these erroneous cases for analysis.\n badMaxPCs.append(tempConj.MAX_COLLISION_PROBABILITY)\n badTruePCs.append(tempConj.TRUE_COLLISION_PROBABILITY)\n badPCsPrimaries.append(tempConj.PRIMARY_SSC)\n badPCsSecondaries.append(tempConj.SECONDARY_SSC)\n \n except Warning as wrng: # There seems to be something wrong with this conjunction. But maybe it involved an ignored TLE.\n if \"NaN\" in wrng.args[0] and not decayEpochs[ wrng.args[1] ] <= tempConj.TCA and not decayEpochs[ wrng.args[2] ] <= tempConj.TCA: # wrng will have primary and secondary objects' SSCs - don't care about bad values for objects from the ignored list.\n utilities.customPrint( str(wrng.args), utilities.RED) # Print the error here as don't want this to be displayed if it came from one of the ignored TLEs.\n utilities.customPrint(\"\\t\"+conjLine, utilities.GRAY)\n NO_NANS_IN_CONJUNCTIONS += 1\n elif not decayEpochs[ wrng.args[1] ] <= tempConj.TCA and not decayEpochs[ wrng.args[2] ] <= tempConj.TCA:\n utilities.customPrint(wrng.args[0], utilities.RED) # Print the error here as don't want this to be displayed if it came from one of the ignored TLEs.\n utilities.customPrint(\"\\t\"+conjLine, utilities.GRAY)\n NO_BAD_PROBABILITY_CONJUNCTIONS += 1\n\nconjunctions.sort(key=lambda x: x.TCA) # Sort by TCA ascending.\nutilities.customPrint(\"Found {} conjunctions out of {} that have collision probability values of either collision probability > 1.0\".format(NO_BAD_PROBABILITY_CONJUNCTIONS, len(conjunctions)), utilities.RED)\nutilities.customPrint(\"Found {} conjunctions out of {} that have NaN values of maximum collision probability\".format(NO_NANS_IN_CONJUNCTIONS, len(conjunctions)), utilities.RED)\nutilities.customPrint(\"Found {} conjunctions out of {} that have maximum Pc <1.0 when collision radius exceeds the miss distance\".format(NO_TOO_LOW_maxPC, len(conjunctions)), utilities.RED)\nutilities.customPrint(\"Found {} conjunctions out of {} that have maximum Pc lower than true Pc\".format(NO_maxPC_LOWER_THAN_truePC, len(conjunctions)), utilities.RED)\n\nACCUMULATED_PCs_MAX = []; ACCUMULATED_PCs_TRUE = []; accumulatedPcMAX = 1.0; accumulatedPcTRUE = 1.0;\nfor conj in conjunctions: # Save the conjunctions' data once they've been sorted by TCA ascending.\n missDistances.append( conj.MISS_DISTANCE )\n maxProbabilities.append( conj.MAX_COLLISION_PROBABILITY )\n trueProbabilities.append( conj.TRUE_COLLISION_PROBABILITY )\n TCAs.append( conj.TCA )\n\n accumulatedPcMAX = accumulatedPcMAX*conj.NO_COLLISION_PROBABILITY_MAX\n accumulatedPcTRUE = accumulatedPcTRUE*conj.NO_COLLISION_PROBABILITY_TRUE\n \n ACCUMULATED_PCs_MAX.append( 1.0-accumulatedPcMAX )\n ACCUMULATED_PCs_TRUE.append( 1.0-accumulatedPcTRUE )\n\n#\" Make a histogram of misss distances. \"\n#binsMD = [0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0]\n#pylab.figure()\n#nMD, binsMD, patchesMD = pylab.hist( [missDistances, STKmissDistances], binsMD, rwidth=0.8, histtype='bar',color=['r', 'b'],label=['C++', 'STK CAT'])\n#pylab.xticks(binsMD, rotation='vertical')\n#pylab.xlabel('Miss distance bin (km)')\n#pylab.ylabel('Conjunction count')\n#pylab.legend()\n#pylab.show()\n\n#\" Make a histogram of maximum probabilities. \"\n#binsPC = numpy.logspace(-5, 2, num=10)\n#PChistFigure=pylab.figure()\n#PChistAxes=PChistFigure.gca()\n#nPC, binsPC, patchesPC = pylab.hist( [maxProbabilities, STKmaxProbabilities], binsPC, rwidth=0.8, histtype='bar')\n#PChistAxes.set_xscale(\"log\")\n#PChistAxes.set_xlabel('Maximum collision probability')\n#PChistAxes.set_ylabel('Conjunction count')\n#pylab.show()\n\n#\" Make a histogram of true probabilities. \"\n#binsPCtrue = numpy.logspace(-30, 1, num=10)\n#PChistFigureTRUE=pylab.figure()\n#PChistAxesTRUE=PChistFigureTRUE.gca()\n#PChistAxesTRUE.hist( [trueProbabilities, STKtrueProbabilities], binsPCtrue, rwidth=0.8, histtype='bar')\n#PChistAxesTRUE.set_xscale(\"log\")\n#PChistAxesTRUE.set_xlabel('True collision probability')\n#PChistAxesTRUE.set_ylabel('Conjunction count')\n#pylab.show()\n\n\n\"\"\"\n============================================================================================================================\n PLOT EVOLUTION OF ACCUMULATED PROBABILITIES.\n============================================================================================================================\n\"\"\"\n \n# FORMAT THE PLOT\nticksFontSize = 18\nlabelsFontSize = 30\ntitleFontSize = 34\n\nmatplotlib.rc('xtick', labelsize=ticksFontSize) \nmatplotlib.rc('ytick', labelsize=ticksFontSize) \n\nfig, ax = matplotlib.pyplot.subplots(1,figsize=(12,8))\nfig.suptitle(r'$Envisat,\\ one\\ year,\\ conjunctions\\ closer\\ than\\ 20\\ km$', fontsize=titleFontSize) #\\ external\\ ephemeris\n\nmatplotlib.pyplot.grid(linewidth=2)\nax.tick_params(axis='both',reset=False,which='both',length=5,width=1.5)\n\nax.set_xlabel(r'$Epoch\\ (UTCG)$',fontsize=labelsFontSize)\nax.set_ylabel(r'$Accumulated\\ collision\\ probability$',fontsize=labelsFontSize)\n\nmatplotlib.pyplot.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.1)\n\n# DATA PLOTTING\nax.plot(TCAs, ACCUMULATED_PCs_MAX, c=\"0.5\", ls='-', lw=5., label=r'$Maximum\\ probability$')\nax.plot(TCAs, ACCUMULATED_PCs_TRUE, c=\"0.5\", ls='--', lw=5., label=r'$True\\ probability$')\n\nax.plot(STK_TCAs, ACCUMULATED_PCs_MAX_STK, c='k', ls='-', lw=5., label=r'$Maximum\\ probability,\\ STK\\ CAT$')\nax.plot(STK_TCAs, ACCUMULATED_PCs_TRUE_STK, c='k', ls='--', lw=5., label=r'$True\\ probability,\\ STK\\ CAT$')\n \n# Shink current axis' height by 15% on the bottom\nbox = ax.get_position()\nax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.85])\n\nmatplotlib.pyplot.setp( ax.xaxis.get_majorticklabels(), rotation=30 )\n\n# Put a legend below current axis\nax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.17), fancybox=True, shadow=True, ncol=4, prop={'size':18})\n \nfig.show()\n\n\"\"\"\n============================================================================================================================\n PLOT HISTORY OF INDIVIDUAL MAXIMUM PROBABILITIES.\n============================================================================================================================\n\"\"\"\n\nmatplotlib.rc('xtick', labelsize=ticksFontSize) \nmatplotlib.rc('ytick', labelsize=ticksFontSize) \n\nfig2, ax2 = matplotlib.pyplot.subplots(1,figsize=(12,8))\nax2.set_yscale(\"log\")\nfig2.suptitle(r'$Envisat,\\ one\\ year$', fontsize=titleFontSize)\n\nmatplotlib.pyplot.grid(linewidth=2)\nax2.tick_params(axis='both',reset=False,which='both',length=5,width=1.5)\n\nax2.set_xlabel(r'$Epoch\\ (UTCG)$',fontsize=labelsFontSize)\nax2.set_ylabel(r'$Maximum\\ collision\\ probability$',fontsize=labelsFontSize)\n\nmatplotlib.pyplot.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.1)\n\n# DATA PLOTTING\nax2.scatter(TCAs, maxProbabilities, c='r', marker='+', label=r'$Maximum\\ probability,\\ C++$')\n\nax2.scatter(STK_TCAs, STKmaxProbabilities, c='b', marker='x', label=r'$Maximum\\ probability,\\ STK\\ CAT$')\n \n# Shink current axis' height by 15% on the bottom\nbox = ax2.get_position()\nax2.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.85])\n\nmatplotlib.pyplot.setp( ax2.xaxis.get_majorticklabels(), rotation=30 )\n\n# Put a legend below current axis\nax2.legend(loc='upper center', bbox_to_anchor=(0.5, -0.17), fancybox=True, shadow=True, ncol=4, prop={'size':18})\n \nfig2.show()\n\n\"\"\"\n============================================================================================================================\n PLOT HISTORY OF INDIVIDUAL TRUE PROBABILITIES.\n============================================================================================================================\n\"\"\"\n\nmatplotlib.rc('xtick', labelsize=ticksFontSize) \nmatplotlib.rc('ytick', labelsize=ticksFontSize) \n\nfig3, ax3 = matplotlib.pyplot.subplots(1,figsize=(12,8))\nax3.set_yscale(\"log\")\nfig3.suptitle(r'$Envisat,\\ one\\ year,\\ external\\ ephemeris$', fontsize=titleFontSize)\n\nmatplotlib.pyplot.grid(linewidth=2)\nax3.tick_params(axis='both',reset=False,which='both',length=5,width=1.5)\n\nax3.set_xlabel(r'$Epoch\\ (UTCG)$',fontsize=labelsFontSize)\nax3.set_ylabel(r'$True collision\\ probability$',fontsize=labelsFontSize)\n\nmatplotlib.pyplot.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.1)\n\n# DATA PLOTTING\nax3.scatter(TCAs, trueProbabilities, c='r', marker='+', label=r'$True probability,\\ C++$')\n\nax3.scatter(STK_TCAs, STKtrueProbabilities, c='b', marker='x', label=r'$True\\ probability,\\ STK\\ CAT$')\n \n# Shink current axis' height by 15% on the bottom\nbox = ax3.get_position()\nax3.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.85])\n\nmatplotlib.pyplot.setp( ax3.xaxis.get_majorticklabels(), rotation=30 )\n\n# Put a legend below current axis\nax3.legend(loc='upper center', bbox_to_anchor=(0.5, -0.17), fancybox=True, shadow=True, ncol=4, prop={'size':18})\n \nfig3.show()\n\n\"\"\"\n============================================================================================================================\n PLOT HISTORY OF INDIVIDUAL MISS DISTANCES.\n============================================================================================================================\n\"\"\"\n\nmatplotlib.rc('xtick', labelsize=ticksFontSize) \nmatplotlib.rc('ytick', labelsize=ticksFontSize) \n\nfig4, ax4 = matplotlib.pyplot.subplots(1,figsize=(12,8))\nfig4.suptitle(r'$Envisat,\\ one\\ year$', fontsize=titleFontSize)\n\nmatplotlib.pyplot.grid(linewidth=2)\nax4.tick_params(axis='both',reset=False,which='both',length=5,width=1.5)\n\nax4.set_xlabel(r'$Epoch\\ (UTCG)$',fontsize=labelsFontSize)\nax4.set_ylabel(r'$Miss\\ distance\\ (km)$',fontsize=labelsFontSize)\n\nmatplotlib.pyplot.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.1)\n\n# DATA PLOTTING\nax4.scatter(TCAs, missDistances, c='r', marker='+', label=r'$C++$')\n\nax4.scatter(STK_TCAs, STKmissDistances, c='b', marker='x', label=r'$STK\\ CAT$')\n \n# Shink current axis' height by 15% on the bottom\nbox = ax4.get_position()\nax4.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.85])\n\nmatplotlib.pyplot.setp( ax4.xaxis.get_majorticklabels(), rotation=30 )\n\n# Put a legend below current axis\nax4.legend(loc='upper center', bbox_to_anchor=(0.5, -0.17), fancybox=True, shadow=True, ncol=4, prop={'size':18})\n \nfig4.show()\n\n\"\"\"\n============================================================================================================================\n PLOT EVOLUTION OF ACCUMULATED TRUE PROBABILITIES ONLY.\n True probabilities are computed using different algorithms, maximum one is\n computed using S. Alfano so will be the same no matter what size of the\n covaraince ellipsoid.\n============================================================================================================================\n\"\"\"\nmatplotlib.rc('xtick', labelsize=ticksFontSize) \nmatplotlib.rc('ytick', labelsize=ticksFontSize) \n\nfig5, ax5 = matplotlib.pyplot.subplots(1,figsize=(12,8))\nfig5.suptitle(r'$Envisat,\\ one\\ year$', fontsize=titleFontSize)\n#ax5.set_yscale(\"log\")\n\nmatplotlib.pyplot.grid(linewidth=2)\nax5.tick_params(axis='both',reset=False,which='both',length=5,width=1.5)\n\nax5.set_xlabel(r'$Epoch\\ (UTCG)$',fontsize=labelsFontSize)\nax5.set_ylabel(r'$Accumulated\\ true\\ collision\\ probability$',fontsize=labelsFontSize)\n\nmatplotlib.pyplot.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.1)\n\n# DATA PLOTTING\nax5.plot(TCAs, ACCUMULATED_PCs_TRUE, c='r', ls='--', lw=3., label=r'$C++$')\n#ax5.plot(STK_TCAs, ACCUMULATED_PCs_TRUE_STK, c='g', ls='--', lw=3., label=r'$STK\\ CAT ellipsoid\\ size\\ is\\ \\sigma^2$')\nax5.plot(STK_TCAs, ACCUMULATED_PCs_TRUE_STK, c='b', ls='--', lw=3., label=r'$STK\\ CAT$')\n \n# Shink current axis' height by 15% on the bottom\nbox = ax5.get_position()\nax5.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.85])\n\nmatplotlib.pyplot.setp( ax.xaxis.get_majorticklabels(), rotation=30 )\n\n# Put a legend below current axis\nax5.legend(loc='upper center', bbox_to_anchor=(0.5, -0.17), fancybox=True, shadow=True, ncol=4, prop={'size':18})\n \nfig5.show()" ]
[ [ "numpy.linalg.inv", "matplotlib.pyplot.grid", "numpy.linalg.det", "matplotlib.pyplot.subplots", "matplotlib.rc", "matplotlib.pyplot.subplots_adjust", "numpy.array", "numpy.linalg.norm" ] ]
Steve-Tod/DeformSyncNet
[ "c4e6628ae4fd80e6e6aa702f4cd5885368047b4f" ]
[ "code/solver/BaseSolver.py" ]
[ "import logging\nimport os\nfrom collections import OrderedDict\nimport torch\nimport torch.nn as nn\nfrom torch.nn.parallel import DistributedDataParallel\n\nlogger = logging.getLogger('base')\n\nclass BaseSolver:\n def __init__(self, opt):\n self.opt = opt\n if opt['gpu_id'] is not None and torch.cuda.is_available():\n self.device = torch.device('cuda')\n else:\n self.device = torch.device('cpu')\n \n if opt['gpu_id'] is not None and len(opt['gpu_id']) >= 2:\n self.parallel = True\n else:\n self.parallel = False\n self.is_train = opt['is_train']\n self.scheduler_list = []\n self.optimizer_list = []\n self.step = 0\n self.best_step = 0\n self.best_res = 1e5\n \n def feed_data(self, data):\n pass\n \n def optimize_parameter(self):\n pass\n \n def get_current_visual(self):\n pass\n \n def get_current_loss(self):\n pass\n \n def print_network(self):\n pass\n \n def save(self, label):\n pass\n \n def load(self):\n pass\n \n def update_learning_rate(self):\n for s in self.scheduler_list:\n s.step()\n \n def get_current_learning_rate(self):\n return self.optimizer_list[0].param_groups[0]['lr']\n \n def print_network(self):\n # Generator\n s, n = self.get_network_description(self.model)\n if isinstance(self.model, nn.DataParallel):\n net_struc_str = '{} - {}'.format(\n self.model.__class__.__name__,\n self.model.module.__class__.__name__)\n else:\n net_struc_str = '{}'.format(self.model.__class__.__name__)\n logger.info('Network G structure: {}, with parameters: {:,d}'.format(\n net_struc_str, n))\n #logger.info(s)\n \n def get_network_description(self, network):\n '''Get the string and total parameters of the network'''\n if isinstance(network, nn.DataParallel) or isinstance(network, DistributedDataParallel):\n network = network.module\n s = str(network)\n n = sum(map(lambda x: x.numel(), network.parameters()))\n return s, n\n\n def save_network(self, network, network_label, iter_label):\n save_filename = '{}_{}.pth'.format(iter_label, network_label)\n save_path = os.path.join(self.opt['path']['model'], save_filename)\n if isinstance(network, nn.DataParallel) or isinstance(network, DistributedDataParallel):\n network = network.module\n state_dict = network.state_dict()\n for key, param in state_dict.items():\n state_dict[key] = param.cpu()\n torch.save(state_dict, save_path)\n\n def load_network(self, load_path, network, strict=True):\n if isinstance(network, nn.DataParallel) or isinstance(network, DistributedDataParallel):\n network = network.module\n load_net = torch.load(load_path)\n load_net_clean = OrderedDict() \n # remove unnecessary 'module.'\n for k, v in load_net.items():\n if k.startswith('module.'):\n load_net_clean[k[7:]] = v\n else:\n load_net_clean[k] = v\n network.load_state_dict(load_net_clean, strict=strict)\n\n def save_training_state(self, epoch):\n '''Saves training state during training, which will be used for resuming'''\n state = {'epoch': epoch, \n 'iter': self.step, \n 'best_step': self.best_step,\n 'best_res': self.best_res,\n 'schedulers': [], \n 'optimizers': []}\n for s in self.scheduler_list:\n state['schedulers'].append(s.state_dict())\n for o in self.optimizer_list:\n state['optimizers'].append(o.state_dict())\n \n save_filename = '{}.state'.format(self.step)\n save_path = os.path.join(self.opt['path']['training_state'], save_filename)\n torch.save(state, save_path)\n\n def resume_training(self, resume_state):\n '''Resume the optimizers and schedulers for training'''\n resume_optimizer_list = resume_state['optimizers']\n resume_scheduler_list = resume_state['schedulers']\n assert len(resume_optimizer_list) == len(self.optimizer_list), 'Wrong lengths of optimizers'\n assert len(resume_scheduler_list) == len(self.scheduler_list), 'Wrong lengths of schedulers'\n for i, o in enumerate(resume_optimizer_list):\n self.optimizer_list[i].load_state_dict(o)\n for i, s in enumerate(resume_scheduler_list):\n self.scheduler_list[i].load_state_dict(s)\n if 'best_step' in resume_state.keys():\n self.best_step = resume_state['best_step'] \n if 'best_res' in resume_state.keys():\n self.best_res = resume_state['best_res']" ]
[ [ "torch.save", "torch.cuda.is_available", "torch.load", "torch.device" ] ]
mk-michal/pytorch-image-models
[ "9c77a1dfbff5ddc229d9ef6578ab19409ba7ca93" ]
[ "timm/models/efficientnet.py" ]
[ "\"\"\" PyTorch EfficientNet Family\n\nAn implementation of EfficienNet that covers variety of related models with efficient architectures:\n\n* EfficientNet (B0-B8, L2 + Tensorflow pretrained AutoAug/RandAug/AdvProp/NoisyStudent weight ports)\n - EfficientNet: Rethinking Model Scaling for CNNs - https://arxiv.org/abs/1905.11946\n - CondConv: Conditionally Parameterized Convolutions for Efficient Inference - https://arxiv.org/abs/1904.04971\n - Adversarial Examples Improve Image Recognition - https://arxiv.org/abs/1911.09665\n - Self-training with Noisy Student improves ImageNet classification - https://arxiv.org/abs/1911.04252\n\n* MixNet (Small, Medium, and Large)\n - MixConv: Mixed Depthwise Convolutional Kernels - https://arxiv.org/abs/1907.09595\n\n* MNasNet B1, A1 (SE), Small\n - MnasNet: Platform-Aware Neural Architecture Search for Mobile - https://arxiv.org/abs/1807.11626\n\n* FBNet-C\n - FBNet: Hardware-Aware Efficient ConvNet Design via Differentiable NAS - https://arxiv.org/abs/1812.03443\n\n* Single-Path NAS Pixel1\n - Single-Path NAS: Designing Hardware-Efficient ConvNets - https://arxiv.org/abs/1904.02877\n\n* And likely more...\n\nHacked together by / Copyright 2020 Ross Wightman\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom typing import List\n\nfrom timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD\nfrom .efficientnet_blocks import round_channels, resolve_bn_args, resolve_act_layer, BN_EPS_TF_DEFAULT\nfrom .efficientnet_builder import EfficientNetBuilder, decode_arch_def, efficientnet_init_weights\nfrom .features import FeatureInfo, FeatureHooks\nfrom .helpers import build_model_with_cfg, default_cfg_for_features\nfrom .layers import create_conv2d, create_classifier\nfrom .registry import register_model\n\n__all__ = ['EfficientNet']\n\n\ndef _cfg(url='', **kwargs):\n return {\n 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),\n 'crop_pct': 0.875, 'interpolation': 'bicubic',\n 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,\n 'first_conv': 'conv_stem', 'classifier': 'classifier',\n **kwargs\n }\n\n\ndefault_cfgs = {\n 'mnasnet_050': _cfg(url=''),\n 'mnasnet_075': _cfg(url=''),\n 'mnasnet_100': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mnasnet_b1-74cb7081.pth'),\n 'mnasnet_140': _cfg(url=''),\n\n 'semnasnet_050': _cfg(url=''),\n 'semnasnet_075': _cfg(url=''),\n 'semnasnet_100': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mnasnet_a1-d9418771.pth'),\n 'semnasnet_140': _cfg(url=''),\n 'mnasnet_small': _cfg(url=''),\n\n 'mobilenetv2_100': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mobilenetv2_100_ra-b33bc2c4.pth'),\n 'mobilenetv2_110d': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mobilenetv2_110d_ra-77090ade.pth'),\n 'mobilenetv2_120d': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mobilenetv2_120d_ra-5987e2ed.pth'),\n 'mobilenetv2_140': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mobilenetv2_140_ra-21a4e913.pth'),\n\n 'fbnetc_100': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/fbnetc_100-c345b898.pth',\n interpolation='bilinear'),\n 'spnasnet_100': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/spnasnet_100-048bc3f4.pth',\n interpolation='bilinear'),\n\n 'efficientnet_b0': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/efficientnet_b0_ra-3dd342df.pth'),\n 'efficientnet_b1': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/efficientnet_b1-533bc792.pth',\n input_size=(3, 240, 240), pool_size=(8, 8)),\n 'efficientnet_b2': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/efficientnet_b2_ra-bcdf34b7.pth',\n input_size=(3, 260, 260), pool_size=(9, 9)),\n 'efficientnet_b2a': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/efficientnet_b2_ra-bcdf34b7.pth',\n input_size=(3, 288, 288), pool_size=(9, 9), crop_pct=1.0),\n 'efficientnet_b3': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/efficientnet_b3_ra2-cf984f9c.pth',\n input_size=(3, 300, 300), pool_size=(10, 10), crop_pct=0.904),\n 'efficientnet_b3a': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/efficientnet_b3_ra2-cf984f9c.pth',\n input_size=(3, 320, 320), pool_size=(10, 10), crop_pct=1.0),\n 'efficientnet_b4': _cfg(\n url='', input_size=(3, 380, 380), pool_size=(12, 12), crop_pct=0.922),\n 'efficientnet_b5': _cfg(\n url='', input_size=(3, 456, 456), pool_size=(15, 15), crop_pct=0.934),\n 'efficientnet_b6': _cfg(\n url='', input_size=(3, 528, 528), pool_size=(17, 17), crop_pct=0.942),\n 'efficientnet_b7': _cfg(\n url='', input_size=(3, 600, 600), pool_size=(19, 19), crop_pct=0.949),\n 'efficientnet_b8': _cfg(\n url='', input_size=(3, 672, 672), pool_size=(21, 21), crop_pct=0.954),\n 'efficientnet_l2': _cfg(\n url='', input_size=(3, 800, 800), pool_size=(25, 25), crop_pct=0.961),\n\n 'efficientnet_es': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/efficientnet_es_ra-f111e99c.pth'),\n 'efficientnet_em': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/efficientnet_em_ra2-66250f76.pth',\n input_size=(3, 240, 240), pool_size=(8, 8), crop_pct=0.882),\n 'efficientnet_el': _cfg(\n url='https://github.com/DeGirum/pruned-models/releases/download/efficientnet_v1.0/efficientnet_el.pth', \n input_size=(3, 300, 300), pool_size=(10, 10), crop_pct=0.904),\n\n 'efficientnet_es_pruned': _cfg(\n url='https://github.com/DeGirum/pruned-models/releases/download/efficientnet_v1.0/efficientnet_es_pruned75.pth'),\n 'efficientnet_el_pruned': _cfg(\n url='https://github.com/DeGirum/pruned-models/releases/download/efficientnet_v1.0/efficientnet_el_pruned70.pth', \n input_size=(3, 300, 300), pool_size=(10, 10), crop_pct=0.904),\n\n 'efficientnet_cc_b0_4e': _cfg(url=''),\n 'efficientnet_cc_b0_8e': _cfg(url=''),\n 'efficientnet_cc_b1_8e': _cfg(url='', input_size=(3, 240, 240), pool_size=(8, 8), crop_pct=0.882),\n\n 'efficientnet_lite0': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/efficientnet_lite0_ra-37913777.pth'),\n 'efficientnet_lite1': _cfg(\n url='',\n input_size=(3, 240, 240), pool_size=(8, 8), crop_pct=0.882),\n 'efficientnet_lite2': _cfg(\n url='',\n input_size=(3, 260, 260), pool_size=(9, 9), crop_pct=0.890),\n 'efficientnet_lite3': _cfg(\n url='',\n input_size=(3, 300, 300), pool_size=(10, 10), crop_pct=0.904),\n 'efficientnet_lite4': _cfg(\n url='', input_size=(3, 380, 380), pool_size=(12, 12), crop_pct=0.922),\n\n 'efficientnet_b1_pruned': _cfg(\n url='https://imvl-automl-sh.oss-cn-shanghai.aliyuncs.com/darts/hyperml/hyperml/job_45403/outputs/effnetb1_pruned_9ebb3fe6.pth',\n input_size=(3, 240, 240), pool_size=(8, 8), crop_pct=0.882, mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD),\n 'efficientnet_b2_pruned': _cfg(\n url='https://imvl-automl-sh.oss-cn-shanghai.aliyuncs.com/darts/hyperml/hyperml/job_45403/outputs/effnetb2_pruned_203f55bc.pth',\n input_size=(3, 260, 260), pool_size=(9, 9), crop_pct=0.890, mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD),\n 'efficientnet_b3_pruned': _cfg(\n url='https://imvl-automl-sh.oss-cn-shanghai.aliyuncs.com/darts/hyperml/hyperml/job_45403/outputs/effnetb3_pruned_5abcc29f.pth',\n input_size=(3, 300, 300), pool_size=(10, 10), crop_pct=0.904, mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD),\n\n 'efficientnet_v2s': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/efficientnet_v2s_ra2-b265c1ba.pth',\n input_size=(3, 224, 224), test_size=(3, 288, 288), pool_size=(7, 7), crop_pct=1.0), # FIXME WIP\n\n 'tf_efficientnet_b0': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b0_aa-827b6e33.pth',\n input_size=(3, 224, 224)),\n 'tf_efficientnet_b1': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b1_aa-ea7a6ee0.pth',\n input_size=(3, 240, 240), pool_size=(8, 8), crop_pct=0.882),\n 'tf_efficientnet_b2': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b2_aa-60c94f97.pth',\n input_size=(3, 260, 260), pool_size=(9, 9), crop_pct=0.890),\n 'tf_efficientnet_b3': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b3_aa-84b4657e.pth',\n input_size=(3, 300, 300), pool_size=(10, 10), crop_pct=0.904),\n 'tf_efficientnet_b4': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b4_aa-818f208c.pth',\n input_size=(3, 380, 380), pool_size=(12, 12), crop_pct=0.922),\n 'tf_efficientnet_b5': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b5_ra-9a3e5369.pth',\n input_size=(3, 456, 456), pool_size=(15, 15), crop_pct=0.934),\n 'tf_efficientnet_b6': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b6_aa-80ba17e4.pth',\n input_size=(3, 528, 528), pool_size=(17, 17), crop_pct=0.942),\n 'tf_efficientnet_b7': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b7_ra-6c08e654.pth',\n input_size=(3, 600, 600), pool_size=(19, 19), crop_pct=0.949),\n 'tf_efficientnet_b8': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b8_ra-572d5dd9.pth',\n input_size=(3, 672, 672), pool_size=(21, 21), crop_pct=0.954),\n\n 'tf_efficientnet_b0_ap': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b0_ap-f262efe1.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD, input_size=(3, 224, 224)),\n 'tf_efficientnet_b1_ap': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b1_ap-44ef0a3d.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD,\n input_size=(3, 240, 240), pool_size=(8, 8), crop_pct=0.882),\n 'tf_efficientnet_b2_ap': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b2_ap-2f8e7636.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD,\n input_size=(3, 260, 260), pool_size=(9, 9), crop_pct=0.890),\n 'tf_efficientnet_b3_ap': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b3_ap-aad25bdd.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD,\n input_size=(3, 300, 300), pool_size=(10, 10), crop_pct=0.904),\n 'tf_efficientnet_b4_ap': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b4_ap-dedb23e6.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD,\n input_size=(3, 380, 380), pool_size=(12, 12), crop_pct=0.922),\n 'tf_efficientnet_b5_ap': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b5_ap-9e82fae8.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD,\n input_size=(3, 456, 456), pool_size=(15, 15), crop_pct=0.934),\n 'tf_efficientnet_b6_ap': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b6_ap-4ffb161f.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD,\n input_size=(3, 528, 528), pool_size=(17, 17), crop_pct=0.942),\n 'tf_efficientnet_b7_ap': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b7_ap-ddb28fec.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD,\n input_size=(3, 600, 600), pool_size=(19, 19), crop_pct=0.949),\n 'tf_efficientnet_b8_ap': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b8_ap-00e169fa.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD,\n input_size=(3, 672, 672), pool_size=(21, 21), crop_pct=0.954),\n\n 'tf_efficientnet_b0_ns': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b0_ns-c0e6a31c.pth',\n input_size=(3, 224, 224)),\n 'tf_efficientnet_b1_ns': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b1_ns-99dd0c41.pth',\n input_size=(3, 240, 240), pool_size=(8, 8), crop_pct=0.882),\n 'tf_efficientnet_b2_ns': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b2_ns-00306e48.pth',\n input_size=(3, 260, 260), pool_size=(9, 9), crop_pct=0.890),\n 'tf_efficientnet_b3_ns': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b3_ns-9d44bf68.pth',\n input_size=(3, 300, 300), pool_size=(10, 10), crop_pct=0.904),\n 'tf_efficientnet_b4_ns': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b4_ns-d6313a46.pth',\n input_size=(3, 380, 380), pool_size=(12, 12), crop_pct=0.922),\n 'tf_efficientnet_b5_ns': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b5_ns-6f26d0cf.pth',\n input_size=(3, 456, 456), pool_size=(15, 15), crop_pct=0.934),\n 'tf_efficientnet_b6_ns': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b6_ns-51548356.pth',\n input_size=(3, 528, 528), pool_size=(17, 17), crop_pct=0.942),\n 'tf_efficientnet_b7_ns': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b7_ns-1dbc32de.pth',\n input_size=(3, 600, 600), pool_size=(19, 19), crop_pct=0.949),\n 'tf_efficientnet_l2_ns_475': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_l2_ns_475-bebbd00a.pth',\n input_size=(3, 475, 475), pool_size=(15, 15), crop_pct=0.936),\n 'tf_efficientnet_l2_ns': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_l2_ns-df73bb44.pth',\n input_size=(3, 800, 800), pool_size=(25, 25), crop_pct=0.96),\n\n 'tf_efficientnet_es': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_es-ca1afbfe.pth',\n mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),\n input_size=(3, 224, 224), ),\n 'tf_efficientnet_em': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_em-e78cfe58.pth',\n mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),\n input_size=(3, 240, 240), pool_size=(8, 8), crop_pct=0.882),\n 'tf_efficientnet_el': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_el-5143854e.pth',\n mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),\n input_size=(3, 300, 300), pool_size=(10, 10), crop_pct=0.904),\n\n 'tf_efficientnet_cc_b0_4e': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_cc_b0_4e-4362b6b2.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD),\n 'tf_efficientnet_cc_b0_8e': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_cc_b0_8e-66184a25.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD),\n 'tf_efficientnet_cc_b1_8e': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_cc_b1_8e-f7c79ae1.pth',\n mean=IMAGENET_INCEPTION_MEAN, std=IMAGENET_INCEPTION_STD,\n input_size=(3, 240, 240), pool_size=(8, 8), crop_pct=0.882),\n\n 'tf_efficientnet_lite0': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_lite0-0aa007d2.pth',\n mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),\n interpolation='bicubic', # should be bilinear but bicubic better match for TF bilinear at low res\n ),\n 'tf_efficientnet_lite1': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_lite1-bde8b488.pth',\n mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),\n input_size=(3, 240, 240), pool_size=(8, 8), crop_pct=0.882,\n interpolation='bicubic', # should be bilinear but bicubic better match for TF bilinear at low res\n ),\n 'tf_efficientnet_lite2': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_lite2-dcccb7df.pth',\n mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),\n input_size=(3, 260, 260), pool_size=(9, 9), crop_pct=0.890,\n interpolation='bicubic', # should be bilinear but bicubic better match for TF bilinear at low res\n ),\n 'tf_efficientnet_lite3': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_lite3-b733e338.pth',\n mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),\n input_size=(3, 300, 300), pool_size=(10, 10), crop_pct=0.904, interpolation='bilinear'),\n 'tf_efficientnet_lite4': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_lite4-741542c3.pth',\n mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),\n input_size=(3, 380, 380), pool_size=(12, 12), crop_pct=0.920, interpolation='bilinear'),\n\n 'mixnet_s': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mixnet_s-a907afbc.pth'),\n 'mixnet_m': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mixnet_m-4647fc68.pth'),\n 'mixnet_l': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mixnet_l-5a9a2ed8.pth'),\n 'mixnet_xl': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mixnet_xl_ra-aac3c00c.pth'),\n 'mixnet_xxl': _cfg(),\n\n 'tf_mixnet_s': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_mixnet_s-89d3354b.pth'),\n 'tf_mixnet_m': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_mixnet_m-0f4d8805.pth'),\n 'tf_mixnet_l': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_mixnet_l-6c92e0c8.pth'),\n}\n\n_DEBUG = False\n\n\nclass EfficientNet(nn.Module):\n \"\"\" (Generic) EfficientNet\n\n A flexible and performant PyTorch implementation of efficient network architectures, including:\n * EfficientNet B0-B8, L2\n * EfficientNet-EdgeTPU\n * EfficientNet-CondConv\n * MixNet S, M, L, XL\n * MnasNet A1, B1, and small\n * FBNet C\n * Single-Path NAS Pixel1\n\n \"\"\"\n\n def __init__(self, block_args, num_classes=1000, num_features=1280, in_chans=3, stem_size=32,\n channel_multiplier=1.0, channel_divisor=8, channel_min=None,\n output_stride=32, pad_type='', fix_stem=False, act_layer=nn.ReLU, drop_rate=0., drop_path_rate=0.,\n se_kwargs=None, norm_layer=nn.BatchNorm2d, norm_kwargs=None, global_pool='avg'):\n super(EfficientNet, self).__init__()\n norm_kwargs = norm_kwargs or {}\n\n self.num_classes = num_classes\n self.num_features = num_features\n self.drop_rate = drop_rate\n\n # Stem\n if not fix_stem:\n stem_size = round_channels(stem_size, channel_multiplier, channel_divisor, channel_min)\n self.conv_stem = create_conv2d(in_chans, stem_size, 3, stride=2, padding=pad_type)\n self.bn1 = norm_layer(stem_size, **norm_kwargs)\n self.act1 = act_layer(inplace=True)\n\n # Middle stages (IR/ER/DS Blocks)\n builder = EfficientNetBuilder(\n channel_multiplier, channel_divisor, channel_min, output_stride, pad_type, act_layer, se_kwargs,\n norm_layer, norm_kwargs, drop_path_rate, verbose=_DEBUG)\n self.blocks = nn.Sequential(*builder(stem_size, block_args))\n self.feature_info = builder.features\n head_chs = builder.in_chs\n\n # Head + Pooling\n self.conv_head = create_conv2d(head_chs, self.num_features, 1, padding=pad_type)\n self.bn2 = norm_layer(self.num_features, **norm_kwargs)\n self.act2 = act_layer(inplace=True)\n self.global_pool, self.classifier = create_classifier(\n self.num_features, self.num_classes, pool_type=global_pool)\n\n efficientnet_init_weights(self)\n\n def as_sequential(self):\n layers = [self.conv_stem, self.bn1, self.act1]\n layers.extend(self.blocks)\n layers.extend([self.conv_head, self.bn2, self.act2, self.global_pool])\n layers.extend([nn.Dropout(self.drop_rate), self.classifier])\n return nn.Sequential(*layers)\n\n def get_classifier(self):\n return self.classifier\n\n def reset_classifier(self, num_classes, global_pool='avg'):\n self.num_classes = num_classes\n self.global_pool, self.classifier = create_classifier(\n self.num_features, self.num_classes, pool_type=global_pool)\n\n def forward_features(self, x):\n x = self.conv_stem(x)\n x = self.bn1(x)\n x = self.act1(x)\n x = self.blocks(x)\n x = self.conv_head(x)\n x = self.bn2(x)\n x = self.act2(x)\n return x\n\n def forward(self, x):\n x = self.forward_features(x)\n x = self.global_pool(x)\n if self.drop_rate > 0.:\n x = F.dropout(x, p=self.drop_rate, training=self.training)\n return self.classifier(x)\n\n\nclass EfficientNetFeatures(nn.Module):\n \"\"\" EfficientNet Feature Extractor\n\n A work-in-progress feature extraction module for EfficientNet, to use as a backbone for segmentation\n and object detection models.\n \"\"\"\n\n def __init__(self, block_args, out_indices=(0, 1, 2, 3, 4), feature_location='bottleneck',\n in_chans=3, stem_size=32, channel_multiplier=1.0, channel_divisor=8, channel_min=None,\n output_stride=32, pad_type='', fix_stem=False, act_layer=nn.ReLU, drop_rate=0., drop_path_rate=0.,\n se_kwargs=None, norm_layer=nn.BatchNorm2d, norm_kwargs=None):\n super(EfficientNetFeatures, self).__init__()\n norm_kwargs = norm_kwargs or {}\n self.drop_rate = drop_rate\n\n # Stem\n if not fix_stem:\n stem_size = round_channels(stem_size, channel_multiplier, channel_divisor, channel_min)\n self.conv_stem = create_conv2d(in_chans, stem_size, 3, stride=2, padding=pad_type)\n self.bn1 = norm_layer(stem_size, **norm_kwargs)\n self.act1 = act_layer(inplace=True)\n\n # Middle stages (IR/ER/DS Blocks)\n builder = EfficientNetBuilder(\n channel_multiplier, channel_divisor, channel_min, output_stride, pad_type, act_layer, se_kwargs,\n norm_layer, norm_kwargs, drop_path_rate, feature_location=feature_location, verbose=_DEBUG)\n self.blocks = nn.Sequential(*builder(stem_size, block_args))\n self.feature_info = FeatureInfo(builder.features, out_indices)\n self._stage_out_idx = {v['stage']: i for i, v in enumerate(self.feature_info) if i in out_indices}\n\n efficientnet_init_weights(self)\n\n # Register feature extraction hooks with FeatureHooks helper\n self.feature_hooks = None\n if feature_location != 'bottleneck':\n hooks = self.feature_info.get_dicts(keys=('module', 'hook_type'))\n self.feature_hooks = FeatureHooks(hooks, self.named_modules())\n\n def forward(self, x) -> List[torch.Tensor]:\n x = self.conv_stem(x)\n x = self.bn1(x)\n x = self.act1(x)\n if self.feature_hooks is None:\n features = []\n if 0 in self._stage_out_idx:\n features.append(x) # add stem out\n for i, b in enumerate(self.blocks):\n x = b(x)\n if i + 1 in self._stage_out_idx:\n features.append(x)\n return features\n else:\n self.blocks(x)\n out = self.feature_hooks.get_output(x.device)\n return list(out.values())\n\n\ndef _create_effnet(variant, pretrained=False, **kwargs):\n features_only = False\n model_cls = EfficientNet\n kwargs_filter = None\n if kwargs.pop('features_only', False):\n features_only = True\n kwargs_filter = ('num_classes', 'num_features', 'head_conv', 'global_pool')\n model_cls = EfficientNetFeatures\n model = build_model_with_cfg(\n model_cls, variant, pretrained,\n default_cfg=default_cfgs[variant],\n pretrained_strict=not features_only,\n kwargs_filter=kwargs_filter,\n **kwargs)\n if features_only:\n model.default_cfg = default_cfg_for_features(model.default_cfg)\n return model\n\n\ndef _gen_mnasnet_a1(variant, channel_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\"Creates a mnasnet-a1 model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet\n Paper: https://arxiv.org/pdf/1807.11626.pdf.\n\n Args:\n channel_multiplier: multiplier to number of channels per layer.\n \"\"\"\n arch_def = [\n # stage 0, 112x112 in\n ['ds_r1_k3_s1_e1_c16_noskip'],\n # stage 1, 112x112 in\n ['ir_r2_k3_s2_e6_c24'],\n # stage 2, 56x56 in\n ['ir_r3_k5_s2_e3_c40_se0.25'],\n # stage 3, 28x28 in\n ['ir_r4_k3_s2_e6_c80'],\n # stage 4, 14x14in\n ['ir_r2_k3_s1_e6_c112_se0.25'],\n # stage 5, 14x14in\n ['ir_r3_k5_s2_e6_c160_se0.25'],\n # stage 6, 7x7 in\n ['ir_r1_k3_s1_e6_c320'],\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def),\n stem_size=32,\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n **kwargs\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_mnasnet_b1(variant, channel_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\"Creates a mnasnet-b1 model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet\n Paper: https://arxiv.org/pdf/1807.11626.pdf.\n\n Args:\n channel_multiplier: multiplier to number of channels per layer.\n \"\"\"\n arch_def = [\n # stage 0, 112x112 in\n ['ds_r1_k3_s1_c16_noskip'],\n # stage 1, 112x112 in\n ['ir_r3_k3_s2_e3_c24'],\n # stage 2, 56x56 in\n ['ir_r3_k5_s2_e3_c40'],\n # stage 3, 28x28 in\n ['ir_r3_k5_s2_e6_c80'],\n # stage 4, 14x14in\n ['ir_r2_k3_s1_e6_c96'],\n # stage 5, 14x14in\n ['ir_r4_k5_s2_e6_c192'],\n # stage 6, 7x7 in\n ['ir_r1_k3_s1_e6_c320_noskip']\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def),\n stem_size=32,\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n **kwargs\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_mnasnet_small(variant, channel_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\"Creates a mnasnet-b1 model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet\n Paper: https://arxiv.org/pdf/1807.11626.pdf.\n\n Args:\n channel_multiplier: multiplier to number of channels per layer.\n \"\"\"\n arch_def = [\n ['ds_r1_k3_s1_c8'],\n ['ir_r1_k3_s2_e3_c16'],\n ['ir_r2_k3_s2_e6_c16'],\n ['ir_r4_k5_s2_e6_c32_se0.25'],\n ['ir_r3_k3_s1_e6_c32_se0.25'],\n ['ir_r3_k5_s2_e6_c88_se0.25'],\n ['ir_r1_k3_s1_e6_c144']\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def),\n stem_size=8,\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n **kwargs\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_mobilenet_v2(\n variant, channel_multiplier=1.0, depth_multiplier=1.0, fix_stem_head=False, pretrained=False, **kwargs):\n \"\"\" Generate MobileNet-V2 network\n Ref impl: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet_v2.py\n Paper: https://arxiv.org/abs/1801.04381\n \"\"\"\n arch_def = [\n ['ds_r1_k3_s1_c16'],\n ['ir_r2_k3_s2_e6_c24'],\n ['ir_r3_k3_s2_e6_c32'],\n ['ir_r4_k3_s2_e6_c64'],\n ['ir_r3_k3_s1_e6_c96'],\n ['ir_r3_k3_s2_e6_c160'],\n ['ir_r1_k3_s1_e6_c320'],\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def, depth_multiplier=depth_multiplier, fix_first_last=fix_stem_head),\n num_features=1280 if fix_stem_head else round_channels(1280, channel_multiplier, 8, None),\n stem_size=32,\n fix_stem=fix_stem_head,\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n act_layer=resolve_act_layer(kwargs, 'relu6'),\n **kwargs\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_fbnetc(variant, channel_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\" FBNet-C\n\n Paper: https://arxiv.org/abs/1812.03443\n Ref Impl: https://github.com/facebookresearch/maskrcnn-benchmark/blob/master/maskrcnn_benchmark/modeling/backbone/fbnet_modeldef.py\n\n NOTE: the impl above does not relate to the 'C' variant here, that was derived from paper,\n it was used to confirm some building block details\n \"\"\"\n arch_def = [\n ['ir_r1_k3_s1_e1_c16'],\n ['ir_r1_k3_s2_e6_c24', 'ir_r2_k3_s1_e1_c24'],\n ['ir_r1_k5_s2_e6_c32', 'ir_r1_k5_s1_e3_c32', 'ir_r1_k5_s1_e6_c32', 'ir_r1_k3_s1_e6_c32'],\n ['ir_r1_k5_s2_e6_c64', 'ir_r1_k5_s1_e3_c64', 'ir_r2_k5_s1_e6_c64'],\n ['ir_r3_k5_s1_e6_c112', 'ir_r1_k5_s1_e3_c112'],\n ['ir_r4_k5_s2_e6_c184'],\n ['ir_r1_k3_s1_e6_c352'],\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def),\n stem_size=16,\n num_features=1984, # paper suggests this, but is not 100% clear\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n **kwargs\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_spnasnet(variant, channel_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\"Creates the Single-Path NAS model from search targeted for Pixel1 phone.\n\n Paper: https://arxiv.org/abs/1904.02877\n\n Args:\n channel_multiplier: multiplier to number of channels per layer.\n \"\"\"\n arch_def = [\n # stage 0, 112x112 in\n ['ds_r1_k3_s1_c16_noskip'],\n # stage 1, 112x112 in\n ['ir_r3_k3_s2_e3_c24'],\n # stage 2, 56x56 in\n ['ir_r1_k5_s2_e6_c40', 'ir_r3_k3_s1_e3_c40'],\n # stage 3, 28x28 in\n ['ir_r1_k5_s2_e6_c80', 'ir_r3_k3_s1_e3_c80'],\n # stage 4, 14x14in\n ['ir_r1_k5_s1_e6_c96', 'ir_r3_k5_s1_e3_c96'],\n # stage 5, 14x14in\n ['ir_r4_k5_s2_e6_c192'],\n # stage 6, 7x7 in\n ['ir_r1_k3_s1_e6_c320_noskip']\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def),\n stem_size=32,\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n **kwargs\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_efficientnet(variant, channel_multiplier=1.0, depth_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\"Creates an EfficientNet model.\n\n Ref impl: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/efficientnet_model.py\n Paper: https://arxiv.org/abs/1905.11946\n\n EfficientNet params\n name: (channel_multiplier, depth_multiplier, resolution, dropout_rate)\n 'efficientnet-b0': (1.0, 1.0, 224, 0.2),\n 'efficientnet-b1': (1.0, 1.1, 240, 0.2),\n 'efficientnet-b2': (1.1, 1.2, 260, 0.3),\n 'efficientnet-b3': (1.2, 1.4, 300, 0.3),\n 'efficientnet-b4': (1.4, 1.8, 380, 0.4),\n 'efficientnet-b5': (1.6, 2.2, 456, 0.4),\n 'efficientnet-b6': (1.8, 2.6, 528, 0.5),\n 'efficientnet-b7': (2.0, 3.1, 600, 0.5),\n 'efficientnet-b8': (2.2, 3.6, 672, 0.5),\n 'efficientnet-l2': (4.3, 5.3, 800, 0.5),\n\n Args:\n channel_multiplier: multiplier to number of channels per layer\n depth_multiplier: multiplier to number of repeats per stage\n\n \"\"\"\n arch_def = [\n ['ds_r1_k3_s1_e1_c16_se0.25'],\n ['ir_r2_k3_s2_e6_c24_se0.25'],\n ['ir_r2_k5_s2_e6_c40_se0.25'],\n ['ir_r3_k3_s2_e6_c80_se0.25'],\n ['ir_r3_k5_s1_e6_c112_se0.25'],\n ['ir_r4_k5_s2_e6_c192_se0.25'],\n ['ir_r1_k3_s1_e6_c320_se0.25'],\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def, depth_multiplier),\n num_features=round_channels(1280, channel_multiplier, 8, None),\n stem_size=32,\n channel_multiplier=channel_multiplier,\n act_layer=resolve_act_layer(kwargs, 'swish'),\n norm_kwargs=resolve_bn_args(kwargs),\n **kwargs,\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_efficientnet_edge(variant, channel_multiplier=1.0, depth_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\" Creates an EfficientNet-EdgeTPU model\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet/edgetpu\n \"\"\"\n\n arch_def = [\n # NOTE `fc` is present to override a mismatch between stem channels and in chs not\n # present in other models\n ['er_r1_k3_s1_e4_c24_fc24_noskip'],\n ['er_r2_k3_s2_e8_c32'],\n ['er_r4_k3_s2_e8_c48'],\n ['ir_r5_k5_s2_e8_c96'],\n ['ir_r4_k5_s1_e8_c144'],\n ['ir_r2_k5_s2_e8_c192'],\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def, depth_multiplier),\n num_features=round_channels(1280, channel_multiplier, 8, None),\n stem_size=32,\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n act_layer=resolve_act_layer(kwargs, 'relu'),\n **kwargs,\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_efficientnet_condconv(\n variant, channel_multiplier=1.0, depth_multiplier=1.0, experts_multiplier=1, pretrained=False, **kwargs):\n \"\"\"Creates an EfficientNet-CondConv model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet/condconv\n \"\"\"\n arch_def = [\n ['ds_r1_k3_s1_e1_c16_se0.25'],\n ['ir_r2_k3_s2_e6_c24_se0.25'],\n ['ir_r2_k5_s2_e6_c40_se0.25'],\n ['ir_r3_k3_s2_e6_c80_se0.25'],\n ['ir_r3_k5_s1_e6_c112_se0.25_cc4'],\n ['ir_r4_k5_s2_e6_c192_se0.25_cc4'],\n ['ir_r1_k3_s1_e6_c320_se0.25_cc4'],\n ]\n # NOTE unlike official impl, this one uses `cc<x>` option where x is the base number of experts for each stage and\n # the expert_multiplier increases that on a per-model basis as with depth/channel multipliers\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def, depth_multiplier, experts_multiplier=experts_multiplier),\n num_features=round_channels(1280, channel_multiplier, 8, None),\n stem_size=32,\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n act_layer=resolve_act_layer(kwargs, 'swish'),\n **kwargs,\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_efficientnet_lite(variant, channel_multiplier=1.0, depth_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\"Creates an EfficientNet-Lite model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet/lite\n Paper: https://arxiv.org/abs/1905.11946\n\n EfficientNet params\n name: (channel_multiplier, depth_multiplier, resolution, dropout_rate)\n 'efficientnet-lite0': (1.0, 1.0, 224, 0.2),\n 'efficientnet-lite1': (1.0, 1.1, 240, 0.2),\n 'efficientnet-lite2': (1.1, 1.2, 260, 0.3),\n 'efficientnet-lite3': (1.2, 1.4, 280, 0.3),\n 'efficientnet-lite4': (1.4, 1.8, 300, 0.3),\n\n Args:\n channel_multiplier: multiplier to number of channels per layer\n depth_multiplier: multiplier to number of repeats per stage\n \"\"\"\n arch_def = [\n ['ds_r1_k3_s1_e1_c16'],\n ['ir_r2_k3_s2_e6_c24'],\n ['ir_r2_k5_s2_e6_c40'],\n ['ir_r3_k3_s2_e6_c80'],\n ['ir_r3_k5_s1_e6_c112'],\n ['ir_r4_k5_s2_e6_c192'],\n ['ir_r1_k3_s1_e6_c320'],\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def, depth_multiplier, fix_first_last=True),\n num_features=1280,\n stem_size=32,\n fix_stem=True,\n channel_multiplier=channel_multiplier,\n act_layer=resolve_act_layer(kwargs, 'relu6'),\n norm_kwargs=resolve_bn_args(kwargs),\n **kwargs,\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_efficientnet_v2s(variant, channel_multiplier=1.0, depth_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\" Creates an EfficientNet-V2s model\n\n NOTE: this is a preliminary definition based on paper, awaiting official code release for details\n and weights\n\n Ref impl:\n Paper: `EfficientNetV2: Smaller Models and Faster Training` - https://arxiv.org/abs/2104.00298\n \"\"\"\n\n arch_def = [\n # FIXME it's not clear if the FusedMBConv layers have SE enabled for the Small variant,\n # Table 4 suggests no. 23.94M params w/o, 23.98 with which is closer to 24M.\n # ['er_r2_k3_s1_e1_c24_se0.25'],\n # ['er_r4_k3_s2_e4_c48_se0.25'],\n # ['er_r4_k3_s2_e4_c64_se0.25'],\n ['er_r2_k3_s1_e1_c24'],\n ['er_r4_k3_s2_e4_c48'],\n ['er_r4_k3_s2_e4_c64'],\n ['ir_r6_k3_s2_e4_c128_se0.25'],\n ['ir_r9_k3_s1_e6_c160_se0.25'],\n ['ir_r15_k3_s2_e6_c272_se0.25'],\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def, depth_multiplier),\n num_features=round_channels(1792, channel_multiplier, 8, None),\n stem_size=24,\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n act_layer=resolve_act_layer(kwargs, 'silu'), # FIXME this is an assumption, paper does not mention\n **kwargs,\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_mixnet_s(variant, channel_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\"Creates a MixNet Small model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet/mixnet\n Paper: https://arxiv.org/abs/1907.09595\n \"\"\"\n arch_def = [\n # stage 0, 112x112 in\n ['ds_r1_k3_s1_e1_c16'], # relu\n # stage 1, 112x112 in\n ['ir_r1_k3_a1.1_p1.1_s2_e6_c24', 'ir_r1_k3_a1.1_p1.1_s1_e3_c24'], # relu\n # stage 2, 56x56 in\n ['ir_r1_k3.5.7_s2_e6_c40_se0.5_nsw', 'ir_r3_k3.5_a1.1_p1.1_s1_e6_c40_se0.5_nsw'], # swish\n # stage 3, 28x28 in\n ['ir_r1_k3.5.7_p1.1_s2_e6_c80_se0.25_nsw', 'ir_r2_k3.5_p1.1_s1_e6_c80_se0.25_nsw'], # swish\n # stage 4, 14x14in\n ['ir_r1_k3.5.7_a1.1_p1.1_s1_e6_c120_se0.5_nsw', 'ir_r2_k3.5.7.9_a1.1_p1.1_s1_e3_c120_se0.5_nsw'], # swish\n # stage 5, 14x14in\n ['ir_r1_k3.5.7.9.11_s2_e6_c200_se0.5_nsw', 'ir_r2_k3.5.7.9_p1.1_s1_e6_c200_se0.5_nsw'], # swish\n # 7x7\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def),\n num_features=1536,\n stem_size=16,\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n **kwargs\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\ndef _gen_mixnet_m(variant, channel_multiplier=1.0, depth_multiplier=1.0, pretrained=False, **kwargs):\n \"\"\"Creates a MixNet Medium-Large model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet/mixnet\n Paper: https://arxiv.org/abs/1907.09595\n \"\"\"\n arch_def = [\n # stage 0, 112x112 in\n ['ds_r1_k3_s1_e1_c24'], # relu\n # stage 1, 112x112 in\n ['ir_r1_k3.5.7_a1.1_p1.1_s2_e6_c32', 'ir_r1_k3_a1.1_p1.1_s1_e3_c32'], # relu\n # stage 2, 56x56 in\n ['ir_r1_k3.5.7.9_s2_e6_c40_se0.5_nsw', 'ir_r3_k3.5_a1.1_p1.1_s1_e6_c40_se0.5_nsw'], # swish\n # stage 3, 28x28 in\n ['ir_r1_k3.5.7_s2_e6_c80_se0.25_nsw', 'ir_r3_k3.5.7.9_a1.1_p1.1_s1_e6_c80_se0.25_nsw'], # swish\n # stage 4, 14x14in\n ['ir_r1_k3_s1_e6_c120_se0.5_nsw', 'ir_r3_k3.5.7.9_a1.1_p1.1_s1_e3_c120_se0.5_nsw'], # swish\n # stage 5, 14x14in\n ['ir_r1_k3.5.7.9_s2_e6_c200_se0.5_nsw', 'ir_r3_k3.5.7.9_p1.1_s1_e6_c200_se0.5_nsw'], # swish\n # 7x7\n ]\n model_kwargs = dict(\n block_args=decode_arch_def(arch_def, depth_multiplier, depth_trunc='round'),\n num_features=1536,\n stem_size=24,\n channel_multiplier=channel_multiplier,\n norm_kwargs=resolve_bn_args(kwargs),\n **kwargs\n )\n model = _create_effnet(variant, pretrained, **model_kwargs)\n return model\n\n\n@register_model\ndef mnasnet_050(pretrained=False, **kwargs):\n \"\"\" MNASNet B1, depth multiplier of 0.5. \"\"\"\n model = _gen_mnasnet_b1('mnasnet_050', 0.5, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mnasnet_075(pretrained=False, **kwargs):\n \"\"\" MNASNet B1, depth multiplier of 0.75. \"\"\"\n model = _gen_mnasnet_b1('mnasnet_075', 0.75, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mnasnet_100(pretrained=False, **kwargs):\n \"\"\" MNASNet B1, depth multiplier of 1.0. \"\"\"\n model = _gen_mnasnet_b1('mnasnet_100', 1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mnasnet_b1(pretrained=False, **kwargs):\n \"\"\" MNASNet B1, depth multiplier of 1.0. \"\"\"\n return mnasnet_100(pretrained, **kwargs)\n\n\n@register_model\ndef mnasnet_140(pretrained=False, **kwargs):\n \"\"\" MNASNet B1, depth multiplier of 1.4 \"\"\"\n model = _gen_mnasnet_b1('mnasnet_140', 1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef semnasnet_050(pretrained=False, **kwargs):\n \"\"\" MNASNet A1 (w/ SE), depth multiplier of 0.5 \"\"\"\n model = _gen_mnasnet_a1('semnasnet_050', 0.5, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef semnasnet_075(pretrained=False, **kwargs):\n \"\"\" MNASNet A1 (w/ SE), depth multiplier of 0.75. \"\"\"\n model = _gen_mnasnet_a1('semnasnet_075', 0.75, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef semnasnet_100(pretrained=False, **kwargs):\n \"\"\" MNASNet A1 (w/ SE), depth multiplier of 1.0. \"\"\"\n model = _gen_mnasnet_a1('semnasnet_100', 1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mnasnet_a1(pretrained=False, **kwargs):\n \"\"\" MNASNet A1 (w/ SE), depth multiplier of 1.0. \"\"\"\n return semnasnet_100(pretrained, **kwargs)\n\n\n@register_model\ndef semnasnet_140(pretrained=False, **kwargs):\n \"\"\" MNASNet A1 (w/ SE), depth multiplier of 1.4. \"\"\"\n model = _gen_mnasnet_a1('semnasnet_140', 1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mnasnet_small(pretrained=False, **kwargs):\n \"\"\" MNASNet Small, depth multiplier of 1.0. \"\"\"\n model = _gen_mnasnet_small('mnasnet_small', 1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mobilenetv2_100(pretrained=False, **kwargs):\n \"\"\" MobileNet V2 w/ 1.0 channel multiplier \"\"\"\n model = _gen_mobilenet_v2('mobilenetv2_100', 1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mobilenetv2_140(pretrained=False, **kwargs):\n \"\"\" MobileNet V2 w/ 1.4 channel multiplier \"\"\"\n model = _gen_mobilenet_v2('mobilenetv2_140', 1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mobilenetv2_110d(pretrained=False, **kwargs):\n \"\"\" MobileNet V2 w/ 1.1 channel, 1.2 depth multipliers\"\"\"\n model = _gen_mobilenet_v2(\n 'mobilenetv2_110d', 1.1, depth_multiplier=1.2, fix_stem_head=True, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mobilenetv2_120d(pretrained=False, **kwargs):\n \"\"\" MobileNet V2 w/ 1.2 channel, 1.4 depth multipliers \"\"\"\n model = _gen_mobilenet_v2(\n 'mobilenetv2_120d', 1.2, depth_multiplier=1.4, fix_stem_head=True, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef fbnetc_100(pretrained=False, **kwargs):\n \"\"\" FBNet-C \"\"\"\n if pretrained:\n # pretrained model trained with non-default BN epsilon\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n model = _gen_fbnetc('fbnetc_100', 1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef spnasnet_100(pretrained=False, **kwargs):\n \"\"\" Single-Path NAS Pixel1\"\"\"\n model = _gen_spnasnet('spnasnet_100', 1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b0(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B0 \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b0', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b1(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B1 \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b1', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b2(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B2 \"\"\"\n # NOTE for train, drop_rate should be 0.3, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b2', channel_multiplier=1.1, depth_multiplier=1.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b2a(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B2 @ 288x288 w/ 1.0 test crop\"\"\"\n # NOTE for train, drop_rate should be 0.3, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b2a', channel_multiplier=1.1, depth_multiplier=1.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b3(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B3 \"\"\"\n # NOTE for train, drop_rate should be 0.3, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b3', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b3a(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B3 @ 320x320 w/ 1.0 test crop-pct \"\"\"\n # NOTE for train, drop_rate should be 0.3, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b3a', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b4(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B4 \"\"\"\n # NOTE for train, drop_rate should be 0.4, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b4', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b5(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B5 \"\"\"\n # NOTE for train, drop_rate should be 0.4, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b5', channel_multiplier=1.6, depth_multiplier=2.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b6(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B6 \"\"\"\n # NOTE for train, drop_rate should be 0.5, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b6', channel_multiplier=1.8, depth_multiplier=2.6, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b7(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B7 \"\"\"\n # NOTE for train, drop_rate should be 0.5, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b7', channel_multiplier=2.0, depth_multiplier=3.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b8(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B8 \"\"\"\n # NOTE for train, drop_rate should be 0.5, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_b8', channel_multiplier=2.2, depth_multiplier=3.6, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_l2(pretrained=False, **kwargs):\n \"\"\" EfficientNet-L2.\"\"\"\n # NOTE for train, drop_rate should be 0.5, drop_path_rate should be 0.2\n model = _gen_efficientnet(\n 'efficientnet_l2', channel_multiplier=4.3, depth_multiplier=5.3, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_es(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Edge Small. \"\"\"\n model = _gen_efficientnet_edge(\n 'efficientnet_es', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n@register_model\ndef efficientnet_es_pruned(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Edge Small Pruned. For more info: https://github.com/DeGirum/pruned-models/releases/tag/efficientnet_v1.0\"\"\"\n model = _gen_efficientnet_edge(\n 'efficientnet_es_pruned', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n@register_model\ndef efficientnet_em(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Edge-Medium. \"\"\"\n model = _gen_efficientnet_edge(\n 'efficientnet_em', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_el(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Edge-Large. \"\"\"\n model = _gen_efficientnet_edge(\n 'efficientnet_el', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)\n return model\n\n@register_model\ndef efficientnet_el_pruned(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Edge-Large pruned. For more info: https://github.com/DeGirum/pruned-models/releases/tag/efficientnet_v1.0\"\"\"\n model = _gen_efficientnet_edge(\n 'efficientnet_el_pruned', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)\n return model\n\n@register_model\ndef efficientnet_cc_b0_4e(pretrained=False, **kwargs):\n \"\"\" EfficientNet-CondConv-B0 w/ 8 Experts \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n model = _gen_efficientnet_condconv(\n 'efficientnet_cc_b0_4e', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_cc_b0_8e(pretrained=False, **kwargs):\n \"\"\" EfficientNet-CondConv-B0 w/ 8 Experts \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n model = _gen_efficientnet_condconv(\n 'efficientnet_cc_b0_8e', channel_multiplier=1.0, depth_multiplier=1.0, experts_multiplier=2,\n pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_cc_b1_8e(pretrained=False, **kwargs):\n \"\"\" EfficientNet-CondConv-B1 w/ 8 Experts \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n model = _gen_efficientnet_condconv(\n 'efficientnet_cc_b1_8e', channel_multiplier=1.0, depth_multiplier=1.1, experts_multiplier=2,\n pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_lite0(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Lite0 \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n model = _gen_efficientnet_lite(\n 'efficientnet_lite0', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_lite1(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Lite1 \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n model = _gen_efficientnet_lite(\n 'efficientnet_lite1', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_lite2(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Lite2 \"\"\"\n # NOTE for train, drop_rate should be 0.3, drop_path_rate should be 0.2\n model = _gen_efficientnet_lite(\n 'efficientnet_lite2', channel_multiplier=1.1, depth_multiplier=1.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_lite3(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Lite3 \"\"\"\n # NOTE for train, drop_rate should be 0.3, drop_path_rate should be 0.2\n model = _gen_efficientnet_lite(\n 'efficientnet_lite3', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_lite4(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Lite4 \"\"\"\n # NOTE for train, drop_rate should be 0.4, drop_path_rate should be 0.2\n model = _gen_efficientnet_lite(\n 'efficientnet_lite4', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b1_pruned(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B1 Pruned. The pruning has been obtained using https://arxiv.org/pdf/2002.08258.pdf \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n variant = 'efficientnet_b1_pruned'\n model = _gen_efficientnet(\n variant, channel_multiplier=1.0, depth_multiplier=1.1, pruned=True, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b2_pruned(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B2 Pruned. The pruning has been obtained using https://arxiv.org/pdf/2002.08258.pdf \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'efficientnet_b2_pruned', channel_multiplier=1.1, depth_multiplier=1.2, pruned=True,\n pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_b3_pruned(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B3 Pruned. The pruning has been obtained using https://arxiv.org/pdf/2002.08258.pdf \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'efficientnet_b3_pruned', channel_multiplier=1.2, depth_multiplier=1.4, pruned=True,\n pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef efficientnet_v2s(pretrained=False, **kwargs):\n \"\"\" EfficientNet-V2 Small. \"\"\"\n model = _gen_efficientnet_v2s(\n 'efficientnet_v2s', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n\n@register_model\ndef tf_efficientnet_b0(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B0. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b0', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b1(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B1. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b1', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b2(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B2. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b2', channel_multiplier=1.1, depth_multiplier=1.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b3(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B3. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b3', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b4(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B4. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b4', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b5(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B5. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b5', channel_multiplier=1.6, depth_multiplier=2.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b6(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B6. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.5\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b6', channel_multiplier=1.8, depth_multiplier=2.6, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b7(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B7. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.5\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b7', channel_multiplier=2.0, depth_multiplier=3.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b8(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B8. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.5\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b8', channel_multiplier=2.2, depth_multiplier=3.6, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b0_ap(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B0 AdvProp. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b0_ap', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b1_ap(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B1 AdvProp. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b1_ap', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b2_ap(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B2 AdvProp. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b2_ap', channel_multiplier=1.1, depth_multiplier=1.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b3_ap(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B3 AdvProp. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b3_ap', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b4_ap(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B4 AdvProp. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b4_ap', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b5_ap(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B5 AdvProp. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b5_ap', channel_multiplier=1.6, depth_multiplier=2.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b6_ap(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B6 AdvProp. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.5\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b6_ap', channel_multiplier=1.8, depth_multiplier=2.6, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b7_ap(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B7 AdvProp. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.5\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b7_ap', channel_multiplier=2.0, depth_multiplier=3.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b8_ap(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B8 AdvProp. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.5\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b8_ap', channel_multiplier=2.2, depth_multiplier=3.6, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b0_ns(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B0 NoisyStudent. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b0_ns', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b1_ns(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B1 NoisyStudent. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b1_ns', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b2_ns(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B2 NoisyStudent. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b2_ns', channel_multiplier=1.1, depth_multiplier=1.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b3_ns(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B3 NoisyStudent. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b3_ns', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b4_ns(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B4 NoisyStudent. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b4_ns', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b5_ns(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B5 NoisyStudent. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b5_ns', channel_multiplier=1.6, depth_multiplier=2.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b6_ns(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B6 NoisyStudent. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.5\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b6_ns', channel_multiplier=1.8, depth_multiplier=2.6, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_b7_ns(pretrained=False, **kwargs):\n \"\"\" EfficientNet-B7 NoisyStudent. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.5\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_b7_ns', channel_multiplier=2.0, depth_multiplier=3.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_l2_ns_475(pretrained=False, **kwargs):\n \"\"\" EfficientNet-L2 NoisyStudent @ 475x475. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.5\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_l2_ns_475', channel_multiplier=4.3, depth_multiplier=5.3, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_l2_ns(pretrained=False, **kwargs):\n \"\"\" EfficientNet-L2 NoisyStudent. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.5\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet(\n 'tf_efficientnet_l2_ns', channel_multiplier=4.3, depth_multiplier=5.3, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_es(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Edge Small. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_edge(\n 'tf_efficientnet_es', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_em(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Edge-Medium. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_edge(\n 'tf_efficientnet_em', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_el(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Edge-Large. Tensorflow compatible variant \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_edge(\n 'tf_efficientnet_el', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_cc_b0_4e(pretrained=False, **kwargs):\n \"\"\" EfficientNet-CondConv-B0 w/ 4 Experts. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_condconv(\n 'tf_efficientnet_cc_b0_4e', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_cc_b0_8e(pretrained=False, **kwargs):\n \"\"\" EfficientNet-CondConv-B0 w/ 8 Experts. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_condconv(\n 'tf_efficientnet_cc_b0_8e', channel_multiplier=1.0, depth_multiplier=1.0, experts_multiplier=2,\n pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_cc_b1_8e(pretrained=False, **kwargs):\n \"\"\" EfficientNet-CondConv-B1 w/ 8 Experts. Tensorflow compatible variant \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_condconv(\n 'tf_efficientnet_cc_b1_8e', channel_multiplier=1.0, depth_multiplier=1.1, experts_multiplier=2,\n pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_lite0(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Lite0 \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_lite(\n 'tf_efficientnet_lite0', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_lite1(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Lite1 \"\"\"\n # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_lite(\n 'tf_efficientnet_lite1', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_lite2(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Lite2 \"\"\"\n # NOTE for train, drop_rate should be 0.3, drop_path_rate should be 0.2\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_lite(\n 'tf_efficientnet_lite2', channel_multiplier=1.1, depth_multiplier=1.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_lite3(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Lite3 \"\"\"\n # NOTE for train, drop_rate should be 0.3, drop_path_rate should be 0.2\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_lite(\n 'tf_efficientnet_lite3', channel_multiplier=1.2, depth_multiplier=1.4, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_efficientnet_lite4(pretrained=False, **kwargs):\n \"\"\" EfficientNet-Lite4 \"\"\"\n # NOTE for train, drop_rate should be 0.4, drop_path_rate should be 0.2\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_efficientnet_lite(\n 'tf_efficientnet_lite4', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mixnet_s(pretrained=False, **kwargs):\n \"\"\"Creates a MixNet Small model.\n \"\"\"\n model = _gen_mixnet_s(\n 'mixnet_s', channel_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mixnet_m(pretrained=False, **kwargs):\n \"\"\"Creates a MixNet Medium model.\n \"\"\"\n model = _gen_mixnet_m(\n 'mixnet_m', channel_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mixnet_l(pretrained=False, **kwargs):\n \"\"\"Creates a MixNet Large model.\n \"\"\"\n model = _gen_mixnet_m(\n 'mixnet_l', channel_multiplier=1.3, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mixnet_xl(pretrained=False, **kwargs):\n \"\"\"Creates a MixNet Extra-Large model.\n Not a paper spec, experimental def by RW w/ depth scaling.\n \"\"\"\n model = _gen_mixnet_m(\n 'mixnet_xl', channel_multiplier=1.6, depth_multiplier=1.2, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef mixnet_xxl(pretrained=False, **kwargs):\n \"\"\"Creates a MixNet Double Extra Large model.\n Not a paper spec, experimental def by RW w/ depth scaling.\n \"\"\"\n model = _gen_mixnet_m(\n 'mixnet_xxl', channel_multiplier=2.4, depth_multiplier=1.3, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_mixnet_s(pretrained=False, **kwargs):\n \"\"\"Creates a MixNet Small model. Tensorflow compatible variant\n \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_mixnet_s(\n 'tf_mixnet_s', channel_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_mixnet_m(pretrained=False, **kwargs):\n \"\"\"Creates a MixNet Medium model. Tensorflow compatible variant\n \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_mixnet_m(\n 'tf_mixnet_m', channel_multiplier=1.0, pretrained=pretrained, **kwargs)\n return model\n\n\n@register_model\ndef tf_mixnet_l(pretrained=False, **kwargs):\n \"\"\"Creates a MixNet Large model. Tensorflow compatible variant\n \"\"\"\n kwargs['bn_eps'] = BN_EPS_TF_DEFAULT\n kwargs['pad_type'] = 'same'\n model = _gen_mixnet_m(\n 'tf_mixnet_l', channel_multiplier=1.3, pretrained=pretrained, **kwargs)\n return model\n" ]
[ [ "torch.nn.functional.dropout", "torch.nn.Dropout", "torch.nn.Sequential" ] ]
nagnath001/ga-learner-dsmp-repo
[ "7035fd2ebe967182a44011dde59cb8ae411badb6" ]
[ "Challenges-in-Machine-Learning/code.py" ]
[ "# --------------\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n# Code starts here\ndf=pd.read_csv(path)\n#print(df.head())\n#print(df.info)\ndf['INCOME'] = df['INCOME'].str.replace('$','')\ndf['INCOME'] = df['INCOME'].str.replace(',','')\ndf['HOME_VAL'] = df['HOME_VAL'].str.replace('$','')\ndf['HOME_VAL'] = df['HOME_VAL'].str.replace(',','')\ndf['BLUEBOOK'] = df['BLUEBOOK'].str.replace('$','')\ndf['BLUEBOOK'] = df['BLUEBOOK'].str.replace(',','')\ndf['OLDCLAIM']=df['OLDCLAIM'].str.replace('$','')\ndf['OLDCLAIM']=df['OLDCLAIM'].str.replace(',','')\ndf['CLM_AMT']=df['CLM_AMT'].str.replace('$','')\ndf['CLM_AMT']=df['CLM_AMT'].str.replace(',','')\nX=df.drop('CLAIM_FLAG',1)\ny=df['CLAIM_FLAG']\nX_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.3, random_state=6)\n\n\n\n# Code ends here\n\n\n# --------------\n# Code starts here\n\nX_train[\"INCOME\"]=X_train[\"INCOME\"].astype(float)\nX_train[\"HOME_VAL\"]=X_train[\"HOME_VAL\"].astype(float)\nX_train[\"BLUEBOOK\"]=X_train[\"BLUEBOOK\"].astype(float)\nX_train[\"OLDCLAIM\"]=X_train[\"OLDCLAIM\"].astype(float)\nX_train[\"CLM_AMT\"]=X_train[\"CLM_AMT\"].astype(float)\nX_test[\"INCOME\"]=X_test[\"INCOME\"].astype(float)\nX_test[\"HOME_VAL\"]=X_test[\"HOME_VAL\"].astype(float)\nX_test[\"BLUEBOOK\"]=X_test[\"BLUEBOOK\"].astype(float)\nX_test[\"OLDCLAIM\"]=X_test[\"OLDCLAIM\"].astype(float)\nX_test[\"CLM_AMT\"]=X_test[\"CLM_AMT\"].astype(float)\nprint(X_train.isnull())\nprint(X_test.isnull())\nprint(X_train.isnull().sum())\nprint(X_test.isnull().sum())\n\n# Code ends here\n\n\n# --------------\n# Code starts here\nX_train=X_train.dropna(subset = ['YOJ', 'OCCUPATION'])\nX_test=X_test.dropna(subset = ['YOJ', 'OCCUPATION'])\ny_train=y_train[X_train.index]\ny_test=y_test[X_test.index]\nX_train[\"AGE\"].fillna(X_train[\"AGE\"].mean(), inplace=True)\nX_train[\"CAR_AGE\"].fillna(X_train[\"CAR_AGE\"].mean(), inplace=True)\nX_train[\"INCOME\"].fillna(X_train[\"INCOME\"].mean(), inplace=True)\nX_train[\"HOME_VAL\"].fillna(X_train[\"HOME_VAL\"].mean(), inplace=True)\nX_test[\"AGE\"].fillna(X_train[\"AGE\"].mean(), inplace=True)\nX_test[\"CAR_AGE\"].fillna(X_train[\"CAR_AGE\"].mean(), inplace=True)\nX_test[\"INCOME\"].fillna(X_train[\"INCOME\"].mean(), inplace=True)\nX_test[\"HOME_VAL\"].fillna(X_train[\"HOME_VAL\"].mean(), inplace=True)\n\n# Code ends here\n\n\n# --------------\nfrom sklearn.preprocessing import LabelEncoder\ncolumns = [\"PARENT1\",\"MSTATUS\",\"GENDER\",\"EDUCATION\",\"OCCUPATION\",\"CAR_USE\",\"CAR_TYPE\",\"RED_CAR\",\"REVOKED\"]\n\n# Code starts here\nle = LabelEncoder()\nfor col in columns:\n X_train[col]=le.fit_transform(X_train[col].astype(str))\nfor col in columns:\n X_test[col]=le.fit_transform(X_test[col].astype(str))\n\n\n\n\n\n# --------------\nfrom sklearn.metrics import precision_score \nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\n#code starts here \nmodel=LogisticRegression(random_state=6)\nmodel.fit(X_train,y_train)\ny_pred=model.predict(X_test)\nscore=accuracy_score(y_test,y_pred)\nprint(\"accuracy score=\",score)\nprecision=precision_score(y_test,y_pred)\nprint(\"precision=\",precision)\n\n\n# Code ends here\n\n\n# --------------\nfrom sklearn.preprocessing import StandardScaler\nfrom imblearn.over_sampling import SMOTE\n\n# code starts here\nsmote=SMOTE(random_state=9)\nX_train,y_train = smote.fit_sample(X_train,y_train)\nscaler=StandardScaler()\nX_train=scaler.fit_transform(X_train)\nX_test=scaler.transform(X_test)\n# Code ends here\n\n\n# --------------\n# Code Starts here\n\nmodel=LogisticRegression()\nmodel.fit(X_train,y_train)\ny_pred=model.predict(X_test)\nscore=accuracy_score(y_test,y_pred)\nprint(\"accuracy=\",score)\n\n\n\n\n\n\n# Code ends here\n\n\n" ]
[ [ "pandas.read_csv", "sklearn.metrics.accuracy_score", "sklearn.metrics.precision_score", "sklearn.preprocessing.LabelEncoder", "sklearn.linear_model.LogisticRegression", "sklearn.preprocessing.StandardScaler", "sklearn.model_selection.train_test_split" ] ]
theycallmepeter/pytorch3d_PBR
[ "bc83c23969ff7843fc05d2da001952b368926174" ]
[ "pytorch3d/io/experimental_gltf_io.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\r\n# All rights reserved.\r\n#\r\n# This source code is licensed under the BSD-style license found in the\r\n# LICENSE file in the root directory of this source tree.\r\n\r\n\r\n\"\"\"\r\nThis module implements loading meshes from glTF 2 assets stored in a\r\nGLB container file or a glTF JSON file with embedded binary data.\r\nIt is experimental.\r\n\r\nThe module provides a MeshFormatInterpreter called\r\nMeshGlbFormat which must be used explicitly.\r\ne.g.\r\n\r\n.. code-block:: python\r\n\r\n from pytorch3d.io import IO\r\n from pytorch3d.io.experimental_gltf_io import MeshGlbFormat\r\n\r\n io = IO()\r\n io.register_meshes_format(MeshGlbFormat())\r\n io.load_mesh(...)\r\n\r\nThis implementation is quite restricted in what it supports.\r\n\r\n - It does not try to validate the input against the standard.\r\n - It loads the default scene only.\r\n - Only triangulated geometry is supported.\r\n - The geometry of all meshes of the entire scene is aggregated into a single mesh.\r\n Use `load_meshes()` instead to get un-aggregated (but transformed) ones.\r\n - All material properties are ignored except for either vertex color, baseColorTexture\r\n or baseColorFactor. If available, one of these (in this order) is exclusively\r\n used which does not match the semantics of the standard.\r\n\"\"\"\r\n\r\nimport json\r\nimport struct\r\nimport warnings\r\nfrom base64 import b64decode\r\nfrom collections import deque\r\nfrom enum import IntEnum\r\nfrom io import BytesIO\r\nfrom typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union, cast\r\n\r\nimport numpy as np\r\nimport torch\r\nfrom iopath.common.file_io import PathManager\r\nfrom PIL import Image\r\nfrom pytorch3d.io.utils import PathOrStr, _open_file\r\nfrom pytorch3d.renderer.mesh import TexturesBase, TexturesUV, TexturesVertex\r\nfrom pytorch3d.structures import Meshes, join_meshes_as_scene\r\nfrom pytorch3d.transforms import Transform3d, quaternion_to_matrix\r\n\r\nfrom .pluggable_formats import MeshFormatInterpreter, endswith\r\n\r\n\r\n_GLTF_MAGIC = 0x46546C67\r\n_JSON_CHUNK_TYPE = 0x4E4F534A\r\n_BINARY_CHUNK_TYPE = 0x004E4942\r\n_DATA_URI_PREFIX = \"data:application/octet-stream;base64,\"\r\n\r\n\r\nclass _PrimitiveMode(IntEnum):\r\n POINTS = 0\r\n LINES = 1\r\n LINE_LOOP = 2\r\n LINE_STRIP = 3\r\n TRIANGLES = 4\r\n TRIANGLE_STRIP = 5\r\n TRIANGLE_FAN = 6\r\n\r\n\r\nclass _ComponentType(IntEnum):\r\n BYTE = 5120\r\n UNSIGNED_BYTE = 5121\r\n SHORT = 5122\r\n UNSIGNED_SHORT = 5123\r\n UNSIGNED_INT = 5125\r\n FLOAT = 5126\r\n\r\n\r\n_ITEM_TYPES: Dict[int, Any] = {\r\n 5120: np.int8,\r\n 5121: np.uint8,\r\n 5122: np.int16,\r\n 5123: np.uint16,\r\n 5125: np.uint32,\r\n 5126: np.float32,\r\n}\r\n\r\n\r\n_ElementShape = Union[Tuple[int], Tuple[int, int]]\r\n_ELEMENT_SHAPES: Dict[str, _ElementShape] = {\r\n \"SCALAR\": (1,),\r\n \"VEC2\": (2,),\r\n \"VEC3\": (3,),\r\n \"VEC4\": (4,),\r\n \"MAT2\": (2, 2),\r\n \"MAT3\": (3, 3),\r\n \"MAT4\": (4, 4),\r\n}\r\n\r\n\r\ndef _read_header(stream: BinaryIO) -> Optional[Tuple[int, int]]:\r\n header = stream.read(12)\r\n magic, version, length = struct.unpack(\"<III\", header)\r\n\r\n if magic != _GLTF_MAGIC:\r\n return None\r\n\r\n return version, length\r\n\r\n\r\ndef _read_chunks(\r\n stream: BinaryIO, length: int\r\n) -> Optional[Tuple[Dict[str, Any], np.ndarray]]:\r\n \"\"\"\r\n Get the json header and the binary data from a\r\n GLB file.\r\n \"\"\"\r\n json_data = None\r\n binary_data = None\r\n\r\n while stream.tell() < length:\r\n chunk_header = stream.read(8)\r\n chunk_length, chunk_type = struct.unpack(\"<II\", chunk_header)\r\n chunk_data = stream.read(chunk_length)\r\n if chunk_type == _JSON_CHUNK_TYPE:\r\n json_data = json.loads(chunk_data)\r\n elif chunk_type == _BINARY_CHUNK_TYPE:\r\n binary_data = chunk_data\r\n else:\r\n warnings.warn(\"Unsupported chunk type\")\r\n return None\r\n\r\n if json_data is None:\r\n raise ValueError(\"Missing json header\")\r\n\r\n if binary_data is not None:\r\n binary_data = np.frombuffer(binary_data, dtype=np.uint8)\r\n\r\n return json_data, binary_data\r\n\r\n\r\ndef _make_node_transform(node: Dict[str, Any]) -> Transform3d:\r\n \"\"\"\r\n Convert a transform from the json data in to a PyTorch3D\r\n Transform3d format.\r\n \"\"\"\r\n array = node.get(\"matrix\")\r\n if array is not None: # Stored in column-major order\r\n M = np.array(array, dtype=np.float32).reshape(4, 4, order=\"F\")\r\n return Transform3d(matrix=torch.from_numpy(M))\r\n\r\n out = Transform3d()\r\n\r\n # Given some of (scale/rotation/translation), we do them in that order to\r\n # get points in to the world space.\r\n # See https://github.com/KhronosGroup/glTF/issues/743 .\r\n\r\n array = node.get(\"scale\", None)\r\n if array is not None:\r\n scale_vector = torch.FloatTensor(array)\r\n out = out.scale(scale_vector[None])\r\n\r\n # Rotation quaternion (x, y, z, w) where w is the scalar\r\n array = node.get(\"rotation\", None)\r\n if array is not None:\r\n x, y, z, w = array\r\n # We negate w. This is equivalent to inverting the rotation.\r\n # This is needed as quaternion_to_matrix makes a matrix which\r\n # operates on column vectors, whereas Transform3d wants a\r\n # matrix which operates on row vectors.\r\n rotation_quaternion = torch.FloatTensor([-w, x, y, z])\r\n rotation_matrix = quaternion_to_matrix(rotation_quaternion)\r\n out = out.rotate(R=rotation_matrix)\r\n\r\n array = node.get(\"translation\", None)\r\n if array is not None:\r\n translation_vector = torch.FloatTensor(array)\r\n out = out.translate(x=translation_vector[None])\r\n\r\n return out\r\n\r\n\r\nclass _GLTFLoader:\r\n def __init__(self, stream: BinaryIO) -> None:\r\n self._json_data = None\r\n # Map from buffer index to (decoded) binary data\r\n self._binary_data = {}\r\n\r\n version_and_length = _read_header(stream)\r\n if version_and_length is None: # GLTF\r\n stream.seek(0)\r\n json_data = json.load(stream)\r\n else: # GLB\r\n version, length = version_and_length\r\n if version != 2:\r\n warnings.warn(\"Unsupported version\")\r\n return\r\n json_and_binary_data = _read_chunks(stream, length)\r\n if json_and_binary_data is None:\r\n raise ValueError(\"Data not found\")\r\n json_data, binary_data = json_and_binary_data\r\n self._binary_data[0] = binary_data\r\n\r\n self._json_data = json_data\r\n self._accessors = json_data.get(\"accessors\", [])\r\n self._buffer_views = json_data.get(\"bufferViews\", [])\r\n self._buffers = json_data.get(\"buffers\", [])\r\n self._texture_map_images = {}\r\n\r\n def _access_image(self, image_index: int) -> np.ndarray:\r\n \"\"\"\r\n Get the data for an image from the file. This is only called\r\n by _get_texture_map_image which caches it.\r\n \"\"\"\r\n\r\n image_json = self._json_data[\"images\"][image_index]\r\n buffer_view = self._buffer_views[image_json[\"bufferView\"]]\r\n if \"byteStride\" in buffer_view:\r\n raise NotImplementedError(\"strided buffer views\")\r\n\r\n length = buffer_view[\"byteLength\"]\r\n offset = buffer_view.get(\"byteOffset\", 0)\r\n\r\n binary_data = self.get_binary_data(buffer_view[\"buffer\"])\r\n\r\n bytesio = BytesIO(binary_data[offset : offset + length].tobytes())\r\n with Image.open(bytesio) as f:\r\n array = np.array(f)\r\n if array.dtype == np.uint8:\r\n return array.astype(np.float32) / 255.0\r\n else:\r\n return array\r\n\r\n def _get_texture_map_image(self, image_index: int) -> torch.Tensor:\r\n \"\"\"\r\n Return a texture map image as a torch tensor.\r\n Calling this function repeatedly with the same arguments returns\r\n the very same tensor, this allows a memory optimization to happen\r\n later in TexturesUV.join_scene.\r\n Any alpha channel is ignored.\r\n \"\"\"\r\n im = self._texture_map_images.get(image_index)\r\n if im is not None:\r\n return im\r\n\r\n im = torch.from_numpy(self._access_image(image_index))[:, :, :3]\r\n self._texture_map_images[image_index] = im\r\n return im\r\n\r\n def _access_data(self, accessor_index: int) -> np.ndarray:\r\n \"\"\"\r\n Get the raw data from an accessor as a numpy array.\r\n \"\"\"\r\n accessor = self._accessors[accessor_index]\r\n\r\n buffer_view_index = accessor.get(\"bufferView\")\r\n # Undefined buffer view (all zeros) are not (yet) supported\r\n if buffer_view_index is None:\r\n raise NotImplementedError(\"Undefined buffer view\")\r\n\r\n accessor_byte_offset = accessor.get(\"byteOffset\", 0)\r\n component_type = accessor[\"componentType\"]\r\n element_count = accessor[\"count\"]\r\n element_type = accessor[\"type\"]\r\n\r\n # Sparse accessors are not (yet) supported\r\n if accessor.get(\"sparse\") is not None:\r\n raise NotImplementedError(\"Sparse Accessors\")\r\n\r\n buffer_view = self._buffer_views[buffer_view_index]\r\n buffer_index = buffer_view[\"buffer\"]\r\n buffer_byte_length = buffer_view[\"byteLength\"]\r\n element_byte_offset = buffer_view.get(\"byteOffset\", 0)\r\n element_byte_stride = buffer_view.get(\"byteStride\", 0)\r\n if element_byte_stride != 0 and element_byte_stride < 4:\r\n raise ValueError(\"Stride is too small.\")\r\n if element_byte_stride > 252:\r\n raise ValueError(\"Stride is too big.\")\r\n\r\n element_shape = _ELEMENT_SHAPES[element_type]\r\n item_type = _ITEM_TYPES[component_type]\r\n item_dtype = np.dtype(item_type)\r\n item_count = np.prod(element_shape)\r\n item_size = item_dtype.itemsize\r\n size = element_count * item_count * item_size\r\n if size > buffer_byte_length:\r\n raise ValueError(\"Buffer did not have enough data for the accessor\")\r\n\r\n buffer_ = self._buffers[buffer_index]\r\n binary_data = self.get_binary_data(buffer_index)\r\n if len(binary_data) < buffer_[\"byteLength\"]:\r\n raise ValueError(\"Not enough binary data for the buffer\")\r\n\r\n if element_byte_stride == 0:\r\n element_byte_stride = item_size * item_count\r\n # The same buffer can store interleaved elements\r\n if element_byte_stride < item_size * item_count:\r\n raise ValueError(\"Items should not overlap\")\r\n\r\n dtype = np.dtype(\r\n {\r\n \"names\": [\"element\"],\r\n \"formats\": [str(element_shape) + item_dtype.str],\r\n \"offsets\": [0],\r\n \"itemsize\": element_byte_stride,\r\n }\r\n )\r\n\r\n byte_offset = accessor_byte_offset + element_byte_offset\r\n if byte_offset % item_size != 0:\r\n raise ValueError(\"Misaligned data\")\r\n byte_length = element_count * element_byte_stride\r\n buffer_view = binary_data[byte_offset : byte_offset + byte_length].view(dtype)[\r\n \"element\"\r\n ]\r\n\r\n # Convert matrix data from column-major (OpenGL) to row-major order\r\n if element_type in (\"MAT2\", \"MAT3\", \"MAT4\"):\r\n buffer_view = np.transpose(buffer_view, (0, 2, 1))\r\n\r\n return buffer_view\r\n\r\n def _get_primitive_attribute(\r\n self, primitive_attributes: Dict[str, Any], key: str, dtype\r\n ) -> Optional[np.ndarray]:\r\n accessor_index = primitive_attributes.get(key)\r\n if accessor_index is None:\r\n return None\r\n primitive_attribute = self._access_data(accessor_index)\r\n if key == \"JOINTS_0\":\r\n pass\r\n elif dtype == np.uint8:\r\n primitive_attribute /= 255.0\r\n elif dtype == np.uint16:\r\n primitive_attribute /= 65535.0\r\n else:\r\n if dtype != np.float32:\r\n raise ValueError(\"Unexpected data type\")\r\n primitive_attribute = primitive_attribute.astype(dtype)\r\n return primitive_attribute\r\n\r\n def get_binary_data(self, buffer_index: int):\r\n \"\"\"\r\n Get the binary data from a buffer as a 1D numpy array of bytes.\r\n This is implemented for explicit uri data buffers or the main GLB data\r\n segment.\r\n \"\"\"\r\n buffer_ = self._buffers[buffer_index]\r\n binary_data = self._binary_data.get(buffer_index)\r\n if binary_data is None: # Lazily decode binary data\r\n uri = buffer_.get(\"uri\")\r\n if not uri.startswith(_DATA_URI_PREFIX):\r\n raise NotImplementedError(\"Unexpected URI type\")\r\n binary_data = b64decode(uri[len(_DATA_URI_PREFIX) :])\r\n binary_data = np.frombuffer(binary_data, dtype=np.uint8)\r\n self._binary_data[buffer_index] = binary_data\r\n return binary_data\r\n\r\n def get_texture_for_mesh(\r\n self, primitive: Dict[str, Any], indices: torch.Tensor\r\n ) -> Optional[TexturesBase]:\r\n \"\"\"\r\n Get the texture object representing the given mesh primitive.\r\n\r\n Args:\r\n primitive: the mesh primitive being loaded.\r\n indices: the face indices of the mesh\r\n \"\"\"\r\n attributes = primitive[\"attributes\"]\r\n vertex_colors = self._get_primitive_attribute(attributes, \"COLOR_0\", np.float32)\r\n if vertex_colors is not None:\r\n return TexturesVertex(torch.from_numpy(vertex_colors))\r\n\r\n vertex_texcoords_0 = self._get_primitive_attribute(\r\n attributes, \"TEXCOORD_0\", np.float32\r\n )\r\n if vertex_texcoords_0 is not None:\r\n verts_uvs = torch.from_numpy(vertex_texcoords_0)\r\n verts_uvs[:, 1] = 1 - verts_uvs[:, -1]\r\n faces_uvs = indices\r\n material_index = primitive.get(\"material\", 0)\r\n material = self._json_data[\"materials\"][material_index]\r\n material_roughness = material[\"pbrMetallicRoughness\"]\r\n if \"baseColorTexture\" in material_roughness:\r\n texture_index = material_roughness[\"baseColorTexture\"][\"index\"]\r\n texture_json = self._json_data[\"textures\"][texture_index]\r\n # Todo - include baseColorFactor when also given\r\n # Todo - look at the sampler\r\n image_index = texture_json[\"source\"]\r\n map = self._get_texture_map_image(image_index)\r\n elif \"baseColorFactor\" in material_roughness:\r\n # Constant color?\r\n map = torch.FloatTensor(material_roughness[\"baseColorFactor\"])[\r\n None, None, :3\r\n ]\r\n texture = TexturesUV(\r\n # pyre-fixme[61]: `map` may not be initialized here.\r\n maps=[map], # alpha channel ignored\r\n faces_uvs=[faces_uvs],\r\n verts_uvs=[verts_uvs],\r\n )\r\n return texture\r\n\r\n return None\r\n\r\n def load(self, include_textures: bool) -> List[Tuple[Optional[str], Meshes]]:\r\n \"\"\"\r\n Attempt to load all the meshes making up the default scene from\r\n the file as a list of possibly-named Meshes objects.\r\n\r\n Args:\r\n include_textures: Whether to try loading textures.\r\n\r\n Returns:\r\n Meshes object containing one mesh.\r\n \"\"\"\r\n if self._json_data is None:\r\n raise ValueError(\"Initialization problem\")\r\n\r\n # This loads the default scene from the file.\r\n # This is usually the only one.\r\n # It is possible to have multiple scenes, in which case\r\n # you could choose another here instead of taking the default.\r\n scene_index = self._json_data.get(\"scene\")\r\n\r\n if scene_index is None:\r\n raise ValueError(\"Default scene is not specified.\")\r\n\r\n scene = self._json_data[\"scenes\"][scene_index]\r\n nodes = self._json_data.get(\"nodes\", [])\r\n meshes = self._json_data.get(\"meshes\", [])\r\n root_node_indices = scene[\"nodes\"]\r\n\r\n mesh_transform = Transform3d()\r\n names_meshes_list: List[Tuple[Optional[str], Meshes]] = []\r\n\r\n # Keep track and apply the transform of the scene node to mesh vertices\r\n Q = deque([(Transform3d(), node_index) for node_index in root_node_indices])\r\n\r\n while Q:\r\n parent_transform, current_node_index = Q.popleft()\r\n\r\n current_node = nodes[current_node_index]\r\n\r\n transform = _make_node_transform(current_node)\r\n current_transform = transform.compose(parent_transform)\r\n\r\n if \"mesh\" in current_node:\r\n mesh_index = current_node[\"mesh\"]\r\n mesh = meshes[mesh_index]\r\n mesh_name = mesh.get(\"name\", None)\r\n mesh_transform = current_transform\r\n\r\n for primitive in mesh[\"primitives\"]:\r\n attributes = primitive[\"attributes\"]\r\n accessor_index = attributes[\"POSITION\"]\r\n positions = torch.from_numpy(\r\n self._access_data(accessor_index).copy()\r\n )\r\n positions = mesh_transform.transform_points(positions)\r\n\r\n mode = primitive.get(\"mode\", _PrimitiveMode.TRIANGLES)\r\n if mode != _PrimitiveMode.TRIANGLES:\r\n raise NotImplementedError(\"Non triangular meshes\")\r\n\r\n if \"indices\" in primitive:\r\n accessor_index = primitive[\"indices\"]\r\n indices = self._access_data(accessor_index).astype(np.int64)\r\n else:\r\n indices = np.arange(0, len(positions), dtype=np.int64)\r\n indices = torch.from_numpy(indices.reshape(-1, 3))\r\n\r\n texture = None\r\n if include_textures:\r\n texture = self.get_texture_for_mesh(primitive, indices)\r\n\r\n mesh_obj = Meshes(\r\n verts=[positions], faces=[indices], textures=texture\r\n )\r\n names_meshes_list.append((mesh_name, mesh_obj))\r\n\r\n if \"children\" in current_node:\r\n children_node_indices = current_node[\"children\"]\r\n Q.extend(\r\n [\r\n (current_transform, node_index)\r\n for node_index in children_node_indices\r\n ]\r\n )\r\n\r\n return names_meshes_list\r\n\r\n\r\ndef load_meshes(\r\n path: PathOrStr,\r\n path_manager: PathManager,\r\n include_textures: bool = True,\r\n) -> List[Tuple[Optional[str], Meshes]]:\r\n \"\"\"\r\n Loads all the meshes from the default scene in the given GLB file.\r\n and returns them separately.\r\n\r\n Args:\r\n path: path to read from\r\n path_manager: PathManager object for interpreting the path\r\n include_textures: whether to load textures\r\n\r\n Returns:\r\n List of (name, mesh) pairs, where the name is the optional name property\r\n from the GLB file, or None if it is absent, and the mesh is a Meshes\r\n object containing one mesh.\r\n \"\"\"\r\n with _open_file(path, path_manager, \"rb\") as f:\r\n loader = _GLTFLoader(cast(BinaryIO, f))\r\n names_meshes_list = loader.load(include_textures=include_textures)\r\n return names_meshes_list\r\n\r\n\r\nclass MeshGlbFormat(MeshFormatInterpreter):\r\n \"\"\"\r\n Implements loading meshes from glTF 2 assets stored in a\r\n GLB container file or a glTF JSON file with embedded binary data.\r\n\r\n This implementation is quite restricted in what it supports.\r\n\r\n - It does not try to validate the input against the standard.\r\n - It loads the default scene only.\r\n - Only triangulated geometry is supported.\r\n - The geometry of all meshes of the entire scene is aggregated into a single mesh.\r\n Use `load_meshes()` instead to get un-aggregated (but transformed) ones.\r\n - All material properties are ignored except for either vertex color, baseColorTexture\r\n or baseColorFactor. If available, one of these (in this order) is exclusively\r\n used which does not match the semantics of the standard.\r\n \"\"\"\r\n\r\n def __init__(self) -> None:\r\n self.known_suffixes = (\".glb\",)\r\n\r\n def read(\r\n self,\r\n path: PathOrStr,\r\n include_textures: bool,\r\n device,\r\n path_manager: PathManager,\r\n **kwargs,\r\n ) -> Optional[Meshes]:\r\n if not endswith(path, self.known_suffixes):\r\n return None\r\n\r\n names_meshes_list = load_meshes(\r\n path=path,\r\n path_manager=path_manager,\r\n include_textures=include_textures,\r\n )\r\n\r\n meshes_list = [mesh for name, mesh in names_meshes_list]\r\n mesh = join_meshes_as_scene(meshes_list)\r\n return mesh.to(device)\r\n\r\n def save(\r\n self,\r\n data: Meshes,\r\n path: PathOrStr,\r\n path_manager: PathManager,\r\n binary: Optional[bool],\r\n **kwargs,\r\n ) -> bool:\r\n return False\r\n" ]
[ [ "torch.FloatTensor", "numpy.transpose", "numpy.dtype", "torch.from_numpy", "numpy.prod", "numpy.array", "numpy.frombuffer" ] ]
ArturoDeza/NeuroFovea_PyTorch
[ "cf8f3e41ccc08b9f631f5f59776c01f92d52e944" ]
[ "Metamer_Transform.py" ]
[ "import argparse\nfrom pathlib import Path\n\nimport torch\nimport torch.nn as nn\nfrom PIL import Image\nfrom torchvision import transforms\nfrom torchvision.utils import save_image\nimport numpy as np\nimport math\nimport time\n\nimport net\nfrom function import adaptive_instance_normalization, coral\n\n# Example code:\n# python Metamer_Transform.py --image 4751.png --output output_Stimuli\n\nparser = argparse.ArgumentParser()\n# Basic options\nparser.add_argument('--image', type=str, help='File path to the content image')\nparser.add_argument('--image_dir', type=str, help='Directory path to a batch of content images')\nparser.add_argument('--vgg', type=str, default='models/vgg_normalised.pth')\nparser.add_argument('--decoder', type=str, default='models/decoder-content-similar.pth') # Notice that this decoder is different than the classically used \"decoder.pth\"!\n\n# Additional options\nparser.add_argument('--image_size', type=int, default=512, help='New (minimum) size for the content image, keeping the original size if set to 0')\nparser.add_argument('--crop', action='store_true', help='do center crop to create squared image')\nparser.add_argument('--save_ext', default='.png', help='The extension name of the output image')\nparser.add_argument('--output', type=str, default='output', help='Directory to save the output image(s)')\nparser.add_argument('--scale',type=str,default='0.4',help='Rate of growth of the Log-Polar Receptive Fields')\nparser.add_argument('--verbose',type=int,default=0,help='Print several hyper-parameters as we run the rendering scheme. Default should be 0, should only be set to 1 for debugging.')\nparser.add_argument('--reference',type=int,default=0,help='Compute the reference image')\n\nargs = parser.parse_args()\n\n# List of potentially different rate of growth of receptive fields\n# assuming a center fixation.\nscale_in = ['0.25','0.3','0.4','0.5','0.6','0.7']\nscale_out = [377,301,187,126,103,91]\n\nPooling_Region_Map = dict(zip(scale_in,scale_out))\n\nverb = args.verbose\n\nresize_output = transforms.Compose([transforms.Resize((256,256))])\nto_pil_image = transforms.ToPILImage()\nto_tensor = transforms.ToTensor()\n\n\n#function that loads receptive fields:\ndef load_receptive_fields():\n d = 1.281 # a value that was fitted via psychophysical experiments assuming 26 deg of visual angle maps to 512 pixels on a screen.\n mask_total = torch.zeros(Pooling_Region_Map[args.scale],64,64)\n alpha_matrix = torch.zeros(Pooling_Region_Map[args.scale])\n for i in range(Pooling_Region_Map[args.scale]):\n i_str = str(i)\n #mask_str = './Receptive_Fields/MetaWindows_clean_s0.4/' + i_str + '.png'\n mask_str = './Receptive_Fields/MetaWindows_clean_s' + args.scale + '/' + i_str + '.png'\n mask_temp = mask_tf(Image.open(str(mask_str)))\n mask_total[i,:,:] = mask_temp\n mask_regular = mask_regular_tf(Image.open(str(mask_str)))\n mask_size = torch.sum(torch.sum(mask_regular>0.5))\n recep_size = np.sqrt(mask_size/3.14)*26.0/512.0\n if i == 0:\n alpha_matrix[i] = 0\n else:\n alpha_matrix[i] = -1 + 2.0 / (1.0+math.exp(-recep_size*d))\n if verb == 1:\n print(alpha_matrix[i])\n return mask_total, alpha_matrix\n\n\ndef test_transform(size, crop):\n transform_list = []\n if size != 0:\n transform_list.append(transforms.Resize(size))\n if crop:\n transform_list.append(transforms.CenterCrop(size))\n transform_list.append(transforms.ToTensor())\n transform = transforms.Compose(transform_list)\n return transform\n\ndef mask_transform():\n transform = transforms.Compose([transforms.Resize(64),transforms.Grayscale(1),transforms.ToTensor()])\n return transform\n\ndef mask_transform_regular():\n transform = transforms.Compose([transforms.Resize(512),transforms.Grayscale(1),transforms.ToTensor()])\n return transform\n\ndef tile(a, dim, n_tile):\n init_dim = a.size(dim)\n repeat_idx = [1] * a.dim()\n repeat_idx[dim] = n_tile\n a = a.repeat(*(repeat_idx))\n order_index = torch.LongTensor(np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)]))\n return torch.index_select(a, dim, order_index)\n\ndef foveated_style_transfer(vgg,decoder, content, mask_total, alpha_matrix, reference):\n noise = torch.randn(3,512,512)\n noise = coral(noise,content)\n # Move images to GPU:\n style = content.to(device).unsqueeze(0) # Remember we are doing something like \"Auto-Style Transfer\"\n content = content.to(device).unsqueeze(0)\n noise = noise.to(device).unsqueeze(0)\n # Create Empty Foveated Feature Vector to which we will allocate the latent crowded feature vectors:\n foveated_f = torch.zeros(1,512,64,64).to(device)\n # Create Content Feature Vector (post VGG):\n content_f = vgg(content)\n # Create Style Feature Vector (post VGG):\n style_f = vgg(style)\n # Create Noise Feature Vector (post VGG):\n noise_f = vgg(noise)\n # assume alpha_i = 0.5\n if reference == 1:\n return decoder(content_f)\n else:\n for i in range(Pooling_Region_Map[args.scale]): # Loop over all the receptive fields (pooling regions)\n alpha_i = alpha_matrix[i]\n mask = mask_total[i,:,:]\n mask = mask.unsqueeze(0)\n mask = tile(mask,0,512)\n mask_binary = mask>0.001\n if verb == 1:\n print(np.shape(content_f))\n print(np.shape(mask_binary[0,:,:]))\n content_f_mask = content_f[:,:,mask_binary[0,:,:]] # 0 was 0th prefix before\n style_f_mask = style_f[:,:,mask_binary[0,:,:]]\n noise_f_mask = noise_f[:,:,mask_binary[0,:,:]]\n #\n if verb == 1:\n print(np.shape(noise_f_mask.unsqueeze(3)))\n print(np.shape(style_f_mask.unsqueeze(3)))\n content_f_mask = content_f_mask.unsqueeze(3)\n noise_f_mask = noise_f_mask.unsqueeze(3)\n style_f_mask = style_f_mask.unsqueeze(3)\n if verb == 1:\n print(np.shape(content_f_mask))\n # Perform the Crowding Operation and Localized Auto Style-Transfer\n texture_f_mask = adaptive_instance_normalization(noise_f_mask,style_f_mask)\n alpha_mixture = (1-alpha_i)*content_f_mask + (alpha_i)*texture_f_mask\n if verb == 1:\n print(np.shape(alpha_mixture))\n foveated_f[:,:,mask_binary[0,:,:]] = alpha_mixture.squeeze(3)\n # Run the now foveated image in the latent space through the decoder to render the metamer\n return decoder(foveated_f)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\noutput_dir = Path(args.output)\noutput_dir.mkdir(exist_ok=True, parents=True)\n\n# Either --image or --imageDir should be given.\nassert (args.image or args.image_dir)\nif args.image:\n image_paths = [Path(args.image)]\nelse:\n image_dir = Path(args.image_dir)\n image_paths = [f for f in image_dir.glob('*')]\n\ndecoder = net.decoder\nvgg = net.vgg\n\ndecoder.eval()\nvgg.eval()\n\ndecoder.load_state_dict(torch.load(args.decoder))\nvgg.load_state_dict(torch.load(args.vgg))\nvgg = nn.Sequential(*list(vgg.children())[:31])\n\nreference = args.reference\n\nvgg.to(device)\ndecoder.to(device)\n\nimage_tf = test_transform(args.image_size, args.crop)\n\n# Define Masked Transforms (for localized style transfer that is the basis \n# of the foveated style transform operation for each pooling region\nmask_tf = mask_transform()\nmask_regular_tf = mask_transform_regular()\n\nif verb == 1:\n print(image_paths)\n print(image_paths[0])\n print(image_paths[0].stem)\n\nprint(len(image_paths))\n\nwith torch.no_grad():\n mask_total, alpha_matrix = load_receptive_fields()\n for z in range(len(image_paths)):\n image_path = image_paths[z]\n image = image_tf(Image.open(str(image_path)).convert('RGB'))\n start_time = time.time()\n output = foveated_style_transfer(vgg,decoder,image,mask_total,alpha_matrix,reference)\n output = output.cpu()\n output2 = to_pil_image(torch.clamp(output.squeeze(0),0,1))\n output = torch.clamp(to_tensor(resize_output(output2)),0,1)\n end_time = time.time()\n # Move from GPU to CPU\n #output = output.cpu()\n # Move Output\n if reference == 0:\n output_name = output_dir / '{:s}_s{:s}{:s}'.format(image_path.stem, args.scale, args.save_ext)\n elif reference == 1:\n output_name = output_dir / '{:s}_Reference{:s}'.format(image_path.stem, args.save_ext)\n # Save Image\n save_image(output, str(output_name))\n # Display Compute Time\n print(['Total Rendering time: ' + str(end_time-start_time) + ' seconds'])\n if z % 50 == 1:\n time.sleep(10)\n" ]
[ [ "torch.sum", "numpy.sqrt", "torch.load", "torch.randn", "torch.no_grad", "numpy.arange", "torch.cuda.is_available", "numpy.shape", "torch.index_select", "torch.zeros" ] ]
QingshuChen/Paddle
[ "25a92be3e123ed21fd98c7be6bd7e3a6320756a3" ]
[ "python/paddle/v2/fluid/tests/test_ftrl_op.py" ]
[ "import unittest\nimport numpy as np\nfrom op_test import OpTest\n\n\nclass TestFTRLOp(OpTest):\n def setUp(self):\n self.op_type = \"ftrl\"\n w = np.random.random((102, 105)).astype(\"float32\")\n g = np.random.random((102, 105)).astype(\"float32\")\n sq_accum = np.full((102, 105), 0.1).astype(\"float32\")\n linear_accum = np.full((102, 105), 0.1).astype(\"float32\")\n lr = np.array([0.01]).astype(\"float32\")\n l1 = 0.1\n l2 = 0.2\n lr_power = -0.5\n\n self.inputs = {\n 'Param': w,\n 'SquaredAccumulator': sq_accum,\n 'LinearAccumulator': linear_accum,\n 'Grad': g,\n 'LearningRate': lr\n }\n self.attrs = {\n 'l1': l1,\n 'l2': l2,\n 'lr_power': lr_power,\n 'learning_rate': lr\n }\n new_accum = sq_accum + g * g\n if lr_power == -0.5:\n linear_out = linear_accum + g - (\n (np.sqrt(new_accum) - np.sqrt(sq_accum)) / lr) * w\n else:\n linear_out = linear_accum + g - ((np.power(\n new_accum, -lr_power) - np.power(sq_accum, -lr_power)) / lr) * w\n\n x = (l1 * np.sign(linear_out) - linear_out)\n if lr_power == -0.5:\n y = (np.sqrt(new_accum) / lr) + (2 * l2)\n pre_shrink = x / y\n param_out = np.where(np.abs(linear_out) > l1, pre_shrink, 0.0)\n else:\n y = (np.power(new_accum, -lr_power) / lr) + (2 * l2)\n pre_shrink = x / y\n param_out = np.where(np.abs(linear_out) > l1, pre_shrink, 0.0)\n\n sq_accum_out = sq_accum + g * g\n\n self.outputs = {\n 'ParamOut': param_out,\n 'SquaredAccumOut': sq_accum_out,\n 'LinearAccumOut': linear_out\n }\n\n def test_check_output(self):\n self.check_output()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.sign", "numpy.abs", "numpy.random.random", "numpy.power", "numpy.sqrt", "numpy.full", "numpy.array" ] ]
jpkulasingham/Eelbrain
[ "1061ce0b781a8e55ec187723b58491a5cde32e08" ]
[ "eelbrain/save/_besa.py" ]
[ "\"\"\"\nExport events for use in the Besa pipeline.\n\nUse :func:`meg160_triggers` to export a trigger list for MEG160, then reject\nunwanted events, and finally use :func:`besa_evt` to export a corresponding\n``.evt`` file.\n\n\"\"\"\nimport numpy as np\n\nfrom .._data_obj import Var, Dataset\nfrom .._utils import ui\nfrom . import _txt\n\n\ndef meg160_triggers(ds, dest=None, pad=1):\n \"\"\"\n Export a list of event times used for epoching in MEG-160\n\n For use together with :func:`besa_evt`. ``save.meg160_triggers(ds)`` adds\n a variable called 'besa_index' which keeps track of the event sequence so\n that the .evt file can be saved correctly after event rejection.\n\n Parameters\n ----------\n ds : Dataset\n Dataset containing all the desired events.\n dest : None | str\n Path where to save the triggers (if None, a dialog will be displayed).\n pad : int\n Number of epochs to pad with at the beginning and end of the file.\n \"\"\"\n sfreq = ds.info['raw'].info['sfreq']\n times = ds['i_start'] / sfreq\n\n # destination\n if dest is None:\n dest = ui.ask_saveas(\"Save MEG-160 Triggers\", \"Please pick a \"\n \"destination for the MEG-160 triggers\",\n [('MEG160 trigger-list', '*.txt')])\n if not dest:\n return\n\n # make trigger list with padding\n a = np.ones(len(times) + pad * 2) * times[0]\n a[pad:-pad] = times.x\n triggers = Var(a, name='triggers')\n\n # export trigger list\n _txt.txt(triggers, dest=dest)\n\n # index the datafile to keep track of rejections\n ds.index('besa_index', pad)\n\n\ndef besa_evt(ds, tstart=-0.1, tstop=0.6, pad=0.1, dest=None):\n \"\"\"\n Export an evt file for use with Besa\n\n For use together with :func:`meg160_triggers`\n\n Parameters\n ----------\n ds : Dataset\n Dataset containing the events.\n tstart, tstop : scalar [sec]\n start and stop of the actual epoch.\n pad : scalar [sec]\n Time interval added before and after every epoch for padding.\n dest : None | str\n Destination file name. If None, a save as dialog will be shown.\n\n Notes\n -----\n ds needs to be the same Dataset (i.e., same length) from which the MEG-160\n triggers were created.\n\n tstart, tstop and pad need to be the same values used for epoching in\n MEG-160.\n \"\"\"\n idx = ds['besa_index']\n N = idx.x.max() + 1\n\n # save trigger times in ds\n tstart2 = tstart - pad\n tstop2 = tstop + pad\n epoch_len = tstop2 - tstart2\n start = -tstart2\n stop = epoch_len * N\n\n # BESA events\n evts = Dataset()\n evts['Tsec'] = Var(np.arange(start, stop, epoch_len))\n evts['Code'] = Var(np.ones(N))\n\n # remove rejected trials\n evts = evts.sub(idx)\n\n evts['TriNo'] = Var(ds['trigger'].x)\n\n # destination\n if dest is None:\n dest = ui.ask_saveas(\"Save Besa Events\", \"Please pick a \"\n \"destination for the Besa events\",\n [('Besa Events', '*.evt')])\n if not dest:\n return\n\n evts.save_txt(dest)\n" ]
[ [ "numpy.arange", "numpy.ones" ] ]
Aggrathon/MtGan
[ "81bc78f9dee485a0f5704109fe4a5a28650feaf3" ]
[ "models/model.py" ]
[ "\"\"\"\n Tensorflow GAN model\n\"\"\"\nimport os\nfrom pathlib import Path\nimport tensorflow as tf\n\nDIRECTORY = Path('network')\nDATA = Path('data')\nIMAGE_LIST = DATA / 'images.txt'\nART_LIST = DATA / 'art.txt'\nART_BLACK_LIST = DATA / 'art_black.txt'\nART_GREEN_LIST = DATA / 'art_green.txt'\nART_WHITE_LIST = DATA / 'art_white.txt'\nIMAGE_WIDTH = 176\nIMAGE_HEIGHT = 128\nGPU = False\n\ndef _read_image(filename):\n string = tf.read_file(filename)\n decoded = tf.image.decode_image(string, 3)\n cropped = tf.image.resize_image_with_crop_or_pad(decoded, IMAGE_HEIGHT, IMAGE_WIDTH)\n factor = 1.0 / 127.5\n floated = tf.to_float(cropped)*factor-1.0\n return floated\n\ndef _read_image_random(filename):\n image = _read_image(filename)\n random = tf.image.random_brightness(image, 0.2)\n random = tf.image.random_contrast(random, 0.85, 1.2)\n random = tf.image.random_flip_left_right(random)\n random = tf.image.random_saturation(random, 0.85, 1.2)\n random = tf.image.random_hue(random, 0.05)\n return random\n\ndef _read_image_random_crop(filename):\n return tf.random_crop(_read_image_random(filename), (8*16, 10*16, 3))\n\ndef get_image_only_data(list_file=IMAGE_LIST, batch_size=32, image_processor=_read_image, image_height=IMAGE_HEIGHT, image_width=IMAGE_WIDTH):\n \"\"\"\n Returns a dataset containing only images\n \"\"\"\n with tf.device('/cpu:0'):\n textfile = tf.data.TextLineDataset(str(list_file))\n shuffled = textfile.cache().repeat().shuffle(5000)\n images = shuffled.map(image_processor, 8).prefetch(batch_size*2)\n batch = images.batch(batch_size).make_one_shot_iterator().get_next()\n return tf.reshape(batch, (batch_size, image_height, image_width, 3))\n\ndef get_art_only_data(list_file=ART_LIST, batch_size=32):\n \"\"\"\n Returns a dataset containing only art\n \"\"\"\n return get_image_only_data(list_file, batch_size, _read_image_random)\n\ndef get_art_only_cropped(art_list=ART_GREEN_LIST, batch_size=32):\n \"\"\"\n Returns a dataset containing cropped art\n \"\"\"\n return get_image_only_data(art_list, batch_size, _read_image_random_crop, 8*16, 10*16)\n\n\nclass BaseGenerator():\n \"\"\"\n Base class for all generators\n \"\"\"\n def __init__(self, name):\n self.name = name\n os.makedirs(str(DIRECTORY / name), exist_ok=True)\n self.session = None\n self.saver = None\n self.summary = None\n self.global_step = tf.train.get_or_create_global_step()\n self.scope = tf.variable_scope(name)\n self.summary_writer = None\n\n def restore(self, session=None):\n \"\"\"\n Restore a saved model or initialize a new one\n \"\"\"\n if session is None:\n session = self.session\n self.saver = tf.train.Saver()\n self.summary = tf.summary.merge_all()\n self.summary_writer = tf.summary.FileWriter(str(DIRECTORY / self.name))\n try:\n self.saver.restore(session, tf.train.latest_checkpoint(str(DIRECTORY / self.name)))\n print(\"Loaded an existing model\")\n except:\n session.run(tf.global_variables_initializer())\n self.summary_writer.add_graph(session.graph, 0)\n print(\"Created a new model\")\n\n def save(self, session=None):\n \"\"\"\n Save the current model\n \"\"\"\n if session is None:\n session = self.session\n self.saver.save(session, str(DIRECTORY / self.name / 'model'), self.global_step)\n\n def train_step(self, summary=False, session=None):\n \"\"\"\n Do a training step and return step_nr and result (and optionally summary to write)\n \"\"\"\n if session is None:\n session = self.session\n\n def add_summary(self, event, step):\n \"\"\"\n Write a tensorboard summary\n \"\"\"\n self.summary_writer.add_summary(event, step)\n\n def __enter__(self):\n print(\"Initializing Tensorflow Session\")\n if GPU:\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True #pylint: disable=E1101\n self.session = tf.Session(config=config)\n else:\n self.session = tf.Session()\n self.restore()\n return self\n\n def __exit__(self, type_, value, traceback):\n if self.global_step.eval(self.session) > 100:\n self.save()\n self.session.close()\n" ]
[ [ "tensorflow.image.random_brightness", "tensorflow.image.random_contrast", "tensorflow.image.random_flip_left_right", "tensorflow.image.random_saturation", "tensorflow.image.resize_image_with_crop_or_pad", "tensorflow.reshape", "tensorflow.device", "tensorflow.summary.merge_all", "tensorflow.to_float", "tensorflow.variable_scope", "tensorflow.read_file", "tensorflow.global_variables_initializer", "tensorflow.train.get_or_create_global_step", "tensorflow.train.Saver", "tensorflow.image.random_hue", "tensorflow.Session", "tensorflow.ConfigProto", "tensorflow.image.decode_image" ] ]
Deeptituscano/Deep-Learning-with-TensorFlow
[ "7ea73195922bce6919864352b529b84194ec9d30" ]
[ "Chapter06/Python 3.5/bidirectional_RNN_1.py" ]
[ "import tensorflow as tf\r\nimport numpy as np\r\nfrom tensorflow.contrib import rnn\r\n\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\r\n\r\nlearning_rate = 0.001\r\ntraining_iters = 100000\r\nbatch_size = 128\r\ndisplay_step = 10\r\n\r\nn_input = 28 \r\nn_steps = 28 \r\nn_hidden = 128 \r\nn_classes = 10 \r\n\r\nx = tf.placeholder(\"float\", [None, n_steps, n_input])\r\ny = tf.placeholder(\"float\", [None, n_classes])\r\n\r\nweights = {\r\n 'out': tf.Variable(tf.random_normal([2*n_hidden, n_classes]))\r\n}\r\nbiases = {\r\n 'out': tf.Variable(tf.random_normal([n_classes]))\r\n}\r\n\r\ndef BiRNN(x, weights, biases):\r\n x = tf.transpose(x, [1, 0, 2])\r\n x = tf.reshape(x, [-1, n_input])\r\n x = tf.split(axis=0, num_or_size_splits=n_steps, value=x)\r\n lstm_fw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)\r\n lstm_bw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)\r\n try:\r\n outputs, _, _ = rnn.static_bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x,\r\n dtype=tf.float32)\r\n except Exception: # Old TensorFlow version only returns outputs not states\r\n outputs = rnn.static_bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x,\r\n dtype=tf.float32)\r\n return tf.matmul(outputs[-1], weights['out']) + biases['out']\r\n\r\npred = BiRNN(x, weights, biases)\r\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))\r\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\r\ncorrect_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))\r\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\r\ninit = tf.global_variables_initializer()\r\n\r\nwith tf.Session() as sess:\r\n sess.run(init)\r\n step = 1\r\n while step * batch_size < training_iters:\r\n batch_x, batch_y = mnist.train.next_batch(batch_size)\r\n batch_x = batch_x.reshape((batch_size, n_steps, n_input))\r\n sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})\r\n if step % display_step == 0:\r\n acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})\r\n loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})\r\n print(\"Iter \" + str(step*batch_size) + \", Minibatch Loss= \" + \\\r\n \"{:.6f}\".format(loss) + \", Training Accuracy= \" + \\\r\n \"{:.5f}\".format(acc))\r\n step += 1\r\n print(\"Optimization Finished!\")\r\n\r\n test_len = 128\r\n test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))\r\n test_label = mnist.test.labels[:test_len]\r\n print(\"Testing Accuracy:\", \\\r\nsess.run(accuracy, feed_dict={x: test_data, y: test_label}))\r\n" ]
[ [ "tensorflow.placeholder", "tensorflow.contrib.rnn.BasicLSTMCell", "tensorflow.random_normal", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.reshape", "tensorflow.global_variables_initializer", "tensorflow.contrib.rnn.static_bidirectional_rnn", "tensorflow.train.AdamOptimizer", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "tensorflow.matmul", "tensorflow.cast", "tensorflow.argmax", "tensorflow.Session", "tensorflow.transpose", "tensorflow.split" ] ]
JoyeBright/nlp981
[ "94267f4c3030319ca753d32fa02df492dda1acae" ]
[ "Week2/ManualNN.py" ]
[ "import numpy as np\n\n# Mini Dataset\ninput_data = np.array([5, 7, 8, 1])\n\nweights = {'node0': np.array([1, 1]),\n 'node1': np.array([-1, 1]),\n 'output': np.array([2, -1])}\n\n\n# Activation Function\ndef ReLu(x):\n out = max(0, x)\n return out\n\n\ndef predict_with_NN(input_data_row, weights):\n print(\"\\nFirst element of input data: %s\" % input_data)\n print(\"Weights for nodes in hidden layer 0: %s\" % weights['node0'])\n print(\"Weights for nodes in hidden layer 1: %s\" % weights['node1'])\n print(\"Weights for nodes in output: %s\" % weights['output'])\n\n # Calculation for node 0 value\n node_0_input = (input_data_row * weights['node0']).sum()\n print(\"Node 0 in hidden layer before activation function: %d\" % node_0_input)\n node_0_output = ReLu(node_0_input)\n print(\"Node 0 in hidden layer after activation function: %d\" % node_0_output)\n\n # Calculation for node 1 value\n node_1_input = (input_data_row * weights['node1']).sum()\n print(\"Node 1 in hidden layer before activation function: %d\" % node_1_input)\n node_1_output = ReLu(node_1_input)\n print(\"Node 1 in hidden layer after activation function: %d\" % node_1_output)\n\n # put node values into array : hidden_layer_output\n hidden_layer_output = np.array([node_0_output, node_1_output])\n print(\"Hidden layer: %s\" % hidden_layer_output)\n\n # Calculate model output\n input_to_final_layer = (hidden_layer_output * weights['output']).sum()\n print(\"Output layer before activation function: %d\" % input_to_final_layer)\n model_output = ReLu(input_to_final_layer)\n print(\"Output layer after activation function: %d\" % model_output)\n\n # Return model output\n return model_output\n\n\n# Create Empty list to store prediction results\nresults = []\nfor input_data_row in input_data:\n # Append prediction to result\n results.append(predict_with_NN(input_data_row, weights))\n\n\nprint(results)\n\n\n" ]
[ [ "numpy.array" ] ]
morkovka1337/mmdetection
[ "5187d94b6c96084b17817249622d6e4520213ae6" ]
[ "mmdet/models/backbones/imgclsmob.py" ]
[ "# Copyright (C) 2020-2021 Intel 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\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an \"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\n# and limitations under the License.\n\nimport logging\nimport os\nimport tempfile\n# import types\n\nimport torch.nn as nn\nfrom pytorchcv.model_provider import _models\nfrom pytorchcv.models.model_store import download_model\nfrom torch import distributed\nfrom torch.nn.modules.batchnorm import _BatchNorm\nfrom mmcv.runner import get_dist_info\n\nfrom mmdet.utils.logger import get_root_logger\n\nfrom ..builder import BACKBONES\n\n\ndef generate_backbones():\n logger = get_root_logger()\n\n for model_name, model_getter in _models.items():\n\n def closure(model_name, model_getter):\n\n def multioutput_forward(self, x):\n outputs = []\n y = x\n\n last_stage = max(self.out_indices)\n for i, stage in enumerate(self.features):\n y = stage(y)\n s = str(i) + ' ' + str(y.shape)\n if i in self.out_indices:\n outputs.append(y)\n s += '*'\n if self.verbose:\n print(s)\n if i == last_stage:\n break\n\n return outputs\n\n def init_weights(self, pretrained=True):\n if pretrained:\n rank, world_size = get_dist_info()\n logger.warning(f'imgclsmob::loading weights proc rank {rank}')\n if rank == 0:\n # Make sure that model is fetched to the local storage.\n logger.warning(f'imgclsmob::downloading {rank}')\n download_model(\n net=self,\n model_name=model_name,\n local_model_store_dir_path=self.models_cache_root)\n if world_size > 1:\n logger.warning(f'imgclsmob::barrier {rank}')\n distributed.barrier()\n else:\n # Wait for model to be in the local storage, then load it.\n logger.warning(f'imgclsmob::barrier {rank}')\n distributed.barrier()\n logger.warning(f'imgclsmob::loading {rank}')\n download_model(\n net=self,\n model_name=model_name,\n local_model_store_dir_path=self.models_cache_root)\n logger.warning(f'imgclsmob::done {rank}')\n\n def train(self, mode=True):\n super(self.__class__, self).train(mode)\n\n for i in range(self.frozen_stages + 1):\n m = self.features[i]\n m.eval()\n for param in m.parameters():\n param.requires_grad = False\n\n if mode and self.norm_eval:\n for m in self.modules():\n # trick: eval have effect on BatchNorm only\n if isinstance(m, _BatchNorm):\n m.eval()\n\n class custom_model_getter(nn.Module):\n def __init__(self, *args, out_indices=None, frozen_stages=0, norm_eval=False, verbose=False, **kwargs):\n super().__init__()\n models_cache_root = kwargs.get('root', os.path.join('~', '.torch', 'models'))\n is_pretrained = kwargs.get('pretrained', False)\n logger.warning(f'Init model {model_name}, pretrained={is_pretrained}, models cache {models_cache_root}')\n # if 'pretrained' in kwargs and kwargs['pretrained']:\n # rank, _ = get_dist_info()\n # if rank > 0:\n # if 'root' not in kwargs:\n # kwargs['root'] = tempfile.mkdtemp()\n # kwargs['root'] = tempfile.mkdtemp(dir=kwargs['root'])\n # logger.info('Rank: {}, Setting {} as a target location of pretrained models'.format(rank, kwargs['root']))\n model = model_getter(*args, **kwargs)\n model.out_indices = out_indices\n model.frozen_stages = frozen_stages\n model.norm_eval = norm_eval\n model.verbose = verbose\n model.models_cache_root = models_cache_root\n if hasattr(model, 'features') and isinstance(model.features, nn.Sequential):\n # Save original forward, just in case.\n model.forward_single_output = model.forward\n model.forward = multioutput_forward.__get__(model)\n model.init_weights = init_weights.__get__(model)\n model.train = train.__get__(model)\n\n # model.forward = types.MethodType(multioutput_forward, model)\n # model.init_weights = types.MethodType(init_weights, model)\n # model.train = types.MethodType(train, model)\n\n model.output = None\n for i, _ in enumerate(model.features):\n if i > max(out_indices):\n model.features[i] = None\n else:\n raise ValueError('Failed to automatically wrap backbone network. '\n 'Object of type {} has no valid attribute called '\n '\"features\".'.format(model.__class__))\n self.__dict__.update(model.__dict__)\n\n custom_model_getter.__name__ = model_name\n return custom_model_getter\n\n BACKBONES.register_module(name=model_name, module=closure(model_name, model_getter))\n\n\ngenerate_backbones()\n" ]
[ [ "torch.distributed.barrier" ] ]
TTitcombe/tfShell2
[ "a95cbc6cb1f2168c1ea51096dcfb9e4a8e33d699" ]
[ "test/utils.py" ]
[ "import tensorflow as tf\n\n\nclass MockModel(tf.keras.Model):\n \"\"\"\n A Mock keras model to test basic tester functionality.\n This model only has one variable: a weight matrix of shape 2x1.\n This model accepts 2-dimensional input data and outputs 1-d data\n \"\"\"\n def __init__(self):\n super(MockModel, self).__init__()\n self.weight = tf.Variable(tf.ones((2, 1)), dtype=tf.float32)\n\n def call(self, input_data):\n return tf.linalg.matmul(input_data, self.weight)\n" ]
[ [ "tensorflow.linalg.matmul", "tensorflow.ones" ] ]
WhatTheFar/practical-ai-bootcamp
[ "e2fe013390c00df0a5486795a737d7b777266f35" ]
[ "day5/lab-guide-ans/lab5-problem1-1.py" ]
[ "import pandas as pd\nimport matplotlib.pyplot as plt\n\ndataframe = pd.read_csv('data/problem1data.txt', header=None)\ndatasetClass0 = dataframe.loc[dataframe[2] == 0]\ndatasetClass1 = dataframe.loc[dataframe[2] == 1]\n\nfigure = plt.figure()\naxis = figure.add_subplot(111)\naxis.scatter(datasetClass0[0], datasetClass0[1], marker='o', label='Class 0')\naxis.scatter(datasetClass1[0], datasetClass1[1], marker='x', label='Class 1')\n\nplt.xlabel('Microchip Test 1')\nplt.ylabel('Microchip Test 1')\nplt.title('Plot of training data')\nplt.legend()\nplt.show()\n" ]
[ [ "matplotlib.pyplot.legend", "pandas.read_csv", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ] ]
WM-CSCI-435-F19/data-science-4-software-engineering
[ "3692163df710550d4ee5b399a2a184968a0f18c6" ]
[ "ds4se/mgmnt/prep/files_mgmnt.py" ]
[ "# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/0.2_mgmnt.prep.files_mgmnt.ipynb (unless otherwise specified).\n\n__all__ = ['logger', 'get_file_name', 'get_files_list', 'jsonl_list_to_dataframe', 'jsonl_to_dataframe',\n 'csv_to_dataframe', 'load_np_vectors', 'get_vector_paths_4_sample_set']\n\n# Cell\n\nimport pandas as pd\nimport numpy as np\n\nfrom pathlib import Path, PosixPath\nfrom typing import List\n\n# Cell\n#Logging configuration\n\nimport logging\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n# Cell\n\ndef _check_file_existence(file_path: str) -> bool:\n \"\"\"\n Validates the existence of a file\n \"\"\"\n path = Path(file_path)\n if not path.exists():\n logging.error('Provided file cannot be found.')\n return False\n return True\n\ndef _check_dir_existence(path: PosixPath):\n \"\"\"\n Validates the existence of a given directory\n \"\"\"\n if not path.exists():\n msg = \"Provided directory cannot be found.\"\n logging.error(msg)\n raise Exception(msg)\n\n\n# Cell\n\ndef get_file_name(full_dir: str):\n \"\"\"\n Retrieves the filename of a path\n \"\"\"\n path = Path(full_dir)\n return Path(path.name).stem\n\n# Cell\n\ndef get_files_list(directory: str, file_extension: str) -> List[str]:\n \"\"\"\n Get a list of files (with a specific extension) within a directory.\n :param directory: Directory to extract list of files\n :param file_extension: File extension of files to include in the list\n\n :return: List of files within the directoy with the provided extension\n \"\"\"\n path = Path(directory)\n _check_dir_existence(path)\n\n return list(path.glob(f'**/*.{file_extension}'))\n\n# Cell\n\ndef jsonl_list_to_dataframe(file_list: List[str]) -> pd.DataFrame:\n \"\"\"Load a list of jsonl.gz files into a pandas DataFrame.\"\"\"\n return pd.concat([pd.read_json(f,\n orient='records',\n compression='gzip',\n lines=True)\n for f in file_list], sort=False)\n\ndef jsonl_to_dataframe(file_path: str) -> pd.DataFrame:\n \"\"\"\n Gets a DataFrame from a jsonl file\n :param file_path: Location of the jsonl file\n :return:\n \"\"\"\n\n _check_file_existence(file_path)\n return pd.read_json(file_path, orient='records', lines=True)\n\n# Cell\n\ndef csv_to_dataframe(file_path: str) -> pd.DataFrame:\n \"\"\"Gets a DataFrame from a csv file\"\"\"\n\n _check_file_existence(file_path)\n return pd.read_csv(file_path)\n\n# Cell\n\ndef load_np_vectors(path: str) -> np.array:\n \"\"\"\n :param path: Location of the .npy files to be loaded\n\n :return: Np array corresponding to the loaded vectors\n \"\"\"\n path = Path(path)\n if not path.exists():\n msg = \"Vectors could not be found\"\n logging.error(msg)\n raise Exception(msg)\n return np.load(str(path))\n\n# Cell\n\ndef get_vector_paths_4_sample_set(set_name: str, base_path: str) -> List[PosixPath]:\n \"\"\"\n Gets the files for a given directory containing sample set\n :param set_name: Str indicating the name of the directory for a given set of samples\n :param base_path: Str indicating the location directory of samples\n \"\"\"\n paths = []\n vectors_path = f\"{base_path}/{set_name}\"\n path = Path(vectors_path)\n\n # TODO: Validate existence of directory\n\n # Iterate over all the samples for a set\n for sample_directory in path.iterdir():\n vectors_path = list(sample_directory.rglob('*-ft_vecs.npy'))\n if len(vectors_path) == 0:\n logging.warning(f\"Could not load vectors for sample {str(directory)}\")\n continue\n\n paths.append(vectors_path[0])\n\n return paths" ]
[ [ "pandas.read_csv", "pandas.read_json" ] ]
zmlabe/InternalSignal
[ "2ac31bc7a0c445ed9fa609f3c7f9800bec7b4aed" ]
[ "DarkScripts/plot_SNRComposites_XLENS_Method4.py" ]
[ "\"\"\"\nPlot signal-to-noise ratios for XLENS simulations\n\nMethod 4 = mean temperature change / mean std of temperature in 1920-1959\n\nReference : Deser et al. [2020, JCLI] & Barnes et al. [2020, JAMES]\nAuthor : Zachary M. Labe\nDate : 28 October 2020\n\"\"\"\n\n### Import packages\nimport math\nimport time\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as sts\nfrom mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\nimport palettable.cubehelix as cm\nimport cmocean as cmocean\nimport calc_Utilities as UT\nimport calc_dataFunctions as df\nimport itertools\n\n##############################################################################\n##############################################################################\n##############################################################################\n## Data preliminaries \ndirectorydataLLS = '/Users/zlabe/Data/LENS/SINGLE/'\ndirectorydataLLL = '/Users/zlabe/Data/LENS/monthly'\ndirectoryfigure = '/Users/zlabe/Desktop/SINGLE_v2.0/Composites/T2M/'\ndatasetsingleq = np.repeat(['AER+ALL','GHG+ALL','TOTAL'],3)\ndatasetsingle = ['XGHG','XAER','lens']\ntimeq = ['1960-1999','2000-2039','2040-2079']\nseasons = ['annual','JFM','AMJ','JAS','OND']\nletters = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\"]\nyears = np.arange(1920,2079+1,1)\ndirectoriesall = [directorydataLLS,directorydataLLS,directorydataLLL]\n\nvariq = 'T2M'\nmonthlychoice = seasons[0]\nreg_name = 'Globe'\n\ndef read_primary_dataset(variq,dataset,lat_bounds,lon_bounds,monthlychoice):\n data,lats,lons = df.readFiles(variq,dataset,monthlychoice)\n datar,lats,lons = df.getRegion(data,lats,lons,lat_bounds,lon_bounds)\n print('\\nOur dataset: ',dataset,' is shaped',data.shape)\n return datar,lats,lons\n\n### Read in data\nlat_bounds,lon_bounds = UT.regions(reg_name)\nghg,lat1,lon1 = read_primary_dataset(variq,datasetsingle[0],lat_bounds,lon_bounds,\n monthlychoice)\naer,lat1,lon1 = read_primary_dataset(variq,datasetsingle[1],lat_bounds,lon_bounds,\n monthlychoice)\nlens,lat1,lon1 = read_primary_dataset(variq,datasetsingle[2],lat_bounds,lon_bounds,\n monthlychoice)\n\n### Calculate to 2079\nghgn = ghg[:,:-1,:,:]\naern = aer[:,:-1,:,:]\nlensn = lens[:,:-1,:,:]\n\n### Calculate early means\nghg_20 = np.nanmean(ghg[:,:40,:,:],axis=1)\naer_20 = np.nanmean(aer[:,:40,:,:],axis=1)\nlens_20 = np.nanmean(lens[:,:40,:,:],axis=1)\nghg_20std = np.nanstd(ghg[:,:40,:,:],axis=1)\naer_20std = np.nanstd(aer[:,:40,:,:],axis=1)\nlens_20std = np.nanstd(lens[:,:40,:,:],axis=1)\n\nghg_20mean = np.nanmean(ghg_20,axis=0)\naer_20mean = np.nanmean(aer_20,axis=0)\nlens_20mean = np.nanmean(lens_20,axis=0)\nghg_20meanstd = np.nanmean(ghg_20std,axis=0)\naer_20meanstd = np.nanmean(aer_20std,axis=0)\nlens_20meanstd = np.nanmean(lens_20std,axis=0)\n\n### Calculate ensemble mean\nmeanghg = np.nanmean(ghgn,axis=0)\nmeanaer = np.nanmean(aern,axis=0)\nmeanlens = np.nanmean(lensn,axis=0)\n\ndiffens_ghg = np.empty((ghgn.shape[0],3,lat1.shape[0],lon1.shape[0]))\ndiffens_aer = np.empty((aern.shape[0],3,lat1.shape[0],lon1.shape[0]))\ndiffens_lens = np.empty((lensn.shape[0],3,lat1.shape[0],lon1.shape[0]))\nstdens_ghg = np.empty((ghgn.shape[0],3,lat1.shape[0],lon1.shape[0]))\nstdens_aer = np.empty((aern.shape[0],3,lat1.shape[0],lon1.shape[0]))\nstdens_lens = np.empty((lensn.shape[0],3,lat1.shape[0],lon1.shape[0]))\n### Calculate change in temperature from 1920-1959 and sigma per period\nfor count,i in enumerate(range(40,len(years),40)):\n diffens_ghg[:,count,:,:] = np.nanmean(ghgn[:,i:i+40,:,:],axis=1) - ghg_20\n diffens_aer[:,count,:,:] = np.nanmean(aern[:,i:i+40,:,:],axis=1) - aer_20\n diffens_lens[:,count,:,:] = np.nanmean(lensn[:,i:i+40,:,:],axis=1) - lens_20\n \n stdens_ghg[:,count,:,:] = np.nanstd(ghgn[:,i:i+40,:,:],axis=1)\n stdens_aer[:,count,:,:] = np.nanstd(aern[:,i:i+40,:,:],axis=1)\n stdens_lens[:,count,:,:] = np.nanstd(lensn[:,i:i+40,:,:],axis=1)\n \n### Calculate change statistics\nmeanchange_ghg = np.nanmean(diffens_ghg,axis=0)\nmeanchange_aer = np.nanmean(diffens_aer,axis=0)\nmeanchange_lens = np.nanmean(diffens_lens,axis=0)\nmeanstd_ghg = np.nanmean(stdens_ghg,axis=0)\nmeanstd_aer = np.nanmean(stdens_aer,axis=0)\nmeanstd_lens = np.nanmean(stdens_lens,axis=0)\n\nmaxchange_ghg = np.nanmax(diffens_ghg,axis=0)\nmaxchange_aer = np.nanmax(diffens_aer,axis=0)\nmaxchange_lens = np.nanmax(diffens_lens,axis=0)\nmaxstd_ghg = np.nanmax(stdens_ghg,axis=0)\nmaxstd_aer = np.nanmax(stdens_aer,axis=0)\nmaxstd_lens = np.nanmax(stdens_lens,axis=0)\n\nminchange_ghg = np.nanmin(diffens_ghg,axis=0)\nminchange_aer = np.nanmin(diffens_aer,axis=0)\nminchange_lens = np.nanmin(diffens_lens,axis=0)\nminstd_ghg = np.nanmin(stdens_ghg,axis=0)\nminstd_aer = np.nanmin(stdens_aer,axis=0)\nminstd_lens = np.nanmin(stdens_lens,axis=0)\n\n### Calculate ensemble spread in change\nspread_ghg = maxchange_ghg - minchange_ghg\nspread_aer = maxchange_aer - minchange_aer\nspread_lens = maxchange_lens - minchange_lens\nspreadstd_ghg = maxstd_ghg - minstd_ghg\nspreadstd_aer = maxstd_aer - minstd_aer\nspreadstd_lens = maxstd_lens - minstd_lens\n\n### Calculate signal-to-noise ratios\nsnr_ghg = meanchange_ghg/ghg_20meanstd\nsnr_aer = meanchange_aer/aer_20meanstd\nsnr_lens = meanchange_lens/lens_20meanstd\n\nruns = list(itertools.chain.from_iterable([snr_ghg,snr_aer,snr_lens]))\n\n###########################################################################\n###########################################################################\n###########################################################################\n### Plot variable data for trends\nplt.rc('text',usetex=True)\nplt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']}) \n\n### Set limits for contours and colorbars\nlimit = np.arange(-5,5.1,0.1)\nbarlim = np.arange(-5,6,5)\ncmap = cmocean.cm.balance\nlabel = r'\\textbf{T2M [signal-to-noise]}'\n \nfig = plt.figure(figsize=(5,3))\nfor r in range(len(runs)):\n var = runs[r]\n \n ax1 = plt.subplot(3,3,r+1)\n m = Basemap(projection='moll',lon_0=0,resolution='l',area_thresh=10000)\n circle = m.drawmapboundary(fill_color='k')\n circle.set_clip_on(False) \n m.drawcoastlines(color='dimgrey',linewidth=0.35)\n \n var, lons_cyclic = addcyclic(var, lon1)\n var, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False)\n lon2d, lat2d = np.meshgrid(lons_cyclic, lat1)\n x, y = m(lon2d, lat2d)\n \n circle = m.drawmapboundary(fill_color='white',color='dimgray',\n linewidth=0.7)\n circle.set_clip_on(False)\n \n cs = m.contourf(x,y,var,limit,extend='both')\n \n cs.set_cmap(cmap) \n if any([r==0,r==3,r==6]):\n ax1.annotate(r'\\textbf{%s}' % datasetsingleq[r],xy=(0,0),xytext=(-0.1,0.5),\n textcoords='axes fraction',color='k',fontsize=9,\n rotation=90,ha='center',va='center')\n if any([r==0,r==1,r==2]):\n ax1.annotate(r'\\textbf{%s}' % timeq[r],xy=(0,0),xytext=(0.5,1.22),\n textcoords='axes fraction',color='dimgrey',fontsize=9,\n rotation=0,ha='center',va='center')\n ax1.annotate(r'\\textbf{[%s]}' % letters[r],xy=(0,0),xytext=(0.87,0.97),\n textcoords='axes fraction',color='k',fontsize=6,\n rotation=330,ha='center',va='center')\n\n###########################################################################\ncbar_ax = fig.add_axes([0.32,0.095,0.4,0.03]) \ncbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal',\n extend='both',extendfrac=0.07,drawedges=False)\n\ncbar.set_label(label,fontsize=9,color='dimgrey',labelpad=1.4) \n\ncbar.set_ticks(barlim)\ncbar.set_ticklabels(list(map(str,barlim)))\ncbar.ax.tick_params(axis='x', size=.01,labelsize=5)\ncbar.outline.set_edgecolor('dimgrey')\n\nplt.tight_layout()\nplt.subplots_adjust(top=0.85,wspace=0.01,hspace=0,bottom=0.14)\n\nplt.savefig(directoryfigure + 'SNRPeriods_T2M_XGHG-XAER-LENS_Method4.png',dpi=300)" ]
[ [ "numpy.empty", "numpy.nanmax", "matplotlib.pyplot.rc", "numpy.nanmean", "matplotlib.pyplot.figure", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.savefig", "numpy.nanstd", "numpy.repeat", "numpy.nanmin", "numpy.arange", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.subplot", "numpy.meshgrid" ] ]
redis-developer/the-pattern
[ "faa629b8152f405f92987c1436565938fa302932" ]
[ "the-pattern-api/qasearch/tokeniser_gears_redisai.py" ]
[ "### This gears will pre-compute (encode) all sentences using BERT tokenizer for QA\n\ntokenizer = None \n\ndef loadTokeniser():\n global tokenizer\n from transformers import BertTokenizerFast\n tokenizer = BertTokenizerFast.from_pretrained(\"bert-large-uncased-whole-word-masking-finetuned-squad\")\n # tokenizer = AutoTokenizer.from_pretrained(\"emilyalsentzer/Bio_ClinicalBERT\")\n return tokenizer\n\ndef remove_prefix(text, prefix):\n return text[text.startswith(prefix) and len(prefix):]\n\n\n\ndef parse_sentence(record):\n import redisAI\n import numpy as np\n global tokenizer\n if not tokenizer:\n tokenizer=loadTokeniser()\n hash_tag=\"{%s}\" % hashtag()\n\n for idx, value in sorted(record['value'].items(), key=lambda item: int(item[0])):\n tokens = tokenizer.encode(value, add_special_tokens=False, max_length=511, truncation=True, return_tensors=\"np\")\n tokens = np.append(tokens,tokenizer.sep_token_id).astype(np.int64) \n tensor=redisAI.createTensorFromBlob('INT64', tokens.shape, tokens.tobytes())\n \n key_prefix='sentence:'\n sentence_key=remove_prefix(record['key'],key_prefix)\n token_key = f\"tokenized:bert:qa:{sentence_key}:{idx}\"\n # execute('SET', token_key, tokens)\n redisAI.setTensorInKey(token_key, tensor)\n execute('SADD',f'processed_docs_stage3_tokenized{hash_tag}', token_key)\n\ngb = GB()\ngb.foreach(parse_sentence)\ngb.count()\ngb.run('sentence:*',keyTypes=['hash'])" ]
[ [ "numpy.append" ] ]
sozuer53/BBC
[ "31bb128cb1e1a19db955fd673d67cf0e92bac3a4" ]
[ "Server/ChatBot/venv/Lib/site-packages/tensorflow/python/ops/gen_dataset_ops.py" ]
[ "\"\"\"Python wrappers around TensorFlow ops.\n\nThis file is MACHINE GENERATED! Do not edit.\n\"\"\"\n\nimport collections as _collections\n\nfrom tensorflow.python.eager import execute as _execute\nfrom tensorflow.python.eager import context as _context\nfrom tensorflow.python.eager import core as _core\nfrom tensorflow.python.framework import dtypes as _dtypes\nfrom tensorflow.python.framework import tensor_shape as _tensor_shape\n\nfrom tensorflow.core.framework import op_def_pb2 as _op_def_pb2\n# Needed to trigger the call to _set_call_cpp_shape_fn.\nfrom tensorflow.python.framework import common_shapes as _common_shapes\nfrom tensorflow.python.framework import op_def_registry as _op_def_registry\nfrom tensorflow.python.framework import ops as _ops\nfrom tensorflow.python.framework import op_def_library as _op_def_library\n\n\ndef batch_dataset(input_dataset, batch_size, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that batches `batch_size` elements from `input_dataset`.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n batch_size: A `Tensor` of type `int64`.\n A scalar representing the number of elements to accumulate in a\n batch.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'batch_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'batch_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"BatchDataset\", input_dataset=input_dataset, batch_size=batch_size,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64)\n _inputs_flat = [input_dataset, batch_size]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"BatchDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"BatchDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef cache_dataset(input_dataset, filename, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that caches elements from `input_dataset`.\n\n A CacheDataset will iterate over the input_dataset, and store tensors. If the\n cache already exists, the cache will be used. If the cache is inappropriate\n (e.g. cannot be opened, contains tensors of the wrong shape / size), an error\n will the returned when used.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n filename: A `Tensor` of type `string`.\n A path on the filesystem where we should cache the dataset. Note: this\n will be a directory.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'cache_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'cache_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"CacheDataset\", input_dataset=input_dataset, filename=filename,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n filename = _ops.convert_to_tensor(filename, _dtypes.string)\n _inputs_flat = [input_dataset, filename]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"CacheDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"CacheDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef concatenate_dataset(input_dataset, another_dataset, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that concatenates `input_dataset` with `another_dataset`.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n another_dataset: A `Tensor` of type `variant`.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'concatenate_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'concatenate_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"ConcatenateDataset\", input_dataset=input_dataset,\n another_dataset=another_dataset, output_types=output_types,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n another_dataset = _ops.convert_to_tensor(another_dataset, _dtypes.variant)\n _inputs_flat = [input_dataset, another_dataset]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"ConcatenateDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"ConcatenateDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef dense_to_sparse_batch_dataset(input_dataset, batch_size, row_shape, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that yields a SparseTensor for each element of the input.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n A handle to an input dataset. Must have a single component.\n batch_size: A `Tensor` of type `int64`.\n A scalar representing the number of elements to accumulate in a\n batch.\n row_shape: A `Tensor` of type `int64`.\n A vector representing the dense shape of each row in the produced\n SparseTensor. The shape may be partially specified, using `-1` to indicate\n that a particular dimension should use the maximum size of all batch elements.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'dense_to_sparse_batch_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'dense_to_sparse_batch_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"DenseToSparseBatchDataset\", input_dataset=input_dataset,\n batch_size=batch_size, row_shape=row_shape, output_types=output_types,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64)\n row_shape = _ops.convert_to_tensor(row_shape, _dtypes.int64)\n _inputs_flat = [input_dataset, batch_size, row_shape]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"DenseToSparseBatchDataset\", 1,\n inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,\n name=name)\n _execute.record_gradient(\n \"DenseToSparseBatchDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef filter_dataset(input_dataset, other_arguments, predicate, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset containing elements of `input_dataset` matching `predicate`.\n\n The `predicate` function must return a scalar boolean and accept the\n following arguments:\n\n * One tensor for each component of an element of `input_dataset`.\n * One tensor for each value in `other_arguments`.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n other_arguments: A list of `Tensor` objects.\n A list of tensors, typically values that were captured when\n building a closure for `predicate`.\n predicate: A function decorated with @Defun.\n A function returning a scalar boolean.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'filter_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'filter_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"FilterDataset\", input_dataset=input_dataset,\n other_arguments=other_arguments, predicate=predicate,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"predicate\", _op.get_attr(\"predicate\"), \"Targuments\",\n _op.get_attr(\"Targuments\"), \"output_types\",\n _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, _ctx)\n _attr_Targuments = [_t.as_datatype_enum for _t in _attr_Targuments]\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n _inputs_flat = [input_dataset] + list(other_arguments)\n _attrs = (\"predicate\", predicate, \"Targuments\", _attr_Targuments,\n \"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"FilterDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"FilterDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef fixed_length_record_dataset(filenames, header_bytes, record_bytes, footer_bytes, buffer_size, name=None):\n r\"\"\"Creates a dataset that emits the records from one or more binary files.\n\n Args:\n filenames: A `Tensor` of type `string`.\n A scalar or a vector containing the name(s) of the file(s) to be\n read.\n header_bytes: A `Tensor` of type `int64`.\n A scalar representing the number of bytes to skip at the\n beginning of a file.\n record_bytes: A `Tensor` of type `int64`.\n A scalar representing the number of bytes in each record.\n footer_bytes: A `Tensor` of type `int64`.\n A scalar representing the number of bytes to skip at the end\n of a file.\n buffer_size: A `Tensor` of type `int64`.\n A scalar representing the number of bytes to buffer. Must be > 0.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"FixedLengthRecordDataset\", filenames=filenames,\n header_bytes=header_bytes, record_bytes=record_bytes,\n footer_bytes=footer_bytes, buffer_size=buffer_size, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = None\n else:\n filenames = _ops.convert_to_tensor(filenames, _dtypes.string)\n header_bytes = _ops.convert_to_tensor(header_bytes, _dtypes.int64)\n record_bytes = _ops.convert_to_tensor(record_bytes, _dtypes.int64)\n footer_bytes = _ops.convert_to_tensor(footer_bytes, _dtypes.int64)\n buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64)\n _inputs_flat = [filenames, header_bytes, record_bytes, footer_bytes, buffer_size]\n _attrs = None\n _result = _execute.execute(b\"FixedLengthRecordDataset\", 1,\n inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,\n name=name)\n _execute.record_gradient(\n \"FixedLengthRecordDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef flat_map_dataset(input_dataset, other_arguments, f, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that applies `f` to the outputs of `input_dataset`.\n\n Unlike MapDataset, the `f` in FlatMapDataset is expected to return a\n Dataset variant, and FlatMapDataset will flatten successive results\n into a single Dataset.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n other_arguments: A list of `Tensor` objects.\n f: A function decorated with @Defun.\n A function mapping elements of `input_dataset`, concatenated with\n `other_arguments`, to a Dataset variant that contains elements matching\n `output_types` and `output_shapes`.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'flat_map_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'flat_map_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"FlatMapDataset\", input_dataset=input_dataset,\n other_arguments=other_arguments, f=f, output_types=output_types,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"f\", _op.get_attr(\"f\"), \"Targuments\",\n _op.get_attr(\"Targuments\"), \"output_types\",\n _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, _ctx)\n _attr_Targuments = [_t.as_datatype_enum for _t in _attr_Targuments]\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n _inputs_flat = [input_dataset] + list(other_arguments)\n _attrs = (\"f\", f, \"Targuments\", _attr_Targuments, \"output_types\",\n output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"FlatMapDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"FlatMapDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef group_by_window_dataset(input_dataset, key_func_other_arguments, reduce_func_other_arguments, window_size_func_other_arguments, key_func, reduce_func, window_size_func, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that computes a windowed group-by on `input_dataset`.\n\n // TODO(mrry): Support non-int64 keys.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n key_func_other_arguments: A list of `Tensor` objects.\n reduce_func_other_arguments: A list of `Tensor` objects.\n window_size_func_other_arguments: A list of `Tensor` objects.\n key_func: A function decorated with @Defun.\n A function mapping an element of `input_dataset`, concatenated\n with `key_func_other_arguments` to a scalar value of type DT_INT64.\n reduce_func: A function decorated with @Defun.\n window_size_func: A function decorated with @Defun.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'group_by_window_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'group_by_window_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"GroupByWindowDataset\", input_dataset=input_dataset,\n key_func_other_arguments=key_func_other_arguments,\n reduce_func_other_arguments=reduce_func_other_arguments,\n window_size_func_other_arguments=window_size_func_other_arguments,\n key_func=key_func, reduce_func=reduce_func,\n window_size_func=window_size_func, output_types=output_types,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"key_func\", _op.get_attr(\"key_func\"), \"reduce_func\",\n _op.get_attr(\"reduce_func\"), \"window_size_func\",\n _op.get_attr(\"window_size_func\"), \"Tkey_func_other_arguments\",\n _op.get_attr(\"Tkey_func_other_arguments\"),\n \"Treduce_func_other_arguments\",\n _op.get_attr(\"Treduce_func_other_arguments\"),\n \"Twindow_size_func_other_arguments\",\n _op.get_attr(\"Twindow_size_func_other_arguments\"),\n \"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n _attr_Tkey_func_other_arguments, key_func_other_arguments = _execute.convert_to_mixed_eager_tensors(key_func_other_arguments, _ctx)\n _attr_Tkey_func_other_arguments = [_t.as_datatype_enum for _t in _attr_Tkey_func_other_arguments]\n _attr_Treduce_func_other_arguments, reduce_func_other_arguments = _execute.convert_to_mixed_eager_tensors(reduce_func_other_arguments, _ctx)\n _attr_Treduce_func_other_arguments = [_t.as_datatype_enum for _t in _attr_Treduce_func_other_arguments]\n _attr_Twindow_size_func_other_arguments, window_size_func_other_arguments = _execute.convert_to_mixed_eager_tensors(window_size_func_other_arguments, _ctx)\n _attr_Twindow_size_func_other_arguments = [_t.as_datatype_enum for _t in _attr_Twindow_size_func_other_arguments]\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n _inputs_flat = [input_dataset] + list(key_func_other_arguments) + list(reduce_func_other_arguments) + list(window_size_func_other_arguments)\n _attrs = (\"key_func\", key_func, \"reduce_func\", reduce_func,\n \"window_size_func\", window_size_func,\n \"Tkey_func_other_arguments\", _attr_Tkey_func_other_arguments,\n \"Treduce_func_other_arguments\",\n _attr_Treduce_func_other_arguments,\n \"Twindow_size_func_other_arguments\",\n _attr_Twindow_size_func_other_arguments, \"output_types\",\n output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"GroupByWindowDataset\", 1,\n inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,\n name=name)\n _execute.record_gradient(\n \"GroupByWindowDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef ignore_errors_dataset(input_dataset, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that contains the elements of `input_dataset` ignoring errors.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'ignore_errors_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'ignore_errors_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"IgnoreErrorsDataset\", input_dataset=input_dataset,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n _inputs_flat = [input_dataset]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"IgnoreErrorsDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"IgnoreErrorsDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef interleave_dataset(input_dataset, other_arguments, cycle_length, block_length, f, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that applies `f` to the outputs of `input_dataset`.\n\n Unlike MapDataset, the `f` in InterleaveDataset is expected to return\n a Dataset variant, and InterleaveDataset will flatten successive\n results into a single Dataset. Unlike FlatMapDataset,\n InterleaveDataset will interleave sequences of up to `block_length`\n consecutive elements from `cycle_length` input elements.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n other_arguments: A list of `Tensor` objects.\n cycle_length: A `Tensor` of type `int64`.\n block_length: A `Tensor` of type `int64`.\n f: A function decorated with @Defun.\n A function mapping elements of `input_dataset`, concatenated with\n `other_arguments`, to a Dataset variant that contains elements matching\n `output_types` and `output_shapes`.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'interleave_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'interleave_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"InterleaveDataset\", input_dataset=input_dataset,\n other_arguments=other_arguments, cycle_length=cycle_length,\n block_length=block_length, f=f, output_types=output_types,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"f\", _op.get_attr(\"f\"), \"Targuments\",\n _op.get_attr(\"Targuments\"), \"output_types\",\n _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, _ctx)\n _attr_Targuments = [_t.as_datatype_enum for _t in _attr_Targuments]\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n cycle_length = _ops.convert_to_tensor(cycle_length, _dtypes.int64)\n block_length = _ops.convert_to_tensor(block_length, _dtypes.int64)\n _inputs_flat = [input_dataset] + list(other_arguments) + [cycle_length, block_length]\n _attrs = (\"f\", f, \"Targuments\", _attr_Targuments, \"output_types\",\n output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"InterleaveDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"InterleaveDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef iterator(shared_name, container, output_types, output_shapes, name=None):\n r\"\"\"A container for an iterator resource.\n\n Args:\n shared_name: A `string`.\n container: A `string`.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `resource`.\n A handle to the iterator that can be passed to a \"MakeIterator\"\n or \"IteratorGetNext\" op.\n \"\"\"\n shared_name = _execute.make_str(shared_name, \"shared_name\")\n container = _execute.make_str(container, \"container\")\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'iterator' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'iterator' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"Iterator\", shared_name=shared_name, container=container,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"shared_name\", _op.get_attr(\"shared_name\"), \"container\",\n _op.get_attr(\"container\"), \"output_types\",\n _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n _inputs_flat = []\n _attrs = (\"shared_name\", shared_name, \"container\", container,\n \"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"Iterator\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"Iterator\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef iterator_from_string_handle(string_handle, output_types=[], output_shapes=[], name=None):\n r\"\"\"Converts the given string representing a handle to an iterator to a resource.\n\n Args:\n string_handle: A `Tensor` of type `string`.\n A string representation of the given handle.\n output_types: An optional list of `tf.DTypes`. Defaults to `[]`.\n If specified, defines the type of each tuple component in an\n element produced by the resulting iterator.\n output_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`.\n If specified, defines the shape of each tuple component in an\n element produced by the resulting iterator.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `resource`. A handle to an iterator resource.\n \"\"\"\n if output_types is None:\n output_types = []\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'iterator_from_string_handle' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if output_shapes is None:\n output_shapes = []\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'iterator_from_string_handle' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"IteratorFromStringHandle\", string_handle=string_handle,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n string_handle = _ops.convert_to_tensor(string_handle, _dtypes.string)\n _inputs_flat = [string_handle]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"IteratorFromStringHandle\", 1,\n inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,\n name=name)\n _execute.record_gradient(\n \"IteratorFromStringHandle\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef iterator_get_next(iterator, output_types, output_shapes, name=None):\n r\"\"\"Gets the next output from the given iterator.\n\n Args:\n iterator: A `Tensor` of type `resource`.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A list of `Tensor` objects of type `output_types`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'iterator_get_next' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'iterator_get_next' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"IteratorGetNext\", iterator=iterator, output_types=output_types,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n if not _result:\n return _op\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n iterator = _ops.convert_to_tensor(iterator, _dtypes.resource)\n _inputs_flat = [iterator]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"IteratorGetNext\", len(output_types),\n inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,\n name=name)\n _execute.record_gradient(\n \"IteratorGetNext\", _inputs_flat, _attrs, _result, name)\n return _result\n\n\ndef iterator_to_string_handle(resource_handle, name=None):\n r\"\"\"Converts the given `resource_handle` representing an iterator to a string.\n\n Args:\n resource_handle: A `Tensor` of type `resource`.\n A handle to an iterator resource.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `string`. A string representation of the given handle.\n \"\"\"\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"IteratorToStringHandle\", resource_handle=resource_handle, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = None\n else:\n resource_handle = _ops.convert_to_tensor(resource_handle, _dtypes.resource)\n _inputs_flat = [resource_handle]\n _attrs = None\n _result = _execute.execute(b\"IteratorToStringHandle\", 1,\n inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,\n name=name)\n _execute.record_gradient(\n \"IteratorToStringHandle\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef make_iterator(dataset, iterator, name=None):\n r\"\"\"Makes a new iterator from the given `dataset` and stores it in `iterator`.\n\n This operation may be executed multiple times. Each execution will reset the\n iterator in `iterator` to the first element of `dataset`.\n\n Args:\n dataset: A `Tensor` of type `variant`.\n iterator: A `Tensor` of type `resource`.\n name: A name for the operation (optional).\n\n Returns:\n The created Operation.\n \"\"\"\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"MakeIterator\", dataset=dataset, iterator=iterator, name=name)\n return _op\n else:\n dataset = _ops.convert_to_tensor(dataset, _dtypes.variant)\n iterator = _ops.convert_to_tensor(iterator, _dtypes.resource)\n _inputs_flat = [dataset, iterator]\n _attrs = None\n _result = _execute.execute(b\"MakeIterator\", 0, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n return _result\n\n\ndef map_dataset(input_dataset, other_arguments, f, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that applies `f` to the outputs of `input_dataset`.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n other_arguments: A list of `Tensor` objects.\n f: A function decorated with @Defun.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'map_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'map_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"MapDataset\", input_dataset=input_dataset,\n other_arguments=other_arguments, f=f, output_types=output_types,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"f\", _op.get_attr(\"f\"), \"Targuments\",\n _op.get_attr(\"Targuments\"), \"output_types\",\n _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, _ctx)\n _attr_Targuments = [_t.as_datatype_enum for _t in _attr_Targuments]\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n _inputs_flat = [input_dataset] + list(other_arguments)\n _attrs = (\"f\", f, \"Targuments\", _attr_Targuments, \"output_types\",\n output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"MapDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"MapDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef one_shot_iterator(dataset_factory, output_types, output_shapes, container=\"\", shared_name=\"\", name=None):\n r\"\"\"Makes a \"one-shot\" iterator that can be iterated only once.\n\n A one-shot iterator bundles the logic for defining the dataset and\n the state of the iterator in a single op, which allows simple input\n pipelines to be defined without an additional initialization\n (\"MakeIterator\") step.\n\n One-shot iterators have the following limitations:\n\n * They do not support parameterization: all logic for creating the underlying\n dataset must be bundled in the `dataset_factory` function.\n * They are not resettable. Once a one-shot iterator reaches the end of its\n underlying dataset, subsequent \"IteratorGetNext\" operations on that\n iterator will always produce an `OutOfRange` error.\n\n For greater flexibility, use \"Iterator\" and \"MakeIterator\" to define\n an iterator using an arbitrary subgraph, which may capture tensors\n (including fed values) as parameters, and which may be reset multiple\n times by rerunning \"MakeIterator\".\n\n Args:\n dataset_factory: A function decorated with @Defun.\n A function of type `() -> DT_VARIANT`, where the returned\n DT_VARIANT is a dataset.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n container: An optional `string`. Defaults to `\"\"`.\n shared_name: An optional `string`. Defaults to `\"\"`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `resource`.\n A handle to the iterator that can be passed to an \"IteratorGetNext\"\n op.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'one_shot_iterator' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'one_shot_iterator' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n if container is None:\n container = \"\"\n container = _execute.make_str(container, \"container\")\n if shared_name is None:\n shared_name = \"\"\n shared_name = _execute.make_str(shared_name, \"shared_name\")\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"OneShotIterator\", dataset_factory=dataset_factory,\n output_types=output_types, output_shapes=output_shapes,\n container=container, shared_name=shared_name, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"dataset_factory\", _op.get_attr(\"dataset_factory\"),\n \"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"), \"container\",\n _op.get_attr(\"container\"), \"shared_name\",\n _op.get_attr(\"shared_name\"))\n else:\n _inputs_flat = []\n _attrs = (\"dataset_factory\", dataset_factory, \"output_types\",\n output_types, \"output_shapes\", output_shapes, \"container\",\n container, \"shared_name\", shared_name)\n _result = _execute.execute(b\"OneShotIterator\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"OneShotIterator\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef padded_batch_dataset(input_dataset, batch_size, padded_shapes, padding_values, output_shapes, name=None):\n r\"\"\"Creates a dataset that batches and pads `batch_size` elements from the input.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n batch_size: A `Tensor` of type `int64`.\n A scalar representing the number of elements to accumulate in a\n batch.\n padded_shapes: A list of at least 1 `Tensor` objects with type `int64`.\n A list of int64 tensors representing the desired padded shapes\n of the corresponding output components. These shapes may be partially\n specified, using `-1` to indicate that a particular dimension should be\n padded to the maximum size of all batch elements.\n padding_values: A list of `Tensor` objects.\n A list of scalars containing the padding value to use for\n each of the outputs.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(padded_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'padded_shapes' argument to \"\n \"'padded_batch_dataset' Op, not %r.\" % padded_shapes)\n _attr_N = len(padded_shapes)\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'padded_batch_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"PaddedBatchDataset\", input_dataset=input_dataset,\n batch_size=batch_size, padded_shapes=padded_shapes,\n padding_values=padding_values, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"Toutput_types\", _op.get_attr(\"Toutput_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"), \"N\", _op.get_attr(\"N\"))\n else:\n _attr_Toutput_types, padding_values = _execute.convert_to_mixed_eager_tensors(padding_values, _ctx)\n _attr_Toutput_types = [_t.as_datatype_enum for _t in _attr_Toutput_types]\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64)\n padded_shapes = _ops.convert_n_to_tensor(padded_shapes, _dtypes.int64)\n _inputs_flat = [input_dataset, batch_size] + list(padded_shapes) + list(padding_values)\n _attrs = (\"Toutput_types\", _attr_Toutput_types, \"output_shapes\",\n output_shapes, \"N\", _attr_N)\n _result = _execute.execute(b\"PaddedBatchDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"PaddedBatchDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef parallel_map_dataset(input_dataset, other_arguments, num_parallel_calls, f, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that applies `f` to the outputs of `input_dataset`.\n\n Unlike a \"MapDataset\", which applies `f` sequentially, this dataset invokes up\n to `num_parallel_calls` copies of `f` in parallel.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n other_arguments: A list of `Tensor` objects.\n num_parallel_calls: A `Tensor` of type `int32`.\n The number of concurrent invocations of `f` that process\n elements from `input_dataset` in parallel.\n f: A function decorated with @Defun.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'parallel_map_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'parallel_map_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"ParallelMapDataset\", input_dataset=input_dataset,\n other_arguments=other_arguments,\n num_parallel_calls=num_parallel_calls, f=f, output_types=output_types,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"f\", _op.get_attr(\"f\"), \"Targuments\",\n _op.get_attr(\"Targuments\"), \"output_types\",\n _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, _ctx)\n _attr_Targuments = [_t.as_datatype_enum for _t in _attr_Targuments]\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int32)\n _inputs_flat = [input_dataset] + list(other_arguments) + [num_parallel_calls]\n _attrs = (\"f\", f, \"Targuments\", _attr_Targuments, \"output_types\",\n output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"ParallelMapDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"ParallelMapDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef prefetch_dataset(input_dataset, buffer_size, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that asynchronously prefetches elements from `input_dataset`.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n buffer_size: A `Tensor` of type `int64`.\n The maximum number of elements to buffer in an iterator over\n this dataset.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'prefetch_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'prefetch_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"PrefetchDataset\", input_dataset=input_dataset,\n buffer_size=buffer_size, output_types=output_types,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64)\n _inputs_flat = [input_dataset, buffer_size]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"PrefetchDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"PrefetchDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef range_dataset(start, stop, step, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset with a range of values. Corresponds to python's xrange.\n\n Args:\n start: A `Tensor` of type `int64`.\n corresponds to start in python's xrange().\n stop: A `Tensor` of type `int64`.\n corresponds to stop in python's xrange().\n step: A `Tensor` of type `int64`.\n corresponds to step in python's xrange().\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'range_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'range_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"RangeDataset\", start=start, stop=stop, step=step,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n start = _ops.convert_to_tensor(start, _dtypes.int64)\n stop = _ops.convert_to_tensor(stop, _dtypes.int64)\n step = _ops.convert_to_tensor(step, _dtypes.int64)\n _inputs_flat = [start, stop, step]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"RangeDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"RangeDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef repeat_dataset(input_dataset, count, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that emits the outputs of `input_dataset` `count` times.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n count: A `Tensor` of type `int64`.\n A scalar representing the number of times that `input_dataset` should\n be repeated. A value of `-1` indicates that it should be repeated infinitely.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'repeat_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'repeat_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"RepeatDataset\", input_dataset=input_dataset, count=count,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n count = _ops.convert_to_tensor(count, _dtypes.int64)\n _inputs_flat = [input_dataset, count]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"RepeatDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"RepeatDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef restore_iterator(iterator, path, name=None):\n r\"\"\"Restores the state of the `iterator` from the checkpoint saved at `path` using \"SaveIterator\".\n\n Args:\n iterator: A `Tensor` of type `resource`.\n path: A `Tensor` of type `string`.\n name: A name for the operation (optional).\n\n Returns:\n The created Operation.\n \"\"\"\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"RestoreIterator\", iterator=iterator, path=path, name=name)\n return _op\n else:\n iterator = _ops.convert_to_tensor(iterator, _dtypes.resource)\n path = _ops.convert_to_tensor(path, _dtypes.string)\n _inputs_flat = [iterator, path]\n _attrs = None\n _result = _execute.execute(b\"RestoreIterator\", 0, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n return _result\n\n\ndef save_iterator(iterator, path, name=None):\n r\"\"\"Saves the state of the `iterator` at `path`.\n\n This state can be restored using \"RestoreIterator\".\n\n Args:\n iterator: A `Tensor` of type `resource`.\n path: A `Tensor` of type `string`.\n name: A name for the operation (optional).\n\n Returns:\n The created Operation.\n \"\"\"\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"SaveIterator\", iterator=iterator, path=path, name=name)\n return _op\n else:\n iterator = _ops.convert_to_tensor(iterator, _dtypes.resource)\n path = _ops.convert_to_tensor(path, _dtypes.string)\n _inputs_flat = [iterator, path]\n _attrs = None\n _result = _execute.execute(b\"SaveIterator\", 0, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n return _result\n\n\ndef shuffle_dataset(input_dataset, buffer_size, seed, seed2, output_types, output_shapes, reshuffle_each_iteration=True, name=None):\n r\"\"\"Creates a dataset that shuffles elements from `input_dataset` pseudorandomly.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n buffer_size: A `Tensor` of type `int64`.\n The number of output elements to buffer in an iterator over\n this dataset. Compare with the `min_after_dequeue` attr when creating a\n `RandomShuffleQueue`.\n seed: A `Tensor` of type `int64`.\n A scalar seed for the random number generator. If either seed or\n seed2 is set to be non-zero, the random number generator is seeded\n by the given seed. Otherwise, a random seed is used.\n seed2: A `Tensor` of type `int64`.\n A second scalar seed to avoid seed collision.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n reshuffle_each_iteration: An optional `bool`. Defaults to `True`.\n If true, each iterator over this dataset will be given\n a different pseudorandomly generated seed, based on a sequence seeded by the\n `seed` and `seed2` inputs. If false, each iterator will be given the same\n seed, and repeated iteration over this dataset will yield the exact same\n sequence of results.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'shuffle_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'shuffle_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n if reshuffle_each_iteration is None:\n reshuffle_each_iteration = True\n reshuffle_each_iteration = _execute.make_bool(reshuffle_each_iteration, \"reshuffle_each_iteration\")\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"ShuffleDataset\", input_dataset=input_dataset,\n buffer_size=buffer_size, seed=seed, seed2=seed2,\n output_types=output_types, output_shapes=output_shapes,\n reshuffle_each_iteration=reshuffle_each_iteration, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"reshuffle_each_iteration\",\n _op.get_attr(\"reshuffle_each_iteration\"), \"output_types\",\n _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64)\n seed = _ops.convert_to_tensor(seed, _dtypes.int64)\n seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64)\n _inputs_flat = [input_dataset, buffer_size, seed, seed2]\n _attrs = (\"reshuffle_each_iteration\", reshuffle_each_iteration,\n \"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"ShuffleDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"ShuffleDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef skip_dataset(input_dataset, count, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that skips `count` elements from the `input_dataset`.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n count: A `Tensor` of type `int64`.\n A scalar representing the number of elements from the `input_dataset`\n that should be skipped. If count is -1, skips everything.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'skip_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'skip_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"SkipDataset\", input_dataset=input_dataset, count=count,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n count = _ops.convert_to_tensor(count, _dtypes.int64)\n _inputs_flat = [input_dataset, count]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"SkipDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"SkipDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef sloppy_interleave_dataset(input_dataset, other_arguments, cycle_length, block_length, f, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that applies `f` to the outputs of `input_dataset`.\n\n The resulting dataset is similar to the `InterleaveDataset`, with the exception\n that if retrieving the next value from a dataset would cause the requester to\n block, it will skip that input dataset. This dataset is especially useful\n when loading data from a variable-latency datastores (e.g. HDFS, GCS), as it\n allows the training step to proceed so long as some data is available.\n\n !! WARNING !! This dataset is not deterministic!\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n other_arguments: A list of `Tensor` objects.\n cycle_length: A `Tensor` of type `int64`.\n block_length: A `Tensor` of type `int64`.\n f: A function decorated with @Defun.\n A function mapping elements of `input_dataset`, concatenated with\n `other_arguments`, to a Dataset variant that contains elements matching\n `output_types` and `output_shapes`.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'sloppy_interleave_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'sloppy_interleave_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"SloppyInterleaveDataset\", input_dataset=input_dataset,\n other_arguments=other_arguments, cycle_length=cycle_length,\n block_length=block_length, f=f, output_types=output_types,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"f\", _op.get_attr(\"f\"), \"Targuments\",\n _op.get_attr(\"Targuments\"), \"output_types\",\n _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, _ctx)\n _attr_Targuments = [_t.as_datatype_enum for _t in _attr_Targuments]\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n cycle_length = _ops.convert_to_tensor(cycle_length, _dtypes.int64)\n block_length = _ops.convert_to_tensor(block_length, _dtypes.int64)\n _inputs_flat = [input_dataset] + list(other_arguments) + [cycle_length, block_length]\n _attrs = (\"f\", f, \"Targuments\", _attr_Targuments, \"output_types\",\n output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"SloppyInterleaveDataset\", 1,\n inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,\n name=name)\n _execute.record_gradient(\n \"SloppyInterleaveDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef sparse_tensor_slice_dataset(indices, values, dense_shape, name=None):\n r\"\"\"Creates a dataset that splits a SparseTensor into elements row-wise.\n\n Args:\n indices: A `Tensor` of type `int64`.\n values: A `Tensor`.\n dense_shape: A `Tensor` of type `int64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"SparseTensorSliceDataset\", indices=indices, values=values,\n dense_shape=dense_shape, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"Tvalues\", _op.get_attr(\"Tvalues\"))\n else:\n _attr_Tvalues, (values,) = _execute.args_to_matching_eager([values], _ctx)\n _attr_Tvalues = _attr_Tvalues.as_datatype_enum\n indices = _ops.convert_to_tensor(indices, _dtypes.int64)\n dense_shape = _ops.convert_to_tensor(dense_shape, _dtypes.int64)\n _inputs_flat = [indices, values, dense_shape]\n _attrs = (\"Tvalues\", _attr_Tvalues)\n _result = _execute.execute(b\"SparseTensorSliceDataset\", 1,\n inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,\n name=name)\n _execute.record_gradient(\n \"SparseTensorSliceDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef sql_dataset(driver_name, data_source_name, query, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that executes a SQL query and emits rows of the result set.\n\n Args:\n driver_name: A `Tensor` of type `string`.\n The database type. Currently, the only supported type is 'sqlite'.\n data_source_name: A `Tensor` of type `string`.\n A connection string to connect to the database.\n query: A `Tensor` of type `string`. A SQL query to execute.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'sql_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'sql_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"SqlDataset\", driver_name=driver_name,\n data_source_name=data_source_name, query=query,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n driver_name = _ops.convert_to_tensor(driver_name, _dtypes.string)\n data_source_name = _ops.convert_to_tensor(data_source_name, _dtypes.string)\n query = _ops.convert_to_tensor(query, _dtypes.string)\n _inputs_flat = [driver_name, data_source_name, query]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"SqlDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"SqlDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef tf_record_dataset(filenames, compression_type, buffer_size, name=None):\n r\"\"\"Creates a dataset that emits the records from one or more TFRecord files.\n\n Args:\n filenames: A `Tensor` of type `string`.\n A scalar or vector containing the name(s) of the file(s) to be\n read.\n compression_type: A `Tensor` of type `string`.\n A scalar containing either (i) the empty string (no\n compression), (ii) \"ZLIB\", or (iii) \"GZIP\".\n buffer_size: A `Tensor` of type `int64`.\n A scalar representing the number of bytes to buffer. A value of\n 0 means no buffering will be performed.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"TFRecordDataset\", filenames=filenames,\n compression_type=compression_type, buffer_size=buffer_size, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = None\n else:\n filenames = _ops.convert_to_tensor(filenames, _dtypes.string)\n compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string)\n buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64)\n _inputs_flat = [filenames, compression_type, buffer_size]\n _attrs = None\n _result = _execute.execute(b\"TFRecordDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"TFRecordDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef take_dataset(input_dataset, count, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that contains `count` elements from the `input_dataset`.\n\n Args:\n input_dataset: A `Tensor` of type `variant`.\n count: A `Tensor` of type `int64`.\n A scalar representing the number of elements from the `input_dataset`\n that should be taken. A value of `-1` indicates that all of `input_dataset`\n is taken.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'take_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'take_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"TakeDataset\", input_dataset=input_dataset, count=count,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant)\n count = _ops.convert_to_tensor(count, _dtypes.int64)\n _inputs_flat = [input_dataset, count]\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes)\n _result = _execute.execute(b\"TakeDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"TakeDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef tensor_dataset(components, output_shapes, name=None):\n r\"\"\"Creates a dataset that emits `components` as a tuple of tensors once.\n\n Args:\n components: A list of `Tensor` objects.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'tensor_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"TensorDataset\", components=components, output_shapes=output_shapes,\n name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"Toutput_types\", _op.get_attr(\"Toutput_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n _attr_Toutput_types, components = _execute.convert_to_mixed_eager_tensors(components, _ctx)\n _attr_Toutput_types = [_t.as_datatype_enum for _t in _attr_Toutput_types]\n _inputs_flat = list(components)\n _attrs = (\"Toutput_types\", _attr_Toutput_types, \"output_shapes\",\n output_shapes)\n _result = _execute.execute(b\"TensorDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"TensorDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef tensor_slice_dataset(components, output_shapes, name=None):\n r\"\"\"Creates a dataset that emits each dim-0 slice of `components` once.\n\n Args:\n components: A list of `Tensor` objects.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'tensor_slice_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"TensorSliceDataset\", components=components,\n output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"Toutput_types\", _op.get_attr(\"Toutput_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"))\n else:\n _attr_Toutput_types, components = _execute.convert_to_mixed_eager_tensors(components, _ctx)\n _attr_Toutput_types = [_t.as_datatype_enum for _t in _attr_Toutput_types]\n _inputs_flat = list(components)\n _attrs = (\"Toutput_types\", _attr_Toutput_types, \"output_shapes\",\n output_shapes)\n _result = _execute.execute(b\"TensorSliceDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"TensorSliceDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef text_line_dataset(filenames, compression_type, buffer_size, name=None):\n r\"\"\"Creates a dataset that emits the lines of one or more text files.\n\n Args:\n filenames: A `Tensor` of type `string`.\n A scalar or a vector containing the name(s) of the file(s) to be\n read.\n compression_type: A `Tensor` of type `string`.\n A scalar containing either (i) the empty string (no\n compression), (ii) \"ZLIB\", or (iii) \"GZIP\".\n buffer_size: A `Tensor` of type `int64`.\n A scalar containing the number of bytes to buffer.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"TextLineDataset\", filenames=filenames,\n compression_type=compression_type, buffer_size=buffer_size, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = None\n else:\n filenames = _ops.convert_to_tensor(filenames, _dtypes.string)\n compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string)\n buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64)\n _inputs_flat = [filenames, compression_type, buffer_size]\n _attrs = None\n _result = _execute.execute(b\"TextLineDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"TextLineDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n\ndef zip_dataset(input_datasets, output_types, output_shapes, name=None):\n r\"\"\"Creates a dataset that zips together `input_datasets`.\n\n Args:\n input_datasets: A list of at least 1 `Tensor` objects with type `variant`.\n output_types: A list of `tf.DTypes` that has length `>= 1`.\n output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n if not isinstance(input_datasets, (list, tuple)):\n raise TypeError(\n \"Expected list for 'input_datasets' argument to \"\n \"'zip_dataset' Op, not %r.\" % input_datasets)\n _attr_N = len(input_datasets)\n if not isinstance(output_types, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_types' argument to \"\n \"'zip_dataset' Op, not %r.\" % output_types)\n output_types = [_execute.make_type(_t, \"output_types\") for _t in output_types]\n if not isinstance(output_shapes, (list, tuple)):\n raise TypeError(\n \"Expected list for 'output_shapes' argument to \"\n \"'zip_dataset' Op, not %r.\" % output_shapes)\n output_shapes = [_execute.make_shape(_s, \"output_shapes\") for _s in output_shapes]\n _ctx = _context.context()\n if _ctx.in_graph_mode():\n _, _, _op = _op_def_lib._apply_op_helper(\n \"ZipDataset\", input_datasets=input_datasets,\n output_types=output_types, output_shapes=output_shapes, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = (\"output_types\", _op.get_attr(\"output_types\"), \"output_shapes\",\n _op.get_attr(\"output_shapes\"), \"N\", _op.get_attr(\"N\"))\n else:\n input_datasets = _ops.convert_n_to_tensor(input_datasets, _dtypes.variant)\n _inputs_flat = list(input_datasets)\n _attrs = (\"output_types\", output_types, \"output_shapes\", output_shapes,\n \"N\", _attr_N)\n _result = _execute.execute(b\"ZipDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"ZipDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\ndef _InitOpDefLibrary(op_list_proto_bytes):\n op_list = _op_def_pb2.OpList()\n op_list.ParseFromString(op_list_proto_bytes)\n _op_def_registry.register_op_list(op_list)\n op_def_lib = _op_def_library.OpDefLibrary()\n op_def_lib.add_op_list(op_list)\n return op_def_lib\n# op {\n# name: \"BatchDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"batch_size\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"CacheDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"filename\"\n# type: DT_STRING\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"ConcatenateDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"another_dataset\"\n# type: DT_VARIANT\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"DenseToSparseBatchDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"batch_size\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"row_shape\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"FilterDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"other_arguments\"\n# type_list_attr: \"Targuments\"\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"predicate\"\n# type: \"func\"\n# }\n# attr {\n# name: \"Targuments\"\n# type: \"list(type)\"\n# has_minimum: true\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"FixedLengthRecordDataset\"\n# input_arg {\n# name: \"filenames\"\n# type: DT_STRING\n# }\n# input_arg {\n# name: \"header_bytes\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"record_bytes\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"footer_bytes\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"buffer_size\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"FlatMapDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"other_arguments\"\n# type_list_attr: \"Targuments\"\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"f\"\n# type: \"func\"\n# }\n# attr {\n# name: \"Targuments\"\n# type: \"list(type)\"\n# has_minimum: true\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"GroupByWindowDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"key_func_other_arguments\"\n# type_list_attr: \"Tkey_func_other_arguments\"\n# }\n# input_arg {\n# name: \"reduce_func_other_arguments\"\n# type_list_attr: \"Treduce_func_other_arguments\"\n# }\n# input_arg {\n# name: \"window_size_func_other_arguments\"\n# type_list_attr: \"Twindow_size_func_other_arguments\"\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"key_func\"\n# type: \"func\"\n# }\n# attr {\n# name: \"reduce_func\"\n# type: \"func\"\n# }\n# attr {\n# name: \"window_size_func\"\n# type: \"func\"\n# }\n# attr {\n# name: \"Tkey_func_other_arguments\"\n# type: \"list(type)\"\n# has_minimum: true\n# }\n# attr {\n# name: \"Treduce_func_other_arguments\"\n# type: \"list(type)\"\n# has_minimum: true\n# }\n# attr {\n# name: \"Twindow_size_func_other_arguments\"\n# type: \"list(type)\"\n# has_minimum: true\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"IgnoreErrorsDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"InterleaveDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"other_arguments\"\n# type_list_attr: \"Targuments\"\n# }\n# input_arg {\n# name: \"cycle_length\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"block_length\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"f\"\n# type: \"func\"\n# }\n# attr {\n# name: \"Targuments\"\n# type: \"list(type)\"\n# has_minimum: true\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"Iterator\"\n# output_arg {\n# name: \"handle\"\n# type: DT_RESOURCE\n# }\n# attr {\n# name: \"shared_name\"\n# type: \"string\"\n# }\n# attr {\n# name: \"container\"\n# type: \"string\"\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"IteratorFromStringHandle\"\n# input_arg {\n# name: \"string_handle\"\n# type: DT_STRING\n# }\n# output_arg {\n# name: \"resource_handle\"\n# type: DT_RESOURCE\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# default_value {\n# list {\n# }\n# }\n# has_minimum: true\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# default_value {\n# list {\n# }\n# }\n# has_minimum: true\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"IteratorGetNext\"\n# input_arg {\n# name: \"iterator\"\n# type: DT_RESOURCE\n# }\n# output_arg {\n# name: \"components\"\n# type_list_attr: \"output_types\"\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"IteratorToStringHandle\"\n# input_arg {\n# name: \"resource_handle\"\n# type: DT_RESOURCE\n# }\n# output_arg {\n# name: \"string_handle\"\n# type: DT_STRING\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"MakeIterator\"\n# input_arg {\n# name: \"dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"iterator\"\n# type: DT_RESOURCE\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"MapDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"other_arguments\"\n# type_list_attr: \"Targuments\"\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"f\"\n# type: \"func\"\n# }\n# attr {\n# name: \"Targuments\"\n# type: \"list(type)\"\n# has_minimum: true\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"OneShotIterator\"\n# output_arg {\n# name: \"handle\"\n# type: DT_RESOURCE\n# }\n# attr {\n# name: \"dataset_factory\"\n# type: \"func\"\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"container\"\n# type: \"string\"\n# default_value {\n# s: \"\"\n# }\n# }\n# attr {\n# name: \"shared_name\"\n# type: \"string\"\n# default_value {\n# s: \"\"\n# }\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"PaddedBatchDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"batch_size\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"padded_shapes\"\n# type: DT_INT64\n# number_attr: \"N\"\n# }\n# input_arg {\n# name: \"padding_values\"\n# type_list_attr: \"Toutput_types\"\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"Toutput_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"N\"\n# type: \"int\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"ParallelMapDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"other_arguments\"\n# type_list_attr: \"Targuments\"\n# }\n# input_arg {\n# name: \"num_parallel_calls\"\n# type: DT_INT32\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"f\"\n# type: \"func\"\n# }\n# attr {\n# name: \"Targuments\"\n# type: \"list(type)\"\n# has_minimum: true\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"PrefetchDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"buffer_size\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"RangeDataset\"\n# input_arg {\n# name: \"start\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"stop\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"step\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"RepeatDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"count\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"RestoreIterator\"\n# input_arg {\n# name: \"iterator\"\n# type: DT_RESOURCE\n# }\n# input_arg {\n# name: \"path\"\n# type: DT_STRING\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"SaveIterator\"\n# input_arg {\n# name: \"iterator\"\n# type: DT_RESOURCE\n# }\n# input_arg {\n# name: \"path\"\n# type: DT_STRING\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"ShuffleDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"buffer_size\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"seed\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"seed2\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"reshuffle_each_iteration\"\n# type: \"bool\"\n# default_value {\n# b: true\n# }\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"SkipDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"count\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"SloppyInterleaveDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"other_arguments\"\n# type_list_attr: \"Targuments\"\n# }\n# input_arg {\n# name: \"cycle_length\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"block_length\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"f\"\n# type: \"func\"\n# }\n# attr {\n# name: \"Targuments\"\n# type: \"list(type)\"\n# has_minimum: true\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"SparseTensorSliceDataset\"\n# input_arg {\n# name: \"indices\"\n# type: DT_INT64\n# }\n# input_arg {\n# name: \"values\"\n# type_attr: \"Tvalues\"\n# }\n# input_arg {\n# name: \"dense_shape\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"Tvalues\"\n# type: \"type\"\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"SqlDataset\"\n# input_arg {\n# name: \"driver_name\"\n# type: DT_STRING\n# }\n# input_arg {\n# name: \"data_source_name\"\n# type: DT_STRING\n# }\n# input_arg {\n# name: \"query\"\n# type: DT_STRING\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"TFRecordDataset\"\n# input_arg {\n# name: \"filenames\"\n# type: DT_STRING\n# }\n# input_arg {\n# name: \"compression_type\"\n# type: DT_STRING\n# }\n# input_arg {\n# name: \"buffer_size\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"TakeDataset\"\n# input_arg {\n# name: \"input_dataset\"\n# type: DT_VARIANT\n# }\n# input_arg {\n# name: \"count\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n# op {\n# name: \"TensorDataset\"\n# input_arg {\n# name: \"components\"\n# type_list_attr: \"Toutput_types\"\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"Toutput_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"TensorSliceDataset\"\n# input_arg {\n# name: \"components\"\n# type_list_attr: \"Toutput_types\"\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"Toutput_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"TextLineDataset\"\n# input_arg {\n# name: \"filenames\"\n# type: DT_STRING\n# }\n# input_arg {\n# name: \"compression_type\"\n# type: DT_STRING\n# }\n# input_arg {\n# name: \"buffer_size\"\n# type: DT_INT64\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# is_stateful: true\n# }\n# op {\n# name: \"ZipDataset\"\n# input_arg {\n# name: \"input_datasets\"\n# type: DT_VARIANT\n# number_attr: \"N\"\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# attr {\n# name: \"output_types\"\n# type: \"list(type)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"output_shapes\"\n# type: \"list(shape)\"\n# has_minimum: true\n# minimum: 1\n# }\n# attr {\n# name: \"N\"\n# type: \"int\"\n# has_minimum: true\n# minimum: 1\n# }\n# }\n_op_def_lib = _InitOpDefLibrary(b\"\\n\\177\\n\\014BatchDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\016\\n\\nbatch_size\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n}\\n\\014CacheDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\014\\n\\010filename\\030\\007\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n\\212\\001\\n\\022ConcatenateDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\023\\n\\017another_dataset\\030\\025\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n\\233\\001\\n\\031DenseToSparseBatchDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\016\\n\\nbatch_size\\030\\t\\022\\r\\n\\trow_shape\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n\\276\\001\\n\\rFilterDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\035\\n\\017other_arguments2\\nTarguments\\032\\n\\n\\006handle\\030\\025\\\"\\021\\n\\tpredicate\\022\\004func\\\"\\032\\n\\nTarguments\\022\\nlist(type)(\\001\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n\\177\\n\\030FixedLengthRecordDataset\\022\\r\\n\\tfilenames\\030\\007\\022\\020\\n\\014header_bytes\\030\\t\\022\\020\\n\\014record_bytes\\030\\t\\022\\020\\n\\014footer_bytes\\030\\t\\022\\017\\n\\013buffer_size\\030\\t\\032\\n\\n\\006handle\\030\\025\\210\\001\\001\\n\\267\\001\\n\\016FlatMapDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\035\\n\\017other_arguments2\\nTarguments\\032\\n\\n\\006handle\\030\\025\\\"\\t\\n\\001f\\022\\004func\\\"\\032\\n\\nTarguments\\022\\nlist(type)(\\001\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n\\377\\003\\n\\024GroupByWindowDataset\\022\\021\\n\\rinput_dataset\\030\\025\\0225\\n\\030key_func_other_arguments2\\031Tkey_func_other_arguments\\022;\\n\\033reduce_func_other_arguments2\\034Treduce_func_other_arguments\\022E\\n window_size_func_other_arguments2!Twindow_size_func_other_arguments\\032\\n\\n\\006handle\\030\\025\\\"\\020\\n\\010key_func\\022\\004func\\\"\\023\\n\\013reduce_func\\022\\004func\\\"\\030\\n\\020window_size_func\\022\\004func\\\")\\n\\031Tkey_func_other_arguments\\022\\nlist(type)(\\001\\\",\\n\\034Treduce_func_other_arguments\\022\\nlist(type)(\\001\\\"1\\n!Twindow_size_func_other_arguments\\022\\nlist(type)(\\001\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\nv\\n\\023IgnoreErrorsDataset\\022\\021\\n\\rinput_dataset\\030\\025\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n\\336\\001\\n\\021InterleaveDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\035\\n\\017other_arguments2\\nTarguments\\022\\020\\n\\014cycle_length\\030\\t\\022\\020\\n\\014block_length\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"\\t\\n\\001f\\022\\004func\\\"\\032\\n\\nTarguments\\022\\nlist(type)(\\001\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n\\207\\001\\n\\010Iterator\\032\\n\\n\\006handle\\030\\024\\\"\\025\\n\\013shared_name\\022\\006string\\\"\\023\\n\\tcontainer\\022\\006string\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\210\\001\\001\\n\\213\\001\\n\\030IteratorFromStringHandle\\022\\021\\n\\rstring_handle\\030\\007\\032\\023\\n\\017resource_handle\\030\\024\\\" \\n\\014output_types\\022\\nlist(type)\\032\\002\\n\\000(\\001\\\"\\\"\\n\\routput_shapes\\022\\013list(shape)\\032\\002\\n\\000(\\001\\210\\001\\001\\n\\200\\001\\n\\017IteratorGetNext\\022\\014\\n\\010iterator\\030\\024\\032\\032\\n\\ncomponents2\\014output_types\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\210\\001\\001\\nC\\n\\026IteratorToStringHandle\\022\\023\\n\\017resource_handle\\030\\024\\032\\021\\n\\rstring_handle\\030\\007\\210\\001\\001\\n,\\n\\014MakeIterator\\022\\013\\n\\007dataset\\030\\025\\022\\014\\n\\010iterator\\030\\024\\210\\001\\001\\n\\263\\001\\n\\nMapDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\035\\n\\017other_arguments2\\nTarguments\\032\\n\\n\\006handle\\030\\025\\\"\\t\\n\\001f\\022\\004func\\\"\\032\\n\\nTarguments\\022\\nlist(type)(\\001\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n\\257\\001\\n\\017OneShotIterator\\032\\n\\n\\006handle\\030\\024\\\"\\027\\n\\017dataset_factory\\022\\004func\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\\"\\027\\n\\tcontainer\\022\\006string\\032\\002\\022\\000\\\"\\031\\n\\013shared_name\\022\\006string\\032\\002\\022\\000\\210\\001\\001\\n\\313\\001\\n\\022PaddedBatchDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\016\\n\\nbatch_size\\030\\t\\022\\024\\n\\rpadded_shapes\\030\\t*\\001N\\022\\037\\n\\016padding_values2\\rToutput_types\\032\\n\\n\\006handle\\030\\025\\\"\\037\\n\\rToutput_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\\"\\014\\n\\001N\\022\\003int(\\0010\\001\\n\\323\\001\\n\\022ParallelMapDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\035\\n\\017other_arguments2\\nTarguments\\022\\026\\n\\022num_parallel_calls\\030\\003\\032\\n\\n\\006handle\\030\\025\\\"\\t\\n\\001f\\022\\004func\\\"\\032\\n\\nTarguments\\022\\nlist(type)(\\001\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n\\203\\001\\n\\017PrefetchDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\017\\n\\013buffer_size\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n~\\n\\014RangeDataset\\022\\t\\n\\005start\\030\\t\\022\\010\\n\\004stop\\030\\t\\022\\010\\n\\004step\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\210\\001\\001\\n{\\n\\rRepeatDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\t\\n\\005count\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n,\\n\\017RestoreIterator\\022\\014\\n\\010iterator\\030\\024\\022\\010\\n\\004path\\030\\007\\210\\001\\001\\n)\\n\\014SaveIterator\\022\\014\\n\\010iterator\\030\\024\\022\\010\\n\\004path\\030\\007\\210\\001\\001\\n\\275\\001\\n\\016ShuffleDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\017\\n\\013buffer_size\\030\\t\\022\\010\\n\\004seed\\030\\t\\022\\t\\n\\005seed2\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"$\\n\\030reshuffle_each_iteration\\022\\004bool\\032\\002(\\001\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\ny\\n\\013SkipDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\t\\n\\005count\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n\\344\\001\\n\\027SloppyInterleaveDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\035\\n\\017other_arguments2\\nTarguments\\022\\020\\n\\014cycle_length\\030\\t\\022\\020\\n\\014block_length\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"\\t\\n\\001f\\022\\004func\\\"\\032\\n\\nTarguments\\022\\nlist(type)(\\001\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\nk\\n\\030SparseTensorSliceDataset\\022\\013\\n\\007indices\\030\\t\\022\\021\\n\\006values\\\"\\007Tvalues\\022\\017\\n\\013dense_shape\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"\\017\\n\\007Tvalues\\022\\004type\\210\\001\\001\\n\\217\\001\\n\\nSqlDataset\\022\\017\\n\\013driver_name\\030\\007\\022\\024\\n\\020data_source_name\\030\\007\\022\\t\\n\\005query\\030\\007\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\210\\001\\001\\nV\\n\\017TFRecordDataset\\022\\r\\n\\tfilenames\\030\\007\\022\\024\\n\\020compression_type\\030\\007\\022\\017\\n\\013buffer_size\\030\\t\\032\\n\\n\\006handle\\030\\025\\210\\001\\001\\ny\\n\\013TakeDataset\\022\\021\\n\\rinput_dataset\\030\\025\\022\\t\\n\\005count\\030\\t\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\n~\\n\\rTensorDataset\\022\\033\\n\\ncomponents2\\rToutput_types\\032\\n\\n\\006handle\\030\\025\\\"\\037\\n\\rToutput_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\210\\001\\001\\n\\203\\001\\n\\022TensorSliceDataset\\022\\033\\n\\ncomponents2\\rToutput_types\\032\\n\\n\\006handle\\030\\025\\\"\\037\\n\\rToutput_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\210\\001\\001\\nV\\n\\017TextLineDataset\\022\\r\\n\\tfilenames\\030\\007\\022\\024\\n\\020compression_type\\030\\007\\022\\017\\n\\013buffer_size\\030\\t\\032\\n\\n\\006handle\\030\\025\\210\\001\\001\\n\\177\\n\\nZipDataset\\022\\025\\n\\016input_datasets\\030\\025*\\001N\\032\\n\\n\\006handle\\030\\025\\\"\\036\\n\\014output_types\\022\\nlist(type)(\\0010\\001\\\" \\n\\routput_shapes\\022\\013list(shape)(\\0010\\001\\\"\\014\\n\\001N\\022\\003int(\\0010\\001\")\n" ]
[ [ "tensorflow.python.eager.execute.args_to_matching_eager", "tensorflow.python.eager.execute.make_type", "tensorflow.python.eager.execute.record_gradient", "tensorflow.python.eager.execute.make_str", "tensorflow.python.eager.execute.make_shape", "tensorflow.python.eager.context.context", "tensorflow.python.framework.op_def_library.OpDefLibrary", "tensorflow.python.eager.execute.execute", "tensorflow.python.framework.ops.convert_n_to_tensor", "tensorflow.python.eager.execute.make_bool", "tensorflow.python.eager.execute.convert_to_mixed_eager_tensors", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.core.framework.op_def_pb2.OpList", "tensorflow.python.framework.op_def_registry.register_op_list" ] ]
danja/elfquake
[ "0c42a32ccc1d7008febf120eabe666fbdccff781" ]
[ "ingv/aggregate.py" ]
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport glob\nimport csv\nimport numpy as np\nfrom numpy import genfromtxt\nimport gc # garbage collection\nimport hickle as hkl\n\n\nclass Aggregate():\n def __init__(self):\n self.csv_dir = \"./csv_data/raw/\"\n # 40N-47N, 7E-15E - northern Italy\n\n # ''Aquila 6 April 2009 > 5 mag\n # 42.3476°N 13.3800°ECoordinates: 42.3476°N 13.3800°E[1]\n\n # http://webservices.ingv.it/fdsnws/event/1/query?starttime=2009-04-01T00:00:00&endtime=2009-04-10T00:00:00\n\n # hmm, note magnitude 6.1 in Emilia-Romagna 2012\n # 44.9°N 11.24°E\n self.min_latitude = 40\n self.max_latitude = 47\n self.min_longitude = 7\n self.max_longitude = 15\n\n def main(self):\n # hopelessly inefficient, but who cares, data is smallish\n # hah! not once looking at matrix...\n count = self.count_records()\n print(\"COUNT = \" + str(count))\n gc.collect()\n X = self.load_records(count)\n\n hkl.dump(X, 'seismo.hkl')\n # 2007-01-02T05:28:38.870000, 43.612, 12.493, 7700, 1.7\n\n# 2007-01-02T05:28:38.870000, 43.612, 12.493, 7700, 1.7\n def load_records(self, count):\n got_start_date = False\n in_zone_count = 0\n max_depth = 0\n max_magnitude = 0\n\n X = np.zeros((count, 128, 128), np.float16) # , n_depth, n_mag\n # X = np.zeros((count, 128, 128), np.float32) # , n_depth, n_mag\n # gave Memory Error\n\n pattern = self.csv_dir + \"*.csv\"\n\n for filename in glob.glob(pattern):\n\n with open(filename) as csvfile: # , newline='\\n'\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n # print(row)\n date_string = row[0].strip()\n datetime = np.datetime64(date_string)\n if not got_start_date:\n self.start_date = datetime\n got_start_date = True\n# print(datetime)\n\n latitude = float(row[1].strip())\n longitude = float(row[2].strip())\n if not self.in_zone(latitude, longitude):\n continue\n\n in_zone_count = in_zone_count + 1\n depth = float(row[3].strip())\n magnitude = float(row[4].strip())\n if magnitude > 4:\n print(row)\n if depth > max_depth:\n max_depth = depth\n if magnitude > max_magnitude:\n max_magnitude = magnitude\n\n print(\"in_zone_count = \" + str(in_zone_count))\n print(\"max_depth = \" + str(max_depth))\n print(\"max_magnitude = \" + str(max_magnitude))\n return X\n\n # latitude = scale_lat(latitude)\n # longitude = scale_lat(longitude)\n\n # read csv file and fill in X\n\n def count_records(self):\n count = 0\n\n pattern = self.csv_dir + \"*.csv\"\n\n for filename in glob.glob(pattern):\n with open(filename) as csvfile: # , newline='\\n'\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n count = count + 1\n depth = float(row[3].strip())\n magnitude = float(row[4].strip())\n\n# 2007-01-02T05:28:38.870000, 43.612, 12.493, 7700, 1.7\n return count\n # is the point within the region of interest?\n # 40N-47N, 7E-15E - northern Italy\n\n def in_zone(self, latitude, longitude):\n if latitude < self.min_latitude or latitude >= self.max_latitude:\n return False\n if longitude < self.min_longitude or longitude >= self.max_longitude:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n Aggregate().main()\n" ]
[ [ "numpy.zeros", "numpy.datetime64" ] ]
estenssoros/sqlwriter
[ "881df2354929944a26418c6673a978568360bdfa" ]
[ "tests/utils.py" ]
[ "# -*- coding: utf-8 -*-\nimport datetime as dt\nimport os\nimport random\nimport string\nimport sys\nimport time\n\nimport pandas as pd\nimport yaml\nfrom past.builtins import basestring\n\nthis_dir = os.path.dirname(__file__)\n\n\ndef get_config(prog=None):\n cfg_file = os.path.join(this_dir, 'conf.yaml')\n\n with open(cfg_file, 'r') as f:\n config = yaml.load(f)\n\n if prog is None:\n return config\n\n try:\n return config[prog]\n except KeyError:\n print('No config found for {}. Exiting now.'.format(prog))\n sys.exit(1)\n\n\ndef connect_db(server):\n db_conn = get_config('db_creds')[server]\n flavor = db_conn.pop('flavor')\n if flavor == 'mysql':\n import MySQLdb as connector\n elif flavor == 'postgres':\n import psycopg2 as connector\n elif flavor == 'mssql':\n import pymssql as connector\n else:\n raise KeyError('%s not supported' % server)\n conn = connector.connect(**db_conn)\n curs = conn.cursor()\n return curs, conn\n\n\nclass DBRouter(object):\n def __init__(self, databases):\n if isinstance(databases, basestring):\n databases = [databases]\n self.databases = databases\n self.cursors = {}\n self.connections = {}\n for db in databases:\n self.cursors[db], self.connections[db] = connect_db(db)\n\n def close(self):\n for db in self.databases:\n self.cursors[db].close()\n try:\n self.connections[db].close()\n except:\n pass\n\n def __getitem__(self, key):\n return self.cursors[key], self.connections[key]\n\n\ndef create_test_dataframe():\n start = dt.datetime.now()\n end = start + dt.timedelta(days=600)\n start = time.mktime(start.timetuple())\n end = time.mktime(end.timetuple())\n\n data = []\n for _ in range(500):\n astring = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(random.randint(1, 50)))\n aninteger = random.randint(-100, 100)\n afloat = random.uniform(random.randint(-50, 0), random.randint(0, 50))\n randtime = start + (end - start) * random.random()\n adate = dt.date.fromtimestamp(randtime)\n adatetime = dt.datetime.fromtimestamp(randtime)\n row = [astring, aninteger, afloat, adate, adatetime]\n data.append(row)\n return pd.DataFrame(data=data, columns=['astring', 'aninteger', 'afloat', 'adate', 'adatetime'])\n" ]
[ [ "pandas.DataFrame" ] ]
zoharli/armin
[ "9bf8e4533850a66bbef26390244f0d0ad30c067b" ]
[ "pmnist_task/ntm/modules/head.py" ]
[ "import torch\nimport torch.nn.functional as F\nfrom torch import nn\n\n\nclass NTMHead(nn.Module):\n\n def __init__(self, mode, controller_size, key_size):\n super().__init__()\n self.mode = mode\n self.key_size = key_size\n\n # all the fc layers to produce scalars for memory addressing\n self.key_fc = nn.Linear(controller_size, key_size)\n self.key_strength_fc = nn.Linear(controller_size, 1)\n\n # these five fc layers cannot be in controller class\n # since each head has its own parameters and scalars\n self.interpolation_gate_fc = nn.Linear(controller_size, 1)\n self.shift_weighting_fc = nn.Linear(controller_size, 3)\n self.sharpen_factor_fc = nn.Linear(controller_size, 1)\n # --(optional : for separation of add and erase mechanism)\n # self.erase_weight_fc = nn.Linear(controller_size, key_size)\n\n # fc layer to produce write data. data vector length=key_size\n self.write_data_fc = nn.Linear(controller_size, key_size)\n# self.reset()\n\n def forward(self, controller_state, prev_weights, memory, data=None):\n \"\"\"Accept previous state (weights and memory) and controller state,\n produce attention weights for current read or write operation.\n Weights are produced by content-based and location-based addressing.\n\n Refer *Figure 2* in the paper to see how weights are produced.\n\n The head returns current weights useful for next time step, while\n it reads from or writes to ``memory`` based on its mode, using the\n ``data`` vector. ``data`` is filled and returned for read mode,\n returned as is for write mode.\n\n Refer *Section 3.1* for read mode and *Section 3.2* for write mode.\n\n Parameters\n ----------\n controller_state : torch.Tensor\n Long-term state of the controller.\n ``(batch_size, controller_size)``\n\n prev_weights : torch.Tensor\n Attention weights from previous time step.\n ``(batch_size, memory_units)``\n\n memory : ntm_modules.NTMMemory\n Memory Instance. Read write operations will be performed in place.\n\n data : torch.Tensor\n Depending upon the mode, this data vector will be used by memory.\n ``(batch_size, memory_unit_size)``\n\n Returns\n -------\n current_weights, data : torch.Tensor, torch.Tensor\n Current weights and data (filled in read operation else as it is).\n ``(batch_size, memory_units), (batch_size, memory_unit_size)``\n \"\"\"\n\n # all these are marked as \"controller outputs\" in Figure 2\n key = self.key_fc(controller_state)\n b = F.softplus(self.key_strength_fc(controller_state))\n g = F.sigmoid(self.interpolation_gate_fc(controller_state))\n s = F.softmax(self.shift_weighting_fc(controller_state))\n # here the sharpening factor is less than 1 whereas as required in the\n # paper it should be greater than 1. hence adding 1.\n y = 1 + F.softplus(self.sharpen_factor_fc(controller_state))\n # e = F.sigmoid(self.erase_weight_fc(controller_state)) # erase vector\n a = self.write_data_fc(controller_state) # add vector\n\n content_weights = memory.content_addressing(key, b)\n # location-based addressing - interpolate, shift, sharpen\n interpolated_weights = g * content_weights + (1 - g) * prev_weights\n shifted_weights = self._circular_conv1d(interpolated_weights, s)\n # the softmax introduces the exp of the argument which isn't there in\n # the paper. there it's just a simple normalization of the arguments.\n current_weights = shifted_weights ** y\n # current_weights = F.softmax(shifted_weights ** y)\n current_weights = torch.div(current_weights, torch.sum(\n current_weights, dim=1).view(-1, 1) + 1e-16)\n\n if self.mode == 'r':\n data = memory.read(current_weights)\n elif self.mode == 'w':\n # memory.write(current_weights, a, e)\n memory.write(current_weights, a)\n else:\n raise ValueError(\"mode must be read ('r') or write('w')\")\n return current_weights, data\n\n @staticmethod\n def _circular_conv1d(in_tensor, weights):\n # pad left with elements from right, and vice-versa\n batch_size = weights.size(0)\n pad = int((weights.size(1) - 1) / 2)\n in_tensor = torch.cat(\n [in_tensor[:, -pad:], in_tensor, in_tensor[:, :pad]], dim=1)\n weights=weights.mean(0,keepdim=True)\n out_tensor = F.conv1d(in_tensor.view(batch_size, 1, -1),\n weights.view(1, 1, -1))\n out_tensor = out_tensor.view(batch_size, -1)\n return out_tensor\n\n def reset(self):\n nn.init.xavier_uniform_(self.key_strength_fc.weight, gain=1.4)\n nn.init.xavier_uniform_(self.interpolation_gate_fc.weight, gain=1.4)\n nn.init.xavier_uniform_(self.shift_weighting_fc.weight, gain=1.4)\n nn.init.xavier_uniform_(self.sharpen_factor_fc.weight, gain=1.4)\n nn.init.xavier_uniform_(self.write_data_fc.weight, gain=1.4)\n # nn.init.xavier_uniform_(self.erase_weight_fc.weight, gain=1.4)\n\n # nn.init.kaiming_uniform_(self.key_strength_fc.weight)\n # nn.init.kaiming_uniform_(self.interpolation_gate_fc.weight)\n # nn.init.kaiming_uniform_(self.shift_weighting_fc.weight)\n # nn.init.kaiming_uniform_(self.sharpen_factor_fc.weight)\n # nn.init.kaiming_uniform_(self.write_data_fc.weight)\n # nn.init.kaiming_uniform_(self.erase_weight_fc.weight)\n\n nn.init.normal_(self.key_fc.bias, std=0.01)\n nn.init.normal_(self.key_strength_fc.bias, std=0.01)\n nn.init.normal_(self.interpolation_gate_fc.bias, std=0.01)\n nn.init.normal_(self.shift_weighting_fc.bias, std=0.01)\n nn.init.normal_(self.sharpen_factor_fc.bias, std=0.01)\n nn.init.normal_(self.write_data_fc.bias, std=0.01)\n # nn.init.normal_(self.erase_weight_fc.bias, std=0.01)\n" ]
[ [ "torch.sum", "torch.nn.init.xavier_uniform_", "torch.nn.Linear", "torch.nn.init.normal_", "torch.cat" ] ]
duncanwood/EO-analysis-jobs
[ "26d22e49c0d2e32fbf2759f504048754f66ecc45" ]
[ "harnessed_jobs/prnu_raft/v0/validator_prnu_raft.py" ]
[ "#!/usr/bin/env ipython\n\"\"\"\nValidator script for raft-level PRNU analysis.\n\"\"\"\nimport astropy.io.fits as fits\nimport numpy as np\nimport lcatr.schema\nimport siteUtils\nimport eotestUtils\nimport camera_components\n\nraft_id = siteUtils.getUnitId()\nraft = camera_components.Raft.create_from_etrav(raft_id)\n\nresults = []\nfor slot, sensor_id in raft.items():\n results_file = '%s_eotest_results.fits' % sensor_id\n prnu_results = fits.open(results_file)['PRNU_RESULTS'].data\n\n for wl, stdev, mean in zip(prnu_results['WAVELENGTH'],\n prnu_results['STDEV'], prnu_results['MEAN']):\n results.append(lcatr.schema.valid(lcatr.schema.get('prnu'),\n wavelength=int(np.round(wl)),\n pixel_stdev=stdev, pixel_mean=mean,\n slot=slot,\n sensor_id=sensor_id))\n\n qe_acq_job_id = \\\n siteUtils.get_prerequisite_job_id('S*/%s_lambda_flat_*.fits' % sensor_id,\n jobname=siteUtils.getProcessName('qe_raft_acq'))\n md = dict(illumination_non_uniformity_file=dict(JOB_ID=qe_acq_job_id))\n results.extend(eotestUtils.eotestCalibsPersist('illumination_non_uniformity_file',\n metadata=md))\n\nresults.extend(siteUtils.jobInfo())\nresults.append(eotestUtils.eotestCalibrations())\n\nlcatr.schema.write_file(results)\nlcatr.schema.validate_file()\n" ]
[ [ "numpy.round" ] ]
2877992943/tensor2tensor
[ "84cab42173724689ebddf853351a5aae704035a5" ]
[ "tensor2tensor/models/research/autoencoders.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Autoencoders.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensor2tensor.layers import common_attention\nfrom tensor2tensor.layers import common_hparams\nfrom tensor2tensor.layers import common_layers\nfrom tensor2tensor.layers import discretization\nfrom tensor2tensor.layers import latent_layers\nfrom tensor2tensor.utils import registry\nfrom tensor2tensor.utils import t2t_model\n\nimport tensorflow as tf\n\n\ndef reverse_gradient(x, lr=1.0):\n return -lr * x + tf.stop_gradient((1.0 + lr) * x)\n\n\[email protected]_model\nclass AutoencoderBasic(t2t_model.T2TModel):\n \"\"\"A basic autoencoder, try with image_mnist_rev or image_cifar10_rev.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(AutoencoderBasic, self).__init__(*args, **kwargs)\n self._cur_bottleneck_tensor = None\n self.is1d = None\n\n @property\n def num_channels(self):\n # TODO(lukaszkaiser): is this a universal enough way to get channels?\n try:\n num_channels = self.hparams.problem.num_channels\n except AttributeError:\n num_channels = 1\n return num_channels\n\n def image_summary(self, name, image_logits, max_outputs=1):\n \"\"\"Helper for image summaries that are safe on TPU.\"\"\"\n if len(image_logits.get_shape()) != 5:\n tf.logging.info(\"Not generating image summary, maybe not an image.\")\n return\n return tf.summary.image(\n name,\n common_layers.tpu_safe_image_summary(tf.argmax(image_logits, -1)),\n max_outputs=max_outputs)\n\n def embed(self, x):\n \"\"\"Input embedding with a non-zero bias for uniform inputs.\"\"\"\n with tf.variable_scope(\"embed\", reuse=tf.AUTO_REUSE):\n x_shape = common_layers.shape_list(x)\n # Merge channels and depth before embedding.\n x = tf.reshape(x, x_shape[:-2] + [x_shape[-2] * x_shape[-1]])\n x = tf.layers.dense(\n x,\n self.hparams.hidden_size,\n name=\"embed\",\n activation=common_layers.belu,\n bias_initializer=tf.random_normal_initializer(stddev=0.01))\n x = common_layers.layer_norm(x, name=\"ln_embed\")\n return common_attention.add_timing_signal_nd(x)\n\n def bottleneck(self, x):\n with tf.variable_scope(\"bottleneck\"):\n hparams = self.hparams\n x = tf.layers.dense(x, hparams.bottleneck_bits, name=\"bottleneck\")\n if hparams.mode == tf.estimator.ModeKeys.TRAIN:\n noise = 2.0 * tf.random_uniform(common_layers.shape_list(x)) - 1.0\n return tf.tanh(x) + noise * hparams.bottleneck_noise, 0.0\n return tf.tanh(x), 0.0\n\n def unbottleneck(self, x, res_size, reuse=None):\n with tf.variable_scope(\"unbottleneck\", reuse=reuse):\n x = tf.layers.dense(x, res_size, name=\"dense\")\n return x\n\n def make_even_size(self, x):\n if not self.is1d:\n return common_layers.make_even_size(x)\n shape1 = x.get_shape().as_list()[1]\n if shape1 is not None and shape1 % 2 == 0:\n return x\n x, _ = common_layers.pad_to_same_length(\n x, x, final_length_divisible_by=2, axis=1)\n return x\n\n def encoder(self, x):\n with tf.variable_scope(\"encoder\"):\n hparams = self.hparams\n layers = []\n kernel, strides = self._get_kernel_and_strides()\n # Down-convolutions.\n for i in range(hparams.num_hidden_layers):\n x = self.make_even_size(x)\n layers.append(x)\n x = tf.layers.conv2d(\n x,\n hparams.hidden_size * 2**(i + 1),\n kernel,\n strides=strides,\n padding=\"SAME\",\n activation=common_layers.belu,\n name=\"conv_%d\" % i)\n x = common_layers.layer_norm(x, name=\"ln_%d\" % i)\n return x, layers\n\n def decoder(self, x, encoder_layers):\n del encoder_layers\n with tf.variable_scope(\"decoder\"):\n hparams = self.hparams\n kernel, strides = self._get_kernel_and_strides()\n # Up-convolutions.\n for i in range(hparams.num_hidden_layers):\n j = hparams.num_hidden_layers - i - 1\n x = tf.layers.conv2d_transpose(\n x,\n hparams.hidden_size * 2**j,\n kernel,\n strides=strides,\n padding=\"SAME\",\n activation=common_layers.belu,\n name=\"deconv_%d\" % j)\n x = common_layers.layer_norm(x, name=\"ln_%d\" % i)\n return x\n\n def gumbel_sample(self, reconstr_gan):\n hparams = self.hparams\n is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN\n vocab_size = self._problem_hparams.target_modality.top_dimensionality\n reconstr_gan = tf.nn.log_softmax(reconstr_gan)\n if is_training and hparams.gumbel_temperature > 0.0:\n gumbel_samples = discretization.gumbel_sample(\n common_layers.shape_list(reconstr_gan))\n gumbel_samples *= hparams.gumbel_noise_factor\n reconstr_gan += gumbel_samples\n reconstr_sample = latent_layers.multinomial_sample(\n reconstr_gan, temperature=hparams.gumbel_temperature)\n reconstr_gan = tf.nn.softmax(reconstr_gan / hparams.gumbel_temperature)\n else:\n reconstr_sample = tf.argmax(reconstr_gan, axis=-1)\n reconstr_gan = tf.nn.softmax(reconstr_gan / 0.1) # Sharpen a bit.\n # Use 1-hot forward, softmax backward.\n reconstr_hot = tf.one_hot(reconstr_sample, vocab_size)\n reconstr_gan += reconstr_hot - tf.stop_gradient(reconstr_gan)\n return reconstr_gan\n\n def body(self, features):\n hparams = self.hparams\n is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN\n vocab_size = self._problem_hparams.target_modality.top_dimensionality\n encoder_layers = None\n self.is1d = hparams.sample_width == 1\n if hparams.mode != tf.estimator.ModeKeys.PREDICT:\n labels = features[\"targets_raw\"]\n shape = common_layers.shape_list(labels)\n x = tf.one_hot(labels, vocab_size)\n x = self.embed(x)\n target_codes = x\n if shape[2] == 1:\n self.is1d = True\n # Run encoder.\n x, encoder_layers = self.encoder(x)\n # Bottleneck.\n b, b_loss = self.bottleneck(x)\n xb_loss = 0.0\n b_shape = common_layers.shape_list(b)\n self._cur_bottleneck_tensor = b\n b = self.unbottleneck(b, common_layers.shape_list(x)[-1])\n if not is_training:\n x = b\n else:\n l = 2**hparams.num_hidden_layers\n warm_step = int(hparams.bottleneck_warmup_steps * 0.25 * l)\n nomix_p = common_layers.inverse_lin_decay(warm_step) + 0.01\n if common_layers.should_generate_summaries():\n tf.summary.scalar(\"nomix_p_bottleneck\", nomix_p)\n rand = tf.random_uniform(common_layers.shape_list(x))\n # This is the distance between b and x. Having this as loss helps learn\n # the bottleneck function, but if we back-propagated to x it would be\n # minimized by just setting x=0 and b=0 -- so we don't want too much\n # of the influence of this, and we stop-gradient to not zero-out x.\n x_stop = tf.stop_gradient(x)\n xb_loss = tf.reduce_mean(tf.reduce_sum(tf.square(x_stop - b), axis=-1))\n # To prevent this loss from exploding we clip at 1, but anneal clipping.\n clip_max = 1.0 / common_layers.inverse_exp_decay(\n warm_step, min_value=0.001)\n xb_clip = tf.maximum(tf.stop_gradient(xb_loss), clip_max)\n xb_loss *= clip_max / xb_clip\n x = tf.where(tf.less(rand, nomix_p), b, x)\n if hparams.gan_loss_factor != 0.0:\n # Add a purely sampled batch on which we'll compute the GAN loss.\n g = self.unbottleneck(\n self.sample(shape=b_shape),\n common_layers.shape_list(x)[-1],\n reuse=True)\n x = tf.concat([g, x], axis=0)\n encoder_layers = [tf.concat([l, l], axis=0) for l in encoder_layers]\n else:\n if self._cur_bottleneck_tensor is None:\n b = self.sample()\n else:\n b = self._cur_bottleneck_tensor\n res_size = self.hparams.hidden_size * 2**self.hparams.num_hidden_layers\n res_size = min(res_size, hparams.max_hidden_size)\n x = self.unbottleneck(b, res_size)\n # Run decoder.\n x = self.decoder(x, encoder_layers)\n\n # Cut to the right size and mix before returning.\n res = x\n if hparams.mode != tf.estimator.ModeKeys.PREDICT:\n res = x[:, :shape[1], :shape[2], :]\n\n # Final dense layer.\n res = tf.layers.dense(\n res, self.num_channels * hparams.hidden_size, name=\"res_dense\")\n\n output_shape = common_layers.shape_list(res)[:-1] + [\n self.num_channels, self.hparams.hidden_size\n ]\n res = tf.reshape(res, output_shape)\n\n if hparams.mode == tf.estimator.ModeKeys.PREDICT:\n if hparams.use_vq_loss:\n (reconstr, _, _, _, _) = discretization.vq_loss(res, labels, vocab_size)\n else:\n reconstr = tf.layers.dense(res, vocab_size, name=\"autoencoder_final\")\n return reconstr, {\"bottleneck_loss\": 0.0}\n\n if hparams.gan_loss_factor != 0.0:\n res_gan, res = tf.split(res, 2, axis=0)\n\n # Losses.\n losses = {\n \"bottleneck_extra\": b_loss,\n \"bottleneck_l2\": hparams.bottleneck_l2_factor * xb_loss\n }\n\n if hparams.use_vq_loss:\n vq_temperature = hparams.vq_temperature / common_layers.inverse_exp_decay(\n hparams.gan_codes_warmup_steps * 1.2,\n min_value=hparams.vq_temperature * 2)\n if hparams.mode != tf.estimator.ModeKeys.TRAIN:\n vq_temperature = None\n with tf.variable_scope(\"vq_loss\"):\n (reconstr, _, target_codes, code_loss,\n targets_loss) = discretization.vq_loss(\n res, labels, vocab_size, temperature=vq_temperature)\n losses[\"code_loss\"] = code_loss * hparams.code_loss_factor\n losses[\"training\"] = targets_loss\n else:\n reconstr = tf.layers.dense(res, vocab_size, name=\"autoencoder_final\")\n targets_loss = tf.losses.sparse_softmax_cross_entropy(\n logits=reconstr, labels=labels)\n losses[\"training\"] = targets_loss\n\n # GAN losses.\n if hparams.gan_loss_factor != 0.0:\n update_means_factor = common_layers.inverse_exp_decay(\n hparams.gan_codes_warmup_steps, min_value=0.0001)\n if hparams.use_vq_loss:\n with tf.variable_scope(\"vq_loss\", reuse=True):\n update_means = tf.less(tf.random_uniform([]), update_means_factor)\n reconstr_gan, gan_codes, _, code_loss_gan, _ = discretization.vq_loss(\n res_gan,\n labels,\n vocab_size,\n do_update=update_means,\n temperature=vq_temperature)\n reconstr_gan_nonoise = reconstr_gan\n code_loss_gan *= hparams.code_loss_factor * update_means_factor\n losses[\"code_loss_gan\"] = code_loss_gan\n else:\n reconstr_gan = tf.layers.dense(\n res_gan, vocab_size, name=\"autoencoder_final\", reuse=True)\n reconstr_gan_nonoise = reconstr_gan\n reconstr_gan = self.gumbel_sample(reconstr_gan)\n # Embed to codes.\n gan_codes = self.embed(reconstr_gan)\n\n # Add GAN loss if requested.\n gan_loss = 0.0\n if hparams.gan_loss_factor != 0.0:\n self.image_summary(\"gan\", reconstr_gan_nonoise)\n\n def discriminate(x):\n \"\"\"Run a dioscriminator depending on the hparams.\"\"\"\n if hparams.discriminator == \"default\":\n return common_layers.deep_discriminator(\n x, hparams.discriminator_batchnorm, is_training)\n elif hparams.discriminator == \"patched\":\n return common_layers.patch_discriminator(x)\n elif hparams.discriminator == \"single\":\n return common_layers.single_discriminator(\n x,\n hparams.discriminator_size,\n hparams.discriminator_kernel_size,\n hparams.discriminator_strides,\n pure_mean=hparams.discriminator_pure_mean)\n elif hparams.discriminator == \"double\":\n return common_layers.double_discriminator(\n x,\n hparams.discriminator_size,\n hparams.discriminator_kernel_size,\n hparams.discriminator_strides,\n pure_mean=hparams.discriminator_pure_mean)\n else:\n raise Exception(\"Unknown discriminator %s\" % hparams.discriminator)\n\n tc_shape = common_layers.shape_list(target_codes)\n if len(tc_shape) > 4:\n target_codes = tf.reshape(target_codes,\n tc_shape[:-2] + [tc_shape[-1] * tc_shape[-2]])\n gan_codes = tf.reshape(gan_codes,\n tc_shape[:-2] + [tc_shape[-1] * tc_shape[-2]])\n gan_lr = common_layers.inverse_exp_decay(\n hparams.gan_codes_warmup_steps * 1.5)\n rev_grad_gan_codes = reverse_gradient(gan_codes, lr=gan_lr)\n gan_loss = common_layers.sliced_gan_loss(\n target_codes, rev_grad_gan_codes, discriminate,\n self.hparams.num_sliced_vecs, do_tanh=hparams.sliced_do_tanh)\n gan_loss *= hparams.gan_loss_factor * update_means_factor\n losses[\"gan_loss\"] = -gan_loss\n\n self.image_summary(\"ae\", reconstr)\n logits = reconstr\n return logits, losses\n\n def sample(self, features=None, shape=None):\n del features\n hp = self.hparams\n div_x = 2**hp.num_hidden_layers\n div_y = 1 if self.is1d else 2**hp.num_hidden_layers\n size = [\n hp.batch_size, hp.sample_height // div_x, hp.sample_width // div_y,\n hp.bottleneck_bits\n ]\n size = size if shape is None else shape\n # Sample in [-1, 1] as the bottleneck is under tanh.\n return 2.0 * tf.random_uniform(size) - 1.0\n\n def encode(self, x):\n \"\"\"Auto-encode x and return the bottleneck.\"\"\"\n features = {\"targets\": x}\n self(features) # pylint: disable=not-callable\n res = tf.maximum(0.0, self._cur_bottleneck_tensor) # Be 0/1 and not -1/1.\n self._cur_bottleneck_tensor = None\n return res\n\n def infer(self, features, *args, **kwargs): # pylint: disable=arguments-differ\n \"\"\"Produce predictions from the model by sampling.\"\"\"\n del args, kwargs\n # Inputs and features preparation needed to handle edge cases.\n if not features:\n features = {}\n inputs_old = None\n if \"inputs\" in features and len(features[\"inputs\"].shape) < 4:\n inputs_old = features[\"inputs\"]\n features[\"inputs\"] = tf.expand_dims(features[\"inputs\"], 2)\n\n # Sample and decode.\n num_channels = self.num_channels\n if \"targets\" not in features:\n features[\"targets\"] = tf.zeros(\n [self.hparams.batch_size, 1, 1, num_channels], dtype=tf.int32)\n logits, _ = self(features) # pylint: disable=not-callable\n samples = tf.argmax(logits, axis=-1)\n\n # Restore inputs to not confuse Estimator in edge cases.\n if inputs_old is not None:\n features[\"inputs\"] = inputs_old\n\n # Return samples.\n return samples\n\n def decode(self, bottleneck):\n \"\"\"Auto-decode from the bottleneck and return the result.\"\"\"\n # Get the shape from bottleneck and num channels.\n shape = common_layers.shape_list(bottleneck)\n try:\n num_channels = self.hparams.problem.num_channels\n except AttributeError:\n num_channels = 1\n dummy_targets = tf.zeros(shape[:-1] + [num_channels])\n # Set the bottleneck to decode.\n if len(shape) > 4:\n bottleneck = tf.squeeze(bottleneck, axis=[1])\n bottleneck = 2 * bottleneck - 1 # Be -1/1 instead of 0/1.\n self._cur_bottleneck_tensor = bottleneck\n # Run decoding.\n res = self.infer({\"targets\": dummy_targets})\n self._cur_bottleneck_tensor = None\n return res\n\n def _get_kernel_and_strides(self):\n hparams = self.hparams\n kernel = (hparams.kernel_height, hparams.kernel_width)\n kernel = (hparams.kernel_height, 1) if self.is1d else kernel\n strides = (2, 1) if self.is1d else (2, 2)\n return (kernel, strides)\n\n\[email protected]_model\nclass AutoencoderAutoregressive(AutoencoderBasic):\n \"\"\"Autoencoder with an autoregressive part.\"\"\"\n\n def body(self, features):\n hparams = self.hparams\n # Run the basic autoencoder part first.\n basic_result, losses = super(AutoencoderAutoregressive, self).body(features)\n if hparams.autoregressive_mode == \"none\":\n assert not hparams.autoregressive_forget_base\n return basic_result, losses\n if \"training\" in losses:\n plain_training_loss = losses.pop(\"training\")\n losses[\"plain\"] = plain_training_loss\n res_shape = common_layers.shape_list(basic_result)\n vocab_size = self._problem_hparams.target_modality.top_dimensionality\n targets = tf.one_hot(features[\"targets_raw\"], vocab_size)\n # Prepare inputs for autoregressive modes.\n if common_layers.shape_list(features[\"targets\"])[1] == 1:\n # This happens on the first step of predicitions.\n assert hparams.mode == tf.estimator.ModeKeys.PREDICT\n targets = tf.zeros_like(basic_result)\n targets = self.embed(targets)\n if hparams.autoregressive_gumbel_sample:\n basic_hot = self.gumbel_sample(basic_result)\n else:\n basic_hot = basic_result\n basic_result = self.embed(basic_hot)\n shape = common_layers.shape_list(basic_result)\n basic1d = tf.reshape(basic_result, [shape[0], -1, shape[-1]])\n targets = tf.reshape(targets, common_layers.shape_list(basic_result))\n # During autoregressive inference, don't resample.\n if hparams.mode == tf.estimator.ModeKeys.PREDICT:\n if hasattr(hparams, \"sampled_basic1d_tensor\"):\n basic1d = hparams.sampled_basic1d_tensor\n else:\n hparams.sampled_basic1d_tensor = basic1d\n # Sometimes it's useful to look at non-autoregressive evals.\n targets_dropout = targets\n if (hparams.mode == tf.estimator.ModeKeys.EVAL and\n hparams.autoregressive_eval_pure_autoencoder):\n targets_dropout = tf.zeros_like(basic_result)\n # Now combine the basic reconstruction with shifted targets.\n targets1d = tf.reshape(targets_dropout, [shape[0], -1, shape[-1]])\n targets_shifted = common_layers.shift_right_3d(targets1d)\n concat1d = tf.concat([basic1d, targets_shifted], axis=-1)\n # The forget_base hparam sets purely-autoregressive mode, no autoencoder.\n if hparams.autoregressive_forget_base:\n concat1d = tf.reshape(targets, [shape[0], -1, shape[-1]])\n concat1d = common_layers.shift_right_3d(concat1d)\n # The autoregressive part depends on the mode.\n if hparams.autoregressive_mode == \"conv3\":\n res = common_layers.conv1d(\n concat1d,\n hparams.hidden_size,\n 3,\n padding=\"LEFT\",\n activation=common_layers.belu,\n name=\"autoregressive_conv3\")\n res = tf.layers.dense(res, vocab_size, name=\"autoregressive_final\")\n return tf.reshape(res, res_shape), losses\n if hparams.autoregressive_mode == \"conv5\":\n res = common_layers.conv1d(\n concat1d,\n hparams.hidden_size,\n 5,\n padding=\"LEFT\",\n activation=common_layers.belu,\n name=\"autoregressive_conv5\")\n res = tf.layers.dense(res, vocab_size, name=\"autoregressive_final\")\n return tf.reshape(res, res_shape), losses\n if hparams.autoregressive_mode == \"sru\":\n res = common_layers.conv1d(\n concat1d,\n hparams.hidden_size,\n 3,\n padding=\"LEFT\",\n activation=common_layers.belu,\n name=\"autoregressive_sru_conv3\")\n res = common_layers.sru(res)\n res = tf.layers.dense(res, vocab_size, name=\"autoregressive_final\")\n return tf.reshape(res, res_shape), losses\n\n raise ValueError(\n \"Unsupported autoregressive mode: %s\" % hparams.autoregressive_mode)\n\n def infer(self, features, *args, **kwargs):\n \"\"\"Produce predictions from the model by sampling.\"\"\"\n # Inputs and features preparation needed to handle edge cases.\n if not features:\n features = {}\n inputs_old = None\n if \"inputs\" in features and len(features[\"inputs\"].shape) < 4:\n inputs_old = features[\"inputs\"]\n features[\"inputs\"] = tf.expand_dims(features[\"inputs\"], 2)\n\n # Sample first.\n try:\n num_channels = self.hparams.problem.num_channels\n except AttributeError:\n num_channels = 1\n if \"targets\" not in features:\n features[\"targets\"] = tf.zeros(\n [self.hparams.batch_size, 1, 1, num_channels], dtype=tf.int32)\n logits, _ = self(features) # pylint: disable=not-callable\n samples = common_layers.sample_with_temperature(logits, 0.0)\n shape = common_layers.shape_list(samples)\n\n # Sample again if requested for the autoregressive part.\n extra_samples = self.hparams.autoregressive_decode_steps\n for i in range(extra_samples):\n if i == extra_samples - 2:\n self.hparams.sampling_temp /= 2\n if i == extra_samples - 1:\n self.hparams.sampling_temp = 0.0\n features[\"targets\"] = samples\n old_samples1d = tf.reshape(samples, [shape[0], -1, shape[3]])\n with tf.variable_scope(tf.get_variable_scope(), reuse=True):\n logits, _ = self(features) # pylint: disable=not-callable\n samples = common_layers.sample_with_temperature(\n logits, self.hparams.sampling_temp)\n samples1d = tf.reshape(samples, [shape[0], -1, shape[3]])\n samples1d = tf.concat(\n [old_samples1d[:, :i, :], samples1d[:, i:, :]], axis=1)\n samples = tf.reshape(samples1d, shape)\n\n # Restore inputs to not confuse Estimator in edge cases.\n if inputs_old is not None:\n features[\"inputs\"] = inputs_old\n\n # Return samples.\n return samples\n\n\[email protected]_model\nclass AutoencoderResidual(AutoencoderAutoregressive):\n \"\"\"Residual autoencoder.\"\"\"\n\n def dropout(self, x):\n is_training = self.hparams.mode == tf.estimator.ModeKeys.TRAIN\n hparams = self.hparams\n if hparams.dropout <= 0.0 or not is_training:\n return x\n warm_step = hparams.bottleneck_warmup_steps * 2**hparams.num_hidden_layers\n dropout = common_layers.inverse_lin_decay(warm_step // 2) * hparams.dropout\n return common_layers.dropout_with_broadcast_dims(\n x, 1.0 - dropout, broadcast_dims=[-1])\n\n def encoder(self, x):\n with tf.variable_scope(\"encoder\"):\n hparams = self.hparams\n layers = []\n kernel, strides = self._get_kernel_and_strides()\n residual_kernel = (hparams.residual_kernel_height,\n hparams.residual_kernel_width)\n residual_kernel1d = (hparams.residual_kernel_height, 1)\n residual_kernel = residual_kernel1d if self.is1d else residual_kernel\n residual_conv = tf.layers.conv2d\n if hparams.residual_use_separable_conv:\n residual_conv = tf.layers.separable_conv2d\n # Down-convolutions.\n for i in range(hparams.num_hidden_layers):\n with tf.variable_scope(\"layer_%d\" % i):\n x = self.make_even_size(x)\n layers.append(x)\n x = self.dropout(x)\n filters = hparams.hidden_size * 2**(i + 1)\n filters = min(filters, hparams.max_hidden_size)\n x = common_attention.add_timing_signal_nd(x)\n x = tf.layers.conv2d(\n x,\n filters,\n kernel,\n strides=strides,\n padding=\"SAME\",\n activation=common_layers.belu,\n name=\"strided\")\n y = x\n for r in range(hparams.num_residual_layers):\n residual_filters = filters\n if r < hparams.num_residual_layers - 1:\n residual_filters = int(\n filters * hparams.residual_filter_multiplier)\n y = residual_conv(\n y,\n residual_filters,\n residual_kernel,\n padding=\"SAME\",\n activation=common_layers.belu,\n name=\"residual_%d\" % r)\n x += tf.nn.dropout(y, 1.0 - hparams.residual_dropout)\n x = common_layers.layer_norm(x, name=\"ln\")\n return x, layers\n\n def decoder(self, x, encoder_layers=None):\n with tf.variable_scope(\"decoder\"):\n hparams = self.hparams\n is_training = self.hparams.mode == tf.estimator.ModeKeys.TRAIN\n kernel, strides = self._get_kernel_and_strides()\n residual_kernel = (hparams.residual_kernel_height,\n hparams.residual_kernel_width)\n residual_kernel1d = (hparams.residual_kernel_height, 1)\n residual_kernel = residual_kernel1d if self.is1d else residual_kernel\n residual_conv = tf.layers.conv2d\n if hparams.residual_use_separable_conv:\n residual_conv = tf.layers.separable_conv2d\n # Up-convolutions.\n for i in range(hparams.num_hidden_layers):\n j = hparams.num_hidden_layers - i - 1\n nomix_p = common_layers.inverse_lin_decay(\n int(hparams.bottleneck_warmup_steps * 0.25 * 2**j)) + 0.01\n if common_layers.should_generate_summaries():\n tf.summary.scalar(\"nomix_p_%d\" % j, nomix_p)\n filters = hparams.hidden_size * 2**j\n filters = min(filters, hparams.max_hidden_size)\n with tf.variable_scope(\"layer_%d\" % i):\n j = hparams.num_hidden_layers - i - 1\n x = tf.layers.conv2d_transpose(\n x,\n filters,\n kernel,\n strides=strides,\n padding=\"SAME\",\n activation=common_layers.belu,\n name=\"strided\")\n y = x\n for r in range(hparams.num_residual_layers):\n residual_filters = filters\n if r < hparams.num_residual_layers - 1:\n residual_filters = int(\n filters * hparams.residual_filter_multiplier)\n y = residual_conv(\n y,\n residual_filters,\n residual_kernel,\n padding=\"SAME\",\n activation=common_layers.belu,\n name=\"residual_%d\" % r)\n x += tf.nn.dropout(y, 1.0 - hparams.residual_dropout)\n x = common_layers.layer_norm(x, name=\"ln\")\n x = common_attention.add_timing_signal_nd(x)\n if encoder_layers is not None:\n enc_x = encoder_layers[j]\n enc_shape = common_layers.shape_list(enc_x)\n x = x[:, :enc_shape[1], :enc_shape[2], :]\n if is_training: # Mix at the beginning of training.\n rand = tf.random_uniform(common_layers.shape_list(x))\n x = tf.where(tf.less(rand, nomix_p), x, enc_x)\n return x\n\n\[email protected]_model\nclass AutoencoderResidualVAE(AutoencoderResidual):\n \"\"\"Residual VAE autoencoder.\"\"\"\n\n def bottleneck(self, x):\n hparams = self.hparams\n z_size = hparams.bottleneck_bits\n x_shape = common_layers.shape_list(x)\n with tf.variable_scope(\"vae\"):\n mu = tf.layers.dense(x, z_size, name=\"mu\")\n if hparams.mode != tf.estimator.ModeKeys.TRAIN:\n return mu, 0.0 # No sampling or kl loss on eval.\n log_sigma = tf.layers.dense(x, z_size, name=\"log_sigma\")\n epsilon = tf.random_normal(x_shape[:-1] + [z_size])\n z = mu + tf.exp(log_sigma / 2) * epsilon\n kl = 0.5 * tf.reduce_mean(\n tf.exp(log_sigma) + tf.square(mu) - 1. - log_sigma, axis=-1)\n free_bits = z_size // 4\n kl_loss = tf.reduce_mean(tf.maximum(kl - free_bits, 0.0))\n return z, kl_loss * hparams.kl_beta\n\n def sample(self, features=None, shape=None):\n del features\n hparams = self.hparams\n div_x = 2**hparams.num_hidden_layers\n div_y = 1 if self.is1d else 2**hparams.num_hidden_layers\n size = [\n hparams.batch_size, hparams.sample_height // div_x,\n hparams.sample_width // div_y, hparams.bottleneck_bits\n ]\n size = size if shape is None else shape\n return tf.random_normal(size)\n\n\[email protected]_model\nclass AutoencoderBasicDiscrete(AutoencoderAutoregressive):\n \"\"\"Discrete autoencoder.\"\"\"\n\n def bottleneck(self, x):\n hparams = self.hparams\n x = tf.tanh(tf.layers.dense(x, hparams.bottleneck_bits, name=\"bottleneck\"))\n d = x + tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x)) - 1.0 - x)\n if hparams.mode == tf.estimator.ModeKeys.TRAIN:\n noise = tf.random_uniform(common_layers.shape_list(x))\n noise = 2.0 * tf.to_float(tf.less(hparams.bottleneck_noise, noise)) - 1.0\n d *= noise\n x = common_layers.mix(d, x, hparams.discretize_warmup_steps,\n hparams.mode == tf.estimator.ModeKeys.TRAIN)\n return x, 0.0\n\n def sample(self, features=None, shape=None):\n del features\n hp = self.hparams\n div_x = 2**hp.num_hidden_layers\n div_y = 1 if self.is1d else 2**hp.num_hidden_layers\n size = [\n hp.batch_size, hp.sample_height // div_x, hp.sample_width // div_y,\n hp.bottleneck_bits\n ]\n size = size if shape is None else shape\n rand = tf.random_uniform(size)\n return 2.0 * tf.to_float(tf.less(0.5, rand)) - 1.0\n\n\[email protected]_model\nclass AutoencoderResidualDiscrete(AutoencoderResidual):\n \"\"\"Discrete residual autoencoder.\"\"\"\n\n def variance_loss(self, b):\n part = tf.random_uniform(common_layers.shape_list(b))\n selection = tf.to_float(tf.less(part, tf.random_uniform([])))\n selection_size = tf.reduce_sum(selection)\n part_avg = tf.abs(tf.reduce_sum(b * selection)) / (selection_size + 1)\n return part_avg\n\n def bottleneck(self, x, bottleneck_bits=None): # pylint: disable=arguments-differ\n if bottleneck_bits is not None:\n old_bottleneck_bits = self.hparams.bottleneck_bits\n self.hparams.bottleneck_bits = bottleneck_bits\n res, loss = discretization.parametrized_bottleneck(x, self.hparams)\n if bottleneck_bits is not None:\n self.hparams.bottleneck_bits = old_bottleneck_bits\n return res, loss\n\n def unbottleneck(self, x, res_size, reuse=None):\n with tf.variable_scope(\"unbottleneck\", reuse=reuse):\n return discretization.parametrized_unbottleneck(x, res_size, self.hparams)\n\n def sample(self, features=None, shape=None):\n del features\n hp = self.hparams\n div_x = 2**hp.num_hidden_layers\n div_y = 1 if self.is1d else 2**hp.num_hidden_layers\n size = [\n hp.batch_size, hp.sample_height // div_x, hp.sample_width // div_y,\n hp.bottleneck_bits\n ]\n size = size if shape is None else shape\n rand = tf.random_uniform(size)\n res = 2.0 * tf.to_float(tf.less(0.5, rand)) - 1.0\n # If you want to set some first bits to a fixed value, do this:\n # fixed = tf.zeros_like(rand) - 1.0\n # nbits = 3\n # res = tf.concat([fixed[:, :, :, :nbits], res[:, :, :, nbits:]], axis=-1)\n return res\n\n\[email protected]_model\nclass AutoencoderOrderedDiscrete(AutoencoderResidualDiscrete):\n \"\"\"Ordered discrete autoencoder.\"\"\"\n\n def bottleneck(self, x): # pylint: disable=arguments-differ\n hparams = self.hparams\n if hparams.unordered:\n return super(AutoencoderOrderedDiscrete, self).bottleneck(x)\n noise = hparams.bottleneck_noise\n hparams.bottleneck_noise = 0.0 # We'll add noise below.\n x, loss = discretization.parametrized_bottleneck(x, hparams)\n hparams.bottleneck_noise = noise\n if hparams.mode == tf.estimator.ModeKeys.TRAIN:\n # We want a number p such that p^bottleneck_bits = 1 - noise.\n # So log(p) * bottleneck_bits = log(noise)\n log_p = tf.log(1 - float(noise) / 2) / float(hparams.bottleneck_bits)\n # Probabilities of flipping are p, p^2, p^3, ..., p^bottleneck_bits.\n noise_mask = 1.0 - tf.exp(tf.cumsum(tf.zeros_like(x) + log_p, axis=-1))\n # Having the no-noise mask, we can make noise just uniformly at random.\n ordered_noise = tf.random_uniform(tf.shape(x))\n # We want our noise to be 1s at the start and random {-1, 1} bits later.\n ordered_noise = tf.to_float(tf.less(noise_mask, ordered_noise))\n # Now we flip the bits of x on the noisy positions (ordered and normal).\n x *= 2.0 * ordered_noise - 1\n return x, loss\n\n\[email protected]_model\nclass AutoencoderStacked(AutoencoderResidualDiscrete):\n \"\"\"A stacked autoencoder.\"\"\"\n\n def stack(self, b, size, bottleneck_bits, name):\n with tf.variable_scope(name + \"_stack\"):\n unb = self.unbottleneck(b, size)\n enc = self.encoder(unb)\n b, _ = self.bottleneck(enc, bottleneck_bits=bottleneck_bits)\n return b\n\n def unstack(self, b, size, bottleneck_bits, name):\n with tf.variable_scope(name + \"_unstack\"):\n unb = self.unbottleneck(b, size)\n dec = self.decoder(unb)\n pred = tf.layers.dense(dec, bottleneck_bits, name=\"pred\")\n pred_shape = common_layers.shape_list(pred)\n pred1 = tf.reshape(pred, pred_shape[:-1] + [-1, 2])\n x, y = tf.split(pred1, 2, axis=-1)\n x = tf.squeeze(x, axis=[-1])\n y = tf.squeeze(y, axis=[-1])\n gt = 2.0 * tf.to_float(tf.less(x, y)) - 1.0\n gtc = tf.tanh(y - x)\n gt += gtc - tf.stop_gradient(gtc)\n return gt, pred1\n\n def stack_loss(self, b, b_pred, name):\n with tf.variable_scope(name):\n labels_discrete = tf.to_int32((b + 1.0) * 0.5)\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=labels_discrete, logits=b_pred)\n return tf.reduce_mean(loss)\n\n def full_stack(self, b, x_size, bottleneck_bits, losses, is_training, i):\n stack1_b = self.stack(b, x_size, bottleneck_bits, \"step%d\" % i)\n if i > 1:\n stack1_b = self.full_stack(stack1_b, 2 * x_size, 2 * bottleneck_bits,\n losses, is_training, i - 1)\n b1, b_pred = self.unstack(stack1_b, x_size, bottleneck_bits, \"step%d\" % i)\n losses[\"stack%d_loss\" % i] = self.stack_loss(b, b_pred, \"step%d\" % i)\n b_shape = common_layers.shape_list(b)\n if is_training:\n condition = tf.less(tf.random_uniform([]), 0.5)\n condition = tf.reshape(condition, [1] * len(b.shape))\n condition = tf.tile(condition, b.shape)\n b1 = tf.where(condition, b, b1)\n return tf.reshape(b1, b_shape)\n\n def body(self, features):\n hparams = self.hparams\n num_stacks = hparams.num_hidden_layers\n hparams.num_hidden_layers = 1\n is_training = hparams.mode == tf.estimator.ModeKeys.TRAIN\n if hparams.mode != tf.estimator.ModeKeys.PREDICT:\n x = features[\"targets\"]\n shape = common_layers.shape_list(x)\n is1d = shape[2] == 1\n self.is1d = is1d\n x, _ = common_layers.pad_to_same_length(\n x, x, final_length_divisible_by=2**num_stacks, axis=1)\n if not is1d:\n x, _ = common_layers.pad_to_same_length(\n x, x, final_length_divisible_by=2**num_stacks, axis=2)\n # Run encoder.\n x = self.encoder(x)\n x_size = common_layers.shape_list(x)[-1]\n # Bottleneck (mix during early training, not too important but stable).\n b, b_loss = self.bottleneck(x)\n losses = {\"bottleneck0_loss\": b_loss}\n b = self.full_stack(b, 2 * x_size, 2 * hparams.bottleneck_bits, losses,\n is_training, num_stacks - 1)\n b = self.unbottleneck(b, x_size)\n b = common_layers.mix(b, x, hparams.bottleneck_warmup_steps, is_training)\n x = b\n else:\n b = self.sample()\n res_size = self.hparams.hidden_size * 2**self.hparams.num_hidden_layers\n res_size = min(res_size, hparams.max_hidden_size)\n x = self.unbottleneck(b, res_size)\n # Run decoder.\n x = self.decoder(x)\n if hparams.mode == tf.estimator.ModeKeys.PREDICT:\n return x\n # Cut to the right size and mix before returning.\n res = x[:, :shape[1], :shape[2], :]\n res = common_layers.mix(res, features[\"targets\"],\n hparams.bottleneck_warmup_steps // 2, is_training)\n hparams.num_hidden_layers = num_stacks\n return res, losses\n\n\[email protected]_hparams\ndef autoencoder_basic():\n \"\"\"Basic autoencoder model.\"\"\"\n hparams = common_hparams.basic_params1()\n hparams.optimizer = \"Adam\"\n hparams.learning_rate_constant = 0.0002\n hparams.learning_rate_warmup_steps = 500\n hparams.learning_rate_schedule = \"constant * linear_warmup\"\n hparams.label_smoothing = 0.0\n hparams.batch_size = 128\n hparams.hidden_size = 64\n hparams.num_hidden_layers = 5\n hparams.initializer = \"uniform_unit_scaling\"\n hparams.initializer_gain = 1.0\n hparams.weight_decay = 0.0\n hparams.kernel_height = 4\n hparams.kernel_width = 4\n hparams.dropout = 0.05\n hparams.add_hparam(\"max_hidden_size\", 1024)\n hparams.add_hparam(\"bottleneck_bits\", 128)\n hparams.add_hparam(\"bottleneck_noise\", 0.1)\n hparams.add_hparam(\"bottleneck_warmup_steps\", 2000)\n hparams.add_hparam(\"sample_height\", 32)\n hparams.add_hparam(\"sample_width\", 32)\n hparams.add_hparam(\"discriminator_batchnorm\", True)\n hparams.add_hparam(\"num_sliced_vecs\", 20000)\n hparams.add_hparam(\"sliced_do_tanh\", int(True))\n hparams.add_hparam(\"discriminator_size\", 256)\n hparams.add_hparam(\"discriminator_kernel_size\", 6)\n hparams.add_hparam(\"discriminator_strides\", 4)\n hparams.add_hparam(\"discriminator_pure_mean\", int(False))\n hparams.add_hparam(\"code_loss_factor\", 1.0)\n hparams.add_hparam(\"gan_codes_warmup_steps\", 16000)\n hparams.add_hparam(\"gan_loss_factor\", 0.0)\n hparams.add_hparam(\"bottleneck_l2_factor\", 0.05)\n hparams.add_hparam(\"gumbel_temperature\", 0.5)\n hparams.add_hparam(\"gumbel_noise_factor\", 0.5)\n hparams.add_hparam(\"vq_temperature\", 0.001)\n hparams.add_hparam(\"use_vq_loss\", int(False))\n hparams.add_hparam(\"discriminator\", \"double\")\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_autoregressive():\n \"\"\"Autoregressive autoencoder model.\"\"\"\n hparams = autoencoder_basic()\n hparams.add_hparam(\"autoregressive_forget_base\", False)\n hparams.add_hparam(\"autoregressive_mode\", \"none\")\n hparams.add_hparam(\"autoregressive_decode_steps\", 0)\n hparams.add_hparam(\"autoregressive_eval_pure_autoencoder\", False)\n hparams.add_hparam(\"autoregressive_gumbel_sample\", False)\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_residual():\n \"\"\"Residual autoencoder model.\"\"\"\n hparams = autoencoder_autoregressive()\n hparams.optimizer = \"Adafactor\"\n hparams.clip_grad_norm = 1.0\n hparams.learning_rate_constant = 0.5\n hparams.learning_rate_warmup_steps = 500\n hparams.learning_rate_schedule = \"constant * linear_warmup * rsqrt_decay\"\n hparams.num_hidden_layers = 5\n hparams.hidden_size = 64\n hparams.max_hidden_size = 1024\n hparams.add_hparam(\"num_residual_layers\", 2)\n hparams.add_hparam(\"residual_kernel_height\", 3)\n hparams.add_hparam(\"residual_kernel_width\", 3)\n hparams.add_hparam(\"residual_filter_multiplier\", 2.0)\n hparams.add_hparam(\"residual_dropout\", 0.2)\n hparams.add_hparam(\"residual_use_separable_conv\", int(True))\n hparams.add_hparam(\"kl_beta\", 1.0)\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_residual_text():\n \"\"\"Residual autoencoder model for text.\"\"\"\n hparams = autoencoder_residual()\n hparams.bottleneck_bits = 32\n hparams.batch_size = 1024\n hparams.hidden_size = 64\n hparams.max_hidden_size = 512\n hparams.bottleneck_noise = 0.0\n hparams.target_modality = \"symbol:identity\"\n hparams.input_modalities = \"symbol:identity\"\n hparams.autoregressive_mode = \"none\"\n hparams.sample_width = 1\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_basic_discrete():\n \"\"\"Basic autoencoder model.\"\"\"\n hparams = autoencoder_autoregressive()\n hparams.num_hidden_layers = 5\n hparams.hidden_size = 64\n hparams.bottleneck_bits = 1024\n hparams.bottleneck_noise = 0.1\n hparams.add_hparam(\"discretize_warmup_steps\", 16000)\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_residual_discrete():\n \"\"\"Residual discrete autoencoder model.\"\"\"\n hparams = autoencoder_residual()\n hparams.bottleneck_bits = 1024\n hparams.bottleneck_noise = 0.05\n hparams.add_hparam(\"discretize_warmup_steps\", 16000)\n hparams.add_hparam(\"bottleneck_kind\", \"tanh_discrete\")\n hparams.add_hparam(\"isemhash_noise_dev\", 0.5)\n hparams.add_hparam(\"isemhash_mix_prob\", 0.5)\n hparams.add_hparam(\"isemhash_filter_size_multiplier\", 2.0)\n hparams.add_hparam(\"vq_beta\", 0.25)\n hparams.add_hparam(\"vq_decay\", 0.999)\n hparams.add_hparam(\"vq_epsilon\", 1e-5)\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_residual_discrete_big():\n \"\"\"Residual discrete autoencoder model, big version.\"\"\"\n hparams = autoencoder_residual_discrete()\n hparams.hidden_size = 128\n hparams.max_hidden_size = 4096\n hparams.bottleneck_noise = 0.1\n hparams.residual_dropout = 0.4\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_ordered_discrete():\n \"\"\"Ordered discrete autoencoder model.\"\"\"\n hparams = autoencoder_residual_discrete()\n hparams.bottleneck_noise = 0.05 # Use 0.8 for ordered.\n hparams.gan_loss_factor = 0.05\n hparams.add_hparam(\"unordered\", True)\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_ordered_discrete_patched():\n \"\"\"Ordered discrete autoencoder model.\"\"\"\n hparams = autoencoder_ordered_discrete()\n hparams.discriminator = \"patched\"\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_ordered_discrete_single():\n \"\"\"Ordered discrete autoencoder model.\"\"\"\n hparams = autoencoder_ordered_discrete()\n hparams.discriminator = \"single\"\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_ordered_discrete_hs256():\n \"\"\"Ordered discrete autoencoder model.\"\"\"\n hparams = autoencoder_ordered_discrete()\n hparams.hidden_size = 256\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_ordered_text():\n \"\"\"Ordered discrete autoencoder model for text.\"\"\"\n hparams = autoencoder_ordered_discrete()\n hparams.bottleneck_bits = 512\n hparams.num_hidden_layers = 7\n hparams.batch_size = 1024\n hparams.autoregressive_mode = \"conv5\"\n hparams.max_hidden_size = 1024\n hparams.target_modality = \"symbol:identity\"\n hparams.input_modalities = \"symbol:identity\"\n hparams.sample_height = 128\n hparams.sample_width = 1\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_ordered_text_small():\n \"\"\"Ordered discrete autoencoder model for text, small version.\"\"\"\n hparams = autoencoder_ordered_text()\n hparams.bottleneck_bits = 14\n hparams.num_hidden_layers = 2\n hparams.hidden_size = 64\n hparams.max_hidden_size = 512\n hparams.bottleneck_noise = 0.0\n hparams.autoregressive_mode = \"conv5\"\n hparams.sample_height = 4\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_ordered_discrete_vq():\n \"\"\"Ordered discrete autoencoder model with VQ bottleneck.\"\"\"\n hparams = autoencoder_ordered_discrete()\n hparams.bottleneck_kind = \"vq\"\n hparams.bottleneck_bits = 16\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_discrete_pong():\n \"\"\"Discrete autoencoder model for compressing pong frames.\"\"\"\n hparams = autoencoder_ordered_discrete()\n hparams.num_hidden_layers = 2\n hparams.bottleneck_bits = 24\n hparams.batch_size = 2\n hparams.bottleneck_noise = 0.2\n hparams.max_hidden_size = 1024\n return hparams\n\n\[email protected]_hparams\ndef autoencoder_discrete_cifar():\n \"\"\"Discrete autoencoder model for compressing cifar.\"\"\"\n hparams = autoencoder_ordered_discrete()\n hparams.bottleneck_noise = 0.0\n hparams.bottleneck_bits = 90\n hparams.num_hidden_layers = 2\n hparams.hidden_size = 256\n hparams.num_residual_layers = 4\n hparams.batch_size = 32\n hparams.learning_rate_constant = 1.0\n return hparams\n\n\[email protected]_ranged_hparams\ndef autoencoder_range(rhp):\n \"\"\"Tuning grid of the main autoencoder params.\"\"\"\n rhp.set_float(\"dropout\", 0.01, 0.3)\n rhp.set_float(\"gan_loss_factor\", 0.01, 0.1)\n rhp.set_float(\"bottleneck_l2_factor\", 0.001, 0.1, scale=rhp.LOG_SCALE)\n rhp.set_discrete(\"bottleneck_warmup_steps\", [200, 2000])\n rhp.set_float(\"gumbel_temperature\", 0, 1)\n rhp.set_float(\"gumbel_noise_factor\", 0, 0.5)\n\n\[email protected]_ranged_hparams\ndef autoencoder_discrete_pong_range(rhp):\n \"\"\"Narrow tuning grid.\"\"\"\n rhp.set_float(\"dropout\", 0.0, 0.2)\n rhp.set_discrete(\"max_hidden_size\", [1024, 2048])\n\n\[email protected]_hparams\ndef autoencoder_stacked():\n \"\"\"Stacked autoencoder model.\"\"\"\n hparams = autoencoder_residual_discrete()\n hparams.bottleneck_bits = 128\n return hparams\n" ]
[ [ "tensorflow.layers.conv2d", "tensorflow.summary.scalar", "tensorflow.reshape", "tensorflow.variable_scope", "tensorflow.squeeze", "tensorflow.one_hot", "tensorflow.concat", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.get_variable_scope", "tensorflow.random_normal", "tensorflow.nn.softmax", "tensorflow.split", "tensorflow.reduce_sum", "tensorflow.nn.dropout", "tensorflow.nn.log_softmax", "tensorflow.losses.sparse_softmax_cross_entropy", "tensorflow.less", "tensorflow.random_normal_initializer", "tensorflow.layers.conv2d_transpose", "tensorflow.shape", "tensorflow.tanh", "tensorflow.expand_dims", "tensorflow.zeros_like", "tensorflow.random_uniform", "tensorflow.tile", "tensorflow.layers.dense", "tensorflow.zeros", "tensorflow.logging.info", "tensorflow.reduce_mean", "tensorflow.stop_gradient", "tensorflow.to_int32", "tensorflow.exp", "tensorflow.where", "tensorflow.argmax", "tensorflow.square", "tensorflow.maximum" ] ]
JulioDeBastiani/yolov3-tf2
[ "c349d352bffbf12a6668ffb90c2487b5f5f3aa33" ]
[ "tools/create_tensorflow_warmup.py" ]
[ "import os\nimport tensorflow as tf\n\nfrom os import path\nfrom absl import app, flags, logging\nfrom absl.flags import FLAGS\nfrom tensorflow_serving.apis import model_pb2, predict_pb2, prediction_log_pb2\n\nfrom yolov3_tf2.dataset import preprocess_image, load_tfrecord_dataset\n\n\nflags.DEFINE_string('dataset', None,\n 'path to the dataset, labels will be ignored')\nflags.DEFINE_string('model_name', 'persondet',\n 'name of the model on tensorflow serving')\nflags.DEFINE_string('input_tensor', 'input', 'name of the input tensor')\n\nflags.DEFINE_integer('size', 10, 'number of samples to take from the dataset')\nflags.DEFINE_integer('input_size', 416,\n 'size of the input tensor (a square image with three '\n 'channels)')\n\nflags.mark_flag_as_required('dataset')\n\n\ndef main(argv):\n\n count = 0\n images = []\n files = [path.join(path.join(FLAGS.dataset, f))\n for f in os.listdir(FLAGS.dataset)\n if path.isfile(path.join(FLAGS.dataset, f))\n ]\n\n files = [f for f in files if f.endswith(('.png', '.jpg', '.jpeg'))]\n\n for file in files:\n img_raw = tf.image.decode_image(open(file, 'rb').read(), channels=3)\n image = preprocess_image(img_raw, FLAGS.input_size)\n image = tf.expand_dims(image, 0)\n images.append(image)\n\n count += 1\n\n if count == FLAGS.size:\n break\n\n input_tensor = tf.concat(images, 0)\n\n with tf.io.TFRecordWriter('tf_serving_warmup_requests') as writer:\n request = predict_pb2.PredictRequest(\n model_spec=model_pb2.ModelSpec(\n name=FLAGS.model_name\n ),\n inputs={\n FLAGS.input_tensor: tf.make_tensor_proto(\n input_tensor,\n shape=input_tensor.shape,\n dtype=input_tensor.dtype\n )\n }\n )\n\n log = prediction_log_pb2.PredictionLog(\n predict_log=prediction_log_pb2.PredictLog(request=request)\n )\n\n writer.write(log.SerializeToString())\n logging.info('\"tf_serving_warmup_requests\" created with success!')\n logging.info('to use it paste it to the \"<model>/<version>/assets.extra\" folder on the serving configuration folder')\n\nif __name__ == '__main__':\n try:\n app.run(main)\n except SystemExit:\n pass\n" ]
[ [ "tensorflow.expand_dims", "tensorflow.make_tensor_proto", "tensorflow.concat", "tensorflow.io.TFRecordWriter" ] ]
jelleman8/TractSeg
[ "2a42efe6016141f3a32d46c8f509758302c5875b" ]
[ "tractseg/libs/tractometry.py" ]
[ "\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import defaultdict\n\nimport numpy as np\nfrom scipy.ndimage.morphology import binary_dilation\nfrom scipy.ndimage.interpolation import map_coordinates\nfrom dipy.segment.clustering import QuickBundles\nfrom dipy.segment.metric import AveragePointwiseEuclideanMetric\nfrom scipy.spatial import cKDTree\nfrom dipy.tracking.streamline import Streamlines\n\n\ndef _get_length_best_orig_peak(predicted_img, orig_img, x, y, z):\n predicted = predicted_img[x, y, z, :] # 1 peak\n orig = [orig_img[x, y, z, 0:3], orig_img[x, y, z, 3:6], orig_img[x, y, z, 6:9]] # 3 peaks\n\n angle1 = abs(np.dot(predicted, orig[0]) / (np.linalg.norm(predicted) * np.linalg.norm(orig[0]) + 1e-7))\n angle2 = abs(np.dot(predicted, orig[1]) / (np.linalg.norm(predicted) * np.linalg.norm(orig[1]) + 1e-7))\n angle3 = abs(np.dot(predicted, orig[2]) / (np.linalg.norm(predicted) * np.linalg.norm(orig[2]) + 1e-7))\n\n argmax = np.argmax([angle1, angle2, angle3])\n best_peak_len = np.linalg.norm(orig[argmax])\n return best_peak_len\n\n\ndef _orient_to_same_start_region(streamlines, beginnings):\n # (we could also use dipy.tracking.streamline.orient_by_streamline instead)\n streamlines_new = []\n for idx, sl in enumerate(streamlines):\n startpoint = sl[0]\n # Flip streamline if not in right order\n if beginnings[int(startpoint[0]), int(startpoint[1]), int(startpoint[2])] == 0:\n sl = sl[::-1, :]\n streamlines_new.append(sl)\n return streamlines_new\n\n\ndef evaluate_along_streamlines(scalar_img, streamlines, beginnings, nr_points, dilate=0, predicted_peaks=None,\n affine=None):\n # Runtime:\n # - default: 2.7s (test), 56s (all), 10s (test 4 bundles, 100 points)\n # - map_coordinate order 1: 1.9s (test), 26s (all), 6s (test 4 bundles, 100 points)\n # - map_coordinate order 3: 2.2s (test), 33s (all),\n # - values_from_volume: 2.5s (test), 43s (all),\n # - AFQ: ?s (test), ?s (all), 85s (test 4 bundles, 100 points)\n # => AFQ a lot slower than others\n\n for i in range(dilate):\n beginnings = binary_dilation(beginnings)\n beginnings = beginnings.astype(np.uint8)\n\n # THIS IS ONLY NEEDED FOR \"MANUAL\":\n # Move from convention \"0mm is in voxel center\" to convention \"0mm is in voxel corner\". This makes it easier\n # to calculate the voxel a streamline point is located in.\n # (dipy is working with the convention \"0mm is in voxel center\" therefore this is not needed there)\n # print(\"INFO: Adding 0.5 to streamlines\")\n # streamlines = fiber_utils.add_to_each_streamline(streamlines, 0.5)\n\n streamlines = _orient_to_same_start_region(streamlines, beginnings)\n\n ### Sampling ###\n\n #################################### Sampling \"MANUAL\" ############################\n # values = []\n # for i in range(nr_points):\n # values.append([])\n #\n # for idx, sl in enumerate(streamlines):\n # for jdx in range(sl.shape[0]): #iterate over nr_points\n # point = sl[jdx]\n # if predicted_peaks is not None:\n # scalar_value = _get_length_best_orig_peak(predicted_peaks, scalar_img,\n # int(point[0]), int(point[1]), int(point[2]))\n # else:\n # scalar_value = scalar_img[int(point[0]), int(point[1]), int(point[2])]\n # values[jdx].append(scalar_value)\n ###################################################################################\n\n #################################### Sampling map_coordinates #####################\n values = map_coordinates(scalar_img, np.array(streamlines).T, order=1)\n ###################################################################################\n\n #################################### Sampling values_from_volume ##################\n # streamlines = list(transform_streamlines(streamlines, affine)) # this has to be here; not remove previous one\n # values = np.array(values_from_volume(scalar_img, streamlines, affine=affine)).T\n ###################################################################################\n\n\n ### Aggregation ###\n\n #################################### Aggregating by MEAN ##########################\n # values_mean = np.array(values).mean(axis=1)\n # values_std = np.array(values).std(axis=1)\n # return values_mean, values_std\n ###################################################################################\n\n #################################### Aggregating by cKDTree #######################\n metric = AveragePointwiseEuclideanMetric()\n qb = QuickBundles(threshold=100., metric=metric)\n clusters = qb.cluster(streamlines)\n centroids = Streamlines(clusters.centroids)\n if len(centroids) > 1:\n print(\"WARNING: number clusters > 1 ({})\".format(len(centroids)))\n _, segment_idxs = cKDTree(centroids.data, 1, copy_data=True).query(streamlines, k=1) # (2000, 20)\n\n values_t = np.array(values).T # (2000, 20)\n\n # If we want to take weighted mean like in AFQ:\n # weights = dsa.gaussian_weights(Streamlines(streamlines))\n # values_t = weights * values_t\n # return np.sum(values_t, 0), None\n\n results_dict = defaultdict(list)\n for idx, sl in enumerate(values_t):\n for jdx, seg in enumerate(sl):\n results_dict[segment_idxs[idx, jdx]].append(seg)\n\n if len(results_dict.keys()) < nr_points:\n print(\"WARNING: found less than required points. Filling up with centroid values.\")\n centroid_values = map_coordinates(scalar_img, np.array([centroids[0]]).T, order=1)\n for i in range(nr_points):\n if len(results_dict[i]) == 0:\n results_dict[i].append(np.array(centroid_values).T[0, i])\n\n results_mean = []\n results_std = []\n for key in sorted(results_dict.keys()):\n value = results_dict[key]\n if len(value) > 0:\n results_mean.append(np.array(value).mean())\n results_std.append(np.array(value).std())\n else:\n print(\"WARNING: empty segment\")\n results_mean.append(0)\n results_std.append(0)\n\n return results_mean, results_std\n ###################################################################################\n\n #################################### AFQ (sampling + aggregation ##################\n # streamlines = list(transform_streamlines(streamlines, affine)) # this has to be here; not remove previous one\n # streamlines = Streamlines(streamlines)\n # weights = dsa.gaussian_weights(streamlines)\n # results_mean = dsa.afq_profile(scalar_img, streamlines, affine=affine, weights=weights)\n # results_std = None\n # return results_mean, results_std\n ###################################################################################\n" ]
[ [ "scipy.ndimage.morphology.binary_dilation", "numpy.argmax", "scipy.spatial.cKDTree", "numpy.array", "numpy.dot", "numpy.linalg.norm" ] ]
mitch-parker/rascore
[ "d6105db80359b43a7573edf7f36a756061be6965" ]
[ "src/rascore/util/scripts/annot_lig.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n Copyright 2022 Mitchell Isaac Parker\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n\"\"\"\n\nimport pandas as pd\nfrom tqdm import tqdm\nimport concurrent.futures\n\nfrom ..functions.chem import get_lig_smiles, is_lig_match, get_lig_simi\nfrom ..functions.lst import lst_unique, lst_to_str, res_to_lst, type_lst, sort_lst\nfrom ..functions.lig import lig_col_lst, lig_lst_dict\nfrom ..functions.coord import (\n load_coord,\n get_resname,\n get_neighbors,\n get_resnum,\n get_residues,\n get_reschainid,\n get_residue_cont,\n is_aa,\n is_het,\n)\nfrom ..functions.col import (\n core_path_col,\n modelid_col,\n chainid_col,\n pharm_lig_col,\n pharm_lig_site_col,\n pharm_lig_match_col,\n pharm_lig_smiles_col,\n bound_lig_cont_col\n)\nfrom ..functions.table import get_df_at_index, fix_val\nfrom ..functions.path import save_table\n\n\ndef build_lig_df(\n df,\n index,\n lig_dir=None,\n site_dict=None,\n match_dict=None,\n other_site=\"Other\",\n other_match=\"Unclassified\",\n none_site=\"None\",\n none_match=\"None\",\n max_site_dist=4,\n coord_path_col=None,\n):\n\n if coord_path_col is None:\n coord_path_col = core_path_col\n\n df = get_df_at_index(df, index)\n\n coord_path = df.at[index, coord_path_col]\n modelid = df.at[index, modelid_col]\n chainid = df.at[index, chainid_col]\n\n lig_dict = dict()\n\n for lig_col in lig_col_lst:\n\n lig_dict[lig_col] = list()\n\n structure = load_coord(coord_path)\n neighbors = get_neighbors(structure[fix_val(modelid, return_int=True)][chainid])\n\n cont_lst = list()\n site_lst = list()\n match_lst = list()\n smiles_lst = list()\n\n for residue in get_residues(structure):\n if is_het(residue):\n resid_cont_lst = lst_unique(\n [\n get_resnum(x)\n for x in get_residue_cont(\n neighbors,\n residue,\n max_dist=max_site_dist,\n level=\"R\",\n )\n if (get_resnum(x) < 50000)\n and (get_reschainid(x) == chainid)\n and (is_aa(x))\n ]\n )\n\n if len(resid_cont_lst) > 0:\n resname = get_resname(residue)\n lig_class = False\n is_pharm = False\n for lig_col in lig_col_lst:\n if resname in lig_lst_dict[lig_col]:\n lig_dict[lig_col].append(resname)\n lig_class = True\n if lig_col == pharm_lig_col:\n is_pharm = True\n\n if not lig_class:\n lig_dict[pharm_lig_col].append(resname)\n is_pharm = True\n\n\n if is_pharm:\n \n if site_dict is not None:\n \n resid_cont_str = resname\n resid_cont_str += ':'\n resid_cont_str += lst_to_str(resid_cont_lst)\n cont_lst.append(resid_cont_str)\n\n max_cont = 0\n pharm_site = other_site\n for site_name, site_cont_lst in site_dict.items():\n site_cont = len([x for x in site_cont_lst if x in resid_cont_lst])\n if site_cont > max_cont:\n pharm_site = site_name\n max_cont = site_cont\n site_lst.append(pharm_site)\n\n if match_dict is not None:\n\n resid_smiles_str = resname\n resid_smiles_str += ':'\n resid_smiles_str += get_lig_smiles(resname, lig_dir=lig_dir)\n smiles_lst.append(resid_smiles_str)\n\n if pharm_site in list(match_dict.keys()):\n pharm_match = other_match\n match_name_lst = list()\n match_simi_lst = list()\n for match_name, query_lst in match_dict[pharm_site].items():\n is_match = is_lig_match(\n resname, query_lst, lig_dir=lig_dir\n )\n if is_match:\n for query in query_lst:\n match_name_lst.append(match_name)\n match_simi_lst.append(\n get_lig_simi(\n resname, query, lig_dir=lig_dir\n )\n )\n if len(match_name_lst) > 0:\n pharm_match = match_name_lst[\n match_simi_lst.index(max(match_simi_lst))\n ]\n pharm_match = f\"{pharm_site}.{pharm_match}\"\n else:\n pharm_match = other_site\n match_lst.append(pharm_match)\n\n for lig_col in lig_col_lst:\n df.at[index, lig_col] = lst_to_str(sort_lst(lst_unique(lig_dict[lig_col])))\n\n df.at[index, pharm_lig_site_col] = lst_to_str(\n sort_lst(lst_unique(site_lst)), join_txt=\"|\", empty=none_site\n )\n df.at[index, pharm_lig_match_col] = lst_to_str(\n sort_lst(lst_unique(match_lst)), join_txt=\"|\", empty=none_match\n )\n df.at[index, pharm_lig_smiles_col] = lst_to_str(smiles_lst, join_txt=\"|\")\n df.at[index, bound_lig_cont_col] = lst_to_str(cont_lst, join_txt=\"|\")\n\n return df\n\n\ndef annot_lig(\n df,\n lig_table_path=None,\n lig_dir=None,\n site_dict=None,\n match_dict=None,\n other_site=\"Other\",\n other_match=\"Unclassified\",\n none_site=\"None\",\n none_match=\"None\",\n max_site_dist=4,\n coord_path_col=None,\n num_cpu=1,\n):\n\n df = df.reset_index(drop=True)\n\n if site_dict is not None:\n for site_name, site_cont in site_dict.items():\n site_dict[site_name] = res_to_lst(site_cont)\n\n if match_dict is not None:\n for site_name in list(match_dict.keys()):\n for match_name, query_lst in match_dict[site_name].items():\n match_dict[site_name][match_name] = type_lst(query_lst)\n\n lig_df = pd.DataFrame()\n\n if num_cpu == 1:\n for index in tqdm(\n list(df.index.values), desc=\"Annotating ligands\", position=0, leave=True\n ):\n\n lig_df = pd.concat(\n [\n lig_df,\n build_lig_df(\n df,\n index,\n lig_dir=lig_dir,\n site_dict=site_dict,\n match_dict=match_dict,\n other_site=other_site,\n other_match=other_match,\n none_site=none_site,\n none_match=none_match,\n max_site_dist=max_site_dist,\n coord_path_col=coord_path_col,\n ),\n ],\n sort=False,\n )\n else:\n with concurrent.futures.ProcessPoolExecutor(max_workers=num_cpu) as executor:\n job_lst = [\n executor.submit(\n build_lig_df,\n df,\n index,\n site_dict=site_dict,\n match_dict=match_dict,\n other_site=other_site,\n other_match=other_match,\n none_site=none_site,\n none_match=none_match,\n max_site_dist=max_site_dist,\n coord_path_col=coord_path_col,\n )\n for index in list(df.index.values)\n ]\n\n for job in tqdm(\n concurrent.futures.as_completed(job_lst),\n desc=\"Annotating ligands\",\n total=len(job_lst),\n miniters=1,\n position=0,\n leave=True,\n ):\n\n lig_df = pd.concat([lig_df, job.result()], sort=False)\n\n lig_df = lig_df.reset_index(drop=True)\n\n print(\"Annotated ligands!\")\n\n if lig_table_path is not None:\n save_table(lig_table_path, lig_df)\n else:\n return lig_df\n" ]
[ [ "pandas.DataFrame" ] ]
neerajprad/pyro
[ "3b5b2c5de208209365bf26f239f12521de68acc4" ]
[ "tests/infer/test_abstract_infer.py" ]
[ "from __future__ import absolute_import, division, print_function\n\nimport torch\n\nimport pyro\nimport pyro.distributions as dist\nimport pyro.poutine as poutine\nfrom pyro.infer import EmpiricalMarginal, TracePredictive\nfrom pyro.infer.mcmc import MCMC, NUTS\nfrom tests.common import assert_equal\n\n\ndef model(num_trials):\n phi_prior = dist.Uniform(num_trials.new_tensor(0.), num_trials.new_tensor(1.))\\\n .expand_by([num_trials.shape[0]])\n success_prob = pyro.sample(\"phi\", phi_prior)\n return pyro.sample(\"obs\", dist.Binomial(num_trials, success_prob))\n\n\ndef test_posterior_predictive():\n true_probs = torch.ones(5) * 0.7\n num_trials = torch.ones(5) * 1000\n num_success = dist.Binomial(num_trials, true_probs).sample()\n conditioned_model = poutine.condition(model, data={\"obs\": num_success})\n nuts_kernel = NUTS(conditioned_model, adapt_step_size=True)\n mcmc_run = MCMC(nuts_kernel, num_samples=1000, warmup_steps=200).run(num_trials)\n posterior_predictive = TracePredictive(model, mcmc_run, num_samples=10000).run(num_trials)\n marginal_return_vals = EmpiricalMarginal(posterior_predictive)\n assert_equal(marginal_return_vals.mean, torch.ones(5) * 700, prec=30)\n" ]
[ [ "torch.ones" ] ]
j2k0618/PECNet_nuScenes
[ "9bed2f846ddae11c21b9a4df6487e5c80e9eb01f" ]
[ "rasterization_q10/input_representation/agents.py" ]
[ "# nuScenes dev-kit.\n# Code written by Freddy Boulton, 2020.\nimport colorsys\nfrom typing import Any, Dict, List, Tuple, Callable\n\nimport cv2\nimport numpy as np\nfrom pyquaternion import Quaternion\n\nfrom nuscenes.prediction import PredictHelper\nfrom nuscenes.prediction.helper import quaternion_yaw\nfrom nuscenes.prediction.input_representation.interface import AgentRepresentation\nfrom nuscenes.prediction.input_representation.utils import convert_to_pixel_coords, get_crops, get_rotation_matrix\n\nHistory = Dict[str, List[Dict[str, Any]]]\n\n\ndef curvature(A, B, C):\n # Augment Columns\n A_aug = np.append(A, 1)\n B_aug = np.append(B, 1)\n C_aug = np.append(C, 1)\n\n # Calculate Area of Triangle\n matrix = np.column_stack((A_aug, B_aug, C_aug))\n area = 1 / 2 * np.linalg.det(matrix)\n\n # Special case: Two or more points are equal\n if np.all(A == B) or np.all(B == C):\n curvature = 0\n else:\n curvature = 4 * area / (np.linalg.norm(A - B) * np.linalg.norm(B - C) * np.linalg.norm(C - A))\n\n # Return Menger curvature\n return curvature\n\n\ndef angle_diff(a, b):\n if np.linalg.norm(a) == 0 or np.linalg.norm(b) == 0:\n return 0\n au = a / np.linalg.norm(a)\n bu = b / np.linalg.norm(b)\n return np.arccos(np.clip(np.dot(au, bu), -1.0, 1.0))\n\n\ndef calculateCurve(points):\n if len(points) < 3:\n return 0\n return abs(angle_diff(points[1] - points[0], points[-1] - points[0]))\n\n\n# def calculateCurve(points):\n# if len(points) < 3:\n# return 0\n# curvature_list = np.empty(0)\n# for i in range(len(points) - 2):\n# A = points[i]\n# B = points[i + 1]\n# C = points[i + 2]\n# curvature_value = abs(curvature(A, B, C))\n# curvature_list = np.append(curvature_list, curvature_value)\n# return np.average(curvature_list)\n\n\ndef pixels_to_box_corners(row_pixel: int,\n column_pixel: int,\n length_in_pixels: float,\n width_in_pixels: float,\n yaw_in_radians: float) -> np.ndarray:\n \"\"\"\n Computes four corners of 2d bounding box for agent.\n The coordinates of the box are in pixels.\n :param row_pixel: Row pixel of the agent.\n :param column_pixel: Column pixel of the agent.\n :param length_in_pixels: Length of the agent.\n :param width_in_pixels: Width of the agent.\n :param yaw_in_radians: Yaw of the agent (global coordinates).\n :return: numpy array representing the four corners of the agent.\n \"\"\"\n\n # cv2 has the convention where they flip rows and columns so it matches\n # the convention of x and y on a coordinate plane\n # Also, a positive angle is a clockwise rotation as opposed to counterclockwise\n # so that is why we negate the rotation angle\n coord_tuple = ((column_pixel, row_pixel), (length_in_pixels, width_in_pixels), -yaw_in_radians * 180 / np.pi)\n\n box = cv2.boxPoints(coord_tuple)\n\n return box\n\n\ndef get_track_box(annotation: Dict[str, Any],\n center_coordinates: Tuple[float, float],\n center_pixels: Tuple[float, float],\n resolution: float = 0.1) -> np.ndarray:\n \"\"\"\n Get four corners of bounding box for agent in pixels.\n :param annotation: The annotation record of the agent.\n :param center_coordinates: (x, y) coordinates in global frame\n of the center of the image.\n :param center_pixels: (row_index, column_index) location of the center\n of the image in pixel coordinates.\n :param resolution: Resolution pixels/meter of the image.\n \"\"\"\n\n assert resolution > 0\n\n location = annotation['translation'][:2]\n yaw_in_radians = quaternion_yaw(Quaternion(annotation['rotation']))\n\n row_pixel, column_pixel = convert_to_pixel_coords(location,\n center_coordinates,\n center_pixels, resolution)\n\n width = annotation['size'][0] / resolution\n length = annotation['size'][1] / resolution\n\n # Width and length are switched here so that we can draw them along the x-axis as\n # opposed to the y. This makes rotation easier.\n return pixels_to_box_corners(row_pixel, column_pixel, length, width, yaw_in_radians)\n\n\ndef reverse_history(history: History) -> History:\n \"\"\"\n Reverse history so that most distant observations are first.\n We do this because we want to draw more recent bounding boxes on top of older ones.\n :param history: result of get_past_for_sample PredictHelper method.\n :return: History with the values reversed.\n \"\"\"\n return {token: anns[::-1] for token, anns in history.items()}\n\n\ndef add_present_time_to_history(current_time: List[Dict[str, Any]],\n history: History) -> History:\n \"\"\"\n Adds the sample annotation records from the current time to the\n history object.\n :param current_time: List of sample annotation records from the\n current time. Result of get_annotations_for_sample method of\n PredictHelper.\n :param history: Result of get_past_for_sample method of PredictHelper.\n :return: History with values from current_time appended.\n \"\"\"\n\n for annotation in current_time:\n token = annotation['instance_token']\n\n if token in history:\n\n # We append because we've reversed the history\n history[token].append(annotation)\n\n else:\n history[token] = [annotation]\n\n return history\n\n\ndef fade_color(color: Tuple[int, int, int],\n step: int,\n total_number_of_steps: int) -> Tuple[int, int, int]:\n \"\"\"\n Fades a color so that past observations are darker in the image.\n :param color: Tuple of ints describing an RGB color.\n :param step: The current time step.\n :param total_number_of_steps: The total number of time steps\n the agent has in the image.\n :return: Tuple representing faded rgb color.\n \"\"\"\n\n LOWEST_VALUE = 0.4\n\n if step == total_number_of_steps:\n return color\n\n hsv_color = colorsys.rgb_to_hsv(*color)\n\n increment = (float(hsv_color[2]) / 255. - LOWEST_VALUE) / total_number_of_steps\n\n new_value = LOWEST_VALUE + step * increment\n\n new_rgb = colorsys.hsv_to_rgb(float(hsv_color[0]),\n float(hsv_color[1]),\n new_value * 255.)\n return new_rgb\n\n\ndef default_colors(category_name: str) -> Tuple[int, int, int]:\n \"\"\"\n Maps a category name to an rgb color (without fading).\n :param category_name: Name of object category for the annotation.\n :return: Tuple representing rgb color.\n \"\"\"\n\n if 'vehicle' in category_name:\n return 255, 255, 0 # yellow\n elif 'object' in category_name:\n return 204, 0, 204 # violet\n elif 'human' in category_name or 'animal' in category_name:\n return 255, 153, 51 # orange\n else:\n raise ValueError(f\"Cannot map {category_name} to a color.\")\n\n\ndef draw_agent_boxes(center_agent_annotation: Dict[str, Any],\n center_agent_pixels: Tuple[float, float],\n agent_history: History,\n base_image: np.ndarray,\n get_color: Callable[[str], Tuple[int, int, int]],\n resolution: float = 0.1) -> None:\n \"\"\"\n Draws past sequence of agent boxes on the image.\n :param center_agent_annotation: Annotation record for the agent\n that is in the center of the image.\n :param center_agent_pixels: Pixel location of the agent in the\n center of the image.\n :param agent_history: History for all agents in the scene.\n :param base_image: Image to draw the agents in.\n :param get_color: Mapping from category_name to RGB tuple.\n :param resolution: Size of the image in pixels / meter.\n :return: None.\n \"\"\"\n\n agent_x, agent_y = center_agent_annotation['translation'][:2]\n\n for instance_token, annotations in agent_history.items():\n\n num_points = len(annotations)\n\n for i, annotation in enumerate(annotations):\n\n box = get_track_box(annotation, (agent_x, agent_y), center_agent_pixels, resolution)\n\n if instance_token == center_agent_annotation['instance_token']:\n color = (255, 0, 0)\n else:\n color = get_color(annotation['category_name'])\n\n # Don't fade the colors if there is no history\n if num_points > 1:\n color = fade_color(color, i, num_points - 1)\n\n cv2.fillPoly(base_image, pts=[np.int0(box)], color=color)\n\n\nclass AgentBoxesWithFadedHistory(AgentRepresentation):\n \"\"\"\n Represents the past sequence of agent states as a three-channel\n image with faded 2d boxes.\n \"\"\"\n\n def __init__(self, helper: PredictHelper,\n seconds_of_history: float = 2,\n frequency_in_hz: float = 2,\n resolution: float = 0.1, # meters / pixel\n meters_ahead: float = 40, meters_behind: float = 10,\n meters_left: float = 25, meters_right: float = 25,\n color_mapping: Callable[[str], Tuple[int, int, int]] = None):\n\n self.helper = helper\n self.seconds_of_history = seconds_of_history\n self.frequency_in_hz = frequency_in_hz\n\n if not resolution > 0:\n raise ValueError(f\"Resolution must be positive. Received {resolution}.\")\n\n self.resolution = resolution\n\n self.meters_ahead = meters_ahead\n self.meters_behind = meters_behind\n self.meters_left = meters_left\n self.meters_right = meters_right\n\n if not color_mapping:\n color_mapping = default_colors\n\n self.color_mapping = color_mapping\n\n def make_representation(self, instance_token: str, sample_token: str) -> np.ndarray:\n \"\"\"\n Draws agent boxes with faded history into a black background.\n :param instance_token: Instance token.\n :param sample_token: Sample token.\n :return: np.ndarray representing a 3 channel image.\n \"\"\"\n\n # Taking radius around track before to ensure all actors are in image\n buffer = max([self.meters_ahead, self.meters_behind,\n self.meters_left, self.meters_right]) * 2\n\n image_side_length = int(buffer / self.resolution)\n\n # We will center the track in the image\n central_track_pixels = (image_side_length / 2, image_side_length / 2)\n\n base_image = np.zeros((image_side_length, image_side_length, 3))\n\n history = self.helper.get_past_for_sample(sample_token,\n self.seconds_of_history,\n in_agent_frame=False,\n just_xy=False)\n history = reverse_history(history)\n\n present_time = self.helper.get_annotations_for_sample(sample_token)\n\n history = add_present_time_to_history(present_time, history)\n\n center_agent_annotation = self.helper.get_sample_annotation(instance_token, sample_token)\n\n draw_agent_boxes(center_agent_annotation, central_track_pixels,\n history, base_image, resolution=self.resolution, get_color=self.color_mapping)\n\n center_agent_yaw = quaternion_yaw(Quaternion(center_agent_annotation['rotation']))\n rotation_mat = get_rotation_matrix(base_image.shape, center_agent_yaw)\n\n rotated_image = cv2.warpAffine(base_image, rotation_mat, (base_image.shape[1],\n base_image.shape[0]))\n\n row_crop, col_crop = get_crops(self.meters_ahead, self.meters_behind,\n self.meters_left, self.meters_right, self.resolution,\n image_side_length)\n\n return rotated_image[row_crop, col_crop].astype('uint8')\n\n def generate_mask(self, translation, rotation, sample_token: str, seconds=3, show_agent=True):\n buffer = max([self.meters_ahead, self.meters_behind, self.meters_left, self.meters_right]) * 2\n image_side_length = int(buffer / self.resolution)\n central_track_pixels = (image_side_length / 2, image_side_length / 2)\n\n base_image = np.zeros((image_side_length, image_side_length, 3))\n present_time_annotation = self.helper.get_annotations_for_sample(sample_token)\n\n agent_x, agent_y = translation[:2]\n\n translation_xy = []\n past_xy = []\n future_xy = []\n\n for annotation in present_time_annotation:\n past_xy_temp = self.helper.get_past_for_agent(\n annotation['instance_token'], sample_token, seconds=seconds, in_agent_frame=False)\n future_xy_temp = self.helper.get_future_for_agent(\n annotation['instance_token'], sample_token, seconds=seconds, in_agent_frame=False)\n\n # vel = self.helper.get_velocity_for_agent(annotation['instance_token'], sample_token)\n # accel = self.helper.get_acceleration_for_agent(annotation['instance_token'], sample_token)\n # yaw_rate = self.helper.get_heading_change_rate_for_agent(annotation['instance_token'], sample_token)\n\n if annotation['category_name'].split('.')[0] != 'vehicle':\n continue\n\n translation_xy.append(annotation['translation'][:2])\n past_xy.append(past_xy_temp)\n future_xy.append(future_xy_temp)\n\n if show_agent:\n box = get_track_box(annotation, (agent_x, agent_y), central_track_pixels, self.resolution)\n color = self.color_mapping(annotation['category_name'])\n cv2.fillPoly(base_image, pts=[np.int0(box)], color=color)\n\n xy_global = [np.asarray(past_xy), np.asarray(future_xy), np.asarray(translation_xy)]\n\n center_agent_yaw = quaternion_yaw(Quaternion(rotation))\n rotation_mat = get_rotation_matrix(base_image.shape, center_agent_yaw)\n\n rotated_image = cv2.warpAffine(base_image, rotation_mat, (base_image.shape[1],\n base_image.shape[0]))\n\n row_crop, col_crop = get_crops(self.meters_ahead, self.meters_behind,\n self.meters_left, self.meters_right, self.resolution,\n image_side_length)\n\n return rotated_image[row_crop, col_crop].astype('uint8'), xy_global\n\n def generate_virtual_mask(self, translation, rotation, lanes, sample_token: str, show_agent=True,\n past_trj_len=4, future_trj_len=6, min_dist=6):\n buffer = max([self.meters_ahead, self.meters_behind, self.meters_left, self.meters_right]) * 2\n image_side_length = int(buffer / self.resolution)\n central_track_pixels = (image_side_length / 2, image_side_length / 2)\n\n base_image = np.zeros((image_side_length, image_side_length, 3))\n\n translation_xy = []\n past_xy = []\n future_xy = []\n\n for lane in lanes:\n length = len(lane)\n\n if length < (past_trj_len + future_trj_len + 1):\n continue\n\n location = None\n current_index = None\n for _ in range(5):\n is_collide = False\n if (length - past_trj_len - future_trj_len - 1) < 1:\n continue\n # start_index = np.random.randint(low=0, high=(length - past_trj_len - future_trj_len - 1))\n start_index = 0\n max_gap = (length - start_index) // (past_trj_len + future_trj_len + 1)\n if max_gap < 2:\n continue\n # gap = np.random.randint(low=1, high=max_gap+1)\n gap = max_gap\n # current_index = start_index + (gap * past_trj_len)\n # location_ = lane[current_index, :2]\n\n mask = np.arange(start_index, length, step=gap)\n lane_ = lane[mask]\n\n current_index = past_trj_len\n location_ = lane_[current_index, :2]\n\n # check collision\n for xy in translation_xy:\n diff = location_ - xy\n if np.linalg.norm(diff) < min_dist:\n is_collide = True\n break\n if not is_collide:\n location = location_\n lane = lane_\n break\n\n if location is None:\n continue\n\n translation_xy.append(location)\n past_xy.append(lane[current_index - past_trj_len:current_index])\n future_xy.append(lane[current_index + 1:current_index + future_trj_len + 1])\n\n # draw virtual agent mask\n if show_agent:\n agent_x, agent_y = translation[:2]\n\n ax, ay = lane[current_index, 0], lane[current_index, 1]\n bx, by = lane[current_index + 1, 0], lane[current_index + 1, 1]\n if ax == bx:\n bx += 0.0001\n rot = np.arctan((by - ay) / (bx - ax))\n\n yaw_in_radians = quaternion_yaw(Quaternion(axis=[0, 0, 1], angle=rot))\n row_pixel, column_pixel = convert_to_pixel_coords(\n location, (agent_x, agent_y), central_track_pixels, self.resolution)\n size = [2.2, 5.6, 2.1]\n width = size[0] / self.resolution\n length = size[1] / self.resolution\n box = pixels_to_box_corners(row_pixel, column_pixel, length, width, yaw_in_radians)\n color = (255, 255, 0)\n cv2.fillPoly(base_image, pts=[np.int0(box)], color=color)\n\n xy_global = [np.asarray(past_xy), np.asarray(future_xy), np.asarray(translation_xy)]\n\n center_agent_yaw = quaternion_yaw(Quaternion(rotation))\n rotation_mat = get_rotation_matrix(base_image.shape, center_agent_yaw)\n\n rotated_image = cv2.warpAffine(base_image, rotation_mat, (base_image.shape[1], base_image.shape[0]))\n\n row_crop, col_crop = get_crops(self.meters_ahead, self.meters_behind,\n self.meters_left, self.meters_right, self.resolution,\n image_side_length)\n\n return rotated_image[row_crop, col_crop].astype('uint8'), xy_global\n" ]
[ [ "numpy.int0", "numpy.append", "numpy.zeros", "numpy.arctan", "numpy.linalg.det", "numpy.column_stack", "numpy.asarray", "numpy.arange", "numpy.all", "numpy.dot", "numpy.linalg.norm" ] ]
victorgmlyra/GA_routing
[ "fe229f55620972c36822bc333953069e67e17a59" ]
[ "roteamento.py" ]
[ "from evo import Evo\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nfrom itertools import islice\n\n\ndef k_shortest_paths(G, source, target, k, weight=None):\n return list(\n islice(nx.shortest_simple_paths(G, source, target, weight=weight), k)\n )\n\ndef draw_graph_with_subpaths(best, k_short_paths, pos):\n # Teste print \n fig, ax = plt.subplots()\n SG=nx.Graph(name=\"graph\")\n routes = []\n for i, path in enumerate(best):\n s_path = k_short_paths[i, path]\n routes.append(s_path)\n\n\n for i in range(0,len(routes)):\n print('Path for node',i+1,': ',routes[i])\n\n edges = []\n for r in routes:\n route_edges = [(r[n],r[n+1]) for n in range(len(r)-1)]\n SG.add_nodes_from(r)\n SG.add_edges_from(route_edges)\n edges.append(route_edges)\n\n nx.draw_networkx_nodes(SG,pos=pos)\n nx.draw_networkx_labels(SG,pos=pos)\n colors = [tuple(np.random.rand(3)) for _ in range(len(pos)-1)]\n linewidths = [1+n/2 for n in range(len(pos)-1)]\n for ctr, edgelist in enumerate(edges):\n nx.draw_networkx_edges(SG,pos=pos,edgelist=edgelist,edge_color = colors[ctr], width=linewidths[ctr])\n\ndef draw_graph(G, pos, draw_weight=False):\n # Colors\n color_map = ['#1f78b4'] * len(G.nodes)\n color_map[0] = 'g'\n\n # add axis\n fig, ax = plt.subplots()\n # nx.draw(G, pos=pos, node_color='b', ax=ax)\n nx.draw(G, pos=pos, node_size=200, ax=ax, node_color=color_map) # draw nodes and edges\n nx.draw_networkx_labels(G, pos=pos) # draw node labels/names\n if draw_weight:\n # # draw edge weights\n labels = nx.get_edge_attributes(G, 'weight')\n labels = {key : round(labels[key], 2) for key in labels}\n nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, ax=ax)\n plt.axis(\"on\")\n ax.set_xlim(-1.5, 100*1.1)\n ax.set_ylim(-1.5, 100*1.1)\n ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)\n # plt.show()\n\ndef build_graph(params, load=True):\n # Create points\n if load:\n nodes = np.load('nodes.npy')\n else:\n nodes = np.random.rand(params['num_points'], 2) * 100\n nodes[0] = np.array([0, 0])\n # nodes[num_points-1] = np.array([100, 100])\n\n # np.save('nodes.npy', nodes)\n\n edges = []\n for i in range(len(nodes)):\n for j in range(i+1, len(nodes)):\n dist = np.linalg.norm(nodes[i] - nodes[j])\n if dist < params['max_dist']:\n edges.append((i, j, dist))\n\n # Create graph\n G = nx.Graph()\n G.add_weighted_edges_from(edges)\n\n # Plot graph\n points = list(map(tuple, nodes))\n pos = {i: point for i, point in enumerate(points)}\n draw_graph(G, points, True)\n\n return G, pos\n\ndef find_all_k_short_paths(G, params):\n # K Shortest Paths\n k_short_paths = []\n for i in range(1, params['num_points']):\n s_path = k_shortest_paths(G, 0, i, params['num_paths'], \"weight\")\n k_short_paths.append(s_path)\n\n k_short_paths = np.array(k_short_paths)\n return k_short_paths\n\ndef find_optimal(k_short_paths, pos, params):\n evolution = Evo(k_short_paths, params['num_paths'], params['num_pop'], pos, params['mut_chance'], params['fitness_alg'])\n return evolution.fit(params['num_iteractions'])\n\nif __name__ == '__main__':\n # PARAMETERS\n params = {\n # Graph building\n 'num_points': 20,\n 'load_graph': True,\n 'max_dist': 40,\n # K shortest paths\n 'num_paths': 5,\n # GA params\n 'num_pop': 100,\n 'num_iteractions': 100,\n 'mut_chance': 0.1,\n 'fitness_alg': 'lifetime', # energy, lifetime\n # Plot\n 'plot': True\n }\n\n # Build graph\n G, pos = build_graph(params, params['load_graph'])\n k_short_paths = find_all_k_short_paths(G, params)\n\n # Run genetic algorithm\n num_runs = 1 # Change to run multiple times\n all_lifetimes, all_sum_energies = [], []\n for i in range(num_runs):\n best, evol_fit, lifetime, sum_energies, node = find_optimal(k_short_paths, pos, params)\n print('Best: ', best, ' Lifetime: ', lifetime, ' for node: ', node, ' Sum energies: ',sum_energies)\n print()\n all_lifetimes.append(lifetime)\n all_sum_energies.append(sum_energies)\n\n # Plot do gráfico\n fig, ax = plt.subplots()\n plt.plot(evol_fit)\n # Plot graph with subpaths\n draw_graph_with_subpaths(best, k_short_paths, pos)\n if params['plot'] == True:\n plt.show()\n\n # Print\n print('\\nMean best lifetimes: {:.3f}'.format(np.mean(np.array(all_lifetimes))))\n print('Mean best sum energies: {:.3f}'.format(np.mean(np.array(all_sum_energies))))\n" ]
[ [ "numpy.load", "matplotlib.pyplot.axis", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show", "numpy.random.rand", "numpy.array", "matplotlib.pyplot.plot", "numpy.linalg.norm" ] ]
ezw21/Geospatial_exw
[ "b128cbbdf6fff929e478d46baadc2259e0be1c25" ]
[ "Matcher/Feature_Matching.py" ]
[ "#__author__ = \"Edward Wong\"\n#__copyright__ = \"Copyright 2021, The X Project\"\n#__credits__ = [\"Edward Wong\"]\n#__license__ = \"MIT\"\n#__version__ = \"1.0.1\"\n#__maintainer__ = \"Edward Wong\"\n#__email__ = \"[email protected]\"\n\n\nimport numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\n\nimg1 = cv.imread(\n \"differencer/17APR08224828-M3DS-013930604400_01_P002-BROWSE.jpg\",\n cv.IMREAD_GRAYSCALE,\n) # queryImage\nimg2 = cv.imread(\n \"differencer/17APR07214525-M3DS-013930604400_01_P003-BROWSE.jpg\",\n cv.IMREAD_GRAYSCALE,\n) # trainImage\n\n# Initiate SIFT detector\nsift = cv.SIFT_create()\n\n# find the keypoints and descriptors with SIFT\nkp1, des1 = sift.detectAndCompute(img1, None)\nkp2, des2 = sift.detectAndCompute(img2, None)\n\n# FLANN parameters\nFLANN_INDEX_KDTREE = 1\nindex_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\nsearch_params = dict(checks=50) # or pass empty dictionary\nflann = cv.FlannBasedMatcher(index_params, search_params)\nmatches = flann.knnMatch(des1, des2, k=2)\n\n# Need to draw only good matches, so create a mask\nmatchesMask = [[0, 0] for i in range(len(matches))]\n\n# Ratio test as per Lowe's paper\nfor i, (m, n) in enumerate(matches):\n if m.distance < 0.7 * n.distance:\n matchesMask[i] = [1, 0]\ndraw_params = dict(\n matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=matchesMask,\n flags=cv.DrawMatchesFlags_DEFAULT,\n)\nimg3 = cv.drawMatchesKnn(img1, kp1, img2, kp2, matches, None, **draw_params)\nplt.imshow(\n img3,\n), plt.show()\n" ]
[ [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.show" ] ]
qiumuyang/NJU-DIP2021
[ "dda047ffc8752cfbb3a0d618c38480b772eaaa22" ]
[ "algorithm.py" ]
[ "from typing import List, Callable\nfrom functools import wraps\nimport numpy as np\nfrom numpy import ndarray\nfrom numpy.fft import fft2, fftshift, ifft2, ifftshift\n\n\ndef split_channel(func: Callable[[ndarray], ndarray]):\n \"\"\" Split channels of the input image.\n\n Assume the decorated function only accept gray-scale image. If the input has more than one channels, separately\n call decorated function on each channel and merge the result at the end.\n \"\"\"\n\n @wraps(func)\n def wrapper(*args):\n img: ndarray = args[0]\n if img.ndim == 2: # gray-scale\n return func(img)\n elif img.ndim == 3: # rgb\n channels = [func(img[:, :, i]) for i in range(3)]\n return np.dstack(channels)\n else:\n raise ValueError('invalid image ndim:', img.ndim)\n\n return wrapper\n\n\ndef position_index(arr: ndarray, idx: ndarray) -> ndarray:\n \"\"\" Select from arr with each index in idx.\n\n :param arr: shape=(L, d)\n :param idx: shape=(L,), idx in [0, d)\n :return: arr[idx] shape=(L,)\n \"\"\"\n onehot = np.eye(arr.shape[1], dtype='int')[idx]\n return (arr * onehot).sum(axis=1)\n\n\nclass Neighbors:\n \"\"\" Get k*k neighbors for each item in the input array.\n\n \"\"\"\n\n def __init__(self, arr: ndarray, k: int) -> None:\n assert (k % 2 == 1)\n assert (arr.ndim == 2)\n\n self.k = k\n\n p = k // 2\n h, w = arr.shape\n xs = np.repeat(np.arange(w), h).reshape(w, h).transpose()\n ys = np.repeat(np.arange(h), w).reshape(h, w)\n\n tmp = []\n for y in range(-p, p + 1):\n for x in range(-p, p + 1):\n xs_offset = xs + np.ones(arr.shape, dtype='int') * x\n ys_offset = ys + np.ones(arr.shape, dtype='int') * y\n xs_offset[xs_offset < 0] = 0\n xs_offset[xs_offset >= w] = w - 1\n ys_offset[ys_offset < 0] = 0\n ys_offset[ys_offset >= h] = h - 1\n tmp.append(arr[ys_offset, xs_offset])\n\n self.neighbors: ndarray = np.dstack(tmp)\n\n def at(self, x: int, y: int) -> ndarray:\n y += self.k // 2\n x += self.k // 2\n return self.neighbors[:, :, y * self.k + x]\n\n\ndef plane(img: ndarray) -> ndarray:\n def kth_plane(img: ndarray, k: int) -> ndarray:\n return np.where(img & (1 << k), 1, 0)\n\n # prepare each bit-plane (9th is empty)\n _planes: List[ndarray] = [kth_plane(img, i) for i in reversed(range(8))]\n _planes.append(np.ones(img.shape))\n\n # horizontally stack (group by 3)\n _stacked: List[ndarray] = [np.hstack(_planes[i * 3:i * 3 + 3]) for i in range(3)]\n return np.vstack(_stacked)\n\n\n@split_channel\ndef equalize(img: ndarray) -> ndarray:\n level = 256\n img = (img * (level - 1)).astype(np.uint)\n\n hist, bins = np.histogram(img, level, (0, level))\n\n # calculate new gray level\n gray = np.cumsum(hist) / np.sum(hist)\n\n return gray[img]\n\n\n@split_channel\ndef denoise(img: ndarray) -> ndarray:\n def median_filter(img: ndarray, k: int) -> ndarray:\n return np.median(Neighbors(img, k).neighbors, axis=2)\n\n def adaptive_median_filter(img: ndarray, k1: int, k2: int) -> ndarray:\n h, w = img.shape\n mult_neighbor = [Neighbors(img, i).neighbors\n for i in range(k1, k2 + 1, 2)]\n\n # median / max / min: shape=((k2 - k1) // 2, h * w)\n medians: ndarray = np.array([np.median(n, axis=2).flatten()\n for n in mult_neighbor])\n maxs: ndarray = np.array([np.max(n, axis=2).flatten()\n for n in mult_neighbor])\n mins: ndarray = np.array([np.min(n, axis=2).flatten()\n for n in mult_neighbor])\n\n # Calculate suitable window size foreach pixel, default largest size\n index = np.ones(h * w, 'int') * (len(medians) - 1)\n\n for i in range(len(medians) - 1):\n index = np.where(\n # median is not noisy\n (medians[i] < maxs[i]) & (medians[i] > mins[i])\n # need update\n & (i < index),\n i, index)\n\n img_flatten = img.flatten() # h * w\n max_selected = position_index(maxs.transpose(), index)\n min_selected = position_index(mins.transpose(), index)\n med_selected = position_index(medians.transpose(), index)\n\n ret = np.where(\n # this pixel is not noisy\n (img_flatten < max_selected) & (img_flatten > min_selected),\n img_flatten, # keep\n med_selected # replaced by median\n )\n return ret.reshape(h, w)\n\n if img.dtype == np.uint8:\n img = img / 255\n return median_filter(img, 3)\n\n # return adaptive_median_filter(img, 3, 9) # seems not working\n\n\n@split_channel\ndef interpolate(img: ndarray) -> ndarray:\n def bilinear(img: ndarray, kw: float, kh: float) -> ndarray:\n # prepare the param matrix (shape [h, w, 4])\n neighbors = Neighbors(img, 3)\n # p0 = f(1, 0) - f(0, 0)\n p0 = neighbors.at(1, 0) - img\n # p1 = f(0, 1) - f(0, 0)\n p1 = neighbors.at(0, 1) - img\n # p2 = f(1, 1) + f(0, 0) - f(0, 1) - f(1, 0)\n p2 = neighbors.at(1, 1) + img - neighbors.at(0, 1) - neighbors.at(1, 0)\n # p3 = f(0, 0)\n p3 = img\n # f(x, y) = p0 * x + p1 * y + p2 * x * y + f(0, 0)\n # = [p0, p1, p2, p3] \\mul [x, y, xy, 1]\n # x \\in [0, 1), y \\in [0, 1)\n params = np.dstack([p0, p1, p2, p3])\n\n # map the pixels' position of the target image to the origin\n h, w = img.shape\n hh, ww = round(h * kh), round(w * kw)\n xs = np.repeat(np.array([range(ww)]), hh, axis=0) / kw\n ys = np.repeat(np.array([range(hh)]), ww, axis=0).transpose() / kh\n xs_int = xs.astype('int')\n ys_int = ys.astype('int')\n xs -= xs_int\n ys -= ys_int\n\n # prepare the matrix\n target_mat_1: ndarray = params[ys_int, xs_int].reshape(hh, ww, 1, 4)\n target_mat_2: ndarray = np.dstack((xs, ys, xs * ys, np.ones((hh, ww)))) \\\n .reshape(hh, ww, 4, 1)\n\n # shape [h, w, 4, 1] \\mul shape [h, w, 4, 1] => shape[h, w, 1, 1]\n ret = np.matmul(target_mat_1, target_mat_2).reshape(hh, ww)\n return ret\n\n if img.dtype == np.uint8:\n img = img / 255\n return bilinear(img, 2, 2)\n\n\ndef dft(img: ndarray) -> ndarray:\n f = fftshift(fft2(img))\n f = np.log(np.abs(f))\n return f\n\n\ndef butterworth(img: ndarray) -> ndarray:\n def _butterworth(D_0: float, k: int = 1):\n freq = fftshift(fft2(img))\n h, w = freq.shape\n xs = np.repeat(np.array([range(w)]), h, axis=0)\n ys = np.repeat(np.array([range(h)]), w, axis=0).transpose()\n xs = np.power((xs - w / 2), 2)\n ys = np.power((ys - h / 2), 2)\n D_uv = np.power(xs + ys, 0.5)\n H_uv = 1 / (1 + np.power(D_uv / D_0, 2 * k))\n freq *= H_uv\n return np.abs(ifft2(ifftshift(freq)))\n\n return _butterworth(70, 1)\n\n\ndef canny(img: ndarray) -> ndarray:\n # Gauss Filter\n gauss = np.array([2, 4, 5, 4, 2,\n 4, 9, 12, 9, 4,\n 5, 12, 15, 12, 5,\n 4, 9, 12, 9, 4,\n 2, 4, 5, 4, 2]) / 159\n img_neighbors = Neighbors(img, 5)\n img = np.matmul(img_neighbors.neighbors, gauss)\n\n # Calculate gradient\n img_neighbors = Neighbors(img, 3)\n grad_x = (img_neighbors.at(1, 0) - img_neighbors.at(-1, 0)) / 2\n grad_y = (img_neighbors.at(0, 1) - img_neighbors.at(0, -1)) / 2\n grad: ndarray = np.power(grad_x * grad_x + grad_y * grad_y, 0.5)\n\n # Non-Maximum Suppression\n # here we get gradient by interpolation (instead of approximation)\n epsilon = np.finfo(np.float64).eps\n grad_x_fix = np.where(grad_x == 0, epsilon, grad_x)\n grad_y_fix = np.where(grad_y == 0, epsilon, grad_y)\n grad_k: ndarray = grad_y / grad_x_fix\n grad_k_abs = np.abs(grad_k)\n grad_t_abs = np.abs(grad_x / grad_y_fix)\n\n grad_neighbors = Neighbors(grad, 3)\n\n discriminate = [\n (\n grad_k >= 1, grad_t_abs,\n grad_neighbors.at(1, 1), grad_neighbors.at(0, 1),\n grad_neighbors.at(-1, -1), grad_neighbors.at(0, -1),\n ),\n (\n grad_k <= -1, grad_t_abs,\n grad_neighbors.at(-1, 1), grad_neighbors.at(0, 1),\n grad_neighbors.at(1, -1), grad_neighbors.at(0, -1),\n ),\n (\n (grad_k < 1) & (grad_k >= 0), grad_k_abs,\n grad_neighbors.at(1, 1), grad_neighbors.at(1, 0),\n grad_neighbors.at(-1, -1), grad_neighbors.at(-1, 0),\n ),\n (\n (grad_k > -1) & (grad_k < 0), grad_k_abs,\n grad_neighbors.at(-1, 1), grad_neighbors.at(-1, 0),\n grad_neighbors.at(1, -1), grad_neighbors.at(1, 0),\n )\n ]\n\n d1 = np.zeros(img.shape)\n d2 = np.zeros(img.shape)\n for cond, coef, p0, p1, p2, p3 in discriminate:\n d1 = np.where(cond, coef * p0 + (np.ones(coef.shape) - coef) * p1, d1)\n d2 = np.where(cond, coef * p2 + (np.ones(coef.shape) - coef) * p3, d2)\n grad_suppress = np.where((grad >= d1) & (grad >= d2), grad, 0)\n\n # Double thresholding\n high, low = 0.75, 0.4\n\n sorted_grad = np.sort(grad.reshape(-1))\n thresh_low = sorted_grad[int(len(sorted_grad) * low)]\n thresh_high = sorted_grad[int(len(sorted_grad) * high)]\n\n neighbors = Neighbors(grad_suppress, 3).neighbors\n\n return np.where((grad_suppress > thresh_low) &\n (np.max(neighbors, axis=2) > thresh_high), 1, 0)\n\n\ndef morphology(img: ndarray) -> ndarray:\n def dilate(img: ndarray, k: int) -> ndarray:\n return np.max(Neighbors(img, k).neighbors, axis=2)\n\n def erode(img: ndarray, k: int) -> ndarray:\n return np.min(Neighbors(img, k).neighbors, axis=2)\n\n k = 3\n img = erode(img, k)\n img = dilate(img, k)\n return img\n" ]
[ [ "numpy.ones", "numpy.sum", "numpy.histogram", "numpy.dstack", "numpy.vstack", "numpy.abs", "numpy.where", "numpy.eye", "numpy.zeros", "numpy.fft.fft2", "numpy.median", "numpy.arange", "numpy.hstack", "numpy.power", "numpy.max", "numpy.min", "numpy.finfo", "numpy.matmul", "numpy.cumsum", "numpy.fft.ifftshift", "numpy.array" ] ]
jcwon0/BlurHPE
[ "c97a57e92a8a7f171b0403aee640222a32513562" ]
[ "mmpose/core/evaluation/top_down_eval.py" ]
[ "import warnings\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\nfrom mmpose.core.post_processing import transform_preds\r\n\r\n\r\ndef _calc_distances(preds, targets, mask, normalize):\r\n \"\"\"Calculate the normalized distances between preds and target.\r\n\r\n Note:\r\n batch_size: N\r\n num_keypoints: K\r\n dimension of keypoints: D (normally, D=2 or D=3)\r\n\r\n Args:\r\n preds (np.ndarray[N, K, D]): Predicted keypoint location.\r\n targets (np.ndarray[N, K, D]): Groundtruth keypoint location.\r\n mask (np.ndarray[N, K]): Visibility of the target. False for invisible\r\n joints, and True for visible. Invisible joints will be ignored for\r\n accuracy calculation.\r\n normalize (np.ndarray[N, D]): Typical value is heatmap_size\r\n\r\n Returns:\r\n np.ndarray[K, N]: The normalized distances.\r\n If target keypoints are missing, the distance is -1.\r\n \"\"\"\r\n N, K, _ = preds.shape\r\n distances = np.full((N, K), -1, dtype=np.float32)\r\n distances[mask] = np.linalg.norm(\r\n ((preds - targets) / normalize[:, None, :])[mask], axis=-1)\r\n return distances.T\r\n\r\n\r\ndef _distance_acc(distances, thr=0.5):\r\n \"\"\"Return the percentage below the distance threshold, while ignoring\r\n distances values with -1.\r\n\r\n Note:\r\n batch_size: N\r\n Args:\r\n distances (np.ndarray[N, ]): The normalized distances.\r\n thr (float): Threshold of the distances.\r\n\r\n Returns:\r\n float: Percentage of distances below the threshold.\r\n If all target keypoints are missing, return -1.\r\n \"\"\"\r\n distance_valid = distances != -1\r\n num_distance_valid = distance_valid.sum()\r\n if num_distance_valid > 0:\r\n return (distances[distance_valid] < thr).sum() / num_distance_valid\r\n return -1\r\n\r\n\r\ndef _get_max_preds(heatmaps):\r\n \"\"\"Get keypoint predictions from score maps.\r\n\r\n Note:\r\n batch_size: N\r\n num_keypoints: K\r\n heatmap height: H\r\n heatmap width: W\r\n\r\n Args:\r\n heatmaps (np.ndarray[N, K, H, W]): model predicted heatmaps.\r\n\r\n Returns:\r\n tuple: A tuple containing aggregated results.\r\n\r\n - preds (np.ndarray[N, K, 2]): Predicted keypoint location.\r\n - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.\r\n \"\"\"\r\n assert isinstance(heatmaps,\r\n np.ndarray), ('heatmaps should be numpy.ndarray')\r\n assert heatmaps.ndim == 4, 'batch_images should be 4-ndim'\r\n\r\n N, K, _, W = heatmaps.shape\r\n heatmaps_reshaped = heatmaps.reshape((N, K, -1))\r\n idx = np.argmax(heatmaps_reshaped, 2).reshape((N, K, 1))\r\n maxvals = np.amax(heatmaps_reshaped, 2).reshape((N, K, 1))\r\n\r\n preds = np.tile(idx, (1, 1, 2)).astype(np.float32)\r\n preds[:, :, 0] = preds[:, :, 0] % W\r\n preds[:, :, 1] = preds[:, :, 1] // W\r\n\r\n preds = np.where(np.tile(maxvals, (1, 1, 2)) > 0.0, preds, -1)\r\n return preds, maxvals\r\n\r\n\r\ndef pose_pck_accuracy(output, target, mask, thr=0.05, normalize=None):\r\n \"\"\"Calculate the pose accuracy of PCK for each individual keypoint and the\r\n averaged accuracy across all keypoints from heatmaps.\r\n\r\n Note:\r\n PCK metric measures accuracy of the localization of the body joints.\r\n The distances between predicted positions and the ground-truth ones\r\n are typically normalized by the bounding box size.\r\n The threshold (thr) of the normalized distance is commonly set\r\n as 0.05, 0.1 or 0.2 etc.\r\n\r\n batch_size: N\r\n num_keypoints: K\r\n heatmap height: H\r\n heatmap width: W\r\n\r\n Args:\r\n output (np.ndarray[N, K, H, W]): Model output heatmaps.\r\n target (np.ndarray[N, K, H, W]): Groundtruth heatmaps.\r\n mask (np.ndarray[N, K]): Visibility of the target. False for invisible\r\n joints, and True for visible. Invisible joints will be ignored for\r\n accuracy calculation.\r\n thr (float): Threshold of PCK calculation. Default 0.05.\r\n normalize (np.ndarray[N, 2]): Normalization factor for H&W.\r\n\r\n Returns:\r\n tuple: A tuple containing keypoint accuracy.\r\n\r\n - np.ndarray[K]: Accuracy of each keypoint.\r\n - float: Averaged accuracy across all keypoints.\r\n - int: Number of valid keypoints.\r\n \"\"\"\r\n N, K, H, W = output.shape\r\n if K == 0:\r\n return None, 0, 0\r\n if normalize is None:\r\n normalize = np.tile(np.array([[H, W]]), (N, 1))\r\n\r\n pred, _ = _get_max_preds(output)\r\n gt, _ = _get_max_preds(target)\r\n return keypoint_pck_accuracy(pred, gt, mask, thr, normalize)\r\n\r\n\r\ndef keypoint_pck_accuracy(pred, gt, mask, thr, normalize):\r\n \"\"\"Calculate the pose accuracy of PCK for each individual keypoint and the\r\n averaged accuracy across all keypoints for coordinates.\r\n\r\n Note:\r\n PCK metric measures accuracy of the localization of the body joints.\r\n The distances between predicted positions and the ground-truth ones\r\n are typically normalized by the bounding box size.\r\n The threshold (thr) of the normalized distance is commonly set\r\n as 0.05, 0.1 or 0.2 etc.\r\n\r\n batch_size: N\r\n num_keypoints: K\r\n\r\n Args:\r\n pred (np.ndarray[N, K, 2]): Predicted keypoint location.\r\n gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.\r\n mask (np.ndarray[N, K]): Visibility of the target. False for invisible\r\n joints, and True for visible. Invisible joints will be ignored for\r\n accuracy calculation.\r\n thr (float): Threshold of PCK calculation.\r\n normalize (np.ndarray[N, 2]): Normalization factor for H&W.\r\n\r\n Returns:\r\n tuple: A tuple containing keypoint accuracy.\r\n\r\n - acc (np.ndarray[K]): Accuracy of each keypoint.\r\n - avg_acc (float): Averaged accuracy across all keypoints.\r\n - cnt (int): Number of valid keypoints.\r\n \"\"\"\r\n distances = _calc_distances(pred, gt, mask, normalize)\r\n\r\n acc = np.array([_distance_acc(d, thr) for d in distances])\r\n valid_acc = acc[acc >= 0]\r\n cnt = len(valid_acc)\r\n avg_acc = valid_acc.mean() if cnt > 0 else 0\r\n return acc, avg_acc, cnt\r\n\r\n\r\ndef keypoint_auc(pred, gt, mask, normalize, num_step=20):\r\n \"\"\"Calculate the pose accuracy of PCK for each individual keypoint and the\r\n averaged accuracy across all keypoints for coordinates.\r\n\r\n Note:\r\n batch_size: N\r\n num_keypoints: K\r\n\r\n Args:\r\n pred (np.ndarray[N, K, 2]): Predicted keypoint location.\r\n gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.\r\n mask (np.ndarray[N, K]): Visibility of the target. False for invisible\r\n joints, and True for visible. Invisible joints will be ignored for\r\n accuracy calculation.\r\n normalize (float): Normalization factor.\r\n\r\n Returns:\r\n float: Area under curve.\r\n \"\"\"\r\n nor = np.tile(np.array([[normalize, normalize]]), (pred.shape[0], 1))\r\n x = [1.0 * i / num_step for i in range(num_step)]\r\n y = []\r\n for thr in x:\r\n _, avg_acc, _ = keypoint_pck_accuracy(pred, gt, mask, thr, nor)\r\n y.append(avg_acc)\r\n\r\n auc = 0\r\n for i in range(num_step):\r\n auc += 1.0 / num_step * y[i]\r\n return auc\r\n\r\n\r\ndef keypoint_nme(pred, gt, mask, normalize_factor):\r\n \"\"\"Calculate the normalized mean error (NME).\r\n\r\n Note:\r\n batch_size: N\r\n num_keypoints: K\r\n\r\n Args:\r\n pred (np.ndarray[N, K, 2]): Predicted keypoint location.\r\n gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.\r\n mask (np.ndarray[N, K]): Visibility of the target. False for invisible\r\n joints, and True for visible. Invisible joints will be ignored for\r\n accuracy calculation.\r\n normalize_factor (np.ndarray[N, 2]): Normalization factor.\r\n\r\n Returns:\r\n float: normalized mean error\r\n \"\"\"\r\n distances = _calc_distances(pred, gt, mask, normalize_factor)\r\n distance_valid = distances[distances != -1]\r\n return distance_valid.sum() / max(1, len(distance_valid))\r\n\r\n\r\ndef keypoint_epe(pred, gt, mask):\r\n \"\"\"Calculate the end-point error.\r\n\r\n Note:\r\n batch_size: N\r\n num_keypoints: K\r\n\r\n Args:\r\n pred (np.ndarray[N, K, 2]): Predicted keypoint location.\r\n gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.\r\n mask (np.ndarray[N, K]): Visibility of the target. False for invisible\r\n joints, and True for visible. Invisible joints will be ignored for\r\n accuracy calculation.\r\n\r\n Returns:\r\n float: Average end-point error.\r\n \"\"\"\r\n\r\n distances = _calc_distances(\r\n pred, gt, mask,\r\n np.ones((pred.shape[0], pred.shape[2]), dtype=np.float32))\r\n distance_valid = distances[distances != -1]\r\n return distance_valid.sum() / max(1, len(distance_valid))\r\n\r\n\r\ndef _taylor(heatmap, coord):\r\n \"\"\"Distribution aware coordinate decoding method.\r\n\r\n Note:\r\n heatmap height: H\r\n heatmap width: W\r\n\r\n Args:\r\n heatmap (np.ndarray[H, W]): Heatmap of a particular joint type.\r\n coord (np.ndarray[2,]): Coordinates of the predicted keypoints.\r\n\r\n Returns:\r\n np.ndarray[2,]: Updated coordinates.\r\n \"\"\"\r\n H, W = heatmap.shape[:2]\r\n px, py = int(coord[0]), int(coord[1])\r\n if 1 < px < W - 2 and 1 < py < H - 2:\r\n dx = 0.5 * (heatmap[py][px + 1] - heatmap[py][px - 1])\r\n dy = 0.5 * (heatmap[py + 1][px] - heatmap[py - 1][px])\r\n dxx = 0.25 * (\r\n heatmap[py][px + 2] - 2 * heatmap[py][px] + heatmap[py][px - 2])\r\n dxy = 0.25 * (\r\n heatmap[py + 1][px + 1] - heatmap[py - 1][px + 1] -\r\n heatmap[py + 1][px - 1] + heatmap[py - 1][px - 1])\r\n dyy = 0.25 * (\r\n heatmap[py + 2 * 1][px] - 2 * heatmap[py][px] +\r\n heatmap[py - 2 * 1][px])\r\n derivative = np.array([[dx], [dy]])\r\n hessian = np.array([[dxx, dxy], [dxy, dyy]])\r\n if dxx * dyy - dxy**2 != 0:\r\n hessianinv = np.linalg.inv(hessian)\r\n offset = -hessianinv @ derivative\r\n offset = np.squeeze(np.array(offset.T), axis=0)\r\n coord += offset\r\n return coord\r\n\r\n\r\ndef post_dark_udp(coords, batch_heatmaps, kernel=3):\r\n \"\"\"DARK post-pocessing. Implemented by udp. Paper ref: Huang et al. The\r\n Devil is in the Details: Delving into Unbiased Data Processing for Human\r\n Pose Estimation (CVPR 2020). Zhang et al. Distribution-Aware Coordinate\r\n Representation for Human Pose Estimation (CVPR 2020).\r\n\r\n Note:\r\n batch size: B\r\n num keypoints: K\r\n num persons: N\r\n hight of heatmaps: H\r\n width of heatmaps: W\r\n B=1 for bottom_up paradigm where all persons share the same heatmap.\r\n B=N for top_down paradigm where each person has its own heatmaps.\r\n\r\n Args:\r\n coords (np.ndarray[N, K, 2]): Initial coordinates of human pose.\r\n batch_heatmaps (np.ndarray[B, K, H, W]): batch_heatmaps\r\n kernel (int): Gaussian kernel size (K) for modulation.\r\n\r\n Returns:\r\n res (np.ndarray[N, K, 2]): Refined coordinates.\r\n \"\"\"\r\n if not isinstance(batch_heatmaps, np.ndarray):\r\n batch_heatmaps = batch_heatmaps.cpu().numpy()\r\n B, K, H, W = batch_heatmaps.shape\r\n N = coords.shape[0]\r\n assert (B == 1 or B == N)\r\n for heatmaps in batch_heatmaps:\r\n for heatmap in heatmaps:\r\n cv2.GaussianBlur(heatmap, (kernel, kernel), 0, heatmap)\r\n np.clip(batch_heatmaps, 0.001, 50, batch_heatmaps)\r\n np.log(batch_heatmaps, batch_heatmaps)\r\n batch_heatmaps = np.transpose(batch_heatmaps,\r\n (2, 3, 0, 1)).reshape(H, W, -1)\r\n batch_heatmaps_pad = cv2.copyMakeBorder(\r\n batch_heatmaps, 1, 1, 1, 1, borderType=cv2.BORDER_REFLECT)\r\n batch_heatmaps_pad = np.transpose(\r\n batch_heatmaps_pad.reshape(H + 2, W + 2, B, K),\r\n (2, 3, 0, 1)).flatten()\r\n\r\n index = coords[..., 0] + 1 + (coords[..., 1] + 1) * (W + 2)\r\n index += (W + 2) * (H + 2) * np.arange(0, B * K).reshape(-1, K)\r\n index = index.astype(np.int).reshape(-1, 1)\r\n i_ = batch_heatmaps_pad[index]\r\n ix1 = batch_heatmaps_pad[index + 1]\r\n iy1 = batch_heatmaps_pad[index + W + 2]\r\n ix1y1 = batch_heatmaps_pad[index + W + 3]\r\n ix1_y1_ = batch_heatmaps_pad[index - W - 3]\r\n ix1_ = batch_heatmaps_pad[index - 1]\r\n iy1_ = batch_heatmaps_pad[index - 2 - W]\r\n\r\n dx = 0.5 * (ix1 - ix1_)\r\n dy = 0.5 * (iy1 - iy1_)\r\n derivative = np.concatenate([dx, dy], axis=1)\r\n derivative = derivative.reshape(N, K, 2, 1)\r\n dxx = ix1 - 2 * i_ + ix1_\r\n dyy = iy1 - 2 * i_ + iy1_\r\n dxy = 0.5 * (ix1y1 - ix1 - iy1 + i_ + i_ - ix1_ - iy1_ + ix1_y1_)\r\n hessian = np.concatenate([dxx, dxy, dxy, dyy], axis=1)\r\n hessian = hessian.reshape(N, K, 2, 2)\r\n hessian = np.linalg.inv(hessian + np.finfo(np.float32).eps * np.eye(2))\r\n coords -= np.einsum('ijmn,ijnk->ijmk', hessian, derivative).squeeze()\r\n return coords\r\n\r\n\r\ndef _gaussian_blur(heatmaps, kernel=11):\r\n \"\"\"Modulate heatmap distribution with Gaussian.\r\n sigma = 0.3*((kernel_size-1)*0.5-1)+0.8\r\n sigma~=3 if k=17\r\n sigma=2 if k=11;\r\n sigma~=1.5 if k=7;\r\n sigma~=1 if k=3;\r\n\r\n Note:\r\n batch_size: N\r\n num_keypoints: K\r\n heatmap height: H\r\n heatmap width: W\r\n\r\n Args:\r\n heatmaps (np.ndarray[N, K, H, W]): model predicted heatmaps.\r\n kernel (int): Gaussian kernel size (K) for modulation, which should\r\n match the heatmap gaussian sigma when training.\r\n K=17 for sigma=3 and k=11 for sigma=2.\r\n\r\n Returns:\r\n np.ndarray[N, K, H, W]: Modulated heatmap distribution.\r\n \"\"\"\r\n assert kernel % 2 == 1\r\n\r\n border = (kernel - 1) // 2\r\n batch_size = heatmaps.shape[0]\r\n num_joints = heatmaps.shape[1]\r\n height = heatmaps.shape[2]\r\n width = heatmaps.shape[3]\r\n for i in range(batch_size):\r\n for j in range(num_joints):\r\n origin_max = np.max(heatmaps[i, j])\r\n dr = np.zeros((height + 2 * border, width + 2 * border),\r\n dtype=np.float32)\r\n dr[border:-border, border:-border] = heatmaps[i, j].copy()\r\n dr = cv2.GaussianBlur(dr, (kernel, kernel), 0)\r\n heatmaps[i, j] = dr[border:-border, border:-border].copy()\r\n heatmaps[i, j] *= origin_max / np.max(heatmaps[i, j])\r\n return heatmaps\r\n\r\n\r\ndef keypoints_from_regression(regression_preds, center, scale, img_size):\r\n \"\"\"Get final keypoint predictions from regression vectors and transform\r\n them back to the image.\r\n\r\n Note:\r\n batch_size: N\r\n num_keypoints: K\r\n\r\n Args:\r\n regression_preds (np.ndarray[N, K, 2]): model prediction.\r\n center (np.ndarray[N, 2]): Center of the bounding box (x, y).\r\n scale (np.ndarray[N, 2]): Scale of the bounding box\r\n wrt height/width.\r\n img_size (list(img_width, img_height)): model input image size.\r\n\r\n\r\n Returns:\r\n preds (np.ndarray[N, K, 2]): Predicted keypoint location in images.\r\n maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.\r\n \"\"\"\r\n N, K, _ = regression_preds.shape\r\n preds, maxvals = regression_preds, np.ones((N, K, 1), dtype=np.float32)\r\n\r\n preds = preds * img_size\r\n\r\n # Transform back to the image\r\n for i in range(N):\r\n preds[i] = transform_preds(preds[i], center[i], scale[i], img_size)\r\n\r\n return preds, maxvals\r\n\r\n\r\ndef keypoints_from_heatmaps(heatmaps,\r\n center,\r\n scale,\r\n unbiased=False,\r\n post_process='default',\r\n kernel=11,\r\n valid_radius_factor=0.0546875,\r\n use_udp=False,\r\n target_type='GaussianHeatMap'):\r\n \"\"\"Get final keypoint predictions from heatmaps and transform them back to\r\n the image.\r\n\r\n Note:\r\n batch size: N\r\n num keypoints: K\r\n heatmap height: H\r\n heatmap width: W\r\n\r\n Args:\r\n heatmaps (np.ndarray[N, K, H, W]): model predicted heatmaps.\r\n center (np.ndarray[N, 2]): Center of the bounding box (x, y).\r\n scale (np.ndarray[N, 2]): Scale of the bounding box\r\n wrt height/width.\r\n post_process (str/None): Choice of methods to post-process\r\n heatmaps. Currently supported: None, 'default', 'unbiased',\r\n 'megvii'.\r\n unbiased (bool): Option to use unbiased decoding. Mutually\r\n exclusive with megvii.\r\n Note: this arg is deprecated and unbiased=True can be replaced\r\n by post_process='unbiased'\r\n Paper ref: Zhang et al. Distribution-Aware Coordinate\r\n Representation for Human Pose Estimation (CVPR 2020).\r\n kernel (int): Gaussian kernel size (K) for modulation, which should\r\n match the heatmap gaussian sigma when training.\r\n K=17 for sigma=3 and k=11 for sigma=2.\r\n valid_radius_factor (float): The radius factor of the positive area\r\n in classification heatmap for UDP.\r\n use_udp (bool): Use unbiased data processing.\r\n target_type (str): 'GaussianHeatMap' or 'CombinedTarget'.\r\n GaussianHeatMap: Classification target with gaussian distribution.\r\n CombinedTarget: The combination of classification target\r\n (response map) and regression target (offset map).\r\n Paper ref: Huang et al. The Devil is in the Details: Delving into\r\n Unbiased Data Processing for Human Pose Estimation (CVPR 2020).\r\n\r\n Returns:\r\n tuple: A tuple containing keypoint predictions and scores.\r\n\r\n - preds (np.ndarray[N, K, 2]): Predicted keypoint location in images.\r\n - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.\r\n \"\"\"\r\n # detect conflicts\r\n if unbiased:\r\n assert post_process not in [False, None, 'megvii']\r\n if post_process in ['megvii', 'unbiased']:\r\n assert kernel > 0\r\n if use_udp:\r\n assert not post_process == 'megvii'\r\n\r\n # normalize configs\r\n if post_process is False:\r\n warnings.warn(\r\n 'post_process=False is deprecated, '\r\n 'please use post_process=None instead', DeprecationWarning)\r\n post_process = None\r\n elif post_process is True:\r\n if unbiased is True:\r\n warnings.warn(\r\n 'post_process=True, unbiased=True is deprecated,'\r\n \" please use post_process='unbiased' instead\",\r\n DeprecationWarning)\r\n post_process = 'unbiased'\r\n else:\r\n warnings.warn(\r\n 'post_process=True, unbiased=False is deprecated, '\r\n \"please use post_process='default' instead\",\r\n DeprecationWarning)\r\n post_process = 'default'\r\n elif post_process == 'default':\r\n if unbiased is True:\r\n warnings.warn(\r\n 'unbiased=True is deprecated, please use '\r\n \"post_process='unbiased' instead\", DeprecationWarning)\r\n post_process = 'unbiased'\r\n\r\n # start processing\r\n if post_process == 'megvii':\r\n heatmaps = _gaussian_blur(heatmaps, kernel=kernel)\r\n\r\n N, K, H, W = heatmaps.shape\r\n if use_udp:\r\n assert target_type in ['GaussianHeatMap', 'CombinedTarget']\r\n if target_type == 'GaussianHeatMap':\r\n preds, maxvals = _get_max_preds(heatmaps)\r\n preds = post_dark_udp(preds, heatmaps, kernel=kernel)\r\n elif target_type == 'CombinedTarget':\r\n for person_heatmaps in heatmaps:\r\n for i, heatmap in enumerate(person_heatmaps):\r\n kt = 2 * kernel + 1 if i % 3 == 0 else kernel\r\n cv2.GaussianBlur(heatmap, (kt, kt), 0, heatmap)\r\n # valid radius is in direct proportion to the height of heatmap.\r\n valid_radius = valid_radius_factor * H\r\n offset_x = heatmaps[:, 1::3, :].flatten() * valid_radius\r\n offset_y = heatmaps[:, 2::3, :].flatten() * valid_radius\r\n heatmaps = heatmaps[:, ::3, :]\r\n preds, maxvals = _get_max_preds(heatmaps)\r\n index = preds[..., 0] + preds[..., 1] * W\r\n index += W * H * np.arange(0, N * K / 3)\r\n index = index.astype(np.int).reshape(N, K // 3, 1)\r\n preds += np.concatenate((offset_x[index], offset_y[index]), axis=2)\r\n else:\r\n preds, maxvals = _get_max_preds(heatmaps)\r\n if post_process == 'unbiased': # alleviate biased coordinate\r\n # apply Gaussian distribution modulation.\r\n heatmaps = np.log(\r\n np.maximum(_gaussian_blur(heatmaps, kernel), 1e-10))\r\n for n in range(N):\r\n for k in range(K):\r\n preds[n][k] = _taylor(heatmaps[n][k], preds[n][k])\r\n elif post_process is not None:\r\n # add +/-0.25 shift to the predicted locations for higher acc.\r\n for n in range(N):\r\n for k in range(K):\r\n heatmap = heatmaps[n][k]\r\n px = int(preds[n][k][0])\r\n py = int(preds[n][k][1])\r\n if 1 < px < W - 1 and 1 < py < H - 1:\r\n diff = np.array([\r\n heatmap[py][px + 1] - heatmap[py][px - 1],\r\n heatmap[py + 1][px] - heatmap[py - 1][px]\r\n ])\r\n preds[n][k] += np.sign(diff) * .25\r\n if post_process == 'megvii':\r\n preds[n][k] += 0.5\r\n\r\n # Transform back to the image\r\n for i in range(N):\r\n preds[i] = transform_preds(\r\n preds[i], center[i], scale[i], [W, H], use_udp=use_udp)\r\n\r\n if post_process == 'megvii':\r\n maxvals = maxvals / 255.0 + 0.5\r\n\r\n return preds, maxvals\r\n" ]
[ [ "numpy.ones", "numpy.log", "numpy.amax", "numpy.transpose", "numpy.tile", "numpy.eye", "numpy.zeros", "numpy.argmax", "numpy.arange", "numpy.max", "numpy.einsum", "numpy.finfo", "numpy.linalg.norm", "numpy.sign", "numpy.linalg.inv", "numpy.clip", "numpy.array", "numpy.concatenate", "numpy.full" ] ]
gully/jax
[ "eb086f9b22154104b216b22ed006264989bcad41" ]
[ "jax/numpy/lax_numpy.py" ]
[ "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# pytype: skip-file\n\"\"\"\nImplements the NumPy API, using the primitives in :mod:`jax.lax`.\n\nNumPy operations are implemented in Python in terms of the primitive operations\nin :mod:`jax.lax`. Since NumPy operations are not primitive and instead are\nimplemented in terms of :mod:`jax.lax` operations, we do not need to define\ntransformation rules such as gradient or batching rules. Instead,\ntransformations for NumPy primitives can be derived from the transformation\nrules for the underlying :code:`lax` primitives.\n\"\"\"\n\nimport builtins\nimport collections\nimport operator\nimport os\nimport types\nfrom typing import Sequence, Set, Tuple, Union\nimport warnings\n\nimport numpy as np\nimport opt_einsum\n\nfrom jax import jit, custom_jvp\nfrom .vectorize import vectorize\nfrom ._util import _wraps\nfrom .. import core\nfrom .. import dtypes\nfrom ..abstract_arrays import UnshapedArray, ShapedArray, ConcreteArray, canonicalize_shape\nfrom ..config import flags, config\nfrom ..interpreters.xla import DeviceArray\nfrom ..interpreters.masking import Poly\nfrom .. import lax\nfrom ..lax.lax import _device_put_raw\nfrom .. import ops\nfrom ..util import (partial, unzip2, prod as _prod,\n subvals, safe_zip)\nfrom ..tree_util import tree_leaves, tree_flatten\n\nFLAGS = flags.FLAGS\nflags.DEFINE_enum(\n 'jax_numpy_rank_promotion', os.getenv('JAX_NUMPY_RANK_PROMOTION', 'allow'),\n enum_values=['allow', 'warn', 'raise'],\n help=\n 'Control NumPy-style automatic rank promotion broadcasting '\n '(\"allow\", \"warn\", or \"raise\").')\n\nnewaxis = None\n\n# Common docstring additions:\n\n_PRECISION_DOC = \"\"\"\\\nIn addition to the original NumPy arguments listed below, also supports\n``precision`` for extra control over matrix-multiplication precision\non supported devices. ``precision`` may be set to ``None``, which means\ndefault precision for the backend, or any ``jax.lax.Precision`` enum value\n(``Precision.DEFAULT``, ``Precision.HIGH`` or ``Precision.HIGHEST``).\n\"\"\"\n\n# We replace some builtin names to follow Numpy's API, so we capture here.\n_abs = builtins.abs\n_all = builtins.all\n_any = builtins.any\n_max = builtins.max\n_min = builtins.min\n_sum = builtins.sum\n_divmod = builtins.divmod\n\n# NumPy constants\n\npi = np.pi\ne = np.e\neuler_gamma = np.euler_gamma\ninf = np.inf\nNINF = np.NINF\nPZERO = np.PZERO\nNZERO = np.NZERO\nnan = np.nan\n\n# And some numpy utility functions\nset_printoptions = np.set_printoptions\n\n# We want isinstance(x, np.ndarray) checks in user code to work with the our\n# array-like types, including DeviceArray and UnshapedArray (i.e. the abstract\n# array base class). We can override the isinstance behavior directly, without\n# having the complexity of multiple inheritance on those classes, by defining\n# the ndarray class to have a metaclass with special __instancecheck__ behavior.\n_arraylike_types = (np.ndarray, UnshapedArray, DeviceArray)\n\nclass _ArrayMeta(type(np.ndarray)): # type: ignore\n \"\"\"Metaclass for overriding ndarray isinstance checks.\"\"\"\n\n def __instancecheck__(self, instance):\n try:\n return isinstance(instance.aval, _arraylike_types)\n except AttributeError:\n return isinstance(instance, _arraylike_types)\n\nclass ndarray(np.ndarray, metaclass=_ArrayMeta):\n dtype: np.dtype\n shape: Tuple[int, ...]\n size: int\n\n def __init__(shape, dtype=None, buffer=None, offset=0, strides=None,\n order=None):\n raise TypeError(\"jax.numpy.ndarray() should not be instantiated explicitly.\"\n \" Use jax.numpy.array, or jax.numpy.zeros instead.\")\n\n\niscomplexobj = np.iscomplexobj\n\nshape = _shape = np.shape\nndim = _ndim = np.ndim\nsize = np.size\n_dtype = dtypes.result_type\n\n# At present JAX doesn't have a reason to distinguish between scalars and arrays\n# in its object system. Further, we want JAX scalars to have the same type\n# promotion behaviors as JAX arrays. Rather than introducing a new type of JAX\n# scalar object with JAX promotion behaviors, instead we make the JAX scalar\n# types return JAX arrays when instantiated.\n\nclass _ScalarMeta(type):\n def __hash__(self):\n return hash(self.dtype.type)\n\n def __eq__(self, other):\n return id(self) == id(other) or self.dtype.type == other\n\n def __ne__(self, other):\n return not (self == other)\n\n def __call__(self, x):\n return array(x, dtype=self.dtype)\n\ndef _make_scalar_type(np_scalar_type):\n return _ScalarMeta(np_scalar_type.__name__, (object,),\n {\"dtype\": np.dtype(np_scalar_type)})\n\nbool_ = _make_scalar_type(np.bool_)\nuint8 = _make_scalar_type(np.uint8)\nuint16 = _make_scalar_type(np.uint16)\nuint32 = _make_scalar_type(np.uint32)\nuint64 = _make_scalar_type(np.uint64)\nint8 = _make_scalar_type(np.int8)\nint16 = _make_scalar_type(np.int16)\nint32 = _make_scalar_type(np.int32)\nint64 = _make_scalar_type(np.int64)\nbfloat16 = _make_scalar_type(dtypes.bfloat16)\nfloat16 = _make_scalar_type(np.float16)\nfloat32 = single = _make_scalar_type(np.float32)\nfloat64 = double = _make_scalar_type(np.float64)\ncomplex64 = csingle = _make_scalar_type(np.complex64)\ncomplex128 = cdouble = _make_scalar_type(np.complex128)\n\nint_ = int32 if dtypes.int_ == np.int32 else int64\nfloat_ = float32 if dtypes.float_ == np.float32 else float64\ncomplex_ = complex64 if dtypes.complex_ == np.complex64 else complex128\n\nnumber = np.number\ninexact = np.inexact\ncomplexfloating = np.complexfloating\nfloating = np.floating\ninteger = np.integer\nsignedinteger = np.signedinteger\nunsignedinteger = np.unsignedinteger\n\nflexible = np.flexible\ncharacter = np.character\nobject_ = np.object_\n\niinfo = dtypes.iinfo\n\ndtype = np.dtype\ncan_cast = dtypes.can_cast\nissubsctype = dtypes.issubsctype\npromote_types = dtypes.promote_types\n\nComplexWarning = np.ComplexWarning\n\narray_str = np.array_str\narray_repr = np.array_repr\n\nsave = np.save\nsavez = np.savez\nload = np.load\n\n\n### utility functions\n\n_canonicalize_axis = lax._canonicalize_axis\n\n_DEFAULT_TYPEMAP = {\n np.bool_: bool_,\n np.int_: int_,\n np.float_: float_,\n np.complex_: complex_\n}\n\ndef _np_array(obj, dtype=None, **kwargs):\n \"\"\"Return a properly-typed numpy array.\n\n `_np_array(obj, **kwds)` is equivalent to `np.array(obj, **kwds)`, with the\n exception that when obj.dtype is not defined and dtype is not specified, it\n uses Jax's default dtypes.\n \"\"\"\n arr = np.array(obj, dtype=dtype, **kwargs)\n obj_dtype = getattr(obj, 'dtype', None)\n arr_dtype = np.dtype(arr.dtype).type\n if dtype is None and obj_dtype is None and arr_dtype in _DEFAULT_TYPEMAP:\n arr = arr.astype(_DEFAULT_TYPEMAP[arr_dtype])\n return arr\n\n_np_asarray = partial(_np_array, copy=False)\n\ndef _promote_shapes(fun_name, *args):\n \"\"\"Prepend implicit leading singleton dimensions for Numpy broadcasting.\"\"\"\n if len(args) < 2:\n return args\n else:\n shapes = [shape(arg) for arg in args]\n nonscalar_ranks = [len(shp) for shp in shapes if shp]\n if not nonscalar_ranks or len(set(nonscalar_ranks)) == 1:\n return args\n else:\n if FLAGS.jax_numpy_rank_promotion != \"allow\":\n _rank_promotion_warning_or_error(fun_name, shapes)\n result_rank = len(lax.broadcast_shapes(*shapes))\n return [broadcast_to(arg, (1,) * (result_rank - len(shp)) + shp)\n for arg, shp in zip(args, shapes)]\n\ndef _rank_promotion_warning_or_error(fun_name, shapes):\n if FLAGS.jax_numpy_rank_promotion == \"warn\":\n msg = (\"Following NumPy automatic rank promotion for {} on shapes {}. \"\n \"Set the jax_numpy_rank_promotion config option to 'allow' to \"\n \"disable this warning; for more information, see \"\n \"https://jax.readthedocs.io/en/latest/rank_promotion_warning.html.\")\n warnings.warn(msg.format(fun_name, ' '.join(map(str, shapes))))\n elif FLAGS.jax_numpy_rank_promotion == \"raise\":\n msg = (\"Operands could not be broadcast together for {} on shapes {} \"\n \"and with the config option jax_numpy_rank_promotion='raise'. \"\n \"For more information, see \"\n \"https://jax.readthedocs.io/en/latest/rank_promotion_warning.html.\")\n raise ValueError(msg.format(fun_name, ' '.join(map(str, shapes))))\n\ndef _promote_dtypes(*args):\n \"\"\"Convenience function to apply Numpy argument dtype promotion.\"\"\"\n # TODO(dougalm,mattjj): This is a performance bottleneck. Consider memoizing.\n if len(args) < 2:\n return args\n else:\n to_dtype = result_type(*args)\n return [lax.convert_element_type(x, to_dtype) for x in args]\n\ndef _promote_dtypes_inexact(*args):\n \"\"\"Convenience function to apply Numpy argument dtype promotion.\n\n Promotes arguments to an inexact type.\"\"\"\n to_dtype = _to_inexact_dtype(result_type(*args))\n return [lax.convert_element_type(x, to_dtype) for x in args]\n\n\ndef _to_inexact_dtype(dtype):\n \"\"\"Promotes a dtype into an inexact dtype, if it is not already one.\"\"\"\n return dtype if issubdtype(dtype, inexact) else promote_types(dtype, float_)\n\ndef _complex_elem_type(dtype):\n \"\"\"Returns the float type of the real/imaginary parts of a complex dtype.\"\"\"\n return np.abs(np.zeros((), dtype)).dtype\n\ndef _result_dtype(op, *args):\n \"\"\"Compute result dtype of applying op to arguments with given dtypes.\"\"\"\n args = [np.ones((0,) * ndim(arg), _dtype(arg)) for arg in args]\n return _dtype(op(*args))\n\n\ndef _arraylike(x): return isinstance(x, ndarray) or isscalar(x)\ndef _check_arraylike(fun_name, *args):\n \"\"\"Check if all args fit JAX's definition of arraylike (ndarray or scalar).\"\"\"\n if _any(not _arraylike(arg) for arg in args):\n pos, arg = next((i, arg) for i, arg in enumerate(args)\n if not _arraylike(arg))\n msg = \"{} requires ndarray or scalar arguments, got {} at position {}.\"\n raise TypeError(msg.format(fun_name, type(arg), pos))\n\n\ndef _promote_args(fun_name, *args):\n \"\"\"Convenience function to apply Numpy argument shape and dtype promotion.\"\"\"\n _check_arraylike(fun_name, *args)\n return _promote_shapes(fun_name, *_promote_dtypes(*args))\n\ndef _promote_args_inexact(fun_name, *args):\n \"\"\"Convenience function to apply Numpy argument shape and dtype promotion.\n\n Promotes non-inexact types to an inexact type.\"\"\"\n _check_arraylike(fun_name, *args)\n return _promote_shapes(fun_name, *_promote_dtypes_inexact(*args))\n\ndef _constant_like(x, const):\n return np.array(const, dtype=_dtype(x))\n\n### implementations of numpy functions in terms of lax\n\n@_wraps(np.fmin)\ndef fmin(x1, x2):\n return where((x1 < x2) | isnan(x2), x1, x2)\n\n@_wraps(np.fmax)\ndef fmax(x1, x2):\n return where((x1 > x2) | isnan(x2), x1, x2)\n\n@_wraps(np.finfo)\ndef finfo(dtype):\n return dtypes.finfo(dtype)\n\n@_wraps(np.issubdtype)\ndef issubdtype(arg1, arg2):\n return dtypes.issubdtype(arg1, arg2)\n\n@_wraps(np.isscalar)\ndef isscalar(element):\n return dtypes.is_python_scalar(element) or np.isscalar(element)\n\niterable = np.iterable\n\n@_wraps(np.result_type)\ndef result_type(*args):\n return dtypes.result_type(*args)\n\ndef _one_to_one_unop(numpy_fn, lax_fn, promote_to_inexact=False):\n if promote_to_inexact:\n def fn(x):\n x = lax.convert_element_type(x, _to_inexact_dtype(_dtype(x)))\n return lax_fn(x)\n else:\n fn = lambda x: lax_fn(x)\n return _wraps(numpy_fn)(fn)\n\ndef _one_to_one_binop(numpy_fn, lax_fn, promote_to_inexact=False):\n if promote_to_inexact:\n fn = lambda x1, x2: lax_fn(*_promote_args_inexact(numpy_fn.__name__, x1, x2))\n else:\n fn = lambda x1, x2: lax_fn(*_promote_args(numpy_fn.__name__, x1, x2))\n return _wraps(numpy_fn)(fn)\n\ndef _maybe_bool_binop(numpy_fn, lax_fn, bool_lax_fn):\n def fn(x1, x2):\n x1, x2 = _promote_args(numpy_fn.__name__, x1, x2)\n return lax_fn(x1, x2) if x1.dtype != bool_ else bool_lax_fn(x1, x2)\n return _wraps(numpy_fn)(fn)\n\nfabs = _one_to_one_unop(np.fabs, lax.abs, True)\nbitwise_not = _one_to_one_unop(np.bitwise_not, lax.bitwise_not)\ninvert = _one_to_one_unop(np.invert, lax.bitwise_not)\nnegative = _one_to_one_unop(np.negative, lax.neg)\npositive = _one_to_one_unop(np.positive, lambda x: x)\n\nfloor = _one_to_one_unop(np.floor, lax.floor, True)\nceil = _one_to_one_unop(np.ceil, lax.ceil, True)\nexp = _one_to_one_unop(np.exp, lax.exp, True)\nlog = _one_to_one_unop(np.log, lax.log, True)\nexpm1 = _one_to_one_unop(np.expm1, lax.expm1, True)\nlog1p = _one_to_one_unop(np.log1p, lax.log1p, True)\nsin = _one_to_one_unop(np.sin, lax.sin, True)\ncos = _one_to_one_unop(np.cos, lax.cos, True)\ntan = _one_to_one_unop(np.tan, lax.tan, True)\narcsin = _one_to_one_unop(np.arcsin, lax.asin, True)\narccos = _one_to_one_unop(np.arccos, lax.acos, True)\narctan = _one_to_one_unop(np.arctan, lax.atan, True)\nsinh = _one_to_one_unop(np.sinh, lax.sinh, True)\ncosh = _one_to_one_unop(np.cosh, lax.cosh, True)\narcsinh = _one_to_one_unop(np.arcsinh, lax.asinh, True)\ntanh = _one_to_one_unop(np.tanh, lax.tanh, True)\narcsinh = _one_to_one_unop(np.arcsinh, lax.asinh, True)\narccosh = _one_to_one_unop(np.arccosh, lax.acosh, True)\narctanh = _one_to_one_unop(np.arctanh, lax.atanh, True)\nsqrt = _one_to_one_unop(np.sqrt, lax.sqrt, True)\n\n\nadd = _maybe_bool_binop(np.add, lax.add, lax.bitwise_or)\nbitwise_and = _one_to_one_binop(np.bitwise_and, lax.bitwise_and)\nbitwise_or = _one_to_one_binop(np.bitwise_or, lax.bitwise_or)\nbitwise_xor = _one_to_one_binop(np.bitwise_xor, lax.bitwise_xor)\nleft_shift = _one_to_one_binop(np.left_shift, lax.shift_left)\nequal = _one_to_one_binop(np.equal, lax.eq)\nmultiply = _maybe_bool_binop(np.multiply, lax.mul, lax.bitwise_and)\nnot_equal = _one_to_one_binop(np.not_equal, lax.ne)\nsubtract = _one_to_one_binop(np.subtract, lax.sub)\narctan2 = _one_to_one_binop(np.arctan2, lax.atan2, True)\nminimum = _one_to_one_binop(np.minimum, lax.min)\nmaximum = _one_to_one_binop(np.maximum, lax.max)\nfloat_power = _one_to_one_binop(np.float_power, lax.pow, True)\nnextafter = _one_to_one_binop(np.nextafter, lax.nextafter, True)\n\n\ndef _comparison_op(numpy_fn, lax_fn):\n def fn(x1, x2):\n x1, x2 = _promote_args(numpy_fn.__name__, x1, x2)\n # Comparison on complex types are defined as a lexicographic ordering on\n # the (real, imag) pair.\n if issubdtype(_dtype(x1), complexfloating):\n rx = lax.real(x1)\n ry = lax.real(x2)\n return lax.select(lax.eq(rx, ry), lax_fn(lax.imag(x1), lax.imag(x2)),\n lax_fn(rx, ry))\n return lax_fn(x1, x2)\n return _wraps(numpy_fn)(fn)\n\ngreater_equal = _comparison_op(np.greater_equal, lax.ge)\ngreater = _comparison_op(np.greater, lax.gt)\nless_equal = _comparison_op(np.less_equal, lax.le)\nless = _comparison_op(np.less, lax.lt)\n\n\ndef _logical_op(np_op, bitwise_op):\n @_wraps(np_op, update_doc=False)\n def op(*args):\n zero = lambda x: lax.full_like(x, shape=(), fill_value=0)\n args = (x if issubdtype(_dtype(x), bool_) else lax.ne(x, zero(x))\n for x in args)\n return bitwise_op(*_promote_args(np_op.__name__, *args))\n return op\n\nlogical_and = _logical_op(np.logical_and, lax.bitwise_and)\nlogical_not = _logical_op(np.logical_not, lax.bitwise_not)\nlogical_or = _logical_op(np.logical_or, lax.bitwise_or)\nlogical_xor = _logical_op(np.logical_xor, lax.bitwise_xor)\n\n\n@_wraps(np.right_shift)\ndef right_shift(x1, x2):\n x1, x2 = _promote_args(np.right_shift.__name__, x1, x2)\n lax_fn = lax.shift_right_logical if \\\n np.issubdtype(x1.dtype, np.unsignedinteger) else lax.shift_right_arithmetic\n return lax_fn(x1, x2)\n\n\n@_wraps(np.absolute)\ndef absolute(x):\n return x if issubdtype(_dtype(x), unsignedinteger) else lax.abs(x)\nabs = _wraps(np.abs)(absolute)\n\n\n@_wraps(np.rint)\ndef rint(x):\n dtype = _dtype(x)\n if issubdtype(dtype, integer):\n return lax.convert_element_type(x, float_)\n if issubdtype(dtype, complexfloating):\n return lax.complex(rint(lax.real(x)), rint(lax.imag(x)))\n return _round_to_nearest_even(x)\n\n\n@_wraps(np.sign)\ndef sign(x):\n dtype = _dtype(x)\n if issubdtype(dtype, complexfloating):\n re = lax.real(x)\n return lax.complex(\n lax.sign(where(re != 0, re, lax.imag(x))), _constant_like(re, 0))\n return lax.sign(x)\n\n\n@_wraps(np.copysign)\ndef copysign(x1, x2):\n if issubdtype(_dtype(x1), complexfloating) or issubdtype(_dtype(x2), complexfloating):\n raise TypeError(\"copysign does not support complex-valued inputs\")\n x1, x2 = _promote_shapes(\"copysign\", x1, x2)\n return where(signbit(x2), -lax.abs(x1), lax.abs(x1))\n\n\n@_wraps(np.true_divide)\ndef true_divide(x1, x2):\n x1, x2 = _promote_args_inexact(\"true_divide\", x1, x2)\n return lax.div(x1, x2)\n\n\n@_wraps(np.divide)\ndef divide(x1, x2):\n # decide whether to perform integer division based on Numpy result dtype, as a\n # way to check whether Python 3 style division is active in Numpy\n result_dtype = _result_dtype(np.divide, x1, x2)\n if issubdtype(result_dtype, integer):\n return floor_divide(x1, x2)\n else:\n return true_divide(x1, x2)\n\n\n@_wraps(np.floor_divide)\ndef floor_divide(x1, x2):\n x1, x2 = _promote_args(\"floor_divide\", x1, x2)\n dtype = _dtype(x1)\n if issubdtype(dtype, integer):\n quotient = lax.div(x1, x2)\n select = logical_and(lax.sign(x1) != lax.sign(x2), lax.rem(x1, x2) != 0)\n # TODO(mattjj): investigate why subtracting a scalar was causing promotion\n return where(select, quotient - np.array(1, _dtype(quotient)), quotient)\n elif issubdtype(dtype, complexfloating):\n x1r = lax.real(x1)\n x1i = lax.imag(x1)\n x2r = lax.real(x2)\n x2i = lax.imag(x2)\n which = lax.ge(lax.abs(x2r), lax.abs(x2i))\n rat1 = where(which, lax._const(x2i, 1), lax.div(x2r, x2i))\n rat2 = where(which, lax.div(x2i, x2r), lax._const(x2i, 1))\n out = lax.floor(lax.div(lax.add(lax.mul(x1r, rat1), lax.mul(x1i, rat2)),\n lax.add(lax.mul(x2r, rat1), lax.mul(x2i, rat2))))\n return lax.convert_element_type(out, dtype)\n else:\n return _float_divmod(x1, x2)[0]\n\n\n@_wraps(np.divmod)\ndef divmod(x1, x2):\n x1, x2 = _promote_args(\"divmod\", x1, x2)\n if issubdtype(_dtype(x1), integer):\n return floor_divide(x1, x2), remainder(x1, x2)\n else:\n return _float_divmod(x1, x2)\n\n\ndef _float_divmod(x1, x2):\n # see float_divmod in floatobject.c of CPython\n mod = lax.rem(x1, x2)\n div = lax.div(lax.sub(x1, mod), x2)\n\n ind = lax.bitwise_and(mod != 0, lax.sign(x2) != lax.sign(mod))\n mod = lax.select(ind, mod + x2, mod)\n div = lax.select(ind, div - _constant_like(div, 1), div)\n\n return lax.round(div), mod\n\n\n@_wraps(np.power)\ndef power(x1, x2):\n # Special case for small positive integer scalars: use binary exponentiation.\n # Using lax.pow may be imprecise for floating-point values; the goal of this\n # code path is to make sure we end up with a precise output for the common\n # pattern ``x ** 2`` or similar.\n if isinstance(x2, int):\n return lax.integer_pow(x1, x2)\n\n x1, x2 = _promote_args(np.power, x1, x2)\n dtype = _dtype(x1)\n if not issubdtype(dtype, integer):\n return lax.pow(x1, x2)\n\n # Integer power => use binary exponentiation.\n\n # TODO(phawkins): add integer pow support to XLA.\n bits = 6 # Anything more would overflow for any x1 > 1\n acc = ones(shape(x1), dtype=dtype)\n for _ in range(bits):\n acc = where(lax.bitwise_and(x2, _constant_like(x2, 1)),\n lax.mul(acc, x1), acc)\n x1 = lax.mul(x1, x1)\n x2 = lax.shift_right_logical(x2, _constant_like(x2, 1))\n return acc\n\n\n@custom_jvp\n@_wraps(np.logaddexp)\ndef logaddexp(x1, x2):\n x1, x2 = _promote_shapes(\"logaddexp\", *_promote_dtypes_inexact(x1, x2))\n amax = lax.max(x1, x2)\n delta = lax.sub(x1, x2)\n return lax.select(isnan(delta),\n lax.add(x1, x2), # NaNs or infinities of the same sign.\n lax.add(amax, lax.log1p(lax.exp(-lax.abs(delta)))))\n\[email protected]\ndef _logaddexp_jvp(primals, tangents):\n x1, x2 = primals\n t1, t2 = tangents\n x1, x2, t1, t2 = broadcast_arrays(x1, x2, t1, t2)\n primal_out = logaddexp(x1, x2)\n tangent_out = (t1 * exp(_replace_inf(x1) - _replace_inf(primal_out)) +\n t2 * exp(_replace_inf(x2) - _replace_inf(primal_out)))\n return primal_out, tangent_out\n\ndef _replace_inf(x):\n return lax.select(isposinf(x), zeros_like(x), x)\n\n\n@custom_jvp\n@_wraps(np.logaddexp2)\ndef logaddexp2(x1, x2):\n x1, x2 = _promote_shapes(\"logaddexp2\", *_promote_dtypes_inexact(x1, x2))\n amax = lax.max(x1, x2)\n delta = lax.sub(x1, x2)\n return lax.select(isnan(delta),\n lax.add(x1, x2), # NaNs or infinities of the same sign.\n lax.add(amax, lax.div(lax.log1p(exp2(-lax.abs(delta))),\n _constant_like(x1, np.log(2)))))\[email protected]\ndef _logaddexp2_jvp(primals, tangents):\n x1, x2 = primals\n t1, t2 = tangents\n x1, x2, t1, t2 = broadcast_arrays(x1, x2, t1, t2)\n primal_out = logaddexp2(x1, x2)\n tangent_out = (t1 * 2 ** (_replace_inf(x1) - _replace_inf(primal_out)) +\n t2 * 2 ** (_replace_inf(x2) - _replace_inf(primal_out)))\n return primal_out, tangent_out\n\n\n@_wraps(np.log2)\ndef log2(x):\n x, = _promote_dtypes_inexact(x)\n return lax.div(lax.log(x), lax.log(_constant_like(x, 2)))\n\n\n@_wraps(np.log10)\ndef log10(x):\n x, = _promote_dtypes_inexact(x)\n return lax.div(lax.log(x), lax.log(_constant_like(x, 10)))\n\n\n@_wraps(np.exp2)\ndef exp2(x):\n x, = _promote_dtypes_inexact(x)\n return lax.exp(lax.mul(lax.log(_constant_like(x, 2)), x))\n\n@_wraps(np.signbit)\ndef signbit(x):\n x, = _promote_shapes(\"signbit\", x)\n dtype = _dtype(x)\n if issubdtype(dtype, integer):\n return lax.lt(x, _constant_like(x, 0))\n elif issubdtype(dtype, bool_):\n return full_like(x, False, dtype=bool_)\n elif not issubdtype(dtype, floating):\n raise ValueError(\n \"jax.numpy.signbit is not well defined for %s\" % dtype)\n\n # TPU supports BF16 but not S16 types, so as a workaround, convert BF16 to\n # F32.\n if dtype == bfloat16:\n dtype = float32\n x = lax.convert_element_type(x, float32)\n\n info = finfo(dtype)\n if info.bits == 16:\n int_type = np.int16\n elif info.bits == 32:\n int_type = np.int32\n elif info.bits == 64:\n int_type = np.int64\n else:\n raise NotImplementedError(\n \"jax.numpy.signbit only supports 16, 32, and 64-bit types.\")\n\n x = lax.bitcast_convert_type(x, int_type)\n return lax.convert_element_type(x >> (info.nexp + info.nmant), np.bool_)\n\n\n\n@_wraps(np.trapz)\ndef trapz(y, x=None, dx=1.0, axis=-1):\n y = moveaxis(y, axis, -1)\n if x is not None:\n if ndim(x) == 1:\n dx = diff(x)\n else:\n dx = moveaxis(diff(x, axis=axis), axis, -1)\n return 0.5 * (dx * (y[..., 1:] + y[..., :-1])).sum(-1)\n\n\n@_wraps(np.trunc)\ndef trunc(x):\n return where(lax.lt(x, lax._const(x, 0)), ceil(x), floor(x))\n\n\ndef _conv(x, y, mode, op, precision):\n if issubdtype(x.dtype, complexfloating) or issubdtype(y.dtype, complexfloating):\n raise NotImplementedError(f\"{op}() does not support complex inputs\")\n if ndim(x) != 1 or ndim(y) != 1:\n raise ValueError(f\"{op}() only support 1-dimensional inputs.\")\n x, y = _promote_dtypes_inexact(x, y)\n if len(x) == 0 or len(y) == 0:\n raise ValueError(f\"{op}: inputs cannot be empty, got shapes {x.shape} and {y.shape}.\")\n\n out_order = slice(None)\n if len(x) < len(y):\n x, y = y, x\n if op == \"correlate\":\n out_order = slice(None, None, -1)\n if op == 'convolve':\n y = y[::-1]\n\n if mode == 'valid':\n padding = [(0, 0)]\n elif mode == 'same':\n padding = [(y.shape[0] // 2, y.shape[0] - y.shape[0] // 2 - 1)]\n elif mode == 'full':\n padding = [(y.shape[0] - 1, y.shape[0] - 1)]\n else:\n raise ValueError(\"mode must be one of ['full', 'same', 'valid']\")\n\n result = lax.conv_general_dilated(x[None, None, :], y[None, None, :], (1,),\n padding, precision=precision)\n return result[0, 0, out_order]\n\n\n@_wraps(np.convolve, lax_description=_PRECISION_DOC)\ndef convolve(a, v, mode='full', *, precision=None):\n return _conv(a, v, mode, 'convolve', precision)\n\n\n@_wraps(np.correlate, lax_description=_PRECISION_DOC)\ndef correlate(a, v, mode='valid', *, precision=None):\n return _conv(a, v, mode, 'correlate', precision)\n\n\ndef _normalize_float(x):\n info = finfo(_dtype(x))\n cond = lax.abs(x) < info.tiny\n x1 = where(cond, x * (1 << info.nmant), x)\n x2 = where(cond,\n full_like(x, -info.nmant, dtype=np.int32),\n zeros_like(x, dtype=np.int32))\n return lax.convert_element_type(x1, _dtype(x)), x2\n\n_INT_DTYPES = {\n 16: np.int16,\n 32: np.int32,\n 64: np.int64,\n}\n\n@_wraps(np.ldexp)\n@jit\ndef ldexp(x1, x2):\n dtype = _result_dtype(np.ldexp, x1, x2)\n x1, x2 = _promote_shapes(\"ldexp\", x1, x2)\n x1 = lax.convert_element_type(x1, dtype)\n\n info = finfo(dtype)\n mask = (1 << info.nexp) - 1\n bias = ((1 << info.nexp) - 1) >> 1\n\n int_type = _INT_DTYPES[info.bits]\n\n x, e = _normalize_float(x1)\n x2 += lax.convert_element_type(e, np.int32)\n x = lax.bitcast_convert_type(x, int_type)\n x2 += ((x >> info.nmant) & mask) - bias\n\n # find underflow/overflow before denormalization\n underflow_cond = x2 < -(bias + info.nmant)\n overflow_cond = x2 > bias\n\n m = ones_like(x, dtype=dtype)\n\n # denormals\n cond = x2 < -bias + 1\n x2 = where(cond, x2 + info.nmant, x2)\n m = where(cond, m / (1 << info.nmant), m)\n\n x2 = lax.convert_element_type(x2, np.int32)\n x &= ~(mask << info.nmant)\n x |= ((lax.convert_element_type(x2, int_type) + bias) << info.nmant)\n\n x = lax.convert_element_type(m, dtype) * lax.bitcast_convert_type(x, dtype)\n\n # underflow\n x = where(underflow_cond, zeros_like(x, dtype=dtype), x)\n # overflow\n x = where(overflow_cond, lax.sign(x1) * full_like(x, np.inf), x)\n # ldexp(x1, x2) = x1 for x1 = inf, -inf, nan, 0\n return where(isinf(x1) | isnan(x1) | (x1 == 0), x1, x)\n\n\n@_wraps(np.frexp)\n@jit\ndef frexp(x):\n x = asarray(x)\n if issubdtype(x.dtype, complexfloating):\n raise TypeError(\"frexp does not support complex-valued inputs\")\n elif not issubdtype(x.dtype, floating):\n x = lax.convert_element_type(x, float_)\n\n dtype = _dtype(x)\n info = finfo(dtype)\n mask = (1 << info.nexp) - 1\n bias = ((1 << info.nexp) - 1) >> 1\n\n int_type = _INT_DTYPES[info.bits]\n\n x1, x2 = _normalize_float(x)\n x1 = lax.bitcast_convert_type(x1, int_type)\n x2 += ((x1 >> info.nmant) & mask) - bias + 1\n x1 &= ~(mask << info.nmant)\n x1 |= (bias - 1) << info.nmant\n x1 = lax.bitcast_convert_type(x1, dtype)\n\n cond = isinf(x) | isnan(x) | (x == 0)\n x2 = where(cond, zeros_like(x2), x2)\n return where(cond, x, x1), lax.convert_element_type(x2, int32)\n\n\n@_wraps(np.remainder)\ndef remainder(x1, x2):\n x1, x2 = _promote_args(\"remainder\", x1, x2)\n zero = _constant_like(x1, 0)\n trunc_mod = lax.rem(x1, x2)\n trunc_mod_not_zero = lax.ne(trunc_mod, zero)\n do_plus = lax.bitwise_and(\n lax.ne(lax.lt(trunc_mod, zero), lax.lt(x2, zero)), trunc_mod_not_zero)\n return lax.select(do_plus, lax.add(trunc_mod, x2), trunc_mod)\nmod = _wraps(np.mod)(remainder)\n\n\n@_wraps(np.fmod)\ndef fmod(x1, x2):\n if issubdtype(_dtype(x1, x2), integer):\n x2 = where(x2 == 0, 1, x2)\n return lax.rem(*_promote_args(np.fmod, x1, x2))\n\n\n@_wraps(np.cbrt)\ndef cbrt(x):\n x, = _promote_dtypes_inexact(x)\n return lax.sign(x) * power(lax.abs(x), _constant_like(x, 1. / 3.))\n\n\n@_wraps(np.square)\ndef square(x): return lax.integer_pow(x, 2)\n\n\n@_wraps(np.deg2rad)\ndef deg2rad(x):\n x, = _promote_dtypes_inexact(x)\n return lax.mul(x, lax._const(x, pi / 180))\n\n\n@_wraps(np.rad2deg)\ndef rad2deg(x):\n x, = _promote_dtypes_inexact(x)\n return lax.mul(x, lax._const(x, 180 / pi))\n\n\ndegrees = rad2deg\nradians = deg2rad\n\n\n@_wraps(np.histogram_bin_edges)\ndef histogram_bin_edges(a, bins=10, range=None, weights=None):\n if isinstance(bins, str):\n raise NotImplementedError(\"string values for `bins` not implemented.\")\n a = ravel(a)\n b = array(bins)\n if b.ndim == 1:\n return b\n if range is None:\n range = (a.min(), a.max())\n assert len(range) == 2\n range = asarray(range)\n range = (where(ptp(range) == 0, range[0] - 0.5, range[0]),\n where(ptp(range) == 0, range[1] + 0.5, range[1]))\n dtype = _dtype(a)\n if issubdtype(dtype, integer):\n dtype = promote_types(dtype, float32)\n return linspace(range[0], range[1], bins + 1, dtype=dtype)\n\n\n@_wraps(np.histogram)\ndef histogram(a, bins=10, range=None, weights=None, density=None):\n if weights is not None and a.shape != weights.shape:\n raise ValueError(\"weights should have the same shape as a.\")\n a = ravel(a)\n if weights is not None:\n weights = ravel(weights)\n else:\n weights = ones_like(a)\n bin_edges = histogram_bin_edges(a, bins, range, weights)\n bin_idx = searchsorted(bin_edges, a, side='right')\n bin_idx = where(a == bin_edges[-1], len(bin_edges) - 1, bin_idx)\n counts = bincount(bin_idx, weights, length=len(bin_edges))[1:]\n if density:\n bin_widths = diff(bin_edges)\n counts = counts / bin_widths / counts.sum()\n return counts, bin_edges\n\n\n@_wraps(np.heaviside)\ndef heaviside(x1, x2):\n x1, x2 = _promote_dtypes_inexact(x1, x2)\n zero = lax._const(x1, 0)\n return where(lax.lt(x1, zero), zero,\n where(lax.gt(x1, zero), lax._const(x1, 1), x2))\n\n\n@_wraps(np.hypot)\ndef hypot(x1, x2):\n x1, x2 = _promote_dtypes_inexact(x1, x2)\n return lax.sqrt(x1*x1 + x2*x2)\n\n\n@_wraps(np.reciprocal)\ndef reciprocal(x):\n x, = _promote_dtypes_inexact(x)\n return lax.integer_pow(x, -1)\n\n\n@_wraps(np.sinc, update_doc=False)\ndef sinc(x):\n x, = _promote_dtypes_inexact(x)\n eq_zero = lax.eq(x, lax._const(x, 0))\n safe_x = where(eq_zero, lax._const(x, 0), x)\n pi_x = lax.mul(lax._const(x, pi), safe_x)\n return where(eq_zero,\n lax._const(x, 1), lax.div(lax.sin(pi_x), pi_x))\n\n\n@_wraps(np.transpose)\ndef transpose(a, axes=None):\n axes = np.arange(ndim(a))[::-1] if axes is None else axes\n return lax.transpose(a, axes)\n\n\n@_wraps(np.rot90)\ndef rot90(m, k=1, axes=(0, 1)):\n ax1, ax2 = axes\n ax1 = _canonicalize_axis(ax1, m.ndim)\n ax2 = _canonicalize_axis(ax2, m.ndim)\n if ax1 == ax2:\n raise ValueError(\"Axes must be different\") # same as numpy error\n k = k % 4\n if k == 0:\n return m\n elif k == 2:\n return flip(flip(m, ax1), ax2)\n else:\n perm = list(range(m.ndim))\n perm[ax1], perm[ax2] = perm[ax2], perm[ax1]\n if k == 1:\n return transpose(flip(m, ax2), perm)\n else:\n return flip(transpose(m, perm), ax2)\n\n\n@_wraps(np.flip)\ndef flip(m, axis=None):\n if axis is None:\n return lax.rev(m, list(range(len(m.shape))))\n return lax.rev(m, [_canonicalize_axis(axis, len(m.shape))])\n\n\n@_wraps(np.fliplr)\ndef fliplr(m):\n return flip(m, 1)\n\n\n@_wraps(np.flipud)\ndef flipud(m):\n return flip(m, 0)\n\n\n@_wraps(np.conjugate)\ndef conjugate(x):\n return lax.conj(x) if iscomplexobj(x) else x\nconj = conjugate\n\n\n@_wraps(np.imag)\ndef imag(val):\n return lax.imag(val) if iscomplexobj(val) else zeros_like(val)\n\n\n@_wraps(np.real)\ndef real(val):\n return lax.real(val) if iscomplexobj(val) else val\n\n\n@_wraps(np.iscomplex)\ndef iscomplex(x):\n i = imag(x)\n return lax.ne(i, lax._const(i, 0))\n\n@_wraps(np.isreal)\ndef isreal(x):\n i = imag(x)\n return lax.eq(i, lax._const(i, 0))\n\n@_wraps(np.angle)\ndef angle(z):\n re = real(z)\n im = imag(z)\n dtype = _dtype(re)\n if not issubdtype(dtype, inexact) or (\n issubdtype(_dtype(z), floating) and ndim(z) == 0):\n dtype = dtypes.canonicalize_dtype(float_)\n re = lax.convert_element_type(re, dtype)\n im = lax.convert_element_type(im, dtype)\n return lax.atan2(im, re)\n\n\n@_wraps(np.diff)\ndef diff(a, n=1, axis=-1,):\n if not isinstance(a, ndarray) or a.ndim == 0:\n return a\n if n == 0:\n return a\n if n < 0:\n raise ValueError(\n \"order must be non-negative but got \" + repr(n))\n\n nd = a.ndim\n\n slice1 = [slice(None)] * nd\n slice2 = [slice(None)] * nd\n slice1[axis] = slice(1, None)\n slice2[axis] = slice(None, -1)\n slice1 = tuple(slice1)\n slice2 = tuple(slice2)\n\n op = not_equal if a.dtype == np.bool_ else subtract\n for _ in range(n):\n a = op(a[slice1], a[slice2])\n\n return a\n\n_EDIFF1D_DOC = \"\"\"\\\nUnlike NumPy's implementation of ediff1d, :py:func:`jax.numpy.ediff1d` will not\nissue an error if casting ``to_end`` or ``to_begin`` to the type of ``ary``\nloses precision.\n\"\"\"\n\n@_wraps(np.ediff1d, lax_description=_EDIFF1D_DOC)\ndef ediff1d(ary, to_end=None, to_begin=None):\n ary = ravel(asarray(ary))\n result = lax.sub(ary[1:], ary[:-1])\n if to_begin is not None:\n result = concatenate((ravel(asarray(to_begin, dtype=ary.dtype)), result))\n if to_end is not None:\n result = concatenate((result, ravel(asarray(to_end, dtype=ary.dtype))))\n return result\n\n\n@partial(jit, static_argnums=2)\ndef _gradient(a, varargs, axis):\n def gradient_along_axis(a, h, axis):\n sliced = partial(lax.slice_in_dim, a, axis=axis)\n a_grad = concatenate((\n (sliced(1, 2) - sliced(0, 1)), # upper edge\n (sliced(2, None) - sliced(None, -2)) * 0.5, # inner\n (sliced(-1, None) - sliced(-2, -1)), # lower edge\n ), axis)\n return a_grad / h\n\n if axis is None:\n axis = range(a.ndim)\n else:\n if isinstance(axis, int):\n axis = (axis,)\n if not isinstance(axis, tuple) and not isinstance(axis, list):\n raise ValueError(\"Give `axis` either as int or iterable\")\n elif len(axis) == 0:\n return []\n axis = [_canonicalize_axis(i, a.ndim) for i in axis]\n\n if _min([s for i, s in enumerate(a.shape) if i in axis]) < 2:\n raise ValueError(\"Shape of array too small to calculate \"\n \"a numerical gradient, \"\n \"at least 2 elements are required.\")\n len_axes = len(axis)\n n = len(varargs)\n if n == 0 or varargs is None:\n # no spacing\n dx = [1.0] * len_axes\n elif n == 1:\n # single value for all axes\n dx = varargs * len_axes\n elif n == len_axes:\n dx = varargs\n else:\n TypeError(\"Invalid number of spacing arguments %d\" % n)\n\n if ndim(dx[0]) != 0:\n raise NotImplementedError(\"Non-constant spacing not implemented\")\n\n # TODO: use jax.lax loop tools if possible\n a_grad = [gradient_along_axis(a, h, ax) for ax, h in zip(axis, dx)]\n\n if len(axis) == 1:\n a_grad = a_grad[0]\n\n return a_grad\n\n\n@_wraps(np.gradient)\ndef gradient(f, *args, **kwargs):\n axis = kwargs.pop(\"axis\", None)\n if not len(kwargs) == 0:\n raise ValueError(\"Only `axis` keyword is implemented\")\n return _gradient(f, args, axis)\n\n\n@_wraps(np.isrealobj)\ndef isrealobj(x):\n return not iscomplexobj(x)\n\n\n@_wraps(np.reshape)\ndef reshape(a, newshape, order=\"C\"):\n try:\n return a.reshape(newshape, order=order) # forward to method for ndarrays\n except AttributeError:\n return _reshape(a, newshape, order=order)\n\ndef _compute_newshape(a, newshape):\n \"\"\"Fixes a -1 value in newshape, if present.\"\"\"\n # other errors, like having more than one -1, are caught downstream\n newsize = _prod(newshape)\n if newsize < 0:\n fix = a.size // -newsize\n return [d if d != -1 else fix for d in newshape]\n else:\n return newshape\n\ndef _reshape(a, newshape, order=\"C\"):\n computed_newshape = _compute_newshape(a, newshape)\n if order == \"C\":\n return lax.reshape(a, computed_newshape, None)\n elif order == \"F\":\n dims = np.arange(ndim(a))[::-1]\n return lax.reshape(a, computed_newshape[::-1], dims).T\n elif order == \"A\":\n raise NotImplementedError(\"np.reshape order=A is not implemented.\")\n else:\n raise ValueError(\"Unexpected value for 'order' argument: {}.\".format(order))\n\ndef _reshape_method(a, *newshape, **kwargs):\n order = kwargs.pop(\"order\", \"C\")\n if len(kwargs) == 1:\n invalid_kwarg, = kwargs\n msg = \"'{}' is an invalid keyword argument for this function\"\n raise TypeError(msg.format(invalid_kwarg)) # same as NumPy error\n elif kwargs:\n invalid_kwargs = \"'{}'\".format(\"'\".join(kwargs))\n msg = \"{} are invalid keyword arguments for this function\"\n raise TypeError(msg.format(invalid_kwargs)) # different from NumPy error\n if len(newshape) == 1 and not isinstance(newshape[0], int):\n newshape = newshape[0]\n return _reshape(a, newshape, order=order)\n\n\n@_wraps(np.ravel)\ndef ravel(a, order=\"C\"):\n if order == \"K\":\n raise NotImplementedError(\"Ravel not implemented for order='K'.\")\n return reshape(a, (size(a),), order)\n\n\n_UNRAVEL_INDEX_DOC = \"\"\"\\\nUnlike numpy's implementation of unravel_index, negative indices are accepted\nand out-of-bounds indices are clipped.\n\"\"\"\n\n@_wraps(np.unravel_index, lax_description=_UNRAVEL_INDEX_DOC)\ndef unravel_index(indices, shape):\n indices = asarray(indices)\n sizes = pad(shape, (0, 1), constant_values=1)\n cumulative_sizes = cumprod(sizes[::-1])[::-1]\n total_size = cumulative_sizes[0]\n # Clip so raveling and unraveling an oob index will not change the behavior\n clipped_indices = clip(indices, -total_size, total_size - 1)\n # Add enough trailing dims to avoid conflict with flat_index\n cumulative_sizes = cumulative_sizes.reshape([-1] + [1] * indices.ndim)\n idx = clipped_indices % cumulative_sizes[:-1] // cumulative_sizes[1:]\n return tuple(idx)\n\n\n@_wraps(np.squeeze)\ndef squeeze(a, axis: Union[int, Tuple[int, ...]] = None):\n if axis is None:\n a_shape = shape(a)\n axis = tuple(i for i, d in enumerate(a_shape) if d == 1)\n elif not isinstance(axis, tuple):\n axis = (axis,)\n return lax.squeeze(a, axis)\n\n\n@_wraps(np.expand_dims)\ndef expand_dims(a, axis: Union[int, Tuple[int, ...]]):\n if not isinstance(axis, tuple):\n axis = (axis,)\n return lax.expand_dims(a, axis)\n\n\n@_wraps(np.swapaxes)\ndef swapaxes(a, axis1, axis2):\n perm = np.arange(ndim(a))\n perm[axis1], perm[axis2] = perm[axis2], perm[axis1]\n return lax.transpose(a, perm)\n\n\n@_wraps(np.moveaxis)\ndef moveaxis(a, source, destination):\n if isinstance(source, int):\n source = (source,)\n if isinstance(destination, int):\n destination = (destination,)\n source = tuple(_canonicalize_axis(i, ndim(a)) for i in source)\n destination = tuple(_canonicalize_axis(i, ndim(a)) for i in destination)\n if len(source) != len(destination):\n raise ValueError(\"Inconsistent number of elements: {} vs {}\"\n .format(len(source), len(destination)))\n perm = [i for i in range(ndim(a)) if i not in source]\n for dest, src in sorted(zip(destination, source)):\n perm.insert(dest, src)\n return lax.transpose(a, perm)\n\n\n@_wraps(np.isclose)\ndef isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):\n a, b = _promote_args(\"isclose\", asarray(a), asarray(b))\n dtype = _dtype(a)\n if issubdtype(dtype, inexact):\n if issubdtype(dtype, complexfloating):\n dtype = _complex_elem_type(dtype)\n rtol = lax.convert_element_type(rtol, dtype)\n atol = lax.convert_element_type(atol, dtype)\n out = lax.le(\n lax.abs(lax.sub(a, b)),\n lax.add(atol, lax.mul(rtol, lax.abs(b))))\n # This corrects the comparisons for infinite and nan values\n a_inf = isinf(a)\n b_inf = isinf(b)\n any_inf = logical_or(a_inf, b_inf)\n both_inf = logical_and(a_inf, b_inf)\n # Make all elements where either a or b are infinite to False\n out = logical_and(out, logical_not(any_inf))\n # Make all elements where both a or b are the same inf to True\n same_value = lax.eq(a, b)\n same_inf = logical_and(both_inf, same_value)\n out = logical_or(out, same_inf)\n\n # Make all elements where either a or b is NaN to False\n a_nan = isnan(a)\n b_nan = isnan(b)\n any_nan = logical_or(a_nan, b_nan)\n out = logical_and(out, logical_not(any_nan))\n if equal_nan:\n # Make all elements where both a and b is NaN to True\n both_nan = logical_and(a_nan, b_nan)\n out = logical_or(out, both_nan)\n return _maybe_numpy_1_13_isclose_behavior(a, out)\n else:\n return lax.eq(a, b)\n\nnumpy_version = tuple(map(int, np.version.version.split('.')[:2]))\nif numpy_version < (1, 14):\n # see discussion at https://github.com/numpy/numpy/pull/9720\n def _maybe_numpy_1_13_isclose_behavior(a, out):\n if size(out) == 1 and issubdtype(_dtype(a), complexfloating):\n return lax.reshape(out, (1,))\n else:\n return out\nelse:\n def _maybe_numpy_1_13_isclose_behavior(a, out):\n return out\n\n@_wraps(np.interp)\ndef interp(x, xp, fp, left=None, right=None, period=None):\n if shape(xp) != shape(fp) or ndim(xp) != 1:\n raise ValueError(\"xp and fp must be one-dimensional arrays of equal size\")\n x, xp, fp = map(asarray, _promote_dtypes_inexact(x, xp, fp))\n if period is not None:\n if period == 0:\n raise ValueError(f\"period must be a non-zero value; got {period}\")\n period = abs(period)\n x = x % period\n xp = xp % period\n xp, fp = lax.sort_key_val(xp, fp)\n xp = concatenate([xp[-1:] - period, xp, xp[:1] + period])\n fp = concatenate([fp[-1:], fp, fp[:1]])\n\n i = clip(searchsorted(xp, x, side='right'), 1, len(xp) - 1)\n df = fp[i] - fp[i - 1]\n dx = xp[i] - xp[i - 1]\n delta = x - xp[i - 1]\n f = where((dx == 0), fp[i], fp[i - 1] + (delta / dx) * df)\n\n if period is None:\n f = where(x < xp[0], fp[0] if left is None else left, f)\n f = where(x > xp[-1], fp[-1] if right is None else right, f)\n return f\n\n\n@_wraps(np.in1d, lax_description=\"\"\"\nIn the JAX version, the `assume_unique` argument is not referenced.\n\"\"\")\ndef in1d(ar1, ar2, assume_unique=False, invert=False):\n # TODO(vanderplas): use sorting-based approach for larger inputs.\n ar1 = ravel(ar1)\n ar2 = ravel(ar2)\n if invert:\n return (ar1[:, None] != ar2).all(-1)\n else:\n return (ar1[:, None] == ar2).any(-1)\n\n@partial(jit, static_argnums=2)\ndef _intersect1d_sorted_mask(ar1, ar2, return_indices=False):\n \"\"\"\n Helper function for intersect1d which is jit-able\n \"\"\"\n ar = concatenate((ar1, ar2))\n if return_indices:\n iota = lax.broadcasted_iota(np.int64, shape(ar), dimension=0)\n aux, indices = lax.sort_key_val(ar, iota)\n else:\n aux = sort(ar)\n\n mask = aux[1:] == aux[:-1]\n if return_indices:\n return aux, mask, indices\n else:\n return aux, mask\n\n@_wraps(np.intersect1d)\ndef intersect1d(ar1, ar2, assume_unique=False, return_indices=False):\n\n if not assume_unique:\n if return_indices:\n ar1, ind1 = unique(ar1, return_index=True)\n ar2, ind2 = unique(ar2, return_index=True)\n else:\n ar1 = unique(ar1)\n ar2 = unique(ar2)\n else:\n ar1 = ravel(ar1)\n ar2 = ravel(ar2)\n\n if return_indices:\n aux, mask, aux_sort_indices = _intersect1d_sorted_mask(ar1, ar2, return_indices)\n else:\n aux, mask = _intersect1d_sorted_mask(ar1, ar2, return_indices)\n\n int1d = aux[:-1][mask]\n\n if return_indices:\n ar1_indices = aux_sort_indices[:-1][mask]\n ar2_indices = aux_sort_indices[1:][mask] - ar1.size\n if not assume_unique:\n ar1_indices = ind1[ar1_indices]\n ar2_indices = ind2[ar2_indices]\n\n return int1d, ar1_indices, ar2_indices\n else:\n return int1d\n\n\n@_wraps(np.isin, lax_description=\"\"\"\nIn the JAX version, the `assume_unique` argument is not referenced.\n\"\"\")\ndef isin(element, test_elements, assume_unique=False, invert=False):\n result = in1d(element, test_elements, assume_unique=assume_unique, invert=invert)\n return result.reshape(shape(element))\n\n\n# The `jit` on `where` exists to avoid materializing constants in cases like\n# `np.where(np.zeros(1000), 7, 4)`. In op-by-op mode, we don't want to\n# materialize the broadcast forms of scalar arguments.\n@jit\ndef _where(condition, x=None, y=None):\n if x is None or y is None:\n raise ValueError(\"Either both or neither of the x and y arguments should \"\n \"be provided to jax.numpy.where, got {} and {}.\"\n .format(x, y))\n if not issubdtype(_dtype(condition), bool_):\n condition = lax.ne(condition, zeros_like(condition))\n x, y = _promote_dtypes(x, y)\n condition, x, y = broadcast_arrays(condition, x, y)\n return lax.select(condition, x, y) if np.size(x) else x\n\n\n_WHERE_DOC = \"\"\"\\\nAt present, JAX does not support JIT-compilation of the single-argument form\nof :py:func:`jax.numpy.where` because its output shape is data-dependent. The\nthree-argument form does not have a data-dependent shape and can be JIT-compiled\nsuccessfully.\n\"\"\"\n\n@_wraps(np.where, update_doc=False, lax_description=_WHERE_DOC)\ndef where(condition, x=None, y=None):\n if x is None and y is None:\n return nonzero(asarray(condition))\n else:\n return _where(condition, x, y)\n\n\n@_wraps(np.select)\ndef select(condlist, choicelist, default=0):\n if len(condlist) != len(choicelist):\n msg = \"condlist must have length equal to choicelist ({} vs {})\"\n raise ValueError(msg.format(len(condlist), len(choicelist)))\n if len(condlist) == 0:\n raise ValueError(\"condlist must be non-empty\")\n choices = _promote_dtypes(default, *choicelist)\n choicelist = choices[1:]\n output = choices[0]\n for cond, choice in zip(condlist[::-1], choicelist[::-1]):\n output = where(cond, choice, output)\n return output\n\n\n@_wraps(np.bincount, lax_description=\"\"\"\\\nJax adds the optional `length` parameter which specifies the output length, and\ndefaults to ``x.max() + 1``. It must be specified for bincount to be compilable.\nValues larger than the specified length will be discarded.\n\nAdditionally, while ``np.bincount`` raises an error if the input array contains\nnegative values, ``jax.numpy.bincount`` treats negative values as zero.\n\"\"\")\ndef bincount(x, weights=None, minlength=0, *, length=None):\n if not issubdtype(_dtype(x), integer):\n msg = f\"x argument to bincount must have an integer type; got {x.dtype}\"\n raise TypeError(msg)\n if length is None:\n length = max(x) + 1\n length = _max(length, minlength)\n if ndim(x) != 1:\n raise ValueError(\"only 1-dimensional input supported.\")\n if weights is None:\n weights = array(1, dtype=int32)\n else:\n if shape(x) != shape(weights):\n raise ValueError(\"shape of weights must match shape of x.\")\n return ops.index_add(zeros((length,), _dtype(weights)), ops.index[clip(x, 0)], weights)\n\n\ndef broadcast_arrays(*args):\n \"\"\"Like Numpy's broadcast_arrays but doesn't return views.\"\"\"\n shapes = [shape(arg) for arg in args]\n if len(set(shapes)) == 1:\n return [arg if isinstance(arg, ndarray) or isscalar(arg) else array(arg)\n for arg in args]\n result_shape = lax.broadcast_shapes(*shapes)\n return [broadcast_to(arg, result_shape) for arg in args]\n\n\n@_wraps(np.broadcast_to, lax_description=\"\"\"\\\nThe JAX version does not necessarily return a view of the input.\n\"\"\")\ndef broadcast_to(arr, shape):\n arr = arr if isinstance(arr, ndarray) else array(arr)\n shape = canonicalize_shape(shape) # check that shape is concrete\n arr_shape = _shape(arr)\n if arr_shape == shape:\n return arr\n else:\n nlead = len(shape) - len(arr_shape)\n compatible = np.equal(arr_shape, shape[nlead:]) | np.equal(arr_shape, 1)\n if nlead < 0 or not np.all(compatible):\n msg = \"Incompatible shapes for broadcasting: {} and requested shape {}\"\n raise ValueError(msg.format(arr_shape, shape))\n diff, = np.where(np.not_equal(shape[nlead:], arr_shape))\n new_dims = tuple(range(nlead)) + tuple(nlead + diff)\n kept_dims = tuple(np.delete(np.arange(len(shape)), new_dims))\n return lax.broadcast_in_dim(squeeze(arr, tuple(diff)), shape, kept_dims)\n\n\n@_wraps(np.split)\ndef split(ary, indices_or_sections, axis=0):\n axis = core.concrete_or_error(int, axis, \"in jax.numpy.split argument `axis`\")\n size = ary.shape[axis]\n if isinstance(indices_or_sections, (tuple, list) + _arraylike_types):\n indices_or_sections = [core.concrete_or_error(int, i_s, \"in jax.numpy.split argument 1\")\n for i_s in indices_or_sections]\n split_indices = np.concatenate([[0], indices_or_sections, [size]])\n else:\n indices_or_sections = core.concrete_or_error(int, indices_or_sections,\n \"in jax.numpy.split argument 1\")\n part_size, r = _divmod(size, indices_or_sections)\n if r != 0:\n raise ValueError(\"array split does not result in an equal division\")\n split_indices = np.arange(indices_or_sections + 1) * part_size\n starts, ends = [0] * ndim(ary), shape(ary)\n _subval = lambda x, i, v: subvals(x, [(i, v)])\n return [lax.slice(ary, _subval(starts, axis, start), _subval(ends, axis, end))\n for start, end in zip(split_indices[:-1], split_indices[1:])]\n\ndef _split_on_axis(np_fun, axis):\n @_wraps(np_fun, update_doc=False)\n def f(ary, indices_or_sections):\n return split(ary, indices_or_sections, axis=axis)\n return f\n\nvsplit = _split_on_axis(np.vsplit, axis=0)\nhsplit = _split_on_axis(np.hsplit, axis=1)\ndsplit = _split_on_axis(np.dsplit, axis=2)\n\n\n@_wraps(np.clip)\ndef clip(a, a_min=None, a_max=None):\n if a_min is None and a_max is None:\n raise ValueError(\"At most one of a_min and a_max may be None\")\n if a_min is not None:\n if _dtype(a_min) != _dtype(a):\n a_min = lax.convert_element_type(a_min, _dtype(a))\n a = maximum(a_min, a)\n if a_max is not None:\n if _dtype(a_max) != _dtype(a):\n a_max = lax.convert_element_type(a_max, _dtype(a))\n a = minimum(a_max, a)\n return a\n\n\ndef _round_to_nearest_even(x):\n half = lax._const(x, 0.5)\n one = lax._const(x, 1)\n round_val = lax.floor(x)\n fraction = x - round_val\n nearest_even_int = lax.sub(\n round_val, lax.mul(lax._const(x, 2), lax.floor(lax.mul(half, x))))\n is_odd = lax.eq(nearest_even_int, one)\n return lax.select(\n lax.bitwise_or(lax.gt(fraction, half),\n lax.bitwise_and(lax.eq(fraction, half), is_odd)),\n lax.add(round_val, one), round_val)\n\n@_wraps(np.round, update_doc=False)\ndef round(a, decimals=0):\n dtype = _dtype(a)\n if issubdtype(dtype, integer):\n if decimals < 0:\n raise NotImplementedError(\n \"integer np.round not implemented for decimals < 0\")\n return a # no-op on integer types\n\n def _round_float(x):\n if decimals == 0:\n return _round_to_nearest_even(x)\n\n # TODO(phawkins): the strategy of rescaling the value isn't necessarily a\n # good one since we may be left with an incorrectly rounded value at the\n # end due to precision problems. As a workaround for float16, convert to\n # float32,\n x = lax.convert_element_type(x, np.float32) if dtype == np.float16 else x\n factor = _constant_like(x, 10 ** decimals)\n out = lax.div(_round_to_nearest_even(lax.mul(x, factor)), factor)\n return lax.convert_element_type(out, dtype) if dtype == np.float16 else out\n\n if issubdtype(dtype, complexfloating):\n return lax.complex(_round_float(lax.real(a)), _round_float(lax.imag(a)))\n else:\n return _round_float(a)\naround = round\n\n\n@_wraps(np.fix)\ndef fix(x, out=None):\n if out is not None:\n raise ValueError(\"fix does not support the `out` argument.\")\n zero = lax._const(x, 0)\n return where(lax.ge(x, zero), floor(x), ceil(x))\n\n\n@_wraps(np.modf)\ndef modf(x, out=None):\n if out is not None:\n raise ValueError(\"modf does not support the `out` argument.\")\n whole = fix(x)\n return x - whole, whole\n\n\n@_wraps(np.isfinite)\ndef isfinite(x):\n dtype = _dtype(x)\n if issubdtype(dtype, floating):\n return lax.is_finite(x)\n elif issubdtype(dtype, complexfloating):\n return lax.bitwise_and(lax.is_finite(real(x)), lax.is_finite(imag(x)))\n else:\n return full_like(x, True, dtype=bool_)\n\n@_wraps(np.isinf)\ndef isinf(x):\n dtype = _dtype(x)\n if issubdtype(dtype, floating):\n return lax.eq(lax.abs(x), _constant_like(x, inf))\n elif issubdtype(dtype, complexfloating):\n re = lax.real(x)\n im = lax.imag(x)\n return lax.bitwise_or(lax.eq(lax.abs(re), _constant_like(re, inf)),\n lax.eq(lax.abs(im), _constant_like(im, inf)))\n else:\n return full_like(x, False, dtype=bool_)\n\ndef _isposneginf(infinity, x):\n dtype = _dtype(x)\n if issubdtype(dtype, floating):\n return lax.eq(x, _constant_like(x, infinity))\n elif issubdtype(dtype, complexfloating):\n raise ValueError(\"isposinf/isneginf are not well defined for complex types\")\n else:\n return full_like(x, False, dtype=bool_)\n\nisposinf = _wraps(np.isposinf)(lambda x: _isposneginf(inf, x))\n\nisneginf = _wraps(np.isneginf)(lambda x: _isposneginf(-inf, x))\n\n@_wraps(np.isnan)\ndef isnan(x):\n return lax.bitwise_and(lax.bitwise_not(isfinite(x)),\n lax.bitwise_not(isinf(x)))\n\n@_wraps(np.nan_to_num)\ndef nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None):\n del copy\n dtype = _dtype(x)\n if issubdtype(dtype, complexfloating):\n return lax.complex(\n nan_to_num(lax.real(x), nan=nan, posinf=posinf, neginf=neginf),\n nan_to_num(lax.imag(x), nan=nan, posinf=posinf, neginf=neginf))\n info = finfo(dtypes.canonicalize_dtype(dtype))\n posinf = info.max if posinf is None else posinf\n neginf = info.min if neginf is None else neginf\n x = where(isnan(x), _constant_like(x, nan), x)\n x = where(isposinf(x), _constant_like(x, posinf), x)\n x = where(isneginf(x), _constant_like(x, neginf), x)\n return x\n\n### Reducers\n\n\ndef _make_reduction(np_fun, op, init_val, preproc=None, bool_op=None,\n upcast_f16_for_computation=False):\n \"\"\"Creates reduction function given a binary operation and monoid identity.\"\"\"\n\n bool_op = bool_op or op\n\n @_wraps(np_fun)\n def reduction(a, axis=None, dtype=None, out=None, keepdims=False):\n if out is not None:\n raise ValueError(\"reduction does not support the `out` argument.\")\n\n if isinstance(a, (list, tuple)):\n msg = (\"jax.numpy reductions won't accept lists and tuples in future \"\n \"versions, only scalars and ndarrays\")\n warnings.warn(msg, category=FutureWarning)\n a = a if isinstance(a, ndarray) else asarray(a)\n a = preproc(a) if preproc else a\n dims = _reduction_dims(a, axis)\n result_dtype = dtype or _dtype(np_fun(np.ones((), dtype=_dtype(a))))\n if upcast_f16_for_computation and issubdtype(result_dtype, inexact):\n computation_dtype = promote_types(result_dtype, float32)\n else:\n computation_dtype = result_dtype\n a = lax.convert_element_type(a, computation_dtype)\n result = lax.reduce(a, _reduction_init_val(a, init_val),\n op if computation_dtype != np.bool_ else bool_op, dims)\n if keepdims:\n result = expand_dims(result, dims)\n return lax.convert_element_type(result, dtype or result_dtype)\n\n return reduction\n\ndef _reduction_dims(a, axis):\n if axis is None:\n return tuple(range(ndim(a)))\n elif isinstance(axis, (np.ndarray, tuple, list)):\n if len(axis) != len(set(axis)):\n raise ValueError(f\"duplicate value in 'axis': {axis}\")\n return tuple(_canonicalize_axis(x, ndim(a)) for x in axis)\n elif isinstance(axis, int):\n return (_canonicalize_axis(axis, ndim(a)),)\n else:\n raise TypeError(\"Unexpected type of axis argument: {}\".format(type(axis)))\n\ndef _reduction_init_val(a, init_val):\n a_dtype = dtypes.canonicalize_dtype(_dtype(a))\n if a_dtype == 'bool':\n return np.array(init_val > 0, dtype=a_dtype)\n try:\n return np.array(init_val, dtype=a_dtype)\n except OverflowError:\n assert issubdtype(a_dtype, integer)\n sign, info = np.sign(init_val), iinfo(a_dtype)\n return np.array(info.min if sign < 0 else info.max, dtype=a_dtype)\n\n_cast_to_bool = partial(lax.convert_element_type, new_dtype=bool_)\n\nsum = _make_reduction(np.sum, lax.add, 0, upcast_f16_for_computation=True,\n bool_op=lax.bitwise_or)\nproduct = prod = _make_reduction(np.prod, lax.mul, 1, bool_op=lax.bitwise_and,\n upcast_f16_for_computation=True)\namax = max = _make_reduction(np.max, lax.max, -np.inf)\namin = min = _make_reduction(np.min, lax.min, np.inf)\nall = alltrue = _make_reduction(np.all, lax.bitwise_and, True, _cast_to_bool)\nany = sometrue = _make_reduction(np.any, lax.bitwise_or, False, _cast_to_bool)\n\n\n@_wraps(np.mean)\ndef mean(a, axis=None, dtype=None, out=None, keepdims=False):\n if out is not None:\n raise ValueError(\"mean does not support the `out` argument.\")\n\n if axis is None:\n normalizer = size(a)\n else:\n normalizer = np.prod(np.take(shape(a), axis))\n if dtype is None:\n if issubdtype(_dtype(a), bool_) or issubdtype(_dtype(a), integer):\n dtype = float_\n else:\n dtype = _dtype(a)\n\n return lax.div(\n sum(a, axis, dtype=dtype, keepdims=keepdims),\n lax.convert_element_type(normalizer, dtype))\n\n@_wraps(np.average)\ndef average(a, axis=None, weights=None, returned=False):\n a = asarray(a)\n\n if weights is None: # Treat all weights as 1\n avg = mean(a, axis=axis)\n if axis is None:\n weights_sum = full((), size(a), dtype=avg.dtype)\n else:\n weights_sum = full_like(avg, a.shape[axis], dtype=avg.dtype)\n else:\n weights = asarray(weights)\n\n if issubdtype(a.dtype, inexact):\n out_dtype = result_type(a.dtype, weights.dtype)\n else:\n out_dtype = result_type(a.dtype, weights.dtype, float_)\n out_dtype = dtypes.canonicalize_dtype(out_dtype)\n\n a_shape = shape(a)\n a_ndim = len(a_shape)\n weights_shape = shape(weights)\n axis = None if axis is None else _canonicalize_axis(axis, a_ndim)\n\n if a_shape != weights_shape:\n # Make sure the dimensions work out\n if axis is None:\n raise ValueError(\"Axis must be specified when shapes of a and \"\n \"weights differ.\")\n if len(weights_shape) != 1:\n raise ValueError(\"1D weights expected when shapes of a and \"\n \"weights differ.\")\n if weights_shape[0] != a_shape[axis]:\n raise ValueError(\"Length of weights not \"\n \"compatible with specified axis.\")\n\n weights = broadcast_to(weights, (a_ndim - 1) * (1,) + weights_shape)\n weights = moveaxis(weights, -1, axis)\n\n weights_sum = sum(weights, axis=axis, dtype=out_dtype)\n avg = sum(multiply(a, weights), axis=axis, dtype=out_dtype) / weights_sum\n\n if returned:\n if avg.shape != weights_sum.shape:\n weights_sum = broadcast_to(weights_sum, avg.shape)\n return avg, weights_sum\n return avg\n\n\n@_wraps(np.var)\ndef var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):\n if out is not None:\n raise ValueError(\"var does not support the `out` argument.\")\n\n a_dtype, dtype = _var_promote_types(_dtype(a), dtype)\n a_mean = mean(a, axis, dtype=a_dtype, keepdims=True)\n centered = a - a_mean\n if issubdtype(centered.dtype, complexfloating):\n centered = lax.real(lax.mul(centered, lax.conj(centered)))\n else:\n centered = lax.square(centered)\n\n if axis is None:\n normalizer = size(a)\n else:\n normalizer = np.prod(np.take(shape(a), axis))\n normalizer = normalizer - ddof\n\n result = sum(centered, axis, keepdims=keepdims)\n out = lax.div(result, lax.convert_element_type(normalizer, result.dtype))\n return lax.convert_element_type(out, dtype)\n\n\ndef _var_promote_types(a_dtype, dtype):\n if dtype:\n if (not issubdtype(dtype, complexfloating) and\n issubdtype(a_dtype, complexfloating)):\n msg = (\"jax.numpy.var does not yet support real dtype parameters when \"\n \"computing the variance of an array of complex values. The \"\n \"semantics of numpy.var seem unclear in this case. Please comment \"\n \"on https://github.com/google/jax/issues/2283 if this behavior is \"\n \"important to you.\")\n raise ValueError(msg)\n a_dtype = promote_types(a_dtype, dtype)\n else:\n if not issubdtype(a_dtype, inexact):\n dtype = a_dtype = float_\n else:\n dtype = _complex_elem_type(a_dtype)\n a_dtype = promote_types(a_dtype, float32)\n return a_dtype, dtype\n\n\n@_wraps(np.std)\ndef std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):\n if out is not None:\n raise ValueError(\"std does not support the `out` argument.\")\n return sqrt(var(a, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims))\n\n\n@_wraps(np.ptp)\ndef ptp(a, axis=None, out=None, keepdims=False):\n if out is not None:\n raise ValueError(\"ptp does not support the `out` argument.\")\n x = amax(a, axis=axis, keepdims=keepdims)\n y = amin(a, axis=axis, keepdims=keepdims)\n return lax.sub(x, y)\n\n\n@_wraps(np.allclose)\ndef allclose(a, b, rtol=1e-05, atol=1e-08):\n return all(isclose(a, b, rtol, atol))\n\n\n@_wraps(np.count_nonzero)\ndef count_nonzero(a, axis=None, keepdims=False):\n return sum(lax.ne(a, _constant_like(a, 0)), axis=axis,\n dtype=dtypes.canonicalize_dtype(np.int_), keepdims=keepdims)\n\n\n_NONZERO_DOC = \"\"\"\\\nAt present, JAX does not support JIT-compilation of :py:func:`jax.numpy.nonzero`\nbecause its output shape is data-dependent.\n\"\"\"\n\n@_wraps(np.nonzero, lax_description=_NONZERO_DOC)\ndef nonzero(a):\n # Note: this function cannot be jitted because its output has a dynamic\n # shape.\n a = atleast_1d(a)\n dims = shape(a)\n ndims = len(dims)\n ds = [lax.broadcasted_iota(int_, dims + (1,), i) for i in range(ndims)]\n d = concatenate(ds, axis=-1)\n indexes = d[a != 0]\n return tuple(indexes[..., i] for i in range(ndims))\n\n\n@_wraps(np.flatnonzero)\ndef flatnonzero(a):\n return nonzero(ravel(a))[0]\n\n\ndef _make_nan_reduction(np_reduction, jnp_reduction, init_val, nan_if_all_nan):\n @_wraps(np_reduction)\n def nan_reduction(a, axis=None, out=None, keepdims=False, **kwargs):\n out = jnp_reduction(where(isnan(a), _reduction_init_val(a, init_val), a),\n axis=axis, out=out, keepdims=keepdims, **kwargs)\n if nan_if_all_nan:\n return where(all(isnan(a), axis=axis, keepdims=keepdims),\n _constant_like(a, nan), out)\n else:\n return out\n\n return nan_reduction\n\nnanmin = _make_nan_reduction(np.nanmin, min, inf, nan_if_all_nan=True)\nnanmax = _make_nan_reduction(np.nanmax, max, -inf, nan_if_all_nan=True)\nnansum = _make_nan_reduction(np.nansum, sum, 0, nan_if_all_nan=False)\nnanprod = _make_nan_reduction(np.nanprod, prod, 1, nan_if_all_nan=False)\n\n@_wraps(np.nanmean)\ndef nanmean(a, axis=None, dtype=None, out=None, keepdims=False):\n if out is not None:\n raise ValueError(\"nanmean does not support the `out` argument.\")\n if issubdtype(_dtype(a), bool_) or issubdtype(_dtype(a), integer):\n return mean(a, axis, dtype, out, keepdims)\n if dtype is None:\n dtype = _dtype(a)\n nan_mask = logical_not(isnan(a))\n normalizer = sum(nan_mask, axis=axis, dtype=int32, keepdims=keepdims)\n normalizer = lax.convert_element_type(normalizer, dtype)\n td = lax.div(nansum(a, axis, dtype=dtype, keepdims=keepdims), normalizer)\n return td\n\n\n@_wraps(np.nanvar)\ndef nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):\n if out is not None:\n raise ValueError(\"nanvar does not support the `out` argument.\")\n\n a_dtype, dtype = _var_promote_types(_dtype(a), dtype)\n a_mean = nanmean(a, axis, dtype=a_dtype, keepdims=True)\n centered = a - a_mean\n if issubdtype(centered.dtype, complexfloating):\n centered = lax.real(lax.mul(centered, lax.conj(centered)))\n else:\n centered = lax.square(centered)\n\n normalizer = sum(logical_not(isnan(a)), axis=axis, keepdims=keepdims)\n normalizer = normalizer - ddof\n if config.omnistaging_enabled:\n normalizer_mask = lax.le(normalizer, 0)\n else:\n zero = lax.full_like(normalizer, 0, shape=())\n normalizer_mask = lax.le(normalizer, zero)\n\n result = nansum(centered, axis, keepdims=keepdims)\n result = where(normalizer_mask, nan, result)\n divisor = where(normalizer_mask, 1, normalizer)\n out = lax.div(result, lax.convert_element_type(divisor, result.dtype))\n return lax.convert_element_type(out, dtype)\n\n\n@_wraps(np.nanstd)\ndef nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):\n if out is not None:\n raise ValueError(\"nanstd does not support the `out` argument.\")\n return sqrt(nanvar(a, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims))\n\n\ndef _make_cumulative_reduction(np_reduction, reduction, fill_nan=False, fill_value=0):\n # We want to allow XLA to fuse the pad and reduce-window operators to\n # avoid materializing the padded output.\n # Consider removing `jit` once again if reduce-window is generalized to\n # support arbitrary padding.\n @partial(jit, static_argnums=(1, 2))\n def _cumulative_reduction(a, axis, dtype):\n if axis is None or isscalar(a):\n a = ravel(a)\n axis = 0\n\n a_shape = list(shape(a))\n num_dims = len(a_shape)\n\n if axis < 0:\n axis = axis + num_dims\n if axis < 0 or axis >= num_dims:\n raise ValueError(\n \"axis {} is out of bounds for array of dimension {}\".format(\n axis, num_dims))\n\n if fill_nan:\n a = where(isnan(a), _constant_like(a, fill_value), a)\n\n if not dtype and _dtype(a) == bool_:\n dtype = int_\n if dtype:\n a = lax.convert_element_type(a, dtype)\n\n return reduction(a, axis)\n\n @_wraps(np_reduction)\n def cumulative_reduction(a, axis=None, dtype=None):\n # jit doesn't support kwargs as static_args.\n return _cumulative_reduction(a, axis, dtype)\n return cumulative_reduction\n\n\ncumsum = _make_cumulative_reduction(np.cumsum, lax.cumsum, fill_nan=False)\ncumprod = _make_cumulative_reduction(np.cumprod, lax.cumprod, fill_nan=False)\ncumproduct = cumprod\nnancumsum = _make_cumulative_reduction(np.nancumsum, lax.cumsum,\n fill_nan=True, fill_value=0)\nnancumprod = _make_cumulative_reduction(np.nancumprod, lax.cumprod,\n fill_nan=True, fill_value=1)\n\n\n@_wraps(np.unwrap)\ndef unwrap(p, discont=pi, axis=-1):\n dd = diff(p, axis=axis)\n ddmod = mod(dd + pi, 2 * pi) - pi\n ddmod = where((ddmod == -pi) & (dd > 0), pi, ddmod)\n\n ph_correct = where(abs(dd) < discont, 0, ddmod - dd)\n\n up = concatenate((\n lax.slice_in_dim(p, 0, 1, axis=axis),\n lax.slice_in_dim(p, 1, None, axis=axis) + cumsum(ph_correct, axis=axis)\n ), axis=axis)\n\n return up\n\n\n### Array-creation functions\n\ndef _check_no_padding(axis_padding, mode):\n if (axis_padding[0] > 0 or axis_padding[1] > 0):\n msg = \"Cannot apply '{}' padding to empty axis\"\n raise ValueError(msg.format(mode))\n\n\ndef _pad_constant(array, pad_width, constant_values):\n nd = ndim(array)\n constant_values = broadcast_to(asarray(constant_values), (nd, 2))\n constant_values = lax.convert_element_type(constant_values, array.dtype)\n for i in range(nd):\n widths = [(0, 0, 0)] * nd\n widths[i] = (pad_width[i, 0], 0, 0)\n array = lax.pad(array, constant_values[i, 0], widths)\n widths[i] = (0, pad_width[i, 1], 0)\n array = lax.pad(array, constant_values[i, 1], widths)\n return array\n\n\ndef _pad_wrap(array, pad_width):\n for i in range(ndim(array)):\n if array.shape[i] == 0:\n _check_no_padding(pad_width[i], \"wrap\")\n continue\n size = array.shape[i]\n repeats, (left_remainder, right_remainder) = _divmod(pad_width[i], size)\n total_repeats = repeats.sum() + 1\n parts = []\n if left_remainder:\n parts += [lax.slice_in_dim(array, size - left_remainder, size, axis=i)]\n parts += total_repeats * [array]\n if right_remainder:\n parts += [lax.slice_in_dim(array, 0, right_remainder, axis=i)]\n array = lax.concatenate(parts, dimension=i)\n return array\n\n\ndef _pad_symmetric_or_reflect(array, pad_width, mode):\n assert mode in (\"symmetric\", \"reflect\")\n\n for i in range(ndim(array)):\n if array.shape[i] == 0:\n _check_no_padding(pad_width[i], mode)\n continue\n\n n = array.shape[i]\n rarray = lax.rev(array, dimensions=(i,))\n offset = 1 if (mode == \"reflect\" and n > 1) else 0\n\n def build_padding(padding, forward):\n xs = []\n delta = n - offset\n while padding > delta:\n padding -= delta\n p = array if forward else rarray\n xs.append(lax.slice_in_dim(p, offset, n, axis=i))\n forward = not forward\n if padding > 0:\n x = lax.slice_in_dim(array if forward else rarray, offset,\n padding + offset, axis=i)\n xs.append(x)\n return xs\n\n parts = reversed(build_padding(pad_width[i, 0], forward=True))\n parts = [lax.rev(x, dimensions=(i,)) for x in parts]\n parts += [array]\n parts += build_padding(pad_width[i, 1], forward=False)\n array = lax.concatenate(parts, dimension=i)\n return array\n\n\ndef _pad_edge(array, pad_width):\n nd = ndim(array)\n for i in range(nd):\n if array.shape[i] == 0:\n _check_no_padding(pad_width[i], \"edge\")\n continue\n\n n = array.shape[i]\n npad_before, npad_after = pad_width[i]\n\n edge_before = lax.slice_in_dim(array, 0, 1, axis=i)\n pad_before = repeat(edge_before, npad_before, axis=i)\n\n edge_after = lax.slice_in_dim(array, n-1, n, axis=i)\n pad_after = repeat(edge_after, npad_after, axis=i)\n\n array = lax.concatenate([pad_before, array, pad_after], dimension=i)\n return array\n\n\n@partial(jit, static_argnums=(1, 2))\ndef _pad(array, pad_width, mode, constant_values):\n array = asarray(array)\n nd = ndim(array)\n pad_width = np.broadcast_to(np.asarray(pad_width), (nd, 2))\n if np.any(pad_width < 0):\n raise ValueError(\"index can't contain negative values\")\n\n if mode == \"constant\":\n return _pad_constant(array, pad_width, constant_values)\n\n elif mode == \"wrap\":\n return _pad_wrap(array, pad_width)\n\n elif mode in (\"symmetric\", \"reflect\"):\n return _pad_symmetric_or_reflect(array, pad_width, mode)\n\n elif mode == \"edge\":\n return _pad_edge(array, pad_width)\n\n else:\n msg = \"Unimplemented padding mode '{}' for np.pad.\"\n raise NotImplementedError(msg.format(mode))\n\n@_wraps(np.pad)\ndef pad(array, pad_width, mode='constant', constant_values=0):\n if isinstance(pad_width, list):\n pad_width = tuple(pad_width)\n return _pad(array, pad_width, mode, constant_values)\n\n\n@_wraps(np.stack)\ndef stack(arrays, axis=0):\n if not len(arrays):\n raise ValueError(\"Need at least one array to stack.\")\n shape0 = shape(arrays[0])\n axis = _canonicalize_axis(axis, len(shape0) + 1)\n new_arrays = []\n for a in arrays:\n if shape(a) != shape0:\n raise ValueError(\"All input arrays must have the same shape.\")\n new_arrays.append(expand_dims(a, axis))\n return concatenate(new_arrays, axis=axis)\n\n@_wraps(np.tile)\ndef tile(A, reps):\n if isinstance(reps, int):\n reps = (reps,)\n A = reshape(A, (1,) * (len(reps) - ndim(A)) + shape(A))\n reps = (1,) * (ndim(A) - len(reps)) + tuple(reps)\n for i, rep in enumerate(reps):\n if rep == 0:\n A = A[tuple(slice(0 if j == i else None) for j in range(A.ndim))]\n elif rep != 1:\n A = concatenate([A] * int(rep), axis=i)\n return A\n\n@_wraps(np.concatenate)\ndef concatenate(arrays, axis=0):\n if not len(arrays):\n raise ValueError(\"Need at least one array to concatenate.\")\n if ndim(arrays[0]) == 0:\n raise ValueError(\"Zero-dimensional arrays cannot be concatenated.\")\n if axis is None:\n return concatenate([ravel(a) for a in arrays], axis=0)\n axis = _canonicalize_axis(axis, ndim(arrays[0]))\n arrays = _promote_dtypes(*arrays)\n # lax.concatenate can be slow to compile for wide concatenations, so form a\n # tree of concatenations as a workaround especially for op-by-op mode.\n # (https://github.com/google/jax/issues/653).\n k = 16\n if len(arrays) == 1:\n return array(arrays[0])\n else:\n while len(arrays) > 1:\n arrays = [lax.concatenate(arrays[i:i+k], axis)\n for i in range(0, len(arrays), k)]\n return arrays[0]\n\n\n@_wraps(np.vstack)\ndef vstack(tup):\n return concatenate([atleast_2d(m) for m in tup], axis=0)\nrow_stack = vstack\n\n\n@_wraps(np.hstack)\ndef hstack(tup):\n arrs = [atleast_1d(m) for m in tup]\n if arrs[0].ndim == 1:\n return concatenate(arrs, 0)\n return concatenate(arrs, 1)\n\n\n@_wraps(np.dstack)\ndef dstack(tup):\n return concatenate([atleast_3d(m) for m in tup], axis=2)\n\n\n@_wraps(np.column_stack)\ndef column_stack(tup):\n arrays = []\n for v in tup:\n arr = array(v)\n if arr.ndim < 2:\n arr = atleast_2d(arr).T\n arrays.append(arr)\n return concatenate(arrays, 1)\n\n\ndef _atleast_nd(x, n):\n m = ndim(x)\n return lax.broadcast(x, (1,) * (n - m)) if m < n else x\n\ndef _block(xs):\n if isinstance(xs, tuple):\n raise ValueError(\"jax.numpy.block does not allow tuples, got {}\"\n .format(xs))\n elif isinstance(xs, list):\n if len(xs) == 0:\n raise ValueError(\"jax.numpy.block does not allow empty list arguments\")\n xs, depths = unzip2([_block(x) for x in xs])\n if _any(d != depths[0] for d in depths[1:]):\n raise ValueError(\"Mismatched list depths in jax.numpy.block\")\n rank = _max(depths[0], _max(ndim(x) for x in xs))\n xs = [_atleast_nd(x, rank) for x in xs]\n return concatenate(xs, axis=-depths[0]), depths[0] + 1\n else:\n return asarray(xs), 1\n\n@_wraps(np.block)\n@jit\ndef block(arrays):\n out, _ = _block(arrays)\n return out\n\n\n@_wraps(np.atleast_1d, update_doc=False)\ndef atleast_1d(*arys):\n if len(arys) == 1:\n arr = array(arys[0])\n return arr if ndim(arr) >= 1 else reshape(arr, -1)\n else:\n return [atleast_1d(arr) for arr in arys]\n\n\n@_wraps(np.atleast_2d, update_doc=False)\ndef atleast_2d(*arys):\n if len(arys) == 1:\n arr = array(arys[0])\n if ndim(arr) >= 2:\n return arr\n elif ndim(arr) == 1:\n return expand_dims(arr, axis=0)\n else:\n return expand_dims(arr, axis=(0, 1))\n else:\n return [atleast_2d(arr) for arr in arys]\n\n\n@_wraps(np.atleast_3d, update_doc=False)\ndef atleast_3d(*arys):\n if len(arys) == 1:\n arr = array(arys[0])\n if ndim(arr) == 0:\n arr = expand_dims(arr, axis=(0, 1, 2))\n elif ndim(arr) == 1:\n arr = expand_dims(arr, axis=(0, 2))\n elif ndim(arr) == 2:\n arr = expand_dims(arr, axis=2)\n return arr\n else:\n return [atleast_3d(arr) for arr in arys]\n\n\n@_wraps(np.array)\ndef array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\n if order is not None and order != \"K\":\n raise NotImplementedError(\"Only implemented for order='K'\")\n lax._check_user_dtype_supported(dtype, \"array\")\n dtype = dtype and dtypes.canonicalize_dtype(dtype)\n\n if _can_call_numpy_array(object):\n object = _np_array(object, dtype=dtype, ndmin=ndmin)\n assert type(object) not in dtypes.python_scalar_dtypes\n\n if type(object) is np.ndarray:\n out = _device_put_raw(object)\n if dtype: assert _dtype(out) == dtype\n elif isinstance(object, (DeviceArray, core.Tracer)):\n if isinstance(object, DeviceArray) and copy:\n # We perform a copy by bouncing back to the host\n # TODO(phawkins): add a device runtime function to copy a buffer\n out = _device_put_raw(_np_asarray(object))\n else:\n out = object\n elif isinstance(object, (list, tuple)):\n if object:\n out = stack([array(elt, dtype=dtype) for elt in object])\n else:\n out = _device_put_raw(_np_array([], dtype=dtype))\n else:\n try:\n view = memoryview(object)\n except TypeError:\n pass # `object` does not support the buffer interface.\n else:\n return array(_np_asarray(view), dtype, copy)\n\n raise TypeError(\"Unexpected input type for array: {}\".format(type(object)))\n\n if dtype and _dtype(out) != dtype:\n out = lax.convert_element_type(out, dtype)\n\n if ndmin > ndim(out):\n out = lax.broadcast(out, (1,) * (ndmin - ndim(out)))\n return out\n\ndef _can_call_numpy_array(x):\n return _all(not isinstance(l, (core.Tracer, DeviceArray))\n for l in tree_leaves(x))\n\n\n@_wraps(np.asarray)\ndef asarray(a, dtype=None, order=None):\n lax._check_user_dtype_supported(dtype, \"asarray\")\n return array(a, dtype=dtype, copy=False, order=order)\n\n\n@_wraps(np.zeros_like)\ndef zeros_like(a, dtype=None):\n lax._check_user_dtype_supported(dtype, \"zeros_like\")\n return lax.full_like(a, 0, dtype)\n\n\n@_wraps(np.ones_like)\ndef ones_like(a, dtype=None):\n lax._check_user_dtype_supported(dtype, \"ones_like\")\n return lax.full_like(a, 1, dtype)\n\n\n@_wraps(np.full)\ndef full(shape, fill_value, dtype=None):\n lax._check_user_dtype_supported(dtype, \"full\")\n shape = (shape,) if ndim(shape) == 0 else shape\n return lax.full(shape, fill_value, dtype)\n\n\n@_wraps(np.full_like)\ndef full_like(a, fill_value, dtype=None):\n lax._check_user_dtype_supported(dtype, \"full_like\")\n return lax.full_like(a, fill_value, dtype)\n\n\n@_wraps(np.zeros)\ndef zeros(shape, dtype=None):\n if isinstance(shape, types.GeneratorType):\n raise TypeError(\"expected sequence object with len >= 0 or a single integer\")\n lax._check_user_dtype_supported(dtype, \"zeros\")\n dtype = float_ if dtype is None else dtype\n shape = (shape,) if ndim(shape) == 0 else shape\n return lax.full(shape, 0, dtype)\n\n@_wraps(np.ones)\ndef ones(shape, dtype=None):\n if isinstance(shape, types.GeneratorType):\n raise TypeError(\"expected sequence object with len >= 0 or a single integer\")\n lax._check_user_dtype_supported(dtype, \"ones\")\n dtype = float_ if dtype is None else dtype\n shape = (shape,) if ndim(shape) == 0 else shape\n return lax.full(shape, 1, dtype)\n\n\n@_wraps(np.array_equal)\ndef array_equal(a1, a2, equal_nan=False):\n try:\n a1, a2 = asarray(a1), asarray(a2)\n except Exception:\n return False\n if shape(a1) != shape(a2):\n return False\n eq = asarray(a1 == a2)\n if equal_nan:\n eq = logical_or(eq, logical_and(isnan(a1), isnan(a2)))\n return all(eq)\n\n\n# We can't create uninitialized arrays in XLA; use zeros for empty.\nempty_like = zeros_like\nempty = zeros\n\n\n@_wraps(np.eye)\ndef eye(N, M=None, k=0, dtype=None):\n lax._check_user_dtype_supported(dtype, \"eye\")\n dtype = float_ if dtype is None else dtype\n M = N if M is None else M\n k = int(k)\n if N < 0 or M < 0:\n msg = \"negative dimensions are not allowed, got {} and {}\"\n raise ValueError(msg.format(N, M))\n if k is not None:\n k_dtype = _dtype(k)\n if not issubdtype(k_dtype, integer):\n msg = \"eye argument `k` must be of integer dtype, got {}\"\n raise TypeError(msg.format(k_dtype))\n return lax._eye(dtype, (N, M), k)\n\n\n@_wraps(np.identity)\ndef identity(n, dtype=None):\n lax._check_user_dtype_supported(dtype, \"identity\")\n return eye(n, dtype=dtype)\n\n\n@_wraps(np.arange)\ndef arange(start, stop=None, step=None, dtype=None):\n lax._check_user_dtype_supported(dtype, \"arange\")\n require = partial(core.concrete_or_error, _np_asarray)\n msg = \"in jax.numpy.arange argument `{}`\".format\n if stop is None and step is None:\n start = require(start, msg(\"stop\"))\n dtype = dtype or _dtype(start)\n return lax.iota(dtype, np.ceil(start)) # avoids materializing\n else:\n start = require(start, msg(\"start\"))\n stop = None if stop is None else require(stop, msg(\"stop\"))\n step = None if step is None else require(step, msg(\"step\"))\n if dtype is None:\n dtype = _dtype(start, *(x for x in [stop, step] if x is not None))\n return array(np.arange(start, stop=stop, step=step, dtype=dtype))\n\n\ndef _wrap_numpy_nullary_function(f):\n \"\"\"Adapts `f` to return a DeviceArray instead of an np.ndarray.\n\n `f` cannot have any non-static array arguments.\n \"\"\"\n @_wraps(f, update_doc=False)\n def wrapper(*args, **kwargs):\n return asarray(f(*args, **kwargs))\n return wrapper\n\n\n@_wraps(np.linspace)\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,\n axis=0):\n \"\"\"Implementation of linspace differentiable in start and stop args.\"\"\"\n lax._check_user_dtype_supported(dtype, \"linspace\")\n if num < 0:\n raise ValueError(\"Number of samples, %s, must be non-negative.\" % num)\n\n dtype = dtype or result_type(start, stop, dtypes.canonicalize_dtype(float_))\n computation_dtype = promote_types(dtype, dtypes.canonicalize_dtype(float_))\n start = asarray(start, dtype=computation_dtype)\n stop = asarray(stop, dtype=computation_dtype)\n\n bounds_shape = list(lax.broadcast_shapes(shape(start), shape(stop)))\n broadcast_start = broadcast_to(start, bounds_shape)\n broadcast_stop = broadcast_to(stop, bounds_shape)\n axis = len(bounds_shape) + axis + 1 if axis < 0 else axis\n bounds_shape.insert(axis, 1)\n iota_shape = [1,] * len(bounds_shape)\n iota_shape[axis] = num\n div = (num - 1) if endpoint else num\n if num > 1:\n delta = lax.convert_element_type(stop - start, computation_dtype) / div\n if issubdtype(dtype, integer):\n # This is similar to how numpy computes linspace, but it\n # can fail to recover the endpoints in float32 arithmetic.\n out = (reshape(broadcast_start, bounds_shape) +\n reshape(lax.iota(dtype, num), iota_shape) *\n reshape(delta, bounds_shape))\n else:\n # This approach recovers the endpoints with float32 arithmetic,\n # but can lead to rounding errors for integer outputs.\n step = reshape(lax.iota(computation_dtype, num), iota_shape) / div\n out = (reshape(broadcast_start, bounds_shape) * (1 - step) +\n reshape(broadcast_stop, bounds_shape) * step)\n elif num == 1:\n delta = nan if endpoint else stop - start\n out = reshape(broadcast_start, bounds_shape)\n else: # num == 0 degenerate case, match numpy behavior\n empty_shape = list(lax.broadcast_shapes(shape(start), shape(stop)))\n empty_shape.insert(axis, 0)\n delta = nan\n out = reshape(array([], dtype=dtype), empty_shape)\n if retstep:\n return lax.convert_element_type(out, dtype), delta\n else:\n return lax.convert_element_type(out, dtype)\n\n\n@_wraps(np.logspace)\ndef logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):\n \"\"\"Implementation of logspace differentiable in start and stop args.\"\"\"\n dtype = dtype or result_type(start, stop, dtypes.canonicalize_dtype(float_))\n computation_dtype = promote_types(dtype, dtypes.canonicalize_dtype(float_))\n start = asarray(start, dtype=computation_dtype)\n stop = asarray(stop, dtype=computation_dtype)\n lin = linspace(start, stop, num,\n endpoint=endpoint, retstep=False, dtype=None, axis=axis)\n return lax.convert_element_type(power(base, lin), dtype)\n\n\n@_wraps(np.geomspace)\ndef geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):\n \"\"\"Implementation of geomspace differentiable in start and stop args.\"\"\"\n dtype = dtype or result_type(start, stop, dtypes.canonicalize_dtype(float_))\n computation_dtype = promote_types(dtype, dtypes.canonicalize_dtype(float_))\n start = asarray(start, dtype=computation_dtype)\n stop = asarray(stop, dtype=computation_dtype)\n # follow the numpy geomspace convention for negative and complex endpoints\n signflip = 1 - (1 - sign(real(start))) * (1 - sign(real(stop))) // 2\n res = signflip * logspace(log10(signflip * start),\n log10(signflip * stop), num,\n endpoint=endpoint, base=10.0,\n dtype=computation_dtype, axis=0)\n if axis != 0:\n res = moveaxis(res, 0, axis)\n return lax.convert_element_type(res, dtype)\n\n\n@_wraps(np.meshgrid)\ndef meshgrid(*args, **kwargs):\n indexing = kwargs.get(\"indexing\", \"xy\")\n sparse = kwargs.get(\"sparse\", False)\n copy = kwargs.get(\"copy\", True)\n if not copy:\n raise ValueError(\"jax.numpy.meshgrid only supports copy=True\")\n\n args = list(args)\n if indexing == \"xy\":\n if len(args) >= 2:\n args[0], args[1] = args[1], args[0]\n elif indexing != \"ij\":\n raise ValueError(\"Valid values for indexing are 'xy' and 'ij', got {}\"\n .format(indexing))\n\n shape = []\n for i, a in enumerate(args):\n args[i] = a = asarray(a)\n if len(a.shape) != 1:\n msg = \"Arguments to jax.numpy.meshgrid must be 1D, got shape {}\"\n raise ValueError(msg.format(a.shape))\n shape.append(1 if sparse else a.shape[0])\n\n output = []\n for i, a in enumerate(args):\n a = asarray(a)\n s = shape\n if sparse:\n s = list(s)\n s[i] = a.shape[0]\n output.append(lax.broadcast_in_dim(a, s, (i,)))\n\n if indexing == \"xy\" and len(args) >= 2:\n output[0], output[1] = output[1], output[0]\n\n return output\n\n\n@_wraps(np.i0)\ndef i0(x):\n x = lax.abs(*_promote_args_inexact(\"i0\", x))\n return lax.mul(lax.exp(x), lax.bessel_i0e(x))\n\n\n@_wraps(np.ix_)\ndef ix_(*args):\n n = len(args)\n output = []\n for i, a in enumerate(args):\n a = asarray(a)\n if len(a.shape) != 1:\n msg = \"Arguments to jax.numpy.ix_ must be 1-dimensional, got shape {}\"\n raise ValueError(msg.format(a.shape))\n if _dtype(a) == bool_:\n raise NotImplementedError(\n \"Boolean arguments to jax.numpy.ix_ are not implemented\")\n shape = [1] * n\n shape[i] = a.shape[0]\n if a.size == 0:\n # Numpy uses an integer index type for empty arrays.\n output.append(lax.full(shape, np.zeros((), np.intp)))\n else:\n output.append(lax.broadcast_in_dim(a, shape, (i,)))\n return tuple(output)\n\n\n@_wraps(np.indices)\ndef indices(dimensions, dtype=int32, sparse=False):\n dimensions = tuple(dimensions)\n N = len(dimensions)\n output = []\n s = dimensions\n for i, dim in enumerate(dimensions):\n idx = lax.iota(dtype, dim)\n if sparse:\n s = (1,)*i + (dim,) + (1,)*(N - i - 1)\n output.append(lax.broadcast_in_dim(idx, s, (i,)))\n if sparse:\n return tuple(output)\n return stack(output, 0) if output else array([], dtype=dtype)\n\n\n_TOTAL_REPEAT_LENGTH_DOC = \"\"\"\\\nJax adds the optional `total_repeat_length` parameter which specifies the total\nnumber of repeat, and defaults to sum(repeats). It must be specified for repeat\nto be compilable. If `sum(repeats)` is larger than the specified\n`total_repeat_length` the remaining values will be discarded. In the case of\n`sum(repeats)` being smaller than the specified target length, the final value\nwill be repeated.\n\"\"\"\n\n\n@_wraps(np.repeat, lax_description=_TOTAL_REPEAT_LENGTH_DOC)\ndef repeat(a, repeats, axis=None, *, total_repeat_length=None):\n if axis is None:\n a = ravel(a)\n axis = 0\n\n # If total_repeat_length is not given, can't compile, use a default.\n if total_repeat_length is None:\n repeats = core.concrete_or_error(np.array, repeats, \"jax.numpy.repeat\")\n repeats = np.ravel(repeats)\n if ndim(a) != 0:\n repeats = np.broadcast_to(repeats, [a.shape[axis]])\n total_repeat_length = np.sum(repeats)\n else:\n repeats = ravel(repeats)\n if ndim(a) != 0:\n repeats = broadcast_to(repeats, [a.shape[axis]])\n\n # Special case when a is a scalar.\n if ndim(a) == 0:\n if repeats.shape == (1,):\n return full([total_repeat_length], a)\n else:\n raise ValueError('`repeat` with a scalar parameter `a` is only '\n 'implemented for scalar values of the parameter `repeats`.')\n\n # Special case if total_repeat_length is zero.\n if total_repeat_length == 0:\n result_shape = list(a.shape)\n result_shape[axis] = 0\n return reshape(array([], dtype=a.dtype), result_shape)\n\n # If repeats is on a zero sized axis, then return the array.\n if a.shape[axis] == 0:\n return a\n\n # This implementation of repeat avoid having to instantiate a large.\n # intermediate tensor.\n\n # Modify repeats from e.g. [1,2,0,5] -> [0,1,2,0] for exclusive repeat.\n exclusive_repeats = roll(repeats, shift=1).at[0].set(0)\n # Cumsum to get indices of new number in repeated tensor, e.g. [0, 1, 3, 3]\n scatter_indices = cumsum(exclusive_repeats)\n # Scatter these onto a zero buffer, e.g. [1,1,0,2,0,0,0,0]\n block_split_indicators = ops.index_add(\n x=zeros([total_repeat_length], dtype=int32),\n idx=scatter_indices,\n y=1)\n # Cumsum again to get scatter indices for repeat, e.g. [0,1,1,3,3,3,3,3]\n gather_indices = cumsum(block_split_indicators) - 1\n return take(a, gather_indices, axis=axis)\n\n\n@_wraps(np.tri)\ndef tri(N, M=None, k=0, dtype=None):\n lax._check_user_dtype_supported(dtype, \"tri\")\n M = M if M is not None else N\n dtype = dtype or float32\n return lax._tri(dtype, (N, M), k)\n\n\n@_wraps(np.tril)\ndef tril(m, k=0):\n m_shape = shape(m)\n if len(m_shape) < 2:\n raise ValueError(\"Argument to jax.numpy.tril must be at least 2D\")\n mask = tri(*m_shape[-2:], k=k, dtype=bool)\n return lax.select(lax.broadcast(mask, m_shape[:-2]), m, zeros_like(m))\n\n\n@_wraps(np.triu, update_doc=False)\ndef triu(m, k=0):\n m_shape = shape(m)\n if len(m_shape) < 2:\n raise ValueError(\"Argument to jax.numpy.triu must be at least 2D\")\n mask = tri(*m_shape[-2:], k=k - 1, dtype=bool)\n return lax.select(lax.broadcast(mask, m_shape[:-2]), zeros_like(m), m)\n\n\n@_wraps(np.trace)\ndef trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):\n if out:\n raise NotImplementedError(\"The 'out' argument to trace is not supported.\")\n lax._check_user_dtype_supported(dtype, \"trace\")\n\n axis1 = _canonicalize_axis(axis1, ndim(a))\n axis2 = _canonicalize_axis(axis2, ndim(a))\n\n a_shape = shape(a)\n if dtype is None:\n dtype = _dtype(a)\n if issubdtype(dtype, integer):\n default_int = dtypes.canonicalize_dtype(np.int_)\n if iinfo(dtype).bits < iinfo(default_int).bits:\n dtype = default_int\n\n # Move the axis? dimensions to the end.\n perm = [i for i in range(len(a_shape)) if i != axis1 and i != axis2]\n perm = perm + [axis1, axis2]\n a = lax.transpose(a, perm)\n\n # Mask out the diagonal and reduce.\n a = where(eye(a_shape[axis1], a_shape[axis2], k=offset, dtype=bool),\n a, zeros_like(a))\n return sum(a, axis=(-2, -1), dtype=dtype)\n\n\ndef _wrap_indices_function(f):\n @_wraps(f, update_doc=False)\n def wrapper(*args, **kwargs):\n return tuple(asarray(x) for x in f(*args, **kwargs))\n return wrapper\n\ntril_indices = _wrap_indices_function(np.tril_indices)\ntriu_indices = _wrap_indices_function(np.triu_indices)\nmask_indices = _wrap_indices_function(np.mask_indices)\n\n\n@_wraps(np.triu_indices_from)\ndef triu_indices_from(arr, k=0):\n return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1])\n\n\n@_wraps(np.tril_indices_from)\ndef tril_indices_from(arr, k=0):\n return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1])\n\n\n@_wraps(np.diag_indices)\ndef diag_indices(n, ndim=2):\n if n < 0:\n raise ValueError(\"n argument to diag_indices must be nonnegative, got {}\"\n .format(n))\n if ndim < 0:\n raise ValueError(\"ndim argument to diag_indices must be nonnegative, got {}\"\n .format(ndim))\n return (lax.iota(int_, n),) * ndim\n\n@_wraps(np.diag_indices_from)\ndef diag_indices_from(arr):\n if not arr.ndim >= 2:\n raise ValueError(\"input array must be at least 2-d\")\n\n if len(set(arr.shape)) != 1:\n raise ValueError(\"All dimensions of input must be of equal length\")\n\n return diag_indices(arr.shape[0], ndim=arr.ndim)\n\n@_wraps(np.diagonal)\ndef diagonal(a, offset=0, axis1=0, axis2=1):\n a_shape = shape(a)\n a_ndims = len(a_shape)\n\n # Move the two dimensions to the end.\n axis1 = _canonicalize_axis(axis1, a_ndims)\n axis2 = _canonicalize_axis(axis2, a_ndims)\n perm = [i for i in range(a_ndims) if i != axis1 and i != axis2]\n perm = perm + [axis1, axis2]\n a = lax.transpose(a, perm)\n\n # Mask out the diagonal and reduce over one of the axes\n a = where(eye(a_shape[axis1], a_shape[axis2], k=offset, dtype=bool),\n a, zeros_like(a))\n reduce_axis = -2 if offset < 0 else -1\n d = sum(a, axis=reduce_axis, dtype=_dtype(a))\n\n # Slice out the correct diagonal size.\n diag_size = _max(0, _min(a_shape[axis1] + _min(offset, 0),\n a_shape[axis2] - _max(offset, 0)))\n return lax.slice_in_dim(d, 0, diag_size, axis=-1)\n\n\n@_wraps(np.diag)\ndef diag(v, k=0):\n v_shape = shape(v)\n if len(v_shape) == 1:\n zero = lambda x: lax.full_like(x, shape=(), fill_value=0)\n n = v_shape[0] + _abs(k)\n v = lax.pad(v, zero(v), ((_max(0, k), _max(0, -k), 0),))\n return where(eye(n, k=k, dtype=bool), v, zeros_like(v))\n elif len(v_shape) == 2:\n return diagonal(v, offset=k)\n else:\n raise ValueError(\"diag input must be 1d or 2d\")\n\n_SCALAR_VALUE_DOC=\"\"\"\\\nThis differs from np.diagflat for some scalar values of v,\njax always returns a two-dimensional array, whereas numpy may\nreturn a scalar depending on the type of v.\n\"\"\"\n\n@_wraps(np.diagflat, lax_description=_SCALAR_VALUE_DOC)\ndef diagflat(v, k=0):\n v = ravel(v)\n v_length = len(v)\n adj_length = v_length + _abs(k)\n res = zeros(adj_length*adj_length, dtype=v.dtype)\n i = arange(0, adj_length-_abs(k))\n if (k >= 0):\n fi = i+k+i*adj_length\n else:\n fi = i+(i-k)*adj_length\n res = ops.index_update(res, ops.index[fi], v)\n res = res.reshape(adj_length,adj_length)\n return res\n\n\n@_wraps(np.polyval)\ndef polyval(p, x):\n if isinstance(p, np.poly1d):\n p = np.asarray(p)\n if isinstance(x, np.poly1d):\n y = 0\n else:\n y = zeros_like(x)\n for i in range(len(p)):\n y = y * x + p[i]\n return y\n\n@_wraps(np.polyadd)\ndef polyadd(a1, a2):\n a1 = asarray(a1)\n a2 = asarray(a2)\n\n if a2.shape[0] <= a1.shape[0]:\n return a1.at[-a2.shape[0]:].add(a2)\n else:\n return a2.at[-a1.shape[0]:].add(a1)\n\n\n@_wraps(np.polyder)\ndef polyder(p, m=1):\n p = asarray(p)\n if m < 0:\n raise ValueError(\"Order of derivative must be positive\")\n if m == 0:\n return p\n if m % 1:\n raise ValueError(\"m must be an integer\")\n coeff = (arange(len(p), m, -1) - 1 - arange(m)[:, newaxis]).prod(0)\n return p[:-m] * coeff\n\ndef _trim_zeros(a):\n for i, v in enumerate(a):\n if v != 0:\n return a[i:]\n return a[:0]\n\n_LEADING_ZEROS_DOC=\"\"\"\\\nSetting trim_leading_zeros=True makes the output match that of numpy.\nBut prevents the function from being able to be used in compiled code.\n\"\"\"\n\n@_wraps(np.polymul, lax_description=_LEADING_ZEROS_DOC)\ndef polymul(a1, a2, *, trim_leading_zeros=False):\n if isinstance(a1, np.poly1d):\n a1 = asarray(a1)\n if isinstance(a2, np.poly1d):\n a2 = asarray(a2)\n if trim_leading_zeros and (len(a1) > 1 or len(a2) > 1):\n a1, a2 = _trim_zeros(a1), _trim_zeros(a2)\n if len(a1) == 0:\n a1 = asarray([0.])\n if len(a2) == 0:\n a2 = asarray([0.])\n val = convolve(a1, a2, mode='full')\n return val\n\n@_wraps(np.polysub)\ndef polysub(a1, a2):\n return polyadd(asarray(a1), -asarray(a2))\n\n\n@_wraps(np.append)\ndef append(arr, values, axis=None):\n if axis is None:\n return concatenate([ravel(arr), ravel(values)], 0)\n else:\n return concatenate([arr, values], axis=axis)\n\n\n### Tensor contraction operations\n\n\n@_wraps(np.dot, lax_description=_PRECISION_DOC)\ndef dot(a, b, *, precision=None): # pylint: disable=missing-docstring\n _check_arraylike(\"dot\", a, b)\n a, b = _promote_dtypes(a, b)\n a_ndim, b_ndim = ndim(a), ndim(b)\n if a_ndim == 0 or b_ndim == 0:\n return lax.mul(a, b)\n if _max(a_ndim, b_ndim) <= 2:\n return lax.dot(a, b, precision=precision)\n\n if b_ndim == 1:\n contract_dims = ((a_ndim - 1,), (0,))\n else:\n contract_dims = ((a_ndim - 1,), (b_ndim - 2,))\n batch_dims = ((), ())\n return lax.dot_general(a, b, (contract_dims, batch_dims), precision)\n\n\n@_wraps(np.matmul, lax_description=_PRECISION_DOC)\ndef matmul(a, b, *, precision=None): # pylint: disable=missing-docstring\n _check_arraylike(\"matmul\", a, b)\n for i, x in enumerate((a, b)):\n if ndim(x) < 1:\n msg = (f\"matmul input operand {i} must have ndim at least 1, \"\n f\"but it has ndim {ndim(x)}\")\n raise ValueError(msg)\n\n a, b = _promote_dtypes(a, b)\n\n a_is_mat, b_is_mat = (ndim(a) > 1), (ndim(b) > 1)\n a_batch_dims = shape(a)[:-2] if a_is_mat else ()\n b_batch_dims = shape(b)[:-2] if b_is_mat else ()\n num_batch_dims = _max(len(a_batch_dims), len(b_batch_dims))\n a_batch_dims = (None,) * (num_batch_dims - len(a_batch_dims)) + a_batch_dims\n b_batch_dims = (None,) * (num_batch_dims - len(b_batch_dims)) + b_batch_dims\n\n # Dimensions to squeeze from the inputs.\n a_squeeze = []\n b_squeeze = []\n\n # Positions of batch dimensions in squeezed inputs.\n a_batch = []\n b_batch = []\n\n # Desired index in final output of each kind of dimension, in the order that\n # lax.dot_general will emit them.\n idx_batch = []\n idx_a_other = [] # other = non-batch, non-contracting.\n idx_b_other = []\n for i, (ba, bb) in enumerate(zip(a_batch_dims, b_batch_dims)):\n if ba is None:\n idx_b_other.append(i)\n elif bb is None:\n idx_a_other.append(i)\n elif ba == 1:\n idx_b_other.append(i)\n a_squeeze.append(len(idx_batch) + len(idx_a_other) + len(a_squeeze))\n elif bb == 1:\n idx_a_other.append(i)\n b_squeeze.append(len(idx_batch) + len(idx_b_other) + len(b_squeeze))\n elif ba == bb:\n a_batch.append(len(idx_batch) + len(idx_a_other))\n b_batch.append(len(idx_batch) + len(idx_b_other))\n idx_batch.append(i)\n else:\n raise ValueError(\"Incompatible shapes for matmul arguments: {} and {}\"\n .format(shape(a), shape(b)))\n\n if a_is_mat: idx_a_other.append(num_batch_dims)\n if b_is_mat: idx_b_other.append(num_batch_dims + a_is_mat)\n perm = np.argsort(np.concatenate([idx_batch, idx_a_other, idx_b_other]))\n\n a = lax.squeeze(a, tuple(a_squeeze))\n b = lax.squeeze(b, tuple(b_squeeze))\n out = lax.dot_general(\n a, b, (((ndim(a) - 1,), (ndim(b) - 1 - b_is_mat,)), (a_batch, b_batch)),\n precision=precision)\n return lax.transpose(out, perm)\n\n\n@_wraps(np.vdot, lax_description=_PRECISION_DOC)\ndef vdot(a, b, *, precision=None):\n if issubdtype(_dtype(a), complexfloating):\n a = conj(a)\n return dot(a.ravel(), b.ravel(), precision=precision)\n\n\n@_wraps(np.tensordot, lax_description=_PRECISION_DOC)\ndef tensordot(a, b, axes=2, *, precision=None):\n _check_arraylike(\"tensordot\", a, b)\n a_ndim = ndim(a)\n b_ndim = ndim(b)\n\n a, b = _promote_dtypes(a, b)\n if type(axes) is int:\n if axes > _min(a_ndim, b_ndim):\n msg = \"Number of tensordot axes (axes {}) exceeds input ranks ({} and {})\"\n raise TypeError(msg.format(axes, a.shape, b.shape))\n contracting_dims = tuple(range(a_ndim - axes, a_ndim)), tuple(range(axes))\n elif type(axes) in (list, tuple) and len(axes) == 2:\n ax1, ax2 = axes\n if type(ax1) == type(ax2) == int:\n contracting_dims = ((_canonicalize_axis(ax1, a_ndim),),\n (_canonicalize_axis(ax2, b_ndim),))\n elif type(ax1) in (list, tuple) and type(ax2) in (list, tuple):\n if len(ax1) != len(ax2):\n msg = \"tensordot requires axes lists to have equal length, got {} and {}.\"\n raise TypeError(msg.format(ax1, ax2))\n contracting_dims = (tuple(_canonicalize_axis(i, a_ndim) for i in ax1),\n tuple(_canonicalize_axis(i, b_ndim) for i in ax2))\n else:\n msg = \"tensordot requires both axes lists to be either ints, tuples or lists, got {} and {}\"\n raise TypeError(msg.format(ax1, ax2))\n else:\n msg = (\"tensordot axes argument must be an int, a pair of ints, or a pair \"\n \"of lists/tuples of ints.\")\n raise TypeError(msg)\n return lax.dot_general(a, b, (contracting_dims, ((), ())),\n precision=precision)\n\n\n@_wraps(np.einsum, lax_description=_PRECISION_DOC)\ndef einsum(*operands, optimize='greedy', precision=None):\n optimize = 'greedy' if optimize is True else optimize\n # using einsum_call=True here is an internal api for opt_einsum\n operands, contractions = opt_einsum.contract_path(\n *operands, einsum_call=True, use_blas=True, optimize=optimize)\n contractions = tuple(data[:3] for data in contractions)\n return _einsum(operands, contractions, precision)\n\n@_wraps(np.einsum_path)\ndef einsum_path(subscripts, *operands, optimize='greedy'):\n # using einsum_call=True here is an internal api for opt_einsum\n return opt_einsum.contract_path(subscripts, *operands, optimize=optimize)\n\ndef _removechars(s, chars):\n return s.translate(str.maketrans(dict.fromkeys(chars)))\n\n@partial(jit, static_argnums=(1, 2))\ndef _einsum(operands: Sequence,\n contractions: Sequence[Tuple[Tuple[int, ...], Set[str], str]],\n precision):\n operands = list(_promote_dtypes(*operands))\n def sum(x, axes):\n return lax.reduce(x, np.array(0, x.dtype),\n lax.add if x.dtype != bool_ else lax.bitwise_or, axes)\n\n def sum_uniques(operand, names, uniques):\n if uniques:\n axes = [names.index(name) for name in uniques]\n operand = sum(operand, axes)\n names = _removechars(names, uniques)\n return operand, names\n\n def sum_repeats(operand, names, counts, keep_names):\n for name, count in counts.items():\n if count > 1:\n axes = [i for i, n in enumerate(names) if n == name]\n eye = lax._delta(operand.dtype, operand.shape, axes)\n if name not in keep_names:\n operand = sum(operand * eye, axes)\n names = names.replace(name, '')\n else:\n operand = sum(operand * eye, axes[:-1])\n names = names.replace(name, '', count - 1)\n return operand, names\n\n def filter_singleton_dims(operand, names, other_shape, other_names):\n s = shape(operand)\n new_shape = []\n new_names = []\n for i, d in enumerate(names):\n other_i = other_names.find(d)\n if s[i] != 1 or other_i == -1 or other_shape[other_i] == 1:\n new_shape.append(s[i])\n new_names.append(d)\n return reshape(operand, tuple(new_shape)), \"\".join(new_names)\n\n for operand_indices, contracted_names_set, einstr in contractions:\n contracted_names = sorted(contracted_names_set)\n input_str, result_names = einstr.split('->')\n input_names = input_str.split(',')\n\n # switch on the number of operands to be processed in this loop iteration.\n # every case here sets 'operand' and 'names'.\n if len(operand_indices) == 1:\n operand = operands.pop(operand_indices[0])\n names, = input_names\n counts = collections.Counter(names)\n\n # sum out unique contracted indices with a single reduce-sum\n uniques = [name for name in contracted_names if counts[name] == 1]\n operand, names = sum_uniques(operand, names, uniques)\n\n # for every repeated index, do a contraction against an identity matrix\n operand, names = sum_repeats(operand, names, counts, result_names)\n\n elif len(operand_indices) == 2:\n lhs, rhs = map(operands.pop, operand_indices)\n lhs_names, rhs_names = input_names\n\n # handle cases where one side of a contracting or batch dimension is 1\n # but its counterpart is not.\n lhs, lhs_names = filter_singleton_dims(lhs, lhs_names, shape(rhs),\n rhs_names)\n rhs, rhs_names = filter_singleton_dims(rhs, rhs_names, shape(lhs),\n lhs_names)\n\n lhs_counts = collections.Counter(lhs_names)\n rhs_counts = collections.Counter(rhs_names)\n\n # sum out unique contracted indices in lhs and rhs\n lhs_uniques = [name for name in contracted_names\n if lhs_counts[name] == 1 and rhs_counts[name] == 0]\n lhs, lhs_names = sum_uniques(lhs, lhs_names, lhs_uniques)\n\n rhs_uniques = [name for name in contracted_names\n if rhs_counts[name] == 1 and lhs_counts[name] == 0]\n rhs, rhs_names = sum_uniques(rhs, rhs_names, rhs_uniques)\n\n # for every repeated index, contract against an identity matrix\n lhs, lhs_names = sum_repeats(lhs, lhs_names, lhs_counts,\n result_names + rhs_names)\n rhs, rhs_names = sum_repeats(rhs, rhs_names, rhs_counts,\n result_names + lhs_names)\n\n lhs_or_rhs_names = set(lhs_names) | set(rhs_names)\n contracted_names = [x for x in contracted_names if x in lhs_or_rhs_names]\n lhs_and_rhs_names = set(lhs_names) & set(rhs_names)\n batch_names = [x for x in result_names if x in lhs_and_rhs_names]\n\n lhs_batch, rhs_batch = unzip2((lhs_names.find(n), rhs_names.find(n))\n for n in batch_names)\n\n # NOTE(mattjj): this can fail non-deterministically in python3, maybe\n # due to opt_einsum\n assert _all(\n name in lhs_names and name in rhs_names and\n lhs.shape[lhs_names.index(name)] == rhs.shape[rhs_names.index(name)]\n for name in contracted_names)\n\n # contract using lax.dot_general\n batch_names_str = ''.join(batch_names)\n lhs_cont, rhs_cont = unzip2((lhs_names.index(n), rhs_names.index(n))\n for n in contracted_names)\n dimension_numbers = ((lhs_cont, rhs_cont), (lhs_batch, rhs_batch))\n operand = lax.dot_general(lhs, rhs, dimension_numbers, precision)\n deleted_names = batch_names_str + ''.join(contracted_names)\n names = (batch_names_str + _removechars(lhs_names, deleted_names)\n + _removechars(rhs_names, deleted_names))\n else:\n raise NotImplementedError # if this is actually reachable, open an issue!\n\n # the resulting 'operand' with axis labels 'names' should be a permutation\n # of the desired result\n assert len(names) == len(result_names) == len(set(names))\n assert set(names) == set(result_names)\n if names != result_names:\n perm = tuple([names.index(name) for name in result_names])\n operand = lax.transpose(operand, perm)\n operands.append(operand) # used in next iteration\n\n return operands[0]\n\n\ndef _movechars(s, src, dst):\n \"\"\"Helper for einsum string munging, like moveaxis on identifier strings.\"\"\"\n chars = [c for i, c in enumerate(s) if i not in src]\n for i, j in sorted(zip(dst, src)):\n chars.insert(i, s[j])\n return ''.join(chars)\n\n\n@_wraps(np.inner, lax_description=_PRECISION_DOC)\ndef inner(a, b, *, precision=None):\n if ndim(a) == 0 or ndim(b) == 0:\n return a * b\n return tensordot(a, b, (-1, -1), precision=precision)\n\n\n@_wraps(np.outer)\ndef outer(a, b, out=None):\n if out:\n raise NotImplementedError(\"The 'out' argument to outer is not supported.\")\n a, b = _promote_dtypes(a, b)\n return ravel(a)[:, None] * ravel(b)\n\n@partial(jit, static_argnums=(2, 3, 4))\ndef _cross(a, b, axisa, axisb, axisc):\n a = moveaxis(a, axisa, -1)\n b = moveaxis(b, axisb, -1)\n\n if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):\n raise ValueError(\"Dimension must be either 2 or 3 for cross product\")\n\n if a.shape[-1] == 2 and b.shape[-1] == 2:\n return a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0]\n\n a0 = a[..., 0]\n a1 = a[..., 1]\n a2 = a[..., 2] if a.shape[-1] == 3 else zeros_like(a0)\n b0 = b[..., 0]\n b1 = b[..., 1]\n b2 = b[..., 2] if b.shape[-1] == 3 else zeros_like(b0)\n c = array([a1 * b2 - a2 * b1, a2 * b0 - a0 * b2, a0 * b1 - a1 * b0])\n return moveaxis(c, 0, axisc)\n\n@_wraps(np.cross)\ndef cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):\n if axis is not None:\n axisa = axis\n axisb = axis\n axisc = axis\n return _cross(a, b, axisa, axisb, axisc)\n\n@_wraps(np.kron)\ndef kron(a, b):\n a, b = _promote_dtypes(a, b)\n if ndim(a) < ndim(b):\n a = reshape(a, (1,) * (ndim(b) - ndim(a)) + shape(a))\n elif ndim(b) < ndim(a):\n b = reshape(b, (1,) * (ndim(a) - ndim(b)) + shape(b))\n a_reshaped = reshape(a, [i for d in shape(a) for i in (d, 1)])\n b_reshaped = reshape(b, [i for d in shape(b) for i in (1, d)])\n out_shape = tuple(np.multiply(shape(a), shape(b)))\n return reshape(lax.mul(a_reshaped, b_reshaped), out_shape)\n\n\n@_wraps(np.vander)\ndef vander(x, N=None, increasing=False):\n x = asarray(x)\n dtype = _dtype(x)\n if ndim(x) != 1:\n raise ValueError(\"x must be a one-dimensional array\")\n x_shape = shape(x)\n N = N or x_shape[0]\n if N < 0:\n raise ValueError(\"N must be nonnegative\")\n\n iota = lax.iota(dtype, N)\n if not increasing:\n iota = lax.sub(lax._const(iota, N - 1), iota)\n\n return power(x[..., None], iota)\n\n\n### Misc\n\n\n@_wraps(np.argwhere)\ndef argwhere(a):\n result = transpose(vstack(nonzero(a)))\n if ndim(a) == 0:\n return result[:0].reshape(result.shape[0], 0)\n return result.reshape(result.shape[0], ndim(a))\n\n\n@_wraps(np.argmax)\ndef argmax(a, axis=None):\n if axis is None:\n a = ravel(a)\n axis = 0\n if a.shape[axis] == 0:\n raise ValueError(\"attempt to get argmax of an empty sequence\")\n return lax.argmax(a, _canonicalize_axis(axis, a.ndim), int64)\n\n@_wraps(np.argmin)\ndef argmin(a, axis=None):\n if axis is None:\n a = ravel(a)\n axis = 0\n if a.shape[axis] == 0:\n raise ValueError(\"attempt to get argmin of an empty sequence\")\n return lax.argmin(a, _canonicalize_axis(axis, a.ndim), int64)\n\n\n_NANARG_DOC = \"\"\"\\\nWarning: jax.numpy.arg{} returns -1 for all-NaN slices and does not raise\nan error.\n\"\"\"\n\n@_wraps(np.nanargmax, lax_description=_NANARG_DOC.format(\"max\"))\ndef nanargmax(a, axis=None):\n if not issubdtype(_dtype(a), inexact):\n return argmax(a, axis=axis)\n nan_mask = isnan(a)\n a = where(nan_mask, -inf, a)\n res = argmax(a, axis=axis)\n return where(all(nan_mask, axis=axis), -1, res)\n\n@_wraps(np.nanargmin, lax_description=_NANARG_DOC.format(\"min\"))\ndef nanargmin(a, axis=None):\n if not issubdtype(_dtype(a), inexact):\n return argmin(a, axis=axis)\n nan_mask = isnan(a)\n a = where(nan_mask, inf, a)\n res = argmin(a, axis=axis)\n return where(all(nan_mask, axis=axis), -1, res)\n\n\n@_wraps(np.sort)\ndef sort(a, axis=-1, kind='quicksort', order=None):\n if kind != 'quicksort':\n warnings.warn(\"'kind' argument to sort is ignored.\")\n if order is not None:\n raise ValueError(\"'order' argument to sort is not supported.\")\n\n if axis is None:\n return lax.sort(a.ravel(), dimension=0)\n else:\n return lax.sort(a, dimension=_canonicalize_axis(axis, ndim(a)))\n\n@_wraps(np.sort_complex)\ndef sort_complex(a):\n a = lax.sort(a, dimension=0)\n return lax.convert_element_type(a, result_type(a, dtypes.canonicalize_dtype(complex_)))\n\n@_wraps(np.lexsort)\ndef lexsort(keys, axis=-1):\n keys = tuple(keys)\n if len(keys) == 0:\n raise TypeError(\"need sequence of keys with len > 0 in lexsort\")\n if len(set(shape(key) for key in keys)) > 1:\n raise ValueError(\"all keys need to be the same shape\")\n if ndim(keys[0]) == 0:\n return np.int64(0)\n axis = _canonicalize_axis(axis, ndim(keys[0]))\n iota = lax.broadcasted_iota(np.int64, shape(keys[0]), axis)\n return lax.sort((*keys[::-1], iota), dimension=axis, num_keys=len(keys))[-1]\n\n\n@_wraps(np.argsort)\ndef argsort(a, axis=-1, kind='quicksort', order=None):\n if kind != 'quicksort':\n warnings.warn(\"'kind' argument to argsort is ignored.\")\n if order is not None:\n raise ValueError(\"'order' argument to argsort is not supported.\")\n\n if axis is None:\n return argsort(a.ravel(), 0)\n else:\n axis = _canonicalize_axis(axis, ndim(a))\n iota = lax.broadcasted_iota(np.int64, shape(a), axis)\n _, perm = lax.sort_key_val(a, iota, dimension=axis)\n return perm\n\n\n@_wraps(np.msort)\ndef msort(a):\n return sort(a, axis=0)\n\n\n@partial(jit, static_argnums=(2,))\ndef _roll(a, shift, axis):\n a = asarray(a)\n a_shape = shape(a)\n if axis is None:\n return lax.reshape(roll(ravel(a), shift, axis=0), a_shape)\n\n a_ndim = len(a_shape)\n shift = asarray(shift)\n axis = np.asarray(axis)\n b_shape = lax.broadcast_shapes(shift.shape, axis.shape, (1,))\n if len(b_shape) != 1:\n msg = \"'shift' and 'axis' arguments to roll must be scalars or 1D arrays\"\n raise ValueError(msg)\n\n for x, i in zip(broadcast_to(shift, b_shape),\n np.broadcast_to(axis, b_shape)):\n i = _canonicalize_axis(i, a_ndim)\n x = remainder(x, (a_shape[i] or 1))\n a = lax.concatenate((a, a), i)\n a = lax.dynamic_slice_in_dim(a, a_shape[i] - x, a_shape[i], axis=i)\n return a\n\n\n@_wraps(np.roll)\ndef roll(a, shift, axis=None):\n return _roll(a, shift, axis)\n\n\n@_wraps(np.rollaxis)\ndef rollaxis(a, axis, start=0):\n a_ndim = ndim(a)\n if not (-a_ndim <= axis < a_ndim):\n raise ValueError(f\"axis={axis} is out of bounds for array of dimension {a_ndim}\")\n if not (-a_ndim <= start <= a_ndim):\n raise ValueError(f\"start={start} must satisfy {-a_ndim}<=start<={a_ndim}\")\n if start < 0:\n start += a_ndim\n if axis < 0:\n axis += a_ndim\n if start > axis:\n start -= 1\n return moveaxis(a, axis, start)\n\n\n@_wraps(np.packbits)\ndef packbits(a, axis=None, bitorder='big'):\n a = asarray(a)\n if not (issubdtype(dtype(a), integer) or issubdtype(dtype(a), bool_)):\n raise TypeError('Expected an input array of integer or boolean data type')\n if bitorder not in ['little', 'big']:\n raise ValueError(\"'order' must be either 'little' or 'big'\")\n a = (a > 0).astype('uint8')\n bits = arange(8, dtype='uint8')\n if bitorder == 'big':\n bits = bits[::-1]\n if axis is None:\n a = ravel(a)\n axis = 0\n a = swapaxes(a, axis, -1)\n\n remainder = a.shape[-1] % 8\n if remainder:\n a = pad(a, (a.ndim - 1) * [(0, 0)] + [(0, 8 - remainder)])\n\n a = a.reshape(a.shape[:-1] + (a.shape[-1] // 8, 8))\n packed = (a << bits).sum(-1).astype('uint8')\n return swapaxes(packed, axis, -1)\n\n\n@_wraps(np.unpackbits)\ndef unpackbits(a, axis=None, count=None, bitorder='big'):\n a = asarray(a)\n if dtype(a) != uint8:\n raise TypeError(\"Expected an input array of unsigned byte data type\")\n if bitorder not in ['little', 'big']:\n raise ValueError(\"'order' must be either 'little' or 'big'\")\n bits = asarray(1) << arange(8, dtype='uint8')\n if bitorder == 'big':\n bits = bits[::-1]\n if axis is None:\n a = a.ravel()\n axis = 0\n a = swapaxes(a, axis, -1)\n unpacked = ((a[..., None] & bits) > 0).astype('uint8')\n unpacked = unpacked.reshape(unpacked.shape[:-2] + (-1,))[..., :count]\n return swapaxes(unpacked, axis, -1)\n\n\n@_wraps(np.take)\ndef take(a, indices, axis=None, out=None, mode=None):\n if out:\n raise NotImplementedError(\"The 'out' argument to np.take is not supported.\")\n\n a = asarray(a)\n indices = asarray(indices)\n\n if axis is None:\n a = ravel(a)\n axis = 0\n axis = _canonicalize_axis(axis, ndim(a))\n\n if mode == \"raise\":\n # TODO(phawkins): we have no way to report out of bounds errors yet.\n raise NotImplementedError(\"The 'raise' mode to np.take is not supported.\")\n elif mode == \"wrap\":\n indices = mod(indices, _constant_like(indices, a.shape[axis]))\n elif mode != \"clip\" and mode is not None:\n raise ValueError(\"Invalid mode '{}' for np.take\".format(mode))\n\n index_dims = len(shape(indices))\n slice_sizes = list(shape(a))\n slice_sizes[axis] = _min(indices.size, 1)\n dnums = lax.GatherDimensionNumbers(\n offset_dims=tuple(\n list(range(axis)) +\n list(range(axis + index_dims, len(a.shape) + index_dims - 1))),\n collapsed_slice_dims=(axis,),\n start_index_map=(axis,))\n return lax.gather(a, indices[..., None], dimension_numbers=dnums,\n slice_sizes=tuple(slice_sizes))\n\n\ndef _normalize_index(index, axis_size):\n \"\"\"Normalizes an index value in the range [-N, N) to the range [0, N).\"\"\"\n if type(axis_size) is Poly:\n return index + axis_size if index < 0 else index\n\n return lax.select(\n lax.lt(index, _constant_like(index, 0)),\n lax.add(index, _constant_like(index, axis_size)),\n index)\n\n@partial(jit, static_argnums=(2,))\ndef _take_along_axis(arr, indices, axis):\n if axis is None:\n if ndim(indices) != 1:\n msg = \"take_along_axis indices must be 1D if axis=None, got shape {}\"\n raise ValueError(msg.format(indices.shape))\n return take_along_axis(arr.ravel(), indices, 0)\n rank = ndim(arr)\n if rank != ndim(indices):\n msg = \"indices and arr must have the same number of dimensions; {} vs. {}\"\n raise ValueError(msg.format(ndim(indices), ndim(arr)))\n axis = _canonicalize_axis(axis, rank)\n\n def replace(tup, val):\n lst = list(tup)\n lst[axis] = val\n return tuple(lst)\n\n bcast_shape = lax.broadcast_shapes(replace(arr.shape, 1), replace(indices.shape, 1))\n indices = broadcast_to(indices, replace(bcast_shape, indices.shape[axis]))\n arr = broadcast_to(arr, replace(bcast_shape, arr.shape[axis]))\n\n axis_size = arr.shape[axis]\n arr_shape = replace(arr.shape, 1)\n idx_shape = indices.shape\n out_shape = lax.broadcast_shapes(idx_shape, arr_shape)\n\n index_dims = [i for i, idx in enumerate(idx_shape) if i == axis or idx != 1]\n\n gather_index_shape = tuple(np.array(out_shape)[index_dims]) + (1,)\n gather_indices = []\n slice_sizes = []\n offset_dims = []\n start_index_map = []\n collapsed_slice_dims = []\n j = 0\n for i in range(rank):\n if i == axis:\n indices = _normalize_index(indices, axis_size)\n gather_indices.append(lax.reshape(indices, gather_index_shape))\n slice_sizes.append(1)\n start_index_map.append(i)\n collapsed_slice_dims.append(i)\n j += 1\n elif idx_shape[i] != 1:\n iota = lax.iota(_dtype(indices), out_shape[i])\n if not config.omnistaging_enabled:\n iota = lax.tie_in(arr, iota)\n iota = lax.broadcast_in_dim(iota, gather_index_shape, (j,))\n gather_indices.append(iota)\n slice_sizes.append(1)\n start_index_map.append(i)\n collapsed_slice_dims.append(i)\n j += 1\n else:\n # If idx_shape[i] == 1, we can just take the entirety of the arr's axis\n # and avoid forming an iota index.\n offset_dims.append(i)\n slice_sizes.append(arr_shape[i])\n\n gather_indices = lax.concatenate(gather_indices, dimension=j)\n dnums = lax.GatherDimensionNumbers(\n offset_dims=tuple(offset_dims),\n collapsed_slice_dims=tuple(collapsed_slice_dims),\n start_index_map=tuple(start_index_map))\n return lax.gather(arr, gather_indices, dnums, tuple(slice_sizes))\n\n\n@_wraps(getattr(np, \"take_along_axis\", None), update_doc=False)\ndef take_along_axis(arr, indices, axis):\n return _take_along_axis(arr, indices, axis)\n\n\n### SetOps\n\n@partial(jit, static_argnums=1)\ndef _unique1d_sorted_mask(ar, optional_indices=False):\n \"\"\"\n Helper function for unique which is jit-able\n \"\"\"\n\n ar = asarray(ar).flatten()\n\n if optional_indices:\n perm = ar.argsort()\n aux = ar[perm]\n else:\n aux = ar.sort()\n\n mask = empty(aux.shape, dtype=bool_)\n mask = ops.index_update(mask, ops.index[:1], True)\n mask = ops.index_update(mask, ops.index[1:], aux[1:] != aux[:-1])\n\n if optional_indices:\n return aux, mask, perm\n else:\n return aux, mask\n\ndef _unique1d(ar, return_index=False, return_inverse=False,\n return_counts=False):\n \"\"\"\n Find the unique elements of an array, ignoring shape.\n \"\"\"\n\n optional_indices = return_index or return_inverse\n\n if optional_indices:\n aux, mask, perm = _unique1d_sorted_mask(ar, optional_indices)\n else:\n aux, mask = _unique1d_sorted_mask(ar, optional_indices)\n\n ret = (aux[mask],)\n if return_index:\n ret += (perm[mask],)\n if return_inverse:\n imask = cumsum(mask) - 1\n inv_idx = zeros(mask.shape, dtype=dtypes.canonicalize_dtype(int_))\n inv_idx = ops.index_update(inv_idx, perm, imask)\n ret += (inv_idx,)\n if return_counts:\n idx = concatenate(nonzero(mask) + (array([mask.size]),))\n ret += (diff(idx),)\n return ret\n\n@_wraps(np.unique)\ndef unique(ar, return_index=False, return_inverse=False,\n return_counts=False, axis=None):\n\n if iscomplexobj(ar):\n raise NotImplementedError(\n \"np.unique is not implemented for complex valued arrays\")\n\n if axis is None:\n ret = _unique1d(ar, return_index, return_inverse, return_counts)\n if len(ret) == 1:\n return ret[0]\n else:\n return ret\n\n raise NotImplementedError(\n \"np.unique is not implemented for the axis argument\")\n\n### Indexing\n\ndef _rewriting_take(arr, idx):\n # Computes arr[idx].\n # All supported cases of indexing can be implemented as an XLA gather,\n # followed by an optional reverse and broadcast_in_dim.\n arr = asarray(arr)\n treedef, static_idx, dynamic_idx = _split_index_for_jit(idx)\n return _gather(arr, treedef, static_idx, dynamic_idx)\n\n# TODO(phawkins): re-enable jit after fixing excessive recompilation for\n# slice indexes (e.g., slice(0, 5, None), slice(10, 15, None), etc.).\n# @partial(jit, static_argnums=(1, 2))\ndef _gather(arr, treedef, static_idx, dynamic_idx):\n idx = _merge_static_and_dynamic_indices(treedef, static_idx, dynamic_idx)\n indexer = _index_to_gather(shape(arr), idx) # shared with _scatter_update\n y = arr\n\n # Avoid calling gather if the slice shape is empty, both as a fast path and to\n # handle cases like zeros(0)[array([], int32)].\n if _prod(indexer.slice_shape) == 0:\n return zeros(indexer.slice_shape, dtype=y.dtype)\n\n # We avoid generating a gather when indexer.gather_indices.size is empty.\n if indexer.gather_indices.size:\n y = lax.gather(y, indexer.gather_indices, indexer.dnums,\n indexer.gather_slice_shape)\n\n # Reverses axes with negative strides.\n if indexer.reversed_y_dims:\n y = lax.rev(y, indexer.reversed_y_dims)\n\n # This adds np.newaxis/None dimensions.\n return expand_dims(y, indexer.newaxis_dims)\n\n_Indexer = collections.namedtuple(\"_Indexer\", [\n # The expected shape of the slice output.\n \"slice_shape\",\n\n # The slice shape to pass to lax.gather().\n \"gather_slice_shape\",\n\n # The gather indices to use.\n \"gather_indices\",\n\n # A GatherDimensionNumbers object describing the gather to perform.\n \"dnums\",\n\n # Slice dimensions that have negative strides, and so must be reversed after\n # the gather.\n \"reversed_y_dims\",\n\n # Keep track of any axes created by `newaxis`. These must be inserted for\n # gathers and eliminated for scatters.\n \"newaxis_dims\",\n])\n\ndef _split_index_for_jit(idx):\n \"\"\"Splits indices into necessarily-static and dynamic parts.\n\n Used to pass indices into `jit`-ted function.\n \"\"\"\n # Convert list indices to tuples in cases (deprecated by NumPy.)\n idx = _eliminate_deprecated_list_indexing(idx)\n\n # Expand any (concrete) boolean indices. We can then use advanced integer\n # indexing logic to handle them.\n idx = _expand_bool_indices(idx)\n\n leaves, treedef = tree_flatten(idx)\n dynamic = [None] * len(leaves)\n static = [None] * len(leaves)\n for i, x in enumerate(leaves):\n if x is Ellipsis:\n static[i] = x\n elif isinstance(x, slice):\n # slice objects aren't hashable.\n static[i] = (x.start, x.stop, x.step)\n else:\n dynamic[i] = x\n return treedef, tuple(static), dynamic\n\ndef _merge_static_and_dynamic_indices(treedef, static_idx, dynamic_idx):\n \"\"\"Recombines indices that were split by _split_index_for_jit.\"\"\"\n idx = []\n for s, d in zip(static_idx, dynamic_idx):\n if d is not None:\n idx.append(d)\n elif isinstance(s, tuple):\n idx.append(slice(s[0], s[1], s[2]))\n else:\n idx.append(s)\n return treedef.unflatten(idx)\n\ndef _int(aval):\n return not aval.shape and issubdtype(aval.dtype, integer)\n\ndef _index_to_gather(x_shape, idx):\n # Remove ellipses and add trailing slice(None)s.\n idx = _canonicalize_tuple_index(len(x_shape), idx)\n\n # Check for advanced indexing:\n # https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing\n\n # Do the advanced indexing axes appear contiguously? If not, NumPy semantics\n # move the advanced axes to the front.\n advanced_axes_are_contiguous = False\n\n advanced_indexes = None\n\n # The positions of the advanced indexing axes in `idx`.\n idx_advanced_axes = []\n\n # The positions of the advanced indexes in x's shape.\n # collapsed, after None axes have been removed. See below.\n x_advanced_axes = None\n\n if _is_advanced_int_indexer(idx):\n idx_no_nones = [(i, d) for i, d in enumerate(idx) if d is not None]\n advanced_pairs = (\n (asarray(e), i, j) for j, (i, e) in enumerate(idx_no_nones)\n if (isinstance(e, Sequence) or isinstance(e, ndarray)))\n advanced_pairs = ((_normalize_index(e, x_shape[j]), i, j)\n for e, i, j in advanced_pairs)\n advanced_indexes, idx_advanced_axes, x_advanced_axes = zip(*advanced_pairs)\n advanced_axes_are_contiguous = np.all(np.diff(idx_advanced_axes) == 1)\n\n x_axis = 0 # Current axis in x.\n y_axis = 0 # Current axis in y, before collapsing. See below.\n collapsed_y_axis = 0 # Current axis in y, after collapsing.\n\n # Scatter dimension numbers.\n offset_dims = []\n collapsed_slice_dims = []\n start_index_map = []\n\n use_64bit_index = _any([type(d) is Poly or d >= (1 << 31) for d in x_shape])\n index_dtype = int64 if use_64bit_index else int32\n gather_indices = np.zeros((0,), dtype=index_dtype) # use np to save a compilation\n\n # We perform three transformations to y before the scatter op, in order:\n # First, y is broadcast to slice_shape. In general `y` only need broadcast to\n # the right shape.\n slice_shape = []\n\n # Next, y is squeezed to remove newaxis_dims. This removes np.newaxis/`None`\n # indices, which the scatter cannot remove itself.\n newaxis_dims = []\n\n # Finally, we reverse reversed_y_dims to handle slices with negative strides.\n reversed_y_dims = []\n\n gather_slice_shape = []\n\n for idx_pos, i in enumerate(idx):\n # Handle the advanced indices here if:\n # * the advanced indices were not contiguous and we are the start.\n # * we are at the position of the first advanced index.\n if (advanced_indexes is not None and\n (advanced_axes_are_contiguous and idx_pos == idx_advanced_axes[0] or\n not advanced_axes_are_contiguous and idx_pos == 0)):\n advanced_indexes = broadcast_arrays(*advanced_indexes)\n shape = advanced_indexes[0].shape\n ndim = len(shape)\n advanced_indexes = [\n lax.convert_element_type(lax.reshape(a, shape + (1,)), index_dtype)\n for a in advanced_indexes]\n\n # Broadcast gather_indices from [..., k] to [..., 1, 1, ..., 1, k].\n gather_indices = lax.broadcast_in_dim(\n gather_indices, np.insert(gather_indices.shape, -1, shape),\n tuple(range(gather_indices.ndim - 1)) + (gather_indices.ndim + ndim - 1,))\n gather_indices = concatenate([gather_indices] + advanced_indexes, -1)\n start_index_map.extend(x_advanced_axes)\n collapsed_slice_dims.extend(x_advanced_axes)\n slice_shape.extend(shape)\n y_axis += ndim\n collapsed_y_axis += ndim\n\n # Per-index bookkeeping for advanced indexes.\n if idx_pos in idx_advanced_axes:\n x_axis += 1\n gather_slice_shape.append(1)\n continue\n\n try:\n abstract_i = core.get_aval(i)\n except TypeError:\n abstract_i = None\n # Handle basic int indexes.\n if (isinstance(abstract_i, ConcreteArray) or\n isinstance(abstract_i, ShapedArray)) and _int(abstract_i):\n if x_shape[x_axis] == 0:\n # XLA gives error when indexing into an axis of size 0\n raise IndexError(f\"index is out of bounds for axis {x_axis} with size 0\")\n i = _normalize_index(i, x_shape[x_axis])\n if type(i) is Poly:\n # dummy index if i is polynomial, doesn't matter for shape inference\n # TODO(mattjj,j-towns,juliuskunze): revise this logic\n i = 0\n i = lax.convert_element_type(i, index_dtype)\n i = broadcast_to(i, tuple(gather_indices.shape[:-1]) + (1,))\n gather_indices = concatenate((gather_indices, i), -1)\n collapsed_slice_dims.append(x_axis)\n gather_slice_shape.append(1)\n start_index_map.append(x_axis)\n x_axis += 1\n # Handle np.newaxis (None)\n elif i is None:\n slice_shape.append(1)\n newaxis_dims.append(y_axis)\n y_axis += 1\n # Handle slice(None)\n elif _is_slice_none(i):\n slice_shape.append(x_shape[x_axis])\n gather_slice_shape.append(x_shape[x_axis])\n offset_dims.append(collapsed_y_axis)\n collapsed_y_axis += 1\n y_axis += 1\n x_axis += 1\n # Handle slice index (only static, otherwise an error is raised)\n elif isinstance(i, slice):\n if not _all(elt is None or type(elt) is Poly\n or type(core.get_aval(elt)) is ConcreteArray\n for elt in (i.start, i.stop, i.step)):\n msg = (\"Array slice indices must have static start/stop/step to be used \"\n \"with NumPy indexing syntax. To index a statically sized \"\n \"array at a dynamic position, try lax.dynamic_slice/\"\n \"dynamic_update_slice (JAX does not support dynamically sized \"\n \"arrays within JIT compiled functions).\")\n raise IndexError(msg)\n start, limit, stride, needs_rev = _static_idx(i, x_shape[x_axis])\n if needs_rev:\n reversed_y_dims.append(collapsed_y_axis)\n if stride == 1:\n i = lax.convert_element_type(start, index_dtype)\n i = broadcast_to(i, tuple(gather_indices.shape[:-1]) + (1,))\n gather_indices = concatenate((gather_indices, i), -1)\n slice_shape.append(limit - start)\n gather_slice_shape.append(limit - start)\n offset_dims.append(collapsed_y_axis)\n start_index_map.append(x_axis)\n else:\n i = arange(start, limit, stride, dtype=index_dtype)\n size = i.shape[0]\n slice_shape.append(size)\n gather_slice_shape.append(1)\n gather_indices_shape = tuple(gather_indices.shape[:-1]) + (size,)\n i = lax.broadcast_in_dim(\n i, shape=gather_indices_shape + (1,),\n broadcast_dimensions=(len(gather_indices_shape) - 1,))\n gather_indices = lax.broadcast_in_dim(\n gather_indices,\n shape=gather_indices_shape + (len(start_index_map),),\n broadcast_dimensions=(\n tuple(range(len(gather_indices_shape) - 1)) +\n (len(gather_indices_shape),)))\n gather_indices = concatenate(\n (gather_indices, i), len(gather_indices_shape))\n start_index_map.append(x_axis)\n collapsed_slice_dims.append(x_axis)\n\n collapsed_y_axis += 1\n y_axis += 1\n x_axis += 1\n else:\n if (abstract_i is not None and\n not (issubdtype(abstract_i.dtype, integer) or issubdtype(abstract_i.dtype, bool_))):\n msg = (\"Indexer must have integer or boolean type, got indexer \"\n \"with type {} at position {}, indexer value {}\")\n raise TypeError(msg.format(abstract_i.dtype.name, idx_pos, i))\n\n msg = \"Indexing mode not yet supported. Open a feature request!\\n{}\"\n raise IndexError(msg.format(idx))\n\n dnums = lax.GatherDimensionNumbers(\n offset_dims = tuple(offset_dims),\n collapsed_slice_dims = tuple(sorted(collapsed_slice_dims)),\n start_index_map = tuple(start_index_map)\n )\n return _Indexer(\n slice_shape=slice_shape,\n newaxis_dims=tuple(newaxis_dims),\n gather_slice_shape=gather_slice_shape,\n reversed_y_dims=reversed_y_dims,\n dnums=dnums,\n gather_indices=gather_indices)\n\ndef _should_unpack_list_index(x):\n \"\"\"Helper for _eliminate_deprecated_list_indexing.\"\"\"\n return (isinstance(x, ndarray) and np.ndim(x) != 0\n or isinstance(x, Sequence)\n or isinstance(x, slice) or x is Ellipsis or x is None)\n\ndef _eliminate_deprecated_list_indexing(idx):\n # \"Basic slicing is initiated if the selection object is a non-array,\n # non-tuple sequence containing slice objects, [Ellipses, or newaxis\n # objects]\". Detects this case and canonicalizes to a tuple. This case is\n # deprecated by NumPy and exists for backward compatibility.\n if not isinstance(idx, tuple):\n if isinstance(idx, Sequence) and not isinstance(idx, ndarray):\n if _any(_should_unpack_list_index(i) for i in idx):\n idx = tuple(idx)\n else:\n idx = (idx,)\n else:\n idx = (idx,)\n return idx\n\ndef _expand_bool_indices(idx):\n \"\"\"Converts concrete bool indexes into advanced integer indexes.\"\"\"\n out = []\n for i in idx:\n try:\n abstract_i = core.get_aval(i)\n except TypeError:\n abstract_i = None\n if (isinstance(abstract_i, ShapedArray) and issubdtype(abstract_i.dtype, bool_)\n or isinstance(i, list) and _all(not _shape(e) and issubdtype(_dtype(e), bool_)\n for e in i)):\n if isinstance(i, list):\n i = array(i)\n abstract_i = core.get_aval(i)\n\n if not type(abstract_i) is ConcreteArray:\n # TODO(mattjj): improve this error by tracking _why_ the indices are not\n # concrete\n raise IndexError(\"Array boolean indices must be concrete.\")\n else:\n out.extend(np.where(i))\n else:\n out.append(i)\n return tuple(out)\n\ndef _is_slice_none(idx):\n \"\"\"Return True if idx is equal to slice(None), False otherwise.\"\"\"\n if isinstance(idx, slice):\n return idx.start is None and idx.stop is None and idx.step is None\n\n# TODO(mattjj): clean up this logic\ndef _is_advanced_int_indexer(idx):\n \"\"\"Returns True if idx should trigger int array indexing, False otherwise.\"\"\"\n # https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing\n assert isinstance(idx, tuple)\n if _all(np.ndim(elt) == 0 for elt in idx):\n return False\n return _all(e is None or e is Ellipsis or isinstance(e, slice)\n or _is_int_arraylike(e) for e in idx)\n\ndef _is_int_arraylike(x):\n \"\"\"Returns True if x is array-like with integer dtype, False otherwise.\"\"\"\n return (isinstance(x, int) and not isinstance(x, bool)\n or issubdtype(getattr(x, \"dtype\", None), np.integer)\n or isinstance(x, (list, tuple)) and _all(_is_int_arraylike(e) for e in x))\n\n\ndef _canonicalize_tuple_index(arr_ndim, idx):\n \"\"\"Helper to remove Ellipsis and add in the implicit trailing slice(None).\"\"\"\n len_without_none = _sum(1 for e in idx if e is not None and e is not Ellipsis)\n if len_without_none > arr_ndim:\n msg = \"Too many indices for array: {} non-None/Ellipsis indices for dim {}.\"\n raise IndexError(msg.format(len_without_none, arr_ndim))\n ellipses = (i for i, elt in enumerate(idx) if elt is Ellipsis)\n ellipsis_index = next(ellipses, None)\n if ellipsis_index is not None:\n if next(ellipses, None) is not None:\n msg = \"Multiple ellipses (...) not supported: {}.\"\n raise IndexError(msg.format(list(map(type, idx))))\n colons = (slice(None),) * (arr_ndim - len_without_none)\n idx = idx[:ellipsis_index] + colons + idx[ellipsis_index + 1:]\n elif len_without_none < arr_ndim:\n colons = (slice(None),) * (arr_ndim - len_without_none)\n idx = tuple(idx) + colons\n return idx\n\ndef _polymorphic_slice_indices(idx: slice, size: Union[int, Poly]):\n # like idx.indices(size), but allows for polymorphic indices and size\n # see https://github.com/python/cpython/blob/6d6508765514c7c10719478a0430f5e47c9a96ac/Objects/sliceobject.c#L372\n assert isinstance(idx, slice)\n\n step = 1 if idx.step is None else idx.step\n step_is_negative = step < 0\n lower = -1 if step_is_negative else 0\n upper = size + lower\n\n def sanitize(index, default):\n if index is None:\n return default\n elif type(index) is Poly:\n return index\n elif index < 0:\n return _max(index + size, lower)\n else:\n return _min(index, upper)\n\n start = sanitize(idx.start, default=upper if step_is_negative else lower)\n stop = sanitize(idx.stop, default=lower if step_is_negative else upper)\n return start, stop, step\n\ndef _static_idx(idx: slice, size: Union[int, Poly]):\n \"\"\"Helper function to compute the static slice start/limit/stride values.\"\"\"\n if _any(type(s) is Poly for s in (idx.start, idx.stop, idx.step, size)):\n start, stop, step = _polymorphic_slice_indices(idx, size)\n elif isinstance(size, int):\n start, stop, step = idx.indices(size)\n else:\n raise TypeError(size)\n\n if type(start) is not Poly and type(stop) is not Poly:\n if (step < 0 and stop >= start) or (step > 0 and start >= stop):\n return 0, 0, 1, False # sliced to size zero\n\n if step > 0:\n return start, stop, step, False\n else:\n k = (start - stop - 1) % (-step)\n return stop + k + 1, start + 1, -step, True\n\n\nblackman = _wrap_numpy_nullary_function(np.blackman)\nbartlett = _wrap_numpy_nullary_function(np.bartlett)\nhamming = _wrap_numpy_nullary_function(np.hamming)\nhanning = _wrap_numpy_nullary_function(np.hanning)\n# TODO: lower `kaiser` via lax to allow non-constant beta values.\nkaiser = _wrap_numpy_nullary_function(np.kaiser)\n\ndef _gcd_cond_fn(xs):\n x1, x2 = xs\n return any(x2 != 0)\n\ndef _gcd_body_fn(xs):\n x1, x2 = xs\n x1, x2 = (where(x2 != 0, x2, x1),\n where(x2 != 0, lax.rem(x1, x2), lax._const(x2, 0)))\n return (where(x1 < x2, x2, x1), where(x1 < x2, x1, x2))\n\n@_wraps(getattr(np, \"gcd\", None))\ndef gcd(x1, x2):\n if (not issubdtype(_dtype(x1), integer) or\n not issubdtype(_dtype(x2), integer)):\n raise ValueError(\"Arguments to jax.numpy.gcd must be integers.\")\n x1, x2 = _promote_dtypes(x1, x2)\n x1, x2 = broadcast_arrays(x1, x2)\n gcd, _ = lax.while_loop(_gcd_cond_fn, _gcd_body_fn, (abs(x1), abs(x2)))\n return gcd\n\n\n@_wraps(getattr(np, \"lcm\", None))\ndef lcm(x1, x2):\n x1, x2 = _promote_dtypes(x1, x2)\n d = gcd(x1, x2)\n return where(d == 0, lax._const(d, 0),\n abs(multiply(x1, floor_divide(x2, d))))\n\n\n@_wraps(np.extract)\ndef extract(condition, arr):\n return compress(ravel(condition), ravel(arr))\n\n\n@_wraps(np.compress)\ndef compress(condition, a, axis=None, out=None):\n if out is not None:\n raise NotImplementedError(\"out argument is not supported.\")\n if ndim(condition) != 1:\n raise ValueError(\"condition must be a 1D array\")\n condition = array(condition).astype(bool)\n a = array(a)\n if axis is None:\n axis = 0\n a = ravel(a)\n else:\n a = moveaxis(a, axis, 0)\n condition, extra = condition[:a.shape[0]], condition[a.shape[0]:]\n if any(extra):\n raise ValueError(\"condition contains entries that are out of bounds\")\n a = a[:condition.shape[0]]\n return moveaxis(a[condition], 0, axis)\n\n\n@_wraps(np.cov)\ndef cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,\n aweights=None):\n msg = (\"jax.numpy.cov not implemented for nontrivial {}. \"\n \"Open a feature request at https://github.com/google/jax/issues !\")\n if y is not None: raise NotImplementedError(msg.format('y'))\n # These next two are actually implemented, just not tested.\n if fweights is not None: raise NotImplementedError(msg.format('fweights'))\n if aweights is not None: raise NotImplementedError(msg.format('aweights'))\n\n if m.ndim > 2:\n raise ValueError(\"m has more than 2 dimensions\") # same as numpy error\n X = array(m, ndmin=2, dtype=dtypes.canonicalize_dtype(result_type(m, float_)))\n if not rowvar and X.shape[0] != 1:\n X = X.T\n if X.shape[0] == 0:\n return array([]).reshape(0, 0)\n if ddof is None:\n ddof = 1 if bias == 0 else 0\n\n w = None\n if fweights is not None:\n if np.ndim(fweights) > 1:\n raise RuntimeError(\"cannot handle multidimensional fweights\")\n if np.shape(fweights)[0] != X.shape[1]:\n raise RuntimeError(\"incompatible numbers of samples and fweights\")\n w = asarray(fweights)\n if aweights is not None:\n if np.ndim(aweights) > 1:\n raise RuntimeError(\"cannot handle multidimensional aweights\")\n if np.shape(aweights)[0] != X.shape[1]:\n raise RuntimeError(\"incompatible numbers of samples and aweights\")\n w = aweights if w is None else w * aweights\n\n avg, w_sum = average(X, axis=1, weights=w, returned=True)\n w_sum = w_sum[0]\n\n if w is None:\n f = X.shape[1] - ddof\n elif ddof == 0:\n f = w_sum\n elif aweights is None:\n f = w_sum - ddof\n else:\n f = w_sum - ddof * sum(w * aweights) / w_sum\n\n X = X - avg[:, None]\n X_T = X.T if w is None else (X * w).T\n return true_divide(dot(X, X_T.conj()), f).squeeze()\n\n\n@_wraps(np.corrcoef)\ndef corrcoef(x, y=None, rowvar=True):\n c = cov(x, y, rowvar)\n if len(shape(c)) == 0:\n # scalar - this should yield nan for values (nan/nan, inf/inf, 0/0), 1 otherwise\n return divide(c, c)\n d = diag(c)\n stddev = sqrt(real(d))\n c = divide(c, stddev[:,None])\n c = divide(c, stddev[None,:])\n\n real_part = clip(real(c), -1, 1)\n if iscomplexobj(c):\n complex_part = clip(imag(c), -1, 1)\n c = lax.complex(real_part, complex_part)\n else:\n c = real_part\n return c\n\n\n@_wraps(getattr(np, \"quantile\", None))\ndef quantile(a, q, axis=None, out=None, overwrite_input=False,\n interpolation=\"linear\", keepdims=False):\n if overwrite_input or out is not None:\n msg = (\"jax.numpy.quantile does not support overwrite_input=True or \"\n \"out != None\")\n raise ValueError(msg)\n return _quantile(a, q, axis, interpolation, keepdims, False)\n\n@_wraps(getattr(np, \"nanquantile\", None))\ndef nanquantile(a, q, axis=None, out=None, overwrite_input=False,\n interpolation=\"linear\", keepdims=False):\n if overwrite_input or out is not None:\n msg = (\"jax.numpy.nanquantile does not support overwrite_input=True or \"\n \"out != None\")\n raise ValueError(msg)\n return _quantile(a, q, axis, interpolation, keepdims, True)\n\n\n@partial(jit, static_argnums=(2, 3, 4, 5))\ndef _quantile(a, q, axis, interpolation, keepdims, squash_nans):\n if interpolation not in [\"linear\", \"lower\", \"higher\", \"midpoint\", \"nearest\"]:\n raise ValueError(\"interpolation can only be 'linear', 'lower', 'higher', \"\n \"'midpoint', or 'nearest'\")\n a = asarray(a, dtype=promote_types(_dtype(a), float32))\n q = asarray(q, dtype=promote_types(_dtype(q), float32))\n if axis is None:\n a = ravel(a)\n axis = 0\n elif isinstance(axis, tuple):\n raise NotImplementedError(\"Tuple values for axis are not implemented\")\n else:\n axis = _canonicalize_axis(axis, ndim(a))\n\n q_shape = shape(q)\n q_ndim = ndim(q)\n if q_ndim > 1:\n raise ValueError(\"q must be have rank <= 1, got shape {}\".format(shape(q)))\n\n a_shape = shape(a)\n a = lax.sort(a, dimension=axis)\n\n if squash_nans:\n counts = sum(logical_not(isnan(a)), axis=axis, dtype=q.dtype,\n keepdims=keepdims)\n shape_after_reduction = counts.shape\n q = lax.expand_dims(\n q, tuple(range(q_ndim, len(shape_after_reduction) + q_ndim)))\n counts = lax.expand_dims(counts, tuple(range(q_ndim)))\n q = lax.mul(q, lax.sub(counts, _constant_like(q, 1)))\n low = lax.floor(q)\n high = lax.ceil(q)\n high_weight = lax.sub(q, low)\n low_weight = lax.sub(_constant_like(high_weight, 1), high_weight)\n\n low = lax.max(_constant_like(low, 0), lax.min(low, counts - 1))\n high = lax.max(_constant_like(high, 0), lax.min(high, counts - 1))\n low = lax.convert_element_type(low, int64)\n high = lax.convert_element_type(high, int64)\n out_shape = q_shape + shape_after_reduction\n index = [lax.broadcasted_iota(int64, out_shape, dim + q_ndim)\n for dim in range(len(shape_after_reduction))]\n if keepdims:\n index[axis] = low\n else:\n index.insert(axis, low)\n low_value = a[tuple(index)]\n index[axis] = high\n high_value = a[tuple(index)]\n else:\n n = a_shape[axis]\n q = lax.mul(q, _constant_like(q, n - 1))\n low = lax.floor(q)\n high = lax.ceil(q)\n high_weight = lax.sub(q, low)\n low_weight = lax.sub(_constant_like(high_weight, 1), high_weight)\n\n low = lax.clamp(_constant_like(low, 0), low, _constant_like(low, n - 1))\n high = lax.clamp(_constant_like(high, 0), high, _constant_like(high, n - 1))\n low = lax.convert_element_type(low, int64)\n high = lax.convert_element_type(high, int64)\n\n slice_sizes = list(a_shape)\n slice_sizes[axis] = 1\n dnums = lax.GatherDimensionNumbers(\n offset_dims=tuple(range(\n q_ndim,\n len(a_shape) + q_ndim if keepdims else len(a_shape) + q_ndim - 1)),\n collapsed_slice_dims=() if keepdims else (axis,),\n start_index_map=(axis,))\n low_value = lax.gather(a, low[..., None], dimension_numbers=dnums,\n slice_sizes=slice_sizes)\n high_value = lax.gather(a, high[..., None], dimension_numbers=dnums,\n slice_sizes=slice_sizes)\n if q_ndim == 1:\n low_weight = lax.broadcast_in_dim(low_weight, low_value.shape,\n broadcast_dimensions=(0,))\n high_weight = lax.broadcast_in_dim(high_weight, high_value.shape,\n broadcast_dimensions=(0,))\n\n if interpolation == \"linear\":\n result = lax.add(lax.mul(low_value.astype(q.dtype), low_weight),\n lax.mul(high_value.astype(q.dtype), high_weight))\n elif interpolation == \"lower\":\n result = low_value\n elif interpolation == \"higher\":\n result = high_value\n elif interpolation == \"nearest\":\n pred = lax.le(high_weight, _constant_like(high_weight, 0.5))\n result = lax.select(pred, low_value, high_value)\n elif interpolation == \"midpoint\":\n result = lax.mul(lax.add(low_value, high_value), _constant_like(low_value, 0.5))\n else:\n raise ValueError(f\"interpolation={interpolation!r} not recognized\")\n\n return lax.convert_element_type(result, a.dtype)\n\n\n@partial(jit, static_argnums=2)\n@partial(vectorize, excluded={0, 2})\ndef _searchsorted(a, v, side):\n if len(a) == 0:\n return 0\n op = operator.le if side == 'left' else operator.lt\n\n def body_fun(i, state):\n low, high = state\n mid = (low + high) // 2\n go_left = op(v, a[mid])\n return (where(go_left, low, mid), where(go_left, mid, high))\n\n n_levels = int(np.ceil(np.log2(len(a) + 1)))\n return lax.fori_loop(0, n_levels, body_fun, (0, len(a)))[1]\n\n\n@_wraps(np.searchsorted)\ndef searchsorted(a, v, side='left', sorter=None):\n if side not in ['left', 'right']:\n raise ValueError(f\"{side!r} is an invalid value for keyword 'side'\")\n if sorter is not None:\n raise NotImplementedError(\"sorter is not implemented\")\n a = asarray(a)\n v = asarray(v)\n if ndim(a) != 1:\n raise ValueError(\"a should be 1-dimensional\")\n return _searchsorted(a, v, side)\n\n\n@_wraps(np.digitize)\ndef digitize(x, bins, right=False):\n if len(bins) == 0:\n return zeros(x, dtype=dtypes.canonicalize_dtype(int_))\n side = 'right' if not right else 'left'\n return where(\n bins[-1] >= bins[0],\n searchsorted(bins, x, side=side),\n len(bins) - searchsorted(bins[::-1], x, side=side)\n )\n\n_PIECEWISE_DOC = \"\"\"\\\nUnlike `np.piecewise`, :py:func:`jax.numpy.piecewise` requires functions in\n`funclist` to be traceable by JAX, as it is implemeted via :func:`jax.lax.switch`.\nSee the :func:`jax.lax.switch` documentation for more information.\n\"\"\"\n\n@_wraps(np.piecewise, lax_description=_PIECEWISE_DOC)\ndef piecewise(x, condlist, funclist, *args, **kw):\n condlist = array(condlist, dtype=bool_)\n nc, nf = len(condlist), len(funclist)\n if nf == nc + 1:\n funclist = funclist[-1:] + funclist[:-1]\n elif nf == nc:\n funclist = [0] + list(funclist)\n else:\n raise ValueError(f\"with {nc} condition(s), either {nc} or {nc+1} functions are expected; got {nf}\")\n indices = argmax(cumsum(vstack([zeros_like(condlist[:1]), condlist]), 0), 0)\n dtype = _dtype(x)\n def _call(f):\n return lambda x: f(x, *args, **kw).astype(dtype)\n def _const(v):\n return lambda x: full_like(x, v)\n funclist = [_call(f) if callable(f) else _const(f) for f in funclist]\n return vectorize(lax.switch, excluded=(1,))(indices, funclist, x)\n\n\n@_wraps(np.percentile)\ndef percentile(a, q, axis=None, out=None, overwrite_input=False,\n interpolation=\"linear\", keepdims=False):\n q = true_divide(asarray(q), float32(100.0))\n return quantile(a, q, axis=axis, out=out, overwrite_input=overwrite_input,\n interpolation=interpolation, keepdims=keepdims)\n\n@_wraps(np.nanpercentile)\ndef nanpercentile(a, q, axis=None, out=None, overwrite_input=False,\n interpolation=\"linear\", keepdims=False):\n q = true_divide(asarray(q), float32(100.0))\n return nanquantile(a, q, axis=axis, out=out, overwrite_input=overwrite_input,\n interpolation=interpolation, keepdims=keepdims)\n\n@_wraps(np.median)\ndef median(a, axis=None, out=None, overwrite_input=False, keepdims=False):\n return quantile(a, 0.5, axis=axis, out=out, overwrite_input=overwrite_input,\n keepdims=keepdims, interpolation='midpoint')\n\n@_wraps(np.nanmedian)\ndef nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=False):\n return nanquantile(a, 0.5, axis=axis, out=out,\n overwrite_input=overwrite_input, keepdims=keepdims,\n interpolation='midpoint')\n\n\ndef _astype(arr, dtype):\n lax._check_user_dtype_supported(dtype, \"astype\")\n return lax.convert_element_type(arr, dtype)\n\n\ndef _nbytes(arr):\n return size(arr) * _dtype(arr).itemsize\n\n\ndef _view(arr, dtype=None, type=None):\n if type is not None:\n raise NotImplementedError(\"`type` argument of array.view()\")\n if dtype is None:\n return arr\n arr_dtype = _dtype(arr)\n if arr_dtype == dtype:\n return arr\n # bool is implemented as lax:PRED, which is not compatible with lax.bitcast_convert_type.\n # We work around this by casting bool to uint8.\n if arr_dtype == bool_:\n arr = arr.astype(uint8)\n nbits_in = 8 * arr_dtype.itemsize\n nbits_out = 8 * _dtype(dtype).itemsize\n if nbits_in == nbits_out:\n if dtype == bool_:\n return lax.bitcast_convert_type(arr, uint8).astype(dtype)\n return lax.bitcast_convert_type(arr, dtype)\n if nbits_out > nbits_in and (shape(arr)[-1] * nbits_in) % nbits_out != 0:\n raise ValueError(\"When changing to a larger dtype, its size must be a divisor \"\n \"of the total size in bytes of the last axis of the array.\")\n byte_dtypes = {8: uint8, 16: uint16, 32: uint32, 64: uint64}\n if nbits_in not in byte_dtypes:\n raise NotImplementedError(f\"arr.view() for arr.dtype={arr_dtype}\")\n if nbits_out not in byte_dtypes:\n raise NotImplementedError(f\"arr.view(dtype) for dtype={dtype}\")\n dt_in = byte_dtypes[nbits_in]\n dt_out = byte_dtypes[nbits_out]\n arr_bytes = lax.bitcast_convert_type(arr, dt_in)\n if nbits_in < nbits_out:\n shifts = arange(0, nbits_out, nbits_in, dtype=dt_out)\n arr_bytes = arr_bytes.reshape(arr.shape[:-1] + (-1, nbits_out // nbits_in)).astype(dt_out)\n arr_bytes = (arr_bytes << shifts).sum(-1).astype(dt_out)\n else:\n shifts = arange(0, nbits_in, nbits_out, dtype=dt_in)\n arr_bytes = ((arr_bytes[..., newaxis] >> shifts) & iinfo(dt_out).max).astype(dt_out)\n arr_bytes = arr_bytes.reshape(arr_bytes.shape[:-2] + (-1,))\n if dtype == bool_:\n return lax.bitcast_convert_type(arr_bytes, uint8).astype(dtype)\n return lax.bitcast_convert_type(arr_bytes, dtype)\n\n### track unimplemented functions\n\ndef _not_implemented(fun):\n @_wraps(fun)\n def wrapped(*args, **kwargs):\n msg = \"Numpy function {} not yet implemented\"\n raise NotImplementedError(msg.format(fun))\n return wrapped\n\n\n### add method and operator overloads to arraylike classes\n\n# We add operator overloads to DeviceArray and ShapedArray. These method and\n# operator overloads mainly just forward calls to the corresponding lax_numpy\n# functions, which can themselves handle instances from any of these classes.\n\n_scalar_types = (int, float, complex, np.generic)\n\ndef _defer_to_unrecognized_arg(binary_op):\n # Ensure that other array types have the chance to override arithmetic.\n def deferring_binary_op(self, other):\n if not isinstance(other, _scalar_types + _arraylike_types + (core.Tracer,)):\n return NotImplemented\n return binary_op(self, other)\n return deferring_binary_op\n\ndef _swap_args(f):\n return lambda x, y: f(y, x)\n\ndef _unimplemented_setitem(self, i, x):\n msg = (\"'{}' object does not support item assignment. JAX arrays are \"\n \"immutable; perhaps you want jax.ops.index_update or \"\n \"jax.ops.index_add instead?\")\n raise TypeError(msg.format(type(self)))\n\ndef _operator_round(number, ndigits=None):\n out = round(number, decimals=ndigits or 0)\n # If `ndigits` is None, for a builtin float round(7.5) returns an integer.\n return out.astype(int_) if ndigits is None else out\n\n_operators = {\n \"getitem\": _rewriting_take,\n \"setitem\": _unimplemented_setitem,\n \"neg\": negative,\n \"pos\": positive,\n \"eq\": _defer_to_unrecognized_arg(equal),\n \"ne\": _defer_to_unrecognized_arg(not_equal),\n \"lt\": _defer_to_unrecognized_arg(less),\n \"le\": _defer_to_unrecognized_arg(less_equal),\n \"gt\": _defer_to_unrecognized_arg(greater),\n \"ge\": _defer_to_unrecognized_arg(greater_equal),\n \"abs\": abs,\n \"add\": _defer_to_unrecognized_arg(add),\n \"radd\": _defer_to_unrecognized_arg(add),\n \"sub\": _defer_to_unrecognized_arg(subtract),\n \"rsub\": _defer_to_unrecognized_arg(_swap_args(subtract)),\n \"mul\": _defer_to_unrecognized_arg(multiply),\n \"rmul\": _defer_to_unrecognized_arg(multiply),\n \"div\": _defer_to_unrecognized_arg(divide),\n \"rdiv\": _defer_to_unrecognized_arg(_swap_args(divide)),\n \"truediv\": _defer_to_unrecognized_arg(true_divide),\n \"rtruediv\": _defer_to_unrecognized_arg(_swap_args(true_divide)),\n \"floordiv\": _defer_to_unrecognized_arg(floor_divide),\n \"rfloordiv\": _defer_to_unrecognized_arg(_swap_args(floor_divide)),\n \"divmod\": _defer_to_unrecognized_arg(divmod),\n \"rdivmod\": _defer_to_unrecognized_arg(_swap_args(divmod)),\n \"mod\": _defer_to_unrecognized_arg(mod),\n \"rmod\": _defer_to_unrecognized_arg(_swap_args(mod)),\n \"pow\": _defer_to_unrecognized_arg(power),\n \"rpow\": _defer_to_unrecognized_arg(_swap_args(power)),\n \"matmul\": _defer_to_unrecognized_arg(matmul),\n \"rmatmul\": _defer_to_unrecognized_arg(_swap_args(matmul)),\n \"and\": _defer_to_unrecognized_arg(bitwise_and),\n \"rand\": _defer_to_unrecognized_arg(bitwise_and),\n \"or\": _defer_to_unrecognized_arg(bitwise_or),\n \"ror\": _defer_to_unrecognized_arg(bitwise_or),\n \"xor\": _defer_to_unrecognized_arg(bitwise_xor),\n \"rxor\": _defer_to_unrecognized_arg(bitwise_xor),\n \"invert\": bitwise_not,\n \"lshift\": _defer_to_unrecognized_arg(left_shift),\n \"rshift\": _defer_to_unrecognized_arg(right_shift),\n \"rlshift\": _defer_to_unrecognized_arg(_swap_args(left_shift)),\n \"rrshift\": _defer_to_unrecognized_arg(_swap_args(right_shift)),\n \"round\": _operator_round,\n}\n\n# These numpy.ndarray methods are just refs to an equivalent numpy function\n_nondiff_methods = [\"all\", \"any\", \"argmax\", \"argmin\", \"argpartition\", \"argsort\",\n \"nonzero\", \"searchsorted\", \"round\"]\n_diff_methods = [\"clip\", \"conj\", \"conjugate\", \"cumprod\", \"cumsum\",\n \"diagonal\", \"dot\", \"max\", \"mean\", \"min\", \"prod\", \"ptp\",\n \"ravel\", \"repeat\", \"sort\", \"squeeze\", \"std\", \"sum\",\n \"swapaxes\", \"take\", \"tile\", \"trace\", \"transpose\", \"var\"]\n\n# These methods are mentioned explicitly by nondiff_methods, so we create\n# _not_implemented implementations of them here rather than in __init__.py.\n# TODO(phawkins): implement these.\nargpartition = _not_implemented(np.argpartition)\n_NOT_IMPLEMENTED = ['argpartition']\n\n# Set up operator, method, and property forwarding on Tracer instances containing\n# ShapedArray avals by following the forwarding conventions for Tracer.\n# Forward operators using a single-underscore-prefix naming convention:\nfor operator_name, function in _operators.items():\n setattr(ShapedArray, \"_{}\".format(operator_name), staticmethod(function))\n# Forward methods and properties using core.aval_method and core.aval_property:\nfor method_name in _nondiff_methods + _diff_methods:\n setattr(ShapedArray, method_name, core.aval_method(globals()[method_name]))\nsetattr(ShapedArray, \"reshape\", core.aval_method(_reshape_method))\nsetattr(ShapedArray, \"flatten\", core.aval_method(ravel))\nsetattr(ShapedArray, \"T\", core.aval_property(transpose))\nsetattr(ShapedArray, \"real\", core.aval_property(real))\nsetattr(ShapedArray, \"imag\", core.aval_property(imag))\nsetattr(ShapedArray, \"astype\", core.aval_method(_astype))\nsetattr(ShapedArray, \"view\", core.aval_method(_view))\nsetattr(ShapedArray, \"nbytes\", core.aval_property(_nbytes))\n\n\n# Forward operators, methods, and properties on DeviceArray to lax_numpy\n# functions (with no Tracers involved; this forwarding is direct)\nfor operator_name, function in _operators.items():\n setattr(DeviceArray, \"__{}__\".format(operator_name), function)\nfor method_name in _nondiff_methods + _diff_methods:\n setattr(DeviceArray, method_name, globals()[method_name])\nsetattr(DeviceArray, \"reshape\", _reshape_method)\nsetattr(DeviceArray, \"flatten\", ravel)\nsetattr(DeviceArray, \"T\", property(transpose))\nsetattr(DeviceArray, \"real\", property(real))\nsetattr(DeviceArray, \"imag\", property(imag))\nsetattr(DeviceArray, \"astype\", _astype)\nsetattr(DeviceArray, \"view\", _view)\nsetattr(DeviceArray, \"nbytes\", property(_nbytes))\n\n\n# Extra methods that are handy\nsetattr(ShapedArray, \"broadcast\", core.aval_method(lax.broadcast))\nsetattr(ShapedArray, \"broadcast_in_dim\", core.aval_method(lax.broadcast_in_dim))\nsetattr(ShapedArray, \"split\", core.aval_method(split))\nsetattr(DeviceArray, \"broadcast\", lax.broadcast)\nsetattr(DeviceArray, \"broadcast_in_dim\", lax.broadcast_in_dim)\nsetattr(DeviceArray, \"split\", split)\n\ndef _compress_method(a, condition, axis=None, out=None):\n return compress(condition, a, axis, out)\n\nsetattr(ShapedArray, \"compress\", _compress_method)\nsetattr(DeviceArray, \"compress\", _compress_method)\n\n@partial(jit, static_argnums=(1,2,3))\ndef _multi_slice(arr: DeviceArray,\n start_indices: Tuple[Tuple[int, ...]],\n limit_indices: Tuple[Tuple[int, ...]],\n removed_dims: Tuple[Tuple[int, ...]]):\n \"\"\"Extracts multiple slices from `arr`.\n\n This is used to shard DeviceArray arguments to pmap. It's implemented as a\n DeviceArray method here to avoid circular imports.\n \"\"\"\n results = []\n for starts, limits, removed in safe_zip(start_indices, limit_indices, removed_dims):\n sliced = lax.slice(arr, starts, limits)\n if removed:\n sliced = sliced.reshape(np.delete(sliced.shape, removed_dims))\n results.append(sliced)\n return results\nsetattr(DeviceArray, \"_multi_slice\", _multi_slice)\n\n\n# Syntactic sugar for scatter operations.\nclass _IndexUpdateHelper:\n # Note: this docstring will appear as the docstring for the `at` property.\n \"\"\"Indexable helper object to call indexed update functions.\n\n The `at` property is syntactic sugar for calling the indexed update functions\n defined in :mod:`jax.ops`, and acts as a pure equivalent of in-place\n modificatons.\n\n In particular:\n - ``x = x.at[idx].set(y)`` is a pure equivalent of ``x[idx] = y``.\n - ``x = x.at[idx].add(y)`` is a pure equivalent of ``x[idx] += y``.\n - ``x = x.at[idx].mul(y)`` is a pure equivalent of ``x[idx] *= y``.\n - ``x = x.at[idx].min(y)`` is a pure equivalent of\n ``x[idx] = minimum(x[idx], y)``.\n - ``x = x.at[idx].max(y)`` is a pure equivalent of\n ``x[idx] = maximum(x[idx], y)``.\n \"\"\"\n __slots__ = (\"array\",)\n\n def __init__(self, array):\n self.array = array\n\n def __getitem__(self, index):\n return _IndexUpdateRef(self.array, index)\n\n def __repr__(self):\n return f\"_IndexUpdateHelper({repr(self.array)})\"\n\n\nclass _IndexUpdateRef:\n \"\"\"Helper object to call indexed update functions for an (advanced) index.\n\n This object references a source array and a specific indexer into that array.\n Methods on this object return copies of the source array that have been\n modified at the positions specified by the indexer.\n \"\"\"\n __slots__ = (\"array\", \"index\")\n\n def __init__(self, array, index):\n self.array = array\n self.index = index\n\n def __repr__(self):\n return f\"_IndexUpdateRef({repr(self.array)}, {repr(self.index)})\"\n\n def set(self, values, indices_are_sorted=False, unique_indices=False):\n \"\"\"Pure equivalent of ``x[idx] = y``.\n\n ``x.at[idx].set(y)`` is syntactic sugar for\n ``jax.ops.index_update(x, jax.ops.index[idx], y)``, and\n returns the value of ``x`` that would result from the NumPy-style\n :mod:indexed assignment <numpy.doc.indexing>` ``x[idx] = y``.\n\n See :mod:`jax.ops` for details.\n \"\"\"\n return ops.index_update(self.array, self.index, values,\n indices_are_sorted=indices_are_sorted,\n unique_indices=unique_indices)\n\n def add(self, values, indices_are_sorted=False, unique_indices=False):\n \"\"\"Pure equivalent of ``x[idx] += y``.\n\n ``x.at[idx].add(y)`` is syntactic sugar for\n ``jax.ops.index_add(x, jax.ops.index[idx], y)``, and\n returns the value of ``x`` that would result from the NumPy-style\n :mod:indexed assignment <numpy.doc.indexing>` ``x[idx] += y``.\n\n See :mod:`jax.ops` for details.\n \"\"\"\n return ops.index_add(self.array, self.index, values,\n indices_are_sorted=indices_are_sorted,\n unique_indices=unique_indices)\n\n def mul(self, values, indices_are_sorted=False, unique_indices=False):\n \"\"\"Pure equivalent of ``x[idx] += y``.\n\n ``x.at[idx].mul(y)`` is syntactic sugar for\n ``jax.ops.index_mul(x, jax.ops.index[idx], y)``, and\n returns the value of ``x`` that would result from the NumPy-style\n :mod:indexed assignment <numpy.doc.indexing>` ``x[idx] *= y``.\n\n See :mod:`jax.ops` for details.\n \"\"\"\n return ops.index_mul(self.array, self.index, values,\n indices_are_sorted=indices_are_sorted,\n unique_indices=unique_indices)\n\n def min(self, values, indices_are_sorted=False, unique_indices=False):\n \"\"\"Pure equivalent of ``x[idx] = minimum(x[idx], y)``.\n\n ``x.at[idx].min(y)`` is syntactic sugar for\n ``jax.ops.index_min(x, jax.ops.index[idx], y)``, and\n returns the value of ``x`` that would result from the NumPy-style\n :mod:indexed assignment <numpy.doc.indexing>`\n ``x[idx] = minimum(x[idx], y)``.\n\n See :mod:`jax.ops` for details.\n \"\"\"\n return ops.index_min(self.array, self.index, values,\n indices_are_sorted=indices_are_sorted,\n unique_indices=unique_indices)\n\n def max(self, values, indices_are_sorted=False, unique_indices=False):\n \"\"\"Pure equivalent of ``x[idx] = maximum(x[idx], y)``.\n\n ``x.at[idx].max(y)`` is syntactic sugar for\n ``jax.ops.index_max(x, jax.ops.index[idx], y)``, and\n returns the value of ``x`` that would result from the NumPy-style\n :mod:indexed assignment <numpy.doc.indexing>`\n ``x[idx] = maximum(x[idx], y)``.\n\n See :mod:`jax.ops` for details.\n \"\"\"\n return ops.index_max(self.array, self.index, values,\n indices_are_sorted=indices_are_sorted,\n unique_indices=unique_indices)\n\nsetattr(DeviceArray, \"at\", property(_IndexUpdateHelper))\nsetattr(ShapedArray, \"at\", core.aval_property(_IndexUpdateHelper))\n" ]
[ [ "numpy.sum", "numpy.version.version.split", "numpy.diff", "numpy.dtype", "numpy.any", "numpy.issubdtype", "numpy.asarray", "numpy.insert", "numpy.size", "numpy.int64", "numpy.log", "numpy.isscalar", "numpy.delete", "numpy.where", "numpy.ceil", "numpy.zeros", "numpy.equal", "numpy.arange", "numpy.all", "numpy.ndim", "numpy.broadcast_to", "numpy.sign", "numpy.not_equal", "numpy.ravel", "numpy.shape", "numpy.array", "numpy.concatenate" ] ]
DHI-GRAS/rmstripes
[ "08012961959275ad7bc4731da9b4da3d90597c76" ]
[ "rmstripes/stripes.py" ]
[ "import numpy as np\nimport pywt\n\n\ndef damp_coefficient(coeff, sigma):\n \"\"\"Filter DWT coefficients by performing an FFT and applying a Gaussian\n kernel.\n \"\"\"\n fft_coeff = np.fft.fft(coeff, axis=0)\n fft_coeff = np.fft.fftshift(fft_coeff, axes=[0])\n\n ydim, _ = fft_coeff.shape\n gauss1d = 1 - np.exp(-np.arange(-ydim // 2, ydim // 2)**2 / (2 * sigma**2))\n damped_fc = fft_coeff * gauss1d[:, np.newaxis]\n\n damped_coeff = np.fft.ifftshift(damped_fc, axes=[0])\n damped_coeff = np.fft.ifft(damped_coeff, axis=0)\n return damped_coeff.real\n\n\ndef remove_stripes(image, decomp_level, wavelet, sigma):\n \"\"\"Removes stripes from `image` with a combined wavelet/FFT approach.\n\n Params\n ------\n image : 2d array\n containing the stripy image\n decomp_level : int\n Decomposition level of DWT (TODO: could be automatically calculated?)\n wavelet : str\n name of wavelet to use for DWT\n sigma : int\n sigma of Gaussian that is used to smooth FFT coefficients\n \"\"\"\n coeffs = pywt.wavedec2(\n image, wavelet=wavelet, level=decomp_level, mode='symmetric')\n\n damped_coeffs = [coeffs[0]]\n\n for ii in range(1, len(coeffs)):\n ch, cv, cd = coeffs[ii]\n\n cv = damp_coefficient(cv, sigma)\n ch = damp_coefficient(ch, sigma)\n\n damped_coeffs.append((ch, cv, cd))\n\n rec_image = pywt.waverec2(damped_coeffs, wavelet=wavelet, mode='symmetric')\n return rec_image\n" ]
[ [ "numpy.fft.fft", "numpy.fft.fftshift", "numpy.fft.ifftshift", "numpy.fft.ifft", "numpy.arange" ] ]
chriscrsmith/pyslim
[ "babfedf4e9758e00ea431cc6d6ce74642796ee38" ]
[ "pyslim/methods.py" ]
[ "import msprime\nimport tskit\nimport warnings\nimport numpy as np\n\nfrom .slim_tree_sequence import *\nfrom .slim_metadata import *\nfrom .provenance import *\nfrom .util import *\n\ndef recapitate(ts,\n ancestral_Ne=None,\n **kwargs):\n '''\n Returns a \"recapitated\" tree sequence, by using msprime to run a\n coalescent simulation from the \"top\" of this tree sequence, i.e.,\n allowing any uncoalesced lineages to coalesce.\n\n To allow recapitation to be done correctly, the nodes of the\n first generation of the SLiM simulation from whom all samples inherit\n are still present in the tree sequence, but are not marked as samples.\n If you simplify the tree sequence before recapitating you must ensure\n these are not removed, which you do by passing the argument\n ``keep_input_roots=True`` to :meth:`.simplify()`.\n\n If you specify an ``ancestral_Ne``, then the recapitated portion of the\n tree sequence will be simulated in a single population with this\n (diploid) size. In other words, all lineages are moved to a single\n population of this size (named \"ancestral\" if this name is not already\n taken), and coalescence is allowed to happen.\n\n You may control the ancestral demography by passing in a ``demography``\n argument: see {ref}``msprime.sim_ancestry``.\n \n In general, all defaults are whatever the defaults of\n {ref}`msprime.sim_ancestry` are; this includes recombination rate, so\n that if neither ``recombination_rate`` or a ``recombination_map`` are\n provided, there will be *no* recombination.\n\n : param TreeSequence ts: The tree sequence to transform.\n :param float ancestral_Ne: If specified, then will simulate from a single\n ancestral population of this size. It is an error to specify this\n as well as ``demography``.\n :param dict kwargs: Any other arguments to :meth:`msprime.sim_ancestry`.\n '''\n demography = None\n if \"demography\" in kwargs:\n demography = kwargs['demography']\n if ancestral_Ne is not None:\n if demography is not None:\n raise ValueError(\"You cannot specify both `demography` and `ancestral_Ne`.\")\n demography = msprime.Demography.from_tree_sequence(ts)\n # must set pop sizes to >0 even though we merge immediately\n for pop in demography.populations:\n pop.initial_size=1.0\n ancestral_name = \"ancestral\"\n derived_names = [pop.name for pop in demography.populations]\n while ancestral_name in derived_names:\n ancestral_name = (ancestral_name + \"_ancestral\")\n ancestral_metadata = default_slim_metadata('population')\n ancestral_metadata['slim_id'] = ts.num_populations\n demography.add_population(\n name=ancestral_name,\n description=\"ancestral population simulated by msprime\",\n initial_size=ancestral_Ne,\n extra_metadata=ancestral_metadata,\n )\n # the split has to come slightly longer ago than slim_generation,\n # since that's when all the linages are at, and otherwise the event\n # won't apply to them\n demography.add_population_split(\n np.nextafter(\n ts.slim_generation,\n 2 * ts.slim_generation,\n ),\n derived=derived_names,\n ancestral=ancestral_name,\n )\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", msprime.IncompletePopulationMetadataWarning)\n recap = msprime.sim_ancestry(\n initial_state = ts,\n demography = demography,\n **kwargs)\n return SlimTreeSequence(recap, reference_sequence=ts.reference_sequence)\n\n\ndef convert_alleles(ts):\n \"\"\"\n Returns a modified tree sequence in which alleles have been replaced by\n their corresponding nucleotides. For sites, SLiM-produced tree sequences\n have \"\" (the empty string) for the ancestral state at each site; this method\n will replace this with the corresponding nucleotide from the reference sequence.\n For mutations, SLiM records the 'derived state' as a SLiM mutation ID; this\n method will this with the nucleotide from the mutation's metadata.\n\n This operation is not reversible: since SLiM mutation IDs are lost, the tree\n sequence will not be able to be read back into SLiM.\n\n The main purpose of this method is for output: for instance, this code will produce\n a VCF file with nucleotide alleles:\n\n nts = pyslim.convert_alleles(ts)\n with open('nucs.vcf', 'w') as f:\n nts.write_vcf(f)\n\n This method will produce an error if the tree sequence does not have a\n valid reference sequence or if any mutations do not have nucleotides: to first\n generate these, see :meth:`.generate_nucleotides`.\n\n :param TreeSequence ts: The tree sequence to transform.\n \"\"\"\n tables = ts.dump_tables()\n has_refseq = (\n hasattr(ts, 'reference_sequence')\n and (ts.reference_sequence is not None)\n )\n # unfortunately, nucleotide mutations may be stacked (e.g., substitutions\n # will appear this way) and they don't appear in any particular order;\n # so we must guess which is the most recent, by choosing the one that\n # has the largest SLiM time, doesn't appear in the parent list, or has\n # the lagest SLiM ID.\n slim_muts = np.repeat(0, ts.num_mutations)\n num_stacked = np.array([len(m.metadata['mutation_list']) for m in ts.mutations()])\n for k in np.where(num_stacked > 1)[0]:\n mut = ts.mutation(k)\n if mut.parent == tskit.NULL:\n pids = []\n else:\n pids = ts.mutation(mut.parent).derived_state.split(\",\")\n x = [\n (\n md['slim_time'],\n i not in pids,\n int(i),\n j\n ) for j, (i, md) in\n enumerate(\n zip(mut.derived_state.split(\",\"), mut.metadata['mutation_list'])\n )\n ]\n x.sort()\n slim_muts[k] = x[-1][3]\n # gah that was terrible, ok back to it\n nuc_inds = np.array(\n [m.metadata['mutation_list'][0]['nucleotide']\n for k, m in zip(slim_muts, ts.mutations())],\n dtype='int',\n )\n if np.any(nuc_inds == -1):\n raise ValueError(\"All mutations must be nucleotide mutations.\")\n if not has_refseq:\n raise ValueError(\"Tree sequence must have a valid reference sequence.\")\n aa = [ts.reference_sequence[k] for k in tables.sites.position.astype('int')]\n da = np.array(NUCLEOTIDES)[nuc_inds]\n tables.sites.packset_ancestral_state(aa)\n tables.mutations.packset_derived_state(da)\n\n out = SlimTreeSequence(tables.tree_sequence())\n out.reference_sequence = ts.reference_sequence\n return out\n\n\ndef generate_nucleotides(ts, reference_sequence=None, keep=True, seed=None):\n \"\"\"\n \n Returns a modified tree sequence in which mutations have been randomly assigned nucleotides\n and (optionally) a reference sequence has been randomly generated.\n\n If ``reference_sequence`` is a string of nucleotides (A, C, G, and T) of\n length equal to the sequence length, this is used for the reference\n sequence. Otherwise (the default), a reference sequence of independent and\n uniformly random nucleotides is generated.\n\n SLiM stores the nucleotide as an integer in the mutation metadata, with -1 meaning \"not\n a nucleotide mutation\". This method assigns nucleotides by stepping through\n each mutation and picking a random nucleotide uniformly out of the three\n possible nucleotides that differ from the parental state (i.e., the derived\n state of the parental mutation, or the ancestral state if the mutation has\n no parent). If ``keep=True`` (the default), the mutations that already have a \n nucleotide (i.e., an integer 0-3 in metadata) will not be modified.\n\n Technical note: in the case of stacked mutations, the SLiM mutation that\n determines the nucleotide state of the (tskit) mutation is the one with the largest\n slim_time attribute. This method tries to assign nucleotides so that each mutation\n differs from the previous state, but this is not always possible in certain\n unlikely cases.\n\n :param TreeSequence ts: The tree sequence to transform.\n :param bool reference_sequence: A reference sequence, or None to randomly generate one.\n :param bool keep: Whether to leave existing nucleotides in mutations that already have one.\n :param int seed: The random seed for generating new alleles.\n \"\"\"\n rng = np.random.default_rng(seed=seed)\n if reference_sequence is None:\n reference_sequence = rng.choice(\n np.array([65, 67, 71, 84], dtype=np.int8),\n int(ts.sequence_length),\n replace=True,\n ).tobytes().decode('ascii')\n\n if len(reference_sequence) != ts.sequence_length:\n raise ValueError(\"Reference sequence must have length equal to sequence_length.\")\n if len([x for x in reference_sequence if x not in NUCLEOTIDES]) > 0:\n raise ValueError(\"Reference sequence must be a string of A, C, G, and T only.\")\n\n tables = ts.dump_tables()\n tables.mutations.clear()\n sets = [[k for k in range(4) if k != i] for i in range(4)]\n states = np.full((ts.num_mutations,), -1)\n for site in ts.sites():\n aa = NUCLEOTIDES.index(reference_sequence[int(site.position)])\n muts = {}\n for mut in site.mutations:\n if mut.parent == tskit.NULL:\n pa = aa\n pds = []\n else:\n pa = states[mut.parent]\n pds = ts.mutation(mut.parent).derived_state.split(\",\")\n this_da = pa\n ml = mut.metadata\n max_time = -np.inf\n for i, md in zip(mut.derived_state.split(\",\"), ml['mutation_list']):\n da = md['nucleotide']\n if da == -1 or not keep:\n if i in muts:\n da = muts[i]\n else:\n da = sets[pa][rng.integers(3)]\n md['nucleotide'] = da\n muts[i] = da\n # the official nucleotide state is from the SLiM mutation with\n # the largest slim_time attribute that was not present in the parent\n # mutation\n if md[\"slim_time\"] >= max_time and i not in pds:\n this_da = da\n max_time = md[\"slim_time\"]\n states[mut.id] = this_da\n tables.mutations.append(mut.replace(metadata=ml))\n\n return SlimTreeSequence(\n tables.tree_sequence(),\n reference_sequence=reference_sequence\n )\n" ]
[ [ "numpy.random.default_rng", "numpy.any", "numpy.repeat", "numpy.nextafter", "numpy.array", "numpy.where", "numpy.full" ] ]
Pratiush/Raspberry-pi-Home-security
[ "56002e98de4d085a500e81f61935f791d54682d2" ]
[ "StoreData.py" ]
[ "import cv2,os\r\nimport numpy as np\r\nfrom PIL import Image\r\ncam = cv2.VideoCapture(0)\r\n\r\nrecognizer = cv2.createLBPHFaceRecognizer()\r\ndetector=cv2.CascadeClassifier('frontface.xml')\r\n\r\n\r\n'''\r\nBelow function converts data into yml\r\n'''\r\ndef getImagesAndLabels(path):\r\n imagePaths=[os.path.join(path,f) for f in os.listdir(path)] \r\n faceSamples=[]\r\n Ids=[]\r\n for imagePath in imagePaths:\r\n pilImage=Image.open(imagePath).convert('L')\r\n imageNp=np.array(pilImage,'uint8')\r\n Id=int(os.path.split(imagePath)[-1].split(\".\")[1])\r\n faces=detector.detectMultiScale(imageNp)\r\n for (x,y,w,h) in faces:\r\n faceSamples.append(imageNp[y:y+h,x:x+w])\r\n Ids.append(Id)\r\n return faceSamples,Ids\r\n\r\nId=raw_input('enter your id')\r\nsampleNum=0\r\nwhile(True):\r\n ret, img = cam.read()\r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n faces = detector.detectMultiScale(gray, 1.3, 5)\r\n for (x,y,w,h) in faces:\r\n #cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) \r\n sampleNum=sampleNum+1\r\n #saving the captured face in the dataset folder\r\n cv2.imwrite(\"dataSet/User.\"+Id +'.'+ str(sampleNum) + \".jpg\", gray[y:y+h,x:x+w])\r\n\r\n cv2.imshow('frame',img)\r\n #wait for 100 miliseconds \r\n if cv2.waitKey(100) & 0xFF == ord('q'):\r\n break\r\n # break if the sample number is morethan 20\r\n elif sampleNum>30:\r\n break\r\ncam.release()\r\nfaces,Ids = getImagesAndLabels('dataSet')\r\nrecognizer.train(faces, np.array(Ids))\r\nrecognizer.save('trainner/trainner.yml')\r\ncv2.destroyAllWindows()\r\n\r\n\r\n" ]
[ [ "numpy.array" ] ]
Puneethnaik/Generative-Adversarial-Networks
[ "283abe2caaccbb99e1516b2a3f251cd8d005a386" ]
[ "utilities/mini_batch_gradient_descent.py" ]
[ "import numpy as np\n\n#This is crafted especially for normal distribution for MLE.\nclass GradientDescentOptimizer:\n def __init__(self, X, tolerance, learning_rate):\n self.learning_rate = learning_rate\n self.tolerance = tolerance\n self.X = X\n if(len(X.shape) == 1):\n self.number_of_points = X.shape[0]\n self.number_of_variables = 2\n else:\n self.number_of_points, self.number_of_variables = X.shape\n # self.number_of_variables -= 1 #we subtract the extra bias term\n print(self.number_of_points, self.number_of_variables, \"hello\")\n\n def optimize(self):\n self.theta = np.array([np.random.randint(1, 10) for _ in range(self.number_of_variables)]) #we choose a random value for theta\n self.theta = np.resize(self.theta, new_shape=(self.number_of_variables, 1))\n self.theta = self.theta.astype(float)\n prev_value = 1\n current_value = 2\n print(\"theta assigned\", self.theta)\n print(\"X\", self.X)\n while abs(prev_value - current_value) >= self.tolerance:\n gradient = self.theta.copy()\n for i in range(2):\n if i == 0:\n gradient[i][0] = self.learning_rate * (1.0 / self.number_of_points) * np.sum((self.X - self.theta[0]))\n else :\n gradient[i][0] = self.learning_rate * (1.0 / self.number_of_points) * np.sum((-1.0 / (2.0 * self.theta[1])) + ((self.X - self.theta[0]) ** 2 / (2.0 * (self.theta[1]) ** 2)))\n # print(\"gradient \", gradient)\n if self.theta[1] + gradient[1][0] < 0:\n break\n self.theta = self.theta + gradient\n prev_value = current_value\n current_value = np.sum(-np.log(np.sqrt(2 * np.pi)) - np.log(np.sqrt(self.theta[1])) - ((self.X - self.theta[0]) ** 2 / (2 * self.theta[1])))\n print(\"loss function \" + str(current_value))\n print(\"theta \", self.theta)\n return self.theta" ]
[ [ "numpy.sqrt", "numpy.sum", "numpy.random.randint", "numpy.resize" ] ]
mjjohns1/catboost
[ "08719381259ab93f00b8e350433f67ae9782fef6" ]
[ "contrib/python/scipy/scipy/_lib/_numpy_compat.py" ]
[ "\"\"\"Functions copypasted from newer versions of numpy.\n\n\"\"\"\nfrom __future__ import division, print_function, absolute_import\n\nimport warnings\nimport sys\n\nimport numpy as np\nfrom numpy.testing._private.nosetester import import_nose\n\nfrom scipy._lib._version import NumpyVersion\n\nif NumpyVersion(np.__version__) > '1.7.0.dev':\n _assert_warns = np.testing.assert_warns\nelse:\n def _assert_warns(warning_class, func, *args, **kw):\n r\"\"\"\n Fail unless the given callable throws the specified warning.\n\n This definition is copypasted from numpy 1.9.0.dev.\n The version in earlier numpy returns None.\n\n Parameters\n ----------\n warning_class : class\n The class defining the warning that `func` is expected to throw.\n func : callable\n The callable to test.\n *args : Arguments\n Arguments passed to `func`.\n **kwargs : Kwargs\n Keyword arguments passed to `func`.\n\n Returns\n -------\n The value returned by `func`.\n\n \"\"\"\n with warnings.catch_warnings(record=True) as l:\n warnings.simplefilter('always')\n result = func(*args, **kw)\n if not len(l) > 0:\n raise AssertionError(\"No warning raised when calling %s\"\n % func.__name__)\n if not l[0].category is warning_class:\n raise AssertionError(\"First warning for %s is not a \"\n \"%s( is %s)\" % (func.__name__, warning_class, l[0]))\n return result\n\n\ndef assert_raises_regex(exception_class, expected_regexp,\n callable_obj=None, *args, **kwargs):\n \"\"\"\n Fail unless an exception of class exception_class and with message that\n matches expected_regexp is thrown by callable when invoked with arguments\n args and keyword arguments kwargs.\n Name of this function adheres to Python 3.2+ reference, but should work in\n all versions down to 2.6.\n Notes\n -----\n .. versionadded:: 1.8.0\n \"\"\"\n __tracebackhide__ = True # Hide traceback for py.test\n nose = import_nose()\n\n if sys.version_info.major >= 3:\n funcname = nose.tools.assert_raises_regex\n else:\n # Only present in Python 2.7, missing from unittest in 2.6\n funcname = nose.tools.assert_raises_regexp\n\n return funcname(exception_class, expected_regexp, callable_obj,\n *args, **kwargs)\n\n\nif NumpyVersion(np.__version__) >= '1.10.0':\n from numpy import broadcast_to\nelse:\n # Definition of `broadcast_to` from numpy 1.10.0.\n\n def _maybe_view_as_subclass(original_array, new_array):\n if type(original_array) is not type(new_array):\n # if input was an ndarray subclass and subclasses were OK,\n # then view the result as that subclass.\n new_array = new_array.view(type=type(original_array))\n # Since we have done something akin to a view from original_array, we\n # should let the subclass finalize (if it has it implemented, i.e., is\n # not None).\n if new_array.__array_finalize__:\n new_array.__array_finalize__(original_array)\n return new_array\n\n def _broadcast_to(array, shape, subok, readonly):\n shape = tuple(shape) if np.iterable(shape) else (shape,)\n array = np.array(array, copy=False, subok=subok)\n if not shape and array.shape:\n raise ValueError('cannot broadcast a non-scalar to a scalar array')\n if any(size < 0 for size in shape):\n raise ValueError('all elements of broadcast shape must be non-'\n 'negative')\n broadcast = np.nditer(\n (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'],\n op_flags=['readonly'], itershape=shape, order='C').itviews[0]\n result = _maybe_view_as_subclass(array, broadcast)\n if not readonly and array.flags.writeable:\n result.flags.writeable = True\n return result\n\n def broadcast_to(array, shape, subok=False):\n return _broadcast_to(array, shape, subok=subok, readonly=True)\n" ]
[ [ "scipy._lib._version.NumpyVersion", "numpy.testing._private.nosetester.import_nose", "numpy.iterable", "numpy.nditer", "numpy.array" ] ]
dcat52/interop
[ "b016b2c25e468e21649bdb7475d828198b5e6958" ]
[ "server/auvsi_suas/models/access_log.py" ]
[ "\"\"\"Model for an access log.\"\"\"\n\nimport datetime\nimport numpy as np\nfrom time_period import TimePeriod\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils import timezone\n\n\nclass AccessLog(models.Model):\n \"\"\"Base class which logs access of information.\n\n Attributes:\n user: The user which accessed the data.\n timestamp: Timestamp of the access.\n \"\"\"\n user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True)\n timestamp = models.DateTimeField(auto_now_add=True, db_index=True)\n\n class Meta:\n abstract = True\n index_together = (('user', 'timestamp'), )\n\n def __unicode__(self):\n \"\"\"Descriptive text for use in displays.\"\"\"\n return unicode(\"%s (pk:%s, user:%s, timestamp:%s)\" %\n (self.__class__.__name__, str(self.pk),\n self.user.__unicode__(), str(self.timestamp)))\n\n @classmethod\n def by_user(cls, user, start_time=None, end_time=None):\n \"\"\"Gets the time-sorted list of access log for the given user.\n\n Args:\n user: The user to get the access log for.\n start_time: Optional. Inclusive start time.\n end_time: Optional. Exclusive end time.\n Returns:\n A list of access log objects for the given user sorted by timestamp.\n \"\"\"\n query = cls.objects.filter(user_id=user.pk)\n if start_time:\n query = query.filter(timestamp__gte=start_time)\n if end_time:\n query = query.filter(timestamp__lt=end_time)\n return query.order_by('timestamp')\n\n @classmethod\n def last_for_user(cls, user, start_time=None, end_time=None):\n \"\"\"Gets the last access log for the user.\n\n Args:\n user: The user to get the access log for.\n start_time: Optional. Inclusive start time.\n end_time: Optional. Exclusive end time.\n Returns:\n The last access log for the user.\n \"\"\"\n return cls.by_user(user, start_time, end_time).last()\n\n @classmethod\n def by_time_period(cls, user, time_periods):\n \"\"\"Gets a list of time-sorted lists of access logs for each time period.\n\n The method returns the full sets of AccessLogs for each TimePeriod. If\n overlapping TimePeriods are provided, the results may contain duplicate\n logs.\n\n Args:\n user: The user to get the access log for.\n time_periods: A list of TimePeriod objects.\n Returns:\n A list of AccessLog lists, where each AccessLog list contains all\n AccessLogs corresponding to the related TimePeriod.\n \"\"\"\n return [cls.by_user(user, p.start, p.end) for p in time_periods]\n\n @classmethod\n def rates(cls, user, time_periods, time_period_logs=None):\n \"\"\"Gets the access log rates.\n\n Args:\n user: The user to get the access log rates for.\n time_periods: A list of TimePeriod objects. Note: to avoid\n computing rates with duplicate logs, ensure that all\n time periods are non-overlapping.\n time_period_logs: Optional. A list of AccessLog lists, where each\n AccessLog list contains all AccessLogs corresponding to the\n related TimePeriod. If None, will obtain by calling\n by_time_period().\n Returns:\n A (max, avg) tuple. The max is the max time between logs, and avg\n is the avg time between logs.\n \"\"\"\n # Check that time periods were provided.\n if not time_periods:\n return (None, None)\n\n # If logs were not provided, obtain.\n if not time_period_logs:\n time_period_logs = cls.by_time_period(user, time_periods)\n\n # Calculate time between log files.\n times_between_logs = []\n for i, period in enumerate(time_periods):\n # Get the logs for this period\n # Coerce the QuerySet into a list, so we can use negative indexing.\n logs = list(time_period_logs[i])\n\n # Account for a time period with no logs\n if len(logs) == 0:\n if period.start is not None and period.end is not None:\n time_diff = (period.end - period.start).total_seconds()\n times_between_logs.append(time_diff)\n continue\n\n # Account for time between takeoff and first log\n if period.start is not None:\n first = logs[0]\n time_diff = (first.timestamp - period.start).total_seconds()\n times_between_logs.append(time_diff)\n\n # Account for time between logs\n for j, log in enumerate(logs[:-1]):\n nextlog = logs[j + 1]\n time_diff = (nextlog.timestamp - log.timestamp).total_seconds()\n times_between_logs.append(time_diff)\n\n # Account for time between last log and landing\n if period.end is not None:\n last_log = logs[-1]\n time_diff = (period.end - last_log.timestamp).total_seconds()\n times_between_logs.append(time_diff)\n\n # Compute rates using the time between log files.\n times_between_logs = np.array(times_between_logs)\n times_between_max = float(np.max(times_between_logs))\n times_between_avg = float(np.mean(times_between_logs))\n return (times_between_max, times_between_avg)\n" ]
[ [ "numpy.array", "numpy.max", "numpy.mean" ] ]
jet-code/multivariable-control-systems
[ "81b57d51a4dfc92964f989794f71d525af0359ff" ]
[ "cp2/cp2_method23.py" ]
[ "\n# coding: utf-8\n\n# In[1]:\n\n# Alexander Hebert\n# ECE 6390\n# Computer Project #2\n# Method 2/3\n\n\n# In[2]:\n\n# Tested using Python v3.4 and IPython v2\n\n\n##### Import libraries and functions\n\n# In[3]:\n\nimport numpy as np\n\n\n# In[4]:\n\nfrom PlaneRotationFn import planeRotation1\nfrom PlaneRotationFn import planeRotation2\n\n\n# In[5]:\n\nimport scipy\n\n\n# In[6]:\n\nimport sympy\n\n\n# In[7]:\n\nfrom IPython.display import display\n\n\n# In[8]:\n\nfrom sympy.interactive import printing\n\n\n# In[9]:\n\nnp.set_printoptions(precision=6)\n\n\n# In[10]:\n\n#np.set_printoptions(suppress=True)\n\n\n##### Original system:\n\n# In[11]:\n\nA = np.loadtxt('A_ex1.txt')\n\n\n# In[12]:\n\nA\n\n\n# In[13]:\n\nn,nc = A.shape\n\n\n# In[14]:\n\nB = np.loadtxt('B_ex1.txt')\n\n\n# In[15]:\n\nB\n\n\n# In[16]:\n\nnr,m = B.shape\n\n\n##### Compute eigenvalues/poles of A to determine system stability:\n\n# In[17]:\n\nA_eigvals, M = np.linalg.eig(A)\n\n\n# In[18]:\n\nA_eigvals\n\n\n# In[19]:\n\n# Two poles lie in the RHP and are unstable.\n\n\n# In[20]:\n\nA_eigvals_desired = np.array([-0.2,-0.5,A_eigvals[2],A_eigvals[3]])\n\n\n# In[21]:\n\nA_eigvals_desired\n\n\n# In[22]:\n\nLambda = np.diag(A_eigvals_desired)\n\n\n# In[23]:\n\nLambda\n\n\n##### Pole Assignment Algorithm from journal paper\n\n# In[24]:\n\n# Step A: Decomposition of B using SVD\n# B = U*S*V.H\n\n\n# In[25]:\n\nU, s, VH = np.linalg.svd(B)\n\n\n# In[26]:\n\nU\n\n\n# In[27]:\n\ns\n\n\n# In[28]:\n\nS = np.zeros((4, 2))\nS[:2, :2] = np.diag(s)\n\n\n# In[29]:\n\nS\n\n\n# In[30]:\n\nVH\n\n\n# In[31]:\n\n# Extract U_0 and U_1 from matrix U = [U_0,U_1]\n\n\n# In[32]:\n\nU_0 = U[:n,:m]\n\n\n# In[33]:\n\nU_0\n\n\n# In[34]:\n\nU_1 = U[:n,m:]\n\n\n# In[35]:\n\nU_1\n\n\n# In[36]:\n\n# B = [U_0,U_1][Z,0].T\n# Compute Z from SVD of B\n\n\n# In[37]:\n\nZ = np.diag(s).dot(VH)\n\n\n# In[38]:\n\nZ\n\n\n# In[39]:\n\n# U_1.T *(A - lambda_j*I)\n# Compute S_hat_j and S_j\n\nfor j in range(len(A_eigvals_desired)):\n \n lambda_j = A_eigvals_desired[j]\n \n # M_j is a temp matrix\n exec(\"M_%d = np.dot(U_1.T,(A - lambda_j*np.identity(n)))\" %(j+1))\n \n # U_1.T *(A - lambda_j*I) = T_j *[Gamma_j,0]*[S_j_hat,S_j].T\n exec(\"T_%d, gamma_%d, SH_%d = np.linalg.svd(M_%d)\" %(j+1,j+1,j+1,j+1))\n \n exec(\"S_hat_%d = SH_%d[:m,:].T\" %(j+1,j+1))\n exec(\"S_%d = SH_%d[m:,:].T\" %(j+1,j+1))\n \n\n\n# In[40]:\n\n# Initial eigenvectors in X_tilde\nX_tilde = np.eye(n)\nX_tilde\n\n\n# In[41]:\n\n# Initial eigenvectors in X\nX = np.zeros((n,n))\nX\n\n\n# In[42]:\n\n# Step X with Method 2/3\n\nmaxiter = 1\nv4prev = 0\nv4current = 0\n\nfor r in range(maxiter):\n \n for j in range(n):\n \n xt_j = X_tilde[:,j].reshape((n,1))\n \n for k in range(j+1,n,1):\n \n xt_k = X_tilde[:,k].reshape((n,1))\n \n exec(\"phi_j = np.linalg.norm(np.dot(S_hat_%d.T,xt_j))\" %(j+1))\n exec(\"phi_k = np.linalg.norm(np.dot(S_hat_%d.T,xt_k))\" %(k+1))\n \n if (phi_j < phi_k):\n \n sin_theta = phi_j\n cos_theta = np.sqrt(1 - phi_j**2)\n protation = planeRotation2(n,cos_theta,sin_theta,j,k)\n v4current = v4current + phi_j**2\n \n else:\n \n sin_theta = phi_k\n cos_theta = np.sqrt(1 - phi_k**2)\n protation = planeRotation2(n,cos_theta,sin_theta,j,k)\n v4current = v4current + phi_k**2\n \n X_tilde = np.dot(protation,X_tilde)\n \n v4current = np.sqrt(v4current)\n print(v4current - v4prev)\n v4prev = v4current\n \n\n\n# In[43]:\n\n# Compute eigenvectors x_j in X from X_tilde\n\nfor j in range(n):\n \n xt_j = X_tilde[:,j].reshape((n,1)) \n exec(\"x_j = np.dot(np.dot(S_%d,S_%d.T),xt_j) / np.linalg.norm(np.dot(S_%d.T,xt_j))\" %(j+1,j+1,j+1))\n X[:,j] = x_j[:,0]\n \n\n\n# In[44]:\n\nX\n\n\n# In[45]:\n\nnp.linalg.matrix_rank(X)\n\n\n# In[46]:\n\nX_inv = np.linalg.inv(X)\n\n\n# In[47]:\n\nX_inv\n\n\n# In[48]:\n\n# M defined as A + BF\nM = X.dot(Lambda).dot(X_inv)\n\n\n# In[49]:\n\nM\n\n\n# In[50]:\n\n# Compute feedback matrix F\nF = np.dot(np.linalg.inv(Z),np.dot(U_0.T,(M - A)))\n\n\n# In[51]:\n\nF\n\n\n# In[52]:\n\n\n\n" ]
[ [ "numpy.sqrt", "numpy.eye", "numpy.zeros", "numpy.diag", "numpy.linalg.inv", "numpy.set_printoptions", "numpy.linalg.svd", "numpy.linalg.matrix_rank", "numpy.array", "numpy.dot", "numpy.linalg.eig", "numpy.loadtxt" ] ]
Anthchirp/dials
[ "211cf7646d6711769b86643b010cb2fe5aaf71b9" ]
[ "command_line/show.py" ]
[ "from __future__ import absolute_import, division, print_function\n\nimport collections\nimport os\n\nimport iotbx.phil\nimport numpy as np\nfrom cctbx import uctbx\nfrom dials.array_family import flex\nfrom dials.util import Sorry, tabulate\nfrom dxtbx.model.experiment_list import ExperimentListFactory\nfrom scitbx.math import five_number_summary\n\nhelp_message = \"\"\"\n\nExamples::\n\n dials.show models.expt\n\n dials.show image_*.cbf\n\n dials.show observations.refl\n\"\"\"\n\nphil_scope = iotbx.phil.parse(\n \"\"\"\\\nshow_scan_varying = False\n .type = bool\n .help = \"Whether or not to show the crystal at each scan point.\"\nshow_shared_models = False\n .type = bool\n .help = \"Show which models are linked to which experiments\"\nshow_all_reflection_data = False\n .type = bool\n .help = \"Whether or not to print individual reflections\"\nshow_intensities = False\n .type = bool\nshow_centroids = False\n .type = bool\nshow_profile_fit = False\n .type = bool\nshow_flags = False\n .type = bool\n .help = \"Show a summary table of reflection flags\"\nshow_identifiers = False\n .type = bool\n .help = \"Show experiment identifiers map if set\"\nimage_statistics{\n show_corrected = False\n .type = bool\n .help = \"Show statistics on the distribution of values in each corrected image\"\n show_raw = False\n .type = bool\n .help = \"Show statistics on the distribution of values in each raw image\"\n}\nmax_reflections = None\n .type = int\n .help = \"Limit the number of reflections in the output.\"\n\"\"\",\n process_includes=True,\n)\n\n\ndef beam_centre_mm(detector, s0):\n x, y = (None, None)\n for panel_id, panel in enumerate(detector):\n try:\n x, y = panel.get_ray_intersection(s0)\n except RuntimeError:\n continue\n else:\n if panel.is_coord_valid_mm((x, y)):\n break\n else:\n x, y = (None, None)\n return panel_id, (x, y)\n\n\ndef beam_centre_raw_image_px(detector, s0):\n panel_id, (x, y) = beam_centre_mm(detector, s0)\n panel = detector[panel_id]\n x_px, y_px = panel.millimeter_to_pixel((x, y))\n offset = panel.get_raw_image_offset()\n return x_px + offset[0], y_px + offset[1]\n\n\ndef show_beam(detector, beam):\n\n # standard static beam model string\n s = str(beam)\n\n # report whether the beam is scan-varying\n if beam.num_scan_points > 0:\n s += \" s0 sampled at \" + str(beam.num_scan_points) + \" scan points\\n\"\n\n # add static model beam centres\n panel_id, (x, y) = beam_centre_mm(detector, beam.get_s0())\n if panel_id >= 0 and x is not None and y is not None:\n x_px, y_px = detector[panel_id].millimeter_to_pixel((x, y))\n if len(detector) > 1:\n beam_centre_mm_str = \" mm: panel %i, (%.2f,%.2f)\" % (panel_id, x, y)\n beam_centre_px_str = \" px: panel %i, (%.2f,%.2f)\" % (\n panel_id,\n x_px,\n y_px,\n )\n x_raw_px, y_raw_px = beam_centre_raw_image_px(detector, beam.get_s0())\n beam_centre_raw_px_str = \" px, raw image: (%.2f,%.2f)\" % (\n x_raw_px,\n y_raw_px,\n )\n x_raw_mm, y_raw_mm = detector[panel_id].pixel_to_millimeter(\n (x_raw_px, y_raw_px)\n )\n beam_centre_raw_mm_str = \" mm, raw image: (%.2f,%.2f)\" % (\n x_raw_mm,\n y_raw_mm,\n )\n else:\n beam_centre_mm_str = \" mm: (%.2f,%.2f)\" % (x, y)\n beam_centre_px_str = \" px: (%.2f,%.2f)\" % (x_px, y_px)\n beam_centre_raw_px_str = \"\"\n beam_centre_raw_mm_str = \"\"\n\n s += \"\\nBeam centre: \\n\"\n s += beam_centre_mm_str + \"\\n\" + beam_centre_px_str + \"\\n\"\n if beam_centre_raw_mm_str:\n s += beam_centre_raw_mm_str + \"\\n\"\n if beam_centre_raw_px_str:\n s += beam_centre_raw_px_str + \"\\n\"\n\n # report range of scan-varying model beam centres\n if beam.num_scan_points > 0:\n # get scan-varying beam centres, ensuring all on same panel\n sv_s0 = beam.get_s0_at_scan_points()\n impacts = [beam_centre_mm(detector, s0) for s0 in sv_s0]\n pnl, xy = zip(*impacts)\n uniq_pnls = set(pnl)\n if len(uniq_pnls) > 1 or min(uniq_pnls) < 0:\n return s\n if any(e == (None, None) for e in xy):\n return s\n pnl = list(uniq_pnls)[0]\n x_mm, y_mm = zip(*xy)\n\n # convert to pixels\n xy = [detector[pnl].millimeter_to_pixel(e) for e in xy]\n x_px, y_px = zip(*xy)\n\n s += \"Beam centre range (mm): ([%.2f,%.2f],[%.2f,%.2f])\\n\" % (\n min(x_mm),\n max(x_mm),\n min(y_mm),\n max(y_mm),\n )\n s += \"Beam centre range (px): ([%.2f,%.2f],[%.2f,%.2f])\\n\" % (\n min(x_px),\n max(x_px),\n min(y_px),\n max(y_px),\n )\n\n return s\n\n\ndef show_goniometer(goniometer):\n\n # standard static goniometer model string\n s = str(goniometer)\n\n # report whether the goniometer is scan-varying\n if goniometer.num_scan_points > 0:\n s += (\n \" Setting rotation sampled at \"\n + str(goniometer.num_scan_points)\n + \" scan points\\n\"\n )\n\n return s\n\n\ndef run(args):\n import dials.util.log\n\n dials.util.log.print_banner()\n\n from dials.util.options import OptionParser, reflections_and_experiments_from_files\n\n usage = \"dials.show [options] models.expt | image_*.cbf\"\n\n parser = OptionParser(\n usage=usage,\n phil=phil_scope,\n read_experiments=True,\n read_experiments_from_images=True,\n read_reflections=True,\n check_format=False,\n epilog=help_message,\n )\n\n params, options = parser.parse_args(args=args, show_diff_phil=True)\n reflections, experiments = reflections_and_experiments_from_files(\n params.input.reflections, params.input.experiments\n )\n\n if len(experiments) == 0 and len(reflections) == 0:\n parser.print_help()\n exit()\n\n if len(experiments):\n if not all(e.detector for e in experiments):\n sys.exit(\"Error: experiment has no detector\")\n if not all(e.beam for e in experiments):\n sys.exit(\"Error: experiment has no beam\")\n print(show_experiments(experiments, show_scan_varying=params.show_scan_varying))\n\n if params.image_statistics.show_raw:\n show_image_statistics(experiments, \"raw\")\n\n if params.image_statistics.show_corrected:\n show_image_statistics(experiments, \"corrected\")\n\n if params.show_shared_models:\n print()\n print(model_connectivity(experiments))\n\n if len(reflections):\n print(\n show_reflections(\n reflections,\n show_intensities=params.show_intensities,\n show_profile_fit=params.show_profile_fit,\n show_centroids=params.show_centroids,\n show_all_reflection_data=params.show_all_reflection_data,\n show_flags=params.show_flags,\n max_reflections=params.max_reflections,\n show_identifiers=params.show_identifiers,\n )\n )\n\n\ndef show_experiments(experiments, show_scan_varying=False):\n\n text = []\n for i_expt, expt in enumerate(experiments):\n text.append(\"Experiment %i:\" % i_expt)\n format_class = expt.imageset.get_format_class()\n if format_class.__name__ != \"Format\":\n text.append(\"Format class: %s\" % format_class.__name__)\n if expt.identifier != \"\":\n text.append(\"Experiment identifier: %s\" % expt.identifier)\n try:\n template = expt.imageset.get_template()\n except AttributeError:\n template = None\n if template:\n text.append(\"Image template: %s\" % template)\n text.append(str(expt.detector))\n text.append(\n \"Max resolution (at corners): %f\"\n % (expt.detector.get_max_resolution(expt.beam.get_s0()))\n )\n text.append(\n \"Max resolution (inscribed): %f\"\n % (expt.detector.get_max_inscribed_resolution(expt.beam.get_s0()))\n )\n text.append(\"\")\n text.append(show_beam(expt.detector, expt.beam))\n if expt.scan is not None:\n text.append(str(expt.scan))\n if expt.goniometer is not None:\n text.append(show_goniometer(expt.goniometer))\n\n if expt.crystal is not None:\n text.append(expt.crystal.as_str(show_scan_varying=show_scan_varying))\n if expt.crystal.num_scan_points:\n abc = flex.vec3_double()\n angles = flex.vec3_double()\n for n in range(expt.crystal.num_scan_points):\n (\n a,\n b,\n c,\n alpha,\n beta,\n gamma,\n ) = expt.crystal.get_unit_cell_at_scan_point(n).parameters()\n abc.append((a, b, c))\n angles.append((alpha, beta, gamma))\n a, b, c = abc.mean()\n alpha, beta, gamma = angles.mean()\n mean_unit_cell = uctbx.unit_cell((a, b, c, alpha, beta, gamma))\n text.append(\" Average unit cell: %s\" % mean_unit_cell)\n if expt.profile is not None:\n text.append(str(expt.profile))\n if expt.scaling_model is not None:\n text.append(str(expt.scaling_model))\n\n return \"\\n\".join(text)\n\n\ndef show_image_statistics(experiments, im_type):\n\n if im_type == \"raw\":\n raw = True\n elif im_type == \"corrected\":\n raw = False\n else:\n raise ValueError(\"Unknown im_type: {0}\".format(im_type))\n\n # To show image statistics, check_format has to be true. So we have to reinstatiate\n # the experiment list here\n try:\n experiments = ExperimentListFactory.from_json(\n experiments.as_json(), check_format=True\n )\n except IOError as e:\n raise Sorry(\n \"Unable to read image data. Please check {0} is accessible\".format(\n e.filename\n )\n )\n\n print(\"Five number summary of the {0} images\".format(im_type))\n for i_expt, expt in enumerate(experiments):\n for i in range(len(expt.imageset)):\n identifier = os.path.basename(expt.imageset.get_image_identifier(i))\n if raw:\n pnl_data = expt.imageset.get_raw_data(i)\n else:\n pnl_data = expt.imageset.get_corrected_data(i)\n if not isinstance(pnl_data, tuple):\n pnl_data = (pnl_data,)\n flat_data = pnl_data[0].as_1d()\n for p in pnl_data[1:]:\n flat_data.extend(p.as_1d())\n fns = five_number_summary(flat_data)\n print(\n \"{0}: Min: {1:.1f} Q1: {2:.1f} Med: {3:.1f} Q3: {4:.1f} Max: {5:.1f}\".format(\n identifier, *fns\n )\n )\n\n\ndef model_connectivity(experiments):\n def model_connectivity_impl(experiments, model):\n text = [\"\"]\n text.append(\"%s:\" % model.capitalize())\n models = getattr(experiments, \"%ss\" % model)()\n rows = [[\"\"] + [str(j) for j in range(len(models))]]\n for j, e in enumerate(experiments):\n row = [\"Experiment %d\" % j]\n for m in models:\n if getattr(e, model) is m:\n row.append(\"x\")\n else:\n row.append(\".\")\n rows.append(row)\n text.append(tabulate(rows, tablefmt=\"plain\"))\n return text\n\n if len(experiments) == 1:\n return \"\"\n\n text = []\n text.append(\"Experiment / Models\")\n text.extend(model_connectivity_impl(experiments, \"detector\"))\n text.extend(model_connectivity_impl(experiments, \"crystal\"))\n text.extend(model_connectivity_impl(experiments, \"beam\"))\n\n return \"\\n\".join(text)\n\n\ndef _create_flag_count_table(table):\n \"\"\"Generate a summary table of flag values in a reflection table.\n\n :param table: A reflection table\n :returns: A string of the formatted flags table\n \"\"\"\n\n # Calculate the counts of entries that match each flag\n numpy_flags = table[\"flags\"].as_numpy_array()\n flag_count = {\n flag: np.sum(numpy_flags & value != 0)\n for value, flag in table.flags.values.items()\n }\n\n # Work out the numeric-value order of the flags\n flag_order = sorted(table.flags.values.values(), key=lambda x: x.real)\n\n # Build the actual table\n flag_rows = [[\"Flag\", \"Count\", \"%\"]]\n max_count_len = max(5, len(str(max(flag_count.values()))))\n last_flag = None\n for flag in flag_order:\n indent = \"\"\n # As a hint for reading, indent any 'summary' flags.\n # A summary flag is any flag which overlaps with the previous one.\n if last_flag and (last_flag.real & flag.real):\n indent = \" \"\n last_flag = flag\n # Add the row to the table we're building\n flag_rows.append(\n [\n indent + flag.name,\n \"{:{:d}d}\".format(flag_count[flag], max_count_len),\n \"{:5.01f}\".format(100 * flag_count[flag] / len(table)),\n ]\n )\n\n # Build the array of output strings\n text = []\n text.append(\"Reflection flags:\")\n text.append(tabulate(flag_rows, headers=\"firstrow\"))\n return \"\\n\".join(text)\n\n\ndef show_reflections(\n reflections,\n show_intensities=False,\n show_profile_fit=False,\n show_centroids=False,\n show_all_reflection_data=False,\n show_flags=False,\n max_reflections=None,\n show_identifiers=False,\n):\n\n text = []\n\n from orderedset import OrderedSet\n\n formats = collections.OrderedDict(\n (\n (\"miller_index\", \"%i, %i, %i\"),\n (\"d\", \"%.2f\"),\n (\"qe\", \"%.3f\"),\n (\"dqe\", \"%.3f\"),\n (\"id\", \"%i\"),\n (\"imageset_id\", \"%i\"),\n (\"panel\", \"%i\"),\n (\"flags\", \"%i\"),\n (\"background.mean\", \"%.1f\"),\n (\"background.dispersion\", \"%.1f\"),\n (\"background.mse\", \"%.1f\"),\n (\"background.sum.value\", \"%.1f\"),\n (\"background.sum.variance\", \"%.1f\"),\n (\"intensity.prf.value\", \"%.1f\"),\n (\"intensity.prf.variance\", \"%.1f\"),\n (\"intensity.sum.value\", \"%.1f\"),\n (\"intensity.sum.variance\", \"%.1f\"),\n (\"intensity.cor.value\", \"%.1f\"),\n (\"intensity.cor.variance\", \"%.1f\"),\n (\"intensity.scale.value\", \"%.1f\"),\n (\"intensity.scale.variance\", \"%.1f\"),\n (\"Ih_values\", \"%.1f\"),\n (\"lp\", \"%.3f\"),\n (\"num_pixels.background\", \"%i\"),\n (\"num_pixels.background_used\", \"%i\"),\n (\"num_pixels.foreground\", \"%i\"),\n (\"num_pixels.valid\", \"%i\"),\n (\"partial_id\", \"%i\"),\n (\"partiality\", \"%.4f\"),\n (\"profile.correlation\", \"%.3f\"),\n (\"profile.rmsd\", \"%.3f\"),\n (\"xyzcal.mm\", \"%.2f, %.2f, %.2f\"),\n (\"xyzcal.px\", \"%.2f, %.2f, %.2f\"),\n (\"delpsical.rad\", \"%.3f\"),\n (\"delpsical2\", \"%.3f\"),\n (\"delpsical.weights\", \"%.3f\"),\n (\"xyzobs.mm.value\", \"%.2f, %.2f, %.2f\"),\n (\"xyzobs.mm.variance\", \"%.4e, %.4e, %.4e\"),\n (\"xyzobs.px.value\", \"%.2f, %.2f, %.2f\"),\n (\"xyzobs.px.variance\", \"%.4f, %.4f, %.4f\"),\n (\"s1\", \"%.4f, %.4f, %.4f\"),\n (\"s2\", \"%.4f, %.4f, %.4f\"),\n (\"shoebox\", \"%.1f\"),\n (\"rlp\", \"%.4f, %.4f, %.4f\"),\n (\"zeta\", \"%.3f\"),\n (\"x_resid\", \"%.3f\"),\n (\"x_resid2\", \"%.3f\"),\n (\"y_resid\", \"%.3f\"),\n (\"y_resid2\", \"%.3f\"),\n (\"kapton_absorption_correction\", \"%.3f\"),\n (\"kapton_absorption_correction_sigmas\", \"%.3f\"),\n (\"inverse_scale_factor\", \"%.3f\"),\n (\"inverse_scale_factor_variance\", \"%.3f\"),\n )\n )\n\n for rlist in reflections:\n from dials.algorithms.shoebox import MaskCode\n\n foreground_valid = MaskCode.Valid | MaskCode.Foreground\n text.append(\"\")\n text.append(\"Reflection list contains %i reflections\" % (len(rlist)))\n\n if len(rlist) == 0:\n continue\n\n rows = [[\"Column\", \"min\", \"max\", \"mean\"]]\n for k, col in rlist.cols():\n if k in formats and \"%\" not in formats.get(k, \"%s\"):\n # Allow blanking out of entries that wouldn't make sense\n rows.append(\n [\n k,\n formats.get(k, \"%s\"),\n formats.get(k, \"%s\"),\n formats.get(k, \"%s\"),\n ]\n )\n elif type(col) in (flex.double, flex.int, flex.size_t):\n if type(col) in (flex.int, flex.size_t):\n col = col.as_double()\n rows.append(\n [\n k,\n formats.get(k, \"%s\") % flex.min(col),\n formats.get(k, \"%s\") % flex.max(col),\n formats.get(k, \"%s\") % flex.mean(col),\n ]\n )\n elif type(col) in (flex.vec3_double, flex.miller_index):\n if isinstance(col, flex.miller_index):\n col = col.as_vec3_double()\n rows.append(\n [\n k,\n formats.get(k, \"%s\") % col.min(),\n formats.get(k, \"%s\") % col.max(),\n formats.get(k, \"%s\") % col.mean(),\n ]\n )\n elif isinstance(col, flex.shoebox):\n rows.append([k, \"\", \"\", \"\"])\n si = col.summed_intensity().observed_value()\n rows.append(\n [\n \" summed I\",\n formats.get(k, \"%s\") % flex.min(si),\n formats.get(k, \"%s\") % flex.max(si),\n formats.get(k, \"%s\") % flex.mean(si),\n ]\n )\n x1, x2, y1, y2, z1, z2 = col.bounding_boxes().parts()\n bbox_sizes = ((z2 - z1) * (y2 - y1) * (x2 - x1)).as_double()\n rows.append(\n [\n \" N pix\",\n formats.get(k, \"%s\") % flex.min(bbox_sizes),\n formats.get(k, \"%s\") % flex.max(bbox_sizes),\n formats.get(k, \"%s\") % flex.mean(bbox_sizes),\n ]\n )\n fore_valid = col.count_mask_values(foreground_valid).as_double()\n rows.append(\n [\n \" N valid foreground pix\",\n formats.get(k, \"%s\") % flex.min(fore_valid),\n formats.get(k, \"%s\") % flex.max(fore_valid),\n formats.get(k, \"%s\") % flex.mean(fore_valid),\n ]\n )\n\n text.append(tabulate(rows, headers=\"firstrow\"))\n\n if show_flags:\n text.append(_create_flag_count_table(rlist))\n\n if show_identifiers:\n if rlist.experiment_identifiers():\n text.append(\n \"\"\"Experiment identifiers id-map values:\\n%s\"\"\"\n % (\n \"\\n\".join(\n \"id:\"\n + str(k)\n + \" -> experiment identifier:\"\n + str(rlist.experiment_identifiers()[k])\n for k in rlist.experiment_identifiers().keys()\n )\n )\n )\n\n intensity_keys = (\n \"miller_index\",\n \"d\",\n \"intensity.prf.value\",\n \"intensity.prf.variance\",\n \"intensity.sum.value\",\n \"intensity.sum.variance\",\n \"background.mean\",\n \"profile.correlation\",\n \"profile.rmsd\",\n )\n\n profile_fit_keys = (\"miller_index\", \"d\")\n\n centroid_keys = (\n \"miller_index\",\n \"d\",\n \"xyzcal.mm\",\n \"xyzcal.px\",\n \"xyzobs.mm.value\",\n \"xyzobs.mm.variance\",\n \"xyzobs.px.value\",\n \"xyzobs.px.variance\",\n )\n\n keys_to_print = OrderedSet()\n\n if show_intensities:\n for k in intensity_keys:\n keys_to_print.add(k)\n if show_profile_fit:\n for k in profile_fit_keys:\n keys_to_print.add(k)\n if show_centroids:\n for k in centroid_keys:\n keys_to_print.add(k)\n if show_all_reflection_data:\n for k in formats:\n keys_to_print.add(k)\n\n def format_column(key, data, format_strings=None):\n if isinstance(data, flex.vec3_double):\n c_strings = [\n c.as_string(format_strings[i].strip())\n for i, c in enumerate(data.parts())\n ]\n elif isinstance(data, flex.miller_index):\n c_strings = [\n c.as_string(format_strings[i].strip())\n for i, c in enumerate(data.as_vec3_double().parts())\n ]\n elif isinstance(data, flex.size_t):\n c_strings = [data.as_int().as_string(format_strings[0].strip())]\n elif isinstance(data, flex.shoebox):\n x1, x2, y1, y2, z1, z2 = data.bounding_boxes().parts()\n bbox_sizes = ((z2 - z1) * (y2 - y1) * (x2 - x1)).as_double()\n c_strings = [bbox_sizes.as_string(format_strings[0].strip())]\n key += \" (N pix)\"\n else:\n c_strings = [data.as_string(format_strings[0].strip())]\n\n column = flex.std_string()\n max_element_lengths = [c.max_element_length() for c in c_strings]\n for i in range(len(c_strings[0])):\n\n column.append(\n (\"%%%is\" % len(key))\n % \", \".join(\n (\"%%%is\" % max_element_lengths[j]) % c_strings[j][i]\n for j in range(len(c_strings))\n )\n )\n return column\n\n if keys_to_print:\n keys = [k for k in keys_to_print if k in rlist]\n if max_reflections is not None:\n max_reflections = min(len(rlist), max_reflections)\n else:\n max_reflections = len(rlist)\n\n columns = []\n\n for k in keys:\n columns.append(\n format_column(k, rlist[k], format_strings=formats[k].split(\",\"))\n )\n\n text.append(\"\")\n text.append(\"Printing %i of %i reflections:\" % (max_reflections, len(rlist)))\n line = []\n for j in range(len(columns)):\n key = keys[j]\n if key == \"shoebox\":\n key += \" (N pix)\"\n width = max(len(key), columns[j].max_element_length())\n line.append(\"%%%is\" % width % key)\n text.append(\" \".join(line))\n for i in range(max_reflections):\n line = (c[i] for c in columns)\n text.append(\" \".join(line))\n\n return \"\\n\".join(text)\n\n\nif __name__ == \"__main__\":\n import sys\n\n run(sys.argv[1:])\n" ]
[ [ "numpy.sum" ] ]
dme65/botorch
[ "508f215bfe987373924e39444c8fb544d5132178" ]
[ "test/acquisition/test_monte_carlo.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport warnings\nfrom unittest import mock\n\nimport torch\nfrom botorch import settings\nfrom botorch.acquisition.monte_carlo import (\n MCAcquisitionFunction,\n qExpectedImprovement,\n qNoisyExpectedImprovement,\n qProbabilityOfImprovement,\n qSimpleRegret,\n qUpperConfidenceBound,\n)\nfrom botorch.acquisition.objective import ScalarizedObjective\nfrom botorch.exceptions import BotorchWarning, UnsupportedError\nfrom botorch.sampling.samplers import IIDNormalSampler, SobolQMCNormalSampler\nfrom botorch.utils.testing import BotorchTestCase, MockModel, MockPosterior\n\n\nclass DummyMCAcquisitionFunction(MCAcquisitionFunction):\n def forward(self, X):\n pass\n\n\nclass TestMCAcquisitionFunction(BotorchTestCase):\n def test_abstract_raises(self):\n with self.assertRaises(TypeError):\n MCAcquisitionFunction()\n # raise if model is multi-output, but no objective is given\n no = \"botorch.utils.testing.MockModel.num_outputs\"\n with mock.patch(no, new_callable=mock.PropertyMock) as mock_num_outputs:\n mock_num_outputs.return_value = 2\n mm = MockModel(MockPosterior())\n with self.assertRaises(UnsupportedError):\n DummyMCAcquisitionFunction(model=mm)\n\n\nclass TestQExpectedImprovement(BotorchTestCase):\n def test_q_expected_improvement(self):\n for dtype in (torch.float, torch.double):\n # the event shape is `b x q x t` = 1 x 1 x 1\n samples = torch.zeros(1, 1, 1, device=self.device, dtype=dtype)\n mm = MockModel(MockPosterior(samples=samples))\n # X is `q x d` = 1 x 1. X is a dummy and unused b/c of mocking\n X = torch.zeros(1, 1, device=self.device, dtype=dtype)\n\n # basic test\n sampler = IIDNormalSampler(num_samples=2)\n acqf = qExpectedImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n\n # test shifting best_f value\n acqf = qExpectedImprovement(model=mm, best_f=-1, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 1.0)\n\n # TODO: Test batched best_f, batched model, batched evaluation\n\n # basic test, no resample\n sampler = IIDNormalSampler(num_samples=2, seed=12345)\n acqf = qExpectedImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n res = acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test, qmc, no resample\n sampler = SobolQMCNormalSampler(num_samples=2)\n acqf = qExpectedImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test, qmc, resample\n sampler = SobolQMCNormalSampler(num_samples=2, resample=True)\n acqf = qExpectedImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test for X_pending and warning\n acqf.set_X_pending()\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(None)\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(X)\n self.assertEqual(acqf.X_pending, X)\n res = acqf(X)\n X2 = torch.zeros(\n 1, 1, 1, device=self.device, dtype=dtype, requires_grad=True\n )\n with warnings.catch_warnings(record=True) as ws, settings.debug(True):\n acqf.set_X_pending(X2)\n self.assertEqual(acqf.X_pending, X2)\n self.assertEqual(len(ws), 1)\n self.assertTrue(issubclass(ws[-1].category, BotorchWarning))\n\n # test bad objective type\n obj = ScalarizedObjective(\n weights=torch.rand(2, device=self.device, dtype=dtype)\n )\n with self.assertRaises(UnsupportedError):\n qExpectedImprovement(model=mm, best_f=0, sampler=sampler, objective=obj)\n\n def test_q_expected_improvement_batch(self):\n for dtype in (torch.float, torch.double):\n # the event shape is `b x q x t` = 2 x 2 x 1\n samples = torch.zeros(2, 2, 1, device=self.device, dtype=dtype)\n samples[0, 0, 0] = 1.0\n mm = MockModel(MockPosterior(samples=samples))\n\n # X is a dummy and unused b/c of mocking\n X = torch.zeros(2, 1, 1, device=self.device, dtype=dtype)\n\n # test batch mode\n sampler = IIDNormalSampler(num_samples=2)\n acqf = qExpectedImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n\n # test shifting best_f value\n acqf = qExpectedImprovement(model=mm, best_f=-1, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res[0].item(), 2.0)\n self.assertEqual(res[1].item(), 1.0)\n\n # test batch mode, no resample\n sampler = IIDNormalSampler(num_samples=2, seed=12345)\n acqf = qExpectedImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X) # 1-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n res = acqf(X.expand(2, 1, 1)) # 2-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n # the base samples should have the batch dim collapsed\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X.expand(2, 1, 1))\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # test batch mode, qmc, no resample\n sampler = SobolQMCNormalSampler(num_samples=2)\n acqf = qExpectedImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # test batch mode, qmc, resample\n sampler = SobolQMCNormalSampler(num_samples=2, resample=True)\n acqf = qExpectedImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X) # 1-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n res = acqf(X.expand(2, 1, 1)) # 2-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n # the base samples should have the batch dim collapsed\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X.expand(2, 1, 1))\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n\n # TODO: Test different objectives (incl. constraints)\n\n\nclass TestQNoisyExpectedImprovement(BotorchTestCase):\n def test_q_noisy_expected_improvement(self):\n for dtype in (torch.float, torch.double):\n # the event shape is `b x q x t` = 1 x 2 x 1\n samples_noisy = torch.tensor([1.0, 0.0], device=self.device, dtype=dtype)\n samples_noisy = samples_noisy.view(1, 2, 1)\n # X_baseline is `q' x d` = 1 x 1\n X_baseline = torch.zeros(1, 1, device=self.device, dtype=dtype)\n mm_noisy = MockModel(MockPosterior(samples=samples_noisy))\n # X is `q x d` = 1 x 1\n X = torch.zeros(1, 1, device=self.device, dtype=dtype)\n\n # basic test\n sampler = IIDNormalSampler(num_samples=2)\n acqf = qNoisyExpectedImprovement(\n model=mm_noisy, X_baseline=X_baseline, sampler=sampler\n )\n res = acqf(X)\n self.assertEqual(res.item(), 1.0)\n\n # basic test, no resample\n sampler = IIDNormalSampler(num_samples=2, seed=12345)\n acqf = qNoisyExpectedImprovement(\n model=mm_noisy, X_baseline=X_baseline, sampler=sampler\n )\n res = acqf(X)\n self.assertEqual(res.item(), 1.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test, qmc, no resample\n sampler = SobolQMCNormalSampler(num_samples=2)\n acqf = qNoisyExpectedImprovement(\n model=mm_noisy, X_baseline=X_baseline, sampler=sampler\n )\n res = acqf(X)\n self.assertEqual(res.item(), 1.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test, qmc, resample\n sampler = SobolQMCNormalSampler(num_samples=2, resample=True, seed=12345)\n acqf = qNoisyExpectedImprovement(\n model=mm_noisy, X_baseline=X_baseline, sampler=sampler\n )\n res = acqf(X)\n self.assertEqual(res.item(), 1.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test for X_pending and warning\n sampler = SobolQMCNormalSampler(num_samples=2)\n samples_noisy_pending = torch.tensor(\n [1.0, 0.0, 0.0], device=self.device, dtype=dtype\n )\n samples_noisy_pending = samples_noisy_pending.view(1, 3, 1)\n mm_noisy_pending = MockModel(MockPosterior(samples=samples_noisy_pending))\n acqf = qNoisyExpectedImprovement(\n model=mm_noisy_pending, X_baseline=X_baseline, sampler=sampler\n )\n acqf.set_X_pending()\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(None)\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(X)\n self.assertEqual(acqf.X_pending, X)\n res = acqf(X)\n X2 = torch.zeros(\n 1, 1, 1, device=self.device, dtype=dtype, requires_grad=True\n )\n with warnings.catch_warnings(record=True) as ws, settings.debug(True):\n acqf.set_X_pending(X2)\n self.assertEqual(acqf.X_pending, X2)\n self.assertEqual(len(ws), 1)\n self.assertTrue(issubclass(ws[-1].category, BotorchWarning))\n\n def test_q_noisy_expected_improvement_batch(self):\n for dtype in (torch.float, torch.double):\n # the event shape is `b x q x t` = 2 x 3 x 1\n samples_noisy = torch.zeros(2, 3, 1, device=self.device, dtype=dtype)\n samples_noisy[0, 0, 0] = 1.0\n mm_noisy = MockModel(MockPosterior(samples=samples_noisy))\n # X is `q x d` = 1 x 1\n X = torch.zeros(2, 1, 1, device=self.device, dtype=dtype)\n X_baseline = torch.zeros(1, 1, device=self.device, dtype=dtype)\n\n # test batch mode\n sampler = IIDNormalSampler(num_samples=2)\n acqf = qNoisyExpectedImprovement(\n model=mm_noisy, X_baseline=X_baseline, sampler=sampler\n )\n res = acqf(X)\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n\n # test batch mode, no resample\n sampler = IIDNormalSampler(num_samples=2, seed=12345)\n acqf = qNoisyExpectedImprovement(\n model=mm_noisy, X_baseline=X_baseline, sampler=sampler\n )\n res = acqf(X) # 1-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 3, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n res = acqf(X.expand(2, 1, 1)) # 2-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n # the base samples should have the batch dim collapsed\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 3, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X.expand(2, 1, 1))\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # test batch mode, qmc, no resample\n sampler = SobolQMCNormalSampler(num_samples=2)\n acqf = qNoisyExpectedImprovement(\n model=mm_noisy, X_baseline=X_baseline, sampler=sampler\n )\n res = acqf(X)\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 3, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # test X_pending w/ batch mode, qmc, resample\n sampler = SobolQMCNormalSampler(num_samples=2, resample=True, seed=12345)\n acqf = qNoisyExpectedImprovement(\n model=mm_noisy, X_baseline=X_baseline, sampler=sampler\n )\n res = acqf(X) # 1-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 3, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n res = acqf(X.expand(2, 1, 1)) # 2-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n # the base samples should have the batch dim collapsed\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 3, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X.expand(2, 1, 1))\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n\n def test_prune_baseline(self):\n no = \"botorch.utils.testing.MockModel.num_outputs\"\n prune = \"botorch.acquisition.monte_carlo.prune_inferior_points\"\n for dtype in (torch.float, torch.double):\n X_baseline = torch.zeros(1, 1, device=self.device, dtype=dtype)\n X_pruned = torch.rand(1, 1, device=self.device, dtype=dtype)\n with mock.patch(no, new_callable=mock.PropertyMock) as mock_num_outputs:\n mock_num_outputs.return_value = 1\n mm = MockModel(mock.Mock())\n with mock.patch(prune, return_value=X_pruned) as mock_prune:\n acqf = qNoisyExpectedImprovement(\n model=mm, X_baseline=X_baseline, prune_baseline=True\n )\n mock_prune.assert_called_once()\n self.assertTrue(torch.equal(acqf.X_baseline, X_pruned))\n\n # TODO: Test different objectives (incl. constraints)\n\n\nclass TestQProbabilityOfImprovement(BotorchTestCase):\n def test_q_probability_of_improvement(self):\n for dtype in (torch.float, torch.double):\n # the event shape is `b x q x t` = 1 x 1 x 1\n samples = torch.zeros(1, 1, 1, device=self.device, dtype=dtype)\n mm = MockModel(MockPosterior(samples=samples))\n # X is `q x d` = 1 x 1. X is a dummy and unused b/c of mocking\n X = torch.zeros(1, 1, device=self.device, dtype=dtype)\n\n # basic test\n sampler = IIDNormalSampler(num_samples=2)\n acqf = qProbabilityOfImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.5)\n\n # basic test, no resample\n sampler = IIDNormalSampler(num_samples=2, seed=12345)\n acqf = qProbabilityOfImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.5)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n res = acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test, qmc, no resample\n sampler = SobolQMCNormalSampler(num_samples=2)\n acqf = qProbabilityOfImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.5)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test, qmc, resample\n sampler = SobolQMCNormalSampler(num_samples=2, resample=True)\n acqf = qProbabilityOfImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.5)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test for X_pending and warning\n acqf.set_X_pending()\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(None)\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(X)\n self.assertEqual(acqf.X_pending, X)\n res = acqf(X)\n X2 = torch.zeros(\n 1, 1, 1, device=self.device, dtype=dtype, requires_grad=True\n )\n with warnings.catch_warnings(record=True) as ws, settings.debug(True):\n acqf.set_X_pending(X2)\n self.assertEqual(acqf.X_pending, X2)\n self.assertEqual(len(ws), 1)\n self.assertTrue(issubclass(ws[-1].category, BotorchWarning))\n\n def test_q_probability_of_improvement_batch(self):\n # the event shape is `b x q x t` = 2 x 2 x 1\n for dtype in (torch.float, torch.double):\n samples = torch.zeros(2, 2, 1, device=self.device, dtype=dtype)\n samples[0, 0, 0] = 1.0\n mm = MockModel(MockPosterior(samples=samples))\n\n # X is a dummy and unused b/c of mocking\n X = torch.zeros(2, 1, 1, device=self.device, dtype=dtype)\n\n # test batch mode\n sampler = IIDNormalSampler(num_samples=2)\n acqf = qProbabilityOfImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.5)\n\n # test batch mode, no resample\n sampler = IIDNormalSampler(num_samples=2, seed=12345)\n acqf = qProbabilityOfImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X) # 1-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.5)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n res = acqf(X.expand(2, 1, 1)) # 2-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.5)\n # the base samples should have the batch dim collapsed\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X.expand(2, 1, 1))\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # test batch mode, qmc, no resample\n sampler = SobolQMCNormalSampler(num_samples=2)\n acqf = qProbabilityOfImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.5)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # test batch mode, qmc, resample\n sampler = SobolQMCNormalSampler(num_samples=2, resample=True)\n acqf = qProbabilityOfImprovement(model=mm, best_f=0, sampler=sampler)\n res = acqf(X) # 1-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.5)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n res = acqf(X.expand(2, 1, 1)) # 2-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.5)\n # the base samples should have the batch dim collapsed\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X.expand(2, 1, 1))\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n\n # TODO: Test different objectives (incl. constraints)\n\n\nclass TestQSimpleRegret(BotorchTestCase):\n def test_q_simple_regret(self):\n for dtype in (torch.float, torch.double):\n # the event shape is `b x q x t` = 1 x 1 x 1\n samples = torch.zeros(1, 1, 1, device=self.device, dtype=dtype)\n mm = MockModel(MockPosterior(samples=samples))\n # X is `q x d` = 1 x 1. X is a dummy and unused b/c of mocking\n X = torch.zeros(1, 1, device=self.device, dtype=dtype)\n\n # basic test\n sampler = IIDNormalSampler(num_samples=2)\n acqf = qSimpleRegret(model=mm, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n\n # basic test, no resample\n sampler = IIDNormalSampler(num_samples=2, seed=12345)\n acqf = qSimpleRegret(model=mm, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n res = acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test, qmc, no resample\n sampler = SobolQMCNormalSampler(num_samples=2)\n acqf = qSimpleRegret(model=mm, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test, qmc, resample\n sampler = SobolQMCNormalSampler(num_samples=2, resample=True)\n acqf = qSimpleRegret(model=mm, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test for X_pending and warning\n acqf.set_X_pending()\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(None)\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(X)\n self.assertEqual(acqf.X_pending, X)\n res = acqf(X)\n X2 = torch.zeros(\n 1, 1, 1, device=self.device, dtype=dtype, requires_grad=True\n )\n with warnings.catch_warnings(record=True) as ws, settings.debug(True):\n acqf.set_X_pending(X2)\n self.assertEqual(acqf.X_pending, X2)\n self.assertEqual(len(ws), 1)\n self.assertTrue(issubclass(ws[-1].category, BotorchWarning))\n\n def test_q_simple_regret_batch(self):\n # the event shape is `b x q x t` = 2 x 2 x 1\n for dtype in (torch.float, torch.double):\n samples = torch.zeros(2, 2, 1, device=self.device, dtype=dtype)\n samples[0, 0, 0] = 1.0\n mm = MockModel(MockPosterior(samples=samples))\n # X is a dummy and unused b/c of mocking\n X = torch.zeros(2, 1, 1, device=self.device, dtype=dtype)\n\n # test batch mode\n sampler = IIDNormalSampler(num_samples=2)\n acqf = qSimpleRegret(model=mm, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n\n # test batch mode, no resample\n sampler = IIDNormalSampler(num_samples=2, seed=12345)\n acqf = qSimpleRegret(model=mm, sampler=sampler)\n res = acqf(X) # 1-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n res = acqf(X.expand(2, 1, 1)) # 2-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n # the base samples should have the batch dim collapsed\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X.expand(2, 1, 1))\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # test batch mode, qmc, no resample\n sampler = SobolQMCNormalSampler(num_samples=2)\n acqf = qSimpleRegret(model=mm, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # test batch mode, qmc, resample\n sampler = SobolQMCNormalSampler(num_samples=2, resample=True)\n acqf = qSimpleRegret(model=mm, sampler=sampler)\n res = acqf(X) # 1-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n res = acqf(X.expand(2, 1, 1)) # 2-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n # the base samples should have the batch dim collapsed\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X.expand(2, 1, 1))\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n\n # TODO: Test different objectives (incl. constraints)\n\n\nclass TestQUpperConfidenceBound(BotorchTestCase):\n def test_q_upper_confidence_bound(self):\n for dtype in (torch.float, torch.double):\n # the event shape is `b x q x t` = 1 x 1 x 1\n samples = torch.zeros(1, 1, 1, device=self.device, dtype=dtype)\n mm = MockModel(MockPosterior(samples=samples))\n # X is `q x d` = 1 x 1. X is a dummy and unused b/c of mocking\n X = torch.zeros(1, 1, device=self.device, dtype=dtype)\n\n # basic test\n sampler = IIDNormalSampler(num_samples=2)\n acqf = qUpperConfidenceBound(model=mm, beta=0.5, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n\n # basic test, no resample\n sampler = IIDNormalSampler(num_samples=2, seed=12345)\n acqf = qUpperConfidenceBound(model=mm, beta=0.5, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n res = acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test, qmc, no resample\n sampler = SobolQMCNormalSampler(num_samples=2)\n acqf = qUpperConfidenceBound(model=mm, beta=0.5, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test, qmc, resample\n sampler = SobolQMCNormalSampler(num_samples=2, resample=True)\n acqf = qUpperConfidenceBound(model=mm, beta=0.5, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res.item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 1, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test for X_pending and warning\n acqf.set_X_pending()\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(None)\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(X)\n self.assertEqual(acqf.X_pending, X)\n res = acqf(X)\n X2 = torch.zeros(\n 1, 1, 1, device=self.device, dtype=dtype, requires_grad=True\n )\n with warnings.catch_warnings(record=True) as ws, settings.debug(True):\n acqf.set_X_pending(X2)\n self.assertEqual(acqf.X_pending, X2)\n self.assertEqual(len(ws), 1)\n self.assertTrue(issubclass(ws[-1].category, BotorchWarning))\n\n def test_q_upper_confidence_bound_batch(self):\n # TODO: T41739913 Implement tests for all MCAcquisitionFunctions\n for dtype in (torch.float, torch.double):\n samples = torch.zeros(2, 2, 1, device=self.device, dtype=dtype)\n samples[0, 0, 0] = 1.0\n mm = MockModel(MockPosterior(samples=samples))\n # X is a dummy and unused b/c of mocking\n X = torch.zeros(2, 1, 1, device=self.device, dtype=dtype)\n\n # test batch mode\n sampler = IIDNormalSampler(num_samples=2)\n acqf = qUpperConfidenceBound(model=mm, beta=0.5, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n\n # test batch mode, no resample\n sampler = IIDNormalSampler(num_samples=2, seed=12345)\n acqf = qUpperConfidenceBound(model=mm, beta=0.5, sampler=sampler)\n res = acqf(X) # 1-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n res = acqf(X.expand(2, 1, 1)) # 2-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n # the base samples should have the batch dim collapsed\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X.expand(2, 1, 1))\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # test batch mode, qmc, no resample\n sampler = SobolQMCNormalSampler(num_samples=2)\n acqf = qUpperConfidenceBound(model=mm, beta=0.5, sampler=sampler)\n res = acqf(X)\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertTrue(torch.equal(acqf.sampler.base_samples, bs))\n\n # test batch mode, qmc, resample\n sampler = SobolQMCNormalSampler(num_samples=2, resample=True)\n acqf = qUpperConfidenceBound(model=mm, beta=0.5, sampler=sampler)\n res = acqf(X) # 1-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X)\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n res = acqf(X.expand(2, 1, 1)) # 2-dim batch\n self.assertEqual(res[0].item(), 1.0)\n self.assertEqual(res[1].item(), 0.0)\n # the base samples should have the batch dim collapsed\n self.assertEqual(acqf.sampler.base_samples.shape, torch.Size([2, 1, 2, 1]))\n bs = acqf.sampler.base_samples.clone()\n acqf(X.expand(2, 1, 1))\n self.assertFalse(torch.equal(acqf.sampler.base_samples, bs))\n\n # basic test for X_pending and warning\n acqf.set_X_pending()\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(None)\n self.assertIsNone(acqf.X_pending)\n acqf.set_X_pending(X)\n self.assertTrue(torch.equal(acqf.X_pending, X))\n res = acqf(X)\n X2 = torch.zeros(\n 1, 1, 1, device=self.device, dtype=dtype, requires_grad=True\n )\n with warnings.catch_warnings(record=True) as ws, settings.debug(True):\n acqf.set_X_pending(X2)\n self.assertEqual(acqf.X_pending, X2)\n self.assertEqual(len(ws), 1)\n self.assertTrue(issubclass(ws[-1].category, BotorchWarning))\n\n # TODO: Test different objectives (incl. constraints)\n" ]
[ [ "torch.Size", "torch.rand", "torch.tensor", "torch.equal", "torch.zeros" ] ]
ESMWG/noahmp-tools
[ "818b6d874f2981098dd3ad1ee239c88ee4743892" ]
[ "noahmp_ldasout2cf.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# convert NoahMP outputs to CF-compatible files\n\n\nimport sys\nimport os\nimport glob\nimport datetime\nimport argparse\nimport dateutil.parser\nimport numpy as np\nimport netCDF4 as nc\nnp.seterr(invalid='ignore')\n\n\nTDIM = 'time'\nTVAR = 'TIMES'\ntimeunits = 'hours since 1900-01-01'\nXDIM = 'west_east'\nXVAR = 'WEST_EAST'\nYDIM = 'south_north'\nYVAR = 'SOUTH_NORTH'\nACCVARS = ['ACSNOW', 'ACSNOM', 'SFCRNOFF', 'UGDRNOFF']\nVALIDMIN = -1e10\n\ndef datetime4name(filename):\n timestr = os.path.basename(filename).split('.')[0]\n return datetime.datetime.strptime(timestr, '%Y%m%d%H')\n\ndef source_info(datadir, begtime, endtime):\n allfiles = sorted(glob.glob(os.path.join(datadir, '*.LDASOUT_DOMAIN1')))\n files = [x for x in allfiles\n if datetime4name(x) >= begtime and datetime4name(x) < endtime]\n timestep = 0\n integrity = False\n if len(files) > 1:\n timesteps = set()\n for ifile in range(1,len(files)):\n timesteps.add((datetime4name(files[ifile]) - datetime4name(files[ifile-1])).total_seconds())\n timestep = timesteps.pop()\n if len(timesteps) == 0 \\\n and ((datetime4name(files[0]) - begtime).total_seconds() < timestep) \\\n and ((endtime - datetime4name(files[-1])).total_seconds() <= timestep):\n integrity = True\n return files, timestep, integrity\n\ndef define_output(wrfinput, fi, fo):\n # inquire spatial dimension from wrfinput\n with nc.Dataset(wrfinput, 'r') as fwrf:\n if fwrf.MAP_PROJ == 6:\n lat2d = np.squeeze(fwrf.variables['XLAT'][:])\n lon2d = np.squeeze(fwrf.variables['XLONG'][:])\n lat = lat2d[:,0]\n lon = lon2d[0,:]\n else:\n lat = None\n lon = None\n # create Dimension\n dimset = set()\n for var in fi.variables:\n if var.upper() in [TVAR, XVAR, YVAR]:\n continue\n dimset.update((x.lower() for x in fi.variables[var].dimensions))\n for dim in dimset:\n if dim == TDIM:\n fo.createDimension(dim, None)\n else:\n fo.createDimension(dim, len(fi.dimensions[dim]))\n # create vars\n fo.createVariable(XDIM, 'f', (XDIM,), zlib=True, complevel=6)\n fo.variables[XDIM].standard_name = 'longitude'.encode('ascii')\n fo.variables[XDIM].units = 'degree_east'.encode('ascii')\n fo.variables[XDIM].axis = 'X'.encode('ascii')\n fo.variables[XDIM][:] = lon\n fo.createVariable(YDIM, 'f', (YDIM,), zlib=True, complevel=6)\n fo.variables[YDIM].standard_name = 'latitude'.encode('ascii')\n fo.variables[YDIM].units = 'degree_north'.encode('ascii')\n fo.variables[YDIM].axis = 'Y'.encode('ascii')\n fo.variables[YDIM][:] = lat\n for var in fi.variables:\n if var.upper() == TVAR:\n fo.createVariable(TDIM, 'f8', (TDIM,), zlib=True, complevel=6)\n fo.variables[TDIM].standard_name = 'time'.encode('ascii')\n fo.variables[TDIM].units = timeunits.encode('ascii')\n fo.variables[TDIM].calendar = 'standard'.encode('ascii')\n fo.variables[TDIM].axis = 'T'.encode('ascii')\n elif var.upper() in set([XVAR, YVAR]):\n pass\n elif var.upper() not in ACCVARS:\n dtype = fi.variables[var].dtype\n dims = [x.lower() for x in fi.variables[var].dimensions]\n dims_n = []\n if TDIM in dims:\n dims.remove(TDIM)\n dims_n.append(TDIM)\n if YDIM in dims:\n dims.remove(YDIM)\n dims_n.append(YDIM)\n if XDIM in dims:\n dims.remove(XDIM)\n dims_n.append(XDIM)\n if len(dims) > 1:\n print(\"don't support multiple z-axis: \" + str(dims) + ' of ' + var)\n sys.exit(1)\n elif len(dims) == 1:\n zdim = dims[0]\n dims_n.insert(1, zdim)\n if np.issubdtype(dtype, np.float):\n fo.createVariable(var, dtype, dims_n,\n zlib=True, complevel=6, fill_value=np.nan)\n else:\n fo.createVariable(var, dtype, dims_n, zlib=True, complevel=6)\n for att in fi.variables[var].ncattrs():\n attval = fi.variables[var].getncattr(att)\n if isinstance(fi.variables[var].getncattr(att), str):\n attval = attval.encode('ascii')\n fo.variables[var].setncattr(att, attval)\n else: # ACCVARS\n dtype = fi.variables[var].dtype\n dims = [x.lower() for x in fi.variables[var].dimensions]\n if np.issubdtype(dtype, np.float):\n fo.createVariable(var, dtype, dims_n,\n zlib=True, complevel=6, fill_value=np.nan)\n else:\n fo.createVariable(var, dtype, dims_n, zlib=True, complevel=6)\n for att in fi.variables[var].ncattrs():\n attval = fi.variables[var].getncattr(att)\n if att.lower() == 'units':\n attval = (attval + ' s-1').encode('ascii')\n elif att.lower() == 'description':\n attval = attval.lower().replace('accumulated ', '').replace('accumulatetd ','').encode('ascii')\n elif isinstance(fi.variables[var].getncattr(att), str):\n attval = attval.encode('ascii')\n fo.variables[var].setncattr(att, attval)\n for att in fi.ncattrs():\n if isinstance(fi.getncattr(att), str):\n fo.setncattr(att, fi.getncattr(att).encode('ascii'))\n else:\n fo.setncattr(att, fi.getncattr(att))\n return\n\ndef copy_var(fi, fo, var, ind):\n if var.lower() in [TDIM, XDIM, YDIM] \\\n or var.upper() in [TVAR, XVAR, YVAR] \\\n or var.upper() in ACCVARS:\n return\n # mask invalid value\n fi.variables[var].set_auto_maskandscale(False)\n fo.variables[var].set_auto_maskandscale(False)\n v = fi.variables[var][:]\n\n if np.issubdtype(fi.variables[var].dtype, np.float):\n v[v <= VALIDMIN] = np.nan\n\n # swap dimension\n dims = [x.lower() for x in fi.variables[var].dimensions]\n zdim = set(dims) - set([TDIM, XDIM, YDIM])\n if len(zdim) == 1:\n zdim = zdim.pop()\n v = np.swapaxes(v, dims.index(zdim), 1)\n fo.variables[var][ind,...] = v\n return\n\ndef acc2flx(fic, fip, fo, var, ind, ts):\n if var.upper() not in ACCVARS:\n return\n fic.variables[var].set_auto_maskandscale(False)\n fip.variables[var].set_auto_maskandscale(False)\n fo.variables[var].set_auto_maskandscale(False)\n vc = fic.variables[var][:]\n vp = fip.variables[var][:]\n vc[vc <= VALIDMIN] = np.nan\n vp[vp <= VALIDMIN] = np.nan\n fo.variables[var][ind,...] = (vc - vp) / ts\n return\n\ndef main(wrfinput, datadir, outfile, begtime, endtime, partially=False):\n files, timestep, integrity = source_info(datadir, begtime, endtime)\n if (not integrity) and (not partially):\n print('not enough files (try --partially)')\n sys.exit(1)\n with nc.Dataset(outfile, 'w') as fo:\n for ifile in range(len(files)):\n print(files[ifile])\n with nc.Dataset(files[ifile], 'r') as fi:\n if ifile == 0:\n define_output(wrfinput, fi, fo)\n fo.variables[TDIM][ifile] = nc.date2num(datetime4name(files[ifile]),\n fo.variables[TDIM].units)\n for var in fi.variables:\n if var.upper() in ACCVARS:\n continue\n copy_var(fi, fo, var, ifile)\n print('acc to flux')\n for ifile in reversed(range(1,len(files))):\n with nc.Dataset(files[ifile], 'r') as fic, \\\n nc.Dataset(files[ifile-1], 'r') as fip:\n for var in ACCVARS:\n acc2flx(fic, fip, fo, var, ifile, timestep)\n startfile = os.path.join(datadir,\n (datetime4name(files[0]) - datetime.timedelta(seconds=timestep)).strftime('%Y%m%d%H') + '.LDASOUT_DOMAIN1')\n if os.path.exists(startfile):\n with nc.Dataset(files[0], 'r') as fic, \\\n nc.Dataset(startfile, 'r') as fip:\n for var in ACCVARS:\n acc2flx(fic, fip, fo, var, 0, timestep)\n else:\n for var in ACCVARS:\n fo.variables[var][0,...] = fo.variables[var][1,...]\n return\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='convert NoahMP outputs to single CF-compatible file')\n parser.add_argument('wrfinput')\n parser.add_argument('datadir', help='root directory of raw NoahMP outputs')\n parser.add_argument('outfile', help='CF-compaible output file')\n parser.add_argument('begtime', help='inclusive')\n parser.add_argument('endtime', help='exclusive')\n parser.add_argument('--partially', action='store_true')\n args = parser.parse_args()\n main(args.wrfinput, args.datadir, args.outfile,\n dateutil.parser.parse(args.begtime),\n dateutil.parser.parse(args.endtime),\n args.partially)\n" ]
[ [ "numpy.seterr", "numpy.issubdtype", "numpy.squeeze" ] ]
ZhiqingXiao/probability
[ "06a2ca643792c0cf8f047fab7971ba6784dec1c4" ]
[ "tensorflow_probability/python/experimental/mcmc/covariance_reducer_test.py" ]
[ "# Copyright 2020 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for CovarianceReducer and VarianceReducer.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\n\nimport numpy as np\n\nimport tensorflow.compat.v2 as tf\nimport tensorflow_probability as tfp\nfrom tensorflow_probability.python.internal import test_util\n\n\n@test_util.test_all_tf_execution_regimes\nclass CovarianceReducersTest(test_util.TestCase):\n\n def test_zero_covariance(self):\n cov_reducer = tfp.experimental.mcmc.CovarianceReducer()\n state = cov_reducer.initialize(0.)\n for _ in range(2):\n state = cov_reducer.one_step(0., state)\n final_num_samples, final_mean, final_cov = self.evaluate([\n state.cov_state.num_samples,\n state.cov_state.mean,\n cov_reducer.finalize(state)])\n self.assertEqual(final_num_samples, 2)\n self.assertEqual(final_mean, 0)\n self.assertEqual(final_cov, 0)\n\n def test_random_sanity_check(self):\n rng = test_util.test_np_rng()\n x = rng.rand(100)\n cov_reducer = tfp.experimental.mcmc.CovarianceReducer()\n state = cov_reducer.initialize(0.)\n for sample in x:\n state = cov_reducer.one_step(sample, state)\n final_mean, final_cov = self.evaluate([\n state.cov_state.mean,\n cov_reducer.finalize(state)])\n self.assertNear(np.mean(x), final_mean, err=1e-6)\n self.assertNear(np.var(x, ddof=0), final_cov, err=1e-6)\n\n def test_covariance_shape(self):\n cov_reducer = tfp.experimental.mcmc.CovarianceReducer(event_ndims=1)\n state = cov_reducer.initialize(tf.ones((9, 3)))\n for _ in range(2):\n state = cov_reducer.one_step(\n tf.zeros((5, 9, 3)), state, axis=0)\n final_mean, final_cov = self.evaluate([\n state.cov_state.mean,\n cov_reducer.finalize(state)])\n self.assertEqual(final_mean.shape, (9, 3))\n self.assertEqual(final_cov.shape, (9, 3, 3))\n\n def test_variance_shape(self):\n var_reducer = tfp.experimental.mcmc.VarianceReducer()\n state = var_reducer.initialize(tf.ones((9, 3)))\n for _ in range(2):\n state = var_reducer.one_step(\n tf.zeros((5, 9, 3)), state, axis=0)\n final_mean, final_var = self.evaluate([\n state.cov_state.mean,\n var_reducer.finalize(state)])\n self.assertEqual(final_mean.shape, (9, 3))\n self.assertEqual(final_var.shape, (9, 3))\n\n def test_attributes(self):\n cov_reducer = tfp.experimental.mcmc.CovarianceReducer(\n event_ndims=1, ddof=1)\n state = cov_reducer.initialize(tf.ones((2, 3), dtype=tf.float64))\n\n # check attributes are correct right after initialization\n self.assertEqual(cov_reducer.event_ndims, 1)\n self.assertEqual(cov_reducer.ddof, 1)\n for _ in range(2):\n state = cov_reducer.one_step(\n tf.zeros((2, 3), dtype=tf.float64), state)\n\n # check attributes don't change after stepping through\n self.assertEqual(cov_reducer.event_ndims, 1)\n self.assertEqual(cov_reducer.ddof, 1)\n\n def test_tf_while(self):\n cov_reducer = tfp.experimental.mcmc.CovarianceReducer()\n state = cov_reducer.initialize(tf.ones((2, 3)))\n _, state = tf.while_loop(\n lambda i, _: i < 100,\n lambda i, state: (i + 1, cov_reducer.one_step(tf.ones((2, 3)), state)),\n (0., state)\n )\n final_cov = self.evaluate(cov_reducer.finalize(state))\n self.assertAllClose(final_cov, tf.zeros((2, 3, 2, 3)), rtol=1e-6)\n\n def test_nested_chain_state(self):\n cov_reducer = tfp.experimental.mcmc.CovarianceReducer(event_ndims=0)\n chain_state = ({'one': tf.ones((2, 3)), 'zero': tf.zeros((2, 3))},\n {'two': tf.ones((2, 3)) * 2})\n state = cov_reducer.initialize(chain_state)\n _, state = tf.while_loop(\n lambda i, _: i < 10,\n lambda i, state: (i + 1, cov_reducer.one_step(chain_state, state)),\n (0., state)\n )\n final_cov = self.evaluate(cov_reducer.finalize(state))\n self.assertAllEqualNested(\n final_cov, ({'one': tf.zeros((2, 3)), 'zero': tf.zeros((2, 3))},\n {'two': tf.zeros((2, 3))}))\n\n def test_nested_with_batching_and_chunking(self):\n cov_reducer = tfp.experimental.mcmc.CovarianceReducer(event_ndims=1)\n chain_state = ({'one': tf.ones((3, 4)), 'zero': tf.zeros((3, 4))},\n {'two': tf.ones((3, 4)) * 2})\n state = cov_reducer.initialize(chain_state)\n _, state = tf.while_loop(\n lambda i, _: i < 10,\n lambda i, state: (i + 1, cov_reducer.one_step(chain_state, state, 0)),\n (0., state)\n )\n final_cov = self.evaluate(cov_reducer.finalize(state))\n self.assertAllEqualNested(\n final_cov, ({'one': tf.zeros((3, 4, 4)), 'zero': tf.zeros((3, 4, 4))},\n {'two': tf.zeros((3, 4, 4))}))\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "numpy.var", "tensorflow.compat.v2.zeros", "tensorflow.compat.v2.test.main", "tensorflow.compat.v2.ones", "numpy.mean" ] ]
AniruddhA-Omni/Personal-projects
[ "bc5380874425ec5319452aaa1ea61f284a4c3b5e" ]
[ "pythonProject1/pr1.py" ]
[ "import pandas as pd\nimport numpy as np\nimport sklearn\nfrom sklearn import linear_model\nfrom sklearn.utils import shuffle\nimport matplotlib.pyplot as py\nimport pickle\nfrom matplotlib import style\n\ndata = pd.read_csv(\"student-mat.csv\", sep=\";\")\n#print(data.head())\ndata = data[[\"G1\", \"G2\", \"G3\", \"studytime\", \"failures\", \"absences\"]]\n#print(data.head())\n\npredict = \"G3\"\n\nX = np.array(data.drop([predict], 1))\nY = np.array(data[predict])\nx_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(X, Y, test_size=0.1)\n\n\"\"\"best = 0\nfor i in range(50):\n x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(X, Y, test_size=0.1)\n linear = linear_model.LinearRegression() #implementing linear regression model\n linear.fit(x_train, y_train) #training the model\n acc = linear.score(x_test, y_test) #testting the model\n print(acc)\n if acc > best:\n with open(\"studentmodel.pickle\", \"wb\") as f:\n pickle.dump(linear, f)\"\"\"\n\npk_in = open(\"studentmodel.pickle\", \"rb\")\nlinear = pickle.load(pk_in)\n\n\nprint(\"Coeff: \", linear.coef_)\nprint(\"Intercept: \", linear.intercept_)\n\npredictions = linear.predict(x_test)\n\nfor x in range(len(predictions)):\n print(\"Predicted: \",round(predictions[x]),\"Target: \", y_test[x])\n\np = 'G2'\nstyle.use('ggplot')\npy.scatter(data[p], data['G3'])\npy.xlabel(p)\npy.ylabel(\"Final Grade\")\npy.show()" ]
[ [ "pandas.read_csv", "matplotlib.pyplot.xlabel", "matplotlib.style.use", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.array", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.scatter" ] ]
ppizarror/CC3501-2018-2
[ "399da13589db46a0898c486469b03929845c631f" ]
[ "aux 6/heroe.py" ]
[ "import pygame\nfrom pygame.locals import *\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nimport numpy as np\n\nfrom curvas import *\nfrom utils import rgb\n\nclass Heroe:\n def __init__(self, p):\n self.p = np.array(p) # posicion\n self.vive = True # marca para poder eliminar ...\n self.r = 30\n\n def mover(self,dt,v):\n self.p = self.p + dt*np.array(v)\n\n\n def dibujar(self):\n glPushMatrix()\n\n glTranslatef(self.p[0], self.p[1], 0.0)\n\n # Cuerpo\n glColor3fv(rgb(0,255,0))\n glBegin(GL_QUADS)\n glVertex2fv([-10, -10])\n glVertex2fv([10, -10])\n glVertex2fv([10, -40])\n glVertex2fv([-10, -40])\n glEnd()\n\n # Piernas\n glColor3fv(rgb(56, 32, 3))\n glBegin(GL_QUADS)\n glVertex2fv([-5, -40])\n glVertex2fv([0, -40])\n glVertex2fv([0, -60])\n glVertex2fv([-5, -60])\n\n glVertex2fv([3, -40])\n glVertex2fv([8, -40])\n glVertex2fv([8, -60])\n glVertex2fv([3, -60])\n glEnd()\n\n #Cabeza\n glColor3fv(rgb(229, 178, 117))\n\n glBegin(GL_TRIANGLE_FAN)\n\n glVertex2f(0,0)\n radio = 20\n ang = 2 * np.pi / 20\n for i in range(21):\n ang_i = ang * i\n glVertex2f( np.cos(ang_i) * radio, np.sin(ang_i) * radio)\n\n glEnd()\n\n #Sombrero\n triangulos = [\n [[0,25], [-10,30], [-40,0]],\n [[-10,30], [-25, 25], [-40,0]],\n [[-25,25], [-50,-10], [-40,0]],\n [[0,25], [-40,0], [-20, -10]]\n ]\n\n glColor3fv(rgb(0,255,0))\n glBegin(GL_TRIANGLES)\n for triangulo in triangulos:\n for vertice in triangulo:\n glVertex2fv(vertice)\n\n glEnd()\n\n\n\n glPopMatrix()\n\n" ]
[ [ "numpy.array", "numpy.sin", "numpy.cos" ] ]
wutong8023/PLM4CL
[ "4e9e98be425150ad75468b26feb8fb7f5e93c34b" ]
[ "analyze/dataset_distribution.py" ]
[ "\"\"\"\n\n\nAuthor: Tong\nTime: --2021\n\"\"\"\nfrom argparse import ArgumentParser\nfrom datasets import NAMES as DATASET_NAMES\nimport importlib\nimport os\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom utils.conf import base_path\n\n\nclass DatasetAnalysis:\n def __init__(self, dataset, args):\n self.dataset = dataset\n self.targets = dataset.targets\n self.lengths = dataset.distribution\n self.args = args\n \n def demonstrate(self):\n print(self.args.info)\n print(\"total_train_instances:\", len(self.targets))\n print(\"total_classes:\", len(np.unique(self.targets)))\n print(\"max_length:\", np.max(self.lengths))\n \n t_count = self._process_targets()\n self._visualize(t_count, typ=\"t\")\n l_count = self._process_distribution()\n self._visualize(l_count, typ=\"l\")\n \n def _process_targets(self):\n unique_labels = np.unique(self.targets)\n count = []\n for label in unique_labels:\n count.append(np.sum(self.targets == label))\n count = np.array(count)\n count = np.sort(count)[::-1]\n return count\n \n def _process_distribution(self):\n count = []\n max_length = np.max(self.lengths)\n num = len(self.lengths)\n fold = max_length\n for i in range(fold):\n count.append(np.sum(self.lengths == i))\n count = np.array(count)\n return count\n \n def _visualize(self, y, typ: str):\n # replace x with your data\n file_name = self.args.info + \"_\" + typ + \".jpg\"\n file_path = os.path.join(base_path(), \"figure\")\n if not os.path.exists(file_path):\n os.mkdir(file_path)\n outfile = os.path.join(file_path, file_name)\n \n plt.figure(figsize=(100, 20), dpi=100)\n x = np.arange(len(y))\n # replace label with your data, mathing with x and y\n ax = sns.barplot(x=x, y=y, palette=\"Blues_d\")\n\n plt.xticks(range(0, len(y), int(0.1*len(y))))\n\n font = {'family': 'DejaVu Sans',\n 'weight': 'normal',\n 'size': 90}\n \n if typ == \"t\":\n # targets\n plt.xlabel(\"num of classes in {dataset}\".format(dataset=args.dataset.split(\"-\")[1]), fontdict=font)\n plt.ylabel(\"number of instances per class\", fontdict=font)\n else:\n plt.yscale('log')\n plt.xlabel(\"sentence length in {dataset}\".format(dataset=args.dataset.split(\"-\")[1]), fontdict=font)\n plt.ylabel(\"number of instances\", fontdict=font)\n \n \n plt.tick_params(axis='both', which='major', labelsize=70)\n \n plt.savefig(outfile)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(description='dataset', allow_abbrev=False)\n parser.add_argument('--dataset', default=\"seq-clinc150\", required=False, choices=DATASET_NAMES)\n parser.add_argument('--info', default=\"\", required=False)\n args = parser.parse_known_args()[0]\n \n dataset_name = args.dataset.split(\"-\")[1]\n module = importlib.import_module('datasets.' + dataset_name)\n # here use x.lower to build such a mapping from filename to classname\n class_name = {x.lower(): x for x in module.__dir__()}[dataset_name]\n dataset_class = getattr(module, class_name)\n \n dataset_inst = dataset_class()\n da = DatasetAnalysis(dataset_inst, args)\n da.demonstrate()\n" ]
[ [ "numpy.sum", "numpy.sort", "matplotlib.pyplot.tick_params", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "matplotlib.pyplot.yscale", "numpy.max", "matplotlib.pyplot.ylabel", "numpy.array", "numpy.unique" ] ]
Japanuspus/pandas
[ "e38e987160c792f315685dc74fc1fc33d9389a71" ]
[ "pandas/tests/frame/methods/test_describe.py" ]
[ "import numpy as np\n\nimport pandas as pd\nfrom pandas import Categorical, DataFrame, Series, Timestamp, date_range\nimport pandas._testing as tm\n\n\nclass TestDataFrameDescribe:\n def test_describe_bool_in_mixed_frame(self):\n df = DataFrame(\n {\n \"string_data\": [\"a\", \"b\", \"c\", \"d\", \"e\"],\n \"bool_data\": [True, True, False, False, False],\n \"int_data\": [10, 20, 30, 40, 50],\n }\n )\n\n # Integer data are included in .describe() output,\n # Boolean and string data are not.\n result = df.describe()\n expected = DataFrame(\n {\"int_data\": [5, 30, df.int_data.std(), 10, 20, 30, 40, 50]},\n index=[\"count\", \"mean\", \"std\", \"min\", \"25%\", \"50%\", \"75%\", \"max\"],\n )\n tm.assert_frame_equal(result, expected)\n\n # Top value is a boolean value that is False\n result = df.describe(include=[\"bool\"])\n\n expected = DataFrame(\n {\"bool_data\": [5, 2, False, 3]}, index=[\"count\", \"unique\", \"top\", \"freq\"]\n )\n tm.assert_frame_equal(result, expected)\n\n def test_describe_empty_object(self):\n # GH#27183\n df = DataFrame({\"A\": [None, None]}, dtype=object)\n result = df.describe()\n expected = DataFrame(\n {\"A\": [0, 0, np.nan, np.nan]},\n dtype=object,\n index=[\"count\", \"unique\", \"top\", \"freq\"],\n )\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[:0].describe()\n tm.assert_frame_equal(result, expected)\n\n def test_describe_bool_frame(self):\n # GH#13891\n df = DataFrame(\n {\n \"bool_data_1\": [False, False, True, True],\n \"bool_data_2\": [False, True, True, True],\n }\n )\n result = df.describe()\n expected = DataFrame(\n {\"bool_data_1\": [4, 2, False, 2], \"bool_data_2\": [4, 2, True, 3]},\n index=[\"count\", \"unique\", \"top\", \"freq\"],\n )\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame(\n {\n \"bool_data\": [False, False, True, True, False],\n \"int_data\": [0, 1, 2, 3, 4],\n }\n )\n result = df.describe()\n expected = DataFrame(\n {\"int_data\": [5, 2, df.int_data.std(), 0, 1, 2, 3, 4]},\n index=[\"count\", \"mean\", \"std\", \"min\", \"25%\", \"50%\", \"75%\", \"max\"],\n )\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame(\n {\"bool_data\": [False, False, True, True], \"str_data\": [\"a\", \"b\", \"c\", \"a\"]}\n )\n result = df.describe()\n expected = DataFrame(\n {\"bool_data\": [4, 2, False, 2], \"str_data\": [4, 3, \"a\", 2]},\n index=[\"count\", \"unique\", \"top\", \"freq\"],\n )\n tm.assert_frame_equal(result, expected)\n\n def test_describe_categorical(self):\n df = DataFrame({\"value\": np.random.randint(0, 10000, 100)})\n labels = [f\"{i} - {i + 499}\" for i in range(0, 10000, 500)]\n cat_labels = Categorical(labels, labels)\n\n df = df.sort_values(by=[\"value\"], ascending=True)\n df[\"value_group\"] = pd.cut(\n df.value, range(0, 10500, 500), right=False, labels=cat_labels\n )\n cat = df\n\n # Categoricals should not show up together with numerical columns\n result = cat.describe()\n assert len(result.columns) == 1\n\n # In a frame, describe() for the cat should be the same as for string\n # arrays (count, unique, top, freq)\n\n cat = Categorical(\n [\"a\", \"b\", \"b\", \"b\"], categories=[\"a\", \"b\", \"c\"], ordered=True\n )\n s = Series(cat)\n result = s.describe()\n expected = Series([4, 2, \"b\", 3], index=[\"count\", \"unique\", \"top\", \"freq\"])\n tm.assert_series_equal(result, expected)\n\n cat = Series(Categorical([\"a\", \"b\", \"c\", \"c\"]))\n df3 = DataFrame({\"cat\": cat, \"s\": [\"a\", \"b\", \"c\", \"c\"]})\n result = df3.describe()\n tm.assert_numpy_array_equal(result[\"cat\"].values, result[\"s\"].values)\n\n def test_describe_empty_categorical_column(self):\n # GH#26397\n # Ensure the index of an an empty categorical DataFrame column\n # also contains (count, unique, top, freq)\n df = DataFrame({\"empty_col\": Categorical([])})\n result = df.describe()\n expected = DataFrame(\n {\"empty_col\": [0, 0, np.nan, np.nan]},\n index=[\"count\", \"unique\", \"top\", \"freq\"],\n dtype=\"object\",\n )\n tm.assert_frame_equal(result, expected)\n # ensure NaN, not None\n assert np.isnan(result.iloc[2, 0])\n assert np.isnan(result.iloc[3, 0])\n\n def test_describe_categorical_columns(self):\n # GH#11558\n columns = pd.CategoricalIndex([\"int1\", \"int2\", \"obj\"], ordered=True, name=\"XXX\")\n df = DataFrame(\n {\n \"int1\": [10, 20, 30, 40, 50],\n \"int2\": [10, 20, 30, 40, 50],\n \"obj\": [\"A\", 0, None, \"X\", 1],\n },\n columns=columns,\n )\n result = df.describe()\n\n exp_columns = pd.CategoricalIndex(\n [\"int1\", \"int2\"],\n categories=[\"int1\", \"int2\", \"obj\"],\n ordered=True,\n name=\"XXX\",\n )\n expected = DataFrame(\n {\n \"int1\": [5, 30, df.int1.std(), 10, 20, 30, 40, 50],\n \"int2\": [5, 30, df.int2.std(), 10, 20, 30, 40, 50],\n },\n index=[\"count\", \"mean\", \"std\", \"min\", \"25%\", \"50%\", \"75%\", \"max\"],\n columns=exp_columns,\n )\n\n tm.assert_frame_equal(result, expected)\n tm.assert_categorical_equal(result.columns.values, expected.columns.values)\n\n def test_describe_datetime_columns(self):\n columns = pd.DatetimeIndex(\n [\"2011-01-01\", \"2011-02-01\", \"2011-03-01\"],\n freq=\"MS\",\n tz=\"US/Eastern\",\n name=\"XXX\",\n )\n df = DataFrame(\n {\n 0: [10, 20, 30, 40, 50],\n 1: [10, 20, 30, 40, 50],\n 2: [\"A\", 0, None, \"X\", 1],\n }\n )\n df.columns = columns\n result = df.describe()\n\n exp_columns = pd.DatetimeIndex(\n [\"2011-01-01\", \"2011-02-01\"], freq=\"MS\", tz=\"US/Eastern\", name=\"XXX\"\n )\n expected = DataFrame(\n {\n 0: [5, 30, df.iloc[:, 0].std(), 10, 20, 30, 40, 50],\n 1: [5, 30, df.iloc[:, 1].std(), 10, 20, 30, 40, 50],\n },\n index=[\"count\", \"mean\", \"std\", \"min\", \"25%\", \"50%\", \"75%\", \"max\"],\n )\n expected.columns = exp_columns\n tm.assert_frame_equal(result, expected)\n assert result.columns.freq == \"MS\"\n assert result.columns.tz == expected.columns.tz\n\n def test_describe_timedelta_values(self):\n # GH#6145\n t1 = pd.timedelta_range(\"1 days\", freq=\"D\", periods=5)\n t2 = pd.timedelta_range(\"1 hours\", freq=\"H\", periods=5)\n df = DataFrame({\"t1\": t1, \"t2\": t2})\n\n expected = DataFrame(\n {\n \"t1\": [\n 5,\n pd.Timedelta(\"3 days\"),\n df.iloc[:, 0].std(),\n pd.Timedelta(\"1 days\"),\n pd.Timedelta(\"2 days\"),\n pd.Timedelta(\"3 days\"),\n pd.Timedelta(\"4 days\"),\n pd.Timedelta(\"5 days\"),\n ],\n \"t2\": [\n 5,\n pd.Timedelta(\"3 hours\"),\n df.iloc[:, 1].std(),\n pd.Timedelta(\"1 hours\"),\n pd.Timedelta(\"2 hours\"),\n pd.Timedelta(\"3 hours\"),\n pd.Timedelta(\"4 hours\"),\n pd.Timedelta(\"5 hours\"),\n ],\n },\n index=[\"count\", \"mean\", \"std\", \"min\", \"25%\", \"50%\", \"75%\", \"max\"],\n )\n\n result = df.describe()\n tm.assert_frame_equal(result, expected)\n\n exp_repr = (\n \" t1 t2\\n\"\n \"count 5 5\\n\"\n \"mean 3 days 00:00:00 0 days 03:00:00\\n\"\n \"std 1 days 13:56:50.394919273 0 days 01:34:52.099788303\\n\"\n \"min 1 days 00:00:00 0 days 01:00:00\\n\"\n \"25% 2 days 00:00:00 0 days 02:00:00\\n\"\n \"50% 3 days 00:00:00 0 days 03:00:00\\n\"\n \"75% 4 days 00:00:00 0 days 04:00:00\\n\"\n \"max 5 days 00:00:00 0 days 05:00:00\"\n )\n assert repr(result) == exp_repr\n\n def test_describe_tz_values(self, tz_naive_fixture):\n # GH#21332\n tz = tz_naive_fixture\n s1 = Series(range(5))\n start = Timestamp(2018, 1, 1)\n end = Timestamp(2018, 1, 5)\n s2 = Series(date_range(start, end, tz=tz))\n df = DataFrame({\"s1\": s1, \"s2\": s2})\n\n expected = DataFrame(\n {\n \"s1\": [5, 2, 0, 1, 2, 3, 4, 1.581139],\n \"s2\": [\n 5,\n Timestamp(2018, 1, 3).tz_localize(tz),\n start.tz_localize(tz),\n s2[1],\n s2[2],\n s2[3],\n end.tz_localize(tz),\n np.nan,\n ],\n },\n index=[\"count\", \"mean\", \"min\", \"25%\", \"50%\", \"75%\", \"max\", \"std\"],\n )\n result = df.describe(include=\"all\", datetime_is_numeric=True)\n tm.assert_frame_equal(result, expected)\n\n def test_datetime_is_numeric_includes_datetime(self):\n df = DataFrame({\"a\": pd.date_range(\"2012\", periods=3), \"b\": [1, 2, 3]})\n result = df.describe(datetime_is_numeric=True)\n expected = DataFrame(\n {\n \"a\": [\n 3,\n Timestamp(\"2012-01-02\"),\n Timestamp(\"2012-01-01\"),\n Timestamp(\"2012-01-01T12:00:00\"),\n Timestamp(\"2012-01-02\"),\n Timestamp(\"2012-01-02T12:00:00\"),\n Timestamp(\"2012-01-03\"),\n np.nan,\n ],\n \"b\": [3, 2, 1, 1.5, 2, 2.5, 3, 1],\n },\n index=[\"count\", \"mean\", \"min\", \"25%\", \"50%\", \"75%\", \"max\", \"std\"],\n )\n tm.assert_frame_equal(result, expected)\n\n def test_describe_tz_values2(self):\n tz = \"CET\"\n s1 = Series(range(5))\n start = Timestamp(2018, 1, 1)\n end = Timestamp(2018, 1, 5)\n s2 = Series(date_range(start, end, tz=tz))\n df = DataFrame({\"s1\": s1, \"s2\": s2})\n\n s1_ = s1.describe()\n s2_ = Series(\n [\n 5,\n 5,\n s2.value_counts().index[0],\n 1,\n start.tz_localize(tz),\n end.tz_localize(tz),\n ],\n index=[\"count\", \"unique\", \"top\", \"freq\", \"first\", \"last\"],\n )\n idx = [\n \"count\",\n \"unique\",\n \"top\",\n \"freq\",\n \"first\",\n \"last\",\n \"mean\",\n \"std\",\n \"min\",\n \"25%\",\n \"50%\",\n \"75%\",\n \"max\",\n ]\n expected = pd.concat([s1_, s2_], axis=1, keys=[\"s1\", \"s2\"]).loc[idx]\n\n with tm.assert_produces_warning(FutureWarning):\n result = df.describe(include=\"all\")\n tm.assert_frame_equal(result, expected)\n\n def test_describe_percentiles_integer_idx(self):\n # GH#26660\n df = DataFrame({\"x\": [1]})\n pct = np.linspace(0, 1, 10 + 1)\n result = df.describe(percentiles=pct)\n\n expected = DataFrame(\n {\"x\": [1.0, 1.0, np.NaN, 1.0, *[1.0 for _ in pct], 1.0]},\n index=[\n \"count\",\n \"mean\",\n \"std\",\n \"min\",\n \"0%\",\n \"10%\",\n \"20%\",\n \"30%\",\n \"40%\",\n \"50%\",\n \"60%\",\n \"70%\",\n \"80%\",\n \"90%\",\n \"100%\",\n \"max\",\n ],\n )\n tm.assert_frame_equal(result, expected)\n" ]
[ [ "pandas._testing.assert_numpy_array_equal", "pandas.timedelta_range", "pandas.Series", "pandas.DatetimeIndex", "pandas.CategoricalIndex", "pandas.date_range", "pandas._testing.assert_categorical_equal", "pandas._testing.assert_produces_warning", "pandas.DataFrame", "pandas._testing.assert_frame_equal", "pandas.Categorical", "pandas.Timedelta", "pandas._testing.assert_series_equal", "pandas.concat", "numpy.isnan", "numpy.linspace", "numpy.random.randint", "pandas.Timestamp" ] ]
Switham1/PromoterArchitecture
[ "0a9021b869ac66cdd622be18cd029950314d111e" ]
[ "src/data_sorting/choose_TFs_cv.py" ]
[ "import argparse\nimport os\n\nimport pandas as pd\n\n\ndef parse_args(args):\n parser = argparse.ArgumentParser(description=\"choose_TFs_cv\")\n parser.add_argument(\n \"file_names\",\n type=str,\n help=\"Name of folder and filenames for the promoters extracted\",\n )\n parser.add_argument(\n \"no_of_genes\",\n type=int,\n help=\"Number of genes in each category to subset\",\n )\n parser.add_argument(\n \"TF_list\", type=str, help=\"List of Arabidopsis transcription factors\"\n )\n parser.add_argument(\n \"Czechowski_rankedcv\",\n type=str,\n help=\"Input location of all genes ranked by CV\",\n )\n parser.add_argument(\n \"Czechowski_gene_categories_tfs\",\n type=str,\n help=\"Output location of the TF gene categories\",\n )\n parser.add_argument(\n \"Czechowski_all_tfs\",\n type=str,\n help=\"Output location of all ranked TFs by CV value\",\n )\n\n return parser.parse_args(args)\n\n\ndef filter_genes_czechowski(TF_list, select_genes_file, Czechowski_all_tfs):\n \"\"\"filter out genes from the microarray data which aren't in the promoter_bed\"\"\"\n # select_genes = pd.read_table(select_genes_file, sep='\\t', header=0)\n select_genes = pd.read_table(select_genes_file, sep=\"\\t\", header=None)\n cols = [\n \"rank\",\n \"probe_id\",\n \"AGI\",\n \"expression_mean\",\n \"expression_SD\",\n \"expression_CV\",\n \"proportion_of_values_present_in_mas5\",\n \"presence_in_araport11\",\n \"constitutive_in_araport11\",\n ]\n select_genes.columns = cols\n # make AGI uppercase\n select_genes.AGI = select_genes.AGI.str.upper()\n\n # read in TF list\n TF_list_df = pd.read_table(TF_list, sep=\"\\t\", header=1)\n\n merged = pd.merge(\n TF_list_df, select_genes, left_on=\"Gene_ID\", right_on=\"AGI\", how=\"left\"\n )\n # remove NaNs in expression_CV column\n filtered_df = merged[merged.expression_CV.notnull()].copy()\n\n # sort by TF ID\n filtered_df.sort_values([\"TF_ID\"], inplace=True, ignore_index=True)\n\n # remove duplicates based on Gene_ID column\n filtered_df.drop_duplicates(subset=[\"Gene_ID\"], inplace=True)\n # sort by CV value\n filtered_df.sort_values(\"expression_CV\", inplace=True, ignore_index=True)\n # save df\n filtered_df.to_csv(\n Czechowski_all_tfs, sep=\"\\t\", columns=filtered_df.columns, index=False\n )\n\n return filtered_df\n\n\ndef subSet_onCV(in_df, out_dir, no_of_genes):\n \"\"\"\n Extract the constitutive, variable, and control subsets based on CV values\n \"\"\"\n # filtering based on presence in the Araport11 annotation, define the first\n # n rows as the constitutive set and add label\n constitutive = in_df[in_df.presence_in_araport11 == 1][0:no_of_genes]\n constitutive[\"state\"] = \"constitutive\"\n\n # define the last n rows as the variable set and add label\n variable = in_df[in_df.presence_in_araport11 == 1][-no_of_genes:]\n variable[\"state\"] = \"variable\"\n\n # extract the rest of the rows as the control search space\n mid_range = in_df[in_df.presence_in_araport11 == 1][\n (no_of_genes + 1) : -(no_of_genes + 1)\n ]\n\n # create 10 labelled bins\n mid_range[\"bins\"] = pd.Series(\n pd.qcut(mid_range[\"expression_CV\"], q=10, precision=2)\n )\n\n # extract 10 random rows from these bins and label as the control set\n sample = no_of_genes / 10\n sample_integar = int(\n str(sample).replace(\".0\", \"\")\n ) # convert sample to an integar\n samples_from_bins = mid_range.groupby(\"bins\").apply(\n pd.DataFrame.sample, sample_integar, random_state=2\n )\n samples_from_bins[\"state\"] = \"control\"\n\n # concatenate and write as output\n output_set = pd.concat(\n [\n constitutive[[\"AGI\", \"state\"]],\n variable[[\"AGI\", \"state\"]],\n samples_from_bins[[\"AGI\", \"state\"]],\n ],\n ignore_index=True,\n )\n output_set.to_csv(out_dir, sep=\"\\t\", index=False, header=False)\n\n # function from expressionVar_subsets_plot.py\n # __author__ = \"Will Nash\"\n # __copyright__ = \"Copyright 2020, The Earlham Institute\"\n # __credits__ = [\"Will Nash\", \"Wilfried Haerty\"]\n # __license__ = \"GPL\"\n # __version__ = \"1.0\"\n # __maintainer__ = \"Will Nash\"\n # __email__ = \"[email protected]\"\n # __status__ = \"Testing\"\n # __modified_by__ \"Sam Witham\"\n\n\ndef main(args):\n # parse arguments\n args = parse_args(args)\n # make directory for the output files to be exported to\n # dirName = f'{args.directory_path}/data/output/{args.file_names}'\n dirName = f\"../../data/output/{args.file_names}/genes\"\n try:\n # Create target Directory\n os.mkdir(dirName)\n print(\"Directory \", dirName, \" created\")\n except FileExistsError:\n print(\"Directory \", dirName, \" already exists\")\n\n filtered_czechowski = filter_genes_czechowski(\n args.TF_list, args.Czechowski_rankedcv, args.Czechowski_all_tfs\n )\n # filtered_mergner = filter_genes_mergner(args.promoters_filtered_contain_motifs,args.Mergner_rankedcv)\n # czechowksi subset\n subSet_onCV(\n filtered_czechowski,\n args.Czechowski_gene_categories_tfs,\n args.no_of_genes,\n )\n # mergner subset\n # subSet_onCV(filtered_mergner,args.Mergner_gene_categories,args.no_of_genes)\n\n\nif __name__ == \"__main__\":\n import sys\n\n main(sys.argv[1:])\n" ]
[ [ "pandas.read_table", "pandas.merge", "pandas.concat", "pandas.qcut" ] ]
Reasmey/adsi_beer_app
[ "345bab07d6fe579c019a06660cffa5d13718e03c" ]
[ "src/data/sets.py" ]
[ "def subset_x_y(target, features, start_index:int, end_index:int):\n \"\"\"Keep only the rows for X and y sets from the specified indexes\n\n Parameters\n ----------\n target : pd.DataFrame\n Dataframe containing the target\n features : pd.DataFrame\n Dataframe containing all features\n features : int\n Index of the starting observation\n features : int\n Index of the ending observation\n\n Returns\n -------\n pd.DataFrame\n Subsetted Pandas dataframe containing the target\n pd.DataFrame\n Subsetted Pandas dataframe containing all features\n \"\"\"\n \n return features[start_index:end_index], target[start_index:end_index]\n\n\n\n# Solution\ndef split_sets_by_time(df, target_col, test_ratio=0.2, to_numpy=True):\n \"\"\"Split sets by indexes for an ordered dataframe\n\n Parameters\n ----------\n df : pd.DataFrame\n Input dataframe\n target_col : str\n Name of the target column\n test_ratio : float\n Ratio used for the validation and testing sets (default: 0.2)\n\n Returns\n -------\n Numpy Array\n Features for the training set\n Numpy Array\n Target for the training set\n Numpy Array\n Features for the validation set\n Numpy Array\n Target for the validation set\n Numpy Array\n Features for the testing set\n Numpy Array\n Target for the testing set\n \"\"\"\n numpy = to_numpy\n df_copy = df.copy()\n target = df_copy.pop(target_col)\n cutoff = int(len(target) / 5)\n \n X_train, y_train = subset_x_y(target=target, features=df_copy, start_index=0,end_index=-cutoff*2)\n X_val, y_val = subset_x_y(target=target, features=df_copy, start_index=cutoff*2, end_index=-cutoff)\n X_test, y_test = subset_x_y(target=target, features=df_copy, start_index=-cutoff, end_index=len(target))\n \n if numpy == True:\n X_train.to_numpy()\n y_train.to_numpy()\n X_val.to_numpy()\n y_val.to_numpy()\n X_test.to_numpy()\n y_test.to_numpy()\n else:\n X_train\n y_train\n X_val\n y_val\n X_test\n y_test\n\n return X_train, y_train, X_val, y_val, X_test, y_test\n\n\n# Solution\n\ndef save_sets(X_train=None, y_train=None, X_val=None, y_val=None, X_test=None, y_test=None, path='../data/processed/'):\n \"\"\"Save the different sets locally\n\n Parameters\n ----------\n X_train: Numpy Array\n Features for the training set\n y_train: Numpy Array\n Target for the training set\n X_val: Numpy Array\n Features for the validation set\n y_val: Numpy Array\n Target for the validation set\n X_test: Numpy Array\n Features for the testing set\n y_test: Numpy Array\n Target for the testing set\n path : str\n Path to the folder where the sets will be saved (default: '../data/processed/')\n\n Returns\n -------\n \"\"\"\n import numpy as np\n # fix system path\n import sys\n #sys.path.append(\"/home/jovyan/work\")\n\n if X_train is not None:\n np.save(f'{path}X_train', X_train)\n if X_val is not None:\n np.save(f'{path}X_val', X_val)\n if X_test is not None:\n np.save(f'{path}X_test', X_test)\n if y_train is not None:\n np.save(f'{path}y_train', y_train)\n if y_val is not None:\n np.save(f'{path}y_val', y_val)\n if y_test is not None:\n np.save(f'{path}y_test', y_test)\n \ndef load_sets(path='../data/processed/', val=False):\n \"\"\"Load the different locally save sets\n\n Parameters\n ----------\n path : str\n Path to the folder where the sets are saved (default: '../data/processed/')\n\n Returns\n -------\n Numpy Array\n Features for the training set\n Numpy Array\n Target for the training set\n Numpy Array\n Features for the validation set\n Numpy Array\n Target for the validation set\n Numpy Array\n Features for the testing set\n Numpy Array\n Target for the testing set\n \"\"\"\n import numpy as np\n import os.path\n\n X_train = np.load(f'{path}X_train.npy') if os.path.isfile(f'{path}X_train.npy') else None\n X_val = np.load(f'{path}X_val.npy' ) if os.path.isfile(f'{path}X_val.npy') else None\n X_test = np.load(f'{path}X_test.npy' ) if os.path.isfile(f'{path}X_test.npy') else None\n y_train = np.load(f'{path}y_train.npy') if os.path.isfile(f'{path}y_train.npy') else None\n y_val = np.load(f'{path}y_val.npy' ) if os.path.isfile(f'{path}y_val.npy') else None\n y_test = np.load(f'{path}y_test.npy' ) if os.path.isfile(f'{path}y_test.npy') else None\n \n return X_train, y_train, X_val, y_val, X_test, y_test\n\n\ndef pop_target(df, target_col, to_numpy=False):\n \"\"\"Extract target variable from dataframe and convert to nympy arrays if required\n\n Parameters\n ----------\n df : pd.DataFrame\n Dataframe\n target_col : str\n Name of the target variable\n to_numpy : bool\n Flag stating to convert to numpy array or not\n\n Returns\n -------\n pd.DataFrame/Numpy array\n Subsetted Pandas dataframe containing all features\n pd.DataFrame/Numpy array\n Subsetted Pandas dataframe containing the target\n \"\"\"\n\n df_copy = df.copy()\n target = df_copy.pop(target_col)\n \n if to_numpy:\n df_copy = df_copy.to_numpy()\n target = target.to_numpy()\n \n return df_copy, target\n\n\n# Solution\ndef split_sets_random(df, target_col, test_ratio=0.2, to_numpy=False):\n \"\"\"Split sets randomly\n\n Parameters\n ----------\n df : pd.DataFrame\n Input dataframe\n target_col : str\n Name of the target column\n test_ratio : float\n Ratio used for the validation and testing sets (default: 0.2)\n\n Returns\n -------\n Numpy Array\n Features for the training set\n Numpy Array\n Target for the training set\n Numpy Array\n Features for the validation set\n Numpy Array\n Target for the validation set\n Numpy Array\n Features for the testing set\n Numpy Array\n Target for the testing set\n \"\"\"\n \n from sklearn.model_selection import train_test_split\n \n features, target = pop_target(df=df, target_col=target_col, to_numpy=to_numpy)\n \n X_data, X_test, y_data, y_test = train_test_split(features, target, test_size=test_ratio, random_state=8)\n \n val_ratio = test_ratio / (1 - test_ratio)\n X_train, X_val, y_train, y_val = train_test_split(X_data, y_data, test_size=val_ratio, random_state=8)\n\n return X_train, y_train, X_val, y_val, X_test, y_test\n\n\n\nimport pandas as pd\nimport numpy as np\n\nclass NullModel:\n \"\"\"\n Class used as baseline model for both regression and classification\n ...\n\n Attributes\n ----------\n target_type : str\n Type of ML problem (default regression)\n y : Numpy Array-like\n Target variable\n pred_value : Float\n Value to be used for prediction\n preds : Numpy Array\n Predicted array\n\n Methods\n -------\n fit(y)\n Store the input target variable and calculate the predicted value to be used based on the problem type\n predict(y)\n Generate the predictions\n fit_predict(y)\n Perform a fit followed by predict\n \"\"\"\n \n \n def __init__(self, target_type: str = \"regression\"):\n self.target_type = target_type\n self.y = None\n self.pred_value = None\n self.preds = None\n \n def fit(self, y):\n self.y = y\n if self.target_type == \"regression\":\n self.pred_value = y.mean()\n else:\n from scipy.stats import mode\n self.pred_value = mode(y)[0][0]\n \n def predict(self, y):\n self.preds = np.full((len(y), 1), self.pred_value)\n return self.preds\n \n def fit_predict(self, y):\n self.fit(y)\n return self.predict(self.y)" ]
[ [ "numpy.save", "numpy.load", "sklearn.model_selection.train_test_split", "scipy.stats.mode" ] ]
xalhs/Random-Walks
[ "106f972e2b9c204039ba4ae0e39ccdec4165e656" ]
[ "source/random_walk.py" ]
[ "import random\nimport math\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\n\ntmax = 875\nt = 0\n\nx = [0]\ny = [0]\n\n\nt=0\nt_total = 0\n\ndist = 0\n\n#coord = [[x[t],y[t]]]\n\nwhile t < tmax:\n coord = random.randint(0,1)\n\n if coord == 0:\n direction = random.randint(0,1)\n direction = 2*direction -1\n x.append(x[t] + direction)\n y.append(y[t])\n #print(\"x , \" + str(direction))\n else:\n direction = random.randint(0,1)\n direction = 2*direction -1\n y.append(y[t] + direction)\n x.append(x[t])\n cur_dist = x[t]*x[t]+y[t]*y[t]\n if cur_dist > dist:\n dist = cur_dist\n # print(\"y , \" + str(direction))\n\n # print(str(x[t]) + \" , \" + str(y[t]))\n t=t+1\n #coord.append([x[t],y[t]])\n\n\n\nprint(\"max distance was \" + str(math.sqrt(dist)))\n\n\n\nheight = 40\nwidth = 40\n\nfig = plt.figure(figsize=(10, 10))\nax = plt.subplot(111)\n\nxdata, ydata = [], []\nln, = plt.plot([], [])\n\npoints = np.c_[x, y]\n\ndef init():\n# ax.set_xticks(range(-10,10))\n# ax.set_yticks(range(-10,10))\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n #ax.grid()\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n# ax.set_xlim([-1*width, width])\n# ax.set_ylim([-1*height, height])\n ax.set_aspect('equal')\n plt.tick_params(length=0)\n return ln,\n\ndef update(points):\n xdata.append(points[0])\n ydata.append(points[1])\n ln.set_data(xdata, ydata)\n ax.set_xticks(range(len(xdata)))\n ax.set_yticks(range(len(ydata)))\n ax.set_xlim([min(xdata+ydata)-1, max(xdata + ydata)+1])\n ax.set_ylim([min(xdata+ydata)-1, max(*xdata, *ydata)+1])\n #ax.grid(b=True, which='both', linewidth=1, c='b', linestyle='-')\n return ln,\n\ninput(\"waiting for input\")\nani = animation.FuncAnimation(fig, update, frames=points,\n init_func=init, blit=True, repeat=False, interval=1)\n\n\n#ani.save('random_walk.mp4')\n\nplt.show()\n" ]
[ [ "matplotlib.pyplot.tick_params", "matplotlib.pyplot.figure", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.animation.FuncAnimation", "matplotlib.pyplot.plot" ] ]
rcarson3/pyFEpX
[ "f95851e41025fb57893041d0395d53a5745b7e6c" ]
[ "PythonScripts/pyevtk/src/examples/lowlevel.py" ]
[ "#! /usr/bin/env python\n\n# ***********************************************************************************\n# * Copyright 2010 - 2016 Paulo A. Herrera. All rights reserved * \n# * *\n# * Redistribution and use in source and binary forms, with or without *\n# * modification, are permitted provided that the following conditions are met: *\n# * *\n# * 1. Redistributions of source code must retain the above copyright notice, *\n# * this list of conditions and the following disclaimer. *\n# * *\n# * 2. Redistributions in binary form must reproduce the above copyright notice, *\n# * this list of conditions and the following disclaimer in the documentation *\n# * and/or other materials provided with the distribution. *\n# * *\n# * THIS SOFTWARE IS PROVIDED BY PAULO A. HERRERA ``AS IS'' AND ANY EXPRESS OR *\n# * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF *\n# * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO *\n# * EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, *\n# * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, *\n# * BUT NOT LIMITED TO, PROCUREMEN OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *\n# * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *\n# * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *\n# * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\n# * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\n# ***********************************************************************************\n\n# **************************************************************\n# * Example of how to use the low level VtkFile class. *\n# **************************************************************\n\nfrom evtk.vtk import VtkFile, VtkRectilinearGrid\nimport numpy as np\n\nnx, ny, nz = 6, 6, 2\nlx, ly, lz = 1.0, 1.0, 1.0\ndx, dy, dz = lx/nx, ly/ny, lz/nz\nncells = nx * ny * nz\nnpoints = (nx + 1) * (ny + 1) * (nz + 1)\nx = np.arange(0, lx + 0.1*dx, dx, dtype='float64')\ny = np.arange(0, ly + 0.1*dy, dy, dtype='float64')\nz = np.arange(0, lz + 0.1*dz, dz, dtype='float64')\nstart, end = (0,0,0), (nx, ny, nz)\n\nw = VtkFile(\"./evtk_test\", VtkRectilinearGrid)\nw.openGrid(start = start, end = end)\nw.openPiece( start = start, end = end)\n\n# Point data\ntemp = np.random.rand(npoints)\nvx = vy = vz = np.zeros([nx + 1, ny + 1, nz + 1], dtype=\"float64\", order = 'F')\nw.openData(\"Point\", scalars = \"Temperature\", vectors = \"Velocity\")\nw.addData(\"Temperature\", temp)\nw.addData(\"Velocity\", (vx,vy,vz))\nw.closeData(\"Point\")\n\n# Cell data\npressure = np.zeros([nx, ny, nz], dtype=\"float64\", order='F')\nw.openData(\"Cell\", scalars = \"Pressure\")\nw.addData(\"Pressure\", pressure)\nw.closeData(\"Cell\")\n\n# Coordinates of cell vertices\nw.openElement(\"Coordinates\")\nw.addData(\"x_coordinates\", x);\nw.addData(\"y_coordinates\", y);\nw.addData(\"z_coordinates\", z);\nw.closeElement(\"Coordinates\");\n\nw.closePiece()\nw.closeGrid()\n\nw.appendData(data = temp)\nw.appendData(data = (vx,vy,vz))\nw.appendData(data = pressure)\nw.appendData(x).appendData(y).appendData(z)\nw.save()\n\n" ]
[ [ "numpy.arange", "numpy.random.rand", "numpy.zeros" ] ]
avilab/sars-cov2-est
[ "94e358740eb3b0830c35b75e0f89dd12387ffe56" ]
[ "scripts/download_google_drive.py" ]
[ "import gdown\nimport tempfile\nimport pandas as pd\nfrom Bio import SeqIO\nimport io\n\n# Download GISAID cov2020 acknowledgements file from Google drive\nexcel_url = \"https://drive.google.com/uc?id=1g85nEcuiVnmO75Hh8yWAty5uW8P_RSiR\"\n\n# Download sars-cov-2 genomic sequences fasta file\nfasta_url = \"https://drive.google.com/uc?id=1ds-tnGObN7wIRDb12yq1Ey0-Ch8sR5V4\"\n\nwith tempfile.TemporaryFile() as tmp:\n gdown.download(excel_url, tmp, quiet=False)\n df = pd.read_excel(tmp, skiprows=[0, 1, 3])\n\ndf.columns = df.columns.str.strip().str.lower().str.replace(\" \", \"_\")\ndf = df.set_index(\"accession_id\")\ncountry = [\"Estonia\", \"Finland\", \"Latvia\", \"Russia\", \"Lietuva\", \"Sweden\", \"Norway\"]\nids = []\nfor i in country:\n ids.append(df[df[\"virus_name\"].str.contains(i)])\n\ndf_country = pd.concat(ids)\ndf_country = df_country[\n df_country[\"submitting_lab\"]\n != \"Charité Universitätsmedizin Berlin, Institute of Virology\"\n]\n\nwith open(\"data/metadata_gisaid.tsv\", \"w\") as oh:\n df_country.to_csv(oh, sep=\"\\t\")\n\nids_list = df_country.index.tolist()\nwith tempfile.TemporaryFile() as tmp:\n gdown.download(fasta_url, tmp, quiet=False)\n tmp.seek(0)\n for record in SeqIO.parse(io.StringIO(tmp.read().decode(\"utf8\")), \"fasta\"):\n try:\n id = record.id.split(\"|\")[1]\n except IndexError:\n id = \"\"\n if id in ids_list:\n SeqIO.write(record, \"data/sequences_gisaid.fasta\", \"fasta\")\n" ]
[ [ "pandas.read_excel", "pandas.concat" ] ]
Praneet9/Docify
[ "a936014750dedf4a6b5a84918bbbf66cd63109de" ]
[ "api/lib/fast_rcnn/nms_wrapper.py" ]
[ "import numpy as np\r\nfrom .config import cfg\r\npure_python_nms = False\r\ntry:\r\n from lib.utils.gpu_nms import gpu_nms\r\n from ..utils.cython_nms import nms as cython_nms\r\nexcept ImportError:\r\n pure_python_nms = True\r\n\r\n\r\ndef nms(dets, thresh):\r\n if dets.shape[0] == 0:\r\n return []\r\n if pure_python_nms:\r\n # print(\"Fall back to pure python nms\")\r\n return py_cpu_nms(dets, thresh)\r\n if cfg.USE_GPU_NMS:\r\n return gpu_nms(dets, thresh, device_id=cfg.GPU_ID)\r\n else:\r\n return cython_nms(dets, thresh)\r\n\r\n\r\ndef py_cpu_nms(dets, thresh):\r\n x1 = dets[:, 0]\r\n y1 = dets[:, 1]\r\n x2 = dets[:, 2]\r\n y2 = dets[:, 3]\r\n scores = dets[:, 4]\r\n\r\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\r\n order = scores.argsort()[::-1]\r\n\r\n keep = []\r\n while order.size > 0:\r\n i = order[0]\r\n keep.append(i)\r\n xx1 = np.maximum(x1[i], x1[order[1:]])\r\n yy1 = np.maximum(y1[i], y1[order[1:]])\r\n xx2 = np.minimum(x2[i], x2[order[1:]])\r\n yy2 = np.minimum(y2[i], y2[order[1:]])\r\n w = np.maximum(0.0, xx2 - xx1 + 1)\r\n h = np.maximum(0.0, yy2 - yy1 + 1)\r\n inter = w * h\r\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\r\n inds = np.where(ovr <= thresh)[0]\r\n order = order[inds + 1]\r\n return keep\r\n" ]
[ [ "numpy.maximum", "numpy.where", "numpy.minimum" ] ]
HPG-AI/bachbot
[ "6656e866ea67a1092a1a450117a7766c9baf88d0" ]
[ "scripts/theanet/utils.py" ]
[ "import climate\nimport pickle\nimport gzip\nimport numpy as np\nimport os\nimport pickle\nimport sys\nimport tarfile\nimport tempfile\nimport urllib\n\ntry:\n import matplotlib.pyplot as plt\nexcept ImportError:\n logging.critical('please install matplotlib to run the examples!')\n raise\n\nlogging = climate.get_logger(__name__)\n\nclimate.enable_default_logging()\n\nDATASETS = os.path.join(tempfile.gettempdir(), 'theanets-datasets')\n\n\ndef find(dataset, url):\n '''Find the location of a dataset on disk, downloading if needed.'''\n fn = os.path.join(DATASETS, dataset)\n dn = os.path.dirname(fn)\n if not os.path.exists(dn):\n logging.info('creating dataset directory: %s', dn)\n os.makedirs(dn)\n if not os.path.exists(fn):\n if sys.version_info < (3, ):\n urllib.urlretrieve(url, fn)\n else:\n urllib.request.urlretrieve(url, fn)\n return fn\n\n\ndef load_mnist(flatten=True, labels=False):\n '''Load the MNIST digits dataset.'''\n fn = find('mnist.pkl.gz', 'http://deeplearning.net/data/mnist/mnist.pkl.gz')\n h = gzip.open(fn, 'rb')\n if sys.version_info < (3, ):\n (timg, tlab), (vimg, vlab), (simg, slab) = pickle.load(h)\n else:\n (timg, tlab), (vimg, vlab), (simg, slab) = pickle.load(h, encoding='bytes')\n h.close()\n if not flatten:\n timg = timg.reshape((-1, 28, 28, 1))\n vimg = vimg.reshape((-1, 28, 28, 1))\n simg = simg.reshape((-1, 28, 28, 1))\n if labels:\n return ((timg, tlab.astype('i')),\n (vimg, vlab.astype('i')),\n (simg, slab.astype('i')))\n return (timg, ), (vimg, ), (simg, )\n\n\ndef load_cifar(flatten=True, labels=False):\n '''Load the CIFAR10 image dataset.'''\n def extract(name):\n logging.info('extracting data from %s', name)\n h = tar.extractfile(name)\n if sys.version_info < (3, ):\n d = pickle.load(h)\n else:\n d = pickle.load(h, encoding='bytes')\n for k in list(d):\n d[k.decode('utf8')] = d[k]\n h.close()\n img = d['data'].reshape(\n (-1, 3, 32, 32)).transpose((0, 2, 3, 1)).astype('f') / 128 - 1\n if flatten:\n img = img.reshape((-1, 32 * 32 * 3))\n d['data'] = img\n return d\n\n fn = find('cifar10.tar.gz', 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz')\n tar = tarfile.open(fn)\n\n imgs = []\n labs = []\n for i in range(1, 6):\n d = extract('cifar-10-batches-py/data_batch_{}'.format(i))\n imgs.extend(d['data'])\n labs.extend(d['labels'])\n timg = np.asarray(imgs[:40000])\n tlab = np.asarray(labs[:40000], 'i')\n vimg = np.asarray(imgs[40000:])\n vlab = np.asarray(labs[40000:], 'i')\n\n d = extract('cifar-10-batches-py/test_batch')\n simg = d['data']\n slab = d['labels']\n\n tar.close()\n\n if labels:\n return (timg, tlab), (vimg, vlab), (simg, slab)\n return (timg, ), (vimg, ), (simg, )\n\n\ndef plot_images(imgs, loc, title=None, channels=1):\n '''Plot an array of images.\n\n We assume that we are given a matrix of data whose shape is (n*n, s*s*c) --\n that is, there are n^2 images along the first axis of the array, and each\n image is c squares measuring s pixels on a side. Each row of the input will\n be plotted as a sub-region within a single image array containing an n x n\n grid of images.\n '''\n n = int(np.sqrt(len(imgs)))\n assert n * n == len(imgs), 'images array must contain a square number of rows!'\n s = int(np.sqrt(len(imgs[0]) / channels))\n assert s * s == len(imgs[0]) / channels, 'images must be square!'\n\n img = np.zeros(((s+1) * n - 1, (s+1) * n - 1, channels), dtype=imgs[0].dtype)\n for i, pix in enumerate(imgs):\n r, c = divmod(i, n)\n img[r * (s+1):(r+1) * (s+1) - 1,\n c * (s+1):(c+1) * (s+1) - 1] = pix.reshape((s, s, channels))\n\n img -= img.min()\n img /= img.max()\n\n ax = plt.gcf().add_subplot(loc)\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n ax.set_frame_on(False)\n ax.imshow(img.squeeze(), cmap=plt.cm.gray)\n if title:\n ax.set_title(title)\n\n\ndef plot_layers(weights, tied_weights=False, channels=1):\n '''Create a plot of weights, visualized as \"bottom-level\" pixel arrays.'''\n if hasattr(weights[0], 'get_value'):\n weights = [w.get_value() for w in weights]\n k = min(len(weights), 9)\n imgs = np.eye(weights[0].shape[0])\n for i, weight in enumerate(weights[:-1]):\n imgs = np.dot(weight.T, imgs)\n plot_images(imgs,\n 100 + 10 * k + i + 1,\n channels=channels,\n title='Layer {}'.format(i+1))\n weight = weights[-1]\n n = weight.shape[1] / channels\n if int(np.sqrt(n)) ** 2 != n:\n return\n if tied_weights:\n imgs = np.dot(weight.T, imgs)\n plot_images(imgs,\n 100 + 10 * k + k,\n channels=channels,\n title='Layer {}'.format(k))\n else:\n plot_images(weight,\n 100 + 10 * k + k,\n channels=channels,\n title='Decoding weights')\n\n\ndef plot_filters(filters):\n '''Create a plot of conv filters, visualized as pixel arrays.'''\n imgs = filters.get_value()\n\n N, channels, x, y = imgs.shape\n n = int(np.sqrt(N))\n assert n * n == N, 'filters must contain a square number of rows!'\n assert channels == 1 or channels == 3, 'can only plot grayscale or rgb filters!'\n\n img = np.zeros(((y+1) * n - 1, (x+1) * n - 1, channels), dtype=imgs[0].dtype)\n for i, pix in enumerate(imgs):\n r, c = divmod(i, n)\n img[r * (y+1):(r+1) * (y+1) - 1,\n c * (x+1):(c+1) * (x+1) - 1] = pix.transpose((1, 2, 0))\n\n img -= img.min()\n img /= img.max()\n\n ax = plt.gcf().add_subplot(111)\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n ax.set_frame_on(False)\n ax.imshow(img.squeeze(), cmap=plt.cm.gray)\n" ]
[ [ "numpy.eye", "numpy.zeros", "matplotlib.pyplot.gcf", "numpy.asarray", "numpy.sqrt", "numpy.dot" ] ]
Juan-S-Galindo/Web-Scraping-Challenge
[ "4f351cecf8f81e8ebb785656728adb7e75afae3c" ]
[ "scrape_mars.py" ]
[ "#Import Libraries\n#Web Scraping tools \nfrom bs4 import BeautifulSoup as bs\nfrom selenium import webdriver\n#from splinter import Browser\n\n#DataFrame tools\nimport pandas as pd\n\n#Misc tools for web scraping\nimport time\nimport requests\n\n#Function to initianilze browser.\ndef init_browser():\n\n #Settings for headless mode.\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n\n #Splinter option - using absolute path\n #executable_path = {'executable_path': '/Users/Sebastian/Documents/GitHub/Data Visualization Bootcamp/Sebastian Homework/Web-Scraping-Challenge/chromedriver'}\n #browser = Browser('chrome', **executable_path, headless = True)\n #path to the driver and load the options.\n browser = webdriver.Chrome(\"/Users/Sebastian/Documents/GitHub/Data Visualization Bootcamp/Sebastian Homework/Web-Scraping-Challenge/chromedriver\",chrome_options = options)\n\n #returns the brower.\n return browser\n\ndef scrapper():\n\n #Call browser function\n browser = init_browser()\n #Dictionary to store all the results.\n marsInfo_dict = {}\n\n #Code to get NASA Mars News ----------------------------------------------------------------------------------------------\n try:\n\n url = \"https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&year=2020%3Apublish_date&category=19%2C165%2C184%2C204&blank_scope=Latest\"\n\n #splinter option - open url\n #browser.visit(url)\n\n #Open url.\n browser.get(url)\n\n #Time to let the website load all the elements\n time.sleep(4) \n\n #splinter option - save HTML \n #html = browser.html \n\n #save the html source.\n html = browser.page_source\n\n #Use bs4 to parse the html response.\n soup = bs(html, \"html.parser\")\n\n #Collect the latest news title\n news_title = soup.find_all('li', class_=\"slide\")[0].find(class_=\"content_title\").text\n news_p = soup.find_all('li', class_=\"slide\")[0].text\n\n marsInfo_dict['news_title'] = news_title\n marsInfo_dict['news_p'] = news_p\n \n except :\n print(f\"Problem at website {url}\")\n\n #Code to get JPL Mars Space Images - Featured Image ---------------------------------------------------------------------------------\n try:\n\n url = \"https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars\"\n\n #splinter option - open url\n #browser.visit(url)\n\n #Opens the url.\n browser.get(url)\n\n #splinter option - FULL IMAGE BUTTON\n #browser.click_link_by_id(\"full_image\")\n\n #Interact with the FULL IMAGE BUTTON\n browser.find_element_by_id(\"full_image\").click()\n\n time.sleep(4)\n\n #splinter option - save HTML \n #html = browser.html \n\n #save the html source.\n html = browser.page_source\n\n #Use bs4 to parse the html response.\n soup = bs(html, \"html.parser\")\n\n featured_image_url = \"https://www.jpl.nasa.gov/\" + soup.find_all('img', class_=\"fancybox-image\")[0]['src']\n\n marsInfo_dict['featured_image_url'] = featured_image_url\n \n except :\n print(f\"Problem at website {url}\")\n \n #Mars Weather ------------------------------------------------------------------------------------------------------------------------\n try:\n url = \"https://twitter.com/marswxreport?lang=en\"\n \n #splinter option - open url\n #browser.visit(url)\n\n #Open the url.\n browser.get(url)\n\n #Time to let the website load all the elements\n time.sleep(4)\n\n #splinter option - save HTML \n #html = browser.html \n\n #save the html source.\n html = browser.page_source\n\n #Use bs4 to parse the html response.\n soup = bs(html, \"html.parser\")\n\n mars_weather = soup.find_all('article', class_=\"css-1dbjc4n r-1loqt21 r-18u37iz r-1ny4l3l r-o7ynqc r-6416eg\")[0].text.strip().replace('Mars Weather@MarsWxReport·19hInSight ','')\n\n marsInfo_dict['mars_weather'] = mars_weather\n \n except :\n print(mars_weather)\n print(f\"Problem at website {url}\")\n\n # Mars Facts--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n try:\n url = 'http://space-facts.com/mars/'\n\n #Load url to pandas read html.\n tables = pd.read_html(url)\n\n #Tables\n marsFacts_df = tables[0]\n earthMars_df = tables[1]\n\n #Rename columns\n marsFacts_df.columns = ['Facts', 'Values']\n\n\n #Outpout\n html_outputFacts = marsFacts_df.to_html(index = False)\n html_outputFacts = html_outputFacts.replace('\\n', '')\n\n html_outputMarsEarth = earthMars_df.to_html(index = False)\n html_outputMarsEarth = html_outputMarsEarth.replace('\\n', '')\n\n marsInfo_dict['html_outputFacts'] = html_outputFacts\n marsInfo_dict['html_outputMarsEarth'] = html_outputMarsEarth\n\n except :\n print(f\"Problem at website {url}\")\n\n #hemisphereImages ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n try:\n temp_list = []\n\n url = \"https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\n\n #splinter option - open url\n #browser.visit(url)\n\n #Opens the url.\n browser.get(url)\n\n time.sleep(4)\n\n #splinter option - save HTML \n #html = browser.html \n\n #save the html source.\n html = browser.page_source\n\n # close web browser\n browser.close()\n\n #Use bs4 to parse the html response.\n soup = bs(html, \"html.parser\")\n\n links = soup.find_all('div', class_=\"description\")\n\n for link in links:\n\n highDef_url = f\"https://astrogeology.usgs.gov{link.find('a')['href']}\"\n\n responseHighDef = requests.get(highDef_url)\n\n soupHighDef = bs(responseHighDef.text, 'html.parser')\n\n highDef_url = soupHighDef.find_all(\"div\", class_=\"downloads\")[0].find('a')['href']\n\n title = link.find('h3').text \n\n temp_list.append({\"title\" : title, \"img_url\" : highDef_url})\n\n marsInfo_dict['hemisphere_image_urls'] = temp_list\n\n except :\n print(f\"Problem at website {url}\")\n\n return marsInfo_dict" ]
[ [ "pandas.read_html" ] ]
bwang514/google-research
[ "b7ae2e24a39cc72b19c1779d9f4b35befc4b8b8b" ]
[ "non_semantic_speech_benchmark/export_model/model_export_utils.py" ]
[ "# coding=utf-8\n# Copyright 2021 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Utilities and common steps for model export.\"\"\"\n\nimport os\n\nfrom typing import Any, Dict, List, Optional\n\nfrom absl import flags\nfrom absl import logging\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom non_semantic_speech_benchmark.data_prep import audio_to_embeddings_beam_utils\nfrom non_semantic_speech_benchmark.distillation import frontend_lib\nfrom non_semantic_speech_benchmark.distillation import models\nfrom non_semantic_speech_benchmark.distillation.compression_lib import compression_op as compression\nfrom non_semantic_speech_benchmark.distillation.compression_lib import compression_wrapper\n\n\ndef get_experiment_dirs(experiment_dir):\n \"\"\"Returns a list of experiment directories.\n\n NOTE: This assumes that only folders with hyperparams in their name occur in\n the working dict.\n\n Args:\n experiment_dir: Base for all directories.\n\n Returns:\n List of specific experiment subdirs.\n \"\"\"\n if not tf.io.gfile.exists(experiment_dir):\n raise ValueError(f'Experiment dir doesn\\'t exist: {experiment_dir}')\n experiment_dirs = [f for f in tf.io.gfile.listdir(experiment_dir)\n if tf.io.gfile.isdir(os.path.join(experiment_dir, f))]\n return experiment_dirs\n\n\ndef get_params(experiment_dir_str):\n \"\"\"Extracts hyperparams from experiment directory string.\n\n Args:\n experiment_dir_str: The folder-name for the set of hyperparams. Eg:\n '1-al=1.0,ap=False,bd=2048,cop=False,lr=0.0001,ms=small,qat=False,tbs=512'\n\n Returns:\n A dict mapping param key (str) to eval'ed value (float/eval/string).\n \"\"\"\n parsed_params = {}\n start_idx = experiment_dir_str.find('-') + 1\n for kv in experiment_dir_str[start_idx:].split(','):\n cur_split = kv.split('=')\n if len(cur_split) != 2:\n raise ValueError(f'Folder doesn\\'t split properly: {kv}')\n key, value = cur_split\n try:\n value = eval(value) # pylint: disable=eval-used\n except: # pylint: disable=bare-except\n pass\n parsed_params[key] = value\n return parsed_params\n\n\ndef get_default_compressor():\n compression_params = compression.CompressionOp.get_default_hparams().parse('')\n compressor = compression_wrapper.get_apply_compression(\n compression_params, global_step=0)\n return compressor\n\n\ndef get_model(checkpoint_folder_path,\n params,\n tflite_friendly,\n checkpoint_number = None,\n include_frontend = False):\n \"\"\"Given folder & training params, exports SavedModel without frontend.\"\"\"\n compressor = None\n if params['cop']:\n compressor = get_default_compressor()\n # Optionally override frontend flags from\n # `non_semantic_speech_benchmark/export_model/tf_frontend.py`\n override_flag_names = ['frame_hop', 'n_required', 'num_mel_bins',\n 'frame_width']\n for flag_name in override_flag_names:\n if flag_name in params:\n setattr(flags.FLAGS, flag_name, params[flag_name])\n\n static_model = models.get_keras_model(\n params['mt'],\n bottleneck_dimension=params['bd'],\n output_dimension=0, # Don't include the unnecessary final layer.\n frontend=include_frontend,\n compressor=compressor,\n quantize_aware_training=params['qat'],\n tflite=tflite_friendly)\n checkpoint = tf.train.Checkpoint(model=static_model)\n if checkpoint_number:\n checkpoint_to_load = os.path.join(\n checkpoint_folder_path, f'ckpt-{checkpoint_number}')\n assert tf.train.load_checkpoint(checkpoint_to_load)\n else:\n checkpoint_to_load = tf.train.latest_checkpoint(checkpoint_folder_path)\n checkpoint.restore(checkpoint_to_load).expect_partial()\n return static_model\n\n\ndef convert_tflite_model(model, quantize,\n model_path):\n \"\"\"Uses TFLiteConverter to convert a Keras Model.\n\n Args:\n model: Keras model obtained from get_tflite_friendly_model.\n quantize: Whether to quantize TFLite model using dynamic quantization. See:\n https://www.tensorflow.org/lite/performance/post_training_quant\n model_path: Path for TFLite file.\n \"\"\"\n converter = tf.lite.TFLiteConverter.from_keras_model(model)\n converter.target_spec.supported_ops = [\n tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.\n # There is a GatherV2 op in the frontend that isn't supported by TFLite\n # as a builtin op. (It works as a TFLite builtin only if the sample size\n # to the frontend is a constant)\n # However, TFLite supports importing some relevant operators from TF,\n # at the cost of binary size (~ a few MB).\n # See: https://www.tensorflow.org/lite/guide/ops_select\n # NOTE: This has no effect on the model/binary size if the graph does not\n # required the extra TF ops (for example, for no-frontend versio\n tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.\n ]\n if quantize:\n converter.optimizations = [tf.lite.Optimize.DEFAULT]\n tflite_buffer = converter.convert()\n\n with tf.io.gfile.GFile(model_path, 'wb') as f:\n f.write(tflite_buffer)\n logging.info('Exported TFLite model to %s.', model_path)\n\n\ndef sanity_check(\n include_frontend,\n model_path,\n embedding_dim,\n tflite,\n n_required = None,\n frame_width = None,\n num_mel_bins = None):\n \"\"\"Sanity check model by running dummy inference.\"\"\"\n n_required = n_required or flags.FLAGS.n_required\n frame_width = frame_width or flags.FLAGS.frame_width\n num_mel_bins = num_mel_bins or flags.FLAGS.num_mel_bins\n\n if include_frontend:\n input_shape = (1, 2 * n_required)\n expected_output_shape = (7, embedding_dim)\n else:\n feats_inner_dim = frontend_lib.get_frontend_output_shape()[0] * frame_width\n input_shape = (1, feats_inner_dim, num_mel_bins, 1)\n expected_output_shape = (1, embedding_dim)\n logging.info('Input shape: %s. Expected output shape: %s', input_shape,\n expected_output_shape)\n model_input = np.zeros(input_shape, dtype=np.float32)\n\n if tflite:\n logging.info('Building tflite interpreter...')\n interpreter = audio_to_embeddings_beam_utils.build_tflite_interpreter(\n model_path)\n logging.info('Running inference...')\n output = audio_to_embeddings_beam_utils.samples_to_embedding_tflite(\n model_input, sample_rate=16000, interpreter=interpreter, output_key='0')\n else:\n logging.info('Loading and running inference with SavedModel...')\n model = tf.saved_model.load(model_path)\n output = model(model_input)['embedding'].numpy()\n np.testing.assert_array_equal(output.shape, expected_output_shape)\n logging.info('Model \"%s\" worked.', model_path)\n" ]
[ [ "tensorflow.io.gfile.exists", "tensorflow.train.load_checkpoint", "tensorflow.saved_model.load", "numpy.zeros", "tensorflow.io.gfile.GFile", "tensorflow.io.gfile.listdir", "numpy.testing.assert_array_equal", "tensorflow.train.latest_checkpoint", "tensorflow.train.Checkpoint", "tensorflow.lite.TFLiteConverter.from_keras_model" ] ]
nla-group/slearn
[ "2c90f11a7f80235dcfcc77be522b97cf3ce689c1" ]
[ "slearn/tools.py" ]
[ "# Copyright (c) 2021, nla group, manchester\n# All rights reserved. \n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n# https://github.com/robcah/RNNExploration4SymbolicTS\nfrom .symbols import *\nfrom random import randint\nimport pandas as pd\nimport numpy as np\nfrom itertools import product\nimport warnings\n\n\n\ndef Symbols(n=52):\n '''Creation of a dictionary with the compression symbols, restricted\n up to 52 alphabetical characters from 'A' to 'z'\n \n Parameters\n ----------\n n : int\n Number of symbols within the dictionary.\n \n Return\n ------\n dict :\n Dictionary containing the symbols an their numerical code.\n '''\n\n range_ = 123\n collection = [chr(i) for i in np.arange(range_) if chr(i).isalpha()]\n dict_symbols = {symbol:i for i,symbol in enumerate(collection) if i<n}\n \n return dict_symbols\n\n\n\ndef LZWcompress(uncompressed):\n \"\"\"LZW compress a string to a list of numerical codes, it is \n restricted to alphabetical values from 'A' to 'z'.\n Based on from https://rosettacode.org/wiki/LZW_compression#Python\n\n Parameters\n ----------\n uncompressed : string\n String to be compressed using Lempel-Ziv-Welch method, as explained in \n 'A Technique for High-Performance Data Compression', Welch, 1984.\n\n Returns\n -------\n list of integers\n Each element in the list is a code equivalent to a character or a \n groups of characters.\n \"\"\"\n \n # Build the dictionary.\n dictionary = Symbols()\n dict_size = len(dictionary)\n \n w = ''\n result = []\n for c in uncompressed:\n # Concatenates previous symbol with current one in the dictionary\n wc = w + c\n if wc in dictionary:\n w = wc\n else:\n # Appends the compression single code to the compression collection\n result.append(dictionary[w])\n \n # Adds wc to the end of the dictionary\n dictionary[wc] = dict_size\n dict_size += 1\n w = c\n \n # Output the code for w, appending the last symbol.\n if w:\n result.append(dictionary[w])\n \n return result\n \n \n\ndef LZWdecompress(compressed):\n \"\"\" LZW decompression from a list of integers to a string.\n\n Parameters\n ----------\n compressed : list of integers\n Each element correspond to a character or combination of characters,\n as explained in 'A Technique for High-Performance Data Compression', \n Welch, 1984.\n\n Returns\n -------\n strb :\n The representation of the list of codes into a string.\n \"\"\"\n\n # Build the dictionary.\n dictionary = Symbols()\n # Swapping keys and values\n dictionary = {value:key for key, value in dictionary.items()}\n dict_size = len(dictionary)\n \n # Initiation of string building\n string = ''\n w = dictionary[compressed.pop(0)]\n string += w\n for k in compressed:\n if k in dictionary:\n entry = dictionary[k]\n elif k == dict_size:\n entry = w + w[0]\n else:\n raise ValueError('Bad compressed k: %s' % k)\n string += entry\n \n # Add w+entry[0] to the dictionary.\n dictionary[dict_size] = w + entry[0]\n dict_size += 1\n \n w = entry\n \n return string \n \n \n \ndef Reduce(s):\n \"\"\" Reduce a string 's' to its shortest period.\n\n Parameters\n ----------\n s : str\n This string will be evaluated to find whether it can be reduced to \n a simpler representation.\n\n Returns\n -------\n str :\n The result of the reduced string.\n \"\"\"\n # This loops makes a revision sweeping the string to find coincidences \n # betwee subdivisions of the string.\n for j in range(1,len(s)//2+1):\n k = j\n while k < len(s):\n if s[k:k+j] != s[0:j]:\n break\n k += j\n if k >= len(s):\n return s[0:j]\n\n return s\n\n\n\ndef LZWStringGenerator(nr_symbols, target_complexity, \n priorise_complexity=True):\n \"\"\"Generator of strings based on LZW complexity (elements within the \n compression symbols' list). If complexity is priorised it will \n stop the string creation until the aimed complexity is achieved.\n\n Parameters\n ----------\n nr_symbols : int\n Aimed number of symbols to use to build the string.\n target_complexity : int\n Aimed level of complexity for the string.\n priorise_complexity : boolean, default True\n If true generates a string with complexity about target_complexity, \n otherwise the generated string goes above the target complexity until \n reach the nr_symbols.\n\n Return\n ------\n str :\n String produced within the specified parameters\n int :\n Level of LZW complexity.\n \"\"\"\n \n # Caping the highest value of number of symbols to 52.\n if nr_symbols > 52:\n warn0 = 'The strings are limited to alphabetic symbols.'\n warn1 = 'Highest number of symbols is 52.'\n warnings.warn(f'{warn0} {warn1}')\n nr_symbols = 52\n \n # Creation of symbol dictionary\n symbols = Symbols()\n\n string = 'A' # current string\n complexity_0 = 1 # current complexity of s\n symbol_max = 1 #65 + 1 # maximal potential symbol\n symbols_pool = ''.join(list(Symbols().keys()))\n stop = True\n \n # Prevents the error of trying to generate a string of complexity >1 with \n # only 1 symbol.\n if nr_symbols == 1 and target_complexity == 1:\n return 'A', target_complexity\n elif nr_symbols == 1 and target_complexity > 1:\n warn0 = 'Complexities higher than one require more than one symbol.'\n warn1 = 'Output fixed to: (\"A\",1)'\n warnings.warn(f'{warn0} {warn1}')\n return 'A', 1\n elif nr_symbols > target_complexity:\n return np.nan , 0\n \n# if nr_symbols == target_complexity:\n symbols = [symbols_pool[i] for i in range(nr_symbols)]\n np.random.shuffle(symbols)\n string = ''.join(symbols)\n complexity_0 = nr_symbols\n symbol_max = nr_symbols\n \n \n # Adds a pseudorandom symbol to the string until either the target \n # complexity is reached or the number of symbols\n while complexity_0 < target_complexity or not stop:\n\n # Limits the pool of symbols to select\n symbol_i = randint(0, symbol_max-1)\n string += symbols_pool[symbol_i]\n complexity_0 = len(LZWcompress(Reduce(string)))\n\n # Switch to create strings without priorising complexity\n if not priorise_complexity:\n stop = False if len(list(set(string))) < nr_symbols else True\n \n return string, complexity_0\n \n \n \ndef LZWStringLibrary(symbols=(1,10,5), complexity=(5,25,5), \n symbols_range_distribution=None, \n complexity_range_distribution=None,\n iterations=1, save_csv=False, \n priorise_complexity=True):\n '''Serialiser generator of string libraries based on LZWStringGenerator\n\n Parameters\n ----------\n symbols : int or array-like, default (1,10,5)\n If integer the function will return a collection of strings of the \n specified number of symbols. If array-like with value two or three\n it will return strings produced serially within the specified \n range (start,stop,values). If the array is larger than three it will \n produce strings with values within the array.\n complexity : integer or array-like, default (5,25,5)\n If integer the function will return a collection of strings with the \n specified LZW complexity. If it is an array-like with value two or three \n it will return strings produced serially within the specified \n range (start,stop,values). If the array is larger than three it will \n produce strings with values within the array.\n symbols_range_distribution : str, default None\n Type of distribution of values within the range specified on symbols.\n Only accept the strings 'linear' or 'geometrical'.\n complexity_range_distribution : str, default None\n Type of distribution of values within the range specified on complexity.\n Only accept the strings 'linear' or 'geometrical'.\n iterations : int, default 1\n Defines the number of iterations of strings to generate within the set \n parameters.\n save_csv: boolean, default False\n Saves the returned data frame into a CSV file.\n priorise_complexity : boolean, default True\n If true generates a string with complexity about target_complexity, \n otherwise the generated string goes above the target complexity until \n reach the nr_symbols.\n\n Returns\n -------\n CSV file and pandas.DataFrame:\n File and Data frame with columns: nr_symbols, LZW_complexity, \n length and string; which stand for number of symbols, quantity of LZW \n compression elements, length of the resulting string, and the string.\n '''\n\n # Gets the ranges of the parameters to calculate the iterations.\n if isinstance(symbols, int):\n symbols = [symbols]\n else:\n symbols = list(symbols)\n if isinstance(complexity, int):\n complexity = [complexity]\n else:\n complexity = list(complexity)\n \n len_symbols = len(symbols) >= 2 \n len_complexity = len(complexity) >= 2 \n \n if symbols_range_distribution:\n if len_symbols:\n if len(symbols) == 2:\n symbols.append(10)\n if symbols_range_distribution == 'geometrical':\n distribution_symbols = np.geomspace(*symbols)\n elif symbols_range_distribution == 'linear':\n distribution_symbols = np.linspace(*symbols)\n else:\n raise Exception('Distribution unknown.')\n else:\n distribution_symbols = symbols\n \n if complexity_range_distribution:\n if len_complexity:\n if len(complexity) == 2:\n complexity.append(10)\n if complexity_range_distribution == 'geometrical':\n distribution_complexity = np.geomspace(*complexity)\n elif complexity_range_distribution == 'linear':\n distribution_complexity = np.linspace(*complexity)\n else:\n raise Exception('Distribution unknown.')\n else:\n distribution_complexity = complexity\n \n symbols_r = np.round(distribution_symbols).astype(int)\n complexity_r = np.round(distribution_complexity).astype(int)\n \n # To avoid nested loops, an iterator product of parameters\n if iterations >= 1:\n iterations_r = range(iterations)\n iterator = list(product(iterations_r, symbols_r, complexity_r))\n n_iter = len(iterator)\n else:\n warnings.warn('Iterations minor than 1, returns no data')\n return \n\n cols = ['nr_symbols', 'LZW_complexity', 'length', 'string']\n string_lib = pd.DataFrame(columns = cols)\n\n for n, i in enumerate(iterator, 1):\n _, symb_i, complex_i = i\n str_, str_complex = LZWStringGenerator(symb_i, complex_i,\n priorise_complexity=priorise_complexity)\n if not isinstance(str_, str):\n nr_symbols = 0\n str_length = 0\n else: \n nr_symbols = len(set(str_))\n str_length = len(str_)\n df = pd.DataFrame([[nr_symbols, str_complex, str_length, str_]], \n columns = cols)\n string_lib = string_lib.append(df)\n \n # To show level of progress\n print(f'\\rProcessing: {n} of {n_iter}', end = '\\r')\n \n # Saving of the results in a CSV file\n if save_csv:\n hd = 'StrLib_Symb'\n xt = '.csv'\n symbols = [symbols] if not isinstance(symbols, list) else symbols\n symbols_str=''\n \n for i, si in enumerate(symbols):\n s = f'{si:02}'\n sym_len = len(symbols)\n sep = '-' if (sym_len>1 and i!=sym_len-1 and i!=sym_len-2\n ) or (sym_len==2 and i!=sym_len-1) else '_' if i==sym_len-2 else ''\n symbols_str += s + sep\n \n complexity=[complexity] if not isinstance(complexity, list) else complexity\n complexity_str=''\n for i, ci in enumerate(complexity):\n c = f'{ci}'\n cpx_len = len(complexity)\n sep = '-' if (cpx_len>1 and i!=cpx_len-1 and i!=cpx_len-2\n ) or (cpx_len==2 and i!=cpx_len-1\n ) else '_' if i==cpx_len-2 else ''\n complexity_str += c + sep\n \n file_name = f'{hd}({symbols_str})_LZWc({complexity_str})_Iters({iterations}){xt}'\n \n # To prevent repetited strings and strings using less symbols than \n # required.\n string_lib = string_lib[string_lib[cols[0]]>=symbols_r[0]]\n string_lib.dropna(inplace=True)\n string_lib.drop_duplicates(subset=cols[-1], keep='first', inplace=True)\n string_lib.sort_values(cols, axis=0, ascending=True, inplace=True) \n \n # Saving the string library to a CSV file\n string_lib.to_csv(file_name, index=False)\n print(f'\\nString library saved in file: {file_name}')\n\n return string_lib\n" ]
[ [ "numpy.random.shuffle", "pandas.DataFrame", "numpy.geomspace", "numpy.arange", "numpy.round", "numpy.linspace" ] ]
Jasputtar/deepr
[ "e887a3b2c55e7e760ca61f8c99978a8284834ac8" ]
[ "deepr/jobs/optimize_saved_model.py" ]
[ "\"\"\"Converts SavedModel into an optimized protobuf for inference\"\"\"\n\nfrom dataclasses import dataclass, field\nimport logging\nimport re\nfrom typing import List, Dict, Iterable, Union\n\nimport tensorflow as tf\nfrom tensorflow.python.tools.freeze_graph import freeze_graph_with_def_protos\nfrom tensorflow.python.framework.graph_util import extract_sub_graph\n\nfrom deepr.io import Path\nfrom deepr.jobs import base\nfrom deepr.utils.graph import INIT_ALL_TABLES\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass TensorsNotFoundError(ValueError):\n \"\"\"No tensors found for those names.\n\n Most Tensorflow operators take a ``name`` argument that should be\n used if you want to use a custom name for a tensor, otherwise a\n default will be used.\n\n If accessing the operator creating a Tensor is not possible, you\n can use ``tf.identity`` to name the Tensor. However, note that it\n adds a new op to the graph that creates a copy of the input Tensor,\n and thus should be limited to avoid overhead.\n \"\"\"\n\n def __init__(self, tensors: Iterable[str]):\n msg = f\"Tensors not found: {tensors}. Use `tf.identity(t, name)` to name nodes in your graph.\"\n super().__init__(msg)\n\n\n@dataclass\nclass OptimizeSavedModel(base.Job):\n \"\"\"Converts SavedModel into an optimized protobuf for inference\n\n This job reads the input SavedModel, rename some nodes using the\n ``new_names`` argument (raises an error if some renames cannot be\n found), create placeholders given by ``feeds`` (and removes all\n other placeholders not in this list), and finally freezes the sub\n graph that produces the output tensor ``fetch``.\n\n When creating the original SavedModel, it is recommended to use\n ``tf.identity`` operators to mark some tensors as future feeds or\n fetches.\n\n WARNING: successful completion of this job is no guarantee that the\n exported Graph is correct. It is recommended to test the export in\n a separate job.\n\n Attributes\n ----------\n path_saved_model : str\n Path to directory containing SavedModel exports to convert\n path_optimized_model : str\n Path to directory that will contain the export\n graph_name : str\n Name of the output graph (name of the protobuf file)\n new_names : Dict[str, str]\n Mapping old names (SavedModel nodes) -> new names (export)\n blacklisted_variables : Union[str, List[str]]\n List of variable names not to include in the export\n feeds : Union[str, List[str]]\n List of nodes to use as inputs, or comma separated string.\n fetch : Union[str, List[str]]\n List of nodes to use as output, or comma separated string.\n \"\"\"\n\n path_saved_model: str\n path_optimized_model: str\n graph_name: str\n feeds: Union[str, List[str]]\n fetch: Union[str, List[str]]\n new_names: Dict[str, str] = field(default_factory=dict)\n blacklisted_variables: List[str] = field(default_factory=list)\n\n def run(self):\n # Normalize feeds and fetch\n fetch = self.fetch.split(\",\") if isinstance(self.fetch, str) else self.fetch\n feeds = self.feeds.split(\",\") if isinstance(self.feeds, str) else self.feeds\n\n # Find latest SavedModel export in path_saved_model\n subdirs = [\n str(path) for path in Path(self.path_saved_model).iterdir() if path.is_dir() and \"temp\" not in str(path)\n ]\n latest = str(sorted(subdirs)[-1])\n LOGGER.info(f\"Using SavedModel {latest}\")\n\n # Reload SavedModel Graph, optimize and export\n with tf.compat.v1.Session(graph=tf.Graph()) as sess:\n meta_graph_def = tf.compat.v1.saved_model.loader.load(sess, [\"serve\"], latest)\n graph_def = meta_graph_def.graph_def\n\n # Add table initializer if present, or create it\n if INIT_ALL_TABLES in {node.name for node in graph_def.node}:\n fetch.append(INIT_ALL_TABLES)\n else:\n table_initializers = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.TABLE_INITIALIZERS)\n if table_initializers:\n LOGGER.info(f\"Adding {INIT_ALL_TABLES} Node to the graph\")\n table_init_op = tf.group(*table_initializers, name=INIT_ALL_TABLES)\n node_def = table_init_op.node_def\n graph_def.node.append(node_def)\n fetch.append(INIT_ALL_TABLES)\n\n # Rename nodes\n graph_def = rename_nodes(graph_def, self.new_names)\n\n # Setup (create / remove) placeholders\n graph_def = make_placeholders(graph_def, feeds)\n\n # Keep only part of the graph that produces tensor 'fetch'\n graph_def = extract_sub_graph(graph_def, fetch)\n\n # Replace variables by constants\n graph_def = freeze_graph_with_def_protos(\n input_graph_def=graph_def,\n input_saver_def=None,\n input_checkpoint=None,\n output_node_names=\",\".join(fetch),\n restore_op_name=None,\n filename_tensor_name=None,\n output_graph=None,\n clear_devices=True,\n initializer_nodes=None,\n variable_names_blacklist=\",\".join(self.blacklisted_variables),\n input_saved_model_dir=latest,\n saved_model_tags=[\"serve\"],\n )\n tf.io.write_graph(graph_def, logdir=self.path_optimized_model, name=self.graph_name, as_text=False)\n LOGGER.info(f\"Optimized Model successfully exported to {self.path_optimized_model}/{self.graph_name}\")\n\n\ndef rename_nodes(graph_def: tf.compat.v1.GraphDef, new_names: Dict[str, str]) -> tf.compat.v1.GraphDef:\n \"\"\"Rename items in the graph to new ones defined in new_names\n\n Parameters\n ----------\n graph_def : tf.GraphDef\n Graph Definition\n new_names : Dict[str, str]\n Mapping old name -> new name\n\n Returns\n -------\n tf.GraphDef\n A copy of the input GraphDef with renamed nodes\n\n Raises\n ------\n TensorsNotFoundError\n If new_names refers to an node not found in graph_def\n \"\"\"\n # Create copy of each node with a new name\n nodes = []\n for node in graph_def.node:\n new_node = tf.compat.v1.NodeDef()\n new_node.CopyFrom(node)\n nodes.append(new_node)\n if node.name in new_names:\n new_node.name = new_names[node.name]\n LOGGER.info(f\"Node renamed: {node.name} -> {new_node.name}\")\n\n # Check that all new names were used\n if not set(new_names.values()) <= set(node.name for node in nodes):\n missing = set(new_names.values()) - set(node.name for node in nodes)\n raise TensorsNotFoundError(missing)\n\n # Update node references (inputs and location) to renamed nodes\n for node in nodes:\n for idx, name in enumerate(node.input):\n node.input[idx] = new_names[name] if name in new_names else name\n if \"_class\" in node.attr:\n attr = node.attr[\"_class\"]\n for idx, item in enumerate(attr.list.s):\n loc_match = re.match(r\"^loc:@(.+)$\", item.decode())\n if loc_match and loc_match.groups()[0] in new_names:\n new_name = new_names[loc_match.groups()[0]]\n attr.list.s[idx] = f\"loc:@{new_name}\".encode()\n\n # Create Graph with renamed nodes\n new_graph = tf.compat.v1.GraphDef()\n new_graph.node.extend(nodes)\n return new_graph\n\n\ndef make_placeholders(graph_def: tf.compat.v1.GraphDef, names: List[str]) -> tf.compat.v1.GraphDef:\n \"\"\"Create placeholders for names and remove other placeholders\n\n Parameters\n ----------\n graph_def : tf.GraphDef\n Graph definition\n names : List[str]\n Names of placeholders to keep / create for this graph\n\n Returns\n -------\n tf.GraphDef\n A copy of the input GraphDef with new placeholders\n\n Raises\n ------\n TensorsNotFoundError\n If names refers to a node that is not present\n \"\"\"\n # Create copy of each node and change to Placeholder if in names\n nodes = []\n for node in graph_def.node:\n if node.name not in names and node.op == \"Placeholder\":\n LOGGER.info(f\"Removing placeholder {node.name}\")\n continue\n new_node = tf.compat.v1.NodeDef()\n if node.name in names and node.op != \"Placeholder\":\n LOGGER.info(f\"Creating placeholder {node.name}\")\n new_node.name = node.name\n new_node.op = \"Placeholder\"\n new_node.attr[\"shape\"].CopyFrom(tf.compat.v1.AttrValue(shape=node.attr[\"_output_shapes\"].list.shape[0]))\n new_node.attr[\"dtype\"].CopyFrom(node.attr[\"T\"])\n else:\n new_node.CopyFrom(node)\n nodes.append(new_node)\n\n # Check that all expected placeholders have been found\n if not set(names) <= set(node.name for node in nodes):\n missing = set(names) - set(node.name for node in nodes)\n raise TensorsNotFoundError(missing)\n\n # Create Graph with renamed nodes\n new_graph = tf.compat.v1.GraphDef()\n new_graph.node.extend(nodes)\n return new_graph\n" ]
[ [ "tensorflow.io.write_graph", "tensorflow.python.framework.graph_util.extract_sub_graph", "tensorflow.compat.v1.NodeDef", "tensorflow.compat.v1.AttrValue", "tensorflow.Graph", "tensorflow.compat.v1.GraphDef", "tensorflow.compat.v1.saved_model.loader.load", "tensorflow.group", "tensorflow.compat.v1.get_collection" ] ]
kubkon/Phd-python
[ "5dccd6a107204a3b196e42205e691025539311aa" ]
[ "Auctions/Digital Marketplace/expected_prices/expected_prices.py" ]
[ "#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nexpected_prices.py\n\nCreated by Jakub Konka on 2012-10-13.\nCopyright (c) 2012 University of Strathclyde. All rights reserved.\n\"\"\"\nimport argparse\nimport csv\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport numpy as np\nimport os\nimport progressbar as pb\nimport scipy.stats as stats\nimport warnings\n\n# Ignore RuntimeWarnings for now\nwarnings.simplefilter(\"ignore\", RuntimeWarning)\n# Widgets for ProgressBar\nwidgets = ['Calculating: ', pb.Percentage(), pb.Bar(marker=pb.RotatingMarker()), ' ', pb.ETA()]\n\ndef estimate_bid_functions(w, reps, granularity=1000):\n # Calculate params\n v1 = [(1-w)*reps[0], (1-w)*reps[0] + w]\n v2 = [(1-w)*reps[1], (1-w)*reps[1] + w]\n # Check whether nontrivial NE\n if (v2[1] >= v1[1]):\n if (v1[1] <= 2*v2[0] - v2[1]):\n graph_vf1 = np.linspace(v1[0], v1[1], granularity)\n bids1 = list(map(lambda x: v2[0], graph_vf1))\n graph_vf2 = np.linspace(v2[0], v2[1], granularity)\n bids2 = graph_vf2\n else:\n # Bid bounds\n b = [(4 * v1[0] * v2[0] - (v1[1] + v2[1])**2) / (4 * (v1[0] - v1[1] + v2[0] - v2[1])), (v1[1] + v2[1]) / 2]\n # Constants of integration\n c1 = ((v2[1]-v1[1])**2 + 4*(b[0]-v2[1])*(v1[0]-v1[1])) / (-2*(b[0]-b[1])*(v1[0]-v1[1])) * np.exp((v2[1]-v1[1]) / (2*(b[0]-b[1])))\n c2 = ((v1[1]-v2[1])**2 + 4*(b[0]-v1[1])*(v2[0]-v2[1])) / (-2*(b[0]-b[1])*(v2[0]-v2[1])) * np.exp((v1[1]-v2[1]) / (2*(b[0]-b[1])))\n # Inverse bid functions\n vf1 = lambda x: v1[1] + (v2[1]-v1[1])**2 / (c1*(v2[1]+v1[1]-2*x)*np.exp((v2[1]-v1[1])/(v2[1]+v1[1]-2*x)) + 4*(v2[1]-x))\n vf2 = lambda x: v2[1] + (v1[1]-v2[1])**2 / (c2*(v1[1]+v2[1]-2*x)*np.exp((v1[1]-v2[1])/(v1[1]+v2[1]-2*x)) + 4*(v1[1]-x)) \\\n if x <= b[1] else x\n # Sampling\n bids1 = np.linspace(b[0], b[1], granularity)\n bids2 = np.linspace(b[0], v2[1], granularity)\n graph_vf1 = list(map(vf1, bids1))\n graph_vf2 = list(map(vf2, bids2))\n else:\n if (v2[1] <= 2*v1[0] - v1[1]):\n graph_vf1 = np.linspace(v1[0], v1[1], granularity)\n bids1 = graph_vf1\n graph_vf2 = np.linspace(v2[0], v2[1], granularity)\n bids2 = list(map(lambda x: v1[0], graph_vf2))\n else:\n # Bid bounds\n b = [(4 * v1[0] * v2[0] - (v1[1] + v2[1])**2) / (4 * (v1[0] - v1[1] + v2[0] - v2[1])), (v1[1] + v2[1]) / 2]\n # Constants of integration\n c1 = ((v2[1]-v1[1])**2 + 4*(b[0]-v2[1])*(v1[0]-v1[1])) / (-2*(b[0]-b[1])*(v1[0]-v1[1])) * np.exp((v2[1]-v1[1]) / (2*(b[0]-b[1])))\n c2 = ((v1[1]-v2[1])**2 + 4*(b[0]-v1[1])*(v2[0]-v2[1])) / (-2*(b[0]-b[1])*(v2[0]-v2[1])) * np.exp((v1[1]-v2[1]) / (2*(b[0]-b[1])))\n # Inverse bid functions\n vf1 = lambda x: v1[1] + (v2[1]-v1[1])**2 / (c1*(v2[1]+v1[1]-2*x)*np.exp((v2[1]-v1[1])/(v2[1]+v1[1]-2*x)) + 4*(v2[1]-x)) \\\n if x <= b[1] else x\n vf2 = lambda x: v2[1] + (v1[1]-v2[1])**2 / (c2*(v1[1]+v2[1]-2*x)*np.exp((v1[1]-v2[1])/(v1[1]+v2[1]-2*x)) + 4*(v1[1]-x))\n # Sampling\n bids1 = np.linspace(b[0], v1[1], granularity)\n bids2 = np.linspace(b[0], b[1], granularity)\n graph_vf1 = list(map(vf1, bids1))\n graph_vf2 = list(map(vf2, bids2))\n return bids1, graph_vf1, bids2, graph_vf2\n\ndef sample(prng, reps, ws):\n win_prices = []\n costs = [prng.uniform(0,1), prng.uniform(0,1)]\n for w in ws:\n if w != 1.0 and reps[0] != reps[1]:\n # Estimate equilibrium bidding strategy function (transformed)\n bids1, values1, bids2, values2 = estimate_bid_functions(w, reps)\n # Calculate Euclidean distance for each value in values1 and costs[0]\n # Get the index and use it to the get the value of the bid\n v1_dist = list(map(lambda x: np.abs(x - ((1-w)*reps[0] + costs[0]*w)), values1))\n t_bid1 = (bids1[v1_dist.index(min(v1_dist))] - (1-w)*reps[0]) / w\n c_bid1 = w*t_bid1 + (1-w)*reps[0]\n # Repeat for bidder 2\n v2_dist = list(map(lambda x: np.abs(x - ((1-w)*reps[1] + costs[1]*w)), values2))\n t_bid2 = (bids2[v2_dist.index(min(v2_dist))] - (1-w)*reps[1]) / w\n c_bid2 = w*t_bid2 + (1-w)*reps[1]\n else:\n t_bid1 = (1 + costs[0]) / 2\n c_bid1 = t_bid1\n t_bid2 = (1 + costs[1]) / 2\n c_bid2 = t_bid2\n if c_bid1 < c_bid2:\n win_prices += [t_bid1]\n elif c_bid1 > c_bid2:\n win_prices += [t_bid2]\n else:\n bid = t_bid1 if prng.randint(2) == 0 else t_bid2\n win_prices += [bid]\n return win_prices\n\n### Parse command line arguments\nparser = argparse.ArgumentParser(description=\"Expected prices in one-shot DM auction\")\nparser.add_argument('N', metavar='N',\n type=int, help='number of replications')\nparser.add_argument('reputations', metavar='reputations',\n help='input reputation list; comma separated')\nparser.add_argument('--save_dir', dest='save_dir', default='out',\n help='output directory')\nparser.add_argument('--confidence', dest='confidence', default=0.95,\n type=float, help='confidence value')\nargs = parser.parse_args()\nN = args.N\nreps = list(map(lambda x: float(x), args.reputations.split(',')))\nsave_dir = args.save_dir\nconfidence = args.confidence\n\n### Init\nws = np.linspace(0.001, 1.0, 100)\n# Create dir for saving if doesn't exist already\nif not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n### Estimate means\nprint(\"Replicating {} times...\".format(N))\n# ProgressBar\npbar = pb.ProgressBar(widgets=widgets, maxval=N).start()\n# Run for N times (different seed)\nprices = []\nfor n in range(N):\n prng = np.random.RandomState(n)\n prices += [sample(prng, reps, ws)]\n pbar.update(n + 1)\npbar.finish()\nprint(\"Calculating the means and confidence intervals...\")\n# Average over n replications\nmeans = list(map(lambda x: sum(x)/N, zip(*prices)))\n# Calculate sd & 95% confidence intervals\nsd = [np.sqrt(sum(map(lambda x: (x-m)**2, tup))/(N-1)) for (tup, m) in zip(zip(*prices), means)]\nalpha = 1-confidence\nci = list(map(lambda x: stats.t.ppf(1-alpha/2,N-1)*x/np.sqrt(N), sd))\n\n### Save to a file\nprint(\"Saving to a file...\")\ndest = save_dir + '/' + '_'.join(map(lambda x: str(x), reps)) + '.out'\nwith open(dest, newline='', mode='w', encoding='utf-8') as f:\n writer = csv.writer(f, delimiter=',')\n writer.writerow(['w', 'mean', 'sd', 'ci'])\n for tup in zip(ws, means, sd, ci):\n writer.writerow(tup)\n" ]
[ [ "scipy.stats.t.ppf", "numpy.abs", "numpy.exp", "numpy.random.RandomState", "numpy.sqrt", "numpy.linspace" ] ]
niwtr/VQA-GAN
[ "61275bf7e5b3f37fd8fbc0ec9ce4e0045343e299" ]
[ "code/model_noattn.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.parallel\nfrom torch.autograd import Variable\nfrom torchvision import models\nimport torch.utils.model_zoo as model_zoo\nimport torch.nn.functional as F\n\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\nfrom miscc.config import cfg\nfrom GlobalAttention import GlobalAttentionGeneral as ATT_NET\n\n# FIXME change this to mutable variables.\nMAX_OBJECTS = cfg.MAX_OBJECTS\n\ndef Level2RNNEncodeMagic(captions, cap_lens, low_level_rnn, high_level_rnn):\n ''' You are not expected to understand this. '''\n cap_mask = (cap_lens > 0)\n actual_captions = captions[cap_mask] # -> (? x n_words)\n actual_cap_lens = cap_lens[cap_mask] # -> (?, )\n L_hidden = low_level_rnn.init_hidden(actual_captions.size(0))\n _, actual_cap_embs = low_level_rnn(actual_captions, actual_cap_lens, L_hidden)\n cap_embs = torch.zeros(captions.size(0), cfg.TEXT.MAX_QA_NUM, actual_cap_embs.size(-1)).cuda()\n cap_embs[cap_mask] = actual_cap_embs\n num_caps = cap_mask.sum(1)\n H_hidden = high_level_rnn.init_hidden(captions.size(0))\n per_cap_embs, avg_cap_embs = high_level_rnn(cap_embs, num_caps, H_hidden)\n return per_cap_embs, avg_cap_embs, num_caps\n\ndef stn(image, transformation_matrix, size):\n grid = torch.nn.functional.affine_grid(transformation_matrix, torch.Size(size))\n out_image = torch.nn.functional.grid_sample(image, grid)\n return out_image\n\n\nclass GLU(nn.Module):\n def __init__(self):\n super(GLU, self).__init__()\n\n def forward(self, x):\n nc = x.size(1)\n assert nc % 2 == 0, 'channels dont divide 2!'\n nc = int(nc/2)\n return x[:, :nc] * torch.sigmoid(x[:, nc:])\n\n\ndef conv1x1(in_planes, out_planes, bias=False):\n \"1x1 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1,\n padding=0, bias=bias)\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\n# Upsale the spatial size by a factor of 2\ndef upBlock(in_planes, out_planes):\n block = nn.Sequential(\n # nn.functional.interpolate(scale_factor=2, mode=\"nearest\"),\n nn.Upsample(scale_factor=2, mode='nearest'),\n conv3x3(in_planes, out_planes * 2),\n nn.BatchNorm2d(out_planes * 2),\n GLU())\n return block\n\n\n# Keep the spatial size\ndef Block3x3_relu(in_planes, out_planes):\n block = nn.Sequential(\n conv3x3(in_planes, out_planes * 2),\n nn.BatchNorm2d(out_planes * 2),\n GLU())\n return block\n\n\nclass ResBlock(nn.Module):\n def __init__(self, channel_num):\n super(ResBlock, self).__init__()\n self.block = nn.Sequential(\n conv3x3(channel_num, channel_num * 2),\n nn.BatchNorm2d(channel_num * 2),\n GLU(),\n conv3x3(channel_num, channel_num),\n nn.BatchNorm2d(channel_num))\n\n def forward(self, x):\n residual = x\n out = self.block(x)\n out += residual\n return out\n\n\nclass BBOX_NET(nn.Module):\n # some code is modified from vae examples\n # (https://github.com/pytorch/examples/blob/master/vae/main.py)\n def __init__(self):\n super(BBOX_NET, self).__init__()\n self.c_dim = cfg.GAN.CONDITION_DIM\n self.encode = nn.Sequential(\n # 128 * 16 x 16\n conv3x3(self.c_dim, self.c_dim // 2, stride=2),\n nn.LeakyReLU(0.2, inplace=True),\n # 64 x 8 x 8\n conv3x3(self.c_dim // 2, self.c_dim // 4, stride=2),\n nn.BatchNorm2d(self.c_dim // 4),\n nn.LeakyReLU(0.2, inplace=True),\n # 32 x 4 x 4\n conv3x3(self.c_dim // 4, self.c_dim // 8, stride=2),\n nn.BatchNorm2d(self.c_dim // 8),\n nn.LeakyReLU(0.2, inplace=True),\n # 16 x 2 x 2\n )\n\n def forward(self, labels, transf_matr_inv):\n label_layout = torch.cuda.FloatTensor(labels.shape[0], self.c_dim, 16, 16).fill_(0)\n for idx in range(MAX_OBJECTS):\n current_label = labels[:, idx]\n current_label = current_label.view(current_label.shape[0], current_label.shape[1], 1, 1)\n current_label = current_label.repeat(1, 1, 16, 16)\n current_label = stn(current_label, transf_matr_inv[:, idx], current_label.shape)\n label_layout += current_label\n\n layout_encoding = self.encode(label_layout).view(labels.shape[0], -1)\n\n return layout_encoding\n\n\n# ############## Text2Image Encoder-Decoder #######\nclass HigherLevelRNN(nn.Module):\n def __init__(self, ninput=256, drop_prob=0.5,\n nhidden=128, nlayers=1, bidirectional=True):\n super(HigherLevelRNN, self).__init__()\n self.n_steps = cfg.TEXT.MAX_QA_NUM\n self.ninput = ninput # size of each embedding vector\n self.drop_prob = drop_prob # probability of an element to be zeroed\n self.nlayers = nlayers # Number of recurrent layers\n self.bidirectional = bidirectional\n self.rnn_type = cfg.RNN_TYPE\n if bidirectional:\n self.num_directions = 2\n else:\n self.num_directions = 1\n # number of features in the hidden state\n self.nhidden = nhidden // self.num_directions\n\n self.define_module()\n\n def define_module(self):\n if self.rnn_type == 'LSTM':\n # dropout: If non-zero, introduces a dropout layer on\n # the outputs of each RNN layer except the last layer\n self.rnn = nn.LSTM(self.ninput, self.nhidden,\n self.nlayers, batch_first=True,\n dropout=self.drop_prob,\n bidirectional=self.bidirectional)\n elif self.rnn_type == 'GRU':\n self.rnn = nn.GRU(self.ninput, self.nhidden,\n self.nlayers, batch_first=True,\n dropout=self.drop_prob,\n bidirectional=self.bidirectional)\n else:\n raise NotImplementedError\n\n def init_weights(self):\n return\n\n def init_hidden(self, bsz):\n weight = next(self.parameters()).data\n if self.rnn_type == 'LSTM':\n return (Variable(weight.new(self.nlayers * self.num_directions,\n bsz, self.nhidden).zero_()),\n Variable(weight.new(self.nlayers * self.num_directions,\n bsz, self.nhidden).zero_()))\n else:\n return Variable(weight.new(self.nlayers * self.num_directions,\n bsz, self.nhidden).zero_())\n\n def forward(self, emb, cap_lens, hidden, mask=None):\n # input: torch.LongTensor of size batch x n_steps\n # emb: batch x n_steps x ninput\n # Returns: a PackedSequence object\n cap_lens = cap_lens.data.tolist()\n emb = pack_padded_sequence(emb, cap_lens, batch_first=True)\n # #hidden and memory (num_layers * num_directions, batch, hidden_size):\n # tensor containing the initial hidden state for each element in batch.\n # #output (batch, seq_len, hidden_size * num_directions)\n # #or a PackedSequence object:\n # tensor containing output features (h_t) from the last layer of RNN\n output, hidden = self.rnn(emb, hidden)\n # PackedSequence object\n # --> (batch, seq_len, hidden_size * num_directions)\n output = pad_packed_sequence(output, batch_first=True)[0]\n # output = self.drop(output)\n # --> batch x hidden_size*num_directions x seq_len\n words_emb = output.transpose(1, 2)\n # --> batch x num_directions*hidden_size\n if self.rnn_type == 'LSTM':\n sent_emb = hidden[0].transpose(0, 1).contiguous()\n else:\n sent_emb = hidden.transpose(0, 1).contiguous()\n sent_emb = sent_emb.view(-1, self.nhidden * self.num_directions)\n return words_emb, sent_emb\n\nclass RNN_ENCODER(nn.Module):\n def __init__(self, ntoken, ninput=300, drop_prob=0.5,\n nhidden=128, nlayers=1, bidirectional=True):\n super(RNN_ENCODER, self).__init__()\n self.n_steps = cfg.TEXT.WORDS_NUM\n self.ntoken = ntoken # size of the dictionary\n self.ninput = ninput # size of each embedding vector\n self.drop_prob = drop_prob # probability of an element to be zeroed\n self.nlayers = nlayers # Number of recurrent layers\n self.bidirectional = bidirectional\n self.rnn_type = cfg.RNN_TYPE\n if bidirectional:\n self.num_directions = 2\n else:\n self.num_directions = 1\n # number of features in the hidden state\n self.nhidden = nhidden // self.num_directions\n\n self.define_module()\n self.init_weights()\n\n def define_module(self):\n self.encoder = nn.Embedding(self.ntoken, self.ninput)\n self.drop = nn.Dropout(self.drop_prob)\n if self.rnn_type == 'LSTM':\n # dropout: If non-zero, introduces a dropout layer on\n # the outputs of each RNN layer except the last layer\n self.rnn = nn.LSTM(self.ninput, self.nhidden,\n self.nlayers, batch_first=True,\n dropout=self.drop_prob,\n bidirectional=self.bidirectional)\n elif self.rnn_type == 'GRU':\n self.rnn = nn.GRU(self.ninput, self.nhidden,\n self.nlayers, batch_first=True,\n dropout=self.drop_prob,\n bidirectional=self.bidirectional)\n else:\n raise NotImplementedError\n\n def init_weights(self):\n initrange = 0.1\n self.encoder.weight.data.uniform_(-initrange, initrange)\n # Do not need to initialize RNN parameters, which have been initialized\n # http://pytorch.org/docs/master/_modules/torch/nn/modules/rnn.html#LSTM\n # self.decoder.weight.data.uniform_(-initrange, initrange)\n # self.decoder.bias.data.fill_(0)\n\n def init_hidden(self, bsz):\n weight = next(self.parameters()).data\n if self.rnn_type == 'LSTM':\n return (Variable(weight.new(self.nlayers * self.num_directions,\n bsz, self.nhidden).zero_()),\n Variable(weight.new(self.nlayers * self.num_directions,\n bsz, self.nhidden).zero_()))\n else:\n return Variable(weight.new(self.nlayers * self.num_directions,\n bsz, self.nhidden).zero_())\n\n def forward(self, captions, cap_lens, hidden, mask=None):\n # input: torch.LongTensor of size batch x n_steps\n # --> emb: batch x n_steps x ninput\n emb = self.drop(self.encoder(captions))\n #\n # Returns: a PackedSequence object\n cap_lens = cap_lens.data.tolist()\n emb = pack_padded_sequence(emb, cap_lens, batch_first=True, enforce_sorted=False)\n # #hidden and memory (num_layers * num_directions, batch, hidden_size):\n # tensor containing the initial hidden state for each element in batch.\n # #output (batch, seq_len, hidden_size * num_directions)\n # #or a PackedSequence object:\n # tensor containing output features (h_t) from the last layer of RNN\n output, hidden = self.rnn(emb, hidden)\n # PackedSequence object\n # --> (batch, seq_len, hidden_size * num_directions)\n output = pad_packed_sequence(output, batch_first=True)[0]\n # output = self.drop(output)\n # --> batch x hidden_size*num_directions x seq_len\n words_emb = output.transpose(1, 2)\n # --> batch x num_directions*hidden_size\n if self.rnn_type == 'LSTM':\n sent_emb = hidden[0].transpose(0, 1).contiguous()\n else:\n sent_emb = hidden.transpose(0, 1).contiguous()\n sent_emb = sent_emb.view(-1, self.nhidden * self.num_directions)\n return words_emb, sent_emb\n\n\nclass CNN_ENCODER(nn.Module):\n def __init__(self, nef):\n super(CNN_ENCODER, self).__init__()\n if cfg.TRAIN.FLAG:\n self.nef = nef\n else:\n self.nef = 256 # define a uniform ranker\n\n model = models.inception_v3()\n url = 'https://download.pytorch.org/models/inception_v3_google-1a9a5a14.pth'\n model.load_state_dict(model_zoo.load_url(url))\n for param in model.parameters():\n param.requires_grad = False\n print('Load pretrained model from ', url)\n # print(model)\n\n self.define_module(model)\n self.init_trainable_weights()\n\n def define_module(self, model):\n self.Conv2d_1a_3x3 = model.Conv2d_1a_3x3\n self.Conv2d_2a_3x3 = model.Conv2d_2a_3x3\n self.Conv2d_2b_3x3 = model.Conv2d_2b_3x3\n self.Conv2d_3b_1x1 = model.Conv2d_3b_1x1\n self.Conv2d_4a_3x3 = model.Conv2d_4a_3x3\n self.Mixed_5b = model.Mixed_5b\n self.Mixed_5c = model.Mixed_5c\n self.Mixed_5d = model.Mixed_5d\n self.Mixed_6a = model.Mixed_6a\n self.Mixed_6b = model.Mixed_6b\n self.Mixed_6c = model.Mixed_6c\n self.Mixed_6d = model.Mixed_6d\n self.Mixed_6e = model.Mixed_6e\n self.Mixed_7a = model.Mixed_7a\n self.Mixed_7b = model.Mixed_7b\n self.Mixed_7c = model.Mixed_7c\n\n self.emb_features = conv1x1(768, self.nef)\n self.emb_cnn_code = nn.Linear(2048, self.nef)\n\n def init_trainable_weights(self):\n initrange = 0.1\n self.emb_features.weight.data.uniform_(-initrange, initrange)\n self.emb_cnn_code.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, x):\n features = None\n # --> fixed-size input: batch x 3 x 299 x 299\n # x = nn.functional.interpolate(x, size=(299, 299), mode='bilinear')\n x = nn.Upsample(size=(299, 299), mode='bilinear')(x)\n # 299 x 299 x 3\n x = self.Conv2d_1a_3x3(x)\n # 149 x 149 x 32\n x = self.Conv2d_2a_3x3(x)\n # 147 x 147 x 32\n x = self.Conv2d_2b_3x3(x)\n # 147 x 147 x 64\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n # 73 x 73 x 64\n x = self.Conv2d_3b_1x1(x)\n # 73 x 73 x 80\n x = self.Conv2d_4a_3x3(x)\n # 71 x 71 x 192\n\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n # 35 x 35 x 192\n x = self.Mixed_5b(x)\n # 35 x 35 x 256\n x = self.Mixed_5c(x)\n # 35 x 35 x 288\n x = self.Mixed_5d(x)\n # 35 x 35 x 288\n\n x = self.Mixed_6a(x)\n # 17 x 17 x 768\n x = self.Mixed_6b(x)\n # 17 x 17 x 768\n x = self.Mixed_6c(x)\n # 17 x 17 x 768\n x = self.Mixed_6d(x)\n # 17 x 17 x 768\n x = self.Mixed_6e(x)\n # 17 x 17 x 768\n\n # image region features\n features = x\n # 17 x 17 x 768\n\n x = self.Mixed_7a(x)\n # 8 x 8 x 1280\n x = self.Mixed_7b(x)\n # 8 x 8 x 2048\n x = self.Mixed_7c(x)\n # 8 x 8 x 2048\n x = F.avg_pool2d(x, kernel_size=8)\n # 1 x 1 x 2048\n # x = F.dropout(x, training=self.training)\n # 1 x 1 x 2048\n x = x.view(x.size(0), -1)\n # 2048\n\n # global image features\n cnn_code = self.emb_cnn_code(x)\n # 512\n if features is not None:\n features = self.emb_features(features)\n return features, cnn_code\n\n\n# ############## G networks ###################\nclass SimpleLrPhiProjector(nn.Module):\n ''' a fake CA_NET. '''\n def __init__(self):\n super(SimpleLrPhiProjector, self).__init__()\n self.t_dim = cfg.TEXT.EMBEDDING_DIM\n self.c_dim = cfg.GAN.CONDITION_DIM\n self.fc = nn.Linear(self.t_dim, self.c_dim, bias=True)\n self.relu = nn.ReLU()\n def forward(self, x):\n return self.relu(self.fc(x)), None, None\n\n\nclass CA_NET(nn.Module):\n # some code is modified from vae examples\n # (https://github.com/pytorch/examples/blob/master/vae/main.py)\n def __init__(self):\n super(CA_NET, self).__init__()\n self.t_dim = cfg.TEXT.EMBEDDING_DIM\n self.c_dim = cfg.GAN.CONDITION_DIM\n self.fc = nn.Linear(self.t_dim, self.c_dim * 4, bias=True)\n self.relu = GLU()\n\n def encode(self, text_embedding):\n x = self.relu(self.fc(text_embedding))\n mu = x[:, :self.c_dim]\n logvar = x[:, self.c_dim:]\n return mu, logvar\n\n def reparametrize(self, mu, logvar):\n std = logvar.mul(0.5).exp_()\n if cfg.CUDA:\n eps = torch.cuda.FloatTensor(std.size()).normal_()\n else:\n eps = torch.FloatTensor(std.size()).normal_()\n eps = Variable(eps)\n return eps.mul(std).add_(mu)\n\n def forward(self, text_embedding):\n mu, logvar = self.encode(text_embedding)\n c_code = self.reparametrize(mu, logvar)\n return c_code, mu, logvar\n\n\nclass INIT_STAGE_G(nn.Module):\n def __init__(self, ngf, ncf):\n super(INIT_STAGE_G, self).__init__()\n self.gf_dim = ngf\n self.in_dim = cfg.GAN.Z_DIM + ncf # cfg.TEXT.EMBEDDING_DIM\n\n self.define_module()\n\n def define_module(self):\n nz, ngf = self.in_dim, self.gf_dim\n linput = 100+cfg.GAN.LABEL_DIM\n self.ef_dim = 100\n\n self.bbox_net = BBOX_NET()\n nz += 48\n\n self.fc = nn.Sequential(\n nn.Linear(nz, ngf * 4 * 4 * 2, bias=False),\n nn.BatchNorm1d(ngf * 4 * 4 * 2),\n GLU())\n\n # local pathway\n self.label = nn.Sequential(\n nn.Linear(linput, self.ef_dim, bias=False),\n nn.BatchNorm1d(self.ef_dim),\n nn.ReLU(True))\n self.local1 = upBlock(self.ef_dim, ngf // 2)\n self.local2 = upBlock(ngf // 2, ngf // 4)\n\n self.upsample1 = upBlock(ngf, ngf // 2)\n self.upsample2 = upBlock(ngf // 2, ngf // 4)\n self.upsample3 = upBlock(ngf // 2, ngf // 8)\n self.upsample4 = upBlock(ngf // 8, ngf // 16)\n\n def forward(self, z_code, c_code, transf_matrices_inv, label_one_hot):\n \"\"\"\n :param z_code: batch x cfg.GAN.Z_DIM\n :param c_code: batch x cfg.TEXT.EMBEDDING_DIM\n :return: batch x ngf/16 x 64 x 64\n \"\"\"\n local_labels = torch.cuda.FloatTensor(z_code.shape[0], MAX_OBJECTS, self.ef_dim).fill_(0)\n\n # local pathway\n h_code_locals = torch.cuda.FloatTensor(z_code.shape[0], self.gf_dim // 4, 16, 16).fill_(0)\n\n for idx in range(MAX_OBJECTS):\n current_label = self.label(torch.cat((c_code, label_one_hot[:, idx]), 1))\n local_labels[:, idx] = current_label\n current_label = current_label.view(current_label.shape[0], self.ef_dim, 1, 1)\n current_label = current_label.repeat(1, 1, 4, 4)\n h_code_local = self.local1(current_label)\n h_code_local = self.local2(h_code_local)\n h_code_local = stn(h_code_local, transf_matrices_inv[:, idx], h_code_local.shape)\n h_code_locals += h_code_local\n\n bbox_code = self.bbox_net(local_labels, transf_matrices_inv)\n c_z_code = torch.cat((c_code, z_code, bbox_code), 1)\n # c_z_code = torch.cat((c_code, z_code), 1)\n # state size ngf x 4 x 4\n out_code = self.fc(c_z_code)\n out_code = out_code.view(-1, self.gf_dim, 4, 4)\n # state size ngf/3 x 8 x 8\n out_code = self.upsample1(out_code)\n # state size ngf/4 x 16 x 16\n out_code = self.upsample2(out_code)\n\n # combine local and global pathways\n out_code = torch.cat((out_code, h_code_locals), 1)\n\n # state size ngf/8 x 32 x 32\n out_code32 = self.upsample3(out_code)\n # state size ngf/16 x 64 x 64\n out_code64 = self.upsample4(out_code32)\n\n return out_code64\n\n\nclass NEXT_STAGE_G(nn.Module):\n def __init__(self, ngf, nef, ncf):\n super(NEXT_STAGE_G, self).__init__()\n self.gf_dim = ngf\n self.ef_dim = nef\n self.cf_dim = ncf\n self.num_residual = cfg.GAN.R_NUM\n self.define_module()\n\n def _make_layer(self, block, channel_num):\n layers = []\n for i in range(cfg.GAN.R_NUM):\n layers.append(block(channel_num))\n return nn.Sequential(*layers)\n\n def define_module(self):\n ngf = self.gf_dim\n self.att = ATT_NET(ngf, self.ef_dim)\n self.jointConv = Block3x3_relu(ngf + 100, ngf) # FIXME del\n self.residual = self._make_layer(ResBlock, ngf) # FIXME ngf * 2\n # self.upsample = upBlock(ngf * 2, ngf) # FIXME\n self.upsample = upBlock(ngf , ngf)\n\n def forward(self, h_code, c_code, word_embs, mask):\n \"\"\"\n h_code1(query): batch x idf x ih x iw (queryL=ihxiw)\n word_embs(context): batch x cdf x sourceL (sourceL=seq_len)\n c_code1: batch x idf x queryL\n att1: batch x sourceL x queryL\n \"\"\"\n self.att.applyMask(mask)\n _c_code, att = self.att(h_code, word_embs)\n\n # FIXME del\n s_size = h_code.size(2)\n c_code = c_code.view(-1, 100, 1, 1)\n c_code = c_code.repeat(1, 1, s_size, s_size)\n\n h_c_code = torch.cat((h_code, c_code), 1)\n h_c_code = self.jointConv(h_c_code) # FIXME del\n out_code = self.residual(h_c_code)\n\n # state size ngf/2 x 2in_size x 2in_size\n out_code = self.upsample(out_code)\n\n return out_code, att\n\n\nclass GET_IMAGE_G(nn.Module):\n def __init__(self, ngf):\n super(GET_IMAGE_G, self).__init__()\n self.gf_dim = ngf\n self.img = nn.Sequential(\n conv3x3(ngf, 3),\n nn.Tanh()\n )\n\n def forward(self, h_code):\n out_img = self.img(h_code)\n return out_img\n\n\nclass G_NET(nn.Module):\n def __init__(self):\n super(G_NET, self).__init__()\n ngf = cfg.GAN.GF_DIM\n nef = cfg.TEXT.EMBEDDING_DIM\n ncf = cfg.GAN.CONDITION_DIM\n \n if cfg.GAN.B_CA_NET:\n self.ca_net = CA_NET()\n else:\n self.ca_net = SimpleLrPhiProjector()\n\n if cfg.TREE.BRANCH_NUM > 0:\n self.h_net1 = INIT_STAGE_G(ngf * 16, ncf)\n self.img_net1 = GET_IMAGE_G(ngf)\n # gf x 64 x 64\n if cfg.TREE.BRANCH_NUM > 1:\n self.h_net2 = NEXT_STAGE_G(ngf, nef, ncf)\n self.img_net2 = GET_IMAGE_G(ngf)\n if cfg.TREE.BRANCH_NUM > 2:\n self.h_net3 = NEXT_STAGE_G(ngf, nef, ncf)\n self.img_net3 = GET_IMAGE_G(ngf)\n\n def forward(self, z_code, sent_emb, word_embs, mask, transf_matrices_inv, label_one_hot):\n \"\"\"\n :param z_code: batch x cfg.GAN.Z_DIM\n :param sent_emb: batch x cfg.TEXT.EMBEDDING_DIM\n :param word_embs: batch x cdf x seq_len\n :param mask: batch x seq_len\n :return:\n \"\"\"\n fake_imgs = []\n att_maps = []\n c_code, mu, logvar = self.ca_net(sent_emb)\n\n if cfg.TREE.BRANCH_NUM > 0:\n h_code1 = self.h_net1(z_code, c_code, transf_matrices_inv, label_one_hot)\n fake_img1 = self.img_net1(h_code1)\n fake_imgs.append(fake_img1)\n if cfg.TREE.BRANCH_NUM > 1:\n h_code2, att1 = \\\n self.h_net2(h_code1, c_code, word_embs, mask)\n fake_img2 = self.img_net2(h_code2)\n fake_imgs.append(fake_img2)\n if att1 is not None:\n att_maps.append(att1)\n if cfg.TREE.BRANCH_NUM > 2:\n h_code3, att2 = \\\n self.h_net3(h_code2, c_code, word_embs, mask)\n fake_img3 = self.img_net3(h_code3)\n fake_imgs.append(fake_img3)\n if att2 is not None:\n att_maps.append(att2)\n\n return fake_imgs, att_maps, mu, logvar\n\n\nclass G_DCGAN(nn.Module):\n def __init__(self):\n super(G_DCGAN, self).__init__()\n ngf = cfg.GAN.GF_DIM\n nef = cfg.TEXT.EMBEDDING_DIM\n ncf = cfg.GAN.CONDITION_DIM\n self.ca_net = CA_NET()\n\n # 16gf x 64 x 64 --> gf x 64 x 64 --> 3 x 64 x 64\n if cfg.TREE.BRANCH_NUM > 0:\n self.h_net1 = INIT_STAGE_G(ngf * 16, ncf)\n # gf x 64 x 64\n if cfg.TREE.BRANCH_NUM > 1:\n self.h_net2 = NEXT_STAGE_G(ngf, nef, ncf)\n if cfg.TREE.BRANCH_NUM > 2:\n self.h_net3 = NEXT_STAGE_G(ngf, nef, ncf)\n self.img_net = GET_IMAGE_G(ngf)\n\n def forward(self, z_code, sent_emb, word_embs, mask):\n \"\"\"\n :param z_code: batch x cfg.GAN.Z_DIM\n :param sent_emb: batch x cfg.TEXT.EMBEDDING_DIM\n :param word_embs: batch x cdf x seq_len\n :param mask: batch x seq_len\n :return:\n \"\"\"\n att_maps = []\n c_code, mu, logvar = self.ca_net(sent_emb)\n if cfg.TREE.BRANCH_NUM > 0:\n h_code = self.h_net1(z_code, c_code)\n if cfg.TREE.BRANCH_NUM > 1:\n h_code, att1 = self.h_net2(h_code, c_code, word_embs, mask)\n if att1 is not None:\n att_maps.append(att1)\n if cfg.TREE.BRANCH_NUM > 2:\n h_code, att2 = self.h_net3(h_code, c_code, word_embs, mask)\n if att2 is not None:\n att_maps.append(att2)\n\n fake_imgs = self.img_net(h_code)\n return [fake_imgs], att_maps, mu, logvar\n\n\n# ############## D networks ##########################\ndef Block3x3_leakRelu(in_planes, out_planes):\n block = nn.Sequential(\n conv3x3(in_planes, out_planes),\n nn.BatchNorm2d(out_planes),\n nn.LeakyReLU(0.2, inplace=True)\n )\n return block\n\n\n# Downsale the spatial size by a factor of 2\ndef downBlock(in_planes, out_planes):\n block = nn.Sequential(\n nn.Conv2d(in_planes, out_planes, 4, 2, 1, bias=False),\n nn.BatchNorm2d(out_planes),\n nn.LeakyReLU(0.2, inplace=True)\n )\n return block\n\n\n# Downsale the spatial size by a factor of 16\ndef encode_image_by_16times(ndf):\n encode_img = nn.Sequential(\n # --> state size. ndf x in_size/2 x in_size/2\n nn.Conv2d(3, ndf, 4, 2, 1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n # --> state size 2ndf x x in_size/4 x in_size/4\n nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 2),\n nn.LeakyReLU(0.2, inplace=True),\n # --> state size 4ndf x in_size/8 x in_size/8\n nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 4),\n nn.LeakyReLU(0.2, inplace=True),\n # --> state size 8ndf x in_size/16 x in_size/16\n nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 8),\n nn.LeakyReLU(0.2, inplace=True)\n )\n return encode_img\n\n\nclass D_GET_LOGITS(nn.Module):\n def __init__(self, ndf, nef, bcondition=False):\n super(D_GET_LOGITS, self).__init__()\n self.df_dim = ndf\n self.ef_dim = nef\n self.bcondition = bcondition\n if self.bcondition:\n self.jointConv = Block3x3_leakRelu(ndf * 8 + nef, ndf * 8)\n\n self.outlogits = nn.Sequential(\n nn.Conv2d(ndf * 8, 1, kernel_size=4, stride=4),\n nn.Sigmoid())\n\n def forward(self, h_code, c_code=None):\n if self.bcondition and c_code is not None:\n # conditioning output\n c_code = c_code.view(-1, self.ef_dim, 1, 1)\n c_code = c_code.repeat(1, 1, 4, 4)\n # state size (ngf+egf) x 4 x 4\n h_c_code = torch.cat((h_code, c_code), 1)\n # state size ngf x in_size x in_size\n h_c_code = self.jointConv(h_c_code)\n else:\n h_c_code = h_code\n\n output = self.outlogits(h_c_code)\n return output.view(-1)\n\n\n# For 64 x 64 images\nclass D_NET64(nn.Module):\n def __init__(self, b_jcu=True):\n super(D_NET64, self).__init__()\n ndf = cfg.GAN.DF_DIM\n nef = cfg.TEXT.EMBEDDING_DIM\n if b_jcu:\n self.UNCOND_DNET = D_GET_LOGITS(ndf, nef, bcondition=False)\n else:\n self.UNCOND_DNET = None\n self.COND_DNET = D_GET_LOGITS(ndf, nef, bcondition=True)\n self.define_module()\n\n def define_module(self):\n self.act = nn.LeakyReLU(0.2, inplace=True)\n ndf = cfg.GAN.DF_DIM\n\n # global pathway\n # --> state size. ndf x in_size/2 x in_size/2\n self.conv1 = nn.Conv2d(3, ndf, 4, 2, 1, bias=False)\n # --> state size 2ndf x x in_size/4 x in_size/4\n self.conv2 = nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False)\n self.bn2 = nn.BatchNorm2d(ndf * 2)\n # --> state size 4ndf x in_size/8 x in_size/8\n self.conv3 = nn.Conv2d(ndf * 4, ndf * 4, 4, 2, 1, bias=False)\n self.bn3 = nn.BatchNorm2d(ndf * 4)\n # --> state size 8ndf x in_size/16 x in_size/16\n self.conv4 = nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False)\n self.bn4 = nn.BatchNorm2d(ndf * 8)\n\n # local pathway\n self.local = nn.Sequential(\n nn.Conv2d(3 + cfg.GAN.LABEL_DIM, ndf * 2, 4, 1, 1, bias=False),\n nn.BatchNorm2d(ndf * 2),\n nn.LeakyReLU(0.2, inplace=True)\n )\n\n def forward(self, image, label, transf_matrices, transf_matrices_inv):\n # local pathway\n h_code_locals = torch.cuda.FloatTensor(image.shape[0], cfg.GAN.DF_DIM * 2, 16, 16).fill_(0)\n for idx in range(MAX_OBJECTS):\n current_label = label[:, idx].view(label.shape[0], cfg.GAN.LABEL_DIM, 1, 1)\n current_label = current_label.repeat(1, 1, 16, 16)\n h_code_local = stn(image, transf_matrices[:, idx], (image.shape[0], image.shape[1], 16, 16))\n h_code_local = torch.cat((h_code_local, current_label), 1)\n h_code_local = self.local(h_code_local)\n h_code_local = stn(h_code_local, transf_matrices_inv[:, idx],\n (h_code_local.shape[0], h_code_local.shape[1], 16, 16))\n h_code_locals += h_code_local\n\n h_code = self.conv1(image)\n h_code = self.act(h_code)\n h_code = self.conv2(h_code)\n h_code = self.bn2(h_code)\n h_code = self.act(h_code)\n\n h_code = torch.cat((h_code, h_code_locals), 1)\n\n h_code = self.conv3(h_code)\n h_code = self.bn3(h_code)\n h_code = self.act(h_code)\n\n h_code = self.conv4(h_code)\n h_code = self.bn4(h_code)\n x_code4 = self.act(h_code)\n\n return x_code4\n\n\n# For 128 x 128 images\nclass D_NET128(nn.Module):\n def __init__(self, b_jcu=True):\n super(D_NET128, self).__init__()\n ndf = cfg.GAN.DF_DIM\n nef = cfg.TEXT.EMBEDDING_DIM\n self.img_code_s16 = encode_image_by_16times(ndf)\n self.img_code_s32 = downBlock(ndf * 8, ndf * 16)\n self.img_code_s32_1 = Block3x3_leakRelu(ndf * 16, ndf * 8)\n #\n if b_jcu:\n self.UNCOND_DNET = D_GET_LOGITS(ndf, nef, bcondition=False)\n else:\n self.UNCOND_DNET = None\n self.COND_DNET = D_GET_LOGITS(ndf, nef, bcondition=True)\n\n def forward(self, x_var):\n x_code8 = self.img_code_s16(x_var) # 8 x 8 x 8df\n x_code4 = self.img_code_s32(x_code8) # 4 x 4 x 16df\n x_code4 = self.img_code_s32_1(x_code4) # 4 x 4 x 8df\n return x_code4\n\n\n# For 256 x 256 images\nclass D_NET256(nn.Module):\n def __init__(self, b_jcu=True):\n super(D_NET256, self).__init__()\n ndf = cfg.GAN.DF_DIM\n nef = cfg.TEXT.EMBEDDING_DIM\n self.img_code_s16 = encode_image_by_16times(ndf)\n self.img_code_s32 = downBlock(ndf * 8, ndf * 16)\n self.img_code_s64 = downBlock(ndf * 16, ndf * 32)\n self.img_code_s64_1 = Block3x3_leakRelu(ndf * 32, ndf * 16)\n self.img_code_s64_2 = Block3x3_leakRelu(ndf * 16, ndf * 8)\n if b_jcu:\n self.UNCOND_DNET = D_GET_LOGITS(ndf, nef, bcondition=False)\n else:\n self.UNCOND_DNET = None\n self.COND_DNET = D_GET_LOGITS(ndf, nef, bcondition=True)\n\n def forward(self, x_var):\n x_code16 = self.img_code_s16(x_var)\n x_code8 = self.img_code_s32(x_code16)\n x_code4 = self.img_code_s64(x_code8)\n x_code4 = self.img_code_s64_1(x_code4)\n x_code4 = self.img_code_s64_2(x_code4)\n return x_code4\n" ]
[ [ "torch.nn.functional.avg_pool2d", "torch.nn.GRU", "torch.nn.Upsample", "torch.nn.Conv2d", "torch.nn.functional.grid_sample", "torch.nn.Sigmoid", "torch.cat", "torch.nn.utils.rnn.pad_packed_sequence", "torch.nn.Dropout", "torch.nn.BatchNorm2d", "torch.nn.BatchNorm1d", "torch.autograd.Variable", "torch.utils.model_zoo.load_url", "torch.sigmoid", "torch.nn.LSTM", "torch.nn.functional.max_pool2d", "torch.Size", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.Linear", "torch.cuda.FloatTensor", "torch.nn.Embedding", "torch.nn.Tanh", "torch.nn.Sequential", "torch.nn.ReLU", "torch.nn.LeakyReLU" ] ]
jorgstei/Datateknologi
[ "6fea7bf2c557cd93981c6996c7f4cca02f343d9e" ]
[ "TDT4195/image_processing/A1/assignment1/dataloaders.py" ]
[ "import torchvision\nimport torch\n\n\ndef load_dataset(batch_size,\n image_transform,\n root_dir=\"data/\"):\n\n dataset_train = torchvision.datasets.MNIST(\n root=root_dir,\n download=True,\n transform=image_transform\n )\n dataset_test = torchvision.datasets.MNIST(\n root=root_dir,\n download=True,\n train=False,\n transform=image_transform\n )\n dataloader_train = torch.utils.data.DataLoader(\n dataset_train,\n batch_size=batch_size,\n shuffle=True,\n )\n dataloader_test = torch.utils.data.DataLoader(\n dataset_test,\n batch_size=batch_size,\n shuffle=False\n )\n return dataloader_train, dataloader_test\n" ]
[ [ "torch.utils.data.DataLoader" ] ]
sirmarcel/cmlk
[ "e099bf3e255b60675e8e1b3ad29db750dbd6faf3" ]
[ "cmlkit/tune/search/hyperopt.py" ]
[ "\"\"\"Hyperopt search algorithm.\"\"\"\n\nimport numpy as np\nfrom copy import deepcopy\nimport hyperopt as hpo\nimport logging\nfrom itertools import count\n\nfrom cmlkit.engine import Component\nfrom cmlkit.utility.config_helpers import (\n find_pattern_apply_f,\n find_pattern,\n tuples_to_lists,\n)\n\n\nclass Hyperopt(Component):\n \"\"\"Interface to the hyperopt optimisers.\n\n The input space is expected to be a nested dict, where\n variables to be optimised are marked by\n\n [\"hp_function\", \"variable_name\", *args]\n\n Function can either be one of the functions natively supported by\n hyperopt (https://github.com/hyperopt/hyperopt/wiki/FMin), or one of\n two custom extensions:\n hp_loggrid(name, start, stop, num, base): returns hp.choice called on\n a logspace grid from start to stop with num steps (start and end are included)\n hp_loggrid_uniform(name, start, stop, q): returns hp.quniform, with its outputs\n then taken as `2**x`. While loggrid implicitly assumes no correlation between\n choices, this should (in theory) encode the assumption that inputs are related\n in log space. This is an experimental feature.\n\n This will also relucantly work with already-instantiated hyperopt functions,\n but this is a non-supported use and there is no guarantee things won't break.\n\n Parameters:\n space: dict with search space, see above.\n seed: seed for RNG.\n method: either \"tpe\" or \"rand\".\n errors_ok: if True, errors are treated as successful trials with infinite loss,\n otherwise they are ignored. (This is an experimental feature.)\n\n \"\"\"\n\n kind = \"search_hyperopt\"\n\n def __init__(self, space, seed=123, method=\"tpe\", errors_ok=False, context={}):\n super().__init__(context=context)\n\n self.og_space = deepcopy(space)\n\n self.space = deepcopy(space)\n # Parse space to contain hyperopt functions\n find_pattern_apply_f(self.space, is_hyperopt, to_hyperopt)\n self._needs_postprocessing = len(find_pattern(self.space, is_exp2)) > 0\n\n self.seed = seed\n\n self.method = method\n if method == \"tpe\":\n self.algo = hpo.tpe\n elif method == \"rand\":\n self.algo = hpo.rand\n else:\n raise ValueError(f\"Do not recognise suggestion method {method}.\")\n\n # determines whether errors are treated as errors, or as trials with infinite loss\n self.errors_ok = errors_ok\n\n # this is to avoid getting spammed with useless TPE diagnostic info\n algo_logger = logging.getLogger(\"hpo\")\n algo_logger.setLevel(logging.WARNING)\n self.algo.logger = algo_logger\n\n # this is hyperopt internals\n self.domain = hpo.Domain(lambda spc: spc, self.space)\n self._hpopt_trials = hpo.Trials()\n\n # this maps internal hyperopt ids to trial ids\n self._live_trial_mapping = {}\n\n self.rstate = np.random.RandomState(self.seed)\n\n self.counter = count() # used to generate unique, but deterministic trial ids\n\n def _get_config(self):\n return {\n \"space\": self.og_space,\n \"seed\": self.seed,\n \"method\": self.method,\n \"errors_ok\": self.errors_ok,\n }\n\n def suggest(self):\n tid = next(self.counter)\n\n suggestion = self._make_suggestion(tid)\n\n if self._needs_postprocessing:\n find_pattern_apply_f(suggestion, is_exp2, apply_exp2)\n\n return tid, suggestion\n\n def _make_suggestion(self, tid):\n # this is where we call hyperopt\n\n # tell hyperopt that we want one new trial\n new_ids = self._hpopt_trials.new_trial_ids(1)\n self._hpopt_trials.refresh()\n\n # Get new suggestion from Hyperopt;\n new_trials = self.algo.suggest(\n new_ids, self.domain, self._hpopt_trials, self.rstate.randint(2 ** 31 - 1)\n )\n self._hpopt_trials.insert_trial_docs(new_trials)\n self._hpopt_trials.refresh()\n new_trial = new_trials[0]\n\n # keep track of this trial with our tid\n self._live_trial_mapping[tid] = (new_trial[\"tid\"], new_trial)\n\n # Taken from HyperOpt.base.evaluate; I think this one actually\n # draws from the distributions. magic!\n config = hpo.base.spec_from_misc(new_trial[\"misc\"])\n ctrl = hpo.base.Ctrl(self._hpopt_trials, current_trial=new_trial)\n memo = self.domain.memo_from_config(config)\n hpo.utils.use_obj_for_literal_in_memo(self.domain.expr, ctrl, hpo.base.Ctrl, memo)\n\n suggested_config = hpo.pyll.rec_eval(\n self.domain.expr,\n memo=memo,\n print_node_on_error=self.domain.rec_eval_print_node_on_error,\n )\n\n suggested_config = deepcopy(suggested_config)\n\n # hyperopt internally converts tuples to lists\n # but we treat *everything* as list in cmlkit\n # (background: yaml doesn't distinguish them,\n # and everything has to be able to go through yaml)\n tuples_to_lists(suggested_config)\n\n return suggested_config\n\n def submit(self, tid, error=False, loss=None, var=None):\n # Inform hyperopt about the results\n\n ho_trial = self._get_hyperopt_trial(tid)\n\n ho_trial[\"refresh_time\"] = hpo.utils.coarse_utcnow()\n\n if error:\n if self.errors_ok:\n ho_trial[\"state\"] = hpo.base.JOB_STATE_DONE\n ho_trial[\"result\"] = self._to_hyperopt_result(float(\"inf\"), None)\n else:\n ho_trial[\"state\"] = hpo.base.JOB_STATE_ERROR\n\n else:\n assert loss is not None, \"Must submit a loss as result if there was no error.\"\n ho_trial[\"state\"] = hpo.base.JOB_STATE_DONE\n ho_trial[\"result\"] = self._to_hyperopt_result(loss, var)\n\n self._hpopt_trials.refresh()\n del self._live_trial_mapping[tid]\n\n def _to_hyperopt_result(self, loss, var):\n if var is None:\n return {\"loss\": loss, \"status\": \"ok\"}\n else:\n return {\"loss\": loss, \"status\": \"ok\", \"loss_variance\": var}\n\n def _get_hyperopt_trial(self, trial_id):\n if trial_id not in self._live_trial_mapping:\n return\n hyperopt_tid = self._live_trial_mapping[trial_id][0]\n return [t for t in self._hpopt_trials.trials if t[\"tid\"] == hyperopt_tid][0]\n\n\n# at some future point, this will be transitioned to standard config syntax\n\n\ndef is_hyperopt(x):\n \"\"\"Check whether a given object is a hyperopt argument\n\n The format expected is ('hp_NAME_OF_FUNCTION', 'name for hyperopt', remaining, arguments)\n\n \"\"\"\n\n if isinstance(x, (tuple, list)):\n if isinstance(x[0], str):\n s = x[0].split(\"_\", 1)\n if s[0] == \"hp\":\n return True\n\n return False\n\n\ndef is_exp2(x):\n if isinstance(x, (tuple, list)):\n if isinstance(x[0], str):\n return x[0] == \"internal_exp2\"\n\n\ndef apply_exp2(x):\n return 2 ** x[1]\n\n\ndef to_hyperopt(x):\n \"\"\"Convert a sequence to a hyperopt function\n\n Example: ('hp_choice', 'mbtr_1', [1, 2, 3])\n -> hp.choice('mbtr_1', [1, 2, 3])\n\n \"\"\"\n # print(f\"Converting {x}\")\n\n s = x[0].split(\"_\", 1)\n\n try:\n f = getattr(hpo.hp, s[1])\n args = x[1:]\n except AttributeError:\n # implement a custom hp function: hp_loggrid,\n # which first generated a base2 loggrid and\n # then applies hp.choice to it.\n if s[1] == \"loggrid\":\n f = hpo.hp.choice\n args = make_grid(*x[1:])\n elif s[1] == \"loggrid_uniform\":\n return [\"internal_exp2\", hpo.hp.quniform(*x[1:])]\n else:\n raise NotImplementedError(\n \"Hyperopt can't find function named {}!\".format(s[1])\n )\n\n for a in args:\n # this takes care of nesting\n find_pattern_apply_f(a, is_hyperopt, to_hyperopt)\n\n f = f(*args)\n return f\n\n\ndef make_grid(label, start, stop, num, base=2.0):\n\n # it's very important to convert to a plain list here; otherwise\n # we carry numpy floats through the computation, which don't hash\n # to the same values as their plain float counterparts, which in\n # turn makes evaluation ids not match after a roundtrip through yaml.\n choices = np.logspace(start, stop, num=num, base=base).tolist()\n\n return (label, choices)\n" ]
[ [ "numpy.random.RandomState", "numpy.logspace" ] ]
williamdjones/cv_assignment_5
[ "d1fc46b26e44ab0fd14b62ea4f8f12b7c8d43678" ]
[ "losses.py" ]
[ "import numpy as np\nfrom keras import backend as K\n\n\n#\n# Tuning these will adjust the output of your network\n# class_weights[0] = penalty for misclassifying background\n# class_weights[1] = penalty for misclassifying unknown \n# class_weights[2] = penalty for misclassifying foreground \n# Setting class_weights = [.25,0,1] seems to do a reasonable job of\n# balancing precision and recall, thereby giving a higher f-measure\n#\n\n#\n# weighted categorical crossentropy\n# \n# Necessary because of imbalaced classes and \"don't care\" labels\n#\n\n\ndef load_myloss(weights=None):\n if weights is None:\n class_weights = [0.25, 0, 1]\n else:\n class_weights = weights\n class_weights = np.array(class_weights, dtype=np.float32).reshape((1, 1, 1, 3))\n\n def myloss(y_true, y_pred):\n y_true = K.squeeze(K.cast(y_true, 'int32'), -1)\n y_true = K.one_hot(y_true, num_classes=3)\n loss_prelim = K.categorical_crossentropy(y_true, y_pred)\n\n # increase penalty on missing foreground and ignore background class\n weight = K.sum(y_true * class_weights, axis=-1)\n\n # apply weight and average across pixels\n loss_final = K.mean(loss_prelim * weight, axis=[-1, -2])\n\n return loss_final\n\n return myloss\n" ]
[ [ "numpy.array" ] ]
Teaksters/MonoScene
[ "0a5803052b54e57eb98556e53d3bf45be890b269" ]
[ "monoscene/loss/sscMetrics.py" ]
[ "\"\"\"\nPart of the code is taken from https://github.com/waterljwant/SSC/blob/master/sscMetrics.py\n\"\"\"\nimport numpy as np\nfrom sklearn.metrics import accuracy_score, precision_recall_fscore_support\n\n\ndef get_iou(iou_sum, cnt_class):\n _C = iou_sum.shape[0] # 12\n iou = np.zeros(_C, dtype=np.float32) # iou for each class\n for idx in range(_C):\n iou[idx] = iou_sum[idx] / cnt_class[idx] if cnt_class[idx] else 0\n\n mean_iou = np.sum(iou[1:]) / np.count_nonzero(cnt_class[1:])\n return iou, mean_iou\n\n\ndef get_accuracy(predict, target, weight=None): # 0.05s\n _bs = predict.shape[0] # batch size\n _C = predict.shape[1] # _C = 12\n target = np.int32(target)\n target = target.reshape(_bs, -1) # (_bs, 60*36*60) 129600\n predict = predict.reshape(_bs, _C, -1) # (_bs, _C, 60*36*60)\n predict = np.argmax(\n predict, axis=1\n ) # one-hot: _bs x _C x 60*36*60 --> label: _bs x 60*36*60.\n\n correct = predict == target # (_bs, 129600)\n if weight: # 0.04s, add class weights\n weight_k = np.ones(target.shape)\n for i in range(_bs):\n for n in range(target.shape[1]):\n idx = 0 if target[i, n] == 255 else target[i, n]\n weight_k[i, n] = weight[idx]\n correct = correct * weight_k\n acc = correct.sum() / correct.size\n return acc\n\n\nclass SSCMetrics:\n def __init__(self, n_classes):\n self.n_classes = n_classes\n self.reset()\n\n def hist_info(self, n_cl, pred, gt):\n assert pred.shape == gt.shape\n k = (gt >= 0) & (gt < n_cl) # exclude 255\n labeled = np.sum(k)\n correct = np.sum((pred[k] == gt[k]))\n\n return (\n np.bincount(\n n_cl * gt[k].astype(int) + pred[k].astype(int), minlength=n_cl ** 2\n ).reshape(n_cl, n_cl),\n correct,\n labeled,\n )\n\n @staticmethod\n def compute_score(hist, correct, labeled):\n iu = np.diag(hist) / (hist.sum(1) + hist.sum(0) - np.diag(hist))\n mean_IU = np.nanmean(iu)\n mean_IU_no_back = np.nanmean(iu[1:])\n freq = hist.sum(1) / hist.sum()\n freq_IU = (iu[freq > 0] * freq[freq > 0]).sum()\n mean_pixel_acc = correct / labeled if labeled != 0 else 0\n\n return iu, mean_IU, mean_IU_no_back, mean_pixel_acc\n\n def add_batch(self, y_pred, y_true, nonempty=None, nonsurface=None):\n self.count += 1\n mask = y_true != 255\n if nonempty is not None:\n mask = mask & nonempty\n if nonsurface is not None:\n mask = mask & nonsurface\n tp, fp, fn = self.get_score_completion(y_pred, y_true, mask)\n\n self.completion_tp += tp\n self.completion_fp += fp\n self.completion_fn += fn\n\n mask = y_true != 255\n if nonempty is not None:\n mask = mask & nonempty\n tp_sum, fp_sum, fn_sum = self.get_score_semantic_and_completion(\n y_pred, y_true, mask\n )\n self.tps += tp_sum\n self.fps += fp_sum\n self.fns += fn_sum\n\n def get_stats(self):\n if self.completion_tp != 0:\n precision = self.completion_tp / (self.completion_tp + self.completion_fp)\n recall = self.completion_tp / (self.completion_tp + self.completion_fn)\n iou = self.completion_tp / (\n self.completion_tp + self.completion_fp + self.completion_fn\n )\n else:\n precision, recall, iou = 0, 0, 0\n iou_ssc = self.tps / (self.tps + self.fps + self.fns + 1e-5)\n return {\n \"precision\": precision,\n \"recall\": recall,\n \"iou\": iou,\n \"iou_ssc\": iou_ssc,\n \"iou_ssc_mean\": np.mean(iou_ssc[1:]),\n }\n\n def reset(self):\n\n self.completion_tp = 0\n self.completion_fp = 0\n self.completion_fn = 0\n self.tps = np.zeros(self.n_classes)\n self.fps = np.zeros(self.n_classes)\n self.fns = np.zeros(self.n_classes)\n\n self.hist_ssc = np.zeros((self.n_classes, self.n_classes))\n self.labeled_ssc = 0\n self.correct_ssc = 0\n\n self.precision = 0\n self.recall = 0\n self.iou = 0\n self.count = 1e-8\n self.iou_ssc = np.zeros(self.n_classes, dtype=np.float32)\n self.cnt_class = np.zeros(self.n_classes, dtype=np.float32)\n\n def get_score_completion(self, predict, target, nonempty=None):\n predict = np.copy(predict)\n target = np.copy(target)\n\n \"\"\"for scene completion, treat the task as two-classes problem, just empty or occupancy\"\"\"\n _bs = predict.shape[0] # batch size\n # ---- ignore\n predict[target == 255] = 0\n target[target == 255] = 0\n # ---- flatten\n target = target.reshape(_bs, -1) # (_bs, 129600)\n predict = predict.reshape(_bs, -1) # (_bs, _C, 129600), 60*36*60=129600\n # ---- treat all non-empty object class as one category, set them to label 1\n b_pred = np.zeros(predict.shape)\n b_true = np.zeros(target.shape)\n b_pred[predict > 0] = 1\n b_true[target > 0] = 1\n p, r, iou = 0.0, 0.0, 0.0\n tp_sum, fp_sum, fn_sum = 0, 0, 0\n for idx in range(_bs):\n y_true = b_true[idx, :] # GT\n y_pred = b_pred[idx, :]\n if nonempty is not None:\n nonempty_idx = nonempty[idx, :].reshape(-1)\n y_true = y_true[nonempty_idx == 1]\n y_pred = y_pred[nonempty_idx == 1]\n\n tp = np.array(np.where(np.logical_and(y_true == 1, y_pred == 1))).size\n fp = np.array(np.where(np.logical_and(y_true != 1, y_pred == 1))).size\n fn = np.array(np.where(np.logical_and(y_true == 1, y_pred != 1))).size\n tp_sum += tp\n fp_sum += fp\n fn_sum += fn\n return tp_sum, fp_sum, fn_sum\n\n def get_score_semantic_and_completion(self, predict, target, nonempty=None):\n target = np.copy(target)\n predict = np.copy(predict)\n _bs = predict.shape[0] # batch size\n _C = self.n_classes # _C = 12\n # ---- ignore\n predict[target == 255] = 0\n target[target == 255] = 0\n # ---- flatten\n target = target.reshape(_bs, -1) # (_bs, 129600)\n predict = predict.reshape(_bs, -1) # (_bs, 129600), 60*36*60=129600\n\n cnt_class = np.zeros(_C, dtype=np.int32) # count for each class\n iou_sum = np.zeros(_C, dtype=np.float32) # sum of iou for each class\n tp_sum = np.zeros(_C, dtype=np.int32) # tp\n fp_sum = np.zeros(_C, dtype=np.int32) # fp\n fn_sum = np.zeros(_C, dtype=np.int32) # fn\n\n for idx in range(_bs):\n y_true = target[idx, :] # GT\n y_pred = predict[idx, :]\n if nonempty is not None:\n nonempty_idx = nonempty[idx, :].reshape(-1)\n y_pred = y_pred[\n np.where(np.logical_and(nonempty_idx == 1, y_true != 255))\n ]\n y_true = y_true[\n np.where(np.logical_and(nonempty_idx == 1, y_true != 255))\n ]\n for j in range(_C): # for each class\n tp = np.array(np.where(np.logical_and(y_true == j, y_pred == j))).size\n fp = np.array(np.where(np.logical_and(y_true != j, y_pred == j))).size\n fn = np.array(np.where(np.logical_and(y_true == j, y_pred != j))).size\n\n tp_sum[j] += tp\n fp_sum[j] += fp\n fn_sum[j] += fn\n\n return tp_sum, fp_sum, fn_sum\n" ]
[ [ "numpy.sum", "numpy.ones", "numpy.zeros", "numpy.diag", "numpy.nanmean", "numpy.logical_and", "numpy.argmax", "numpy.count_nonzero", "numpy.int32", "numpy.copy", "numpy.mean" ] ]
UTS-AnimalLogicAcademy/nuke-ML-server
[ "3bec5e9efc1f3101e7506401eb57e7b8c955f84c" ]
[ "Models/common/model_builder.py" ]
[ "# Copyright (c) 2019 Foundry.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############################################################################\n\nfrom builtins import range # python 2/3 forward-compatible (xrange)\nimport tensorflow as tf\n\nclass ResNetBlock(tf.keras.layers.Layer):\n \"\"\"Classic ResNet residual block\"\"\"\n\n def __init__(self, new_dim=32, ksize=5, name='resblock'):\n super(ResNetBlock, self).__init__(name=name)\n self.conv2D_1 = tf.keras.layers.Conv2D(\n filters=new_dim, kernel_size=ksize, padding='SAME',\n activation=tf.nn.relu, name='conv1')\n self.conv2D_2 = tf.keras.layers.Conv2D(\n filters=new_dim, kernel_size=ksize, padding='SAME',\n activation=None, name='conv2')\n\n def call(self, inputs):\n x = self.conv2D_1(inputs)\n x = self.conv2D_2(x)\n return x + inputs\n\nclass EncoderDecoder(tf.keras.Model):\n \"\"\"Create an encoder decoder model\"\"\"\n\n def __init__(self, n_levels, scale, channels, name='g_net'):\n super(EncoderDecoder, self).__init__(name=name)\n self.n_levels = n_levels\n self.scale = scale\n\n # Encoder layers\n self.conv1_1 = tf.keras.layers.Conv2D(\n filters=32, kernel_size=5, padding='SAME',\n activation=tf.nn.relu, name='enc1_1')\n self.block1_2 = ResNetBlock(32, 5, name='enc1_2')\n self.block1_3 = ResNetBlock(32, 5, name='enc1_3')\n self.block1_4 = ResNetBlock(32, 5, name='enc1_4')\n self.conv2_1 = tf.keras.layers.Conv2D(\n filters=64, kernel_size=5, strides=2,\n padding='SAME', activation=tf.nn.relu, name='enc2_1')\n self.block2_2 = ResNetBlock(64, 5, name='enc2_2')\n self.block2_3 = ResNetBlock(64, 5, name='enc2_3')\n self.block2_4 = ResNetBlock(64, 5, name='enc2_4')\n self.conv3_1 = tf.keras.layers.Conv2D(\n filters=128, kernel_size=5, strides=2,\n padding='SAME', activation=tf.nn.relu, name='enc3_1')\n self.block3_2 = ResNetBlock(128, 5, name='enc3_2')\n self.block3_3 = ResNetBlock(128, 5, name='enc3_3')\n self.block3_4 = ResNetBlock(128, 5, name='enc3_4')\n # Decoder layers\n self.deblock3_3 = ResNetBlock(128, 5, name='dec3_3')\n self.deblock3_2 = ResNetBlock(128, 5, name='dec3_2')\n self.deblock3_1 = ResNetBlock(128, 5, name='dec3_1')\n self.deconv2_4 = tf.keras.layers.Conv2DTranspose(\n filters=64, kernel_size=4, strides=2,\n padding='SAME', activation=tf.nn.relu, name='dec2_4')\n self.deblock2_3 = ResNetBlock(64, 5, name='dec2_3')\n self.deblock2_2 = ResNetBlock(64, 5, name='dec2_2')\n self.deblock2_1 = ResNetBlock(64, 5, name='dec2_1')\n self.deconv1_4 = tf.keras.layers.Conv2DTranspose(\n filters=32, kernel_size=4, strides=2,\n padding='SAME', activation=tf.nn.relu, name='dec1_4')\n self.deblock1_3 = ResNetBlock(32, 5, name='dec1_3')\n self.deblock1_2 = ResNetBlock(32, 5, name='dec1_2')\n self.deblock1_1 = ResNetBlock(32, 5, name='dec1_1')\n self.deconv0_4 = tf.keras.layers.Conv2DTranspose(\n filters=channels, kernel_size=5, padding='SAME',\n activation=None, name='dec1_0')\n\n def call(self, inputs, reuse=False):\n # Apply encoder decoder\n n, h, w, c = inputs.get_shape().as_list()\n n_outputs = []\n input_pred = inputs\n with tf.compat.v1.variable_scope('', reuse=reuse):\n for i in range(self.n_levels):\n scale = self.scale ** (self.n_levels - i - 1)\n hi = int(round(h * scale))\n wi = int(round(w * scale))\n input_init = tf.image.resize(inputs, [hi, wi], method='bilinear')\n input_pred = tf.stop_gradient(tf.image.resize(input_pred, [hi, wi], method='bilinear'))\n input_all = tf.concat([input_init, input_pred], axis=3, name='inp')\n\n # Encoder\n conv1_1 = self.conv1_1(input_all)\n conv1_2 = self.block1_2(conv1_1)\n conv1_3 = self.block1_3(conv1_2)\n conv1_4 = self.block1_4(conv1_3)\n conv2_1 = self.conv2_1(conv1_4)\n conv2_2 = self.block2_2(conv2_1)\n conv2_3 = self.block2_3(conv2_2)\n conv2_4 = self.block2_4(conv2_3)\n conv3_1 = self.conv3_1(conv2_4)\n conv3_2 = self.block3_2(conv3_1)\n conv3_3 = self.block3_3(conv3_2)\n encoded = self.block3_4(conv3_3)\n\n # Decoder\n deconv3_3 = self.deblock3_3(encoded)\n deconv3_2 = self.deblock3_2(deconv3_3)\n deconv3_1 = self.deblock3_1(deconv3_2)\n deconv2_4 = self.deconv2_4(deconv3_1)\n cat2 = deconv2_4 + conv2_4 # Skip connection\n deconv2_3 = self.deblock2_3(cat2)\n deconv2_2 = self.deblock2_2(deconv2_3)\n deconv2_1 = self.deblock2_1(deconv2_2)\n deconv1_4 = self.deconv1_4(deconv2_1)\n cat1 = deconv1_4 + conv1_4 # Skip connection\n deconv1_3 = self.deblock1_3(cat1)\n deconv1_2 = self.deblock1_2(deconv1_3)\n deconv1_1 = self.deblock1_1(deconv1_2)\n input_pred = self.deconv0_4(deconv1_1)\n\n if i >= 0:\n n_outputs.append(input_pred)\n if i == 0:\n tf.compat.v1.get_variable_scope().reuse_variables()\n return n_outputs\n\ndef mobilenet_transfer(class_number):\n \"\"\"Return a classification model with a mobilenet backbone pretrained on ImageNet\n \n # Arguments:\n class_number: Number of classes / labels to detect\n \"\"\"\n # Import the mobilenet model and discards the last 1000 neuron layer.\n base_model = tf.keras.applications.MobileNet(input_shape=(224,224,3), weights='imagenet',include_top=False, pooling='avg')\n\n x = base_model.output\n x = tf.keras.layers.Dense(1024,activation='relu')(x)\n x = tf.keras.layers.Dense(1024,activation='relu')(x)\n x = tf.keras.layers.Dense(512,activation='relu')(x)\n # Final layer with softmax activation\n preds = tf.keras.layers.Dense(class_number,activation='softmax')(x)\n # Build the model\n model = tf.keras.models.Model(inputs=base_model.input,outputs=preds)\n\n # Freeze base_model\n # for layer in base_model.layers: # <=> to [:86]\n # layer.trainable = False\n # Freeze the first 60 layers and fine-tune the rest\n for layer in model.layers[:60]:\n layer.trainable=False\n for layer in model.layers[60:]:\n layer.trainable=True\n\n return model\n\ndef baseline_model(input_shape, output_param_number=1, hidden_layer_size=16):\n \"\"\"Return a fully connected model with 1 hidden layer\"\"\"\n if hidden_layer_size < output_param_number:\n raise ValueError(\"Neurons in the hidden layer (={}) \\\n should be > output param number (={})\".format(\n hidden_layer_size, output_param_number))\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Flatten(input_shape=input_shape))\n # Regular densely connected NN layer\n model.add(tf.keras.layers.Dense(hidden_layer_size, activation=tf.nn.relu))\n model.add(tf.keras.layers.Dense(output_param_number, activation=None)) # linear activation\n return model" ]
[ [ "tensorflow.keras.layers.Flatten", "tensorflow.keras.layers.Conv2DTranspose", "tensorflow.image.resize", "tensorflow.keras.Sequential", "tensorflow.keras.applications.MobileNet", "tensorflow.keras.models.Model", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.get_variable_scope", "tensorflow.keras.layers.Dense", "tensorflow.concat", "tensorflow.keras.layers.Conv2D" ] ]
brainvisa/aims-free
[ "5852c1164292cadefc97cecace022d14ab362dc4" ]
[ "pyaimsalgo/python/soma/aimsalgo/tests/test_geometric.py" ]
[ "# -*- coding: utf-8 -*-\n# This software and supporting documentation are distributed by\n# Institut Federatif de Recherche 49\n# CEA/NeuroSpin, Batiment 145,\n# 91191 Gif-sur-Yvette cedex\n# France\n#\n# This software is governed by the CeCILL-B license under\n# French law and abiding by the rules of distribution of free software.\n# You can use, modify and/or redistribute the software under the\n# terms of the CeCILL-B license as circulated by CEA, CNRS\n# and INRIA at the following URL \"http://www.cecill.info\".\n#\n# As a counterpart to the access to the source code and rights to copy,\n# modify and redistribute granted by the license, users are provided only\n# with a limited warranty and the software's author, the holder of the\n# economic rights, and the successive licensors have only limited\n# liability.\n#\n# In this respect, the user's attention is drawn to the risks associated\n# with loading, using, modifying and/or developing or reproducing the\n# software by the user in light of its specific status of free software,\n# that may mean that it is complicated to manipulate, and that also\n# therefore means that it is reserved for developers and experienced\n# professionals having in-depth computer knowledge. Users are therefore\n# encouraged to load and test the software's suitability as regards their\n# requirements in conditions enabling the security of their systems and/or\n# data to be ensured and, more generally, to use and operate it in the\n# same conditions as regards security.\n#\n# The fact that you are presently reading this means that you have had\n# knowledge of the CeCILL-B license and that you accept its terms.\n\nfrom __future__ import absolute_import\n\nimport unittest\nfrom soma import aims\nfrom soma import aimsalgo\nimport numpy as np\n\n\nclass GeometricTestCase(unittest.TestCase):\n\n def test_delaunay(self):\n plist = [\n [0, 0],\n [1, 0],\n [1, 1],\n [.5, 1.2],\n [0, 1]]\n d = aimsalgo.simple_delaunay_triangulation(plist)\n self.assertEqual(d, [[3, 0, 1], [3, 1, 2], [4, 0, 3]])\n plist.append([0.5, 0.5])\n d = aimsalgo.simple_delaunay_triangulation(plist)\n self.assertEqual(d, [[5, 0, 1], [5, 1, 2], [5, 2, 3], [5, 3, 4]])\n # NOTE: scipy.spatial.Delaunay gives:\n # from scipy.spatial import Delaunay\n # d2 = Delaunay(plist).simplices\n # array([[1, 5, 0],\n # [2, 5, 1],\n # [5, 2, 3],\n # [5, 4, 0],\n # [4, 5, 3]], dtype=int32)\n # but simple_delaunay_triangulation triangulates an ordered polygon,\n # not a cloud points convex hull.\n\n def test_vertex_remover(self):\n plist = [\n [0, 0],\n [1, 0],\n [1, 1],\n [.5, 1.2],\n [0, 1],\n [0.5, 0.5]]\n d = aimsalgo.simple_delaunay_triangulation(plist)\n mesh = aims.AimsSurfaceTriangle()\n mesh.vertex().assign([p[:2] + [0] for p in plist])\n mesh.polygon().assign(d)\n vr = aims.VertexRemover(mesh)\n gp = vr.geometricProperties()\n gp.doNeighbor()\n self.assertEqual(gp.getNeighbor(),\n [[1, 5], [2, 5, 0], [3, 5, 1], [4, 5, 2], [5, 3],\n [0, 1, 2, 3, 4]])\n self.assertEqual(gp.getTriangleNeighbor(),\n [[0], [0, 1], [1, 2], [2, 3], [3],\n [0, 1, 2, 3]])\n # VertexRemover.__call__ has no more python bindings since the data\n # structures (iterators on complex C++ things) are not bound\n #vr(5)\n #self.assertEqual(gp.getNeighbor(),\n #[[1, 3, 4], [2, 3, 0], [3, 1], [4, 0, 1, 2], [0, 3]])\n #self.assertEqual(gp.getTriangleNeighbor(),\n #[[0, 2], [0, 1], [1], [2, 0, 1], [2]])\n\n # now test several removals in a grid mesh\n grid = np.mgrid[0:10, 0:10:].T\n n = 10\n m = 9\n grid_v = grid.reshape((grid.shape[0] * grid.shape[1], 2))\n grid_v = np.hstack((grid_v, np.zeros((grid_v.shape[0], 1))))\n grid_s = [(i + j*n, i+1 + j*n,\n i+1 + (j+1)*n)\n for j in range(m)\n for i in range(m)] \\\n + [(i + j*n, (i+1) + (j + 1) * n,\n i + (j+1) * n)\n for j in range(m)\n for i in range(m)]\n mesh = aims.AimsTimeSurface_3()\n mesh.vertex().assign(grid_v)\n mesh.polygon().assign(grid_s)\n vr = aims.VertexRemover(mesh)\n ##print('REMOVING PT 57')\n #vr(57)\n ##print('REMOVING PT 36')\n #vr(36)\n ## pt 46 has changed (was 47 formerly)\n #self.assertEqual(mesh.vertex()[46], (7, 4, 0))\n ##print('REMOVING PT 46')\n #vr(46)\n ##aims.write(mesh, '/tmp/vr2.gii')\n ## vertex 48 has \"moved\" again\n #self.assertEqual(mesh.vertex()[46], (8, 4, 0))\n ## 100 - 3 vertices\n #self.assertEqual(len(mesh.vertex()), 97)\n #self.assertEqual(len(mesh.polygon()), 156)\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n" ]
[ [ "numpy.zeros" ] ]
zhigangjiang/LGT-Net
[ "d9a619158b2dc66a50c100e7fa7e491f1df16fd7" ]
[ "loss/grad_loss.py" ]
[ "\"\"\" \n@Date: 2021/08/12\n@description:\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\nfrom visualization.grad import get_all\n\n\nclass GradLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.loss = nn.L1Loss()\n self.cos = nn.CosineSimilarity(dim=-1, eps=0)\n\n self.grad_conv = nn.Conv1d(1, 1, kernel_size=3, stride=1, padding=0, bias=False, padding_mode='circular')\n self.grad_conv.weight = nn.Parameter(torch.tensor([[[1, 0, -1]]]).float())\n self.grad_conv.weight.requires_grad = False\n\n def forward(self, gt, dt):\n gt_direction, _, gt_angle_grad = get_all(gt['depth'], self.grad_conv)\n dt_direction, _, dt_angle_grad = get_all(dt['depth'], self.grad_conv)\n\n normal_loss = (1 - self.cos(gt_direction, dt_direction)).mean()\n grad_loss = self.loss(gt_angle_grad, dt_angle_grad)\n return [normal_loss, grad_loss]\n\n\nif __name__ == '__main__':\n from dataset.mp3d_dataset import MP3DDataset\n from utils.boundary import depth2boundaries\n from utils.conversion import uv2xyz\n from visualization.boundary import draw_boundaries\n from visualization.floorplan import draw_floorplan\n\n def show_boundary(image, depth, ratio):\n boundary_list = depth2boundaries(ratio, depth, step=None)\n draw_boundaries(image.transpose(1, 2, 0), boundary_list=boundary_list, show=True)\n draw_floorplan(uv2xyz(boundary_list[0])[..., ::2], show=True, center_color=0.8)\n\n mp3d_dataset = MP3DDataset(root_dir='../src/dataset/mp3d', mode='train', patch_num=256)\n gt = mp3d_dataset.__getitem__(1)\n gt['depth'] = torch.from_numpy(gt['depth'][np.newaxis]) # batch size is 1\n dummy_dt = {\n 'depth': gt['depth'].clone(),\n }\n # dummy_dt['depth'][..., 20] *= 3 # some different\n\n # show_boundary(gt['image'], gt['depth'][0].numpy(), gt['ratio'])\n # show_boundary(gt['image'], dummy_dt['depth'][0].numpy(), gt['ratio'])\n\n grad_loss = GradLoss()\n loss = grad_loss(gt, dummy_dt)\n print(loss)\n" ]
[ [ "torch.nn.L1Loss", "torch.tensor", "torch.nn.Conv1d", "torch.from_numpy", "torch.nn.CosineSimilarity" ] ]
NehzUx/AutoGraph-KDDCup2020
[ "d2fc228f4ccc5785db3129cca0445a80b6fef11d" ]
[ "src/code_submission/2_pasanju/preprocessing/prepredict.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time: 2020/5/14 20:41\n# @Author: Mecthew\nimport time\n\nimport numpy as np\nimport pandas as pd\nimport scipy\nfrom sklearn.svm import LinearSVC\nfrom sklearn.linear_model import logistic\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import OneHotEncoder\nimport scipy.sparse as sp\nfrom utils.logger import get_logger\nlogger = get_logger(\"INFO\")\n\n\nclass SVM:\n def __init__(self, **kwargs):\n self.name = \"SVM\"\n self._model = CalibratedClassifierCV(LinearSVC(C=1.0, max_iter=500, class_weight=None, random_state=666))\n\n def fit(self, x_train, y_train):\n self._model.fit(x_train, y_train)\n\n def predict(self, x_test):\n return self._model.predict_proba(x_test)\n\n\nclass LR:\n def __init__(self, **kwargs):\n self.name = \"LR\"\n self._model = logistic.LogisticRegression(C=1.0, solver=\"liblinear\", multi_class=\"auto\",\n class_weight=None, max_iter=100, random_state=666)\n\n def fit(self, x_train, y_train):\n self._model.fit(x_train, y_train)\n\n def predict(self, x_test):\n return self._model.predict_proba(x_test)\n\n\ndef prepredict(graph_df, train_indices, use_valid, use_ohe=False):\n t1 = time.time()\n fea_table = graph_df['fea_table'].set_index(keys=\"node_index\")\n train_indices = train_indices\n if use_valid:\n valid_indices = list(set(graph_df['train_indices']) - set(train_indices))\n test_indices = graph_df['test_indices'] + valid_indices\n else:\n test_indices = graph_df['test_indices']\n train_label = graph_df['train_label'].set_index('node_index').loc[train_indices][['label']]\n\n x_train, y_train = fea_table.loc[train_indices].to_numpy(), train_label.to_numpy()\n x_test = fea_table.loc[test_indices].to_numpy()\n lr = LR()\n lr.fit(x_train, y_train)\n\n if use_ohe:\n ohe = OneHotEncoder(handle_unknown=\"ignore\").fit(y_train.reshape(-1, 1))\n x_train_feat, x_test_feat = ohe.transform(np.argmax(lr.predict(x_train), axis=1).reshape(-1, 1)).toarray(), \\\n ohe.transform(np.argmax(lr.predict(x_test), axis=1).reshape(-1, 1)).toarray()\n else:\n x_train_feat, x_test_feat = lr.predict(x_train), \\\n lr.predict(x_test)\n pre_feat = np.concatenate([x_train_feat, x_test_feat], axis=0)\n total_indices = np.concatenate([train_indices, test_indices], axis=0)\n\n train_predict = np.argmax(x_train_feat, axis=1)\n train_acc = accuracy_score(y_true=y_train, y_pred=train_predict)\n t2 = time.time()\n logger.info(\"Time cost for training {}: {}s, train acc {}\".format(lr.name, t2-t1, train_acc))\n\n return pd.DataFrame(data=pre_feat, index=total_indices)\n\n\ndef lpa_predict(graph_df, n_class, train_indices, use_valid, max_iter=100, tol=1e-3, use_ohe=False):\n t1 = time.time()\n train_indices = train_indices\n if use_valid:\n valid_indices = list(set(graph_df['train_indices']) - set(train_indices))\n test_indices = graph_df['test_indices'] + valid_indices\n else:\n test_indices = graph_df['test_indices']\n train_label = graph_df['train_label'].set_index('node_index').loc[train_indices][['label']].to_numpy()\n print(\"Train label shape {}\".format(train_label.shape))\n train_label = train_label.reshape(-1)\n edges = graph_df['edge_file'][['src_idx', 'dst_idx', 'edge_weight']].to_numpy()\n edge_index = edges[:, :2].astype(np.int).transpose() # transpose to (2, num_edges)\n edge_weight = edges[:, 2].astype(np.float)\n num_nodes = len(train_indices) + len(test_indices)\n\n t2 = time.time()\n total_indices = np.concatenate([train_indices, test_indices], axis=0)\n adj = sp.coo_matrix((edge_weight, edge_index), shape=(num_nodes, num_nodes)).tocsr()\n adj = adj[total_indices] # reorder\n adj = adj[:, total_indices]\n\n t3 = time.time()\n logger.debug(\"Time cost for transform adj {}s\".format(t3 - t2))\n row_sum = np.array(adj.sum(axis=1), dtype=np.float)\n d_inv = np.power(row_sum, -1).flatten()\n d_inv[np.isinf(d_inv)] = 0.\n normal_adj = sp.diags(d_inv).dot(adj).tocsr().transpose()\n\n Pll = normal_adj[:len(train_indices), :len(train_indices)].copy()\n Plu = normal_adj[:len(train_indices), len(train_indices):].copy()\n Pul = normal_adj[len(train_indices):, :len(train_indices)].copy()\n Puu = normal_adj[len(train_indices):, len(train_indices):].copy()\n label_mat = np.eye(n_class)[train_label]\n label_mat_prob = label_mat.copy()\n print(\"Pul shape {}, label_mat shape {}\".format(Pul.shape, label_mat_prob.shape))\n\n Pul_dot_lable_mat = Pul.dot(label_mat)\n unlabel_mat = np.zeros(shape=(len(test_indices), n_class))\n iter, changed = 0, np.inf\n t4 = time.time()\n logger.debug(\"Time cost for prepare matrix {}s\".format(t4-t3))\n while iter < max_iter and changed > tol:\n if iter % 10 == 0:\n logger.debug(\"---> Iteration %d/%d, changed: %f\" % (iter, max_iter, changed))\n\n iter += 1\n pre_unlabel_mat = unlabel_mat\n unlabel_mat = Puu.dot(unlabel_mat) + Pul_dot_lable_mat\n label_mat_prob = Pll.dot(label_mat_prob) + Plu.dot(pre_unlabel_mat)\n changed = np.abs(pre_unlabel_mat - unlabel_mat).sum()\n logger.debug(\"Time cost for training lpa {}\".format(time.time() - t4))\n # preds = np.argmax(np.array(unlabel_mat), axis=1)\n # unlabel_mat = np.eye(n_class)[preds]\n train_acc = accuracy_score(y_true=train_label, y_pred=np.argmax(label_mat_prob, axis=1))\n logger.info(\"LPA training acc {}\".format(train_acc))\n logger.info(\"Time cost for LPA {}s\".format(time.time() - t1))\n total_indices = np.concatenate([train_indices, test_indices], axis=0)\n if use_ohe:\n ohe = OneHotEncoder(handle_unknown=\"ignore\").fit(train_label.reshape(-1, 1))\n label_mat_ohe = ohe.transform(np.argmax(label_mat_prob, axis=1).reshape(-1, 1)).toarray()\n unlabel_mat_ohe = ohe.transform(np.argmax(unlabel_mat, axis=1).reshape(-1, 1)).toarray()\n lu_mat_ohe = np.concatenate([label_mat_ohe, unlabel_mat_ohe], axis=0)\n return pd.DataFrame(data=lu_mat_ohe, index=total_indices), train_acc\n else:\n unlabel_mat_prob = unlabel_mat\n lu_mat_prob = np.concatenate([label_mat_prob, unlabel_mat_prob], axis=0)\n return pd.DataFrame(data=lu_mat_prob, index=total_indices), train_acc\n\n\ndef is_nonnegative_integer(x_feats):\n is_nonnegative = (x_feats >= 0).all()\n is_integer = True\n for feat in x_feats:\n feat_int_sum = np.array(feat, dtype=np.int).sum()\n feat_sum = np.array(feat, dtype=np.float).sum()\n is_integer = (feat_int_sum == feat_sum)\n if is_integer is False:\n break\n return is_nonnegative and is_integer\n" ]
[ [ "numpy.eye", "sklearn.linear_model.logistic.LogisticRegression", "sklearn.svm.LinearSVC", "pandas.DataFrame", "numpy.isinf", "numpy.abs", "numpy.argmax", "scipy.sparse.diags", "sklearn.metrics.accuracy_score", "scipy.sparse.coo_matrix", "numpy.power", "numpy.array", "numpy.concatenate", "sklearn.preprocessing.OneHotEncoder" ] ]
Mitchwatts93/thunderfit
[ "a722d9160281cd0058c653181ab662b6988c714d" ]
[ "thunderfit/thunderfit/utilities.py" ]
[ "import logging\r\nfrom json import dump as j_dumps\r\nfrom json import load as j_load\r\nfrom os import mkdir\r\nfrom os.path import join, abspath\r\nfrom time import strftime\r\n\r\nimport pandas as pd\r\nfrom dill import dump as d_dump\r\nfrom dill import load as d_load\r\nfrom numpy import vstack, pad, diff, frombuffer, round, mean, ndarray, std, histogram, exp, percentile\r\nfrom sklearn.mixture import GaussianMixture\r\nfrom tqdm import tqdm\r\n\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nmatplotlib.use('TkAgg')\r\n\r\nfrom . import normalisation\r\n\r\n# tools\r\ndef save_thunder(obj, path, filename='thunder.d'):\r\n \"\"\"\r\n save a thunder object to a path using the dill package\r\n :param obj:\r\n :param path:\r\n :param filename:\r\n :return:\r\n \"\"\"\r\n logging.debug(f'saving using dill {filename}')\r\n d_dump(obj, open(abspath(join(path, filename)), 'wb'))\r\n\r\n\r\ndef load_thunder(path):\r\n \"\"\"\r\n load a dill dumped object\r\n :param path:\r\n :return:\r\n \"\"\"\r\n logging.debug('loading using dill')\r\n obj = d_load(open(path, 'rb'))\r\n return obj\r\n\r\n\r\ndef save_plot(plot, path='.', figname='figure.svg'):\r\n \"\"\"\r\n save a plot as a svg\r\n :param plot:\r\n :param path:\r\n :param figname:\r\n :return:\r\n \"\"\"\r\n logging.debug(f'saving figure {figname}')\r\n plot.savefig(join(path, figname), transparent=True, format='svg')\r\n\r\n\r\ndef save_fit_report(obj, path, filename=\"report.json\"):\r\n \"\"\"\r\n save a fit report dictionary as a json\r\n :param obj:\r\n :param path:\r\n :param filename:\r\n :return:\r\n \"\"\"\r\n logging.debug(f'saving report {filename}')\r\n j_dumps(obj, open(abspath(join(path, filename)), 'w'), indent=4)\r\n\r\n\r\ndef find_closest_indices(list1, list2):\r\n \"\"\"\r\n given two lists returns list of indices indicating which indices in list 1 match each index in list 2. i.e. index 0\r\n of the returned list indicates which index in list 1 matches index 0 in list 2\r\n :param list1: a list of numbers\r\n :param list2: a list of numbers\r\n :return: a list of indices of matches\r\n \"\"\"\r\n try:\r\n list_of_matching_indices = [min(range(len(list1)), key=lambda i: abs(\r\n list1[i] - cent)) for cent in list2] # the lambda function is what min uses\r\n except ValueError:\r\n print('this dataset has no values!')\r\n return\r\n return list_of_matching_indices\r\n\r\n\r\ndef normalise_all(y_bg_rem, bg, y_raw):\r\n \"\"\"\r\n given data with background removed, a background and the raw data, normalise the data with the bg removed and then\r\n normalise the others according to this normalisation (i.e. use the mean and std from that)\r\n :param y_bg_rem: np array of data after bg removed\r\n :param bg: np array of bg\r\n :param y_raw: np array of data before bg removed\r\n :return: data np arrays normalised by svn normalisaiton\r\n \"\"\"\r\n logging.debug('normalising many objects')\r\n y_data_bg_rm, (mean_y_data, std_dev) = normalisation.svn(\r\n y_bg_rem) # normalise the data\r\n # normalise with data from bg subtracted data\r\n background, _ = normalisation.svn(bg, mean_y_data, std_dev)\r\n # normalise with data from bg subtracted data\r\n y_data_norm, _ = normalisation.svn(y_raw, mean_y_data, std_dev)\r\n\r\n return y_data_bg_rm, background, y_data_norm\r\n\r\n\r\ndef safe_list_get(l, idx, default):\r\n \"\"\"fetch items safely from a list, if it isn't long enough return a default value\"\"\"\r\n try:\r\n return l[idx]\r\n except IndexError:\r\n return default\r\n\r\n\r\ndef sharpening_routine(x_data, y_data):\r\n \"\"\"\r\n a function to run a user guided routine to sharpen data using peak_sharpening function\r\n :param x_data: np array of x data\r\n :param y_data: np array of y data\r\n :return: y_data sharpened by user chosen factors\r\n \"\"\"\r\n sharpening_factor = (0, 0)\r\n res_enhanced = y_data\r\n while True:\r\n plt.plot(x_data, res_enhanced)\r\n print(\r\n f\"Do you want to sharpen the peaks to help find components? Note this will not edit the actual data. \"\r\n f\"Current sharpening factor is: {sharpening_factor}\")\r\n plt.show()\r\n ans = input(\r\n \"Please enter the method (either 'power' or 'deriv'), then a comma, then a new sharpening factors \"\r\n \"(comma seperated if mutliple i.e. for derivative), \"\r\n \"or type y to continue with the current factor\")\r\n if ans == 'y':\r\n plt.close()\r\n return y_data\r\n else:\r\n try:\r\n ans = ans.split(',')\r\n _type = ans[0]\r\n ans = ans[1:]\r\n sharpening_factor = [float(fac) for fac in ans]\r\n res_enhanced = peak_sharpening(\r\n y_data, _type, sharpening_factor)\r\n except BaseException:\r\n print(\"You entered an incorrect answer! Trying again...\")\r\n\r\n\r\ndef peak_sharpening(y_data, _type, sharpening_factor):\r\n \"\"\"\r\n function to sharpen peaks. can use power or derivative methods\r\n :param y_data: np array of y data\r\n :param _type: the type of sharpening to be used\r\n :param sharpening_factor: the factors to sharpen with\r\n :return: the data sharpened\r\n \"\"\"\r\n if _type == 'power':\r\n res_enhanced = y_data ** sharpening_factor[0] # raise to the power\r\n elif _type == 'deriv':\r\n y_double_prime = pad(diff(y_data, n=2), (0, 2), 'constant')\r\n y_4_prime = pad(diff(y_data, n=4), (0, 4), 'constant')\r\n res_enhanced = y_data - sharpening_factor[0] * y_double_prime + sharpening_factor[\r\n 1] * y_4_prime # this is the original data minus its\r\n # derivative multiplied by some factor\r\n else:\r\n raise ValueError(\"enter a correct type\")\r\n return res_enhanced\r\n\r\n# tools\r\n\r\n# user inputs and loading etc\r\n\r\n\r\ndef load_data(datapath, x_ind, y_ind, e_ind=None):\r\n \"\"\"\r\n load in data as an np arra. can load from a csv or hs5 pandas\r\n :param datapath: where to get data from\r\n :param x_ind: which column to find x data\r\n :param y_ind: which column to find y data\r\n :param e_ind: optional, which column to find error data\r\n :return: np arrays of the data loaded with nan values dropped across all values (note might break with error values)\r\n \"\"\"\r\n logging.debug('loading data')\r\n if '.h5' in datapath: # if the data is already stored as a pandas df\r\n store = pd.HDFStore(datapath)\r\n keys = store.keys()\r\n if len(keys) > 1:\r\n logging.warning(\r\n \"Too many keys in the hdfstore, will assume all should be concated\")\r\n logging.warning(\"not sure this concat works yet\")\r\n # not sure this will work! concat all keys dfs together\r\n data = store.concat([store[key] for key in keys])\r\n else:\r\n # if only one key then we use it as the datafile\r\n data = store[keys[0]]\r\n else: # its a txt or csv file\r\n # load in, works for .txt and .csv\r\n data = pd.read_csv(datapath, header=None, sep='\\t', dtype='float')\r\n if len(data.columns) < 2:\r\n # load in, works for .txt and .csv\r\n data = pd.read_csv(\r\n datapath,\r\n header=None,\r\n sep=r'\\s+',\r\n dtype='float')\r\n # this needs to be made more flexible/user defined\r\n if e_ind: # if we have specified this column then we use it, otherwise just x and y\r\n assert (len(data.columns) >=\r\n 2), \"You have specified an e_ind but there are less than 3 columns in the data\"\r\n e_data = data[e_ind].values\r\n else:\r\n e_data = None\r\n\r\n data.dropna() # drop any rows with NaN etc in them\r\n\r\n x_data = data[x_ind].values\r\n y_data = data[y_ind].values\r\n\r\n return x_data, y_data, e_data\r\n\r\n\r\ndef map_unique_coords(x_data, y_data, x_coords, y_coords):\r\n \"\"\"\r\n function to get the unique coordinate values out from np arrays of data and coordinates\r\n :param x_data:np array of x data\r\n :param y_data: np array of y data\r\n :param x_coords: np array of x coordinates, index corresponds to x and y data\r\n :param y_coords: np array of y coordinates, index corresponds to x and y data\r\n :return: lists of np arrays, each element matches, x_coords and y_coords contain lists of numbers only. so e.g.\r\n index 0 of all has the x and y coordinates in coords lists at 0, and x and y data in those lists at 0 as np arrays\r\n \"\"\"\r\n logging.debug('parsing coordinates')\r\n data = vstack((x_coords, y_coords, x_data, y_data)\r\n ).transpose() # now have columns as the data\r\n df = pd.DataFrame(\r\n data=data,\r\n columns=[\r\n 'x_coords',\r\n 'y_coords',\r\n 'x_data',\r\n 'y_data'])\r\n # get a dictionary of the unique values for\r\n unique_dict = dict(tuple(df.groupby(['x_coords', 'y_coords'])))\r\n # coordinates (as tuples of (x,y)) and then the whole df rows for these\r\n # values\r\n\r\n x_data, y_data, x_coords, y_coords = [], [], [], []\r\n for key in unique_dict.keys():\r\n x_data_ = unique_dict[key]['x_data'].values # get the x_data\r\n x_data.append(x_data_)\r\n y_data_ = unique_dict[key]['y_data'].values\r\n y_data.append(y_data_)\r\n x_coords.append(key[0])\r\n y_coords.append(key[1])\r\n\r\n return x_data, y_data, x_coords, y_coords\r\n\r\n\r\ndef parse_param_file(filepath='./params.txt'):\r\n \"\"\"\r\n parse a params file which we assume is a dictionary\r\n :param filepath: str: path to params file\r\n :return: dictionary of paramters\r\n \"\"\"\r\n # maybe use json loads if you end up writing parameter files non-manually\r\n logging.debug('parsing params file')\r\n with open(filepath, 'r') as f:\r\n arguments = j_load(f)\r\n f.close()\r\n\r\n # TODO: add some checks to user passed data\r\n return arguments\r\n\r\n\r\ndef parse_args(arg):\r\n \"\"\"\r\n convert argparse arguments into a dictionary for consistency later\r\n :param arg: argparse parsed args\r\n :return: dictionary of parameters\r\n \"\"\"\r\n logging.debug('parsing args')\r\n arguments = {}\r\n arguments['x_ind'] = arg.x_ind\r\n arguments['y_ind'] = arg.y_ind\r\n arguments['e_ind'] = arg.e_ind\r\n arguments['datapath'] = arg.datapath\r\n arguments['no_peaks'] = arg.no_peaks\r\n arguments['background'] = arg.background\r\n arguments['scarf_params'] = arg.scarf_params\r\n arguments['peak_types'] = arg.peak_types\r\n arguments['peak_centres'] = arg.peak_centres\r\n arguments['peak_widths'] = arg.peak_widths\r\n arguments['peak_amps'] = arg.peak_amps\r\n arguments['tightness'] = arg.tightness\r\n arguments['bounds'] = arg.bounds\r\n\r\n # TODO: add some checks to user passed data\r\n return arguments\r\n\r\n\r\ndef make_dir(dirname, i=1):\r\n \"\"\"\r\n function to make a directory, recursively adding _new if that name already exists\r\n :param dirname: str: name of directory to create\r\n :param i: the run number we are on\r\n :return: str: the directory name which was available, and all subsequent data should be saved in\r\n \"\"\"\r\n logging.debug('making dir')\r\n try:\r\n mkdir(f'{dirname}')\r\n except FileExistsError as e:\r\n dirname = make_dir(f'{dirname}_new', i + 1)\r\n if i == 1:\r\n print(e, f'. So I named the file: {dirname}')\r\n return dirname\r\n return dirname\r\n\r\n\r\ndef clip_data(x_data, y_data, clips=None):\r\n \"\"\"\r\n given data either clip it or run a user guided routine to clip it\r\n :param x_data: np array of x data\r\n :param y_data: np array of y data\r\n :param clips: either none or a list of two values which are left and right clips in terms of x values\r\n :return: the indices of the clips to use\r\n \"\"\"\r\n logging.debug('clipping data')\r\n if clips:\r\n clip_left, clip_right = clips\r\n clip_left = find_closest_indices(list(x_data), [clip_left])[0]\r\n clip_right = find_closest_indices(list(x_data), [clip_right])[0]\r\n else:\r\n clip_left, clip_right = 0, len(x_data) - 1\r\n while True:\r\n fig, ax = plt.subplots()\r\n ax.plot(x_data[clip_left:clip_right], y_data[clip_left:clip_right])\r\n print(\r\n f\"Removing background, please type two x values seperated by a space for the clips. \\n\"\r\n f\"Current values are: {x_data[clip_left]}, {x_data[clip_right]}. \\n\"\r\n f\"PLEASE MAKE SURE YOU ENTER IN THE SAME ORDER AS HERE. i.e. if first value is larger than right then the \"\r\n f\"first value will be the large x_clip second small\")\r\n plt.show(block=True)\r\n ans = input(\r\n \"If you are happy with the clips type y. If not then please type a new pair of values \")\r\n if ans == 'y':\r\n break\r\n else:\r\n try:\r\n ans = ans.split(' ')\r\n if len(ans) != 2:\r\n raise ValueError(\r\n \"The tuple was more than two elements long\")\r\n clip_left = float(ans[0])\r\n clip_left = find_closest_indices(\r\n list(x_data), [clip_left])[0]\r\n clip_right = float(ans[1])\r\n clip_right = find_closest_indices(\r\n list(x_data), [clip_right])[0]\r\n except ValueError:\r\n print(\"You entered an incorrect answer! Trying again...\")\r\n\r\n plt.close()\r\n return clip_left, clip_right\r\n\r\n\r\ndef apply_func(key_kwargs_, func):\r\n \"\"\"\r\n given some keywords and a function call the function\r\n :param key_kwargs_: a tuple of (key, args) to use\r\n :param func: function to call\r\n :return: the key for this and the value returned from calling the func\r\n \"\"\"\r\n key = key_kwargs_[0]\r\n kwargs_ = key_kwargs_[1]\r\n val = func(*kwargs_)\r\n return key, val\r\n\r\n\r\ndef setup_logger(log_name):\r\n \"\"\"\r\n function to setup a logger to save to file\r\n :param log_name:\r\n :return:\r\n \"\"\"\r\n curr_time = strftime('%d_%m_%Y__%H;%M')\r\n log_filename = f\"{log_name}_{curr_time}.log\"\r\n logging.getLogger().setLevel(logging.DEBUG)\r\n logger = logging.getLogger('')\r\n logger.handlers = []\r\n logging.basicConfig(filename=log_filename, level=logging.DEBUG)\r\n logging.info('have read in user arguments')\r\n return log_filename\r\n\r\n\r\ndef gif_maker(bag, filename):\r\n \"\"\"\r\n function to make a gif of all the plots (with no uncertainty) and save it at filename\r\n :param bag: a dictionary of the thunder objects which have been fit etc and are to be plotted\r\n :param filename: where to save the gif\r\n :return:\r\n \"\"\"\r\n bags = iter(bag.values())\r\n\r\n def update(i):\r\n thund = next(bags)\r\n ax, fig = thund.plot_all(plot_unc=False)\r\n plt.text(\r\n 0.1,\r\n 0.9,\r\n f'PLOT_{i}',\r\n horizontalalignment='center',\r\n verticalalignment='center',\r\n transform=ax.transAxes)\r\n fig.canvas.draw()\r\n img = frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')\r\n img = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))\r\n plt.close()\r\n return img\r\n\r\n import imageio\r\n print(\"Creating gif\")\r\n imageio.mimsave(filename, tqdm([update(i) for i in range(len(bag))]), fps=2)\r\n#\r\n\r\ndef cosmic_rays(y_data, width_threshold=3):\r\n \"\"\"\r\n this currently fails if data is sloping and cosmic ray is below max values. change to sloping mad in future\r\n :param y_data: np array of data\r\n :return:\r\n \"\"\"\r\n \"\"\"\r\n import numpy as np\r\n from scipy.signal import find_peaks\r\n import ipdb\r\n ipdb.set_trace()\r\n peaks, properties = find_peaks(y_data, width=0, rel_height=0.8) # find peaks with a minimum prominence of zero -\r\n # finds widths at 0.8 the height of peaks - quick experiment shows this is optimal for a random example\r\n # - needs more testing\r\n prominences = properties['prominences']\r\n peak_ind = np.argwhere(prominences > np.percentile(prominences, 99))[:,0] # indices of peaks with prominence in 99th percentile\r\n y_data_peak_indices = np.take(peaks, peak_ind)\r\n\r\n widths = np.take(properties['widths'], peak_ind) # these are the widths with this peak prominence\r\n np.argwhere(widths < width_threshold) # this may fail often?\r\n\r\n \"\"\"\r\n\r\n\r\n\r\n \"\"\"\r\n mad = np.median(abs(y_data - np.median(y_data))) # median abs deviation of the data\r\n y_mad = abs(y_data - np.median(y_data)) / mad # abs mdeviation from median divided by mad to get ratio\r\n cutoff = np.percentile(y_mad, 99.5) # what values make up the 99th percentile, above this are rare!\r\n bad_indices = np.argwhere(y_mad > cutoff)\r\n for i in bad_indices[:,0]:\r\n y_data[i] = np.mean(y_data[i-10:i+10]) # set as the mean value in a window around the peak\r\n \"\"\"\r\n #### ideas:\r\n ### detection:\r\n ## r-pca as from stanford - probably not good here. https://medium.com/netflix-techblog/rad-outlier-detection-on-big-data-d6b0494371cc : https://github.com/dganguli/robust-pca/blob/master/r_pca.py\r\n ## differentiate in time across multiple spectra, use that to detect spikes - for single spectra do user guided 'zap' function?\r\n ## just smoothing? or smoothing and then a residual threshold?\r\n ## find peaks using scipy and delete low width peaks, doesn't work if small though\r\n ## https://journals.sagepub.com/doi/pdf/10.1366/000370207781745847 - simulate the data and set a threshold for\r\n # residual, replace pixels with simulated. this would involve a cosmic spike removal step at the end of fitting.\r\n # if fitting has already failed then wouldn't work. could be a bit delicate\r\n ## asto guy: https://cosmicrayapp.com/2017/02/03/signal-processing-details/\r\n ## mad - also captures peaks in general so no bueno\r\n ## https://pureportal.strath.ac.uk/files-asset/38783720/Littlejohn_Automated_cosmic_spike_filter.pdf\r\n ## https://www.osti.gov/pages/servlets/purl/1334720\r\n ## https://www.researchgate.net/publication/233403614_Automated_Cosmic_Spike_Filter_Optimized_for_Process_Raman_Spectroscopy\r\n\r\n\r\n return y_data\r\n\r\n\r\ndef hist_chooser(u_vals, bins, lower_per=1, upper_perc=99):\r\n range_l, range_h = percentile(u_vals, lower_per), percentile(u_vals, upper_perc)\r\n heights, edges = histogram(a=u_vals, bins=bins, range=(range_l, range_h))\r\n if len(edges) > 70:\r\n heights, edges = hist_chooser(u_vals, bins, lower_per + 2, upper_perc - 2)\r\n return heights, edges\r\n\r\n\r\ndef histogram_func(u_vals:ndarray, x_label, gmm=False, f=None, ax=None, bins='auto'):\r\n assert(len(u_vals.shape) == 1), \"The nd array passed to histogram func must be a 1d ndarray\"\r\n if not ax or f: # then create the figure\r\n f = plt.figure()\r\n ax = f.add_subplot(111)\r\n # get the hist\r\n heights, edges = hist_chooser(u_vals, bins)\r\n widths = [0.8*(edges[i+1] - edges[i]) for i in range(len(edges) - 1)]\r\n edges = edges[:-1]\r\n # plot it\r\n ax.bar(edges, heights, width=widths, color='r', align='edge')\r\n ax.grid(axis='y', alpha=0.75)\r\n ax.set(xlabel=x_label, ylabel='Frequency')\r\n mu = round(mean(u_vals), 1)\r\n mu_unc = round(std(u_vals) / len(u_vals), 1) # standard error\r\n sig = round(std(u_vals), 1) # sigma\r\n\r\n plt.text(0.3, 0.9, r'$\\mu=$' + f'{mu}' + f'pm {mu_unc}' + ', ' + r'$\\sigma=$' + f'{sig}' ,\r\n horizontalalignment='center', verticalalignment='center', transform=ax.transAxes)\r\n if gmm: # then add gaussian mixture\r\n vals, bins = histogram(u_vals, bins='auto')\r\n gmm = GaussianMixture(n_components=3)\r\n gmm = gmm.fit(u_vals[:, None])\r\n plt.plot(bins[:None], exp(gmm.score_samples(bins[:, None])))\r\n plt.text(0.3, 0.8, r'GaussianMixture Components:', horizontalalignment='center',\r\n verticalalignment='center', transform=ax.transAxes)\r\n return f, ax, bins\r\n" ]
[ [ "numpy.vstack", "numpy.diff", "numpy.histogram", "pandas.read_csv", "matplotlib.pyplot.figure", "pandas.DataFrame", "numpy.std", "matplotlib.pyplot.subplots", "pandas.HDFStore", "matplotlib.pyplot.show", "matplotlib.pyplot.text", "matplotlib.pyplot.close", "matplotlib.use", "matplotlib.pyplot.plot", "sklearn.mixture.GaussianMixture", "numpy.percentile", "numpy.mean" ] ]
Amit-H/Rosalind-Problems
[ "b0256b66fd1e3e6669899eb24ce5a7ed055e92f1" ]
[ "Bioinformatics Stronghold/iprb.py" ]
[ "from scipy.special import comb\n\ndef mendelian_probability(k, m, n):\n '''\n Calculates the chance of getting dominant alleles in a population\n\n Input params:\n k = homozygous dominant\n m = heterozygous\n n = homozygous recessive\n '''\n total_population = k + m + n \n total_combinations = comb(total_population, 2)\n dominant_combinations = comb(k, 2) + k*m + k*n + .5*m*n + .75*comb(m, 2)\n probability = dominant_combinations/total_combinations\n return probability\n\n# Example Call: \nk = 19\nm = 30\nn = 29\nprint(mendelian_probability(k, m, n))" ]
[ [ "scipy.special.comb" ] ]
Bastianleaf/TravellingSalesman
[ "fafd7bb2e2ac79abc23bc261899e7d89cd0d8e9e" ]
[ "Main/perfomance_graph.py" ]
[ "from Main.Tools import *\nfrom time import time\nimport matplotlib.pyplot as plt\nimport numpy\n\n\n#Parametros Globales\ndataset_path = \"../Data/ciudades_europa\" # 1- \"../Data/ciudades_europa 2- \"../Data/region_metropolitana 3- \"../Data/cities\norigin_name = \"Madrid\" #Nombre de la ciudad, depende del dataset\npopulation_size = 20 #Individuos de poblacion\ngenerations_number = 10 #Limite de generaciones identicas\n\n## Creacion de lista de ciudades con caminos al azar\n## manteniendo ciudad elegida como base para el origen y destino final\ndata_set = DataManagement(dataset_path)\ncities = data_set.create_cities(origin_name)\n# generate random\nPopulation = generate_random_route(population_size, cities, generations_number)\n\n# Algoritmo Principal\nprint(\"Calculando ruta optima...\")\nstart_time = time()\ncount = 0\ndata_x = []\ndata_y = []\nwhile not Population.optimal:\n\tdata_x.append(count)\n\tdata_y.append(numpy.mean(list(map(lambda x: x.score, Population.population))))\n\tPopulation.evolution()\n\tcount += 1\nelapsed_time = time() - start_time\nprint(data_y)\n\n# Impresion de informacion\nprint(\"Generacion: \" + str(Population.generation))\noptimal = Population.population[random.randint(0, Population.size - 1)]\nroad = list(map(lambda x: x.value, optimal.cities))\nprint(\"Camino optimo: \" + str(road))\ncities = list(map(lambda x: x.name, optimal.cities))\nprint(\"Ciudades: \" + str(cities))\nprint(\"Peso de camino optimo: \" + str(round(optimal.score, 2)) + \" km\")\nprint(\"Tiempo demorado: %.10f segundos.\" % elapsed_time)\n\nplt.grid(True)\nplt.plot(data_x, data_y)\nplt.title('Camino más corto según generación. ')\nplt.xlabel(\"Generacion de la poblacion\")\nplt.show()\n\n" ]
[ [ "matplotlib.pyplot.grid", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel" ] ]
QinglinDong/nilearn-extenstion
[ "8eba7f29f1d5a788758514a639ed1c639041fe7d" ]
[ "nilearn/decomposition/canica.py" ]
[ "\"\"\"\nCanICA\n\"\"\"\n\n# Author: Alexandre Abraham, Gael Varoquaux,\n# License: BSD 3 clause\n\nfrom operator import itemgetter\n\nimport numpy as np\nfrom scipy.stats import scoreatpercentile\nfrom sklearn.decomposition import fastica\nfrom sklearn.externals.joblib import Memory, delayed, Parallel\nfrom sklearn.utils import check_random_state\n\nfrom .multi_pca import MultiPCA\n\n\nclass CanICA(MultiPCA):\n \"\"\"Perform Canonical Independent Component Analysis.\n\n Parameters\n ----------\n mask: Niimg-like object or MultiNiftiMasker instance, optional\n Mask to be used on data. If an instance of masker is passed,\n then its mask will be used. If no mask is given,\n it will be computed automatically by a MultiNiftiMasker with default\n parameters.\n\n n_components: int\n Number of components to extract. By default n_components=20.\n\n smoothing_fwhm: float, optional, default 6mm\n If smoothing_fwhm is not None, it gives the size in millimeters of the\n spatial smoothing to apply to the signal.\n\n do_cca: boolean, optional\n Indicate if a Canonical Correlation Analysis must be run after the\n PCA.\n\n standardize: boolean, optional, default True\n If standardize is True, the time-series are centered and normed:\n their variance is put to 1 in the time dimension.\n\n detrend : boolean, optional, default True\n If detrend is True, the time-series will be detrended before\n components extraction.\n\n threshold: None, 'auto' or float\n If None, no thresholding is applied. If 'auto',\n then we apply a thresholding that will keep the n_voxels,\n more intense voxels across all the maps, n_voxels being the number\n of voxels in a brain volume. A float value indicates the\n ratio of voxels to keep (2. means that the maps will together\n have 2 x n_voxels non-zero voxels ). The float value\n must be bounded by [0. and n_components].\n\n n_init: int, optional\n The number of times the fastICA algorithm is restarted\n\n random_state: int or RandomState\n Pseudo number generator state used for random sampling.\n\n target_affine: 3x3 or 4x4 matrix, optional\n This parameter is passed to image.resample_img. Please see the\n related documentation for details.\n\n target_shape: 3-tuple of integers, optional\n This parameter is passed to image.resample_img. Please see the\n related documentation for details.\n\n low_pass: None or float, optional\n This parameter is passed to signal.clean. Please see the related\n documentation for details\n\n high_pass: None or float, optional\n This parameter is passed to signal.clean. Please see the related\n documentation for details\n\n t_r: float, optional\n This parameter is passed to signal.clean. Please see the related\n documentation for details\n\n mask_strategy: {'background', 'epi'}, optional\n The strategy used to compute the mask: use 'background' if your\n images present a clear homogeneous background, and 'epi' if they\n are raw EPI images. Depending on this value, the mask will be\n computed from masking.compute_background_mask or\n masking.compute_epi_mask. Default is 'epi'.\n\n mask_args: dict, optional\n If mask is None, these are additional parameters passed to\n masking.compute_background_mask or masking.compute_epi_mask\n to fine-tune mask computation. Please see the related documentation\n for details.\n\n memory: instance of joblib.Memory or string\n Used to cache the masking process.\n By default, no caching is done. If a string is given, it is the\n path to the caching directory.\n\n memory_level: integer, optional\n Rough estimator of the amount of memory used by caching. Higher value\n means more memory for caching.\n\n n_jobs: integer, optional\n The number of CPUs to use to do the computation. -1 means\n 'all CPUs', -2 'all CPUs but one', and so on.\n\n verbose: integer, optional\n Indicate the level of verbosity. By default, nothing is printed\n\n Attributes\n ----------\n `components_` : 2D numpy array (n_components x n-voxels)\n Masked ICA components extracted from the input images. They can be\n unmasked thanks to the `masker_` attribute.\n\n Deprecated since version 0.4.1. Use `components_img_` instead.\n\n `components_img_` : 4D Nifti image\n 4D image giving the extracted ICA components. Each 3D image is a\n component.\n\n New in version 0.4.1.\n\n `masker_` : instance of MultiNiftiMasker\n Masker used to filter and mask data as first step. If an instance of\n MultiNiftiMasker is given in `mask` parameter,\n this is a copy of it. Otherwise, a masker is created using the value\n of `mask` and other NiftiMasker related parameters as initialization.\n\n `mask_img_` : Niimg-like object\n See http://nilearn.github.io/manipulating_images/input_output.html\n The mask of the data. If no mask was given at masker creation, contains\n the automatically computed mask.\n\n References\n ----------\n * G. Varoquaux et al. \"A group model for stable multi-subject ICA on\n fMRI datasets\", NeuroImage Vol 51 (2010), p. 288-299\n\n * G. Varoquaux et al. \"ICA-based sparse features recovery from fMRI\n datasets\", IEEE ISBI 2010, p. 1177\n\n \"\"\"\n\n def __init__(self, mask=None, n_components=20, smoothing_fwhm=6,\n do_cca=True,\n threshold='auto',\n n_init=10,\n random_state=None,\n standardize=True, detrend=True,\n low_pass=None, high_pass=None, t_r=None,\n target_affine=None, target_shape=None,\n mask_strategy='epi', mask_args=None,\n memory=Memory(cachedir=None), memory_level=0,\n n_jobs=1, verbose=0\n ):\n\n super(CanICA, self).__init__(\n n_components=n_components,\n do_cca=do_cca,\n random_state=random_state,\n # feature_compression=feature_compression,\n mask=mask, smoothing_fwhm=smoothing_fwhm,\n standardize=standardize, detrend=detrend,\n low_pass=low_pass, high_pass=high_pass, t_r=t_r,\n target_affine=target_affine, target_shape=target_shape,\n mask_strategy=mask_strategy, mask_args=mask_args,\n memory=memory, memory_level=memory_level,\n n_jobs=n_jobs, verbose=verbose)\n\n def _unmix_components(self, components):\n \"\"\"Core function of CanICA than rotate components_ to maximize\n independance\"\"\"\n random_state = check_random_state(self.random_state)\n\n seeds = random_state.randint(np.iinfo(np.int32).max, size=self.n_init)\n # Note: fastICA is very unstable, hence we use 64bit on it\n results = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(\n delayed(self._cache(fastica, func_memory_level=2))\n (components.astype(np.float64), whiten=True, fun='cube',\n random_state=seed)\n for seed in seeds)\n\n ica_maps_gen_ = (result[2].T for result in results)\n ica_maps_and_sparsities = ((ica_map,\n np.sum(np.abs(ica_map), axis=1).max())\n for ica_map in ica_maps_gen_)\n ica_maps, _ = min(ica_maps_and_sparsities, key=itemgetter(-1))\n\n # Thresholding\n ratio = None\n if isinstance(self.threshold, float):\n ratio = self.threshold\n elif self.threshold == 'auto':\n ratio = 1.\n elif self.threshold is not None:\n raise ValueError(\"Threshold must be None, \"\n \"'auto' or float. You provided %s.\" %\n str(self.threshold))\n if ratio is not None:\n abs_ica_maps = np.abs(ica_maps)\n threshold = scoreatpercentile(\n abs_ica_maps,\n 100. - (100. / len(ica_maps)) * ratio)\n ica_maps[abs_ica_maps < threshold] = 0.\n # We make sure that we keep the dtype of components\n self.components_ = ica_maps.astype(self.components_.dtype)\n\n # flip signs in each component so that peak is +ve\n for component in self.components_:\n if component.max() < -component.min():\n component *= -1\n if hasattr(self, \"masker_\"):\n self.components_img_ = self.masker_.inverse_transform(self.components_)\n\n # Overriding MultiPCA._raw_fit overrides MultiPCA.fit behavior\n def _raw_fit(self, data):\n \"\"\"Helper function that directly process unmasked data.\n\n Useful when called by another estimator that has already\n unmasked data.\n\n Parameters\n ----------\n data: ndarray or memmap\n Unmasked data to process\n\n \"\"\"\n components = MultiPCA._raw_fit(self, data)\n self._unmix_components(components)\n return self\n def _raw_fit2(self, data):\n \"\"\"Helper function that directly process unmasked data.\n\n Useful when called by another estimator that has already\n unmasked data.\n\n Parameters\n ----------\n data: ndarray or memmap\n Unmasked data to process\n\n \"\"\"\n components = MultiPCA._raw_fit(self, data)\n random_state = check_random_state(self.random_state)\n\n seeds = random_state.randint(np.iinfo(np.int32).max, size=self.n_init)\n # Note: fastICA is very unstable, hence we use 64bit on it\n results = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(\n delayed(self._cache(fastica, func_memory_level=2))\n (components.astype(np.float64), whiten=True, fun='cube',\n random_state=seed)\n for seed in seeds)\n\n ica_maps_gen_ = (result[2].T for result in results)\n ica_maps_and_sparsities = ((ica_map,\n np.sum(np.abs(ica_map), axis=1).max())\n for ica_map in ica_maps_gen_)\n ica_maps, _ = min(ica_maps_and_sparsities, key=itemgetter(-1))\n return ica_maps\n def _raw_fit3(self, data):\n \"\"\"Helper function that directly process unmasked data.\n\n Useful when called by another estimator that has already\n unmasked data.\n\n Parameters\n ----------\n data: ndarray or memmap\n Unmasked data to process\n\n \"\"\"\n components = MultiPCA._raw_fit(self, data)\n random_state = check_random_state(self.random_state)\n\n seeds = random_state.randint(np.iinfo(np.int32).max, size=10)\n # Note: fastICA is very unstable, hence we use 64bit on it\n results = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(\n delayed(self._cache(fastica, func_memory_level=2))\n (components.astype(np.float64), whiten=True, fun='cube',\n random_state=seed)\n for seed in seeds)\n\n return results\n#from unmix_components\n def thresholding(self,ica_maps):\n ratio=1\n #ica_maps = ica_maps.T\n\n S = np.sqrt(np.sum(ica_maps ** 2, axis=1))\n S[S == 0] = 1\n ica_maps /= S[:, np.newaxis]\n\n abs_ica_maps = np.abs(ica_maps)\n threshold = scoreatpercentile(\n abs_ica_maps,\n 100. - (100. / len(ica_maps)) * ratio)\n ica_maps[abs_ica_maps < threshold] = 0.\n # We make sure that we keep the dtype of components\n #ica_maps= ica_maps.astype(self.components_.dtype)\n\n # flip signs in each component so that peak is +ve\n for component in ica_maps:\n if component.max() < -component.min():\n component *= -1\n return ica_maps\n\n def _check_components_(self):\n if not hasattr(self, 'components_'):\n raise ValueError(\"Object has no components_ attribute. \"\n \"This is probably because fit has not \"\n \"been called.\")" ]
[ [ "numpy.sum", "sklearn.utils.check_random_state", "numpy.abs", "numpy.iinfo", "sklearn.externals.joblib.Memory", "sklearn.externals.joblib.Parallel" ] ]
yazdotai/tensorlayer
[ "dea9d4023b578b4452c3861618e46466d4553658" ]
[ "tensorlayer/files/utils.py" ]
[ "#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\n\nimport gzip\nimport math\nimport pickle\nimport progressbar\nimport re\nimport requests\nimport shutil\nimport tarfile\nimport time\nimport zipfile\n\nfrom tqdm import tqdm\n\nfrom six.moves import cPickle\n# from six.moves import zip\n\nfrom lxml import etree\nimport xml.etree.ElementTree as ET\n\nif sys.version_info[0] == 2:\n from urllib import urlretrieve\nelse:\n from urllib.request import urlretrieve\n\nimport matplotlib.pyplot as plt\n\nimport scipy.io as sio\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.python.platform import gfile\n\nfrom tensorlayer import tl_logging as logging\n\nfrom tensorlayer import nlp\nfrom tensorlayer import utils\nfrom tensorlayer import visualize\n\n__all__ = [\n 'assign_params',\n 'del_file',\n 'del_folder',\n 'download_file_from_google_drive',\n 'exists_or_mkdir',\n 'file_exists',\n 'folder_exists',\n 'load_and_assign_npz',\n 'load_and_assign_npz_dict',\n 'load_ckpt',\n 'load_cropped_svhn',\n 'load_file_list',\n 'load_folder_list',\n 'load_npy_to_any',\n 'load_npz',\n 'maybe_download_and_extract',\n 'natural_keys',\n 'npz_to_W_pdf',\n 'read_file',\n 'save_any_to_npy',\n 'save_ckpt',\n 'save_npz',\n 'save_npz_dict',\n]\n\n\n## Load dataset functions\ndef load_mnist_dataset(shape=(-1, 784), path='data'):\n \"\"\"Load the original mnist.\n\n Automatically download MNIST dataset and return the training, validation and test set with 50000, 10000 and 10000 digit images respectively.\n\n Parameters\n ----------\n shape : tuple\n The shape of digit images (the default is (-1, 784), alternatively (-1, 28, 28, 1)).\n path : str\n The path that the data is downloaded to.\n\n Returns\n -------\n X_train, y_train, X_val, y_val, X_test, y_test: tuple\n Return splitted training/validation/test set respectively.\n\n Examples\n --------\n >>> X_train, y_train, X_val, y_val, X_test, y_test = tl.files.load_mnist_dataset(shape=(-1,784), path='datasets')\n >>> X_train, y_train, X_val, y_val, X_test, y_test = tl.files.load_mnist_dataset(shape=(-1, 28, 28, 1))\n \"\"\"\n return _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/')\n\n\ndef load_fashion_mnist_dataset(shape=(-1, 784), path='data'):\n \"\"\"Load the fashion mnist.\n\n Automatically download fashion-MNIST dataset and return the training, validation and test set with 50000, 10000 and 10000 fashion images respectively, `examples <http://marubon-ds.blogspot.co.uk/2017/09/fashion-mnist-exploring.html>`__.\n\n Parameters\n ----------\n shape : tuple\n The shape of digit images (the default is (-1, 784), alternatively (-1, 28, 28, 1)).\n path : str\n The path that the data is downloaded to.\n\n Returns\n -------\n X_train, y_train, X_val, y_val, X_test, y_test: tuple\n Return splitted training/validation/test set respectively.\n\n Examples\n --------\n >>> X_train, y_train, X_val, y_val, X_test, y_test = tl.files.load_fashion_mnist_dataset(shape=(-1,784), path='datasets')\n >>> X_train, y_train, X_val, y_val, X_test, y_test = tl.files.load_fashion_mnist_dataset(shape=(-1, 28, 28, 1))\n \"\"\"\n return _load_mnist_dataset(\n shape, path, name='fashion_mnist', url='http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/'\n )\n\n\ndef _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'):\n \"\"\"A generic function to load mnist-like dataset.\n\n Parameters:\n ----------\n shape : tuple\n The shape of digit images.\n path : str\n The path that the data is downloaded to.\n name : str\n The dataset name you want to use(the default is 'mnist').\n url : str\n The url of dataset(the default is 'http://yann.lecun.com/exdb/mnist/').\n \"\"\"\n path = os.path.join(path, name)\n\n # Define functions for loading mnist-like data's images and labels.\n # For convenience, they also download the requested files if needed.\n def load_mnist_images(path, filename):\n filepath = maybe_download_and_extract(filename, path, url)\n\n logging.info(filepath)\n # Read the inputs in Yann LeCun's binary format.\n with gzip.open(filepath, 'rb') as f:\n data = np.frombuffer(f.read(), np.uint8, offset=16)\n # The inputs are vectors now, we reshape them to monochrome 2D images,\n # following the shape convention: (examples, channels, rows, columns)\n data = data.reshape(shape)\n # The inputs come as bytes, we convert them to float32 in range [0,1].\n # (Actually to range [0, 255/256], for compatibility to the version\n # provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)\n return data / np.float32(256)\n\n def load_mnist_labels(path, filename):\n filepath = maybe_download_and_extract(filename, path, url)\n # Read the labels in Yann LeCun's binary format.\n with gzip.open(filepath, 'rb') as f:\n data = np.frombuffer(f.read(), np.uint8, offset=8)\n # The labels are vectors of integers now, that's exactly what we want.\n return data\n\n # Download and read the training and test set images and labels.\n logging.info(\"Load or Download {0} > {1}\".format(name.upper(), path))\n X_train = load_mnist_images(path, 'train-images-idx3-ubyte.gz')\n y_train = load_mnist_labels(path, 'train-labels-idx1-ubyte.gz')\n X_test = load_mnist_images(path, 't10k-images-idx3-ubyte.gz')\n y_test = load_mnist_labels(path, 't10k-labels-idx1-ubyte.gz')\n\n # We reserve the last 10000 training examples for validation.\n X_train, X_val = X_train[:-10000], X_train[-10000:]\n y_train, y_val = y_train[:-10000], y_train[-10000:]\n\n # We just return all the arrays in order, as expected in main().\n # (It doesn't matter how we do this as long as we can read them again.)\n X_train = np.asarray(X_train, dtype=np.float32)\n y_train = np.asarray(y_train, dtype=np.int32)\n X_val = np.asarray(X_val, dtype=np.float32)\n y_val = np.asarray(y_val, dtype=np.int32)\n X_test = np.asarray(X_test, dtype=np.float32)\n y_test = np.asarray(y_test, dtype=np.int32)\n return X_train, y_train, X_val, y_val, X_test, y_test\n\n\ndef load_cifar10_dataset(shape=(-1, 32, 32, 3), path='data', plotable=False):\n \"\"\"Load CIFAR-10 dataset.\n\n It consists of 60000 32x32 colour images in 10 classes, with\n 6000 images per class. There are 50000 training images and 10000 test images.\n\n The dataset is divided into five training batches and one test batch, each with\n 10000 images. The test batch contains exactly 1000 randomly-selected images from\n each class. The training batches contain the remaining images in random order,\n but some training batches may contain more images from one class than another.\n Between them, the training batches contain exactly 5000 images from each class.\n\n Parameters\n ----------\n shape : tupe\n The shape of digit images e.g. (-1, 3, 32, 32) and (-1, 32, 32, 3).\n path : str\n The path that the data is downloaded to, defaults is ``data/cifar10/``.\n plotable : boolean\n Whether to plot some image examples, False as default.\n\n Examples\n --------\n >>> X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))\n\n References\n ----------\n - `CIFAR website <https://www.cs.toronto.edu/~kriz/cifar.html>`__\n - `Data download link <https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz>`__\n - `<https://teratail.com/questions/28932>`__\n\n \"\"\"\n path = os.path.join(path, 'cifar10')\n logging.info(\"Load or Download cifar10 > {}\".format(path))\n\n #Helper function to unpickle the data\n def unpickle(file):\n fp = open(file, 'rb')\n if sys.version_info.major == 2:\n data = pickle.load(fp)\n elif sys.version_info.major == 3:\n data = pickle.load(fp, encoding='latin-1')\n fp.close()\n return data\n\n filename = 'cifar-10-python.tar.gz'\n url = 'https://www.cs.toronto.edu/~kriz/'\n #Download and uncompress file\n maybe_download_and_extract(filename, path, url, extract=True)\n\n #Unpickle file and fill in data\n X_train = None\n y_train = []\n for i in range(1, 6):\n data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', \"data_batch_{}\".format(i)))\n if i == 1:\n X_train = data_dic['data']\n else:\n X_train = np.vstack((X_train, data_dic['data']))\n y_train += data_dic['labels']\n\n test_data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', \"test_batch\"))\n X_test = test_data_dic['data']\n y_test = np.array(test_data_dic['labels'])\n\n if shape == (-1, 3, 32, 32):\n X_test = X_test.reshape(shape)\n X_train = X_train.reshape(shape)\n elif shape == (-1, 32, 32, 3):\n X_test = X_test.reshape(shape, order='F')\n X_train = X_train.reshape(shape, order='F')\n X_test = np.transpose(X_test, (0, 2, 1, 3))\n X_train = np.transpose(X_train, (0, 2, 1, 3))\n else:\n X_test = X_test.reshape(shape)\n X_train = X_train.reshape(shape)\n\n y_train = np.array(y_train)\n\n if plotable:\n logging.info('\\nCIFAR-10')\n fig = plt.figure(1)\n\n logging.info('Shape of a training image: X_train[0] %s' % X_train[0].shape)\n\n plt.ion() # interactive mode\n count = 1\n for _ in range(10): # each row\n for _ in range(10): # each column\n _ = fig.add_subplot(10, 10, count)\n if shape == (-1, 3, 32, 32):\n # plt.imshow(X_train[count-1], interpolation='nearest')\n plt.imshow(np.transpose(X_train[count - 1], (1, 2, 0)), interpolation='nearest')\n # plt.imshow(np.transpose(X_train[count-1], (2, 1, 0)), interpolation='nearest')\n elif shape == (-1, 32, 32, 3):\n plt.imshow(X_train[count - 1], interpolation='nearest')\n # plt.imshow(np.transpose(X_train[count-1], (1, 0, 2)), interpolation='nearest')\n else:\n raise Exception(\"Do not support the given 'shape' to plot the image examples\")\n plt.gca().xaxis.set_major_locator(plt.NullLocator()) # 不显示刻度(tick)\n plt.gca().yaxis.set_major_locator(plt.NullLocator())\n count = count + 1\n plt.draw() # interactive mode\n plt.pause(3) # interactive mode\n\n logging.info(\"X_train: %s\" % X_train.shape)\n logging.info(\"y_train: %s\" % y_train.shape)\n logging.info(\"X_test: %s\" % X_test.shape)\n logging.info(\"y_test: %s\" % y_test.shape)\n\n X_train = np.asarray(X_train, dtype=np.float32)\n X_test = np.asarray(X_test, dtype=np.float32)\n y_train = np.asarray(y_train, dtype=np.int32)\n y_test = np.asarray(y_test, dtype=np.int32)\n\n return X_train, y_train, X_test, y_test\n\n\ndef load_cropped_svhn(path='data', include_extra=True):\n \"\"\"Load Cropped SVHN.\n\n The Cropped Street View House Numbers (SVHN) Dataset contains 32x32x3 RGB images.\n Digit '1' has label 1, '9' has label 9 and '0' has label 0 (the original dataset uses 10 to represent '0'), see `ufldl website <http://ufldl.stanford.edu/housenumbers/>`__.\n\n Parameters\n ----------\n path : str\n The path that the data is downloaded to.\n include_extra : boolean\n If True (default), add extra images to the training set.\n\n Returns\n -------\n X_train, y_train, X_test, y_test: tuple\n Return splitted training/test set respectively.\n\n Examples\n ---------\n >>> X_train, y_train, X_test, y_test = tl.files.load_cropped_svhn(include_extra=False)\n >>> tl.vis.save_images(X_train[0:100], [10, 10], 'svhn.png')\n\n \"\"\"\n\n start_time = time.time()\n\n path = os.path.join(path, 'cropped_svhn')\n logging.info(\"Load or Download Cropped SVHN > {} | include extra images: {}\".format(path, include_extra))\n url = \"http://ufldl.stanford.edu/housenumbers/\"\n\n np_file = os.path.join(path, \"train_32x32.npz\")\n if file_exists(np_file) is False:\n filename = \"train_32x32.mat\"\n filepath = maybe_download_and_extract(filename, path, url)\n mat = sio.loadmat(filepath)\n X_train = mat['X'] / 255.0 # to [0, 1]\n X_train = np.transpose(X_train, (3, 0, 1, 2))\n y_train = np.squeeze(mat['y'], axis=1)\n y_train[y_train == 10] = 0 # replace 10 to 0\n np.savez(np_file, X=X_train, y=y_train)\n del_file(filepath)\n else:\n v = np.load(np_file)\n X_train = v['X']\n y_train = v['y']\n logging.info(\" n_train: {}\".format(len(y_train)))\n\n np_file = os.path.join(path, \"test_32x32.npz\")\n if file_exists(np_file) is False:\n filename = \"test_32x32.mat\"\n filepath = maybe_download_and_extract(filename, path, url)\n mat = sio.loadmat(filepath)\n X_test = mat['X'] / 255.0\n X_test = np.transpose(X_test, (3, 0, 1, 2))\n y_test = np.squeeze(mat['y'], axis=1)\n y_test[y_test == 10] = 0\n np.savez(np_file, X=X_test, y=y_test)\n del_file(filepath)\n else:\n v = np.load(np_file)\n X_test = v['X']\n y_test = v['y']\n logging.info(\" n_test: {}\".format(len(y_test)))\n\n if include_extra:\n logging.info(\" getting extra 531131 images, please wait ...\")\n np_file = os.path.join(path, \"extra_32x32.npz\")\n if file_exists(np_file) is False:\n logging.info(\" the first time to load extra images will take long time to convert the file format ...\")\n filename = \"extra_32x32.mat\"\n filepath = maybe_download_and_extract(filename, path, url)\n mat = sio.loadmat(filepath)\n X_extra = mat['X'] / 255.0\n X_extra = np.transpose(X_extra, (3, 0, 1, 2))\n y_extra = np.squeeze(mat['y'], axis=1)\n y_extra[y_extra == 10] = 0\n np.savez(np_file, X=X_extra, y=y_extra)\n del_file(filepath)\n else:\n v = np.load(np_file)\n X_extra = v['X']\n y_extra = v['y']\n # print(X_train.shape, X_extra.shape)\n logging.info(\" adding n_extra {} to n_train {}\".format(len(y_extra), len(y_train)))\n t = time.time()\n X_train = np.concatenate((X_train, X_extra), 0)\n y_train = np.concatenate((y_train, y_extra), 0)\n # X_train = np.append(X_train, X_extra, axis=0)\n # y_train = np.append(y_train, y_extra, axis=0)\n logging.info(\" added n_extra {} to n_train {} took {}s\".format(len(y_extra), len(y_train), time.time() - t))\n else:\n logging.info(\" no extra images are included\")\n logging.info(\" image size: %s n_train: %d n_test: %d\" % (str(X_train.shape[1:4]), len(y_train), len(y_test)))\n logging.info(\" took: {}s\".format(int(time.time() - start_time)))\n return X_train, y_train, X_test, y_test\n\n\ndef load_ptb_dataset(path='data'):\n \"\"\"Load Penn TreeBank (PTB) dataset.\n\n It is used in many LANGUAGE MODELING papers,\n including \"Empirical Evaluation and Combination of Advanced Language\n Modeling Techniques\", \"Recurrent Neural Network Regularization\".\n It consists of 929k training words, 73k validation words, and 82k test\n words. It has 10k words in its vocabulary.\n\n Parameters\n ----------\n path : str\n The path that the data is downloaded to, defaults is ``data/ptb/``.\n\n Returns\n --------\n train_data, valid_data, test_data : list of int\n The training, validating and testing data in integer format.\n vocab_size : int\n The vocabulary size.\n\n Examples\n --------\n >>> train_data, valid_data, test_data, vocab_size = tl.files.load_ptb_dataset()\n\n References\n ---------------\n - ``tensorflow.models.rnn.ptb import reader``\n - `Manual download <http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz>`__\n\n Notes\n ------\n - If you want to get the raw data, see the source code.\n\n \"\"\"\n path = os.path.join(path, 'ptb')\n logging.info(\"Load or Download Penn TreeBank (PTB) dataset > {}\".format(path))\n\n #Maybe dowload and uncompress tar, or load exsisting files\n filename = 'simple-examples.tgz'\n url = 'http://www.fit.vutbr.cz/~imikolov/rnnlm/'\n maybe_download_and_extract(filename, path, url, extract=True)\n\n data_path = os.path.join(path, 'simple-examples', 'data')\n train_path = os.path.join(data_path, \"ptb.train.txt\")\n valid_path = os.path.join(data_path, \"ptb.valid.txt\")\n test_path = os.path.join(data_path, \"ptb.test.txt\")\n\n word_to_id = nlp.build_vocab(nlp.read_words(train_path))\n\n train_data = nlp.words_to_word_ids(nlp.read_words(train_path), word_to_id)\n valid_data = nlp.words_to_word_ids(nlp.read_words(valid_path), word_to_id)\n test_data = nlp.words_to_word_ids(nlp.read_words(test_path), word_to_id)\n vocab_size = len(word_to_id)\n\n # logging.info(nlp.read_words(train_path)) # ... 'according', 'to', 'mr.', '<unk>', '<eos>']\n # logging.info(train_data) # ... 214, 5, 23, 1, 2]\n # logging.info(word_to_id) # ... 'beyond': 1295, 'anti-nuclear': 9599, 'trouble': 1520, '<eos>': 2 ... }\n # logging.info(vocabulary) # 10000\n # exit()\n return train_data, valid_data, test_data, vocab_size\n\n\ndef load_matt_mahoney_text8_dataset(path='data'):\n \"\"\"Load Matt Mahoney's dataset.\n\n Download a text file from Matt Mahoney's website\n if not present, and make sure it's the right size.\n Extract the first file enclosed in a zip file as a list of words.\n This dataset can be used for Word Embedding.\n\n Parameters\n ----------\n path : str\n The path that the data is downloaded to, defaults is ``data/mm_test8/``.\n\n Returns\n --------\n list of str\n The raw text data e.g. [.... 'their', 'families', 'who', 'were', 'expelled', 'from', 'jerusalem', ...]\n\n Examples\n --------\n >>> words = tl.files.load_matt_mahoney_text8_dataset()\n >>> print('Data size', len(words))\n\n \"\"\"\n path = os.path.join(path, 'mm_test8')\n logging.info(\"Load or Download matt_mahoney_text8 Dataset> {}\".format(path))\n\n filename = 'text8.zip'\n url = 'http://mattmahoney.net/dc/'\n maybe_download_and_extract(filename, path, url, expected_bytes=31344016)\n\n with zipfile.ZipFile(os.path.join(path, filename)) as f:\n word_list = f.read(f.namelist()[0]).split()\n for idx, _ in enumerate(word_list):\n word_list[idx] = word_list[idx].decode()\n return word_list\n\n\ndef load_imdb_dataset(\n path='data', nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2,\n index_from=3\n):\n \"\"\"Load IMDB dataset.\n\n Parameters\n ----------\n path : str\n The path that the data is downloaded to, defaults is ``data/imdb/``.\n nb_words : int\n Number of words to get.\n skip_top : int\n Top most frequent words to ignore (they will appear as oov_char value in the sequence data).\n maxlen : int\n Maximum sequence length. Any longer sequence will be truncated.\n seed : int\n Seed for reproducible data shuffling.\n start_char : int\n The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.\n oov_char : int\n Words that were cut out because of the num_words or skip_top limit will be replaced with this character.\n index_from : int\n Index actual words with this index and higher.\n\n Examples\n --------\n >>> X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(\n ... nb_words=20000, test_split=0.2)\n >>> print('X_train.shape', X_train.shape)\n (20000,) [[1, 62, 74, ... 1033, 507, 27],[1, 60, 33, ... 13, 1053, 7]..]\n >>> print('y_train.shape', y_train.shape)\n (20000,) [1 0 0 ..., 1 0 1]\n\n References\n -----------\n - `Modified from keras. <https://github.com/fchollet/keras/blob/master/keras/datasets/imdb.py>`__\n\n \"\"\"\n path = os.path.join(path, 'imdb')\n\n filename = \"imdb.pkl\"\n url = 'https://s3.amazonaws.com/text-datasets/'\n maybe_download_and_extract(filename, path, url)\n\n if filename.endswith(\".gz\"):\n f = gzip.open(os.path.join(path, filename), 'rb')\n else:\n f = open(os.path.join(path, filename), 'rb')\n\n X, labels = cPickle.load(f)\n f.close()\n\n np.random.seed(seed)\n np.random.shuffle(X)\n np.random.seed(seed)\n np.random.shuffle(labels)\n\n if start_char is not None:\n X = [[start_char] + [w + index_from for w in x] for x in X]\n elif index_from:\n X = [[w + index_from for w in x] for x in X]\n\n if maxlen:\n new_X = []\n new_labels = []\n for x, y in zip(X, labels):\n if len(x) < maxlen:\n new_X.append(x)\n new_labels.append(y)\n X = new_X\n labels = new_labels\n if not X:\n raise Exception(\n 'After filtering for sequences shorter than maxlen=' + str(maxlen) + ', no sequence was kept. '\n 'Increase maxlen.'\n )\n if not nb_words:\n nb_words = max([max(x) for x in X])\n\n # by convention, use 2 as OOV word\n # reserve 'index_from' (=3 by default) characters: 0 (padding), 1 (start), 2 (OOV)\n if oov_char is not None:\n X = [[oov_char if (w >= nb_words or w < skip_top) else w for w in x] for x in X]\n else:\n nX = []\n for x in X:\n nx = []\n for w in x:\n if (w >= nb_words or w < skip_top):\n nx.append(w)\n nX.append(nx)\n X = nX\n\n X_train = np.array(X[:int(len(X) * (1 - test_split))])\n y_train = np.array(labels[:int(len(X) * (1 - test_split))])\n\n X_test = np.array(X[int(len(X) * (1 - test_split)):])\n y_test = np.array(labels[int(len(X) * (1 - test_split)):])\n\n return X_train, y_train, X_test, y_test\n\n\ndef load_nietzsche_dataset(path='data'):\n \"\"\"Load Nietzsche dataset.\n\n Parameters\n ----------\n path : str\n The path that the data is downloaded to, defaults is ``data/nietzsche/``.\n\n Returns\n --------\n str\n The content.\n\n Examples\n --------\n >>> see tutorial_generate_text.py\n >>> words = tl.files.load_nietzsche_dataset()\n >>> words = basic_clean_str(words)\n >>> words = words.split()\n\n \"\"\"\n logging.info(\"Load or Download nietzsche dataset > {}\".format(path))\n path = os.path.join(path, 'nietzsche')\n\n filename = \"nietzsche.txt\"\n url = 'https://s3.amazonaws.com/text-datasets/'\n filepath = maybe_download_and_extract(filename, path, url)\n\n with open(filepath, \"r\") as f:\n words = f.read()\n return words\n\n\ndef load_wmt_en_fr_dataset(path='data'):\n \"\"\"Load WMT'15 English-to-French translation dataset.\n\n It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set.\n Returns the directories of training data and test data.\n\n Parameters\n ----------\n path : str\n The path that the data is downloaded to, defaults is ``data/wmt_en_fr/``.\n\n References\n ----------\n - Code modified from /tensorflow/models/rnn/translation/data_utils.py\n\n Notes\n -----\n Usually, it will take a long time to download this dataset.\n\n \"\"\"\n path = os.path.join(path, 'wmt_en_fr')\n # URLs for WMT data.\n _WMT_ENFR_TRAIN_URL = \"http://www.statmt.org/wmt10/\"\n _WMT_ENFR_DEV_URL = \"http://www.statmt.org/wmt15/\"\n\n def gunzip_file(gz_path, new_path):\n \"\"\"Unzips from gz_path into new_path.\"\"\"\n logging.info(\"Unpacking %s to %s\" % (gz_path, new_path))\n with gzip.open(gz_path, \"rb\") as gz_file:\n with open(new_path, \"wb\") as new_file:\n for line in gz_file:\n new_file.write(line)\n\n def get_wmt_enfr_train_set(path):\n \"\"\"Download the WMT en-fr training corpus to directory unless it's there.\"\"\"\n filename = \"training-giga-fren.tar\"\n maybe_download_and_extract(filename, path, _WMT_ENFR_TRAIN_URL, extract=True)\n train_path = os.path.join(path, \"giga-fren.release2.fixed\")\n gunzip_file(train_path + \".fr.gz\", train_path + \".fr\")\n gunzip_file(train_path + \".en.gz\", train_path + \".en\")\n return train_path\n\n def get_wmt_enfr_dev_set(path):\n \"\"\"Download the WMT en-fr training corpus to directory unless it's there.\"\"\"\n filename = \"dev-v2.tgz\"\n dev_file = maybe_download_and_extract(filename, path, _WMT_ENFR_DEV_URL, extract=False)\n dev_name = \"newstest2013\"\n dev_path = os.path.join(path, \"newstest2013\")\n if not (gfile.Exists(dev_path + \".fr\") and gfile.Exists(dev_path + \".en\")):\n logging.info(\"Extracting tgz file %s\" % dev_file)\n with tarfile.open(dev_file, \"r:gz\") as dev_tar:\n fr_dev_file = dev_tar.getmember(\"dev/\" + dev_name + \".fr\")\n en_dev_file = dev_tar.getmember(\"dev/\" + dev_name + \".en\")\n fr_dev_file.name = dev_name + \".fr\" # Extract without \"dev/\" prefix.\n en_dev_file.name = dev_name + \".en\"\n dev_tar.extract(fr_dev_file, path)\n dev_tar.extract(en_dev_file, path)\n return dev_path\n\n logging.info(\"Load or Download WMT English-to-French translation > {}\".format(path))\n\n train_path = get_wmt_enfr_train_set(path)\n dev_path = get_wmt_enfr_dev_set(path)\n\n return train_path, dev_path\n\n\ndef load_flickr25k_dataset(tag='sky', path=\"data\", n_threads=50, printable=False):\n \"\"\"Load Flickr25K dataset.\n\n Returns a list of images by a given tag from Flick25k dataset,\n it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__\n at the first time you use it.\n\n Parameters\n ------------\n tag : str or None\n What images to return.\n - If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.\n - If you want to get all images, set to ``None``.\n\n path : str\n The path that the data is downloaded to, defaults is ``data/flickr25k/``.\n n_threads : int\n The number of thread to read image.\n printable : boolean\n Whether to print infomation when reading images, default is ``False``.\n\n Examples\n -----------\n Get images with tag of sky\n\n >>> images = tl.files.load_flickr25k_dataset(tag='sky')\n\n Get all images\n\n >>> images = tl.files.load_flickr25k_dataset(tag=None, n_threads=100, printable=True)\n\n \"\"\"\n path = os.path.join(path, 'flickr25k')\n\n filename = 'mirflickr25k.zip'\n url = 'http://press.liacs.nl/mirflickr/mirflickr25k/'\n\n # download dataset\n if folder_exists(os.path.join(path, \"mirflickr\")) is False:\n logging.info(\"[*] Flickr25k is nonexistent in {}\".format(path))\n maybe_download_and_extract(filename, path, url, extract=True)\n del_file(os.path.join(path, filename))\n\n # return images by the given tag.\n # 1. image path list\n folder_imgs = os.path.join(path, \"mirflickr\")\n path_imgs = load_file_list(path=folder_imgs, regx='\\\\.jpg', printable=False)\n path_imgs.sort(key=natural_keys)\n\n # 2. tag path list\n folder_tags = os.path.join(path, \"mirflickr\", \"meta\", \"tags\")\n path_tags = load_file_list(path=folder_tags, regx='\\\\.txt', printable=False)\n path_tags.sort(key=natural_keys)\n\n # 3. select images\n if tag is None:\n logging.info(\"[Flickr25k] reading all images\")\n else:\n logging.info(\"[Flickr25k] reading images with tag: {}\".format(tag))\n images_list = []\n for idx, _v in enumerate(path_tags):\n tags = read_file(os.path.join(folder_tags, path_tags[idx])).split('\\n')\n # logging.info(idx+1, tags)\n if tag is None or tag in tags:\n images_list.append(path_imgs[idx])\n\n images = visualize.read_images(images_list, folder_imgs, n_threads=n_threads, printable=printable)\n return images\n\n\ndef load_flickr1M_dataset(tag='sky', size=10, path=\"data\", n_threads=50, printable=False):\n \"\"\"Load Flick1M dataset.\n\n Returns a list of images by a given tag from Flickr1M dataset,\n it will download Flickr1M from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__\n at the first time you use it.\n\n Parameters\n ------------\n tag : str or None\n What images to return.\n - If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.\n - If you want to get all images, set to ``None``.\n\n size : int\n integer between 1 to 10. 1 means 100k images ... 5 means 500k images, 10 means all 1 million images. Default is 10.\n path : str\n The path that the data is downloaded to, defaults is ``data/flickr25k/``.\n n_threads : int\n The number of thread to read image.\n printable : boolean\n Whether to print infomation when reading images, default is ``False``.\n\n Examples\n ----------\n Use 200k images\n\n >>> images = tl.files.load_flickr1M_dataset(tag='zebra', size=2)\n\n Use 1 Million images\n\n >>> images = tl.files.load_flickr1M_dataset(tag='zebra')\n\n \"\"\"\n\n path = os.path.join(path, 'flickr1M')\n logging.info(\"[Flickr1M] using {}% of images = {}\".format(size * 10, size * 100000))\n images_zip = [\n 'images0.zip', 'images1.zip', 'images2.zip', 'images3.zip', 'images4.zip', 'images5.zip', 'images6.zip',\n 'images7.zip', 'images8.zip', 'images9.zip'\n ]\n tag_zip = 'tags.zip'\n url = 'http://press.liacs.nl/mirflickr/mirflickr1m/'\n\n # download dataset\n for image_zip in images_zip[0:size]:\n image_folder = image_zip.split(\".\")[0]\n # logging.info(path+\"/\"+image_folder)\n if folder_exists(os.path.join(path, image_folder)) is False:\n # logging.info(image_zip)\n logging.info(\"[Flickr1M] {} is missing in {}\".format(image_folder, path))\n maybe_download_and_extract(image_zip, path, url, extract=True)\n del_file(os.path.join(path, image_zip))\n # os.system(\"mv {} {}\".format(os.path.join(path, 'images'), os.path.join(path, image_folder)))\n shutil.move(os.path.join(path, 'images'), os.path.join(path, image_folder))\n else:\n logging.info(\"[Flickr1M] {} exists in {}\".format(image_folder, path))\n\n # download tag\n if folder_exists(os.path.join(path, \"tags\")) is False:\n logging.info(\"[Flickr1M] tag files is nonexistent in {}\".format(path))\n maybe_download_and_extract(tag_zip, path, url, extract=True)\n del_file(os.path.join(path, tag_zip))\n else:\n logging.info(\"[Flickr1M] tags exists in {}\".format(path))\n\n # 1. image path list\n images_list = []\n images_folder_list = []\n for i in range(0, size):\n images_folder_list += load_folder_list(path=os.path.join(path, 'images%d' % i))\n images_folder_list.sort(key=lambda s: int(s.split('/')[-1])) # folder/images/ddd\n\n for folder in images_folder_list[0:size * 10]:\n tmp = load_file_list(path=folder, regx='\\\\.jpg', printable=False)\n tmp.sort(key=lambda s: int(s.split('.')[-2])) # ddd.jpg\n images_list.extend([os.path.join(folder, x) for x in tmp])\n\n # 2. tag path list\n tag_list = []\n tag_folder_list = load_folder_list(os.path.join(path, \"tags\"))\n\n # tag_folder_list.sort(key=lambda s: int(s.split(\"/\")[-1])) # folder/images/ddd\n tag_folder_list.sort(key=lambda s: int(os.path.basename(s)))\n\n for folder in tag_folder_list[0:size * 10]:\n tmp = load_file_list(path=folder, regx='\\\\.txt', printable=False)\n tmp.sort(key=lambda s: int(s.split('.')[-2])) # ddd.txt\n tmp = [os.path.join(folder, s) for s in tmp]\n tag_list += tmp\n\n # 3. select images\n logging.info(\"[Flickr1M] searching tag: {}\".format(tag))\n select_images_list = []\n for idx, _val in enumerate(tag_list):\n tags = read_file(tag_list[idx]).split('\\n')\n if tag in tags:\n select_images_list.append(images_list[idx])\n\n logging.info(\"[Flickr1M] reading images with tag: {}\".format(tag))\n images = visualize.read_images(select_images_list, '', n_threads=n_threads, printable=printable)\n return images\n\n\ndef load_cyclegan_dataset(filename='summer2winter_yosemite', path='data'):\n \"\"\"Load images from CycleGAN's database, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__.\n\n Parameters\n ------------\n filename : str\n The dataset you want, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__.\n path : str\n The path that the data is downloaded to, defaults is `data/cyclegan`\n\n Examples\n ---------\n >>> im_train_A, im_train_B, im_test_A, im_test_B = load_cyclegan_dataset(filename='summer2winter_yosemite')\n\n \"\"\"\n path = os.path.join(path, 'cyclegan')\n url = 'https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/'\n\n if folder_exists(os.path.join(path, filename)) is False:\n logging.info(\"[*] {} is nonexistent in {}\".format(filename, path))\n maybe_download_and_extract(filename + '.zip', path, url, extract=True)\n del_file(os.path.join(path, filename + '.zip'))\n\n def load_image_from_folder(path):\n path_imgs = load_file_list(path=path, regx='\\\\.jpg', printable=False)\n return visualize.read_images(path_imgs, path=path, n_threads=10, printable=False)\n\n im_train_A = load_image_from_folder(os.path.join(path, filename, \"trainA\"))\n im_train_B = load_image_from_folder(os.path.join(path, filename, \"trainB\"))\n im_test_A = load_image_from_folder(os.path.join(path, filename, \"testA\"))\n im_test_B = load_image_from_folder(os.path.join(path, filename, \"testB\"))\n\n def if_2d_to_3d(images): # [h, w] --> [h, w, 3]\n for i, _v in enumerate(images):\n if len(images[i].shape) == 2:\n images[i] = images[i][:, :, np.newaxis]\n images[i] = np.tile(images[i], (1, 1, 3))\n return images\n\n im_train_A = if_2d_to_3d(im_train_A)\n im_train_B = if_2d_to_3d(im_train_B)\n im_test_A = if_2d_to_3d(im_test_A)\n im_test_B = if_2d_to_3d(im_test_B)\n\n return im_train_A, im_train_B, im_test_A, im_test_B\n\n\ndef download_file_from_google_drive(ID, destination):\n \"\"\"Download file from Google Drive.\n\n See ``tl.files.load_celebA_dataset`` for example.\n\n Parameters\n --------------\n ID : str\n The driver ID.\n destination : str\n The destination for save file.\n\n \"\"\"\n\n def save_response_content(response, destination, chunk_size=32 * 1024):\n total_size = int(response.headers.get('content-length', 0))\n with open(destination, \"wb\") as f:\n for chunk in tqdm(response.iter_content(chunk_size), total=total_size, unit='B', unit_scale=True,\n desc=destination):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n\n def get_confirm_token(response):\n for key, value in response.cookies.items():\n if key.startswith('download_warning'):\n return value\n return None\n\n URL = \"https://docs.google.com/uc?export=download\"\n session = requests.Session()\n\n response = session.get(URL, params={'id': ID}, stream=True)\n token = get_confirm_token(response)\n\n if token:\n params = {'id': ID, 'confirm': token}\n response = session.get(URL, params=params, stream=True)\n save_response_content(response, destination)\n\n\ndef load_celebA_dataset(path='data'):\n \"\"\"Load CelebA dataset\n\n Return a list of image path.\n\n Parameters\n -----------\n path : str\n The path that the data is downloaded to, defaults is ``data/celebA/``.\n\n \"\"\"\n data_dir = 'celebA'\n filename, drive_id = \"img_align_celeba.zip\", \"0B7EVK8r0v71pZjFTYXZWM3FlRnM\"\n save_path = os.path.join(path, filename)\n image_path = os.path.join(path, data_dir)\n if os.path.exists(image_path):\n logging.info('[*] {} already exists'.format(save_path))\n else:\n exists_or_mkdir(path)\n download_file_from_google_drive(drive_id, save_path)\n zip_dir = ''\n with zipfile.ZipFile(save_path) as zf:\n zip_dir = zf.namelist()[0]\n zf.extractall(path)\n os.remove(save_path)\n os.rename(os.path.join(path, zip_dir), image_path)\n\n data_files = load_file_list(path=image_path, regx='\\\\.jpg', printable=False)\n for i, _v in enumerate(data_files):\n data_files[i] = os.path.join(image_path, data_files[i])\n return data_files\n\n\ndef load_voc_dataset(path='data', dataset='2012', contain_classes_in_person=False):\n \"\"\"Pascal VOC 2007/2012 Dataset.\n\n It has 20 objects:\n aeroplane, bicycle, bird, boat, bottle, bus, car, cat, chair, cow, diningtable, dog, horse, motorbike, person, pottedplant, sheep, sofa, train, tvmonitor\n and additional 3 classes : head, hand, foot for person.\n\n Parameters\n -----------\n path : str\n The path that the data is downloaded to, defaults is ``data/VOC``.\n dataset : str\n The VOC dataset version, `2012`, `2007`, `2007test` or `2012test`. We usually train model on `2007+2012` and test it on `2007test`.\n contain_classes_in_person : boolean\n Whether include head, hand and foot annotation, default is False.\n\n Returns\n ---------\n imgs_file_list : list of str\n Full paths of all images.\n imgs_semseg_file_list : list of str\n Full paths of all maps for semantic segmentation. Note that not all images have this map!\n imgs_insseg_file_list : list of str\n Full paths of all maps for instance segmentation. Note that not all images have this map!\n imgs_ann_file_list : list of str\n Full paths of all annotations for bounding box and object class, all images have this annotations.\n classes : list of str\n Classes in order.\n classes_in_person : list of str\n Classes in person.\n classes_dict : dictionary\n Class label to integer.\n n_objs_list : list of int\n Number of objects in all images in ``imgs_file_list`` in order.\n objs_info_list : list of str\n Darknet format for the annotation of all images in ``imgs_file_list`` in order. ``[class_id x_centre y_centre width height]`` in ratio format.\n objs_info_dicts : dictionary\n The annotation of all images in ``imgs_file_list``, ``{imgs_file_list : dictionary for annotation}``,\n format from `TensorFlow/Models/object-detection <https://github.com/tensorflow/models/blob/master/object_detection/create_pascal_tf_record.py>`__.\n\n Examples\n ----------\n >>> imgs_file_list, imgs_semseg_file_list, imgs_insseg_file_list, imgs_ann_file_list,\n >>> classes, classes_in_person, classes_dict,\n >>> n_objs_list, objs_info_list, objs_info_dicts = tl.files.load_voc_dataset(dataset=\"2012\", contain_classes_in_person=False)\n >>> idx = 26\n >>> print(classes)\n ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']\n >>> print(classes_dict)\n {'sheep': 16, 'horse': 12, 'bicycle': 1, 'bottle': 4, 'cow': 9, 'sofa': 17, 'car': 6, 'dog': 11, 'cat': 7, 'person': 14, 'train': 18, 'diningtable': 10, 'aeroplane': 0, 'bus': 5, 'pottedplant': 15, 'tvmonitor': 19, 'chair': 8, 'bird': 2, 'boat': 3, 'motorbike': 13}\n >>> print(imgs_file_list[idx])\n data/VOC/VOC2012/JPEGImages/2007_000423.jpg\n >>> print(n_objs_list[idx])\n 2\n >>> print(imgs_ann_file_list[idx])\n data/VOC/VOC2012/Annotations/2007_000423.xml\n >>> print(objs_info_list[idx])\n 14 0.173 0.461333333333 0.142 0.496\n 14 0.828 0.542666666667 0.188 0.594666666667\n >>> ann = tl.prepro.parse_darknet_ann_str_to_list(objs_info_list[idx])\n >>> print(ann)\n [[14, 0.173, 0.461333333333, 0.142, 0.496], [14, 0.828, 0.542666666667, 0.188, 0.594666666667]]\n >>> c, b = tl.prepro.parse_darknet_ann_list_to_cls_box(ann)\n >>> print(c, b)\n [14, 14] [[0.173, 0.461333333333, 0.142, 0.496], [0.828, 0.542666666667, 0.188, 0.594666666667]]\n\n References\n -------------\n - `Pascal VOC2012 Website <http://host.robots.ox.ac.uk/pascal/VOC/voc2012/#devkit>`__.\n - `Pascal VOC2007 Website <http://host.robots.ox.ac.uk/pascal/VOC/voc2007/>`__.\n\n \"\"\"\n path = os.path.join(path, 'VOC')\n\n def _recursive_parse_xml_to_dict(xml):\n \"\"\"Recursively parses XML contents to python dict.\n\n We assume that `object` tags are the only ones that can appear\n multiple times at the same level of a tree.\n\n Args:\n xml: xml tree obtained by parsing XML file contents using lxml.etree\n\n Returns:\n Python dictionary holding XML contents.\n\n \"\"\"\n if not xml:\n # if xml is not None:\n return {xml.tag: xml.text}\n result = {}\n for child in xml:\n child_result = _recursive_parse_xml_to_dict(child)\n if child.tag != 'object':\n result[child.tag] = child_result[child.tag]\n else:\n if child.tag not in result:\n result[child.tag] = []\n result[child.tag].append(child_result[child.tag])\n return {xml.tag: result}\n\n if dataset == \"2012\":\n url = \"http://host.robots.ox.ac.uk/pascal/VOC/voc2012/\"\n tar_filename = \"VOCtrainval_11-May-2012.tar\"\n extracted_filename = \"VOC2012\" #\"VOCdevkit/VOC2012\"\n logging.info(\" [============= VOC 2012 =============]\")\n elif dataset == \"2012test\":\n extracted_filename = \"VOC2012test\" #\"VOCdevkit/VOC2012\"\n logging.info(\" [============= VOC 2012 Test Set =============]\")\n logging.info(\n \" \\nAuthor: 2012test only have person annotation, so 2007test is highly recommended for testing !\\n\"\n )\n time.sleep(3)\n if os.path.isdir(os.path.join(path, extracted_filename)) is False:\n logging.info(\"For VOC 2012 Test data - online registration required\")\n logging.info(\n \" Please download VOC2012test.tar from: \\n register: http://host.robots.ox.ac.uk:8080 \\n voc2012 : http://host.robots.ox.ac.uk:8080/eval/challenges/voc2012/ \\ndownload: http://host.robots.ox.ac.uk:8080/eval/downloads/VOC2012test.tar\"\n )\n logging.info(\" unzip VOC2012test.tar,rename the folder to VOC2012test and put it into %s\" % path)\n exit()\n # # http://host.robots.ox.ac.uk:8080/eval/downloads/VOC2012test.tar\n # url = \"http://host.robots.ox.ac.uk:8080/eval/downloads/\"\n # tar_filename = \"VOC2012test.tar\"\n elif dataset == \"2007\":\n url = \"http://host.robots.ox.ac.uk/pascal/VOC/voc2007/\"\n tar_filename = \"VOCtrainval_06-Nov-2007.tar\"\n extracted_filename = \"VOC2007\"\n logging.info(\" [============= VOC 2007 =============]\")\n elif dataset == \"2007test\":\n # http://host.robots.ox.ac.uk/pascal/VOC/voc2007/index.html#testdata\n # http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar\n url = \"http://host.robots.ox.ac.uk/pascal/VOC/voc2007/\"\n tar_filename = \"VOCtest_06-Nov-2007.tar\"\n extracted_filename = \"VOC2007test\"\n logging.info(\" [============= VOC 2007 Test Set =============]\")\n else:\n raise Exception(\"Please set the dataset aug to 2012, 2012test or 2007.\")\n\n # download dataset\n if dataset != \"2012test\":\n _platform = sys.platform\n if folder_exists(os.path.join(path, extracted_filename)) is False:\n logging.info(\"[VOC] {} is nonexistent in {}\".format(extracted_filename, path))\n maybe_download_and_extract(tar_filename, path, url, extract=True)\n del_file(os.path.join(path, tar_filename))\n if dataset == \"2012\":\n if _platform == \"win32\":\n os.system(\"mv {}\\VOCdevkit\\VOC2012 {}\\VOC2012\".format(path, path))\n else:\n os.system(\"mv {}/VOCdevkit/VOC2012 {}/VOC2012\".format(path, path))\n elif dataset == \"2007\":\n if _platform == \"win32\":\n os.system(\"mv {}\\VOCdevkit\\VOC2007 {}\\VOC2007\".format(path, path))\n else:\n os.system(\"mv {}/VOCdevkit/VOC2007 {}/VOC2007\".format(path, path))\n elif dataset == \"2007test\":\n if _platform == \"win32\":\n os.system(\"mv {}\\VOCdevkit\\VOC2007 {}\\VOC2007test\".format(path, path))\n else:\n os.system(\"mv {}/VOCdevkit/VOC2007 {}/VOC2007test\".format(path, path))\n del_folder(os.path.join(path, 'VOCdevkit'))\n # object classes(labels) NOTE: YOU CAN CUSTOMIZE THIS LIST\n classes = [\n \"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\", \"dog\",\n \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\", \"sofa\", \"train\", \"tvmonitor\"\n ]\n if contain_classes_in_person:\n classes_in_person = [\"head\", \"hand\", \"foot\"]\n else:\n classes_in_person = []\n\n classes += classes_in_person # use extra 3 classes for person\n\n classes_dict = utils.list_string_to_dict(classes)\n logging.info(\"[VOC] object classes {}\".format(classes_dict))\n\n # 1. image path list\n # folder_imgs = path+\"/\"+extracted_filename+\"/JPEGImages/\"\n folder_imgs = os.path.join(path, extracted_filename, \"JPEGImages\")\n imgs_file_list = load_file_list(path=folder_imgs, regx='\\\\.jpg', printable=False)\n logging.info(\"[VOC] {} images found\".format(len(imgs_file_list)))\n\n imgs_file_list.sort(key=lambda s: int(s.replace('.', ' ').replace('_', '').split(' ')[-2])\n ) # 2007_000027.jpg --> 2007000027\n\n imgs_file_list = [os.path.join(folder_imgs, s) for s in imgs_file_list]\n # logging.info('IM',imgs_file_list[0::3333], imgs_file_list[-1])\n if dataset != \"2012test\":\n ##======== 2. semantic segmentation maps path list\n # folder_semseg = path+\"/\"+extracted_filename+\"/SegmentationClass/\"\n folder_semseg = os.path.join(path, extracted_filename, \"SegmentationClass\")\n imgs_semseg_file_list = load_file_list(path=folder_semseg, regx='\\\\.png', printable=False)\n logging.info(\"[VOC] {} maps for semantic segmentation found\".format(len(imgs_semseg_file_list)))\n imgs_semseg_file_list.sort(key=lambda s: int(s.replace('.', ' ').replace('_', '').split(' ')[-2])\n ) # 2007_000032.png --> 2007000032\n imgs_semseg_file_list = [os.path.join(folder_semseg, s) for s in imgs_semseg_file_list]\n # logging.info('Semantic Seg IM',imgs_semseg_file_list[0::333], imgs_semseg_file_list[-1])\n ##======== 3. instance segmentation maps path list\n # folder_insseg = path+\"/\"+extracted_filename+\"/SegmentationObject/\"\n folder_insseg = os.path.join(path, extracted_filename, \"SegmentationObject\")\n imgs_insseg_file_list = load_file_list(path=folder_insseg, regx='\\\\.png', printable=False)\n logging.info(\"[VOC] {} maps for instance segmentation found\".format(len(imgs_semseg_file_list)))\n imgs_insseg_file_list.sort(key=lambda s: int(s.replace('.', ' ').replace('_', '').split(' ')[-2])\n ) # 2007_000032.png --> 2007000032\n imgs_insseg_file_list = [os.path.join(folder_insseg, s) for s in imgs_insseg_file_list]\n # logging.info('Instance Seg IM',imgs_insseg_file_list[0::333], imgs_insseg_file_list[-1])\n else:\n imgs_semseg_file_list = []\n imgs_insseg_file_list = []\n # 4. annotations for bounding box and object class\n # folder_ann = path+\"/\"+extracted_filename+\"/Annotations/\"\n folder_ann = os.path.join(path, extracted_filename, \"Annotations\")\n imgs_ann_file_list = load_file_list(path=folder_ann, regx='\\\\.xml', printable=False)\n logging.info(\n \"[VOC] {} XML annotation files for bounding box and object class found\".format(len(imgs_ann_file_list))\n )\n imgs_ann_file_list.sort(key=lambda s: int(s.replace('.', ' ').replace('_', '').split(' ')[-2])\n ) # 2007_000027.xml --> 2007000027\n imgs_ann_file_list = [os.path.join(folder_ann, s) for s in imgs_ann_file_list]\n # logging.info('ANN',imgs_ann_file_list[0::3333], imgs_ann_file_list[-1])\n\n if dataset == \"2012test\": # remove unused images in JPEG folder\n imgs_file_list_new = []\n for ann in imgs_ann_file_list:\n ann = os.path.split(ann)[-1].split('.')[0]\n for im in imgs_file_list:\n if ann in im:\n imgs_file_list_new.append(im)\n break\n imgs_file_list = imgs_file_list_new\n logging.info(\"[VOC] keep %d images\" % len(imgs_file_list_new))\n\n # parse XML annotations\n def convert(size, box):\n dw = 1. / size[0]\n dh = 1. / size[1]\n x = (box[0] + box[1]) / 2.0\n y = (box[2] + box[3]) / 2.0\n w = box[1] - box[0]\n h = box[3] - box[2]\n x = x * dw\n w = w * dw\n y = y * dh\n h = h * dh\n return x, y, w, h\n\n def convert_annotation(file_name):\n \"\"\"Given VOC2012 XML Annotations, returns number of objects and info.\"\"\"\n in_file = open(file_name)\n out_file = \"\"\n tree = ET.parse(in_file)\n root = tree.getroot()\n size = root.find('size')\n w = int(size.find('width').text)\n h = int(size.find('height').text)\n n_objs = 0\n\n for obj in root.iter('object'):\n if dataset != \"2012test\":\n difficult = obj.find('difficult').text\n cls = obj.find('name').text\n if cls not in classes or int(difficult) == 1:\n continue\n else:\n cls = obj.find('name').text\n if cls not in classes:\n continue\n cls_id = classes.index(cls)\n xmlbox = obj.find('bndbox')\n b = (\n float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),\n float(xmlbox.find('ymax').text)\n )\n bb = convert((w, h), b)\n\n out_file += str(cls_id) + \" \" + \" \".join([str(a) for a in bb]) + '\\n'\n n_objs += 1\n if cls in \"person\":\n for part in obj.iter('part'):\n cls = part.find('name').text\n if cls not in classes_in_person:\n continue\n cls_id = classes.index(cls)\n xmlbox = part.find('bndbox')\n b = (\n float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text),\n float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text)\n )\n bb = convert((w, h), b)\n # out_file.write(str(cls_id) + \" \" + \" \".join([str(a) for a in bb]) + '\\n')\n out_file += str(cls_id) + \" \" + \" \".join([str(a) for a in bb]) + '\\n'\n n_objs += 1\n in_file.close()\n return n_objs, out_file\n\n logging.info(\"[VOC] Parsing xml annotations files\")\n n_objs_list = []\n objs_info_list = [] # Darknet Format list of string\n objs_info_dicts = {}\n for idx, ann_file in enumerate(imgs_ann_file_list):\n n_objs, objs_info = convert_annotation(ann_file)\n n_objs_list.append(n_objs)\n objs_info_list.append(objs_info)\n with tf.gfile.GFile(ann_file, 'r') as fid:\n xml_str = fid.read()\n xml = etree.fromstring(xml_str)\n data = _recursive_parse_xml_to_dict(xml)['annotation']\n objs_info_dicts.update({imgs_file_list[idx]: data})\n\n return imgs_file_list, imgs_semseg_file_list, imgs_insseg_file_list, imgs_ann_file_list, classes, classes_in_person, classes_dict, n_objs_list, objs_info_list, objs_info_dicts\n\n\ndef load_mpii_pose_dataset(path='data', is_16_pos_only=False):\n \"\"\"Load MPII Human Pose Dataset.\n\n Parameters\n -----------\n path : str\n The path that the data is downloaded to.\n is_16_pos_only : boolean\n If True, only return the peoples contain 16 pose keypoints. (Usually be used for single person pose estimation)\n\n Returns\n ----------\n img_train_list : list of str\n The image directories of training data.\n ann_train_list : list of dict\n The annotations of training data.\n img_test_list : list of str\n The image directories of testing data.\n ann_test_list : list of dict\n The annotations of testing data.\n\n Examples\n --------\n >>> import pprint\n >>> import tensorlayer as tl\n >>> img_train_list, ann_train_list, img_test_list, ann_test_list = tl.files.load_mpii_pose_dataset()\n >>> image = tl.vis.read_image(img_train_list[0])\n >>> tl.vis.draw_mpii_pose_to_image(image, ann_train_list[0], 'image.png')\n >>> pprint.pprint(ann_train_list[0])\n\n References\n -----------\n - `MPII Human Pose Dataset. CVPR 14 <http://human-pose.mpi-inf.mpg.de>`__\n - `MPII Human Pose Models. CVPR 16 <http://pose.mpi-inf.mpg.de>`__\n - `MPII Human Shape, Poselet Conditioned Pictorial Structures and etc <http://pose.mpi-inf.mpg.de/#related>`__\n - `MPII Keyponts and ID <http://human-pose.mpi-inf.mpg.de/#download>`__\n \"\"\"\n path = os.path.join(path, 'mpii_human_pose')\n logging.info(\"Load or Download MPII Human Pose > {}\".format(path))\n\n # annotation\n url = \"http://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/\"\n tar_filename = \"mpii_human_pose_v1_u12_2.zip\"\n extracted_filename = \"mpii_human_pose_v1_u12_2\"\n if folder_exists(os.path.join(path, extracted_filename)) is False:\n logging.info(\"[MPII] (annotation) {} is nonexistent in {}\".format(extracted_filename, path))\n maybe_download_and_extract(tar_filename, path, url, extract=True)\n del_file(os.path.join(path, tar_filename))\n\n # images\n url = \"http://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/\"\n tar_filename = \"mpii_human_pose_v1.tar.gz\"\n extracted_filename2 = \"images\"\n if folder_exists(os.path.join(path, extracted_filename2)) is False:\n logging.info(\"[MPII] (images) {} is nonexistent in {}\".format(extracted_filename, path))\n maybe_download_and_extract(tar_filename, path, url, extract=True)\n del_file(os.path.join(path, tar_filename))\n\n # parse annotation, format see http://human-pose.mpi-inf.mpg.de/#download\n logging.info(\"reading annotations from mat file ...\")\n # mat = sio.loadmat(os.path.join(path, extracted_filename, \"mpii_human_pose_v1_u12_1.mat\"))\n\n # def fix_wrong_joints(joint): # https://github.com/mitmul/deeppose/blob/master/datasets/mpii_dataset.py\n # if '12' in joint and '13' in joint and '2' in joint and '3' in joint:\n # if ((joint['12'][0] < joint['13'][0]) and\n # (joint['3'][0] < joint['2'][0])):\n # joint['2'], joint['3'] = joint['3'], joint['2']\n # if ((joint['12'][0] > joint['13'][0]) and\n # (joint['3'][0] > joint['2'][0])):\n # joint['2'], joint['3'] = joint['3'], joint['2']\n # return joint\n\n ann_train_list = []\n ann_test_list = []\n img_train_list = []\n img_test_list = []\n\n def save_joints():\n # joint_data_fn = os.path.join(path, 'data.json')\n # fp = open(joint_data_fn, 'w')\n mat = sio.loadmat(os.path.join(path, extracted_filename, \"mpii_human_pose_v1_u12_1.mat\"))\n\n for _, (anno, train_flag) in enumerate( # all images\n zip(mat['RELEASE']['annolist'][0, 0][0], mat['RELEASE']['img_train'][0, 0][0])):\n\n img_fn = anno['image']['name'][0, 0][0]\n train_flag = int(train_flag)\n\n # print(i, img_fn, train_flag) # DEBUG print all images\n\n if train_flag:\n img_train_list.append(img_fn)\n ann_train_list.append([])\n else:\n img_test_list.append(img_fn)\n ann_test_list.append([])\n\n head_rect = []\n if 'x1' in str(anno['annorect'].dtype):\n head_rect = zip(\n [x1[0, 0] for x1 in anno['annorect']['x1'][0]], [y1[0, 0] for y1 in anno['annorect']['y1'][0]],\n [x2[0, 0] for x2 in anno['annorect']['x2'][0]], [y2[0, 0] for y2 in anno['annorect']['y2'][0]]\n )\n else:\n head_rect = [] # TODO\n\n if 'annopoints' in str(anno['annorect'].dtype):\n annopoints = anno['annorect']['annopoints'][0]\n head_x1s = anno['annorect']['x1'][0]\n head_y1s = anno['annorect']['y1'][0]\n head_x2s = anno['annorect']['x2'][0]\n head_y2s = anno['annorect']['y2'][0]\n\n for annopoint, head_x1, head_y1, head_x2, head_y2 in zip(annopoints, head_x1s, head_y1s, head_x2s,\n head_y2s):\n # if annopoint != []:\n # if len(annopoint) != 0:\n if annopoint.size:\n head_rect = [\n float(head_x1[0, 0]),\n float(head_y1[0, 0]),\n float(head_x2[0, 0]),\n float(head_y2[0, 0])\n ]\n\n # joint coordinates\n annopoint = annopoint['point'][0, 0]\n j_id = [str(j_i[0, 0]) for j_i in annopoint['id'][0]]\n x = [x[0, 0] for x in annopoint['x'][0]]\n y = [y[0, 0] for y in annopoint['y'][0]]\n joint_pos = {}\n for _j_id, (_x, _y) in zip(j_id, zip(x, y)):\n joint_pos[int(_j_id)] = [float(_x), float(_y)]\n # joint_pos = fix_wrong_joints(joint_pos)\n\n # visibility list\n if 'is_visible' in str(annopoint.dtype):\n vis = [v[0] if v.size > 0 else [0] for v in annopoint['is_visible'][0]]\n vis = dict([(k, int(v[0])) if len(v) > 0 else v for k, v in zip(j_id, vis)])\n else:\n vis = None\n\n # if len(joint_pos) == 16:\n if ((is_16_pos_only ==True) and (len(joint_pos) == 16)) or (is_16_pos_only == False):\n # only use image with 16 key points / or use all\n data = {\n 'filename': img_fn,\n 'train': train_flag,\n 'head_rect': head_rect,\n 'is_visible': vis,\n 'joint_pos': joint_pos\n }\n # print(json.dumps(data), file=fp) # py3\n if train_flag:\n ann_train_list[-1].append(data)\n else:\n ann_test_list[-1].append(data)\n\n # def write_line(datum, fp):\n # joints = sorted([[int(k), v] for k, v in datum['joint_pos'].items()])\n # joints = np.array([j for i, j in joints]).flatten()\n #\n # out = [datum['filename']]\n # out.extend(joints)\n # out = [str(o) for o in out]\n # out = ','.join(out)\n #\n # print(out, file=fp)\n\n # def split_train_test():\n # # fp_test = open('data/mpii/test_joints.csv', 'w')\n # fp_test = open(os.path.join(path, 'test_joints.csv'), 'w')\n # # fp_train = open('data/mpii/train_joints.csv', 'w')\n # fp_train = open(os.path.join(path, 'train_joints.csv'), 'w')\n # # all_data = open('data/mpii/data.json').readlines()\n # all_data = open(os.path.join(path, 'data.json')).readlines()\n # N = len(all_data)\n # N_test = int(N * 0.1)\n # N_train = N - N_test\n #\n # print('N:{}'.format(N))\n # print('N_train:{}'.format(N_train))\n # print('N_test:{}'.format(N_test))\n #\n # np.random.seed(1701)\n # perm = np.random.permutation(N)\n # test_indices = perm[:N_test]\n # train_indices = perm[N_test:]\n #\n # print('train_indices:{}'.format(len(train_indices)))\n # print('test_indices:{}'.format(len(test_indices)))\n #\n # for i in train_indices:\n # datum = json.loads(all_data[i].strip())\n # write_line(datum, fp_train)\n #\n # for i in test_indices:\n # datum = json.loads(all_data[i].strip())\n # write_line(datum, fp_test)\n\n save_joints()\n # split_train_test() #\n\n ## read images dir\n logging.info(\"reading images list ...\")\n img_dir = os.path.join(path, extracted_filename2)\n _img_list = load_file_list(path=os.path.join(path, extracted_filename2), regx='\\\\.jpg', printable=False)\n # ann_list = json.load(open(os.path.join(path, 'data.json')))\n for i, im in enumerate(img_train_list):\n if im not in _img_list:\n print('missing training image {} in {} (remove from img(ann)_train_list)'.format(im, img_dir))\n # img_train_list.remove(im)\n del img_train_list[i]\n del ann_train_list[i]\n for i, im in enumerate(img_test_list):\n if im not in _img_list:\n print('missing testing image {} in {} (remove from img(ann)_test_list)'.format(im, img_dir))\n # img_test_list.remove(im)\n del img_train_list[i]\n del ann_train_list[i]\n\n ## check annotation and images\n n_train_images = len(img_train_list)\n n_test_images = len(img_test_list)\n n_images = n_train_images + n_test_images\n logging.info(\"n_images: {} n_train_images: {} n_test_images: {}\".format(n_images, n_train_images, n_test_images))\n n_train_ann = len(ann_train_list)\n n_test_ann = len(ann_test_list)\n n_ann = n_train_ann + n_test_ann\n logging.info(\"n_ann: {} n_train_ann: {} n_test_ann: {}\".format(n_ann, n_train_ann, n_test_ann))\n n_train_people = len(sum(ann_train_list, []))\n n_test_people = len(sum(ann_test_list, []))\n n_people = n_train_people + n_test_people\n logging.info(\"n_people: {} n_train_people: {} n_test_people: {}\".format(n_people, n_train_people, n_test_people))\n # add path to all image file name\n for i, value in enumerate(img_train_list):\n img_train_list[i] = os.path.join(img_dir, value)\n for i, value in enumerate(img_test_list):\n img_test_list[i] = os.path.join(img_dir, value)\n return img_train_list, ann_train_list, img_test_list, ann_test_list\n\n\ndef save_npz(save_list=None, name='model.npz', sess=None):\n \"\"\"Input parameters and the file name, save parameters into .npz file. Use tl.utils.load_npz() to restore.\n\n Parameters\n ----------\n save_list : list of tensor\n A list of parameters (tensor) to be saved.\n name : str\n The name of the `.npz` file.\n sess : None or Session\n Session may be required in some case.\n\n Examples\n --------\n Save model to npz\n\n >>> tl.files.save_npz(network.all_params, name='model.npz', sess=sess)\n\n Load model from npz (Method 1)\n\n >>> load_params = tl.files.load_npz(name='model.npz')\n >>> tl.files.assign_params(sess, load_params, network)\n\n Load model from npz (Method 2)\n\n >>> tl.files.load_and_assign_npz(sess=sess, name='model.npz', network=network)\n\n Notes\n -----\n If you got session issues, you can change the value.eval() to value.eval(session=sess)\n\n References\n ----------\n `Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`__\n\n \"\"\"\n if save_list is None:\n save_list = []\n\n save_list_var = []\n if sess:\n save_list_var = sess.run(save_list)\n else:\n try:\n save_list_var.extend([v.eval() for v in save_list])\n except Exception:\n logging.info(\n \" Fail to save model, Hint: pass the session into this function, tl.files.save_npz(network.all_params, name='model.npz', sess=sess)\"\n )\n np.savez(name, params=save_list_var)\n save_list_var = None\n del save_list_var\n logging.info(\"[*] %s saved\" % name)\n\n\ndef load_npz(path='', name='model.npz'):\n \"\"\"Load the parameters of a Model saved by tl.files.save_npz().\n\n Parameters\n ----------\n path : str\n Folder path to `.npz` file.\n name : str\n The name of the `.npz` file.\n\n Returns\n --------\n list of array\n A list of parameters in order.\n\n Examples\n --------\n - See ``tl.files.save_npz``\n\n References\n ----------\n - `Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`__\n\n \"\"\"\n d = np.load(path + name)\n return d['params']\n\n\ndef assign_params(sess, params, network):\n \"\"\"Assign the given parameters to the TensorLayer network.\n\n Parameters\n ----------\n sess : Session\n TensorFlow Session.\n params : list of array\n A list of parameters (array) in order.\n network : :class:`Layer`\n The network to be assigned.\n\n Returns\n --------\n list of operations\n A list of tf ops in order that assign params. Support sess.run(ops) manually.\n\n Examples\n --------\n - See ``tl.files.save_npz``\n\n References\n ----------\n - `Assign value to a TensorFlow variable <http://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable>`__\n\n \"\"\"\n ops = []\n for idx, param in enumerate(params):\n ops.append(network.all_params[idx].assign(param))\n if sess is not None:\n sess.run(ops)\n return ops\n\n\ndef load_and_assign_npz(sess=None, name=None, network=None):\n \"\"\"Load model from npz and assign to a network.\n\n Parameters\n -------------\n sess : Session\n TensorFlow Session.\n name : str\n The name of the `.npz` file.\n network : :class:`Layer`\n The network to be assigned.\n\n Returns\n --------\n False or network\n Returns False, if the model is not exist.\n\n Examples\n --------\n - See ``tl.files.save_npz``\n\n \"\"\"\n if network is None:\n raise ValueError(\"network is None.\")\n if sess is None:\n raise ValueError(\"session is None.\")\n if not os.path.exists(name):\n logging.info(\"[!] Load {} failed!\".format(name))\n return False\n else:\n params = load_npz(name=name)\n assign_params(sess, params, network)\n logging.info(\"[*] Load {} SUCCESS!\".format(name))\n return network\n\n\ndef save_npz_dict(save_list=None, name='model.npz', sess=None):\n \"\"\"Input parameters and the file name, save parameters as a dictionary into .npz file.\n\n Use ``tl.files.load_and_assign_npz_dict()`` to restore.\n\n Parameters\n ----------\n save_list : list of parameters\n A list of parameters (tensor) to be saved.\n name : str\n The name of the `.npz` file.\n sess : Session\n TensorFlow Session.\n\n \"\"\"\n if sess is None:\n raise ValueError(\"session is None.\")\n if save_list is None:\n save_list = []\n\n save_list_names = [tensor.name for tensor in save_list]\n save_list_var = sess.run(save_list)\n save_var_dict = {save_list_names[idx]: val for idx, val in enumerate(save_list_var)}\n np.savez(name, **save_var_dict)\n save_list_var = None\n save_var_dict = None\n del save_list_var\n del save_var_dict\n logging.info(\"[*] Model saved in npz_dict %s\" % name)\n\n\ndef load_and_assign_npz_dict(name='model.npz', sess=None):\n \"\"\"Restore the parameters saved by ``tl.files.save_npz_dict()``.\n\n Parameters\n ----------\n name : str\n The name of the `.npz` file.\n sess : Session\n TensorFlow Session.\n\n \"\"\"\n if sess is None:\n raise ValueError(\"session is None.\")\n\n if not os.path.exists(name):\n logging.info(\"[!] Load {} failed!\".format(name))\n return False\n\n params = np.load(name)\n if len(params.keys()) != len(set(params.keys())):\n raise Exception(\"Duplication in model npz_dict %s\" % name)\n ops = list()\n for key in params.keys():\n try:\n # tensor = tf.get_default_graph().get_tensor_by_name(key)\n # varlist = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=key)\n varlist = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=key)\n if len(varlist) > 1:\n raise Exception(\"[!] Multiple candidate variables to be assigned for name %s\" % key)\n elif len(varlist) == 0:\n raise KeyError\n else:\n ops.append(varlist[0].assign(params[key]))\n logging.info(\"[*] params restored: %s\" % key)\n except KeyError:\n logging.info(\"[!] Warning: Tensor named %s not found in network.\" % key)\n\n sess.run(ops)\n logging.info(\"[*] Model restored from npz_dict %s\" % name)\n\n\ndef save_ckpt(\n sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, global_step=None, printable=False\n):\n \"\"\"Save parameters into `ckpt` file.\n\n Parameters\n ------------\n sess : Session\n TensorFlow Session.\n mode_name : str\n The name of the model, default is ``model.ckpt``.\n save_dir : str\n The path / file directory to the `ckpt`, default is ``checkpoint``.\n var_list : list of tensor\n The parameters / variables (tensor) to be saved. If empty, save all global variables (default).\n global_step : int or None\n Step number.\n printable : boolean\n Whether to print all parameters information.\n\n See Also\n --------\n load_ckpt\n\n \"\"\"\n if sess is None:\n raise ValueError(\"session is None.\")\n if var_list is None:\n var_list = []\n\n ckpt_file = os.path.join(save_dir, mode_name)\n if var_list == []:\n var_list = tf.global_variables()\n\n logging.info(\"[*] save %s n_params: %d\" % (ckpt_file, len(var_list)))\n\n if printable:\n for idx, v in enumerate(var_list):\n logging.info(\" param {:3}: {:15} {}\".format(idx, v.name, str(v.get_shape())))\n\n saver = tf.train.Saver(var_list)\n saver.save(sess, ckpt_file, global_step=global_step)\n\n\ndef load_ckpt(sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, is_latest=True, printable=False):\n \"\"\"Load parameters from `ckpt` file.\n\n Parameters\n ------------\n sess : Session\n TensorFlow Session.\n mode_name : str\n The name of the model, default is ``model.ckpt``.\n save_dir : str\n The path / file directory to the `ckpt`, default is ``checkpoint``.\n var_list : list of tensor\n The parameters / variables (tensor) to be saved. If empty, save all global variables (default).\n is_latest : boolean\n Whether to load the latest `ckpt`, if False, load the `ckpt` with the name of ```mode_name``.\n printable : boolean\n Whether to print all parameters information.\n\n Examples\n ----------\n Save all global parameters.\n\n >>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', save_dir='model', printable=True)\n\n Save specific parameters.\n\n >>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', printable=True)\n\n Load latest ckpt.\n\n >>> tl.files.load_ckpt(sess=sess, var_list=net.all_params, save_dir='model', printable=True)\n\n Load specific ckpt.\n\n >>> tl.files.load_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', is_latest=False, printable=True)\n\n \"\"\"\n if sess is None:\n raise ValueError(\"session is None.\")\n if var_list is None:\n var_list = []\n\n if is_latest:\n ckpt_file = tf.train.latest_checkpoint(save_dir)\n else:\n ckpt_file = os.path.join(save_dir, mode_name)\n\n if not var_list:\n var_list = tf.global_variables()\n\n logging.info(\"[*] load %s n_params: %d\" % (ckpt_file, len(var_list)))\n\n if printable:\n for idx, v in enumerate(var_list):\n logging.info(\" param {:3}: {:15} {}\".format(idx, v.name, str(v.get_shape())))\n\n try:\n saver = tf.train.Saver(var_list)\n saver.restore(sess, ckpt_file)\n except Exception as e:\n logging.info(e)\n logging.info(\"[*] load ckpt fail ...\")\n\n\ndef save_any_to_npy(save_dict=None, name='file.npy'):\n \"\"\"Save variables to `.npy` file.\n\n Parameters\n ------------\n save_dict : directory\n The variables to be saved.\n name : str\n File name.\n\n Examples\n ---------\n >>> tl.files.save_any_to_npy(save_dict={'data': ['a','b']}, name='test.npy')\n >>> data = tl.files.load_npy_to_any(name='test.npy')\n >>> print(data)\n {'data': ['a','b']}\n\n \"\"\"\n if save_dict is None:\n save_dict = {}\n np.save(name, save_dict)\n\n\ndef load_npy_to_any(path='', name='file.npy'):\n \"\"\"Load `.npy` file.\n\n Parameters\n ------------\n path : str\n Path to the file (optional).\n name : str\n File name.\n\n Examples\n ---------\n - see tl.files.save_any_to_npy()\n\n \"\"\"\n file_path = os.path.join(path, name)\n try:\n return np.load(file_path).item()\n except Exception:\n return np.load(file_path)\n raise Exception(\"[!] Fail to load %s\" % file_path)\n\n\ndef file_exists(filepath):\n \"\"\"Check whether a file exists by given file path.\"\"\"\n return os.path.isfile(filepath)\n\n\ndef folder_exists(folderpath):\n \"\"\"Check whether a folder exists by given folder path.\"\"\"\n return os.path.isdir(folderpath)\n\n\ndef del_file(filepath):\n \"\"\"Delete a file by given file path.\"\"\"\n os.remove(filepath)\n\n\ndef del_folder(folderpath):\n \"\"\"Delete a folder by given folder path.\"\"\"\n shutil.rmtree(folderpath)\n\n\ndef read_file(filepath):\n \"\"\"Read a file and return a string.\n\n Examples\n ---------\n >>> data = tl.files.read_file('data.txt')\n\n \"\"\"\n with open(filepath, 'r') as afile:\n return afile.read()\n\n\ndef load_file_list(path=None, regx='\\.npz', printable=True):\n r\"\"\"Return a file list in a folder by given a path and regular expression.\n\n Parameters\n ----------\n path : str or None\n A folder path, if `None`, use the current directory.\n regx : str\n The regx of file name.\n printable : boolean\n Whether to print the files infomation.\n\n Examples\n ----------\n >>> file_list = tl.files.load_file_list(path=None, regx='w1pre_[0-9]+\\.(npz)')\n\n \"\"\"\n if path is None:\n path = os.getcwd()\n file_list = os.listdir(path)\n return_list = []\n for _, f in enumerate(file_list):\n if re.search(regx, f):\n return_list.append(f)\n # return_list.sort()\n if printable:\n logging.info('Match file list = %s' % return_list)\n logging.info('Number of files = %d' % len(return_list))\n return return_list\n\n\ndef load_folder_list(path=\"\"):\n \"\"\"Return a folder list in a folder by given a folder path.\n\n Parameters\n ----------\n path : str\n A folder path.\n\n \"\"\"\n return [os.path.join(path, o) for o in os.listdir(path) if os.path.isdir(os.path.join(path, o))]\n\n\ndef exists_or_mkdir(path, verbose=True):\n \"\"\"Check a folder by given name, if not exist, create the folder and return False,\n if directory exists, return True.\n\n Parameters\n ----------\n path : str\n A folder path.\n verbose : boolean\n If True (default), prints results.\n\n Returns\n --------\n boolean\n True if folder already exist, otherwise, returns False and create the folder.\n\n Examples\n --------\n >>> tl.files.exists_or_mkdir(\"checkpoints/train\")\n\n \"\"\"\n if not os.path.exists(path):\n if verbose:\n logging.info(\"[*] creates %s ...\" % path)\n os.makedirs(path)\n return False\n else:\n if verbose:\n logging.info(\"[!] %s exists ...\" % path)\n return True\n\n\ndef maybe_download_and_extract(filename, working_directory, url_source, extract=False, expected_bytes=None):\n \"\"\"Checks if file exists in working_directory otherwise tries to dowload the file,\n and optionally also tries to extract the file if format is \".zip\" or \".tar\"\n\n Parameters\n -----------\n filename : str\n The name of the (to be) dowloaded file.\n working_directory : str\n A folder path to search for the file in and dowload the file to\n url : str\n The URL to download the file from\n extract : boolean\n If True, tries to uncompress the dowloaded file is \".tar.gz/.tar.bz2\" or \".zip\" file, default is False.\n expected_bytes : int or None\n If set tries to verify that the downloaded file is of the specified size, otherwise raises an Exception, defaults is None which corresponds to no check being performed.\n\n Returns\n ----------\n str\n File path of the dowloaded (uncompressed) file.\n\n Examples\n --------\n >>> down_file = tl.files.maybe_download_and_extract(filename='train-images-idx3-ubyte.gz',\n ... working_directory='data/',\n ... url_source='http://yann.lecun.com/exdb/mnist/')\n >>> tl.files.maybe_download_and_extract(filename='ADEChallengeData2016.zip',\n ... working_directory='data/',\n ... url_source='http://sceneparsing.csail.mit.edu/data/',\n ... extract=True)\n\n \"\"\"\n\n # We first define a download function, supporting both Python 2 and 3.\n def _download(filename, working_directory, url_source):\n\n progress_bar = progressbar.ProgressBar()\n\n def _dlProgress(count, blockSize, totalSize, pbar=progress_bar):\n if (totalSize != 0):\n\n if not pbar.max_value:\n totalBlocks = math.ceil(float(totalSize) / float(blockSize))\n pbar.max_value = int(totalBlocks)\n\n pbar.update(count, force=True)\n\n filepath = os.path.join(working_directory, filename)\n\n logging.info('Downloading %s...\\n' % filename)\n\n urlretrieve(url_source + filename, filepath, reporthook=_dlProgress)\n\n exists_or_mkdir(working_directory, verbose=False)\n filepath = os.path.join(working_directory, filename)\n\n if not os.path.exists(filepath):\n _download(filename, working_directory, url_source)\n statinfo = os.stat(filepath)\n logging.info('Succesfully downloaded %s %s bytes.' % (filename, statinfo.st_size)) #, 'bytes.')\n if (not (expected_bytes is None) and (expected_bytes != statinfo.st_size)):\n raise Exception('Failed to verify ' + filename + '. Can you get to it with a browser?')\n if (extract):\n if tarfile.is_tarfile(filepath):\n logging.info('Trying to extract tar file')\n tarfile.open(filepath, 'r').extractall(working_directory)\n logging.info('... Success!')\n elif zipfile.is_zipfile(filepath):\n logging.info('Trying to extract zip file')\n with zipfile.ZipFile(filepath) as zf:\n zf.extractall(working_directory)\n logging.info('... Success!')\n else:\n logging.info(\"Unknown compression_format only .tar.gz/.tar.bz2/.tar and .zip supported\")\n return filepath\n\n\ndef natural_keys(text):\n \"\"\"Sort list of string with number in human order.\n\n Examples\n ----------\n >>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']\n >>> l.sort(key=tl.files.natural_keys)\n ['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg']\n >>> l.sort() # that is what we dont want\n ['im03.jpg', 'im05', 'im1.jpg', 'im11.jpg', 'im21.jpg', 'im31.jpg']\n\n References\n ----------\n - `link <http://nedbatchelder.com/blog/200712/human_sorting.html>`__\n\n \"\"\"\n\n # - alist.sort(key=natural_keys) sorts in human order\n # http://nedbatchelder.com/blog/200712/human_sorting.html\n # (See Toothy's implementation in the comments)\n def atoi(text):\n return int(text) if text.isdigit() else text\n\n return [atoi(c) for c in re.split('(\\d+)', text)]\n\n\n# Visualizing npz files\ndef npz_to_W_pdf(path=None, regx='w1pre_[0-9]+\\.(npz)'):\n r\"\"\"Convert the first weight matrix of `.npz` file to `.pdf` by using `tl.visualize.W()`.\n\n Parameters\n ----------\n path : str\n A folder path to `npz` files.\n regx : str\n Regx for the file name.\n\n Examples\n ---------\n Convert the first weight matrix of w1_pre...npz file to w1_pre...pdf.\n\n >>> tl.files.npz_to_W_pdf(path='/Users/.../npz_file/', regx='w1pre_[0-9]+\\.(npz)')\n\n \"\"\"\n file_list = load_file_list(path=path, regx=regx)\n for f in file_list:\n W = load_npz(path, f)[0]\n logging.info(\"%s --> %s\" % (f, f.split('.')[0] + '.pdf'))\n visualize.draw_weights(W, second=10, saveable=True, name=f.split('.')[0], fig_idx=2012)\n" ]
[ [ "numpy.save", "numpy.random.seed", "numpy.asarray", "matplotlib.pyplot.imshow", "numpy.vstack", "matplotlib.pyplot.pause", "numpy.transpose", "matplotlib.pyplot.figure", "numpy.savez", "tensorflow.gfile.GFile", "matplotlib.pyplot.gca", "scipy.io.loadmat", "numpy.load", "numpy.tile", "matplotlib.pyplot.draw", "tensorflow.get_collection", "numpy.float32", "tensorflow.global_variables", "matplotlib.pyplot.NullLocator", "tensorflow.train.Saver", "matplotlib.pyplot.ion", "numpy.random.shuffle", "numpy.squeeze", "tensorflow.python.platform.gfile.Exists", "tensorflow.train.latest_checkpoint", "numpy.array", "numpy.concatenate" ] ]
anon-paper-github/cvpr-641
[ "d969e2a3ca002bee9d9320d0ee33802b2f532742" ]
[ "ZSSGAN/mapper/training/ranger.py" ]
[ "# Ranger deep learning optimizer - RAdam + Lookahead + Gradient Centralization, combined into one optimizer.\r\n\r\n# https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer\r\n# and/or\r\n# https://github.com/lessw2020/Best-Deep-Learning-Optimizers\r\n\r\n# Ranger has now been used to capture 12 records on the FastAI leaderboard.\r\n\r\n# This version = 20.4.11\r\n\r\n# Credits:\r\n# Gradient Centralization --> https://arxiv.org/abs/2004.01461v2 (a new optimization technique for DNNs), github: https://github.com/Yonghongwei/Gradient-Centralization\r\n# RAdam --> https://github.com/LiyuanLucasLiu/RAdam\r\n# Lookahead --> rewritten by lessw2020, but big thanks to Github @LonePatient and @RWightman for ideas from their code.\r\n# Lookahead paper --> MZhang,G Hinton https://arxiv.org/abs/1907.08610\r\n\r\n# summary of changes:\r\n# 4/11/20 - add gradient centralization option. Set new testing benchmark for accuracy with it, toggle with use_gc flag at init.\r\n# full code integration with all updates at param level instead of group, moves slow weights into state dict (from generic weights),\r\n# supports group learning rates (thanks @SHolderbach), fixes sporadic load from saved model issues.\r\n# changes 8/31/19 - fix references to *self*.N_sma_threshold;\r\n# changed eps to 1e-5 as better default than 1e-8.\r\n\r\nimport math\r\nimport torch\r\nfrom torch.optim.optimizer import Optimizer\r\n\r\n\r\nclass Ranger(Optimizer):\r\n\r\n\tdef __init__(self, params, lr=1e-3, # lr\r\n\t\t\t\t alpha=0.5, k=6, N_sma_threshhold=5, # Ranger options\r\n\t\t\t\t betas=(.95, 0.999), eps=1e-5, weight_decay=0, # Adam options\r\n\t\t\t\t use_gc=True, gc_conv_only=False\r\n\t\t\t\t # Gradient centralization on or off, applied to conv layers only or conv + fc layers\r\n\t\t\t\t ):\r\n\r\n\t\t# parameter checks\r\n\t\tif not 0.0 <= alpha <= 1.0:\r\n\t\t\traise ValueError(f'Invalid slow update rate: {alpha}')\r\n\t\tif not 1 <= k:\r\n\t\t\traise ValueError(f'Invalid lookahead steps: {k}')\r\n\t\tif not lr > 0:\r\n\t\t\traise ValueError(f'Invalid Learning Rate: {lr}')\r\n\t\tif not eps > 0:\r\n\t\t\traise ValueError(f'Invalid eps: {eps}')\r\n\r\n\t\t# parameter comments:\r\n\t\t# beta1 (momentum) of .95 seems to work better than .90...\r\n\t\t# N_sma_threshold of 5 seems better in testing than 4.\r\n\t\t# In both cases, worth testing on your dataset (.90 vs .95, 4 vs 5) to make sure which works best for you.\r\n\r\n\t\t# prep defaults and init torch.optim base\r\n\t\tdefaults = dict(lr=lr, alpha=alpha, k=k, step_counter=0, betas=betas, N_sma_threshhold=N_sma_threshhold,\r\n\t\t\t\t\t\teps=eps, weight_decay=weight_decay)\r\n\t\tsuper().__init__(params, defaults)\r\n\r\n\t\t# adjustable threshold\r\n\t\tself.N_sma_threshhold = N_sma_threshhold\r\n\r\n\t\t# look ahead params\r\n\r\n\t\tself.alpha = alpha\r\n\t\tself.k = k\r\n\r\n\t\t# radam buffer for state\r\n\t\tself.radam_buffer = [[None, None, None] for ind in range(10)]\r\n\r\n\t\t# gc on or off\r\n\t\tself.use_gc = use_gc\r\n\r\n\t\t# level of gradient centralization\r\n\t\tself.gc_gradient_threshold = 3 if gc_conv_only else 1\r\n\r\n\tdef __setstate__(self, state):\r\n\t\tsuper(Ranger, self).__setstate__(state)\r\n\r\n\tdef step(self, closure=None):\r\n\t\tloss = None\r\n\r\n\t\t# Evaluate averages and grad, update param tensors\r\n\t\tfor group in self.param_groups:\r\n\r\n\t\t\tfor p in group['params']:\r\n\t\t\t\tif p.grad is None:\r\n\t\t\t\t\tcontinue\r\n\t\t\t\tgrad = p.grad.data.float()\r\n\r\n\t\t\t\tif grad.is_sparse:\r\n\t\t\t\t\traise RuntimeError('Ranger optimizer does not support sparse gradients')\r\n\r\n\t\t\t\tp_data_fp32 = p.data.float()\r\n\r\n\t\t\t\tstate = self.state[p] # get state dict for this param\r\n\r\n\t\t\t\tif len(state) == 0: # if first time to run...init dictionary with our desired entries\r\n\t\t\t\t\t# if self.first_run_check==0:\r\n\t\t\t\t\t# self.first_run_check=1\r\n\t\t\t\t\t# print(\"Initializing slow buffer...should not see this at load from saved model!\")\r\n\t\t\t\t\tstate['step'] = 0\r\n\t\t\t\t\tstate['exp_avg'] = torch.zeros_like(p_data_fp32)\r\n\t\t\t\t\tstate['exp_avg_sq'] = torch.zeros_like(p_data_fp32)\r\n\r\n\t\t\t\t\t# look ahead weight storage now in state dict\r\n\t\t\t\t\tstate['slow_buffer'] = torch.empty_like(p.data)\r\n\t\t\t\t\tstate['slow_buffer'].copy_(p.data)\r\n\r\n\t\t\t\telse:\r\n\t\t\t\t\tstate['exp_avg'] = state['exp_avg'].type_as(p_data_fp32)\r\n\t\t\t\t\tstate['exp_avg_sq'] = state['exp_avg_sq'].type_as(p_data_fp32)\r\n\r\n\t\t\t\t# begin computations\r\n\t\t\t\texp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\r\n\t\t\t\tbeta1, beta2 = group['betas']\r\n\r\n\t\t\t\t# GC operation for Conv layers and FC layers\r\n\t\t\t\tif grad.dim() > self.gc_gradient_threshold:\r\n\t\t\t\t\tgrad.add_(-grad.mean(dim=tuple(range(1, grad.dim())), keepdim=True))\r\n\r\n\t\t\t\tstate['step'] += 1\r\n\r\n\t\t\t\t# compute variance mov avg\r\n\t\t\t\texp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\r\n\t\t\t\t# compute mean moving avg\r\n\t\t\t\texp_avg.mul_(beta1).add_(1 - beta1, grad)\r\n\r\n\t\t\t\tbuffered = self.radam_buffer[int(state['step'] % 10)]\r\n\r\n\t\t\t\tif state['step'] == buffered[0]:\r\n\t\t\t\t\tN_sma, step_size = buffered[1], buffered[2]\r\n\t\t\t\telse:\r\n\t\t\t\t\tbuffered[0] = state['step']\r\n\t\t\t\t\tbeta2_t = beta2 ** state['step']\r\n\t\t\t\t\tN_sma_max = 2 / (1 - beta2) - 1\r\n\t\t\t\t\tN_sma = N_sma_max - 2 * state['step'] * beta2_t / (1 - beta2_t)\r\n\t\t\t\t\tbuffered[1] = N_sma\r\n\t\t\t\t\tif N_sma > self.N_sma_threshhold:\r\n\t\t\t\t\t\tstep_size = math.sqrt(\r\n\t\t\t\t\t\t\t(1 - beta2_t) * (N_sma - 4) / (N_sma_max - 4) * (N_sma - 2) / N_sma * N_sma_max / (\r\n\t\t\t\t\t\t\t\t\t\tN_sma_max - 2)) / (1 - beta1 ** state['step'])\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tstep_size = 1.0 / (1 - beta1 ** state['step'])\r\n\t\t\t\t\tbuffered[2] = step_size\r\n\r\n\t\t\t\tif group['weight_decay'] != 0:\r\n\t\t\t\t\tp_data_fp32.add_(-group['weight_decay'] * group['lr'], p_data_fp32)\r\n\r\n\t\t\t\t# apply lr\r\n\t\t\t\tif N_sma > self.N_sma_threshhold:\r\n\t\t\t\t\tdenom = exp_avg_sq.sqrt().add_(group['eps'])\r\n\t\t\t\t\tp_data_fp32.addcdiv_(-step_size * group['lr'], exp_avg, denom)\r\n\t\t\t\telse:\r\n\t\t\t\t\tp_data_fp32.add_(-step_size * group['lr'], exp_avg)\r\n\r\n\t\t\t\tp.data.copy_(p_data_fp32)\r\n\r\n\t\t\t\t# integrated look ahead...\r\n\t\t\t\t# we do it at the param level instead of group level\r\n\t\t\t\tif state['step'] % group['k'] == 0:\r\n\t\t\t\t\tslow_p = state['slow_buffer'] # get access to slow param tensor\r\n\t\t\t\t\tslow_p.add_(self.alpha, p.data - slow_p) # (fast weights - slow weights) * alpha\r\n\t\t\t\t\tp.data.copy_(slow_p) # copy interpolated weights to RAdam param tensor\r\n\r\n\t\treturn loss" ]
[ [ "torch.zeros_like", "torch.empty_like" ] ]
parekhmitchell/NCAA-ML
[ "f075448e89b993a8515d02ab52bec1fb0ac3c020" ]
[ "src/NCAAClassification.py" ]
[ "# Toolkit used for Classification\n\n# Importing Libraries\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Logistic Regression Classification\ndef logRegress(X_train, y_train, X_test, y_test):\n # Fitting Logistic Regression to the Training set\n classifier = LogisticRegression(random_state = 0)\n classifier.fit(X_train, y_train)\n \n # Predicting the Test set results\n y_pred = classifier.predict(X_test)\n\n # Counting accurate responses\n cm = numClose(y_test, y_pred)\n\n return [y_pred, cm]\n\n# SVM Classificaiton\ndef svm(X_train, y_train, X_test, y_test):\n # Fitting SVM to the Training set\n classifier = SVC(kernel = 'linear', random_state = 0)\n classifier.fit(X_train, y_train)\n \n # Predicting the Test set results\n y_pred = classifier.predict(X_test)\n \n # Counting accurate responses\n cm = numClose(y_test, y_pred)\n\n return [y_pred, cm]\n\n# Random Forest Classification\ndef rfor(X_train, y_train, X_test, y_test):\n # Fitting Random Forest Classification to the Training set\n classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)\n classifier.fit(X_train, y_train)\n\n # Predicting the Test set results\n y_pred = classifier.predict(X_test)\n\n # Counting accurate responses\n cm = numClose(y_test, y_pred)\n \n return [y_pred, cm]\n\n# Helper Method to Calculate num close\ndef numClose(y_test, y_pred):\n result = 0;\n for pos in range(0, len(y_test)):\n if(y_test[pos] == y_pred[pos]):\n # or\n #y_test[pos] == y_pred[pos] + 1 or\n #y_test[pos] == y_pred[pos] -1):\n result += 1\n \n return result" ]
[ [ "sklearn.ensemble.RandomForestClassifier", "sklearn.svm.SVC", "sklearn.linear_model.LogisticRegression" ] ]
Asurada2015/TF-_for_MI
[ "5fafdb78286b122036fa9aecf2a4be72ea4673e1" ]
[ "chapters/04_machine_learning_basics/generic.py" ]
[ "# TF code scaffolding for building simple models.\n# 为模型训练和评估定义一个通用的代码框架\nimport tensorflow as tf\n\n\n# 初始化变量和模型参数,定义训练闭环中的运算\n# initialize variables/model parameters\n# define the training loop operations\ndef inference(X):\n # compute inference model over data X and return the result\n # 计算推断模型在数据X上的输出,并将结果返回\n return\n\n\ndef loss(X, Y):\n # compute loss over training data X and expected values Y\n # 依据训练数据X及其期望输出Y计算损失\n return\n\n\ndef inputs():\n # read/generate input training data X and expected outputs Y\n # 读取或生成训练数据X及其期望输出Y\n return\n\n\ndef train(total_loss):\n # train / adjust model parameters according to computed total loss\n # 依据计算的总损失训练或调整模型参数\n return\n\n\ndef evaluate(sess, X, Y):\n # evaluate the resulting trained model\n # 对训练得到的模型进行评估\n return\n\n\n# Launch the graph in a session, setup boilerplate\n# 在一个回话对象红启动数据流图,搭建流程\nwith tf.Session() as sess:\n tf.initialize_all_variables().run()\n\n X, Y = inputs()\n\n total_loss = loss(X, Y)\n train_op = train(total_loss)\n\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n # actual training loop\n # 实际的训练闭环迭代次数\n training_steps = 1000\n for step in range(training_steps):\n sess.run([train_op])\n # for debugging and learning purposes, see how the loss gets decremented thru training steps\n # 处于调试和学习的目的,查看损失在训练从过程中递减的情况\n if step%10 == 0:\n print(\"loss: \", sess.run([total_loss]))\n\n evaluate(sess, X, Y)\n\n coord.request_stop()\n coord.join(threads)\n sess.close()\n" ]
[ [ "tensorflow.initialize_all_variables", "tensorflow.train.start_queue_runners", "tensorflow.Session", "tensorflow.train.Coordinator" ] ]