repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
egao1980/pandas | [
"a3abb9eb7822e7bb9c1bc03181f05d40377fc628"
]
| [
"pandas/tests/internals/test_internals.py"
]
| [
"# -*- coding: utf-8 -*-\n# pylint: disable=W0102\n\nfrom datetime import datetime, date\nimport operator\nimport sys\nimport pytest\nimport numpy as np\n\nimport re\nfrom distutils.version import LooseVersion\nimport itertools\nfrom pandas import (Index, MultiIndex, DataFrame, DatetimeIndex,\n Series, Categorical, TimedeltaIndex, SparseArray)\nfrom pandas.compat import OrderedDict, lrange\nfrom pandas.core.internals import (BlockPlacement, SingleBlockManager,\n make_block, BlockManager)\nimport pandas.core.algorithms as algos\nimport pandas.util.testing as tm\nimport pandas as pd\nfrom pandas.util.testing import (assert_almost_equal, assert_frame_equal,\n randn, assert_series_equal)\nfrom pandas.compat import zip, u\n\n# in 3.6.1 a c-api slicing function changed, see src/compat_helper.h\nPY361 = LooseVersion(sys.version) >= LooseVersion('3.6.1')\n\n\[email protected]\ndef mgr():\n return create_mgr(\n 'a: f8; b: object; c: f8; d: object; e: f8;'\n 'f: bool; g: i8; h: complex; i: datetime-1; j: datetime-2;'\n 'k: M8[ns, US/Eastern]; l: M8[ns, CET];')\n\n\ndef assert_block_equal(left, right):\n tm.assert_numpy_array_equal(left.values, right.values)\n assert left.dtype == right.dtype\n assert isinstance(left.mgr_locs, BlockPlacement)\n assert isinstance(right.mgr_locs, BlockPlacement)\n tm.assert_numpy_array_equal(left.mgr_locs.as_array,\n right.mgr_locs.as_array)\n\n\ndef get_numeric_mat(shape):\n arr = np.arange(shape[0])\n return np.lib.stride_tricks.as_strided(x=arr, shape=shape, strides=(\n arr.itemsize, ) + (0, ) * (len(shape) - 1)).copy()\n\n\nN = 10\n\n\ndef create_block(typestr, placement, item_shape=None, num_offset=0):\n \"\"\"\n Supported typestr:\n\n * float, f8, f4, f2\n * int, i8, i4, i2, i1\n * uint, u8, u4, u2, u1\n * complex, c16, c8\n * bool\n * object, string, O\n * datetime, dt, M8[ns], M8[ns, tz]\n * timedelta, td, m8[ns]\n * sparse (SparseArray with fill_value=0.0)\n * sparse_na (SparseArray with fill_value=np.nan)\n * category, category2\n\n \"\"\"\n placement = BlockPlacement(placement)\n num_items = len(placement)\n\n if item_shape is None:\n item_shape = (N, )\n\n shape = (num_items, ) + item_shape\n\n mat = get_numeric_mat(shape)\n\n if typestr in ('float', 'f8', 'f4', 'f2', 'int', 'i8', 'i4', 'i2', 'i1',\n 'uint', 'u8', 'u4', 'u2', 'u1'):\n values = mat.astype(typestr) + num_offset\n elif typestr in ('complex', 'c16', 'c8'):\n values = 1.j * (mat.astype(typestr) + num_offset)\n elif typestr in ('object', 'string', 'O'):\n values = np.reshape(['A%d' % i for i in mat.ravel() + num_offset],\n shape)\n elif typestr in ('b', 'bool', ):\n values = np.ones(shape, dtype=np.bool_)\n elif typestr in ('datetime', 'dt', 'M8[ns]'):\n values = (mat * 1e9).astype('M8[ns]')\n elif typestr.startswith('M8[ns'):\n # datetime with tz\n m = re.search(r'M8\\[ns,\\s*(\\w+\\/?\\w*)\\]', typestr)\n assert m is not None, \"incompatible typestr -> {0}\".format(typestr)\n tz = m.groups()[0]\n assert num_items == 1, \"must have only 1 num items for a tz-aware\"\n values = DatetimeIndex(np.arange(N) * 1e9, tz=tz)\n elif typestr in ('timedelta', 'td', 'm8[ns]'):\n values = (mat * 1).astype('m8[ns]')\n elif typestr in ('category', ):\n values = Categorical([1, 1, 2, 2, 3, 3, 3, 3, 4, 4])\n elif typestr in ('category2', ):\n values = Categorical(['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd'\n ])\n elif typestr in ('sparse', 'sparse_na'):\n # FIXME: doesn't support num_rows != 10\n assert shape[-1] == 10\n assert all(s == 1 for s in shape[:-1])\n if typestr.endswith('_na'):\n fill_value = np.nan\n else:\n fill_value = 0.0\n values = SparseArray([fill_value, fill_value, 1, 2, 3, fill_value,\n 4, 5, fill_value, 6], fill_value=fill_value)\n arr = values.sp_values.view()\n arr += (num_offset - 1)\n else:\n raise ValueError('Unsupported typestr: \"%s\"' % typestr)\n\n return make_block(values, placement=placement, ndim=len(shape))\n\n\ndef create_single_mgr(typestr, num_rows=None):\n if num_rows is None:\n num_rows = N\n\n return SingleBlockManager(\n create_block(typestr, placement=slice(0, num_rows), item_shape=()),\n np.arange(num_rows))\n\n\ndef create_mgr(descr, item_shape=None):\n \"\"\"\n Construct BlockManager from string description.\n\n String description syntax looks similar to np.matrix initializer. It looks\n like this::\n\n a,b,c: f8; d,e,f: i8\n\n Rules are rather simple:\n\n * see list of supported datatypes in `create_block` method\n * components are semicolon-separated\n * each component is `NAME,NAME,NAME: DTYPE_ID`\n * whitespace around colons & semicolons are removed\n * components with same DTYPE_ID are combined into single block\n * to force multiple blocks with same dtype, use '-SUFFIX'::\n\n 'a:f8-1; b:f8-2; c:f8-foobar'\n\n \"\"\"\n if item_shape is None:\n item_shape = (N, )\n\n offset = 0\n mgr_items = []\n block_placements = OrderedDict()\n for d in descr.split(';'):\n d = d.strip()\n if not len(d):\n continue\n names, blockstr = d.partition(':')[::2]\n blockstr = blockstr.strip()\n names = names.strip().split(',')\n\n mgr_items.extend(names)\n placement = list(np.arange(len(names)) + offset)\n try:\n block_placements[blockstr].extend(placement)\n except KeyError:\n block_placements[blockstr] = placement\n offset += len(names)\n\n mgr_items = Index(mgr_items)\n\n blocks = []\n num_offset = 0\n for blockstr, placement in block_placements.items():\n typestr = blockstr.split('-')[0]\n blocks.append(create_block(typestr,\n placement,\n item_shape=item_shape,\n num_offset=num_offset, ))\n num_offset += len(placement)\n\n return BlockManager(sorted(blocks, key=lambda b: b.mgr_locs[0]),\n [mgr_items] + [np.arange(n) for n in item_shape])\n\n\nclass TestBlock(object):\n\n def setup_method(self, method):\n # self.fblock = get_float_ex() # a,c,e\n # self.cblock = get_complex_ex() #\n # self.oblock = get_obj_ex()\n # self.bool_block = get_bool_ex()\n # self.int_block = get_int_ex()\n\n self.fblock = create_block('float', [0, 2, 4])\n self.cblock = create_block('complex', [7])\n self.oblock = create_block('object', [1, 3])\n self.bool_block = create_block('bool', [5])\n self.int_block = create_block('int', [6])\n\n def test_constructor(self):\n int32block = create_block('i4', [0])\n assert int32block.dtype == np.int32\n\n def test_pickle(self):\n def _check(blk):\n assert_block_equal(tm.round_trip_pickle(blk), blk)\n\n _check(self.fblock)\n _check(self.cblock)\n _check(self.oblock)\n _check(self.bool_block)\n\n def test_mgr_locs(self):\n assert isinstance(self.fblock.mgr_locs, BlockPlacement)\n tm.assert_numpy_array_equal(self.fblock.mgr_locs.as_array,\n np.array([0, 2, 4], dtype=np.int64))\n\n def test_attrs(self):\n assert self.fblock.shape == self.fblock.values.shape\n assert self.fblock.dtype == self.fblock.values.dtype\n assert len(self.fblock) == len(self.fblock.values)\n\n def test_merge(self):\n avals = randn(2, 10)\n bvals = randn(2, 10)\n\n ref_cols = Index(['e', 'a', 'b', 'd', 'f'])\n\n ablock = make_block(avals, ref_cols.get_indexer(['e', 'b']))\n bblock = make_block(bvals, ref_cols.get_indexer(['a', 'd']))\n merged = ablock.merge(bblock)\n tm.assert_numpy_array_equal(merged.mgr_locs.as_array,\n np.array([0, 1, 2, 3], dtype=np.int64))\n tm.assert_numpy_array_equal(merged.values[[0, 2]], np.array(avals))\n tm.assert_numpy_array_equal(merged.values[[1, 3]], np.array(bvals))\n\n # TODO: merge with mixed type?\n\n def test_copy(self):\n cop = self.fblock.copy()\n assert cop is not self.fblock\n assert_block_equal(self.fblock, cop)\n\n def test_reindex_index(self):\n pass\n\n def test_reindex_cast(self):\n pass\n\n def test_insert(self):\n pass\n\n def test_delete(self):\n newb = self.fblock.copy()\n newb.delete(0)\n assert isinstance(newb.mgr_locs, BlockPlacement)\n tm.assert_numpy_array_equal(newb.mgr_locs.as_array,\n np.array([2, 4], dtype=np.int64))\n assert (newb.values[0] == 1).all()\n\n newb = self.fblock.copy()\n newb.delete(1)\n assert isinstance(newb.mgr_locs, BlockPlacement)\n tm.assert_numpy_array_equal(newb.mgr_locs.as_array,\n np.array([0, 4], dtype=np.int64))\n assert (newb.values[1] == 2).all()\n\n newb = self.fblock.copy()\n newb.delete(2)\n tm.assert_numpy_array_equal(newb.mgr_locs.as_array,\n np.array([0, 2], dtype=np.int64))\n assert (newb.values[1] == 1).all()\n\n newb = self.fblock.copy()\n with pytest.raises(Exception):\n newb.delete(3)\n\n def test_make_block_same_class(self):\n # issue 19431\n block = create_block('M8[ns, US/Eastern]', [3])\n with tm.assert_produces_warning(DeprecationWarning,\n check_stacklevel=False):\n block.make_block_same_class(block.values.values,\n dtype=block.values.dtype)\n\n\nclass TestDatetimeBlock(object):\n\n def test_try_coerce_arg(self):\n block = create_block('datetime', [0])\n\n # coerce None\n none_coerced = block._try_coerce_args(block.values, None)[2]\n assert pd.Timestamp(none_coerced) is pd.NaT\n\n # coerce different types of date bojects\n vals = (np.datetime64('2010-10-10'), datetime(2010, 10, 10),\n date(2010, 10, 10))\n for val in vals:\n coerced = block._try_coerce_args(block.values, val)[2]\n assert np.int64 == type(coerced)\n assert pd.Timestamp('2010-10-10') == pd.Timestamp(coerced)\n\n\nclass TestBlockManager(object):\n\n def test_constructor_corner(self):\n pass\n\n def test_attrs(self):\n mgr = create_mgr('a,b,c: f8-1; d,e,f: f8-2')\n assert mgr.nblocks == 2\n assert len(mgr) == 6\n\n def test_is_mixed_dtype(self):\n assert not create_mgr('a,b:f8').is_mixed_type\n assert not create_mgr('a:f8-1; b:f8-2').is_mixed_type\n\n assert create_mgr('a,b:f8; c,d: f4').is_mixed_type\n assert create_mgr('a,b:f8; c,d: object').is_mixed_type\n\n def test_is_indexed_like(self):\n mgr1 = create_mgr('a,b: f8')\n mgr2 = create_mgr('a:i8; b:bool')\n mgr3 = create_mgr('a,b,c: f8')\n assert mgr1._is_indexed_like(mgr1)\n assert mgr1._is_indexed_like(mgr2)\n assert mgr1._is_indexed_like(mgr3)\n\n assert not mgr1._is_indexed_like(mgr1.get_slice(\n slice(-1), axis=1))\n\n def test_duplicate_ref_loc_failure(self):\n tmp_mgr = create_mgr('a:bool; a: f8')\n\n axes, blocks = tmp_mgr.axes, tmp_mgr.blocks\n\n blocks[0].mgr_locs = np.array([0])\n blocks[1].mgr_locs = np.array([0])\n\n # test trying to create block manager with overlapping ref locs\n with pytest.raises(AssertionError):\n BlockManager(blocks, axes)\n\n blocks[0].mgr_locs = np.array([0])\n blocks[1].mgr_locs = np.array([1])\n mgr = BlockManager(blocks, axes)\n mgr.iget(1)\n\n def test_contains(self, mgr):\n assert 'a' in mgr\n assert 'baz' not in mgr\n\n def test_pickle(self, mgr):\n\n mgr2 = tm.round_trip_pickle(mgr)\n assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))\n\n # share ref_items\n # assert mgr2.blocks[0].ref_items is mgr2.blocks[1].ref_items\n\n # GH2431\n assert hasattr(mgr2, \"_is_consolidated\")\n assert hasattr(mgr2, \"_known_consolidated\")\n\n # reset to False on load\n assert not mgr2._is_consolidated\n assert not mgr2._known_consolidated\n\n def test_non_unique_pickle(self):\n\n mgr = create_mgr('a,a,a:f8')\n mgr2 = tm.round_trip_pickle(mgr)\n assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))\n\n mgr = create_mgr('a: f8; a: i8')\n mgr2 = tm.round_trip_pickle(mgr)\n assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))\n\n def test_categorical_block_pickle(self):\n mgr = create_mgr('a: category')\n mgr2 = tm.round_trip_pickle(mgr)\n assert_frame_equal(DataFrame(mgr), DataFrame(mgr2))\n\n smgr = create_single_mgr('category')\n smgr2 = tm.round_trip_pickle(smgr)\n assert_series_equal(Series(smgr), Series(smgr2))\n\n def test_get_scalar(self, mgr):\n for item in mgr.items:\n for i, index in enumerate(mgr.axes[1]):\n res = mgr.get_scalar((item, index))\n exp = mgr.get(item, fastpath=False)[i]\n assert res == exp\n exp = mgr.get(item).internal_values()[i]\n assert res == exp\n\n def test_get(self):\n cols = Index(list('abc'))\n values = np.random.rand(3, 3)\n block = make_block(values=values.copy(), placement=np.arange(3))\n mgr = BlockManager(blocks=[block], axes=[cols, np.arange(3)])\n\n assert_almost_equal(mgr.get('a', fastpath=False), values[0])\n assert_almost_equal(mgr.get('b', fastpath=False), values[1])\n assert_almost_equal(mgr.get('c', fastpath=False), values[2])\n assert_almost_equal(mgr.get('a').internal_values(), values[0])\n assert_almost_equal(mgr.get('b').internal_values(), values[1])\n assert_almost_equal(mgr.get('c').internal_values(), values[2])\n\n def test_set(self):\n mgr = create_mgr('a,b,c: int', item_shape=(3, ))\n\n mgr.set('d', np.array(['foo'] * 3))\n mgr.set('b', np.array(['bar'] * 3))\n tm.assert_numpy_array_equal(mgr.get('a').internal_values(),\n np.array([0] * 3))\n tm.assert_numpy_array_equal(mgr.get('b').internal_values(),\n np.array(['bar'] * 3, dtype=np.object_))\n tm.assert_numpy_array_equal(mgr.get('c').internal_values(),\n np.array([2] * 3))\n tm.assert_numpy_array_equal(mgr.get('d').internal_values(),\n np.array(['foo'] * 3, dtype=np.object_))\n\n def test_set_change_dtype(self, mgr):\n mgr.set('baz', np.zeros(N, dtype=bool))\n\n mgr.set('baz', np.repeat('foo', N))\n assert mgr.get('baz').dtype == np.object_\n\n mgr2 = mgr.consolidate()\n mgr2.set('baz', np.repeat('foo', N))\n assert mgr2.get('baz').dtype == np.object_\n\n mgr2.set('quux', randn(N).astype(int))\n assert mgr2.get('quux').dtype == np.int_\n\n mgr2.set('quux', randn(N))\n assert mgr2.get('quux').dtype == np.float_\n\n def test_set_change_dtype_slice(self): # GH8850\n cols = MultiIndex.from_tuples([('1st', 'a'), ('2nd', 'b'), ('3rd', 'c')\n ])\n df = DataFrame([[1.0, 2, 3], [4.0, 5, 6]], columns=cols)\n df['2nd'] = df['2nd'] * 2.0\n\n blocks = df._to_dict_of_blocks()\n assert sorted(blocks.keys()) == ['float64', 'int64']\n assert_frame_equal(blocks['float64'], DataFrame(\n [[1.0, 4.0], [4.0, 10.0]], columns=cols[:2]))\n assert_frame_equal(blocks['int64'], DataFrame(\n [[3], [6]], columns=cols[2:]))\n\n def test_copy(self, mgr):\n cp = mgr.copy(deep=False)\n for blk, cp_blk in zip(mgr.blocks, cp.blocks):\n\n # view assertion\n assert cp_blk.equals(blk)\n if isinstance(blk.values, np.ndarray):\n assert cp_blk.values.base is blk.values.base\n else:\n # DatetimeTZBlock has DatetimeIndex values\n assert cp_blk.values.values.base is blk.values.values.base\n\n cp = mgr.copy(deep=True)\n for blk, cp_blk in zip(mgr.blocks, cp.blocks):\n\n # copy assertion we either have a None for a base or in case of\n # some blocks it is an array (e.g. datetimetz), but was copied\n assert cp_blk.equals(blk)\n if not isinstance(cp_blk.values, np.ndarray):\n assert cp_blk.values.values.base is not blk.values.values.base\n else:\n assert cp_blk.values.base is None and blk.values.base is None\n\n def test_sparse(self):\n mgr = create_mgr('a: sparse-1; b: sparse-2')\n # what to test here?\n assert mgr.as_array().dtype == np.float64\n\n def test_sparse_mixed(self):\n mgr = create_mgr('a: sparse-1; b: sparse-2; c: f8')\n assert len(mgr.blocks) == 3\n assert isinstance(mgr, BlockManager)\n\n # what to test here?\n\n def test_as_array_float(self):\n mgr = create_mgr('c: f4; d: f2; e: f8')\n assert mgr.as_array().dtype == np.float64\n\n mgr = create_mgr('c: f4; d: f2')\n assert mgr.as_array().dtype == np.float32\n\n def test_as_array_int_bool(self):\n mgr = create_mgr('a: bool-1; b: bool-2')\n assert mgr.as_array().dtype == np.bool_\n\n mgr = create_mgr('a: i8-1; b: i8-2; c: i4; d: i2; e: u1')\n assert mgr.as_array().dtype == np.int64\n\n mgr = create_mgr('c: i4; d: i2; e: u1')\n assert mgr.as_array().dtype == np.int32\n\n def test_as_array_datetime(self):\n mgr = create_mgr('h: datetime-1; g: datetime-2')\n assert mgr.as_array().dtype == 'M8[ns]'\n\n def test_as_array_datetime_tz(self):\n mgr = create_mgr('h: M8[ns, US/Eastern]; g: M8[ns, CET]')\n assert mgr.get('h').dtype == 'datetime64[ns, US/Eastern]'\n assert mgr.get('g').dtype == 'datetime64[ns, CET]'\n assert mgr.as_array().dtype == 'object'\n\n def test_astype(self):\n # coerce all\n mgr = create_mgr('c: f4; d: f2; e: f8')\n for t in ['float16', 'float32', 'float64', 'int32', 'int64']:\n t = np.dtype(t)\n tmgr = mgr.astype(t)\n assert tmgr.get('c').dtype.type == t\n assert tmgr.get('d').dtype.type == t\n assert tmgr.get('e').dtype.type == t\n\n # mixed\n mgr = create_mgr('a,b: object; c: bool; d: datetime;'\n 'e: f4; f: f2; g: f8')\n for t in ['float16', 'float32', 'float64', 'int32', 'int64']:\n t = np.dtype(t)\n tmgr = mgr.astype(t, errors='ignore')\n assert tmgr.get('c').dtype.type == t\n assert tmgr.get('e').dtype.type == t\n assert tmgr.get('f').dtype.type == t\n assert tmgr.get('g').dtype.type == t\n\n assert tmgr.get('a').dtype.type == np.object_\n assert tmgr.get('b').dtype.type == np.object_\n if t != np.int64:\n assert tmgr.get('d').dtype.type == np.datetime64\n else:\n assert tmgr.get('d').dtype.type == t\n\n def test_convert(self):\n def _compare(old_mgr, new_mgr):\n \"\"\" compare the blocks, numeric compare ==, object don't \"\"\"\n old_blocks = set(old_mgr.blocks)\n new_blocks = set(new_mgr.blocks)\n assert len(old_blocks) == len(new_blocks)\n\n # compare non-numeric\n for b in old_blocks:\n found = False\n for nb in new_blocks:\n if (b.values == nb.values).all():\n found = True\n break\n assert found\n\n for b in new_blocks:\n found = False\n for ob in old_blocks:\n if (b.values == ob.values).all():\n found = True\n break\n assert found\n\n # noops\n mgr = create_mgr('f: i8; g: f8')\n new_mgr = mgr.convert()\n _compare(mgr, new_mgr)\n\n mgr = create_mgr('a, b: object; f: i8; g: f8')\n new_mgr = mgr.convert()\n _compare(mgr, new_mgr)\n\n # convert\n mgr = create_mgr('a,b,foo: object; f: i8; g: f8')\n mgr.set('a', np.array(['1'] * N, dtype=np.object_))\n mgr.set('b', np.array(['2.'] * N, dtype=np.object_))\n mgr.set('foo', np.array(['foo.'] * N, dtype=np.object_))\n new_mgr = mgr.convert(numeric=True)\n assert new_mgr.get('a').dtype == np.int64\n assert new_mgr.get('b').dtype == np.float64\n assert new_mgr.get('foo').dtype == np.object_\n assert new_mgr.get('f').dtype == np.int64\n assert new_mgr.get('g').dtype == np.float64\n\n mgr = create_mgr('a,b,foo: object; f: i4; bool: bool; dt: datetime;'\n 'i: i8; g: f8; h: f2')\n mgr.set('a', np.array(['1'] * N, dtype=np.object_))\n mgr.set('b', np.array(['2.'] * N, dtype=np.object_))\n mgr.set('foo', np.array(['foo.'] * N, dtype=np.object_))\n new_mgr = mgr.convert(numeric=True)\n assert new_mgr.get('a').dtype == np.int64\n assert new_mgr.get('b').dtype == np.float64\n assert new_mgr.get('foo').dtype == np.object_\n assert new_mgr.get('f').dtype == np.int32\n assert new_mgr.get('bool').dtype == np.bool_\n assert new_mgr.get('dt').dtype.type, np.datetime64\n assert new_mgr.get('i').dtype == np.int64\n assert new_mgr.get('g').dtype == np.float64\n assert new_mgr.get('h').dtype == np.float16\n\n def test_interleave(self):\n\n # self\n for dtype in ['f8', 'i8', 'object', 'bool', 'complex', 'M8[ns]',\n 'm8[ns]']:\n mgr = create_mgr('a: {0}'.format(dtype))\n assert mgr.as_array().dtype == dtype\n mgr = create_mgr('a: {0}; b: {0}'.format(dtype))\n assert mgr.as_array().dtype == dtype\n\n # will be converted according the actual dtype of the underlying\n mgr = create_mgr('a: category')\n assert mgr.as_array().dtype == 'i8'\n mgr = create_mgr('a: category; b: category')\n assert mgr.as_array().dtype == 'i8'\n mgr = create_mgr('a: category; b: category2')\n assert mgr.as_array().dtype == 'object'\n mgr = create_mgr('a: category2')\n assert mgr.as_array().dtype == 'object'\n mgr = create_mgr('a: category2; b: category2')\n assert mgr.as_array().dtype == 'object'\n\n # combinations\n mgr = create_mgr('a: f8')\n assert mgr.as_array().dtype == 'f8'\n mgr = create_mgr('a: f8; b: i8')\n assert mgr.as_array().dtype == 'f8'\n mgr = create_mgr('a: f4; b: i8')\n assert mgr.as_array().dtype == 'f8'\n mgr = create_mgr('a: f4; b: i8; d: object')\n assert mgr.as_array().dtype == 'object'\n mgr = create_mgr('a: bool; b: i8')\n assert mgr.as_array().dtype == 'object'\n mgr = create_mgr('a: complex')\n assert mgr.as_array().dtype == 'complex'\n mgr = create_mgr('a: f8; b: category')\n assert mgr.as_array().dtype == 'object'\n mgr = create_mgr('a: M8[ns]; b: category')\n assert mgr.as_array().dtype == 'object'\n mgr = create_mgr('a: M8[ns]; b: bool')\n assert mgr.as_array().dtype == 'object'\n mgr = create_mgr('a: M8[ns]; b: i8')\n assert mgr.as_array().dtype == 'object'\n mgr = create_mgr('a: m8[ns]; b: bool')\n assert mgr.as_array().dtype == 'object'\n mgr = create_mgr('a: m8[ns]; b: i8')\n assert mgr.as_array().dtype == 'object'\n mgr = create_mgr('a: M8[ns]; b: m8[ns]')\n assert mgr.as_array().dtype == 'object'\n\n def test_interleave_non_unique_cols(self):\n df = DataFrame([\n [pd.Timestamp('20130101'), 3.5],\n [pd.Timestamp('20130102'), 4.5]],\n columns=['x', 'x'],\n index=[1, 2])\n\n df_unique = df.copy()\n df_unique.columns = ['x', 'y']\n assert df_unique.values.shape == df.values.shape\n tm.assert_numpy_array_equal(df_unique.values[0], df.values[0])\n tm.assert_numpy_array_equal(df_unique.values[1], df.values[1])\n\n def test_consolidate(self):\n pass\n\n def test_consolidate_ordering_issues(self, mgr):\n mgr.set('f', randn(N))\n mgr.set('d', randn(N))\n mgr.set('b', randn(N))\n mgr.set('g', randn(N))\n mgr.set('h', randn(N))\n\n # we have datetime/tz blocks in mgr\n cons = mgr.consolidate()\n assert cons.nblocks == 4\n cons = mgr.consolidate().get_numeric_data()\n assert cons.nblocks == 1\n assert isinstance(cons.blocks[0].mgr_locs, BlockPlacement)\n tm.assert_numpy_array_equal(cons.blocks[0].mgr_locs.as_array,\n np.arange(len(cons.items), dtype=np.int64))\n\n def test_reindex_index(self):\n pass\n\n def test_reindex_items(self):\n # mgr is not consolidated, f8 & f8-2 blocks\n mgr = create_mgr('a: f8; b: i8; c: f8; d: i8; e: f8;'\n 'f: bool; g: f8-2')\n\n reindexed = mgr.reindex_axis(['g', 'c', 'a', 'd'], axis=0)\n assert reindexed.nblocks == 2\n tm.assert_index_equal(reindexed.items, pd.Index(['g', 'c', 'a', 'd']))\n assert_almost_equal(\n mgr.get('g', fastpath=False), reindexed.get('g', fastpath=False))\n assert_almost_equal(\n mgr.get('c', fastpath=False), reindexed.get('c', fastpath=False))\n assert_almost_equal(\n mgr.get('a', fastpath=False), reindexed.get('a', fastpath=False))\n assert_almost_equal(\n mgr.get('d', fastpath=False), reindexed.get('d', fastpath=False))\n assert_almost_equal(\n mgr.get('g').internal_values(),\n reindexed.get('g').internal_values())\n assert_almost_equal(\n mgr.get('c').internal_values(),\n reindexed.get('c').internal_values())\n assert_almost_equal(\n mgr.get('a').internal_values(),\n reindexed.get('a').internal_values())\n assert_almost_equal(\n mgr.get('d').internal_values(),\n reindexed.get('d').internal_values())\n\n def test_multiindex_xs(self):\n mgr = create_mgr('a,b,c: f8; d,e,f: i8')\n\n index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two',\n 'three']],\n labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],\n [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],\n names=['first', 'second'])\n\n mgr.set_axis(1, index)\n result = mgr.xs('bar', axis=1)\n assert result.shape == (6, 2)\n assert result.axes[1][0] == ('bar', 'one')\n assert result.axes[1][1] == ('bar', 'two')\n\n def test_get_numeric_data(self):\n mgr = create_mgr('int: int; float: float; complex: complex;'\n 'str: object; bool: bool; obj: object; dt: datetime',\n item_shape=(3, ))\n mgr.set('obj', np.array([1, 2, 3], dtype=np.object_))\n\n numeric = mgr.get_numeric_data()\n tm.assert_index_equal(numeric.items,\n pd.Index(['int', 'float', 'complex', 'bool']))\n assert_almost_equal(\n mgr.get('float', fastpath=False), numeric.get('float',\n fastpath=False))\n assert_almost_equal(\n mgr.get('float').internal_values(),\n numeric.get('float').internal_values())\n\n # Check sharing\n numeric.set('float', np.array([100., 200., 300.]))\n assert_almost_equal(\n mgr.get('float', fastpath=False), np.array([100., 200., 300.]))\n assert_almost_equal(\n mgr.get('float').internal_values(), np.array([100., 200., 300.]))\n\n numeric2 = mgr.get_numeric_data(copy=True)\n tm.assert_index_equal(numeric.items,\n pd.Index(['int', 'float', 'complex', 'bool']))\n numeric2.set('float', np.array([1000., 2000., 3000.]))\n assert_almost_equal(\n mgr.get('float', fastpath=False), np.array([100., 200., 300.]))\n assert_almost_equal(\n mgr.get('float').internal_values(), np.array([100., 200., 300.]))\n\n def test_get_bool_data(self):\n mgr = create_mgr('int: int; float: float; complex: complex;'\n 'str: object; bool: bool; obj: object; dt: datetime',\n item_shape=(3, ))\n mgr.set('obj', np.array([True, False, True], dtype=np.object_))\n\n bools = mgr.get_bool_data()\n tm.assert_index_equal(bools.items, pd.Index(['bool']))\n assert_almost_equal(mgr.get('bool', fastpath=False),\n bools.get('bool', fastpath=False))\n assert_almost_equal(\n mgr.get('bool').internal_values(),\n bools.get('bool').internal_values())\n\n bools.set('bool', np.array([True, False, True]))\n tm.assert_numpy_array_equal(mgr.get('bool', fastpath=False),\n np.array([True, False, True]))\n tm.assert_numpy_array_equal(mgr.get('bool').internal_values(),\n np.array([True, False, True]))\n\n # Check sharing\n bools2 = mgr.get_bool_data(copy=True)\n bools2.set('bool', np.array([False, True, False]))\n tm.assert_numpy_array_equal(mgr.get('bool', fastpath=False),\n np.array([True, False, True]))\n tm.assert_numpy_array_equal(mgr.get('bool').internal_values(),\n np.array([True, False, True]))\n\n def test_unicode_repr_doesnt_raise(self):\n repr(create_mgr(u('b,\\u05d0: object')))\n\n def test_missing_unicode_key(self):\n df = DataFrame({\"a\": [1]})\n try:\n df.loc[:, u(\"\\u05d0\")] # should not raise UnicodeEncodeError\n except KeyError:\n pass # this is the expected exception\n\n def test_equals(self):\n # unique items\n bm1 = create_mgr('a,b,c: i8-1; d,e,f: i8-2')\n bm2 = BlockManager(bm1.blocks[::-1], bm1.axes)\n assert bm1.equals(bm2)\n\n bm1 = create_mgr('a,a,a: i8-1; b,b,b: i8-2')\n bm2 = BlockManager(bm1.blocks[::-1], bm1.axes)\n assert bm1.equals(bm2)\n\n def test_equals_block_order_different_dtypes(self):\n # GH 9330\n\n mgr_strings = [\n \"a:i8;b:f8\", # basic case\n \"a:i8;b:f8;c:c8;d:b\", # many types\n \"a:i8;e:dt;f:td;g:string\", # more types\n \"a:i8;b:category;c:category2;d:category2\", # categories\n \"c:sparse;d:sparse_na;b:f8\", # sparse\n ]\n\n for mgr_string in mgr_strings:\n bm = create_mgr(mgr_string)\n block_perms = itertools.permutations(bm.blocks)\n for bm_perm in block_perms:\n bm_this = BlockManager(bm_perm, bm.axes)\n assert bm.equals(bm_this)\n assert bm_this.equals(bm)\n\n def test_single_mgr_ctor(self):\n mgr = create_single_mgr('f8', num_rows=5)\n assert mgr.as_array().tolist() == [0., 1., 2., 3., 4.]\n\n def test_validate_bool_args(self):\n invalid_values = [1, \"True\", [1, 2, 3], 5.0]\n bm1 = create_mgr('a,b,c: i8-1; d,e,f: i8-2')\n\n for value in invalid_values:\n with pytest.raises(ValueError):\n bm1.replace_list([1], [2], inplace=value)\n\n\nclass TestIndexing(object):\n # Nosetests-style data-driven tests.\n #\n # This test applies different indexing routines to block managers and\n # compares the outcome to the result of same operations on np.ndarray.\n #\n # NOTE: sparse (SparseBlock with fill_value != np.nan) fail a lot of tests\n # and are disabled.\n\n MANAGERS = [\n create_single_mgr('f8', N),\n create_single_mgr('i8', N),\n # create_single_mgr('sparse', N),\n create_single_mgr('sparse_na', N),\n\n # 2-dim\n create_mgr('a,b,c,d,e,f: f8', item_shape=(N,)),\n create_mgr('a,b,c,d,e,f: i8', item_shape=(N,)),\n create_mgr('a,b: f8; c,d: i8; e,f: string', item_shape=(N,)),\n create_mgr('a,b: f8; c,d: i8; e,f: f8', item_shape=(N,)),\n # create_mgr('a: sparse', item_shape=(N,)),\n create_mgr('a: sparse_na', item_shape=(N,)),\n\n # 3-dim\n create_mgr('a,b,c,d,e,f: f8', item_shape=(N, N)),\n create_mgr('a,b,c,d,e,f: i8', item_shape=(N, N)),\n create_mgr('a,b: f8; c,d: i8; e,f: string', item_shape=(N, N)),\n create_mgr('a,b: f8; c,d: i8; e,f: f8', item_shape=(N, N)),\n # create_mgr('a: sparse', item_shape=(1, N)),\n ]\n\n # MANAGERS = [MANAGERS[6]]\n\n def test_get_slice(self):\n def assert_slice_ok(mgr, axis, slobj):\n # import pudb; pudb.set_trace()\n mat = mgr.as_array()\n\n # we maybe using an ndarray to test slicing and\n # might not be the full length of the axis\n if isinstance(slobj, np.ndarray):\n ax = mgr.axes[axis]\n if len(ax) and len(slobj) and len(slobj) != len(ax):\n slobj = np.concatenate([slobj, np.zeros(\n len(ax) - len(slobj), dtype=bool)])\n sliced = mgr.get_slice(slobj, axis=axis)\n mat_slobj = (slice(None), ) * axis + (slobj, )\n tm.assert_numpy_array_equal(mat[mat_slobj], sliced.as_array(),\n check_dtype=False)\n tm.assert_index_equal(mgr.axes[axis][slobj], sliced.axes[axis])\n\n for mgr in self.MANAGERS:\n for ax in range(mgr.ndim):\n # slice\n assert_slice_ok(mgr, ax, slice(None))\n assert_slice_ok(mgr, ax, slice(3))\n assert_slice_ok(mgr, ax, slice(100))\n assert_slice_ok(mgr, ax, slice(1, 4))\n assert_slice_ok(mgr, ax, slice(3, 0, -2))\n\n # boolean mask\n assert_slice_ok(\n mgr, ax, np.array([], dtype=np.bool_))\n assert_slice_ok(\n mgr, ax,\n np.ones(mgr.shape[ax], dtype=np.bool_))\n assert_slice_ok(\n mgr, ax,\n np.zeros(mgr.shape[ax], dtype=np.bool_))\n\n if mgr.shape[ax] >= 3:\n assert_slice_ok(\n mgr, ax,\n np.arange(mgr.shape[ax]) % 3 == 0)\n assert_slice_ok(\n mgr, ax, np.array(\n [True, True, False], dtype=np.bool_))\n\n # fancy indexer\n assert_slice_ok(mgr, ax, [])\n assert_slice_ok(mgr, ax, lrange(mgr.shape[ax]))\n\n if mgr.shape[ax] >= 3:\n assert_slice_ok(mgr, ax, [0, 1, 2])\n assert_slice_ok(mgr, ax, [-1, -2, -3])\n\n def test_take(self):\n def assert_take_ok(mgr, axis, indexer):\n mat = mgr.as_array()\n taken = mgr.take(indexer, axis)\n tm.assert_numpy_array_equal(np.take(mat, indexer, axis),\n taken.as_array(), check_dtype=False)\n tm.assert_index_equal(mgr.axes[axis].take(indexer),\n taken.axes[axis])\n\n for mgr in self.MANAGERS:\n for ax in range(mgr.ndim):\n # take/fancy indexer\n assert_take_ok(mgr, ax, [])\n assert_take_ok(mgr, ax, [0, 0, 0])\n assert_take_ok(mgr, ax, lrange(mgr.shape[ax]))\n\n if mgr.shape[ax] >= 3:\n assert_take_ok(mgr, ax, [0, 1, 2])\n assert_take_ok(mgr, ax, [-1, -2, -3])\n\n def test_reindex_axis(self):\n def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value):\n mat = mgr.as_array()\n indexer = mgr.axes[axis].get_indexer_for(new_labels)\n\n reindexed = mgr.reindex_axis(new_labels, axis,\n fill_value=fill_value)\n tm.assert_numpy_array_equal(algos.take_nd(mat, indexer, axis,\n fill_value=fill_value),\n reindexed.as_array(),\n check_dtype=False)\n tm.assert_index_equal(reindexed.axes[axis], new_labels)\n\n for mgr in self.MANAGERS:\n for ax in range(mgr.ndim):\n for fill_value in (None, np.nan, 100.):\n assert_reindex_axis_is_ok(\n mgr, ax,\n pd.Index([]), fill_value)\n assert_reindex_axis_is_ok(\n mgr, ax, mgr.axes[ax],\n fill_value)\n assert_reindex_axis_is_ok(\n mgr, ax,\n mgr.axes[ax][[0, 0, 0]], fill_value)\n assert_reindex_axis_is_ok(\n mgr, ax,\n pd.Index(['foo', 'bar', 'baz']), fill_value)\n assert_reindex_axis_is_ok(\n mgr, ax,\n pd.Index(['foo', mgr.axes[ax][0], 'baz']),\n fill_value)\n\n if mgr.shape[ax] >= 3:\n assert_reindex_axis_is_ok(\n mgr, ax,\n mgr.axes[ax][:-3], fill_value)\n assert_reindex_axis_is_ok(\n mgr, ax,\n mgr.axes[ax][-3::-1], fill_value)\n assert_reindex_axis_is_ok(\n mgr, ax,\n mgr.axes[ax][[0, 1, 2, 0, 1, 2]], fill_value)\n\n def test_reindex_indexer(self):\n\n def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer,\n fill_value):\n mat = mgr.as_array()\n reindexed_mat = algos.take_nd(mat, indexer, axis,\n fill_value=fill_value)\n reindexed = mgr.reindex_indexer(new_labels, indexer, axis,\n fill_value=fill_value)\n tm.assert_numpy_array_equal(reindexed_mat,\n reindexed.as_array(),\n check_dtype=False)\n tm.assert_index_equal(reindexed.axes[axis], new_labels)\n\n for mgr in self.MANAGERS:\n for ax in range(mgr.ndim):\n for fill_value in (None, np.nan, 100.):\n assert_reindex_indexer_is_ok(\n mgr, ax,\n pd.Index([]), [], fill_value)\n assert_reindex_indexer_is_ok(\n mgr, ax,\n mgr.axes[ax], np.arange(mgr.shape[ax]), fill_value)\n assert_reindex_indexer_is_ok(\n mgr, ax,\n pd.Index(['foo'] * mgr.shape[ax]),\n np.arange(mgr.shape[ax]), fill_value)\n assert_reindex_indexer_is_ok(\n mgr, ax,\n mgr.axes[ax][::-1], np.arange(mgr.shape[ax]),\n fill_value)\n assert_reindex_indexer_is_ok(\n mgr, ax, mgr.axes[ax],\n np.arange(mgr.shape[ax])[::-1], fill_value)\n assert_reindex_indexer_is_ok(\n mgr, ax,\n pd.Index(['foo', 'bar', 'baz']),\n [0, 0, 0], fill_value)\n assert_reindex_indexer_is_ok(\n mgr, ax,\n pd.Index(['foo', 'bar', 'baz']),\n [-1, 0, -1], fill_value)\n assert_reindex_indexer_is_ok(\n mgr, ax,\n pd.Index(['foo', mgr.axes[ax][0], 'baz']),\n [-1, -1, -1], fill_value)\n\n if mgr.shape[ax] >= 3:\n assert_reindex_indexer_is_ok(\n mgr, ax,\n pd.Index(['foo', 'bar', 'baz']),\n [0, 1, 2], fill_value)\n\n # test_get_slice(slice_like, axis)\n # take(indexer, axis)\n # reindex_axis(new_labels, axis)\n # reindex_indexer(new_labels, indexer, axis)\n\n\nclass TestBlockPlacement(object):\n\n def test_slice_len(self):\n assert len(BlockPlacement(slice(0, 4))) == 4\n assert len(BlockPlacement(slice(0, 4, 2))) == 2\n assert len(BlockPlacement(slice(0, 3, 2))) == 2\n\n assert len(BlockPlacement(slice(0, 1, 2))) == 1\n assert len(BlockPlacement(slice(1, 0, -1))) == 1\n\n def test_zero_step_raises(self):\n with pytest.raises(ValueError):\n BlockPlacement(slice(1, 1, 0))\n with pytest.raises(ValueError):\n BlockPlacement(slice(1, 2, 0))\n\n def test_unbounded_slice_raises(self):\n def assert_unbounded_slice_error(slc):\n tm.assert_raises_regex(ValueError, \"unbounded slice\",\n lambda: BlockPlacement(slc))\n\n assert_unbounded_slice_error(slice(None, None))\n assert_unbounded_slice_error(slice(10, None))\n assert_unbounded_slice_error(slice(None, None, -1))\n assert_unbounded_slice_error(slice(None, 10, -1))\n\n # These are \"unbounded\" because negative index will change depending on\n # container shape.\n assert_unbounded_slice_error(slice(-1, None))\n assert_unbounded_slice_error(slice(None, -1))\n assert_unbounded_slice_error(slice(-1, -1))\n assert_unbounded_slice_error(slice(-1, None, -1))\n assert_unbounded_slice_error(slice(None, -1, -1))\n assert_unbounded_slice_error(slice(-1, -1, -1))\n\n def test_not_slice_like_slices(self):\n def assert_not_slice_like(slc):\n assert not BlockPlacement(slc).is_slice_like\n\n assert_not_slice_like(slice(0, 0))\n assert_not_slice_like(slice(100, 0))\n\n assert_not_slice_like(slice(100, 100, -1))\n assert_not_slice_like(slice(0, 100, -1))\n\n assert not BlockPlacement(slice(0, 0)).is_slice_like\n assert not BlockPlacement(slice(100, 100)).is_slice_like\n\n def test_array_to_slice_conversion(self):\n def assert_as_slice_equals(arr, slc):\n assert BlockPlacement(arr).as_slice == slc\n\n assert_as_slice_equals([0], slice(0, 1, 1))\n assert_as_slice_equals([100], slice(100, 101, 1))\n\n assert_as_slice_equals([0, 1, 2], slice(0, 3, 1))\n assert_as_slice_equals([0, 5, 10], slice(0, 15, 5))\n assert_as_slice_equals([0, 100], slice(0, 200, 100))\n\n assert_as_slice_equals([2, 1], slice(2, 0, -1))\n\n if not PY361:\n assert_as_slice_equals([2, 1, 0], slice(2, None, -1))\n assert_as_slice_equals([100, 0], slice(100, None, -100))\n\n def test_not_slice_like_arrays(self):\n def assert_not_slice_like(arr):\n assert not BlockPlacement(arr).is_slice_like\n\n assert_not_slice_like([])\n assert_not_slice_like([-1])\n assert_not_slice_like([-1, -2, -3])\n assert_not_slice_like([-10])\n assert_not_slice_like([-1])\n assert_not_slice_like([-1, 0, 1, 2])\n assert_not_slice_like([-2, 0, 2, 4])\n assert_not_slice_like([1, 0, -1])\n assert_not_slice_like([1, 1, 1])\n\n def test_slice_iter(self):\n assert list(BlockPlacement(slice(0, 3))) == [0, 1, 2]\n assert list(BlockPlacement(slice(0, 0))) == []\n assert list(BlockPlacement(slice(3, 0))) == []\n\n if not PY361:\n assert list(BlockPlacement(slice(3, 0, -1))) == [3, 2, 1]\n assert list(BlockPlacement(slice(3, None, -1))) == [3, 2, 1, 0]\n\n def test_slice_to_array_conversion(self):\n def assert_as_array_equals(slc, asarray):\n tm.assert_numpy_array_equal(\n BlockPlacement(slc).as_array,\n np.asarray(asarray, dtype=np.int64))\n\n assert_as_array_equals(slice(0, 3), [0, 1, 2])\n assert_as_array_equals(slice(0, 0), [])\n assert_as_array_equals(slice(3, 0), [])\n\n assert_as_array_equals(slice(3, 0, -1), [3, 2, 1])\n\n if not PY361:\n assert_as_array_equals(slice(3, None, -1), [3, 2, 1, 0])\n assert_as_array_equals(slice(31, None, -10), [31, 21, 11, 1])\n\n def test_blockplacement_add(self):\n bpl = BlockPlacement(slice(0, 5))\n assert bpl.add(1).as_slice == slice(1, 6, 1)\n assert bpl.add(np.arange(5)).as_slice == slice(0, 10, 2)\n assert list(bpl.add(np.arange(5, 0, -1))) == [5, 5, 5, 5, 5]\n\n def test_blockplacement_add_int(self):\n def assert_add_equals(val, inc, result):\n assert list(BlockPlacement(val).add(inc)) == result\n\n assert_add_equals(slice(0, 0), 0, [])\n assert_add_equals(slice(1, 4), 0, [1, 2, 3])\n assert_add_equals(slice(3, 0, -1), 0, [3, 2, 1])\n assert_add_equals([1, 2, 4], 0, [1, 2, 4])\n\n assert_add_equals(slice(0, 0), 10, [])\n assert_add_equals(slice(1, 4), 10, [11, 12, 13])\n assert_add_equals(slice(3, 0, -1), 10, [13, 12, 11])\n assert_add_equals([1, 2, 4], 10, [11, 12, 14])\n\n assert_add_equals(slice(0, 0), -1, [])\n assert_add_equals(slice(1, 4), -1, [0, 1, 2])\n assert_add_equals([1, 2, 4], -1, [0, 1, 3])\n\n with pytest.raises(ValueError):\n BlockPlacement(slice(1, 4)).add(-10)\n with pytest.raises(ValueError):\n BlockPlacement([1, 2, 4]).add(-10)\n\n if not PY361:\n assert_add_equals(slice(3, 0, -1), -1, [2, 1, 0])\n assert_add_equals(slice(2, None, -1), 0, [2, 1, 0])\n assert_add_equals(slice(2, None, -1), 10, [12, 11, 10])\n\n with pytest.raises(ValueError):\n BlockPlacement(slice(2, None, -1)).add(-1)\n\n\nclass DummyElement(object):\n def __init__(self, value, dtype):\n self.value = value\n self.dtype = np.dtype(dtype)\n\n def __array__(self):\n return np.array(self.value, dtype=self.dtype)\n\n def __str__(self):\n return \"DummyElement({}, {})\".format(self.value, self.dtype)\n\n def __repr__(self):\n return str(self)\n\n def astype(self, dtype, copy=False):\n self.dtype = dtype\n return self\n\n def view(self, dtype):\n return type(self)(self.value.view(dtype), dtype)\n\n def any(self, axis=None):\n return bool(self.value)\n\n\nclass TestCanHoldElement(object):\n @pytest.mark.parametrize('value, dtype', [\n (1, 'i8'),\n (1.0, 'f8'),\n (2**63, 'f8'),\n (1j, 'complex128'),\n (2**63, 'complex128'),\n (True, 'bool'),\n (np.timedelta64(20, 'ns'), '<m8[ns]'),\n (np.datetime64(20, 'ns'), '<M8[ns]'),\n ])\n @pytest.mark.parametrize('op', [\n operator.add,\n operator.sub,\n operator.mul,\n operator.truediv,\n operator.mod,\n operator.pow,\n ], ids=lambda x: x.__name__)\n def test_binop_other(self, op, value, dtype):\n skip = {(operator.add, 'bool'),\n (operator.sub, 'bool'),\n (operator.mul, 'bool'),\n (operator.truediv, 'bool'),\n (operator.mod, 'i8'),\n (operator.mod, 'complex128'),\n (operator.mod, '<M8[ns]'),\n (operator.mod, '<m8[ns]'),\n (operator.pow, 'bool')}\n if (op, dtype) in skip:\n pytest.skip(\"Invalid combination {},{}\".format(op, dtype))\n e = DummyElement(value, dtype)\n s = pd.DataFrame({\"A\": [e.value, e.value]}, dtype=e.dtype)\n result = op(s, e).dtypes\n expected = op(s, value).dtypes\n assert_series_equal(result, expected)\n\n\[email protected]('typestr, holder', [\n ('category', Categorical),\n ('M8[ns]', DatetimeIndex),\n ('M8[ns, US/Central]', DatetimeIndex),\n ('m8[ns]', TimedeltaIndex),\n ('sparse', SparseArray),\n])\ndef test_holder(typestr, holder):\n blk = create_block(typestr, [1])\n assert blk._holder is holder\n\n\ndef test_deprecated_fastpath():\n # GH#19265\n values = np.random.rand(3, 3)\n with tm.assert_produces_warning(DeprecationWarning,\n check_stacklevel=False):\n make_block(values, placement=np.arange(3), fastpath=True)\n\n\ndef test_validate_ndim():\n values = np.array([1.0, 2.0])\n placement = slice(2)\n msg = r\"Wrong number of dimensions. values.ndim != ndim \\[1 != 2\\]\"\n\n with tm.assert_raises_regex(ValueError, msg):\n make_block(values, placement, ndim=2)\n"
]
| [
[
"pandas.Series",
"numpy.take",
"numpy.asarray",
"pandas.util.testing.assert_produces_warning",
"pandas.MultiIndex.from_tuples",
"pandas.DataFrame",
"numpy.dtype",
"pandas.util.testing.assert_index_equal",
"pandas.core.internals.BlockPlacement",
"pandas.util.testing.round_trip_pickle",
"pandas.compat.OrderedDict",
"pandas.util.testing.assert_numpy_array_equal",
"numpy.arange",
"pandas.Index",
"pandas.util.testing.assert_series_equal",
"pandas.core.internals.BlockManager",
"numpy.repeat",
"numpy.zeros",
"pandas.core.algorithms.take_nd",
"pandas.compat.u",
"pandas.MultiIndex",
"pandas.core.internals.make_block",
"pandas.Categorical",
"numpy.timedelta64",
"numpy.random.rand",
"pandas.util.testing.randn",
"numpy.array",
"pandas.SparseArray",
"pandas.util.testing.assert_raises_regex",
"numpy.datetime64",
"numpy.ones",
"pandas.compat.zip",
"pandas.Timestamp",
"pandas.compat.lrange"
]
]
|
jdngibson/CanFlood | [
"37f738be6944ea6b68dfcffeee6b6ac6ff7eb8a0"
]
| [
"canflood/model/sofda/scripts.py"
]
| [
"'''\nCreated on Jun 11, 2018\n\n@author: cef\n'''\n#===============================================================================\n# HIERARCHY and RUN LOOPS --------------------------------------------------------------\n#===============================================================================\n'''\nsee discussion in hp_sim.py\nKEY RUN LOOPS\n*Session.run_all(): 10,000x controls a single scenario\n *Simulation.run_timeline(): 50x controls one simulation of a scenario (a set of stochastic parameters)\n *Tstep.run_dt(): 4x: runs all the user specified models (and their submodels)\n *Udev.run() 2x : runs all the Actions specified on the timeline\n Action.run()\n Action.run() 5x: we allow chaining of actions\n Dynamic_par.run() 5x\n Dynamic_par.run() 5x\n \n *Fdmg.run() 10x: bundles the flood damage tasks\n Flood.run() 1000x calcluate the damage for each house\n House.run() 4x get damage at this depth from each Dfunc\n Dfunc.run() 1x main damage call. get the damage from the wsl\n\n*5 special top-level objects PARENT/POINTERS \n'''\n\n\n\n\n#===============================================================================\n# IMPORT STANDARD MODS -------------------------------------------------------\n#===============================================================================\nimport os, time, logging, gc, weakref, datetime\n\n\nimport pandas as pd\nimport numpy as np\n\n\nfrom collections import OrderedDict as od\nfrom weakref import WeakValueDictionary as wdict\nfrom hlpr.exceptions import Error\n#from weakref import proxy\n\n#===============================================================================\n# IMPORT CUSTOM MODS ---------------------------------------------------------\n#===============================================================================\n#import hp.plot #need to call this first so thet matplotlib backend configures correctly\nimport model.sofda.hp.basic as basic\n\n#from .. import model.sofda.hp.pd as hp_pd\nimport model.sofda.hp.pd as hp_pd \nimport model.sofda.hp.oop as hp_oop\n\nimport model.sofda.hp.sim as hp_sim\nimport model.sofda.hp.dynp as hp_dynp\n\nimport model.sofda.hp.dyno as hp_dyno\nimport model.sofda.hp.sel as hp_sel\nimport model.sofda.hp.outs as hp_outs\nimport model.sofda.hp.dict as hp_dict #wasnt added before for some reason...\nimport model.sofda.hp.data as hp_data\n\nfrom model.sofda.hp.pd import view\n\n#===============================================================================\n# import in project mods\n#===============================================================================\nimport model.sofda.fdmg.scripts_fdmg as fscripts\nimport model.sofda.udev.scripts as udev_scripts\n\n#===============================================================================\n# mod_logger\n#===============================================================================\nmod_logger = logging.getLogger(__name__)\nmod_logger.debug('initilized')\n\n\n#===============================================================================\n# module parameter file setup\n#===============================================================================\n'reserved for parameter files of this module hidden from the user'\n_mod_dir = os.path.dirname(__file__)\n\n\n\"\"\"this is super gross\"\"\"\nclass Session( #main session handler. runs many simulations for stochastic modelling\n \n hp_sim.Sim_session,\n hp_dyno.Dyno_controller,\n hp_oop.Session_o, \n hp_sel.Sel_controller, \n hp_dynp.Dynp_session,\n hp_outs.Out_controller,\n hp_data.Data_wrapper,\n #hp.plot.Plot_o,\n hp_oop.Child): \n \n #===========================================================================\n # program parametser\n #===========================================================================\n mod_n_l = ['udev', 'fdmg'] #list of model names recognized by the simulation\n \n color = 'blue'\n \n bfh_min = 1.0 #minimum acceptable basement finish height\n \n #===========================================================================\n # calculated pars\n #===========================================================================\n #session style flags\n wdfeats_f = False #flag whether dfeats are used in teh session\n\n 'not sure about this'\n dyn_haza_f = False #flag to indicate whether the hazard is dynamic (changes through time)\n dyn_vuln_f = False #dynamic vulnerability (i.e. udev model has some actions)\n load_dfeats_first_f = True\n \n bdmg_dx = None \n #===========================================================================\n # user pars\n #===========================================================================\n \n transp_f = False\n \n #output flags\n \"\"\"not sure where all the other ones are...\"\"\"\n write_fly_bdmg_dx = False\n \n \n\n def __init__(self, dynp_hnd_file = None, *vars, **kwargs):\n logger = mod_logger.getChild('Session') #have to use this as our own logger hasnt loaded yet\n logger.debug('start __init__')\n \n #=======================================================================\n # set defaults\n #=======================================================================\n if dynp_hnd_file is None:\n dynp_hnd_file = os.path.join(os.path.dirname(__file__), '_pars', 'dynp_handles_20190512.xls')\n \n assert os.path.exists(dynp_hnd_file)\n \n self.dynp_hnd_file = dynp_hnd_file\n \n #initilzie the first baseclass\n super(Session, self).__init__(*vars, **kwargs) \n \n\n \n #=======================================================================\n # debug inits \n #=======================================================================\n #resource profiler\n if self._prof_mem>0:\n import model.sofda.hp.prof_mem as hp_profMem\n self.resc_prof = hp_profMem.Resource_profiler(logger = self.logger,\n _wtf = self.session._write_data,\n name = self.tag,\n session = self)\n \n self.prof(state='0.%s'%self.session.state) #make the first write to the frame\n \n #=======================================================================\n # special loader funcs\n #=======================================================================\n logger.debug('set_flags () \\n')\n self.set_flags()\n \n #fly results\n if self.write_fly_f:\n #basic results \n self.fly_res_fpath = os.path.join(self.outpath, '%s fly_res.csv'%self.tag)\n \n #dx results\n if self.output_dx_f:\n self.fly_resx_fpath = os.path.join(self.outpath, '%s fly_res_dx.csv'%self.tag)\n \n #bdmg results\n if self.write_fly_bdmg_dx:\n self.fly_bdmg_fpath = os.path.join(self.outpath, '%s bdmg_fly_res.csv'%self.tag)\n self.bdmg_dx = pd.DataFrame() #set the empty container\n \n\n self.logger.info('SOFDA simulation initialized as \\'%s\\' with %i runs (_dbgmstr=%s) \\n \\n'\n %(self.name, self.run_cnt, self._dbgmstr))\n \n\n \n return\n \n def set_flags(self): #set the calculation session style flags\n \"\"\"need to load all of these up front so the other models can initilize properly\"\"\"\n logger = self.logger.getChild('set_flags')\n\n if self._parlo_f:\n logger.warning('_parlo_f = TRUE!!!')\n else:\n logger.info('_parlo_f = FALSE')\n\n if not self.glbl_stoch_f:\n logger.warning('Dynamic Pars disabled!!!!')\n #time.sleep(3)\n #=======================================================================\n # dynamic hazard and udev\n #=======================================================================\n self.dyn_vuln_f = True\n self.dyn_haza_f = True\n \n \"\"\"this doesn't really work\n if self.glbl_stoch_f:\n self.dyn_vuln_f = True\n self.dyn_haza_f = True\n \n todo: come up wtih better exclusions\n\n df = self.session.pars_df_d['timeline']\n \n for ind, run_seq_d in df.loc[:,'run_seq_d'].iteritems():\n d = OrderedDict(eval(run_seq_d))\n \n for modn, run_seq_l in d.iteritems():\n #drop normal runs\n try:\n run_seq_l.remove('*run')\n except:\n logger.debug('no \\'*run\\' in run_seq')\n \n if len(run_seq_l) > 0: #if there are any left we have a dynamic run\n if modn == 'Udev': self.dyn_vuln_f = True\n elif modn == 'Fdmg': self.dyn_haza_f = True \n \n run_seq_l.remove('xx')\n if np.any(df.loc[:,'Fdmg.wsl_delta'] !=0):\n self.dyn_haza_f = True #flag to indicate whether the hazard is dynamic (changes through time)\n \n if np.any(df.loc[:,'Fdmg.fprob_mult'] !=1):\n self.dyn_haza_f = True #flag to indicate whether the hazard is dynamic (changes through time)\"\"\"\n\n \n logger.info('dyn_haza_f = %s and dyn_vuln_f = %s'%(self.dyn_haza_f, self.dyn_vuln_f))\n\n\n #=======================================================================\n # damage functions\n #=======================================================================\n df = self.session.pars_df_d['dfunc']\n boolidx = df.loc[:,'dfunc_type'] == 'dfeats'\n if boolidx.sum() > 0: \n self.wdfeats_f = True\n\n\n else:\n self.wdfeats_f = False\n \n logger.info('wdfeats_f = %s'%self.wdfeats_f)\n\n \n #=======================================================================\n # dynamic vulnerability\n #=======================================================================\n \"\"\"\n #dynamic vulnerability (i.e. udev model has some actions)\n if self.glbl_stoch_f: \n df = self.session.pars_df_d['timeline']\n boolcol = df['01udev'] == 'no'\n if boolcol.sum() < len(df): #timeline has some udev runs loaded onto it\n self.dyn_vuln_f = True\n \n logger.info('dyn_vuln_f = %s'%self.dyn_vuln_f)\"\"\"\n \n #=======================================================================\n # determine all the outpars\n #=======================================================================\n self.build_outpars_d()\n\n \n return\n \n def load_models(self):\n logger = self.logger.getChild('load_models')\n \"\"\"\n #=======================================================================\n # CALLS\n #=======================================================================\n have main.py call this\n \n #=======================================================================\n # DEPENDENCIES\n #=======================================================================\n order matters.\n timeline\n Fdmg\n Udev\n \n Udev\n Selectors\n Dynp\n \n \n setup_outs_library (out_lib_od)\n needs all the children to be loaded\n \n self._parlo_f\n \n \"\"\"\n #=======================================================================\n # fdmg model\n #=======================================================================\n logger.info('loading damage submodel')\n logger.debug('\\n ')\n \n self.fdmg = self.spawn_child(childname = 'fdmg', kid_class = fscripts.Fdmg)\n self.prof(state='load.fdmg')\n self.model = self.fdmg #this avoids alot of error flags during inheritance\n \n #=======================================================================\n # udev model\n #=======================================================================\n logger.debug('\\n \\n')\n logger.info('loading udev submodel')\n logger.debug('\\n \\n')\n \n self.udev = self.spawn_child(childname = 'udev', kid_class = udev_scripts.Udev)\n self.prof(state='load.udev')\n self.fdmg.udev = self.udev\n \n self.models_d = {'Fdmg':self.fdmg,'Udev':self.udev}\n #self.udev.load_data()\n \"\"\"\n seperated this out so that the buildinv inventory special attributes are loaded\n before the Selelectors run for the first time.\n \n self.inherit_parent_ans\n \n \"\"\"\n \n\n\n #=======================================================================\n # #selectors\n #=======================================================================\n logger.debug('\\n \\n')\n logger.info('loading object selectors')\n logger.debug(\"\\n \\n\")\n \n self.raise_selectors(self.pars_df_d['selectors'])\n self.prof(state='load.sels')\n \n #=======================================================================\n # #dynamic parameters\n #=======================================================================\n logger.debug('\\n \\n')\n logger.info('loading dynps')\n logger.debug('\\n \\n')\n \n self.raise_dynps(self.pars_df_d['dynp'])\n self.prof(state='load.dynps')\n \n #=======================================================================\n # udev Actions (steal Selectors and Dynps)\n #=======================================================================\n logger.debug('\\n \\n')\n logger.info('raising Udev')\n logger.debug('\\n \\n')\n 'seperated this out so the dynamic pars are accessible'\n \n self.udev.raise_children()\n self.prof(state='load.Actions')\n \n #=======================================================================\n # #Actions\n #=======================================================================\n logger.info('loading agent Actions')\n logger.debug('\\n \\n')\n self.acts_d = self.raise_children_df(self.session.pars_df_d['actions'], \n kid_class = Action)\n \n #=======================================================================\n # timeline\n #=======================================================================\n logger.debug('\\n \\n')\n logger.info('loading timeline')\n logger.debug('\\n \\n')\n \n self.load_timeline()\n self.prof(state='load.Tsteps')\n\n \n #=======================================================================\n # load the simulations\n #=======================================================================\n logger.debug('\\n \\n')\n logger.info('loading sims for sensi_f = %s'%self.session.sensi_f)\n logger.debug(\"\\n \\n\")\n \n if self.session.sensi_f: self.load_sensi_sims()\n else: \n self.load_sims() #spawn all the simulation children\n self.prof(state='load.Sims')\n \n \n #=======================================================================\n # Outputrs \n #=======================================================================\n logger.debug('\\n \\n')\n logger.info('loading Outputrs')\n logger.debug(\"\\n \\n\")\n \n self.raise_outputrs()\n self.prof(state='load.Outputrs')\n \n if self.session.sensi_f: self.check_sensi_delta_outrs()\n \n #=======================================================================\n # Dynp handles\n #=======================================================================\n logger.debug('\\n')\n \"\"\" movd to Dynp_controller.__init__\n 'not actually children'\n self.load_dynp_hnd_file(_dynp_hnd_file)\"\"\"\n \"\"\" having each object do this itself\n self.init_dynos() #secondary initilization on all dyno kids\"\"\"\n \n \n #self.check_family_refs(max_cnt = 3)\n \n logger.debug('finished with %i children (gc = %i) \\n'%(len(self.kids_d), gc.collect()))\n \n return\n \n def load_timeline(self):\n logger = self.logger.getChild('load_timeline')\n #=======================================================================\n # #get the list of mod heads on the timeline with values entered\n #=======================================================================\n df = self.pars_df_d['timeline'].sort_values('rank')\n \n logger.debug('on timeline with \\'%s\\''%str(df.shape))\n \n 'the Tstep needs this..'\n df_clean = df.dropna(axis='columns',how='all')\n #search_ser = pd.Series(df_clean.columns)\n \n l = []\n for e in df_clean.columns.tolist():\n if basic.isnum(e[:2]):\n l.append(e)\n \n l.sort()\n \n self.tl_mod_head_n_l = l\n\n #=======================================================================\n # spawn the timeline\n #=======================================================================\n logger.debug('raise_children_df() \\n')\n self.timeline_d = self.raise_children_df(df, kid_class = Tstep, \n dup_sibs_f=False,\n container = od)\n \n #self.timeline_d = OrderedDict(sorted(d.items(), key=lambda t: t[0])) #sort it\n \n #=======================================================================\n # secondary\n #=======================================================================\n self.year0 = list(self.timeline_d.values())[0].year #take the year from the first time step object\n \n logger.debug('finished with year0 = %i \\n'%self.year0)\n \n def load_sims(self): #load sims\n logger = self.logger.getChild('load_sims')\n \n df = self.get_sim_metadf(self.run_cnt) #build a dummy frame with the sim meta data\n \n self.sims_meta_df = df\n #=======================================================================\n # raise all thse\n #=======================================================================\n self.sims_od = self.raise_children_df(df, kid_class = Simulation, \n dup_sibs_f=True,\n container = wdict)\n \n logger.debug('loaded %i Simulations \\n'%len(self.sims_od))\n \n return\n\n def load_sensi_sims(self, sims_per_var = None): #load simulations for sensitivity analysis\n #=======================================================================\n # defaults\n #=======================================================================\n logger = self.logger.getChild('load_sensi_sims')\n \n #if sims_per_var is None: sims_per_var = self.sims_per_var\n \n df = self.get_sensi_metadf(wtf=False)\n \n self.run_cnt = min(len(df), self.run_cnt)\n \n \"\"\"NO! We always want to allow partial run cnt\n \n if self._parlo_f: \n self.run_cnt = min(len(df), self.run_cnt)\n logger.warning('trimming sensitivity simulations for testing')\n else: self.run_cnt = len(df)\"\"\"\n \n logger.info('set run_cnt to %i'%self.run_cnt)\n \n \"\"\"\n we cannot precoimpile the simulations with set dynps \n cant do a complete copy of the dynp_d\n \n self.sims_od.keys()\n \n hp_pd.v(df)\n \"\"\"\n #=======================================================================\n # load the sims\n #=======================================================================\n self.load_sims()\n \n #=======================================================================\n # attach the sensi_ser\n #=======================================================================\n sim_l = self.sims_meta_df['name'].values.tolist()\n for sim_key in sim_l:\n\n sim = self.sims_od[sim_key]\n sim_ind = sim.ind\n \n \n sensi_ser = df.loc[sim_ind, :]\n \n sim.sensi_ser = sensi_ser.copy()\n \n logger.debug('finished and attached sensi_ser to %i simulations'%len(self.sims_od))\n \n return\n \n def run_session(self, wtf=None): #run each simulation\n \"\"\"\n #=======================================================================\n # CALLS\n #=======================================================================\n main.py\n \"\"\"\n logger = self.logger.getChild('run_session')\n \n if wtf is None: wtf = self.session._write_data\n \n #=======================================================================\n # setup the run\n #=======================================================================\n logger.debug('\\n \\n \\n ')\n \n logger.debug('\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n logger.info('setting up run')\n \"\"\"\n Unlike other sim objects, the Session needs to setup its own run\n not sure how to differentiate between this and the .__init__ commands\n \"\"\"\n \"\"\"happens during selector __init__?\n self.run_selectors()\"\"\"\n # set the initial sample values\n self.run_dynps() #first call. set all 'Session' values\n\n # setup the results frame\n df = pd.DataFrame()\n dxcol = pd.DataFrame() #multi dimensional outputs\n \n \n logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n logger.info('running %i simulations'%len(self.sims_od))\n #=======================================================================\n # loop through each simulation and run\n #=======================================================================\n \n first = True\n ldf_cnt = None #for testing\n \n 'workaround for ordered dict and weakref'\n sim_l = self.sims_meta_df['name'].values.tolist()\n for sim_key in sim_l:\n self.state = 'run.%s'%sim_key\n \n self.prof(state = '0.%s.start'%self.state) #profiling\n 'state needs to start with zero so the profiler runs for _prof_mem = 0'\n #===================================================================\n # setup vals\n #===================================================================\n start = time.time()\n sim = self.sims_od[sim_key]\n sim_ind = sim.ind\n self.hs_stamp = (sim.upd_sim_lvl, sim.ind)\n \n #===================================================================\n # runs\n #===================================================================\n logger.info('\\n (%i/%i)*************************************************************** \\n \\n'%(sim_ind+1, len(sim_l)))\n logger.debug('run_selectors() \\n')\n sim.run_selectors() #update all the selectors\n \n #sensitivity\n if self.session.sensi_f:\n logger.debug('sensi_f=TRUE. raise_dynps_sensi() \\n') \n sim.raise_dynps_sensi() #re calibrate the dynps for this sensitivity analysis\n \n logger.debug('run_dynps() \\n')\n sim.run_dynps() #second call. set all dynp 'Simulation' values\n \n logger.debug('run_timeline() \\n')\n sim.run_sim()\n #===================================================================\n # #get/write the results\n #===================================================================\n self.session.state = 'getres.%s'%sim_key\n logger.debug('get_results() \\n')\n res_ser, res_dx = sim.get_res_sim(wtf = self.write_sim_res_f) #get teh stats results summary\n \n df = df.append(res_ser, ignore_index = False) #add these\n \n if self.output_dx_f:\n dxcol = dxcol.append(res_dx)\n \n #fly writers\n if self.write_fly_f: \n hp_pd.write_fly_df(self.fly_res_fpath,res_ser, lindex=sim_key,\n first = first, tag = self.tag, \n db_f = self.db_f, logger=self.logger) #write results on the fly\n \n if self.output_dx_f:\n hp_pd.write_fly_df(self.fly_resx_fpath,res_dx, sim_key,\n first = first, tag = self.tag,\n db_f = self.db_f, logger=self.logger) #write results on the fly\n \n \n if not self.bdmg_dx is None:\n self.write_bdmg_dx(sim.name, first)\n\n\n \n \n #===================================================================\n # #clean up\n #===================================================================\n if not len(sim_l) -1 == sim_ind: #skip the last sim\n self.session.state = 'clean.%s'%sim_key\n logger.debug('reset_all() \\n')\n self.reset_all()\n \n #===================================================================\n # clean out previous\n #===================================================================\n if first:\n first = False\n else:\n self.kill_obj(sim)\n del self.sims_od[sim_key]\n del sim\n logger.debug('killed sim \\'%s\\''%sim_key)\n #gc.collect()\n\n #===============================================================\n # testing\n #===============================================================\n if self.db_f:\n if 'Dmg_feat' in self.family_d:\n df_cnt = len(self.family_d['Dmg_feat'])\n else:\n df_cnt = 0\n \n if not ldf_cnt is None:\n if not df_cnt == df_cnt:\n raise IOError\n \n ldf_cnt = df_cnt #set for next time\n \n\n \n stop = time.time()\n logger.info('finished in %.2f mins sim %s'%((stop - start)/60.0, sim_key))\n self.prof(state = sim_key + '.end') #profiling\n\n #=======================================================================\n # wrap up\n #=======================================================================\n self.state = 'run.wrap'\n self.prof(state='0.run_session.post')\n \n logger.info('finished with res_df %s \\n'%str(df.shape))\n \n #attach to the session\n self.res_df = df.dropna(axis='columns', how='all')\n self.res_dxcol = dxcol.dropna(axis='columns', how='all')\n self.data = df.dropna(axis='columns', how='all')\n \n return\n \n def write_results(self):\n #logger = self.logger.getChild('write_results')\n \n if self._write_data and self.write_fancy_outs: \n #session.write_summary_df()\n self.write_fancy_res()\n \n self.prof(state='write_fancy_res')\n \n if self.session._write_figs: \n self.plot_hists() #plot histograms as directed by the 'outputs' - ses_plot tab\n self.prof(state='plot_hists')\n \n def write_fancy_res(self):\n logger = self.logger.getChild('write_results_fancy')\n logger.debug('executing')\n res_d = od() #start empty\n \n #=======================================================================\n # inputs tab\n #=======================================================================\n df_raw = self.pars_df_d['gen']\n df1 = df_raw.drop('rank',axis=1)\n \n df2 = pd.DataFrame(columns = df1.columns)\n\n #add extra details\n for attn in ['outpath', 'pars_filename', 'time']:\n desc = None\n if attn == 'pars_filename':\n _, v = os.path.split(self.parspath)\n elif attn == 'time':\n v = datetime.datetime.now()\n desc = 'session close time'\n else:\n v = getattr(self, attn)\n \n ser = pd.Series([attn,desc,v], index = df2.columns)\n \n df2 = df2.append(ser, ignore_index = True) #add this tot he end\n \n #add the rest to the end\n df2 = df2.append(df1, ignore_index = True)\n\n \n res_d['ins'] = df2\n \n \n #=======================================================================\n # summaruy rseults\n #=======================================================================\n res_d['res_summary'] = self.res_df #store thsi into the dict\n logger.debug(\" on res_df %s\"%str(self.res_df.shape))\n \n \"\"\"\n hp_pd.v(self.res_df)\n hp_pd.v(df2)\n hp_pd.v(self.pars_df_d['gen'].drop('rank',axis=1))\n \"\"\"\n \n #=======================================================================\n # output meta data\n #=======================================================================\n #make the blank frame\n outmeta_df = pd.DataFrame(index = ['sim_stats_exe', 'sel_n', 'desc'], columns = self.res_df.columns)\n \n for k, v in self.outs_od.items():\n boolcol = outmeta_df.columns == v.codename\n \n if boolcol.sum() == 0 : continue \n \n ar = np.array([[v.sim_stats_exe, v.sel_n, v.desc]]).T\n \n outmeta_df.iloc[:,boolcol] = ar.tolist()\n \n res_d['outmeta'] = outmeta_df\n \n\n #=======================================================================\n # sensi results\n #=======================================================================\n if self.sensi_f: \n 'I dont like passing the d here...'\n res_d = self.get_sensi_results(res_d)\n \n #=======================================================================\n # mdex results\n #=======================================================================\n if self.output_dx_f:\n res_d['summary_dxcol'] = self.res_dxcol\n\n #=======================================================================\n # #write to excel\n #=======================================================================\n filetail = '%s fancy_res'%(self.tag)\n\n filepath = os.path.join(self.outpath, filetail)\n hp_pd.write_dfset_excel(res_d, filepath, engine='xlsxwriter', logger=self.logger)\n \n logger.debug('finished \\n')\n \n return\n \n def write_bdmg_dx(self, tag, first):\n logger = self.logger.getChild('write_bdmg_dx')\n\n \"\"\"using the builtin to_csv with an append method\n this adds the df as a new set of rows each time\"\"\"\n #get data (and add the sim to the index)\n dxcol = pd.concat([self.bdmg_dx], keys=[tag], names=['sim'])\n \n \"\"\"\n view(dxcol)\n \"\"\"\n \n dxcol.to_csv(self.fly_bdmg_fpath ,\n header = first, #writ eht eheaders the ifrst time through\n mode = 'a', #appending\n )\n \n logger.debug('appendded bdmg_dx %s to file \\n %s'%\n (str(dxcol.shape), self.fly_bdmg_fpath))\n \n #clear it\n self.bdmg_dx = pd.DataFrame()\n \n return\n \n \n\n def get_sensi_results(self, res_d):\n \n logger = self.logger.getChild('get_sensi_results')\n \n df2 = self.sensi_df.copy()\n \n #=======================================================================\n # #reforat the headers to codenae\n #=======================================================================\n l = []\n for old_col in df2.columns:\n if old_col == 'focus': l.append(old_col)\n else:\n dynpo = self.dynp_d[old_col]\n l.append(dynpo.codename)\n \n df2.columns = l\n \n df3 = df2.reindex(sorted(df2.columns), axis=1)\n \n #=======================================================================\n # #move focus to front\n #=======================================================================\n df3 = hp_pd.move_col_to_front(df3, 'focus', logger = logger)\n \n res_d['sensi_mat'] = df3\n \n #=======================================================================\n # #do the merging\n #=======================================================================\n res_df = res_d['res_summary'].copy()\n res_df = res_df.reset_index(drop=True)\n \n merge_df = pd.merge(res_df, df3, \n on = None,\n how = 'left',\n left_index = True,\n right_index = True, \n left_on = None,\n right_on = None,\n sort = False,\n indicator = False)\n \n if not hp_pd.isdf(merge_df):\n raise IOError\n \n #=======================================================================\n # #get the comparison columns\n #=======================================================================\n \n l = self.delta_compare_col_nl\n logger.debug('generating %i comparison columns: %s'%(len(l), l))\n merge_df1 = merge_df.copy()\n \n for cmpre_coln in l:\n merge_df1 = self.get_sensi_base_delta(merge_df1, cmpre_coln)\n \n merge_df2 = hp_pd.move_col_to_front(merge_df1, 'focus', logger = logger)\n\n res_d['sensi_merge'] = merge_df2\n \n \"\"\"\n res_d.keys()\n hp_pd.view_web_df(res_d['res_summary'])\n \"\"\"\n \n return res_d\n \n def get_sensi_base_delta(self, df, cmpre_coln):\n \n logger = self.logger.getChild('get_sensi_base_delta')\n #=======================================================================\n # get baseline delta\n #=======================================================================\n \n boolcol = df.columns.str.contains(cmpre_coln) #get the delta column\n boolidx = df.loc[:,'focus'] == 'baseline' #get the baseline row\n \n if not boolcol.sum() == 1:\n if boolcol.sum() == 0:\n logger.warning('no \\'%s\\' Outputr loaded'%cmpre_coln)\n return\n else:raise IOError\n if not boolidx.sum() == 1:raise IOError\n \n \n base_ead = float(df.loc[boolidx, boolcol].values) #what we are comparing to\n \n #=======================================================================\n # add a delta column\n #=======================================================================\n\n #get \n new_coln = '%s_dlt'%cmpre_coln\n new_ar = df.loc[:, boolcol].values - base_ead\n \n #set these\n df.loc[:,new_coln] = new_ar #sim minus baseline\n df1 = hp_pd.move_col_to_front(df, new_coln, logger=logger)\n logger.debug('for base_ead = %.2f made delta column\\'%s\\''%(base_ead, new_coln))\n #=======================================================================\n # add a relative change column \n #=======================================================================\n \"\"\"\n for nm in df1.columns:\n print nm\n type(df1.loc[:,new_coln2])\n \"\"\"\n new_coln2 = '%s_rdlt'%cmpre_coln\n new_ar2 = new_ar/float(base_ead)\n \n df1.loc[:,new_coln2] = new_ar2 #delta over baseline\n df2 = hp_pd.move_col_to_front(df1, new_coln2, logger=logger)\n\n \n \n return df2\n \n def wrap_up(self): #shut down and write\n if self.session._write_data:\n \n if self._prof_mem>0:\n self.resc_prof.write()\n \n \nclass Simulation( #a single simulation within the session\n hp_sim.Sim_simulation, \n hp_sel.Sel_controller, \n hp_dynp.Dynp_controller,\n hp_outs.Out_controller,\n hp_oop.Child):\n \n 'todo: move this to hp_sim and make generic'\n\n #===========================================================================\n # object handling overrides\n #===========================================================================\n #load_data_f = False \n last_tstep = None\n db_f = True\n \n def __init__(self, *vars, **kwargs):\n logger = mod_logger.getChild('Simulation')\n logger.debug('start _init_')\n \n self.inherit_parent_ans = set()\n \n super(Simulation, self).__init__(*vars, **kwargs) #initilzie teh baseclass\n \n self.ind = int(self.ind)\n #=======================================================================\n # commons\n #=======================================================================\n 'each simulation should have these in commmon'\n if self.sib_cnt == 0:\n self.timeline_d = self.parent.timeline_d\n \n self.udev = self.session.udev\n self.fdmg = self.session.fdmg \n \n\n \n self.logger.debug('finish _init_ as %s\\n'%self.name)\n \n return\n \n def run_sim(self): #run the full timeline\n \"\"\"\n #=======================================================================\n # FUNCTION\n #=======================================================================\n loops through each timestep\n \n \"\"\"\n #=======================================================================\n # defaults\n #=======================================================================\n logger = self.logger.getChild('run_sim')\n \n logger.info('with %i Tsteps: %s'%(len(self.timeline_d), (list(self.timeline_d.keys()))))\n\n #=======================================================================\n # loop and run\n #=======================================================================\n cnt = 0\n for time_str, tstep_o in self.timeline_d.items():\n #===================================================================\n # setup\n #===================================================================\n logger.info('\\n %s (%i of %i) dtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdtdt'%\n (time_str, cnt+1, len(self.timeline_d)))\n\n logger.debug('\\n')\n self.session.hs_stamp = (tstep_o.upd_sim_lvl, cnt) #update the hierarchy/sequence stamp\n self.session.state = 'run.%s.%s'%(self.name, tstep_o.name)\n #===================================================================\n # execute\n #===================================================================\n self.init_tstep(tstep_o) #initilize teh time step\n tstep_o.run_dt() #run the timestep\n #===================================================================\n # wrap\n #===================================================================\n self.last_tstep = tstep_o.time\n \n self.session.prof(state = '%s.run_sim.%s.end'%(self.name, time_str)) #profiling\n \n logger.debug('finished for %s \\n'%time_str)\n cnt +=1\n \n logger.debug('ended on %s \\n'%self.last_tstep)\n \n def init_tstep(self, tstep_o): #initilize teh tstep for this simulation\n logger = self.logger.getChild('init_tstep')\n \n logger.debug('on \\'%s\\''%tstep_o.name)\n self.time = tstep_o.time\n self.tstep_o = tstep_o\n \n tstep_o.inherit(self)\n 'this should trigger Tstep.inherit()'\n \n if self.db_f:\n if tstep_o.parent is None:\n raise IOError\n \"\"\"\n op = tstep_o.parent\n op.name\n \"\"\"\n return\n \n def get_res_sim(self, wtf=None): #calculat ethe summary of outputs from the timeline\n #=======================================================================\n # defaults\n #======================================================================= \n logger = self.logger.getChild('get_res_sim')\n if wtf is None: wtf = self.session._write_data\n \n xtra_d = od() #for collection extra outputs\n \n logger.debug('start')\n \n #outs_od = self.session.outs_od\n \n \"\"\"no.. running these only on timesteps\n self.run_outputrs() #final run on the outputrs\"\"\"\n \n #=======================================================================\n # single line results\n #=======================================================================\n logger.debug('\\n')\n res_ser = self.get_outputs_summary()\n \n xtra_d['res_ser'] = res_ser\n \n #=======================================================================\n # multi line results\n #=======================================================================\n if self.session.output_dx_f:\n res_dx = self.get_outputs_summary_dx()\n xtra_d['res_dx']=res_dx\n \n else: res_dx = None\n\n #write this to file\n if wtf: \n logger.debug('write_full_outputs ()\\n')\n self.write_full_outputs(xtra_d = xtra_d)\n \n logger.debug('finished with res_ser: \\n %s'%res_ser)\n \n return res_ser, res_dx\n \nclass Tstep( #a timestep from teh simulation timeline\n hp_oop.Parent,\n hp_sim.Sim_o, \n hp_sel.Sel_controller, \n hp_outs.Out_controller, \n hp_dynp.Dynp_controller,\n hp_oop.Child): \n \n \n #===========================================================================\n # submodel handling\n #===========================================================================\n mod_runs_od = None #dictionary of model call sequences\n #===========================================================================\n # #pars from timeline tab\n #===========================================================================\n date = None\n\n run_seq_d = None #dictionary of model:run_seq_l\n \n \n #===========================================================================\n # simulation states\n #===========================================================================\n #re_reset_anl_Tstep = ['']\n 'mod_runs_od: shouldnt change between simulations'\n \n sim_lvl = 2\n \n #===========================================================================\n # Object Handling\n #===========================================================================\n \"\"\"\n raise_kids_f = False #tell the generic raise kids to also raise the grand kids here\n load_data_flag = False\"\"\"\n \n def __init__(self, *args, **kwargs):\n logger = mod_logger.getChild('Tstep')\n logger.debug('start _init_')\n super(Tstep, self).__init__(*args, **kwargs) #initilzie teh baseclass\n \"\"\"\n NOTE on Simulation __init__\n \n everything here will only happen once\n (When teh session initilizes the timeline)\n commands in the self.inherit() will run for each Simulation\n \n self.name\n self.time\n datetime.datetime(2000)\n \"\"\"\n #=======================================================================\n # attach custom atts\n #=======================================================================\n 'using a string name and a sepearate column for date seems to keep things nice'\n self.dt_cnt = int(self.rank)\n self.year = int(self.date.strftime('%Y'))\n #hp_oop.clean_l_atts(self, logger = self.logger)\n #=======================================================================\n # cleaning/formatting\n #=======================================================================\n self.tstep_o = self\n \n #=======================================================================\n # commons\n #=======================================================================\n if self.sib_cnt == 0: \n self.timeline_df = self.session.pars_df_d['timeline']\n \n\n #=======================================================================\n # custom loader funcs\n #=======================================================================\n if not self.run_seq_d is None:\n try:\n d = od(eval(self.run_seq_d))\n except:\n if not isinstance(eval(self.run_seq_d), tuple):\n logger.error('failed to evaluate a tuple from \\'%s\\''%self.run_seq_d)\n\n raise IOError\n \n self.run_seq_d = d\n\n else:\n self.run_seq_d = dict() #empty dic\n\n \n #=======================================================================\n # post checks\n #=======================================================================\n if self.db_f: self.check_tstep()\n\n \n self.logger.debug(\"_init_ finished \\n\")\n \n return\n \n def check_tstep(self):\n if not isinstance(self.date, pd.Timestamp): \n raise IOError\n \n if self.parent is None:\n raise IOError\n \n #check the run sequence\n if not isinstance(self.run_seq_d, dict):\n raise IOError\n \n for k, v in self.run_seq_d.items():\n \n if not k in list(self.session.models_d.keys()):\n raise IOError\n \n if not isinstance(v, list):\n raise IOError\n \n def inherit(self, parent): #inherit custom attributes from the parent\n\n \"\"\"\n #=======================================================================\n # calls\n #=======================================================================\n this is called during session _init_\n \n as well as during Simulation.init_tstep\n \n \"\"\"\n #=======================================================================\n # defaults\n #=======================================================================\n pcn = parent.__class__.__name__\n \n #=======================================================================\n # common inherits\n #=======================================================================\n #shortcut for single time step simulations\n if len(self.session.timeline_d) == 1:\n self.outpath = parent.outpath \n else:\n self.outpath = os.path.join(parent.outpath, self.name)\n \n #=======================================================================\n # parent based\n #=======================================================================\n if pcn == 'Session':\n if not parent.state == 'init': raise IOError\n\n logger = self.logger.getChild('inherit')\n \n #=======================================================================\n # inheritance based on whether were actually simulating\n #=======================================================================\n elif pcn == 'Simulation':\n \"\"\"note this is triggerd multiple times for the same Tstep object\n as Tstep objects are recycled between simulations\"\"\"\n self.inherit_logr(parent)\n logger = self.logger.getChild('inherit')\n logger.debug('assigning inheritance from sim \\'%s\\''%parent.name)\n \n self.simu_o = parent\n \n \"\"\"id rather keep the tstep out of the family \n self.inherit_family(parent)\"\"\"\n \n self.session.tstep_o = self #tell the session what the tstep is\n self.session.year = self.year\n \n \n else: raise IOError\n \n logger.debug('finished from %s'%parent.name)\n \n if self.db_f:\n if self.parent is None:\n raise IOError\n \n return\n \n def run_dt(self): #loop through the model dictionary and run each one\n\n #=======================================================================\n # defaults\n #=======================================================================\n start = time.time()\n logger = self.logger.getChild('run_dt')\n \n #=======================================================================\n # pre runs\n #=======================================================================\n self.session.update_all(loc = self.name) #run udpates on everything in the que\n \n self.run_selectors() #update all the selectors with update_ste = 'Tstep'\n \n self.run_dynps() #apply all dynp with sample_step = 'Tstep'\n \n d = self.run_seq_d\n \n logger.debug('running %i models: %s'%(len(d), list(d.keys())))\n #=======================================================================\n # execute each assigned model\n #=======================================================================\n cnt = 1\n for model_name, run_seq_l in d.items(): #loop through \n \"\"\"this mcode_l has the flag, and the model in the first 2 entries\n Should only do one run for a string of commands\n \"\"\"\n #===================================================================\n # set parameters for this run\n #===================================================================\n logger.debug(\"%02d executing \\'%s,%s\\'\"%(cnt, model_name, run_seq_l))\n modloc = '%s.%s.%s'%(self.simu_o.name, self.name, model_name)\n self.session.state = '%s.run'%modloc\n \n #get model\n model = self.session.models_d[model_name]\n \n #state assignments\n self.session.model = model\n model.assign_handler(self) \n self.session.hs_stamp = (model.upd_sim_lvl, cnt) #update the hierarchy/sequence stamp\n\n #===================================================================\n # pre run commands\n #===================================================================\n model.run_selectors()\n 'shouldnt we execute the dynps as well for the model level?'\n \n #===================================================================\n # exceute run sequence\n #===================================================================\n seq_cnt = 1\n for seq in run_seq_l:\n logger.debug('%02d executing \\'%s.%s\\''%(seq_cnt, model_name, seq))\n seqloc = '%s.%s'%(modloc, seq)\n self.session.hs_stamp = (model.upd_sim_lvl +1, seq_cnt) #update the hierarchy/sequence stamp\n self.session.state = '%s.run'%seqloc\n #===============================================================\n # pre run commands\n #===============================================================\n self.session.prof(state = seqloc) #profiling\n \n self.session.update_all(loc = seqloc) #update all the objects\n \n #===============================================================\n # run by key\n #===============================================================\n #special \n if seq == '*run':\n model.run()\n \n #model commands\n elif seq.startswith('*model'):\n raise IOError #should strip this and execute it as a method\n eval(seq)\n \n #action run\n else:\n acto = self.session.acts_d[seq] #retrieve the action object\n acto.model = model #set the model\n acto.run() #run the action\n acto.model = None\n \n seq_cnt += 1\n logger.debug('finished sequence \\'%s\\' \\n'%seq)\n \n #===================================================================\n # get results\n #===================================================================\n self.session.state = 'run.%s.post'%modloc\n self.session.prof() #profiling\n model.get_results()\n\n #===================================================================\n # wrap up this loop piece\n #===================================================================\n self.session.state = 'run.%s.wrap'%modloc\n model.wrap_up()\n self.session.prof() #profiling\n cnt +=1\n \n #=======================================================================\n # wrap up\n #=======================================================================\\\n self.session.state = 'run.%s.%s.wrap'%(self.simu_o.name, self.name)\n self.get_res_tstep()\n \n stop = time.time()\n logger.info('finished in %.4f secs'%(stop - start))\n\n return\n \n\n def get_res_tstep(self):\n \n #=======================================================================\n # final updating\n #=======================================================================\n \"\"\"\n usually, this doesnt do anything as the last model run is fdmg\n but we want to make sure everything is up to date before outputting\n \"\"\"\n self.session.update_all(loc = '%s_wrap'%(self.name)) #update all the objects\n \n 'only care about these right before outputting'\n self.session.post_update()\n \n self.session.run_outputrs() #tell all the object writers to run\n \n return\n\nclass Action( #collection of modifications of the objects in the Fdmg\n hp_sel.Sel_usr_wrap,\n hp_sim.Sim_o,\n hp_oop.Parent,\n hp_oop.Child): \n '''\n #===========================================================================\n # DEPENDENCIES\n #===========================================================================\n Dynps\n \n inherited actions (make sure the order of hte 'actions' tab is correct\n \n '''\n #===========================================================================\n # program pars\n #===========================================================================\n \n # object handling overrides\n \"\"\"\n load_data_f = False\n raise_kids_f = True\n raise_in_spawn_f = False #load all the children before moving on to the next sibling\"\"\"\n 'this has to be false so we can chain actions'\n \n #===========================================================================\n # user pars\n #===========================================================================\n dynp_n_l = None #list of modifications for this\n act_n_l = None #list of chained actions\n\n mark_f = False #adds a flag to this object \n #===========================================================================\n # calculated pars\n #===========================================================================\n acts_d = None #nested actionss\n obj_cnt = 0 #number of objects directly influenced by teh action\n \n upd_all_d = None #container of all objects this Action has been applied to. useful for get_results()\n \n upd_sim_lvl = 3\n \n dynp_wd = None \n \n def __init__(self, *args, **kwargs):\n logger = mod_logger.getChild('Action')\n logger.debug('start _init_')\n super(Action, self).__init__(*args, **kwargs) #initilzie teh baseclass\n #=======================================================================\n #unique setup\n #=======================================================================\n 'todo: convert these to sets'\n self.dynp_n_l = basic.excel_str_to_py(self.dynp_n_l, logger = self.logger)\n \n self.act_n_l = basic.excel_str_to_py(self.act_n_l, logger = self.logger)\n \n logger.debug('setup_action() \\n')\n self.setup_action()\n \n \"\"\"handled by outputrs\n self.reset_d.update({'obj_cnt': 0})\"\"\"\n \n #=======================================================================\n # checks\n #=======================================================================\n if self.db_f: self.check_action()\n\n \n logger.debug('_init_ finished \\n')\n \n def check_action(self):\n \"\"\"allowing now\n if self.model is None:\n raise IOError\"\"\"\n \n logger = self.logger.getChild('check_action')\n \n if not self.act_n_l is None:\n if not isinstance(self.act_n_l, list):\n raise IOError\n \n if self.pclass_n is None:\n logger.error('no pclass_n provided')\n raise IOError\n \n \n def setup_action(self, #special child raising per the mod_n_l\n container=wdict): \n logger = self.logger.getChild('setup_action')\n \"\"\"\n self.name\n \n \"\"\"\n\n #=======================================================================\n # get the dynamic pars by trype\n #=======================================================================\n if not self.dynp_n_l is None:\n logger.debug('setting up dynps with \\'%s\\''%self.dynp_n_l)\n \n #===================================================================\n # precheck\n #===================================================================\n if self.db_f:\n #check we have all the reuqested dynps\n boolar = np.invert(np.isin(\n np.array(self.dynp_n_l), \n np.array(list(self.session.dynp_d.keys()))\n ))\n if np.any(boolar):\n raise IOError('Action %s cant find %i requested dynps: %s'\n %(self.name, boolar.sum(), np.array(self.dynp_n_l)[boolar]))\n \n #===================================================================\n # get the set of requested dynps by name\n #===================================================================\n try:\n #extract with some fancy searching\n self.dynp_wd = hp_dict.subset(self.session.dynp_d, #container to pull values from\n self.dynp_n_l,#list of keys to search from from the dynp_d\n container = container, logger = logger)\n except:\n raise IOError(\"dict subset failed for some reason\")\n else:\n logger.debug('no \\'dynp_n_l\\'. setting \\'dynp_wd\\' as an empty container')\n \n \n if self.dynp_wd is None: \n self.dynp_wd = container()\n \n\n 'todo: check if this dynp has been loaded '\n #=======================================================================\n # get teh child actions by type\n #=======================================================================\n \n if not self.act_n_l is None:\n logger.debug('setting up child actions with \\'%s\\''%self.act_n_l)\n #global pulls\n class_d = self.session.family_d['Action']\n self.acts_d = od()\n \n #loop and collect\n for actn in self.act_n_l:\n \n #upll this action object from teh class_d\n acto = hp_dict.value_by_ksearch(actn, class_d, logger = logger)\n \n if acto is None: \n logger.error('got None for \\'%s\\'. check the order??'%actn)\n raise IOError\n \n self.acts_d[actn] = acto\n \n \n logger.debug('finished with %i sub actions collected: %s'%(len(self.acts_d), list(self.acts_d.keys())))\n \n \n \n \n \"\"\"\n boolar = basic.bool_list_in_list(self.model.kids_d.keys(), self.act_n_l)\n \n if not np.all(boolar):\n logger.error('some chained actions have not been loaded yet. make sure the order is correct')\n raise IOError\n \n self.acts_d = hp_dict.subset(self.model.kids_d, self.act_n_l, \n container = container, logger = logger)\"\"\"\n 'have to use kids_d here because the model.acts_d hasnt finished yet'\n\n #=======================================================================\n # get the selector\n #=======================================================================\n if not self.sel_n is None:\n \"\"\"why?\n logger.error(\"must provide a selector (even for Actions with a single dynp)\")\n raise IOError #todo.. just pull the selector from the single dynp\"\"\"\n \n self.sel_o = weakref.proxy(self.session.sels_d[self.sel_n]) #attach your selector\n else:\n self.sel_o = None\n #=======================================================================\n # wrap up\n #=======================================================================\n logger.debug('finished\\n')\n \n def run(self, actk_d = None , container=wdict): #execute the chained Actions and all my dynp\n 'models and submodels must have the simple run name'\n \n \"\"\"\n #===========================================================================\n # CALLS\n #===========================================================================\n\n \n \"\"\"\n logger = self.logger.getChild('run(%s)'%self.get_id())\n #=======================================================================\n # setup\n #=======================================================================\n\n upd_all_s = set() #set of gids \n self.run_cnt += 1\n \n #=======================================================================\n # prechecks\n #=======================================================================\n if self.db_f:\n pass\n \n #=======================================================================\n # defaults\n #=======================================================================\n if actk_d is None: k = 'empty'\n else: k = list(actk_d.keys())\n\n logger.debug('executing with\\n actk_d: %s \\n acts_d: %s \\n dynp_wd.keys(): %s'%\n (k, self.acts_d, list(self.dynp_wd.keys())))\n \n #=======================================================================\n # build set\n #=======================================================================\n \n actk_d1 = self.make_pick(big_d = actk_d)\n 'I guess Actions make fresh picks each time?'\n #shortcut\n if len(actk_d1) == 0: \n logger.debug(\"no objects passed by selector. doing nothing\")\n return container()\n \n \n #=======================================================================\n # run the chained actions\n #=======================================================================\n if not self.acts_d is None:\n sub_act_cnt = len(self.acts_d)\n \n #run the nested actions agaisnt your set\n 'workaround for wdict order limitation' \n for act_n in self.act_n_l:\n act_o = self.acts_d[act_n] #retrieve the action\n\n logger.debug('on my pick (%i) running nested act_n: \\'%s\\' and their dynp_wd: %s \\n '\n %(len(actk_d1), act_n, list(act_o.dynp_wd.keys())))\n \n upd_s = act_o.run(actk_d = actk_d1) #use my subset when you run\n \n #warp up\n upd_all_s.update(upd_s)\n logger.debug('finished nested act_n \\'%s\\' with %i updates'%(act_n, len(upd_s)))\n\n else: sub_act_cnt = 0\n \n #=======================================================================\n # loop through each mod/dynp associated with this action and set the new value\n #=======================================================================\n if len(self.dynp_wd) > 0:\n logger.debug('running my dynps: %s'%list(self.dynp_wd.keys()))\n \n 'workaround for wdict order limitation' \n for dynp_n in self.dynp_n_l:\n dynp_o = self.dynp_wd[dynp_n] #get this dynp\n\n logger.debug('running dynp \\'%s\\' with \\'%s\\' on my set (%i) of \\'%s\\' \\n'\n %(dynp_n, dynp_o.value_assign_str, len(actk_d1), list(actk_d1.values())[0].__class__.__name__))\n #===================================================================\n # set the values on the intersection of the two\n #=================================================================== \n upd_s = dynp_o.run_dynp(big_d = actk_d1)\n \n upd_all_s.update(upd_s) #add these items to the list\n\n #=======================================================================\n # wrap up\n #======================================================================= \n if self.mark_f: self.mark_set(actk_d1)\n \n self.get_results(upd_all_s)\n \n logger.info('changed %i objects with %i sub-Actions and %i prime-dynps: %s'\n %(len(upd_all_s), sub_act_cnt, len(list(self.dynp_wd.keys())),list(self.dynp_wd.keys())))\n \n \n return upd_all_s\n \n def mark_set(self, d): #add an entry to the parents childmeta_df marking that this Action has been applied\n logger = self.logger.getChild('mark_set')\n #=======================================================================\n # setup\n #=======================================================================\n obj1 = list(d.values())[0] #just take the first\n df = obj1.parent.childmeta_df.copy()\n \n logger.debug('on %i objects with childmeta_df %s'%(len(d), str(df.shape)))\n \n #find the attributes column\n if not self.name in df.columns.values.tolist():\n df[self.name] = np.nan #add an empty column\n logger.debug('added a column \\'%s\\' to the \\'%s\\'s childmeta_df'%(self.name, obj1.parent.name))\n \n boolcol = df.columns == self.name\n \n new_val = self.model.tstep_o.name\n #=======================================================================\n # update the df\n #=======================================================================\n for obj_n, obj in d.items():\n \n boolidx = df.loc[:,'name'] == obj.name #find yourself\n \n df.loc[boolidx, boolcol] = new_val#set the timestamp\n\n logger.debug('marked object \\'%s\\'s childmeta_df entry with \\'%s\\''%(obj_n, new_val))\n \n #=======================================================================\n # update the parents frame\n #=======================================================================\n obj1.parent.childmeta_df = df\n logger.debug('finished marking %i objects and udpating the parents frame'%len(d))\n \n def get_results(self, upd_all_s):\n\n s = self.session.outpars_d[self.__class__.__name__]\n \n if 'obj_cnt' in s:\n 'needs to be cumulative as some actions are chained'\n self.obj_cnt = self.obj_cnt =+ len(upd_all_s)\n \n return\n \n\n\n \n \n\n \n \n\n \n"
]
| [
[
"pandas.concat",
"pandas.merge",
"pandas.Series",
"pandas.DataFrame",
"numpy.any",
"numpy.array"
]
]
|
PRECISE/ROSLab | [
"2a6a295b71d4c73bc5c6ae2ec0330274afa31d0d"
]
| [
"resources/mechanics_lib/api/graphs/transforms.py"
]
| [
"import numpy as np\nfrom api.symbolic import LinearExpr\n\n\ndef MirrorX():\n return np.diag([-1, 1, 1, 1])\n\ndef MirrorY():\n return np.diag([1, -1, 1, 1])\n\ndef Scale(scale):\n return np.diag([scale, scale, scale, 1])\n\ndef RotateX(angle):\n r = np.array([[1, 0, 0, 0],\n [0, np.cos(angle), -np.sin(angle), 0],\n [0, np.sin(angle), np.cos(angle), 0],\n [0, 0, 0, 1]]) \n return r\n\ndef RotateZ(angle):\n r = np.array([[np.cos(angle), -np.sin(angle), 0, 0],\n [np.sin(angle), np.cos(angle), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]]) \n return r\n\ndef symbolic_atan2(y, x):\n if isinstance(y, LinearExpr) or isinstance(x, LinearExpr):\n return LinearExpr.atan2(y, x)\n return np.arctan2(y, x)\n\ndef MoveToOrigin(pt):\n return Translate([-pt[0], -pt[1], 0])\n\ndef RotateOntoX(pt, pt2=(0,0)):\n return RotateZ(-symbolic_atan2(pt[1] - pt2[1], pt[0] - pt2[0]))\n\ndef MoveOriginTo(pt):\n return Translate([pt[0], pt[1], 0])\n\ndef RotateXTo(pt, pt2=(0,0)):\n return RotateZ(symbolic_atan2(pt[1] - pt2[1], pt[0] - pt2[0]))\n\ndef Translate(origin):\n r = np.array([[1, 0, 0, origin[0]],\n [0, 1, 0, origin[1]],\n [0, 0, 1, origin[2]],\n [0, 0, 0, 1]]) \n return r\n"
]
| [
[
"numpy.diag",
"numpy.cos",
"numpy.sin",
"numpy.arctan2",
"numpy.array"
]
]
|
finkbeiner-lab/cellpose | [
"ec859343f61988806093d65d0d6172f22596e9e7"
]
| [
"cellpose/io.py"
]
| [
"import os, datetime, gc, warnings, glob\nfrom natsort import natsorted\nimport numpy as np\nimport cv2\nimport tifffile\nimport logging, pathlib, sys\nfrom pathlib import Path\n\nfrom . import utils, plot, transforms\n\ntry:\n from PyQt5 import QtGui, QtCore, Qt, QtWidgets\n GUI = True\nexcept:\n GUI = False\n\ntry:\n import matplotlib.pyplot as plt\n MATPLOTLIB = True\nexcept:\n MATPLOTLIB = False\n \ntry:\n from google.cloud import storage\n SERVER_UPLOAD = True\nexcept:\n SERVER_UPLOAD = False\n\nio_logger = logging.getLogger(__name__)\nio_logger.setLevel(logging.DEBUG)\n\ndef logger_setup():\n cp_dir = pathlib.Path.home().joinpath('.cellpose')\n cp_dir.mkdir(exist_ok=True)\n log_file = cp_dir.joinpath('run.log')\n try:\n log_file.unlink()\n except:\n print('creating new log file')\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s [%(levelname)s] %(message)s\",\n handlers=[\n logging.FileHandler(log_file),\n logging.StreamHandler(sys.stdout)\n ]\n )\n logger = logging.getLogger(__name__)\n logger.info(f'WRITING LOG OUTPUT TO {log_file}')\n #logger.handlers[1].stream = sys.stdout\n\n return logger, log_file\n\n# helper function to check for a path; if it doesn't exist, make it \ndef check_dir(path):\n if not os.path.isdir(path):\n os.mkdir(path)\n\ndef outlines_to_text(base, outlines):\n with open(base + '_cp_outlines.txt', 'w') as f:\n for o in outlines:\n xy = list(o.flatten())\n xy_str = ','.join(map(str, xy))\n f.write(xy_str)\n f.write('\\n')\n\ndef imread(filename):\n ext = os.path.splitext(filename)[-1]\n if ext== '.tif' or ext=='tiff':\n img = tifffile.imread(filename)\n return img\n else:\n try:\n img = cv2.imread(filename, -1)#cv2.LOAD_IMAGE_ANYDEPTH)\n if img.ndim > 2:\n img = img[..., [2,1,0]]\n return img\n except Exception as e:\n io_logger.critical('ERROR: could not read file, %s'%e)\n return None\n\ndef imsave(filename, arr):\n ext = os.path.splitext(filename)[-1]\n if ext== '.tif' or ext=='tiff':\n tifffile.imsave(filename, arr)\n else:\n if len(arr.shape)>2:\n arr = cv2.cvtColor(arr, cv2.COLOR_BGR2RGB) \n cv2.imwrite(filename, arr)\n\ndef get_image_files(folder, mask_filter, imf=None, look_one_level_down=False):\n \"\"\" find all images in a folder and if look_one_level_down all subfolders \"\"\"\n mask_filters = ['_cp_masks', '_cp_output', '_flows', mask_filter]\n image_names = []\n if imf is None:\n imf = ''\n \n folders = []\n if look_one_level_down:\n folders = natsorted(glob.glob(os.path.join(folder, \"*/\")))\n folders.append(folder)\n\n for folder in folders:\n image_names.extend(glob.glob(folder + '/*%s.png'%imf))\n image_names.extend(glob.glob(folder + '/*%s.jpg'%imf))\n image_names.extend(glob.glob(folder + '/*%s.jpeg'%imf))\n image_names.extend(glob.glob(folder + '/*%s.tif'%imf))\n image_names.extend(glob.glob(folder + '/*%s.tiff'%imf))\n image_names = natsorted(image_names)\n imn = []\n for im in image_names:\n imfile = os.path.splitext(im)[0]\n igood = all([(len(imfile) > len(mask_filter) and imfile[-len(mask_filter):] != mask_filter) or len(imfile) < len(mask_filter) \n for mask_filter in mask_filters])\n if len(imf)>0:\n igood &= imfile[-len(imf):]==imf\n if igood:\n imn.append(im)\n image_names = imn\n\n if len(image_names)==0:\n raise ValueError('ERROR: no images in --dir folder')\n \n return image_names\n \ndef get_label_files(image_names, mask_filter, imf=None):\n nimg = len(image_names)\n label_names0 = [os.path.splitext(image_names[n])[0] for n in range(nimg)]\n\n if imf is not None and len(imf) > 0:\n label_names = [label_names0[n][:-len(imf)] for n in range(nimg)]\n else:\n label_names = label_names0\n \n # check for flows\n if os.path.exists(label_names0[0] + '_flows.tif'):\n flow_names = [label_names0[n] + '_flows.tif' for n in range(nimg)]\n else:\n flow_names = [label_names[n] + '_flows.tif' for n in range(nimg)]\n if not all([os.path.exists(flow) for flow in flow_names]):\n print('Not all flows are present. Run flow generation again.')\n flow_names = None\n \n # check for masks\n if os.path.exists(label_names[0] + mask_filter + '.tif'):\n label_names = [label_names[n] + mask_filter + '.tif' for n in range(nimg)]\n elif os.path.exists(label_names[0] + mask_filter + '.png'):\n label_names = [label_names[n] + mask_filter + '.png' for n in range(nimg)]\n else:\n raise ValueError('labels not provided with correct --mask_filter')\n if not all([os.path.exists(label) for label in label_names]):\n raise ValueError('labels not provided for all images in train and/or test set')\n\n return label_names, flow_names\n\n\ndef load_train_test_data(train_dir, test_dir=None, image_filter=None, mask_filter='_masks', unet=False, look_one_level_down=True):\n image_names = get_image_files(train_dir, mask_filter, image_filter, look_one_level_down)\n nimg = len(image_names)\n images = [imread(image_names[n]) for n in range(nimg)]\n\n # training data\n label_names, flow_names = get_label_files(image_names, mask_filter, imf=image_filter)\n nimg = len(image_names)\n labels = [imread(label_names[n]) for n in range(nimg)]\n if flow_names is not None and not unet:\n for n in range(nimg):\n flows = imread(flow_names[n])\n if flows.shape[0]<4:\n labels[n] = np.concatenate((labels[n][np.newaxis,:,:], flows), axis=0) \n else:\n labels[n] = flows\n \n # testing data\n test_images, test_labels, image_names_test = None, None, None\n if test_dir is not None:\n image_names_test = get_image_files(test_dir, mask_filter, image_filter, look_one_level_down)\n label_names_test, flow_names_test = get_label_files(image_names_test, mask_filter, imf=image_filter)\n nimg = len(image_names_test)\n test_images = [imread(image_names_test[n]) for n in range(nimg)]\n test_labels = [imread(label_names_test[n]) for n in range(nimg)]\n if flow_names_test is not None and not unet:\n for n in range(nimg):\n flows = imread(flow_names_test[n])\n if flows.shape[0]<4:\n test_labels[n] = np.concatenate((test_labels[n][np.newaxis,:,:], flows), axis=0) \n else:\n test_labels[n] = flows\n return images, labels, image_names, test_images, test_labels, image_names_test\n\n\n\ndef masks_flows_to_seg(images, masks, flows, diams, file_names, channels=None):\n \"\"\" save output of model eval to be loaded in GUI \n\n can be list output (run on multiple images) or single output (run on single image)\n\n saved to file_names[k]+'_seg.npy'\n \n Parameters\n -------------\n\n images: (list of) 2D or 3D arrays\n images input into cellpose\n\n masks: (list of) 2D arrays, int\n masks output from Cellpose.eval, where 0=NO masks; 1,2,...=mask labels\n\n flows: (list of) list of ND arrays \n flows output from Cellpose.eval\n\n diams: float array\n diameters used to run Cellpose\n\n file_names: (list of) str\n names of files of images\n\n channels: list of int (optional, default None)\n channels used to run Cellpose \n \n \"\"\"\n \n if channels is None:\n channels = [0,0]\n \n if isinstance(masks, list):\n if not isinstance(diams, (list, np.ndarray)):\n diams = diams * np.ones(len(masks), np.float32)\n for k, [image, mask, flow, diam, file_name] in enumerate(zip(images, masks, flows, diams, file_names)):\n channels_img = channels\n if channels_img is not None and len(channels) > 2:\n channels_img = channels[k]\n masks_flows_to_seg(image, mask, flow, diam, file_name, channels_img)\n return\n\n if len(channels)==1:\n channels = channels[0]\n\n flowi = []\n if flows[0].ndim==3:\n Ly, Lx = masks.shape[-2:]\n flowi.append(cv2.resize(flows[0], (Lx, Ly), interpolation=cv2.INTER_NEAREST)[np.newaxis,...])\n else:\n flowi.append(flows[0])\n if flows[0].ndim==3:\n cellprob = (np.clip(transforms.normalize99(flows[2]),0,1) * 255).astype(np.uint8)\n cellprob = cv2.resize(cellprob, (Lx, Ly), interpolation=cv2.INTER_NEAREST)\n flowi.append(cellprob[np.newaxis,...])\n flowi.append(np.zeros(flows[0].shape, dtype=np.uint8))\n flowi[-1] = flowi[-1][np.newaxis,...]\n else:\n flowi.append((np.clip(transforms.normalize99(flows[2]),0,1) * 255).astype(np.uint8))\n flowi.append((flows[1][0]/10 * 127 + 127).astype(np.uint8))\n if len(flows)>2:\n flowi.append(flows[3])\n flowi.append(np.concatenate((flows[1], flows[2][np.newaxis,...]), axis=0))\n outlines = masks * utils.masks_to_outlines(masks)\n base = os.path.splitext(file_names)[0]\n if masks.ndim==3:\n np.save(base+ '_seg.npy',\n {'outlines': outlines.astype(np.uint16) if outlines.max()<2**16-1 else outlines.astype(np.uint32),\n 'masks': masks.astype(np.uint16) if outlines.max()<2**16-1 else masks.astype(np.uint32),\n 'chan_choose': channels,\n 'img': images,\n 'ismanual': np.zeros(masks.max(), bool),\n 'filename': file_names,\n 'flows': flowi,\n 'est_diam': diams})\n else:\n if images.shape[0]<8:\n np.transpose(images, (1,2,0))\n np.save(base+ '_seg.npy',\n {'img': images,\n 'outlines': outlines.astype(np.uint16) if outlines.max()<2**16-1 else outlines.astype(np.uint32),\n 'masks': masks.astype(np.uint16) if masks.max()<2**16-1 else masks.astype(np.uint32),\n 'chan_choose': channels,\n 'ismanual': np.zeros(masks.max(), bool),\n 'filename': file_names,\n 'flows': flowi,\n 'est_diam': diams}) \n\ndef save_to_png(images, masks, flows, file_names):\n \"\"\" deprecated (runs io.save_masks with png=True) \n \n does not work for 3D images\n \n \"\"\"\n save_masks(images, masks, flows, file_names, png=True)\n\n# Now saves flows, masks, etc. to separate folders.\ndef save_masks(images, masks, flows, file_names, png=True, tif=False, channels=[0,0],\n suffix='',save_flows=False, save_outlines=False, save_ncolor=False, \n dir_above=False, in_folders=False, savedir=None, save_txt=True):\n \"\"\" save masks + nicely plotted segmentation image to png and/or tiff\n\n if png, masks[k] for images[k] are saved to file_names[k]+'_cp_masks.png'\n\n if tif, masks[k] for images[k] are saved to file_names[k]+'_cp_masks.tif'\n\n if png and matplotlib installed, full segmentation figure is saved to file_names[k]+'_cp.png'\n\n only tif option works for 3D data\n \n Parameters\n -------------\n\n images: (list of) 2D, 3D or 4D arrays\n images input into cellpose\n\n masks: (list of) 2D arrays, int\n masks output from Cellpose.eval, where 0=NO masks; 1,2,...=mask labels\n\n flows: (list of) list of ND arrays \n flows output from Cellpose.eval\n\n file_names: (list of) str\n names of files of images\n \n savedir: str\n absolute path where images will be saved. Default is none (saves to image directory)\n \n save_flows, save_outlines, save_ncolor, save_txt: bool\n Can choose which outputs/views to save.\n ncolor is a 4 (or 5, if 4 takes too long) index version of the labels that\n is way easier to visualize than having hundreds of unique colors that may\n be similar and touch. Any color map can be applied to it (0,1,2,3,4,...).\n \n \"\"\"\n\n if isinstance(masks, list):\n for image, mask, flow, file_name in zip(images, masks, flows, file_names):\n save_masks(image, mask, flow, file_name, png=png, tif=tif, suffix=suffix,dir_above=dir_above,\n save_flows=save_flows,save_outlines=save_outlines,save_ncolor=save_ncolor,\n savedir=savedir,save_txt=save_txt,in_folders=in_folders)\n return\n \n if masks.ndim > 2 and not tif:\n raise ValueError('cannot save 3D outputs as PNG, use tif option instead')\n# base = os.path.splitext(file_names)[0]\n \n if savedir is None: \n if dir_above:\n savedir = Path(file_names).parent.parent.absolute() #go up a level to save in its own folder\n else:\n savedir = Path(file_names).parent.absolute()\n \n check_dir(savedir) \n \n basename = os.path.splitext(os.path.basename(file_names))[0]\n if in_folders:\n maskdir = os.path.join(savedir,'masks')\n outlinedir = os.path.join(savedir,'outlines')\n txtdir = os.path.join(savedir,'txt_outlines')\n ncolordir = os.path.join(savedir,'ncolor_masks')\n flowdir = os.path.join(savedir,'flows')\n else:\n maskdir = savedir\n outlinedir = savedir\n txtdir = savedir\n ncolordir = savedir\n flowdir = savedir\n \n check_dir(maskdir) \n\n exts = []\n if masks.ndim > 2 or masks.max()>2**16-1:\n png = False\n tif = True\n if png: \n exts.append('.png')\n if tif:\n exts.append('.tif')\n\n # format_labels will also automatically use lowest bit depth possible \n masks = utils.format_labels(masks) \n\n # save masks\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n for ext in exts:\n imsave(os.path.join(maskdir,basename + '_cp_masks' + suffix + ext), masks)\n \n if png and MATPLOTLIB and not min(images.shape) > 3:\n img = images.copy()\n if img.ndim<3:\n img = img[:,:,np.newaxis]\n elif img.shape[0]<8:\n np.transpose(img, (1,2,0))\n \n fig = plt.figure(figsize=(12,3))\n plot.show_segmentation(fig, img, masks, flows[0])\n fig.savefig(os.path.join(savedir,basename + '_cp_output' + suffix + '.png'), dpi=300)\n plt.close(fig)\n\n # ImageJ txt outline files \n if masks.ndim < 3 and save_txt:\n check_dir(txtdir)\n outlines = utils.outlines_list(masks)\n outlines_to_text(os.path.join(txtdir,basename), outlines)\n \n # RGB outline images\n if masks.ndim < 3 and save_outlines: \n check_dir(outlinedir) \n outlines = utils.masks_to_outlines(masks)\n outX, outY = np.nonzero(outlines)\n img0 = images.copy()\n if img0.shape[0] < 4:\n img0 = np.transpose(img0, (1,2,0))\n if img0.shape[-1] < 3 or img0.ndim < 3:\n img0 = plot.image_to_rgb(img0, channels=channels)\n else:\n if img0.max()<=50.0:\n img0 = np.uint8(np.clip(img0*255, 0, 1))\n imgout= img0.copy()\n imgout[outX, outY] = np.array([255,0,0]) #pure red \n imsave(os.path.join(outlinedir, basename + '_outlines' + suffix + '.png'), imgout)\n \n # ncolor labels (ready for color map application)\n if masks.ndim < 3 and save_ncolor:\n check_dir(ncolordir)\n #convert masks to minimal n-color reresentation \n imsave(os.path.join(ncolordir, basename + '_cp_ncolor_masks' + suffix + '.png'),\n utils.ncolorlabel(masks))\n \n # save RGB flow picture\n if masks.ndim < 3 and save_flows:\n check_dir(flowdir)\n imsave(os.path.join(flowdir, basename + '_flows' + suffix + '.png'), (flows[0]*(2**16 - 1)).astype(np.uint16))\n\ndef save_server(parent=None, filename=None):\n \"\"\" Uploads a *_seg.npy file to the bucket.\n \n Parameters\n ----------------\n\n parent: PyQt.MainWindow (optional, default None)\n GUI window to grab file info from\n\n filename: str (optional, default None)\n if no GUI, send this file to server\n\n \"\"\"\n if parent is not None:\n q = QtGui.QMessageBox.question(\n parent,\n \"Send to server\",\n \"Are you sure? Only send complete and fully manually segmented data.\\n (do not send partially automated segmentations)\",\n QtGui.QMessageBox.Yes | QtGui.QMessageBox.No\n )\n if q != QtGui.QMessageBox.Yes:\n return\n else:\n filename = parent.filename\n\n if filename is not None:\n os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n 'key/cellpose-data-writer.json')\n bucket_name = 'cellpose_data'\n base = os.path.splitext(filename)[0]\n source_file_name = base + '_seg.npy'\n io_logger.info(f'sending {source_file_name} to server')\n time = datetime.datetime.now().strftime(\"%Y_%m_%d_%H_%M_%S.%f\")\n filestring = time + '.npy'\n io_logger.info(f'name on server: {filestring}')\n destination_blob_name = filestring\n storage_client = storage.Client()\n bucket = storage_client.bucket(bucket_name)\n blob = bucket.blob(destination_blob_name)\n\n blob.upload_from_filename(source_file_name)\n\n io_logger.info(\n \"File {} uploaded to {}.\".format(\n source_file_name, destination_blob_name\n )\n )\n\n"
]
| [
[
"numpy.nonzero",
"numpy.clip",
"numpy.concatenate",
"matplotlib.pyplot.close",
"numpy.transpose",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
]
|
youyexie/Learning-To-Find-Good-Correspondences-Of-Multiple-Objects | [
"01df2bd8448486fe417d4e014706e89144ba6224"
]
| [
"Simulation/FaceClassifier/model_multiObject.py"
]
| [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Youye\r\n\"\"\"\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n\r\n#%% Define the ResNet block\r\n\r\nclass ResNetBlock(nn.Module):\r\n \r\n def __init__(self,inter_channel = 128):\r\n \r\n super(ResNetBlock, self).__init__()\r\n \r\n \r\n # RESNET Block Operator \r\n self.conv1 = nn.Conv2d( in_channels=inter_channel , out_channels=inter_channel, kernel_size=(1,1))\r\n self.CN1 = nn.InstanceNorm2d( num_features=inter_channel )\r\n self.BN1 = nn.BatchNorm2d( num_features=inter_channel , affine=False )\r\n \r\n self.conv2 = nn.Conv2d( in_channels=inter_channel , out_channels=inter_channel, kernel_size=(1,1))\r\n self.CN2 = nn.InstanceNorm2d( num_features=inter_channel )\r\n self.BN2 = nn.BatchNorm2d( num_features=inter_channel , affine=False )\r\n \r\n def forward(self,x):\r\n \r\n # define the structure of the ResNetBlock\r\n identity = x;\r\n x = self.conv1(x); #print(x.size())\r\n x = self.CN1(x); #print(x.size())\r\n x = self.BN1(x); #print(x.size())\r\n x = F.relu(x); # print(x.size())\r\n \r\n x = self.conv2(x);\r\n x = self.CN2(x);\r\n x = self.BN2(x);\r\n x = F.relu(x); \r\n \r\n x = x + identity;\r\n \r\n return x\r\n\r\n#% Define the network structure\r\n \r\nclass Net(nn.Module):\r\n\r\n def __init__(self, numBlocks1 = 5, numBlocks2=19,inter_channel=128):\r\n self.numBlocks1 = numBlocks1 # for inlier predictor\r\n self.numBlocks2 = numBlocks2 # for object weight predictor\r\n \r\n super(Net, self).__init__()\r\n \r\n # INPUT layer operator\r\n self.convInt = nn.Conv2d( in_channels=1 , out_channels=inter_channel , kernel_size=(1,5) )\r\n \r\n # Common ResNetBlock \r\n layers1 = [] \r\n \r\n for _ in range(0,self.numBlocks1):\r\n layers1.append( ResNetBlock(inter_channel) )\r\n \r\n self.ResNet1 = nn.Sequential(*layers1) \r\n \r\n\r\n # OUTPUT layer operator \r\n self.convInlierPredictor = nn.Conv2d( in_channels=inter_channel , out_channels=1, kernel_size=(1,1) )\r\n \r\n def forward(self, x):\r\n # Input Layer\r\n x = self.convInt(x)\r\n \r\n # ResNet blocks\r\n x = self.ResNet1(x) \r\n \r\n \r\n######### inlier predictor ################\r\n\r\n \r\n # [ Batch_size , 128 , num_weight, 1 ] \r\n [batch_size, _, numData,_] = x.shape\r\n \r\n # inlier predictor\r\n x = self.convInlierPredictor(x)\r\n x = x.view([batch_size,numData])\r\n \r\n \r\n x = torch.tanh(x)\r\n x = F.relu(x) \r\n \r\n return x\r\n \r\n \r\n#% Define the network structure\r\n \r\nclass AngleNet(nn.Module):\r\n\r\n def __init__(self, numBlocks = 20,inter_channel=128):\r\n self.numBlocks = numBlocks\r\n super(AngleNet, self).__init__()\r\n \r\n # INPUT layer operator\r\n self.convInt = nn.Conv2d( in_channels=1 , out_channels=inter_channel , kernel_size=(1,5) )\r\n \r\n # Common ResNetBlock \r\n layers = [] \r\n \r\n for _ in range(0,self.numBlocks):\r\n layers.append( ResNetBlock(inter_channel) )\r\n \r\n self.ResNet = nn.Sequential(*layers) \r\n \r\n \r\n # OUTPUT layer operator \r\n self.convOut = nn.Conv2d( in_channels=inter_channel , out_channels=9, kernel_size=(1,1) )\r\n \r\n self.SoftMax = nn.LogSoftmax(dim=1)\r\n \r\n def forward(self, x):\r\n # Input Layer\r\n x = self.convInt(x)\r\n \r\n # ResNet blocks\r\n x = self.ResNet(x) \r\n\r\n \r\n # [ Batch_size , 128 ,numData, 1 ] \r\n [batch_size, _, numData,_] = x.shape\r\n \r\n # [ Batch_size , 9 ,numData, 1 ] \r\n x = self.convOut(x)\r\n x = x[:,:,:,0] \r\n \r\n x = self.SoftMax(x)\r\n \r\n return x"
]
| [
[
"torch.nn.Sequential",
"torch.nn.LogSoftmax",
"torch.nn.Conv2d",
"torch.tanh",
"torch.nn.functional.relu",
"torch.nn.InstanceNorm2d",
"torch.nn.BatchNorm2d"
]
]
|
kunalsharma05/cclib | [
"6976824bcbf810ecd3e7f3dc25c4b6910c1e3b56"
]
| [
"cclib/parser/daltonparser.py"
]
| [
"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2017, the cclib development team\n#\n# This file is part of cclib (http://cclib.github.io) and is distributed under\n# the terms of the BSD 3-Clause License.\n\n\"\"\"Parser for DALTON output files\"\"\"\n\n\nfrom __future__ import print_function\n\nimport numpy\n\nfrom cclib.parser import logfileparser\nfrom cclib.parser import utils\n\n\nclass DALTON(logfileparser.Logfile):\n \"\"\"A DALTON log file.\"\"\"\n\n def __init__(self, *args, **kwargs):\n\n # Call the __init__ method of the superclass\n super(DALTON, self).__init__(logname=\"DALTON\", *args, **kwargs)\n\n def __str__(self):\n \"\"\"Return a string representation of the object.\"\"\"\n return \"DALTON log file %s\" % (self.filename)\n\n def __repr__(self):\n \"\"\"Return a representation of the object.\"\"\"\n return 'DALTON(\"%s\")' % (self.filename)\n\n def normalisesym(self, label):\n \"\"\"DALTON does not require normalizing symmetry labels.\"\"\"\n return label\n\n def before_parsing(self):\n\n # Used to decide whether to wipe the atomcoords clean.\n self.firststdorient = True\n\n # Use to track which section/program output we are parsing,\n # since some programs print out the same headers, which we\n # would like to use as triggers.\n self.section = None\n\n # If there is no symmetry, assume this.\n self.symlabels = ['Ag']\n\n # Is the basis set from a single library file? This is true\n # when the first line is BASIS, false for INTGRL/ATOMBASIS.\n self.basislibrary = True\n\n\n def parse_geometry(self, lines):\n \"\"\"Parse DALTON geometry lines into an atomcoords array.\"\"\"\n\n coords = []\n for lin in lines:\n\n # Without symmetry there are simply four columns, and with symmetry\n # an extra label is printed after the atom type.\n cols = lin.split()\n if cols[1][0] == \"_\":\n xyz = cols[2:]\n else:\n xyz = cols[1:]\n\n # The assumption is that DALTON always print in atomic units.\n xyz = [utils.convertor(float(x), 'bohr', 'Angstrom') for x in xyz]\n coords.append(xyz)\n\n return coords\n\n def extract(self, inputfile, line):\n \"\"\"Extract information from the file object inputfile.\"\"\"\n # extract the version number first\n if line[4:30] == \"This is output from DALTON\":\n if line.split()[5] == \"release\" or line.split()[5] == \"(Release\":\n self.metadata[\"package_version\"] = line.split()[6][6:]\n else:\n self.metadata[\"package_version\"] = line.split()[5]\n\n # Is the basis set from a single library file, or is it\n # manually specified? See before_parsing().\n if line[:6] == 'INTGRL'or line[:9] == 'ATOMBASIS':\n self.basislibrary = False\n\n # This section at the start of geometry optimization jobs gives us information\n # about optimization targets (geotargets) and possibly other things as well.\n # Notice how the number of criteria required to converge is set to 2 here,\n # but this parameter can (probably) be tweaked in the input.\n #\n # Chosen parameters for *OPTIMI :\n # -------------------------------\n #\n # Default 1st order method will be used: BFGS update.\n # Optimization will be performed in redundant internal coordinates (by default).\n # Model Hessian will be used as initial Hessian.\n # The model Hessian parameters of Roland Lindh will be used.\n #\n #\n # Trust region method will be used to control step (default).\n #\n # Convergence threshold for gradient set to : 1.00D-04\n # Convergence threshold for energy set to : 1.00D-06\n # Convergence threshold for step set to : 1.00D-04\n # Number of convergence criteria set to : 2\n #\n if line.strip()[:25] == \"Convergence threshold for\":\n\n if not hasattr(self, 'geotargets'):\n self.geotargets = []\n self.geotargets_names = []\n\n target = self.float(line.split()[-1])\n name = line.strip()[25:].split()[0]\n\n self.geotargets.append(target)\n self.geotargets_names.append(name)\n\n # This is probably the first place where atomic symmetry labels are printed,\n # somewhere afer the SYMGRP point group information section. We need to know\n # which atom is in which symmetry, since this influences how some things are\n # print later on. We can also get some generic attributes along the way.\n #\n # Isotopic Masses\n # ---------------\n #\n # C _1 12.000000\n # C _2 12.000000\n # C _1 12.000000\n # C _2 12.000000\n # ...\n #\n # Note that when there is no symmetry there are only two columns here.\n #\n # It is also a good idea to keep in mind that DALTON, with symmetry on, operates\n # in a specific point group, so symmetry atoms have no internal representation.\n # Therefore only atoms marked as \"_1\" or \"#1\" in other places are actually\n # represented in the model. The symmetry atoms (higher symmetry indices) are\n # generated on the fly when writing the output. We will save the symmetry indices\n # here for later use.\n #\n # Additional note: the symmetry labels are printed only for atoms that have\n # symmetry images... so assume \"_1\" if a label is missing. For example, there will\n # be no label for atoms on an axes, such as the oxygen in water in C2v:\n #\n # O 15.994915\n # H _1 1.007825\n # H _2 1.007825\n #\n if line.strip() == \"Isotopic Masses\":\n\n self.skip_lines(inputfile, ['d', 'b'])\n\n # Since some symmetry labels may be missing, read in all lines first.\n lines = []\n line = next(inputfile)\n while line.strip():\n lines.append(line)\n line = next(inputfile)\n\n # Split lines into columsn and dd any missing symmetry labels, if needed.\n lines = [l.split() for l in lines]\n if any([len(l) == 3 for l in lines]):\n for il, l in enumerate(lines):\n if len(l) == 2:\n lines[il] = [l[0], \"_1\", l[1]]\n\n atomnos = []\n symmetry_atoms = []\n atommasses = []\n for cols in lines:\n cols0 = ''.join([i for i in cols[0] if not i.isdigit()]) #remove numbers\n atomnos.append(self.table.number[cols0])\n if len(cols) == 3:\n symmetry_atoms.append(int(cols[1][1]))\n atommasses.append(float(cols[2]))\n else:\n atommasses.append(float(cols[1]))\n\n self.set_attribute('atomnos', atomnos)\n self.set_attribute('atommasses', atommasses)\n\n self.set_attribute('natom', len(atomnos))\n self.set_attribute('natom', len(atommasses))\n\n # Save this for later if there were any labels.\n self.symmetry_atoms = symmetry_atoms or None\n\n # This section is close to the beginning of the file, and can be used\n # to parse natom, nbasis and atomnos. We also construct atombasis here,\n # although that is symmetry-dependent (see inline comments). Note that\n # DALTON operates on the idea of atom type, which are not necessarily\n # unique element-wise.\n #\n # Atoms and basis sets\n # --------------------\n #\n # Number of atom types : 6\n # Total number of atoms: 20\n #\n # Basis set used is \"STO-3G\" from the basis set library.\n #\n # label atoms charge prim cont basis\n # ----------------------------------------------------------------------\n # C 6 6.0000 15 5 [6s3p|2s1p]\n # H 4 1.0000 3 1 [3s|1s]\n # C 2 6.0000 15 5 [6s3p|2s1p]\n # H 2 1.0000 3 1 [3s|1s]\n # C 2 6.0000 15 5 [6s3p|2s1p]\n # H 4 1.0000 3 1 [3s|1s]\n # ----------------------------------------------------------------------\n # total: 20 70.0000 180 60\n # ----------------------------------------------------------------------\n #\n # Threshold for neglecting AO integrals: 1.00D-12\n #\n if line.strip() == \"Atoms and basis sets\":\n\n self.skip_lines(inputfile, ['d', 'b'])\n\n line = next(inputfile)\n assert \"Number of atom types\" in line\n self.ntypes = int(line.split()[-1])\n\n line = next(inputfile)\n assert \"Total number of atoms:\" in line\n self.set_attribute(\"natom\", int(line.split()[-1]))\n\n # When using the INTGRL keyword and not pulling from the\n # basis set library, the \"Basis set used\" line doesn't\n # appear.\n if not self.basislibrary:\n self.skip_line(inputfile, 'b')\n else:\n #self.skip_lines(inputfile, ['b', 'basisname', 'b'])\n line = next(inputfile)\n line = next(inputfile)\n self.metadata[\"basis_set\"] = line.split()[4].strip('\\\"')\n line = next(inputfile)\n\n line = next(inputfile)\n cols = line.split()\n\n # Detecting which columns things are in will be somewhat more robust\n # to formatting changes in the future.\n iatoms = cols.index('atoms')\n icharge = cols.index('charge')\n icont = cols.index('cont')\n\n self.skip_line(inputfile, 'dashes')\n\n atomnos = []\n atombasis = []\n nbasis = 0\n for itype in range(self.ntypes):\n\n line = next(inputfile)\n cols = line.split()\n\n atoms = int(cols[iatoms])\n charge = float(cols[icharge])\n assert int(charge) == charge\n charge = int(charge)\n cont = int(cols[icont])\n\n for at in range(atoms):\n\n atomnos.append(charge)\n\n # If symmetry atoms are present, these will have basis functions\n # printed immediately after the one unique atom, so for all\n # practical purposes cclib can assume the ordering in atombasis\n # follows this out-of order scheme to match the output.\n if self.symmetry_atoms:\n\n # So we extend atombasis only for the unique atoms (with a\n # symmetry index of 1), interleaving the basis functions\n # for this atoms with basis functions for all symmetry atoms.\n if self.symmetry_atoms[at] == 1:\n nsyms = 1\n while (at + nsyms < self.natom) and self.symmetry_atoms[at + nsyms] == nsyms + 1:\n nsyms += 1\n for isym in range(nsyms):\n istart = nbasis + isym\n iend = nbasis + cont*nsyms + isym\n atombasis.append(list(range(istart, iend, nsyms)))\n nbasis += cont*nsyms\n\n else:\n atombasis.append(list(range(nbasis, nbasis + cont)))\n nbasis += cont\n\n self.set_attribute('atomnos', atomnos)\n self.set_attribute('atombasis', atombasis)\n self.set_attribute('nbasis', nbasis)\n\n self.skip_line(inputfile, 'dashes')\n\n line = next(inputfile)\n self.set_attribute('natom', int(line.split()[iatoms]))\n self.set_attribute('nbasis', int(line.split()[icont]))\n\n self.skip_line(inputfile, 'dashes')\n\n # The Gaussian exponents and contraction coefficients are printed for each primitive\n # and then the contraction information is printed separately (see below) Both segmented\n # and general contractions are used, but we can parse them the same way since zeros are\n # inserted for primitives that are not used. However, no atom index is printed here\n # so we don't really know when a new atom is started without using information\n # from other section (we should already have atombasis parsed at this point).\n #\n # Orbital exponents and contraction coefficients\n # ----------------------------------------------\n #\n #\n # C #1 1s 1 71.616837 0.1543 0.0000\n # seg. cont. 2 13.045096 0.5353 0.0000\n # 3 3.530512 0.4446 0.0000\n # 4 2.941249 0.0000 -0.1000\n # ...\n #\n # Here is a corresponding fragment for general contractions:\n #\n # C 1s 1 33980.000000 0.0001 -0.0000 0.0000 0.0000 0.0000\n # 0.0000 0.0000 0.0000 0.0000\n # gen. cont. 2 5089.000000 0.0007 -0.0002 0.0000 0.0000 0.0000\n # 0.0000 0.0000 0.0000 0.0000\n # 3 1157.000000 0.0037 -0.0008 0.0000 0.0000 0.0000\n # 0.0000 0.0000 0.0000 0.0000\n # 4 326.600000 0.0154 -0.0033 0.0000 0.0000 0.0000\n # ...\n #\n if line.strip() == \"Orbital exponents and contraction coefficients\":\n\n self.skip_lines(inputfile, ['d', 'b', 'b'])\n\n # Here we simply want to save the numbers defining each primitive for later use,\n # where the first number is the exponent, and the rest are coefficients which\n # should be zero if the primitive is not used in a contraction. This list is\n # symmetry agnostic, although primitives/contractions are not generally.\n self.primitives = []\n\n prims = []\n line = next(inputfile)\n while line.strip():\n\n # Each contraction/section is separated by a blank line, and at the very\n # end there is an extra blank line.\n while line.strip():\n\n # For generalized contraction it is typical to see the coefficients wrapped\n # to new lines, so we must collect them until we are sure a primitive starts.\n if line[:30].strip():\n if prims:\n self.primitives.append(prims)\n prims = []\n\n prims += [float(x) for x in line[20:].split()]\n\n line = next(inputfile)\n\n line = next(inputfile)\n\n # At the end we have the final primitive to save.\n self.primitives.append(prims)\n\n # This is the corresponding section to the primitive definitions parsed above, so we\n # assume those numbers are available in the variable 'primitives'. Here we read in the\n # indicies of primitives, which we use to construct gbasis.\n # \n # Contracted Orbitals\n # -------------------\n #\n # 1 C 1s 1 2 3 4 5 6 7 8 9 10 11 12\n # 2 C 1s 1 2 3 4 5 6 7 8 9 10 11 12\n # 3 C 1s 10\n # 4 C 1s 11\n # ...\n #\n # Here is an fragment with symmetry labels:\n #\n # ...\n # 1 C #1 1s 1 2 3\n # 2 C #2 1s 7 8 9\n # 3 C #1 1s 4 5 6\n # ...\n #\n if line.strip() == \"Contracted Orbitals\":\n\n self.skip_lines(inputfile, ['d', 'b'])\n\n # This is the reverse of atombasis, so that we can easily map from a basis functions\n # to the corresponding atom for use in the loop below.\n basisatoms = [None for i in range(self.nbasis)]\n for iatom in range(self.natom):\n for ibasis in self.atombasis[iatom]:\n basisatoms[ibasis] = iatom\n\n # Since contractions are not generally given in order (when there is symmetry),\n # start with an empty list for gbasis.\n gbasis = [[] for i in range(self.natom)]\n\n # This will hold the number of contractions already printed for each orbital,\n # counting symmetry orbitals separately.\n orbitalcount = {}\n\n for ibasis in range(self.nbasis):\n\n line = next(inputfile)\n cols = line.split()\n\n # The first columns is always the basis function index, which we can assert.\n assert int(cols[0]) == ibasis + 1\n\n # The number of columns is differnet when symmetry is used. If there are further\n # complications, it may be necessary to use exact slicing, since the formatting\n # of this section seems to be fixed (although columns can be missing). Notice how\n # We subtract one from the primitive indices here already to match cclib's\n # way of counting from zero in atombasis.\n if '#' in line:\n sym = cols[2]\n orbital = cols[3]\n prims = [int(i) - 1 for i in cols[4:]]\n else:\n sym = None\n orbital = cols[2]\n prims = [int(i) - 1 for i in cols[3:]]\n\n shell = orbital[0]\n subshell = orbital[1].upper()\n\n iatom = basisatoms[ibasis]\n\n # We want to count the number of contractiong already parsed for each orbital,\n # but need to make sure to differentiate between atoms and symmetry atoms.\n orblabel = str(iatom) + '.' + orbital + (sym or \"\")\n orbitalcount[orblabel] = orbitalcount.get(orblabel, 0) + 1\n\n # Here construct the actual primitives for gbasis, which should be a list\n # of 2-tuples containing an exponent an coefficient. Note how we are indexing\n # self.primitives from zero although the printed numbering starts from one.\n primitives = []\n for ip in prims:\n p = self.primitives[ip]\n exponent = p[0]\n coefficient = p[orbitalcount[orblabel]]\n primitives.append((exponent, coefficient))\n\n contraction = (subshell, primitives)\n if contraction not in gbasis[iatom]:\n gbasis[iatom].append(contraction)\n\n self.skip_line(inputfile, 'blank')\n\n self.set_attribute('gbasis', gbasis)\n\n # Since DALTON sometimes uses symmetry labels (Ag, Au, etc.) and sometimes\n # just the symmetry group index, we need to parse and keep a mapping between\n # these two for later use.\n #\n # Symmetry Orbitals\n # -----------------\n #\n # Number of orbitals in each symmetry: 25 5 25 5\n #\n #\n # Symmetry Ag ( 1)\n #\n # 1 C 1s 1 + 2\n # 2 C 1s 3 + 4\n # ...\n #\n if line.strip() == \"Symmetry Orbitals\":\n\n self.skip_lines(inputfile, ['d', 'b'])\n\n line = inputfile.next()\n self.symcounts = [int(c) for c in line.split(':')[1].split()]\n\n self.symlabels = []\n for sc in self.symcounts:\n\n self.skip_lines(inputfile, ['b', 'b'])\n\n # If the number of orbitals for a symmetry is zero, the printout\n # is different (see MP2 unittest logfile for an example).\n line = inputfile.next()\n\n if sc == 0:\n assert \"No orbitals in symmetry\" in line\n else:\n assert line.split()[0] == \"Symmetry\"\n self.symlabels.append(line.split()[1])\n self.skip_line(inputfile, 'blank')\n for i in range(sc):\n orbital = inputfile.next()\n\n if \"Starting in Wave Function Section (SIRIUS)\" in line:\n self.section = \"SIRIUS\"\n\n # Orbital specifications\n # ======================\n # Abelian symmetry species All | 1 2 3 4\n # | Ag Au Bu Bg\n # --- | --- --- --- ---\n # Total number of orbitals 60 | 25 5 25 5\n # Number of basis functions 60 | 25 5 25 5\n #\n # ** Automatic occupation of RKS orbitals **\n #\n # -- Initial occupation of symmetries is determined from extended Huckel guess.\n # -- Initial occupation of symmetries is :\n # @ Occupied SCF orbitals 35 | 15 2 15 3\n #\n # Maximum number of Fock iterations 0\n # Maximum number of DIIS iterations 60\n # Maximum number of QC-SCF iterations 60\n # Threshold for SCF convergence 1.00D-05\n # This is a DFT calculation of type: B3LYP\n # ...\n #\n if \"Total number of orbitals\" in line:\n # DALTON 2015 adds a @ in front of number of orbitals\n chomp = line.split()\n index = 4\n if \"@\" in chomp:\n index = 5\n self.set_attribute(\"nbasis\", int(chomp[index]))\n self.nmo_per_symmetry = list(map(int, chomp[index+2:]))\n assert self.nbasis == sum(self.nmo_per_symmetry)\n if \"Threshold for SCF convergence\" in line:\n if not hasattr(self, \"scftargets\"):\n self.scftargets = []\n scftarget = self.float(line.split()[-1])\n self.scftargets.append([scftarget])\n\n # Wave function specification\n # ============================\n # @ Wave function type >>> KS-DFT <<<\n # @ Number of closed shell electrons 70\n # @ Number of electrons in active shells 0\n # @ Total charge of the molecule 0\n #\n # @ Spin multiplicity and 2 M_S 1 0\n # @ Total number of symmetries 4 (point group: C2h)\n # @ Reference state symmetry 1 (irrep name : Ag )\n #\n # This is a DFT calculation of type: B3LYP\n # ...\n #\n if line.strip() == \"Wave function specification\":\n self.skip_line(inputfile, 'e')\n line = next(inputfile)\n # Must be a coupled cluster calculation.\n if line.strip() == '':\n self.skip_lines(inputfile, ['b', 'Coupled Cluster', 'b'])\n else:\n assert \"wave function\" in line.lower()\n line = next(inputfile)\n assert \"Number of closed shell electrons\" in line\n self.paired_electrons = int(line.split()[-1])\n line = next(inputfile)\n assert \"Number of electrons in active shells\" in line\n self.unpaired_electrons = int(line.split()[-1])\n line = next(inputfile)\n assert \"Total charge of the molecule\" in line\n self.set_attribute(\"charge\", int(line.split()[-1]))\n self.skip_line(inputfile, 'b')\n line = next(inputfile)\n assert \"Spin multiplicity and 2 M_S\" in line\n self.set_attribute(\"mult\", int(line.split()[-2]))\n # Dalton only has ROHF, no UHF\n if self.mult != 1:\n self.metadata[\"unrestricted\"] = True\n\n if not hasattr(self, 'homos'):\n self.set_attribute('homos', [(self.paired_electrons // 2) - 1])\n if self.unpaired_electrons > 0:\n self.homos.append(self.homos[0])\n self.homos[0] += self.unpaired_electrons\n\n # *********************************************\n # ***** DIIS optimization of Hartree-Fock *****\n # *********************************************\n #\n # C1-DIIS algorithm; max error vectors = 8\n #\n # Automatic occupation of symmetries with 70 electrons.\n #\n # Iter Total energy Error norm Delta(E) SCF occupation\n # -----------------------------------------------------------------------------\n # K-S energy, electrons, error : -46.547567739269 69.9999799123 -2.01D-05\n # @ 1 -381.645762476 4.00D+00 -3.82D+02 15 2 15 3\n # Virial theorem: -V/T = 2.008993\n # @ MULPOP C _1 0.15; C _2 0.15; C _1 0.12; C _2 0.12; C _1 0.11; C _2 0.11; H _1 -0.15; H _2 -0.15; H _1 -0.14; H _2 -0.14;\n # @ C _1 0.23; C _2 0.23; H _1 -0.15; H _2 -0.15; C _1 0.08; C _2 0.08; H _1 -0.12; H _2 -0.12; H _1 -0.13; H _2 -0.13;\n # -----------------------------------------------------------------------------\n # K-S energy, electrons, error : -46.647668038900 69.9999810430 -1.90D-05\n # @ 2 -381.949410128 1.05D+00 -3.04D-01 15 2 15 3\n # Virial theorem: -V/T = 2.013393\n # ...\n #\n # With and without symmetry, the \"Total energy\" line is shifted a little.\n if self.section == \"SIRIUS\" and \"Iter\" in line and \"Total energy\" in line:\n\n iteration = 0\n converged = False\n values = []\n if not hasattr(self, \"scfvalues\"):\n self.scfvalues = []\n\n while not converged:\n\n try:\n line = next(inputfile)\n except StopIteration:\n self.logger.warning('File terminated before end of last SCF!')\n break\n\n # each iteration is bracketed by \"-------------\"\n if \"-------------------\" in line:\n iteration += 1\n continue\n\n # the first hit of @ n where n is the current iteration\n strcompare = \"@{0:>3d}\".format(iteration)\n if strcompare in line:\n temp = line.split()\n error_norm = self.float(temp[3])\n values.append([error_norm])\n\n if line[0] == \"@\" and \"converged in\" in line:\n converged = True\n\n # It seems DALTON does change the SCF convergence criteria during a\n # geometry optimization, but also does not print them. So, assume they\n # are unchanged and copy the initial values after the first step. However,\n # it would be good to check up on this - perhaps it is possible to print.\n self.scfvalues.append(values)\n if len(self.scfvalues) > 1:\n self.scftargets.append(self.scftargets[-1])\n\n # DALTON organizes the energies by symmetry, so we need to parse first,\n # and then sort the energies (and labels) before we store them.\n #\n # The formatting varies depending on RHF/DFT and/or version. Here is\n # an example from a DFT job:\n #\n # *** SCF orbital energy analysis ***\n #\n # Only the five lowest virtual orbital energies printed in each symmetry.\n #\n # Number of electrons : 70\n # Orbital occupations : 15 2 15 3\n #\n # Sym Kohn-Sham orbital energies\n #\n # 1 Ag -10.01616533 -10.00394288 -10.00288640 -10.00209612 -9.98818062\n # -0.80583154 -0.71422407 -0.58487249 -0.55551093 -0.50630125\n # ...\n #\n # Here is an example from an RHF job that only has symmetry group indices:\n #\n # *** SCF orbital energy analysis ***\n #\n # Only the five lowest virtual orbital energies printed in each symmetry.\n #\n # Number of electrons : 70\n # Orbital occupations : 15 2 15 3\n #\n # Sym Hartree-Fock orbital energies\n #\n # 1 -11.04052518 -11.03158921 -11.02882211 -11.02858563 -11.01747921\n # -1.09029777 -0.97492511 -0.79988247 -0.76282547 -0.69677619\n # ...\n #\n if self.section == \"SIRIUS\" and \"*** SCF orbital energy analysis ***\" in line:\n\n # to get ALL orbital energies, the .PRINTLEVELS keyword needs\n # to be at least 0,10 (up from 0,5). I know, obvious, right?\n # this, however, will conflict with the scfvalues output that\n # changes into some weird form of DIIS debug output.\n\n mosyms = []\n moenergies = []\n\n self.skip_line(inputfile, 'blank')\n line = next(inputfile)\n\n # There is some extra text between the section header and\n # the number of electrons for open-shell calculations.\n while \"Number of electrons\" not in line:\n line = next(inputfile)\n nelectrons = int(line.split()[-1])\n\n line = next(inputfile)\n occupations = [int(o) for o in line.split()[3:]]\n nsym = len(occupations)\n\n self.skip_lines(inputfile, ['b', 'header', 'b'])\n\n # now parse nsym symmetries\n for isym in range(nsym):\n\n # For unoccupied symmetries, nothing is printed here.\n if occupations[isym] == 0:\n continue\n\n # When there are exactly five energies printed (on just one line), it seems\n # an extra blank line is printed after a block.\n line = next(inputfile)\n if not line.strip():\n line = next(inputfile)\n cols = line.split()\n\n # The first line has the orbital symmetry information, but sometimes\n # it's the label and sometimes it's the index. There are always five\n # energies per line, though, so we can deduce if we have the labels or\n # not just the index. In the latter case, we depend on the labels\n # being read earlier into the list `symlabels`. Finally, if no symlabels\n # were read that implies there is only one symmetry, namely Ag.\n if 'A' in cols[1] or 'B' in cols[1]:\n sym = self.normalisesym(cols[1])\n energies = [float(t) for t in cols[2:]]\n else:\n if hasattr(self, 'symlabels'):\n sym = self.normalisesym(self.symlabels[int(cols[0]) - 1])\n else:\n assert cols[0] == '1'\n sym = \"Ag\"\n energies = [float(t) for t in cols[1:]]\n\n while len(energies) > 0:\n moenergies.extend(energies)\n mosyms.extend(len(energies)*[sym])\n line = next(inputfile)\n energies = [float(col) for col in line.split()]\n\n # now sort the data about energies and symmetries. see the following post for the magic\n # http://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python-inverse-of-zip\n sdata = sorted(zip(moenergies, mosyms), key=lambda x: x[0])\n moenergies, mosyms = zip(*sdata)\n\n self.moenergies = [[]]\n self.moenergies[0] = [utils.convertor(moenergy, 'hartree', 'eV') for moenergy in moenergies]\n self.mosyms = [[]]\n self.mosyms[0] = mosyms\n\n if not hasattr(self, \"nmo\"):\n self.nmo = self.nbasis\n if len(self.moenergies[0]) != self.nmo:\n self.set_attribute('nmo', len(self.moenergies[0]))\n\n # .-----------------------------------.\n # | >>> Final results from SIRIUS <<< |\n # `-----------------------------------'\n #\n #\n # @ Spin multiplicity: 1\n # @ Spatial symmetry: 1 ( irrep Ag in C2h )\n # @ Total charge of molecule: 0\n #\n # @ Final DFT energy: -382.050716652387\n # @ Nuclear repulsion: 445.936979976608\n # @ Electronic energy: -827.987696628995\n #\n # @ Final gradient norm: 0.000003746706\n # ...\n #\n if \"Final HF energy\" in line and not (hasattr(self, \"mpenergies\") or hasattr(self, \"ccenergies\")):\n self.metadata[\"methods\"].append(\"HF\")\n if \"Final DFT energy\" in line:\n self.metadata[\"methods\"].append(\"DFT\")\n if \"This is a DFT calculation of type\" in line:\n self.metadata[\"functional\"] = line.split()[-1]\n\n if \"Final DFT energy\" in line or \"Final HF energy\" in line:\n if not hasattr(self, \"scfenergies\"):\n self.scfenergies = []\n temp = line.split()\n self.scfenergies.append(utils.convertor(float(temp[-1]), \"hartree\", \"eV\"))\n\n if \"@ = MP2 second order energy\" in line:\n self.metadata[\"methods\"].append(\"MP2\")\n energ = utils.convertor(float(line.split()[-1]), 'hartree', 'eV')\n if not hasattr(self, \"mpenergies\"):\n self.mpenergies = []\n self.mpenergies.append([])\n self.mpenergies[-1].append(energ)\n\n if \"Total CCSD energy:\" in line:\n self.metadata[\"methods\"].append(\"CCSD\")\n energ = utils.convertor(float(line.split()[-1]), 'hartree', 'eV')\n if not hasattr(self, \"ccenergies\"):\n self.ccenergies = []\n self.ccenergies.append(energ)\n\n if \"Total energy CCSD(T)\" in line:\n self.metadata[\"methods\"].append(\"CCSD(T)\")\n energ = utils.convertor(float(line.split()[-1]), 'hartree', 'eV')\n if not hasattr(self, \"ccenergies\"):\n self.ccenergies = []\n self.ccenergies.append(energ)\n\n # The molecular geometry requires the use of .RUN PROPERTIES in the input.\n # Note that the second column is not the nuclear charge, but the atom type\n # index used internally by DALTON.\n #\n # Molecular geometry (au)\n # -----------------------\n #\n # C _1 1.3498778652 2.3494125195 0.0000000000\n # C _2 -1.3498778652 -2.3494125195 0.0000000000\n # C _1 2.6543517307 0.0000000000 0.0000000000\n # ...\n #\n if \"Molecular geometry (au)\" in line:\n\n if not hasattr(self, \"atomcoords\"):\n self.atomcoords = []\n\n if self.firststdorient:\n self.firststdorient = False\n\n self.skip_lines(inputfile, ['d', 'b'])\n\n lines = [next(inputfile) for i in range(self.natom)]\n atomcoords = self.parse_geometry(lines)\n self.atomcoords.append(atomcoords)\n\n if \"Optimization Control Center\" in line:\n self.section = \"OPT\"\n assert set(next(inputfile).strip()) == set(\":\")\n\n # During geometry optimizations the geometry is printed in the section\n # that is titles \"Optimization Control Center\". Note that after an optimizations\n # finishes, DALTON normally runs another \"static property section (ABACUS)\",\n # so the final geometry will be repeated in atomcoords.\n #\n # Next geometry (au)\n # ------------------\n #\n # C _1 1.3203201560 2.3174808341 0.0000000000\n # C _2 -1.3203201560 -2.3174808341 0.0000000000\n # ...\n if self.section == \"OPT\" and line.strip() == \"Next geometry (au)\":\n\n self.skip_lines(inputfile, ['d', 'b'])\n\n lines = [next(inputfile) for i in range(self.natom)]\n coords = self.parse_geometry(lines)\n self.atomcoords.append(coords)\n\n # This section contains data for optdone and geovalues, although we could use\n # it to double check some atttributes that were parsed before.\n #\n # Optimization information\n # ------------------------\n #\n # Iteration number : 4\n # End of optimization : T\n # Energy at this geometry is : -379.777956\n # Energy change from last geom. : -0.000000\n # Predicted change : -0.000000\n # Ratio, actual/predicted change : 0.952994\n # Norm of gradient : 0.000058\n # Norm of step : 0.000643\n # Updated trust radius : 0.714097\n # Total Hessian index : 0\n #\n if self.section == \"OPT\" and line.strip() == \"Optimization information\":\n\n self.skip_lines(inputfile, ['d', 'b'])\n\n line = next(inputfile)\n assert 'Iteration number' in line\n iteration = int(line.split()[-1])\n line = next(inputfile)\n assert 'End of optimization' in line\n if not hasattr(self, 'optdone'):\n self.optdone = []\n self.optdone.append(line.split()[-1] == 'T')\n\n # We need a way to map between lines here and the targets stated at the\n # beginning of the file in 'Chosen parameters for *OPTIMI (see above),\n # and this dictionary facilitates that. The keys are target names parsed\n # in that initial section after input processing, and the values are\n # substrings that should appear in the lines in this section. Make an\n # exception for the energy at iteration zero where there is no gradient,\n # and take the total energy for geovalues.\n targets_labels = {\n 'gradient': 'Norm of gradient',\n 'energy': 'Energy change from last',\n 'step': 'Norm of step',\n }\n values = [numpy.nan] * len(self.geotargets)\n while line.strip():\n if iteration == 0 and \"Energy at this geometry\" in line:\n index = self.geotargets_names.index('energy')\n values[index] = self.float(line.split()[-1])\n for tgt, lbl in targets_labels.items():\n if lbl in line and tgt in self.geotargets_names:\n index = self.geotargets_names.index(tgt)\n values[index] = self.float(line.split()[-1])\n line = next(inputfile)\n\n # If we're missing something above, throw away the partial geovalues since\n # we don't want artificial NaNs getting into cclib. Instead, fix the dictionary\n # to make things work.\n if not numpy.nan in values:\n if not hasattr(self, 'geovalues'):\n self.geovalues = []\n self.geovalues.append(values)\n\n # -------------------------------------------------\n # extract the center of mass line\n if \"Center-of-mass coordinates (a.u.):\" in line:\n temp = line.split()\n reference = [utils.convertor(float(temp[i]), \"bohr\", \"Angstrom\") for i in [3, 4, 5]]\n if not hasattr(self, 'moments'):\n self.moments = [reference]\n\n # -------------------------------------------------\n # Extract the dipole moment\n if \"Dipole moment components\" in line:\n dipole = numpy.zeros(3)\n line = next(inputfile)\n line = next(inputfile)\n line = next(inputfile)\n if not \"zero by symmetry\" in line:\n line = next(inputfile)\n\n line = next(inputfile)\n temp = line.split()\n for i in range(3):\n dipole[i] = float(temp[2]) # store the Debye value\n if hasattr(self, 'moments'):\n self.moments.append(dipole)\n\n ## 'vibfreqs', 'vibirs', and 'vibsyms' appear in ABACUS.\n # Vibrational Frequencies and IR Intensities\n # ------------------------------------------\n #\n # mode irrep frequency IR intensity\n # ============================================================\n # cm-1 hartrees km/mol (D/A)**2/amu\n # ------------------------------------------------------------\n # 1 A 3546.72 0.016160 0.000 0.0000\n # 2 A 3546.67 0.016160 0.024 0.0006\n # ...\n if \"Vibrational Frequencies and IR Intensities\" in line:\n\n self.skip_lines(inputfile, ['dashes', 'blank'])\n line = next(inputfile)\n assert line.strip() == \"mode irrep frequency IR intensity\"\n self.skip_line(inputfile, 'equals')\n line = next(inputfile)\n assert line.strip() == \"cm-1 hartrees km/mol (D/A)**2/amu\"\n self.skip_line(inputfile, 'dashes')\n line = next(inputfile)\n\n # The normal modes are in order of decreasing IR\n # frequency, so they can't be added directly to\n # attributes; they must be grouped together first, sorted\n # in order of increasing frequency, then added to their\n # respective attributes.\n\n vibdata = []\n\n while line.strip():\n sline = line.split()\n vibsym = sline[1]\n vibfreq = float(sline[2])\n vibir = float(sline[4])\n vibdata.append((vibfreq, vibir, vibsym))\n line = next(inputfile)\n\n vibdata.sort(key=lambda normalmode: normalmode[0])\n\n self.vibfreqs = [normalmode[0] for normalmode in vibdata]\n self.vibirs = [normalmode[1] for normalmode in vibdata]\n self.vibsyms = [normalmode[2] for normalmode in vibdata]\n\n # Now extract the normal mode displacements.\n self.skip_lines(inputfile, ['b', 'b'])\n line = next(inputfile)\n assert line.strip() == \"Normal Coordinates (bohrs*amu**(1/2)):\"\n\n # Normal Coordinates (bohrs*amu**(1/2)):\n # --------------------------------------\n #\n #\n # 1 3547 2 3547 3 3474 4 3471 5 3451 \n # ----------------------------------------------------------------------\n #\n # C x -0.000319 -0.000314 0.002038 0.000003 -0.001599\n # C y -0.000158 -0.000150 -0.001446 0.003719 -0.002576\n # C z 0.000000 -0.000000 -0.000000 0.000000 -0.000000\n #\n # C x 0.000319 -0.000315 -0.002038 0.000003 0.001600\n # C y 0.000157 -0.000150 0.001448 0.003717 0.002577\n # ...\n self.skip_line(inputfile, 'd')\n line = next(inputfile)\n\n vibdisps = numpy.empty(shape=(len(self.vibirs), self.natom, 3))\n\n ndisps = 0\n while ndisps < len(self.vibirs):\n # Skip two blank lines.\n line = next(inputfile)\n line = next(inputfile)\n # Use the header with the normal mode indices and\n # frequencies to update where we are.\n ndisps_block = (len(line.split()) // 2)\n mode_min, mode_max = ndisps, ndisps + ndisps_block\n # Skip a line of dashes and a blank line.\n line = next(inputfile)\n line = next(inputfile)\n for w in range(self.natom):\n for coord in range(3):\n line = next(inputfile)\n vibdisps[mode_min:mode_max, w, coord] = [float(i) for i in line.split()[2:]]\n # Skip a blank line.\n line = next(inputfile)\n ndisps += ndisps_block\n\n # The vibrational displacements are in the wrong order;\n # reverse them.\n self.vibdisps = vibdisps[::-1, :, :]\n\n ## 'vibramans'\n # Raman related properties for freq. 0.000000 au = Infinity nm\n # ---------------------------------------------------------------\n #\n # Mode Freq. Alpha**2 Beta(a)**2 Pol.Int. Depol.Int. Dep. Ratio \n #\n # 1 3546.72 0.379364 16.900089 84.671721 50.700268 0.598786\n # 2 3546.67 0.000000 0.000000 0.000000 0.000000 0.599550\n if \"Raman related properties for freq.\" in line:\n\n self.skip_lines(inputfile, ['d', 'b'])\n line = next(inputfile)\n assert line[1:76] == \"Mode Freq. Alpha**2 Beta(a)**2 Pol.Int. Depol.Int. Dep. Ratio\"\n self.skip_line(inputfile, 'b')\n line = next(inputfile)\n\n vibramans = []\n\n # The Raman intensities appear under the \"Pol.Int.\"\n # (polarization intensity) column.\n for m in range(len(self.vibfreqs)):\n vibramans.append(float(line.split()[4]))\n line = next(inputfile)\n\n # All vibrational properties in DALTON appear in reverse\n # order.\n self.vibramans = vibramans[::-1]\n\n # Static polarizability from **PROPERTIES/.POLARI.\n if line.strip() == \"Static polarizabilities (au)\":\n if not hasattr(self, 'polarizabilities'):\n self.polarizabilities = []\n polarizability = []\n self.skip_lines(inputfile, ['d', 'b', 'directions', 'b'])\n for _ in range(3):\n line = next(inputfile)\n # Separate possibly unspaced huge negative polarizability tensor\n # element and the left adjacent column from each other.\n line = line.replace('-', ' -')\n polarizability.append(line.split()[1:])\n self.polarizabilities.append(numpy.array(polarizability))\n\n # Static and dynamic polarizability from **PROPERTIES/.ALPHA/*ABALNR.\n if \"Polarizability tensor for frequency\" in line:\n if not hasattr(self, 'polarizabilities'):\n self.polarizabilities = []\n polarizability = []\n self.skip_lines(inputfile, ['d', 'directions', 'b'])\n for _ in range(3):\n line = next(inputfile)\n polarizability.append(line.split()[1:])\n self.polarizabilities.append(numpy.array(polarizability))\n\n # Static and dynamic polarizability from **RESPONSE/*LINEAR.\n # This section is *very* general and will need to be expanded later.\n # For now, only form the matrix from dipole (length gauge) values.\n if \"@ FREQUENCY INDEPENDENT SECOND ORDER PROPERTIES\" in line:\n\n coord_to_idx = {'X': 0, 'Y': 1, 'Z': 2}\n\n self.skip_line(inputfile, 'b')\n line = next(inputfile)\n\n polarizability_diplen = numpy.empty(shape=(3, 3)) * numpy.nan\n while \"Time used in linear response calculation is\" not in line:\n tokens = line.split()\n if line.count(\"DIPLEN\") == 2:\n assert len(tokens) == 8\n if not hasattr(self, 'polarizabilities'):\n self.polarizabilities = []\n i, j = coord_to_idx[tokens[2][0]], coord_to_idx[tokens[4][0]]\n polarizability_diplen[i, j] = self.float(tokens[7])\n line = next(inputfile)\n\n polarizability_diplen = utils.symmetrize(polarizability_diplen, use_triangle='upper')\n if hasattr(self, 'polarizabilities'):\n self.polarizabilities.append(polarizability_diplen)\n\n # Electronic excitations: single residues of the linear\n # response equations.\n if \"Linear Response single residue calculation\" in line:\n\n etsyms = []\n etenergies = []\n # etoscs = []\n etsecs = []\n\n symmap = {\"T\": \"Triplet\", \"F\": \"Singlet\"}\n\n while \"End of Dynamic Property Section (RESPONS)\" not in line:\n\n line = next(inputfile)\n\n if \"Operator symmetry\" in line:\n do_triplet = line[-2]\n\n if \"@ Excited state no:\" in line:\n etsym = line.split()[9] # -2\n etsyms.append(symmap[do_triplet] + \"-\" + etsym)\n self.skip_lines(inputfile, ['d', 'b', 'Excitation energy in a.u.'])\n line = next(inputfile)\n etenergy = float(line.split()[1])\n etenergies.append(etenergy)\n\n while \"The dominant contributions\" not in line:\n line = next(inputfile)\n\n self.skip_line(inputfile, 'b')\n line = next(inputfile)\n # [0] is the starting (occupied) MO\n # [1] is the ending (unoccupied) MO\n # [2] and [3] are the excitation/deexcitation coefficients\n # [4] is the orbital overlap\n # [5] is the ...\n # [6] is the ...\n # [7] is the ...\n assert \"I A K_IA K_AI <|I|*|A|> <I^2*A^2> Weight Contrib\" in line\n self.skip_line(inputfile, 'b')\n line = next(inputfile)\n sec = []\n\n while line.strip():\n chomp = line.split()\n startidx = int(chomp[0]) - 1\n endidx = int(chomp[1]) - 1\n contrib = float(chomp[2])\n # Since DALTON is restricted open-shell only,\n # there is not distinction between alpha and\n # beta spin.\n sec.append([(startidx, 0), (endidx, 0), contrib])\n line = next(inputfile)\n\n etsecs.append(sec)\n\n self.set_attribute('etsyms', etsyms)\n self.set_attribute('etenergies', etenergies)\n # self.set_attribute('etoscs', etoscs)\n self.set_attribute('etsecs', etsecs)\n\n if line[:37] == ' >>>> Total wall time used in DALTON:':\n self.metadata['success'] = True\n\n # TODO:\n # aonames\n # aooverlaps\n # atomcharges\n # atomspins\n # coreelectrons\n # enthalpy\n # entropy\n # etoscs\n # etrotats\n # freeenergy\n # grads\n # hessian\n # mocoeffs\n # nocoeffs\n # nooccnos\n # scancoords\n # scanenergies\n # scannames\n # scanparm\n # temperature\n # vibanharms\n\n # N/A:\n # fonames\n # fooverlaps\n # fragnames\n # frags\n"
]
| [
[
"numpy.array",
"numpy.zeros",
"numpy.empty"
]
]
|
shubham1206agra/pretrained-models.pytorch | [
"a2940f79dd65656eabe5a0cd6d5d014ef1fc2523"
]
| [
"pretrainedmodels/models/xception.py"
]
| [
"\"\"\"\nPorted to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch)\n\n@author: tstandley\nAdapted by cadene\n\nCreates an Xception Model as defined in:\n\nFrancois Chollet\nXception: Deep Learning with Depthwise Separable Convolutions\nhttps://arxiv.org/pdf/1610.02357.pdf\n\nThis weights ported from the Keras implementation. Achieves the following performance on the validation set:\n\nLoss:0.9173 Prec@1:78.892 Prec@5:94.292\n\nREMEMBER to set your image size to 3x299x299 for both test and validation\n\nnormalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],\n std=[0.5, 0.5, 0.5])\n\nThe resize parameter of the validation transform should be 333, and make sure to center crop at 299x299\n\"\"\"\nfrom __future__ import print_function, division, absolute_import\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.model_zoo as model_zoo\nfrom torch.nn import init\n\n__all__ = ['xception']\n\npretrained_settings = {\n 'xception': {\n 'imagenet': {\n 'url': 'https://github.com/shubham1206agra/pretrained-models.pytorch/releases/download/test/xception-43020ad28.pth',\n 'input_space': 'RGB',\n 'input_size': [3, 299, 299],\n 'input_range': [0, 1],\n 'mean': [0.5, 0.5, 0.5],\n 'std': [0.5, 0.5, 0.5],\n 'num_classes': 1000,\n 'scale': 0.8975 # The resize parameter of the validation transform should be 333, and make sure to center crop at 299x299\n }\n }\n}\n\n\nclass SeparableConv2d(nn.Module):\n def __init__(self,in_channels,out_channels,kernel_size=1,stride=1,padding=0,dilation=1,bias=False):\n super(SeparableConv2d,self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels,in_channels,kernel_size,stride,padding,dilation,groups=in_channels,bias=bias)\n self.pointwise = nn.Conv2d(in_channels,out_channels,1,1,0,1,1,bias=bias)\n\n def forward(self,x):\n x = self.conv1(x)\n x = self.pointwise(x)\n return x\n\n\nclass Block(nn.Module):\n def __init__(self,in_filters,out_filters,reps,strides=1,start_with_relu=True,grow_first=True):\n super(Block, self).__init__()\n\n if out_filters != in_filters or strides!=1:\n self.skip = nn.Conv2d(in_filters,out_filters,1,stride=strides, bias=False)\n self.skipbn = nn.BatchNorm2d(out_filters)\n else:\n self.skip=None\n\n rep=[]\n\n filters=in_filters\n if grow_first:\n rep.append(nn.ReLU(inplace=True))\n rep.append(SeparableConv2d(in_filters,out_filters,3,stride=1,padding=1,bias=False))\n rep.append(nn.BatchNorm2d(out_filters))\n filters = out_filters\n\n for i in range(reps-1):\n rep.append(nn.ReLU(inplace=True))\n rep.append(SeparableConv2d(filters,filters,3,stride=1,padding=1,bias=False))\n rep.append(nn.BatchNorm2d(filters))\n\n if not grow_first:\n rep.append(nn.ReLU(inplace=True))\n rep.append(SeparableConv2d(in_filters,out_filters,3,stride=1,padding=1,bias=False))\n rep.append(nn.BatchNorm2d(out_filters))\n\n if not start_with_relu:\n rep = rep[1:]\n else:\n rep[0] = nn.ReLU(inplace=False)\n\n if strides != 1:\n rep.append(nn.MaxPool2d(3,strides,1))\n self.rep = nn.Sequential(*rep)\n\n def forward(self,inp):\n x = self.rep(inp)\n\n if self.skip is not None:\n skip = self.skip(inp)\n skip = self.skipbn(skip)\n else:\n skip = inp\n\n x+=skip\n return x\n\n\nclass Xception(nn.Module):\n \"\"\"\n Xception optimized for the ImageNet dataset, as specified in\n https://arxiv.org/pdf/1610.02357.pdf\n \"\"\"\n def __init__(self, num_classes=1000):\n \"\"\" Constructor\n Args:\n num_classes: number of classes\n \"\"\"\n super(Xception, self).__init__()\n self.num_classes = num_classes\n\n self.conv1 = nn.Conv2d(3, 32, 3,2, 0, bias=False)\n self.bn1 = nn.BatchNorm2d(32)\n self.relu1 = nn.ReLU(inplace=True)\n\n self.conv2 = nn.Conv2d(32,64,3,bias=False)\n self.bn2 = nn.BatchNorm2d(64)\n self.relu2 = nn.ReLU(inplace=True)\n #do relu here\n\n self.block1=Block(64,128,2,2,start_with_relu=False,grow_first=True)\n self.block2=Block(128,256,2,2,start_with_relu=True,grow_first=True)\n self.block3=Block(256,728,2,2,start_with_relu=True,grow_first=True)\n\n self.block4=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block5=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block6=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block7=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n\n self.block8=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block9=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block10=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n self.block11=Block(728,728,3,1,start_with_relu=True,grow_first=True)\n\n self.block12=Block(728,1024,2,2,start_with_relu=True,grow_first=False)\n\n self.conv3 = SeparableConv2d(1024,1536,3,1,1)\n self.bn3 = nn.BatchNorm2d(1536)\n self.relu3 = nn.ReLU(inplace=True)\n\n #do relu here\n self.conv4 = SeparableConv2d(1536,2048,3,1,1)\n self.bn4 = nn.BatchNorm2d(2048)\n\n self.fc = nn.Linear(2048, num_classes)\n\n # #------- init weights --------\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 # elif isinstance(m, nn.BatchNorm2d):\n # m.weight.data.fill_(1)\n # m.bias.data.zero_()\n # #-----------------------------\n\n def features(self, input):\n x = self.conv1(input)\n x = self.bn1(x)\n x = self.relu1(x)\n\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu2(x)\n\n x = self.block1(x)\n x = self.block2(x)\n x = self.block3(x)\n x = self.block4(x)\n x = self.block5(x)\n x = self.block6(x)\n x = self.block7(x)\n x = self.block8(x)\n x = self.block9(x)\n x = self.block10(x)\n x = self.block11(x)\n x = self.block12(x)\n\n x = self.conv3(x)\n x = self.bn3(x)\n x = self.relu3(x)\n\n x = self.conv4(x)\n x = self.bn4(x)\n return x\n\n def logits(self, features):\n x = nn.ReLU(inplace=True)(features)\n\n x = F.adaptive_avg_pool2d(x, (1, 1))\n x = x.view(x.size(0), -1)\n x = self.last_linear(x)\n return x\n\n def forward(self, input):\n x = self.features(input)\n x = self.logits(x)\n return x\n\n\ndef xception(num_classes=1000, pretrained='imagenet'):\n model = Xception(num_classes=num_classes)\n if pretrained:\n settings = pretrained_settings['xception'][pretrained]\n assert num_classes == settings['num_classes'], \\\n \"num_classes should be {}, but is {}\".format(settings['num_classes'], num_classes)\n\n model = Xception(num_classes=num_classes)\n model.load_state_dict(model_zoo.load_url(settings['url']))\n\n model.input_space = settings['input_space']\n model.input_size = settings['input_size']\n model.input_range = settings['input_range']\n model.mean = settings['mean']\n model.std = settings['std']\n\n # TODO: ugly\n model.last_linear = model.fc\n del model.fc\n return model\n"
]
| [
[
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.nn.functional.adaptive_avg_pool2d",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.utils.model_zoo.load_url"
]
]
|
mezzX/Connect4-AlphaZero | [
"68aed3f77f939a8c93d0e3a5c3251312258877b7"
]
| [
"mcts.py"
]
| [
"import torch\r\nfrom copy import copy\r\nimport math\r\nimport random\r\n\r\nc = 1.0\r\n\r\n# transformations\r\nt0 = lambda x: x\r\nt1 = lambda x: x[:, ::-1].copy()\r\nt2 = lambda x: x[::-1, :].copy()\r\nt3 = lambda x: x[::-1, ::-1].copy()\r\nt4 = lambda x: x.T\r\nt5 = lambda x: x[:, ::-1].T.copy()\r\nt6 = lambda x: x[::-1, :].T.copy()\r\nt7 = lambda x: x[::-1, ::-1].T.copy()\r\n\r\ntlist = [t0, t1, t2, t3, t4, t5, t6, t7]\r\ntlist_half = [t0, t1, t2, t3]\r\n\r\ndef flip(x, dim):\r\n indices = [slice(None)] * x.dim()\r\n indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,\r\n dtype=torch.long, device=x.device)\r\n return x[tuple(indices)]\r\n\r\n\r\nt0inv = lambda x: x\r\nt1inv = lambda x: flip(x,1)\r\nt2inv = lambda x: flip(x,0)\r\nt3inv = lambda x: flip(flip(x,0),1)\r\nt4inv = lambda x: x.t()\r\nt5inv = lambda x: flip(x,0).t()\r\nt6inv = lambda x: flip(x,1).t()\r\nt7inv = lambda x: flip(flip(x,0),1).t()\r\n\r\ntinvlist = [t0inv, t1inv, t2inv, t3inv, t4inv, t5inv, t6inv, t7inv]\r\ntinvlist_half = [t0inv, t1inv, t2inv, t3inv]\r\n\r\ntransformation_list = list(zip(tlist, tinvlist))\r\ntransformation_list_half = list(zip(tlist_half, tinvlist_half))\r\n\r\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\ndevice = 'cpu'\r\n\r\ndef process_policy(policy, game):\r\n\r\n # for square board, add rotations as well\r\n if game.size[0]==game.size[1]:\r\n t, tinv = random.choice(transformation_list)\r\n\r\n # otherwise only add reflections\r\n else:\r\n t, tinv = random.choice(transformation_list_half)\r\n \r\n frame=torch.tensor(t(game.state*game.player), dtype=torch.float, device=device)\r\n input=frame.unsqueeze(0).unsqueeze(0)\r\n prob, v = policy(input)\r\n mask = torch.tensor(game.available_mask())\r\n \r\n # we add a negative sign because when deciding next move,\r\n # the current player is the previous player making the move\r\n return game.available_moves, tinv(prob)[mask].view(-1), v.squeeze().squeeze()\r\n\r\n\r\nclass Node:\r\n def __init__(self, game, mother=None, prob=torch.tensor(0., dtype=torch.float)):\r\n self.game = game\r\n \r\n # child nodes\r\n self.child = {}\r\n # numbers for determining which actions to take next\r\n self.U = 0\r\n\r\n # V from neural net output\r\n # it's a torch.tensor object\r\n # has require_grad enabled\r\n self.prob = prob\r\n # the predicted expectation from neural net\r\n self.nn_v = torch.tensor(0., dtype=torch.float)\r\n \r\n # visit count\r\n self.N = 0\r\n\r\n # expected V from MCTS\r\n self.V = 0\r\n\r\n # keeps track of the guaranteed outcome\r\n # initialized to None\r\n # this is for speeding the tree-search up\r\n # but stopping exploration when the outcome is certain\r\n # and there is a known perfect play\r\n self.outcome = self.game.score\r\n\r\n\r\n # if game is won/loss/draw\r\n if self.game.score is not None:\r\n self.V = self.game.score * self.game.player\r\n self.U = 0 if self.game.score is 0 else self.V * float('inf')\r\n\r\n # link to previous node\r\n self.mother = mother\r\n\r\n\r\n def create_child(self, actions, probs):\r\n # create a dictionary of children\r\n games = [ copy(self.game) for a in actions ]\r\n\r\n for action, game in zip(actions, games):\r\n game.move(action)\r\n\r\n child = { a : Node(g, self, p) for a, g, p in zip(actions, games, probs) }\r\n self.child = child\r\n\r\n\r\n def explore(self, policy):\r\n\r\n if self.game.score is not None:\r\n raise ValueError(\"game has ended with score {0:d}\".format(self.game.score))\r\n\r\n current = self\r\n\r\n \r\n # explore children of the node\r\n # to speed things up \r\n while current.child and current.outcome is None:\r\n\r\n child = current.child\r\n max_U = max(c.U for c in child.values())\r\n #print(\"current max_U \", max_U) \r\n actions = [ a for a,c in child.items() if c.U == max_U ]\r\n if len(actions) == 0:\r\n print(\"error zero length \", max_U)\r\n print(current.game.state)\r\n \r\n action = random.choice(actions)\r\n\r\n if max_U == -float(\"inf\"):\r\n current.U = float(\"inf\")\r\n current.V = 1.0\r\n break\r\n \r\n elif max_U == float(\"inf\"):\r\n current.U = -float(\"inf\")\r\n current.V = -1.0\r\n break\r\n \r\n current = child[action]\r\n \r\n # if node hasn't been expanded\r\n if not current.child and current.outcome is None:\r\n # policy outputs results from the perspective of the next player\r\n # thus extra - sign is needed\r\n next_actions, probs, v = process_policy(policy, current.game)\r\n current.nn_v = -v\r\n current.create_child(next_actions, probs)\r\n current.V = -float(v)\r\n\r\n \r\n current.N += 1\r\n\r\n # now update U and back-prop\r\n while current.mother:\r\n mother = current.mother\r\n mother.N += 1\r\n # beteen mother and child, the player is switched, extra - sign\r\n mother.V += (-current.V - mother.V)/mother.N\r\n\r\n #update U for all sibling nodes\r\n for sibling in mother.child.values():\r\n if sibling.U is not float(\"inf\") and sibling.U is not -float(\"inf\"):\r\n sibling.U = sibling.V + c*float(sibling.prob)* math.sqrt(mother.N)/(1+sibling.N)\r\n\r\n current = current.mother\r\n\r\n\r\n def next(self, temperature=1.0):\r\n\r\n if self.game.score is not None:\r\n raise ValueError('game has ended with score {0:d}'.format(self.game.score))\r\n\r\n if not self.child:\r\n print(self.game.state)\r\n raise ValueError('no children found and game hasn\\'t ended')\r\n \r\n child=self.child\r\n\r\n \r\n # if there are winning moves, just output those\r\n max_U = max(c.U for c in child.values())\r\n\r\n if max_U == float(\"inf\"):\r\n prob = torch.tensor([ 1.0 if c.U == float(\"inf\") else 0 for c in child.values()], device=device)\r\n \r\n else:\r\n # divide things by maxN for numerical stability\r\n maxN = max(node.N for node in child.values())+1\r\n prob = torch.tensor([ (node.N/maxN)**(1/temperature) for node in child.values() ], device=device)\r\n\r\n # normalize the probability\r\n if torch.sum(prob) > 0:\r\n prob /= torch.sum(prob)\r\n \r\n # if sum is zero, just make things random\r\n else:\r\n prob = torch.tensor(1.0/len(child), device=device).repeat(len(child))\r\n\r\n nn_prob = torch.stack([ node.prob for node in child.values() ]).to(device)\r\n\r\n nextstate = random.choices(list(child.values()), weights=prob)[0]\r\n \r\n # V was for the previous player making a move\r\n # to convert to the current player we add - sign\r\n return nextstate, (-self.V, -self.nn_v, prob, nn_prob)\r\n\r\n def detach_mother(self):\r\n del self.mother\r\n self.mother = None"
]
| [
[
"torch.sum",
"torch.cuda.is_available",
"torch.tensor"
]
]
|
jingyi7777/CasRx_guide_efficiency | [
"c9e900e4c4a73215f09852bd621b30e8dcb039e8"
]
| [
"models/Deep-learning/models/guide_all_cnn_hyp_ninef_classi_model.py"
]
| [
"import tensorflow as tf\nfrom kerastuner import HyperParameters\nfrom tensorflow import keras\n\nfrom models.layers import recurrent_dense, strided_down, encoder_down_block\n\n\ndef guide_all_cnn_hyp_ninef_classi_model(num_strided_down=4,kernel=5,cnn_units=128, dense_units=128, recurrent_layers=8, noise=True):\n seq = keras.Input(shape=(30, 4))\n other = keras.Input(shape=9)\n\n x = seq\n for _ in range(num_strided_down):\n x = strided_down(x, cnn_units, 1, kernel)\n if noise:\n x = keras.layers.GaussianNoise(.01)(x)\n\n x = keras.layers.Flatten()(x)\n\n x = keras.layers.Concatenate()([x, other])\n\n x = keras.layers.Dense(dense_units, activation=tf.nn.leaky_relu)(x)\n for _ in range(recurrent_layers):\n x = recurrent_dense(x, dense_units)\n\n outputs = keras.layers.Dense(1)(x)\n # TODO: make a second output that is confidence, and have some allowance of reduced penalty\n # for low confidence wrong guesses, but overall penalty for low confidence\n return keras.Model(inputs=[seq,other], outputs=outputs)\n\n\ndef guide_all_cnn_hyp_ninef_classi_model_hp(hp: HyperParameters):\n kernel= hp.Choice('kernel',[3,4,5])\n cnn_units = hp.Choice('cnn_units', [8,16,32,64])\n dense_units = hp.Choice('dense_units', [8,16,32,64])\n num_strided_down = hp.Int('num_strided_down', 3,5)\n recurrent_layers = hp.Choice('num_recurrent_layers', [0,1,2,3])\n noise = True # hp.Boolean('use_noise')\n\n model = guide_all_cnn_hyp_ninef_classi_model(num_strided_down=num_strided_down, kernel=kernel, cnn_units=cnn_units, dense_units=dense_units,\n recurrent_layers=recurrent_layers, noise=noise)\n\n #metrics = [keras.metrics.MeanAbsoluteError(), keras.metrics.MeanSquaredError()]\n\n metrics = ['accuracy']\n\n model.compile(keras.optimizers.Adam(), tf.losses.binary_crossentropy, metrics=metrics)\n #model.compile(keras.optimizers.Adam(), tf.keras.losses.MeanSquaredError(), metrics=metrics)\n\n return model\n"
]
| [
[
"tensorflow.keras.layers.Concatenate",
"tensorflow.keras.Input",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.Model",
"tensorflow.keras.layers.GaussianNoise",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.Flatten"
]
]
|
NCAR/dash-eol-prod | [
"4269454dbd67e470f789d556ecdffc7ccdb270c7"
]
| [
"actions/CGD/create_plots.py"
]
| [
"#---------------------------------------------------\n# This code will take CSV files and plot graphs\n# representing EMDAC Metadata completeness scores\n#\n# Before running, edit the text in \n# input_directory and output_directory statements\n# after the import section. All *.csv files should\n# be located in the input directory and all the final\n# plots will end up in the output_directory\n#\n#\n#---------------------------------------------------\n#---------------------------------------------------\n#\t\tIMPORT\n#---------------------------------------------------\n\nimport sys\nimport csv\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport collections\nimport os\n\n#---------------------------------------------------\n#\tSET INPUT AND OUTPUT DIRECTORIES\n#---------------------------------------------------\ncurrentdir = os.getcwd()\ncurrentdirstring = str(currentdir)\n#input_directory = os.fsencode('../LevelsScores/')\ninput_directory = './LevelsScores/'\noutput_directory = './barcharts/'\n\n#---------------------------------------------------\n#\tCREATE CORRECT KEYS CORRESPONDING\n#\tTO METADATE ELEMENTS IN CSV FILES\n#---------------------------------------------------\n\ndef createTotals():\n\ttotals = collections.OrderedDict.fromkeys(['metadataRecordID', 'ISO assetType', 'metadataContact', 'metadataDate', 'landingPage', 'title', 'publicationDate', 'author', 'publisher', 'abstract', 'resourceSupportContact', 'DataCite resourceType', 'legalConstraints', 'accessConstraints', 'resourceLanguage', '| Tier 2 |', 'otherResponsibleParty/Custodian', 'otherResponsibleParty/Originator', 'otherResponsibleParty/ResourceProvider', 'credit', 'citationDate', 'scienceSupportContact/PI', 'keywords (tags)', 'keywords (GCMD )', 'keywordVocabulary', 'referenceSystem', 'spatialRepresentation', 'spatialResolution', 'ISO topicCategory', 'datasetExtent (Geolocation)', 'datasetExtentDescription', 'temporalCoverage', 'startDate', 'endDate', 'temporalResolution', 'verticalExtent', '| Tier 3 |', 'relatedLinkIdentifier', 'relatedLinkName', 'relatedLinkType', 'relatedlinkDescription', 'alternateIdentifier', 'resourceVersion', 'progress', 'resourceFormat', 'softwareImplementationLanguage', 'additionalInformation', 'distributor', 'distributionFormat', 'assetSize', 'authorIdentifier', '| from Templates |', 'dataIdentification', 'metadataStandardName', 'metadataStandardVersion'], 0) \n\treturn totals\n\n#--------------------------------------------------\n#\tLOOP THROUGH FILES IN input_directory\n#\tTO TOTAL AND PLOT VALUES IN output_directory\n#--------------------------------------------------\n\nfor filename in os.listdir(input_directory):\n# for filename in listdir(input_directory):\n\t#filename_str = filename.decode(\"utf-8\") \n\t#object has already been decoded\n\tfilename_str = filename\n\tindex = filename_str.find('-Scores')\n\tlab_name = filename_str[0:index] \t#extract lab name from filename\n\tprint('Reading in totals for metadata values from ', lab_name) \n\t#with open(input_directory.decode(\"utf-8\") + filename_str, mode='r') as csv_file:\n\t#removed decode since object is already decoded\n\twith open(input_directory + filename_str, mode='r') as csv_file:\n \t\tcsv_reader = csv.DictReader(csv_file)\n \t\ttotals = createTotals()\n \t\tnext(csv_reader)\n \t\tfor row in csv_reader:\n \t\tdel row['archive ident']\n \t\tdel row['Total Score']\n \t\tfor key in row:\n \t\t\trow[key] = int(row[key])\n \t\t\ttotals[key] += row[key]\n \n\t# Create two lists from the totals dictionary to be used for plotting\n\tlabels = list(totals.keys())\n\tvalues = list(totals.values())\n\n\tprint('Creating completeness graph for ', lab_name)\n\t# Create a figure\n\tfig = plt.figure(figsize=(20,8))\n\n\t# All bars uniform except tier dividers\n\tcolors = ['steelblue' for i in range(len(labels))]\n\tcolors[labels.index('| Tier 2 |')] = 'lightgray'\n\tcolors[labels.index('| Tier 3 |')] = 'lightgray'\n\tcolors[labels.index('| from Templates |')] = 'lightgray'\n\t\n\t# Change values at tier dividers\n\tvalues[labels.index('| Tier 2 |')] = max(values)\n\tvalues[labels.index('| Tier 3 |')] = max(values)\n\tvalues[labels.index('| from Templates |')] = max(values)\n\t\n\t# Retrieve date information to display on plot\n\t#today = date.today()\n\n\t# Plot metadata type as x-axis and number of datasets containing such as y-axis\n\tindex = np.arange(len(labels))\n\tscale_index = [3*i for i in index]\n\tplt.bar(scale_index, values, color=colors, width=2, align='center')\n\tplt.xlabel('NCAR Dialect', fontsize=15)\n\tplt.ylabel('Number of metadata files with element', fontsize=15)\n\tplt.xticks(scale_index, labels, fontsize=11, rotation=45, ha='right')\n\tplt.title(lab_name.upper()+' Completeness Score', fontsize=20)\n\tplt.subplots_adjust(bottom=0.4, top=0.9)\n\n\t# Set yticks to be integers for values less than 25\n\tif max(values) == 2:\n\t\tyticks = [0,1,2]\n\t\tplt.yticks(yticks, yticks, fontsize=11)\n\telif max(values) <= 40 :\n\t\tyticks = [int(max(values)/4 * i) for i in range(5)]\n\t\tplt.yticks(yticks, yticks, fontsize=11)\n\n\t#save filename to strFile\n\tstrFileName = output_directory+lab_name+'.png'\n\n\n\t#removing old figure and saving new one\n\tif os.path.isfile(strFileName):\n \t\tos.remove(strFileName)\n\n\t# Save figure to output directory as .gif\n\tfig.savefig(strFileName)\n\t\t\n\tprint('Plot saved in the plots directory with the name '+ lab_name+ '.png')\n\nprint('Done')\n"
]
| [
[
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel"
]
]
|
keshavashiya/Machine-Learning-with-Python | [
"fb1d08c7e4499c255c9cce5abcec9b1e18b1a1ec"
]
| [
"k_nearest_neighbors/utils.py"
]
| [
"import random\nfrom collections import Counter\n\nimport matplotlib.pyplot as plt\n\nfrom helpers.linear_algebra import distance\nfrom k_nearest_neighbors.data import cities\n\n\ndef raw_majority_vote(labels):\n votes = Counter(labels)\n winner, _ = votes.most_common(1)[0]\n return winner\n\n\ndef majority_vote(labels):\n \"\"\"assumes that labels are ordered from nearest to farthest\"\"\"\n vote_counts = Counter(labels)\n winner, winner_count = vote_counts.most_common(1)[0]\n num_winners = len([count\n for count in vote_counts.values()\n if count == winner_count])\n\n if num_winners == 1:\n return winner # unique winner, so return it\n else:\n return majority_vote(labels[:-1]) # try again without the farthest\n\n\ndef knn_classify(k, labeled_points, new_point):\n \"\"\"each labeled point should be a pair (point, label)\"\"\"\n\n # order the labeled points from nearest to farthest\n by_distance = sorted(labeled_points,\n key=lambda point_label: distance(point_label[0], new_point))\n\n # find the labels for the k closest\n k_nearest_labels = [label for _, label in by_distance[:k]]\n\n # and let them vote\n return majority_vote(k_nearest_labels)\n\n\ndef plot_state_borders(plt):\n pass\n\n\ndef plot_cities():\n\n # key is language, value is pair (longitudes, latitudes)\n plots = { \"Java\" : ([], []), \"Python\" : ([], []), \"R\" : ([], []) }\n\n # we want each language to have a different marker and color\n markers = { \"Java\" : \"o\", \"Python\" : \"s\", \"R\" : \"^\" }\n colors = { \"Java\" : \"r\", \"Python\" : \"b\", \"R\" : \"g\" }\n\n for (longitude, latitude), language in cities:\n plots[language][0].append(longitude)\n plots[language][1].append(latitude)\n\n # create a scatter series for each language\n for language, (x, y) in plots.items():\n plt.scatter(x, y, color=colors[language], marker=markers[language],\n label=language, zorder=10)\n\n plot_state_borders(plt) # assume we have a function that does this\n\n plt.legend(loc=0) # let matplotlib choose the location\n plt.axis([-130,-60,20,55]) # set the axes\n plt.title(\"Favorite Programming Languages\")\n plt.show()\n\n\ndef classify_and_plot_grid(k=1):\n plots = { \"Java\" : ([], []), \"Python\" : ([], []), \"R\" : ([], []) }\n markers = { \"Java\" : \"o\", \"Python\" : \"s\", \"R\" : \"^\" }\n colors = { \"Java\" : \"r\", \"Python\" : \"b\", \"R\" : \"g\" }\n\n for longitude in range(-130, -60):\n for latitude in range(20, 55):\n predicted_language = knn_classify(k, cities, [longitude, latitude])\n plots[predicted_language][0].append(longitude)\n plots[predicted_language][1].append(latitude)\n\n # create a scatter series for each language\n for language, (x, y) in plots.items():\n plt.scatter(x, y, color=colors[language], marker=markers[language],\n label=language, zorder=0)\n\n plot_state_borders(plt) # assume we have a function that does this\n\n plt.legend(loc=0) # let matplotlib choose the location\n plt.axis([-130,-60,20,55]) # set the axes\n plt.title(str(k) + \"-Nearest Neighbor Programming Languages\")\n plt.show()\n\n#\n# the curse of dimensionality\n#\n\n\ndef random_point(dim):\n return [random.random() for _ in range(dim)]\n\n\ndef random_distances(dim, num_pairs):\n return [distance(random_point(dim), random_point(dim))\n for _ in range(num_pairs)]\n"
]
| [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show"
]
]
|
irenecortinovis/madminer | [
"2f7afd9698861d37483d7a62388e8962ee535d02"
]
| [
"madminer/utils/interfaces/delphes_root.py"
]
| [
"from __future__ import absolute_import, division, print_function, unicode_literals\nimport six\n\nimport numpy as np\nfrom collections import OrderedDict\nimport uproot\nimport os\nimport logging\nimport itertools\n\n\nfrom madminer.utils.particle import MadMinerParticle\nfrom madminer.utils.various import math_commands\n\nlogger = logging.getLogger(__name__)\nimport itertools\n\n\ndef parse_delphes_root_file(\n delphes_sample_file,\n observables,\n observables_required,\n observables_defaults,\n cuts,\n cuts_default_pass,\n weight_labels=None,\n use_generator_truth=False,\n acceptance_pt_min_e=None,\n acceptance_pt_min_mu=None,\n acceptance_pt_min_a=None,\n acceptance_pt_min_j=None,\n acceptance_eta_max_e=None,\n acceptance_eta_max_mu=None,\n acceptance_eta_max_a=None,\n acceptance_eta_max_j=None,\n delete_delphes_sample_file=False,\n):\n \"\"\" Extracts observables and weights from a Delphes ROOT file \"\"\"\n\n logger.debug(\"Parsing Delphes file %s\", delphes_sample_file)\n if weight_labels is None:\n logger.debug(\"Not extracting weights\")\n else:\n logger.debug(\"Extracting weights %s\", weight_labels)\n\n # Delphes ROOT file\n root_file = uproot.open(str(delphes_sample_file))\n # The str() call is important when using numpy 1.16.0 and Python 2.7. In this combination of versions, a unicode\n # delphes_sample_file would lead to a crash.\n\n # Delphes tree\n tree = root_file[\"Delphes\"]\n\n # Weights\n n_weights = 0\n weights = None\n if weight_labels is not None:\n try:\n weights = tree.array(\"Weight.Weight\")\n\n n_weights = len(weights[0])\n n_events = len(weights)\n\n logger.debug(\"Found %s events, %s weights\", n_events, n_weights)\n\n weights = np.array(weights).reshape((n_events, n_weights)).T\n except KeyError:\n raise RuntimeError(\n \"Extracting weights from Delphes ROOT file failed. Please install inofficial patches\"\n \" for the MG-Pythia interface and Delphes, available upong request, or parse weights\"\n \" from the LHE file!\"\n )\n else:\n n_events = _get_n_events(tree)\n logger.debug(\"Found %s events\", n_events)\n\n # Get all particle properties\n if use_generator_truth:\n photons_all_events = _get_particles_truth(tree, acceptance_pt_min_a, acceptance_eta_max_a, [22])\n electrons_all_events = _get_particles_truth(tree, acceptance_pt_min_a, acceptance_eta_max_a, [11, -11])\n muons_all_events = _get_particles_truth(tree, acceptance_pt_min_a, acceptance_eta_max_a, [13, -13])\n leptons_all_events = _get_particles_truth_leptons(\n tree, acceptance_pt_min_e, acceptance_eta_max_e, acceptance_pt_min_mu, acceptance_eta_max_mu\n )\n jets_all_events = _get_particles_truth_jets(tree, acceptance_pt_min_j, acceptance_eta_max_j)\n met_all_events = _get_particles_truth_met(tree)\n\n else:\n photons_all_events = _get_particles_photons(tree, acceptance_pt_min_a, acceptance_eta_max_a)\n electrons_all_events = _get_particles_charged(\n tree, \"Electron\", 0.000511, -11, acceptance_pt_min_e, acceptance_eta_max_e\n )\n muons_all_events = _get_particles_charged(tree, \"Muon\", 0.105, -13, acceptance_pt_min_mu, acceptance_eta_max_mu)\n leptons_all_events = _get_particles_leptons(\n tree, acceptance_pt_min_e, acceptance_eta_max_e, acceptance_pt_min_mu, acceptance_eta_max_mu\n )\n jets_all_events = _get_particles_jets(tree, acceptance_pt_min_j, acceptance_eta_max_j)\n met_all_events = _get_particles_met(tree)\n\n # Prepare variables\n def get_objects(ievent):\n\n\n visible_momentum = MadMinerParticle()\n for p in (\n electrons_all_events[ievent]\n + jets_all_events[ievent]\n + muons_all_events[ievent]\n + photons_all_events[ievent]\n ):\n visible_momentum += p\n all_momentum = visible_momentum + met_all_events[ievent][0]\n\n objects = math_commands()\n objects.update(\n {\n \"e\": electrons_all_events[ievent],\n \"j\": jets_all_events[ievent],\n \"a\": photons_all_events[ievent],\n \"mu\": muons_all_events[ievent],\n \"l\": leptons_all_events[ievent],\n \"met\": met_all_events[ievent][0],\n \"visible\": visible_momentum,\n \"all\": all_momentum,\n \"boost_to_com\": lambda momentum: momentum.boost(all_momentum.boost_vector()),\n }\n )\n\n ##################### PREPARE FUNCTIONS TO FIND BEST ZZ CANDIDATE #####################\n\n #find same flavour opposite sign lepton pairs,\n #given the list of electrons or muons in an event\n #returns all possible SFOS pairs ([pos_idx, neg_idx],...)\n #which satisfy invariant mass cuts\n def find_Z_cand(cand_list, part_list):\n #positively and negatively charged leptons, and their\n idx_pos = []\n cand_pos = []\n idx_neg = []\n cand_neg = []\n for idx, (is_cand, part) in enumerate(zip(cand_list, part_list)):\n #checking if the lepton is a candidate\n if part.charge > 0:\n idx_pos.append(idx)\n cand_pos.append(is_cand)\n if part.charge < 0:\n idx_neg.append(idx)\n cand_neg.append(is_cand)\n\n z_cand_list = []\n for candpair, pair in zip(itertools.product(cand_pos, cand_neg), itertools.product(idx_pos, idx_neg)):\n iscand = candpair[0]*candpair[1] #1 only if both are candidates\n #cut invariant mass\n invm = (part_list[pair[0]] + part_list[pair[1]]).m\n if invm < 120 and invm > 12:\n z_cand_list.append([pair[0],pair[1]])\n\n return z_cand_list #[[pos_idx,neg_idx], [pos_idx,neg_idx], ...]\n\n #find pairs of SFOS pairs with no leptons in common\n #keep track of their different flavours\n #order of Z1 and Z2 is not important (each only counted once)\n def find_ZZ_cand(Z_cand_e_list, Z_cand_mu_list):\n ZZ_cand_ee = []; ZZ_cand_mm = []; ZZ_cand_em = []\n #same flavour e\n for Zcand1,Zcand2 in itertools.product(Z_cand_e_list,Z_cand_e_list):\n if not any(x in Zcand1 for x in Zcand2):\n ZZ_cand_ee.append([Zcand1[0], Zcand1[1], Zcand2[0], Zcand2[1]])\n\n #same flavour mu\n for Zcand1,Zcand2 in itertools.product(Z_cand_mu_list,Z_cand_mu_list):\n if not any(x in Zcand1 for x in Zcand2):\n ZZ_cand_mm.append([Zcand1[0], Zcand1[1], Zcand2[0], Zcand2[1]])\n\n #different flavour\n for Zcand1,Zcand2 in itertools.product(Z_cand_e_list,Z_cand_mu_list):\n ZZ_cand_em.append([Zcand1[0], Zcand1[1], Zcand2[0], Zcand2[1]])\n\n return ZZ_cand_ee, ZZ_cand_mm, ZZ_cand_em\n\n #return the list of particles in the correct order:\n #first list with flavour of first Z, second flavour of second Z\n def set_flavours_lists(part_list_e, part_list_mu, flavours):\n if flavours == \"ee\":\n part_list1 = part_list_e\n part_list2 = part_list_e\n elif flavours == \"mm\":\n part_list1 = part_list_mu\n part_list2 = part_list_mu\n elif flavours == \"em\":\n part_list1 = part_list_e\n part_list2 = part_list_mu\n elif flavours == \"me\":\n part_list1 = part_list_mu\n part_list2 = part_list_e\n else:\n print(\"set_flavours_lists: flavour not valid: choose between ee, mm, em\")\n return\n return part_list1, part_list2\n\n #return the leptons corresponding to the index in ZZcand\n #taking into account the flavours\n def ZZidx_to_leps(ZZcand, part_list_e, part_list_mu, flavours):\n part_list1, part_list2 = set_flavours_lists(part_list_e, part_list_mu, flavours)\n leps = [part_list1[ZZcand[0]], part_list1[ZZcand[1]], part_list2[ZZcand[2]], part_list2[ZZcand[3]]]\n return leps\n\n #reorder the two Z in each pair: first the one with closest mass to Z\n #keep track of the possible swapping in case of different flavours\n def Z1Z2_ordering(ZZcand, part_list_e, part_list_mu, flavours):\n leps = ZZidx_to_leps(ZZcand, part_list_e, part_list_mu, flavours)\n #compute invariant masses of each Z\n mz_p1 = (leps[0] + leps[1]).m\n mz_p2 = (leps[2] + leps[3]).m\n #order accordingly to closest mass to Z mass\n if min([mz_p1,mz_p2], key=lambda x:abs(x-91.2), default=-1) == mz_p1:\n z1z2 = ZZcand\n swapped = False\n else:\n z1z2 = [ZZcand[2],ZZcand[3],ZZcand[0],ZZcand[1]]\n swapped = True\n return(z1z2, swapped)\n\n #apply cuts to ZZ candidate\n #consider differently the case of same flavour ZZ\n def ZZ_cuts(ZZcand, part_list_e, part_list_mu, flavours, isSF):\n leps = ZZidx_to_leps(ZZcand, part_list_e, part_list_mu, flavours)\n #Z1 mass\n mz1 = (leps[0] + leps[1]).m\n if not mz1 > 40:\n #print(\"fail mz1 mass cut\")\n return False\n #leptons pt\n leps_pt_sort = sorted(leps, key=lambda x:x.pt)\n if not (leps_pt_sort[3].pt > 20 and leps_pt_sort[2].pt > 10):\n #print(\"fail leptons pt cut\")\n #print(\"leptons pt: \", [a.pt for a in leps_pt_sort])\n return False\n #OS invariant mass (pos, neg, pos, neg)\n mza = (leps[0]+leps[3]).m\n mzb = (leps[1]+leps[2]).m\n mz2 = (leps[2]+leps[3]).m\n if not (mza > 4 and mzb > 4 and mz2 > 4):\n #print(\"fail os cut\")\n return False\n #4l invariant mass\n m4l = (leps[0]+leps[1]+leps[2]+leps[3]).m\n #print(\"m4l: \", m4l)\n if not m4l>70:\n #print(\"fail m4l cut\")\n return False\n #same flavour cut\n if isSF == True:\n mz_pdg = 91.2\n mzab_ord = [mza, mzb] if min([mza,mzb], key=lambda x:abs(x-mz_pdg)) == mza else [mzb,mza]\n if (abs(mzab_ord[0]-mz_pdg) < abs(mz1-mz_pdg) and mzb < mzab_ord[0]):\n #print(\"fail SF cut\")\n return False\n #if candidate passes all cuts\n return True\n\n #choose ZZ candidate for which Z1 has mass closest to Z\n #keep track of the flavour of Z1 and Z2\n def choose_final_ZZ(ZZlist, part_list_e, part_list_mu, flavourslist):\n if len(ZZlist) == 1:\n return ZZlist[0], flavourslist[0]\n else:\n mz1list = []\n for ZZcand, flavours in zip(ZZlist,flavourslist):\n part_list1, part_list2 = set_flavours_lists(part_list_e, part_list_mu, flavours)\n mz1 = (part_list1[ZZcand[0]] + part_list1[ZZcand[1]]).m\n mz1list.append(mz1)\n mz1min = min(mz1list, key=lambda x:abs(x-91.2))\n idx = mz1list.index(mz1min)\n return ZZlist[idx], flavourslist[idx]\n\n ##################### MAIN CODE TO FIND BEST ZZ CANDIDATE #####################\n #default values\n isZZcand = 0\n lep1 = MadMinerParticle(); lep2 = MadMinerParticle(); lep3 = MadMinerParticle(); lep4 = MadMinerParticle()\n\n #list of candidates electrons/muons: 1 if candidate, 0 if not\n candidate_es = np.ones(len(objects[\"e\"]))\n candidate_mus = np.ones(len(objects[\"mu\"]))\n #print(len(objects[\"e\"]), len(objects[\"mu\"]))\n\n #find candidate leptons: eta and pt cuts (to be checked)\n for idx, el in enumerate(objects[\"e\"]):\n if not (abs(el.eta) < 2.5 and el.pt > 7):\n candidate_es[idx] = 0\n for idx, mu in enumerate(objects[\"mu\"]):\n if not (abs(mu.eta) < 2.4 and mu.pt > 5):\n candidate_mus[idx] = 0\n\n #find Z candidates\n e_Z_cand = find_Z_cand(candidate_es, objects[\"e\"])\n mu_Z_cand = find_Z_cand(candidate_mus, objects[\"mu\"])\n\n #find ZZ candidates\n ZZ_cand_ee_list, ZZ_cand_mm_list, ZZ_cand_em_list = find_ZZ_cand(e_Z_cand,mu_Z_cand)\n \n #initialise lists for ZZ candidates which pass cuts, and keep track of flavours\n ZZ_cands_final = []\n ZZ_cands_final_flavours = []\n\n #same flavours, electrons\n for ZZ_cand_ee in ZZ_cand_ee_list:\n ZZ_cand_ee, swapped = Z1Z2_ordering(ZZ_cand_ee, objects[\"e\"], objects[\"mu\"], flavours=\"ee\")\n #apply cuts\n if ZZ_cuts(ZZ_cand_ee, objects[\"e\"], objects[\"mu\"], flavours=\"ee\", isSF=True) == True:\n ZZ_cands_final.append(ZZ_cand_ee)\n ZZ_cands_final_flavours.append(\"ee\")\n #same flavours, muons\n for ZZ_cand_mm in ZZ_cand_mm_list:\n ZZ_cand_mm, swapped = Z1Z2_ordering(ZZ_cand_mm, objects[\"e\"], objects[\"mu\"], flavours=\"mm\")\n #apply cuts\n if ZZ_cuts(ZZ_cand_mm, objects[\"e\"], objects[\"mu\"], flavours=\"mm\", isSF=True) == True:\n ZZ_cands_final.append(ZZ_cand_mm)\n ZZ_cands_final_flavours.append(\"mm\")\n #different flavours\n for ZZ_cand_em in ZZ_cand_em_list:\n ZZ_cand_em, swapped = Z1Z2_ordering(ZZ_cand_em, objects[\"e\"], objects[\"mu\"], flavours=\"em\")\n #apply cuts, careful when swapping em/me\n flavours_OF = \"em\" if swapped==False else \"me\"\n if ZZ_cuts(ZZ_cand_em, objects[\"e\"], objects[\"mu\"], flavours=flavours_OF, isSF=False) == True:\n ZZ_cands_final.append(ZZ_cand_em)\n ZZ_cands_final_flavours.append(flavours_OF)\n\n #find final best ZZ candidate\n #if more than one ZZ candidate is left: choose the one with Z1 mass closest to MZ\n\n def printlep(lep, name):\n #print(name, \" = [\", lep.px, \",\", lep.py, \",\", lep.pz, \"]\")\n print(\"[\", lep.e,\",\", lep.px, \",\", lep.py, \",\", lep.pz, \"]\")\n return\n \n\n if len(ZZ_cands_final) > 0:\n isZZcand = 1\n ZZfinal, flavours = choose_final_ZZ(ZZ_cands_final, objects[\"e\"], objects[\"mu\"], ZZ_cands_final_flavours)\n lep1, lep2, lep3, lep4 = ZZidx_to_leps(ZZfinal, objects[\"e\"], objects[\"mu\"], flavours)\n #print(\"chosen leptons: (flavours\", flavours)\n #for lep, nlep in zip([lep1,lep2,lep3,lep4],[\"a\",\"b\",\"c\",\"d\"]):\n #printlep(lep, nlep)\n #print((lep1+lep2+lep3+lep4).m)\n #print((lep1+lep2).m, (lep3+lep4).m)\n\n #print(\"original leptons: e\")\n #for idx, lep in enumerate(objects[\"e\"]):\n #nlep = \"ne\" + str(idx)\n #printlep(lep, nlep)\n #print(\"original leptons: mu\")\n #for idx, lep in enumerate(objects[\"mu\"]):\n #nlep = \"nmu\" + str(idx)\n #printlep(lep, nlep)\n\n\n #logger.debug(\"Value of isZZcand: %d\", isZZcand)\n #debugging\n #print(len(objects[\"e\"]), len(objects[\"mu\"]))\n\n #if(len(ZZ_cand_ee_list) + len(ZZ_cand_mm_list) + len(ZZ_cand_em_list)) >= 1:\n #print(len(objects[\"e\"]), len(objects[\"mu\"]))\n #if isZZcand != 1:\n #print(\"no ZZ cand found after cuts\")\n #else:\n #print(\"ok candidate and found\")\n\n #update objects dictionary\n objects.update(\n {\n \"isZZcand\": isZZcand,\n \"lep1ZZ\": lep1,\n \"lep2ZZ\": lep2,\n \"lep3ZZ\": lep3,\n \"lep4ZZ\": lep4,\n }\n )\n return objects\n\n # Observations\n observable_values = OrderedDict()\n\n for obs_name, obs_definition in six.iteritems(observables):\n values_this_observable = []\n\n # Loop over events\n for event in range(n_events):\n variables = get_objects(event)\n\n if isinstance(obs_definition, six.string_types):\n try:\n values_this_observable.append(eval(obs_definition, variables))\n except (SyntaxError, NameError, TypeError, ZeroDivisionError, IndexError):\n default = observables_defaults[obs_name]\n if default is None:\n default = np.nan\n values_this_observable.append(default)\n else:\n try:\n values_this_observable.append(\n obs_definition(\n leptons_all_events[event],\n photons_all_events[event],\n jets_all_events[event],\n met_all_events[event][0],\n )\n )\n except RuntimeError:\n default = observables_defaults[obs_name]\n if default is None:\n default = np.nan\n values_this_observable.append(default)\n\n values_this_observable = np.array(values_this_observable, dtype=np.float)\n observable_values[obs_name] = values_this_observable\n\n logger.debug(\" First 10 values for observable %s:\\n%s\", obs_name, values_this_observable[:10])\n\n # Cuts\n cut_values = []\n\n for cut, default_pass in zip(cuts, cuts_default_pass):\n values_this_cut = []\n\n # Loop over events\n for event in range(n_events):\n variables = get_objects(event)\n\n for obs_name in observable_values:\n variables[obs_name] = observable_values[obs_name][event]\n\n try:\n values_this_cut.append(eval(cut, variables))\n except (SyntaxError, NameError, TypeError, ZeroDivisionError, IndexError):\n values_this_cut.append(default_pass)\n\n values_this_cut = np.array(values_this_cut, dtype=np.bool)\n cut_values.append(values_this_cut)\n\n # Check for existence of required observables\n combined_filter = None\n\n for obs_name, obs_required in six.iteritems(observables_required):\n if obs_required:\n this_filter = np.isfinite(observable_values[obs_name])\n n_pass = np.sum(this_filter)\n n_fail = np.sum(np.invert(this_filter))\n\n logger.debug(\" %s / %s events pass required observable %s\", n_pass, n_pass + n_fail, obs_name)\n\n if combined_filter is None:\n combined_filter = this_filter\n else:\n combined_filter = np.logical_and(combined_filter, this_filter)\n\n # Check cuts\n for cut, values_this_cut in zip(cuts, cut_values):\n n_pass = np.sum(values_this_cut)\n n_fail = np.sum(np.invert(values_this_cut))\n\n logger.debug(\" %s / %s events pass cut %s\", n_pass, n_pass + n_fail, cut)\n\n if combined_filter is None:\n combined_filter = values_this_cut\n else:\n combined_filter = np.logical_and(combined_filter, values_this_cut)\n\n # Apply filter\n if combined_filter is not None:\n n_pass = np.sum(combined_filter)\n n_fail = np.sum(np.invert(combined_filter))\n\n if n_pass == 0:\n logger.warning(\" No observations remainining!\")\n\n return None, None, combined_filter\n\n logger.info(\" %s / %s events pass everything\", n_pass, n_pass + n_fail)\n\n for obs_name in observable_values:\n observable_values[obs_name] = observable_values[obs_name][combined_filter]\n\n if weights is not None:\n weights = weights[:, combined_filter]\n\n # Wrap weights\n if weights is None:\n weights_dict = None\n else:\n weights_dict = OrderedDict()\n for weight_label, this_weights in zip(weight_labels, weights):\n weights_dict[weight_label] = this_weights\n\n # Delete Delphes file\n if delete_delphes_sample_file:\n logger.debug(\" Deleting %s\", delphes_sample_file)\n os.remove(delphes_sample_file)\n\n return observable_values, weights_dict, combined_filter\n\n\ndef _get_n_events(tree):\n es = tree.array(\"Event\")\n n_events = len(es)\n return n_events\n\n\ndef _get_particles_truth(tree, pt_min, eta_max, included_pdgids=None):\n es = tree.array(\"Particle.E\")\n pts = tree.array(\"Particle.PT\")\n etas = tree.array(\"Particle.Eta\")\n phis = tree.array(\"Particle.Phi\")\n charges = tree.array(\"Particle.Charge\")\n pdgids = tree.array(\"Particle.PID\")\n\n all_particles = []\n\n for ievent in range(len(pts)):\n event_particles = []\n\n for e, pt, eta, phi, pdgid in zip(es[ievent], pts[ievent], etas[ievent], phis[ievent], pdgids[ievent]):\n\n if pt_min is not None and pt < pt_min:\n continue\n if eta_max is not None and abs(eta) > eta_max:\n continue\n if (included_pdgids is not None) and (not pdgid in included_pdgids):\n continue\n\n particle = MadMinerParticle()\n particle.setptetaphie(pt, eta, phi, e)\n particle.set_pdgid(pdgid)\n event_particles.append(particle)\n\n all_particles.append(event_particles)\n\n return all_particles\n\n\ndef _get_particles_charged(tree, name, mass, pdgid_positive_charge, pt_min, eta_max):\n pts = tree.array(name + \".PT\")\n etas = tree.array(name + \".Eta\")\n phis = tree.array(name + \".Phi\")\n charges = tree.array(name + \".Charge\")\n\n all_particles = []\n\n for ievent in range(len(pts)):\n event_particles = []\n\n for pt, eta, phi, charge in zip(pts[ievent], etas[ievent], phis[ievent], charges[ievent]):\n\n if pt_min is not None and pt < pt_min:\n continue\n if eta_max is not None and abs(eta) > eta_max:\n continue\n\n pdgid = pdgid_positive_charge if charge >= 0.0 else -pdgid_positive_charge\n\n particle = MadMinerParticle()\n particle.setptetaphim(pt, eta, phi, mass)\n particle.set_pdgid(pdgid)\n event_particles.append(particle)\n\n all_particles.append(event_particles)\n\n return all_particles\n\n\ndef _get_particles_leptons(tree, pt_min_e, eta_max_e, pt_min_mu, eta_max_mu):\n pt_mu = tree.array(\"Muon.PT\")\n eta_mu = tree.array(\"Muon.Eta\")\n phi_mu = tree.array(\"Muon.Phi\")\n charge_mu = tree.array(\"Muon.Charge\")\n pt_e = tree.array(\"Electron.PT\")\n eta_e = tree.array(\"Electron.Eta\")\n phi_e = tree.array(\"Electron.Phi\")\n charge_e = tree.array(\"Electron.Charge\")\n\n all_particles = []\n\n for ievent in range(len(pt_mu)):\n event_particles = []\n\n # Combined muons and electrons\n event_pts = np.concatenate((pt_mu[ievent], pt_e[ievent]))\n event_etas = np.concatenate((eta_mu[ievent], eta_e[ievent]))\n event_phis = np.concatenate((phi_mu[ievent], phi_e[ievent]))\n event_masses = np.concatenate((0.105 * np.ones_like(pt_mu[ievent]), 0.000511 * np.ones_like(pt_e[ievent])))\n event_charges = np.concatenate((charge_mu[ievent], charge_e[ievent]))\n event_pdgid_positive_charges = np.concatenate(\n (-13 * np.ones_like(pt_mu[ievent], dtype=np.int), -11 * np.ones_like(pt_e[ievent], dtype=np.int))\n )\n\n # Sort by descending pT\n order = np.argsort(-1.0 * event_pts, axis=None)\n event_pts = event_pts[order]\n event_etas = event_etas[order]\n event_phis = event_phis[order]\n\n # Create particles\n for pt, eta, phi, mass, charge, pdgid_positive_charge in zip(\n event_pts, event_etas, event_phis, event_masses, event_charges, event_pdgid_positive_charges\n ):\n\n pdgid = pdgid_positive_charge if charge >= 0.0 else -pdgid_positive_charge\n\n if abs(int(pdgid)) == 11:\n if pt_min_e is not None and pt < pt_min_e:\n continue\n if eta_max_e is not None and abs(eta) > eta_max_e:\n continue\n\n elif abs(int(pdgid)) == 13:\n if pt_min_mu is not None and pt < pt_min_mu:\n continue\n if eta_max_mu is not None and abs(eta) > eta_max_mu:\n continue\n\n else:\n logger.warning(\"Delphes ROOT file has lepton with PDG ID %s, ignoring it\", pdgid)\n continue\n\n particle = MadMinerParticle()\n particle.setptetaphim(pt, eta, phi, mass)\n particle.set_pdgid(pdgid)\n event_particles.append(particle)\n\n all_particles.append(event_particles)\n\n return all_particles\n\n\ndef _get_particles_truth_leptons(tree, pt_min_e, eta_max_e, pt_min_mu, eta_max_mu):\n es = tree.array(\"Particle.E\")\n pts = tree.array(\"Particle.PT\")\n etas = tree.array(\"Particle.Eta\")\n phis = tree.array(\"Particle.Phi\")\n charges = tree.array(\"Particle.Charge\")\n pdgids = tree.array(\"Particle.PID\")\n\n all_particles = []\n\n for ievent in range(len(pts)):\n event_particles = []\n\n for e, pt, eta, phi, pdgid in zip(es[ievent], pts[ievent], etas[ievent], phis[ievent], pdgids[ievent]):\n if pdgid not in [11, 13, -11, -13]:\n continue\n if pdgid in [11, -11] and (pt_min_e is not None and pt < pt_min_e):\n continue\n if pdgid in [11, -11] and (eta_max_e is not None and abs(eta) > eta_max_e):\n continue\n if pdgid in [13, -13] and (pt_min_mu is not None and pt < pt_min_mu):\n continue\n if pdgid in [13, -13] and (eta_max_mu is not None and abs(eta) > eta_max_mu):\n continue\n\n particle = MadMinerParticle()\n particle.setptetaphie(pt, eta, phi, e)\n particle.set_pdgid(pdgid)\n event_particles.append(particle)\n\n all_particles.append(event_particles)\n\n return all_particles\n\n\ndef _get_particles_photons(tree, pt_min, eta_max):\n pts = tree.array(\"Photon.PT\")\n etas = tree.array(\"Photon.Eta\")\n phis = tree.array(\"Photon.Phi\")\n es = tree.array(\"Photon.E\")\n\n all_particles = []\n\n for ievent in range(len(pts)):\n event_particles = []\n\n for pt, eta, phi, e in zip(pts[ievent], etas[ievent], phis[ievent], es[ievent]):\n\n if pt_min is not None and pt < pt_min:\n continue\n if eta_max is not None and abs(eta) > eta_max:\n continue\n\n particle = MadMinerParticle()\n particle.setptetaphie(pt, eta, phi, e)\n particle.set_pdgid(22)\n event_particles.append(particle)\n\n all_particles.append(event_particles)\n\n return all_particles\n\n\ndef _get_particles_jets(tree, pt_min, eta_max):\n pts = tree.array(\"Jet.PT\")\n etas = tree.array(\"Jet.Eta\")\n phis = tree.array(\"Jet.Phi\")\n masses = tree.array(\"Jet.Mass\")\n try:\n tau_tags = tree.array(\"Jet.TauTag\")\n except:\n logger.warning(\"Did not find tau-tag information in Delphes ROOT file.\")\n tau_tags = [0 for _ in range(len(pts))]\n try:\n b_tags = tree.array(\"Jet.BTag\")\n except:\n logger.warning(\"Did not find b-tag information in Delphes ROOT file.\")\n b_tags = [0 for _ in range(len(pts))]\n\n all_particles = []\n\n for ievent in range(len(pts)):\n event_particles = []\n\n for pt, eta, phi, mass, tau_tag, b_tag in zip(\n pts[ievent], etas[ievent], phis[ievent], masses[ievent], tau_tags[ievent], b_tags[ievent]\n ):\n\n if pt_min is not None and pt < pt_min:\n continue\n if eta_max is not None and abs(eta) > eta_max:\n continue\n\n particle = MadMinerParticle()\n particle.setptetaphim(pt, eta, phi, mass)\n particle.set_pdgid(9)\n particle.set_tags(tau_tag >= 1, b_tag >= 1, False)\n event_particles.append(particle)\n\n all_particles.append(event_particles)\n\n return all_particles\n\n\ndef _get_particles_truth_jets(tree, pt_min, eta_max):\n pts = tree.array(\"GenJet.PT\")\n etas = tree.array(\"GenJet.Eta\")\n phis = tree.array(\"GenJet.Phi\")\n masses = tree.array(\"GenJet.Mass\")\n try:\n tau_tags = tree.array(\"GenJet.TauTag\")\n except:\n logger.warning(\"Did not find tau-tag information for GenJets in Delphes ROOT file.\")\n tau_tags = [0 for _ in range(len(pts))]\n try:\n b_tags = tree.array(\"GenJet.BTag\")\n except:\n logger.warning(\"Did not find b-tag information for GenJets in Delphes ROOT file.\")\n b_tags = [0 for _ in range(len(pts))]\n\n all_particles = []\n\n for ievent in range(len(pts)):\n event_particles = []\n\n for pt, eta, phi, mass, tau_tag, b_tag in zip(\n pts[ievent], etas[ievent], phis[ievent], masses[ievent], tau_tags[ievent], b_tags[ievent]\n ):\n\n if pt_min is not None and pt < pt_min:\n continue\n if eta_max is not None and abs(eta) > eta_max:\n continue\n\n particle = MadMinerParticle()\n particle.setptetaphim(pt, eta, phi, mass)\n particle.set_pdgid(9)\n particle.set_tags(tau_tag >= 1, b_tag >= 1, False)\n event_particles.append(particle)\n\n all_particles.append(event_particles)\n\n return all_particles\n\n\ndef _get_particles_truth_met(tree):\n mets = tree.array(\"GenMissingET.MET\")\n phis = tree.array(\"GenMissingET.Phi\")\n\n all_particles = []\n\n for ievent in range(len(mets)):\n event_particles = []\n\n for met, phi in zip(mets[ievent], phis[ievent]):\n particle = MadMinerParticle()\n particle.setptetaphim(met, 0.0, phi, 0.0)\n particle.set_pdgid(0)\n event_particles.append(particle)\n\n all_particles.append(event_particles)\n\n return all_particles\n\n\ndef _get_particles_met(tree):\n mets = tree.array(\"MissingET.MET\")\n phis = tree.array(\"MissingET.Phi\")\n\n all_particles = []\n\n for ievent in range(len(mets)):\n event_particles = []\n\n for met, phi in zip(mets[ievent], phis[ievent]):\n particle = MadMinerParticle()\n particle.setptetaphim(met, 0.0, phi, 0.0)\n particle.set_pdgid(0)\n event_particles.append(particle)\n\n all_particles.append(event_particles)\n\n return all_particles\n"
]
| [
[
"numpy.ones_like",
"numpy.isfinite",
"numpy.invert",
"numpy.logical_and",
"numpy.concatenate",
"numpy.argsort",
"numpy.array",
"numpy.sum"
]
]
|
Yard1/lightgbm_ray | [
"234e809f2903c8f55d34a88aebd7a232a1e7337f"
]
| [
"lightgbm_ray/tests/test_tune.py"
]
| [
"import os\nimport shutil\nimport tempfile\nimport unittest\nfrom unittest.mock import patch\n\nimport numpy as np\n\nimport ray\nfrom ray import tune\ntry:\n from ray.tune.integration.lightgbm import \\\n TuneReportCallback as OrigTuneReportCallback, \\\n TuneReportCheckpointCallback as OrigTuneReportCheckpointCallback\nexcept ImportError:\n OrigTuneReportCallback = OrigTuneReportCheckpointCallback = \\\n None\n\nfrom lightgbm_ray import RayDMatrix, train, RayParams, RayShardingMode\nfrom lightgbm_ray.tune import TuneReportCallback,\\\n TuneReportCheckpointCallback, _try_add_tune_callback\n\n\nclass LightGBMRayTuneTest(unittest.TestCase):\n def setUp(self):\n repeat = 64 # Repeat data a couple of times for stability\n x = np.array([\n [1, 0, 0, 0], # Feature 0 -> Label 0\n [0, 1, 0, 0], # Feature 1 -> Label 1\n [0, 0, 1, 1], # Feature 2+3 -> Label 2\n [0, 0, 1, 0], # Feature 2+!3 -> Label 3\n ] * repeat)\n y = np.array([0, 1, 2, 3] * repeat)\n\n self.params = {\n \"lgbm\": {\n \"boosting\": \"gbdt\",\n \"objective\": \"multiclass\",\n \"num_class\": 4,\n \"random_state\": 1,\n \"tree_learner\": \"data\",\n \"metrics\": [\"multi_logloss\", \"multi_error\"]\n },\n \"num_boost_round\": tune.choice([1, 3])\n }\n\n def train_func(ray_params, callbacks=None, **kwargs):\n def _inner_train(config, checkpoint_dir):\n train_set = RayDMatrix(x, y, sharding=RayShardingMode.BATCH)\n train(\n config[\"lgbm\"],\n dtrain=train_set,\n ray_params=ray_params,\n num_boost_round=config[\"num_boost_round\"],\n evals=[(train_set, \"train\")],\n callbacks=callbacks,\n **kwargs)\n\n return _inner_train\n\n self.train_func = train_func\n self.experiment_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n ray.shutdown()\n shutil.rmtree(self.experiment_dir)\n\n # noinspection PyTypeChecker\n def testNumIters(self, init=True):\n \"\"\"Test that the number of reported tune results is correct\"\"\"\n if init:\n ray.init(num_cpus=8)\n ray_params = RayParams(cpus_per_actor=2, num_actors=2)\n analysis = tune.run(\n self.train_func(ray_params),\n config=self.params,\n resources_per_trial=ray_params.get_tune_resources(),\n num_samples=2)\n\n self.assertSequenceEqual(\n list(analysis.results_df[\"training_iteration\"]),\n list(analysis.results_df[\"config.num_boost_round\"]))\n\n def testNumItersClient(self):\n \"\"\"Test ray client mode\"\"\"\n ray.init(num_cpus=8)\n if ray.__version__ <= \"1.2.0\":\n self.skipTest(\"Ray client mocks do not work in Ray <= 1.2.0\")\n\n from ray.util.client.ray_client_helpers import ray_start_client_server\n\n self.assertFalse(ray.util.client.ray.is_connected())\n with ray_start_client_server():\n self.assertTrue(ray.util.client.ray.is_connected())\n self.testNumIters(init=False)\n\n @unittest.skipIf(OrigTuneReportCallback is None,\n \"integration.lightgbmnot yet in ray.tune\")\n def testReplaceTuneCheckpoints(self):\n \"\"\"Test if ray.tune.integration.lightgbm callbacks are replaced\"\"\"\n ray.init(num_cpus=4)\n # Report callback\n in_cp = [OrigTuneReportCallback(metrics=\"met\")]\n in_dict = {\"callbacks\": in_cp}\n\n with patch(\"lightgbm_ray.tune.is_session_enabled\") as mocked:\n mocked.return_value = True\n _try_add_tune_callback(in_dict)\n\n replaced = in_dict[\"callbacks\"][0]\n self.assertTrue(isinstance(replaced, TuneReportCallback))\n self.assertSequenceEqual(replaced._metrics, [\"met\"])\n\n # Report and checkpointing callback\n in_cp = [\n OrigTuneReportCheckpointCallback(metrics=\"met\", filename=\"test\")\n ]\n in_dict = {\"callbacks\": in_cp}\n\n with patch(\"lightgbm_ray.tune.is_session_enabled\") as mocked:\n mocked.return_value = True\n _try_add_tune_callback(in_dict)\n\n replaced = in_dict[\"callbacks\"][0]\n self.assertTrue(isinstance(replaced, TuneReportCheckpointCallback))\n self.assertSequenceEqual(replaced._report._metrics, [\"met\"])\n self.assertEqual(replaced._checkpoint._filename, \"test\")\n\n def testEndToEndCheckpointing(self):\n ray.init(num_cpus=4)\n ray_params = RayParams(cpus_per_actor=2, num_actors=1)\n analysis = tune.run(\n self.train_func(\n ray_params,\n callbacks=[TuneReportCheckpointCallback(frequency=1)]),\n config=self.params,\n resources_per_trial=ray_params.get_tune_resources(),\n num_samples=1,\n metric=\"train-multi_logloss\",\n mode=\"min\",\n log_to_file=True,\n local_dir=self.experiment_dir)\n\n self.assertTrue(os.path.exists(analysis.best_checkpoint))\n\n @unittest.skipIf(OrigTuneReportCallback is None,\n \"integration.lightgbmnot yet in ray.tune\")\n def testEndToEndCheckpointingOrigTune(self):\n ray.init(num_cpus=4)\n ray_params = RayParams(cpus_per_actor=2, num_actors=1)\n analysis = tune.run(\n self.train_func(\n ray_params, callbacks=[OrigTuneReportCheckpointCallback()]),\n config=self.params,\n resources_per_trial=ray_params.get_tune_resources(),\n num_samples=1,\n metric=\"train-multi_logloss\",\n mode=\"min\",\n log_to_file=True,\n local_dir=self.experiment_dir)\n\n self.assertTrue(os.path.exists(analysis.best_checkpoint))\n\n\nif __name__ == \"__main__\":\n import pytest\n import sys\n sys.exit(pytest.main([\"-v\", __file__]))\n"
]
| [
[
"numpy.array"
]
]
|
SumitM0432/Explicit-Content-Classifier-using-ResNet | [
"2a5de322b018afd5fa32b461704f3e9f1ac44a45"
]
| [
"engine.py"
]
| [
"import torch\nfrom tqdm import tqdm\nfrom time import time\n\ndef training_func(model, train_dataloader, val_dataloader, epochs, device, optimizer, criterion):\n # Training the model\n train_losses, val_losses = [], []\n steps = 0\n for epoch in tqdm(range(epochs)):\n \n # Taking the average loss or epoch loss\n correct_train = 0\n total_train = 0\n running_loss = 0\n\n start_time = time()\n iter_time = time()\n\n model.train()\n for i, (images, labels) in enumerate(train_dataloader):\n steps+=1\n images = images.to(device)\n labels = labels.to(device)\n \n # Model\n output = model(images)\n \n loss = criterion(output, labels)\n\n correct_train += (torch.max(output, dim=1)[1] == labels).sum()\n total_train += labels.size(0)\n \n # setting the gradient to zero or it will start accumulating\n optimizer.zero_grad()\n\n # Back prop\n loss.backward()\n \n # optimizer update the parameters\n optimizer.step()\n\n running_loss += loss.item()\n\n if steps % 200 == 0:\n print (f'Epoch [{epoch+1}]/[{epochs}]. Batch [{i+1}]/[{len(train_dataloader)}].', end = ' ')\n print (f'train loss {running_loss/steps:.3f}.', end = ' ')\n print (f'train_acc {(correct_train/ total_train) * 100:.3f}.', end = ' ')\n\n with torch.no_grad():\n model.eval()\n correct_val, total_val = 0, 0\n val_loss = 0\n\n for images, labels in val_dataloader:\n images = images.to(device)\n labels = labels.to(device)\n output = model(images)\n loss = criterion(output, labels)\n val_loss += loss.item()\n\n correct_val += (torch.max(output, dim=1)[1] == labels).sum()\n total_val += labels.size(0)\n\n print(f'Val loss {val_loss / len(val_dataloader):.3f}. Val acc {correct_val / total_val * 100:.3f}.', end=' ')\n print(f'Took {time() - iter_time:.3f} seconds')\n iter_time = time()\n\n train_losses.append(running_loss / total_train)\n val_losses.append(val_loss / total_val)\n\n print(f'Epoch took {time() - start_time}') \n # scheduler.step(average_loss)\n\n return model, train_losses, val_losses"
]
| [
[
"torch.no_grad",
"torch.max"
]
]
|
GregoryEHunter/generalization_to_OOD_category_viewpoint_combinations | [
"52aacbb3420639cae64ce65085c17b245e5ef865"
]
| [
"res/models/LONG_DECODER_COMBINED.py"
]
| [
"import torch\nimport torch.nn as nn\n\n\ndef conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n __constants__ = ['downsample']\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None):\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n if groups != 1 or base_width != 64:\n raise ValueError('BasicBlock only supports groups=1 and base_width=64')\n if dilation > 1:\n raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n __constants__ = ['downsample']\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None):\n super(Bottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n width = int(planes * (base_width / 64.)) * groups\n # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv1x1(inplanes, width)\n self.bn1 = norm_layer(width)\n self.conv2 = conv3x3(width, width, stride, groups, dilation)\n self.bn2 = norm_layer(width)\n self.conv3 = conv1x1(width, planes * self.expansion)\n self.bn3 = norm_layer(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,\n groups=1, width_per_group=64, replace_stride_with_dilation=None,\n norm_layer=None):\n super(ResNet, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self._norm_layer = norm_layer\n\n self.inplanes = 64\n self.dilation = 1\n if replace_stride_with_dilation is None:\n # each element in the tuple indicates if we should replace\n # the 2x2 stride with a dilated convolution instead\n replace_stride_with_dilation = [False, False, False]\n if len(replace_stride_with_dilation) != 3:\n raise ValueError(\"replace_stride_with_dilation should be None \"\n \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation))\n self.groups = groups\n self.base_width = width_per_group\n self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = norm_layer(self.inplanes)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2,\n dilate=replace_stride_with_dilation[0])\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2,\n dilate=replace_stride_with_dilation[1])\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2])\n\n print(self.inplanes)\n # self.inplanes = int((self.inplanes)/2)\n\n self.layer5_1 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2])\n\n # self.inplanes = int((self.inplanes)/2)\n\n self.layer5_2 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2])\n\n # self.inplanes = int((self.inplanes)/2)\n\n self.layer6_1 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2])\n\n # self.inplanes = int((self.inplanes)/2)\n\n self.layer6_2 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2])\n\n # self.inplanes = int((self.inplanes)/2)\n\n self.layer7_1 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2])\n\n # self.inplanes = int((self.inplanes)/2)\n\n self.layer7_2 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2])\n\n self.avgpools_1 = nn.AdaptiveAvgPool2d((1, 1))\n self.avgpools_2 = nn.AdaptiveAvgPool2d((1, 1))\n\n self.fc_1 = nn.Linear(512 * block.expansion, num_classes[0])\n self.fc_2 = nn.Linear(512 * block.expansion, num_classes[0])\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n # Zero-initialize the last BN in each residual branch,\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0)\n elif isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2.weight, 0)\n\n def _make_layer(self, block, planes, blocks, stride=1, dilate=False):\n norm_layer = self._norm_layer\n downsample = None\n previous_dilation = self.dilation\n if dilate:\n self.dilation *= stride\n stride = 1\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv1x1(self.inplanes, planes * block.expansion, stride),\n norm_layer(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, self.groups,\n self.base_width, previous_dilation, norm_layer))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes, groups=self.groups,\n base_width=self.base_width, dilation=self.dilation,\n norm_layer=norm_layer))\n\n return nn.Sequential(*layers)\n\n # def _make_copied_layers(self, count, block, planes, blocks, stride=1, dilate=False):\n # norm_layer = self._norm_layer\n # downsample = None\n # previous_dilation = self.dilation\n # if dilate:\n # self.dilation *= stride\n # stride = 1\n # if stride != 1 or self.inplanes != planes * block.expansion:\n # downsample = nn.Sequential(\n # conv1x1(self.inplanes, planes * block.expansion, stride),\n # norm_layer(planes * block.expansion),\n # )\n #\n #\n # branches = []\n # orig_in_planes = self.inplanes\n # for i in range(count):\n # self.inplanes = orig_in_planes\n # print('inplanes',self.inplanes)\n # layers = []\n # layers.append(block(self.inplanes, planes, stride, downsample, self.groups,\n # self.base_width, previous_dilation, norm_layer))\n # self.inplanes = planes * block.expansion\n # for _ in range(1, blocks):\n # layers.append(block(self.inplanes, planes, groups=self.groups,\n # base_width=self.base_width, dilation=self.dilation,\n # norm_layer=norm_layer))\n #\n # branch = nn.Sequential(*layers)\n # branches.append(branch)\n # return branches\n\n\n def _forward_impl(self, x):\n # See note [TorchScript super()]\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n\n x_5_1 = self.layer5_1(x)\n x_6_1 = self.layer6_1(x_5_1)\n x_7_1 = self.layer7_1(x_6_1)\n x_pools_1 = self.avgpools_1(x_7_1)\n x_flats_1 = torch.flatten(x_pools_1, 1)\n x_out_1 = self.fc_1(x_flats_1)\n\n x_5_2 = self.layer5_2(x)\n x_6_2 = self.layer6_2(x_5_2)\n x_7_2 = self.layer7_2(x_6_2)\n x_pools_2 = self.avgpools_2(x_7_2)\n x_flats_2 = torch.flatten(x_pools_2, 1)\n x_out_2 = self.fc_2(x_flats_2)\n\n\n return x_out_1, x_out_1, x_out_2, x_out_2\n\n def forward(self, x):\n return self._forward_impl(x)\n\n def get_activations(self, x, layer_name):\n\n activations_dict = {}\n\n x = self.conv1(x)\n if layer_name == 'conv1':\n activations_dict['trunk_conv1'] = x\n\n x = self.bn1(x)\n\n if layer_name == 'bn1':\n activations_dict['trunk_bn1'] = x\n\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n\n if layer_name == 'layer1':\n activations_dict['trunk_layer1'] = x\n\n x = self.layer2(x)\n if layer_name == 'layer2':\n activations_dict['trunk_layer2'] = x\n\n x_3 = [layer3(x) for layer3 in self.layer3s]\n\n if layer_name == 'layer3':\n for i in range(len(x_3)):\n activations_dict['branch_%s_layer3'%i] = x_3[i]\n\n x_4 = [self.layer4s[i](x_3[i]) for i in range(len(x_3))]\n\n if layer_name == 'layer4':\n for i in range(len(x_4)):\n activations_dict['branch_%s_layer4'%i] = x_4[i]\n\n x_pool = [self.avgpools[i](x_4[i]) for i in range(len(x_4))]\n if layer_name == 'avgpool':\n for i in range(len(x_pool)):\n activations_dict['branch_%s_avgpool'%i] = x_pool[i]\n\n x_flats = [torch.flatten(x_pool[i], 1) for i in range(len(x_pool))]\n\n if layer_name == 'flatten':\n for i in range(len(x_flats)):\n activations_dict['branch_%s_avgpool'%i] = x_flats[i]\n\n outs = [self.fcs[i](x_flats[i]) for i in range(len(x_flats))]\n if layer_name == 'fcs':\n for i in range(len(outs)):\n activations_dict['branch_%s_fcs'%i] = outs[i]\n\n if len(activations_dict.keys()) == 0:\n print('layer_name not valid, please check.')\n sys.exit()\n\n return activations_dict\n\n\ndef _resnet(arch, block, layers, pretrained, progress, **kwargs):\n model = ResNet(block, layers, **kwargs)\n# if pretrained:\n# state_dict = load_state_dict_from_url(model_urls[arch],\n# progress=progress)\n# model.load_state_dict(state_dict)\n return model\n\n\ndef resnet18(pretrained=False, progress=True, **kwargs):\n r\"\"\"ResNet-18 model from\n `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,\n **kwargs)\n"
]
| [
[
"torch.nn.Sequential",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.nn.AdaptiveAvgPool2d",
"torch.flatten",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_"
]
]
|
xmyqsh/fvcore | [
"364d1bb6f1ac66368dff710dee491422b8569695"
]
| [
"tests/test_transform.py"
]
| [
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nimport itertools\nimport numpy as np\nimport unittest\nfrom typing import Any, Tuple\nfrom PIL import Image\n\nfrom fvcore.transforms import transform as T\n\n\n# pyre-ignore-all-errors\nclass TestTransforms(unittest.TestCase):\n def test_register(self):\n \"\"\"\n Test register.\n \"\"\"\n dtype = \"int\"\n\n def add1(t, x):\n return x + 1\n\n def flip_sub_width(t, x):\n return x - t.width\n\n T.Transform.register_type(dtype, add1)\n T.HFlipTransform.register_type(dtype, flip_sub_width)\n\n transforms = T.TransformList(\n [\n T.ScaleTransform(0, 0, 0, 0, 0),\n T.CropTransform(0, 0, 0, 0),\n T.HFlipTransform(3),\n ]\n )\n self.assertEqual(transforms.apply_int(3), 2)\n\n with self.assertRaises(AssertionError):\n T.HFlipTransform.register_type(dtype, lambda x: 1)\n\n @staticmethod\n def BlendTransform_gt(img, *args) -> Tuple[np.ndarray, list]:\n \"\"\"\n Given the input array, return the expected output array and shape after\n applying the blend transformation.\n Args:\n imgs (array): image(s) array before the transform.\n args (list): list of arguments. Details can be found in test case.\n Returns:\n img (array): expected output array after apply the transformation.\n (list): expected shape of the output array.\n \"\"\"\n src_image, src_weight, dst_weight = args\n if img.dtype == np.uint8:\n img = img.astype(np.float32)\n img = src_weight * src_image + dst_weight * img\n img = np.clip(img, 0, 255).astype(np.uint8)\n else:\n img = src_weight * src_image + dst_weight * img\n return img, img.shape\n\n @staticmethod\n def CropTransform_gt(imgs, *args) -> Tuple[np.ndarray, list]:\n \"\"\"\n Given the input array, return the expected output array and shape after\n applying the crop transformation.\n Args:\n imgs (array): image(s) array before the transform.\n args (list): list of arguments. Details can be found in test case.\n Returns:\n img (array): expected output array after apply the transformation.\n (list): expected shape of the output array.\n \"\"\"\n x0, y0, w, h = args\n if len(imgs.shape) <= 3:\n ret = imgs[y0 : y0 + h, x0 : x0 + w]\n else:\n ret = imgs[..., y0 : y0 + h, x0 : x0 + w, :]\n return ret, ret.shape\n\n @staticmethod\n def GridSampleTransform_gt(imgs, *args) -> Tuple[np.ndarray, list]:\n \"\"\"\n Given the input array, return the expected output array and shape after\n applying the grid sampling transformation. Currently only dummy gt is\n prepared.\n Args:\n imgs (array): image(s) array before the transform.\n args (list): list of arguments. Details can be found in test case.\n Returns:\n img (array): expected output array after apply the transformation.\n (list): expected shape of the output array.\n \"\"\"\n return imgs, imgs.shape\n\n @staticmethod\n def HFlipTransform_gt(imgs, *args) -> Tuple[np.ndarray, list]:\n \"\"\"\n Given the input array, return the expected output array and shape after\n applying the horizontal flip transformation.\n Args:\n imgs (array): image(s) array before the transform.\n args (list): list of arguments. Details can be found in test case.\n Returns:\n img (array): expected output array after apply the transformation.\n (list): expected shape of the output array.\n \"\"\"\n\n if len(imgs.shape) <= 3:\n # HxW or HxWxC.\n return imgs[:, ::-1], imgs.shape\n else:\n # TxHxWxC.\n return imgs[:, :, ::-1], imgs.shape\n\n @staticmethod\n def NoOpTransform_gt(imgs, *args) -> Tuple[np.ndarray, list]:\n \"\"\"\n Given the input array, return the expected output array and shape after\n applying no transformation.\n Args:\n imgs (array): image(s) array before the transform.\n args (list): list of arguments. Details can be found in test case.\n Returns:\n img (array): expected output array after apply the transformation.\n (list): expected shape of the output array.\n\n \"\"\"\n return imgs, imgs.shape\n\n @staticmethod\n def ScaleTransform_gt(imgs, *args) -> Tuple[Any, Any]:\n \"\"\"\n Given the input array, return the expected output array and shape after\n applying the resize transformation.\n Args:\n imgs (array): image(s) array before the transform.\n args (list): list of arguments. Details can be found in test case.\n Returns:\n img (array): expected output array after apply the transformation.\n None means does not have expected output array for sanity check.\n (list): expected shape of the output array. None means does not have\n expected output shape for sanity check.\n \"\"\"\n _INTERP_MODE_PYTORCH_TO_PIL = {\n \"nearest\": Image.NEAREST,\n \"bilinear\": Image.BILINEAR,\n \"bicubic\": Image.BICUBIC,\n }\n\n h, w, new_h, new_w, interp = args\n # D2 support input dtype of uint8, when the input shape is HxW or HxWxC.\n # Use these supported cases as sanity check.\n if imgs.dtype == np.uint8 and len(imgs.shape) <= 3:\n pil_image = Image.fromarray(imgs)\n pil_image = pil_image.resize(\n (new_w, new_h), _INTERP_MODE_PYTORCH_TO_PIL[interp]\n )\n ret = np.asarray(pil_image)\n return ret, ret.shape\n else:\n return None, None\n\n @staticmethod\n def _img_provider() -> Tuple[np.ndarray, type, str]:\n \"\"\"\n Provide different image inputs as test cases.\n Returns:\n (np.ndarray): an image to test on.\n (type): type of the current array.\n (str): string to represent the shape. Options include `hw`, `hwc`,\n `nhwc`.\n\n \"\"\"\n N, C, H, W = 8, 3, 10, 10\n # Prepare mesh grid as test case.\n img_h_grid, img_w_grid = np.mgrid[0 : H * 2 : 2, 0 : W * 2 : 2]\n img_hw_grid = img_h_grid * W + img_w_grid\n img_hwc_grid = np.repeat(img_hw_grid[:, :, None], C, axis=2)\n img_nhwc_grid = np.repeat(img_hwc_grid[None, :, :, :], N, axis=0)\n for n in range(img_nhwc_grid.shape[0]):\n img_nhwc_grid[n] = img_nhwc_grid[n] + n\n\n # Prepare random array as test case.\n np.random.seed(0)\n img_hw_random = np.random.rand(H, W)\n img_hwc_random = np.random.rand(H, W, C)\n img_nhwc_random = np.random.rand(N, H, W, C)\n\n for array_type, input_shape, init in itertools.product(\n [np.uint8, np.float32], [\"hw\", \"hwc\", \"nhwc\"], [\"grid\", \"random\"]\n ):\n yield locals()[\"img_{}_{}\".format(input_shape, init)].astype(\n array_type\n ), array_type, input_shape\n\n def test_blend_transforms(self):\n \"\"\"\n Test BlendTransform.\n \"\"\"\n _trans_name = \"BlendTransform\"\n blend_src_hw = np.ones((10, 10))\n blend_src_hwc = np.ones((10, 10, 3))\n blend_src_nhwc = np.ones((8, 10, 10, 3))\n\n for img, array_type, shape_str in TestTransforms._img_provider():\n blend_src = locals()[\"blend_src_{}\".format(shape_str)].astype(\n array_type\n )\n params = (\n (blend_src, 0.0, 1.0),\n (blend_src, 0.3, 0.7),\n (blend_src, 0.5, 0.5),\n (blend_src, 0.7, 0.3),\n (blend_src, 1.0, 0.0),\n )\n for param in params:\n gt_transformer = getattr(self, \"{}_gt\".format(_trans_name))\n transformer = getattr(T, _trans_name)(*param)\n\n result = transformer.apply_image(img)\n img_gt, shape_gt = gt_transformer(img, *param)\n\n self.assertEqual(\n shape_gt,\n result.shape,\n \"transform {} failed to pass the shape check with\"\n \"params {} given input with shape {} and type {}\".format(\n _trans_name, param, shape_str, array_type\n ),\n )\n self.assertTrue(\n np.allclose(result, img_gt),\n \"transform {} failed to pass the value check with\"\n \"params {} given input with shape {} and type {}\".format(\n _trans_name, param, shape_str, array_type\n ),\n )\n\n def test_crop_transforms(self):\n \"\"\"\n Test CropTransform..\n \"\"\"\n _trans_name = \"CropTransform\"\n params = (\n (0, 0, 0, 0),\n (0, 0, 1, 1),\n (0, 0, 6, 6),\n (3, 3, 6, 6),\n (6, 6, 6, 6),\n )\n for (img, array_type, shape_str), param in itertools.product(\n TestTransforms._img_provider(), params\n ):\n gt_transformer = getattr(self, \"{}_gt\".format(_trans_name))\n transformer = getattr(T, _trans_name)(*param)\n\n result = transformer.apply_image(img)\n img_gt, shape_gt = gt_transformer(img, *param)\n\n self.assertEqual(\n shape_gt,\n result.shape,\n \"transform {} failed to pass the shape check with\"\n \"params {} given input with shape {} and type {}\".format(\n _trans_name, param, shape_str, array_type\n ),\n )\n self.assertTrue(\n np.allclose(result, img_gt),\n \"transform {} failed to pass the value check with\"\n \"params {} given input with shape {} and type {}\".format(\n _trans_name, param, shape_str, array_type\n ),\n )\n\n def test_hflip_transforms(self):\n \"\"\"\n Test HFlipTransform..\n \"\"\"\n _trans_name = \"HFlipTransform\"\n params = ((0,), (1,))\n\n for (img, array_type, shape_str), param in itertools.product(\n TestTransforms._img_provider(), params\n ):\n gt_transformer = getattr(self, \"{}_gt\".format(_trans_name))\n transformer = getattr(T, _trans_name)(*param)\n\n result = transformer.apply_image(img)\n img_gt, shape_gt = gt_transformer(img, *param)\n\n self.assertEqual(\n shape_gt,\n result.shape,\n \"transform {} failed to pass the shape check with\"\n \"params {} given input with shape {} and type {}\".format(\n _trans_name, param, shape_str, array_type\n ),\n )\n self.assertTrue(\n np.allclose(result, img_gt),\n \"transform {} failed to pass the value check with\"\n \"params {} given input with shape {} and type {}\".format(\n _trans_name, param, shape_str, array_type\n ),\n )\n\n def test_no_op_transforms(self):\n \"\"\"\n Test NoOpTransform..\n \"\"\"\n _trans_name = \"NoOpTransform\"\n params = ()\n\n for (img, array_type, shape_str), param in itertools.product(\n TestTransforms._img_provider(), params\n ):\n gt_transformer = getattr(self, \"{}_gt\".format(_trans_name))\n transformer = getattr(T, _trans_name)(*param)\n\n result = transformer.apply_image(img)\n img_gt, shape_gt = gt_transformer(img, *param)\n\n self.assertEqual(\n shape_gt,\n result.shape,\n \"transform {} failed to pass the shape check with\"\n \"params {} given input with shape {} and type {}\".format(\n _trans_name, param, shape_str, array_type\n ),\n )\n self.assertTrue(\n np.allclose(result, img_gt),\n \"transform {} failed to pass the value check with\"\n \"params {} given input with shape {} and type {}\".format(\n _trans_name, param, shape_str, array_type\n ),\n )\n\n def test_scale_transforms(self):\n \"\"\"\n Test ScaleTransform..\n \"\"\"\n _trans_name = \"ScaleTransform\"\n params = ((0, 0, 20, 20, \"nearest\"), (10, 10, 20, 20, \"nearest\"))\n\n for (img, array_type, shape_str), param in itertools.product(\n TestTransforms._img_provider(), params\n ):\n gt_transformer = getattr(self, \"{}_gt\".format(_trans_name))\n transformer = getattr(T, _trans_name)(*param)\n\n result = transformer.apply_image(img)\n img_gt, shape_gt = gt_transformer(img, *param)\n\n if shape_gt is not None:\n self.assertEqual(\n shape_gt,\n result.shape,\n \"transform {} failed to pass the shape check with\"\n \"params {} given input with shape {} and type {}\".format(\n _trans_name, param, shape_str, array_type\n ),\n )\n if img_gt is not None:\n self.assertTrue(\n np.allclose(result, img_gt),\n \"transform {} failed to pass the value check with\"\n \"params {} given input with shape {} and type {}\".format(\n _trans_name, param, shape_str, array_type\n ),\n )\n\n def test_grid_sample(self):\n \"\"\"\n Test grid sampling tranformation.\n \"\"\"\n # TODO: add more complex test case for grid sample.\n for interp in [\"nearest\"]:\n grid_2d = np.stack(\n np.meshgrid(np.linspace(-1, 1, 10), np.linspace(-1, 1, 10)),\n axis=2,\n ).astype(np.float)\n grid = np.tile(grid_2d[None, :, :, :], [8, 1, 1, 1])\n transformer = T.GridSampleTransform(grid, interp)\n\n img_h, img_w = np.mgrid[0:10:1, 0:10:1].astype(np.float)\n img_hw = img_h * 10 + img_w\n img_hwc = np.repeat(img_hw[:, :, None], 3, axis=2)\n img_bhwc = np.repeat(img_hwc[None, :, :, :], 8, axis=0)\n\n result = transformer.apply_image(img_bhwc)\n img_gt, shape_gt = TestTransforms.GridSampleTransform_gt(\n img_bhwc, *(grid_2d, interp)\n )\n\n self.assertEqual(shape_gt, result.shape)\n self.assertTrue(np.allclose(result, img_gt))\n\n def test_crop_polygons(self):\n # Ensure that shapely produce an extra vertex at the end\n # This is assumed when copping polygons\n import shapely.geometry as geometry\n\n polygon = np.asarray([3, 3.5, 11, 10.0, 38, 98, 15.0, 100.0]).reshape(\n -1, 2\n )\n g = geometry.Polygon(polygon)\n coords = np.asarray(g.exterior.coords)\n self.assertEqual(coords[0].tolist(), coords[-1].tolist())\n"
]
| [
[
"numpy.allclose",
"numpy.random.seed",
"numpy.clip",
"numpy.asarray",
"numpy.linspace",
"numpy.tile",
"numpy.ones",
"numpy.random.rand",
"numpy.repeat"
]
]
|
homomorfism/wise-programming | [
"e0589e8900237ddc9c3abf54c85be532cacf2d33",
"e0589e8900237ddc9c3abf54c85be532cacf2d33"
]
| [
"src/emotion_predictor/face_detection/yolov5_face/test.py",
"src/emotion_predictor/emotion_analysis/classifier.py"
]
| [
"import argparse\nimport json\nimport os\nfrom pathlib import Path\nfrom threading import Thread\n\nimport numpy as np\nimport torch\nimport yaml\nfrom tqdm import tqdm\n\nfrom models.experimental import attempt_load\nfrom utils.datasets import create_dataloader\nfrom utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, \\\n scale_coords, xyxy2xywh, xywh2xyxy, set_logging, increment_path, non_max_suppression_face\nfrom utils.loss import compute_loss\nfrom utils.metrics import ap_per_class, ConfusionMatrix\nfrom utils.plots import plot_images, output_to_target, plot_study_txt\nfrom utils.torch_utils import select_device, time_synchronized\n\n\ndef test(data,\n weights=None,\n batch_size=32,\n imgsz=640,\n conf_thres=0.001,\n iou_thres=0.6, # for NMS\n save_json=False,\n single_cls=False,\n augment=False,\n verbose=False,\n model=None,\n dataloader=None,\n save_dir=Path(''), # for saving images\n save_txt=False, # for auto-labelling\n save_hybrid=False, # for hybrid auto-labelling\n save_conf=False, # save auto-label confidences\n plots=True,\n log_imgs=0): # number of logged images\n\n # Initialize/load model and set device\n training = model is not None\n if training: # called by train.py\n device = next(model.parameters()).device # get model device\n\n else: # called directly\n set_logging()\n device = select_device(opt.device, batch_size=batch_size)\n\n # Directories\n save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run\n (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir\n\n # Load model\n model = attempt_load(weights, map_location=device) # load FP32 model\n imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size\n\n # Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99\n # if device.type != 'cpu' and torch.cuda.device_count() > 1:\n # model = nn.DataParallel(model)\n\n # Half\n half = device.type != 'cpu' # half precision only supported on CUDA\n if half:\n model.half()\n\n # Configure\n model.eval()\n is_coco = data.endswith('coco.yaml') # is COCO dataset\n with open(data) as f:\n data = yaml.load(f, Loader=yaml.FullLoader) # model dict\n check_dataset(data) # check\n nc = 1 if single_cls else int(data['nc']) # number of classes\n iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for [email protected]:0.95\n niou = iouv.numel()\n\n # Logging\n log_imgs, wandb = min(log_imgs, 100), None # ceil\n try:\n import wandb # Weights & Biases\n except ImportError:\n log_imgs = 0\n\n # Dataloader\n if not training:\n img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img\n _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once\n path = data['test'] if opt.task == 'test' else data['val'] # path to val/test images\n dataloader = create_dataloader(path, imgsz, batch_size, model.stride.max(), opt, pad=0.5, rect=True)[0]\n\n seen = 0\n confusion_matrix = ConfusionMatrix(nc=nc)\n names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}\n coco91class = coco80_to_coco91_class()\n s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', '[email protected]', '[email protected]:.95')\n p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.\n loss = torch.zeros(3, device=device)\n jdict, stats, ap, ap_class, wandb_images = [], [], [], [], []\n for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):\n img = img.to(device, non_blocking=True)\n img = img.half() if half else img.float() # uint8 to fp16/32\n img /= 255.0 # 0 - 255 to 0.0 - 1.0\n targets = targets.to(device)\n nb, _, height, width = img.shape # batch size, channels, height, width\n\n with torch.no_grad():\n # Run model\n t = time_synchronized()\n inf_out, train_out = model(img, augment=augment) # inference and training outputs\n t0 += time_synchronized() - t\n\n # Compute loss\n if training:\n loss += compute_loss([x.float() for x in train_out], targets, model)[1][:3] # box, obj, cls\n\n # Run NMS\n targets[:, 2:6] *= torch.Tensor([width, height, width, height]).to(device) # to pixels\n lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling\n t = time_synchronized()\n # output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres, labels=lb)\n output = non_max_suppression_face(inf_out, conf_thres=conf_thres, iou_thres=iou_thres, labels=lb)\n t1 += time_synchronized() - t\n\n # Statistics per image\n for si, pred in enumerate(output):\n pred = torch.cat((pred[:, :5], pred[:, 15:]), 1) # throw landmark in thresh\n labels = targets[targets[:, 0] == si, 1:]\n nl = len(labels)\n tcls = labels[:, 0].tolist() if nl else [] # target class\n path = Path(paths[si])\n seen += 1\n\n if len(pred) == 0:\n if nl:\n stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))\n continue\n\n # Predictions\n predn = pred.clone()\n scale_coords(img[si].shape[1:], predn[:, :4], shapes[si][0], shapes[si][1]) # native-space pred\n\n # Append to text file\n if save_txt:\n gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh\n for *xyxy, conf, cls in predn.tolist():\n xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh\n line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format\n with open(save_dir / 'labels' / (path.stem + '.txt'), 'a') as f:\n f.write(('%g ' * len(line)).rstrip() % line + '\\n')\n\n # W&B logging\n if plots and len(wandb_images) < log_imgs:\n box_data = [{\"position\": {\"minX\": xyxy[0], \"minY\": xyxy[1], \"maxX\": xyxy[2], \"maxY\": xyxy[3]},\n \"class_id\": int(cls),\n \"box_caption\": \"%s %.3f\" % (names[cls], conf),\n \"scores\": {\"class_score\": conf},\n \"domain\": \"pixel\"} for *xyxy, conf, cls in pred.tolist()]\n boxes = {\"predictions\": {\"box_data\": box_data, \"class_labels\": names}} # inference-space\n wandb_images.append(wandb.Image(img[si], boxes=boxes, caption=path.name))\n\n # Append to pycocotools JSON dictionary\n if save_json:\n # [{\"image_id\": 42, \"category_id\": 18, \"bbox\": [258.15, 41.29, 348.26, 243.78], \"score\": 0.236}, ...\n image_id = int(path.stem) if path.stem.isnumeric() else path.stem\n box = xyxy2xywh(predn[:, :4]) # xywh\n box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner\n for p, b in zip(pred.tolist(), box.tolist()):\n jdict.append({'image_id': image_id,\n 'category_id': coco91class[int(p[15])] if is_coco else int(p[15]),\n 'bbox': [round(x, 3) for x in b],\n 'score': round(p[4], 5)})\n\n # Assign all predictions as incorrect\n correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)\n if nl:\n detected = [] # target indices\n tcls_tensor = labels[:, 0]\n\n # target boxes\n tbox = xywh2xyxy(labels[:, 1:5])\n scale_coords(img[si].shape[1:], tbox, shapes[si][0], shapes[si][1]) # native-space labels\n if plots:\n confusion_matrix.process_batch(pred, torch.cat((labels[:, 0:1], tbox), 1))\n\n # Per target class\n for cls in torch.unique(tcls_tensor):\n ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # prediction indices\n pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # target indices\n\n # Search for detections\n if pi.shape[0]:\n # Prediction to target ious\n ious, i = box_iou(predn[pi, :4], tbox[ti]).max(1) # best ious, indices\n\n # Append detections\n detected_set = set()\n for j in (ious > iouv[0]).nonzero(as_tuple=False):\n d = ti[i[j]] # detected target\n if d.item() not in detected_set:\n detected_set.add(d.item())\n detected.append(d)\n correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn\n if len(detected) == nl: # all targets already located in image\n break\n\n # Append statistics (correct, conf, pcls, tcls)\n stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))\n\n # Plot images\n if plots and batch_i < 3:\n f = save_dir / f'test_batch{batch_i}_labels.jpg' # labels\n Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start()\n f = save_dir / f'test_batch{batch_i}_pred.jpg' # predictions\n Thread(target=plot_images, args=(img, output_to_target(output), paths, f, names), daemon=True).start()\n\n # Compute statistics\n stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy\n if len(stats) and stats[0].any():\n p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)\n p, r, ap50, ap = p[:, 0], r[:, 0], ap[:, 0], ap.mean(1) # [P, R, [email protected], [email protected]:0.95]\n mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()\n nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class\n else:\n nt = torch.zeros(1)\n\n # Print results\n pf = '%20s' + '%12.3g' * 6 # print format\n print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))\n\n # Print results per class\n if verbose and nc > 1 and len(stats):\n for i, c in enumerate(ap_class):\n print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))\n\n # Print speeds\n t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple\n if not training:\n print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)\n\n # Plots\n if plots:\n confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))\n if wandb and wandb.run:\n wandb.log({\"Images\": wandb_images})\n wandb.log({\"Validation\": [wandb.Image(str(f), caption=f.name) for f in sorted(save_dir.glob('test*.jpg'))]})\n\n # Save JSON\n if save_json and len(jdict):\n w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights\n anno_json = '../coco/annotations/instances_val2017.json' # annotations json\n pred_json = str(save_dir / f\"{w}_predictions.json\") # predictions json\n print('\\nEvaluating pycocotools mAP... saving %s...' % pred_json)\n with open(pred_json, 'w') as f:\n json.dump(jdict, f)\n\n try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n from pycocotools.coco import COCO\n from pycocotools.cocoeval import COCOeval\n\n anno = COCO(anno_json) # init annotations api\n pred = anno.loadRes(pred_json) # init predictions api\n eval = COCOeval(anno, pred, 'bbox')\n if is_coco:\n eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate\n eval.evaluate()\n eval.accumulate()\n eval.summarize()\n map, map50 = eval.stats[:2] # update results ([email protected]:0.95, [email protected])\n except Exception as e:\n print(f'pycocotools unable to run: {e}')\n\n # Return results\n if not training:\n s = f\"\\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}\" if save_txt else ''\n print(f\"Results saved to {save_dir}{s}\")\n model.float() # for training\n maps = np.zeros(nc) + map\n for i, c in enumerate(ap_class):\n maps[c] = ap[i]\n return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(prog='test.py')\n parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')\n parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path')\n parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')\n parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')\n parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')\n parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS')\n parser.add_argument('--task', default='val', help=\"'val', 'test', 'study'\")\n parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')\n parser.add_argument('--augment', action='store_true', help='augmented inference')\n parser.add_argument('--verbose', action='store_true', help='report mAP by class')\n parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')\n parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')\n parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')\n parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')\n parser.add_argument('--project', default='runs/test', help='save to project/name')\n parser.add_argument('--name', default='exp', help='save to project/name')\n parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')\n opt = parser.parse_args()\n opt.save_json |= opt.data.endswith('coco.yaml')\n opt.data = check_file(opt.data) # check file\n print(opt)\n\n if opt.task in ['val', 'test']: # run normally\n test(opt.data,\n opt.weights,\n opt.batch_size,\n opt.img_size,\n opt.conf_thres,\n opt.iou_thres,\n opt.save_json,\n opt.single_cls,\n opt.augment,\n opt.verbose,\n save_txt=opt.save_txt | opt.save_hybrid,\n save_hybrid=opt.save_hybrid,\n save_conf=opt.save_conf,\n )\n\n elif opt.task == 'study': # run over a range of settings and save/plot\n for weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:\n f = 'study_%s_%s.txt' % (Path(opt.data).stem, Path(weights).stem) # filename to save to\n x = list(range(320, 800, 64)) # x axis\n y = [] # y axis\n for i in x: # img-size\n print('\\nRunning %s point %s...' % (f, i))\n r, _, t = test(opt.data, weights, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json,\n plots=False)\n y.append(r + t) # results and times\n np.savetxt(f, y, fmt='%10.4g') # save\n os.system('zip -r study.zip study_*.txt')\n plot_study_txt(f, x) # plot\n",
"from pathlib import Path\n\nimport numpy as np\nimport onnx\nimport onnxruntime\nfrom scipy.special import softmax\nfrom skimage import color\nfrom skimage import io\nfrom skimage.transform import resize\n\nemotions_order = ['neutral', 'happiness', 'surprise', 'sadness', 'anger', 'disgust', 'fear', 'contempt']\n\n\ndef predict_emotion(image: np.array, session: onnxruntime.InferenceSession):\n ort_inputs = {session.get_inputs()[0].name: image}\n scores = session.run(None, ort_inputs)[0][0]\n scores = softmax(scores, axis=0)\n\n emotions_predictions = {emotion: score for emotion, score in zip(emotions_order, scores)}\n\n return emotions_predictions\n\n\ndef preprocess(image: np.array):\n image = color.rgb2gray(image)\n image = resize(image, (64, 64), anti_aliasing=True)\n image = (image - 0.485) / 0.229\n\n image = image.reshape(1, 1, 64, 64)\n image = image.astype(np.float32)\n\n return image\n\n\ndef get_onnx_session(model_path: Path):\n assert model_path.is_file(), f\"Weights file not found in {model_path.absolute()}!\"\n\n model = onnx.load(str(model_path))\n session = onnxruntime.InferenceSession(model.SerializeToString())\n return session\n\n\ndef make_classification(model_path: Path, image_path: Path):\n session = get_onnx_session(model_path)\n image = io.imread(str(image_path))\n image = preprocess(image)\n predictions = predict_emotion(image, session)\n print(predictions)\n\n\nif __name__ == '__main__':\n make_classification(\n model_path=Path('/home/shamil/PycharmProjects/wise-programming/weights/emotion-ferplus-8.onnx'),\n image_path=Path(\n \"/home/shamil/PycharmProjects/wise-programming/demo_images/emotion_examples/shamil-sad-crop.png\")\n )\n"
]
| [
[
"torch.linspace",
"torch.Tensor",
"torch.zeros",
"torch.cat",
"torch.tensor",
"numpy.concatenate",
"torch.unique",
"torch.no_grad",
"numpy.savetxt",
"numpy.zeros"
],
[
"scipy.special.softmax"
]
]
|
xiangsheng1325/CPGAN | [
"f05d7183a28601d5af849229766ddaf1e4c5cba8"
]
| [
"CPGAN/models.py"
]
| [
"from torch import nn\nimport torch\nfrom torch.nn.parameter import Parameter\nimport torch.nn.functional as F\nfrom torch.nn.modules.module import Module\nimport math\nimport copy\n# from CPGAN.data_utils import timelog\n# from torch_geometric.nn.conv.gat_conv import GATConv\n\nclass GraphAttnMultiHead(Module):\n def __init__(self, in_features=128, out_features=128, negative_slope=0.2, num_heads=4, bias=False, residual=True):\n super(GraphAttnMultiHead, self).__init__()\n self.num_heads = num_heads\n self.out_features = out_features\n #self.weight = Parameter(torch.FloatTensor(in_features, out_features))\n self.in_proj = nn.Linear(in_features, out_features, bias=bias)\n self.weight_u = Parameter(torch.FloatTensor(num_heads, out_features//num_heads, 1))\n self.weight_v = Parameter(torch.FloatTensor(num_heads, out_features//num_heads, 1))\n self.leaky_relu = nn.LeakyReLU(negative_slope=negative_slope)\n self.residual = residual\n if self.residual:\n self.project = nn.Linear(in_features, out_features)\n else:\n self.project = None\n if bias:\n self.bias = Parameter(torch.FloatTensor(num_heads, out_features))\n else:\n self.register_parameter('bias', None)\n self.bias = None\n self.reset_parameters()\n\n def reset_parameters(self):\n if self.bias is not None:\n stdv = 1. / math.sqrt(self.bias.size(-1))\n self.bias.data.uniform_(-stdv, stdv)\n # self.weight.data.uniform_(-stdv, stdv)\n stdv = 1. / math.sqrt(self.weight_u.size(-1))\n self.weight_u.data.uniform_(-stdv, stdv)\n self.weight_v.data.uniform_(-stdv, stdv)\n\n def forward(self, inputs, adj_mat, requires_weight=False):\n # inputs (n_nodes, in_features)\n # print(inputs.shape)\n support = self.in_proj(inputs)\n # support (n_node, out_features)\n support = support.reshape(-1, self.num_heads, self.out_features//self.num_heads).permute(dims=(1, 0, 2))\n # support (n_head, n_node, out_features//n_head)\n f_1 = torch.matmul(support, self.weight_u)\n f_2 = torch.matmul(support, self.weight_v).permute((0, 2, 1))\n logits = f_1 + f_2\n weight = self.leaky_relu(logits)\n masked_weight = torch.mul(weight, adj_mat).to_sparse()\n attn_weights = torch.sparse.softmax(masked_weight, dim=2).to_dense()\n # attn_weights (n_head, n_node, n_node)\n # print(attn_weights)\n support = torch.matmul(attn_weights, support)\n support = support.permute(dims=(1, 0, 2)).reshape(-1, self.out_features)\n if self.bias is not None:\n support = support + self.bias\n if self.residual:\n support = support + self.project(inputs)\n if requires_weight:\n return support, attn_weights\n else:\n return support\n\nclass GCN(Module):\n \"\"\"\n GCN layer, reference to: https://arxiv.org/abs/1609.02907\n \"\"\"\n\n def __init__(self, input_len, output_len, bias=True):\n super(GCN, self).__init__()\n self.input_len = input_len\n self.output_len = output_len\n # print(\"Type of ouput_len: {}\\t, value of output_len: {}\".format(type(output_len), output_len))\n self.weight = Parameter(torch.FloatTensor(input_len, output_len))\n if bias:\n self.bias = Parameter(torch.FloatTensor(output_len))\n else:\n self.register_parameter('bias', None)\n\n def reset_parameters(self):\n \"\"\"\n reset parameters in uniform distribution\n \"\"\"\n margin = 1. / math.sqrt(self.weight.size(1))\n self.weight.data.uniform_(-margin, margin)\n if self.bias is not None:\n self.bias.data.uniform_(-margin, margin)\n\n def forward(self, inputs, adj):\n \"\"\"\n When this layer is called, execute this function.\n :param inputs: embedded node vectors (with condition context)\n :param adj: adjacent matrix\n :return: output of GCN layer\n \"\"\"\n # print(\"Type of inputs: {}\".format(type(inputs)))\n # print(\"Type of weights: {}\".format(type(self.W)))\n support = torch.mm(inputs, self.weight)\n # output = torch._sparse_mm(adj, support)\n output = torch.spmm(adj, support)\n if self.bias is None:\n return output\n else:\n return output + self.bias\n\n def __str__(self):\n return \"Layer: {}({}->{})\".format(self.__class__.__name__, self.input_len, self.output_len)\n\n def __repr__(self):\n return \"Layer: {}({}->{})\".format(self.__class__.__name__, self.input_len, self.output_len)\n\n\nclass PairNorm(nn.Module):\n def __init__(self, mode='PN', scale=1):\n \"\"\"\n mode:\n 'None' : No normalization\n 'PN' : Original version\n 'PN-SI' : Scale-Individually version\n 'PN-SCS' : Scale-and-Center-Simultaneously version\n\n ('SCS'-mode is not in the paper but we found it works well in practice,\n especially for GCN and GAT.)\n PairNorm is typically used after each graph convolution operation.\n \"\"\"\n assert mode in ['None', 'PN', 'PN-SI', 'PN-SCS']\n super(PairNorm, self).__init__()\n self.mode = mode\n self.scale = scale\n\n # Scale can be set based on origina data, and also the current feature lengths.\n # We leave the experiments to future. A good pool we used for choosing scale:\n # [0.1, 1, 10, 50, 100]\n\n def forward(self, x):\n if self.mode == 'None':\n return x\n\n col_mean = x.mean(dim=0)\n if self.mode == 'PN':\n x = x - col_mean\n rownorm_mean = (1e-6 + x.pow(2).sum(dim=1).mean()).sqrt()\n x = self.scale * x / rownorm_mean\n\n if self.mode == 'PN-SI':\n x = x - col_mean\n rownorm_individual = (1e-6 + x.pow(2).sum(dim=1, keepdim=True)).sqrt()\n x = self.scale * x / rownorm_individual\n\n if self.mode == 'PN-SCS':\n rownorm_individual = (1e-6 + x.pow(2).sum(dim=1, keepdim=True)).sqrt()\n x = self.scale * x / rownorm_individual - col_mean\n\n return x\n\n\nclass CPEncoder(nn.Module):\n def __init__(self, input_size, encoding_size, pool_size, n_heads):\n super(CPEncoder, self).__init__()\n self.pn = PairNorm(mode='PN-SI')\n self.act = nn.PReLU()\n self.encode = GraphAttnMultiHead(in_features=input_size,\n out_features=encoding_size)\n self.pool = GraphAttnMultiHead(in_features=encoding_size,\n out_features=pool_size,\n num_heads=n_heads)\n self.encode2 = GraphAttnMultiHead(in_features=encoding_size,\n out_features=encoding_size)\n def forward(self, x, adj):\n support = self.encode(x, adj)\n assignment_matrix = self.pool(support, adj)\n clustering_result = F.softmax(assignment_matrix, dim=1)\n pooled_adj = clustering_result.t() @ adj @ clustering_result\n cluster_representation = self.encode2(clustering_result.t() @ support, pooled_adj)\n return support, assignment_matrix, cluster_representation\n\n\nclass ConvRecEncoder(nn.Module):\n def __init__(self, input_size, encoding_size, pool_size, variational=True):\n super(ConvRecEncoder, self).__init__()\n self.variational = variational\n self.act1 = nn.ReLU()\n self.act2 = nn.Softmax()\n self.gc1 = GCN(input_size, encoding_size)\n self.bn1 = nn.BatchNorm1d(encoding_size)\n self.pl1 = GCN(encoding_size, pool_size)\n self.gc2 = GCN(encoding_size, encoding_size)\n self.bn2 = nn.BatchNorm1d(encoding_size)\n self.mpn = GCN(encoding_size, pool_size)\n self.mean = nn.Sequential(nn.Linear(encoding_size*2, encoding_size),\n nn.BatchNorm1d(encoding_size),\n nn.ReLU(),\n nn.Linear(encoding_size, encoding_size))\n self.logv = nn.Sequential(nn.Linear(encoding_size*2, encoding_size),\n nn.BatchNorm1d(encoding_size),\n nn.ReLU(),\n nn.Linear(encoding_size, encoding_size))\n for m in self.modules():\n if isinstance(m, GCN):\n m.reset_parameters()\n elif isinstance(m, nn.BatchNorm1d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data = nn.init.xavier_uniform(m.weight.data,gain=nn.init.calculate_gain('relu'))\n\n @staticmethod\n def normalize_(x, norm_type='softmax'):\n \"\"\"\n A simple trick to avoid exponential exploding\n :param norm_type: strategy for normalization\n :param x: message matrix with shape->(n, d)\n :return:\n \"\"\"\n if norm_type == \"softmax\":\n normalized_x = F.softmax(x, dim=0)\n elif norm_type == \"sum\":\n rowsum = x.sum(0)\n n_matrix = torch.diag(torch.pow(rowsum, -1).flatten())\n normalized_x = torch.mm(x, n_matrix)\n else:\n normalized_x = F.softmax(x, dim=0)\n return normalized_x\n\n def forward(self, x, adj):\n x1 = self.gc1(x, adj)\n x1 = self.bn1(x1)\n x1 = self.act1(x1)\n s1 = self.pl1(x1, adj)\n s1 = self.act2(s1)\n x2 = torch.mm(s1.t(), x1)\n adj2 = torch.mm(s1.t(), torch.spmm(adj, s1))\n x2 = self.gc2(x2, adj2)\n x2 = self.bn2(x2)\n x2 = self.act1(x2)\n\n s2 = self.mpn(x1, adj)\n s2 = self.normalize_(s2)\n rec_x1 = torch.mm(s2, x2)\n rec_x = torch.cat([x1, rec_x1], dim=-1)\n if self.variational:\n mean = self.mean(rec_x)\n logvar = self.logv(rec_x)\n return mean, logvar\n else:\n return rec_x, x1\n\n\nclass ConvPoolEncoder(nn.Module):\n def __init__(self, input_size, encoding_size, pool_size):\n super(ConvPoolEncoder, self).__init__()\n self.act1 = nn.ReLU()\n self.act2 = nn.Sigmoid()\n self.gc1 = GCN(input_size, encoding_size)\n self.bn1 = nn.BatchNorm1d(encoding_size)\n self.pl1 = GCN(encoding_size, pool_size)\n self.gc2 = GCN(encoding_size, encoding_size)\n self.bn2 = nn.BatchNorm1d(encoding_size)\n # self.gc_stack = nn.ModuleList([GCN(encoding_size, encoding_size) for i in range(layer_num-1)])\n\n for m in self.modules():\n if isinstance(m, GCN):\n m.reset_parameters()\n\n # @timelog\n def forward(self, x, adj):\n \"\"\"\n Encoder\n :param x: In conditional vae, x should be concatenated with condition vector before this function is called.\n :param adj: To avoid exponential explosion, adjacency matrix must be normalized before this function is called.\n :return: As you can see, features and adjacency matrixs after convolution and pooling layer.\n \"\"\"\n x1 = self.gc1(x, adj)\n x1 = self.bn1(x1)\n x1 = self.act1(x1)\n s1 = self.pl1(x1, adj)\n s1 = self.act2(s1)\n x2 = torch.mm(s1.permute(1, 0), x1)\n adj2 = torch.mm(torch.spmm(s1.permute(1, 0), adj), s1)\n x2 = self.gc2(x2, adj2)\n x2 = self.bn2(x2)\n x2 = self.act1(x2)\n return x1, x2, adj\n\n\nclass MLPEncoder(nn.Module):\n def __init__(self, input_size, encoding_size, layer_num=2):\n super(MLPEncoder, self).__init__()\n self.act = nn.ReLU()\n self.encode1 = nn.Linear(input_size, encoding_size)\n self.en_stack = nn.ModuleList([nn.Linear(encoding_size, encoding_size) for i in range(layer_num - 1)])\n\n for m in self.modules():\n if isinstance(m, nn.Linear):\n m.weight.data = nn.init.xavier_uniform(m.weight.data, gain=nn.init.calculate_gain('relu'))\n\n def forward(self, x):\n x = self.encode1(x)\n x = self.act(x)\n for encode in self.en_stack:\n x = encode(x)\n x = self.act(x)\n return x\n\n\nclass ConvEncoder(nn.Module):\n def __init__(self, input_size, encoding_size, layer_num=2):\n super(ConvEncoder, self).__init__()\n self.act = nn.ReLU()\n self.gc_top = GCN(input_size, encoding_size)\n self.gc_stack = nn.ModuleList([GCN(encoding_size, encoding_size) for i in range(layer_num)])\n\n for m in self.modules():\n if isinstance(m, nn.Linear):\n m.weight.data = nn.init.xavier_uniform(m.weight.data, gain=nn.init.calculate_gain('relu'))\n\n def forward(self, x, adj):\n x = self.gc_top(x, adj)\n x = self.act(x)\n for gcn in self.gc_stack:\n x = gcn(x, adj)\n x = self.act(x)\n return x\n\n\n# Dot product for once-for-all prediction\nclass MLPDecoder(nn.Module):\n def __init__(self, encoding_size, decoding_size, layer_num=2):\n super(MLPDecoder, self).__init__()\n self.act1 = nn.ReLU()\n self.act2 = nn.Sigmoid()\n self.decode = nn.Linear(encoding_size, decoding_size)\n self.de_stack = nn.ModuleList([nn.Linear(decoding_size, decoding_size) for i in range(layer_num-1)])\n self.bn_stack = nn.ModuleList([nn.BatchNorm1d(decoding_size) for i in range(layer_num-1)])\n\n for m in self.modules():\n if isinstance(m, nn.Linear):\n m.weight.data = nn.init.xavier_uniform(m.weight.data, gain=nn.init.calculate_gain('relu'))\n\n def forward(self, x, attr=None):\n if attr is not None:\n x = torch.cat([x, attr], dim=1)\n x = self.decode(x)\n for decode in self.de_stack:\n x = self.act1(x)\n x = decode(x)\n pred_matrix = torch.mm(x, x.permute(1, 0))\n return self.act2(pred_matrix)\n\n\nclass MPNDecoder(nn.Module):\n def __init__(self, input_size, encoding_size, pool_size, decoding_size, layer_num=2, variational=True):\n super(MPNDecoder, self).__init__()\n self.act1 = nn.ReLU()\n self.act2 = nn.Sigmoid()\n self.mpn = GCN(encoding_size+input_size, pool_size)\n self.decode = nn.Linear(input_size+encoding_size*2, decoding_size)\n self.de_stack = nn.ModuleList([nn.Linear(decoding_size, decoding_size) for i in range(layer_num-1)])\n self.batch_norm = nn.BatchNorm1d(decoding_size)\n # param: self.variational: bool, whether map the features to approximate specific distribution\n self.variational = variational\n if self.variational:\n self.mean = nn.Sequential(nn.Linear(input_size+encoding_size*2, decoding_size),\n nn.BatchNorm1d(decoding_size),\n nn.ReLU(),\n nn.Linear(decoding_size, decoding_size))\n self.logv = nn.Sequential(nn.Linear(input_size+encoding_size*2, decoding_size),\n nn.BatchNorm1d(decoding_size),\n nn.ReLU(),\n nn.Linear(decoding_size, decoding_size))\n\n for m in self.modules():\n if isinstance(m, nn.Linear):\n m.weight.data = nn.init.xavier_uniform(m.weight.data, gain=nn.init.calculate_gain('relu'))\n elif isinstance(m, GCN):\n m.reset_parameters()\n\n @staticmethod\n def normalize_(x, norm_type='sum'):\n \"\"\"\n A simple trick to avoid exponential exploding\n :param norm_type: strategy for normalization\n :param x: message matrix with shape->(n, d)\n :return:\n \"\"\"\n if norm_type == \"softmax\":\n normalized_x = F.softmax(x, dim=0)\n elif norm_type == \"sum\":\n rowsum = x.sum(0)\n n_matrix = torch.diag(torch.pow(rowsum, -1).flatten())\n normalized_x = torch.mm(x, n_matrix)\n else:\n normalized_x = F.softmax(x, dim=0)\n return normalized_x\n\n def predict_(self, x):\n for decode in self.de_stack:\n x = self.act1(x)\n x = decode(x)\n return self.act2(torch.mm(x, x.permute(1, 0)))\n\n # @timelog\n def forward(self, x1, x2, adj1):\n \"\"\"\n Message Passing Network Decoder implementation\n :param x1: In conditional vae, x1 should be concatenated with condition vector before this function is called.\n :param x2: If there are condition vectors, x2 should be conditioned before this.\n :param adj1: Raw adjacency matrix(should be normalized before calling this func)\n :return:\n \"\"\"\n s1 = self.mpn(x1, adj1) # n * pooling_size\n s1 = self.normalize_(s1, norm_type='softmax')\n rec_x1 = torch.mm(s1, x2) # n * encoding_size\n rec_x = torch.cat([x1, rec_x1], dim=-1)\n if not self.variational:\n decode_x = self.decode(rec_x)\n decode_x = self.batch_norm(decode_x)\n return self.predict_(decode_x)\n else:\n mean = self.mean(rec_x)\n logv = self.logv(rec_x)\n std = logv.mul(0.5).exp_()\n noise = torch.randn(size=mean.size(), requires_grad=True).cuda()\n final_x = mean + noise * std\n return self.predict_(final_x), mean, logv\n\n\nclass MATReconstructor(nn.Module):\n def __init__(self, encoding_size, hidden_dim):\n super(MATReconstructor, self).__init__()\n self.source = nn.Linear(encoding_size, hidden_dim)\n self.target = nn.Linear(encoding_size, hidden_dim)\n self.att = nn.Sequential(nn.Linear(hidden_dim*2, hidden_dim),\n nn.BatchNorm1d(hidden_dim),\n nn.Linear(hidden_dim, hidden_dim))\n self.mean = nn.Sequential(nn.Linear(hidden_dim + encoding_size, hidden_dim),\n nn.BatchNorm1d(hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim))\n self.logv = nn.Sequential(nn.Linear(hidden_dim + encoding_size, hidden_dim),\n nn.BatchNorm1d(hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim))\n\n def attention(self, x, inputs):\n x_input = x.repeat(inputs.shape[0], 1)\n x_input = self.source(x_input)\n inputs = self.target(inputs)\n x_attention = torch.cat([x_input, inputs], dim=1)\n x_attention = self.att(x_attention)\n weights = F.softmax(x_attention.t())\n return torch.mm(weights, inputs)[0]\n\n def forward(self, x1, x2):\n x_att = copy.deepcopy(x1)\n for i, x_i in enumerate(x1):\n c_i = self.attention(x_i, x2)\n x_att[i] = c_i\n rec_x = torch.cat([x1, x_att], dim=1)\n mean = self.mean(rec_x)\n logvar = self.logv(rec_x)\n return mean, logvar\n\n\nclass GRUDecoder(nn.Module):\n def __init__(self, input_size, hidden_size, num_layers=1, has_output=True, output_size=16):\n super(GRUDecoder, self).__init__()\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.has_output = has_output\n self.rnn = nn.GRU(input_size=input_size,\n hidden_size=hidden_size,\n num_layers=num_layers,\n batch_first=True,\n bidirectional=True)\n if has_output:\n self.output = nn.Sequential(nn.Linear(hidden_size*2, hidden_size),\n nn.BatchNorm1d(hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, output_size))\n for name, param in self.rnn.named_parameters():\n if 'bias' in name:\n nn.init.constant(param, 0.25)\n elif 'weight' in name:\n nn.init.xavier_uniform(param,gain=nn.init.calculate_gain('sigmoid'))\n for m in self.modules():\n if isinstance(m, nn.Linear):\n m.weight.data = nn.init.xavier_uniform(m.weight.data, gain=nn.init.calculate_gain('relu'))\n\n def init_hidden(self, num_nodes):\n return torch.autograd.Variable(torch.zeros(self.num_layers, num_nodes, self.hidden_size)).cuda()\n\n def forward(self, inputs):\n \"\"\"\n rnn decoder forward\n :param inputs: shape(num_nodes, pooling_layers, input_size)\n :return:\n \"\"\"\n output_raw, self.hidden = self.rnn(inputs, self.hidden)\n if self.has_output:\n output = self.output(output_raw)\n return\n\n\nclass GraphHiddenDiscriminator(nn.Module):\n def __init__(self, input_size, hidden_size, layer_num=2):\n super(GraphHiddenDiscriminator, self).__init__()\n self.act1 = nn.ReLU()\n self.encode = nn.Linear(input_size, hidden_size)\n # self.bn = nn.BatchNorm1d(hidden_size)\n self.en_stack = nn.ModuleList([nn.Linear(hidden_size, hidden_size) for i in range(layer_num-2)])\n self.sigmoid_output = nn.Sequential(nn.Linear(hidden_size, 1),\n nn.Sigmoid())\n\n for m in self.modules():\n if isinstance(m, nn.Linear):\n m.weight.data = nn.init.xavier_uniform(m.weight.data, gain=nn.init.calculate_gain('relu'))\n\n # @timelog\n def forward(self, x):\n x = self.encode(x)\n # x = self.bn(x)\n x = self.act1(x)\n for encode in self.en_stack:\n x = encode(x)\n x = self.act1(x)\n y_pred = self.sigmoid_output(x)\n return y_pred\n\n\nclass GraphCPVAE(nn.Module):\n def __init__(self, input_size, encoding_size, pool_size, decoding_size, decode_layer_num, variational=True):\n super(GraphCPVAE, self).__init__()\n self.variational = variational\n self.encoder = ConvRecEncoder(input_size=input_size, encoding_size=encoding_size, pool_size=pool_size, variational=variational)\n self.decoder = MLPDecoder(encoding_size=encoding_size+input_size, decoding_size=decoding_size, layer_num=decode_layer_num)\n if not variational:\n self.encode = nn.Linear(2*encoding_size, encoding_size)\n self.encode.weight.data = nn.init.xavier_uniform(self.encode.weight.data, gain=nn.init.calculate_gain('relu'))\n\n def forward(self, x, adj, attr):\n if self.variational:\n mean, logvar = self.encoder(x, adj)\n std = logvar.mul(0.5).exp_()\n _noise = torch.randn(mean.shape, requires_grad=True).cuda()\n gen_hidden = mean + std * _noise\n rec_adj = self.decoder(gen_hidden, attr)\n return rec_adj, mean, logvar\n else:\n rec_x, _ = self.encoder(x, adj)\n encode_x = self.encode(rec_x)\n rec_adj = self.decoder(encode_x, attr)\n return rec_adj, _, _\n\n\nclass GraphCPDiscriminator(nn.Module):\n def __init__(self, input_size, encoding_size, pool_size, hidden_size, layer_num=2, variational=True):\n super(GraphCPDiscriminator, self).__init__()\n self.act1 = nn.ReLU()\n self.encoder = ConvRecEncoder(input_size=input_size, encoding_size=encoding_size, pool_size=pool_size, variational=variational)\n # self.bn = nn.BatchNorm1d(hidden_size)\n self.variational = variational\n if not self.variational:\n self.encode = nn.Linear(2*encoding_size, hidden_size)\n self.en_stack = nn.ModuleList([nn.Linear(hidden_size, hidden_size) for i in range(layer_num-1)])\n self.sigmoid_output = nn.Sequential(nn.Linear(hidden_size, 1),\n nn.Sigmoid())\n\n for m in self.modules():\n if isinstance(m, nn.Linear):\n m.weight.data = nn.init.xavier_uniform(m.weight.data, gain=nn.init.calculate_gain('relu'))\n\n # @timelog\n def forward(self, x, adj):\n x, _ = self.encoder(x, adj)\n # x = self.bn(x)\n # x = self.act1(x)\n if not self.variational:\n x = self.encode(x)\n x = self.act1(x)\n for encode in self.en_stack:\n x = encode(x)\n x = self.act1(x)\n x = x.mean(0)\n y_pred = self.sigmoid_output(x)\n return y_pred\n\n\nclass CPDiscriminator(nn.Module):\n def __init__(self, input_dim, encoding_dim):\n super(CPDiscriminator, self).__init__()\n self.enc1 = nn.Linear(input_dim, encoding_dim)\n self.enc2 = nn.Linear(input_dim, encoding_dim)\n self.infer = nn.Sequential(nn.Linear(encoding_dim, encoding_dim),\n nn.ReLU(),\n nn.Linear(encoding_dim, 1))\n def forward(self, x1, x2):\n support1 = self.enc1(x1).mean(0)\n support2 = self.enc2(x2).mean(0)\n support = torch.stack([support1, support2])\n return self.infer(support).mean(0)\n\n\nclass CPGenerator(nn.Module):\n def __init__(self, input_dim, encoding_dim):\n super(CPGenerator, self).__init__()\n self.decoding1 = nn.GRU(batch_first=True,\n input_size=input_dim,\n hidden_size=encoding_dim)\n self.encoding_size = encoding_dim\n self.decoding2 = nn.Sequential(nn.Linear(encoding_dim, encoding_dim),\n nn.ReLU(),\n nn.Linear(encoding_dim, encoding_dim))\n self.h0 = None\n def forward(self, x1, pool, x2):\n if self.h0 is None:\n self.h0 = torch.zeros(1, x1.shape[0], self.encoding_size).to(x1.device)\n pool_mat = F.softmax(pool, dim=0)\n rec_x1 = pool_mat @ x2\n _, support = self.decoding1(torch.stack([x1, rec_x1], dim=1), self.h0)\n return self.decoding2(support.squeeze())\n\nclass GraphATVAE(nn.Module):\n def __init__(self):\n super(GraphATVAE, self).__init__()\n self.convpool = ConvPoolEncoder\n self.attrec = MATReconstructor\n self.decoder = MLPDecoder\n\n def forward(self, *inputs, **kwargs):\n return\n\n\nimport numpy as np\nimport networkx as nx\nimport torch.optim as optim\ndef coo_to_csp(sp_coo):\n num = sp_coo.shape[0]\n row = sp_coo.row\n col = sp_coo.col\n sp_tensor = torch.sparse.FloatTensor(torch.LongTensor(np.stack([row, col])),\n torch.tensor(sp_coo.data),\n torch.Size([num, num]))\n return sp_tensor\n\n\nif __name__ == '__main__':\n pass"
]
| [
[
"torch.nn.Softmax",
"torch.nn.functional.softmax",
"torch.cat",
"torch.zeros",
"torch.nn.GRU",
"torch.FloatTensor",
"torch.pow",
"torch.nn.init.calculate_gain",
"torch.Size",
"torch.mm",
"torch.randn",
"numpy.stack",
"torch.nn.Sigmoid",
"torch.tensor",
"torch.mul",
"torch.nn.init.constant",
"torch.nn.BatchNorm1d",
"torch.nn.PReLU",
"torch.sparse.softmax",
"torch.nn.Linear",
"torch.nn.LeakyReLU",
"torch.stack",
"torch.matmul",
"torch.nn.ReLU",
"torch.spmm"
]
]
|
huangch/PyCudaSampling | [
"a806956409b69871f49a3009beb99ec400b6cf5b"
]
| [
"setup.py"
]
| [
"import os\nimport pathlib\nfrom os.path import join as pjoin\nfrom setuptools import setup, Extension\nfrom setuptools.command.build_ext import build_ext\nimport shutil\n\ndef find_in_path(name, path):\n \"\"\"Find a file in a search path\"\"\"\n\n # Adapted fom http://code.activestate.com/recipes/52224\n for dir in path.split(os.pathsep):\n binpath = pjoin(dir, name)\n if os.path.exists(binpath):\n return os.path.abspath(binpath)\n return None\n\n\ndef locate_cuda():\n \"\"\"Locate the CUDA environment on the system\n Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64'\n and values giving the absolute path to each directory.\n Starts by looking for the CUDAHOME env variable. If not found,\n everything is based on finding 'nvcc' in the PATH.\n \"\"\"\n\n # First check if the CUDAHOME env variable is in use\n if 'CUDAHOME' in os.environ:\n home = os.environ['CUDAHOME']\n nvcc = pjoin(home, 'bin', 'nvcc')\n else:\n # Otherwise, search the PATH for NVCC\n nvcc = find_in_path('nvcc', os.environ['PATH'])\n if nvcc is None:\n raise EnvironmentError('The nvcc binary could not be '\n 'located in your $PATH. Either add it to your path, '\n 'or set $CUDAHOME')\n home = os.path.dirname(os.path.dirname(nvcc))\n\n cudaconfig = {'home': home, 'nvcc': nvcc,\n 'include': pjoin(home, 'include'),\n 'lib64': pjoin(home, 'lib64')}\n for k, v in iter(cudaconfig.items()):\n if not os.path.exists(v):\n raise EnvironmentError('The CUDA %s path could not be '\n 'located in %s' % (k, v))\n\n return cudaconfig\n\n\ndef customize_compiler_for_nvcc(self):\n \"\"\"Inject deep into distutils to customize how the dispatch\n to gcc/nvcc works.\n If you subclass UnixCCompiler, it's not trivial to get your subclass\n injected in, and still have the right customizations (i.e.\n distutils.sysconfig.customize_compiler) run on it. So instead of going\n the OO route, I have this. Note, it's kindof like a wierd functional\n subclassing going on.\n \"\"\"\n\n # Tell the compiler it can processes .cu\n self.src_extensions.append('.cu')\n\n # Save references to the default compiler_so and _comple methods\n default_compiler_so = self.compiler_so\n super = self._compile\n\n # Now redefine the _compile method. This gets executed for each\n # object but distutils doesn't have the ability to change compilers\n # based on source extension: we add it.\n def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts):\n if os.path.splitext(src)[1] == '.cu':\n # use the cuda for .cu files\n self.set_executable('compiler_so', CUDA['nvcc'])\n # use only a subset of the extra_postargs, which are 1-1\n # translated from the extra_compile_args in the Extension class\n postargs = extra_postargs['nvcc']\n else:\n postargs = extra_postargs['gcc']\n\n super(obj, src, ext, cc_args, postargs, pp_opts)\n # Reset the default compiler_so, which we might have changed for cuda\n self.compiler_so = default_compiler_so\n\n # Inject our redefined _compile method into the class\n self._compile = _compile\n \nclass CMakeExtension(Extension):\n\n def __init__(self, name, sources):\n # don't invoke the original build_ext for this special extension\n Extension.__init__(self, name, sources=sources)\n\nclass my_build_ext(build_ext):\n # This class allows C extension building to fail.\n def finalize_options(self):\n build_ext.finalize_options(self)\n # Prevent numpy from thinking it is still in its setup process:\n __builtins__.__NUMPY_SETUP__ = False\n import numpy\n self.include_dirs.append(numpy.get_include())\n\n def run(self):\n build_ext.run(self)\n\n def build_cmake(self, ext):\n cwd = pathlib.Path().absolute()\n\n # these dirs will be created in build_py, so if you don't have\n # any python sources to bundle, the dirs will be missing\n build_temp = pathlib.Path(self.build_temp)\n if os.path.isdir(str(build_temp.absolute())):\n shutil.rmtree(str(build_temp.absolute()))\n build_temp.mkdir(parents=True)\n extdir = pathlib.Path(self.get_ext_fullpath(ext.name))\n # extdir.mkdir(parents=True, exist_ok=True)\n\n # example of cmake args\n config = 'Debug' if self.debug else 'Release'\n cmake_args = [\n # '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + str(extdir.parent.absolute()),\n # '-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=' + str(extdir.parent.absolute()),\n '-DCMAKE_BUILD_TYPE=' + config\n ]\n\n # example of build args\n build_args = [\n '--config', config,\n '--', '-j4'\n ]\n\n os.chdir(str(build_temp)) \n self.spawn(['cmake', os.path.join(str(cwd), 'PyCudaSampling')] + cmake_args)\n if not self.dry_run:\n self.spawn(['cmake', '--build', '.'] + build_args)\n \n os.chdir(str(cwd))\n \n def build_python(self, ext):\n # extdir = pathlib.Path(self.get_ext_fullpath(ext.name))\n build_temp = pathlib.Path(self.build_temp)\n # ext.library_dirs.append(str(extdir.parent.absolute()))\n ext.library_dirs.append(str(build_temp.absolute()))\n build_ext.build_extension(self, ext)\n \n def build_extension(self, ext):\n if isinstance(ext, CMakeExtension):\n self.build_cmake(ext)\n else:\n self.build_python(ext)\n \nCUDA = locate_cuda()\n\nmodule1 = CMakeExtension('cudaSampling',\n sources=[\n os.path.join('PyCudaSampling', 'CMakeLists.txt'),\n os.path.join('PyCudaSampling', 'cudaCommon.h'),\n os.path.join('PyCudaSampling', 'cudaSampling_kernel.cu'),\n os.path.join('PyCudaSampling', 'cudaSampling.cu'),\n os.path.join('PyCudaSampling', 'cudaSampling.h'),\n ],\n )\n \nmodule2 = Extension('PyCudaSampling',\n sources=[\n os.path.join('PyCudaSampling', 'PyCudaSampling.cpp'),\n ],\n extra_compile_args=['-fPIC'],\n include_dirs = ['./PyCudaSampling', CUDA['include']],\n library_dirs = [CUDA['lib64']],\n libraries=['cudaSampling', 'cudart'],\n ) \n \nsetup(name = 'PyCudaSampling',\n author = 'huangch', \n author_email='[email protected]',\n version = '0.0.2.dev201902141822',\n description=\"CUDA-based Image Sampling Tool.\",\n ext_modules=[module1, module2],\n cmdclass = {'build_ext': my_build_ext},\n setup_requires=['numpy'],\n packages=['PyCudaSampling'],\n # package_data={'PyCudaSampling': ['libcudaSampling.so']},\n )\n"
]
| [
[
"numpy.get_include"
]
]
|
qxcheng/fasterrcnn-pytorch-comments | [
"05da4526fc29e7179017bc5cc00b2d602c2f2327"
]
| [
"model/faster_rcnn_vgg16.py"
]
| [
"from __future__ import absolute_import\nimport torch as t\nfrom torch import nn\nfrom torchvision.models import vgg16\n\nfrom model.region_proposal_network import RegionProposalNetwork\nfrom model.faster_rcnn import FasterRCNN\nfrom model.roi_module import RoIPooling2D\nfrom utils import array_tool as at\nfrom utils.config import opt\n\n\ndef normal_init(m, mean, stddev, truncated=False):\n if truncated:\n m.weight.data.normal_().fmod_(2).mul_(stddev).add_(mean) # not a perfect approximation\n else:\n m.weight.data.normal_(mean, stddev)\n m.bias.data.zero_()\n\n\ndef decom_vgg16():\n # the 30th layer of features is relu of conv5_3\n if opt.caffe_pretrain:\n model = vgg16(pretrained=False)\n if not opt.load_path:\n model.load_state_dict(t.load(opt.caffe_pretrain_path))\n else:\n model = vgg16(not opt.load_path)\n\n features = list(model.features)[:30] # 前30层特征提取\n\n classifier = list(model.classifier)\n del classifier[6] # 去掉最后分类层\n if not opt.use_drop: # 去掉dropout层\n del classifier[5]\n del classifier[2]\n classifier = nn.Sequential(*classifier)\n\n # freeze top4 conv\n for layer in features[:10]:\n for p in layer.parameters():\n p.requires_grad = False\n\n return nn.Sequential(*features), classifier\n\n'''\ndecom_vgg16()返回的结果 features和classifier\nSequential(\n (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (1): ReLU(inplace)\n (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (3): ReLU(inplace)\n (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (6): ReLU(inplace)\n (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (8): ReLU(inplace)\n (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (11): ReLU(inplace)\n (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (13): ReLU(inplace)\n (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (15): ReLU(inplace)\n (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (18): ReLU(inplace)\n (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (20): ReLU(inplace)\n (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (22): ReLU(inplace)\n (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (25): ReLU(inplace)\n (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (27): ReLU(inplace)\n (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (29): ReLU(inplace)\n)\nSequential(\n (0): Linear(in_features=25088, out_features=4096, bias=True)\n (1): ReLU(inplace)\n (2): Linear(in_features=4096, out_features=4096, bias=True)\n (3): ReLU(inplace)\n)\n'''\n\n\nclass FasterRCNNVGG16(FasterRCNN):\n\n feat_stride = 16 # downsample 16x for output of conv5 in vgg16\n\n def __init__(self,\n n_fg_class=20, # number of classes\n ratios=[0.5, 1, 2], # width to height of the anchors\n anchor_scales=[8, 16, 32] # areas of anchors\n ):\n\n extractor, classifier = decom_vgg16()\n\n rpn = RegionProposalNetwork(\n 512, 512,\n ratios=ratios,\n anchor_scales=anchor_scales,\n feat_stride=self.feat_stride,\n )\n\n head = VGG16RoIHead(\n n_class=n_fg_class + 1,\n roi_size=7,\n spatial_scale=(1. / self.feat_stride),\n classifier=classifier\n )\n\n super(FasterRCNNVGG16, self).__init__(extractor, rpn, head,)\n\n\nclass VGG16RoIHead(nn.Module):\n \"\"\"\n n_class (int): The number of classes possibly including the background.\n roi_size (int): Height and width of the feature maps after RoI-pooling.\n spatial_scale (float): Scale of the roi is resized.\n classifier (nn.Module): Two layer Linear ported from vgg16\n \"\"\"\n\n def __init__(self, n_class, roi_size, spatial_scale, classifier):\n # n_class includes the background\n super(VGG16RoIHead, self).__init__()\n\n self.classifier = classifier\n self.cls_loc = nn.Linear(4096, n_class * 4)\n self.score = nn.Linear(4096, n_class)\n\n normal_init(self.cls_loc, 0, 0.001)\n normal_init(self.score, 0, 0.01)\n\n self.n_class = n_class\n self.roi_size = roi_size\n self.spatial_scale = spatial_scale\n self.roi = RoIPooling2D(self.roi_size, self.roi_size, self.spatial_scale)\n\n def forward(self, x, rois, roi_indices):\n # in case roi_indices is ndarray\n roi_indices = at.totensor(roi_indices).float()\n rois = at.totensor(rois).float()\n indices_and_rois = t.cat([roi_indices[:, None], rois], dim=1)\n # NOTE: important: yx->xy\n xy_indices_and_rois = indices_and_rois[:, [0, 2, 1, 4, 3]]\n indices_and_rois = xy_indices_and_rois.contiguous()\n\n pool = self.roi(x, indices_and_rois)\n pool = pool.view(pool.size(0), -1)\n fc7 = self.classifier(pool)\n roi_cls_locs = self.cls_loc(fc7)\n roi_scores = self.score(fc7)\n return roi_cls_locs, roi_scores\n\n\n\n\n"
]
| [
[
"torch.nn.Linear",
"torch.nn.Sequential",
"torch.load",
"torch.cat"
]
]
|
sachinpro/sachinpro.github.io | [
"c3bbd8d89818f5d8bb7296c851ed5e52c19728e3"
]
| [
"tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py"
]
| [
"# pylint: disable=g-bad-file-header\n# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"TensorFlow estimators for Linear and DNN joined training models.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport inspect\nimport math\n\nimport numpy as np\nimport six\n\nfrom tensorflow.contrib import layers\nfrom tensorflow.contrib import metrics as metrics_lib\nfrom tensorflow.contrib.framework.python.ops import variables as variables\nfrom tensorflow.contrib.learn.python.learn.estimators import estimator\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gradients\nfrom tensorflow.python.ops import logging_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import parsing_ops\nfrom tensorflow.python.ops import state_ops\n\n\n# TODO(ispir): Increase test coverage\nclass _DNNLinearCombinedBaseEstimator(estimator.BaseEstimator):\n \"\"\"An estimator for TensorFlow Linear and DNN joined training models.\n\n Input of `fit`, `train`, and `evaluate` should have following features,\n otherwise there will be a `KeyError`:\n if `weight_column_name` is not `None`, a feature with\n `key=weight_column_name` whose value is a `Tensor`.\n for each `column` in `dnn_feature_columns` + `linear_feature_columns`:\n - if `column` is a `SparseColumn`, a feature with `key=column.name`\n whose `value` is a `SparseTensor`.\n - if `column` is a `RealValuedColumn, a feature with `key=column.name`\n whose `value` is a `Tensor`.\n\n Parameters:\n model_dir: Directory to save model parameters, graph and etc.\n n_classes: number of target classes. Default is binary classification.\n weight_column_name: A string defining feature column name representing\n weights. It is used to down weight or boost examples during training. It\n will be multiplied by the loss of the example.\n linear_feature_columns: An iterable containing all the feature columns used\n by linear part of the model. All items in the set should be instances of\n classes derived from `FeatureColumn`.\n linear_optimizer: An instance of `tf.Optimizer` used to apply gradients to\n the linear part of the model. If `None`, will use a FTRL optimizer.\n dnn_feature_columns: An iterable containing all the feature columns used by\n deep part of the model. All items in the set should be instances of\n classes derived from `FeatureColumn`.\n dnn_hidden_units: List of hidden units per layer. All layers are fully\n connected.\n dnn_optimizer: An instance of `tf.Optimizer` used to apply gradients to the\n deep part of the model. If `None`, will use an Adagrad optimizer.\n dnn_activation_fn: Activation function applied to each layer. If `None`,\n will use `tf.nn.relu`.\n config: RunConfig object to configure the runtime settings.\n\n Raises:\n ValueError: If both linear_feature_columns and dnn_features_columns are\n empty at the same time.\n \"\"\"\n\n def __init__(self,\n model_dir=None,\n n_classes=2,\n weight_column_name=None,\n linear_feature_columns=None,\n linear_optimizer=None,\n dnn_feature_columns=None,\n dnn_optimizer=None,\n dnn_hidden_units=None,\n dnn_activation_fn=nn.relu,\n config=None):\n super(_DNNLinearCombinedBaseEstimator, self).__init__(model_dir=model_dir,\n config=config)\n self._n_classes = n_classes\n self._weight_column_name = weight_column_name\n self._linear_feature_columns = linear_feature_columns\n self._linear_optimizer = linear_optimizer\n self._dnn_feature_columns = dnn_feature_columns\n self._dnn_optimizer = dnn_optimizer\n self._dnn_hidden_units = dnn_hidden_units\n self._dnn_activation_fn = dnn_activation_fn\n if self._dnn_activation_fn is None:\n self._dnn_activation_fn = nn.relu\n self._dnn_weight_collection = \"DNNLinearCombined_dnn\"\n self._linear_weight_collection = \"DNNLinearCombined_linear\"\n\n def predict(self, x=None, input_fn=None, batch_size=None):\n \"\"\"Returns predictions for given features.\n\n Args:\n x: features.\n input_fn: Input function. If set, x must be None.\n batch_size: Override default batch size.\n\n Returns:\n Numpy array of predicted classes or regression values.\n \"\"\"\n predictions = self._infer_model(x=x,\n input_fn=input_fn,\n batch_size=batch_size)\n if self._n_classes > 1:\n predictions = np.argmax(predictions, axis=1)\n return predictions\n\n def predict_proba(self, x=None, input_fn=None, batch_size=None):\n \"\"\"Returns prediction probabilities for given features (classification).\n\n Args:\n x: features.\n input_fn: Input function. If set, x and y must be None.\n batch_size: Override default batch size.\n\n Returns:\n Numpy array of predicted probabilities.\n \"\"\"\n return self._infer_model(x=x, input_fn=input_fn, batch_size=batch_size)\n\n def _get_train_ops(self, features, targets):\n \"\"\"See base class.\"\"\"\n global_step = variables.get_global_step()\n assert global_step\n loss = self._loss(\n self._logits(features), targets, self._get_weight_tensor(features))\n logging_ops.scalar_summary(\"loss\", loss)\n\n linear_vars = self._get_linear_vars()\n dnn_vars = self._get_dnn_vars()\n grads = gradients.gradients(loss, dnn_vars + linear_vars)\n dnn_grads = grads[0:len(dnn_vars)]\n linear_grads = grads[len(dnn_vars):]\n\n train_ops = self._get_linear_training_ops(\n linear_grads, linear_vars) + self._get_dnn_training_ops(dnn_grads,\n dnn_vars)\n\n train_step = control_flow_ops.group(*train_ops, name=\"combined_training_op\")\n with ops.control_dependencies([train_step]):\n with ops.get_default_graph().colocate_with(global_step):\n return state_ops.assign_add(global_step, 1).op, loss\n\n def _run_metrics(self, predictions, targets, metrics, weights):\n result = {}\n targets = math_ops.cast(targets, predictions.dtype)\n for name, metric in six.iteritems(metrics or {}):\n if \"weights\" in inspect.getargspec(metric)[0]:\n result[name] = metric(predictions, targets, weights=weights)\n else:\n result[name] = metric(predictions, targets)\n\n return result\n\n def _get_eval_ops(self, features, targets, metrics=None):\n \"\"\"See base class.\"\"\"\n logits = self._logits(features)\n result = {\"loss\": metrics_lib.streaming_mean(self._loss(\n logits, targets,\n weight_tensor=self._get_weight_tensor(features)))}\n\n # Adding default metrics\n if metrics is None and self._n_classes > 1:\n metrics = {\"accuracy\": metrics_lib.streaming_accuracy}\n\n if self._n_classes == 2:\n predictions = math_ops.sigmoid(logits)\n result[\"eval_auc\"] = metrics_lib.streaming_auc(predictions, targets)\n\n if metrics:\n predictions = self._logits_to_predictions(logits, proba=False)\n result.update(self._run_metrics(predictions, targets, metrics,\n self._get_weight_tensor(features)))\n\n return result\n\n def _get_predict_ops(self, features):\n \"\"\"See base class.\"\"\"\n logits = self._logits(features)\n return self._logits_to_predictions(logits, proba=True)\n\n def _logits_to_predictions(self, logits, proba=False):\n if self._n_classes < 2:\n return array_ops.reshape(logits, [-1])\n\n if self._n_classes == 2:\n logits = array_ops.concat(1, [array_ops.zeros_like(logits), logits])\n\n if proba:\n return nn.softmax(logits)\n else:\n return math_ops.argmax(logits, 1)\n\n def _get_feature_ops_from_example(self, examples_batch):\n column_types = layers.create_dict_for_parse_example(\n (self._get_linear_feature_columns() or []) +\n (self._get_dnn_feature_columns() or []))\n features = parsing_ops.parse_example(examples_batch, column_types)\n return features\n\n def _num_label_columns(self):\n return 1 if self._n_classes <= 2 else self._n_classes\n\n def _get_linear_feature_columns(self):\n return sorted(\n set(self._linear_feature_columns),\n key=lambda x: x.key) if self._linear_feature_columns else None\n\n def _get_dnn_feature_columns(self):\n return sorted(set(\n self._dnn_feature_columns)) if self._dnn_feature_columns else None\n\n def _dnn_logits(self, features):\n net = layers.input_from_feature_columns(\n features,\n self._get_dnn_feature_columns(),\n weight_collections=[self._dnn_weight_collection])\n for layer_id, num_hidden_units in enumerate(self._dnn_hidden_units):\n net = layers.legacy_fully_connected(\n net,\n num_hidden_units,\n activation_fn=self._dnn_activation_fn,\n weight_collections=[self._dnn_weight_collection],\n bias_collections=[self._dnn_weight_collection],\n name=\"hiddenlayer_%d\" % layer_id)\n self._add_hidden_layer_summary(net, \"hiddenlayer_%d\" % layer_id)\n logit = layers.legacy_fully_connected(\n net,\n self._num_label_columns(),\n weight_collections=[self._dnn_weight_collection],\n bias_collections=[self._dnn_weight_collection],\n name=\"dnn_logit\")\n self._add_hidden_layer_summary(logit, \"dnn_logit\")\n return logit\n\n def _add_hidden_layer_summary(self, value, tag):\n # TODO(zakaria): Move this code to tf.learn and add test.\n logging_ops.scalar_summary(\"%s:fraction_of_zero_values\" % tag,\n nn.zero_fraction(value))\n logging_ops.histogram_summary(\"%s:activation\" % tag, value)\n\n def _linear_logits(self, features):\n logits, _, _ = layers.weighted_sum_from_feature_columns(\n columns_to_tensors=features,\n feature_columns=self._get_linear_feature_columns(),\n num_outputs=self._num_label_columns(),\n weight_collections=[self._linear_weight_collection],\n name=\"linear\")\n return logits\n\n def _get_feature_dict(self, features):\n if isinstance(features, dict):\n return features\n return {\"\": features}\n\n def _logits(self, features):\n if not (self._get_linear_feature_columns() or\n self._get_dnn_feature_columns()):\n raise ValueError(\"Either linear_feature_columns or dnn_feature_columns \"\n \"should be defined.\")\n\n features = self._get_feature_dict(features)\n if self._get_linear_feature_columns() and self._get_dnn_feature_columns():\n return self._linear_logits(features) + self._dnn_logits(features)\n elif self._get_dnn_feature_columns():\n return self._dnn_logits(features)\n else:\n return self._linear_logits(features)\n\n def _get_weight_tensor(self, features):\n if not self._weight_column_name:\n return None\n else:\n return array_ops.reshape(\n math_ops.to_float(features[self._weight_column_name]),\n shape=(-1,))\n\n def _loss(self, logits, target, weight_tensor):\n if self._n_classes < 2:\n loss_vec = math_ops.square(logits - math_ops.to_float(target))\n elif self._n_classes == 2:\n loss_vec = nn.sigmoid_cross_entropy_with_logits(logits,\n math_ops.to_float(target))\n else:\n loss_vec = nn.sparse_softmax_cross_entropy_with_logits(\n logits, array_ops.reshape(target, [-1]))\n\n if weight_tensor is None:\n return math_ops.reduce_mean(loss_vec, name=\"loss\")\n else:\n loss_vec = array_ops.reshape(loss_vec, shape=(-1,))\n loss_vec = math_ops.mul(\n loss_vec, array_ops.reshape(weight_tensor, shape=(-1,)))\n return math_ops.div(\n math_ops.reduce_sum(loss_vec),\n math_ops.to_float(math_ops.reduce_sum(weight_tensor)),\n name=\"loss\")\n\n def _get_linear_vars(self):\n if self._get_linear_feature_columns():\n return ops.get_collection(self._linear_weight_collection)\n return []\n\n def _get_linear_training_ops(self, linear_grads, linear_vars):\n if self._get_linear_feature_columns():\n self._linear_optimizer = self._get_optimizer(\n self._linear_optimizer,\n default_optimizer=\"Ftrl\",\n default_learning_rate=1. / math.sqrt(len(\n self._get_linear_feature_columns())))\n return [\n self._linear_optimizer.apply_gradients(zip(linear_grads, linear_vars))\n ]\n return []\n\n def _get_dnn_vars(self):\n if self._get_dnn_feature_columns():\n return ops.get_collection(self._dnn_weight_collection)\n return []\n\n def _get_dnn_training_ops(self, dnn_grads, dnn_vars):\n if self._get_dnn_feature_columns():\n self._dnn_optimizer = self._get_optimizer(self._dnn_optimizer,\n default_optimizer=\"Adagrad\",\n default_learning_rate=0.05)\n return [self._dnn_optimizer.apply_gradients(zip(dnn_grads, dnn_vars))]\n return []\n\n def _get_optimizer(self, optimizer, default_optimizer, default_learning_rate):\n if optimizer is None:\n optimizer = default_optimizer\n if isinstance(optimizer, six.string_types):\n optimizer = layers.OPTIMIZER_CLS_NAMES[optimizer](\n learning_rate=default_learning_rate)\n return optimizer\n\n\nclass DNNLinearCombinedClassifier(_DNNLinearCombinedBaseEstimator):\n \"\"\"A classifier for TensorFlow Linear and DNN joined training models.\n\n Example:\n ```\n installed_app_id = sparse_column_with_hash_bucket(\"installed_id\", 1e6)\n impression_app_id = sparse_column_with_hash_bucket(\"impression_id\", 1e6)\n\n installed_x_impression = crossed_column(\n [installed_app_id, impression_app_id])\n\n installed_emb = embedding_column(installed_app_id, dimension=16,\n combiner=\"sum\")\n impression_emb = embedding_column(impression_app_id, dimension=16,\n combiner=\"sum\")\n\n estimator = DNNLinearCombinedClassifier(\n # common settings\n n_classes, weight_column_name,\n # wide settings\n linear_feature_columns=[installed_x_impression],\n linear_optimizer=tf.train.FtrlOptimizer(...),\n # deep settings\n dnn_feature_columns=[installed_emb, impression_emb],\n dnn_hidden_units=[1000, 500, 100],\n dnn_optimizer=tf.train.AdagradOptimizer(...))\n\n # Input builders\n def input_fn_train: # returns X, Y\n ...\n def input_fn_eval: # returns X, Y\n ...\n estimator.train(input_fn_train)\n estimator.evaluate(input_fn_eval)\n estimator.predict(x)\n ```\n\n Input of `fit`, `train`, and `evaluate` should have following features,\n otherwise there will be a `KeyError`:\n if `weight_column_name` is not `None`, a feature with\n `key=weight_column_name` whose value is a `Tensor`.\n for each `column` in `dnn_feature_columns` + `linear_feature_columns`:\n - if `column` is a `SparseColumn`, a feature with `key=column.name`\n whose `value` is a `SparseTensor`.\n - if `column` is a `RealValuedColumn, a feature with `key=column.name`\n whose `value` is a `Tensor`.\n\n Parameters:\n model_dir: Directory to save model parameters, graph and etc.\n n_classes: number of target classes. Default is binary classification.\n weight_column_name: A string defining feature column name representing\n weights. It is used to down weight or boost examples during training. It\n will be multiplied by the loss of the example.\n linear_feature_columns: An iterable containing all the feature columns used\n by linear part of the model. All items in the set must be instances of\n classes derived from `FeatureColumn`.\n linear_optimizer: An instance of `tf.Optimizer` used to apply gradients to\n the linear part of the model. If `None`, will use a FTRL optimizer.\n dnn_feature_columns: An iterable containing all the feature columns used by\n deep part of the model. All items in the set must be instances of\n classes derived from `FeatureColumn`.\n dnn_hidden_units: List of hidden units per layer. All layers are fully\n connected.\n dnn_optimizer: An instance of `tf.Optimizer` used to apply gradients to the\n deep part of the model. If `None`, will use an Adagrad optimizer.\n dnn_activation_fn: Activation function applied to each layer. If `None`,\n will use `tf.nn.relu`.\n config: RunConfig object to configure the runtime settings.\n\n Raises:\n ValueError: If both linear_feature_columns and dnn_features_columns are\n empty at the same time.\n ValueError: If both n_classes < 2.\n \"\"\"\n\n def __init__(self,\n model_dir=None,\n n_classes=2,\n weight_column_name=None,\n linear_feature_columns=None,\n linear_optimizer=None,\n dnn_feature_columns=None,\n dnn_optimizer=None,\n dnn_hidden_units=None,\n dnn_activation_fn=nn.relu,\n config=None):\n if n_classes < 2:\n raise ValueError(\"n_classes should be greater than 1. Given: {}\".format(\n n_classes))\n\n super(DNNLinearCombinedClassifier, self).__init__(\n model_dir=model_dir,\n n_classes=n_classes,\n weight_column_name=weight_column_name,\n linear_feature_columns=linear_feature_columns,\n linear_optimizer=linear_optimizer,\n dnn_feature_columns=dnn_feature_columns,\n dnn_optimizer=dnn_optimizer,\n dnn_hidden_units=dnn_hidden_units,\n dnn_activation_fn=dnn_activation_fn,\n config=config)\n\n\nclass DNNLinearCombinedRegressor(_DNNLinearCombinedBaseEstimator):\n \"\"\"A regressor for TensorFlow Linear and DNN joined training models.\n\n Example:\n ```\n installed_app_id = sparse_column_with_hash_bucket(\"installed_id\", 1e6)\n impression_app_id = sparse_column_with_hash_bucket(\"impression_id\", 1e6)\n\n installed_x_impression = crossed_column(\n [installed_app_id, impression_app_id])\n\n installed_emb = embedding_column(installed_app_id, dimension=16,\n combiner=\"sum\")\n impression_emb = embedding_column(impression_app_id, dimension=16,\n combiner=\"sum\")\n\n estimator = DNNLinearCombinedClassifier(\n # common settings\n n_classes, weight_column_name,\n # wide settings\n linear_feature_columns=[installed_x_impression],\n linear_optimizer=tf.train.FtrlOptimizer(...),\n # deep settings\n dnn_feature_columns=[installed_emb, impression_emb],\n dnn_hidden_units=[1000, 500, 100],\n dnn_optimizer=tf.train.AdagradOptimizer(...))\n\n # Input builders\n def input_fn_train: # returns X, Y\n ...\n def input_fn_eval: # returns X, Y\n ...\n estimator.train(input_fn_train)\n estimator.evaluate(input_fn_eval)\n estimator.predict(x)\n ```\n\n Input of `fit`, `train`, and `evaluate` should have following features,\n otherwise there will be a `KeyError`:\n if `weight_column_name` is not `None`, a feature with\n `key=weight_column_name` whose value is a `Tensor`.\n for each `column` in `dnn_feature_columns` + `linear_feature_columns`:\n - if `column` is a `SparseColumn`, a feature with `key=column.name`\n whose `value` is a `SparseTensor`.\n - if `column` is a `RealValuedColumn, a feature with `key=column.name`\n whose `value` is a `Tensor`.\n\n Parameters:\n model_dir: Directory to save model parameters, graph and etc.\n weight_column_name: A string defining feature column name representing\n weights. It is used to down weight or boost examples during training. It\n will be multiplied by the loss of the example.\n linear_feature_columns: An iterable containing all the feature columns used\n by linear part of the model. All items in the set must be instances of\n classes derived from `FeatureColumn`.\n linear_optimizer: An instance of `tf.Optimizer` used to apply gradients to\n the linear part of the model. If `None`, will use a FTRL optimizer.\n dnn_feature_columns: An iterable containing all the feature columns used by\n deep part of the model. All items in the set must be instances of\n classes derived from `FeatureColumn`.\n dnn_hidden_units: List of hidden units per layer. All layers are fully\n connected.\n dnn_optimizer: An instance of `tf.Optimizer` used to apply gradients to the\n deep part of the model. If `None`, will use an Adagrad optimizer.\n dnn_activation_fn: Activation function applied to each layer. If None, will\n use `tf.nn.relu`.\n config: RunConfig object to configure the runtime settings.\n\n Raises:\n ValueError: If both linear_feature_columns and dnn_features_columns are\n empty at the same time.\n \"\"\"\n\n def __init__(self,\n model_dir=None,\n weight_column_name=None,\n linear_feature_columns=None,\n linear_optimizer=None,\n dnn_feature_columns=None,\n dnn_optimizer=None,\n dnn_hidden_units=None,\n dnn_activation_fn=nn.relu,\n config=None):\n super(DNNLinearCombinedRegressor, self).__init__(\n model_dir=model_dir,\n n_classes=0,\n weight_column_name=weight_column_name,\n linear_feature_columns=linear_feature_columns,\n linear_optimizer=linear_optimizer,\n dnn_feature_columns=dnn_feature_columns,\n dnn_optimizer=dnn_optimizer,\n dnn_hidden_units=dnn_hidden_units,\n dnn_activation_fn=dnn_activation_fn,\n config=config)\n"
]
| [
[
"tensorflow.python.ops.nn.softmax",
"tensorflow.contrib.metrics.streaming_auc",
"tensorflow.python.ops.state_ops.assign_add",
"tensorflow.python.ops.logging_ops.scalar_summary",
"tensorflow.python.ops.logging_ops.histogram_summary",
"tensorflow.python.ops.nn.zero_fraction",
"tensorflow.python.ops.math_ops.to_float",
"tensorflow.python.ops.math_ops.argmax",
"tensorflow.python.framework.ops.get_collection",
"numpy.argmax",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.contrib.framework.python.ops.variables.get_global_step",
"tensorflow.python.ops.array_ops.zeros_like",
"tensorflow.python.ops.math_ops.reduce_mean",
"tensorflow.python.ops.math_ops.sigmoid",
"tensorflow.python.ops.gradients.gradients",
"tensorflow.python.ops.control_flow_ops.group",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.contrib.layers.legacy_fully_connected",
"tensorflow.python.ops.parsing_ops.parse_example",
"tensorflow.python.ops.math_ops.reduce_sum"
]
]
|
cabrust/chia | [
"3eaf815b261dc8a85d64fd698e0079515ec0dde9"
]
| [
"chia/components/base_models/keras/keras_featureextractor.py"
]
| [
"import tensorflow as tf\nfrom tensorflow.keras.applications import (\n inception_resnet_v2,\n mobilenet_v2,\n nasnet,\n resnet_v2,\n)\n\nfrom chia import components, helpers, instrumentation\n\n\nclass KerasFeatureExtractor(instrumentation.Observable):\n def __init__(\n self,\n side_length,\n use_pretrained_weights=\"ILSVRC2012\",\n architecture=\"ResNet50V2\",\n l2=5e-5,\n trainable=False,\n ):\n instrumentation.Observable.__init__(self)\n\n # Weights\n self.use_pretrained_weights = use_pretrained_weights\n\n # Architecture\n self.architecture = architecture\n if self.architecture == \"ResNet50V2\":\n self.feature_extractor = resnet_v2.ResNet50V2(\n include_top=False,\n input_tensor=None,\n input_shape=None,\n pooling=\"avg\",\n weights=\"imagenet\"\n if self.use_pretrained_weights == \"ILSVRC2012\"\n else None,\n )\n\n elif self.architecture == \"InceptionResNetV2\":\n self.feature_extractor = inception_resnet_v2.InceptionResNetV2(\n include_top=False,\n input_tensor=None,\n input_shape=None,\n pooling=\"avg\",\n weights=\"imagenet\"\n if self.use_pretrained_weights == \"ILSVRC2012\"\n else None,\n )\n\n elif self.architecture == \"MobileNetV2\":\n self.side_length = side_length\n self.feature_extractor = mobilenet_v2.MobileNetV2(\n include_top=False,\n input_tensor=None,\n input_shape=(self.side_length, self.side_length, 3),\n pooling=\"avg\",\n weights=\"imagenet\"\n if self.use_pretrained_weights == \"ILSVRC2012\"\n else None,\n )\n\n elif self.architecture == \"NASNetMobile\":\n self.side_length = side_length\n self.feature_extractor = nasnet.NASNetMobile(\n include_top=False,\n input_tensor=None,\n input_shape=(self.side_length, self.side_length, 3),\n pooling=\"avg\",\n weights=\"imagenet\"\n if self.use_pretrained_weights == \"ILSVRC2012\"\n else None,\n )\n\n else:\n raise ValueError(f'Unknown architecture \"{self.architecture}\"')\n\n # Load other pre-trained weights if necessary\n if (\n self.use_pretrained_weights is not None\n and self.use_pretrained_weights != \"ILSVRC2012\"\n ):\n self.log_info(\n f\"Loading alternative pretrained weights {self.use_pretrained_weights}\"\n )\n self.feature_extractor.load_weights(\n helpers.maybe_expand_path(self.use_pretrained_weights, self)\n )\n\n # Freezing of layers\n self.trainable = trainable\n if not self.trainable:\n for layer in self.feature_extractor.layers:\n layer.trainable = False\n\n # L2 Regularization\n self.l2_regularization = l2\n self._add_l2_regularizers()\n\n def _add_l2_regularizers(self):\n if self.l2_regularization == 0:\n return\n\n # Add regularizer:\n # see https://jricheimer.github.io/keras/2019/02/06/keras-hack-1/\n for layer in self.feature_extractor.layers:\n if (\n isinstance(layer, tf.keras.layers.Conv2D)\n and not isinstance(layer, tf.keras.layers.DepthwiseConv2D)\n ) or isinstance(layer, tf.keras.layers.Dense):\n layer.add_loss(\n lambda layer=layer: tf.keras.regularizers.l2(\n self.l2_regularization\n )(layer.kernel)\n )\n elif isinstance(layer, tf.keras.layers.DepthwiseConv2D):\n layer.add_loss(\n lambda layer=layer: tf.keras.regularizers.l2(\n self.l2_regularization\n )(layer.depthwise_kernel)\n )\n if hasattr(layer, \"bias_regularizer\") and layer.use_bias:\n layer.add_loss(\n lambda layer=layer: tf.keras.regularizers.l2(\n self.l2_regularization\n )(layer.bias)\n )\n\n def __call__(self, image_batch, training):\n return self.feature_extractor(image_batch, training)\n\n\nclass KerasFeatureExtractorFactory(components.Factory):\n name_to_class_mapping = KerasFeatureExtractor\n default_section = \"keras_feature_extractor\"\n"
]
| [
[
"tensorflow.keras.regularizers.l2",
"tensorflow.keras.applications.mobilenet_v2.MobileNetV2",
"tensorflow.keras.applications.resnet_v2.ResNet50V2",
"tensorflow.keras.applications.inception_resnet_v2.InceptionResNetV2",
"tensorflow.keras.applications.nasnet.NASNetMobile"
]
]
|
amrishAK/-DeviceSimulation | [
"aa06359a8a3fc1e728dc55eda6450f77ada2b309"
]
| [
"Characteristics/bokeh visuals amrish.py"
]
| [
"import json\nimport pandas as pd\nfrom pandas.io.json import json_normalize\nimport numpy as np\n\nfrom bokeh.io import output_file, output_notebook, save\nfrom bokeh.plotting import figure, show\nfrom bokeh.models import ColumnDataSource, LabelSet\nfrom bokeh.layouts import row, column, gridplot\nfrom bokeh.models.widgets import Tabs, Panel\nfrom bokeh.plotting import reset_output\n\nimport random\n\nfiles = ['batterylog.json'] #### add log file paths\nout_html = \"dashboard_amrish.html\" #### add path for output dashboard html file\n\n\ncs = ''\nfigures = ''\n \nfor i in range(len(files)):\n with open(files[i]) as data_file:\n j = json.load(data_file)\n\n df = pd.io.json.json_normalize(j['Log'])\n df['TimeStamp'] = df['TimeStamp'].astype('datetime64[s]')\n\n df2 = df[['TimeStamp','CurrentPower']]\n df2 = df2.sort_values(by = 'TimeStamp')\n df2 = df2.set_index('TimeStamp')\n\n figures = figures + \"'p_\"+str(i)+\"', \"\n cs = cs + \"\\n\\n\" + \"source = ColumnDataSource(df2); \\np_\"+str(i)+\" = figure(x_axis_type='datetime', plot_width=500, plot_height=250, title = 'Remaining Power'); \\np_\"+str(i)+\".line('TimeStamp', 'CurrentPower', source=source, color='firebrick'); \\np_\"+str(i)+\".sizing_mode = 'scale_width'\"\n exec(cs)\n# output_file('filename.html', mode='inline')\n# save(column(row(p,p1),p2))\n# reset_output()\n\ns_fig_list = \"fig_list = list([\"+figures[:-2]+\"])\"\n\nexec(s_fig_list)\n\ns = ''\nfor i in range(len(fig_list)):\n if i%2 == 0:\n try:\n s = s + \"row(\"+fig_list[i]+\",\"+fig_list[i+1]+\"),\"\n except:\n s = s + \"row(\"+fig_list[i]+\"),\"\n\nstruct_s = \"save(column(\"+s[:-1]+\"))\"\noutput_file(out_html, mode='inline')\nexec(struct_s)"
]
| [
[
"pandas.io.json.json_normalize"
]
]
|
nickeener/starfish | [
"7f74fb9143661929b6614b6f46b3521faa24cdaf"
]
| [
"starfish/core/spots/DecodeSpots/check_all_decoder.py"
]
| [
"from copy import deepcopy\nfrom typing import Any, Hashable, Mapping, Tuple\n\nimport numpy as np\nimport pandas as pd\n\nfrom starfish.core.codebook.codebook import Codebook\nfrom starfish.core.intensity_table.decoded_intensity_table import DecodedIntensityTable\nfrom starfish.core.intensity_table.intensity_table import IntensityTable\nfrom starfish.core.intensity_table.intensity_table_coordinates import \\\n transfer_physical_coords_to_intensity_table\nfrom starfish.core.types import SpotFindingResults\nfrom starfish.types import Axes, Features\nfrom ._base import DecodeSpotsAlgorithm\nfrom .check_all_funcs import buildBarcodes, cleanup, createRefDicts, decoder, distanceFilter, \\\n removeUsedSpots\nfrom .util import _merge_spots_by_round\n\nclass CheckAll(DecodeSpotsAlgorithm):\n \"\"\"\n Decode spots by generating all possible combinations of spots to form barcodes given a radius\n distance that spots must be from each other in order to form a barcode. Then chooses the best\n set of nonoverlapping spot combinations by choosing the ones with the least spatial variance\n of their spot coordinates and are also found to be best for multiple spots in the barcode\n (see algorithm below). Allows for error correction rounds.\n\n (see input parmeters below)\n 1. For each spot in each round, find all neighbors in other rounds that are within the search\n radius\n 2. For each spot in each round, build all possible full length barcodes based on the channel\n labels of the spot's neighbors and itself\n 3. Drop barcodes that don't have a matching target in the codebook\n 4. Choose the \"best\" barcode of each spot's possible target matching barcodes by calculating\n the sum of variances for each of the spatial coordinates of the spots that make up each barcode\n and choosing the minimum distance barcode (if there is a tie, they are all dropped as\n ambiguous). Each spot is assigned a \"best\" barcode in this way.\n 5. Only keep barcodes/targets that were found as \"best\" using at least 2 of the spots that make\n each up\n 6. Find maximum independent set (approximation) of the spot combinations so no two barcodes use\n the same spot\n 7. Remove all spots used in decoded targets that passed the previous filtering steps from the\n original set of spots\n 8. Rerun steps 2-5 for barcodes that use less than the full set of rounds for codebook\n matching (how many rounds can be dropped determined by error_rounds parameter)\n\n Parameters\n ----------\n codebook : Codebook\n Contains codes to decode IntensityTable\n search_radius : float\n Number of pixels over which to search for spots in other rounds and channels.\n error_rounds : int\n Maximum hamming distance a barcode can be from it's target in the codebook and still be\n uniquely identified (i.e. number of error correction rounds in each the experiment)\n \"\"\"\n\n def __init__(\n self,\n codebook: Codebook,\n search_radius: float=3,\n error_rounds: int=0):\n self.codebook = codebook\n self.searchRadius = search_radius\n self.errorRounds = error_rounds\n\n def run(self,\n spots: SpotFindingResults,\n n_processes: int=1,\n *args) -> DecodedIntensityTable:\n \"\"\"\n Decode spots by finding the set of nonoverlapping barcodes that have the minimum spatial\n variance within each barcode\n\n Parameters\n ----------\n spots: SpotFindingResults\n A Dict of tile indices and their corresponding measured spots\n\n n_processes: int\n Number of threads to run decoder in parallel with\n\n Returns\n -------\n DecodedIntensityTable :\n IntensityTable decoded and appended with Features.TARGET and Features.QUALITY values.\n\n \"\"\"\n\n # Rename n_processes (trying to stay consistent between starFISH's _ variables and my\n # camel case ones)\n numJobs = n_processes\n\n # If using an search radius exactly equal to a possible distance between two pixels\n # (ex: 1), some distances will be calculated as slightly less than their exact distance\n # (either due to rounding or precision errors) so search radius needs to be slightly\n # increased to ensure this doesn't happen\n self.searchRadius += 0.001\n\n # Create dictionary where keys are round labels and the values are pandas dataframes\n # containing information on the spots found in that round\n spotTables = _merge_spots_by_round(spots)\n\n # Add one to channels labels (prevents collisions between hashes of barcodes later)\n for r in spots.round_labels:\n spotTables[r]['c'] += 1\n\n # Set list of round omission numbers to loop through\n roundOmits = range(self.errorRounds + 1)\n\n # Decode for each round omission number, store results in allCodes table\n allCodes = pd.DataFrame()\n for currentRoundOmitNum in roundOmits:\n\n # Create necessary reference dictionaries\n neighborDict, channelDict, spotCoords = createRefDicts(spotTables, self.searchRadius)\n\n # Chooses best barcode for all spots in each round sequentially (possible barcode\n # space can become quite large which can increase memory needs so I do it this way so\n # we only need to store all potential barcodes that originate from one round at a\n # time)\n decodedTables = {}\n for r in range(len(spotTables)):\n roundData = deepcopy(spotTables[r])\n roundData = roundData.drop(['intensity', 'z', 'y', 'x', 'radius', 'c'], axis=1)\n roundData.index += 1\n\n # Create dictionary of dataframes (based on spotTables data) that contains\n # additional columns for each spot containing all the possible barcodes that\n # could be constructed from the neighbors of that spot\n roundData = buildBarcodes(roundData, neighborDict, currentRoundOmitNum,\n channelDict, r, numJobs)\n\n # Match possible barcodes to codebook and add new columns with info about barcodes\n # that had a codebook match\n roundData = decoder(roundData, self.codebook, currentRoundOmitNum, r, numJobs)\n\n # Choose most likely barcode for each spot in each round by find the possible\n # decodable barcode with the least spatial variance between the spots that made up\n # the barcode\n roundData = distanceFilter(roundData, spotCoords, r, numJobs)\n\n # Assign to DecodedTables dictionary\n decodedTables[r] = roundData\n\n # Only do the following if barcodes were founds\n totalSpots = sum([len(decodedTables[table]) for table in decodedTables])\n if totalSpots:\n\n # Turn spot table dictionary into single table, filter barcodes by round frequency,\n # add additional information, and choose between barcodes that have overlapping\n # spots\n finalCodes = cleanup(decodedTables, spotCoords, channelDict)\n\n # If this is not the last round omission number to run, remove spots that have just\n # been found to be in passing barcodes from spotTables so they are not used for the\n # next round omission number\n if currentRoundOmitNum != roundOmits[-1]:\n spotTables = removeUsedSpots(finalCodes, spotTables)\n\n # Append found codes to allCodes table\n allCodes = allCodes.append(finalCodes).reset_index(drop=True)\n\n # Create and fill in intensity table\n channels = spots.ch_labels\n rounds = spots.round_labels\n\n # create empty IntensityTable filled with np.nan\n data = np.full((len(allCodes), len(rounds), len(channels)), fill_value=np.nan)\n dims = (Features.AXIS, Axes.ROUND.value, Axes.CH.value)\n centers = allCodes['center']\n coords: Mapping[Hashable, Tuple[str, Any]] = {\n Features.SPOT_RADIUS: (Features.AXIS, np.full(len(allCodes), 1)),\n Axes.ZPLANE.value: (Features.AXIS, np.asarray([round(c[2]) for c in centers])),\n Axes.Y.value: (Features.AXIS, np.asarray([round(c[1]) for c in centers])),\n Axes.X.value: (Features.AXIS, np.asarray([round(c[0]) for c in centers])),\n Features.SPOT_ID: (Features.AXIS, np.arange(len(allCodes))),\n Features.AXIS: (Features.AXIS, np.arange(len(allCodes))),\n Axes.ROUND.value: (Axes.ROUND.value, rounds),\n Axes.CH.value: (Axes.CH.value, channels)\n }\n int_table = IntensityTable(data=data, dims=dims, coords=coords)\n\n # Fill in data values\n table_codes = []\n for i in range(len(allCodes)):\n code = []\n for ch in allCodes.loc[i, 'best_barcodes']:\n # If a round is not used, row will be all zeros\n code.append(np.asarray([0 if j != ch else 1 for j in range(len(channels))]))\n table_codes.append(np.asarray(code))\n int_table.values = np.asarray(table_codes)\n int_table = transfer_physical_coords_to_intensity_table(intensity_table=int_table,\n spots=spots)\n\n # Validate results are correct shape\n self.codebook._validate_decode_intensity_input_matches_codebook_shape(int_table)\n\n # Create DecodedIntensityTable\n result = DecodedIntensityTable.from_intensity_table(\n int_table,\n targets=(Features.AXIS, allCodes['best_targets'].astype('U')),\n distances=(Features.AXIS, allCodes[\"best_distances\"]),\n passes_threshold=(Features.AXIS, np.full(len(allCodes), True)),\n rounds_used=(Features.AXIS, allCodes['rounds_used']))\n\n return result\n"
]
| [
[
"numpy.asarray",
"pandas.DataFrame"
]
]
|
mrlucasrib/inteligencia-artificial-ufop | [
"f6ce14267c56b61e1c3e6d40e7da9a937427e102"
]
| [
"lesson2/main.py"
]
| [
"from dataclasses import dataclass, field\nimport numpy as np\nfrom utils.definitions import ABCAgent, ABCEnvironment\nfrom scipy.spatial import distance\n\n\nclass Environment(ABCEnvironment):\n\n def __init__(self, map, start, goal):\n self.map = np.array(map)\n self.start = np.array(start)\n self.goal = np.array(goal)\n self.agent_position = np.array(start)\n self.actions = np.array([[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]])\n\n def initial_percepts(self):\n available = []\n for a in self.actions:\n pos = self.start + a\n if (0 <= pos[0] < self.map.shape[0]) and (0 <= pos[1] < self.map.shape[1]) and self.map[pos[0]][\n pos[1]] == 0:\n available.append(pos)\n\n return {'available_positions': available,\n 'position': self.agent_position,\n 'goal': self.goal}\n\n def signal(self, action):\n\n self.agent_position = action['go_to']\n\n available = []\n for a in self.actions:\n pos = self.agent_position + a\n if (0 <= pos[0] < self.map.shape[0]) and (0 <= pos[1] < self.map.shape[1]) and self.map[pos[0]][\n pos[1]] == 0:\n available.append(pos)\n\n return {'available_positions': available,\n 'position': self.agent_position,\n 'goal': self.goal}\n\n\nclass AgentBFS(ABCAgent):\n\n def __init__(self, env):\n\n self.belief_state = env.initial_percepts()\n self.env = env\n\n def act(self):\n\n F = [[self.belief_state['position']]]\n\n while F:\n path = F.pop(0)\n\n self.belief_state = self.env.signal({'go_to': path[-1]})\n\n if (path[-1] == self.belief_state['goal']).all():\n return path\n else:\n for p in self.belief_state['available_positions']:\n F.append(path + [p])\n\n return []\n\n\nclass AgentDFS(ABCAgent):\n\n def __init__(self, env):\n\n self.belief_state = env.initial_percepts()\n self.env = env\n\n def act(self):\n\n F = [[self.belief_state['position']]]\n\n while F:\n path = F.pop(0)\n\n self.belief_state = self.env.signal({'go_to': path[-1]})\n\n if (path[-1] == self.belief_state['goal']).all():\n return path\n else:\n for p in self.belief_state['available_positions']:\n # Checks whether a cycle will be made\n makes_cycle = False\n for pos in path:\n if (pos == p).all():\n makes_cycle = True\n break\n\n if not makes_cycle:\n F = [path + [p]] + F\n\n return []\n\n\nclass GreedyAgent(ABCAgent):\n def __init__(self, env):\n self.belief_state = env.initial_percepts()\n self.frontier = [[self.belief_state['position']]]\n self.visited = []\n\n def act(self):\n \"\"\"Implements the agent action\n \"\"\"\n\n # Select a path from the frontier\n cost = 999999\n j = 0\n k = 0\n\n for i in self.frontier:\n if distance.euclidean(i[-1], self.belief_state['goal']) < cost:\n j = k\n cost = distance.euclidean(i[-1], self.belief_state['goal'])\n k = k + 1\n\n # Path with the lowest value of heuristic function of frontier\n path = self.frontier.pop(j)\n\n # Visit the last node in the path\n action = {'go_to': path[-1]}\n # The agente sends a position and the full path to the environment\n self.belief_state = self.env.signal(action)\n\n # Add visited node\n self.visited.append(path[-1])\n\n # From the list of viable available_positions given by the environment\n # Select a random neighbor that has not been visited yet\n\n viable_neighbors = self.belief_state['available_positions']\n\n # If the agent is not stuck\n if viable_neighbors:\n for neighbor in viable_neighbors:\n\n # Multiple-Path Pruning\n exist = False\n\n for node in self.visited:\n if (node == neighbor).all():\n exist = True\n break\n\n # If node is not in self.visited\n if exist == False:\n self.frontier = [path + [neighbor]] + self.frontier\n\n def run(self):\n \"\"\"Keeps the agent acting until it finds the goal\n \"\"\"\n\n # Run agent\n while (self.belief_state['position'] != self.belief_state['goal']).any() and self.frontier:\n self.act()\n\n print(self.belief_state['position'])\n\n\nclass AStarAgent(ABCAgent):\n def __init__(self, env):\n self.env = env\n self.belief_state = env.initial_percepts()\n self.frontier = [[self.belief_state['position']]]\n self.cost = [0]\n # Initializes list of visited nodes for multiple path prunning\n self.visited = []\n\n def act(self):\n \"\"\"Implements the agent action\n \"\"\"\n\n # Select a path from the frontier\n cost = 999999\n j = 0\n k = 0\n\n for i in self.frontier:\n if self.cost[k] + distance.euclidean(i[-1], self.belief_state['goal']) < cost:\n j = k\n cost = self.cost[k] + distance.euclidean(i[-1], self.belief_state['goal'])\n k = k + 1\n\n # Path with the lowest value of cost + heuristic function of frontier\n path = self.frontier.pop(j)\n cost = self.cost.pop(j)\n\n # Visit the last node in the path\n action = {'go_to': path[-1]}\n # Send position\n self.belief_state = self.env.signal(action)\n\n # Add visited node\n self.visited.append(path[-1])\n\n # From the list of viable available_positions given by the environment\n # Select a random neighbor that has not been visited yet\n\n viable_neighbors = self.belief_state['available_positions']\n\n # If the agent is not stuck\n if viable_neighbors:\n for neighbor in viable_neighbors:\n\n # Multiple-Path Pruning\n exist = False\n\n for node in self.visited:\n if (node == neighbor).all():\n exist = True\n break\n\n # If node is not in self.visited\n if exist == False:\n self.frontier = [path + [neighbor]] + self.frontier\n self.cost = [cost + distance.euclidean(path[-1], neighbor)] + self.cost\n\n def run(self):\n \"\"\"Keeps the agent acting until it finds the goal\n \"\"\"\n\n # Run agent\n while (self.belief_state['position'] != self.belief_state['goal']).any() and self.frontier:\n self.act()\n print(self.belief_state['position'])\n\n\nif __name__ == \"__main__\":\n map = [[0, 0, 1],\n [1, 0, 1],\n [1, 0, 0]]\n\n env = Environment(map, [0, 0], [2, 2])\n\n ag = AStarAgent(env)\n\n ag.run()\n\n GreedyAgent(env).run()\n"
]
| [
[
"numpy.array",
"scipy.spatial.distance.euclidean"
]
]
|
ErikNoren92/Exjobb | [
"eb4b36d2241043a7b81f6bf9ff5596176aebcd27"
]
| [
"segmentering/plotData.py"
]
| [
"import numpy as np\nfrom vispy import scene, visuals, app, gloo\nimport matplotlib.pyplot as plt\nimport sys\n#import nn\n\n\npointCloud = []\ninputFile = open(\"set2.pcd\",\"r\")\nfor line in inputFile:\n\ttry:\n\t\tfloats=[float(x) for x in line.split(\" \")]\n\t\t#if floats[2]>groundLevel and floats[0] < 40 and floats[0] > -40 and floats[1] < 40 and floats[1] > -40 :\n\t\t#print(floats)\n\t\tpointCloud.append(floats)\n\texcept Exception as e:\n\t\tpass\n\ndata = np.asarray(pointCloud,dtype=np.float32)\n\ncanvas = scene.SceneCanvas(keys='interactive', show=True)\nview = canvas.central_widget.add_view()\n\ncolor1 = np.array([[1, 0, 0.4]] * 123398)\ncolor2 = np.array([[0.4, 1, 0]] * 128)\ncolor3 = np.array([[0, 0.4, 1]] * 128)\n\n\n\n# Create the scatter plot\nscatter = scene.visuals.Markers()\nprint(data.shape)\nscatter.set_data(data[:,:2], face_color=color1,size=0.5)\nview.add(scatter)\nview.camera = scene.PanZoomCamera(aspect=1)\nview.camera.set_range()\napp.run()\n\n#plt.cm.jet(data[:,2]"
]
| [
[
"numpy.asarray",
"numpy.array"
]
]
|
fmckenna/BRAILS | [
"cdd4ca4bbc50cbf58f03877b46f1b3d10a281204"
]
| [
"brails/modules/Year_Built_Classifier/train.py"
]
| [
"'''\n@author: Sascha Hornauer\nThis code is a heavily modified but based on Progressive Multi-Granularity Training of\nDu, Ruoyi and Chang, Dongliang and Bhunia, Ayan Kumar and Xie, Jiyang and Song, Yi-Zhe and Ma, Zhanyu and Guo, Jun\n\nSee the LICENSE file for further citation information\n'''\n\nfrom __future__ import print_function\nimport os\n\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nimport numpy as np\nfrom lib.datasets import YearBuiltFolder\nfrom torchvision.transforms import transforms\nfrom lib.utils import load_model, cosine_anneal_schedule, jigsaw_generator, \\\n test_softlabels, test\nfrom torch.autograd.variable import Variable\nimport argparse\n\nparser = argparse.ArgumentParser(description='Classify Year Built')\n\nparser.add_argument('--image-path', help='Path to one image or a folder containing images.', required=True)\nparser.add_argument('--epochs', help='Epochs to train', default=200)\nparser.add_argument('--batch-size', help='Batch size to use for training. Recommended is 128 for 8 GPUs or significantly less when no GPU is available. Default is 8', default=8)\nparser.add_argument('--soft-labels', help='Activate soft labels', action='store_true')\nparser.add_argument('--gaussian-std', help='Standard deviation of the unimodal gaussian used to model class membership', default=1.5)\nparser.add_argument('--checkpoint', default='', type=str,\n help='Path to checkpoint. Defaults to best pretrained version.')\nparser.add_argument('--exp-name', default='unnamed_experiment', help='Name of this experiment for saved files.')\n\nargs = parser.parse_args()\n\ndef train(nb_epoch, batch_size, store_name, image_path, soft_labels=False, gaussian_std=1.5, resume=False, start_epoch=0, model_path=None):\n batch_size = int(batch_size)\n nb_epoch = int(nb_epoch)\n start_epoch = int(start_epoch)\n \n exp_dir = store_name\n try:\n os.stat(exp_dir)\n except:\n os.makedirs(exp_dir)\n\n use_cuda = torch.cuda.is_available()\n # GPU\n # Data\n print('==> Preparing data..')\n transform_train = transforms.Compose([\n transforms.Scale((550, 550)),\n transforms.RandomCrop(448, padding=8),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n \n transform_test = transforms.Compose([\n transforms.Scale((550, 550)),\n transforms.CenterCrop(448),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n \n trainset = YearBuiltFolder(image_path, calc_perf=True,soft_labels=soft_labels, gaussian_std=gaussian_std, transforms=transform_train)\n \n train_weights = np.array(trainset.train_weights)\n train_sampler = torch.utils.data.WeightedRandomSampler(train_weights, len(train_weights),\n replacement=True)\n \n \n if use_cuda:\n device = 'cuda'\n else:\n device = 'cpu'\n \n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=(train_sampler == None), num_workers=4, sampler=train_sampler)\n \n # Testing is on the same data but without the transforms. This whole class\n # only givey training performance and the user has to use the detect script\n # to check the performance.\n train_set_without_transforms = YearBuiltFolder(image_path,calc_perf=True, soft_labels=soft_labels, gaussian_std=gaussian_std, transforms=transform_test)\n \n train_test_loader = torch.utils.data.DataLoader(train_set_without_transforms, batch_size=3, shuffle=True, num_workers=4)\n \n # Model\n if resume:\n net = torch.load(model_path)\n else:\n net = load_model(model_name='resnet50_pmg', pretrain=True, require_grad=True, num_classes = len(trainset.classes))\n netp = torch.nn.DataParallel(net)\n\n net.to(device)\n \n if soft_labels:\n loss = nn.KLDivLoss(reduction='batchmean')\n else:\n loss = nn.CrossEntropyLoss()\n \n sm = nn.LogSoftmax(dim=1)\n \n optimizer = optim.SGD([\n {'params': net.classifier_concat.parameters(), 'lr': 0.002},\n {'params': net.conv_block1.parameters(), 'lr': 0.002},\n {'params': net.classifier1.parameters(), 'lr': 0.002},\n {'params': net.conv_block2.parameters(), 'lr': 0.002},\n {'params': net.classifier2.parameters(), 'lr': 0.002},\n {'params': net.conv_block3.parameters(), 'lr': 0.002},\n {'params': net.classifier3.parameters(), 'lr': 0.002},\n {'params': net.features.parameters(), 'lr': 0.0002}\n\n ],\n momentum=0.9, weight_decay=5e-4)\n\n max_train_acc = 0\n lr = [0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.0002]\n for epoch in range(start_epoch, nb_epoch):\n print('\\nEpoch: %d' % epoch)\n net.train()\n train_loss = 0\n train_loss1 = 0\n train_loss2 = 0\n train_loss3 = 0\n train_loss4 = 0\n correct = 0\n total = 0\n idx = 0\n for batch_idx, (inputs, targets, indexes) in enumerate(trainloader):\n idx = batch_idx\n if inputs.shape[0] < batch_size:\n continue\n if use_cuda:\n inputs, targets = inputs.to(device), targets.to(device)\n inputs, targets = Variable(inputs), Variable(targets)\n\n # update learning rate\n for nlr in range(len(optimizer.param_groups)):\n optimizer.param_groups[nlr]['lr'] = cosine_anneal_schedule(epoch, nb_epoch, lr[nlr])\n\n # Step 1\n optimizer.zero_grad()\n inputs1 = jigsaw_generator(inputs, 8) \n output_1, _, _, _ = netp(inputs1)\n\n loss1 = loss(sm(output_1), targets) * 1\n loss1.backward()\n optimizer.step()\n\n # Step 2\n optimizer.zero_grad()\n inputs2 = jigsaw_generator(inputs, 4)\n _, output_2, _, _ = netp(inputs2)\n loss2 = loss(sm(output_2), targets) * 1\n loss2.backward()\n optimizer.step()\n\n # Step 3\n optimizer.zero_grad()\n inputs3 = jigsaw_generator(inputs, 2)\n _, _, output_3, _ = netp(inputs3)\n loss3 = loss(sm(output_3), targets) * 1\n loss3.backward()\n optimizer.step()\n\n # Step 4\n optimizer.zero_grad()\n _, _, _, output_concat = netp(inputs)\n concat_loss = loss(sm(output_concat), targets) * 2\n concat_loss.backward()\n optimizer.step()\n\n # training log\n _, predicted = torch.max(output_concat.data, 1)\n if soft_labels:\n _, targets = torch.max(targets.data, 1)\n \n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum()\n\n train_loss += (loss1.item() + loss2.item() + loss3.item() + concat_loss.item())\n train_loss1 += loss1.item()\n train_loss2 += loss2.item()\n train_loss3 += loss3.item()\n train_loss4 += concat_loss.item()\n\n if batch_idx % 50 == 0:\n print(\n 'Step: %d | Loss1: %.3f | Loss2: %.5f | Loss3: %.5f | Loss_concat: %.5f | Loss: %.3f | Acc: %.3f%% (%d/%d)' % (\n batch_idx, train_loss1 / (batch_idx + 1), train_loss2 / (batch_idx + 1),\n train_loss3 / (batch_idx + 1), train_loss4 / (batch_idx + 1), train_loss / (batch_idx + 1),\n 100. * float(correct) / total, correct, total))\n\n train_acc = 100. * float(correct) / total\n train_loss = train_loss / (idx + 1)\n with open(os.path.join(exp_dir,'results_train.txt'), 'a') as file:\n file.write(\n 'Iteration %d | train_acc = %.5f | train_loss = %.5f | Loss1: %.3f | Loss2: %.5f | Loss3: %.5f | Loss_concat: %.5f |\\n' % (\n epoch, train_acc, train_loss, train_loss1 / (idx + 1), train_loss2 / (idx + 1), train_loss3 / (idx + 1),\n train_loss4 / (idx + 1)))\n\n # if epoch < 5 or epoch >= 80:\n print ('Start testing')\n if soft_labels:\n train_acc, train_acc_com, train_loss, y_gt, y_pred = test_softlabels(net, loss, train_test_loader)\n else:\n train_acc, train_acc_com, train_loss, y_gt, y_pred = test(net, loss, train_test_loader)\n if train_acc_com > max_train_acc:\n max_train_acc = train_acc_com\n net.cpu()\n torch.save(net, os.path.join(store_name,'model_best.pth'))\n net.to(device)\n with open(os.path.join(exp_dir,'results_test.txt'), 'a') as file:\n file.write('Iteration %d, test_acc = %.5f, test_acc_combined = %.5f, test_loss = %.6f\\n' % (\n epoch, train_acc, train_acc_com, train_loss))\n \n net.cpu()\n torch.save(net, os.path.join(store_name,'model_epoch_{}.pth'.format(epoch)))\n net.to(device)\n\n\ntry:\n train(nb_epoch=args.epochs, # number of epoch\n batch_size=args.batch_size, # batch size\n image_path=args.image_path,\n soft_labels=args.soft_labels,\n gaussian_std=args.gaussian_std,\n store_name=args.exp_name, # folder for output\n resume=not (args.checkpoint == ''), # resume training from checkpoint\n start_epoch=0, # the start epoch number when you resume the training\n model_path=args.checkpoint\n ) # the saved model where you want to resume the training\nexcept ValueError as ex:\n if 'Expected more than 1 value per channel when training' in str(ex):\n print('Error: The chosen batch size is not compatible with the size of the dataset due to the batch norm layers in the model. Please choose a different batch size, preferably larger.')\n exit(1)\n"
]
| [
[
"torch.nn.CrossEntropyLoss",
"torch.nn.LogSoftmax",
"torch.nn.KLDivLoss",
"torch.max",
"torch.load",
"torch.utils.data.DataLoader",
"torch.autograd.variable.Variable",
"torch.cuda.is_available",
"torch.nn.DataParallel",
"numpy.array"
]
]
|
Ynakatsuka/kaggle_utils | [
"a23b62745bd7881e1a91c74e17612189d1f08784"
]
| [
"kaggle_utils/features/text.py"
]
| [
"import os\n\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\nimport nltk\nimport numpy as np\nimport pandas as pd\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport tensorflow_hub as hub\nfrom tensorflow.keras.preprocessing.text import text_to_word_sequence\nfrom transformers import pipeline\n\nfrom .base import BaseFeatureTransformer\n\n\nclass BasicTextFeatureTransformer(BaseFeatureTransformer):\n def __init__(self, text_columns):\n self.text_columns = text_columns\n \n def _get_features(self, dataframe, column):\n dataframe[column+'_num_chars'] = dataframe[column].apply(len)\n dataframe[column+'_num_capitals'] = dataframe[column].apply(lambda x: sum(1 for c in x if c.isupper()))\n dataframe[column+'_caps_vs_length'] = dataframe[column+'_num_chars'] / dataframe[column+'_num_capitals']\n dataframe[column+'_num_exclamation_marks'] = dataframe[column].apply(lambda x: x.count('!'))\n dataframe[column+'_num_question_marks'] = dataframe[column].apply(lambda x: x.count('?'))\n dataframe[column+'_num_punctuation'] = dataframe[column].apply(lambda x: sum(x.count(w) for w in '.,;:'))\n dataframe[column+'_num_symbols'] = dataframe[column].apply(lambda x: sum(x.count(w) for w in '*&$%'))\n dataframe[column+'_num_words'] = dataframe[column].apply(lambda x: len(x.split()))\n dataframe[column+'_num_unique_words'] = dataframe[column].apply(lambda x: len(set(w for w in x.split())))\n dataframe[column+'_words_vs_unique'] = dataframe[column+'_num_unique_words'] / dataframe[column+'_num_words']\n dataframe[column+'_num_smilies'] = dataframe[column].apply(lambda x: sum(x.count(w) for w in (':-)', ':)', ';-)', ';)')))\n return dataframe\n \n def transform(self, dataframe):\n dataframe[self.text_columns] = dataframe[self.text_columns].astype(str).fillna('missing')\n for c in self.text_columns:\n dataframe = self._get_features(dataframe, c)\n return dataframe\n\n\nclass TextVectorizer(BaseFeatureTransformer): \n '''\n from sklearn.decomposition import TruncatedSVD, NMF\n from sklearn.feature_extraction.text import TfidfVectorizer\n from sklearn.pipeline import make_pipeline, make_union\n \n vectorizer = make_pipeline(\n TfidfVectorizer(),\n make_union(\n TruncatedSVD(n_components=n_components, random_state=seed),\n NMF(n_components=n_components, random_state=seed),\n make_pipeline(\n BM25Transformer(use_idf=True, k1=2.0, b=0.75),\n TruncatedSVD(n_components=n_components, random_state=seed)\n ),\n n_jobs=1,\n ),\n )\n '''\n def __init__(self, text_columns,\n vectorizer=CountVectorizer(), \n transformer=TruncatedSVD(n_components=128),\n name='count_svd'):\n self.text_columns = text_columns\n self.n_components = transformer.n_components\n self.vectorizer = vectorizer\n self.transformer = transformer\n self.name = name + str(self.n_components)\n \n def transform(self, dataframe):\n dataframe[self.text_columns] = dataframe[self.text_columns].astype(str).fillna('missing')\n features = []\n for c in self.text_columns:\n sentence = self.vectorizer.fit_transform(dataframe[c])\n feature = self.transformer.fit_transform(sentence)\n feature = pd.DataFrame(feature, columns=[self.name + f'_{i:03}' for i in range(self.n_components)])\n features.append(feature)\n dataframe = pd.concat([dataframe]+features, axis=1)\n return dataframe\n \n \nclass Doc2VecFeatureTransformer(BaseFeatureTransformer):\n def __init__(self, text_columns, name='doc2vec'):\n self.text_columns = text_columns\n self.name = name\n \n def transform(self, dataframe):\n self.features = []\n for c in self.text_columns:\n texts = dataframe[c].astype(str)\n corpus = [TaggedDocument(words=text, tags=[i]) for i, text in enumerate(texts)]\n model = Doc2Vec(documents=corpus)\n result = np.array([model.infer_vector(text.split('. ')) for text in texts])\n features = pd.DataFrame({\n f'{self.name}_mean': np.mean(result, axis=1),\n f'{self.name}_median': np.median(result, axis=1),\n f'{self.name}_sum': np.sum(result, axis=1),\n f'{self.name}_max': np.max(result, axis=1),\n f'{self.name}_min': np.min(result, axis=1),\n f'{self.name}_var': np.var(result, axis=1), \n })\n self.features.append(features)\n dataframe = pd.concat([dataframe]+self.features, axis=1)\n return dataframe\n\n \nclass EmojiFeatureTransformer(BaseFeatureTransformer):\n def __init__(self, text_columns):\n self.text_columns = text_columns\n\n def transform(self, dataframe):\n dataframe[self.text_columns] = dataframe[self.text_columns].astype(str).fillna('missing')\n \n module_path = os.path.dirname(__file__)\n emoji1 = pd.read_csv(os.path.join(module_path, 'external_data', 'Emoji_Sentiment_Data_v1.0.csv'))\n emoji2 = pd.read_csv(os.path.join(module_path, 'external_data', 'Emojitracker_20150604.csv'))\n emoji = emoji1.merge(emoji2, how='left', on='Emoji', suffixes=('', '_tracker'))\n emoji_list = emoji['Emoji'].values\n \n features = []\n for column in self.text_columns:\n emoji_count = {}\n for e in emoji_list:\n emoji_count[e] = dataframe[column].str.count(e)\n emoji_count = pd.DataFrame(emoji_count)\n\n emoji_columns = ['Occurrences', 'Position', 'Negative', 'Neutral', 'Positive', 'Occurrences_tracker']\n stats = [np.sum, np.mean, np.max, np.median, np.std]\n\n feature = {}\n for c in emoji_columns:\n v = emoji_count * emoji[c].values.T\n for stat in stats:\n feature[column+'_'+stat.__name__+'_'+c] = stat(v, axis=1)\n feature = pd.DataFrame(feature)\n features.append(feature)\n\n dataframe = pd.concat([dataframe]+features, axis=1)\n \n return dataframe\n\n \nclass W2VFeatureTransformer(BaseFeatureTransformer):\n '''\n from gensim.models import FastText, word2vec, KeyedVectors\n \n model = word2vec.Word2Vec.load('../data/w2v.model')\n # model = KeyedVectors.load_word2vec_format(path, binary=True)\n '''\n ps = nltk.stem.PorterStemmer()\n lc = nltk.stem.lancaster.LancasterStemmer()\n sb = nltk.stem.snowball.SnowballStemmer('english')\n \n def __init__(self, text_columns, model, name='w2v'):\n self.text_columns = text_columns\n self.model = model\n self.name = name\n \n def transform(self, dataframe):\n self.features = []\n for c in self.text_columns:\n texts = dataframe[c].astype(str)\n texts = [text_to_word_sequence(text) for text in texts]\n result = []\n for text in texts:\n n_skip = 0\n vec = np.zeros(self.model.vector_size)\n for n_w, word in enumerate(text):\n if self.model.__contains__(word):\n vec = vec + self.model[word]\n continue\n word_ = word.upper()\n if self.model.__contains__(word_):\n vec = vec + self.model[word_]\n continue\n word_ = word.capitalize()\n if self.model.__contains__(word_):\n vec = vec + self.model[word_]\n continue\n word_ = self.ps.stem(word)\n if self.model.__contains__(word_):\n vec = vec + self.model[word_]\n continue\n word_ = self.lc.stem(word)\n if self.model.__contains__(word_):\n vec = vec + self.model[word_]\n continue\n word_ = self.sb.stem(word)\n if self.model.__contains__(word_):\n vec = vec + self.model[word_]\n continue\n else:\n n_skip += 1\n continue\n vec = vec / (n_w - n_skip + 1)\n result.append(vec)\n result = pd.DataFrame(\n result, \n columns=[f'{c}_{self.name}_{i:03}' for i in range(self.model.vector_size)]\n )\n self.features.append(result)\n dataframe = pd.concat([dataframe]+self.features, axis=1)\n return dataframe\n\n\nclass USEFeatureTransformer(BaseFeatureTransformer):\n '''\n Example\n -------\n urls = [\n 'https://tfhub.dev/google/universal-sentence-encoder/4',\n ]\n '''\n def __init__(self, text_columns, urls, name='use'):\n self.text_columns = text_columns\n self.urls = urls\n self.name = name\n \n def transform(self, dataframe):\n self.features = []\n for url in self.urls: \n model_name = url.split('/')[-2]\n embed = hub.load(url)\n for c in self.text_columns:\n texts = dataframe[c].astype(str)\n result = embed(texts).numpy()\n result = pd.DataFrame(\n result, \n columns=[f'{self.name}_{model_name}_{i:03}' for i in range(result.shape[1])]\n )\n self.features.append(result)\n dataframe = pd.concat([dataframe]+self.features, axis=1)\n return dataframe\n\n \nclass BERTFeatureTransformer(BaseFeatureTransformer):\n '''\n Reference\n ---------\n https://huggingface.co/transformers/pretrained_models.html\n \n Example\n -------\n '''\n def __init__(self, text_columns, model_names, batch_size=8, device=-1):\n self.text_columns = text_columns\n self.model_names = model_names\n self.batch_size = batch_size\n self.device = device\n\n def transform(self, dataframe):\n self.features = []\n for model_name in self.model_names: \n model = pipeline('feature-extraction', device=self.device, model=model_name) \n for c in self.text_columns:\n texts = dataframe[c].astype(str).tolist()\n result = []\n for i in range(np.ceil(len(texts)/self.batch_size).astype(int)):\n result.append(\n np.max(model(\n texts[i*self.batch_size:min(len(texts), (i+1)*self.batch_size)]\n ), axis=1)\n )\n result = np.concatenate(result, axis=0)\n result = pd.DataFrame(\n result, \n columns=[f'{model_name}_{i:03}' for i in range(result.shape[1])]\n )\n self.features.append(result)\n dataframe = pd.concat([dataframe]+self.features, axis=1)\n return dataframe\n\n\nclass BM25Transformer(BaseEstimator, TransformerMixin):\n '''\n Parameters\n ----------\n use_idf : boolean, optional (default=True)\n k1 : float, optional (default=2.0)\n b : float, optional (default=0.75)\n\n References\n ----------\n Okapi BM25: a non-binary model - Introduction to Information Retrieval\n http://nlp.stanford.edu/IR-book/html/htmledition/okapi-bm25-a-non-binary-model-1.html\n '''\n def __init__(self, use_idf=True, k1=2.0, b=0.75):\n self.use_idf = use_idf\n self.k1 = k1\n self.b = b\n\n def fit(self, X):\n '''\n Parameters\n ----------\n X : sparse matrix, [n_samples, n_features] document-term matrix\n '''\n if not sp.sparse.issparse(X):\n X = sp.sparse.csc_matrix(X)\n if self.use_idf:\n n_samples, n_features = X.shape\n df = _document_frequency(X)\n idf = np.log((n_samples - df + 0.5) / (df + 0.5))\n self._idf_diag = sp.sparse.spdiags(idf, diags=0, m=n_features, n=n_features)\n\n doc_len = X.sum(axis=1)\n self._average_document_len = np.average(doc_len)\n\n return self\n\n def transform(self, X, copy=True):\n '''\n Parameters\n ----------\n X : sparse matrix, [n_samples, n_features] document-term matrix\n copy : boolean, optional (default=True)\n '''\n if hasattr(X, 'dtype') and np.issubdtype(X.dtype, np.float):\n # preserve float family dtype\n X = sp.sparse.csr_matrix(X, copy=copy)\n else:\n # convert counts or binary occurrences to floats\n X = sp.sparse.csr_matrix(X, dtype=np.float, copy=copy)\n\n n_samples, n_features = X.shape\n\n # Document length (number of terms) in each row\n # Shape is (n_samples, 1)\n doc_len = X.sum(axis=1)\n # Number of non-zero elements in each row\n # Shape is (n_samples, )\n sz = X.indptr[1:] - X.indptr[0:-1]\n\n # In each row, repeat `doc_len` for `sz` times\n # Shape is (sum(sz), )\n # Example\n # -------\n # dl = [4, 5, 6]\n # sz = [1, 2, 3]\n # rep = [4, 5, 5, 6, 6, 6]\n rep = np.repeat(np.asarray(doc_len), sz)\n\n # Compute BM25 score only for non-zero elements\n nom = self.k1 + 1\n denom = X.data + self.k1 * (1 - self.b + self.b * rep / self._average_document_len)\n data = X.data * nom / denom\n\n X = sp.sparse.csr_matrix((data, X.indices, X.indptr), shape=X.shape)\n\n if self.use_idf:\n check_is_fitted(self, '_idf_diag', 'idf vector is not fitted')\n\n expected_n_features = self._idf_diag.shape[0]\n if n_features != expected_n_features:\n raise ValueError(\"Input has n_features=%d while the model\"\n \" has been trained with n_features=%d\" % (\n n_features, expected_n_features))\n X = X * self._idf_diag\n\n return X\n"
]
| [
[
"sklearn.decomposition.TruncatedSVD",
"pandas.concat",
"numpy.log",
"numpy.min",
"numpy.asarray",
"numpy.issubdtype",
"tensorflow.keras.preprocessing.text.text_to_word_sequence",
"numpy.median",
"pandas.DataFrame",
"numpy.concatenate",
"sklearn.feature_extraction.text.CountVectorizer",
"numpy.max",
"numpy.mean",
"numpy.var",
"numpy.average",
"numpy.zeros",
"numpy.sum"
]
]
|
almostdutch/image-denoising-algorithms | [
"1db3c71b32ada71b5613b5692e5d1233bb31afa3"
]
| [
"utils/conjugate_gradient_algorithm_fft.py"
]
| [
"\"\"\"\nconjugate_gradient_algorithm_fft.py\n\nReturns the minimizer of the function in the frequency domain\nX0 - initial guess\nfunc - anonimous function\nfunc_grad - anonimous function gradient\nfunc_hessian - anonimous function hessian\n\"\"\"\n\nimport numpy as np\nfrom image_restoration_utils import CapIntensityFFT, AreWeDoneYet\nfrom secant_algorithm_fft import SecantAlgorithmAlphaLinesearchFFT\n\ndef hestenes_stiefel(grad_old, grad, d):\n beta = (np.conj(grad) * (grad - grad_old)) / (np.conj(d) * (grad - grad_old));\n return beta;\n \ndef polak_ribiere(grad_old, grad, d):\n beta = (np.conj(grad) * (grad - grad_old)) / (np.conj(grad_old) * grad_old);\n return beta;\n\ndef fletcher_reeves(grad_old, grad, d):\n beta = (np.conj(grad) * grad) / (np.conj(grad_old) * grad_old);\n return beta;\n \ndef powel(grad_old, grad, d):\n beta = (np.conj(grad) * (grad - grad_old)) / (np.conj(grad_old) * grad_old);\n beta = np.max([0, beta]); \n return beta; \n\ndef ConjGradAlgorithmVarAlphaFFT(X0, func, func_grad, func_hessian, options):\n \n epsilon = 10e-6\n report = {};\n N_iter_max = options['N_iter_max'];\n tolerance_x = options['tolerance_x'];\n tolerance_y = options['tolerance_y'];\n bpp = options['bpp'];\n progress_x = np.zeros((N_iter_max + 1, X0.shape[0], X0.shape[1]), dtype = np.complex128);\n progress_y = np.zeros((N_iter_max + 1, X0.shape[0], X0.shape[1]), dtype = np.complex128);\n progress_x[0] = X0;\n progress_y[0] = func(X0);\n X_old = X0;\n \n for iter_no in range(1, N_iter_max + 1):\n grad = func_grad(X_old);\n \n if (np.linalg.norm(grad) < epsilon):\n print('norm(grad) < epsilon in %d iterations, exit..' % (iter_no));\n break; \n \n if (iter_no == 1):\n d = -grad; # directional vector\n else:\n # coefficient for calculating conjugate directional vector, this formula valid only for quadratic function\n beta = (np.conj(grad) * func_hessian(X_old) * d) / (np.conj(d) * func_hessian(X_old) * d); \n d = -grad + beta * d; # directional vector\n \n alpha = -(np.conj(grad) * d) / (np.conj(d) * func_hessian(X_old) * d); # step size, this formula valid only for quadratic function\n X = X_old + alpha * d; \n\n # Projection onto the box constraints of X\n CapIntensityFFT(X, bpp);\n\n progress_x[iter_no] = X;\n progress_y[iter_no] = func(X);\n \n if (AreWeDoneYet(iter_no, progress_x, progress_y, tolerance_x, tolerance_y) == True):\n break;\n \n X_old = X;\n \n report = {'N_iter_max' : N_iter_max, 'iter_no' : iter_no, 'X0' : X0, 'X' : X, 'progress_x' : progress_x, 'progress_y' : progress_y};\n return (X, report);\n\ndef ConjGradAlgorithmManualAlphaFFT(X0, func, func_grad, func_hessian, options):\n \n epsilon = 10e-6;\n report = {};\n N_iter_max = options['N_iter_max'];\n tolerance_x = options['tolerance_x'];\n tolerance_y = options['tolerance_y'];\n bpp = options['bpp'];\n alpha = options['alpha'];\n progress_x = np.zeros((N_iter_max + 1, X0.shape[0], X0.shape[1]), dtype = np.complex128);\n progress_y = np.zeros((N_iter_max + 1, X0.shape[0], X0.shape[1]), dtype = np.complex128);\n progress_x[0] = X0;\n progress_y[0] = func(X0);\n X_old = X0;\n \n for iter_no in range(1, N_iter_max + 1):\n grad = func_grad(X_old);\n \n if (np.linalg.norm(grad) < epsilon):\n print('norm(grad) < epsilon in %d iterations, exit..' % (iter_no));\n break; \n \n if (iter_no == 1):\n d = -grad; # directional vector\n else:\n # coefficient for calculating conjugate directional vector, this formula valid only for quadratic function\n beta = (np.conj(grad) * func_hessian(X_old) * d) / (np.conj(d) * func_hessian(X_old) * d); \n d = -grad + beta * d; # directional vector\n \n X = X_old + alpha * d; \n\n # Projection onto the box constraints of X\n CapIntensityFFT(X, bpp);\n\n progress_x[iter_no] = X;\n progress_y[iter_no] = func(X);\n \n if (AreWeDoneYet(iter_no, progress_x, progress_y, tolerance_x, tolerance_y) == True):\n break;\n \n X_old = X;\n \n report = {'N_iter_max' : N_iter_max, 'iter_no' : iter_no, 'X0' : X0, 'X' : X, 'progress_x' : progress_x, 'progress_y' : progress_y};\n return (X, report);\n \ndef ConjGradAlgorithmLinesearchFFT(X0, func, func_grad, options):\n \n epsilon = 10e-6\n reset_dir_every_n_iter = X0.size;\n report = {};\n N_iter_max = options['N_iter_max'];\n tolerance_x = options['tolerance_x'];\n tolerance_y = options['tolerance_y'];\n bpp = options['bpp'];\n progress_x = np.zeros((N_iter_max + 1, X0.shape[0], X0.shape[1]), dtype = np.complex128);\n progress_y = np.zeros((N_iter_max + 1, X0.shape[0], X0.shape[1]), dtype = np.complex128);\n progress_x[0] = X0;\n progress_y[0] = func(X0);\n X_old = X0;\n grad_old = 0;\n \n for iter_no in range(1, N_iter_max + 1):\n grad = func_grad(X_old);\n \n if (np.linalg.norm(grad) < epsilon):\n print('norm(grad) < epsilon in %d iterations, exit..' % (iter_no));\n break; \n \n if (iter_no == 1 or iter_no % (reset_dir_every_n_iter) == 0):\n d = -grad; # # resetting directional vector\n else:\n beta = fletcher_reeves(grad_old, grad, d); # coefficient for calculating conjugate directional vector\n d = -grad + beta * d; # directional vector\n \n alpha = SecantAlgorithmAlphaLinesearchFFT(X_old, func_grad, d); # step size\n X = X_old + alpha * d; \n\n # Projection onto the box constraints of X\n CapIntensityFFT(X, bpp);\n\n progress_x[iter_no] = X;\n progress_y[iter_no] = func(X);\n \n if (AreWeDoneYet(iter_no, progress_x, progress_y, tolerance_x, tolerance_y) == True):\n break;\n \n X_old = X;\n grad_old = grad;\n \n report = {'N_iter_max' : N_iter_max, 'iter_no' : iter_no, 'X0' : X0, 'X' : X, 'progress_x' : progress_x, 'progress_y' : progress_y};\n return (X, report);\n\n"
]
| [
[
"numpy.max",
"numpy.zeros",
"numpy.conj",
"numpy.linalg.norm"
]
]
|
ALEX95GOGO/nnunet_bottleneck_github | [
"75349f0fc541fd260d2e498e87bd53325a576f67"
]
| [
"nnunet/training/network_training/nnUNetTrainerV2_DP.py"
]
| [
"# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport numpy as np\nimport torch\nfrom batchgenerators.utilities.file_and_folder_operations import *\nfrom nnunet.network_architecture.generic_UNet_DP import Generic_UNet_DP\nfrom nnunet.training.data_augmentation.default_data_augmentation import get_moreDA_augmentation\nfrom nnunet.training.network_training.nnUNetTrainerV2 import nnUNetTrainerV2\nfrom nnunet.utilities.to_torch import maybe_to_torch, to_cuda\nfrom nnunet.network_architecture.initialization import InitWeights_He\nfrom nnunet.network_architecture.neural_network import SegmentationNetwork\nfrom nnunet.training.dataloading.dataset_loading import unpack_dataset\nfrom nnunet.training.network_training.nnUNetTrainer import nnUNetTrainer\nfrom nnunet.utilities.nd_softmax import softmax_helper\nfrom torch import nn\nfrom torch.cuda.amp import autocast\nfrom torch.nn.parallel.data_parallel import DataParallel\nfrom torch.nn.utils import clip_grad_norm_\n\n\nclass nnUNetTrainerV2_DP(nnUNetTrainerV2):\n def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,\n unpack_data=True, deterministic=True, num_gpus=1, distribute_batch_size=False, fp16=False):\n super(nnUNetTrainerV2_DP, self).__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage,\n unpack_data, deterministic, fp16)\n self.init_args = (plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data,\n deterministic, num_gpus, distribute_batch_size, fp16)\n self.num_gpus = num_gpus\n self.distribute_batch_size = distribute_batch_size\n self.dice_smooth = 1e-5\n self.dice_do_BG = False\n self.loss = None\n self.loss_weights = None\n\n def setup_DA_params(self):\n super(nnUNetTrainerV2_DP, self).setup_DA_params()\n self.data_aug_params['num_threads'] = 8 * self.num_gpus\n\n def process_plans(self, plans):\n super(nnUNetTrainerV2_DP, self).process_plans(plans)\n if not self.distribute_batch_size:\n self.batch_size = self.num_gpus * self.plans['plans_per_stage'][self.stage]['batch_size']\n else:\n if self.batch_size < self.num_gpus:\n print(\"WARNING: self.batch_size < self.num_gpus. Will not be able to use the GPUs well\")\n elif self.batch_size % self.num_gpus != 0:\n print(\"WARNING: self.batch_size % self.num_gpus != 0. Will not be able to use the GPUs well\")\n\n def initialize(self, training=True, force_load_plans=False):\n \"\"\"\n - replaced get_default_augmentation with get_moreDA_augmentation\n - only run this code once\n - loss function wrapper for deep supervision\n\n :param training:\n :param force_load_plans:\n :return:\n \"\"\"\n if not self.was_initialized:\n maybe_mkdir_p(self.output_folder)\n\n if force_load_plans or (self.plans is None):\n self.load_plans_file()\n\n self.process_plans(self.plans)\n\n self.setup_DA_params()\n\n ################# Here configure the loss for deep supervision ############\n net_numpool = len(self.net_num_pool_op_kernel_sizes)\n weights = np.array([1 / (2 ** i) for i in range(net_numpool)])\n mask = np.array([True if i < net_numpool - 1 else False for i in range(net_numpool)])\n weights[~mask] = 0\n weights = weights / weights.sum()\n self.loss_weights = weights\n ################# END ###################\n\n self.folder_with_preprocessed_data = join(self.dataset_directory, self.plans['data_identifier'] +\n \"_stage%d\" % self.stage)\n if training:\n self.dl_tr, self.dl_val = self.get_basic_generators()\n if self.unpack_data:\n print(\"unpacking dataset\")\n unpack_dataset(self.folder_with_preprocessed_data)\n print(\"done\")\n else:\n print(\n \"INFO: Not unpacking data! Training may be slow due to that. Pray you are not using 2d or you \"\n \"will wait all winter for your model to finish!\")\n\n self.tr_gen, self.val_gen = get_moreDA_augmentation(self.dl_tr, self.dl_val,\n self.data_aug_params[\n 'patch_size_for_spatialtransform'],\n self.data_aug_params,\n deep_supervision_scales=self.deep_supervision_scales,\n pin_memory=self.pin_memory)\n self.print_to_log_file(\"TRAINING KEYS:\\n %s\" % (str(self.dataset_tr.keys())),\n also_print_to_console=False)\n self.print_to_log_file(\"VALIDATION KEYS:\\n %s\" % (str(self.dataset_val.keys())),\n also_print_to_console=False)\n else:\n pass\n\n self.initialize_network()\n self.initialize_optimizer_and_scheduler()\n\n assert isinstance(self.network, (SegmentationNetwork, DataParallel))\n else:\n self.print_to_log_file('self.was_initialized is True, not running self.initialize again')\n self.was_initialized = True\n\n def initialize_network(self):\n \"\"\"\n replace genericUNet with the implementation of above for super speeds\n \"\"\"\n if self.threeD:\n conv_op = nn.Conv3d\n dropout_op = nn.Dropout3d\n norm_op = nn.InstanceNorm3d\n\n else:\n conv_op = nn.Conv2d\n dropout_op = nn.Dropout2d\n norm_op = nn.InstanceNorm2d\n\n norm_op_kwargs = {'eps': 1e-5, 'affine': True}\n dropout_op_kwargs = {'p': 0, 'inplace': True}\n net_nonlin = nn.LeakyReLU\n net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True}\n self.network = Generic_UNet_DP(self.num_input_channels, self.base_num_features, self.num_classes,\n len(self.net_num_pool_op_kernel_sizes),\n self.conv_per_stage, 2, conv_op, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs,\n net_nonlin, net_nonlin_kwargs, True, False, InitWeights_He(1e-2),\n self.net_num_pool_op_kernel_sizes, self.net_conv_kernel_sizes, False, True, True)\n if torch.cuda.is_available():\n self.network.cuda()\n self.network.inference_apply_nonlin = softmax_helper\n\n def initialize_optimizer_and_scheduler(self):\n assert self.network is not None, \"self.initialize_network must be called first\"\n self.optimizer = torch.optim.SGD(self.network.parameters(), self.initial_lr, weight_decay=self.weight_decay,\n momentum=0.99, nesterov=True)\n self.lr_scheduler = None\n\n def run_training(self):\n self.maybe_update_lr(self.epoch)\n\n # amp must be initialized before DP\n\n ds = self.network.do_ds\n self.network.do_ds = True\n self.network = DataParallel(self.network, tuple(range(self.num_gpus)), )\n ret = nnUNetTrainer.run_training(self)\n self.network = self.network.module\n self.network.do_ds = ds\n return ret\n\n def run_iteration(self, data_generator, do_backprop=True, run_online_evaluation=False):\n data_dict = next(data_generator)\n data = data_dict['data']\n target = data_dict['target']\n\n data = maybe_to_torch(data)\n target = maybe_to_torch(target)\n\n if torch.cuda.is_available():\n data = to_cuda(data)\n target = to_cuda(target)\n\n self.optimizer.zero_grad()\n\n if self.fp16:\n with autocast():\n ret = self.network(data, target, return_hard_tp_fp_fn=run_online_evaluation)\n if run_online_evaluation:\n ces, tps, fps, fns, tp_hard, fp_hard, fn_hard = ret\n self.run_online_evaluation(tp_hard, fp_hard, fn_hard)\n else:\n ces, tps, fps, fns = ret\n del data, target\n l = self.compute_loss(ces, tps, fps, fns)\n\n if do_backprop:\n self.amp_grad_scaler.scale(l).backward()\n self.amp_grad_scaler.unscale_(self.optimizer)\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)\n self.amp_grad_scaler.step(self.optimizer)\n self.amp_grad_scaler.update()\n else:\n ret = self.network(data, target, return_hard_tp_fp_fn=run_online_evaluation)\n if run_online_evaluation:\n ces, tps, fps, fns, tp_hard, fp_hard, fn_hard = ret\n self.run_online_evaluation(tp_hard, fp_hard, fn_hard)\n else:\n ces, tps, fps, fns = ret\n del data, target\n l = self.compute_loss(ces, tps, fps, fns)\n\n if do_backprop:\n l.backward()\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)\n self.optimizer.step()\n\n return l.detach().cpu().numpy()\n\n def run_online_evaluation(self, tp_hard, fp_hard, fn_hard):\n tp_hard = tp_hard.detach().cpu().numpy().mean(0)\n fp_hard = fp_hard.detach().cpu().numpy().mean(0)\n fn_hard = fn_hard.detach().cpu().numpy().mean(0)\n self.online_eval_foreground_dc.append(list((2 * tp_hard) / (2 * tp_hard + fp_hard + fn_hard + 1e-8)))\n self.online_eval_tp.append(list(tp_hard))\n self.online_eval_fp.append(list(fp_hard))\n self.online_eval_fn.append(list(fn_hard))\n\n def compute_loss(self, ces, tps, fps, fns):\n # we now need to effectively reimplement the loss\n loss = None\n for i in range(len(ces)):\n if not self.dice_do_BG:\n tp = tps[i][:, 1:]\n fp = fps[i][:, 1:]\n fn = fns[i][:, 1:]\n else:\n tp = tps[i]\n fp = fps[i]\n fn = fns[i]\n\n if self.batch_dice:\n tp = tp.sum(0)\n fp = fp.sum(0)\n fn = fn.sum(0)\n else:\n pass\n\n nominator = 2 * tp + self.dice_smooth\n denominator = 2 * tp + fp + fn + self.dice_smooth\n\n dice_loss = (- nominator / denominator).mean()\n if loss is None:\n loss = self.loss_weights[i] * (ces[i].mean() + dice_loss)\n else:\n loss += self.loss_weights[i] * (ces[i].mean() + dice_loss)\n ###########\n return loss"
]
| [
[
"torch.cuda.is_available",
"torch.cuda.amp.autocast"
]
]
|
Akinduko/ml-task | [
"fc62b779656e83c0489b13628063a5f426c6551e"
]
| [
"server/utils/train_model.py"
]
| [
"import os\nimport sys\n#import json\nimport logging\nimport math\nfrom keras.callbacks import EarlyStopping\n\nimport keras\nimport numpy as np\nimport tensorflow as tf\n\nfrom keras.models import load_model\n\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\n\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\nfrom keras_tqdm import TQDMCallback\n\nfrom keras.models import Sequential\nfrom keras.callbacks import ModelCheckpoint\n\nfrom .constants import model_dir\nfrom .constants import default_test_folder_path\nfrom .constants import default_train_folder_path\nfrom .constants import root_dir\nfrom .constants import image_extensions\n\ntrain_datagen = ImageDataGenerator(rescale=1. / 255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\n\nclass progBarCallback(tf.keras.callbacks.Callback):\n def setEpochSize(self, es):\n self.epoch_size = es\n\n def on_epoch_begin(self, epoch, logs={}):\n self.done = 0\n self.cur_epoch = epoch\n printProgBar(epoch, 0, self.epoch_size)\n\n def on_batch_end(self, batch, logs={}):\n self.done += 1\n print(\"\\rEpoch \" + str(batch + 1) + \" [\", end=\"\", flush=True)\n sys.stdout.flush()\n printProgBar(self.cur_epoch, self.done, self.epoch_size)\n\n\ndef printProgBar(batch, amount, biggest, args=[]):\n fraction = amount / biggest\n num = math.floor(fraction * 50)\n print(\"\\rEpoch \" + str(batch + 1) + \" [\", end=\"\", flush=True)\n sys.stdout.flush()\n for i in range(num - 1):\n print(\"=\", end=\"\")\n sys.stdout.flush()\n if (num > 0):\n print(\">\", end=\"\")\n sys.stdout.flush()\n for i in range(50 - num):\n print(\"_\", end=\"\")\n sys.stdout.flush()\n print(\"]\", end=\"\")\n sys.stdout.flush()\n for arg in args:\n print(\" \" + str(arg), end=\"\")\n sys.stdout.flush()\n print(\" \" + str(amount) + \"/\" + str(biggest), end=\"\")\n sys.stdout.flush()\n\n\ndef train_model(new_model, train_folder_path, test_folder_path):\n # Check that both train and test folders are present (Catch both orders)\n if os.path.isdir(train_folder_path):\n # test_folder_path must also be a directory\n if os.path.isdir(test_folder_path):\n train(new_model,\n train_folder=train_folder_path,\n test_folder=test_folder_path)\n print('The provided test folder is not a directory')\n sys.stdout.flush()\n return # You must return\n #Means train_folder_path is not a directory\n print('The provided train folder is not a directory')\n sys.stdout.flush()\n return\n\n\ndef get_total_images(folder_path):\n '''\n\tThis function counts the total number of images in a folder.\n\t\n\t'''\n count = 0\n for root, folders, files in os.walk(folder_path):\n for file in files:\n if file.endswith(image_extensions):\n count += 1\n print(' The provided test folder is not a directory')\n sys.stdout.flush()\n return count\n\n\ndef _generator(folder_path=None, is_train_set=True):\n \"\"\"\n\tAccepts a training folder path and generate training set from it.\n\tif a folder is not supplied, defaults to using ./datasets/training_set\n\tNo need to make default dataset folder constant because it's only used here\n\t\"\"\"\n if is_train_set:\n if folder_path is None:\n folder_path = default_train_folder_path\n\n total_sample_size = get_total_images(folder_path)\n training_data = train_datagen.flow_from_directory(folder_path,\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n return dict(training_dataset=training_data,\n total_sample_size=total_sample_size)\n if folder_path is None:\n folder_path = default_test_folder_path\n total_sample_size = get_total_images(folder_path)\n test_data = test_datagen.flow_from_directory(folder_path,\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n return dict(test_data=test_data, total_sample_size=total_sample_size)\n\n\ndef train(model_name, epochs=100, train_folder=None, test_folder=None):\n batch_size = 32\n\n #Configure keras_tqdm logger callback.\n\n logfile = open(os.path.join(root_dir, 'training.log'), 'w')\n #Get samples sizes\n\n #Generate training data set\n training_gen = _generator(train_folder, is_train_set=True)\n training_set = training_gen.get(\"training_dataset\")\n total_training_data_sample = training_gen.get(\"total_sample_size\")\n steps_per_epoch = math.ceil(total_training_data_sample / batch_size)\n\n #Generate test data set\n test_gen = _generator(test_folder, is_train_set=False)\n test_set = test_gen.get(\"test_dataset\")\n total_testing_datasample = test_gen.get('total_sample_size')\n validation_steps = math.ceil(total_testing_datasample / batch_size)\n\n model_path = os.path.join(model_dir, model_name)\n classifier = Sequential()\n print(\"Training model, You will be notified at the end of each epoch\")\n sys.stdout.flush()\n # Step 1 - Convolution\n classifier.add(\n Conv2D(32, (3, 3), input_shape=(64, 64, 3), activation='relu'))\n # Step 2 - Pooling\n classifier.add(MaxPooling2D(pool_size=(2, 2)))\n\n # Adding a second convolutional layer\n classifier.add(Conv2D(32, (3, 3), activation='relu'))\n classifier.add(MaxPooling2D(pool_size=(2, 2)))\n # Step 3 - Flattening\n classifier.add(Flatten())\n\n # Step 4 - Full connection\n classifier.add(Dense(units=128, activation='relu'))\n classifier.add(Dense(units=1, activation='sigmoid'))\n # checkpoint\n progBar = progBarCallback()\n progBar.setEpochSize(len(training_set))\n early_stopping = EarlyStopping(monitor='loss',\n patience=20,\n verbose=1,\n mode='auto')\n checkpoint = ModelCheckpoint(model_path,\n monitor='acc',\n verbose=1,\n save_best_only=True,\n mode='max')\n callbacks_list = [checkpoint, progBar, early_stopping]\n if os.path.isfile(model_path):\n print(\"Resumed model's weights from {}\".format(model_path))\n sys.stdout.flush()\n # load weights\n classifier.load_weights(model_path)\n # Compiling the CNN\n classifier.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n classifier.fit_generator(training_set,\n steps_per_epoch=steps_per_epoch,\n epochs=epochs,\n verbose=0,\n validation_data=test_set,\n validation_steps=validation_steps,\n callbacks=callbacks_list)\n #Model confidence\n x, y = zip(*(test_set[i] for i in range(len(test_set))))\n x_test, y_test = np.vstack(x), np.vstack(y)\n loss, acc = classifier.evaluate(x_test,\n y_test.ravel(),\n batch_size=batch_size)\n print(\"Confidence: \", round(acc * 100), '%')\n sys.stdout.flush()\n #print(\"Loss: \", loss)\n # training_set.class_indices\n classifier.save(model_path)\n\n\ndef prepImage(testImage):\n test_image = image.load_img(testImage, target_size=(64, 64))\n test_image = image.img_to_array(test_image)\n test_image = np.expand_dims(test_image, axis=0)\n return test_image\n\n\ndef setupTF():\n\n config = tf.ConfigProto(device_count={'GPU': 1})\n sess = tf.Session(config=config)\n keras.backend.set_session(sess)\n\n return\n"
]
| [
[
"tensorflow.ConfigProto",
"numpy.vstack",
"numpy.expand_dims",
"tensorflow.Session"
]
]
|
NarnePranay/Movie-genre-prediction-model | [
"ac3d119e89534500a42ca92b53c41d5e7e2dbe12"
]
| [
"tension_measuring/textclassify.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 1 05:20:35 2018\n\n@author: Half_BlooD PrincE\n\"\"\"\n\nfrom sklearn import model_selection, preprocessing, linear_model, naive_bayes, metrics, svm\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn import decomposition, ensemble\n\nimport pandas, xgboost, numpy, textblob, string\n\n\n#data = open('corpus',encoding=\"utf8\").read()\n#labels, texts = [], []\n#\n#\n#for i, line in enumerate(data.split(\"\\n\")):\n# content = line.split()\n# #print(content)\n# if len(content) is not 0:\n# labels.append(content[0])\n# #texts.append(content[1:])\n# texts.append(' '.join(content[1:]))\n\n\n# create a dataframe using texts and lables\ntrainDF = pandas.DataFrame()\ntrainDF['text'] = texts\ntrainDF['label'] = labels\n\n\ntrain_x, valid_x, train_y, valid_y = model_selection.train_test_split(trainDF['text'], trainDF['label'])\n\n# label encode the target variable \nencoder = preprocessing.LabelEncoder()\ntrain_y = encoder.fit_transform(train_y)\nvalid_y = encoder.fit_transform(valid_y)\n\nprint(train_y)\n\n\n# create a count vectorizer object \ncount_vect = CountVectorizer(analyzer='word', token_pattern=r'\\w{1,}')\ncount_vect.fit(trainDF['text'])\n\n# transform the training and validation data using count vectorizer object\nxtrain_count = count_vect.transform(train_x)\nxvalid_count = count_vect.transform(valid_x)\n\n# word level tf-idf\ntfidf_vect = TfidfVectorizer(analyzer='word', token_pattern=r'\\w{1,}', max_features=5000)\ntfidf_vect.fit(trainDF['text'])\nxtrain_tfidf = tfidf_vect.transform(train_x)\nxvalid_tfidf = tfidf_vect.transform(valid_x)\n\n\n# ngram level tf-idf \ntfidf_vect_ngram = TfidfVectorizer(analyzer='word', token_pattern=r'\\w{1,}', ngram_range=(2,3), max_features=5000)\ntfidf_vect_ngram.fit(trainDF['text'])\nxtrain_tfidf_ngram = tfidf_vect_ngram.transform(train_x)\nxvalid_tfidf_ngram = tfidf_vect_ngram.transform(valid_x)\n\n# characters level tf-idf\ntfidf_vect_ngram_chars = TfidfVectorizer(analyzer='char', token_pattern=r'\\w{1,}', ngram_range=(2,3), max_features=5000)\ntfidf_vect_ngram_chars.fit(trainDF['text'])\nxtrain_tfidf_ngram_chars = tfidf_vect_ngram_chars.transform(train_x) \nxvalid_tfidf_ngram_chars = tfidf_vect_ngram_chars.transform(valid_x) \n\ndef train_model(classifier, feature_vector_train, label, feature_vector_valid, is_neural_net=False):\n # fit the training dataset on the classifier\n classifier.fit(feature_vector_train, label)\n \n # predict the labels on validation dataset\n predictions = classifier.predict(feature_vector_valid)\n \n if is_neural_net:\n predictions = predictions.argmax(axis=-1)\n \n return metrics.accuracy_score(predictions, valid_y)\n\n\n# Naive Bayes on Count Vectors\naccuracy = train_model(naive_bayes.MultinomialNB(), xtrain_count, train_y, xvalid_count)\nprint (\"NB, Count Vectors: \", accuracy)\n\n# Naive Bayes on Word Level TF IDF Vectors\naccuracy = train_model(naive_bayes.MultinomialNB(), xtrain_tfidf, train_y, xvalid_tfidf)\nprint (\"NB, WordLevel TF-IDF: \", accuracy)\n\n# Naive Bayes on Ngram Level TF IDF Vectors\naccuracy = train_model(naive_bayes.MultinomialNB(), xtrain_tfidf_ngram, train_y, xvalid_tfidf_ngram)\nprint (\"NB, N-Gram Vectors: \", accuracy)\n\n# Naive Bayes on Character Level TF IDF Vectors\naccuracy = train_model(naive_bayes.MultinomialNB(), xtrain_tfidf_ngram_chars, train_y, xvalid_tfidf_ngram_chars)\nprint (\"NB, CharLevel Vectors: \", accuracy)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
]
| [
[
"sklearn.naive_bayes.MultinomialNB",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.preprocessing.LabelEncoder",
"sklearn.feature_extraction.text.TfidfVectorizer",
"sklearn.metrics.accuracy_score"
]
]
|
zoeleeee/mnist_challenge | [
"8a98f7dde35ee1d7a1fb77e85ca931000fb71631"
]
| [
"keras_rnd_multi_eval.py"
]
| [
"#CUDA_VISIBLE_DEVICES=0 python keras_rnd_multi_eval.py 0.9 window 16 1 100 0 4 configs/\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport math\nimport os\nimport sys\nimport time\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nfrom utils import *\nimport numpy as np\n\nconf = sys.argv[-1]\nnb_models = int(sys.argv[-2])\nt = int(sys.argv[-3])\nnb_imgs = int(sys.argv[-4])\nst_imgs = int(sys.argv[-5])\ninput_bytes = eval(sys.argv[-6])\n_type = sys.argv[-7]\n_t = eval(sys.argv[-8])\n#dataset = sys.argv[-2]\n# Global constants\nwith open(conf) as config_file:\n config = json.load(config_file)\nnum_eval_examples = config['num_eval_examples']\neval_batch_size = config['eval_batch_size']\neval_on_cpu = config['eval_on_cpu']\nnb_labels = config['num_labels']\nst_lab = config['start_label']\nrep = np.load('2_label_permutation.npy')[st_lab:st_lab+nb_labels*nb_models].T\nrep[rep==0] = -1\nnb_channel = int(config['permutation'].split('_')[1].split('.')[1])\nnb_label = config['num_labels']\n#if dataset == 'origin.npy':\n# imgs, labels, input_shape = load_data(config['permutation'], config['num_labels'])\nlabels = np.load('data/mnist_labels.npy')\nimgs = np.load('data/mnist_data.npy').transpose((0,2,3,1))\npermut = np.load(config['permutation'])\n# labels = np.array([rep[i] for i in labels]).astype(np.float32)\nx_train, y_train = imgs[:60000], labels[:60000]\nx_test, y_test = imgs[-nb_imgs-st_imgs:-st_imgs], labels[-nb_imgs-st_imgs:-st_imgs]\n\nif len(x_test.shape) == 3:\n x_test = x_test.reshape(x_test.shape[0], x_test.shape[1], x_test.shape[2], 1)\nprint(x_test.shape, len(x_test))\n\ndef custom_loss():\n def loss(y_true, y_pred):\n if config['loss_func'] == 'bce':\n _loss = keras.losses.BinaryCrossentropy()\n return _loss(y_true, tf.nn.sigmoid(y_pred))\n elif config['loss_func'] == 'xent':\n _loss = keras.losses.SparseCategoricalCrossentropy()\n return _loss(y_true, tf.nn.softmax(y_pred))\n return loss\n\nmodels = []\nif _type == 'window':\n model_var = '_window' + str(input_bytes)\nelif _type == 'slide4':\n model_var = '_slide'+str(input_bytes)\nfor i in range(nb_models):\n with open(conf) as config_file:\n config = json.load(config_file)\n model_dir = config['model_dir']\n models.append(keras.models.load_model(model_dir+model_var+'.h5', custom_objects={ 'custom_loss': custom_loss(), 'loss':custom_loss() }, compile=False))\n conf = conf[:conf.find(conf.split('_')[-1])]+str(nb_labels*(i+1))+'.json'\n\ntot_advs_acc = np.zeros(len(y_test))\ntot_amt = 0\nchange_advs_acc = []\nrnd_imgs = np.zeros(imgs[-nb_imgs-st_imgs:-st_imgs].shape)\nprint(rnd_imgs.shape, x_test.shape)\nwhile True:\n if np.mean(tot_advs_acc) == 1.: \n print(tot_amt, 'totally attacked succeed!')\n np.save('preds/rnd_'+model_dir.split('/')[-1]+'.npy', change_advs_acc)\n break\n elif tot_amt == 1e5:\n np.save('preds/rnd_'+model_dir.split('/')[-1]+'.npy', change_advs_acc)\n print(tot_amt, 'total adversarial acc:', tot_advs_acc)\n break\n else:\n tot_amt += 1\n # noise = x_test\n noise = np.clip(np.random.randint(-1*int(config['epsilon']*255), int(config['epsilon']*255), x_test.shape)+x_test, 0, 255).astype(np.int)\n if _type == 'window':\n x_input = [window_perm_sliding_img_AES(nb_channel, noise, st_lab+i*nb_label, input_bytes) for i in range(nb_models)]\n if _type == 'slide4':\n x_input = [four_pixel_perm_sliding_img_AES(nb_channel, noise, st_lab+i*nb_label, input_bytes) for i in range(nb_models)]\n # samples = np.array([[[permut[d[0]] for d in c] for c in b] for b in noise])\n # x_input = [samples[i].astype(np.float32) / 255. for i in range(len(models))]\n scores = []\n for i in range(nb_models):\n scores.append(models[i].predict(x_input[i], batch_size=eval_batch_size))\n scores = np.hstack(scores)\n nat_labels = np.zeros(scores.shape)\n nat_labels[scores>=_t] = 1.\n if _t == .5:\n nat_labels[scores<1-_t] = -1\n else:\n nat_labels[scores <= 1-_t] = -1\n\n preds, preds_dist, preds_score = [], [], []\n print(scores.shape)\n for i in range(len(nat_labels)):\n tmp = np.repeat([nat_labels[i]], rep.shape[0], axis=0)\n dists = np.sum(np.absolute(tmp-rep), axis=-1)\n min_dist = np.min(dists)\n pred_labels = np.arange(len(dists))[dists==min_dist]\n pred_scores = [np.sum([scores[i][k] if rep[j][k]==1 else 1-scores[i][k] for k in np.arange(len(scores[i]))]) for j in pred_labels]\n pred_label = pred_labels[np.argmax(pred_scores)]\n preds.append(pred_label)\n preds_dist.append(dists[pred_label])\n preds_score.append(np.max(pred_scores))\n\n error_idxs = np.arange(len(preds))[preds != y_test]\n preds = np.array(preds)\n preds_dist = np.array(preds_dist)\n tot_advs_acc[error_idxs[preds_dist[preds!=y_test]<= t]] = 1.\n print(rnd_imgs.shape, noise.shape)\n rnd_imgs[error_idxs[preds_dist[preds!=y_test]<= t]] = noise[error_idxs[preds_dist[preds!=y_test]<= t]]\n change_advs_acc.append(np.mean(tot_advs_acc))\n if tot_amt % 1000 == 0:\n np.save('advs/rnd_'+model_dir.split('/')[-1]+model_var+'.npy', rnd_imgs)\n print('{} error rate per time: {:.2f}%; right rate: {:.2f}%; total adversarial acc:{}%'.format(tot_amt, np.sum(preds_dist[preds!=y_test] <= t)/len(preds)*100, np.sum(preds_dist[preds==y_test] <= t)/len(preds)*100, np.mean(tot_advs_acc)*100))\n"
]
| [
[
"numpy.hstack",
"tensorflow.nn.softmax",
"tensorflow.nn.sigmoid",
"numpy.absolute",
"numpy.min",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.keras.losses.BinaryCrossentropy",
"numpy.max",
"numpy.argmax",
"numpy.mean",
"numpy.load",
"numpy.repeat",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
]
|
tianyu-lu/torchsde | [
"187a05d7615d910d362ddf013ea4039338af76e5"
]
| [
"diagnostics/stratonovich_additive.py"
]
| [
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\n\nimport torch\n\nfrom tests.basic_sde import AdditiveSDE\nfrom torchsde import BrownianInterval\nfrom torchsde.settings import LEVY_AREA_APPROXIMATIONS, SDE_TYPES\nfrom . import inspection\nfrom . import utils\n\n\ndef main():\n small_batch_size, large_batch_size, d, m = 16, 16384, 3, 5\n t0, t1, steps, dt = 0., 2., 10, 1e-1\n ts = torch.linspace(t0, t1, steps=steps, device=device)\n dts = tuple(2 ** -i for i in range(1, 7)) # For checking strong order.\n sde = AdditiveSDE(d=d, m=m, sde_type=SDE_TYPES.stratonovich).to(device)\n # Don't test Milstein methods, since there's no advantage to use extra resource to compute 0s.\n methods = ('heun', 'euler_heun', 'midpoint')\n labels = ('heun', 'euler-heun', 'midpoint')\n img_dir = os.path.join(os.path.dirname(__file__), 'plots', 'stratonovich_additive')\n\n y0 = torch.full((small_batch_size, d), fill_value=0.1, device=device)\n bm = BrownianInterval(\n t0=t0, t1=t1, size=(small_batch_size, m), dtype=y0.dtype, device=device,\n levy_area_approximation=LEVY_AREA_APPROXIMATIONS.space_time\n )\n inspection.inspect_samples(y0, ts, dt, sde, bm, img_dir, methods, labels=labels)\n\n y0 = torch.full((large_batch_size, d), fill_value=0.1, device=device)\n bm = BrownianInterval(\n t0=t0, t1=t1, size=(large_batch_size, m), dtype=y0.dtype, device=device,\n levy_area_approximation=LEVY_AREA_APPROXIMATIONS.space_time\n )\n inspection.inspect_orders(y0, t0, t1, dts, sde, bm, img_dir, methods, labels=labels)\n\n\nif __name__ == '__main__':\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n torch.set_default_dtype(torch.float64)\n utils.manual_seed()\n\n main()\n"
]
| [
[
"torch.set_default_dtype",
"torch.linspace",
"torch.cuda.is_available",
"torch.full"
]
]
|
flydream0428/GPy | [
"111727e139dee0812a596304774779929c42c77d"
]
| [
"GPy/examples/classification.py"
]
| [
"# Copyright (c) 2012-2014, GPy authors (see AUTHORS.txt).\n# Licensed under the BSD 3-clause license (see LICENSE.txt)\n\"\"\"\nGaussian Processes classification examples\n\"\"\"\nMPL_AVAILABLE = True\ntry:\n import matplotlib.pyplot as plt\nexcept ImportError:\n MPL_AVAILABLE = False\n\nimport GPy\n\ndefault_seed = 10000\n\n\ndef oil(num_inducing=50, max_iters=100, kernel=None, optimize=True, plot=True):\n \"\"\"\n Run a Gaussian process classification on the three phase oil data. The demonstration calls the basic GP classification model and uses EP to approximate the likelihood.\n\n \"\"\"\n try:\n import pods\n except ImportError:\n raise ImportWarning(\n \"Need pods for example datasets. See https://github.com/sods/ods, or pip install pods.\"\n )\n data = pods.datasets.oil()\n X = data[\"X\"]\n Xtest = data[\"Xtest\"]\n Y = data[\"Y\"][:, 0:1]\n Ytest = data[\"Ytest\"][:, 0:1]\n Y[Y.flatten() == -1] = 0\n Ytest[Ytest.flatten() == -1] = 0\n\n # Create GP model\n m = GPy.models.SparseGPClassification(\n X, Y, kernel=kernel, num_inducing=num_inducing\n )\n m.Ytest = Ytest\n\n # Contrain all parameters to be positive\n # m.tie_params('.*len')\n m[\".*len\"] = 10.0\n\n # Optimize\n if optimize:\n m.optimize(messages=1)\n print(m)\n\n # Test\n probs = m.predict(Xtest)[0]\n GPy.util.classification.conf_matrix(probs, Ytest)\n return m\n\n\ndef toy_linear_1d_classification(seed=default_seed, optimize=True, plot=True):\n \"\"\"\n Simple 1D classification example using EP approximation\n\n :param seed: seed value for data generation (default is 4).\n :type seed: int\n\n \"\"\"\n try:\n import pods\n except ImportError:\n raise ImportWarning(\n \"Need pods for example datasets. See https://github.com/sods/ods, or pip install pods.\"\n )\n data = pods.datasets.toy_linear_1d_classification(seed=seed)\n Y = data[\"Y\"][:, 0:1]\n Y[Y.flatten() == -1] = 0\n\n # Model definition\n m = GPy.models.GPClassification(data[\"X\"], Y)\n\n # Optimize\n if optimize:\n # m.update_likelihood_approximation()\n # Parameters optimization:\n m.optimize()\n # m.update_likelihood_approximation()\n # m.pseudo_EM()\n\n # Plot\n if MPL_AVAILABLE and plot:\n fig, axes = plt.subplots(2, 1)\n m.plot_f(ax=axes[0])\n m.plot(ax=axes[1])\n\n print(m)\n return m\n\n\ndef toy_linear_1d_classification_laplace(seed=default_seed, optimize=True, plot=True):\n \"\"\"\n Simple 1D classification example using Laplace approximation\n\n :param seed: seed value for data generation (default is 4).\n :type seed: int\n\n \"\"\"\n\n try:\n import pods\n except ImportError:\n print(\"pods unavailable, see https://github.com/sods/ods for example datasets\")\n data = pods.datasets.toy_linear_1d_classification(seed=seed)\n Y = data[\"Y\"][:, 0:1]\n Y[Y.flatten() == -1] = 0\n\n likelihood = GPy.likelihoods.Bernoulli()\n laplace_inf = GPy.inference.latent_function_inference.Laplace()\n kernel = GPy.kern.RBF(1)\n\n # Model definition\n m = GPy.core.GP(\n data[\"X\"], Y, kernel=kernel, likelihood=likelihood, inference_method=laplace_inf\n )\n\n # Optimize\n if optimize:\n m.optimize(\"scg\", messages=True)\n\n return m\n\n # Plot\n if MPL_AVAILABLE and plot:\n fig, axes = plt.subplots(2, 1)\n m.plot_f(ax=axes[0])\n m.plot(ax=axes[1])\n\n print(m)\n return m\n\n\ndef sparse_toy_linear_1d_classification(\n num_inducing=10, seed=default_seed, optimize=True, plot=True\n):\n \"\"\"\n Sparse 1D classification example\n\n :param seed: seed value for data generation (default is 4).\n :type seed: int\n\n \"\"\"\n\n try:\n import pods\n except ImportError:\n print(\"pods unavailable, see https://github.com/sods/ods for example datasets\")\n data = pods.datasets.toy_linear_1d_classification(seed=seed)\n Y = data[\"Y\"][:, 0:1]\n Y[Y.flatten() == -1] = 0\n\n # Model definition\n m = GPy.models.SparseGPClassification(data[\"X\"], Y, num_inducing=num_inducing)\n m[\".*len\"] = 4.0\n\n # Optimize\n if optimize:\n m.optimize()\n\n # Plot\n if MPL_AVAILABLE and plot:\n fig, axes = plt.subplots(2, 1)\n m.plot_f(ax=axes[0])\n m.plot(ax=axes[1])\n\n print(m)\n return m\n\n\ndef sparse_toy_linear_1d_classification_uncertain_input(\n num_inducing=10, seed=default_seed, optimize=True, plot=True\n):\n \"\"\"\n Sparse 1D classification example\n\n :param seed: seed value for data generation (default is 4).\n :type seed: int\n\n \"\"\"\n\n try:\n import pods\n except ImportError:\n print(\"pods unavailable, see https://github.com/sods/ods for example datasets\")\n import numpy as np\n\n data = pods.datasets.toy_linear_1d_classification(seed=seed)\n Y = data[\"Y\"][:, 0:1]\n Y[Y.flatten() == -1] = 0\n X = data[\"X\"]\n X_var = np.random.uniform(0.3, 0.5, X.shape)\n\n # Model definition\n m = GPy.models.SparseGPClassificationUncertainInput(\n X, X_var, Y, num_inducing=num_inducing\n )\n m[\".*len\"] = 4.0\n\n # Optimize\n if optimize:\n m.optimize()\n\n # Plot\n if MPL_AVAILABLE and plot:\n fig, axes = plt.subplots(2, 1)\n m.plot_f(ax=axes[0])\n m.plot(ax=axes[1])\n\n print(m)\n return m\n\n\ndef toy_heaviside(seed=default_seed, max_iters=100, optimize=True, plot=True):\n \"\"\"\n Simple 1D classification example using a heavy side gp transformation\n\n :param seed: seed value for data generation (default is 4).\n :type seed: int\n\n \"\"\"\n\n try:\n import pods\n except ImportError:\n print(\"pods unavailable, see https://github.com/sods/ods for example datasets\")\n data = pods.datasets.toy_linear_1d_classification(seed=seed)\n Y = data[\"Y\"][:, 0:1]\n Y[Y.flatten() == -1] = 0\n\n # Model definition\n kernel = GPy.kern.RBF(1)\n likelihood = GPy.likelihoods.Bernoulli(\n gp_link=GPy.likelihoods.link_functions.Heaviside()\n )\n ep = GPy.inference.latent_function_inference.expectation_propagation.EP()\n m = GPy.core.GP(\n X=data[\"X\"],\n Y=Y,\n kernel=kernel,\n likelihood=likelihood,\n inference_method=ep,\n name=\"gp_classification_heaviside\",\n )\n # m = GPy.models.GPClassification(data['X'], likelihood=likelihood)\n\n # Optimize\n if optimize:\n # Parameters optimization:\n for _ in range(5):\n m.optimize(max_iters=int(max_iters / 5))\n print(m)\n\n # Plot\n if MPL_AVAILABLE and plot:\n fig, axes = plt.subplots(2, 1)\n m.plot_f(ax=axes[0])\n m.plot(ax=axes[1])\n\n print(m)\n return m\n\n\ndef crescent_data(\n model_type=\"Full\",\n num_inducing=10,\n seed=default_seed,\n kernel=None,\n optimize=True,\n plot=True,\n):\n \"\"\"\n Run a Gaussian process classification on the crescent data. The demonstration calls the basic GP classification model and uses EP to approximate the likelihood.\n\n :param model_type: type of model to fit ['Full', 'FITC', 'DTC'].\n :param inducing: number of inducing variables (only used for 'FITC' or 'DTC').\n :type inducing: int\n :param seed: seed value for data generation.\n :type seed: int\n :param kernel: kernel to use in the model\n :type kernel: a GPy kernel\n \"\"\"\n try:\n import pods\n except ImportError:\n print(\"pods unavailable, see https://github.com/sods/ods for example datasets\")\n data = pods.datasets.crescent_data(seed=seed)\n Y = data[\"Y\"]\n Y[Y.flatten() == -1] = 0\n\n if model_type == \"Full\":\n m = GPy.models.GPClassification(data[\"X\"], Y, kernel=kernel)\n\n elif model_type == \"DTC\":\n m = GPy.models.SparseGPClassification(\n data[\"X\"], Y, kernel=kernel, num_inducing=num_inducing\n )\n m[\".*len\"] = 10.0\n\n elif model_type == \"FITC\":\n m = GPy.models.FITCClassification(\n data[\"X\"], Y, kernel=kernel, num_inducing=num_inducing\n )\n m[\".*len\"] = 3.0\n if optimize:\n m.optimize(messages=1)\n\n if MPL_AVAILABLE and plot:\n m.plot()\n\n print(m)\n return m\n"
]
| [
[
"numpy.random.uniform",
"matplotlib.pyplot.subplots"
]
]
|
rishabh-16/CS231N-assignments | [
"7f73e754e185213f75598257fd86172219215375"
]
| [
"assignment3/cs231n/classifiers/rnn.py"
]
| [
"from builtins import range\nfrom builtins import object\nimport numpy as np\n\nfrom cs231n.layers import *\nfrom cs231n.rnn_layers import *\n\n\nclass CaptioningRNN(object):\n \"\"\"\n A CaptioningRNN produces captions from image features using a recurrent\n neural network.\n\n The RNN receives input vectors of size D, has a vocab size of V, works on\n sequences of length T, has an RNN hidden dimension of H, uses word vectors\n of dimension W, and operates on minibatches of size N.\n\n Note that we don't use any regularization for the CaptioningRNN.\n \"\"\"\n\n def __init__(self, word_to_idx, input_dim=512, wordvec_dim=128,\n hidden_dim=128, cell_type='rnn', dtype=np.float32):\n \"\"\"\n Construct a new CaptioningRNN instance.\n\n Inputs:\n - word_to_idx: A dictionary giving the vocabulary. It contains V entries,\n and maps each string to a unique integer in the range [0, V).\n - input_dim: Dimension D of input image feature vectors.\n - wordvec_dim: Dimension W of word vectors.\n - hidden_dim: Dimension H for the hidden state of the RNN.\n - cell_type: What type of RNN to use; either 'rnn' or 'lstm'.\n - dtype: numpy datatype to use; use float32 for training and float64 for\n numeric gradient checking.\n \"\"\"\n if cell_type not in {'rnn', 'lstm'}:\n raise ValueError('Invalid cell_type \"%s\"' % cell_type)\n\n self.cell_type = cell_type\n self.dtype = dtype\n self.word_to_idx = word_to_idx\n self.idx_to_word = {i: w for w, i in word_to_idx.items()}\n self.params = {}\n\n vocab_size = len(word_to_idx)\n\n self._null = word_to_idx['<NULL>']\n self._start = word_to_idx.get('<START>', None)\n self._end = word_to_idx.get('<END>', None)\n\n # Initialize word vectors\n self.params['W_embed'] = np.random.randn(vocab_size, wordvec_dim)\n self.params['W_embed'] /= 100\n\n # Initialize CNN -> hidden state projection parameters\n self.params['W_proj'] = np.random.randn(input_dim, hidden_dim)\n self.params['W_proj'] /= np.sqrt(input_dim)\n self.params['b_proj'] = np.zeros(hidden_dim)\n\n # Initialize parameters for the RNN\n dim_mul = {'lstm': 4, 'rnn': 1}[cell_type]\n self.params['Wx'] = np.random.randn(wordvec_dim, dim_mul * hidden_dim)\n self.params['Wx'] /= np.sqrt(wordvec_dim)\n self.params['Wh'] = np.random.randn(hidden_dim, dim_mul * hidden_dim)\n self.params['Wh'] /= np.sqrt(hidden_dim)\n self.params['b'] = np.zeros(dim_mul * hidden_dim)\n\n # Initialize output to vocab weights\n self.params['W_vocab'] = np.random.randn(hidden_dim, vocab_size)\n self.params['W_vocab'] /= np.sqrt(hidden_dim)\n self.params['b_vocab'] = np.zeros(vocab_size)\n\n # Cast parameters to correct dtype\n for k, v in self.params.items():\n self.params[k] = v.astype(self.dtype)\n\n\n def loss(self, features, captions):\n \"\"\"\n Compute training-time loss for the RNN. We input image features and\n ground-truth captions for those images, and use an RNN (or LSTM) to compute\n loss and gradients on all parameters.\n\n Inputs:\n - features: Input image features, of shape (N, D)\n - captions: Ground-truth captions; an integer array of shape (N, T) where\n each element is in the range 0 <= y[i, t] < V\n\n Returns a tuple of:\n - loss: Scalar loss\n - grads: Dictionary of gradients parallel to self.params\n \"\"\"\n # Cut captions into two pieces: captions_in has everything but the last word\n # and will be input to the RNN; captions_out has everything but the first\n # word and this is what we will expect the RNN to generate. These are offset\n # by one relative to each other because the RNN should produce word (t+1)\n # after receiving word t. The first element of captions_in will be the START\n # token, and the first element of captions_out will be the first word.\n captions_in = captions[:, :-1]\n captions_out = captions[:, 1:]\n\n # You'll need this\n mask = (captions_out != self._null)\n\n # Weight and bias for the affine transform from image features to initial\n # hidden state\n W_proj, b_proj = self.params['W_proj'], self.params['b_proj']\n\n # Word embedding matrix\n W_embed = self.params['W_embed']\n\n # Input-to-hidden, hidden-to-hidden, and biases for the RNN\n Wx, Wh, b = self.params['Wx'], self.params['Wh'], self.params['b']\n\n # Weight and bias for the hidden-to-vocab transformation.\n W_vocab, b_vocab = self.params['W_vocab'], self.params['b_vocab']\n\n loss, grads = 0.0, {}\n ############################################################################\n # TODO: Implement the forward and backward passes for the CaptioningRNN. #\n # In the forward pass you will need to do the following: #\n # (1) Use an affine transformation to compute the initial hidden state #\n # from the image features. This should produce an array of shape (N, H)#\n # (2) Use a word embedding layer to transform the words in captions_in #\n # from indices to vectors, giving an array of shape (N, T, W). #\n # (3) Use either a vanilla RNN or LSTM (depending on self.cell_type) to #\n # process the sequence of input word vectors and produce hidden state #\n # vectors for all timesteps, producing an array of shape (N, T, H). #\n # (4) Use a (temporal) affine transformation to compute scores over the #\n # vocabulary at every timestep using the hidden states, giving an #\n # array of shape (N, T, V). #\n # (5) Use (temporal) softmax to compute loss using captions_out, ignoring #\n # the points where the output word is <NULL> using the mask above. #\n # #\n # In the backward pass you will need to compute the gradient of the loss #\n # with respect to all model parameters. Use the loss and grads variables #\n # defined above to store loss and gradients; grads[k] should give the #\n # gradients for self.params[k]. #\n # #\n # Note also that you are allowed to make use of functions from layers.py #\n # in your implementation, if needed. #\n ############################################################################\n # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n h0 = features.dot(W_proj) + b_proj \n x, cache_embed = word_embedding_forward(captions_in, W_embed)\n if (self.cell_type == 'rnn'):\n h, cache = rnn_forward(x, h0, Wx, Wh, b) \n else:\n h, cache = lstm_forward(x, h0, Wx, Wh, b)\n out, cache_voc = temporal_affine_forward(h, W_vocab, b_vocab)\n loss, dout = temporal_softmax_loss(out, captions_out, mask, verbose=False)\n \n dh, dW_vocab, db_vocab = temporal_affine_backward(dout, cache_voc)\n if (self.cell_type == 'rnn'):\n dx, dh0, dWx, dWh, db = rnn_backward(dh, cache)\n else:\n dx, dh0, dWx, dWh, db = lstm_backward(dh, cache)\n dW_embed = word_embedding_backward(dx, cache_embed)\n dW_proj = features.T.dot(dh0)\n db_proj = dh0.sum(axis=0)\n grads = {'W_vocab':dW_vocab, 'b_vocab':db_vocab, 'Wx':dWx, 'Wh':dWh, \n 'b':db, 'W_embed':dW_embed, 'W_proj':dW_proj, 'b_proj':db_proj}\n # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n\n return loss, grads\n\n\n def sample(self, features, max_length=30):\n \"\"\"\n Run a test-time forward pass for the model, sampling captions for input\n feature vectors.\n\n At each timestep, we embed the current word, pass it and the previous hidden\n state to the RNN to get the next hidden state, use the hidden state to get\n scores for all vocab words, and choose the word with the highest score as\n the next word. The initial hidden state is computed by applying an affine\n transform to the input image features, and the initial word is the <START>\n token.\n\n For LSTMs you will also have to keep track of the cell state; in that case\n the initial cell state should be zero.\n\n Inputs:\n - features: Array of input image features of shape (N, D).\n - max_length: Maximum length T of generated captions.\n\n Returns:\n - captions: Array of shape (N, max_length) giving sampled captions,\n where each element is an integer in the range [0, V). The first element\n of captions should be the first sampled word, not the <START> token.\n \"\"\"\n N = features.shape[0]\n captions = self._null * np.ones((N, max_length), dtype=np.int32)\n\n # Unpack parameters\n W_proj, b_proj = self.params['W_proj'], self.params['b_proj']\n W_embed = self.params['W_embed']\n Wx, Wh, b = self.params['Wx'], self.params['Wh'], self.params['b']\n W_vocab, b_vocab = self.params['W_vocab'], self.params['b_vocab']\n\n ###########################################################################\n # TODO: Implement test-time sampling for the model. You will need to #\n # initialize the hidden state of the RNN by applying the learned affine #\n # transform to the input image features. The first word that you feed to #\n # the RNN should be the <START> token; its value is stored in the #\n # variable self._start. At each timestep you will need to do to: #\n # (1) Embed the previous word using the learned word embeddings #\n # (2) Make an RNN step using the previous hidden state and the embedded #\n # current word to get the next hidden state. #\n # (3) Apply the learned affine transformation to the next hidden state to #\n # get scores for all words in the vocabulary #\n # (4) Select the word with the highest score as the next word, writing it #\n # (the word index) to the appropriate slot in the captions variable #\n # #\n # For simplicity, you do not need to stop generating after an <END> token #\n # is sampled, but you can if you want to. #\n # #\n # HINT: You will not be able to use the rnn_forward or lstm_forward #\n # functions; you'll need to call rnn_step_forward or lstm_step_forward in #\n # a loop. #\n # #\n # NOTE: we are still working over minibatches in this function. Also if #\n # you are using an LSTM, initialize the first cell state to zeros. #\n ###########################################################################\n # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n h0 = features.dot(W_proj) + b_proj\n c0 = np.zeros_like(h0)\n x = np.repeat(W_embed[self._start].reshape(1, -1), N, axis = 0)\n for i in range(max_length):\n if self.cell_type == 'rnn':\n next_h, _ = rnn_step_forward(x, h0, Wx, Wh, b)\n else:\n next_h, next_c, _ = lstm_step_forward(x, h0, c0, Wx, Wh, b)\n c0 = next_c\n out = next_h.dot(W_vocab) + b_vocab\n max_ind = out.argmax(axis=1)\n captions[:,i] = max_ind\n x = W_embed[max_ind]\n h0 = next_h\n\n # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n return captions"
]
| [
[
"numpy.sqrt",
"numpy.ones",
"numpy.zeros_like",
"numpy.random.randn",
"numpy.zeros"
]
]
|
walkevin/ParallelTopologicalSorting | [
"d2da5f8ae99a49b130a2a91429c63da90e0083ff"
]
| [
"measurements/plotscripts/helper.py"
]
| [
"############### Color#############################################################\nimport numpy as np\nimport scipy as sp\nimport scipy.stats\nimport sqlite3\n\nmyFGcolors = [\t(0,0,200), (0,200,0), (200,0,0), \\\n\t\t\t\t(200,0,200), (0,200,200), (200,200,0), \\\n\t\t\t\t(100,100,200), (100,200,100), (200,100,100), \\\n\t\t\t\t(200,200,100), (100,200,200), (200,100,200), \\\n\t\t\t\t(50,50,50), (100,100,100), (200,200,200) ]\nmyFGcolors = list([tuple([x/255. for x in tup]) for tup in myFGcolors])\nmyBGcolors = list([tuple([np.min([x+0.4,1.0]) for x in tup]) for tup in myFGcolors])\n \ndef getFGcolor(i):\n\treturn (myFGcolors[i%len(myFGcolors)])\n\ndef getBGcolor(i):\n\treturn (myBGcolors[i%len(myBGcolors)])\n\n\n\nfontsize_title=14\nfontsize_label=12\n\n\ndef median_and_quantiles(data):\n\ta = np.array(data)\n\tmedian = np.median(a)\n\tq25 = np.percentile(a,25)\n\tq75 = np.percentile(a,75)\n\treturn median, q25, q75\n\nplotdir = \"plots/\";\nshow = False\n\n\ndef getData(field, wherestring):\n\n\twith sqlite3.connect('measurements.db') as db:\n\t\tquery = db.cursor()\n\t\tquerystring = \"SELECT {0} FROM measurements WHERE {1}\".format(field,wherestring)\n\t\tquery.execute(querystring)\n\t\tdata = query.fetchall() \n\t\t\n\treturn np.array(data)\n\n\n\n\n\n##################################################################################\n"
]
| [
[
"numpy.median",
"numpy.array",
"numpy.percentile",
"numpy.min"
]
]
|
jb-leger/assignator | [
"6047e739b0a65be8aa0f8f685b1b20f5a0622f81"
]
| [
"assignator/_cli.py"
]
| [
"# Copyright 2020, Jean-Benoist Leger <[email protected]>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport io\nimport sys\nimport csv\nimport argparse\nimport textwrap\nimport collections\n\nimport cchardet\nimport argcomplete\nimport numpy as np\n\nfrom .assignment import assignments\n\n\ndef parseargs():\n parser = argparse.ArgumentParser(\n description=textwrap.dedent(\n \"\"\"\n A tool to assign students to time slots.\n\n With allowed assignments provided in a csv (e.g. from a survey),\n provide a acceptable solution.\n \"\"\"\n ),\n epilog=textwrap.dedent(\n \"\"\"\n Workflow example:\n - Give a survey to your students providing a little bit more time\n slots than student number. Export the survey result in CSV.\n - To have a fist allocation, run the command:\n %(prog)s survey.csv -o output.csv\n If you have not assigned students, contact all the students\n marked as problematic (not only the not assigned) to extend\n their choices. Once a allocation can be made go to next step.\n - If you have more time slots than student, you can try to choice\n the time slot you want to free.\n 1. First, export the timeslot list from the csv:\n %(prog)s survey.csv -e timeslots.txt\n 2. Edit the timeslots file, adding a '#' in the begining of the\n timeslots you want to free.\n 3. Run the command with the timeslots\n %(prog)s -t timeslots.txt survey.csv -o output.csv\n \"\"\"\n ),\n formatter_class=argparse.RawDescriptionHelpFormatter,\n )\n\n parser.add_argument(\n \"--version\", action=\"version\", version=\"\", help=argparse.SUPPRESS\n )\n\n parser.add_argument(\n \"-e\",\n \"--export-timeslots\",\n dest=\"export\",\n type=argparse.FileType(\"wb\"),\n metavar=\"TIMESLOT_FILE\",\n help=\"\"\"\n Export in TIMESLOT_FILE all timeslots from the input csv.\n \"\"\",\n )\n\n parser.add_argument(\n \"-o\",\n \"--output\",\n type=argparse.FileType(\"wb\"),\n metavar=\"OUTPUT_FILE\",\n help=\"\"\"\n Output CSV file where to write assignments. The encoding and CSV\n dialect is the same than the input.\n \"\"\",\n )\n\n parser.add_argument(\n \"-t\",\n \"--timeslots\",\n type=argparse.FileType(\"rb\"),\n metavar=\"TIMESLOT_FILE\",\n help=\"\"\"\n Restrict allowed timeslots to timeslots provided in TIMESLOT_FILE.\n All line beginning with a '#' is ignored. See -e to generate a\n version of this file. If not provided, all timeslots are allowed.\n \"\"\",\n )\n\n parser.add_argument(\n \"-g\",\n \"--groups\",\n type=argparse.FileType(\"rb\"),\n metavar=\"GROUPS_FILE\",\n help=\"\"\"\n Students are in groups, and the assignments must be done by groups.\n The GROUPS_FILE must be a CSV with a header and two columns, the\n first must be a column identifying the student and must have exactly\n the same name than one of the columns provided in the INPUT_FILE,\n and values must corresponds (order or rows doesn't matter), and the\n second column must be a group identifier (whatever its name). If\n more than one student answer for a group, the intersection is made\n to build allowed timeslots for the group.\n \"\"\",\n )\n\n parser.add_argument(\n \"input\",\n type=argparse.FileType(\"rb\"),\n metavar=\"INPUT_FILE\",\n help=\"\"\"\n Input CSV file with headers. Encoding and CSV dialect are\n autodetected. This file must contain a header. The firsts\n columns contains a student identifier (e.g. the name or the name and\n the email address). Following columns are timeslots. the column name\n must identify the timeslot and therefore must be unique.\n \"\"\",\n )\n\n argcomplete.autocomplete(parser)\n args = parser.parse_args()\n return args\n\n\nclass InputDesc:\n def __init__(self, encoding, dialect, timeslots, student_id, students, bmat):\n self.encoding = encoding\n self.dialect = dialect\n self.timeslots = timeslots\n self.student_id = student_id\n self.students = students\n self.bmat = bmat\n\n def __repr__(self):\n return textwrap.dedent(\n f\"\"\"\n InputDesc(\n encoding={self.encoding!r}, \n dialect={self.dialect!r},\n timeslots={self.timeslots!r},\n student_id={self.student_id!r},\n students={self.students!r},\n bmat={self.bmat!r},\n )\"\"\"\n )\n\n\ndef read_input(filedesc) -> InputDesc:\n bcontent = filedesc.read()\n filedesc.close()\n encoding = cchardet.detect(bcontent)[\"encoding\"]\n content = bcontent.decode(encoding)\n dialect = csv.Sniffer().sniff(content)\n reader = csv.DictReader(io.StringIO(content), dialect=dialect)\n fieldnames = reader.fieldnames\n readed = list(reader)\n allbin = lambda cn: all((r[cn] in (\"0\", \"1\")) for r in readed[:-1])\n timeslots = tuple(cn for cn in fieldnames if allbin(cn))\n student_id = tuple(cn for cn in fieldnames if not allbin(cn))\n if not all((readed[-1][cn] in (\"0\", \"1\")) for cn in timeslots):\n # last row not valid\n readed.pop()\n bmat = np.array([[r[ts] for ts in timeslots] for r in readed], dtype=int)\n students = tuple({si: r[si] for si in student_id} for r in readed)\n return InputDesc(encoding, dialect, timeslots, student_id, students, bmat)\n\n\ndef make_timeslots_input(input_desc: InputDesc, timeslotfile):\n bcontent = timeslotfile.read()\n timeslotfile.close()\n encoding = cchardet.detect(bcontent)[\"encoding\"]\n content = bcontent.decode(encoding)\n content.replace(\"\\r\", \"\")\n allowed_timeslots = set(x for x in content.split(\"\\n\") if not x.startswith(\"#\"))\n newts = tuple(\n (i, ts) for i, ts in enumerate(input_desc.timeslots) if ts in allowed_timeslots\n )\n input_desc.timeslots = tuple(ts for i, ts in newts)\n input_desc.bmat = input_desc.bmat[:, [i for i, ts in newts]]\n\n\ndef make_groups_input(input_desc: InputDesc, groupsfile):\n bcontent = groupsfile.read()\n groupsfile.close()\n encoding = cchardet.detect(bcontent)[\"encoding\"]\n content = bcontent.decode(encoding)\n dialect = csv.Sniffer().sniff(content)\n reader = csv.DictReader(io.StringIO(content), dialect=dialect)\n readed = list(reader)\n\n if len(reader.fieldnames) < 2:\n print(\"E: Groups file must contains 2 columns\", file=sys.stderr)\n sys.exit(1)\n if len(reader.fieldnames) > 2:\n print(f\"W: Groups file must contains 2 columns.\", file=sys.stderr)\n print(\n f\"W: This file contains {len(reader.fieldnames)}, columns after the second are ignored\",\n file=sys.stderr,\n )\n\n student_id = reader.fieldnames[0]\n if not student_id in input_desc.student_id:\n print(\n f\"E: The column {student_id!r} from the groups file must be a id of the student found in the input file\",\n file=sys.stderr,\n )\n sys.exit(1)\n\n students = set(r[student_id] for r in readed)\n student_dict = {s[student_id]: i for i, s in enumerate(input_desc.students)}\n not_found_students = [\n s for s in input_desc.students if s[student_id] not in students\n ]\n if not_found_students:\n print(\n \"E: The following students from input file are not found in group file:\",\n file=sys.stderr,\n )\n for s in not_found_students:\n print(f\"E: - {s}\", file=sys.stderr)\n sys.exit(1)\n\n groupcolname = reader.fieldnames[1]\n groups = collections.defaultdict(lambda: [])\n for r in readed:\n if r[student_id] in student_dict:\n groups[r[groupcolname]].append(r[student_id])\n\n for g, gstud in groups.items():\n if not gstud:\n print(\"W: No reply for group {g!r}\", file=sys.stderr)\n\n groups_list = tuple(groups.keys())\n groups_bmat = np.array(\n [\n input_desc.bmat[[student_dict[sid] for sid in groups[g]], :].prod(axis=0)\n if groups[g]\n else np.ones(input_desc.bmat.shape[1], dtype=int)\n for g in groups_list\n ],\n dtype=int,\n )\n\n input_desc.bmat = groups_bmat\n input_desc.students = tuple({groupcolname: g} for g in groups)\n input_desc.student_id = (groupcolname,)\n\n\ndef main():\n args = parseargs()\n if args.export is not None and (\n args.output is not None or args.groups is not None or args.timeslots is not None\n ):\n print(\n \"When --export-timeslots is used, the following options are forbidden: --output, --groups, --timeslots.\",\n file=sys.stderr,\n )\n sys.exit(1)\n\n input_desc = read_input(args.input)\n\n if args.export is not None:\n export_file = io.TextIOWrapper(args.export, encoding=input_desc.encoding)\n for timeslot in input_desc.timeslots:\n print(timeslot, file=export_file)\n export_file.close()\n args.export.close()\n sys.exit(0)\n\n if args.timeslots is not None:\n make_timeslots_input(input_desc, args.timeslots)\n\n if args.groups is not None:\n make_groups_input(input_desc, args.groups)\n\n res = assignments(input_desc.bmat)\n if res.not_assigned_rows:\n print(\"W: The following students are not assigned:\", file=sys.stderr)\n for i in res.not_assigned_rows:\n print(f\"W: - {input_desc.students[i]}\", file=sys.stderr)\n print(\n \"W: The problem can be solved by examinating the following students:\",\n file=sys.stderr,\n )\n for i, _ in res.pb_rows:\n print(f\"W: - {input_desc.students[i]}\", file=sys.stderr)\n\n if args.output is not None:\n writer = csv.DictWriter(\n io.TextIOWrapper(args.output, encoding=input_desc.encoding),\n [\"Timeslot\"] + list(input_desc.student_id),\n )\n writer.writeheader()\n for i, j in sorted(res.best_assignments, key=lambda x: x[1]):\n row = {\"Timeslot\": input_desc.timeslots[j]}\n row.update(input_desc.students[i])\n writer.writerow(row)\n else:\n print(\n \"W: No output provided. See -o/--output to write the output to a file\",\n file=sys.stderr,\n )\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"numpy.array",
"numpy.ones"
]
]
|
tyunist/Kaggle_PKU_Baidu | [
"48651d8a0fc8a7beda0822a2db794861feada7c6"
]
| [
"demo/duplication_check.py"
]
| [
"\"\"\"\r\nThis is to example how many images are duplicated in the test train ApolloScape 3D set:\r\nhttps://github.com/idealo/imagededup\r\nPHash: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html\r\n\"\"\"\r\nimport os\r\nimport matplotlib.pylab as plt\r\nimport imagededupSt\r\nfrom imagededup.methods import PHash\r\nfrom imagededup.utils import plot_duplicates\r\n\r\nPATH = 'E:\\DATASET\\pku-autonomous-driving'\r\n\r\ntest_img_dir = os.path.join(PATH, 'test_images')\r\n# Find similar images\r\n\r\n# __Note:__ `max_distance_threshold` defines the threshold of differences between two images to consider them similar,\r\n# the higher the value, the more tolerant it is in differences.\r\n#\r\n# Below we list the first 15 images found having similar content according to imagededup.\r\n# To get the full list, you have to display the content of variable `duplicates`.\r\nphasher = PHash()\r\nduplicates = phasher.find_duplicates(image_dir=test_img_dir, scores=True, max_distance_threshold=3)\r\n\r\nprint('There are', len([x for x in duplicates if duplicates[x] != []]), 'images with similar images over', len(duplicates), 'images.')\r\n# There are 429 images with similar images over 2021 images.\r\n\r\nplt.figure(figsize=(20, 20))\r\nplot_duplicates(image_dir=test_img_dir, duplicate_map=duplicates, filename='ID_5bf531cf3.jpg')"
]
| [
[
"matplotlib.pylab.figure"
]
]
|
amznero/pandas | [
"7d4757b4deb851bb44ab6bb20cdc404fa13fffcf"
]
| [
"pandas/tests/reshape/concat/test_append.py"
]
| [
"import datetime as dt\nfrom datetime import datetime\nfrom itertools import combinations\n\nimport dateutil\nimport numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n Timestamp,\n concat,\n isna,\n)\nimport pandas._testing as tm\n\n\nclass TestAppend:\n def test_append(self, sort, float_frame):\n mixed_frame = float_frame.copy()\n mixed_frame[\"foo\"] = \"bar\"\n\n begin_index = float_frame.index[:5]\n end_index = float_frame.index[5:]\n\n begin_frame = float_frame.reindex(begin_index)\n end_frame = float_frame.reindex(end_index)\n\n appended = begin_frame.append(end_frame)\n tm.assert_almost_equal(appended[\"A\"], float_frame[\"A\"])\n\n del end_frame[\"A\"]\n partial_appended = begin_frame.append(end_frame, sort=sort)\n assert \"A\" in partial_appended\n\n partial_appended = end_frame.append(begin_frame, sort=sort)\n assert \"A\" in partial_appended\n\n # mixed type handling\n appended = mixed_frame[:5].append(mixed_frame[5:])\n tm.assert_frame_equal(appended, mixed_frame)\n\n # what to test here\n mixed_appended = mixed_frame[:5].append(float_frame[5:], sort=sort)\n mixed_appended2 = float_frame[:5].append(mixed_frame[5:], sort=sort)\n\n # all equal except 'foo' column\n tm.assert_frame_equal(\n mixed_appended.reindex(columns=[\"A\", \"B\", \"C\", \"D\"]),\n mixed_appended2.reindex(columns=[\"A\", \"B\", \"C\", \"D\"]),\n )\n\n def test_append_empty(self, float_frame):\n empty = DataFrame()\n\n appended = float_frame.append(empty)\n tm.assert_frame_equal(float_frame, appended)\n assert appended is not float_frame\n\n appended = empty.append(float_frame)\n tm.assert_frame_equal(float_frame, appended)\n assert appended is not float_frame\n\n def test_append_overlap_raises(self, float_frame):\n msg = \"Indexes have overlapping values\"\n with pytest.raises(ValueError, match=msg):\n float_frame.append(float_frame, verify_integrity=True)\n\n def test_append_new_columns(self):\n # see gh-6129: new columns\n df = DataFrame({\"a\": {\"x\": 1, \"y\": 2}, \"b\": {\"x\": 3, \"y\": 4}})\n row = Series([5, 6, 7], index=[\"a\", \"b\", \"c\"], name=\"z\")\n expected = DataFrame(\n {\n \"a\": {\"x\": 1, \"y\": 2, \"z\": 5},\n \"b\": {\"x\": 3, \"y\": 4, \"z\": 6},\n \"c\": {\"z\": 7},\n }\n )\n result = df.append(row)\n tm.assert_frame_equal(result, expected)\n\n def test_append_length0_frame(self, sort):\n df = DataFrame(columns=[\"A\", \"B\", \"C\"])\n df3 = DataFrame(index=[0, 1], columns=[\"A\", \"B\"])\n df5 = df.append(df3, sort=sort)\n\n expected = DataFrame(index=[0, 1], columns=[\"A\", \"B\", \"C\"])\n tm.assert_frame_equal(df5, expected)\n\n def test_append_records(self):\n arr1 = np.zeros((2,), dtype=(\"i4,f4,a10\"))\n arr1[:] = [(1, 2.0, \"Hello\"), (2, 3.0, \"World\")]\n\n arr2 = np.zeros((3,), dtype=(\"i4,f4,a10\"))\n arr2[:] = [(3, 4.0, \"foo\"), (5, 6.0, \"bar\"), (7.0, 8.0, \"baz\")]\n\n df1 = DataFrame(arr1)\n df2 = DataFrame(arr2)\n\n result = df1.append(df2, ignore_index=True)\n expected = DataFrame(np.concatenate((arr1, arr2)))\n tm.assert_frame_equal(result, expected)\n\n # rewrite sort fixture, since we also want to test default of None\n def test_append_sorts(self, sort):\n df1 = DataFrame({\"a\": [1, 2], \"b\": [1, 2]}, columns=[\"b\", \"a\"])\n df2 = DataFrame({\"a\": [1, 2], \"c\": [3, 4]}, index=[2, 3])\n\n with tm.assert_produces_warning(None):\n result = df1.append(df2, sort=sort)\n\n # for None / True\n expected = DataFrame(\n {\"b\": [1, 2, None, None], \"a\": [1, 2, 1, 2], \"c\": [None, None, 3, 4]},\n columns=[\"a\", \"b\", \"c\"],\n )\n if sort is False:\n expected = expected[[\"b\", \"a\", \"c\"]]\n tm.assert_frame_equal(result, expected)\n\n def test_append_different_columns(self, sort):\n df = DataFrame(\n {\n \"bools\": np.random.randn(10) > 0,\n \"ints\": np.random.randint(0, 10, 10),\n \"floats\": np.random.randn(10),\n \"strings\": [\"foo\", \"bar\"] * 5,\n }\n )\n\n a = df[:5].loc[:, [\"bools\", \"ints\", \"floats\"]]\n b = df[5:].loc[:, [\"strings\", \"ints\", \"floats\"]]\n\n appended = a.append(b, sort=sort)\n assert isna(appended[\"strings\"][0:4]).all()\n assert isna(appended[\"bools\"][5:]).all()\n\n def test_append_many(self, sort, float_frame):\n chunks = [\n float_frame[:5],\n float_frame[5:10],\n float_frame[10:15],\n float_frame[15:],\n ]\n\n result = chunks[0].append(chunks[1:])\n tm.assert_frame_equal(result, float_frame)\n\n chunks[-1] = chunks[-1].copy()\n chunks[-1][\"foo\"] = \"bar\"\n result = chunks[0].append(chunks[1:], sort=sort)\n tm.assert_frame_equal(result.loc[:, float_frame.columns], float_frame)\n assert (result[\"foo\"][15:] == \"bar\").all()\n assert result[\"foo\"][:15].isna().all()\n\n def test_append_preserve_index_name(self):\n # #980\n df1 = DataFrame(columns=[\"A\", \"B\", \"C\"])\n df1 = df1.set_index([\"A\"])\n df2 = DataFrame(data=[[1, 4, 7], [2, 5, 8], [3, 6, 9]], columns=[\"A\", \"B\", \"C\"])\n df2 = df2.set_index([\"A\"])\n\n result = df1.append(df2)\n assert result.index.name == \"A\"\n\n indexes_can_append = [\n pd.RangeIndex(3),\n Index([4, 5, 6]),\n Index([4.5, 5.5, 6.5]),\n Index(list(\"abc\")),\n pd.CategoricalIndex(\"A B C\".split()),\n pd.CategoricalIndex(\"D E F\".split(), ordered=True),\n pd.IntervalIndex.from_breaks([7, 8, 9, 10]),\n pd.DatetimeIndex(\n [\n dt.datetime(2013, 1, 3, 0, 0),\n dt.datetime(2013, 1, 3, 6, 10),\n dt.datetime(2013, 1, 3, 7, 12),\n ]\n ),\n ]\n\n indexes_cannot_append_with_other = [\n pd.MultiIndex.from_arrays([\"A B C\".split(), \"D E F\".split()])\n ]\n\n all_indexes = indexes_can_append + indexes_cannot_append_with_other\n\n @pytest.mark.parametrize(\"index\", all_indexes, ids=lambda x: type(x).__name__)\n def test_append_same_columns_type(self, index):\n # GH18359\n\n # df wider than ser\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index)\n ser_index = index[:2]\n ser = Series([7, 8], index=ser_index, name=2)\n result = df.append(ser)\n expected = DataFrame(\n [[1.0, 2.0, 3.0], [4, 5, 6], [7, 8, np.nan]], index=[0, 1, 2], columns=index\n )\n tm.assert_frame_equal(result, expected)\n\n # ser wider than df\n ser_index = index\n index = index[:2]\n df = DataFrame([[1, 2], [4, 5]], columns=index)\n ser = Series([7, 8, 9], index=ser_index, name=2)\n result = df.append(ser)\n expected = DataFrame(\n [[1, 2, np.nan], [4, 5, np.nan], [7, 8, 9]],\n index=[0, 1, 2],\n columns=ser_index,\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"df_columns, series_index\",\n combinations(indexes_can_append, r=2),\n ids=lambda x: type(x).__name__,\n )\n def test_append_different_columns_types(self, df_columns, series_index):\n # GH18359\n # See also test 'test_append_different_columns_types_raises' below\n # for errors raised when appending\n\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=df_columns)\n ser = Series([7, 8, 9], index=series_index, name=2)\n\n result = df.append(ser)\n idx_diff = ser.index.difference(df_columns)\n combined_columns = Index(df_columns.tolist()).append(idx_diff)\n expected = DataFrame(\n [\n [1.0, 2.0, 3.0, np.nan, np.nan, np.nan],\n [4, 5, 6, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, 7, 8, 9],\n ],\n index=[0, 1, 2],\n columns=combined_columns,\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"index_can_append\", indexes_can_append, ids=lambda x: type(x).__name__\n )\n @pytest.mark.parametrize(\n \"index_cannot_append_with_other\",\n indexes_cannot_append_with_other,\n ids=lambda x: type(x).__name__,\n )\n def test_append_different_columns_types_raises(\n self, index_can_append, index_cannot_append_with_other\n ):\n # GH18359\n # Dataframe.append will raise if MultiIndex appends\n # or is appended to a different index type\n #\n # See also test 'test_append_different_columns_types' above for\n # appending without raising.\n\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index_can_append)\n ser = Series([7, 8, 9], index=index_cannot_append_with_other, name=2)\n msg = (\n r\"Expected tuple, got (int|long|float|str|\"\n r\"pandas._libs.interval.Interval)|\"\n r\"object of type '(int|float|Timestamp|\"\n r\"pandas._libs.interval.Interval)' has no len\\(\\)|\"\n )\n with pytest.raises(TypeError, match=msg):\n df.append(ser)\n\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index_cannot_append_with_other)\n ser = Series([7, 8, 9], index=index_can_append, name=2)\n\n with pytest.raises(TypeError, match=msg):\n df.append(ser)\n\n def test_append_dtype_coerce(self, sort):\n\n # GH 4993\n # appending with datetime will incorrectly convert datetime64\n\n df1 = DataFrame(\n index=[1, 2],\n data=[dt.datetime(2013, 1, 1, 0, 0), dt.datetime(2013, 1, 2, 0, 0)],\n columns=[\"start_time\"],\n )\n df2 = DataFrame(\n index=[4, 5],\n data=[\n [dt.datetime(2013, 1, 3, 0, 0), dt.datetime(2013, 1, 3, 6, 10)],\n [dt.datetime(2013, 1, 4, 0, 0), dt.datetime(2013, 1, 4, 7, 10)],\n ],\n columns=[\"start_time\", \"end_time\"],\n )\n\n expected = concat(\n [\n Series(\n [\n pd.NaT,\n pd.NaT,\n dt.datetime(2013, 1, 3, 6, 10),\n dt.datetime(2013, 1, 4, 7, 10),\n ],\n name=\"end_time\",\n ),\n Series(\n [\n dt.datetime(2013, 1, 1, 0, 0),\n dt.datetime(2013, 1, 2, 0, 0),\n dt.datetime(2013, 1, 3, 0, 0),\n dt.datetime(2013, 1, 4, 0, 0),\n ],\n name=\"start_time\",\n ),\n ],\n axis=1,\n sort=sort,\n )\n result = df1.append(df2, ignore_index=True, sort=sort)\n if sort:\n expected = expected[[\"end_time\", \"start_time\"]]\n else:\n expected = expected[[\"start_time\", \"end_time\"]]\n\n tm.assert_frame_equal(result, expected)\n\n def test_append_missing_column_proper_upcast(self, sort):\n df1 = DataFrame({\"A\": np.array([1, 2, 3, 4], dtype=\"i8\")})\n df2 = DataFrame({\"B\": np.array([True, False, True, False], dtype=bool)})\n\n appended = df1.append(df2, ignore_index=True, sort=sort)\n assert appended[\"A\"].dtype == \"f8\"\n assert appended[\"B\"].dtype == \"O\"\n\n # TODO(ArrayManager) DataFrame.append reindexes a Series itself (giving\n # float dtype) -> delay reindexing until concat_array_managers which properly\n # takes care of all-null dtype inference\n @td.skip_array_manager_not_yet_implemented\n def test_append_empty_frame_to_series_with_dateutil_tz(self):\n # GH 23682\n date = Timestamp(\"2018-10-24 07:30:00\", tz=dateutil.tz.tzutc())\n ser = Series({\"date\": date, \"a\": 1.0, \"b\": 2.0})\n df = DataFrame(columns=[\"c\", \"d\"])\n result_a = df.append(ser, ignore_index=True)\n expected = DataFrame(\n [[np.nan, np.nan, 1.0, 2.0, date]], columns=[\"c\", \"d\", \"a\", \"b\", \"date\"]\n )\n # These columns get cast to object after append\n expected[\"c\"] = expected[\"c\"].astype(object)\n expected[\"d\"] = expected[\"d\"].astype(object)\n tm.assert_frame_equal(result_a, expected)\n\n expected = DataFrame(\n [[np.nan, np.nan, 1.0, 2.0, date]] * 2, columns=[\"c\", \"d\", \"a\", \"b\", \"date\"]\n )\n expected[\"c\"] = expected[\"c\"].astype(object)\n expected[\"d\"] = expected[\"d\"].astype(object)\n result_b = result_a.append(ser, ignore_index=True)\n tm.assert_frame_equal(result_b, expected)\n\n # column order is different\n expected = expected[[\"c\", \"d\", \"date\", \"a\", \"b\"]]\n result = df.append([ser, ser], ignore_index=True)\n tm.assert_frame_equal(result, expected)\n\n def test_append_empty_tz_frame_with_datetime64ns(self):\n # https://github.com/pandas-dev/pandas/issues/35460\n df = DataFrame(columns=[\"a\"]).astype(\"datetime64[ns, UTC]\")\n\n # pd.NaT gets inferred as tz-naive, so append result is tz-naive\n result = df.append({\"a\": pd.NaT}, ignore_index=True)\n expected = DataFrame({\"a\": [pd.NaT]}).astype(object)\n tm.assert_frame_equal(result, expected)\n\n # also test with typed value to append\n df = DataFrame(columns=[\"a\"]).astype(\"datetime64[ns, UTC]\")\n other = Series({\"a\": pd.NaT}, dtype=\"datetime64[ns]\")\n result = df.append(other, ignore_index=True)\n expected = DataFrame({\"a\": [pd.NaT]}).astype(object)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"dtype_str\", [\"datetime64[ns, UTC]\", \"datetime64[ns]\", \"Int64\", \"int64\"]\n )\n @pytest.mark.parametrize(\"val\", [1, \"NaT\"])\n def test_append_empty_frame_with_timedelta64ns_nat(self, dtype_str, val):\n # https://github.com/pandas-dev/pandas/issues/35460\n df = DataFrame(columns=[\"a\"]).astype(dtype_str)\n\n other = DataFrame({\"a\": [np.timedelta64(val, \"ns\")]})\n result = df.append(other, ignore_index=True)\n\n expected = other.astype(object)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"dtype_str\", [\"datetime64[ns, UTC]\", \"datetime64[ns]\", \"Int64\", \"int64\"]\n )\n @pytest.mark.parametrize(\"val\", [1, \"NaT\"])\n def test_append_frame_with_timedelta64ns_nat(self, dtype_str, val):\n # https://github.com/pandas-dev/pandas/issues/35460\n df = DataFrame({\"a\": pd.array([1], dtype=dtype_str)})\n\n other = DataFrame({\"a\": [np.timedelta64(val, \"ns\")]})\n result = df.append(other, ignore_index=True)\n\n expected = DataFrame({\"a\": [df.iloc[0, 0], other.iloc[0, 0]]}, dtype=object)\n tm.assert_frame_equal(result, expected)\n"
]
| [
[
"numpy.array",
"pandas._testing.assert_almost_equal",
"pandas._testing.assert_produces_warning",
"pandas.Series",
"pandas.RangeIndex",
"pandas.array",
"pandas.Index",
"pandas.DataFrame",
"pandas.IntervalIndex.from_breaks",
"numpy.concatenate",
"numpy.timedelta64",
"numpy.random.randn",
"pandas.isna",
"pandas._testing.assert_frame_equal",
"numpy.zeros",
"numpy.random.randint"
]
]
|
ishine/pnf-sampling | [
"d92a6b82c2abd8ce26aae6a470cd78f686c7282a"
]
| [
"pnf-wavenet/wavenet_vocoder/pnf/pnf_utils.py"
]
| [
"import torch\n\nfrom train import build_model\n\n\n# The various noise levels, geometrically spaced\nCHECKPOINTS = {\n 175.9 : 'checkpoints175pt9',\n 110. : 'checkpoints110pt0',\n 68.7 : 'checkpoints68pt7',\n 54.3 : 'checkpoints54pt3',\n 42.9 : 'checkpoints42pt9',\n 34.0 : 'checkpoints34pt0',\n 26.8 : 'checkpoints26pt8',\n 21.2 : 'checkpoints21pt2',\n 16.8 : 'checkpoints16pt8',\n 13.3 : 'checkpoints13pt3',\n 10.5 : 'checkpoints10pt5',\n 8.29 : 'checkpoints8pt29',\n 6.55 : 'checkpoints6pt55',\n 5.18 : 'checkpoints5pt18',\n 4.1 : 'checkpoints4pt1',\n 3.24 : 'checkpoints3pt24',\n 2.56 : 'checkpoints2pt56',\n 1.6 : 'checkpoints1pt6',\n 1.0 : 'checkpoints1pt0',\n 0.625 : 'checkpoints0pt625',\n 0.39 : 'checkpoints0pt39',\n 0.244 : 'checkpoints0pt244',\n 0.15 : 'checkpoints0pt15',\n 0.1 : 'checkpoints0pt1'\n}\n\n\nclass ModelWrapper(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.model = build_model()\n self.model.eval()\n self.receptive_field = self.model.receptive_field\n\n def load_checkpoint(self, path):\n print(\"Load checkpoint from {}\".format(path))\n checkpoint = torch.load(path)\n self.model.load_state_dict(checkpoint[\"state_dict\"])\n\n def forward(self, x, sigma, c=None):\n return self.model.smoothed_loss(x, c=c, sigma=sigma, batched=True)\n"
]
| [
[
"torch.load"
]
]
|
ThomasRanvier/deep_rl_project | [
"6be1f655f7bbcf6aab5e7da353be3ca35fba449b"
]
| [
"atari/run_trained_model.py"
]
| [
"import matplotlib.pyplot as plt\nimport torch\nfrom atari import Atari\nimport sys\n\nN_EPISODES = 1\nMEAN_K = 10\nDISPLAY = False\nDYNAMIC = False\nSAVE_GIF = True\n\ndef run_episode(net, env):\n env.reset()\n episode_reward = 0\n terminal = False\n terminal_life_loss = False\n while not terminal:\n if DISPLAY:\n env.render(mode='human')\n if not terminal_life_loss:\n output = net(env.get_state())\n action_index = int(torch.argmax(output)) + 1\n else:\n action_index = 1\n _, reward, terminal, terminal_life_loss = env.step(action_index)\n episode_reward += reward\n return episode_reward\n\nif __name__ == \"__main__\":\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model_path = sys.argv[1]\n policy_net = torch.load(model_path).double()\n policy_net.eval()\n env = Atari(device, save_gif=SAVE_GIF)\n ep = []\n rew = []\n ep_mean = []\n rew_mean = []\n iterations = 0\n reward_sum = 0\n total = 0\n if DYNAMIC:\n plt.ion()\n fig, ax = plt.subplots()\n for episode in range(N_EPISODES):\n episode_reward = run_episode(policy_net, env)\n reward_sum += episode_reward\n total += episode_reward\n rew.append(episode_reward)\n ep.append(episode + 1)\n if episode % MEAN_K == MEAN_K - 1:\n print('Episode', episode + 1)\n ep_mean.append(episode + 1)\n rew_mean.append(reward_sum / MEAN_K)\n reward_sum = 0\n if DYNAMIC:\n ax.set_xlabel('Episodes')\n ax.set_ylabel('Reward', color='red')\n ax.plot(ep, rew, color='orange', alpha=.35)\n ax.plot(ep_mean, rew_mean, color='red')\n ax.tick_params(axis='y', labelcolor='red')\n print('Reward mean:', total / N_EPISODES)\n if DYNAMIC:\n plt.ioff()\n else:\n ax.set_xlabel('Episodes')\n ax.set_ylabel('Reward', color='red')\n ax.plot(ep, rew, color='orange', alpha=.35)\n ax.plot(ep_mean, rew_mean, color='red')\n ax.tick_params(axis='y', labelcolor='red')\n plt.show()\n"
]
| [
[
"torch.load",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.ioff",
"torch.cuda.is_available",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ion",
"torch.argmax"
]
]
|
SWhardfish/CSVtoMatplotlib | [
"f791de6029530a43fc471033494a689b1f4222ff"
]
| [
"EncryptionStats.py"
]
| [
"import pandas as pd\nimport glob\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport datetime\nimport numpy as np\nfrom matplotlib.ticker import (MultipleLocator, FormatStrFormatter,\n AutoMinorLocator)\n\n\npd.set_option('display.max_rows', 10000)\npd.set_option('display.max_columns', 100)\npd.set_option('display.width', 1000)\n\nDataFiles = glob.glob('C:/Users/anders.rylander2/PycharmProjects/Stats/venv/Files/*Protocol*.csv') #creates a list of all csv files\n#DataFiles = glob.glob('*Protocol*.csv') #creates a list of all csv files\n\ndata = [] # pd.concat takes a list of dataframes as an argument\nfor csv in DataFiles:\n frame = pd.read_csv(csv)\n frame['Date'] = os.path.basename(csv)\n data.append(frame)\n\ndf = pd.concat(data, ignore_index=True) #dont want pandas to try an align row indexes\n\n#REGEX to extract Date from Filename\ndf['Date'] = df['Date'].str.extract('([0-9]{8})', expand=False)\n\n#Index Date Column and Create DateTime column\ndf.index = pd.to_datetime(df[\"Date\"])\n\n#Drop Date column\ndf = df.drop(columns=[\"Date\"])\n\n#Date in Filename is for 1 day after so correcting here\ndf.index = df.index + pd.Timedelta(days=-1)\n\ndf['Total Bytes'] = df['Total Bytes']/1024/1024/1024 #Convert to GB\ndf['Bytes Received'] = df['Bytes Received']/1024/1024/1024 #Convert to GB\ndf['Bytes Sent'] = df['Bytes Sent']/1024/1024/1024 #Convert to GB\ndf['Requests'] = df['Requests']/1000 #Convert to K Request\n\n#ratio = df['Bytes Received'] / df['Bytes Sent']\n#print(ratio)\n#df['RatioII'] = df['Bytes Received'] / df['Bytes Sent']\n#print(df)\n\n\n#Sort index (date) in cronological order)\ndf = df.sort_index()\n\n#Name index column\ndf.index.name = 'DateTime'\n\nHTTP = df.loc[df['Protocol'] == 'http']\n#print(HTTP)\nHTTPS = df.loc[df['Protocol'] == 'https']\n#print(HTTPS)\n#print(df)\n\nHTTP['HTTPSReceived'] = HTTPS['Bytes Received'] #add the HTTPS column to the HTTP DF\nRatio = (HTTP['HTTPSReceived'] / (HTTP['Bytes Received'] + HTTP['HTTPSReceived'])) * 100\nHTTP['Ratio'] = Ratio #add Ratio to the HTTP DF\nHTTP = HTTP.drop(columns=[\"Page Views\", \"Bytes Sent\", \"Total Bytes\", \"Protocol\"])\nprint(HTTP)\n\n\n\n#Stats = df['Requests'].describe()\n#print(Stats)\n\n#df.insert(7, \"HTTP\", [HTTP], True)\n#HTTPS = [df.loc[df['Protocol'] == 'https']]\n#df['HTTPS'] = HTTPS\n\n#print(df)\n#Find largest value in column\n##print(df['Total Bytes'].max())\n#Print row with largest hour 'Total Bytes'\nprint('------------------------------------------------------------------------------')\nprint('Date and Hour with largest Total Thousand Requests:')\nprint(df[df['Requests'] == df['Requests'].max()])\nprint('------------------------------------------------------------------------------')\nprint('Date and Hour with largest Total GB:')\nprint(df[df['Total Bytes'] == df['Total Bytes'].max()])\nprint('------------------------------------------------------------------------------')\nprint('Date and Hour with largest Total Received GB:')\nprint(df[df['Bytes Received'] == df['Bytes Received'].max()])\nprint('------------------------------------------------------------------------------')\nprint('Date and Hour with largest Total Sent GB:')\nprint(df[df['Bytes Sent'] == df['Bytes Sent'].max()])\nprint('------------------------------------------------------------------------------')\n#print(df.index)\n#print(type(df.index))\n##### P L O T #####\n#df.plot(kind='bar', x='DateTime', y='Bytes Received', color='lightblue')\n#df.plot(kind='bar', x='DateTime', y='Bytes Sent', color='lightblue')\n\n#fig, ax = plt.subplots(figsize=(13, 3))\n#xaxis = df.index\n#yaxis = df['Total Bytes']\n#ax.plot(xaxis, yaxis)\n#xfmt = mdates.DateFormatter('%d %b')\n#ax.xaxis.set_major_formatter(xfmt)\n#plt.title('Amount of Data Uploaded Data during Peak Hour per Day')\n#plt.ylabel('Uploaded Data (GB)')\n\n##TEST SUBPLOT1##\n#xaxis = df.index\n#y1axis = df['Total Bytes']\n#y2axis = df['Bytes Sent']\n#y3axis = df['Bytes Received']\n\n#plt.subplot(3, 1, 1)\n#plt.plot(xaxis, y1axis)\n#plt.title('3 subplots')\n#plt.ylabel('Total Bytes (GB)')\n\n#plt.subplot(3, 1, 2)\n#plt.plot(xaxis, y2axis)\n#plt.ylabel('Bytes Sent (GB)')\n\n#plt.subplot(3, 1, 3)\n#plt.plot(xaxis, y3axis)\n#plt.ylabel('Bytes Received (GB)')\n################\n\n#######TEST SUBPLOT2#####\n# Create two subplots sharing x axis\n#xaxis = df.index\nxHTTP = HTTP.index\ny1axis = HTTP['Ratio']\ny2axis = HTTP['HTTPSReceived']\ny3axis = HTTP['Bytes Received']\ny4axis = HTTP['Requests']\n\n\nfig, (ax4, ax1, ax2) = plt.subplots(3, sharey=False, figsize=(15, 6))\nplt.subplots_adjust(hspace=0.5)\n\nax4.plot(xHTTP, y4axis, color='black', linewidth=0.4)\nax4.grid(which='major', axis='y', linestyle='dotted')\nax4.legend(['Total Requests (x1000) per Day'], loc='upper right', fontsize='x-small')\nax4.set(title='Internet Proxy Volume of HTTPS Traffic - INBOUND', ylabel='No. Requests')\n\nax1.plot(xHTTP, y1axis, color='black', linewidth=0.4)\nax1.grid(which='both', axis='y', linestyle='dotted')\nax1.grid(which='both', axis='x', linestyle='dotted')\nax1.set_ylim([0, 100])\nax1.legend(['% HTTPS'], loc='lower right', fontsize='x-small')\nax1.set(ylabel= '% HTTPS')\nax1.yaxis.set_minor_locator(AutoMinorLocator())\nax1.tick_params(which='both')\nax1.tick_params(which='major')\n#ax1.tick_params(which='minor', labelsize=4)\n#ax1.yaxis.set_minor_formatter(FormatStrFormatter(\"%.0f\"))\n\n# Annotate\n#style = dict(size=10, color='gray')\n#ax1.text('2020-1-1', 50, \"New Year's Day\", **style)\n#x_line_annotation = HTTP.Date(2020, 03, 03)\n#x_text_annotation = df.index(2020, 03, 04)\n#ax1.axvline(x=x_line_annotation, linestyle='dashed', alpha=0.5)\n#ax1.text(x=x_text_annotation, y=90, s='Holiday in US', alpha=0.7, color='#334f8d')\n\np1 = ax2.bar(xHTTP, y2axis, width=0.7, color='red')\np2 = ax2.bar(xHTTP, y3axis, width=0.7, color='green')\nax2.grid(which='major', axis='y', linestyle='dotted')\n#ax2.legend((y2axis, y3axis), ('HTTPS Received GB per Day', 'HTTP Received GB per Day'))\nax2.legend((p1[0], p2[0]), ('HTTPS Received GB per Day', 'HTTP Received GB per Day'), loc='upper right', fontsize='x-small')\nax2.set(ylabel='HTTP/S Data')\n\n###ax3.bar(xHTTP, y3axis, width=0.7, color='green')\n###ax3.grid(which='major', axis='y', linestyle='dotted')\n###ax3.legend(['HTTP Received GB per Day'], loc='upper right', fontsize='x-small')\n###ax3.set(ylabel='HTTP Data')\n\n#df.plot(kind='bar', y='Total Bytes', figsize=(10, 3), use_index=True)\nplt.savefig('ProxyEncrypted.pdf', bbox_inches='tight', pad_inches=2)\nplt.savefig('ProxyEncrypted.png', bbox_inches='tight', pad_inches=0.5)\n#df.groupby(['Bytes Received', 'Bytes Sent']).size().unstack().plot(kind='bar', stacked=True)\n#plt.plot_date([d.astype(datetime.datetime) for d in df[0]], df['Total Bytes'])\nplt.show()\n#print(df)\n\n\n\n\n"
]
| [
[
"pandas.concat",
"pandas.to_datetime",
"pandas.read_csv",
"matplotlib.ticker.AutoMinorLocator",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"pandas.Timedelta",
"matplotlib.pyplot.subplots_adjust",
"pandas.set_option",
"matplotlib.pyplot.show"
]
]
|
dazhwu/pydynpd | [
"910563c28000e6200c11beddd6aa80b9602c5315"
]
| [
"pydynpd/instruments.py"
]
| [
"import numpy as np\n\nfrom pydynpd.info import df_info, z_info, options_info\n\n\nclass instruments(object):\n\n def __init__(self, variables: dict, gmm_tables: dict, df_information: df_info, options: options_info):\n level = options.level\n collapse = options.collapse\n transformation = options.transformation\n self.z_information, self.gmm_diff_info, self.iv_diff_info, self.gmm_level_info = self.calculate_z_dimension(\n variables, df_information, level, transformation, collapse)\n\n if level:\n self.z_table = self.build_z_level(variables, gmm_tables, df_information, transformation, collapse)\n else:\n self.z_table = self.build_z_diff(variables, gmm_tables, df_information, False, transformation, collapse)\n\n def build_z_level(self, variables: dict, gmm_tables: dict, info: df_info, transformation, collapse=False):\n last_level_index = info.last_level_index\n first_level_index = info.first_level_index\n\n z_table = self.build_z_diff(\n variables, gmm_tables, info, True, transformation, collapse)\n\n level_width = self.z_information.level_width\n level_height = self.z_information.level_height\n diff_width = self.z_information.diff_width\n diff_height = self.z_information.diff_height\n width = self.z_information.width\n height = self.z_information.height\n\n Lgmm_vars = variables['Lgmm']\n iv_vars = variables['iv']\n Lgmm_dat = gmm_tables['Lgmm']\n iv_dat = gmm_tables['iv']\n\n Lgmm_iv_height = int(Lgmm_dat.shape[0] / info.N)\n\n start_row = diff_height # z_table[0].shape[0]-height\n start_col = diff_width # z_table[0].shape[1]-width\n\n for i in range(info.N):\n z = z_table[(i * height):(i * height + height), :]\n # z[start_row-1,start_col:(start_col+self.level_width)]=1\n z[height - 1, start_col:width] = 1\n array_Lgmm = Lgmm_dat[(i * Lgmm_iv_height):(i * Lgmm_iv_height + Lgmm_iv_height), :]\n array_iv = iv_dat[(i * Lgmm_iv_height):(i * Lgmm_iv_height + Lgmm_iv_height), :]\n\n for var_id in range(len(Lgmm_vars)):\n lag = Lgmm_vars[var_id].min_lag\n t_info = self.gmm_level_info[3 * var_id: (3 * var_id + 3), :]\n for j in range(level_width):\n the_index = t_info[0, j]\n if the_index >= 0:\n the_row = start_row + t_info[2, j]\n\n the_index = t_info[0, j]\n\n z[the_row, start_col + j] = array_Lgmm[the_index, var_id]\n\n start_pos = self.z_information.num_Dgmm_instr\n for var_id in range(len(iv_vars)):\n var = iv_vars[var_id]\n z[start_pos + var_id,\n start_col:width] = array_iv[first_level_index:(last_level_index + 1), var_id]\n\n z[np.isnan(z)] = 0\n\n return z_table\n\n def prepare_z_gmm_level(self, variables: dict, level_width, info: df_info, collapse=False):\n\n gmm_vars = variables['Lgmm']\n num_gmm = len(gmm_vars)\n t_info = np.empty((num_gmm * 3, level_width),\n dtype='int32') # row 0: gmm_index, 2: which row, 1: empty right now\n\n start_row = 0\n var_id = 0\n for var_id in range(num_gmm):\n var = gmm_vars[var_id]\n for i in range(level_width):\n the_index = info.first_level_index + i\n gmm_index = the_index - var.min_lag\n\n t_info[var_id * 3 + 2, i] = start_row\n\n if gmm_index >= 1:\n t_info[var_id * 3 + 0, i] = gmm_index\n if collapse:\n if i == level_width - 1:\n start_row += 1\n else:\n start_row += 1\n\n else:\n t_info[var_id * 3 + 0, i] = -9999\n\n num_Lgmm_instr = start_row # number of gmm instruments in diff eq\n\n return (num_Lgmm_instr, t_info)\n\n def calculate_z_dimension(self, variables: dict, info: df_info, level, transformation, collapse=False):\n Lgmm_vars = variables['Lgmm']\n\n diff_width = info.last_diff_index - info.first_diff_index + 1\n\n level_width = info.last_level_index - info.first_level_index + 1\n\n level_height = 0\n num_Lgmm_instr = 0\n gmm_level_info = None\n if level:\n num_Lgmm_instr, gmm_level_info = self.prepare_z_gmm_level(variables, level_width, info, collapse)\n level_height = num_Lgmm_instr + 1\n\n num_Dgmm_instr, gmm_diff_info = self.prepare_Z_gmm_diff(\n variables, info, level, transformation, collapse)\n iv_diff_info = self.prepare_Z_iv_diff(variables, diff_width, info)\n\n diff_height = (num_Dgmm_instr + iv_diff_info.shape[0])\n\n if level:\n height = diff_height + level_height\n width = diff_width + level_width\n else:\n height = diff_height\n width = diff_width\n\n z_information = z_info(diff_height=diff_height, diff_width=diff_width, level_width=level_width,\n level_height=level_height, height=height, width=width,\n num_Dgmm_instr=num_Dgmm_instr, num_Lgmm_instr=num_Lgmm_instr, num_instr=height)\n\n return (z_information, gmm_diff_info, iv_diff_info, gmm_level_info)\n\n def build_z_diff(self, variables: dict, gmm_tables: dict, info: df_info, level, transformation, collapse=False):\n\n gmm_vars = variables['Dgmm']\n iv_vars = variables['iv']\n Dgmm_dat = gmm_tables['Dgmm']\n Div_dat = gmm_tables['Div']\n\n gmm_Div_height = int(Dgmm_dat.shape[0] / info.N)\n\n diff_width = self.z_information.diff_width\n height = self.z_information.height\n width = self.z_information.width\n num_Dgmm_instr = self.z_information.num_Dgmm_instr\n\n z_table = np.zeros((height * info.N, width), dtype=np.float64)\n\n for i in range(info.N):\n if level and transformation == 'fod':\n z = z_table[i * height:(i + 1) * height, 1:diff_width]\n\n else:\n z = z_table[i * height:(i + 1) * height, 0:diff_width]\n\n z_width = z.shape[1]\n array_gmm = Dgmm_dat[i * gmm_Div_height:(i + 1) * gmm_Div_height, :]\n array_fd_iv = Div_dat[i * gmm_Div_height:(i + 1) * gmm_Div_height, :]\n\n var_id = 0\n for var in gmm_vars:\n for j in range(z_width):\n row_pos = self.gmm_diff_info[var_id * 3 + 2, j]\n\n start = self.gmm_diff_info[var_id * 3 + 0, j]\n end = self.gmm_diff_info[var_id * 3 + 1, j]\n\n for k in range(end - start + 1):\n z[row_pos + k, j] = array_gmm[end - k, var_id]\n var_id += 1\n\n row_pos = num_Dgmm_instr\n\n var_id = 0\n for var_id in range(len(iv_vars)):\n var = iv_vars[var_id]\n for j in range(z_width):\n index_to_take = self.iv_diff_info[var_id, j]\n\n z[row_pos, j] = array_fd_iv[index_to_take, var_id]\n\n row_pos += 1\n\n z[np.isnan(z)] = 0\n\n return z_table\n\n def prepare_Z_iv_diff(self, variables: dict, width, info: df_info):\n iv_vars = variables['iv'] # need to be placed at the beginning\n num_iv = len(iv_vars)\n\n t_info = np.empty((num_iv, width), dtype='int32')\n # num_iv_instr = 0\n var_id = 0\n for var_id in range(num_iv):\n var = iv_vars[var_id]\n t_info[var_id,] = range(info.first_diff_index, info.last_diff_index + 1)\n # num_iv_instr += width\n\n return (t_info)\n\n def prepare_Z_gmm_diff(self, variables: dict, info: df_info, level, transformation, collapse=False):\n start_row = 0\n\n gmm_vars = variables['Dgmm']\n num_gmm = len(gmm_vars)\n\n var_id = 0\n if level and transformation == 'fod':\n first_index = info.first_diff_index + 1\n else:\n first_index = info.first_diff_index\n last_index = info.last_diff_index\n width = last_index - first_index + 1\n\n t_info = np.empty((num_gmm * 3, width), dtype='int32')\n\n for var_id in range(num_gmm):\n var = gmm_vars[var_id]\n\n first_tend = first_index - var.min_lag\n last_tend = last_index - var.min_lag\n\n tend = np.arange(first_tend, last_tend + 1, dtype='int32')\n t_info[var_id * 3 + 1,] = tend\n\n for i in range(width):\n tstart = max(0, tend[i] + var.min_lag - var.max_lag)\n t_info[var_id * 3 + 0, i] = tstart\n # t_info[var_id*3+1, i]=tend[i]\n # physical position of the row\n t_info[var_id * 3 + 2, i] = start_row\n\n num = tend[i] - tstart + 1\n # num_instru += num\n if collapse:\n if i == (width - 1):\n start_row += num\n else:\n start_row += num\n\n num_gmm_instr = start_row # number of gmm instruments in diff eq\n\n return ((num_gmm_instr, t_info))\n"
]
| [
[
"numpy.isnan",
"numpy.arange",
"numpy.zeros",
"numpy.empty"
]
]
|
VNOpenAI/OpenControl | [
"0087408c57bc77f34f524b28f8c4363b116700bb"
]
| [
"OpenControl/visualize/visualize.py"
]
| [
"import numpy as np\nimport os\nfrom torch.utils.tensorboard import SummaryWriter\n\nclass Logger(object):\n \"\"\"Real-time visualize simulation results, using Tensorboard\n \n Attributes:\n writer (class): the same as SummaryWriter_\n \n .. _SummaryWriter: https://pytorch.org/docs/stable/tensorboard.html\n \"\"\"\n def __init__(self, log_dir='results', filename_suffix=''):\n \"\"\"The same as SummaryWriter_ \n\n Args:\n log_dir (str, optional): the direction to save the log file. Defaults to 'results' folder.\n filename_suffix (str, optional): suffix added to the name of log file. Defaults to ''.\n \"\"\"\n if not os.path.isdir(log_dir):\n os.mkdir(log_dir)\n self.writer = SummaryWriter(log_dir=log_dir, filename_suffix=filename_suffix)\n \n def log(self, section, signals, step):\n \"\"\"Log the signals with the name of section in the step time\n\n Args:\n section (str): name of signals\n signals (array): signals\n step (int): only `int` type is acceptable. Please convert `float` timestep to `int`\n \"\"\"\n signals = np.array(signals).flatten()\n sig_dict = {}\n for i in range(len(signals)):\n sig_dict['_'+str(i)] = signals[i]\n self.writer.add_scalars(main_tag=section, tag_scalar_dict=sig_dict, global_step=step)\n \n # def log_series(self, section, series, steps):\n # # series.shape = [n_series, n_signal]\n # series = np.array(series)\n # sample_time = (steps[-1] - steps[0])/(len(steps)-1)\n # steps = (steps/sample_time).astype(int)\n # for i in range(len(series)):\n # self.log(section, series[i], steps[i])\n \n def end_log(self):\n \"\"\"Call this function to end logging\n \"\"\"\n self.writer.close()\n \nif __name__ == '__main__':\n logX = Logger(log_dir='results', filename_suffix='step1')\n for i in range(100):\n logX.log('euler', [i*np.cos(i), i*np.sin(i)], i)\n logX.end_log()"
]
| [
[
"numpy.cos",
"numpy.array",
"torch.utils.tensorboard.SummaryWriter",
"numpy.sin"
]
]
|
zkurtz/kaggle_malware_2019 | [
"72465b2f5d5f49d1acefa9b4f6b06df2aa53e4a8"
]
| [
"build_data/refactor_data.py"
]
| [
"from feather import read_dataframe as read_feather\nimport numpy as np\nimport pandas as pd\nimport pdb\n\nfrom zpylib import data_path as dp\nfrom zpylib import train_colnames\nfrom zpylib.datatools import FeaturesByType\n\ndef refactor_col(infile, col):\n print(\" ... \" + col)\n series = read_feather(infile, columns=[col])[col]\n if col in PREDCOLS:\n metadata = pd.read_csv(dp(\"metadata/\" + col)).drop('counts', axis=1)\n if col in FeaturesByType.categorical:\n df = pd.DataFrame({col: series})\n df['order'] = range(df.shape[0])\n df = df.merge(metadata, how='left').sort_values('order')\n newcol = 'new_' + col\n series = df[newcol].fillna(metadata.shape[0])\n values = series.astype(np.int64).values # Lightgbm treats this as missing for categorical features\n elif metadata[col].dtype.name in ['int64', 'float64']:\n values = series.values\n else:\n pdb.set_trace()\n else:\n values = series.values\n return values\n\ndef refactor(infile, outfile, expected_columns):\n print(\"### Loading \" + infile)\n df = pd.DataFrame({col: refactor_col(infile, col) for col in expected_columns})\n df.to_feather(outfile)\n\n# Constants\nALLCOLS = pd.read_csv(dp('raw/train.csv'), nrows=2).columns.tolist()\nALLCOLS_EXCEPT_RESPONSE = [a for a in ALLCOLS if a != 'HasDetections']\nPREDCOLS = train_colnames()\n\n# Main\nrefactor(dp(\"raw/train.feather\"), dp(\"refactored/train.feather\"), ALLCOLS)\nrefactor(dp(\"raw/test.feather\"), dp(\"refactored/test.feather\"), ALLCOLS_EXCEPT_RESPONSE)"
]
| [
[
"pandas.DataFrame"
]
]
|
tannonk/datasets | [
"c59950a557d9021fb1597f266c03c47aba09cb56"
]
| [
"src/datasets/fingerprint.py"
]
| [
"import inspect\nimport json\nimport os\nimport random\nimport shutil\nimport tempfile\nimport weakref\nfrom dataclasses import asdict\nfrom functools import wraps\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Union\n\nimport numpy as np\nimport pyarrow as pa\nimport xxhash\n\nfrom datasets.table import ConcatenationTable, InMemoryTable, MemoryMappedTable, Table\n\nfrom .info import DatasetInfo\nfrom .utils.logging import get_logger\nfrom .utils.py_utils import dumps\n\n\nif TYPE_CHECKING:\n from .arrow_dataset import Dataset\n\n\nlogger = get_logger(__name__)\n\n\n# Fingerprinting allows to have one deterministic fingerprint per dataset state.\n# A dataset fingerprint is updated after each transform.\n# Re-running the same transforms on a dataset in a different session results in the same fingerprint.\n# This is possible thanks to a custom hashing function that works with most python objects.\n\n# Fingerprinting is the main mechanism that enables caching.\n# The caching mechanism allows to reload an existing cache file if it's already been computed.\n\n\n#################\n# Caching\n#################\n\n_CACHING_ENABLED = True\n_TEMP_DIR_FOR_TEMP_CACHE_FILES: Optional[\"_TempDirWithCustomCleanup\"] = None\n_DATASETS_WITH_TABLE_IN_TEMP_DIR: Optional[weakref.WeakSet] = None\n\n\nclass _TempDirWithCustomCleanup:\n \"\"\"\n A temporary directory with a custom cleanup function.\n We need a custom temporary directory cleanup in order to delete the dataset objects that have\n cache files in the temporary directory before deleting the dorectory itself.\n \"\"\"\n\n def __init__(self, cleanup_func=None, *cleanup_func_args, **cleanup_func_kwargs):\n self.name = tempfile.mkdtemp()\n self._finalizer = weakref.finalize(self, self._cleanup)\n self._cleanup_func = cleanup_func\n self._cleanup_func_args = cleanup_func_args\n self._cleanup_func_kwargs = cleanup_func_kwargs\n\n def _cleanup(self):\n self._cleanup_func(*self._cleanup_func_args, **self._cleanup_func_kwargs)\n if os.path.exists(self.name):\n shutil.rmtree(self.name)\n\n def cleanup(self):\n if self._finalizer.detach():\n self._cleanup()\n\n\ndef maybe_register_dataset_for_temp_dir_deletion(dataset):\n \"\"\"\n This function registers the datasets that have cache files in _TEMP_DIR_FOR_TEMP_CACHE_FILES in order\n to properly delete them before deleting the temporary directory.\n The temporary directory _TEMP_DIR_FOR_TEMP_CACHE_FILES is used when caching is disabled.\n \"\"\"\n if _TEMP_DIR_FOR_TEMP_CACHE_FILES is None:\n return\n\n global _DATASETS_WITH_TABLE_IN_TEMP_DIR\n if _DATASETS_WITH_TABLE_IN_TEMP_DIR is None:\n _DATASETS_WITH_TABLE_IN_TEMP_DIR = weakref.WeakSet()\n if any(\n os.path.samefile(os.path.dirname(cache_file[\"filename\"]), _TEMP_DIR_FOR_TEMP_CACHE_FILES.name)\n for cache_file in dataset.cache_files\n ):\n _DATASETS_WITH_TABLE_IN_TEMP_DIR.add(dataset)\n\n\ndef get_datasets_with_cache_file_in_temp_dir():\n return list(_DATASETS_WITH_TABLE_IN_TEMP_DIR) if _DATASETS_WITH_TABLE_IN_TEMP_DIR is not None else []\n\n\ndef set_caching_enabled(boolean: bool):\n \"\"\"\n When applying transforms on a dataset, the data are stored in cache files.\n The caching mechanism allows to reload an existing cache file if it's already been computed.\n\n Reloading a dataset is possible since the cache files are named using the dataset fingerprint, which is updated\n after each transform.\n\n If disabled, the library will no longer reload cached datasets files when applying transforms to the datasets.\n More precisely, if the caching is disabled:\n - cache files are always recreated\n - cache files are written to a temporary directory that is deleted when session closes\n - cache files are named using a random hash instead of the dataset fingerprint\n - use :func:`datasets.Dataset.save_to_disk` to save a transformed dataset or it will be deleted when session closes\n - caching doesn't affect :func:`datasets.load_dataset`. If you want to regenerate a dataset from scratch you should use\n the ``download_mode`` parameter in :func:`datasets.load_dataset`.\n \"\"\"\n global _CACHING_ENABLED\n _CACHING_ENABLED = bool(boolean)\n\n\ndef is_caching_enabled() -> bool:\n \"\"\"\n When applying transforms on a dataset, the data are stored in cache files.\n The caching mechanism allows to reload an existing cache file if it's already been computed.\n\n Reloading a dataset is possible since the cache files are named using the dataset fingerprint, which is updated\n after each transform.\n\n If disabled, the library will no longer reload cached datasets files when applying transforms to the datasets.\n More precisely, if the caching is disabled:\n - cache files are always recreated\n - cache files are written to a temporary directory that is deleted when session closes\n - cache files are named using a random hash instead of the dataset fingerprint\n - use :func:`datasets.Dataset.save_to_disk` to save a transformed dataset or it will be deleted when session closes\n - caching doesn't affect :func:`datasets.load_dataset`. If you want to regenerate a dataset from scratch you should use\n the ``download_mode`` parameter in :func:`datasets.load_dataset`.\n \"\"\"\n global _CACHING_ENABLED\n return bool(_CACHING_ENABLED)\n\n\ndef get_temporary_cache_files_directory() -> str:\n \"\"\"Return a directory that is deleted when session closes.\"\"\"\n global _TEMP_DIR_FOR_TEMP_CACHE_FILES\n if _TEMP_DIR_FOR_TEMP_CACHE_FILES is None:\n\n # Avoids a PermissionError on Windows caused by the datasets referencing\n # the files from the cache directory on clean-up\n def cleanup_func():\n for dset in get_datasets_with_cache_file_in_temp_dir():\n dset.__del__()\n\n _TEMP_DIR_FOR_TEMP_CACHE_FILES = _TempDirWithCustomCleanup(cleanup_func=cleanup_func)\n return _TEMP_DIR_FOR_TEMP_CACHE_FILES.name\n\n\n#################\n# Hashing\n#################\n\n\ndef hashregister(*types):\n def proxy(func):\n for t in types:\n Hasher.dispatch[t] = func\n return func\n\n return proxy\n\n\nclass Hasher:\n \"\"\"Hasher that accepts python objets as inputs.\"\"\"\n\n dispatch: Dict = {}\n\n def __init__(self):\n self.m = xxhash.xxh64()\n\n @classmethod\n def hash_bytes(cls, value: Union[bytes, List[bytes]]) -> str:\n value = [value] if isinstance(value, bytes) else value\n m = xxhash.xxh64()\n for x in value:\n m.update(x)\n return m.hexdigest()\n\n @classmethod\n def hash_default(cls, value: Any) -> str:\n return cls.hash_bytes(dumps(value))\n\n @classmethod\n def hash(cls, value: Any) -> str:\n if type(value) in cls.dispatch:\n return cls.dispatch[type(value)](cls, value)\n else:\n return cls.hash_default(value)\n\n def update(self, value: Any) -> None:\n header_for_update = f\"=={type(value)}==\"\n value_for_update = self.hash(value)\n self.m.update(header_for_update.encode(\"utf8\"))\n self.m.update(value_for_update.encode(\"utf-8\"))\n\n def hexdigest(self) -> str:\n return self.m.hexdigest()\n\n\n# Register a new hasher can be useful for two possible reasons:\n# 1 - optimize the hashing of large amount of data (e.g. pa.Table)\n# 2 - take advantage of a custom serialization method (e.g. DatasetInfo)\n\n\n@hashregister(pa.Table, Table, InMemoryTable, MemoryMappedTable, ConcatenationTable)\ndef _hash_pa_table(hasher, value):\n def _hash_pa_array(value):\n if isinstance(value, pa.ChunkedArray):\n return hasher.hash_bytes(c.to_string().encode(\"utf-8\") for c in value.chunks)\n else:\n return hasher.hash_bytes(value.to_string().encode(\"utf-8\"))\n\n value = \"-\".join(col + \"-\" + _hash_pa_array(value[col]) for col in sorted(value.column_names))\n return hasher.hash_bytes(value.encode(\"utf-8\"))\n\n\n@hashregister(DatasetInfo)\ndef _hash_dataset_info(hasher, value):\n return hasher.hash_bytes(json.dumps(asdict(value), sort_keys=True).encode(\"utf-8\"))\n\n\n#################\n# Fingerprinting\n#################\n\n# we show a warning only once when fingerprinting fails to avoid spam\nfingerprint_warnings: Dict[str, bool] = {}\n\n\ndef generate_fingerprint(dataset) -> str:\n state = dataset.__dict__\n hasher = Hasher()\n for key in sorted(state):\n if key == \"_fingerprint\":\n continue\n hasher.update(key)\n hasher.update(state[key])\n # hash data files last modification timestamps as well\n for cache_file in dataset.cache_files:\n hasher.update(os.path.getmtime(cache_file[\"filename\"]))\n return hasher.hexdigest()\n\n\ndef generate_random_fingerprint(nbits=64) -> str:\n return f\"{random.getrandbits(nbits):0{nbits//4}x}\"\n\n\ndef update_fingerprint(fingerprint, transform, transform_args):\n global fingerprint_warnings\n hasher = Hasher()\n hasher.update(fingerprint)\n try:\n hasher.update(transform)\n except: # noqa various errors might raise here from pickle or dill\n if _CACHING_ENABLED:\n if not fingerprint_warnings.get(\"update_fingerprint_transform_hash_failed\", False):\n logger.warning(\n f\"Transform {transform} couldn't be hashed properly, a random hash was used instead. \"\n \"Make sure your transforms and parameters are serializable with pickle or dill for the dataset fingerprinting and caching to work. \"\n \"If you reuse this transform, the caching mechanism will consider it to be different from the previous calls and recompute everything. \"\n \"This warning is only showed once. Subsequent hashing failures won't be showed.\"\n )\n fingerprint_warnings[\"update_fingerprint_transform_hash_failed\"] = True\n else:\n logger.info(f\"Transform {transform} couldn't be hashed properly, a random hash was used instead.\")\n else:\n logger.info(\n f\"Transform {transform} couldn't be hashed properly, a random hash was used instead. This doesn't affect caching since it's disabled.\"\n )\n\n return generate_random_fingerprint()\n for key in sorted(transform_args):\n hasher.update(key)\n try:\n hasher.update(transform_args[key])\n except: # noqa various errors might raise here from pickle or dill\n if _CACHING_ENABLED:\n if not fingerprint_warnings.get(\"update_fingerprint_transform_hash_failed\", False):\n logger.warning(\n f\"Parameter '{key}'={transform_args[key]} of the transform {transform} couldn't be hashed properly, a random hash was used instead. \"\n \"Make sure your transforms and parameters are serializable with pickle or dill for the dataset fingerprinting and caching to work. \"\n \"If you reuse this transform, the caching mechanism will consider it to be different from the previous calls and recompute everything. \"\n \"This warning is only showed once. Subsequent hashing failures won't be showed.\"\n )\n fingerprint_warnings[\"update_fingerprint_transform_hash_failed\"] = True\n else:\n logger.info(\n f\"Parameter '{key}'={transform_args[key]} of the transform {transform} couldn't be hashed properly, a random hash was used instead.\"\n )\n else:\n logger.info(\n f\"Parameter '{key}'={transform_args[key]} of the transform {transform} couldn't be hashed properly, a random hash was used instead. This doesn't affect caching since it's disabled.\"\n )\n return generate_random_fingerprint()\n return hasher.hexdigest()\n\n\ndef fingerprint_transform(\n inplace: bool,\n use_kwargs: Optional[List[str]] = None,\n ignore_kwargs: Optional[List[str]] = None,\n fingerprint_names: Optional[List[str]] = None,\n randomized_function: bool = False,\n version: Optional[str] = None,\n):\n \"\"\"\n Wrapper for dataset transforms to update the dataset fingerprint using ``update_fingerprint``\n\n Args:\n inplace (``bool``): If inplace is True, the fingerprint of the dataset is updated inplace.\n Otherwise, a parameter \"new_fingerprint\" is passed to the wrapped method that should take care of\n setting the fingerprint of the returned Dataset.\n use_kwargs (Optional ``List[str]``): optional white list of argument names to take into account\n to update the fingerprint to the wrapped method that should take care of\n setting the fingerprint of the returned Dataset. By default all the arguments are used.\n ignore_kwargs (Optional ``List[str]``): optional black list of argument names to take into account\n to update the fingerprint. Note that ignore_kwargs prevails on use_kwargs.\n fingerprint_names (Optional ``List[str]``, defaults to [\"new_fingerprint\"]):\n If the dataset transforms is not inplace and returns a DatasetDict, then it can require\n several fingerprints (one per dataset in the DatasetDict). By specifying fingerprint_names,\n one fingerprint named after each element of fingerprint_names is going to be passed.\n randomized_function (``bool``, defaults to False): If the dataset transform is random and has\n optional parameters \"seed\" and \"generator\", then you can set randomized_function to True.\n This way, even if users set \"seed\" and \"generator\" to None, then the fingerprint is\n going to be randomly generated depending on numpy's current state. In this case, the\n generator is set to np.random.default_rng(np.random.get_state()[1][0]).\n version (Optional ``str``): version of the transform. The version is taken into account when\n computing the fingerprint. If a datase transform changes (or at least if the output data\n that are cached changes), then one should increase the version. If the version stays the\n same, then old cached data could be reused that are not compatible with the new transform.\n It should be in the format \"MAJOR.MINOR.PATCH\".\n \"\"\"\n\n assert use_kwargs is None or isinstance(use_kwargs, list), \"use_kwargs is supposed to be a list, not {}\".format(\n type(use_kwargs)\n )\n assert ignore_kwargs is None or isinstance(\n ignore_kwargs, list\n ), \"ignore_kwargs is supposed to be a list, not {}\".format(type(use_kwargs))\n assert not inplace or not fingerprint_names, \"fingerprint_names are only used when inplace is False\"\n fingerprint_names = fingerprint_names if fingerprint_names is not None else [\"new_fingerprint\"]\n\n def _fingerprint(func):\n\n assert inplace or all( # check that not in-place functions require fingerprint parameters\n name in func.__code__.co_varnames for name in fingerprint_names\n ), \"function {} is missing parameters {} in signature\".format(func, fingerprint_names)\n if randomized_function: # randomized function have seed and generator parameters\n assert \"seed\" in func.__code__.co_varnames, \"'seed' must be in {}'s signature\".format(func)\n assert \"generator\" in func.__code__.co_varnames, \"'generator' must be in {}'s signature\".format(func)\n # this has to be outside the wrapper or since __qualname__ changes in multiprocessing\n transform = f\"{func.__module__}.{func.__qualname__}\"\n if version is not None:\n transform += f\"@{version}\"\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n kwargs_for_fingerprint = kwargs.copy()\n if args:\n params = [p.name for p in inspect.signature(func).parameters.values() if p != p.VAR_KEYWORD]\n self: \"Dataset\" = args[0]\n args = args[1:]\n params = params[1:]\n kwargs_for_fingerprint.update(zip(params, args))\n else:\n self: \"Dataset\" = kwargs.pop(\"self\")\n\n # keep the right kwargs to be hashed to generate the fingerprint\n\n if use_kwargs:\n kwargs_for_fingerprint = {k: v for k, v in kwargs_for_fingerprint.items() if k in use_kwargs}\n if ignore_kwargs:\n kwargs_for_fingerprint = {k: v for k, v in kwargs_for_fingerprint.items() if k not in ignore_kwargs}\n if randomized_function: # randomized functions have `seed` and `generator` parameters\n if kwargs_for_fingerprint.get(\"seed\") is None and kwargs_for_fingerprint.get(\"generator\") is None:\n kwargs_for_fingerprint[\"generator\"] = np.random.default_rng(np.random.get_state()[1][0])\n\n # remove kwargs that are the default values\n\n default_values = {\n p.name: p.default for p in inspect.signature(func).parameters.values() if p.default != inspect._empty\n }\n for default_varname, default_value in default_values.items():\n if (\n default_varname in kwargs_for_fingerprint\n and kwargs_for_fingerprint[default_varname] == default_value\n ):\n kwargs_for_fingerprint.pop(default_varname)\n\n # compute new_fingerprint and add it to the args of not in-place transforms\n if inplace:\n new_fingerprint = update_fingerprint(self._fingerprint, transform, kwargs_for_fingerprint)\n else:\n for fingerprint_name in fingerprint_names: # transforms like `train_test_split` have several hashes\n if kwargs.get(fingerprint_name) is None:\n kwargs_for_fingerprint[\"fingerprint_name\"] = fingerprint_name\n kwargs[fingerprint_name] = update_fingerprint(\n self._fingerprint, transform, kwargs_for_fingerprint\n )\n\n # Call actual function\n\n out = func(self, *args, **kwargs)\n\n # Update fingerprint of in-place transforms + update in-place history of transforms\n\n if inplace: # update after calling func so that the fingerprint doesn't change if the function fails\n self._fingerprint = new_fingerprint\n\n return out\n\n wrapper._decorator_name_ = \"fingerprint\"\n return wrapper\n\n return _fingerprint\n"
]
| [
[
"numpy.random.get_state"
]
]
|
pandok/openpilot | [
"d67ee20fb7ca14d6a4462a597696cf2f2bf47ecc"
]
| [
"selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py"
]
| [
"#!/usr/bin/env python3\nimport os\nimport numpy as np\n\nfrom common.realtime import sec_since_boot\nfrom common.numpy_fast import clip, interp\nfrom selfdrive.swaglog import cloudlog\nfrom selfdrive.modeld.constants import index_function\nfrom selfdrive.controls.lib.radar_helpers import _LEAD_ACCEL_TAU\nfrom common.conversions import Conversions as CV\n\nif __name__ == '__main__': # generating code\n from pyextra.acados_template import AcadosModel, AcadosOcp, AcadosOcpSolver\nelse:\n from selfdrive.controls.lib.longitudinal_mpc_lib.c_generated_code.acados_ocp_solver_pyx import AcadosOcpSolverCython # pylint: disable=no-name-in-module, import-error\n\nfrom casadi import SX, vertcat\n\nfrom common.params import Params\nfrom decimal import Decimal\n\nMODEL_NAME = 'long'\nLONG_MPC_DIR = os.path.dirname(os.path.abspath(__file__))\nEXPORT_DIR = os.path.join(LONG_MPC_DIR, \"c_generated_code\")\nJSON_FILE = os.path.join(LONG_MPC_DIR, \"acados_ocp_long.json\")\n\nSOURCES = ['lead0', 'lead1', 'cruise', 'stop']\n\nX_DIM = 3\nU_DIM = 1\nPARAM_DIM = 5\nCOST_E_DIM = 5\nCOST_DIM = COST_E_DIM + 1\nCONSTR_DIM = 4\n\nX_EGO_OBSTACLE_COST = 3.\nX_EGO_COST = 0.\nV_EGO_COST = 0.\nA_EGO_COST = 0.\nJ_EGO_COST = 5.0\nA_CHANGE_COST = 100. # 낮을수록 선행차에 민강하게 반응. def:0.5\nDANGER_ZONE_COST = 100.\nCRASH_DISTANCE = .5\nLIMIT_COST = 1e6\nACADOS_SOLVER_TYPE = 'SQP_RTI'\n\n\n# Fewer timestamps don't hurt performance and lead to\n# much better convergence of the MPC with low iterations\nN = 12\nMAX_T = 10.0\nT_IDXS_LST = [index_function(idx, max_val=MAX_T, max_idx=N) for idx in range(N+1)]\n\nT_IDXS = np.array(T_IDXS_LST)\nT_DIFFS = np.diff(T_IDXS, prepend=[0.])\nMIN_ACCEL = -4.0\nT_FOLLOW = 1.45\nCOMFORT_BRAKE = 2.5\nSTOP_DISTANCE = 6.0\n\ndef get_stopped_equivalence_factor(v_lead):\n return (v_lead**2) / (2 * COMFORT_BRAKE)\n\ndef get_safe_obstacle_distance(v_ego, t_react=T_FOLLOW):\n return (v_ego**2) / (2 * COMFORT_BRAKE) + t_react * v_ego + STOP_DISTANCE\n\ndef desired_follow_distance(v_ego, v_lead, t_react=T_FOLLOW):\n return get_safe_obstacle_distance(v_ego, t_react) - get_stopped_equivalence_factor(v_lead)\n\n\ndef gen_long_model():\n model = AcadosModel()\n model.name = MODEL_NAME\n\n # set up states & controls\n x_ego = SX.sym('x_ego')\n v_ego = SX.sym('v_ego')\n a_ego = SX.sym('a_ego')\n model.x = vertcat(x_ego, v_ego, a_ego)\n\n # controls\n j_ego = SX.sym('j_ego')\n model.u = vertcat(j_ego)\n\n # xdot\n x_ego_dot = SX.sym('x_ego_dot')\n v_ego_dot = SX.sym('v_ego_dot')\n a_ego_dot = SX.sym('a_ego_dot')\n model.xdot = vertcat(x_ego_dot, v_ego_dot, a_ego_dot)\n\n # live parameters\n desired_TR = SX.sym('desired_TR')\n a_min = SX.sym('a_min')\n a_max = SX.sym('a_max')\n x_obstacle = SX.sym('x_obstacle')\n prev_a = SX.sym('prev_a')\n model.p = vertcat(a_min, a_max, x_obstacle, prev_a, desired_TR)\n\n # dynamics model\n f_expl = vertcat(v_ego, a_ego, j_ego)\n model.f_impl_expr = model.xdot - f_expl\n model.f_expl_expr = f_expl\n return model\n\n\ndef gen_long_ocp():\n ocp = AcadosOcp()\n ocp.model = gen_long_model()\n\n Tf = T_IDXS[-1]\n\n # set dimensions\n ocp.dims.N = N\n\n # set cost module\n ocp.cost.cost_type = 'NONLINEAR_LS'\n ocp.cost.cost_type_e = 'NONLINEAR_LS'\n\n QR = np.zeros((COST_DIM, COST_DIM))\n Q = np.zeros((COST_E_DIM, COST_E_DIM))\n\n ocp.cost.W = QR\n ocp.cost.W_e = Q\n\n x_ego, v_ego, a_ego = ocp.model.x[0], ocp.model.x[1], ocp.model.x[2]\n j_ego = ocp.model.u[0]\n\n a_min, a_max = ocp.model.p[0], ocp.model.p[1]\n x_obstacle = ocp.model.p[2]\n prev_a = ocp.model.p[3]\n desired_TR = ocp.model.p[4]\n\n ocp.cost.yref = np.zeros((COST_DIM, ))\n ocp.cost.yref_e = np.zeros((COST_E_DIM, ))\n\n desired_dist_comfort = get_safe_obstacle_distance(v_ego, desired_TR)\n\n # The main cost in normal operation is how close you are to the \"desired\" distance\n # from an obstacle at every timestep. This obstacle can be a lead car\n # or other object. In e2e mode we can use x_position targets as a cost\n # instead.\n costs = [((x_obstacle - x_ego) - (desired_dist_comfort)) / (v_ego + 10.),\n x_ego,\n v_ego,\n a_ego,\n a_ego - prev_a,\n j_ego]\n ocp.model.cost_y_expr = vertcat(*costs)\n ocp.model.cost_y_expr_e = vertcat(*costs[:-1])\n\n # Constraints on speed, acceleration and desired distance to\n # the obstacle, which is treated as a slack constraint so it\n # behaves like an asymmetrical cost.\n constraints = vertcat(v_ego,\n (a_ego - a_min),\n (a_max - a_ego),\n ((x_obstacle - x_ego) - (3/4) * (desired_dist_comfort)) / (v_ego + 10.))\n ocp.model.con_h_expr = constraints\n\n x0 = np.zeros(X_DIM)\n ocp.constraints.x0 = x0\n ocp.parameter_values = np.array([-1.2, 1.2, 0.0, 0.0, T_FOLLOW])\n\n # We put all constraint cost weights to 0 and only set them at runtime\n cost_weights = np.zeros(CONSTR_DIM)\n ocp.cost.zl = cost_weights\n ocp.cost.Zl = cost_weights\n ocp.cost.Zu = cost_weights\n ocp.cost.zu = cost_weights\n\n ocp.constraints.lh = np.zeros(CONSTR_DIM)\n ocp.constraints.uh = 1e4*np.ones(CONSTR_DIM)\n ocp.constraints.idxsh = np.arange(CONSTR_DIM)\n\n # The HPIPM solver can give decent solutions even when it is stopped early\n # Which is critical for our purpose where compute time is strictly bounded\n # We use HPIPM in the SPEED_ABS mode, which ensures fastest runtime. This\n # does not cause issues since the problem is well bounded.\n ocp.solver_options.qp_solver = 'PARTIAL_CONDENSING_HPIPM'\n ocp.solver_options.hessian_approx = 'GAUSS_NEWTON'\n ocp.solver_options.integrator_type = 'ERK'\n ocp.solver_options.nlp_solver_type = ACADOS_SOLVER_TYPE\n ocp.solver_options.qp_solver_cond_N = 1\n\n # More iterations take too much time and less lead to inaccurate convergence in\n # some situations. Ideally we would run just 1 iteration to ensure fixed runtime.\n ocp.solver_options.qp_solver_iter_max = 10\n ocp.solver_options.qp_tol = 1e-3\n\n # set prediction horizon\n ocp.solver_options.tf = Tf\n ocp.solver_options.shooting_nodes = T_IDXS\n\n ocp.code_export_directory = EXPORT_DIR\n return ocp\n\n\nclass LongitudinalMpc:\n def __init__(self, e2e=False, desired_TR=T_FOLLOW):\n self.e2e = e2e\n self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N)\n self.desired_TR = desired_TR\n self.v_ego = 0.\n self.reset()\n self.source = SOURCES[2]\n\n self.TR = 1.45\n self.dynamic_TR = 0\n self.cruise_gap1 = float(Decimal(Params().get(\"CruiseGap1\", encoding=\"utf8\")) * Decimal('0.1'))\n self.cruise_gap2 = float(Decimal(Params().get(\"CruiseGap2\", encoding=\"utf8\")) * Decimal('0.1'))\n self.cruise_gap3 = float(Decimal(Params().get(\"CruiseGap3\", encoding=\"utf8\")) * Decimal('0.1'))\n self.cruise_gap4 = float(Decimal(Params().get(\"CruiseGap4\", encoding=\"utf8\")) * Decimal('0.1'))\n\n self.dynamic_tr_spd = list(map(float, Params().get(\"DynamicTRSpd\", encoding=\"utf8\").split(',')))\n self.dynamic_tr_set = list(map(float, Params().get(\"DynamicTRSet\", encoding=\"utf8\").split(',')))\n self.dynamic_TR_mode = int(Params().get(\"DynamicTRGap\", encoding=\"utf8\"))\n self.custom_tr_enabled = Params().get_bool(\"CustomTREnabled\")\n\n self.ms_to_spd = CV.MS_TO_KPH if Params().get_bool(\"IsMetric\") else CV.MS_TO_MPH\n\n self.stop_line = Params().get_bool(\"ShowStopLine\")\n\n self.lo_timer = 0 \n\n self.lead_0_obstacle = np.zeros(13, dtype=np.float64)\n self.lead_1_obstacle = np.zeros(13, dtype=np.float64)\n self.e2e_x = np.zeros(13, dtype=np.float64)\n self.cruise_target = np.zeros(13, dtype=np.float64)\n self.stopline = np.zeros(13, dtype=np.float64)\n self.stop_prob = 0.0\n\n def reset(self):\n # self.solver = AcadosOcpSolverCython(MODEL_NAME, ACADOS_SOLVER_TYPE, N)\n self.solver.reset()\n # self.solver.options_set('print_level', 2)\n self.v_solution = np.zeros(N+1)\n self.a_solution = np.zeros(N+1)\n self.prev_a = np.array(self.a_solution)\n self.j_solution = np.zeros(N)\n self.yref = np.zeros((N+1, COST_DIM))\n for i in range(N):\n self.solver.cost_set(i, \"yref\", self.yref[i])\n self.solver.cost_set(N, \"yref\", self.yref[N][:COST_E_DIM])\n self.x_sol = np.zeros((N+1, X_DIM))\n self.u_sol = np.zeros((N,1))\n self.params = np.zeros((N+1, PARAM_DIM))\n for i in range(N+1):\n self.solver.set(i, 'x', np.zeros(X_DIM))\n self.last_cloudlog_t = 0\n self.status = False\n self.crash_cnt = 0.0\n self.solution_status = 0\n # timers\n self.solve_time = 0.0\n self.time_qp_solution = 0.0\n self.time_linearization = 0.0\n self.time_integrator = 0.0\n self.x0 = np.zeros(X_DIM)\n self.set_weights()\n\n def set_weights(self, prev_accel_constraint=True):\n if self.e2e:\n self.set_weights_for_xva_policy()\n self.params[:,0] = -10.\n self.params[:,1] = 10.\n self.params[:,2] = 1e5\n else:\n self.set_weights_for_lead_policy(prev_accel_constraint)\n\n def set_weights_for_lead_policy(self, prev_accel_constraint=True):\n a_change_cost = A_CHANGE_COST if prev_accel_constraint else 0\n W = np.asfortranarray(np.diag([X_EGO_OBSTACLE_COST, X_EGO_COST, V_EGO_COST, A_EGO_COST, a_change_cost, J_EGO_COST]))\n for i in range(N):\n # reduce the cost on (a-a_prev) later in the horizon.\n W[4,4] = a_change_cost * np.interp(T_IDXS[i], [0.0, 1.0, 2.0], [1.0, 1.0, 0.0])\n self.solver.cost_set(i, 'W', W)\n # Setting the slice without the copy make the array not contiguous,\n # causing issues with the C interface.\n self.solver.cost_set(N, 'W', np.copy(W[:COST_E_DIM, :COST_E_DIM]))\n\n # Set L2 slack cost on lower bound constraints\n Zl = np.array([LIMIT_COST, LIMIT_COST, LIMIT_COST, DANGER_ZONE_COST])\n for i in range(N):\n self.solver.cost_set(i, 'Zl', Zl)\n\n def set_weights_for_xva_policy(self):\n W = np.asfortranarray(np.diag([0., 0.2, 0.25, 1., 0.0, .1]))\n for i in range(N):\n self.solver.cost_set(i, 'W', W)\n self.solver.cost_set(N, 'W', np.copy(W[:COST_E_DIM, :COST_E_DIM]))\n\n # Set L2 slack cost on lower bound constraints\n Zl = np.array([LIMIT_COST, LIMIT_COST, LIMIT_COST, 0.0])\n for i in range(N):\n self.solver.cost_set(i, 'Zl', Zl)\n\n def set_cur_state(self, v, a):\n v_prev = self.x0[1]\n self.x0[1] = v\n self.x0[2] = a\n if abs(v_prev - v) > 2.: # probably only helps if v < v_prev\n for i in range(0, N+1):\n self.solver.set(i, 'x', self.x0)\n\n @staticmethod\n def extrapolate_lead(x_lead, v_lead, a_lead, a_lead_tau):\n a_lead_traj = a_lead * np.exp(-a_lead_tau * (T_IDXS**2)/2.)\n v_lead_traj = np.clip(v_lead + np.cumsum(T_DIFFS * a_lead_traj), 0.0, 1e8)\n x_lead_traj = x_lead + np.cumsum(T_DIFFS * v_lead_traj)\n lead_xv = np.column_stack((x_lead_traj, v_lead_traj))\n return lead_xv\n\n def process_lead(self, lead):\n v_ego = self.x0[1]\n if lead is not None and lead.status:\n x_lead = lead.dRel if lead.radar else max(lead.dRel - 1., 0.)\n v_lead = lead.vLead\n a_lead = lead.aLeadK\n a_lead_tau = lead.aLeadTau\n else:\n # Fake a fast lead car, so mpc can keep running in the same mode\n x_lead = 50.0\n v_lead = v_ego + 10.0\n a_lead = 0.0\n a_lead_tau = _LEAD_ACCEL_TAU\n\n # MPC will not converge if immediate crash is expected\n # Clip lead distance to what is still possible to brake for\n min_x_lead = ((v_ego + v_lead)/2) * (v_ego - v_lead) / (-MIN_ACCEL * 2)\n x_lead = clip(x_lead, min_x_lead, 1e8)\n v_lead = clip(v_lead, 0.0, 1e8)\n a_lead = clip(a_lead, -10., 5.)\n lead_xv = self.extrapolate_lead(x_lead, v_lead, a_lead, a_lead_tau)\n return lead_xv\n\n def set_accel_limits(self, min_a, max_a):\n self.cruise_min_a = min_a\n self.cruise_max_a = max_a\n\n def set_desired_TR(self, desired_TR):\n self.desired_TR = desired_TR\n self.set_weights()\n\n def update(self, carstate, radarstate, model, v_cruise, x, v, a):\n self.v_ego = carstate.vEgo\n v_ego = self.x0[1]\n stopping = model.stopLine.prob > 0.5 if self.stop_line else False\n\n # opkr\n self.lo_timer += 1\n if self.lo_timer > 200:\n self.lo_timer = 0\n self.e2e = Params().get_bool(\"E2ELong\")\n self.dynamic_TR_mode = int(Params().get(\"DynamicTRGap\", encoding=\"utf8\"))\n self.custom_tr_enabled = Params().get_bool(\"CustomTREnabled\")\n\n xforward = ((v[1:] + v[:-1]) / 2) * (T_IDXS[1:] - T_IDXS[:-1])\n x = np.cumsum(np.insert(xforward, 0, x[0]))\n self.yref[:,1] = x\n self.yref[:,2] = v\n self.yref[:,3] = a\n self.status = radarstate.leadOne.status or radarstate.leadTwo.status\n\n lead_xv_0 = self.process_lead(radarstate.leadOne)\n lead_xv_1 = self.process_lead(radarstate.leadTwo)\n\n if self.custom_tr_enabled:\n cruise_gap = int(clip(carstate.cruiseGapSet, 1., 4.))\n self.dynamic_TR = interp(self.v_ego*self.ms_to_spd, self.dynamic_tr_spd, self.dynamic_tr_set)\n if self.dynamic_TR_mode == 1:\n self.TR = interp(float(cruise_gap), [1., 2., 3., 4.], [self.dynamic_TR, self.cruise_gap2, self.cruise_gap3, self.cruise_gap4])\n elif self.dynamic_TR_mode == 2:\n self.TR = interp(float(cruise_gap), [1., 2., 3., 4.], [self.cruise_gap1, self.dynamic_TR, self.cruise_gap3, self.cruise_gap4])\n elif self.dynamic_TR_mode == 3:\n self.TR = interp(float(cruise_gap), [1., 2., 3., 4.], [self.cruise_gap1, self.cruise_gap2, self.dynamic_TR, self.cruise_gap4])\n elif self.dynamic_TR_mode == 4:\n self.TR = interp(float(cruise_gap), [1., 2., 3., 4.], [self.cruise_gap1, self.cruise_gap2, self.cruise_gap3, self.dynamic_TR])\n else:\n self.TR = interp(float(cruise_gap), [1., 2., 3., 4.], [self.cruise_gap1, self.cruise_gap2, self.cruise_gap3, self.cruise_gap4])\n else:\n self.TR = 1.45\n\n self.set_desired_TR(self.TR)\n\n # set accel limits in params\n self.params[:,0] = interp(float(self.status), [0.0, 1.0], [self.cruise_min_a, MIN_ACCEL])\n self.params[:,1] = self.cruise_max_a\n\n # To estimate a safe distance from a moving lead, we calculate how much stopping\n # distance that lead needs as a minimum. We can add that to the current distance\n # and then treat that as a stopped car/obstacle at this new distance.\n lead_0_obstacle = lead_xv_0[:,0] + get_stopped_equivalence_factor(lead_xv_0[:,1])\n lead_1_obstacle = lead_xv_1[:,0] + get_stopped_equivalence_factor(lead_xv_1[:,1])\n\n v_lower = v_ego + (T_IDXS * self.cruise_min_a * 1.05)\n v_upper = v_ego + (T_IDXS * self.cruise_max_a * 1.05)\n v_cruise_clipped = np.clip(v_cruise * np.ones(N+1),\n v_lower,\n v_upper)\n cruise_obstacle = np.cumsum(T_DIFFS * v_cruise_clipped) + get_safe_obstacle_distance(v_cruise_clipped, self.desired_TR)\n\n stopline = (model.stopLine.x + 6.0) * np.ones(N+1) if stopping else 400 * np.ones(N+1)\n x = (x[N] + 6.0) * np.ones(N+1)\n\n if self.status:\n x_obstacles = np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle])\n elif x[N] > 30 and stopline[N] < 30 and self.v_ego < 6.0:\n x_obstacles = np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle*2, x])\n elif x[N] < 100 and stopline[N] < 100:\n x_obstacles = np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle*2, (stopline+x)/2])\n else:\n x_obstacles = np.column_stack([lead_0_obstacle, lead_1_obstacle, cruise_obstacle])\n\n self.source = SOURCES[np.argmin(x_obstacles[N])]\n self.params[:,2] = np.min(x_obstacles, axis=1)\n self.params[:,3] = np.copy(self.prev_a)\n self.params[:,4] = self.desired_TR # shane\n\n self.e2e_x = x[:]\n self.lead_0_obstacle = lead_0_obstacle[:]\n self.lead_1_obstacle = lead_1_obstacle[:]\n self.cruise_target = cruise_obstacle[:]\n self.stopline = stopline[:]\n self.stop_prob = model.stopLine.prob\n\n if self.e2e:\n self.yref[:,1] = np.min(x_obstacles, axis=1)\n for i in range(N):\n self.solver.set(i, \"yref\", self.yref[i])\n self.solver.set(N, \"yref\", self.yref[N][:COST_E_DIM])\n\n self.run()\n if (np.any(lead_xv_0[:,0] - self.x_sol[:,0] < CRASH_DISTANCE) and\n radarstate.leadOne.modelProb > 0.9):\n self.crash_cnt += 1\n else:\n self.crash_cnt = 0\n\n def update_with_xva(self, x, v, a):\n # v, and a are in local frame, but x is wrt the x[0] position\n # In >90degree turns, x goes to 0 (and may even be -ve)\n # So, we use integral(v) + x[0] to obtain the forward-distance\n xforward = ((v[1:] + v[:-1]) / 2) * (T_IDXS[1:] - T_IDXS[:-1])\n x = np.cumsum(np.insert(xforward, 0, x[0]))\n self.yref[:,1] = x\n self.yref[:,2] = v\n self.yref[:,3] = a\n for i in range(N):\n self.solver.cost_set(i, \"yref\", self.yref[i])\n self.solver.cost_set(N, \"yref\", self.yref[N][:COST_E_DIM])\n self.params[:,3] = np.copy(self.prev_a)\n self.run()\n\n def run(self):\n # t0 = sec_since_boot()\n # reset = 0\n for i in range(N+1):\n self.solver.set(i, 'p', self.params[i])\n self.solver.constraints_set(0, \"lbx\", self.x0)\n self.solver.constraints_set(0, \"ubx\", self.x0)\n\n self.solution_status = self.solver.solve()\n self.solve_time = float(self.solver.get_stats('time_tot')[0])\n self.time_qp_solution = float(self.solver.get_stats('time_qp')[0])\n self.time_linearization = float(self.solver.get_stats('time_lin')[0])\n self.time_integrator = float(self.solver.get_stats('time_sim')[0])\n\n # qp_iter = self.solver.get_stats('statistics')[-1][-1] # SQP_RTI specific\n # print(f\"long_mpc timings: tot {self.solve_time:.2e}, qp {self.time_qp_solution:.2e}, lin {self.time_linearization:.2e}, integrator {self.time_integrator:.2e}, qp_iter {qp_iter}\")\n # res = self.solver.get_residuals()\n # print(f\"long_mpc residuals: {res[0]:.2e}, {res[1]:.2e}, {res[2]:.2e}, {res[3]:.2e}\")\n # self.solver.print_statistics()\n\n for i in range(N+1):\n self.x_sol[i] = self.solver.get(i, 'x')\n for i in range(N):\n self.u_sol[i] = self.solver.get(i, 'u')\n\n self.v_solution = self.x_sol[:,1]\n self.a_solution = self.x_sol[:,2]\n self.j_solution = self.u_sol[:,0]\n\n self.prev_a = np.interp(T_IDXS + 0.05, T_IDXS, self.a_solution)\n\n t = sec_since_boot()\n if self.solution_status != 0:\n if t > self.last_cloudlog_t + 5.0:\n self.last_cloudlog_t = t\n cloudlog.warning(f\"Long mpc reset, solution_status: {self.solution_status}\")\n self.reset()\n # reset = 1\n # print(f\"long_mpc timings: total internal {self.solve_time:.2e}, external: {(sec_since_boot() - t0):.2e} qp {self.time_qp_solution:.2e}, lin {self.time_linearization:.2e} qp_iter {qp_iter}, reset {reset}\")\n\n\nif __name__ == \"__main__\":\n ocp = gen_long_ocp()\n AcadosOcpSolver.generate(ocp, json_file=JSON_FILE)\n # AcadosOcpSolver.build(ocp.code_export_directory, with_cython=True)\n"
]
| [
[
"numpy.diag",
"numpy.min",
"numpy.arange",
"numpy.cumsum",
"numpy.ones",
"numpy.copy",
"numpy.diff",
"numpy.interp",
"numpy.insert",
"numpy.column_stack",
"numpy.exp",
"numpy.any",
"numpy.argmin",
"numpy.array",
"numpy.zeros"
]
]
|
twangnh/Distilling-Object-Detectors-FRCNN | [
"c6583f3a2844bfbb7664c0552be17eccac03bffb"
]
| [
"lib/model/faster_rcnn/vgg16.py"
]
| [
"# --------------------------------------------------------\n# Tensorflow Faster R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Xinlei Chen\n# --------------------------------------------------------\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport math\nimport torchvision.models as models\nfrom model.faster_rcnn.faster_rcnn import _fasterRCNN\nimport pdb\n\nclass vgg16(_fasterRCNN):\n def __init__(self, classes, pretrained=False, class_agnostic=False, sup=False):\n self.model_path = 'data/pretrained_model/vgg16_caffe.pth'\n self.dout_base_model = 512\n self.pretrained = pretrained\n self.class_agnostic = class_agnostic\n\n _fasterRCNN.__init__(self, classes, class_agnostic, sup)\n\n def _init_modules(self):\n vgg = models.vgg16()\n if self.pretrained:\n print(\"Loading pretrained weights from %s\" %(self.model_path))\n state_dict = torch.load(self.model_path)\n vgg.load_state_dict({k:v for k,v in state_dict.items() if k in vgg.state_dict()})\n\n vgg.classifier = nn.Sequential(*list(vgg.classifier._modules.values())[:-1])\n\n # not using the last maxpool layer\n self.RCNN_base = nn.Sequential(*list(vgg.features._modules.values())[:-1])\n\n # Fix the layers before conv3:\n for layer in range(10):\n for p in self.RCNN_base[layer].parameters(): p.requires_grad = False\n\n # self.RCNN_base = _RCNN_base(vgg.features, self.classes, self.dout_base_model)\n\n self.RCNN_top = vgg.classifier\n\n # not using the last maxpool layer\n self.RCNN_cls_score = nn.Linear(4096, self.n_classes)\n\n # self.stu_feature_adap = nn.Sequential(nn.Conv2d(512, 1024, kernel_size=3, padding=1),\n # nn.ReLU(),\n # nn.ConstantPad2d((0,1,0,1), 0.))\n #\n # self.stu_mask_pad = nn.ConstantPad2d((0, 1, 0, 1), 0.)\n\n\n if self.class_agnostic:\n self.RCNN_bbox_pred = nn.Linear(4096, 4)\n else:\n self.RCNN_bbox_pred = nn.Linear(4096, 4 * self.n_classes) \n\n def _head_to_tail(self, pool5):\n \n pool5_flat = pool5.view(pool5.size(0), -1)\n fc7 = self.RCNN_top(pool5_flat)\n\n return fc7\n\n"
]
| [
[
"torch.nn.Linear",
"torch.load"
]
]
|
davidhintelmann/PyQt5- | [
"bb896e7e11ab6f046d2385f7bef96c7f8516d93d"
]
| [
"src/main/python/main.py"
]
| [
"from fbs_runtime.application_context.PyQt5 import ApplicationContext\nfrom PyQt5.QtWidgets import QMainWindow\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nimport pandas as pd\n\nimport sys\n\n\"\"\"\nClass below is for displaying a pandas dataframe on the canvas of a PyQt5 app\n\"\"\"\nclass DataFrameModel(QtCore.QAbstractTableModel):\n DtypeRole = QtCore.Qt.UserRole + 1000\n ValueRole = QtCore.Qt.UserRole + 1001\n\n def __init__(self, df=pd.DataFrame(), parent=None):\n super(DataFrameModel, self).__init__(parent)\n self._dataframe = df\n\n def setDataFrame(self, dataframe):\n self.beginResetModel()\n self._dataframe = dataframe.copy()\n self.endResetModel()\n\n def dataFrame(self):\n return self._dataframe\n\n dataFrame = QtCore.pyqtProperty(pd.DataFrame, fget=dataFrame, fset=setDataFrame)\n\n @QtCore.pyqtSlot(int, QtCore.Qt.Orientation, result=str)\n def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = QtCore.Qt.DisplayRole):\n if role == QtCore.Qt.DisplayRole:\n if orientation == QtCore.Qt.Horizontal:\n return self._dataframe.columns[section]\n else:\n return str(self._dataframe.index[section])\n return QtCore.QVariant()\n\n def rowCount(self, parent=QtCore.QModelIndex()):\n if parent.isValid():\n return 0\n return len(self._dataframe.index)\n\n def columnCount(self, parent=QtCore.QModelIndex()):\n if parent.isValid():\n return 0\n return self._dataframe.columns.size\n\n def data(self, index, role=QtCore.Qt.DisplayRole):\n if not index.isValid() or not (0 <= index.row() < self.rowCount() \\\n and 0 <= index.column() < self.columnCount()):\n return QtCore.QVariant()\n row = self._dataframe.index[index.row()]\n col = self._dataframe.columns[index.column()]\n dt = self._dataframe[col].dtype\n\n val = self._dataframe.iloc[row][col]\n if role == QtCore.Qt.DisplayRole:\n return str(val)\n elif role == DataFrameModel.ValueRole:\n return val\n if role == DataFrameModel.DtypeRole:\n return dt\n return QtCore.QVariant()\n\n def roleNames(self):\n roles = {\n QtCore.Qt.DisplayRole: b'display',\n DataFrameModel.DtypeRole: b'dtype',\n DataFrameModel.ValueRole: b'value'\n }\n return roles\n\nclass Widget(QtWidgets.QWidget):\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent=None)\n vLayout = QtWidgets.QVBoxLayout(self)\n hLayout = QtWidgets.QHBoxLayout()\n self.pathLE = QtWidgets.QLineEdit(self)\n hLayout.addWidget(self.pathLE)\n self.loadBtn = QtWidgets.QPushButton(\"Select File\", self)\n hLayout.addWidget(self.loadBtn)\n vLayout.addLayout(hLayout)\n self.pandasTv = QtWidgets.QTableView(self)\n vLayout.addWidget(self.pandasTv)\n self.loadBtn.clicked.connect(self.loadFile)\n self.pandasTv.setSortingEnabled(True)\n\n def loadFile(self):\n fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, \"Open File\", \"\", \"CSV Files (*.csv)\");\n self.pathLE.setText(fileName)\n df = pd.read_csv(fileName)\n model = DataFrameModel(df)\n self.pandasTv.setModel(model)\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n w = Widget()\n w.show()\n sys.exit(app.exec_())\n"
]
| [
[
"pandas.read_csv",
"pandas.DataFrame"
]
]
|
imbillu/arche | [
"67a24b83e2f936f1f6f8d1c7bbd4aa147f128b66"
]
| [
"tests/conftest.py"
]
| [
"from copy import deepcopy\nfrom itertools import zip_longest\nfrom typing import Dict, Iterable, List, Optional\n\nfrom arche.readers.items import CollectionItems, JobItems\nfrom arche.rules.result import Level, Message, Result, Stat\nimport numpy as np\nimport pandas as pd\nimport pytest\n\n\nCLOUD_ITEMS = [\n {\"_key\": \"112358/13/21/0\", \"_type\": \"Type\", \"price\": 0, \"name\": \"Elizabeth\"},\n {\"_key\": \"112358/13/21/1\", \"_type\": \"Type\", \"name\": \"Margaret\"},\n {\"_key\": \"112358/13/21/2\", \"_type\": \"Type\", \"price\": 10, \"name\": \"Yulia\"},\n {\"_key\": \"112358/13/21/3\", \"_type\": \"Type\", \"price\": 11, \"name\": \"Vivien\"},\n]\n\nDEFAULT_SCHEMA = {\n \"$schema\": \"http://json-schema.org/draft-07/schema\",\n \"required\": [\"name\"],\n \"type\": \"object\",\n \"properties\": {\"price\": {\"type\": \"integer\"}, \"name\": {\"type\": \"string\"}},\n \"additionalProperties\": False,\n}\n\n\[email protected](scope=\"session\")\ndef get_cloud_items(request):\n return CLOUD_ITEMS\n\n\[email protected](scope=\"session\")\ndef get_raw_items(request):\n return np.array(CLOUD_ITEMS)\n\n\[email protected](scope=\"session\")\ndef get_schema():\n return DEFAULT_SCHEMA\n\n\[email protected](scope=\"function\")\ndef get_df():\n df = pd.DataFrame({\"first\": [0.25, 0.75], \"second\": [0.0, 1.0]})\n df.name = \"a df\"\n return df\n\n\nclass Job:\n def __init__(\n self,\n items: Optional[Iterable] = None,\n metadata: Optional[Dict] = None,\n stats: Optional[Dict] = None,\n key: str = \"112358/13/21\",\n ):\n self.items = Source(items, stats)\n self.key = key\n if metadata:\n self.metadata = metadata\n else:\n self.metadata = {}\n\n\nclass Collection:\n def __init__(self, count: Optional[int] = None):\n self._count = count\n\n def count(self) -> Optional[int]:\n return self._count\n\n\ndef _is_filtered(x, by):\n if by:\n return x.get(by[0][0]) == by[0][1][0]\n return True\n\n\nclass Source:\n def __init__(\n self, items: Optional[List[Dict]] = None, stats: Optional[Dict] = None\n ):\n self.items = items\n if stats:\n # add `_type` to not care about it in tests\n if stats.get(\"counts\"):\n stats[\"counts\"][\"_type\"] = 1\n else:\n stats[\"counts\"] = {\"_type\": 1}\n self._stats = stats\n else:\n if self.items:\n input_values = len(self.items)\n else:\n input_values = 0\n self._stats = {\"totals\": {\"input_values\": input_values}}\n\n def stats(self):\n return self._stats\n\n def iter(self, **kwargs):\n start = kwargs.get(\"start\", 0)\n count = kwargs.get(\"count\", None)\n counter = 0\n if start:\n start = int(start.split(\"/\")[-1])\n\n for item in self.items[start:]:\n if counter == count:\n return\n if _is_filtered(item, kwargs.get(\"filter\")):\n counter += 1\n yield item\n\n\nclass StoreSource:\n def __init__(self, items: List[Dict] = None):\n self.items = items\n\n def count(self):\n return len(self.items)\n\n def iter(self, **kwargs):\n start = kwargs.get(\"start\", self.items[0].get(\"_key\"))\n\n def start_idx():\n for i, item in enumerate(self.items):\n if item.get(\"_key\") == start:\n return i\n\n count = kwargs.get(\"count\", None)\n counter = 0\n for item in self.items[start_idx() :]:\n if counter == count:\n return\n if _is_filtered(item, kwargs.get(\"filter\")):\n counter += 1\n yield item\n\n\[email protected](scope=\"function\")\ndef get_source():\n return Source(items=CLOUD_ITEMS)\n\n\[email protected](scope=\"function\", params=[(CLOUD_ITEMS, None, None)])\ndef get_job(request):\n return Job(*request.param)\n\n\[email protected](scope=\"function\")\ndef get_collection():\n return Collection()\n\n\[email protected](scope=\"function\")\ndef get_jobs():\n return Job(), Job()\n\n\nclass ScrapinghubClient:\n def __init__(self, job: Optional[Job] = get_job):\n self._job = job\n\n def get_job(self):\n return self._job\n\n\[email protected](scope=\"function\")\ndef get_client():\n return ScrapinghubClient()\n\n\[email protected](scope=\"function\")\ndef get_job_items(mocker):\n mocker.patch(\n \"arche.readers.items.JobItems.job\", return_value=get_job, autospec=True\n )\n raw_data = deepcopy(CLOUD_ITEMS)\n mocker.patch(\n \"arche.readers.items.JobItems.fetch_data\",\n return_value=np.array(raw_data),\n autospec=True,\n )\n job_items = JobItems(key=\"112358/13/21\", count=len(raw_data))\n return job_items\n\n\[email protected](scope=\"function\")\ndef get_collection_items(mocker):\n mocker.patch(\n \"arche.tools.api.get_collection\", return_value=get_collection, autospec=True\n )\n mocker.patch(\n \"arche.readers.items.CollectionItems.fetch_data\",\n return_value=np.array(CLOUD_ITEMS),\n autospec=True,\n )\n\n collection_items = CollectionItems(\n key=\"112358/collections/s/pages\", count=len(CLOUD_ITEMS)\n )\n return collection_items\n\n\ndef create_result(\n rule_name: str,\n messages: Dict[Level, List[Message]],\n stats: Optional[List[Stat]] = None,\n items_count: Optional[int] = None,\n) -> Result:\n result = Result(rule_name)\n for level, messages in messages.items():\n for message in messages:\n result.add_message(level, *message)\n\n if stats:\n result.stats = stats\n if items_count:\n result.items_count = items_count\n return result\n\n\ndef pytest_assertrepr_compare(op, left, right):\n if isinstance(left, Result) and isinstance(right, Result) and op == \"==\":\n assert_msgs = [\"Results are equal\"]\n for (left_n, left_v), (_, right_v) in zip_longest(\n left.__dict__.items(), right.__dict__.items()\n ):\n if left_n == \"_stats\":\n for left_stat, right_stat in zip_longest(left_v, right_v):\n try:\n if isinstance(left_stat, pd.DataFrame):\n pd.testing.assert_frame_equal(left_stat, right_stat)\n else:\n pd.testing.assert_series_equal(left_stat, right_stat)\n except AssertionError as e:\n assert_msgs.extend([f\"{left_stat}\", \"!=\", f\"{right_stat}\"])\n assert_msgs.extend(str(e).split(\"\\n\"))\n elif left_v != right_v:\n assert_msgs.extend([f\"{left_v}\", \"!=\", f\"{right_v}\"])\n return assert_msgs\n\n\ndef create_named_df(data: Dict, index: List[str], name: str) -> pd.DataFrame:\n df = pd.DataFrame(data, index=index)\n df.name = name\n return df\n"
]
| [
[
"numpy.array",
"pandas.testing.assert_frame_equal",
"pandas.testing.assert_series_equal",
"pandas.DataFrame"
]
]
|
HuangLED/euler | [
"a56b5fe3fe56123af062317ca0b4160ce3b3ace9"
]
| [
"tf_euler/python/euler_ops/mp_ops_test.py"
]
| [
"# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Message Passing ops test\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport tensorflow as tf\n\nfrom tf_euler.python.euler_ops import mp_ops\n\n\nclass ScatterTest(tf.test.TestCase):\n\n def testScatterAdd(self):\n x = tf.constant([[1., 2.], [3., 4.], [5., 6.]])\n idx = tf.constant([1, 0, 1])\n out = mp_ops.scatter_add(x, idx, size=2)\n\n with self.test_session():\n self.assertAllEqual([[3., 4.], [6., 8.]], out.eval())\n\n def testScatterAddGrad(self):\n x = tf.constant([[1., 2.], [3., 4.], [5., 6.]])\n idx = tf.constant([1, 0, 1])\n out = mp_ops.scatter_add(x, idx, size=2)\n with self.test_session():\n diff = tf.test.compute_gradient_error(x, [3, 2], out, [2, 2])\n self.assertLess(diff, 1e-4)\n\n def testScatterMean(self):\n x = tf.constant([[1., 2.], [3., 4.], [5., 6.]])\n idx = tf.constant([1, 0, 1])\n out = mp_ops.scatter_mean(x, idx, size=2)\n exp = tf.constant([[3., 4.], [3., 4.]])\n diff = tf.reduce_sum(tf.abs(out - exp))\n with self.test_session():\n # self.assertAllEqual([[3., 4.], [3., 4.]], out.eval())\n self.assertLess(diff.eval(), 1e-6)\n\n def testScatterMeanGrad(self):\n x = tf.constant([[1., 2.], [3., 4.], [5., 6.]])\n idx = tf.constant([1, 0, 1])\n out = mp_ops.scatter_mean(x, idx, size=2)\n with self.test_session():\n diff = tf.test.compute_gradient_error(x, [3, 2], out, [2, 2])\n self.assertLess(diff, 1e-4)\n\n def testScatterMax(self):\n x = tf.constant([[1., 6.], [3., 4.], [5., 2.]])\n idx = tf.constant([1, 0, 1])\n out = mp_ops.scatter_max(x, idx, size=2)\n\n with self.test_session():\n self.assertAllEqual([[3., 4.], [5., 6.]], out.eval())\n\n def testScatterMaxGrad(self):\n x = tf.constant([[1., 2., 7], [3., 4., 8.], [5., 6., 7.]])\n idx = tf.constant([1, 0, 1])\n out = mp_ops.scatter_max(x, idx, size=2)\n with self.test_session():\n diff = tf.test.compute_gradient_error(x, [3, 3], out, [2, 3])\n self.assertLess(diff, 1e-4)\n\n def testGather(self):\n x = tf.constant([[1., 2.], [3., 4.], [5., 6.]])\n idx = tf.constant([1, 0, 1, 2])\n out = mp_ops.gather(x, idx)\n with self.test_session():\n self.assertAllEqual([[3., 4.], [1., 2.], [3., 4.], [5., 6]],\n out.eval())\n\n def testGatherGrad(self):\n x = tf.constant([[1., 2.], [3., 4.], [5., 6.]])\n idx = tf.constant([1, 0, 1, 2])\n out = mp_ops.gather(x, idx)\n with self.test_session():\n diff = tf.test.compute_gradient_error(x, [3, 2], out, [4, 2])\n self.assertLess(diff, 1e-4)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
]
| [
[
"tensorflow.test.compute_gradient_error",
"tensorflow.constant",
"tensorflow.test.main",
"tensorflow.abs"
]
]
|
MattToast/SmartSim | [
"4bd5e231445abd9b888561930db859062708678a"
]
| [
"tutorials/ml_training/surrogate/tf_model.py"
]
| [
"\n# take code for VAE from Keras https://keras.io/examples/generative/vae/\nfrom tensorflow import keras\n\nfrom tensorflow.keras.layers import Conv2D, Conv2DTranspose, BatchNormalization, \\\n Add, SpatialDropout2D, Layer, InputLayer\nfrom tensorflow.keras.models import Model\n\nimport tensorflow as tf\n\nactivation = \"selu\"\npadding = \"same\"\n\n\n# Next function initially taken from\n# https://towardsdatascience.com/building-a-resnet-in-keras-e8f1322a49ba\nclass ResBlock(Layer):\n def __init__(self, downsample: bool, filters: int, kernel_size: int = 3):\n super(ResBlock, self).__init__()\n self.conv1 = Conv2D(kernel_size=kernel_size,\n strides= (1 if not downsample else 2),\n filters=filters,\n padding=padding,\n activation=activation)\n self.bn1 = BatchNormalization()\n self.conv2 = Conv2D(kernel_size=kernel_size,\n strides=1,\n filters=filters,\n padding=padding)\n\n if downsample:\n self.conv3 = Conv2D(kernel_size=1,\n strides=2,\n filters=filters,\n padding=padding)\n else:\n self.conv3 = Conv2D(kernel_size=1,\n strides=1,\n filters=filters,\n padding=padding)\n\n\n self.bn2 = BatchNormalization()\n\n def call(self, inputs):\n x = self.conv1(inputs)\n x = self.bn1(x)\n x = self.conv2(x)\n y = self.conv3(inputs)\n z = Add()([x, y])\n z = keras.activations.selu(z)\n z = self.bn2(z)\n return z\n\n# Next function initially taken from\n# https://towardsdatascience.com/building-a-resnet-in-keras-e8f1322a49ba\nclass ResBlockTranspose(Layer):\n def __init__(self, downsample: bool, filters: int, kernel_size: int = 3):\n super(ResBlockTranspose, self).__init__()\n self.conv1 = Conv2DTranspose(kernel_size=kernel_size,\n strides=(1 if not downsample else 2),\n filters=filters,\n padding=padding,\n activation=activation)\n self.bn1 = BatchNormalization()\n self.conv2 = Conv2DTranspose(kernel_size=kernel_size,\n strides=1,\n filters=filters,\n padding=padding)\n\n if downsample:\n self.conv3 = Conv2DTranspose(kernel_size=1,\n strides=2,\n filters=filters,\n padding=padding)\n else:\n self.conv3 = Conv2DTranspose(kernel_size=1,\n strides=1,\n filters=filters,\n padding=padding)\n\n\n self.bn2 = BatchNormalization()\n\n def call(self, inputs):\n x = self.conv1(inputs)\n x = self.bn1(x)\n x = self.conv2(x)\n y = self.conv3(inputs)\n z = Add()([x, y])\n z = keras.activations.selu(z)\n z = self.bn2(z)\n return z\n\nclass DiffusionResNet(Model):\n def __init__(self, sample_shape, depth=4, downsample=True):\n super().__init__(name = f\"DiffusionResNet_{depth}\")\n filters = sample_shape[-1]\n self.skips = [Conv2D(filters, 3, (1,1), padding=\"same\", activation=activation)]\n self.res_blocks = []\n self.dropout1 = SpatialDropout2D(0.4)\n for i in range(depth):\n filters *= 2\n self.res_blocks.append(ResBlock(downsample, filters, 3))\n if i < depth-1:\n self.skips.append(Conv2D(filters, 3, (1,1), padding=\"same\", activation=activation))\n else:\n self.skips.append(None)\n self.res_blocks_tr = []\n for _ in range(depth):\n filters /= 2\n self.res_blocks_tr.append(ResBlockTranspose(downsample, filters, 3))\n self.dropout2 = SpatialDropout2D(0.4)\n self.bn = BatchNormalization()\n\n def call(self, inputs):\n x = self.res_blocks[0](inputs)\n res_outs = [self.dropout1(x)]\n for i in range(1,len(self.res_blocks)):\n res_outs.append(self.res_blocks[i](res_outs[-1]))\n x = self.res_blocks_tr[0](res_outs[-1])\n for i in range(1,len(self.res_blocks_tr)):\n y = self.skips[-i-1](res_outs[-i-1])\n x = Add()([x, y])\n x = keras.activations.selu(x)\n x = self.res_blocks_tr[i](x)\n x = Add()([self.skips[0](inputs),x])\n x = keras.activations.selu(x)\n x = self.dropout2(x)\n x = self.bn(x)\n return x\n\n\n"
]
| [
[
"tensorflow.keras.activations.selu",
"tensorflow.keras.layers.Conv2DTranspose",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.Add",
"tensorflow.keras.layers.SpatialDropout2D"
]
]
|
jkoessle/PRETSA | [
"93435f1ab37a87a96487496c9facae51971bcfd1"
]
| [
"calculateBaselineEventLogStatistics.py"
]
| [
"import sys\nimport pandas as pd\nimport numpy as np\ndictPath = sys.argv[1]\n\ncaseIDColName = \"Case ID\"\n\ndatasets = [\"Road_Traffic_Fine_Management_Process\",\"CoSeLoG\",\"Sepsis\"]\ndf = pd.DataFrame(columns=['Dataset', 'k', 'method','variants','cases'])\nfor dataset in datasets:\n for k in range(1,9):\n k = 2**k\n filePath = dictPath + dataset + \"_duration_pretsa_baseline_k\" + str(k) + \".csv\"\n eventLog = pd.read_csv(filePath, delimiter=\";\")\n number_variants = eventLog.Variant.value_counts()\n traces = eventLog[caseIDColName].value_counts()\n\n variants = eventLog.groupby('Variant')[caseIDColName].nunique(False)\n\n if len(traces) != 0:\n row = dict()\n row['Dataset'] = dataset\n row['k'] = k\n row['method'] = \"baseline\"\n row['variants'] = number_variants.size\n row['cases'] = len(traces)\n df = df.append(row,ignore_index=True)\n #print(\"Number of variants: \" + str(number_variants.size))\n #print(\"Min cases for Variant: \" + str(min(variants)))\n #print(\"Max cases for Variant: \" + str(max(variants)))\n\n #print(\"Min events in case: \" + str(min(traces)))\n #print(\"Max events in case: \" + str(max(traces)))\n #print(\"Avg events in case: \" + str(np.mean(traces)))\n #print(len(traces))\n\n #print(variants.sort_values())\ncsvPath = dictPath + \"baseline_event_logs_statistics.csv\"\ndf.to_csv(sep=\";\",path_or_buf=csvPath)"
]
| [
[
"pandas.read_csv",
"pandas.DataFrame"
]
]
|
heskarioth/crypto_investment_tracker | [
"74a4a9704df439b2a5b9160f44a8156b56e651fb"
]
| [
"misc_functions/watchlist_funcs.py"
]
| [
"import requests\nimport pandas as pd\nimport numpy as np\nfrom global_vars import *\n\n# functions\ndef watchlist_get_overview():\n url = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=1&sparkline=false'\n client = requests.Session()\n r = client.get(url)\n results = []\n for json_line in r.json():\n if json_line['symbol'] in COIN_WATCHLIST_GECKO_SYMBOL:\n results.append(json_line)\n \n results = pd.DataFrame(results)[['name','symbol', 'current_price', 'market_cap','market_cap_rank', 'total_volume','high_24h', 'low_24h','price_change_percentage_24h','market_cap_change_percentage_24h', 'circulating_supply','total_supply', 'ath', 'ath_change_percentage','ath_date']]\n results.rename(columns={\n 'market_cap_change_percentage_24h':'markcap_%_change_24h'\n ,'ath_change_percentage':'ath_%_change'\n ,'price_change_percentage_24h':'price_%_change_24h'\n ,'total_volume':'tot_vol'\n ,'market_cap_rank':'markcap_rank'\n ,'market_cap':'markcap'\n },inplace=True)\n return results\n"
]
| [
[
"pandas.DataFrame"
]
]
|
zhentaoshi/Boosted_HP_filter | [
"bbc9ce517c30793496b979dadb798ea78e10544b"
]
| [
"python/BoostedHP.py"
]
| [
"#' Boosting the Hodrick-Prescott Filter\n#'\n#' Coded by Mei Ziwei\n#' Documented by Shi Zhentao\n#'\n#' All in one function of conducting the boosted HP-filter.\n##############################################################################\n#' Parameters: \n#'\n#' x - a raw time series to be filtered.\n#' lam - turning parameter, default value is 1600,\n#' as recommended by Hodrick and Prescott (1997) for quarterly data.\n#' iter - logical, True (default) to conduct the boosted HP filter.\n#' False does not iterated, which is exactly the original HP filter.\n#' stopping - stopping criterion. \"BIC\" (default), or \"adf\", or \"nonstop\" means keeping\n#' iteration until the maximum number of iteration, specified by Max_Iter is reached.\n#' sig_p - a threshold of the p-value for the ADF test, with default value 0.050.\n#' Only effective when stopping = \"adf\".\n#' Max_Iter - maximal number of iterations. The default is 100.\n##############################################################################\n#' The function returns a dictionary containing the following items:\n#'\n#' cycle - The cyclical component in the final iteration.\n#' trend - The trend component in the final iteration.\n#' trend_hist - The estimated trend in each iteration.\n#' iter_num - The total number of iterations when it stops.\n#' BIC_hist - The path of the BIC up to the final iterations.\n#' adf_p_hist - The path of the ADF test p-value up to the final iteration.\n##############################################################################\n#' Details:\n#'\n#' This is the main function of implementing the boosted HP filter (Phillisp and\n#' Shi, 2019). The arguments accommendate the orginal HP filter (iter =\n#' False), the boosted HP filter with the BIC stopping criterion (stopping = \"BIC\"),\n#' or ADF test stopping criterion (stopping = \"adf\"), \n#' or keep going until the maximum number of iterations is reached (stopping = \"nonstop\").\n#'\n#' Either the original HP filter or the bHP filter requires lambda to\n#' control the strength of the weak learner for in-sample fitting. \n#' The default is lambda = 1600, \n#' which is recommended by Hodrick and Prescott (1997) for quarterly data. \n#' lambda should be adjusted for different frequencies.\n#' For example, lambda = 129600 for monthly data and\n#' lambda = 100 or 6.25 for annual data.\n#'\n#' See the vignette with a brief introduction of the idea of bHP.\n#'\n##############################################################################\n#' References: \n#'\n#' Phillips, Peter CB, and Zhentao Shi. \"Boosting: Why you can use the hp\n#' filter.\" arXiv: 1905.00175, Cowles Foundation Discussion Paper No.2192,\n#' (2019).\n#'\n##############################################################################\n\nimport numpy as np \nimport statsmodels.tsa.stattools as ts\nimport math \nimport logging \n\ndef BoostedHP(x, lam = 1600, iter = True, stopping = \"BIC\", \\\n sig_p = 0.050, Max_Iter = 100):\n \n \n x = np.array(x)\n \n ## generating trend operator matrix \"S: \n raw_x = x # save the raw data before HP\n n = len(x) # data size\n \n I_n = np.eye(n)\n D_temp = np.vstack((np.zeros([1,n]),np.eye(n-1,n)))\n D_temp= np.dot((I_n-D_temp),(I_n-D_temp))\n D = D_temp[2:n].T\n S = np.linalg.inv(I_n+lam*np.dot(D,D.T)) # Equation 4 in PJ\n mS = I_n - S\n \n ########################################################################## \n \n ## the simple HP-filter\n if not iter:\n \n print(\"Original HP filter.\")\n x_f = np.dot(S,x)\n x_c = x - x_f\n result = {\"cycle\": x_c, \"trend_hist\" : x_f, \\\n \"stopping\" : \"nonstop\", \"trend\" : x - x_c, \"raw_data\" : raw_x}\n \n ##########################################################################\n \n ## The Boosted HP-filter \n if iter:\n ### ADF test as the stopping criterion\n if stopping == \"adf\":\n \n print(\"Boosted HP-ADF.\")\n \n r = 1\n stationary = False\n x_c = x\n \n x_f = np.zeros([n,Max_Iter])\n adf_p = np.zeros([Max_Iter,1])\n \n while (r <= Max_Iter) and (not stationary):\n \n x_c = np.dot(mS,x_c)\n x_f[:,[r-1]] = x-x_c\n adf_p_r = ts.adfuller(x_c, maxlag = math.floor(pow(n-1,1/3)), autolag=None, \\\n regression = \"ct\")[1]\n\n # x_c is the residual after the mean and linear trend being removed by HP filter\n # we use the critical value for the ADF distribution with\n # the intercept and linear trend specification\n \n adf_p[[r-1]] = adf_p_r\n stationary = adf_p_r <= sig_p\n \n # Truncate the storage matrix and vectors\n if stationary:\n R = r\n x_f = x_f[:,0:R]\n adf_p = adf_p[0:R]\n break\n \n r += 1\n \n if r > Max_Iter:\n R = Max_Iter\n logging.warning(\"The number of iterations exceeds Max_Iter. \\\n The residual cycle remains non-stationary.\")\n \n result = {\"cycle\" : x_c, \"trend_hist\" : x_f, \"stopping\" : stopping,\n \"signif_p\" : sig_p, \"adf_p_hist\" : adf_p, \"iter_num\" : R,\n \"trend\" : x - x_c, \"raw_data\" : raw_x}\n \n \n else: # either BIC or nonstopping\n \n # assignment \n r = 0\n x_c_r = x\n x_f = np.zeros([n,Max_Iter])\n IC = np.zeros([Max_Iter,1])\n # IC_decrease = True\n \n I_S_0 = I_n - S\n c_HP = np.dot(I_S_0, x)\n I_S_r = I_S_0\n \n while r < Max_Iter:\n \n r += 1\n \n x_c_r = np.dot(I_S_r, x)\n x_f[:,[r-1]] = x - x_c_r\n B_r = I_n - I_S_r \n IC[[r-1]] = np.var(x_c_r)/np.var(c_HP) + \\\n np.log(n)/(n-np.sum(np.diag(S))) * np.sum(np.diag(B_r))\n \n I_S_r = np.dot(I_S_0, I_S_r) # update for the next round\n \n if r >= 2 and stopping == \"BIC\":\n if IC[[r-2]] < IC[[r-1]]:\n break\n \n # final assignment\n R = r-1\n x_f = x_f[:, list(range(0,R))]\n x_c = x - x_f[:, [R-1]]\n \n if stopping == \"BIC\":\n \n print(\"Boosted HP-BIC.\")\n # save the path of BIC till iter+1 times to keep the \"turning point\" of BIC history.\n result = {\"cycle\" : x_c, \"trend_hist\" : x_f, \"stopping\" : stopping, \n \"BIC_hist\" : IC[0:(R+1)], \"iter_num\" : R, \"trend\" : x- x_c, \"raw_data\" : raw_x}\n \n if stopping == \"nonstop\":\n \n print('Boosted HP-BIC with stopping = \"nonstop\".')\n result = {\"cycle\" : x_c, \"trend_hist\" : x_f, \"stopping\" : stopping, \n \"BIC_hist\" : IC, \"iter_num\" : Max_Iter - 1, \"trend\" : x- x_c, \"raw_data\" : raw_x}\n \n return result \n\n### function ends \n##############################################################################\n# Examples of Boosted HP\n \nimport pandas as pd \nimport os\nos.chdir(os.path.split(os.path.realpath(__file__))[0]) # set current path\n\nIRE = np.array(pd.read_csv(\"IRE.csv\", header = None)) # load the data 'IRE'\nlam = 100 # tuning parameter for the annual data\n\n#\n#' # raw HP filter\nbx_HP = BoostedHP(IRE, lam = lam, iter = False)\n# bx_HP_cycle = bx_HP[\"cycle\"] # The cyclical component \n# bx_HP_trend = bx_HP[\"trend\"] # The trend component \n#'\n#' # by BIC\nbx_BIC = BoostedHP(IRE, lam = lam, iter = True, stopping = \"BIC\")\n#'\n#' # by ADF\n#' # CAVEAT: Results may be slightly different from other languages \n#' # due to different critical values of ADF test. \nbx_ADF = BoostedHP(IRE, lam = lam, iter = True, stopping = \"adf\")\n#'\n#' # If stopping = \"nonstop\",\n#' # Iterated HP filter until Max_Iter and keep the path of BIC.\nbx_nonstop = BoostedHP(IRE, lam = lam, iter = True, stopping = \"nonstop\")\n\n"
]
| [
[
"numpy.diag",
"numpy.dot",
"numpy.log",
"pandas.read_csv",
"numpy.eye",
"numpy.var",
"numpy.array",
"numpy.zeros"
]
]
|
rems75/ray | [
"6f436d8805a5d97deadd6e133a2ecbda87889aee"
]
| [
"python/ray/tune/logger.py"
]
| [
"import csv\nimport json\nimport logging\nimport numpy as np\nimport os\nimport time\nimport yaml\n\nfrom typing import Iterable, TYPE_CHECKING, Dict, List, Optional, TextIO, Type\n\nimport ray.cloudpickle as cloudpickle\n\nfrom ray.tune.callback import Callback\nfrom ray.tune.utils.util import SafeFallbackEncoder\nfrom ray.util.debug import log_once\nfrom ray.tune.result import (TRAINING_ITERATION, TIME_TOTAL_S, TIMESTEPS_TOTAL,\n EXPR_PARAM_FILE, EXPR_PARAM_PICKLE_FILE,\n EXPR_PROGRESS_FILE, EXPR_RESULT_FILE)\nfrom ray.tune.utils import flatten_dict\nfrom ray.util.annotations import PublicAPI\n\nif TYPE_CHECKING:\n from ray.tune.trial import Trial # noqa: F401\n\nlogger = logging.getLogger(__name__)\n\ntf = None\nVALID_SUMMARY_TYPES = [int, float, np.float32, np.float64, np.int32, np.int64]\n\n\nclass Logger:\n \"\"\"Logging interface for ray.tune.\n\n By default, the UnifiedLogger implementation is used which logs results in\n multiple formats (TensorBoard, rllab/viskit, plain json, custom loggers)\n at once.\n\n Arguments:\n config: Configuration passed to all logger creators.\n logdir: Directory for all logger creators to log to.\n trial (Trial): Trial object for the logger to access.\n \"\"\"\n\n def __init__(self,\n config: Dict,\n logdir: str,\n trial: Optional[\"Trial\"] = None):\n self.config = config\n self.logdir = logdir\n self.trial = trial\n self._init()\n\n def _init(self):\n pass\n\n def on_result(self, result):\n \"\"\"Given a result, appends it to the existing log.\"\"\"\n\n raise NotImplementedError\n\n def update_config(self, config):\n \"\"\"Updates the config for logger.\"\"\"\n\n pass\n\n def close(self):\n \"\"\"Releases all resources used by this logger.\"\"\"\n\n pass\n\n def flush(self):\n \"\"\"Flushes all disk writes to storage.\"\"\"\n\n pass\n\n\nclass NoopLogger(Logger):\n def on_result(self, result):\n pass\n\n\nclass JsonLogger(Logger):\n \"\"\"Logs trial results in json format.\n\n Also writes to a results file and param.json file when results or\n configurations are updated. Experiments must be executed with the\n JsonLogger to be compatible with the ExperimentAnalysis tool.\n \"\"\"\n\n def _init(self):\n self.update_config(self.config)\n local_file = os.path.join(self.logdir, EXPR_RESULT_FILE)\n self.local_out = open(local_file, \"a\")\n\n def on_result(self, result: Dict):\n json.dump(result, self, cls=SafeFallbackEncoder)\n self.write(\"\\n\")\n self.local_out.flush()\n\n def write(self, b):\n self.local_out.write(b)\n\n def flush(self):\n if not self.local_out.closed:\n self.local_out.flush()\n\n def close(self):\n self.local_out.close()\n\n def update_config(self, config: Dict):\n self.config = config\n config_out = os.path.join(self.logdir, EXPR_PARAM_FILE)\n with open(config_out, \"w\") as f:\n json.dump(\n self.config,\n f,\n indent=2,\n sort_keys=True,\n cls=SafeFallbackEncoder)\n config_pkl = os.path.join(self.logdir, EXPR_PARAM_PICKLE_FILE)\n with open(config_pkl, \"wb\") as f:\n cloudpickle.dump(self.config, f)\n\n\nclass CSVLogger(Logger):\n \"\"\"Logs results to progress.csv under the trial directory.\n\n Automatically flattens nested dicts in the result dict before writing\n to csv:\n\n {\"a\": {\"b\": 1, \"c\": 2}} -> {\"a/b\": 1, \"a/c\": 2}\n\n \"\"\"\n\n def _init(self):\n \"\"\"CSV outputted with Headers as first set of results.\"\"\"\n progress_file = os.path.join(self.logdir, EXPR_PROGRESS_FILE)\n self._continuing = os.path.exists(progress_file)\n self._file = open(progress_file, \"a\")\n self._csv_out = None\n\n def on_result(self, result: Dict):\n tmp = result.copy()\n if \"config\" in tmp:\n del tmp[\"config\"]\n result = flatten_dict(tmp, delimiter=\"/\")\n if self._csv_out is None:\n self._csv_out = csv.DictWriter(self._file, result.keys())\n if not self._continuing:\n self._csv_out.writeheader()\n self._csv_out.writerow(\n {k: v\n for k, v in result.items() if k in self._csv_out.fieldnames})\n self._file.flush()\n\n def flush(self):\n if not self._file.closed:\n self._file.flush()\n\n def close(self):\n self._file.close()\n\n\nclass TBXLogger(Logger):\n \"\"\"TensorBoardX Logger.\n\n Note that hparams will be written only after a trial has terminated.\n This logger automatically flattens nested dicts to show on TensorBoard:\n\n {\"a\": {\"b\": 1, \"c\": 2}} -> {\"a/b\": 1, \"a/c\": 2}\n \"\"\"\n\n VALID_HPARAMS = (str, bool, int, float, list, type(None))\n VALID_NP_HPARAMS = (np.bool8, np.float32, np.float64, np.int32, np.int64)\n\n def _init(self):\n try:\n from tensorboardX import SummaryWriter\n except ImportError:\n if log_once(\"tbx-install\"):\n logger.info(\n \"pip install \\\"ray[tune]\\\" to see TensorBoard files.\")\n raise\n self._file_writer = SummaryWriter(self.logdir, flush_secs=30)\n self.last_result = None\n\n def on_result(self, result: Dict):\n step = result.get(TIMESTEPS_TOTAL) or result[TRAINING_ITERATION]\n\n tmp = result.copy()\n for k in [\n \"config\", \"pid\", \"timestamp\", TIME_TOTAL_S, TRAINING_ITERATION\n ]:\n if k in tmp:\n del tmp[k] # not useful to log these\n\n flat_result = flatten_dict(tmp, delimiter=\"/\")\n path = [\"ray\", \"tune\"]\n valid_result = {}\n\n for attr, value in flat_result.items():\n full_attr = \"/\".join(path + [attr])\n if (isinstance(value, tuple(VALID_SUMMARY_TYPES))\n and not np.isnan(value)):\n valid_result[full_attr] = value\n self._file_writer.add_scalar(\n full_attr, value, global_step=step)\n elif ((isinstance(value, list) and len(value) > 0)\n or (isinstance(value, np.ndarray) and value.size > 0)):\n valid_result[full_attr] = value\n\n # Must be video\n if isinstance(value, np.ndarray) and value.ndim == 5:\n self._file_writer.add_video(\n full_attr, value, global_step=step, fps=20)\n continue\n\n try:\n self._file_writer.add_histogram(\n full_attr, value, global_step=step)\n # In case TensorboardX still doesn't think it's a valid value\n # (e.g. `[[]]`), warn and move on.\n except (ValueError, TypeError):\n if log_once(\"invalid_tbx_value\"):\n logger.warning(\n \"You are trying to log an invalid value ({}={}) \"\n \"via {}!\".format(full_attr, value,\n type(self).__name__))\n\n self.last_result = valid_result\n self._file_writer.flush()\n\n def flush(self):\n if self._file_writer is not None:\n self._file_writer.flush()\n\n def close(self):\n if self._file_writer is not None:\n if self.trial and self.trial.evaluated_params and self.last_result:\n flat_result = flatten_dict(self.last_result, delimiter=\"/\")\n scrubbed_result = {\n k: value\n for k, value in flat_result.items()\n if isinstance(value, tuple(VALID_SUMMARY_TYPES))\n }\n self._try_log_hparams(scrubbed_result)\n self._file_writer.close()\n\n def _try_log_hparams(self, result):\n # TBX currently errors if the hparams value is None.\n flat_params = flatten_dict(self.trial.evaluated_params)\n scrubbed_params = {\n k: v\n for k, v in flat_params.items()\n if isinstance(v, self.VALID_HPARAMS)\n }\n\n np_params = {\n k: v.tolist()\n for k, v in flat_params.items()\n if isinstance(v, self.VALID_NP_HPARAMS)\n }\n\n scrubbed_params.update(np_params)\n\n removed = {\n k: v\n for k, v in flat_params.items()\n if not isinstance(v, self.VALID_HPARAMS + self.VALID_NP_HPARAMS)\n }\n if removed:\n logger.info(\n \"Removed the following hyperparameter values when \"\n \"logging to tensorboard: %s\", str(removed))\n\n from tensorboardX.summary import hparams\n try:\n experiment_tag, session_start_tag, session_end_tag = hparams(\n hparam_dict=scrubbed_params, metric_dict=result)\n self._file_writer.file_writer.add_summary(experiment_tag)\n self._file_writer.file_writer.add_summary(session_start_tag)\n self._file_writer.file_writer.add_summary(session_end_tag)\n except Exception:\n logger.exception(\"TensorboardX failed to log hparams. \"\n \"This may be due to an unsupported type \"\n \"in the hyperparameter values.\")\n\n\nDEFAULT_LOGGERS = (JsonLogger, CSVLogger, TBXLogger)\n\n\nclass UnifiedLogger(Logger):\n \"\"\"Unified result logger for TensorBoard, rllab/viskit, plain json.\n\n Arguments:\n config: Configuration passed to all logger creators.\n logdir: Directory for all logger creators to log to.\n loggers (list): List of logger creators. Defaults to CSV, Tensorboard,\n and JSON loggers.\n \"\"\"\n\n def __init__(self,\n config: Dict,\n logdir: str,\n trial: Optional[\"Trial\"] = None,\n loggers: Optional[List[Type[Logger]]] = None):\n if loggers is None:\n self._logger_cls_list = DEFAULT_LOGGERS\n else:\n self._logger_cls_list = loggers\n if JsonLogger not in self._logger_cls_list:\n if log_once(\"JsonLogger\"):\n logger.warning(\n \"JsonLogger not provided. The ExperimentAnalysis tool is \"\n \"disabled.\")\n\n super(UnifiedLogger, self).__init__(config, logdir, trial)\n\n def _init(self):\n self._loggers = []\n for cls in self._logger_cls_list:\n try:\n self._loggers.append(cls(self.config, self.logdir, self.trial))\n except Exception as exc:\n if log_once(f\"instantiate:{cls.__name__}\"):\n logger.warning(\"Could not instantiate %s: %s.\",\n cls.__name__, str(exc))\n\n def on_result(self, result):\n for _logger in self._loggers:\n _logger.on_result(result)\n\n def update_config(self, config):\n for _logger in self._loggers:\n _logger.update_config(config)\n\n def close(self):\n for _logger in self._loggers:\n _logger.close()\n\n def flush(self):\n for _logger in self._loggers:\n _logger.flush()\n\n\n@PublicAPI\nclass LoggerCallback(Callback):\n \"\"\"Base class for experiment-level logger callbacks\n\n This base class defines a general interface for logging events,\n like trial starts, restores, ends, checkpoint saves, and receiving\n trial results.\n\n Callbacks implementing this interface should make sure that logging\n utilities are cleaned up properly on trial termination, i.e. when\n ``log_trial_end`` is received. This includes e.g. closing files.\n \"\"\"\n\n def log_trial_start(self, trial: \"Trial\"):\n \"\"\"Handle logging when a trial starts.\n\n Args:\n trial (Trial): Trial object.\n \"\"\"\n pass\n\n def log_trial_restore(self, trial: \"Trial\"):\n \"\"\"Handle logging when a trial restores.\n\n Args:\n trial (Trial): Trial object.\n \"\"\"\n pass\n\n def log_trial_save(self, trial: \"Trial\"):\n \"\"\"Handle logging when a trial saves a checkpoint.\n\n Args:\n trial (Trial): Trial object.\n \"\"\"\n pass\n\n def log_trial_result(self, iteration: int, trial: \"Trial\", result: Dict):\n \"\"\"Handle logging when a trial reports a result.\n\n Args:\n trial (Trial): Trial object.\n result (dict): Result dictionary.\n \"\"\"\n pass\n\n def log_trial_end(self, trial: \"Trial\", failed: bool = False):\n \"\"\"Handle logging when a trial ends.\n\n Args:\n trial (Trial): Trial object.\n failed (bool): True if the Trial finished gracefully, False if\n it failed (e.g. when it raised an exception).\n \"\"\"\n pass\n\n def on_trial_result(self, iteration: int, trials: List[\"Trial\"],\n trial: \"Trial\", result: Dict, **info):\n self.log_trial_result(iteration, trial, result)\n\n def on_trial_start(self, iteration: int, trials: List[\"Trial\"],\n trial: \"Trial\", **info):\n self.log_trial_start(trial)\n\n def on_trial_restore(self, iteration: int, trials: List[\"Trial\"],\n trial: \"Trial\", **info):\n self.log_trial_restore(trial)\n\n def on_trial_save(self, iteration: int, trials: List[\"Trial\"],\n trial: \"Trial\", **info):\n self.log_trial_save(trial)\n\n def on_trial_complete(self, iteration: int, trials: List[\"Trial\"],\n trial: \"Trial\", **info):\n self.log_trial_end(trial, failed=False)\n\n def on_trial_error(self, iteration: int, trials: List[\"Trial\"],\n trial: \"Trial\", **info):\n self.log_trial_end(trial, failed=True)\n\n\nclass LegacyLoggerCallback(LoggerCallback):\n \"\"\"Supports logging to trial-specific `Logger` classes.\n\n Previously, Ray Tune logging was handled via `Logger` classes that have\n been instantiated per-trial. This callback is a fallback to these\n `Logger`-classes, instantiating each `Logger` class for each trial\n and logging to them.\n\n Args:\n logger_classes (Iterable[Type[Logger]]): Logger classes that should\n be instantiated for each trial.\n\n \"\"\"\n\n def __init__(self, logger_classes: Iterable[Type[Logger]]):\n self.logger_classes = list(logger_classes)\n self._class_trial_loggers: Dict[Type[Logger], Dict[\"Trial\",\n Logger]] = {}\n\n def log_trial_start(self, trial: \"Trial\"):\n trial.init_logdir()\n\n for logger_class in self.logger_classes:\n trial_loggers = self._class_trial_loggers.get(logger_class, {})\n if trial not in trial_loggers:\n logger = logger_class(trial.config, trial.logdir, trial)\n trial_loggers[trial] = logger\n self._class_trial_loggers[logger_class] = trial_loggers\n\n def log_trial_restore(self, trial: \"Trial\"):\n for logger_class, trial_loggers in self._class_trial_loggers.items():\n if trial in trial_loggers:\n trial_loggers[trial].flush()\n\n def log_trial_save(self, trial: \"Trial\"):\n for logger_class, trial_loggers in self._class_trial_loggers.items():\n if trial in trial_loggers:\n trial_loggers[trial].flush()\n\n def log_trial_result(self, iteration: int, trial: \"Trial\", result: Dict):\n for logger_class, trial_loggers in self._class_trial_loggers.items():\n if trial in trial_loggers:\n trial_loggers[trial].on_result(result)\n\n def log_trial_end(self, trial: \"Trial\", failed: bool = False):\n for logger_class, trial_loggers in self._class_trial_loggers.items():\n if trial in trial_loggers:\n trial_loggers[trial].close()\n\n\nclass JsonLoggerCallback(LoggerCallback):\n \"\"\"Logs trial results in json format.\n\n Also writes to a results file and param.json file when results or\n configurations are updated. Experiments must be executed with the\n JsonLoggerCallback to be compatible with the ExperimentAnalysis tool.\n \"\"\"\n\n def __init__(self):\n self._trial_configs: Dict[\"Trial\", Dict] = {}\n self._trial_files: Dict[\"Trial\", TextIO] = {}\n\n def log_trial_start(self, trial: \"Trial\"):\n if trial in self._trial_files:\n self._trial_files[trial].close()\n\n # Update config\n self.update_config(trial, trial.config)\n\n # Make sure logdir exists\n trial.init_logdir()\n local_file = os.path.join(trial.logdir, EXPR_RESULT_FILE)\n self._trial_files[trial] = open(local_file, \"at\")\n\n def log_trial_result(self, iteration: int, trial: \"Trial\", result: Dict):\n if trial not in self._trial_files:\n self.log_trial_start(trial)\n json.dump(result, self._trial_files[trial], cls=SafeFallbackEncoder)\n self._trial_files[trial].write(\"\\n\")\n self._trial_files[trial].flush()\n\n def log_trial_end(self, trial: \"Trial\", failed: bool = False):\n if trial not in self._trial_files:\n return\n\n self._trial_files[trial].close()\n del self._trial_files[trial]\n\n def update_config(self, trial: \"Trial\", config: Dict):\n self._trial_configs[trial] = config\n\n config_out = os.path.join(trial.logdir, EXPR_PARAM_FILE)\n with open(config_out, \"w\") as f:\n json.dump(\n self._trial_configs[trial],\n f,\n indent=2,\n sort_keys=True,\n cls=SafeFallbackEncoder)\n\n config_pkl = os.path.join(trial.logdir, EXPR_PARAM_PICKLE_FILE)\n with open(config_pkl, \"wb\") as f:\n cloudpickle.dump(self._trial_configs[trial], f)\n\n\nclass CSVLoggerCallback(LoggerCallback):\n \"\"\"Logs results to progress.csv under the trial directory.\n\n Automatically flattens nested dicts in the result dict before writing\n to csv:\n\n {\"a\": {\"b\": 1, \"c\": 2}} -> {\"a/b\": 1, \"a/c\": 2}\n\n \"\"\"\n\n def __init__(self):\n self._trial_continue: Dict[\"Trial\", bool] = {}\n self._trial_files: Dict[\"Trial\", TextIO] = {}\n self._trial_csv: Dict[\"Trial\", csv.DictWriter] = {}\n\n def log_trial_start(self, trial: \"Trial\"):\n if trial in self._trial_files:\n self._trial_files[trial].close()\n\n # Make sure logdir exists\n trial.init_logdir()\n local_file = os.path.join(trial.logdir, EXPR_PROGRESS_FILE)\n self._trial_continue[trial] = os.path.exists(local_file)\n self._trial_files[trial] = open(local_file, \"at\")\n self._trial_csv[trial] = None\n\n def log_trial_result(self, iteration: int, trial: \"Trial\", result: Dict):\n if trial not in self._trial_files:\n self.log_trial_start(trial)\n\n tmp = result.copy()\n tmp.pop(\"config\", None)\n result = flatten_dict(tmp, delimiter=\"/\")\n\n if not self._trial_csv[trial]:\n self._trial_csv[trial] = csv.DictWriter(self._trial_files[trial],\n result.keys())\n if not self._trial_continue[trial]:\n self._trial_csv[trial].writeheader()\n\n self._trial_csv[trial].writerow({\n k: v\n for k, v in result.items()\n if k in self._trial_csv[trial].fieldnames\n })\n self._trial_files[trial].flush()\n\n if os.environ.get('FLUSH', False):\n # Need to close and reopen files for logging to actually happen on our clusters.\n self.log_trial_start(trial)\n\n def log_trial_end(self, trial: \"Trial\", failed: bool = False):\n if trial not in self._trial_files:\n return\n\n del self._trial_csv[trial]\n self._trial_files[trial].close()\n del self._trial_files[trial]\n\n\nclass TBXLoggerCallback(LoggerCallback):\n \"\"\"TensorBoardX Logger.\n\n Note that hparams will be written only after a trial has terminated.\n This logger automatically flattens nested dicts to show on TensorBoard:\n\n {\"a\": {\"b\": 1, \"c\": 2}} -> {\"a/b\": 1, \"a/c\": 2}\n \"\"\"\n\n VALID_HPARAMS = (str, bool, int, float, list, type(None))\n VALID_NP_HPARAMS = (np.bool8, np.float32, np.float64, np.int32, np.int64)\n\n def __init__(self):\n try:\n from tensorboardX import SummaryWriter\n self._summary_writer_cls = SummaryWriter\n except ImportError:\n if log_once(\"tbx-install\"):\n logger.info(\n \"pip install \\\"ray[tune]\\\" to see TensorBoard files.\")\n raise\n self._trial_writer: Dict[\"Trial\", SummaryWriter] = {}\n self._trial_result: Dict[\"Trial\", Dict] = {}\n\n def log_trial_start(self, trial: \"Trial\"):\n if trial in self._trial_writer:\n self._trial_writer[trial].close()\n trial.init_logdir()\n self._trial_writer[trial] = self._summary_writer_cls(\n trial.logdir, flush_secs=30)\n self._trial_result[trial] = {}\n\n def log_trial_result(self, iteration: int, trial: \"Trial\", result: Dict):\n if trial not in self._trial_writer:\n self.log_trial_start(trial)\n\n step = result.get(TIMESTEPS_TOTAL) or result[TRAINING_ITERATION]\n\n tmp = result.copy()\n for k in [\n \"config\", \"pid\", \"timestamp\", TIME_TOTAL_S, TRAINING_ITERATION\n ]:\n if k in tmp:\n del tmp[k] # not useful to log these\n\n flat_result = flatten_dict(tmp, delimiter=\"/\")\n path = [\"ray\", \"tune\"]\n valid_result = {}\n\n for attr, value in flat_result.items():\n full_attr = \"/\".join(path + [attr])\n if (isinstance(value, tuple(VALID_SUMMARY_TYPES))\n and not np.isnan(value)):\n valid_result[full_attr] = value\n self._trial_writer[trial].add_scalar(\n full_attr, value, global_step=step)\n elif ((isinstance(value, list) and len(value) > 0)\n or (isinstance(value, np.ndarray) and value.size > 0)):\n valid_result[full_attr] = value\n\n # Must be video\n if isinstance(value, np.ndarray) and value.ndim == 5:\n self._trial_writer[trial].add_video(\n full_attr, value, global_step=step, fps=20)\n continue\n\n try:\n self._trial_writer[trial].add_histogram(\n full_attr, value, global_step=step)\n # In case TensorboardX still doesn't think it's a valid value\n # (e.g. `[[]]`), warn and move on.\n except (ValueError, TypeError):\n if log_once(\"invalid_tbx_value\"):\n logger.warning(\n \"You are trying to log an invalid value ({}={}) \"\n \"via {}!\".format(full_attr, value,\n type(self).__name__))\n\n self._trial_result[trial] = valid_result\n self._trial_writer[trial].flush()\n\n if os.environ.get('FLUSH', False):\n # Need to close and reopen files for logging to actually happen on our clusters.\n try:\n path = self._trial_writer[trial].file_writer.event_writer._ev_writer._py_recordio_writer.path\n self._trial_writer[trial].file_writer.event_writer._ev_writer._py_recordio_writer._writer.flush()\n while True:\n if self._trial_writer[trial].file_writer.event_writer._event_queue.empty():\n break\n time.sleep(0.1) # Increased from 0.1 -> X s\n self._trial_writer[trial].file_writer.event_writer._ev_writer._py_recordio_writer._writer = open(path, 'ab')\n except:\n pass\n\n def log_trial_end(self, trial: \"Trial\", failed: bool = False):\n if trial in self._trial_writer:\n if trial and trial.evaluated_params and self._trial_result[trial]:\n flat_result = flatten_dict(\n self._trial_result[trial], delimiter=\"/\")\n scrubbed_result = {\n k: value\n for k, value in flat_result.items()\n if isinstance(value, tuple(VALID_SUMMARY_TYPES))\n }\n self._try_log_hparams(trial, scrubbed_result)\n self._trial_writer[trial].close()\n del self._trial_writer[trial]\n del self._trial_result[trial]\n\n def _try_log_hparams(self, trial: \"Trial\", result: Dict):\n # TBX currently errors if the hparams value is None.\n flat_params = flatten_dict(trial.evaluated_params)\n scrubbed_params = {\n k: v\n for k, v in flat_params.items()\n if isinstance(v, self.VALID_HPARAMS)\n }\n\n np_params = {\n k: v.tolist()\n for k, v in flat_params.items()\n if isinstance(v, self.VALID_NP_HPARAMS)\n }\n\n scrubbed_params.update(np_params)\n\n removed = {\n k: v\n for k, v in flat_params.items()\n if not isinstance(v, self.VALID_HPARAMS + self.VALID_NP_HPARAMS)\n }\n if removed:\n logger.info(\n \"Removed the following hyperparameter values when \"\n \"logging to tensorboard: %s\", str(removed))\n\n from tensorboardX.summary import hparams\n try:\n experiment_tag, session_start_tag, session_end_tag = hparams(\n hparam_dict=scrubbed_params, metric_dict=result)\n self._trial_writer[trial].file_writer.add_summary(experiment_tag)\n self._trial_writer[trial].file_writer.add_summary(\n session_start_tag)\n self._trial_writer[trial].file_writer.add_summary(session_end_tag)\n except Exception:\n logger.exception(\"TensorboardX failed to log hparams. \"\n \"This may be due to an unsupported type \"\n \"in the hyperparameter values.\")\n\n\n# Maintain backwards compatibility.\nfrom ray.tune.integration.mlflow import MLflowLogger as _MLflowLogger # noqa: E402, E501\nMLflowLogger = _MLflowLogger\n# The capital L is a typo, but needs to remain for backwards compatibility.\nMLFLowLogger = _MLflowLogger\n\n\ndef pretty_print(result):\n result = result.copy()\n result.update(config=None) # drop config from pretty print\n result.update(hist_stats=None) # drop hist_stats from pretty print\n out = {}\n for k, v in result.items():\n if v is not None:\n out[k] = v\n\n cleaned = json.dumps(out, cls=SafeFallbackEncoder)\n return yaml.safe_dump(json.loads(cleaned), default_flow_style=False)\n"
]
| [
[
"numpy.isnan"
]
]
|
rushic24/python-stocks-charting-from-scratch | [
"d496f8d0373cbb9a607e08c23e5f6a982fbbf866"
]
| [
"temp.py"
]
| [
"import urllib.request, urllib.error, urllib.parse\nimport time\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nimport matplotlib.dates as mdates\nfrom matplotlib.finance import candlestick_ohlc\nimport matplotlib\nimport pylab\nmatplotlib.rcParams.update({'font.size': 9})\n\n\ndef bytespdate2num(fmt, encoding='utf-8'):\n strconverter = mdates.strpdate2num(fmt)\n def bytesconverter(b):\n s = b.decode(encoding)\n return strconverter(s)\n return bytesconverter\n\ndef graphData(stock,MA1,MA2):\n\n '''\n Use this to dynamically pull a stock:\n '''\n try:\n print('Currently Pulling',stock)\n urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv'\n stockFile =[]\n try:\n sourceCode = urllib.request.urlopen(urlToVisit).read().decode()\n splitSource = sourceCode.split('\\n')\n for eachLine in splitSource:\n splitLine = eachLine.split(',')\n if len(splitLine)==6:\n if 'values' not in eachLine:\n stockFile.append(eachLine)\n except Exception as e:\n print(str(e), 'failed to organize pulled data.')\n except Exception as e:\n print(str(e), 'failed to pull pricing data')\n\n try:\n date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile,delimiter=',', unpack=True,\n converters={ 0: bytespdate2num('%Y%m%d')})\n x = 0\n y = len(date)\n newAr = []\n while x < y:\n appendLine = date[x],openp[x],highp[x],lowp[x],closep[x],volume[x]\n newAr.append(appendLine)\n x+=1\n \n Av1 = movingaverage(closep, MA1)\n Av2 = movingaverage(closep, MA2)\n\n SP = len(date[MA2-1:])\n \n fig = plt.figure(facecolor='#07000d')\n\n ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')\n candlestick_ohlc(ax1, newAr[-SP:], width=.6, colorup='#53c156', colordown='#ff1717')\n\n Label1 = str(MA1)+' SMA'\n Label2 = str(MA2)+' SMA'\n\n ax1.plot(date[-SP:],Av1[-SP:],'#e1edf9',label=Label1, linewidth=1.5)\n ax1.plot(date[-SP:],Av2[-SP:],'#4ee6fd',label=Label2, linewidth=1.5)\n \n ax1.grid(True, color='w')\n ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))\n ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\n ax1.yaxis.label.set_color(\"w\")\n ax1.spines['bottom'].set_color(\"#5998ff\")\n ax1.spines['top'].set_color(\"#5998ff\")\n ax1.spines['left'].set_color(\"#5998ff\")\n ax1.spines['right'].set_color(\"#5998ff\")\n ax1.tick_params(axis='y', colors='w')\n plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))\n ax1.tick_params(axis='x', colors='w')\n plt.ylabel('Stock price and Volume')\n\n maLeg = plt.legend(loc=9, ncol=2, prop={'size':7},\n fancybox=True, borderaxespad=0.)\n maLeg.get_frame().set_alpha(0.4)\n textEd = pylab.gca().get_legend().get_texts()\n pylab.setp(textEd[0:5], color = 'w')\n\n volumeMin = 0\n \n ax0 = plt.subplot2grid((6,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')\n rsi = rsiFunc(closep)\n rsiCol = '#c1f9f7'\n posCol = '#386d13'\n negCol = '#8f2020'\n \n ax0.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=1.5)\n ax0.axhline(70, color=negCol)\n ax0.axhline(30, color=posCol)\n ax0.fill_between(date[-SP:], rsi[-SP:], 70, where=(rsi[-SP:]>=70), facecolor=negCol, edgecolor=negCol, alpha=0.5)\n ax0.fill_between(date[-SP:], rsi[-SP:], 30, where=(rsi[-SP:]<=30), facecolor=posCol, edgecolor=posCol, alpha=0.5)\n ax0.set_yticks([30,70])\n ax0.yaxis.label.set_color(\"w\")\n ax0.spines['bottom'].set_color(\"#5998ff\")\n ax0.spines['top'].set_color(\"#5998ff\")\n ax0.spines['left'].set_color(\"#5998ff\")\n ax0.spines['right'].set_color(\"#5998ff\")\n ax0.tick_params(axis='y', colors='w')\n ax0.tick_params(axis='x', colors='w')\n plt.ylabel('RSI')\n\n ax1v = ax1.twinx()\n ax1v.fill_between(date[-SP:],volumeMin, volume[-SP:], facecolor='#00ffe8', alpha=.4)\n ax1v.axes.yaxis.set_ticklabels([])\n ax1v.grid(False)\n ###Edit this to 3, so it's a bit larger\n ax1v.set_ylim(0, 3*volume.max())\n ax1v.spines['bottom'].set_color(\"#5998ff\")\n ax1v.spines['top'].set_color(\"#5998ff\")\n ax1v.spines['left'].set_color(\"#5998ff\")\n ax1v.spines['right'].set_color(\"#5998ff\")\n ax1v.tick_params(axis='x', colors='w')\n ax1v.tick_params(axis='y', colors='w')\n \n ax2 = plt.subplot2grid((6,4), (5,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')\n fillcolor = '#00ffe8'\n nslow = 26\n nfast = 12\n nema = 9\n emaslow, emafast, macd = computeMACD(closep)\n ema9 = ExpMovingAverage(macd, nema)\n ax2.plot(date[-SP:], macd[-SP:], color='#4ee6fd', lw=2)\n ax2.plot(date[-SP:], ema9[-SP:], color='#e1edf9', lw=1)\n ax2.fill_between(date[-SP:], macd[-SP:]-ema9[-SP:], 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor)\n\n plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))\n ax2.spines['bottom'].set_color(\"#5998ff\")\n ax2.spines['top'].set_color(\"#5998ff\")\n ax2.spines['left'].set_color(\"#5998ff\")\n ax2.spines['right'].set_color(\"#5998ff\")\n ax2.tick_params(axis='x', colors='w')\n ax2.tick_params(axis='y', colors='w')\n plt.ylabel('MACD', color='w')\n ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))\n for label in ax2.xaxis.get_ticklabels():\n label.set_rotation(45)\n\n plt.suptitle(stock.upper(),color='w')\n plt.setp(ax0.get_xticklabels(), visible=False)\n plt.setp(ax1.get_xticklabels(), visible=False)\n \n ax1.annotate('Big news!',(date[510],Av1[510]),\n xytext=(0.8, 0.9), textcoords='axes fraction',\n arrowprops=dict(facecolor='white', shrink=0.05),\n fontsize=14, color = 'w',\n horizontalalignment='right', verticalalignment='bottom')\n\n plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0)\n plt.show()\n fig.savefig('example.png',facecolor=fig.get_facecolor())\n \n except Exception as e:\n print('main loop',str(e))\n\nwhile True:\n stock = input('Stock to plot: ')\n graphData(stock,10,50)"
]
| [
[
"matplotlib.pyplot.legend",
"matplotlib.dates.DateFormatter",
"matplotlib.pyplot.gca",
"matplotlib.dates.strpdate2num",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.rcParams.update",
"matplotlib.ticker.MaxNLocator",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplot2grid",
"matplotlib.finance.candlestick_ohlc"
]
]
|
ryutok/mpl_axes_aligner | [
"bc956ffbdaad0dc6fefc1aaa98f5bc6b55e8ea8a"
]
| [
"tests/test_shift.py"
]
| [
"import pytest\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom mpl_axes_aligner import shift\n\nfig = plt.figure()\n\n\ndef test_expand_range_simple():\n org = 0.0\n ival = 0.0\n fval = 2.0\n pos = 0.5\n ival, fval = shift._expand_range(org, pos, ival, fval)\n assert round(ival, 15) == -2.0\n assert round(fval, 15) == 2.0\n\n\ndef test_expand_range_inverted():\n org = 0.0\n ival = 2.0\n fval = 0.0\n pos = 0.5\n ival, fval = shift._expand_range(org, pos, ival, fval)\n assert round(ival, 15) == 2.0\n assert round(fval, 15) == -2.0\n\n\ndef test_expand_range_outrange_n():\n org = -1.0\n ival = 0.0\n fval = 2.0\n pos = 0.5\n ival, fval = shift._expand_range(org, pos, ival, fval)\n assert round(ival, 15) == -4.0\n assert round(fval, 15) == 2.0\n\n\ndef test_expand_range_outrange_p():\n org = 3.0\n ival = 0.0\n fval = 2.0\n pos = 0.5\n ival, fval = shift._expand_range(org, pos, ival, fval)\n assert round(ival, 15) == 0.0\n assert round(fval, 15) == 6.0\n\n\ndef test_shift_range_simple():\n org = 0.5\n ival = 0.0\n fval = 2.0\n pos = 0.5\n ival, fval = shift._shift_range(org, pos, ival, fval)\n assert round(ival, 15) == -0.5\n assert round(fval, 15) == 1.5\n\n\ndef test_shift_range_inverted():\n org = 0.5\n ival = 2.0\n fval = 0.0\n pos = 0.5\n ival, fval = shift._shift_range(org, pos, ival, fval)\n assert round(ival, 15) == 1.5\n assert round(fval, 15) == -0.5\n\n\ndef test_shift_range_outrange_n():\n org = -1.0\n ival = 0.0\n fval = 2.0\n pos = 0.5\n ival, fval = shift._shift_range(org, pos, ival, fval)\n assert round(ival, 15) == -2.0\n assert round(fval, 15) == 0.0\n\n\ndef test_shift_range_outrange_p():\n org = 3.0\n ival = 0.0\n fval = 2.0\n pos = 0.5\n ival, fval = shift._shift_range(org, pos, ival, fval)\n assert round(ival, 15) == 2.0\n assert round(fval, 15) == 4.0\n\n\[email protected]('pos', [-2, 2])\ndef test_yaxis_shift_ValueError(pos):\n fig.clear()\n ax = fig.add_subplot(111)\n org = 0.5\n with pytest.raises(ValueError):\n shift.yaxis(ax, org, pos)\n\n\[email protected]('pos', [-2, 2])\ndef test_xaxis_shift_ValueError(pos):\n fig.clear()\n ax = fig.add_subplot(111)\n org = 0.5\n with pytest.raises(ValueError):\n shift.xaxis(ax, org, pos)\n\n\[email protected]('pos', [0, 1])\ndef test_yaxis_shift_NoError(pos):\n fig.clear()\n ax = fig.add_subplot(111)\n org = 0.5\n shift.yaxis(ax, org, pos)\n\n\[email protected]('pos', [0, 1])\ndef test_xaxis_shift_NoError(pos):\n fig.clear()\n ax = fig.add_subplot(111)\n org = 0.5\n shift.xaxis(ax, org, pos)\n\n\[email protected]('pos', [-2, 0, 1, 2])\ndef test_yaxis_expand_ValueError(pos):\n fig.clear()\n ax = fig.add_subplot(111)\n org = 0.5\n with pytest.raises(ValueError):\n shift.yaxis(ax, org, pos, True)\n\n\[email protected]('pos', [-2, 0, 1, 2])\ndef test_xaxis_expand_ValueError(pos):\n fig.clear()\n ax = fig.add_subplot(111)\n org = 0.5\n with pytest.raises(ValueError):\n shift.xaxis(ax, org, pos, True)\n\n\ndef test_yaxes_expand_simple():\n fig.clear()\n ax = fig.add_subplot(111)\n ax.set_xlim(0.0, 1.0)\n org = 0.0\n pos = 0.5\n shift.yaxis(ax, org, pos, True)\n assert ax.get_ylim() == (-1.0, 1.0)\n\n\ndef test_xaxes_expand_simple():\n fig.clear()\n ax = fig.add_subplot(111)\n ax.set_xlim(0.0, 1.0)\n org = 0.0\n pos = 0.5\n shift.xaxis(ax, org, pos, True)\n assert ax.get_xlim() == (-1.0, 1.0)\n"
]
| [
[
"matplotlib.use",
"matplotlib.pyplot.figure"
]
]
|
ZerinHwang03/SiamFC_online_finetuning | [
"b139349e993c96ad66f368ee822a688906c83d99"
]
| [
"src/windows.py"
]
| [
"# -*- coding:utf-8 -*-\n\n\"\"\"\nin this function, I defined some functions for the process for score map\n\nincludes:\n make_hanning_window(): create penalty for score map on the basis of hanning window\n make_guassian_window(): create penalty for score map on the basis of gaussian window\n add_window_to_img(): add the created window to the score map. as the punishment to the score map\n\nNotes:\n the data are np-type\n\"\"\"\nimport numpy as np\n\ndef make_hanning_window(sz):\n hann_1d = np.expand_dims(np.hanning(sz), axis=0)\n window = np.transpose(hann_1d) * hann_1d\n window = window / np.sum(window)\n# assert (len(img.shape) == 3 and img.shape[2] == 1), 'img.shape should be (weight, height, 1)'\n return window\n\ndef make_guassian_window(n, sigma=1):\n\n #print(\"n should be an odd\")\n nn = int((n - 1) / 2)\n a = np.asarray([[x ** 2 + y ** 2 for x in range(-nn, nn + 1)] for y in range(-nn, nn + 1)])\n # np.asarray可以将输入转化为np.array, 这里输入为一个列表推导式\n window = np.exp(-a / (2 * sigma ** 2))\n # 归一化...\n window = window / np.sum(window)\n return window\n\ndef add_window_to_scoremap(scoremap, window, window_influence):\n scoremap = (1 - window_influence) * scoremap + window_influence * window\n return scoremap\n\n"
]
| [
[
"numpy.exp",
"numpy.sum",
"numpy.hanning",
"numpy.transpose"
]
]
|
bghojogh/Quantile-Quantile-Embedding | [
"5daff878a838f6dbeb04cc0b15da2ad66ab9796c"
]
| [
"2_deep_codes/3_Siamese_triplet/CNN_Siamese.py"
]
| [
"# import tensorflow as tf\nimport tensorflow.compat.v1 as tf\n\ntf.disable_v2_behavior()\nimport numpy as np\n\n\n# I googled: tensorflow cnn example\n# https://www.datacamp.com/community/tutorials/cnn-tensorflow-python\n\nclass CNN_Siamese:\n\n # Create model\n def __init__(self, loss_type, feature_space_dimension, margin_in_loss=0.25):\n # self.x1 = tf.placeholder(tf.float32, [None, 49152])\n # self.x1Image = tf.reshape(self.x1, [-1, 128, 128, 3])\n # self.x2 = tf.placeholder(tf.float32, [None, 49152])\n # self.x2Image = tf.reshape(self.x2, [-1, 128, 128, 3])\n # self.x3 = tf.placeholder(tf.float32, [None, 49152])\n # self.x3Image = tf.reshape(self.x3, [-1, 128, 128, 3])\n\n self.x1 = tf.placeholder(tf.float32, [None, 128, 128, 3])\n self.x1Image = self.x1\n self.x2 = tf.placeholder(tf.float32, [None, 128, 128, 3])\n self.x2Image = self.x2\n self.x3 = tf.placeholder(tf.float32, [None, 128, 128, 3])\n self.x3Image = self.x3\n\n self.margin_in_loss = margin_in_loss\n\n # self.loss_type = tf.placeholder(tf.float32, [1, 1])\n\n # self.weights = {\n # 'wc1': tf.get_variable('W0', shape=(3,3,3,32), initializer=tf.contrib.layers.xavier_initializer()),\n # 'wc2': tf.get_variable('W1', shape=(3,3,32,64), initializer=tf.contrib.layers.xavier_initializer()),\n # 'wc3': tf.get_variable('W2', shape=(3,3,64,128), initializer=tf.contrib.layers.xavier_initializer()),\n # 'wd1': tf.get_variable('W3', shape=(4*4*128,1024), initializer=tf.contrib.layers.xavier_initializer()),\n # }\n\n self.weights = {\n 'wc1': tf.get_variable('W0', shape=(3, 3, 3, 32), initializer=tf.glorot_uniform_initializer()),\n 'wc2': tf.get_variable('W1', shape=(3, 3, 32, 64), initializer=tf.glorot_uniform_initializer()),\n 'wc3': tf.get_variable('W2', shape=(3, 3, 64, 128), initializer=tf.glorot_uniform_initializer()),\n 'wd1': tf.get_variable('W3', shape=(16 * 16 * 128, 500), initializer=tf.glorot_uniform_initializer()),\n 'out': tf.get_variable('W6', shape=(500, feature_space_dimension), initializer=tf.glorot_uniform_initializer()),\n }\n self.biases = {\n 'bc1': tf.get_variable('B0', shape=(32), initializer=tf.glorot_uniform_initializer()),\n 'bc2': tf.get_variable('B1', shape=(64), initializer=tf.glorot_uniform_initializer()),\n 'bc3': tf.get_variable('B2', shape=(128), initializer=tf.glorot_uniform_initializer()),\n 'bd1': tf.get_variable('B3', shape=(500), initializer=tf.glorot_uniform_initializer()),\n 'out': tf.get_variable('B4', shape=(feature_space_dimension), initializer=tf.glorot_uniform_initializer()),\n }\n\n self.loss_type = loss_type\n # Create loss\n if self.loss_type == \"triplet\":\n with tf.variable_scope(\"siamese\") as scope:\n self.o1 = self.conv_net(self.x1Image, self.weights, self.biases)\n self.o2 = self.conv_net(self.x2Image, self.weights, self.biases)\n self.o3 = self.conv_net(self.x3Image, self.weights, self.biases)\n self.loss = self.loss_with_spring()\n elif self.loss_type == \"FDA\":\n with tf.variable_scope(\"siamese\") as scope:\n self.o1 = self.conv_net_FDA(self.x1Image, self.weights, self.biases, o_index=1)\n self.o2 = self.conv_net_FDA(self.x2Image, self.weights, self.biases, o_index=2)\n self.o3 = self.conv_net_FDA(self.x3Image, self.weights, self.biases, o_index=3)\n self.loss = self.loss_FDA()\n # self.learning_rate = tf.placeholder(tf.float32, name='learning_rate')\n\n def conv2d(self, x, W, b, strides=1):\n x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')\n x = tf.nn.bias_add(x, b)\n return tf.nn.relu(x)\n\n def maxpool2d(self, x, k=2):\n return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')\n\n def conv_net(self, x, weights, biases):\n conv1 = self.conv2d(x, weights['wc1'], biases['bc1'])\n conv1 = tf.nn.relu(conv1)\n conv1 = self.maxpool2d(conv1, k=2)\n conv2 = self.conv2d(conv1, weights['wc2'], biases['bc2'])\n conv2 = tf.nn.relu(conv2)\n conv2 = self.maxpool2d(conv2, k=2)\n conv3 = self.conv2d(conv2, weights['wc3'], biases['bc3'])\n conv3 = tf.nn.relu(conv3)\n conv3 = self.maxpool2d(conv3, k=2)\n fc1 = tf.reshape(conv3, [-1, weights['wd1'].get_shape().as_list()[0]])\n fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n # fc1 = tf.nn.relu(fc1)\n # fc1 = tf.nn.sigmoid(fc1)\n # finally we multiply the fully connected layer with the weights and add a bias term.\n out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n return out\n\n def conv_net_FDA(self, x, weights, biases, o_index):\n conv1 = self.conv2d(x, weights['wc1'], biases['bc1'])\n conv1 = tf.nn.relu(conv1)\n conv1 = self.maxpool2d(conv1, k=2)\n conv2 = self.conv2d(conv1, weights['wc2'], biases['bc2'])\n conv2 = tf.nn.relu(conv2)\n conv2 = self.maxpool2d(conv2, k=2)\n conv3 = self.conv2d(conv2, weights['wc3'], biases['bc3'])\n conv3 = tf.nn.relu(conv3)\n conv3 = self.maxpool2d(conv3, k=2)\n fc1 = tf.reshape(conv3, [-1, weights['wd1'].get_shape().as_list()[0]])\n fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n if o_index == 1:\n self.o1_output_oneToLastLayer = fc1\n elif o_index == 2:\n self.o2_output_oneToLastLayer = fc1\n elif o_index == 3:\n self.o3_output_oneToLastLayer = fc1\n # fc1 = tf.nn.relu(fc1)\n # fc1 = tf.nn.sigmoid(fc1)\n # finally we multiply the fully connected layer with the weights and add a bias term.\n out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n self.weights_lastLayer = weights['out']\n return out\n\n # def loss_with_spring(self):\n # # margin = 0.2\n # margin = 0.25\n # eucdP = tf.pow(tf.subtract(self.o1, self.o2), 2)\n # pos = tf.reduce_sum(eucdP, 1)\n #\n # eucdN = tf.pow(tf.subtract(self.o1, self.o3), 2)\n # neg = tf.reduce_sum(eucdN, 1)\n #\n # C = tf.constant(margin, name=\"C\")\n # basic_loss = tf.subtract(pos, neg, name=\"loss\")\n # basic_loss = tf.add(basic_loss, C, name=\"loss\")\n # loss = tf.maximum(basic_loss, 0.0)\n #\n # return loss\n\n def loss_with_spring(self):\n d_pos = tf.reduce_sum(tf.square(self.o1 - self.o2), 1)\n d_neg = tf.reduce_sum(tf.square(self.o1 - self.o3), 1)\n\n loss = tf.maximum(0., self.margin_in_loss + d_pos - d_neg)\n loss = tf.reduce_mean(loss)\n\n return loss\n\n def loss_FDA(self):\n # margin = 0.2\n # margin = 0.25\n margin = 10\n\n # calculation of within scatter:\n temp1 = self.o1_output_oneToLastLayer - self.o2_output_oneToLastLayer\n temp1 = tf.transpose(temp1) # --> becomes: rows are features and columns are samples of batch\n S_within = tf.linalg.matmul(a=temp1, b=tf.transpose(temp1))\n\n # calculation of between scatter:\n temp2 = self.o1_output_oneToLastLayer - self.o3_output_oneToLastLayer\n temp2 = tf.transpose(temp2) # --> becomes: rows are features and columns are samples of batch\n S_between = tf.linalg.matmul(a=temp2, b=tf.transpose(temp2))\n\n # calculation of variance of projection considering within scatter:\n temp3 = tf.linalg.matmul(a=tf.transpose(self.weights_lastLayer), b=S_within)\n temp3 = tf.linalg.matmul(a=temp3, b=self.weights_lastLayer)\n within_scatter_term = tf.linalg.trace(temp3)\n\n # calculation of variance of projection considering between scatter:\n temp4 = tf.linalg.matmul(a=tf.transpose(self.weights_lastLayer), b=S_between)\n temp4 = tf.linalg.matmul(a=temp4, b=self.weights_lastLayer)\n between_scatter_term = tf.linalg.trace(temp4)\n\n # calculation of loss:\n loss = tf.math.maximum(0., margin + within_scatter_term - between_scatter_term)\n # loss = within_scatter_term - between_scatter_term + margin\n # loss = (within_scatter_term) / (between_scatter_term)\n # loss = (within_scatter_term + margin) / (between_scatter_term)\n # loss = (within_scatter_term) / (between_scatter_term - margin)\n loss = tf.reduce_mean(loss)\n\n return loss\n\n # def network(self, x):\n # weights = []\n # fc1 = self.fc_layer(x, 1024, \"fc1\")\n # ac1 = tf.nn.relu(fc1)\n # fc2 = self.fc_layer(ac1, 1024, \"fc2\")\n # ac2 = tf.nn.relu(fc2)\n # fc3 = self.fc_layer(ac2, 3, \"fc3\")\n # return fc3\n\n # def fc_layer(self, bottom, n_weight, name):\n # n_prev_weight = bottom.get_shape()[1]\n # initer = tf.truncated_normal_initializer(stddev=0.01)\n # W = tf.get_variable(name+'W', dtype=tf.float32, shape=[n_prev_weight, n_weight], initializer=initer)\n # b = tf.get_variable(name+'b', dtype=tf.float32, initializer=tf.constant(0.01, shape=[n_weight], dtype=tf.float32))\n # fc = tf.nn.bias_add(tf.matmul(bottom, W), b)\n # return fc\n"
]
| [
[
"tensorflow.compat.v1.math.maximum",
"tensorflow.compat.v1.square",
"tensorflow.compat.v1.disable_v2_behavior",
"tensorflow.compat.v1.reduce_mean",
"tensorflow.compat.v1.linalg.trace",
"tensorflow.compat.v1.linalg.matmul",
"tensorflow.compat.v1.nn.conv2d",
"tensorflow.compat.v1.matmul",
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.nn.relu",
"tensorflow.compat.v1.maximum",
"tensorflow.compat.v1.nn.max_pool",
"tensorflow.compat.v1.glorot_uniform_initializer",
"tensorflow.compat.v1.nn.bias_add",
"tensorflow.compat.v1.variable_scope",
"tensorflow.compat.v1.transpose"
]
]
|
vishalbelsare/palladium | [
"3e7bd7d8f38b8ad1a175d0cd387fe5959acbfe2e"
]
| [
"palladium/tests/test_dataset.py"
]
| [
"import os\nfrom threading import Thread\nfrom unittest.mock import MagicMock\nfrom unittest.mock import patch\n\nfrom pandas import DataFrame\nimport pytest\nimport sklearn\n\ndummy_dataframe = DataFrame({\n 'datacol1': [10, 11, 12, 13, 14],\n 'datacol2': [20.0, 21.0, 22.0, 23.0, 24.0],\n 'targetcol': [0, 1, 2, 3, 4],\n })\n\n\nclass TestCSV:\n @pytest.fixture\n def CSV(self):\n from palladium.dataset import CSV\n return CSV\n\n def test_it(self, CSV):\n with patch(\"palladium.dataset.CSV.pandas_read\") as read_csv:\n read_csv.return_value = dummy_dataframe[3:5] # simulate skiprows\n dataset = CSV('mypath', 'targetcol', some='keyword', skiprows=3)\n data, target = dataset()\n\n read_csv.assert_called_with('mypath', some='keyword', skiprows=3)\n assert len(data) == len(target) == 2\n assert data.tolist() == [[13, 23.0], [14, 24.0]]\n assert target.tolist() == [3, 4]\n\n def test_ndarray_false(self, CSV):\n with patch(\"palladium.dataset.CSV.pandas_read\") as read_csv:\n read_csv.return_value = dummy_dataframe[3:5]\n dataset = CSV('mypath', 'targetcol', some='keyword',\n skiprows=3, ndarray=False) # simulate skiprows\n data, target = dataset()\n\n assert data['datacol1'].tolist() == [13, 14]\n assert data['datacol2'].tolist() == [23.0, 24.0]\n assert target.tolist() == [3, 4]\n\n def test_no_slice(self, CSV):\n with patch(\"palladium.dataset.CSV.pandas_read\") as read_csv:\n read_csv.return_value = dummy_dataframe\n dataset = CSV('mypath', 'targetcol', some='keyword')\n data, target = dataset()\n\n read_csv.assert_called_with('mypath', some='keyword')\n assert len(data) == len(target) == len(dummy_dataframe)\n assert data.tolist() == [\n [10, 20.0], [11, 21.0], [12, 22.0], [13, 23.0], [14, 24.0],\n ]\n assert target.tolist() == [0, 1, 2, 3, 4]\n\n def test_no_target(self, CSV):\n with patch(\"palladium.dataset.CSV.pandas_read\") as read_csv:\n read_csv.return_value = dummy_dataframe\n dataset = CSV('mypath', some='keyword')\n data, target = dataset()\n\n read_csv.assert_called_with('mypath', some='keyword')\n assert len(data) == len(dummy_dataframe)\n assert target is None\n\n\nclass TestSQL:\n @pytest.fixture\n def SQL(self):\n from palladium.dataset import SQL\n return SQL\n\n @pytest.fixture\n def sql(self, request, SQL):\n path = '/tmp/palladium.testing-{}.sqlite'.format(os.getpid())\n request.addfinalizer(lambda: os.remove(path))\n sql = SQL(\n url='sqlite:///{}'.format(path),\n sql='select age, weight, salary from employee',\n target_column='salary',\n )\n\n connection = sql.engine.connect()\n connection.execute(\"\"\"\n CREATE TABLE EMPLOYEE (\n id INT PRIMARY KEY,\n name TEXT,\n age INT,\n weight REAL,\n salary REAL\n )\n \"\"\")\n for values in [\n \"(1, 'James', 24, 60.0, 10000.0)\",\n \"(2, 'Guido', 33, 73.0, 20000.0)\",\n \"(3, 'Handsome Jack', 27, 67.5, 35000.0)\",\n ]:\n connection.execute(\n \"INSERT INTO EMPLOYEE VALUES {}\".format(values))\n\n return sql\n\n def test_it(self, sql):\n X, y = sql()\n assert X.tolist() == [\n [24., 60.],\n [33., 73.],\n [27., 67.5],\n ]\n assert y.tolist() == [\n 10000.0,\n 20000.0,\n 35000.0,\n ]\n\n def test_ndarray_false(self, sql):\n sql.ndarray = False\n X, y = sql()\n assert X.values.tolist() == [\n [24., 60.],\n [33., 73.],\n [27., 67.5],\n ]\n assert y.values.tolist() == [\n 10000.0,\n 20000.0,\n 35000.0,\n ]\n\n def test_concurrency(self, sql):\n threads = [Thread(target=sql) for i in range(5)]\n [th.start() for th in threads]\n [th.join() for th in threads]\n\n\[email protected](sklearn.__version__ < \"0.20.1\",\n reason=\"scikit-learn version too old\")\nclass TestOpenML:\n @pytest.fixture\n def OpenML(self):\n from palladium.dataset import OpenML\n return OpenML\n\n @pytest.mark.slow\n def test_wine_quality(self, OpenML):\n X, y = OpenML('wine-quality-red')()\n assert X.shape == (1599, 11)\n assert y.shape == (1599,)\n\n\ndef test_empty_dataset_loader():\n from palladium.dataset import EmptyDatasetLoader\n edl = EmptyDatasetLoader()\n X, y = edl()\n assert X is None\n assert y is None\n\n\nclass TestScheduledDatasetLoader:\n @pytest.fixture\n def ScheduledDatasetLoader(self, process_store):\n from palladium.dataset import ScheduledDatasetLoader\n return ScheduledDatasetLoader\n\n @pytest.fixture\n def loader(self, ScheduledDatasetLoader, config):\n loader = ScheduledDatasetLoader(\n MagicMock(),\n {\n 'freq': 'DAILY',\n 'dtstart': '2014-10-30T13:21:18',\n },\n )\n loader.initialize_component(config)\n return loader\n\n def test_call(self, process_store, loader):\n assert loader() is loader.impl.return_value\n\n def test_call_custom_value(self, process_store, loader):\n process_store['data'] = ('X', 'y')\n assert loader() == ('X', 'y')\n\n def test_update_cache(self, loader):\n loader.impl.return_value = ('bla', 'bla')\n assert loader.update_cache() == ('bla', 'bla')\n assert loader() == ('bla', 'bla')\n assert loader.impl.call_count == 2\n"
]
| [
[
"pandas.DataFrame"
]
]
|
xiedidan/sparse-coding | [
"36fb106217382dedbbea9234b10e02b0505d9b50"
]
| [
"src/model/SparseNet.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass SparseNet(nn.Module):\n\n def __init__(self, K:int, M:int, R_lr:float=0.1, lmda:float=5e-3, device=None):\n super(SparseNet, self).__init__()\n self.K = K\n self.M = M\n self.R_lr = R_lr\n self.lmda = lmda\n \n # synaptic weights\n self.device = torch.device(\"cpu\") if device is None else device\n self.U = nn.Linear(self.K, self.M ** 2, bias=False).to(self.device)\n \n # responses\n self.R = None\n self.normalize_weights()\n \n self.r_loss = None\n\n def ista_(self, img_batch):\n # create R\n self.R = torch.zeros((img_batch.shape[0], self.K), requires_grad=True, device=self.device)\n self.r_loss = torch.zeros_like(img_batch)\n \n converged = False\n \n # update R\n optim = torch.optim.Adam([{'params': self.R, \"lr\": self.R_lr}])\n \n # train\n while not converged:\n old_R = self.R.clone().detach()\n \n # pred\n pred = self.U(self.R)\n \n # loss\n loss = ((img_batch - pred) ** 2)\n self.r_loss = loss.cpu().detach()\n loss = loss.sum()\n loss.backward()\n \n # update R in place\n optim.step()\n \n # zero grad\n self.zero_grad()\n \n # prox\n self.R.data = SparseNet.soft_thresholding_(self.R, self.lmda)\n \n # convergence\n converged = torch.norm(self.R - old_R) / torch.norm(old_R) < 0.01\n\n @staticmethod\n def soft_thresholding_(x, alpha):\n with torch.no_grad():\n rtn = F.relu(x - alpha) - F.relu(-x - alpha)\n \n return rtn.data\n\n def zero_grad(self):\n self.R.grad.zero_()\n self.U.zero_grad()\n\n def normalize_weights(self):\n with torch.no_grad():\n self.U.weight.data = F.normalize(self.U.weight.data, dim=0)\n\n def forward(self, img_batch):\n # first fit\n self.ista_(img_batch)\n \n # now predict again\n pred = self.U(self.R)\n \n return pred\n\n\n"
]
| [
[
"torch.optim.Adam",
"torch.nn.functional.normalize",
"torch.norm",
"torch.zeros",
"torch.zeros_like",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.no_grad",
"torch.device"
]
]
|
aliciawyy/sheep | [
"b21231dfdaee63d3f868421cba2a50be26c513f4"
]
| [
"sheepts/data.py"
]
| [
"from os import path, walk\nimport pandas as pd\n\n\nclass CsvDataHandler(object):\n _suffix = \".csv\"\n\n def __init__(self, data_dir):\n self.data_dir = data_dir\n\n def get_time_series_data(self, ticker):\n filename = ticker + self._suffix\n for dir_path, dir_names, filenames in walk(self.data_dir):\n if filename in set(filenames):\n return read_time_series_csv(path.join(dir_path, filename))\n\n\ndef read_time_series_csv(filename):\n return pd.read_csv(filename, header=0, parse_dates=True, index_col=0)\n"
]
| [
[
"pandas.read_csv"
]
]
|
sneznaj/graspologic | [
"640811efb64061fee3b6ff7c94b2179aeabc0e4a"
]
| [
"graspologic/datasets/base.py"
]
| [
"# Copyright (c) Microsoft Corporation and contributors.\n# Licensed under the MIT License.\n\nfrom os.path import dirname, join\nfrom pathlib import Path\nfrom typing import Tuple, Union\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.utils import Bunch\n\nfrom ..utils import import_edgelist\n\n\ndef load_drosophila_left(\n return_labels: bool = False,\n) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:\n \"\"\"\n Load the left Drosophila larva mushroom body connectome\n\n The mushroom body is a learning and memory center in the fly\n brain which is involved in sensory integration and processing.\n This connectome was observed by electron microscopy and then\n individial neurons were reconstructed; synaptic partnerships\n between these neurons became the edges of the graph.\n\n Parameters\n ----------\n return_labels : bool, optional (default=False)\n whether to have a second return value which is an array of\n cell type labels for each node in the adjacency matrix\n\n Returns\n -------\n graph : np.ndarray\n Adjacency matrix of the connectome\n labels : np.ndarray\n Only returned if ``return_labels`` is true. Array of\n string labels for each cell (vertex)\n\n References\n ----------\n .. [1] Eichler, K., Li, F., Litwin-Kumar, A., Park, Y., Andrade, I.,\n Schneider-Mizell, C. M., ... & Fetter, R. D. (2017). The\n complete connectome of a learning and memory centre in an insect\n brain. Nature, 548(7666), 175.\n \"\"\"\n\n module_path = dirname(__file__)\n folder = \"drosophila\"\n filename = \"left_adjacency.csv\"\n with open(join(module_path, folder, filename)) as csv_file:\n graph = np.loadtxt(csv_file, dtype=int)\n if return_labels:\n filename = \"left_cell_labels.csv\"\n with open(join(module_path, folder, filename)) as csv_file:\n labels = np.loadtxt(csv_file, dtype=str)\n return graph, labels\n else:\n return graph\n\n\ndef load_drosophila_right(\n return_labels: bool = False,\n) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:\n \"\"\"\n Load the right Drosophila larva mushroom body connectome\n\n The mushroom body is a learning and memory center in the fly\n brain which is involved in sensory integration and processing.\n This connectome was observed by electron microscopy and then\n individial neurons were reconstructed; synaptic partnerships\n between these neurons became the edges of the graph.\n\n Parameters\n ----------\n return_labels : bool, optional (default=False)\n whether to have a second return value which is an array of\n cell type labels for each node in the adjacency matrix\n\n Returns\n -------\n graph : np.ndarray\n Adjacency matrix of the connectome\n labels : np.ndarray\n Only returned if ``return_labels`` is true. Array of\n string labels for each cell (vertex)\n\n References\n ----------\n .. [1] Eichler, K., Li, F., Litwin-Kumar, A., Park, Y., Andrade, I.,\n Schneider-Mizell, C. M., ... & Fetter, R. D. (2017). The\n complete connectome of a learning and memory centre in an insect\n brain. Nature, 548(7666), 175.\n \"\"\"\n\n module_path = dirname(__file__)\n folder = \"drosophila\"\n filename = \"right_adjacency.csv\"\n with open(join(module_path, folder, filename)) as csv_file:\n graph = np.loadtxt(csv_file, dtype=int)\n if return_labels:\n filename = \"right_cell_labels.csv\"\n with open(join(module_path, folder, filename)) as csv_file:\n labels = np.loadtxt(csv_file, dtype=str)\n return graph, labels\n else:\n return graph\n\n\ndef load_mice() -> Bunch:\n \"\"\"\n Load connectomes of mice from distinct genotypes.\n\n Dataset of 32 mouse connectomes derived from whole-brain diffusion\n magnetic resonance imaging of four distinct mouse genotypes:\n BTBR T+ Itpr3tf/J (BTBR), C57BL/6J(B6), CAST/EiJ (CAST), and DBA/2J (DBA2).\n For each strain, connectomes were generated from eight age-matched mice\n (N = 8 per strain), with a sex distribution of four males and four females.\n Each connectome was parcellated using asymmetric Waxholm Space, yielding a\n vertex set with a total of 332 regions of interest (ROIs) symmetrically\n distributed across the left and right hemispheres. Within a given\n hemisphere, there are seven superstructures consisting up multiple ROIs,\n resulting in a total of 14 distinct communities in each connectome.\n\n Returns\n -------\n data : :class:`~sklearn.utils.Bunch`\n Dictionary-like object, with the following attributes.\n\n graphs : list of np.ndarray\n List of adjacency matrices of the connectome\n labels : np.ndarray\n Array of string labels for each mouse (subject)\n atlas : pd.DataFrame\n DataFrame of information for each ROI\n blocks : pd.DataFrame\n DataFrame of block assignments for each ROI\n features : pd.DataFrame\n DataFrame of anatomical features for each ROI in each connectome\n participants : pd.DataFrame\n DataFrame of subject IDs and genotypes for each connectome\n meta : Dictionary\n Dictionary with meta information about the dataset (n_subjects and n_vertices)\n\n References\n ----------\n .. [1] Wang, N., Anderson, R. J., Ashbrook, D. G., Gopalakrishnan, V.,\n Park, Y., Priebe, C. E., ... & Johnson, G. A. (2020). Variability\n and heritability of mouse brain structure: Microscopic MRI atlases\n and connectomes for diverse strains. NeuroImage.\n https://doi.org/10.1016/j.neuroimage.2020.117274\n \"\"\"\n\n data = Path(__file__).parent.joinpath(\"mice\")\n\n # Load all connectomes and construct a dictionary of study metadata\n graphs, vertices = import_edgelist(data.joinpath(\"edgelists\"), return_vertices=True)\n\n n_vertices = len(vertices)\n n_subjects = len(graphs)\n meta = {\"n_subjects\": n_subjects, \"n_vertices\": n_vertices}\n\n # Read the participants file and get genotype labels\n participants = pd.read_csv(data.joinpath(\"participants.csv\"))\n labels = participants[\"genotype\"].values\n\n # Read the atlas and block information\n atlas = pd.read_csv(data.joinpath(\"atlas.csv\"))\n blocks = pd.read_csv(data.joinpath(\"blocks.csv\"))\n\n # Read features\n tmp = []\n for fl in data.joinpath(\"features\").glob(\"*\" + \"csv\"):\n subid = fl.stem\n df = pd.read_csv(fl, skiprows=2)\n df[\"participant_id\"] = subid\n tmp.append(df)\n features = pd.concat(tmp, axis=0)\n features = features.reset_index(drop=True)\n\n return Bunch(\n graphs=graphs,\n labels=labels,\n atlas=atlas,\n blocks=blocks,\n features=features,\n participants=participants,\n meta=meta,\n )\n"
]
| [
[
"pandas.concat",
"pandas.read_csv",
"sklearn.utils.Bunch",
"numpy.loadtxt"
]
]
|
floraaws/quickstart-aws-utility-meter-data-analytics-platform | [
"47e94e76ecf67c5b437b80dfca0ed0d00e868d94"
]
| [
"assets/functions/meter_forecast/app.py"
]
| [
"'''\nTesting event\n{\n \"Data_start\": \"2013-06-01\",\n \"Data_end\": \"2014-01-01\",\n \"Meter_id\": \"MAC004534\",\n \"ML_endpoint_name\": \"ml-endpoint-0001\"\n}\n'''\n\nimport boto3, os\nimport pandas as pd\nimport numpy as np\nimport json\nfrom pyathena import connect\n\nREGION = os.environ['AWS_REGION']\nWORKING_BUCKET = os.environ['WORKING_BUCKET']\nATHENA_OUTPUT_BUCKET = os.environ['Athena_bucket']\nDB_SCHEMA = os.environ['Db_schema']\nUSE_WEATHER_DATA = os.environ['With_weather_data']\n\nS3 = boto3.client('s3')\nSAGEMAKER = boto3.client('runtime.sagemaker')\n\n\ndef get_weather(connection, start, db_schema):\n weather_data = '''select date_parse(time,'%Y-%m-%d %H:%i:%s') as datetime, temperature,\n apparenttemperature, humidity\n from \"{}\".weather\n where time >= '{}'\n order by 1;\n '''.format(db_schema, start)\n df_weather = pd.read_sql(weather_data, connection)\n df_weather = df_weather.set_index('datetime')\n return df_weather\n\n\ndef encode_request(ts, weather):\n instance = {\n \"start\": str(ts.index[0]),\n \"target\": [x if np.isfinite(x) else \"NaN\" for x in ts]\n }\n if weather is not None:\n instance[\"dynamic_feat\"] = [weather['temperature'].tolist(),\n weather['humidity'].tolist(),\n weather['apparenttemperature'].tolist()]\n\n configuration = {\n \"num_samples\": 100,\n \"output_types\": [\"quantiles\"],\n \"quantiles\": [\"0.9\"]\n }\n\n http_request_data = {\n \"instances\": [instance],\n \"configuration\": configuration\n }\n\n return json.dumps(http_request_data).encode('utf-8')\n\n\ndef decode_response(response, freq, prediction_time):\n predictions = json.loads(response.decode('utf-8'))['predictions'][0]\n prediction_length = len(next(iter(predictions['quantiles'].values())))\n prediction_index = pd.date_range(start=prediction_time,\n end=prediction_time + pd.Timedelta(prediction_length - 1, unit='H'), freq=freq)\n dict_of_samples = {}\n return pd.DataFrame(data={**predictions['quantiles'], **dict_of_samples}, index=prediction_index)\n\n\ndef load_json_from_file(bucket, path):\n data = S3.get_object(Bucket=bucket, Key=path)\n\n return json.load(data['Body'])\n\n\n# expect request: forecast/{meter_id}?ml_endpoint_name={}&data_start={}&data_end={}\ndef lambda_handler(event, context):\n pathParameter = event[\"pathParameters\"]\n queryParameter = event[\"queryStringParameters\"]\n\n if (\"meter_id\" not in pathParameter) \\\n or (\"data_start\" not in queryParameter) \\\n or (\"data_end\" not in queryParameter):\n return {\n 'statusCode': 400,\n 'body': \"error: meter_id, data_start, and data_end needs to be provided.\"\n }\n\n meter_id = pathParameter['meter_id']\n ml_endpoint_name = load_json_from_file(WORKING_BUCKET, \"meteranalytics/initial_pass\")[\"ML_endpoint_name\"]\n data_start = queryParameter['data_start']\n data_end = queryParameter['data_end']\n\n connection = connect(s3_staging_dir='s3://{}/'.format(ATHENA_OUTPUT_BUCKET), region_name=REGION)\n query = '''select date_trunc('HOUR', reading_date_time) as datetime, sum(reading_value) as consumption\n from \"{}\".daily\n where meter_id = '{}' and reading_date_time >= timestamp '{}'\n and reading_date_time < timestamp '{}'\n and reading_type = 'INT'\n group by 1;\n '''.format(DB_SCHEMA, meter_id, data_start, data_end)\n result = pd.read_sql(query, connection)\n result = result.set_index('datetime')\n\n data_kw = result.resample('1H').sum()\n timeseries = data_kw.iloc[:, 0] # np.trim_zeros(data_kw.iloc[:,0], trim='f')\n\n freq = 'H'\n df_weather = None\n if USE_WEATHER_DATA == 1:\n df_weather = get_weather(connection, data_start, DB_SCHEMA)\n\n response = SAGEMAKER.invoke_endpoint(EndpointName=ml_endpoint_name,\n ContentType='application/json',\n Body=encode_request(timeseries[:], df_weather))\n prediction_time = timeseries.index[-1] + pd.Timedelta(1, unit='H')\n df_prediction = decode_response(response['Body'].read(), freq, prediction_time)\n\n df_prediction.columns = ['consumption']\n prediction_result = df_prediction.to_json()\n\n return {\n \"statusCode\": 200,\n \"body\": prediction_result\n }\n"
]
| [
[
"pandas.Timedelta",
"numpy.isfinite",
"pandas.read_sql",
"pandas.DataFrame"
]
]
|
fruchart/numpy | [
"bf20e3034085716c4559ec4bf31b23b6016f266c"
]
| [
"numpy/core/tests/test_numeric.py"
]
| [
"from __future__ import division, absolute_import, print_function\n\nimport sys\nimport warnings\nimport itertools\nimport platform\nimport pytest\nfrom decimal import Decimal\n\nimport numpy as np\nfrom numpy.core import umath\nfrom numpy.random import rand, randint, randn\nfrom numpy.testing import (\n assert_, assert_equal, assert_raises, assert_raises_regex,\n assert_array_equal, assert_almost_equal, assert_array_almost_equal,\n HAS_REFCOUNT\n )\n\n\nclass TestResize(object):\n def test_copies(self):\n A = np.array([[1, 2], [3, 4]])\n Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]])\n assert_equal(np.resize(A, (2, 4)), Ar1)\n\n Ar2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])\n assert_equal(np.resize(A, (4, 2)), Ar2)\n\n Ar3 = np.array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]])\n assert_equal(np.resize(A, (4, 3)), Ar3)\n\n def test_zeroresize(self):\n A = np.array([[1, 2], [3, 4]])\n Ar = np.resize(A, (0,))\n assert_array_equal(Ar, np.array([]))\n assert_equal(A.dtype, Ar.dtype)\n\n Ar = np.resize(A, (0, 2))\n assert_equal(Ar.shape, (0, 2))\n\n Ar = np.resize(A, (2, 0))\n assert_equal(Ar.shape, (2, 0))\n\n def test_reshape_from_zero(self):\n # See also gh-6740\n A = np.zeros(0, dtype=[('a', np.float32, 1)])\n Ar = np.resize(A, (2, 1))\n assert_array_equal(Ar, np.zeros((2, 1), Ar.dtype))\n assert_equal(A.dtype, Ar.dtype)\n\n\nclass TestNonarrayArgs(object):\n # check that non-array arguments to functions wrap them in arrays\n def test_choose(self):\n choices = [[0, 1, 2],\n [3, 4, 5],\n [5, 6, 7]]\n tgt = [5, 1, 5]\n a = [2, 0, 1]\n\n out = np.choose(a, choices)\n assert_equal(out, tgt)\n\n def test_clip(self):\n arr = [-1, 5, 2, 3, 10, -4, -9]\n out = np.clip(arr, 2, 7)\n tgt = [2, 5, 2, 3, 7, 2, 2]\n assert_equal(out, tgt)\n\n def test_compress(self):\n arr = [[0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9]]\n tgt = [[5, 6, 7, 8, 9]]\n out = np.compress([0, 1], arr, axis=0)\n assert_equal(out, tgt)\n\n def test_count_nonzero(self):\n arr = [[0, 1, 7, 0, 0],\n [3, 0, 0, 2, 19]]\n tgt = np.array([2, 3])\n out = np.count_nonzero(arr, axis=1)\n assert_equal(out, tgt)\n\n def test_cumproduct(self):\n A = [[1, 2, 3], [4, 5, 6]]\n assert_(np.all(np.cumproduct(A) == np.array([1, 2, 6, 24, 120, 720])))\n\n def test_diagonal(self):\n a = [[0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11]]\n out = np.diagonal(a)\n tgt = [0, 5, 10]\n\n assert_equal(out, tgt)\n\n def test_mean(self):\n A = [[1, 2, 3], [4, 5, 6]]\n assert_(np.mean(A) == 3.5)\n assert_(np.all(np.mean(A, 0) == np.array([2.5, 3.5, 4.5])))\n assert_(np.all(np.mean(A, 1) == np.array([2., 5.])))\n\n with warnings.catch_warnings(record=True) as w:\n warnings.filterwarnings('always', '', RuntimeWarning)\n assert_(np.isnan(np.mean([])))\n assert_(w[0].category is RuntimeWarning)\n\n def test_ptp(self):\n a = [3, 4, 5, 10, -3, -5, 6.0]\n assert_equal(np.ptp(a, axis=0), 15.0)\n\n def test_prod(self):\n arr = [[1, 2, 3, 4],\n [5, 6, 7, 9],\n [10, 3, 4, 5]]\n tgt = [24, 1890, 600]\n\n assert_equal(np.prod(arr, axis=-1), tgt)\n\n def test_ravel(self):\n a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]\n tgt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n assert_equal(np.ravel(a), tgt)\n\n def test_repeat(self):\n a = [1, 2, 3]\n tgt = [1, 1, 2, 2, 3, 3]\n\n out = np.repeat(a, 2)\n assert_equal(out, tgt)\n\n def test_reshape(self):\n arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]\n tgt = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]\n assert_equal(np.reshape(arr, (2, 6)), tgt)\n\n def test_round(self):\n arr = [1.56, 72.54, 6.35, 3.25]\n tgt = [1.6, 72.5, 6.4, 3.2]\n assert_equal(np.around(arr, decimals=1), tgt)\n\n def test_searchsorted(self):\n arr = [-8, -5, -1, 3, 6, 10]\n out = np.searchsorted(arr, 0)\n assert_equal(out, 3)\n\n def test_size(self):\n A = [[1, 2, 3], [4, 5, 6]]\n assert_(np.size(A) == 6)\n assert_(np.size(A, 0) == 2)\n assert_(np.size(A, 1) == 3)\n\n def test_squeeze(self):\n A = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]]]\n assert_equal(np.squeeze(A).shape, (3, 3))\n assert_equal(np.squeeze(np.zeros((1, 3, 1))).shape, (3,))\n assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=0).shape, (3, 1))\n assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=-1).shape, (1, 3))\n assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=2).shape, (1, 3))\n assert_equal(np.squeeze([np.zeros((3, 1))]).shape, (3,))\n assert_equal(np.squeeze([np.zeros((3, 1))], axis=0).shape, (3, 1))\n assert_equal(np.squeeze([np.zeros((3, 1))], axis=2).shape, (1, 3))\n assert_equal(np.squeeze([np.zeros((3, 1))], axis=-1).shape, (1, 3))\n\n def test_std(self):\n A = [[1, 2, 3], [4, 5, 6]]\n assert_almost_equal(np.std(A), 1.707825127659933)\n assert_almost_equal(np.std(A, 0), np.array([1.5, 1.5, 1.5]))\n assert_almost_equal(np.std(A, 1), np.array([0.81649658, 0.81649658]))\n\n with warnings.catch_warnings(record=True) as w:\n warnings.filterwarnings('always', '', RuntimeWarning)\n assert_(np.isnan(np.std([])))\n assert_(w[0].category is RuntimeWarning)\n\n def test_swapaxes(self):\n tgt = [[[0, 4], [2, 6]], [[1, 5], [3, 7]]]\n a = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]\n out = np.swapaxes(a, 0, 2)\n assert_equal(out, tgt)\n\n def test_sum(self):\n m = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n tgt = [[6], [15], [24]]\n out = np.sum(m, axis=1, keepdims=True)\n\n assert_equal(tgt, out)\n\n def test_take(self):\n tgt = [2, 3, 5]\n indices = [1, 2, 4]\n a = [1, 2, 3, 4, 5]\n\n out = np.take(a, indices)\n assert_equal(out, tgt)\n\n def test_trace(self):\n c = [[1, 2], [3, 4], [5, 6]]\n assert_equal(np.trace(c), 5)\n\n def test_transpose(self):\n arr = [[1, 2], [3, 4], [5, 6]]\n tgt = [[1, 3, 5], [2, 4, 6]]\n assert_equal(np.transpose(arr, (1, 0)), tgt)\n\n def test_var(self):\n A = [[1, 2, 3], [4, 5, 6]]\n assert_almost_equal(np.var(A), 2.9166666666666665)\n assert_almost_equal(np.var(A, 0), np.array([2.25, 2.25, 2.25]))\n assert_almost_equal(np.var(A, 1), np.array([0.66666667, 0.66666667]))\n\n with warnings.catch_warnings(record=True) as w:\n warnings.filterwarnings('always', '', RuntimeWarning)\n assert_(np.isnan(np.var([])))\n assert_(w[0].category is RuntimeWarning)\n\n B = np.array([None, 0])\n B[0] = 1j\n assert_almost_equal(np.var(B), 0.25)\n\nclass TestIsscalar(object):\n def test_isscalar(self):\n assert_(np.isscalar(3.1))\n assert_(np.isscalar(np.int16(12345)))\n assert_(np.isscalar(False))\n assert_(np.isscalar('numpy'))\n assert_(not np.isscalar([3.1]))\n assert_(not np.isscalar(None))\n\n # PEP 3141\n from fractions import Fraction\n assert_(np.isscalar(Fraction(5, 17)))\n from numbers import Number\n assert_(np.isscalar(Number()))\n\n\nclass TestBoolScalar(object):\n def test_logical(self):\n f = np.False_\n t = np.True_\n s = \"xyz\"\n assert_((t and s) is s)\n assert_((f and s) is f)\n\n def test_bitwise_or(self):\n f = np.False_\n t = np.True_\n assert_((t | t) is t)\n assert_((f | t) is t)\n assert_((t | f) is t)\n assert_((f | f) is f)\n\n def test_bitwise_and(self):\n f = np.False_\n t = np.True_\n assert_((t & t) is t)\n assert_((f & t) is f)\n assert_((t & f) is f)\n assert_((f & f) is f)\n\n def test_bitwise_xor(self):\n f = np.False_\n t = np.True_\n assert_((t ^ t) is f)\n assert_((f ^ t) is t)\n assert_((t ^ f) is t)\n assert_((f ^ f) is f)\n\n\nclass TestBoolArray(object):\n def setup(self):\n # offset for simd tests\n self.t = np.array([True] * 41, dtype=bool)[1::]\n self.f = np.array([False] * 41, dtype=bool)[1::]\n self.o = np.array([False] * 42, dtype=bool)[2::]\n self.nm = self.f.copy()\n self.im = self.t.copy()\n self.nm[3] = True\n self.nm[-2] = True\n self.im[3] = False\n self.im[-2] = False\n\n def test_all_any(self):\n assert_(self.t.all())\n assert_(self.t.any())\n assert_(not self.f.all())\n assert_(not self.f.any())\n assert_(self.nm.any())\n assert_(self.im.any())\n assert_(not self.nm.all())\n assert_(not self.im.all())\n # check bad element in all positions\n for i in range(256 - 7):\n d = np.array([False] * 256, dtype=bool)[7::]\n d[i] = True\n assert_(np.any(d))\n e = np.array([True] * 256, dtype=bool)[7::]\n e[i] = False\n assert_(not np.all(e))\n assert_array_equal(e, ~d)\n # big array test for blocked libc loops\n for i in list(range(9, 6000, 507)) + [7764, 90021, -10]:\n d = np.array([False] * 100043, dtype=bool)\n d[i] = True\n assert_(np.any(d), msg=\"%r\" % i)\n e = np.array([True] * 100043, dtype=bool)\n e[i] = False\n assert_(not np.all(e), msg=\"%r\" % i)\n\n def test_logical_not_abs(self):\n assert_array_equal(~self.t, self.f)\n assert_array_equal(np.abs(~self.t), self.f)\n assert_array_equal(np.abs(~self.f), self.t)\n assert_array_equal(np.abs(self.f), self.f)\n assert_array_equal(~np.abs(self.f), self.t)\n assert_array_equal(~np.abs(self.t), self.f)\n assert_array_equal(np.abs(~self.nm), self.im)\n np.logical_not(self.t, out=self.o)\n assert_array_equal(self.o, self.f)\n np.abs(self.t, out=self.o)\n assert_array_equal(self.o, self.t)\n\n def test_logical_and_or_xor(self):\n assert_array_equal(self.t | self.t, self.t)\n assert_array_equal(self.f | self.f, self.f)\n assert_array_equal(self.t | self.f, self.t)\n assert_array_equal(self.f | self.t, self.t)\n np.logical_or(self.t, self.t, out=self.o)\n assert_array_equal(self.o, self.t)\n assert_array_equal(self.t & self.t, self.t)\n assert_array_equal(self.f & self.f, self.f)\n assert_array_equal(self.t & self.f, self.f)\n assert_array_equal(self.f & self.t, self.f)\n np.logical_and(self.t, self.t, out=self.o)\n assert_array_equal(self.o, self.t)\n assert_array_equal(self.t ^ self.t, self.f)\n assert_array_equal(self.f ^ self.f, self.f)\n assert_array_equal(self.t ^ self.f, self.t)\n assert_array_equal(self.f ^ self.t, self.t)\n np.logical_xor(self.t, self.t, out=self.o)\n assert_array_equal(self.o, self.f)\n\n assert_array_equal(self.nm & self.t, self.nm)\n assert_array_equal(self.im & self.f, False)\n assert_array_equal(self.nm & True, self.nm)\n assert_array_equal(self.im & False, self.f)\n assert_array_equal(self.nm | self.t, self.t)\n assert_array_equal(self.im | self.f, self.im)\n assert_array_equal(self.nm | True, self.t)\n assert_array_equal(self.im | False, self.im)\n assert_array_equal(self.nm ^ self.t, self.im)\n assert_array_equal(self.im ^ self.f, self.im)\n assert_array_equal(self.nm ^ True, self.im)\n assert_array_equal(self.im ^ False, self.im)\n\n\nclass TestBoolCmp(object):\n def setup(self):\n self.f = np.ones(256, dtype=np.float32)\n self.ef = np.ones(self.f.size, dtype=bool)\n self.d = np.ones(128, dtype=np.float64)\n self.ed = np.ones(self.d.size, dtype=bool)\n # generate values for all permutation of 256bit simd vectors\n s = 0\n for i in range(32):\n self.f[s:s+8] = [i & 2**x for x in range(8)]\n self.ef[s:s+8] = [(i & 2**x) != 0 for x in range(8)]\n s += 8\n s = 0\n for i in range(16):\n self.d[s:s+4] = [i & 2**x for x in range(4)]\n self.ed[s:s+4] = [(i & 2**x) != 0 for x in range(4)]\n s += 4\n\n self.nf = self.f.copy()\n self.nd = self.d.copy()\n self.nf[self.ef] = np.nan\n self.nd[self.ed] = np.nan\n\n self.inff = self.f.copy()\n self.infd = self.d.copy()\n self.inff[::3][self.ef[::3]] = np.inf\n self.infd[::3][self.ed[::3]] = np.inf\n self.inff[1::3][self.ef[1::3]] = -np.inf\n self.infd[1::3][self.ed[1::3]] = -np.inf\n self.inff[2::3][self.ef[2::3]] = np.nan\n self.infd[2::3][self.ed[2::3]] = np.nan\n self.efnonan = self.ef.copy()\n self.efnonan[2::3] = False\n self.ednonan = self.ed.copy()\n self.ednonan[2::3] = False\n\n self.signf = self.f.copy()\n self.signd = self.d.copy()\n self.signf[self.ef] *= -1.\n self.signd[self.ed] *= -1.\n self.signf[1::6][self.ef[1::6]] = -np.inf\n self.signd[1::6][self.ed[1::6]] = -np.inf\n self.signf[3::6][self.ef[3::6]] = -np.nan\n self.signd[3::6][self.ed[3::6]] = -np.nan\n self.signf[4::6][self.ef[4::6]] = -0.\n self.signd[4::6][self.ed[4::6]] = -0.\n\n def test_float(self):\n # offset for alignment test\n for i in range(4):\n assert_array_equal(self.f[i:] > 0, self.ef[i:])\n assert_array_equal(self.f[i:] - 1 >= 0, self.ef[i:])\n assert_array_equal(self.f[i:] == 0, ~self.ef[i:])\n assert_array_equal(-self.f[i:] < 0, self.ef[i:])\n assert_array_equal(-self.f[i:] + 1 <= 0, self.ef[i:])\n r = self.f[i:] != 0\n assert_array_equal(r, self.ef[i:])\n r2 = self.f[i:] != np.zeros_like(self.f[i:])\n r3 = 0 != self.f[i:]\n assert_array_equal(r, r2)\n assert_array_equal(r, r3)\n # check bool == 0x1\n assert_array_equal(r.view(np.int8), r.astype(np.int8))\n assert_array_equal(r2.view(np.int8), r2.astype(np.int8))\n assert_array_equal(r3.view(np.int8), r3.astype(np.int8))\n\n # isnan on amd64 takes the same code path\n assert_array_equal(np.isnan(self.nf[i:]), self.ef[i:])\n assert_array_equal(np.isfinite(self.nf[i:]), ~self.ef[i:])\n assert_array_equal(np.isfinite(self.inff[i:]), ~self.ef[i:])\n assert_array_equal(np.isinf(self.inff[i:]), self.efnonan[i:])\n assert_array_equal(np.signbit(self.signf[i:]), self.ef[i:])\n\n def test_double(self):\n # offset for alignment test\n for i in range(2):\n assert_array_equal(self.d[i:] > 0, self.ed[i:])\n assert_array_equal(self.d[i:] - 1 >= 0, self.ed[i:])\n assert_array_equal(self.d[i:] == 0, ~self.ed[i:])\n assert_array_equal(-self.d[i:] < 0, self.ed[i:])\n assert_array_equal(-self.d[i:] + 1 <= 0, self.ed[i:])\n r = self.d[i:] != 0\n assert_array_equal(r, self.ed[i:])\n r2 = self.d[i:] != np.zeros_like(self.d[i:])\n r3 = 0 != self.d[i:]\n assert_array_equal(r, r2)\n assert_array_equal(r, r3)\n # check bool == 0x1\n assert_array_equal(r.view(np.int8), r.astype(np.int8))\n assert_array_equal(r2.view(np.int8), r2.astype(np.int8))\n assert_array_equal(r3.view(np.int8), r3.astype(np.int8))\n\n # isnan on amd64 takes the same code path\n assert_array_equal(np.isnan(self.nd[i:]), self.ed[i:])\n assert_array_equal(np.isfinite(self.nd[i:]), ~self.ed[i:])\n assert_array_equal(np.isfinite(self.infd[i:]), ~self.ed[i:])\n assert_array_equal(np.isinf(self.infd[i:]), self.ednonan[i:])\n assert_array_equal(np.signbit(self.signd[i:]), self.ed[i:])\n\n\nclass TestSeterr(object):\n def test_default(self):\n err = np.geterr()\n assert_equal(err,\n dict(divide='warn',\n invalid='warn',\n over='warn',\n under='ignore')\n )\n\n def test_set(self):\n with np.errstate():\n err = np.seterr()\n old = np.seterr(divide='print')\n assert_(err == old)\n new = np.seterr()\n assert_(new['divide'] == 'print')\n np.seterr(over='raise')\n assert_(np.geterr()['over'] == 'raise')\n assert_(new['divide'] == 'print')\n np.seterr(**old)\n assert_(np.geterr() == old)\n\n @pytest.mark.skipif(platform.machine() == \"armv5tel\", reason=\"See gh-413.\")\n def test_divide_err(self):\n with np.errstate(divide='raise'):\n with assert_raises(FloatingPointError):\n np.array([1.]) / np.array([0.])\n\n np.seterr(divide='ignore')\n np.array([1.]) / np.array([0.])\n\n def test_errobj(self):\n olderrobj = np.geterrobj()\n self.called = 0\n try:\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n with np.errstate(divide='warn'):\n np.seterrobj([20000, 1, None])\n np.array([1.]) / np.array([0.])\n assert_equal(len(w), 1)\n\n def log_err(*args):\n self.called += 1\n extobj_err = args\n assert_(len(extobj_err) == 2)\n assert_(\"divide\" in extobj_err[0])\n\n with np.errstate(divide='ignore'):\n np.seterrobj([20000, 3, log_err])\n np.array([1.]) / np.array([0.])\n assert_equal(self.called, 1)\n\n np.seterrobj(olderrobj)\n with np.errstate(divide='ignore'):\n np.divide(1., 0., extobj=[20000, 3, log_err])\n assert_equal(self.called, 2)\n finally:\n np.seterrobj(olderrobj)\n del self.called\n\n def test_errobj_noerrmask(self):\n # errmask = 0 has a special code path for the default\n olderrobj = np.geterrobj()\n try:\n # set errobj to something non default\n np.seterrobj([umath.UFUNC_BUFSIZE_DEFAULT,\n umath.ERR_DEFAULT + 1, None])\n # call a ufunc\n np.isnan(np.array([6]))\n # same with the default, lots of times to get rid of possible\n # pre-existing stack in the code\n for i in range(10000):\n np.seterrobj([umath.UFUNC_BUFSIZE_DEFAULT, umath.ERR_DEFAULT,\n None])\n np.isnan(np.array([6]))\n finally:\n np.seterrobj(olderrobj)\n\n\nclass TestFloatExceptions(object):\n def assert_raises_fpe(self, fpeerr, flop, x, y):\n ftype = type(x)\n try:\n flop(x, y)\n assert_(False,\n \"Type %s did not raise fpe error '%s'.\" % (ftype, fpeerr))\n except FloatingPointError as exc:\n assert_(str(exc).find(fpeerr) >= 0,\n \"Type %s raised wrong fpe error '%s'.\" % (ftype, exc))\n\n def assert_op_raises_fpe(self, fpeerr, flop, sc1, sc2):\n # Check that fpe exception is raised.\n #\n # Given a floating operation `flop` and two scalar values, check that\n # the operation raises the floating point exception specified by\n # `fpeerr`. Tests all variants with 0-d array scalars as well.\n\n self.assert_raises_fpe(fpeerr, flop, sc1, sc2)\n self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2)\n self.assert_raises_fpe(fpeerr, flop, sc1, sc2[()])\n self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2[()])\n\n def test_floating_exceptions(self):\n # Test basic arithmetic function errors\n with np.errstate(all='raise'):\n # Test for all real and complex float types\n for typecode in np.typecodes['AllFloat']:\n ftype = np.obj2sctype(typecode)\n if np.dtype(ftype).kind == 'f':\n # Get some extreme values for the type\n fi = np.finfo(ftype)\n ft_tiny = fi.tiny\n ft_max = fi.max\n ft_eps = fi.eps\n underflow = 'underflow'\n divbyzero = 'divide by zero'\n else:\n # 'c', complex, corresponding real dtype\n rtype = type(ftype(0).real)\n fi = np.finfo(rtype)\n ft_tiny = ftype(fi.tiny)\n ft_max = ftype(fi.max)\n ft_eps = ftype(fi.eps)\n # The complex types raise different exceptions\n underflow = ''\n divbyzero = ''\n overflow = 'overflow'\n invalid = 'invalid'\n\n self.assert_raises_fpe(underflow,\n lambda a, b: a/b, ft_tiny, ft_max)\n self.assert_raises_fpe(underflow,\n lambda a, b: a*b, ft_tiny, ft_tiny)\n self.assert_raises_fpe(overflow,\n lambda a, b: a*b, ft_max, ftype(2))\n self.assert_raises_fpe(overflow,\n lambda a, b: a/b, ft_max, ftype(0.5))\n self.assert_raises_fpe(overflow,\n lambda a, b: a+b, ft_max, ft_max*ft_eps)\n self.assert_raises_fpe(overflow,\n lambda a, b: a-b, -ft_max, ft_max*ft_eps)\n self.assert_raises_fpe(overflow,\n np.power, ftype(2), ftype(2**fi.nexp))\n self.assert_raises_fpe(divbyzero,\n lambda a, b: a/b, ftype(1), ftype(0))\n self.assert_raises_fpe(invalid,\n lambda a, b: a/b, ftype(np.inf), ftype(np.inf))\n self.assert_raises_fpe(invalid,\n lambda a, b: a/b, ftype(0), ftype(0))\n self.assert_raises_fpe(invalid,\n lambda a, b: a-b, ftype(np.inf), ftype(np.inf))\n self.assert_raises_fpe(invalid,\n lambda a, b: a+b, ftype(np.inf), ftype(-np.inf))\n self.assert_raises_fpe(invalid,\n lambda a, b: a*b, ftype(0), ftype(np.inf))\n\n def test_warnings(self):\n # test warning code path\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n with np.errstate(all=\"warn\"):\n np.divide(1, 0.)\n assert_equal(len(w), 1)\n assert_(\"divide by zero\" in str(w[0].message))\n np.array(1e300) * np.array(1e300)\n assert_equal(len(w), 2)\n assert_(\"overflow\" in str(w[-1].message))\n np.array(np.inf) - np.array(np.inf)\n assert_equal(len(w), 3)\n assert_(\"invalid value\" in str(w[-1].message))\n np.array(1e-300) * np.array(1e-300)\n assert_equal(len(w), 4)\n assert_(\"underflow\" in str(w[-1].message))\n\n\nclass TestTypes(object):\n def check_promotion_cases(self, promote_func):\n # tests that the scalars get coerced correctly.\n b = np.bool_(0)\n i8, i16, i32, i64 = np.int8(0), np.int16(0), np.int32(0), np.int64(0)\n u8, u16, u32, u64 = np.uint8(0), np.uint16(0), np.uint32(0), np.uint64(0)\n f32, f64, fld = np.float32(0), np.float64(0), np.longdouble(0)\n c64, c128, cld = np.complex64(0), np.complex128(0), np.clongdouble(0)\n\n # coercion within the same kind\n assert_equal(promote_func(i8, i16), np.dtype(np.int16))\n assert_equal(promote_func(i32, i8), np.dtype(np.int32))\n assert_equal(promote_func(i16, i64), np.dtype(np.int64))\n assert_equal(promote_func(u8, u32), np.dtype(np.uint32))\n assert_equal(promote_func(f32, f64), np.dtype(np.float64))\n assert_equal(promote_func(fld, f32), np.dtype(np.longdouble))\n assert_equal(promote_func(f64, fld), np.dtype(np.longdouble))\n assert_equal(promote_func(c128, c64), np.dtype(np.complex128))\n assert_equal(promote_func(cld, c128), np.dtype(np.clongdouble))\n assert_equal(promote_func(c64, fld), np.dtype(np.clongdouble))\n\n # coercion between kinds\n assert_equal(promote_func(b, i32), np.dtype(np.int32))\n assert_equal(promote_func(b, u8), np.dtype(np.uint8))\n assert_equal(promote_func(i8, u8), np.dtype(np.int16))\n assert_equal(promote_func(u8, i32), np.dtype(np.int32))\n assert_equal(promote_func(i64, u32), np.dtype(np.int64))\n assert_equal(promote_func(u64, i32), np.dtype(np.float64))\n assert_equal(promote_func(i32, f32), np.dtype(np.float64))\n assert_equal(promote_func(i64, f32), np.dtype(np.float64))\n assert_equal(promote_func(f32, i16), np.dtype(np.float32))\n assert_equal(promote_func(f32, u32), np.dtype(np.float64))\n assert_equal(promote_func(f32, c64), np.dtype(np.complex64))\n assert_equal(promote_func(c128, f32), np.dtype(np.complex128))\n assert_equal(promote_func(cld, f64), np.dtype(np.clongdouble))\n\n # coercion between scalars and 1-D arrays\n assert_equal(promote_func(np.array([b]), i8), np.dtype(np.int8))\n assert_equal(promote_func(np.array([b]), u8), np.dtype(np.uint8))\n assert_equal(promote_func(np.array([b]), i32), np.dtype(np.int32))\n assert_equal(promote_func(np.array([b]), u32), np.dtype(np.uint32))\n assert_equal(promote_func(np.array([i8]), i64), np.dtype(np.int8))\n assert_equal(promote_func(u64, np.array([i32])), np.dtype(np.int32))\n assert_equal(promote_func(i64, np.array([u32])), np.dtype(np.uint32))\n assert_equal(promote_func(np.int32(-1), np.array([u64])),\n np.dtype(np.float64))\n assert_equal(promote_func(f64, np.array([f32])), np.dtype(np.float32))\n assert_equal(promote_func(fld, np.array([f32])), np.dtype(np.float32))\n assert_equal(promote_func(np.array([f64]), fld), np.dtype(np.float64))\n assert_equal(promote_func(fld, np.array([c64])),\n np.dtype(np.complex64))\n assert_equal(promote_func(c64, np.array([f64])),\n np.dtype(np.complex128))\n assert_equal(promote_func(np.complex64(3j), np.array([f64])),\n np.dtype(np.complex128))\n\n # coercion between scalars and 1-D arrays, where\n # the scalar has greater kind than the array\n assert_equal(promote_func(np.array([b]), f64), np.dtype(np.float64))\n assert_equal(promote_func(np.array([b]), i64), np.dtype(np.int64))\n assert_equal(promote_func(np.array([b]), u64), np.dtype(np.uint64))\n assert_equal(promote_func(np.array([i8]), f64), np.dtype(np.float64))\n assert_equal(promote_func(np.array([u16]), f64), np.dtype(np.float64))\n\n # uint and int are treated as the same \"kind\" for\n # the purposes of array-scalar promotion.\n assert_equal(promote_func(np.array([u16]), i32), np.dtype(np.uint16))\n\n # float and complex are treated as the same \"kind\" for\n # the purposes of array-scalar promotion, so that you can do\n # (0j + float32array) to get a complex64 array instead of\n # a complex128 array.\n assert_equal(promote_func(np.array([f32]), c128),\n np.dtype(np.complex64))\n\n def test_coercion(self):\n def res_type(a, b):\n return np.add(a, b).dtype\n\n self.check_promotion_cases(res_type)\n\n # Use-case: float/complex scalar * bool/int8 array\n # shouldn't narrow the float/complex type\n for a in [np.array([True, False]), np.array([-3, 12], dtype=np.int8)]:\n b = 1.234 * a\n assert_equal(b.dtype, np.dtype('f8'), \"array type %s\" % a.dtype)\n b = np.longdouble(1.234) * a\n assert_equal(b.dtype, np.dtype(np.longdouble),\n \"array type %s\" % a.dtype)\n b = np.float64(1.234) * a\n assert_equal(b.dtype, np.dtype('f8'), \"array type %s\" % a.dtype)\n b = np.float32(1.234) * a\n assert_equal(b.dtype, np.dtype('f4'), \"array type %s\" % a.dtype)\n b = np.float16(1.234) * a\n assert_equal(b.dtype, np.dtype('f2'), \"array type %s\" % a.dtype)\n\n b = 1.234j * a\n assert_equal(b.dtype, np.dtype('c16'), \"array type %s\" % a.dtype)\n b = np.clongdouble(1.234j) * a\n assert_equal(b.dtype, np.dtype(np.clongdouble),\n \"array type %s\" % a.dtype)\n b = np.complex128(1.234j) * a\n assert_equal(b.dtype, np.dtype('c16'), \"array type %s\" % a.dtype)\n b = np.complex64(1.234j) * a\n assert_equal(b.dtype, np.dtype('c8'), \"array type %s\" % a.dtype)\n\n # The following use-case is problematic, and to resolve its\n # tricky side-effects requires more changes.\n #\n # Use-case: (1-t)*a, where 't' is a boolean array and 'a' is\n # a float32, shouldn't promote to float64\n #\n # a = np.array([1.0, 1.5], dtype=np.float32)\n # t = np.array([True, False])\n # b = t*a\n # assert_equal(b, [1.0, 0.0])\n # assert_equal(b.dtype, np.dtype('f4'))\n # b = (1-t)*a\n # assert_equal(b, [0.0, 1.5])\n # assert_equal(b.dtype, np.dtype('f4'))\n #\n # Probably ~t (bitwise negation) is more proper to use here,\n # but this is arguably less intuitive to understand at a glance, and\n # would fail if 't' is actually an integer array instead of boolean:\n #\n # b = (~t)*a\n # assert_equal(b, [0.0, 1.5])\n # assert_equal(b.dtype, np.dtype('f4'))\n\n def test_result_type(self):\n self.check_promotion_cases(np.result_type)\n assert_(np.result_type(None) == np.dtype(None))\n\n def test_promote_types_endian(self):\n # promote_types should always return native-endian types\n assert_equal(np.promote_types('<i8', '<i8'), np.dtype('i8'))\n assert_equal(np.promote_types('>i8', '>i8'), np.dtype('i8'))\n\n assert_equal(np.promote_types('>i8', '>U16'), np.dtype('U21'))\n assert_equal(np.promote_types('<i8', '<U16'), np.dtype('U21'))\n assert_equal(np.promote_types('>U16', '>i8'), np.dtype('U21'))\n assert_equal(np.promote_types('<U16', '<i8'), np.dtype('U21'))\n\n assert_equal(np.promote_types('<S5', '<U8'), np.dtype('U8'))\n assert_equal(np.promote_types('>S5', '>U8'), np.dtype('U8'))\n assert_equal(np.promote_types('<U8', '<S5'), np.dtype('U8'))\n assert_equal(np.promote_types('>U8', '>S5'), np.dtype('U8'))\n assert_equal(np.promote_types('<U5', '<U8'), np.dtype('U8'))\n assert_equal(np.promote_types('>U8', '>U5'), np.dtype('U8'))\n\n assert_equal(np.promote_types('<M8', '<M8'), np.dtype('M8'))\n assert_equal(np.promote_types('>M8', '>M8'), np.dtype('M8'))\n assert_equal(np.promote_types('<m8', '<m8'), np.dtype('m8'))\n assert_equal(np.promote_types('>m8', '>m8'), np.dtype('m8'))\n\n def test_promote_types_strings(self):\n assert_equal(np.promote_types('bool', 'S'), np.dtype('S5'))\n assert_equal(np.promote_types('b', 'S'), np.dtype('S4'))\n assert_equal(np.promote_types('u1', 'S'), np.dtype('S3'))\n assert_equal(np.promote_types('u2', 'S'), np.dtype('S5'))\n assert_equal(np.promote_types('u4', 'S'), np.dtype('S10'))\n assert_equal(np.promote_types('u8', 'S'), np.dtype('S20'))\n assert_equal(np.promote_types('i1', 'S'), np.dtype('S4'))\n assert_equal(np.promote_types('i2', 'S'), np.dtype('S6'))\n assert_equal(np.promote_types('i4', 'S'), np.dtype('S11'))\n assert_equal(np.promote_types('i8', 'S'), np.dtype('S21'))\n assert_equal(np.promote_types('bool', 'U'), np.dtype('U5'))\n assert_equal(np.promote_types('b', 'U'), np.dtype('U4'))\n assert_equal(np.promote_types('u1', 'U'), np.dtype('U3'))\n assert_equal(np.promote_types('u2', 'U'), np.dtype('U5'))\n assert_equal(np.promote_types('u4', 'U'), np.dtype('U10'))\n assert_equal(np.promote_types('u8', 'U'), np.dtype('U20'))\n assert_equal(np.promote_types('i1', 'U'), np.dtype('U4'))\n assert_equal(np.promote_types('i2', 'U'), np.dtype('U6'))\n assert_equal(np.promote_types('i4', 'U'), np.dtype('U11'))\n assert_equal(np.promote_types('i8', 'U'), np.dtype('U21'))\n assert_equal(np.promote_types('bool', 'S1'), np.dtype('S5'))\n assert_equal(np.promote_types('bool', 'S30'), np.dtype('S30'))\n assert_equal(np.promote_types('b', 'S1'), np.dtype('S4'))\n assert_equal(np.promote_types('b', 'S30'), np.dtype('S30'))\n assert_equal(np.promote_types('u1', 'S1'), np.dtype('S3'))\n assert_equal(np.promote_types('u1', 'S30'), np.dtype('S30'))\n assert_equal(np.promote_types('u2', 'S1'), np.dtype('S5'))\n assert_equal(np.promote_types('u2', 'S30'), np.dtype('S30'))\n assert_equal(np.promote_types('u4', 'S1'), np.dtype('S10'))\n assert_equal(np.promote_types('u4', 'S30'), np.dtype('S30'))\n assert_equal(np.promote_types('u8', 'S1'), np.dtype('S20'))\n assert_equal(np.promote_types('u8', 'S30'), np.dtype('S30'))\n\n def test_can_cast(self):\n assert_(np.can_cast(np.int32, np.int64))\n assert_(np.can_cast(np.float64, complex))\n assert_(not np.can_cast(complex, float))\n\n assert_(np.can_cast('i8', 'f8'))\n assert_(not np.can_cast('i8', 'f4'))\n assert_(np.can_cast('i4', 'S11'))\n\n assert_(np.can_cast('i8', 'i8', 'no'))\n assert_(not np.can_cast('<i8', '>i8', 'no'))\n\n assert_(np.can_cast('<i8', '>i8', 'equiv'))\n assert_(not np.can_cast('<i4', '>i8', 'equiv'))\n\n assert_(np.can_cast('<i4', '>i8', 'safe'))\n assert_(not np.can_cast('<i8', '>i4', 'safe'))\n\n assert_(np.can_cast('<i8', '>i4', 'same_kind'))\n assert_(not np.can_cast('<i8', '>u4', 'same_kind'))\n\n assert_(np.can_cast('<i8', '>u4', 'unsafe'))\n\n assert_(np.can_cast('bool', 'S5'))\n assert_(not np.can_cast('bool', 'S4'))\n\n assert_(np.can_cast('b', 'S4'))\n assert_(not np.can_cast('b', 'S3'))\n\n assert_(np.can_cast('u1', 'S3'))\n assert_(not np.can_cast('u1', 'S2'))\n assert_(np.can_cast('u2', 'S5'))\n assert_(not np.can_cast('u2', 'S4'))\n assert_(np.can_cast('u4', 'S10'))\n assert_(not np.can_cast('u4', 'S9'))\n assert_(np.can_cast('u8', 'S20'))\n assert_(not np.can_cast('u8', 'S19'))\n\n assert_(np.can_cast('i1', 'S4'))\n assert_(not np.can_cast('i1', 'S3'))\n assert_(np.can_cast('i2', 'S6'))\n assert_(not np.can_cast('i2', 'S5'))\n assert_(np.can_cast('i4', 'S11'))\n assert_(not np.can_cast('i4', 'S10'))\n assert_(np.can_cast('i8', 'S21'))\n assert_(not np.can_cast('i8', 'S20'))\n\n assert_(np.can_cast('bool', 'S5'))\n assert_(not np.can_cast('bool', 'S4'))\n\n assert_(np.can_cast('b', 'U4'))\n assert_(not np.can_cast('b', 'U3'))\n\n assert_(np.can_cast('u1', 'U3'))\n assert_(not np.can_cast('u1', 'U2'))\n assert_(np.can_cast('u2', 'U5'))\n assert_(not np.can_cast('u2', 'U4'))\n assert_(np.can_cast('u4', 'U10'))\n assert_(not np.can_cast('u4', 'U9'))\n assert_(np.can_cast('u8', 'U20'))\n assert_(not np.can_cast('u8', 'U19'))\n\n assert_(np.can_cast('i1', 'U4'))\n assert_(not np.can_cast('i1', 'U3'))\n assert_(np.can_cast('i2', 'U6'))\n assert_(not np.can_cast('i2', 'U5'))\n assert_(np.can_cast('i4', 'U11'))\n assert_(not np.can_cast('i4', 'U10'))\n assert_(np.can_cast('i8', 'U21'))\n assert_(not np.can_cast('i8', 'U20'))\n\n assert_raises(TypeError, np.can_cast, 'i4', None)\n assert_raises(TypeError, np.can_cast, None, 'i4')\n\n # Also test keyword arguments\n assert_(np.can_cast(from_=np.int32, to=np.int64))\n\n def test_can_cast_values(self):\n # gh-5917\n for dt in np.sctypes['int'] + np.sctypes['uint']:\n ii = np.iinfo(dt)\n assert_(np.can_cast(ii.min, dt))\n assert_(np.can_cast(ii.max, dt))\n assert_(not np.can_cast(ii.min - 1, dt))\n assert_(not np.can_cast(ii.max + 1, dt))\n\n for dt in np.sctypes['float']:\n fi = np.finfo(dt)\n assert_(np.can_cast(fi.min, dt))\n assert_(np.can_cast(fi.max, dt))\n\n\n# Custom exception class to test exception propagation in fromiter\nclass NIterError(Exception):\n pass\n\n\nclass TestFromiter(object):\n def makegen(self):\n for x in range(24):\n yield x**2\n\n def test_types(self):\n ai32 = np.fromiter(self.makegen(), np.int32)\n ai64 = np.fromiter(self.makegen(), np.int64)\n af = np.fromiter(self.makegen(), float)\n assert_(ai32.dtype == np.dtype(np.int32))\n assert_(ai64.dtype == np.dtype(np.int64))\n assert_(af.dtype == np.dtype(float))\n\n def test_lengths(self):\n expected = np.array(list(self.makegen()))\n a = np.fromiter(self.makegen(), int)\n a20 = np.fromiter(self.makegen(), int, 20)\n assert_(len(a) == len(expected))\n assert_(len(a20) == 20)\n assert_raises(ValueError, np.fromiter,\n self.makegen(), int, len(expected) + 10)\n\n def test_values(self):\n expected = np.array(list(self.makegen()))\n a = np.fromiter(self.makegen(), int)\n a20 = np.fromiter(self.makegen(), int, 20)\n assert_(np.alltrue(a == expected, axis=0))\n assert_(np.alltrue(a20 == expected[:20], axis=0))\n\n def load_data(self, n, eindex):\n # Utility method for the issue 2592 tests.\n # Raise an exception at the desired index in the iterator.\n for e in range(n):\n if e == eindex:\n raise NIterError('error at index %s' % eindex)\n yield e\n\n def test_2592(self):\n # Test iteration exceptions are correctly raised.\n count, eindex = 10, 5\n assert_raises(NIterError, np.fromiter,\n self.load_data(count, eindex), dtype=int, count=count)\n\n def test_2592_edge(self):\n # Test iter. exceptions, edge case (exception at end of iterator).\n count = 10\n eindex = count-1\n assert_raises(NIterError, np.fromiter,\n self.load_data(count, eindex), dtype=int, count=count)\n\n\nclass TestNonzero(object):\n def test_nonzero_trivial(self):\n assert_equal(np.count_nonzero(np.array([])), 0)\n assert_equal(np.count_nonzero(np.array([], dtype='?')), 0)\n assert_equal(np.nonzero(np.array([])), ([],))\n\n assert_equal(np.count_nonzero(np.array(0)), 0)\n assert_equal(np.count_nonzero(np.array(0, dtype='?')), 0)\n assert_equal(np.nonzero(np.array(0)), ([],))\n assert_equal(np.count_nonzero(np.array(1)), 1)\n assert_equal(np.count_nonzero(np.array(1, dtype='?')), 1)\n assert_equal(np.nonzero(np.array(1)), ([0],))\n\n def test_nonzero_onedim(self):\n x = np.array([1, 0, 2, -1, 0, 0, 8])\n assert_equal(np.count_nonzero(x), 4)\n assert_equal(np.count_nonzero(x), 4)\n assert_equal(np.nonzero(x), ([0, 2, 3, 6],))\n\n x = np.array([(1, 2), (0, 0), (1, 1), (-1, 3), (0, 7)],\n dtype=[('a', 'i4'), ('b', 'i2')])\n assert_equal(np.count_nonzero(x['a']), 3)\n assert_equal(np.count_nonzero(x['b']), 4)\n assert_equal(np.nonzero(x['a']), ([0, 2, 3],))\n assert_equal(np.nonzero(x['b']), ([0, 2, 3, 4],))\n\n def test_nonzero_twodim(self):\n x = np.array([[0, 1, 0], [2, 0, 3]])\n assert_equal(np.count_nonzero(x), 3)\n assert_equal(np.nonzero(x), ([0, 1, 1], [1, 0, 2]))\n\n x = np.eye(3)\n assert_equal(np.count_nonzero(x), 3)\n assert_equal(np.nonzero(x), ([0, 1, 2], [0, 1, 2]))\n\n x = np.array([[(0, 1), (0, 0), (1, 11)],\n [(1, 1), (1, 0), (0, 0)],\n [(0, 0), (1, 5), (0, 1)]], dtype=[('a', 'f4'), ('b', 'u1')])\n assert_equal(np.count_nonzero(x['a']), 4)\n assert_equal(np.count_nonzero(x['b']), 5)\n assert_equal(np.nonzero(x['a']), ([0, 1, 1, 2], [2, 0, 1, 1]))\n assert_equal(np.nonzero(x['b']), ([0, 0, 1, 2, 2], [0, 2, 0, 1, 2]))\n\n assert_(not x['a'].T.flags.aligned)\n assert_equal(np.count_nonzero(x['a'].T), 4)\n assert_equal(np.count_nonzero(x['b'].T), 5)\n assert_equal(np.nonzero(x['a'].T), ([0, 1, 1, 2], [1, 1, 2, 0]))\n assert_equal(np.nonzero(x['b'].T), ([0, 0, 1, 2, 2], [0, 1, 2, 0, 2]))\n\n def test_sparse(self):\n # test special sparse condition boolean code path\n for i in range(20):\n c = np.zeros(200, dtype=bool)\n c[i::20] = True\n assert_equal(np.nonzero(c)[0], np.arange(i, 200 + i, 20))\n\n c = np.zeros(400, dtype=bool)\n c[10 + i:20 + i] = True\n c[20 + i*2] = True\n assert_equal(np.nonzero(c)[0],\n np.concatenate((np.arange(10 + i, 20 + i), [20 + i*2])))\n\n def test_return_type(self):\n class C(np.ndarray):\n pass\n\n for view in (C, np.ndarray):\n for nd in range(1, 4):\n shape = tuple(range(2, 2+nd))\n x = np.arange(np.prod(shape)).reshape(shape).view(view)\n for nzx in (np.nonzero(x), x.nonzero()):\n for nzx_i in nzx:\n assert_(type(nzx_i) is np.ndarray)\n assert_(nzx_i.flags.writeable)\n\n def test_count_nonzero_axis(self):\n # Basic check of functionality\n m = np.array([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]])\n\n expected = np.array([1, 1, 1, 1, 1])\n assert_equal(np.count_nonzero(m, axis=0), expected)\n\n expected = np.array([2, 3])\n assert_equal(np.count_nonzero(m, axis=1), expected)\n\n assert_raises(ValueError, np.count_nonzero, m, axis=(1, 1))\n assert_raises(TypeError, np.count_nonzero, m, axis='foo')\n assert_raises(np.AxisError, np.count_nonzero, m, axis=3)\n assert_raises(TypeError, np.count_nonzero,\n m, axis=np.array([[1], [2]]))\n\n def test_count_nonzero_axis_all_dtypes(self):\n # More thorough test that the axis argument is respected\n # for all dtypes and responds correctly when presented with\n # either integer or tuple arguments for axis\n msg = \"Mismatch for dtype: %s\"\n\n def assert_equal_w_dt(a, b, err_msg):\n assert_equal(a.dtype, b.dtype, err_msg=err_msg)\n assert_equal(a, b, err_msg=err_msg)\n\n for dt in np.typecodes['All']:\n err_msg = msg % (np.dtype(dt).name,)\n\n if dt != 'V':\n if dt != 'M':\n m = np.zeros((3, 3), dtype=dt)\n n = np.ones(1, dtype=dt)\n\n m[0, 0] = n[0]\n m[1, 0] = n[0]\n\n else: # np.zeros doesn't work for np.datetime64\n m = np.array(['1970-01-01'] * 9)\n m = m.reshape((3, 3))\n\n m[0, 0] = '1970-01-12'\n m[1, 0] = '1970-01-12'\n m = m.astype(dt)\n\n expected = np.array([2, 0, 0], dtype=np.intp)\n assert_equal_w_dt(np.count_nonzero(m, axis=0),\n expected, err_msg=err_msg)\n\n expected = np.array([1, 1, 0], dtype=np.intp)\n assert_equal_w_dt(np.count_nonzero(m, axis=1),\n expected, err_msg=err_msg)\n\n expected = np.array(2)\n assert_equal(np.count_nonzero(m, axis=(0, 1)),\n expected, err_msg=err_msg)\n assert_equal(np.count_nonzero(m, axis=None),\n expected, err_msg=err_msg)\n assert_equal(np.count_nonzero(m),\n expected, err_msg=err_msg)\n\n if dt == 'V':\n # There are no 'nonzero' objects for np.void, so the testing\n # setup is slightly different for this dtype\n m = np.array([np.void(1)] * 6).reshape((2, 3))\n\n expected = np.array([0, 0, 0], dtype=np.intp)\n assert_equal_w_dt(np.count_nonzero(m, axis=0),\n expected, err_msg=err_msg)\n\n expected = np.array([0, 0], dtype=np.intp)\n assert_equal_w_dt(np.count_nonzero(m, axis=1),\n expected, err_msg=err_msg)\n\n expected = np.array(0)\n assert_equal(np.count_nonzero(m, axis=(0, 1)),\n expected, err_msg=err_msg)\n assert_equal(np.count_nonzero(m, axis=None),\n expected, err_msg=err_msg)\n assert_equal(np.count_nonzero(m),\n expected, err_msg=err_msg)\n\n def test_count_nonzero_axis_consistent(self):\n # Check that the axis behaviour for valid axes in\n # non-special cases is consistent (and therefore\n # correct) by checking it against an integer array\n # that is then casted to the generic object dtype\n from itertools import combinations, permutations\n\n axis = (0, 1, 2, 3)\n size = (5, 5, 5, 5)\n msg = \"Mismatch for axis: %s\"\n\n rng = np.random.RandomState(1234)\n m = rng.randint(-100, 100, size=size)\n n = m.astype(object)\n\n for length in range(len(axis)):\n for combo in combinations(axis, length):\n for perm in permutations(combo):\n assert_equal(\n np.count_nonzero(m, axis=perm),\n np.count_nonzero(n, axis=perm),\n err_msg=msg % (perm,))\n\n def test_countnonzero_axis_empty(self):\n a = np.array([[0, 0, 1], [1, 0, 1]])\n assert_equal(np.count_nonzero(a, axis=()), a.astype(bool))\n\n def test_array_method(self):\n # Tests that the array method\n # call to nonzero works\n m = np.array([[1, 0, 0], [4, 0, 6]])\n tgt = [[0, 1, 1], [0, 0, 2]]\n\n assert_equal(m.nonzero(), tgt)\n\n def test_nonzero_invalid_object(self):\n # gh-9295\n a = np.array([np.array([1, 2]), 3])\n assert_raises(ValueError, np.nonzero, a)\n\n class BoolErrors:\n def __bool__(self):\n raise ValueError(\"Not allowed\")\n def __nonzero__(self):\n raise ValueError(\"Not allowed\")\n\n assert_raises(ValueError, np.nonzero, np.array([BoolErrors()]))\n\n\nclass TestIndex(object):\n def test_boolean(self):\n a = rand(3, 5, 8)\n V = rand(5, 8)\n g1 = randint(0, 5, size=15)\n g2 = randint(0, 8, size=15)\n V[g1, g2] = -V[g1, g2]\n assert_((np.array([a[0][V > 0], a[1][V > 0], a[2][V > 0]]) == a[:, V > 0]).all())\n\n def test_boolean_edgecase(self):\n a = np.array([], dtype='int32')\n b = np.array([], dtype='bool')\n c = a[b]\n assert_equal(c, [])\n assert_equal(c.dtype, np.dtype('int32'))\n\n\nclass TestBinaryRepr(object):\n def test_zero(self):\n assert_equal(np.binary_repr(0), '0')\n\n def test_positive(self):\n assert_equal(np.binary_repr(10), '1010')\n assert_equal(np.binary_repr(12522),\n '11000011101010')\n assert_equal(np.binary_repr(10736848),\n '101000111101010011010000')\n\n def test_negative(self):\n assert_equal(np.binary_repr(-1), '-1')\n assert_equal(np.binary_repr(-10), '-1010')\n assert_equal(np.binary_repr(-12522),\n '-11000011101010')\n assert_equal(np.binary_repr(-10736848),\n '-101000111101010011010000')\n\n def test_sufficient_width(self):\n assert_equal(np.binary_repr(0, width=5), '00000')\n assert_equal(np.binary_repr(10, width=7), '0001010')\n assert_equal(np.binary_repr(-5, width=7), '1111011')\n\n def test_neg_width_boundaries(self):\n # see gh-8670\n\n # Ensure that the example in the issue does not\n # break before proceeding to a more thorough test.\n assert_equal(np.binary_repr(-128, width=8), '10000000')\n\n for width in range(1, 11):\n num = -2**(width - 1)\n exp = '1' + (width - 1) * '0'\n assert_equal(np.binary_repr(num, width=width), exp)\n\n\nclass TestBaseRepr(object):\n def test_base3(self):\n assert_equal(np.base_repr(3**5, 3), '100000')\n\n def test_positive(self):\n assert_equal(np.base_repr(12, 10), '12')\n assert_equal(np.base_repr(12, 10, 4), '000012')\n assert_equal(np.base_repr(12, 4), '30')\n assert_equal(np.base_repr(3731624803700888, 36), '10QR0ROFCEW')\n\n def test_negative(self):\n assert_equal(np.base_repr(-12, 10), '-12')\n assert_equal(np.base_repr(-12, 10, 4), '-000012')\n assert_equal(np.base_repr(-12, 4), '-30')\n\n def test_base_range(self):\n with assert_raises(ValueError):\n np.base_repr(1, 1)\n with assert_raises(ValueError):\n np.base_repr(1, 37)\n\n\nclass TestArrayComparisons(object):\n def test_array_equal(self):\n res = np.array_equal(np.array([1, 2]), np.array([1, 2]))\n assert_(res)\n assert_(type(res) is bool)\n res = np.array_equal(np.array([1, 2]), np.array([1, 2, 3]))\n assert_(not res)\n assert_(type(res) is bool)\n res = np.array_equal(np.array([1, 2]), np.array([3, 4]))\n assert_(not res)\n assert_(type(res) is bool)\n res = np.array_equal(np.array([1, 2]), np.array([1, 3]))\n assert_(not res)\n assert_(type(res) is bool)\n res = np.array_equal(np.array(['a'], dtype='S1'), np.array(['a'], dtype='S1'))\n assert_(res)\n assert_(type(res) is bool)\n res = np.array_equal(np.array([('a', 1)], dtype='S1,u4'),\n np.array([('a', 1)], dtype='S1,u4'))\n assert_(res)\n assert_(type(res) is bool)\n\n def test_none_compares_elementwise(self):\n a = np.array([None, 1, None], dtype=object)\n assert_equal(a == None, [True, False, True])\n assert_equal(a != None, [False, True, False])\n\n a = np.ones(3)\n assert_equal(a == None, [False, False, False])\n assert_equal(a != None, [True, True, True])\n\n def test_array_equiv(self):\n res = np.array_equiv(np.array([1, 2]), np.array([1, 2]))\n assert_(res)\n assert_(type(res) is bool)\n res = np.array_equiv(np.array([1, 2]), np.array([1, 2, 3]))\n assert_(not res)\n assert_(type(res) is bool)\n res = np.array_equiv(np.array([1, 2]), np.array([3, 4]))\n assert_(not res)\n assert_(type(res) is bool)\n res = np.array_equiv(np.array([1, 2]), np.array([1, 3]))\n assert_(not res)\n assert_(type(res) is bool)\n\n res = np.array_equiv(np.array([1, 1]), np.array([1]))\n assert_(res)\n assert_(type(res) is bool)\n res = np.array_equiv(np.array([1, 1]), np.array([[1], [1]]))\n assert_(res)\n assert_(type(res) is bool)\n res = np.array_equiv(np.array([1, 2]), np.array([2]))\n assert_(not res)\n assert_(type(res) is bool)\n res = np.array_equiv(np.array([1, 2]), np.array([[1], [2]]))\n assert_(not res)\n assert_(type(res) is bool)\n res = np.array_equiv(np.array([1, 2]), np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))\n assert_(not res)\n assert_(type(res) is bool)\n\n\ndef assert_array_strict_equal(x, y):\n assert_array_equal(x, y)\n # Check flags, 32 bit arches typically don't provide 16 byte alignment\n if ((x.dtype.alignment <= 8 or\n np.intp().dtype.itemsize != 4) and\n sys.platform != 'win32'):\n assert_(x.flags == y.flags)\n else:\n assert_(x.flags.owndata == y.flags.owndata)\n assert_(x.flags.writeable == y.flags.writeable)\n assert_(x.flags.c_contiguous == y.flags.c_contiguous)\n assert_(x.flags.f_contiguous == y.flags.f_contiguous)\n assert_(x.flags.writebackifcopy == y.flags.writebackifcopy)\n # check endianness\n assert_(x.dtype.isnative == y.dtype.isnative)\n\n\nclass TestClip(object):\n def setup(self):\n self.nr = 5\n self.nc = 3\n\n def fastclip(self, a, m, M, out=None):\n if out is None:\n return a.clip(m, M)\n else:\n return a.clip(m, M, out)\n\n def clip(self, a, m, M, out=None):\n # use slow-clip\n selector = np.less(a, m) + 2*np.greater(a, M)\n return selector.choose((a, m, M), out=out)\n\n # Handy functions\n def _generate_data(self, n, m):\n return randn(n, m)\n\n def _generate_data_complex(self, n, m):\n return randn(n, m) + 1.j * rand(n, m)\n\n def _generate_flt_data(self, n, m):\n return (randn(n, m)).astype(np.float32)\n\n def _neg_byteorder(self, a):\n a = np.asarray(a)\n if sys.byteorder == 'little':\n a = a.astype(a.dtype.newbyteorder('>'))\n else:\n a = a.astype(a.dtype.newbyteorder('<'))\n return a\n\n def _generate_non_native_data(self, n, m):\n data = randn(n, m)\n data = self._neg_byteorder(data)\n assert_(not data.dtype.isnative)\n return data\n\n def _generate_int_data(self, n, m):\n return (10 * rand(n, m)).astype(np.int64)\n\n def _generate_int32_data(self, n, m):\n return (10 * rand(n, m)).astype(np.int32)\n\n # Now the real test cases\n def test_simple_double(self):\n # Test native double input with scalar min/max.\n a = self._generate_data(self.nr, self.nc)\n m = 0.1\n M = 0.6\n ac = self.fastclip(a, m, M)\n act = self.clip(a, m, M)\n assert_array_strict_equal(ac, act)\n\n def test_simple_int(self):\n # Test native int input with scalar min/max.\n a = self._generate_int_data(self.nr, self.nc)\n a = a.astype(int)\n m = -2\n M = 4\n ac = self.fastclip(a, m, M)\n act = self.clip(a, m, M)\n assert_array_strict_equal(ac, act)\n\n def test_array_double(self):\n # Test native double input with array min/max.\n a = self._generate_data(self.nr, self.nc)\n m = np.zeros(a.shape)\n M = m + 0.5\n ac = self.fastclip(a, m, M)\n act = self.clip(a, m, M)\n assert_array_strict_equal(ac, act)\n\n def test_simple_nonnative(self):\n # Test non native double input with scalar min/max.\n # Test native double input with non native double scalar min/max.\n a = self._generate_non_native_data(self.nr, self.nc)\n m = -0.5\n M = 0.6\n ac = self.fastclip(a, m, M)\n act = self.clip(a, m, M)\n assert_array_equal(ac, act)\n\n # Test native double input with non native double scalar min/max.\n a = self._generate_data(self.nr, self.nc)\n m = -0.5\n M = self._neg_byteorder(0.6)\n assert_(not M.dtype.isnative)\n ac = self.fastclip(a, m, M)\n act = self.clip(a, m, M)\n assert_array_equal(ac, act)\n\n def test_simple_complex(self):\n # Test native complex input with native double scalar min/max.\n # Test native input with complex double scalar min/max.\n a = 3 * self._generate_data_complex(self.nr, self.nc)\n m = -0.5\n M = 1.\n ac = self.fastclip(a, m, M)\n act = self.clip(a, m, M)\n assert_array_strict_equal(ac, act)\n\n # Test native input with complex double scalar min/max.\n a = 3 * self._generate_data(self.nr, self.nc)\n m = -0.5 + 1.j\n M = 1. + 2.j\n ac = self.fastclip(a, m, M)\n act = self.clip(a, m, M)\n assert_array_strict_equal(ac, act)\n\n def test_clip_complex(self):\n # Address Issue gh-5354 for clipping complex arrays\n # Test native complex input without explicit min/max\n # ie, either min=None or max=None\n a = np.ones(10, dtype=complex)\n m = a.min()\n M = a.max()\n am = self.fastclip(a, m, None)\n aM = self.fastclip(a, None, M)\n assert_array_strict_equal(am, a)\n assert_array_strict_equal(aM, a)\n\n def test_clip_non_contig(self):\n # Test clip for non contiguous native input and native scalar min/max.\n a = self._generate_data(self.nr * 2, self.nc * 3)\n a = a[::2, ::3]\n assert_(not a.flags['F_CONTIGUOUS'])\n assert_(not a.flags['C_CONTIGUOUS'])\n ac = self.fastclip(a, -1.6, 1.7)\n act = self.clip(a, -1.6, 1.7)\n assert_array_strict_equal(ac, act)\n\n def test_simple_out(self):\n # Test native double input with scalar min/max.\n a = self._generate_data(self.nr, self.nc)\n m = -0.5\n M = 0.6\n ac = np.zeros(a.shape)\n act = np.zeros(a.shape)\n self.fastclip(a, m, M, ac)\n self.clip(a, m, M, act)\n assert_array_strict_equal(ac, act)\n\n def test_simple_int32_inout(self):\n # Test native int32 input with double min/max and int32 out.\n a = self._generate_int32_data(self.nr, self.nc)\n m = np.float64(0)\n M = np.float64(2)\n ac = np.zeros(a.shape, dtype=np.int32)\n act = ac.copy()\n self.fastclip(a, m, M, ac)\n self.clip(a, m, M, act)\n assert_array_strict_equal(ac, act)\n\n def test_simple_int64_out(self):\n # Test native int32 input with int32 scalar min/max and int64 out.\n a = self._generate_int32_data(self.nr, self.nc)\n m = np.int32(-1)\n M = np.int32(1)\n ac = np.zeros(a.shape, dtype=np.int64)\n act = ac.copy()\n self.fastclip(a, m, M, ac)\n self.clip(a, m, M, act)\n assert_array_strict_equal(ac, act)\n\n def test_simple_int64_inout(self):\n # Test native int32 input with double array min/max and int32 out.\n a = self._generate_int32_data(self.nr, self.nc)\n m = np.zeros(a.shape, np.float64)\n M = np.float64(1)\n ac = np.zeros(a.shape, dtype=np.int32)\n act = ac.copy()\n self.fastclip(a, m, M, ac)\n self.clip(a, m, M, act)\n assert_array_strict_equal(ac, act)\n\n def test_simple_int32_out(self):\n # Test native double input with scalar min/max and int out.\n a = self._generate_data(self.nr, self.nc)\n m = -1.0\n M = 2.0\n ac = np.zeros(a.shape, dtype=np.int32)\n act = ac.copy()\n self.fastclip(a, m, M, ac)\n self.clip(a, m, M, act)\n assert_array_strict_equal(ac, act)\n\n def test_simple_inplace_01(self):\n # Test native double input with array min/max in-place.\n a = self._generate_data(self.nr, self.nc)\n ac = a.copy()\n m = np.zeros(a.shape)\n M = 1.0\n self.fastclip(a, m, M, a)\n self.clip(a, m, M, ac)\n assert_array_strict_equal(a, ac)\n\n def test_simple_inplace_02(self):\n # Test native double input with scalar min/max in-place.\n a = self._generate_data(self.nr, self.nc)\n ac = a.copy()\n m = -0.5\n M = 0.6\n self.fastclip(a, m, M, a)\n self.clip(ac, m, M, ac)\n assert_array_strict_equal(a, ac)\n\n def test_noncontig_inplace(self):\n # Test non contiguous double input with double scalar min/max in-place.\n a = self._generate_data(self.nr * 2, self.nc * 3)\n a = a[::2, ::3]\n assert_(not a.flags['F_CONTIGUOUS'])\n assert_(not a.flags['C_CONTIGUOUS'])\n ac = a.copy()\n m = -0.5\n M = 0.6\n self.fastclip(a, m, M, a)\n self.clip(ac, m, M, ac)\n assert_array_equal(a, ac)\n\n def test_type_cast_01(self):\n # Test native double input with scalar min/max.\n a = self._generate_data(self.nr, self.nc)\n m = -0.5\n M = 0.6\n ac = self.fastclip(a, m, M)\n act = self.clip(a, m, M)\n assert_array_strict_equal(ac, act)\n\n def test_type_cast_02(self):\n # Test native int32 input with int32 scalar min/max.\n a = self._generate_int_data(self.nr, self.nc)\n a = a.astype(np.int32)\n m = -2\n M = 4\n ac = self.fastclip(a, m, M)\n act = self.clip(a, m, M)\n assert_array_strict_equal(ac, act)\n\n def test_type_cast_03(self):\n # Test native int32 input with float64 scalar min/max.\n a = self._generate_int32_data(self.nr, self.nc)\n m = -2\n M = 4\n ac = self.fastclip(a, np.float64(m), np.float64(M))\n act = self.clip(a, np.float64(m), np.float64(M))\n assert_array_strict_equal(ac, act)\n\n def test_type_cast_04(self):\n # Test native int32 input with float32 scalar min/max.\n a = self._generate_int32_data(self.nr, self.nc)\n m = np.float32(-2)\n M = np.float32(4)\n act = self.fastclip(a, m, M)\n ac = self.clip(a, m, M)\n assert_array_strict_equal(ac, act)\n\n def test_type_cast_05(self):\n # Test native int32 with double arrays min/max.\n a = self._generate_int_data(self.nr, self.nc)\n m = -0.5\n M = 1.\n ac = self.fastclip(a, m * np.zeros(a.shape), M)\n act = self.clip(a, m * np.zeros(a.shape), M)\n assert_array_strict_equal(ac, act)\n\n def test_type_cast_06(self):\n # Test native with NON native scalar min/max.\n a = self._generate_data(self.nr, self.nc)\n m = 0.5\n m_s = self._neg_byteorder(m)\n M = 1.\n act = self.clip(a, m_s, M)\n ac = self.fastclip(a, m_s, M)\n assert_array_strict_equal(ac, act)\n\n def test_type_cast_07(self):\n # Test NON native with native array min/max.\n a = self._generate_data(self.nr, self.nc)\n m = -0.5 * np.ones(a.shape)\n M = 1.\n a_s = self._neg_byteorder(a)\n assert_(not a_s.dtype.isnative)\n act = a_s.clip(m, M)\n ac = self.fastclip(a_s, m, M)\n assert_array_strict_equal(ac, act)\n\n def test_type_cast_08(self):\n # Test NON native with native scalar min/max.\n a = self._generate_data(self.nr, self.nc)\n m = -0.5\n M = 1.\n a_s = self._neg_byteorder(a)\n assert_(not a_s.dtype.isnative)\n ac = self.fastclip(a_s, m, M)\n act = a_s.clip(m, M)\n assert_array_strict_equal(ac, act)\n\n def test_type_cast_09(self):\n # Test native with NON native array min/max.\n a = self._generate_data(self.nr, self.nc)\n m = -0.5 * np.ones(a.shape)\n M = 1.\n m_s = self._neg_byteorder(m)\n assert_(not m_s.dtype.isnative)\n ac = self.fastclip(a, m_s, M)\n act = self.clip(a, m_s, M)\n assert_array_strict_equal(ac, act)\n\n def test_type_cast_10(self):\n # Test native int32 with float min/max and float out for output argument.\n a = self._generate_int_data(self.nr, self.nc)\n b = np.zeros(a.shape, dtype=np.float32)\n m = np.float32(-0.5)\n M = np.float32(1)\n act = self.clip(a, m, M, out=b)\n ac = self.fastclip(a, m, M, out=b)\n assert_array_strict_equal(ac, act)\n\n def test_type_cast_11(self):\n # Test non native with native scalar, min/max, out non native\n a = self._generate_non_native_data(self.nr, self.nc)\n b = a.copy()\n b = b.astype(b.dtype.newbyteorder('>'))\n bt = b.copy()\n m = -0.5\n M = 1.\n self.fastclip(a, m, M, out=b)\n self.clip(a, m, M, out=bt)\n assert_array_strict_equal(b, bt)\n\n def test_type_cast_12(self):\n # Test native int32 input and min/max and float out\n a = self._generate_int_data(self.nr, self.nc)\n b = np.zeros(a.shape, dtype=np.float32)\n m = np.int32(0)\n M = np.int32(1)\n act = self.clip(a, m, M, out=b)\n ac = self.fastclip(a, m, M, out=b)\n assert_array_strict_equal(ac, act)\n\n def test_clip_with_out_simple(self):\n # Test native double input with scalar min/max\n a = self._generate_data(self.nr, self.nc)\n m = -0.5\n M = 0.6\n ac = np.zeros(a.shape)\n act = np.zeros(a.shape)\n self.fastclip(a, m, M, ac)\n self.clip(a, m, M, act)\n assert_array_strict_equal(ac, act)\n\n def test_clip_with_out_simple2(self):\n # Test native int32 input with double min/max and int32 out\n a = self._generate_int32_data(self.nr, self.nc)\n m = np.float64(0)\n M = np.float64(2)\n ac = np.zeros(a.shape, dtype=np.int32)\n act = ac.copy()\n self.fastclip(a, m, M, ac)\n self.clip(a, m, M, act)\n assert_array_strict_equal(ac, act)\n\n def test_clip_with_out_simple_int32(self):\n # Test native int32 input with int32 scalar min/max and int64 out\n a = self._generate_int32_data(self.nr, self.nc)\n m = np.int32(-1)\n M = np.int32(1)\n ac = np.zeros(a.shape, dtype=np.int64)\n act = ac.copy()\n self.fastclip(a, m, M, ac)\n self.clip(a, m, M, act)\n assert_array_strict_equal(ac, act)\n\n def test_clip_with_out_array_int32(self):\n # Test native int32 input with double array min/max and int32 out\n a = self._generate_int32_data(self.nr, self.nc)\n m = np.zeros(a.shape, np.float64)\n M = np.float64(1)\n ac = np.zeros(a.shape, dtype=np.int32)\n act = ac.copy()\n self.fastclip(a, m, M, ac)\n self.clip(a, m, M, act)\n assert_array_strict_equal(ac, act)\n\n def test_clip_with_out_array_outint32(self):\n # Test native double input with scalar min/max and int out\n a = self._generate_data(self.nr, self.nc)\n m = -1.0\n M = 2.0\n ac = np.zeros(a.shape, dtype=np.int32)\n act = ac.copy()\n self.fastclip(a, m, M, ac)\n self.clip(a, m, M, act)\n assert_array_strict_equal(ac, act)\n\n def test_clip_with_out_transposed(self):\n # Test that the out argument works when tranposed\n a = np.arange(16).reshape(4, 4)\n out = np.empty_like(a).T\n a.clip(4, 10, out=out)\n expected = self.clip(a, 4, 10)\n assert_array_equal(out, expected)\n\n def test_clip_with_out_memory_overlap(self):\n # Test that the out argument works when it has memory overlap\n a = np.arange(16).reshape(4, 4)\n ac = a.copy()\n a[:-1].clip(4, 10, out=a[1:])\n expected = self.clip(ac[:-1], 4, 10)\n assert_array_equal(a[1:], expected)\n\n def test_clip_inplace_array(self):\n # Test native double input with array min/max\n a = self._generate_data(self.nr, self.nc)\n ac = a.copy()\n m = np.zeros(a.shape)\n M = 1.0\n self.fastclip(a, m, M, a)\n self.clip(a, m, M, ac)\n assert_array_strict_equal(a, ac)\n\n def test_clip_inplace_simple(self):\n # Test native double input with scalar min/max\n a = self._generate_data(self.nr, self.nc)\n ac = a.copy()\n m = -0.5\n M = 0.6\n self.fastclip(a, m, M, a)\n self.clip(a, m, M, ac)\n assert_array_strict_equal(a, ac)\n\n def test_clip_func_takes_out(self):\n # Ensure that the clip() function takes an out=argument.\n a = self._generate_data(self.nr, self.nc)\n ac = a.copy()\n m = -0.5\n M = 0.6\n a2 = np.clip(a, m, M, out=a)\n self.clip(a, m, M, ac)\n assert_array_strict_equal(a2, ac)\n assert_(a2 is a)\n\n def test_clip_nan(self):\n d = np.arange(7.)\n assert_equal(d.clip(min=np.nan), d)\n assert_equal(d.clip(max=np.nan), d)\n assert_equal(d.clip(min=np.nan, max=np.nan), d)\n assert_equal(d.clip(min=-2, max=np.nan), d)\n assert_equal(d.clip(min=np.nan, max=10), d)\n\n\nclass TestAllclose(object):\n rtol = 1e-5\n atol = 1e-8\n\n def setup(self):\n self.olderr = np.seterr(invalid='ignore')\n\n def teardown(self):\n np.seterr(**self.olderr)\n\n def tst_allclose(self, x, y):\n assert_(np.allclose(x, y), \"%s and %s not close\" % (x, y))\n\n def tst_not_allclose(self, x, y):\n assert_(not np.allclose(x, y), \"%s and %s shouldn't be close\" % (x, y))\n\n def test_ip_allclose(self):\n # Parametric test factory.\n arr = np.array([100, 1000])\n aran = np.arange(125).reshape((5, 5, 5))\n\n atol = self.atol\n rtol = self.rtol\n\n data = [([1, 0], [1, 0]),\n ([atol], [0]),\n ([1], [1+rtol+atol]),\n (arr, arr + arr*rtol),\n (arr, arr + arr*rtol + atol*2),\n (aran, aran + aran*rtol),\n (np.inf, np.inf),\n (np.inf, [np.inf])]\n\n for (x, y) in data:\n self.tst_allclose(x, y)\n\n def test_ip_not_allclose(self):\n # Parametric test factory.\n aran = np.arange(125).reshape((5, 5, 5))\n\n atol = self.atol\n rtol = self.rtol\n\n data = [([np.inf, 0], [1, np.inf]),\n ([np.inf, 0], [1, 0]),\n ([np.inf, np.inf], [1, np.inf]),\n ([np.inf, np.inf], [1, 0]),\n ([-np.inf, 0], [np.inf, 0]),\n ([np.nan, 0], [np.nan, 0]),\n ([atol*2], [0]),\n ([1], [1+rtol+atol*2]),\n (aran, aran + aran*atol + atol*2),\n (np.array([np.inf, 1]), np.array([0, np.inf]))]\n\n for (x, y) in data:\n self.tst_not_allclose(x, y)\n\n def test_no_parameter_modification(self):\n x = np.array([np.inf, 1])\n y = np.array([0, np.inf])\n np.allclose(x, y)\n assert_array_equal(x, np.array([np.inf, 1]))\n assert_array_equal(y, np.array([0, np.inf]))\n\n def test_min_int(self):\n # Could make problems because of abs(min_int) == min_int\n min_int = np.iinfo(np.int_).min\n a = np.array([min_int], dtype=np.int_)\n assert_(np.allclose(a, a))\n\n def test_equalnan(self):\n x = np.array([1.0, np.nan])\n assert_(np.allclose(x, x, equal_nan=True))\n\n def test_return_class_is_ndarray(self):\n # Issue gh-6475\n # Check that allclose does not preserve subtypes\n class Foo(np.ndarray):\n def __new__(cls, *args, **kwargs):\n return np.array(*args, **kwargs).view(cls)\n\n a = Foo([1])\n assert_(type(np.allclose(a, a)) is bool)\n\n\nclass TestIsclose(object):\n rtol = 1e-5\n atol = 1e-8\n\n def setup(self):\n atol = self.atol\n rtol = self.rtol\n arr = np.array([100, 1000])\n aran = np.arange(125).reshape((5, 5, 5))\n\n self.all_close_tests = [\n ([1, 0], [1, 0]),\n ([atol], [0]),\n ([1], [1 + rtol + atol]),\n (arr, arr + arr*rtol),\n (arr, arr + arr*rtol + atol),\n (aran, aran + aran*rtol),\n (np.inf, np.inf),\n (np.inf, [np.inf]),\n ([np.inf, -np.inf], [np.inf, -np.inf]),\n ]\n self.none_close_tests = [\n ([np.inf, 0], [1, np.inf]),\n ([np.inf, -np.inf], [1, 0]),\n ([np.inf, np.inf], [1, -np.inf]),\n ([np.inf, np.inf], [1, 0]),\n ([np.nan, 0], [np.nan, -np.inf]),\n ([atol*2], [0]),\n ([1], [1 + rtol + atol*2]),\n (aran, aran + rtol*1.1*aran + atol*1.1),\n (np.array([np.inf, 1]), np.array([0, np.inf])),\n ]\n self.some_close_tests = [\n ([np.inf, 0], [np.inf, atol*2]),\n ([atol, 1, 1e6*(1 + 2*rtol) + atol], [0, np.nan, 1e6]),\n (np.arange(3), [0, 1, 2.1]),\n (np.nan, [np.nan, np.nan, np.nan]),\n ([0], [atol, np.inf, -np.inf, np.nan]),\n (0, [atol, np.inf, -np.inf, np.nan]),\n ]\n self.some_close_results = [\n [True, False],\n [True, False, False],\n [True, True, False],\n [False, False, False],\n [True, False, False, False],\n [True, False, False, False],\n ]\n\n def test_ip_isclose(self):\n self.setup()\n tests = self.some_close_tests\n results = self.some_close_results\n for (x, y), result in zip(tests, results):\n assert_array_equal(np.isclose(x, y), result)\n\n def tst_all_isclose(self, x, y):\n assert_(np.all(np.isclose(x, y)), \"%s and %s not close\" % (x, y))\n\n def tst_none_isclose(self, x, y):\n msg = \"%s and %s shouldn't be close\"\n assert_(not np.any(np.isclose(x, y)), msg % (x, y))\n\n def tst_isclose_allclose(self, x, y):\n msg = \"isclose.all() and allclose aren't same for %s and %s\"\n msg2 = \"isclose and allclose aren't same for %s and %s\"\n if np.isscalar(x) and np.isscalar(y):\n assert_(np.isclose(x, y) == np.allclose(x, y), msg=msg2 % (x, y))\n else:\n assert_array_equal(np.isclose(x, y).all(), np.allclose(x, y), msg % (x, y))\n\n def test_ip_all_isclose(self):\n self.setup()\n for (x, y) in self.all_close_tests:\n self.tst_all_isclose(x, y)\n\n def test_ip_none_isclose(self):\n self.setup()\n for (x, y) in self.none_close_tests:\n self.tst_none_isclose(x, y)\n\n def test_ip_isclose_allclose(self):\n self.setup()\n tests = (self.all_close_tests + self.none_close_tests +\n self.some_close_tests)\n for (x, y) in tests:\n self.tst_isclose_allclose(x, y)\n\n def test_equal_nan(self):\n assert_array_equal(np.isclose(np.nan, np.nan, equal_nan=True), [True])\n arr = np.array([1.0, np.nan])\n assert_array_equal(np.isclose(arr, arr, equal_nan=True), [True, True])\n\n def test_masked_arrays(self):\n # Make sure to test the output type when arguments are interchanged.\n\n x = np.ma.masked_where([True, True, False], np.arange(3))\n assert_(type(x) is type(np.isclose(2, x)))\n assert_(type(x) is type(np.isclose(x, 2)))\n\n x = np.ma.masked_where([True, True, False], [np.nan, np.inf, np.nan])\n assert_(type(x) is type(np.isclose(np.inf, x)))\n assert_(type(x) is type(np.isclose(x, np.inf)))\n\n x = np.ma.masked_where([True, True, False], [np.nan, np.nan, np.nan])\n y = np.isclose(np.nan, x, equal_nan=True)\n assert_(type(x) is type(y))\n # Ensure that the mask isn't modified...\n assert_array_equal([True, True, False], y.mask)\n y = np.isclose(x, np.nan, equal_nan=True)\n assert_(type(x) is type(y))\n # Ensure that the mask isn't modified...\n assert_array_equal([True, True, False], y.mask)\n\n x = np.ma.masked_where([True, True, False], [np.nan, np.nan, np.nan])\n y = np.isclose(x, x, equal_nan=True)\n assert_(type(x) is type(y))\n # Ensure that the mask isn't modified...\n assert_array_equal([True, True, False], y.mask)\n\n def test_scalar_return(self):\n assert_(np.isscalar(np.isclose(1, 1)))\n\n def test_no_parameter_modification(self):\n x = np.array([np.inf, 1])\n y = np.array([0, np.inf])\n np.isclose(x, y)\n assert_array_equal(x, np.array([np.inf, 1]))\n assert_array_equal(y, np.array([0, np.inf]))\n\n def test_non_finite_scalar(self):\n # GH7014, when two scalars are compared the output should also be a\n # scalar\n assert_(np.isclose(np.inf, -np.inf) is np.False_)\n assert_(np.isclose(0, np.inf) is np.False_)\n assert_(type(np.isclose(0, np.inf)) is np.bool_)\n\n\nclass TestStdVar(object):\n def setup(self):\n self.A = np.array([1, -1, 1, -1])\n self.real_var = 1\n\n def test_basic(self):\n assert_almost_equal(np.var(self.A), self.real_var)\n assert_almost_equal(np.std(self.A)**2, self.real_var)\n\n def test_scalars(self):\n assert_equal(np.var(1), 0)\n assert_equal(np.std(1), 0)\n\n def test_ddof1(self):\n assert_almost_equal(np.var(self.A, ddof=1),\n self.real_var*len(self.A)/float(len(self.A)-1))\n assert_almost_equal(np.std(self.A, ddof=1)**2,\n self.real_var*len(self.A)/float(len(self.A)-1))\n\n def test_ddof2(self):\n assert_almost_equal(np.var(self.A, ddof=2),\n self.real_var*len(self.A)/float(len(self.A)-2))\n assert_almost_equal(np.std(self.A, ddof=2)**2,\n self.real_var*len(self.A)/float(len(self.A)-2))\n\n def test_out_scalar(self):\n d = np.arange(10)\n out = np.array(0.)\n r = np.std(d, out=out)\n assert_(r is out)\n assert_array_equal(r, out)\n r = np.var(d, out=out)\n assert_(r is out)\n assert_array_equal(r, out)\n r = np.mean(d, out=out)\n assert_(r is out)\n assert_array_equal(r, out)\n\n\nclass TestStdVarComplex(object):\n def test_basic(self):\n A = np.array([1, 1.j, -1, -1.j])\n real_var = 1\n assert_almost_equal(np.var(A), real_var)\n assert_almost_equal(np.std(A)**2, real_var)\n\n def test_scalars(self):\n assert_equal(np.var(1j), 0)\n assert_equal(np.std(1j), 0)\n\n\nclass TestCreationFuncs(object):\n # Test ones, zeros, empty and full.\n\n def setup(self):\n dtypes = {np.dtype(tp) for tp in itertools.chain(*np.sctypes.values())}\n # void, bytes, str\n variable_sized = {tp for tp in dtypes if tp.str.endswith('0')}\n self.dtypes = sorted(dtypes - variable_sized |\n {np.dtype(tp.str.replace(\"0\", str(i)))\n for tp in variable_sized for i in range(1, 10)},\n key=lambda dtype: dtype.str)\n self.orders = {'C': 'c_contiguous', 'F': 'f_contiguous'}\n self.ndims = 10\n\n def check_function(self, func, fill_value=None):\n par = ((0, 1, 2),\n range(self.ndims),\n self.orders,\n self.dtypes)\n fill_kwarg = {}\n if fill_value is not None:\n fill_kwarg = {'fill_value': fill_value}\n\n for size, ndims, order, dtype in itertools.product(*par):\n shape = ndims * [size]\n\n # do not fill void type\n if fill_kwarg and dtype.str.startswith('|V'):\n continue\n\n arr = func(shape, order=order, dtype=dtype,\n **fill_kwarg)\n\n assert_equal(arr.dtype, dtype)\n assert_(getattr(arr.flags, self.orders[order]))\n\n if fill_value is not None:\n if dtype.str.startswith('|S'):\n val = str(fill_value)\n else:\n val = fill_value\n assert_equal(arr, dtype.type(val))\n\n def test_zeros(self):\n self.check_function(np.zeros)\n\n def test_ones(self):\n self.check_function(np.zeros)\n\n def test_empty(self):\n self.check_function(np.empty)\n\n def test_full(self):\n self.check_function(np.full, 0)\n self.check_function(np.full, 1)\n\n @pytest.mark.skipif(not HAS_REFCOUNT, reason=\"Python lacks refcounts\")\n def test_for_reference_leak(self):\n # Make sure we have an object for reference\n dim = 1\n beg = sys.getrefcount(dim)\n np.zeros([dim]*10)\n assert_(sys.getrefcount(dim) == beg)\n np.ones([dim]*10)\n assert_(sys.getrefcount(dim) == beg)\n np.empty([dim]*10)\n assert_(sys.getrefcount(dim) == beg)\n np.full([dim]*10, 0)\n assert_(sys.getrefcount(dim) == beg)\n\n\nclass TestLikeFuncs(object):\n '''Test ones_like, zeros_like, empty_like and full_like'''\n\n def setup(self):\n self.data = [\n # Array scalars\n (np.array(3.), None),\n (np.array(3), 'f8'),\n # 1D arrays\n (np.arange(6, dtype='f4'), None),\n (np.arange(6), 'c16'),\n # 2D C-layout arrays\n (np.arange(6).reshape(2, 3), None),\n (np.arange(6).reshape(3, 2), 'i1'),\n # 2D F-layout arrays\n (np.arange(6).reshape((2, 3), order='F'), None),\n (np.arange(6).reshape((3, 2), order='F'), 'i1'),\n # 3D C-layout arrays\n (np.arange(24).reshape(2, 3, 4), None),\n (np.arange(24).reshape(4, 3, 2), 'f4'),\n # 3D F-layout arrays\n (np.arange(24).reshape((2, 3, 4), order='F'), None),\n (np.arange(24).reshape((4, 3, 2), order='F'), 'f4'),\n # 3D non-C/F-layout arrays\n (np.arange(24).reshape(2, 3, 4).swapaxes(0, 1), None),\n (np.arange(24).reshape(4, 3, 2).swapaxes(0, 1), '?'),\n ]\n self.shapes = [(5,), (5,6,), (5,6,7,)]\n\n def compare_array_value(self, dz, value, fill_value):\n if value is not None:\n if fill_value:\n try:\n z = dz.dtype.type(value)\n except OverflowError:\n pass\n else:\n assert_(np.all(dz == z))\n else:\n assert_(np.all(dz == value))\n\n def check_like_function(self, like_function, value, fill_value=False):\n if fill_value:\n fill_kwarg = {'fill_value': value}\n else:\n fill_kwarg = {}\n for d, dtype in self.data:\n # default (K) order, dtype\n dz = like_function(d, dtype=dtype, **fill_kwarg)\n assert_equal(dz.shape, d.shape)\n assert_equal(np.array(dz.strides)*d.dtype.itemsize,\n np.array(d.strides)*dz.dtype.itemsize)\n assert_equal(d.flags.c_contiguous, dz.flags.c_contiguous)\n assert_equal(d.flags.f_contiguous, dz.flags.f_contiguous)\n if dtype is None:\n assert_equal(dz.dtype, d.dtype)\n else:\n assert_equal(dz.dtype, np.dtype(dtype))\n self.compare_array_value(dz, value, fill_value)\n\n # C order, default dtype\n dz = like_function(d, order='C', dtype=dtype, **fill_kwarg)\n assert_equal(dz.shape, d.shape)\n assert_(dz.flags.c_contiguous)\n if dtype is None:\n assert_equal(dz.dtype, d.dtype)\n else:\n assert_equal(dz.dtype, np.dtype(dtype))\n self.compare_array_value(dz, value, fill_value)\n\n # F order, default dtype\n dz = like_function(d, order='F', dtype=dtype, **fill_kwarg)\n assert_equal(dz.shape, d.shape)\n assert_(dz.flags.f_contiguous)\n if dtype is None:\n assert_equal(dz.dtype, d.dtype)\n else:\n assert_equal(dz.dtype, np.dtype(dtype))\n self.compare_array_value(dz, value, fill_value)\n\n # A order\n dz = like_function(d, order='A', dtype=dtype, **fill_kwarg)\n assert_equal(dz.shape, d.shape)\n if d.flags.f_contiguous:\n assert_(dz.flags.f_contiguous)\n else:\n assert_(dz.flags.c_contiguous)\n if dtype is None:\n assert_equal(dz.dtype, d.dtype)\n else:\n assert_equal(dz.dtype, np.dtype(dtype))\n self.compare_array_value(dz, value, fill_value)\n\n # Test the 'shape' parameter\n for s in self.shapes:\n for o in 'CFA':\n sz = like_function(d, dtype=dtype, shape=s, order=o,\n **fill_kwarg)\n assert_equal(sz.shape, s)\n if dtype is None:\n assert_equal(sz.dtype, d.dtype)\n else:\n assert_equal(sz.dtype, np.dtype(dtype))\n if o == 'C' or (o == 'A' and d.flags.c_contiguous):\n assert_(sz.flags.c_contiguous)\n elif o == 'F' or (o == 'A' and d.flags.f_contiguous):\n assert_(sz.flags.f_contiguous)\n self.compare_array_value(sz, value, fill_value)\n\n if (d.ndim != len(s)):\n assert_equal(np.argsort(like_function(d, dtype=dtype,\n shape=s, order='K',\n **fill_kwarg).strides),\n np.argsort(np.empty(s, dtype=dtype,\n order='C').strides))\n else:\n assert_equal(np.argsort(like_function(d, dtype=dtype,\n shape=s, order='K',\n **fill_kwarg).strides),\n np.argsort(d.strides))\n\n # Test the 'subok' parameter\n class MyNDArray(np.ndarray):\n pass\n\n a = np.array([[1, 2], [3, 4]]).view(MyNDArray)\n\n b = like_function(a, **fill_kwarg)\n assert_(type(b) is MyNDArray)\n\n b = like_function(a, subok=False, **fill_kwarg)\n assert_(type(b) is not MyNDArray)\n\n def test_ones_like(self):\n self.check_like_function(np.ones_like, 1)\n\n def test_zeros_like(self):\n self.check_like_function(np.zeros_like, 0)\n\n def test_empty_like(self):\n self.check_like_function(np.empty_like, None)\n\n def test_filled_like(self):\n self.check_like_function(np.full_like, 0, True)\n self.check_like_function(np.full_like, 1, True)\n self.check_like_function(np.full_like, 1000, True)\n self.check_like_function(np.full_like, 123.456, True)\n self.check_like_function(np.full_like, np.inf, True)\n\n\nclass TestCorrelate(object):\n def _setup(self, dt):\n self.x = np.array([1, 2, 3, 4, 5], dtype=dt)\n self.xs = np.arange(1, 20)[::3]\n self.y = np.array([-1, -2, -3], dtype=dt)\n self.z1 = np.array([ -3., -8., -14., -20., -26., -14., -5.], dtype=dt)\n self.z1_4 = np.array([-2., -5., -8., -11., -14., -5.], dtype=dt)\n self.z1r = np.array([-15., -22., -22., -16., -10., -4., -1.], dtype=dt)\n self.z2 = np.array([-5., -14., -26., -20., -14., -8., -3.], dtype=dt)\n self.z2r = np.array([-1., -4., -10., -16., -22., -22., -15.], dtype=dt)\n self.zs = np.array([-3., -14., -30., -48., -66., -84.,\n -102., -54., -19.], dtype=dt)\n\n def test_float(self):\n self._setup(float)\n z = np.correlate(self.x, self.y, 'full')\n assert_array_almost_equal(z, self.z1)\n z = np.correlate(self.x, self.y[:-1], 'full')\n assert_array_almost_equal(z, self.z1_4)\n z = np.correlate(self.y, self.x, 'full')\n assert_array_almost_equal(z, self.z2)\n z = np.correlate(self.x[::-1], self.y, 'full')\n assert_array_almost_equal(z, self.z1r)\n z = np.correlate(self.y, self.x[::-1], 'full')\n assert_array_almost_equal(z, self.z2r)\n z = np.correlate(self.xs, self.y, 'full')\n assert_array_almost_equal(z, self.zs)\n\n def test_object(self):\n self._setup(Decimal)\n z = np.correlate(self.x, self.y, 'full')\n assert_array_almost_equal(z, self.z1)\n z = np.correlate(self.y, self.x, 'full')\n assert_array_almost_equal(z, self.z2)\n\n def test_no_overwrite(self):\n d = np.ones(100)\n k = np.ones(3)\n np.correlate(d, k)\n assert_array_equal(d, np.ones(100))\n assert_array_equal(k, np.ones(3))\n\n def test_complex(self):\n x = np.array([1, 2, 3, 4+1j], dtype=complex)\n y = np.array([-1, -2j, 3+1j], dtype=complex)\n r_z = np.array([3-1j, 6, 8+1j, 11+5j, -5+8j, -4-1j], dtype=complex)\n r_z = r_z[::-1].conjugate()\n z = np.correlate(y, x, mode='full')\n assert_array_almost_equal(z, r_z)\n\n\nclass TestConvolve(object):\n def test_object(self):\n d = [1.] * 100\n k = [1.] * 3\n assert_array_almost_equal(np.convolve(d, k)[2:-2], np.full(98, 3))\n\n def test_no_overwrite(self):\n d = np.ones(100)\n k = np.ones(3)\n np.convolve(d, k)\n assert_array_equal(d, np.ones(100))\n assert_array_equal(k, np.ones(3))\n\n\nclass TestArgwhere(object):\n def test_2D(self):\n x = np.arange(6).reshape((2, 3))\n assert_array_equal(np.argwhere(x > 1),\n [[0, 2],\n [1, 0],\n [1, 1],\n [1, 2]])\n\n def test_list(self):\n assert_equal(np.argwhere([4, 0, 2, 1, 3]), [[0], [2], [3], [4]])\n\n\nclass TestStringFunction(object):\n\n def test_set_string_function(self):\n a = np.array([1])\n np.set_string_function(lambda x: \"FOO\", repr=True)\n assert_equal(repr(a), \"FOO\")\n np.set_string_function(None, repr=True)\n assert_equal(repr(a), \"array([1])\")\n\n np.set_string_function(lambda x: \"FOO\", repr=False)\n assert_equal(str(a), \"FOO\")\n np.set_string_function(None, repr=False)\n assert_equal(str(a), \"[1]\")\n\n\nclass TestRoll(object):\n def test_roll1d(self):\n x = np.arange(10)\n xr = np.roll(x, 2)\n assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]))\n\n def test_roll2d(self):\n x2 = np.reshape(np.arange(10), (2, 5))\n x2r = np.roll(x2, 1)\n assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]))\n\n x2r = np.roll(x2, 1, axis=0)\n assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))\n\n x2r = np.roll(x2, 1, axis=1)\n assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))\n\n # Roll multiple axes at once.\n x2r = np.roll(x2, 1, axis=(0, 1))\n assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]]))\n\n x2r = np.roll(x2, (1, 0), axis=(0, 1))\n assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))\n\n x2r = np.roll(x2, (-1, 0), axis=(0, 1))\n assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))\n\n x2r = np.roll(x2, (0, 1), axis=(0, 1))\n assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))\n\n x2r = np.roll(x2, (0, -1), axis=(0, 1))\n assert_equal(x2r, np.array([[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]]))\n\n x2r = np.roll(x2, (1, 1), axis=(0, 1))\n assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]]))\n\n x2r = np.roll(x2, (-1, -1), axis=(0, 1))\n assert_equal(x2r, np.array([[6, 7, 8, 9, 5], [1, 2, 3, 4, 0]]))\n\n # Roll the same axis multiple times.\n x2r = np.roll(x2, 1, axis=(0, 0))\n assert_equal(x2r, np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]))\n\n x2r = np.roll(x2, 1, axis=(1, 1))\n assert_equal(x2r, np.array([[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]]))\n\n # Roll more than one turn in either direction.\n x2r = np.roll(x2, 6, axis=1)\n assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))\n\n x2r = np.roll(x2, -4, axis=1)\n assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))\n\n def test_roll_empty(self):\n x = np.array([])\n assert_equal(np.roll(x, 1), np.array([]))\n\n\nclass TestRollaxis(object):\n\n # expected shape indexed by (axis, start) for array of\n # shape (1, 2, 3, 4)\n tgtshape = {(0, 0): (1, 2, 3, 4), (0, 1): (1, 2, 3, 4),\n (0, 2): (2, 1, 3, 4), (0, 3): (2, 3, 1, 4),\n (0, 4): (2, 3, 4, 1),\n (1, 0): (2, 1, 3, 4), (1, 1): (1, 2, 3, 4),\n (1, 2): (1, 2, 3, 4), (1, 3): (1, 3, 2, 4),\n (1, 4): (1, 3, 4, 2),\n (2, 0): (3, 1, 2, 4), (2, 1): (1, 3, 2, 4),\n (2, 2): (1, 2, 3, 4), (2, 3): (1, 2, 3, 4),\n (2, 4): (1, 2, 4, 3),\n (3, 0): (4, 1, 2, 3), (3, 1): (1, 4, 2, 3),\n (3, 2): (1, 2, 4, 3), (3, 3): (1, 2, 3, 4),\n (3, 4): (1, 2, 3, 4)}\n\n def test_exceptions(self):\n a = np.arange(1*2*3*4).reshape(1, 2, 3, 4)\n assert_raises(np.AxisError, np.rollaxis, a, -5, 0)\n assert_raises(np.AxisError, np.rollaxis, a, 0, -5)\n assert_raises(np.AxisError, np.rollaxis, a, 4, 0)\n assert_raises(np.AxisError, np.rollaxis, a, 0, 5)\n\n def test_results(self):\n a = np.arange(1*2*3*4).reshape(1, 2, 3, 4).copy()\n aind = np.indices(a.shape)\n assert_(a.flags['OWNDATA'])\n for (i, j) in self.tgtshape:\n # positive axis, positive start\n res = np.rollaxis(a, axis=i, start=j)\n i0, i1, i2, i3 = aind[np.array(res.shape) - 1]\n assert_(np.all(res[i0, i1, i2, i3] == a))\n assert_(res.shape == self.tgtshape[(i, j)], str((i,j)))\n assert_(not res.flags['OWNDATA'])\n\n # negative axis, positive start\n ip = i + 1\n res = np.rollaxis(a, axis=-ip, start=j)\n i0, i1, i2, i3 = aind[np.array(res.shape) - 1]\n assert_(np.all(res[i0, i1, i2, i3] == a))\n assert_(res.shape == self.tgtshape[(4 - ip, j)])\n assert_(not res.flags['OWNDATA'])\n\n # positive axis, negative start\n jp = j + 1 if j < 4 else j\n res = np.rollaxis(a, axis=i, start=-jp)\n i0, i1, i2, i3 = aind[np.array(res.shape) - 1]\n assert_(np.all(res[i0, i1, i2, i3] == a))\n assert_(res.shape == self.tgtshape[(i, 4 - jp)])\n assert_(not res.flags['OWNDATA'])\n\n # negative axis, negative start\n ip = i + 1\n jp = j + 1 if j < 4 else j\n res = np.rollaxis(a, axis=-ip, start=-jp)\n i0, i1, i2, i3 = aind[np.array(res.shape) - 1]\n assert_(np.all(res[i0, i1, i2, i3] == a))\n assert_(res.shape == self.tgtshape[(4 - ip, 4 - jp)])\n assert_(not res.flags['OWNDATA'])\n\n\nclass TestMoveaxis(object):\n def test_move_to_end(self):\n x = np.random.randn(5, 6, 7)\n for source, expected in [(0, (6, 7, 5)),\n (1, (5, 7, 6)),\n (2, (5, 6, 7)),\n (-1, (5, 6, 7))]:\n actual = np.moveaxis(x, source, -1).shape\n assert_(actual, expected)\n\n def test_move_new_position(self):\n x = np.random.randn(1, 2, 3, 4)\n for source, destination, expected in [\n (0, 1, (2, 1, 3, 4)),\n (1, 2, (1, 3, 2, 4)),\n (1, -1, (1, 3, 4, 2)),\n ]:\n actual = np.moveaxis(x, source, destination).shape\n assert_(actual, expected)\n\n def test_preserve_order(self):\n x = np.zeros((1, 2, 3, 4))\n for source, destination in [\n (0, 0),\n (3, -1),\n (-1, 3),\n ([0, -1], [0, -1]),\n ([2, 0], [2, 0]),\n (range(4), range(4)),\n ]:\n actual = np.moveaxis(x, source, destination).shape\n assert_(actual, (1, 2, 3, 4))\n\n def test_move_multiples(self):\n x = np.zeros((0, 1, 2, 3))\n for source, destination, expected in [\n ([0, 1], [2, 3], (2, 3, 0, 1)),\n ([2, 3], [0, 1], (2, 3, 0, 1)),\n ([0, 1, 2], [2, 3, 0], (2, 3, 0, 1)),\n ([3, 0], [1, 0], (0, 3, 1, 2)),\n ([0, 3], [0, 1], (0, 3, 1, 2)),\n ]:\n actual = np.moveaxis(x, source, destination).shape\n assert_(actual, expected)\n\n def test_errors(self):\n x = np.random.randn(1, 2, 3)\n assert_raises_regex(np.AxisError, 'source.*out of bounds',\n np.moveaxis, x, 3, 0)\n assert_raises_regex(np.AxisError, 'source.*out of bounds',\n np.moveaxis, x, -4, 0)\n assert_raises_regex(np.AxisError, 'destination.*out of bounds',\n np.moveaxis, x, 0, 5)\n assert_raises_regex(ValueError, 'repeated axis in `source`',\n np.moveaxis, x, [0, 0], [0, 1])\n assert_raises_regex(ValueError, 'repeated axis in `destination`',\n np.moveaxis, x, [0, 1], [1, 1])\n assert_raises_regex(ValueError, 'must have the same number',\n np.moveaxis, x, 0, [0, 1])\n assert_raises_regex(ValueError, 'must have the same number',\n np.moveaxis, x, [0, 1], [0])\n\n def test_array_likes(self):\n x = np.ma.zeros((1, 2, 3))\n result = np.moveaxis(x, 0, 0)\n assert_(x.shape, result.shape)\n assert_(isinstance(result, np.ma.MaskedArray))\n\n x = [1, 2, 3]\n result = np.moveaxis(x, 0, 0)\n assert_(x, list(result))\n assert_(isinstance(result, np.ndarray))\n\n\nclass TestCross(object):\n def test_2x2(self):\n u = [1, 2]\n v = [3, 4]\n z = -2\n cp = np.cross(u, v)\n assert_equal(cp, z)\n cp = np.cross(v, u)\n assert_equal(cp, -z)\n\n def test_2x3(self):\n u = [1, 2]\n v = [3, 4, 5]\n z = np.array([10, -5, -2])\n cp = np.cross(u, v)\n assert_equal(cp, z)\n cp = np.cross(v, u)\n assert_equal(cp, -z)\n\n def test_3x3(self):\n u = [1, 2, 3]\n v = [4, 5, 6]\n z = np.array([-3, 6, -3])\n cp = np.cross(u, v)\n assert_equal(cp, z)\n cp = np.cross(v, u)\n assert_equal(cp, -z)\n\n def test_broadcasting(self):\n # Ticket #2624 (Trac #2032)\n u = np.tile([1, 2], (11, 1))\n v = np.tile([3, 4], (11, 1))\n z = -2\n assert_equal(np.cross(u, v), z)\n assert_equal(np.cross(v, u), -z)\n assert_equal(np.cross(u, u), 0)\n\n u = np.tile([1, 2], (11, 1)).T\n v = np.tile([3, 4, 5], (11, 1))\n z = np.tile([10, -5, -2], (11, 1))\n assert_equal(np.cross(u, v, axisa=0), z)\n assert_equal(np.cross(v, u.T), -z)\n assert_equal(np.cross(v, v), 0)\n\n u = np.tile([1, 2, 3], (11, 1)).T\n v = np.tile([3, 4], (11, 1)).T\n z = np.tile([-12, 9, -2], (11, 1))\n assert_equal(np.cross(u, v, axisa=0, axisb=0), z)\n assert_equal(np.cross(v.T, u.T), -z)\n assert_equal(np.cross(u.T, u.T), 0)\n\n u = np.tile([1, 2, 3], (5, 1))\n v = np.tile([4, 5, 6], (5, 1)).T\n z = np.tile([-3, 6, -3], (5, 1))\n assert_equal(np.cross(u, v, axisb=0), z)\n assert_equal(np.cross(v.T, u), -z)\n assert_equal(np.cross(u, u), 0)\n\n def test_broadcasting_shapes(self):\n u = np.ones((2, 1, 3))\n v = np.ones((5, 3))\n assert_equal(np.cross(u, v).shape, (2, 5, 3))\n u = np.ones((10, 3, 5))\n v = np.ones((2, 5))\n assert_equal(np.cross(u, v, axisa=1, axisb=0).shape, (10, 5, 3))\n assert_raises(np.AxisError, np.cross, u, v, axisa=1, axisb=2)\n assert_raises(np.AxisError, np.cross, u, v, axisa=3, axisb=0)\n u = np.ones((10, 3, 5, 7))\n v = np.ones((5, 7, 2))\n assert_equal(np.cross(u, v, axisa=1, axisc=2).shape, (10, 5, 3, 7))\n assert_raises(np.AxisError, np.cross, u, v, axisa=-5, axisb=2)\n assert_raises(np.AxisError, np.cross, u, v, axisa=1, axisb=-4)\n # gh-5885\n u = np.ones((3, 4, 2))\n for axisc in range(-2, 2):\n assert_equal(np.cross(u, u, axisc=axisc).shape, (3, 4))\n\n\ndef test_outer_out_param():\n arr1 = np.ones((5,))\n arr2 = np.ones((2,))\n arr3 = np.linspace(-2, 2, 5)\n out1 = np.ndarray(shape=(5,5))\n out2 = np.ndarray(shape=(2, 5))\n res1 = np.outer(arr1, arr3, out1)\n assert_equal(res1, out1)\n assert_equal(np.outer(arr2, arr3, out2), out2)\n\n\nclass TestRequire(object):\n flag_names = ['C', 'C_CONTIGUOUS', 'CONTIGUOUS',\n 'F', 'F_CONTIGUOUS', 'FORTRAN',\n 'A', 'ALIGNED',\n 'W', 'WRITEABLE',\n 'O', 'OWNDATA']\n\n def generate_all_false(self, dtype):\n arr = np.zeros((2, 2), [('junk', 'i1'), ('a', dtype)])\n arr.setflags(write=False)\n a = arr['a']\n assert_(not a.flags['C'])\n assert_(not a.flags['F'])\n assert_(not a.flags['O'])\n assert_(not a.flags['W'])\n assert_(not a.flags['A'])\n return a\n\n def set_and_check_flag(self, flag, dtype, arr):\n if dtype is None:\n dtype = arr.dtype\n b = np.require(arr, dtype, [flag])\n assert_(b.flags[flag])\n assert_(b.dtype == dtype)\n\n # a further call to np.require ought to return the same array\n # unless OWNDATA is specified.\n c = np.require(b, None, [flag])\n if flag[0] != 'O':\n assert_(c is b)\n else:\n assert_(c.flags[flag])\n\n def test_require_each(self):\n\n id = ['f8', 'i4']\n fd = [None, 'f8', 'c16']\n for idtype, fdtype, flag in itertools.product(id, fd, self.flag_names):\n a = self.generate_all_false(idtype)\n self.set_and_check_flag(flag, fdtype, a)\n\n def test_unknown_requirement(self):\n a = self.generate_all_false('f8')\n assert_raises(KeyError, np.require, a, None, 'Q')\n\n def test_non_array_input(self):\n a = np.require([1, 2, 3, 4], 'i4', ['C', 'A', 'O'])\n assert_(a.flags['O'])\n assert_(a.flags['C'])\n assert_(a.flags['A'])\n assert_(a.dtype == 'i4')\n assert_equal(a, [1, 2, 3, 4])\n\n def test_C_and_F_simul(self):\n a = self.generate_all_false('f8')\n assert_raises(ValueError, np.require, a, None, ['C', 'F'])\n\n def test_ensure_array(self):\n class ArraySubclass(np.ndarray):\n pass\n\n a = ArraySubclass((2, 2))\n b = np.require(a, None, ['E'])\n assert_(type(b) is np.ndarray)\n\n def test_preserve_subtype(self):\n class ArraySubclass(np.ndarray):\n pass\n\n for flag in self.flag_names:\n a = ArraySubclass((2, 2))\n self.set_and_check_flag(flag, None, a)\n\n\nclass TestBroadcast(object):\n def test_broadcast_in_args(self):\n # gh-5881\n arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)),\n np.empty((5, 1, 7))]\n mits = [np.broadcast(*arrs),\n np.broadcast(np.broadcast(*arrs[:2]), np.broadcast(*arrs[2:])),\n np.broadcast(arrs[0], np.broadcast(*arrs[1:-1]), arrs[-1])]\n for mit in mits:\n assert_equal(mit.shape, (5, 6, 7))\n assert_equal(mit.ndim, 3)\n assert_equal(mit.nd, 3)\n assert_equal(mit.numiter, 4)\n for a, ia in zip(arrs, mit.iters):\n assert_(a is ia.base)\n\n def test_broadcast_single_arg(self):\n # gh-6899\n arrs = [np.empty((5, 6, 7))]\n mit = np.broadcast(*arrs)\n assert_equal(mit.shape, (5, 6, 7))\n assert_equal(mit.ndim, 3)\n assert_equal(mit.nd, 3)\n assert_equal(mit.numiter, 1)\n assert_(arrs[0] is mit.iters[0].base)\n\n def test_number_of_arguments(self):\n arr = np.empty((5,))\n for j in range(35):\n arrs = [arr] * j\n if j < 1 or j > 32:\n assert_raises(ValueError, np.broadcast, *arrs)\n else:\n mit = np.broadcast(*arrs)\n assert_equal(mit.numiter, j)\n\n\nclass TestKeepdims(object):\n\n class sub_array(np.ndarray):\n def sum(self, axis=None, dtype=None, out=None):\n return np.ndarray.sum(self, axis, dtype, out, keepdims=True)\n\n def test_raise(self):\n sub_class = self.sub_array\n x = np.arange(30).view(sub_class)\n assert_raises(TypeError, np.sum, x, keepdims=True)\n\n\nclass TestTensordot(object):\n\n def test_zero_dimension(self):\n # Test resolution to issue #5663\n a = np.ndarray((3,0))\n b = np.ndarray((0,4))\n td = np.tensordot(a, b, (1, 0))\n assert_array_equal(td, np.dot(a, b))\n assert_array_equal(td, np.einsum('ij,jk', a, b))\n \n def test_zero_dimensional(self):\n # gh-12130\n arr_0d = np.array(1)\n ret = np.tensordot(arr_0d, arr_0d, ([], [])) # contracting no axes is well defined\n assert_array_equal(ret, arr_0d)\n"
]
| [
[
"numpy.binary_repr",
"numpy.broadcast",
"numpy.all",
"numpy.searchsorted",
"numpy.ma.masked_where",
"numpy.complex64",
"numpy.full",
"numpy.outer",
"numpy.zeros",
"numpy.testing.assert_raises_regex",
"numpy.sctypes.values",
"numpy.testing.assert_raises",
"numpy.array",
"numpy.sum",
"numpy.void",
"numpy.indices",
"numpy.argwhere",
"numpy.testing.assert_array_equal",
"numpy.add",
"numpy.isinf",
"numpy.complex128",
"numpy.resize",
"numpy.asarray",
"numpy.ndarray",
"numpy.promote_types",
"numpy.seterr",
"numpy.geterrobj",
"numpy.iinfo",
"numpy.var",
"numpy.divide",
"numpy.allclose",
"numpy.uint32",
"numpy.reshape",
"numpy.less",
"numpy.float16",
"numpy.std",
"numpy.size",
"numpy.float32",
"numpy.int64",
"numpy.base_repr",
"numpy.random.rand",
"numpy.testing.assert_",
"numpy.require",
"numpy.errstate",
"numpy.random.RandomState",
"numpy.ptp",
"numpy.ones",
"numpy.isscalar",
"numpy.empty",
"numpy.rollaxis",
"numpy.logical_xor",
"numpy.can_cast",
"numpy.take",
"numpy.linspace",
"numpy.around",
"numpy.longdouble",
"numpy.ndarray.sum",
"numpy.alltrue",
"numpy.mean",
"numpy.zeros_like",
"numpy.moveaxis",
"numpy.bool_",
"numpy.roll",
"numpy.trace",
"numpy.random.randint",
"numpy.testing.assert_equal",
"numpy.swapaxes",
"numpy.greater",
"numpy.clip",
"numpy.cumproduct",
"numpy.eye",
"numpy.int8",
"numpy.choose",
"numpy.uint16",
"numpy.count_nonzero",
"numpy.repeat",
"numpy.testing.assert_array_almost_equal",
"numpy.logical_not",
"numpy.set_string_function",
"numpy.nonzero",
"numpy.isnan",
"numpy.logical_or",
"numpy.transpose",
"numpy.argsort",
"numpy.correlate",
"numpy.diagonal",
"numpy.convolve",
"numpy.tile",
"numpy.uint64",
"numpy.dot",
"numpy.einsum",
"numpy.squeeze",
"numpy.dtype",
"numpy.random.randn",
"numpy.any",
"numpy.cross",
"numpy.clongdouble",
"numpy.obj2sctype",
"numpy.geterr",
"numpy.arange",
"numpy.uint8",
"numpy.empty_like",
"numpy.finfo",
"numpy.tensordot",
"numpy.ravel",
"numpy.ma.zeros",
"numpy.isclose",
"numpy.seterrobj",
"numpy.signbit",
"numpy.logical_and",
"numpy.abs",
"numpy.isfinite",
"numpy.intp",
"numpy.int32",
"numpy.compress",
"numpy.int16",
"numpy.result_type",
"numpy.float64",
"numpy.prod"
]
]
|
dheerajgupta0001/wrldc_mis_monthly_report_generator | [
"dd5ae6f28ec6bf8e6532820fd71dd63f8b223f0b"
]
| [
"src/app/section_1_11/section_1_11_GenCurve.py"
]
| [
"import datetime as dt\nfrom typing import List\nfrom src.repos.metricsData.metricsDataRepo import MetricsDataRepo\nfrom src.utils.addMonths import addMonths\nfrom src.config.appConfig import getREConstituentsMappings\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\n### Generation Curvers of Wind and Wind and Solar Combined\n\ndef fetchSection1_11_GenerationCurve(appDbConnStr: str, startDt: dt.datetime, endDt: dt.datetime):\n windWR = fetchSection1_11_WindGenCurveContext(appDbConnStr ,startDt, endDt)\n solarWR = fetchSection1_11_WindSolarCombinedWR(appDbConnStr ,startDt, endDt)\n\n secData :dict = {}\n\n secData['windWR'] = windWR\n secData['solarWR'] = solarWR\n\n return secData\n\ndef fetchSection1_11_WindSolarCombinedWR(appDbConnStr: str, startDt: dt.datetime, endDt: dt.datetime):\n mRepo = MetricsDataRepo(appDbConnStr)\n\n hourlyGenerationObj = [] \n hourlyGen = mRepo.getEntityMetricHourlyData('wr','Wind(MW)',startDt,endDt) \n hourlyGenerationObj.append(hourlyGen)\n\n hourlyGen = mRepo.getEntityMetricHourlyData('wr','Solar(MW)',startDt,endDt) \n hourlyGenerationObj.append(hourlyGen)\n\n if(len(hourlyGenerationObj) > 0):\n pltDataObj:list = []\n\n for temp in range(len(hourlyGenerationObj)):\n \n pltDataObj = pltDataObj + [{'Hours': x[\"time_stamp\"], 'colName': 'Total Solar' if x['metric_name'] == 'Solar(MW)' else 'Total Wind',\n 'val': x[\"data_value\"]} for x in hourlyGenerationObj[temp] ]\n \n pltDataDf = pd.DataFrame(pltDataObj)\n\n pltDataDf = pltDataDf.pivot(index='Hours',columns='colName',values='val')\n pltDataDf.reset_index(inplace=True)\n pltDataDf.to_excel(\"assets/plot_1_11_WindSolarGenCurve.xlsx\", index=True)\n\n pltTitle = 'Wind Gen. & Solar Gen. curve {0} '.format(startDt.strftime('%b-%y'))\n\n fig, ax = plt.subplots(figsize=(7.5, 5.6))\n\n ax.set_title(pltTitle)\n ax.set_ylabel('MW')\n ax.set_xlabel('Time')\n\n ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y %H:%M'))\n\n clr = ['#00ccff', '#ff8533']\n for col in range(len(pltDataDf.columns)-1):\n ax.plot(pltDataDf['Hours'], pltDataDf[pltDataDf.columns[col+1]], color=clr[col], label=pltDataDf.columns[col+1])\n\n\n ax.yaxis.grid(True)\n ax.legend( loc='best',\n ncol=4, borderaxespad=0.)\n\n \n plt.xticks(rotation=90)\n ax.set_xlim(xmin=startDt , xmax= endDt)\n fig.subplots_adjust(bottom=0.25, top=0.8)\n\n fig.savefig('assets/section_1_11_WindSolarGenCurve.png')\n # plt.close()\n\n secData: dict = {}\n \n return secData\n \ndef fetchSection1_11_WindGenCurveContext(appDbConnStr: str, startDt: dt.datetime, endDt: dt.datetime) :\n constituentsInfos = getREConstituentsMappings()\n mRepo = MetricsDataRepo(appDbConnStr)\n\n hourlyGenerationObj = [] \n for cIter in range(len(constituentsInfos)):\n constInfo = constituentsInfos[cIter]\n\n if(pd.isna(constInfo['windCapacity'])):\n continue\n\n hourlyGen = mRepo.getEntityMetricHourlyData(constInfo['entity_tag'],'Wind(MW)',startDt,endDt) \n hourlyGenerationObj.append(hourlyGen)\n\n\n if(len(hourlyGenerationObj) > 0):\n pltDataObj:list = []\n\n for temp in range(len(hourlyGenerationObj)):\n pltDataObj = pltDataObj + [{'Hours': x[\"time_stamp\"], 'colName': x['entity_tag'],\n 'val': x[\"data_value\"]} for x in hourlyGenerationObj[temp] ]\n \n pltDataDf = pd.DataFrame(pltDataObj)\n\n pltDataDf = pltDataDf.pivot(index='Hours',columns='colName',values='val')\n pltDataDf.reset_index(inplace=True)\n pltDataDf.to_excel(\"assets/plot_1_11_windGenCurve.xlsx\", index=True)\n\n pltTitle = 'Wind Gen Curve {0} '.format(startDt.strftime('%b-%y'))\n\n fig, ax = plt.subplots(figsize=(7.5, 5.6))\n\n ax.set_title(pltTitle)\n ax.set_ylabel('MW')\n ax.set_xlabel('Time')\n\n ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y %H:%M'))\n\n clr = ['#00ccff', '#ff8533', '#ff0000', '#9900ff','#00ff88']\n for col in range(1,len(pltDataDf.columns)):\n ax.plot(pltDataDf['Hours'], pltDataDf[pltDataDf.columns[col]], color=clr[col-1], label=pltDataDf.columns[col])\n\n\n ax.yaxis.grid(True)\n ax.legend(loc='best',\n ncol=4, borderaxespad=0.)\n\n \n plt.xticks(rotation=90)\n ax.set_xlim(xmin=startDt , xmax= endDt)\n fig.subplots_adjust(bottom=0.25, top=0.8)\n\n fig.savefig('assets/section_1_11_windGenCurve.png')\n # plt.close()\n\n secData: dict = {}\n \n return secData\n"
]
| [
[
"matplotlib.dates.DateFormatter",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"pandas.isna",
"matplotlib.dates.DayLocator",
"matplotlib.pyplot.xticks"
]
]
|
gcampax/tensorflow_estimator | [
"ef9b7fb5ab275677fdc2adee698cde2d2294d4fd"
]
| [
"tensorflow_estimator/python/estimator/canned/dnn_estimator_test.py"
]
| [
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for DNNEstimatorV2.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport shutil\nimport tempfile\n\nimport numpy as np\nimport six\n\nfrom tensorflow.python.feature_column import feature_column_lib as feature_column\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops.losses import losses\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.summary.writer import writer_cache\nfrom tensorflow_estimator.python.estimator.canned import dnn\nfrom tensorflow_estimator.python.estimator.canned import dnn_testing_utils\nfrom tensorflow_estimator.python.estimator.canned import prediction_keys\nfrom tensorflow_estimator.python.estimator.export import export\nfrom tensorflow_estimator.python.estimator.head import multi_class_head\nfrom tensorflow_estimator.python.estimator.head import regression_head\nfrom tensorflow_estimator.python.estimator.inputs import numpy_io\n\n\ndef _dnn_estimator_fn(weight_column=None, label_dimension=1, **kwargs):\n \"\"\"Returns a DNNEstimator that uses regression_head.\"\"\"\n return dnn.DNNEstimatorV2(\n head=regression_head.RegressionHead(\n weight_column=weight_column,\n label_dimension=label_dimension,\n # Tests in core (from which this test inherits) test the sum loss.\n loss_reduction=losses.Reduction.SUM_OVER_BATCH_SIZE),\n **kwargs)\n\n\ndef _dnn_estimator_classifier_fn(n_classes=3, **kwargs):\n return dnn.DNNEstimatorV2(\n head=multi_class_head.MultiClassHead(\n n_classes=n_classes),\n **kwargs)\n\n\nclass DNNEstimatorEvaluateTest(dnn_testing_utils.BaseDNNRegressorEvaluateTest,\n test.TestCase):\n\n def __init__(self, methodName='runTest'): # pylint: disable=invalid-name\n test.TestCase.__init__(self, methodName)\n dnn_testing_utils.BaseDNNRegressorEvaluateTest.__init__(\n self, _dnn_estimator_fn)\n\n\nclass DNNEstimatorPredictTest(dnn_testing_utils.BaseDNNRegressorPredictTest,\n test.TestCase):\n\n def __init__(self, methodName='runTest'): # pylint: disable=invalid-name\n test.TestCase.__init__(self, methodName)\n dnn_testing_utils.BaseDNNRegressorPredictTest.__init__(\n self, _dnn_estimator_fn)\n\n\nclass DNNEstimatorTrainTest(dnn_testing_utils.BaseDNNRegressorTrainTest,\n test.TestCase):\n\n def __init__(self, methodName='runTest'): # pylint: disable=invalid-name\n test.TestCase.__init__(self, methodName)\n dnn_testing_utils.BaseDNNRegressorTrainTest.__init__(\n self, _dnn_estimator_fn)\n\n\nclass DNNEstimatorWarmStartingTest(dnn_testing_utils.BaseDNNWarmStartingTest,\n test.TestCase):\n\n def __init__(self, methodName='runTest'): # pylint: disable=invalid-name\n test.TestCase.__init__(self, methodName)\n dnn_testing_utils.BaseDNNWarmStartingTest.__init__(\n self, _dnn_estimator_classifier_fn, _dnn_estimator_fn)\n\n\nclass DNNEstimatorIntegrationTest(test.TestCase):\n\n def setUp(self):\n self._model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self._model_dir:\n writer_cache.FileWriterCache.clear()\n shutil.rmtree(self._model_dir)\n\n def _test_complete_flow(self, train_input_fn, eval_input_fn, predict_input_fn,\n input_dimension, label_dimension, batch_size):\n feature_columns = [\n feature_column.numeric_column('x', shape=(input_dimension,))\n ]\n est = dnn.DNNEstimatorV2(\n head=regression_head.RegressionHead(label_dimension=label_dimension),\n hidden_units=(2, 2),\n feature_columns=feature_columns,\n model_dir=self._model_dir)\n\n # Train\n num_steps = 10\n est.train(train_input_fn, steps=num_steps)\n\n # Evaluate\n scores = est.evaluate(eval_input_fn)\n self.assertEqual(num_steps, scores[ops.GraphKeys.GLOBAL_STEP])\n self.assertIn('loss', six.iterkeys(scores))\n\n # Predict\n predictions = np.array([\n x[prediction_keys.PredictionKeys.PREDICTIONS]\n for x in est.predict(predict_input_fn)\n ])\n self.assertAllEqual((batch_size, label_dimension), predictions.shape)\n\n # Export\n feature_spec = feature_column.make_parse_example_spec(feature_columns)\n serving_input_receiver_fn = export.build_parsing_serving_input_receiver_fn(\n feature_spec)\n export_dir = est.export_saved_model(tempfile.mkdtemp(),\n serving_input_receiver_fn)\n self.assertTrue(gfile.Exists(export_dir))\n\n def test_numpy_input_fn(self):\n \"\"\"Tests complete flow with numpy_input_fn.\"\"\"\n label_dimension = 2\n batch_size = 10\n data = np.linspace(0., 2., batch_size * label_dimension, dtype=np.float32)\n data = data.reshape(batch_size, label_dimension)\n # learn y = x\n train_input_fn = numpy_io.numpy_input_fn(\n x={'x': data},\n y=data,\n batch_size=batch_size,\n num_epochs=None,\n shuffle=True)\n eval_input_fn = numpy_io.numpy_input_fn(\n x={'x': data}, y=data, batch_size=batch_size, shuffle=False)\n predict_input_fn = numpy_io.numpy_input_fn(\n x={'x': data}, batch_size=batch_size, shuffle=False)\n\n self._test_complete_flow(\n train_input_fn=train_input_fn,\n eval_input_fn=eval_input_fn,\n predict_input_fn=predict_input_fn,\n input_dimension=label_dimension,\n label_dimension=label_dimension,\n batch_size=batch_size)\n\n\nif __name__ == '__main__':\n test.main()\n"
]
| [
[
"numpy.linspace",
"tensorflow.python.platform.test.TestCase.__init__",
"tensorflow.python.platform.gfile.Exists",
"tensorflow.python.platform.test.main",
"tensorflow.python.feature_column.feature_column_lib.make_parse_example_spec",
"tensorflow.python.summary.writer.writer_cache.FileWriterCache.clear",
"tensorflow.python.feature_column.feature_column_lib.numeric_column"
]
]
|
sisl/Chimp | [
"39aecc18a635ce2608b3f604310dedd738946574"
]
| [
"chimp/simulators/pomdp/models/tools/belief.py"
]
| [
"import numpy as np\nfrom copy import deepcopy\n\n#################################################################\n# Implements Belief and Belief Updater\n#################################################################\n\nclass DiscreteBelief():\n\n def __init__(self, n):\n self.bold = np.zeros(n) + 1.0/n\n self.bnew = np.zeros(n) + 1.0/n\n self.n = n\n\n def __getitem__(self, idx):\n return self.bnew[idx]\n\n def __setitem__(self, idx, val):\n self.bold[idx] = val\n self.bnew[idx] = val\n\n def update(self, pomdp, a, o):\n \n # swap pointers\n (bnew, bold) = (self.bold, self.bnew)\n\n sspace = pomdp.states()\n \n td = pomdp.create_transition_distribution()\n od = pomdp.create_observation_distribution()\n\n # old belief is now new, new is fresh\n bnew.fill(0.0)\n\n for (i, sp) in enumerate(sspace):\n # get the distributions\n od = pomdp.observation(sp, a, od)\n # get the prob of o from the current distribution\n probo = pomdp.observation_pdf(od, o)\n # if observation prob is 0.0, then skip rest of update b/c bnew[i] is zero\n if probo == 0.0:\n continue\n b_sum = 0.0 # belef for state sp\n for (j, s) in enumerate(sspace):\n td = pomdp.transition(s, a, td)\n pp = pomdp.transition_pdf(td, sp)\n b_sum += pp * bold[j]\n bnew[i] = probo * b_sum\n norm = sum(bnew)\n for i in range(self.length()):\n bnew[i] /= norm\n (self.bnew, self.bold) = (bnew, bold)\n return self\n\n def length(self):\n return self.n\n\n def empty(self):\n self.bold.fill(0.0)\n self.bnew.fill(0.0)\n\n def empty_old(self):\n self.bold.fill(0.0)\n\n def empty_new(self):\n self.bnew.fill(0.0)\n\n def old_belief(self):\n return self.bold\n\n def new_belief(self):\n return self.bnew\n\n"
]
| [
[
"numpy.zeros"
]
]
|
alexanderkell/elecsim | [
"35e400809759a8e9a9baa3776344e383b13d8c54"
]
| [
"elecsim/data_manipulation/data_modifications/inverse_transform_sampling.py"
]
| [
"import numpy as np\nimport numpy.random as ra\n\"\"\"\nFile name: inverse_transform_sampling\nDate created: 10/01/2019\nFeature: # Generate random numbers from a custom distribution\n\"\"\"\n\n__author__ = \"Alexander Kell\"\n__copyright__ = \"Copyright 2018, Alexander Kell\"\n__license__ = \"MIT\"\n__email__ = \"[email protected]\"\n\n\ndef sample_from_custom_distribution(count, division, n_samples):\n prob = [c/sum(count) for c in count]\n prob_sum = np.cumsum(prob)\n N=n_samples\n R=ra.uniform(0, 1, N)\n\n prob_sum = np.array(prob_sum)\n division = np.array(division)\n\n generate_points = [division[np.argwhere(prob_sum == min(prob_sum[(prob_sum - r) > 0]))][0][0] for r in R]\n if n_samples > 1:\n return generate_points\n elif n_samples == 1:\n return generate_points[0]\n"
]
| [
[
"numpy.random.uniform",
"numpy.array",
"numpy.cumsum"
]
]
|
Siddharthm10/Face_Recognition_and_detection | [
"018a2cd5800ab69fd3bbfa76c0ac874e65845412"
]
| [
"face_recognition/basic_api/f_recognition.py"
]
| [
"\nif __name__ == \"__main__\":\n \n import cv2\n import numpy as np\n import face_recognition as fr\n import os\n from datetime import datetime\n import time\n import json\n\n path = 'face_recognition/basic_api/images/known'\n images = []\n classNames = []\n tolerance = 0.6\n fpsReport = 0\n name = \"Unknown\"\n scaleFactor = 0.5\n myList = os.listdir(path)\n for cls in myList:\n curImg = cv2.imread(f'{path}/{cls}')\n images.append(curImg)\n classNames.append(os.path.splitext(cls)[0])\n\n # encodeListKnown = findEncodings(images)\n with open(\"face_recognition/basic_api/encodings.json\", 'r+') as f:\n data = json.load(f)\n\n encodeListKnown = list(data.values())\n\n cap = cv2.VideoCapture(0)\n # cap = cv2.VideoCapture('rtsp://admin:[email protected]:554/')\n\n count = 0\n # start = time.time()\n while True:\n timeStamp = cv2.getTickCount()\n success, img = cap.read()\n # img = img[:][150:]\n imgS = cv2.resize(img, (0,0), None, scaleFactor, scaleFactor)\n imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)\n count +=1 \n\n facesCurFrame = fr.face_locations(imgS, number_of_times_to_upsample=1)\n encodeCurFrame = fr.face_encodings(imgS, facesCurFrame)\n for encodeFace, faceLoc in zip(encodeCurFrame, facesCurFrame):\n matches = fr.compare_faces(encodeListKnown, encodeFace)\n faceDis = fr.face_distance(encodeListKnown, encodeFace)\n\n matchIndex = np.argmin(faceDis)\n if faceDis[matchIndex]<tolerance:\n if matches[matchIndex]:\n name = classNames[matchIndex]\n y1, x2, y2, x1 = faceLoc\n y1, x2, y2, x1 = int(y1/scaleFactor), int(x2/scaleFactor), int(y2/scaleFactor), int(x1/scaleFactor)\n cv2.rectangle(img, (x1,y1), (x2,y2), (0,255,0),1)\n cv2.rectangle(img, (x1,y2-35), (x2,y2),(0,255,255), cv2.FILLED)\n cv2.putText(img, name, (x1+10,y2-10), cv2.FONT_HERSHEY_COMPLEX, 0.75, (0,0,0),1)\n # cv2.imwrite(\"output.jpg\", img)\n # markAttendance(name)\n else:\n y1, x2, y2, x1 = faceLoc\n y1, x2, y2, x1 = int(y1/scaleFactor), int(x2/scaleFactor), int(y2/scaleFactor), int(x1/scaleFactor)\n cv2.rectangle(img, (x1,y1), (x2,y2), (0,0,255),2)\n cv2.rectangle(img, (x1,y2-35), (x2,y2),(0,255,255), cv2.FILLED)\n cv2.putText(img, name, (x1+6,y2-6), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,0),2)\n\n else:\n y1, x2, y2, x1 = faceLoc\n y1, x2, y2, x1 = int(y1/scaleFactor), int(x2/scaleFactor), int(y2/scaleFactor), int(x1/scaleFactor)\n cv2.rectangle(img, (x1,y1), (x2,y2), (0,0,255),2)\n cv2.rectangle(img, (x1,y2-35), (x2,y2),(0,255,255), cv2.FILLED)\n cv2.putText(img, name, (x1+10, y2-10), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,0), 1)\n\n \n cv2.imshow(\"Webcam\", img)\n count+=1\n # dt = time.time() - timeStamp\n fps = cv2.getTickFrequency()/(cv2.getTickCount() - timeStamp)\n fpsReport = 0.95*fpsReport + 0.05*fps\n print(fpsReport)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n if(count>120):\n break\n # end = time.time()\n # duration = end - start\n # fps = 120/duration\n # print(fps)\n # print(fps) #- 5.2677 at 1/4 times resolution\n # - 9.026 at 1/2 times resolution\n\n cap.release()\n cv2.destroyAllWindows()\n\n"
]
| [
[
"numpy.argmin"
]
]
|
qcware/bmw | [
"761e405587bffe5dc4ca9f79432a79df2c7fd8f8"
]
| [
"prod-1/2-prod/verify/data_visualization/plot_rules.py"
]
| [
"import bmw \nimport numpy as np\nimport matplotlib.pyplot as plt \n\nproblem = bmw.Problem.parse(filepath='../../../../data/3-refined')\n\ndat = np.load('../../test-0.npz')\nconstellation = dat['constellation']\nconstellation_type_indices = dat['constellation_type_indices']\n\n\nconstellation = constellation[:60, :]\nconstellation_type_indices = constellation_type_indices[:60]\n\nmetric = np.array([10 * problem.test_groups[index] - problem.test_set.counts[index] for index in range(len(problem.test_groups))])\ntest_indices = list(np.argsort(metric))\n\n\nx = np.zeros(60,dtype=int)\nfor index in range(60):\n x[index] = index\n\n\ny = np.zeros(60,dtype=int)\nfor t2, test_index in enumerate(test_indices):\n\n expression = problem.test_set.expressions[test_index]\n\n car_candidates = [index for index, state in enumerate(constellation) if expression.evaluate(state)]\n for ii, value in enumerate(car_candidates):\n y[value] += 1\n\n\nplt.rcParams.update({'font.size': 8})\nplt.clf()\nplt.bar(x,y,color='b',label='Phase 1')\nplt.axis([-1, 60, 50, 250])\nplt.yticks(np.arange(0, 250+1, 50))\nplt.legend(loc=1)\nplt.xlabel('Test Vehicle')\nplt.ylabel('Number of Test Rules Satisfied Per Test Vehicle')\nplt.savefig('rules.pdf',bbox_inches='tight')\n\n\n"
]
| [
[
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.axis",
"numpy.argsort",
"numpy.load",
"matplotlib.pyplot.rcParams.update",
"numpy.zeros",
"matplotlib.pyplot.ylabel"
]
]
|
ligenchang/CarND-Capstone | [
"51a45a6a897721f05123be453710756dab4b80f0"
]
| [
"ros/src/waypoint_updater/waypoint_updater.py"
]
| [
"#!/usr/bin/env python\n\nimport rospy\nimport numpy as np\n\nfrom std_msgs.msg import Int32\nfrom geometry_msgs.msg import PoseStamped\nfrom styx_msgs.msg import Lane, Waypoint\n\nfrom scipy.spatial import KDTree\nimport math\n\n'''\nThis node will publish waypoints from the car's current position to some `x` distance ahead.\n\nAs mentioned in the doc, you should ideally first implement a version which does not care\nabout traffic lights or obstacles.\n\nOnce you have created dbw_node, you will update this node to use the status of traffic lights too.\n\nPlease note that our simulator also provides the exact location of traffic lights and their\ncurrent status in `/vehicle/traffic_lights` message. You can use this message to build this node\nas well as to verify your TL classifier.\n\nTODO (for Yousuf and Aaron): Stopline location for each traffic light.\n'''\n\nLOOKAHEAD_WPS = 50 # Number of waypoints we will publish. You can change this number\nMAX_DECEL = .5\n\n\nclass WaypointUpdater(object):\n def __init__(self):\n rospy.init_node('waypoint_updater')\n\n rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)\n rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)\n rospy.Subscriber('/traffic_waypoint', Int32, self.traffic_cb)\n\n # TODO: Add a subscriber for /traffic_waypoint and /obstacle_waypoint below\n self.final_waypoints_pub = rospy.Publisher('final_waypoints', Lane, queue_size=1)\n\n # TODO: Add other member variables you need below\n self.pose = None\n self.base_waypoints = None\n self.waypoints_2d = None\n self.waypoint_tree = None\n self.stopline_wp_idx = -1\n\n self.loop()\n\n def loop(self):\n rate = rospy.Rate(10)\n while not rospy.is_shutdown():\n if self.pose and self.base_waypoints and self.waypoint_tree:\n # Get closest waypoint\n closest_waypoint_idx = self.get_closest_waypoint_idx()\n self.publish_waypoints(closest_waypoint_idx)\n\n rate.sleep()\n\n def get_closest_waypoint_idx(self):\n x = self.pose.pose.position.x\n y = self.pose.pose.position.y\n closest_idx = self.waypoint_tree.query([x, y], 1)[1]\n\n ###############\n # Check where closest is relative to the car (in front or behind)\n ###############\n closest_coord = self.waypoints_2d[closest_idx]\n prev_coord = self.waypoints_2d[closest_idx - 1]\n\n # Equation for hyperplane through closes_coord\n cl_vect = np.array(closest_coord)\n prev_vect = np.array(prev_coord)\n pos_vect = np.array([x, y])\n\n val = np.dot(cl_vect - prev_vect, pos_vect - cl_vect)\n\n # Closest point was behind, so take next one\n if val > 0:\n closest_idx = (closest_idx + 1) % len(self.waypoints_2d)\n\n return closest_idx\n\n def publish_waypoints(self, closest_idx):\n final_lane = self.generate_lane()\n self.final_waypoints_pub.publish(final_lane)\n\n def generate_lane(self):\n lane = Lane()\n\n closest_idx = self.get_closest_waypoint_idx()\n farthest_idx = closest_idx + LOOKAHEAD_WPS\n base_waypoints = self.base_waypoints.waypoints[closest_idx: farthest_idx]\n\n # Either no traffic light detected, or else too far ahead\n if self.stopline_wp_idx == -1 or self.stopline_wp_idx >= farthest_idx:\n lane.waypoints = base_waypoints\n else:\n lane.waypoints = self.decelerate_waypoints(base_waypoints, closest_idx)\n\n return lane\n\n def decelerate_waypoints(self, waypoints, closest_idx):\n temp = []\n for i, wp in enumerate(waypoints):\n\n p = Waypoint()\n p.pose = wp.pose\n\n # The \"2\" below refers to half the length of the car (to make sure the front of the car stops at the line)\n stop_idx = max(self.stopline_wp_idx - closest_idx - 2, 0)\n dist = self.distance(waypoints, i, stop_idx)\n vel = math.sqrt(2 * MAX_DECEL * dist)\n if vel < 1.:\n vel = 0\n\n p.twist.twist.linear.x = min(vel, wp.twist.twist.linear.x)\n temp.append(p)\n\n return temp\n\n def pose_cb(self, msg):\n self.pose = msg\n\n def waypoints_cb(self, waypoints):\n self.base_waypoints = waypoints\n if not self.waypoints_2d:\n self.waypoints_2d = [[wp.pose.pose.position.x, wp.pose.pose.position.y] for wp in waypoints.waypoints]\n self.waypoint_tree = KDTree(self.waypoints_2d)\n\n def traffic_cb(self, msg):\n self.stopline_wp_idx = msg.data\n\n def obstacle_cb(self, msg):\n # TODO: Callback for /obstacle_waypoint message. We will implement it later\n pass\n\n def get_waypoint_velocity(self, waypoint):\n return waypoint.twist.twist.linear.x\n\n def set_waypoint_velocity(self, waypoints, waypoint, velocity):\n waypoints[waypoint].twist.twist.linear.x = velocity\n\n def distance(self, waypoints, wp1, wp2):\n dist = 0\n dl = lambda a, b: math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2)\n for i in range(wp1, wp2+1):\n dist += dl(waypoints[wp1].pose.pose.position, waypoints[i].pose.pose.position)\n wp1 = i\n return dist\n\n\nif __name__ == '__main__':\n try:\n WaypointUpdater()\n except rospy.ROSInterruptException:\n rospy.logerr('Could not start waypoint updater node.')\n"
]
| [
[
"numpy.dot",
"numpy.array",
"scipy.spatial.KDTree"
]
]
|
jnwestra/self-critical.pytorch | [
"a0ccbc101fb7af547ffa9fbc115dcb4291b87261"
]
| [
"captioning/utils/eval_utils.py"
]
| [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport numpy as np\nimport json\nfrom json import encoder\nimport random\nimport string\nimport time\nimport os\nimport sys\nfrom . import misc as utils\n\n# load coco-caption if available\ntry:\n sys.path.append(\"coco-caption\")\n from pycocotools.coco import COCO\n from pycocoevalcap.eval import COCOEvalCap\nexcept:\n print('Warning: coco-caption not available')\n\nbad_endings = ['a','an','the','in','for','at','of','with','before','after','on','upon','near','to','is','are','am']\nbad_endings += ['the']\n\n\ndef count_bad(sen):\n sen = sen.split(' ')\n if sen[-1] in bad_endings:\n return 1\n else:\n return 0\n\n\ndef getCOCO(dataset):\n if 'coco' in dataset:\n annFile = 'coco-caption/annotations/captions_val2014.json'\n elif 'flickr30k' in dataset or 'f30k' in dataset:\n annFile = 'data/f30k_captions4eval.json'\n return COCO(annFile)\n\n\ndef language_eval(dataset, preds, preds_n, eval_kwargs, split):\n model_id = eval_kwargs['id']\n eval_oracle = eval_kwargs.get('eval_oracle', 0)\n \n # create output dictionary\n out = {}\n\n if len(preds_n) > 0:\n # vocab size and novel sentences\n if 'coco' in dataset:\n dataset_file = 'data/dataset_coco.json'\n elif 'flickr30k' in dataset or 'f30k' in dataset:\n dataset_file = 'data/dataset_flickr30k.json'\n training_sentences = set([' '.join(__['tokens']) for _ in json.load(open(dataset_file))['images'] if not _['split'] in ['val', 'test'] for __ in _['sentences']])\n generated_sentences = set([_['caption'] for _ in preds_n])\n novels = generated_sentences - training_sentences\n out['novel_sentences'] = float(len(novels)) / len(preds_n)\n tmp = [_.split() for _ in generated_sentences]\n words = []\n for _ in tmp:\n words += _\n out['vocab_size'] = len(set(words))\n\n # encoder.FLOAT_REPR = lambda o: format(o, '.3f')\n\n cache_path = os.path.join('eval_results/', '.cache_'+ model_id + '_' + split + '.json')\n\n coco = getCOCO(dataset)\n valids = coco.getImgIds()\n\n # filter results to only those in MSCOCO validation set\n preds_filt = [p for p in preds if p['image_id'] in valids]\n mean_perplexity = sum([_['perplexity'] for _ in preds_filt]) / len(preds_filt)\n mean_entropy = sum([_['entropy'] for _ in preds_filt]) / len(preds_filt)\n print('using %d/%d predictions' % (len(preds_filt), len(preds)))\n json.dump(preds_filt, open(cache_path, 'w')) # serialize to temporary json file. Sigh, COCO API...\n\n cocoRes = coco.loadRes(cache_path)\n cocoEval = COCOEvalCap(coco, cocoRes)\n cocoEval.params['image_id'] = cocoRes.getImgIds()\n cocoEval.evaluate()\n\n for metric, score in cocoEval.eval.items():\n out[metric] = score\n # Add mean perplexity\n out['perplexity'] = mean_perplexity\n out['entropy'] = mean_entropy\n\n imgToEval = cocoEval.imgToEval\n for k in list(imgToEval.values())[0]['SPICE'].keys():\n if k != 'All':\n out['SPICE_'+k] = np.array([v['SPICE'][k]['f'] for v in imgToEval.values()])\n out['SPICE_'+k] = (out['SPICE_'+k][out['SPICE_'+k]==out['SPICE_'+k]]).mean()\n for p in preds_filt:\n image_id, caption = p['image_id'], p['caption']\n imgToEval[image_id]['caption'] = caption\n\n if len(preds_n) > 0:\n from . import eval_multi\n cache_path_n = os.path.join('eval_results/', '.cache_'+ model_id + '_' + split + '_n.json')\n allspice = eval_multi.eval_allspice(dataset, preds_n, model_id, split)\n out.update(allspice['overall'])\n div_stats = eval_multi.eval_div_stats(dataset, preds_n, model_id, split)\n out.update(div_stats['overall'])\n if eval_oracle:\n oracle = eval_multi.eval_oracle(dataset, preds_n, model_id, split)\n out.update(oracle['overall'])\n else:\n oracle = None\n self_cider = eval_multi.eval_self_cider(dataset, preds_n, model_id, split)\n out.update(self_cider['overall'])\n with open(cache_path_n, 'w') as outfile:\n json.dump({'allspice': allspice, 'div_stats': div_stats, 'oracle': oracle, 'self_cider': self_cider}, outfile)\n \n out['bad_count_rate'] = sum([count_bad(_['caption']) for _ in preds_filt]) / float(len(preds_filt))\n outfile_path = os.path.join('eval_results/', model_id + '_' + split + '.json')\n with open(outfile_path, 'w') as outfile:\n json.dump({'overall': out, 'imgToEval': imgToEval}, outfile)\n\n return out\n\ndef eval_split(model, crit, loader, eval_kwargs={}):\n verbose = eval_kwargs.get('verbose', True)\n verbose_beam = eval_kwargs.get('verbose_beam', 0)\n verbose_loss = eval_kwargs.get('verbose_loss', 1)\n num_images = eval_kwargs.get('num_images', eval_kwargs.get('val_images_use', -1))\n split = eval_kwargs.get('split', 'val')\n lang_eval = eval_kwargs.get('language_eval', 0)\n dataset = eval_kwargs.get('dataset', 'coco')\n beam_size = eval_kwargs.get('beam_size', 1)\n sample_n = eval_kwargs.get('sample_n', 1)\n remove_bad_endings = eval_kwargs.get('remove_bad_endings', 0)\n os.environ[\"REMOVE_BAD_ENDINGS\"] = str(remove_bad_endings) # Use this nasty way to make other code clean since it's a global configuration\n device = eval_kwargs.get('device', 'cuda')\n\n # Make sure in the evaluation mode\n model.eval()\n\n loader.reset_iterator(split)\n\n n = 0\n loss = 0\n loss_sum = 0\n loss_evals = 1e-8\n predictions = []\n n_predictions = [] # when sample_n > 1\n cap_enc_list = []\n while True:\n data = loader.get_batch(split)\n n = n + len(data['infos'])\n\n tmp = [data['fc_feats'], data['att_feats'], data['labels'], data['masks'], data['att_masks']]\n tmp = [_.to(device) if _ is not None else _ for _ in tmp]\n fc_feats, att_feats, labels, masks, att_masks = tmp\n if labels is not None and verbose_loss:\n # forward the model to get loss\n with torch.no_grad():\n loss = crit(model(fc_feats, att_feats, labels[..., :-1], att_masks), labels[..., 1:], masks[..., 1:]).item()\n loss_sum = loss_sum + loss\n loss_evals = loss_evals + 1\n\n # forward the model to also get generated samples for each image\n with torch.no_grad():\n tmp_eval_kwargs = eval_kwargs.copy()\n tmp_eval_kwargs.update({'sample_n': 1})\n seq, seq_logprobs = model(fc_feats, att_feats, att_masks, opt=tmp_eval_kwargs, mode='sample')\n \n out_encoder = model.encode(att_feats, att_masks)\n \n seq = seq.data\n print(seq.shape, seq_logprobs.shape, out_encoder.shape)\n cap_enc_list.extend(out_encoder)\n \n entropy = - (F.softmax(seq_logprobs, dim=2) * seq_logprobs).sum(2).sum(1) / ((seq>0).to(seq_logprobs).sum(1)+1)\n perplexity = - seq_logprobs.gather(2, seq.unsqueeze(2)).squeeze(2).sum(1) / ((seq>0).to(seq_logprobs).sum(1)+1)\n \n # Print beam search\n if beam_size > 1 and verbose_beam:\n for i in range(fc_feats.shape[0]):\n print('\\n'.join([utils.decode_sequence(model.vocab, _['seq'].unsqueeze(0))[0] for _ in model.done_beams[i]]))\n print('--' * 10)\n sents = utils.decode_sequence(model.vocab, seq)\n\n for k, sent in enumerate(sents):\n entry = {'image_id': data['infos'][k]['id'], 'caption': sent, 'perplexity': perplexity[k].item(), 'entropy': entropy[k].item()}\n if eval_kwargs.get('dump_path', 0) == 1:\n entry['file_name'] = data['infos'][k]['file_path']\n predictions.append(entry)\n if eval_kwargs.get('dump_images', 0) == 1:\n # dump the raw image to vis/ folder\n cmd = 'cp \"' + os.path.join(eval_kwargs['image_root'], data['infos'][k]['file_path']) + '\" vis/imgs/img' + str(len(predictions)) + '.jpg' # bit gross\n print(cmd)\n os.system(cmd)\n\n if verbose:\n print('image %s: %s' %(entry['image_id'], entry['caption']))\n\n if sample_n > 1:\n eval_split_n(model, n_predictions, [fc_feats, att_feats, att_masks, data], eval_kwargs)\n \n # ix0 = data['bounds']['it_pos_now']\n ix1 = data['bounds']['it_max']\n if num_images != -1:\n ix1 = min(ix1, num_images)\n else:\n num_images = ix1\n for i in range(n - ix1):\n predictions.pop()\n\n if verbose:\n print('evaluating validation preformance... %d/%d (%f)' %(n, ix1, loss))\n\n if num_images >= 0 and n >= num_images:\n break\n\n lang_stats = None\n if len(n_predictions) > 0 and 'perplexity' in n_predictions[0]:\n n_predictions = sorted(n_predictions, key=lambda x: x['perplexity'])\n if not os.path.isdir('eval_results'):\n os.mkdir('eval_results')\n torch.save((predictions, n_predictions), os.path.join('eval_results/', '.saved_pred_'+ eval_kwargs['id'] + '_' + split + '.pth'))\n if lang_eval == 1:\n lang_stats = language_eval(dataset, predictions, n_predictions, eval_kwargs, split)\n\n # Switch back to training mode\n model.train()\n return loss_sum/loss_evals, predictions, lang_stats, cap_enc_list\n\n\n# Only run when sample_n > 0\ndef eval_split_n(model, n_predictions, input_data, eval_kwargs={}):\n verbose = eval_kwargs.get('verbose', True)\n beam_size = eval_kwargs.get('beam_size', 1)\n sample_n = eval_kwargs.get('sample_n', 1)\n sample_n_method = eval_kwargs.get('sample_n_method', 'sample')\n\n fc_feats, att_feats, att_masks, data = input_data\n\n tmp_eval_kwargs = eval_kwargs.copy()\n if sample_n_method == 'bs':\n # case 1 sample_n == beam size\n tmp_eval_kwargs.update({'sample_n': 1, 'beam_size': sample_n, 'group_size': 1}) # randomness from softmax\n with torch.no_grad():\n model(fc_feats, att_feats, att_masks, opt=tmp_eval_kwargs, mode='sample')\n for k in range(fc_feats.shape[0]):\n _sents = utils.decode_sequence(model.vocab, torch.stack([model.done_beams[k][_]['seq'] for _ in range(sample_n)]))\n for sent in _sents:\n entry = {'image_id': data['infos'][k]['id'], 'caption': sent}\n n_predictions.append(entry)\n # case 2 sample / gumbel / topk sampling/ nucleus sampling\n elif sample_n_method == 'sample' or \\\n sample_n_method == 'gumbel' or \\\n sample_n_method.startswith('top'):\n tmp_eval_kwargs.update({'sample_n': sample_n, 'sample_method': sample_n_method, 'beam_size': 1}) # randomness from sample\n with torch.no_grad():\n _seq, _sampleLogprobs = model(fc_feats, att_feats, att_masks, opt=tmp_eval_kwargs, mode='sample')\n _sents = utils.decode_sequence(model.vocab, _seq)\n _perplexity = - _sampleLogprobs.gather(2, _seq.unsqueeze(2)).squeeze(2).sum(1) / ((_seq>0).to(_sampleLogprobs).sum(1)+1)\n for k, sent in enumerate(_sents):\n entry = {'image_id': data['infos'][k // sample_n]['id'], 'caption': sent, 'perplexity': _perplexity[k].item()}\n n_predictions.append(entry)\n elif sample_n_method == 'dbs':\n # Use diverse beam search\n tmp_eval_kwargs.update({'beam_size': sample_n * beam_size, 'group_size': sample_n}) # randomness from softmax\n with torch.no_grad():\n model(fc_feats, att_feats, att_masks, opt=tmp_eval_kwargs, mode='sample')\n for k in range(loader.batch_size):\n _sents = utils.decode_sequence(model.vocab, torch.stack([model.done_beams[k][_]['seq'] for _ in range(0, sample_n*beam_size, beam_size)]))\n for sent in _sents:\n entry = {'image_id': data['infos'][k]['id'], 'caption': sent}\n n_predictions.append(entry)\n else:\n tmp_eval_kwargs.update({'sample_method': sample_n_method[1:], 'group_size': sample_n, 'beam_size':1}) # randomness from softmax\n with torch.no_grad():\n _seq, _sampleLogprobs = model(fc_feats, att_feats, att_masks, opt=tmp_eval_kwargs, mode='sample')\n _sents = utils.decode_sequence(model.vocab, _seq)\n for k, sent in enumerate(_sents):\n entry = {'image_id': data['infos'][k // sample_n]['id'], 'caption': sent}\n n_predictions.append(entry)\n if verbose:\n for entry in sorted(n_predictions[-fc_feats.shape[0] * sample_n:], key=lambda x: x['image_id']):\n print('image %s: %s' %(entry['image_id'], entry['caption']))\n"
]
| [
[
"torch.nn.functional.softmax",
"torch.no_grad"
]
]
|
ElementAI/am3 | [
"fc93813b7366933273dfeaea172f68de744c6d97"
]
| [
"AM3_protonet++.py"
]
| [
"#!/usr/bin/env python3\n\n\"\"\"Training and evaluation entry point.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport numpy as np\nimport argparse\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.framework import dtypes\nfrom scipy.spatial import KDTree\nfrom common.util import Dataset\nfrom common.util import ACTIVATION_MAP\nfrom tqdm import trange\nimport pathlib\nimport logging\nfrom common.util import summary_writer\nfrom common.gen_experiments import load_and_save_params\nimport time\nimport pickle as pkl\n\n\ntf.logging.set_verbosity(tf.logging.INFO)\nlogging.basicConfig(level=logging.INFO)\n\n\n\ndef _load_mini_imagenet(data_dir, split):\n \"\"\"Load mini-imagenet from numpy's npz file format.\"\"\"\n _split_tag = {'sources': 'train', 'target_val': 'val', 'target_tst': 'test'}[split]\n dataset_path = os.path.join(data_dir, 'few-shot-{}.npz'.format(_split_tag))\n logging.info(\"Loading mini-imagenet...\")\n data = np.load(dataset_path)\n fields = data['features'], data['targets']\n logging.info(\"Done loading.\")\n return fields\n\ndef get_image_size(data_dir):\n if 'mini-imagenet' or 'tiered' in data_dir:\n image_size = 84\n elif 'cifar' in data_dir:\n image_size = 32\n else:\n raise Exception('Unknown dataset: %s' % data_dir)\n return image_size\n\n\nclass Namespace(object):\n def __init__(self, adict):\n self.__dict__.update(adict)\n\n\ndef get_arguments():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--mode', type=str, default='train',\n choices=['train', 'eval', 'test', 'train_classifier', 'create_embedding'])\n # Dataset parameters\n parser.add_argument('--data_dir', type=str, default=None, help='Path to the data.')\n parser.add_argument('--data_split', type=str, default='sources', choices=['sources', 'target_val', 'target_tst'],\n help='Split of the data to be used to perform operation.')\n\n # Training parameters\n parser.add_argument('--number_of_steps', type=int, default=int(30000),\n help=\"Number of training steps (number of Epochs in Hugo's paper)\")\n parser.add_argument('--number_of_steps_to_early_stop', type=int, default=int(1000000),\n help=\"Number of training steps after half way to early stop the training\")\n parser.add_argument('--log_dir', type=str, default='', help='Base log dir')\n parser.add_argument('--num_classes_train', type=int, default=5,\n help='Number of classes in the train phase, this is coming from the prototypical networks')\n parser.add_argument('--num_shots_train', type=int, default=5,\n help='Number of shots in a few shot meta-train scenario')\n parser.add_argument('--train_batch_size', type=int, default=32, help='Training batch size.')\n parser.add_argument('--num_tasks_per_batch', type=int, default=2,\n help='Number of few shot tasks per batch, so the task encoding batch is num_tasks_per_batch x num_classes_test x num_shots_train .')\n parser.add_argument('--init_learning_rate', type=float, default=0.1, help='Initial learning rate.')\n parser.add_argument('--save_summaries_secs', type=int, default=60, help='Time between saving summaries')\n parser.add_argument('--save_interval_secs', type=int, default=60, help='Time between saving model?')\n parser.add_argument('--optimizer', type=str, default='sgd', choices=['sgd', 'adam'])\n parser.add_argument('--augment', type=bool, default=False)\n # Learning rate paramteres\n parser.add_argument('--lr_anneal', type=str, default='pwc', choices=['const', 'pwc', 'cos', 'exp'])\n parser.add_argument('--n_lr_decay', type=int, default=3)\n parser.add_argument('--lr_decay_rate', type=float, default=10.0)\n parser.add_argument('--num_steps_decay_pwc', type=int, default=2500,\n help='Decay learning rate every num_steps_decay_pwc')\n\n parser.add_argument('--clip_gradient_norm', type=float, default=1.0, help='gradient clip norm.')\n parser.add_argument('--weights_initializer_factor', type=float, default=0.1,\n help='multiplier in the variance of the initialization noise.')\n # Evaluation parameters\n parser.add_argument('--max_number_of_evaluations', type=float, default=float('inf'))\n parser.add_argument('--eval_interval_secs', type=int, default=120, help='Time between evaluating model?')\n parser.add_argument('--eval_interval_steps', type=int, default=1000,\n help='Number of train steps between evaluating model in the training loop')\n parser.add_argument('--eval_interval_fine_steps', type=int, default=250,\n help='Number of train steps between evaluating model in the training loop in the final phase')\n # Test parameters\n parser.add_argument('--num_classes_test', type=int, default=5, help='Number of classes in the test phase')\n parser.add_argument('--num_shots_test', type=int, default=5,\n help='Number of shots in a few shot meta-test scenario')\n parser.add_argument('--num_cases_test', type=int, default=100000,\n help='Number of few-shot cases to compute test accuracy')\n # Architecture parameters\n parser.add_argument('--dropout', type=float, default=1.0)\n parser.add_argument('--conv_dropout', type=float, default=None)\n parser.add_argument('--feature_dropout_p', type=float, default=None)\n\n parser.add_argument('--weight_decay', type=float, default=0.0005)\n parser.add_argument('--num_filters', type=int, default=64)\n parser.add_argument('--num_units_in_block', type=int, default=3)\n parser.add_argument('--num_blocks', type=int, default=4)\n parser.add_argument('--num_max_pools', type=int, default=3)\n parser.add_argument('--block_size_growth', type=float, default=2.0)\n parser.add_argument('--activation', type=str, default='swish-1', choices=['relu', 'selu', 'swish-1'])\n\n parser.add_argument('--feature_expansion_size', type=int, default=None)\n parser.add_argument('--feature_bottleneck_size', type=int, default=None)\n\n parser.add_argument('--feature_extractor', type=str, default='simple_res_net',\n choices=['simple_res_net'], help='Which feature extractor to use')\n\n\n parser.add_argument('--encoder_sharing', type=str, default='shared',\n choices=['shared'],\n help='How to link fetaure extractors in task encoder and classifier')\n parser.add_argument('--encoder_classifier_link', type=str, default='prototypical',\n choices=['prototypical'],\n help='How to link fetaure extractors in task encoder and classifier')\n parser.add_argument('--embedding_pooled', type=bool, default=True,\n help='Whether to use avg pooling to create embedding')\n parser.add_argument('--task_encoder', type=str, default='self_att_mlp',\n choices=['class_mean', 'fixed_alpha','fixed_alpha_mlp','self_att_mlp'])\n\n #\n parser.add_argument('--num_batches_neg_mining', type=int, default=0)\n parser.add_argument('--eval_batch_size', type=int, default=100, help='Evaluation batch size')\n\n parser.add_argument('--alpha', type=float, default=1.0)\n parser.add_argument('--mlp_weight_decay', type=float, default=0.0)\n parser.add_argument('--mlp_dropout', type=float, default=0.0)\n parser.add_argument('--mlp_type', type=str, default='non-linear')\n parser.add_argument('--att_input', type=str, default='word')\n\n args = parser.parse_args()\n\n print(args)\n return args\n\n\ndef get_logdir_name(flags):\n \"\"\"Generates the name of the log directory from the values of flags\n Parameters\n ----------\n flags: neural net architecture generated by get_arguments()\n Outputs\n -------\n the name of the directory to store the training and evaluation results\n \"\"\"\n logdir = flags.log_dir\n\n return logdir\n\n\nclass ScaledVarianceRandomNormal(init_ops.Initializer):\n \"\"\"Initializer that generates tensors with a normal distribution scaled as per https://arxiv.org/pdf/1502.01852.pdf.\n Args:\n mean: a python scalar or a scalar tensor. Mean of the random values\n to generate.\n stddev: a python scalar or a scalar tensor. Standard deviation of the\n random values to generate.\n seed: A Python integer. Used to create random seeds. See\n @{tf.set_random_seed}\n for behavior.\n dtype: The data type. Only floating point types are supported.\n \"\"\"\n\n def __init__(self, mean=0.0, factor=1.0, seed=None, dtype=dtypes.float32):\n self.mean = mean\n self.factor = factor\n self.seed = seed\n self.dtype = dtypes.as_dtype(dtype)\n\n def __call__(self, shape, dtype=None, partition_info=None):\n if dtype is None:\n dtype = self.dtype\n\n if shape:\n n = float(shape[-1])\n else:\n n = 1.0\n for dim in shape[:-2]:\n n *= float(dim)\n\n self.stddev = np.sqrt(self.factor * 2.0 / n)\n return random_ops.random_normal(shape, self.mean, self.stddev,\n dtype, seed=self.seed)\n\n\ndef _get_scope(is_training, flags):\n normalizer_params = {\n 'epsilon': 0.001,\n 'momentum': .95,\n 'trainable': is_training,\n 'training': is_training,\n }\n conv2d_arg_scope = slim.arg_scope(\n [slim.conv2d, slim.fully_connected],\n activation_fn=ACTIVATION_MAP[flags.activation],\n normalizer_fn=tf.layers.batch_normalization,\n normalizer_params=normalizer_params,\n # padding='SAME',\n trainable=is_training,\n weights_regularizer=tf.contrib.layers.l2_regularizer(scale=flags.weight_decay),\n weights_initializer=ScaledVarianceRandomNormal(factor=flags.weights_initializer_factor),\n biases_initializer=tf.constant_initializer(0.0)\n )\n dropout_arg_scope = slim.arg_scope(\n [slim.dropout],\n keep_prob=flags.dropout,\n is_training=is_training)\n return conv2d_arg_scope, dropout_arg_scope\n\n\ndef build_simple_conv_net(images, flags, is_training, reuse=None, scope=None):\n conv2d_arg_scope, dropout_arg_scope = _get_scope(is_training, flags)\n with conv2d_arg_scope, dropout_arg_scope:\n with tf.variable_scope(scope or 'feature_extractor', reuse=reuse):\n h = images\n for i in range(4):\n h = slim.conv2d(h, num_outputs=flags.num_filters, kernel_size=3, stride=1,\n scope='conv' + str(i), padding='SAME',\n weights_initializer=ScaledVarianceRandomNormal(factor=flags.weights_initializer_factor))\n h = slim.max_pool2d(h, kernel_size=2, stride=2, padding='VALID', scope='max_pool' + str(i))\n\n if flags.embedding_pooled == True:\n kernel_size = h.shape.as_list()[-2]\n h = slim.avg_pool2d(h, kernel_size=kernel_size, scope='avg_pool')\n h = slim.flatten(h)\n return h\n\n\ndef leaky_relu(x, alpha=0.1, name=None):\n return tf.maximum(x, alpha * x, name=name)\n\n\n\n\ndef build_simple_res_net(images, flags, num_filters, beta=None, gamma=None, is_training=False, reuse=None, scope=None):\n conv2d_arg_scope, dropout_arg_scope = _get_scope(is_training, flags)\n activation_fn = ACTIVATION_MAP[flags.activation]\n with conv2d_arg_scope, dropout_arg_scope:\n with tf.variable_scope(scope or 'feature_extractor', reuse=reuse):\n h = images\n for i in range(len(num_filters)):\n # make shortcut\n shortcut = slim.conv2d(h, num_outputs=num_filters[i], kernel_size=1, stride=1,\n activation_fn=None,\n scope='shortcut' + str(i), padding='SAME')\n\n for j in range(flags.num_units_in_block):\n h = slim.conv2d(h, num_outputs=num_filters[i], kernel_size=3, stride=1,\n scope='conv' + str(i) + '_' + str(j), padding='SAME', activation_fn=None)\n if flags.conv_dropout:\n h = slim.dropout(h, keep_prob=1.0 - flags.conv_dropout)\n\n if j < (flags.num_units_in_block - 1):\n h = activation_fn(h, name='activation_' + str(i) + '_' + str(j))\n h = h + shortcut\n\n h = activation_fn(h, name='activation_' + str(i) + '_' + str(flags.num_units_in_block - 1))\n if i < flags.num_max_pools:\n h = slim.max_pool2d(h, kernel_size=2, stride=2, padding='SAME', scope='max_pool' + str(i))\n\n if flags.feature_expansion_size:\n if flags.feature_dropout_p:\n h = slim.dropout(h, scope='feature_expansion_dropout', keep_prob=1.0 - flags.feature_dropout_p)\n h = slim.conv2d(slim.dropout(h), num_outputs=flags.feature_expansion_size, kernel_size=1, stride=1,\n scope='feature_expansion', padding='SAME')\n\n if flags.embedding_pooled == True:\n kernel_size = h.shape.as_list()[-2]\n h = slim.avg_pool2d(h, kernel_size=kernel_size, scope='avg_pool')\n h = slim.flatten(h)\n\n if flags.feature_dropout_p:\n h = slim.dropout(h, scope='feature_bottleneck_dropout', keep_prob=1.0 - flags.feature_dropout_p)\n # Bottleneck layer\n if flags.feature_bottleneck_size:\n h = slim.fully_connected(h, num_outputs=flags.feature_bottleneck_size,\n activation_fn=activation_fn, normalizer_fn=None,\n scope='feature_bottleneck')\n\n return h\n\n\n\ndef build_wordemb_transformer(embeddings, flags, is_training=False, reuse=None, scope=None):\n with tf.variable_scope(scope or 'mlp_transformer', reuse=reuse):\n h = embeddings\n if flags.mlp_type=='linear':\n h = slim.fully_connected(h, 512, reuse=False, scope='mlp_layer',\n activation_fn=None, trainable=is_training,\n weights_regularizer=tf.contrib.layers.l2_regularizer(scale=flags.mlp_weight_decay),\n weights_initializer=ScaledVarianceRandomNormal(factor=flags.weights_initializer_factor),\n biases_initializer=tf.constant_initializer(0.0))\n elif flags.mlp_type=='non-linear':\n h = slim.fully_connected(h, 300, reuse=False, scope='mlp_layer',\n activation_fn=tf.nn.relu, trainable=is_training,\n weights_regularizer=tf.contrib.layers.l2_regularizer(\n scale=flags.mlp_weight_decay),\n weights_initializer=ScaledVarianceRandomNormal(\n factor=flags.weights_initializer_factor),\n biases_initializer=tf.constant_initializer(0.0))\n h = slim.dropout(h, scope='mlp_dropout', keep_prob=1.0 - flags.mlp_dropout, is_training=is_training)\n h = slim.fully_connected(h, 512, reuse=False, scope='mlp_layer_1',\n activation_fn=None, trainable=is_training,\n weights_regularizer=tf.contrib.layers.l2_regularizer(\n scale=flags.mlp_weight_decay),\n weights_initializer=ScaledVarianceRandomNormal(\n factor=flags.weights_initializer_factor),\n biases_initializer=tf.constant_initializer(0.0))\n\n return h\n\ndef build_self_attention(embeddings, flags, is_training=False, reuse=None, scope=None):\n with tf.variable_scope(scope or 'self_attention', reuse=reuse):\n h = embeddings\n if flags.mlp_type=='linear':\n h = slim.fully_connected(h, 1, reuse=False, scope='self_att_layer',\n activation_fn=None, trainable=is_training,\n weights_regularizer=tf.contrib.layers.l2_regularizer(scale=flags.mlp_weight_decay),\n weights_initializer=ScaledVarianceRandomNormal(factor=flags.weights_initializer_factor),\n biases_initializer=tf.constant_initializer(0.0))\n elif flags.mlp_type=='non-linear':\n h = slim.fully_connected(h, 300, reuse=False, scope='self_att_layer',\n activation_fn=tf.nn.relu, trainable=is_training,\n weights_regularizer=tf.contrib.layers.l2_regularizer(\n scale=flags.mlp_weight_decay),\n weights_initializer=ScaledVarianceRandomNormal(\n factor=flags.weights_initializer_factor),\n biases_initializer=tf.constant_initializer(0.0))\n h = slim.dropout(h, scope='self_att_dropout', keep_prob=1.0 - flags.mlp_dropout, is_training=is_training)\n h = slim.fully_connected(h, 1, reuse=False, scope='self_att_layer_1',\n activation_fn=None, trainable=is_training,\n weights_regularizer=tf.contrib.layers.l2_regularizer(\n scale=flags.mlp_weight_decay),\n weights_initializer=ScaledVarianceRandomNormal(\n factor=flags.weights_initializer_factor),\n biases_initializer=tf.constant_initializer(0.0))\n h = tf.sigmoid(h)\n\n return h\n\ndef get_res_net_block(h, flags, num_filters, num_units, pool=False, is_training=False,\n reuse=None, scope=None):\n conv2d_arg_scope, dropout_arg_scope = _get_scope(is_training, flags)\n activation_fn = ACTIVATION_MAP[flags.activation]\n with conv2d_arg_scope, dropout_arg_scope:\n with tf.variable_scope(scope, reuse=reuse):\n # make shortcut\n shortcut = slim.conv2d(h, num_outputs=num_filters, kernel_size=1, stride=1,\n activation_fn=None,\n scope='shortcut', padding='SAME')\n\n for j in range(num_units):\n h = slim.conv2d(h, num_outputs=num_filters, kernel_size=3, stride=1,\n scope='conv_' + str(j), padding='SAME', activation_fn=None)\n if flags.conv_dropout:\n h = slim.dropout(h, keep_prob=1.0 - flags.conv_dropout)\n if j < (num_units - 1):\n h = activation_fn(h, name='activation_' + str(j))\n h = h + shortcut\n h = activation_fn(h, name='activation_' + '_' + str(flags.num_units_in_block - 1))\n if pool:\n h = slim.max_pool2d(h, kernel_size=2, stride=2, padding='SAME', scope='max_pool')\n return h\n\n\n\ndef build_feature_extractor_graph(images, flags, num_filters, beta=None, gamma=None, is_training=False,\n scope='feature_extractor_task_encoder', reuse=None, is_64way=False):\n if flags.feature_extractor == 'simple_conv_net':\n h = build_simple_conv_net(images, flags=flags, is_training=is_training, reuse=reuse, scope=scope)\n elif flags.feature_extractor == 'simple_res_net':\n h = build_simple_res_net(images, flags=flags, num_filters=num_filters, beta=beta, gamma=gamma,\n is_training=is_training, reuse=reuse, scope=scope)\n else:\n h = None\n\n embedding_shape = h.get_shape().as_list()\n if is_training and is_64way is False:\n h = tf.reshape(h, shape=(flags.num_tasks_per_batch, embedding_shape[0] // flags.num_tasks_per_batch, -1),\n name='reshape_to_separate_tasks_generic_features')\n else:\n h = tf.reshape(h, shape=(1, embedding_shape[0], -1),\n name='reshape_to_separate_tasks_generic_features')\n\n return h\n\n\n\ndef build_task_encoder(embeddings, label_embeddings, flags, is_training, querys=None, reuse=None, scope='class_encoder'):\n conv2d_arg_scope, dropout_arg_scope = _get_scope(is_training, flags)\n alpha=None\n\n with conv2d_arg_scope, dropout_arg_scope:\n with tf.variable_scope(scope, reuse=reuse):\n\n if flags.task_encoder == 'talkthrough':\n task_encoding = embeddings\n elif flags.task_encoder == 'class_mean':\n task_encoding = embeddings\n\n if is_training:\n task_encoding = tf.reshape(task_encoding, shape=(\n flags.num_tasks_per_batch, flags.num_classes_train, flags.num_shots_train, -1),\n name='reshape_to_separate_tasks_task_encoding')\n else:\n task_encoding = tf.reshape(task_encoding,\n shape=(1, flags.num_classes_test, flags.num_shots_test, -1),\n name='reshape_to_separate_tasks_task_encoding')\n task_encoding = tf.reduce_mean(task_encoding, axis=2, keep_dims=False)\n elif flags.task_encoder == 'fixed_alpha':\n task_encoding = embeddings\n print(\"entered the word embedding task encoder...\")\n\n if is_training:\n task_encoding = tf.reshape(task_encoding, shape=(\n flags.num_tasks_per_batch, flags.num_classes_train, flags.num_shots_train, -1),\n name='reshape_to_separate_tasks_task_encoding')\n label_embeddings = tf.reshape(label_embeddings, shape=(\n flags.num_tasks_per_batch, flags.num_classes_train, -1),\n name='reshape_to_separate_tasks_label_embedding')\n else:\n task_encoding = tf.reshape(task_encoding,\n shape=(1, flags.num_classes_test, flags.num_shots_test, -1),\n name='reshape_to_separate_tasks_task_encoding')\n label_embeddings = tf.reshape(label_embeddings,\n shape=(1, flags.num_classes_test, -1),\n name='reshape_to_separate_tasks_label_embedding')\n task_encoding = tf.reduce_mean(task_encoding, axis=2, keep_dims=False)\n task_encoding = flags.alpha*task_encoding+(1-flags.alpha)*label_embeddings\n elif flags.task_encoder == 'fixed_alpha_mlp':\n task_encoding = embeddings\n print(\"entered the word embedding task encoder...\")\n label_embeddings = build_wordemb_transformer(label_embeddings,flags,is_training)\n\n if is_training:\n task_encoding = tf.reshape(task_encoding, shape=(\n flags.num_tasks_per_batch, flags.num_classes_train, flags.num_shots_train, -1),\n name='reshape_to_separate_tasks_task_encoding')\n label_embeddings = tf.reshape(label_embeddings, shape=(\n flags.num_tasks_per_batch, flags.num_classes_train, -1),\n name='reshape_to_separate_tasks_label_embedding')\n else:\n task_encoding = tf.reshape(task_encoding,\n shape=(1, flags.num_classes_test, flags.num_shots_test, -1),\n name='reshape_to_separate_tasks_task_encoding')\n label_embeddings = tf.reshape(label_embeddings,\n shape=(1, flags.num_classes_test, -1),\n name='reshape_to_separate_tasks_label_embedding')\n task_encoding = tf.reduce_mean(task_encoding, axis=2, keep_dims=False)\n task_encoding = flags.alpha*task_encoding+(1-flags.alpha)*label_embeddings\n elif flags.task_encoder == 'self_att_mlp':\n task_encoding = embeddings\n print(\"entered the word embedding task encoder...\")\n label_embeddings = build_wordemb_transformer(label_embeddings,flags,is_training)\n\n if is_training:\n task_encoding = tf.reshape(task_encoding, shape=(\n flags.num_tasks_per_batch, flags.num_classes_train, flags.num_shots_train, -1),\n name='reshape_to_separate_tasks_task_encoding')\n label_embeddings = tf.reshape(label_embeddings, shape=(\n flags.num_tasks_per_batch, flags.num_classes_train, -1),\n name='reshape_to_separate_tasks_label_embedding')\n else:\n task_encoding = tf.reshape(task_encoding,\n shape=(1, flags.num_classes_test, flags.num_shots_test, -1),\n name='reshape_to_separate_tasks_task_encoding')\n label_embeddings = tf.reshape(label_embeddings,\n shape=(1, flags.num_classes_test, -1),\n name='reshape_to_separate_tasks_label_embedding')\n task_encoding = tf.reduce_mean(task_encoding, axis=2, keep_dims=False)\n\n if flags.att_input=='proto':\n alpha = build_self_attention(task_encoding,flags,is_training)\n elif flags.att_input=='word':\n alpha = build_self_attention(label_embeddings,flags,is_training)\n elif flags.att_input=='combined':\n embeddings=tf.concat([task_encoding, label_embeddings], axis=2)\n alpha = build_self_attention(embeddings, flags, is_training)\n\n elif flags.att_input=='queryword':\n j = label_embeddings.get_shape().as_list()[1]\n i = querys.get_shape().as_list()[1]\n task_encoding_tile = tf.expand_dims(task_encoding, axis=1)\n task_encoding_tile = tf.tile(task_encoding_tile, (1, i, 1, 1))\n querys_tile = tf.expand_dims(querys, axis=2)\n querys_tile = tf.tile(querys_tile, (1, 1, j, 1))\n label_embeddings_tile = tf.expand_dims(label_embeddings, axis=1)\n label_embeddings_tile = tf.tile(label_embeddings_tile, (1, i, 1, 1))\n att_input = tf.concat([label_embeddings_tile, querys_tile], axis=3)\n alpha = build_self_attention(att_input, flags, is_training)\n elif flags.att_input=='queryproto':\n j = task_encoding.get_shape().as_list()[1]\n i = querys.get_shape().as_list()[1]\n task_encoding_tile = tf.expand_dims(task_encoding, axis=1)\n task_encoding_tile = tf.tile(task_encoding_tile, (1, i, 1, 1))\n querys_tile = tf.expand_dims(querys, axis=2)\n querys_tile = tf.tile(querys_tile, (1, 1, j, 1))\n label_embeddings_tile = tf.expand_dims(label_embeddings, axis=1)\n label_embeddings_tile = tf.tile(label_embeddings_tile, (1, i, 1, 1))\n att_input = tf.concat([task_encoding_tile, querys_tile], axis=3)\n alpha = build_self_attention(att_input, flags, is_training)\n\n if querys is None:\n task_encoding = alpha*task_encoding+(1-alpha)*label_embeddings\n else:\n task_encoding = alpha * task_encoding_tile + (1-alpha) * label_embeddings_tile\n\n else:\n task_encoding = None\n\n return task_encoding, alpha\n\n\ndef build_prototypical_head(features_generic, task_encoding, flags, is_training, scope='prototypical_head'):\n \"\"\"\n Implements the prototypical networks few-shot head\n :param features_generic:\n :param task_encoding:\n :param flags:\n :param is_training:\n :param reuse:\n :param scope:\n :return:\n \"\"\"\n\n with tf.variable_scope(scope):\n\n if len(features_generic.get_shape().as_list()) == 2:\n features_generic = tf.expand_dims(features_generic, axis=0)\n if len(task_encoding.get_shape().as_list()) == 2:\n task_encoding = tf.expand_dims(task_encoding, axis=0)\n\n # i is the number of steps in the task_encoding sequence\n # j is the number of steps in the features_generic sequence\n j = task_encoding.get_shape().as_list()[1]\n i = features_generic.get_shape().as_list()[1]\n\n # tile to be able to produce weight matrix alpha in (i,j) space\n features_generic = tf.expand_dims(features_generic, axis=2)\n task_encoding = tf.expand_dims(task_encoding, axis=1)\n # features_generic changes over i and is constant over j\n # task_encoding changes over j and is constant over i\n task_encoding_tile = tf.tile(task_encoding, (1, i, 1, 1))\n features_generic_tile = tf.tile(features_generic, (1, 1, j, 1))\n # implement equation (4)\n euclidian = -tf.norm(task_encoding_tile - features_generic_tile, name='neg_euclidian_distance', axis=-1)\n\n if is_training:\n euclidian = tf.reshape(euclidian, shape=(flags.num_tasks_per_batch * flags.train_batch_size, -1))\n else:\n euclidian_shape = euclidian.get_shape().as_list()\n euclidian = tf.reshape(euclidian, shape=(euclidian_shape[1], -1))\n\n return euclidian\n\n\ndef build_prototypical_head_protoperquery(features_generic, task_encoding, flags, is_training, scope='prototypical_head'):\n \"\"\"\n Implements the prototypical networks few-shot head\n :param features_generic:\n :param task_encoding:\n :param flags:\n :param is_training:\n :param reuse:\n :param scope:\n :return:\n \"\"\"\n # the shape of task_encoding is [num_tasks, batch_size, num_classes, ]\n\n with tf.variable_scope(scope):\n\n if len(features_generic.get_shape().as_list()) == 2:\n features_generic = tf.expand_dims(features_generic, axis=0)\n if len(task_encoding.get_shape().as_list()) == 2:\n task_encoding = tf.expand_dims(task_encoding, axis=0)\n\n # i is the number of steps in the task_encoding sequence\n # j is the number of steps in the features_generic sequence\n j = task_encoding.get_shape().as_list()[2]\n i = features_generic.get_shape().as_list()[1]\n\n # tile to be able to produce weight matrix alpha in (i,j) space\n features_generic = tf.expand_dims(features_generic, axis=2)\n #task_encoding = tf.expand_dims(task_encoding, axis=1)\n # features_generic changes over i and is constant over j\n # task_encoding changes over j and is constant over i\n features_generic_tile = tf.tile(features_generic, (1, 1, j, 1))\n # implement equation (4)\n euclidian = -tf.norm(task_encoding - features_generic_tile, name='neg_euclidian_distance', axis=-1)\n\n if is_training:\n euclidian = tf.reshape(euclidian, shape=(flags.num_tasks_per_batch * flags.train_batch_size, -1))\n else:\n euclidian_shape = euclidian.get_shape().as_list()\n euclidian = tf.reshape(euclidian, shape=(euclidian_shape[1], -1))\n\n return euclidian\n\ndef build_regularizer_head(embeddings, label_embeddings, flags, is_training, scope='regularizer_head'):\n \"\"\"\n Implements the prototypical networks few-shot head\n :param features_generic:\n :param task_encoding:\n :param flags:\n :param is_training:\n :param reuse:\n :param scope:\n :return:\n \"\"\"\n\n with tf.variable_scope(scope):\n task_encoding = embeddings\n\n if is_training:\n task_encoding = tf.reshape(task_encoding, shape=(\n flags.num_tasks_per_batch, flags.num_classes_train, flags.num_shots_train, -1),\n name='reshape_to_separate_tasks_task_encoding')\n label_embeddings = tf.reshape(label_embeddings, shape=(\n flags.num_tasks_per_batch, flags.num_classes_train, -1),\n name='reshape_to_separate_tasks_label_embedding')\n else:\n task_encoding = tf.reshape(task_encoding,\n shape=(1, flags.num_classes_test, flags.num_shots_test, -1),\n name='reshape_to_separate_tasks_task_encoding')\n label_embeddings = tf.reshape(label_embeddings,\n shape=(1, flags.num_classes_test, -1),\n name='reshape_to_separate_tasks_label_embedding')\n task_encoding = tf.reduce_mean(task_encoding, axis=2, keep_dims=False)\n\n # i is the number of steps in the task_encoding sequence\n # j is the number of steps in the features_generic sequence\n j = task_encoding.get_shape().as_list()[1]\n i = label_embeddings.get_shape().as_list()[1]\n\n # tile to be able to produce weight matrix alpha in (i,j) space\n task_encoding = tf.expand_dims(task_encoding, axis=2)\n label_embeddings = tf.expand_dims(label_embeddings, axis=1)\n # features_generic changes over i and is constant over j\n # task_encoding changes over j and is constant over i\n label_embeddings_tile = tf.tile(label_embeddings, (1, i, 1, 1))\n task_encoding_tile = tf.tile(task_encoding, (1, 1, j, 1))\n # implement equation (4)\n euclidian = -tf.norm(task_encoding_tile - label_embeddings_tile, name='neg_euclidian_distance_regularizer', axis=-1)\n\n if is_training:\n euclidian = tf.reshape(euclidian, shape=(flags.num_tasks_per_batch * flags.num_classes_train, -1))\n else:\n euclidian_shape = euclidian.get_shape().as_list()\n euclidian = tf.reshape(euclidian, shape=(euclidian_shape[1], -1))\n\n return euclidian\n\n\ndef placeholder_inputs(batch_size, image_size, scope):\n \"\"\"\n :param batch_size:\n :return: placeholders for images and\n \"\"\"\n with tf.variable_scope(scope):\n images_placeholder = tf.placeholder(tf.float32, shape=(batch_size, image_size, image_size, 3), name='images')\n labels_placeholder = tf.placeholder(tf.int64, shape=(batch_size), name='labels')\n return images_placeholder, labels_placeholder\n\n\ndef get_batch(data_set, images_placeholder, labels_placeholder, batch_size):\n \"\"\"\n :param data_set:\n :param images_placeholder:\n :param labels_placeholder:\n :return:\n \"\"\"\n images_feed, labels_feed = data_set.next_batch(batch_size)\n\n feed_dict = {\n images_placeholder: images_feed.astype(dtype=np.float32),\n labels_placeholder: labels_feed,\n }\n return feed_dict\n\n\ndef preprocess(images):\n # mean = tf.constant(np.asarray([127.5, 127.5, 127.5]).reshape([1, 1, 3]), dtype=tf.float32, name='image_mean')\n # std = tf.constant(np.asarray([127.5, 127.5, 127.5]).reshape([1, 1, 3]), dtype=tf.float32, name='image_std')\n # return tf.div(tf.subtract(images, mean), std)\n\n std = tf.constant(np.asarray([0.5, 0.5, 0.5]).reshape([1, 1, 3]), dtype=tf.float32, name='image_std')\n return tf.div(images, std)\n\n\ndef get_nearest_neighbour_acc(flags, embeddings, labels):\n num_correct = 0\n num_tot = 0\n for i in trange(flags.num_cases_test):\n test_classes = np.random.choice(np.unique(labels), size=flags.num_classes_test, replace=False)\n train_idxs, test_idxs = get_few_shot_idxs(labels=labels, classes=test_classes, num_shots=flags.num_shots_test)\n # TODO: this is to fix the OOM error, this can be removed when embed() supports batch processing\n test_idxs = np.random.choice(test_idxs, size=100, replace=False)\n\n np_embedding_train = embeddings[train_idxs]\n # Using the np.std instead of np.linalg.norm improves results by around 1-1.5%\n np_embedding_train = np_embedding_train / np.std(np_embedding_train, axis=1, keepdims=True)\n # np_embedding_train = np_embedding_train / np.linalg.norm(np_embedding_train, axis=1, keepdims=True)\n labels_train = labels[train_idxs]\n\n np_embedding_test = embeddings[test_idxs]\n np_embedding_test = np_embedding_test / np.std(np_embedding_test, axis=1, keepdims=True)\n # np_embedding_test = np_embedding_test / np.linalg.norm(np_embedding_test, axis=1, keepdims=True)\n labels_test = labels[test_idxs]\n\n kdtree = KDTree(np_embedding_train)\n nns, nn_idxs = kdtree.query(np_embedding_test, k=1)\n labels_predicted = labels_train[nn_idxs]\n\n num_matches = sum(labels_predicted == labels_test)\n\n num_correct += num_matches\n num_tot += len(labels_predicted)\n\n # print(\"Accuracy: \", (100.0 * num_correct) / num_tot)\n return (100.0 * num_correct) / num_tot\n\n\n\ndef build_inference_graph(images_deploy_pl, images_task_encode_pl, flags, is_training,\n is_primary, label_embeddings):\n num_filters = [round(flags.num_filters * pow(flags.block_size_growth, i)) for i in range(flags.num_blocks)]\n reuse = not is_primary\n alpha=None\n\n with tf.variable_scope('Model'):\n feature_extractor_encoding_scope = 'feature_extractor_encoder'\n\n features_task_encode = build_feature_extractor_graph(images=images_task_encode_pl, flags=flags,\n is_training=is_training,\n num_filters=num_filters,\n scope=feature_extractor_encoding_scope,\n reuse=False)\n if flags.encoder_sharing == 'shared':\n ecoder_reuse = True\n feature_extractor_classifier_scope = feature_extractor_encoding_scope\n elif flags.encoder_sharing == 'siamese':\n # TODO: in the case of pretrained feature extractor this is not good,\n # because the classfier part will be randomly initialized\n ecoder_reuse = False\n feature_extractor_classifier_scope = 'feature_extractor_classifier'\n else:\n raise Exception('Option not implemented')\n\n if flags.encoder_classifier_link == 'prototypical':\n #flags.task_encoder = 'class_mean'\n features_generic = build_feature_extractor_graph(images=images_deploy_pl, flags=flags,\n is_training=is_training,\n scope=feature_extractor_classifier_scope,\n num_filters=num_filters,\n reuse=ecoder_reuse)\n querys = None\n if 'query' in flags.att_input:\n querys = features_generic\n task_encoding, alpha = build_task_encoder(embeddings=features_task_encode,\n label_embeddings=label_embeddings,\n flags=flags, is_training=is_training, reuse=reuse, querys=querys,\n threshold=flags.alpha)\n if 'query' in flags.att_input:\n logits = build_prototypical_head_protoperquery(features_generic, task_encoding, flags,\n is_training=is_training)\n else:\n logits = build_prototypical_head(features_generic, task_encoding, flags, is_training=is_training)\n # logits_regularizer = build_regularizer_head(embeddings= features_task_encode,\n # label_embeddings=label_embeddings, flags=flags,\n # is_training=is_training )\n else:\n raise Exception('Option not implemented')\n\n return logits, None, features_task_encode, features_generic, alpha\n\n\n\n\ndef get_train_datasets(flags):\n mini_imagenet = _load_mini_imagenet(data_dir=flags.data_dir, split='sources')\n few_shot_data_train = Dataset(mini_imagenet)\n pretrain_data_train, pretrain_data_test = None, None\n return few_shot_data_train, pretrain_data_train, pretrain_data_test\n\n\ndef get_pwc_learning_rate(global_step, flags):\n learning_rate = tf.train.piecewise_constant(global_step, [np.int64(flags.number_of_steps / 2),\n np.int64(\n flags.number_of_steps / 2 + flags.num_steps_decay_pwc),\n np.int64(\n flags.number_of_steps / 2 + 2 * flags.num_steps_decay_pwc)],\n [flags.init_learning_rate, flags.init_learning_rate * 0.1,\n flags.init_learning_rate * 0.01,\n flags.init_learning_rate * 0.001])\n return learning_rate\n\n\ndef create_hard_negative_batch(misclass, feed_dict, sess, few_shot_data_train, flags,\n images_deploy_pl, labels_deploy_pl, images_task_encode_pl, labels_task_encode_pl):\n \"\"\"\n\n :param logits:\n :param feed_dict:\n :param sess:\n :param few_shot_data_train:\n :param flags:\n :param images_deploy_pl:\n :param labels_deploy_pl:\n :param images_task_encode_pl:\n :param labels_task_encode_pl:\n :return:\n \"\"\"\n feed_dict_test = dict(feed_dict)\n misclass_test_final = 0.0\n misclass_history = np.zeros(flags.num_batches_neg_mining)\n for i in range(flags.num_batches_neg_mining):\n images_deploy, labels_deploy, images_task_encode, labels_task_encode = \\\n few_shot_data_train.next_few_shot_batch(deploy_batch_size=flags.train_batch_size,\n num_classes_test=flags.num_classes_train,\n num_shots=flags.num_shots_train,\n num_tasks=flags.num_tasks_per_batch)\n\n feed_dict_test[images_deploy_pl] = images_deploy.astype(dtype=np.float32)\n feed_dict_test[labels_deploy_pl] = labels_deploy\n feed_dict_test[images_task_encode_pl] = images_task_encode.astype(dtype=np.float32)\n feed_dict_test[labels_task_encode_pl] = labels_task_encode\n\n # logits\n misclass_test = sess.run(misclass, feed_dict=feed_dict_test)\n misclass_history[i] = misclass_test\n if misclass_test > misclass_test_final:\n misclass_test_final = misclass_test\n feed_dict = dict(feed_dict_test)\n\n return feed_dict\n\n\ndef train(flags):\n log_dir = get_logdir_name(flags)\n flags.pretrained_model_dir = log_dir\n fout=open(log_dir+'/out','a')\n log_dir = os.path.join(log_dir, 'train')\n # This is setting to run evaluation loop only once\n flags.max_number_of_evaluations = 1\n flags.eval_interval_secs = 0\n image_size = get_image_size(flags.data_dir)\n\n with tf.Graph().as_default():\n global_step = tf.Variable(0, trainable=False, name='global_step', dtype=tf.int64)\n global_step_pretrain = tf.Variable(0, trainable=False, name='global_step_pretrain', dtype=tf.int64)\n\n images_deploy_pl, labels_deploy_pl = placeholder_inputs(\n batch_size=flags.num_tasks_per_batch * flags.train_batch_size,\n image_size=image_size, scope='inputs/deploy')\n images_task_encode_pl, _ = placeholder_inputs(\n batch_size=flags.num_tasks_per_batch * flags.num_classes_train * flags.num_shots_train,\n image_size=image_size, scope='inputs/task_encode')\n with tf.variable_scope('inputs/task_encode'):\n labels_task_encode_pl_real = tf.placeholder(tf.int64,\n shape=(flags.num_tasks_per_batch * flags.num_classes_train), name='labels_real')\n labels_task_encode_pl = tf.placeholder(tf.int64,\n shape=(flags.num_tasks_per_batch * flags.num_classes_train),\n name='labels')\n\n #here is the word embedding layer for training\n\n emb_path = os.path.join(flags.data_dir, 'few-shot-wordemb-{}.npz'.format(\"train\"))\n embedding_train = np.load(emb_path)[\"features\"].astype(np.float32)\n print(embedding_train.dtype)\n logging.info(\"Loading mini-imagenet...\")\n W_train = tf.constant(embedding_train, name=\"W_train\")\n label_embeddings_train = tf.nn.embedding_lookup(W_train, labels_task_encode_pl_real)\n\n # Primary task operations\n logits, regularizer_logits, _, _, alpha = build_inference_graph(images_deploy_pl=images_deploy_pl,\n images_task_encode_pl=images_task_encode_pl,\n flags=flags, is_training=True, is_primary=True,\n label_embeddings=label_embeddings_train)\n loss = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(logits=logits,\n labels=tf.one_hot(labels_deploy_pl, flags.num_classes_train)))\n # Losses and optimizer\n regu_losses = slim.losses.get_regularization_losses()\n loss = tf.add_n([loss] + regu_losses)\n misclass = 1.0 - slim.metrics.accuracy(tf.argmax(logits, 1), labels_deploy_pl)\n\n # Learning rate\n if flags.lr_anneal == 'const':\n learning_rate = flags.init_learning_rate\n elif flags.lr_anneal == 'pwc':\n learning_rate = get_pwc_learning_rate(global_step, flags)\n elif flags.lr_anneal == 'exp':\n lr_decay_step = flags.number_of_steps // flags.n_lr_decay\n learning_rate = tf.train.exponential_decay(flags.init_learning_rate, global_step, lr_decay_step,\n 1.0 / flags.lr_decay_rate, staircase=True)\n else:\n raise Exception('Not implemented')\n\n # Optimizer\n if flags.optimizer == 'sgd':\n optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=0.9)\n else:\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n\n train_op = slim.learning.create_train_op(total_loss=loss, optimizer=optimizer, global_step=global_step,\n clip_gradient_norm=flags.clip_gradient_norm)\n\n tf.summary.scalar('loss', loss)\n tf.summary.scalar('misclassification', misclass)\n tf.summary.scalar('learning_rate', learning_rate)\n # Merge all summaries except for pretrain\n summary = tf.summary.merge(tf.get_collection('summaries', scope='(?!pretrain).*'))\n\n\n # Get datasets\n few_shot_data_train, pretrain_data_train, pretrain_data_test = get_train_datasets(flags)\n # Define session and logging\n summary_writer = tf.summary.FileWriter(log_dir, flush_secs=1)\n saver = tf.train.Saver(max_to_keep=1, save_relative_paths=True)\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n supervisor = tf.train.Supervisor(logdir=log_dir, init_feed_dict=None,\n summary_op=None,\n init_op=tf.global_variables_initializer(),\n summary_writer=summary_writer,\n saver=saver,\n global_step=global_step, save_summaries_secs=flags.save_summaries_secs,\n save_model_secs=0) # flags.save_interval_secs\n\n with supervisor.managed_session() as sess:\n checkpoint_step = sess.run(global_step)\n if checkpoint_step > 0:\n checkpoint_step += 1\n\n eval_interval_steps = flags.eval_interval_steps\n for step in range(checkpoint_step, flags.number_of_steps):\n # get batch of data to compute classification loss\n images_deploy, labels_deploy, images_task_encode, labels_task_encode_real, labels_task_encode = \\\n few_shot_data_train.next_few_shot_batch_wordemb(deploy_batch_size=flags.train_batch_size,\n num_classes_test=flags.num_classes_train,\n num_shots=flags.num_shots_train,\n num_tasks=flags.num_tasks_per_batch)\n if flags.augment:\n images_deploy = image_augment(images_deploy)\n images_task_encode = image_augment(images_task_encode)\n\n feed_dict = {images_deploy_pl: images_deploy.astype(dtype=np.float32), labels_deploy_pl: labels_deploy,\n images_task_encode_pl: images_task_encode.astype(dtype=np.float32),\n labels_task_encode_pl_real: labels_task_encode_real,\n labels_task_encode_pl: labels_task_encode}\n\n\n t_batch = time.time()\n feed_dict = create_hard_negative_batch(misclass, feed_dict, sess, few_shot_data_train, flags,\n images_deploy_pl, labels_deploy_pl, images_task_encode_pl,\n labels_task_encode_pl_real)\n dt_batch = time.time() - t_batch\n\n t_train = time.time()\n loss,alpha_np = sess.run([train_op,alpha], feed_dict=feed_dict)\n dt_train = time.time() - t_train\n\n if step % 100 == 0:\n summary_str = sess.run(summary, feed_dict=feed_dict)\n summary_writer.add_summary(summary_str, step)\n summary_writer.flush()\n logging.info(\"step %d, loss : %.4g, dt: %.3gs, dt_batch: %.3gs\" % (step, loss, dt_train, dt_batch))\n fout.write(\"step: \"+str(step)+' loss: '+str(loss)+'\\n')\n\n if float(step) / flags.number_of_steps > 0.5:\n eval_interval_steps = flags.eval_interval_fine_steps\n\n if eval_interval_steps > 0 and step % eval_interval_steps == 0:\n saver.save(sess, os.path.join(log_dir, 'model'), global_step=step)\n eval(flags=flags, is_primary=True, fout=fout)\n\n if float(step) > 0.5 * flags.number_of_steps + flags.number_of_steps_to_early_stop:\n break\n\n\n\nclass ModelLoader:\n def __init__(self, model_path, batch_size, is_primary, split):\n self.batch_size = batch_size\n\n latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir=os.path.join(model_path, 'train'))\n step = int(os.path.basename(latest_checkpoint).split('-')[1])\n\n flags = Namespace(load_and_save_params(default_params=dict(), exp_dir=model_path))\n image_size = get_image_size(flags.data_dir)\n\n with tf.Graph().as_default():\n images_deploy_pl, labels_deploy_pl = placeholder_inputs(batch_size=batch_size,\n image_size=image_size, scope='inputs/deploy')\n if is_primary:\n task_encode_batch_size = flags.num_classes_test * flags.num_shots_test\n images_task_encode_pl, _ = placeholder_inputs(batch_size=task_encode_batch_size,\n image_size=image_size,\n scope='inputs/task_encode')\n with tf.variable_scope('inputs/task_encode'):\n labels_task_encode_pl_real = tf.placeholder(tf.int64,\n shape=(flags.num_classes_test), name='labels_real')\n labels_task_encode_pl = tf.placeholder(tf.int64,\n shape=(flags.num_classes_test),\n name='labels')\n self.vocab_size = tf.placeholder(tf.float32, shape=(), name='vocab_size')\n self.tensor_images_deploy = images_deploy_pl\n self.tensor_labels_deploy = labels_deploy_pl\n self.tensor_labels_task_encode_real = labels_task_encode_pl_real\n self.tensor_labels_task_encode = labels_task_encode_pl\n self.tensor_images_task_encode = images_task_encode_pl\n\n emb_path = os.path.join(flags.data_dir, 'few-shot-wordemb-{}.npz'.format(split))\n embedding_train = np.load(emb_path)[\"features\"].astype(np.float32)\n print(embedding_train.dtype)\n logging.info(\"Loading mini-imagenet...\")\n W = tf.constant(embedding_train, name=\"W_\"+split)\n\n\n label_embeddings_train = tf.nn.embedding_lookup(W, labels_task_encode_pl_real)\n\n # Primary task operations\n logits, regularizer_logits, features_sample, features_query, self.alpha = build_inference_graph(images_deploy_pl=images_deploy_pl,\n images_task_encode_pl=images_task_encode_pl,\n flags=flags, is_training=False, is_primary=True,\n label_embeddings=label_embeddings_train)\n loss = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(logits=logits,\n labels=tf.one_hot(labels_deploy_pl, flags.num_classes_test)))\n regularizer_loss = 0.0\n\n # Losses and optimizer\n regu_losses = slim.losses.get_regularization_losses()\n\n loss = tf.add_n([loss] + regu_losses + [regularizer_loss])\n\n init_fn = slim.assign_from_checkpoint_fn(\n latest_checkpoint,\n slim.get_model_variables('Model'))\n\n config = tf.ConfigProto(allow_soft_placement=True)\n config.gpu_options.allow_growth = True\n self.sess = tf.Session(config=config)\n\n # Run init before loading the weights\n self.sess.run(tf.global_variables_initializer())\n # Load weights\n init_fn(self.sess)\n\n self.flags = flags\n self.logits = logits\n self.loss = loss\n self.features_sample = features_sample\n self.features_query = features_query\n self.logits_size = self.logits.get_shape().as_list()[-1]\n self.step = step\n self.is_primary = is_primary\n\n log_dir = get_logdir_name(flags)\n graphpb_txt = str(tf.get_default_graph().as_graph_def())\n pathlib.Path(os.path.join(log_dir, 'eval')).mkdir(parents=True, exist_ok=True)\n with open(os.path.join(log_dir, 'eval', 'graph.pbtxt'), 'w') as f:\n f.write(graphpb_txt)\n\n def eval(self, data_dir, num_cases_test, split='target_val'):\n data_set = Dataset(_load_mini_imagenet(data_dir=data_dir, split=split))\n\n num_batches = num_cases_test // self.batch_size\n num_correct = 0.0\n num_tot = 0.0\n loss_tot = 0.0\n final_alpha=[]\n for i in range(num_batches):\n num_classes, num_shots = self.flags.num_classes_test, self.flags.num_shots_test\n\n images_deploy, labels_deploy, images_task_encode, labels_task_encode_real, labels_task_encode = \\\n data_set.next_few_shot_batch_wordemb(deploy_batch_size=self.batch_size,\n num_classes_test=num_classes, num_shots=num_shots,\n num_tasks=1)\n\n\n feed_dict = {self.tensor_images_deploy: images_deploy.astype(dtype=np.float32),\n self.tensor_labels_task_encode_real: labels_task_encode_real,\n self.tensor_labels_deploy: labels_deploy,\n self.tensor_labels_task_encode: labels_task_encode,\n self.tensor_images_task_encode: images_task_encode.astype(dtype=np.float32)}\n [logits, loss, alpha] = self.sess.run([self.logits, self.loss, self.alpha], feed_dict)\n final_alpha.append(alpha)\n labels_deploy_pred = np.argmax(logits, axis=-1)\n\n num_matches = sum(labels_deploy_pred == labels_deploy)\n num_correct += num_matches\n num_tot += len(labels_deploy_pred)\n loss_tot += loss\n if split=='target_tst':\n log_dir = get_logdir_name(self.flags)\n pathlib.Path(os.path.join(log_dir, 'eval')).mkdir(parents=True, exist_ok=True)\n pkl.dump(final_alpha,open(os.path.join(log_dir, 'eval', 'lambdas.pkl'), \"wb\"))\n\n return num_correct / num_tot, loss_tot / num_batches\n\n\ndef get_few_shot_idxs(labels, classes, num_shots):\n train_idxs, test_idxs = [], []\n idxs = np.arange(len(labels))\n for cl in classes:\n class_idxs = idxs[labels == cl]\n class_idxs_train = np.random.choice(class_idxs, size=num_shots, replace=False)\n class_idxs_test = np.setxor1d(class_idxs, class_idxs_train)\n\n train_idxs.extend(class_idxs_train)\n test_idxs.extend(class_idxs_test)\n\n assert set(class_idxs_train).isdisjoint(test_idxs)\n\n return np.array(train_idxs), np.array(test_idxs)\n\n\ndef test(flags):\n test_dataset = _load_mini_imagenet(data_dir=flags.data_dir, split='target_val')\n\n # test_dataset = _load_mini_imagenet(data_dir=flags.data_dir, split='sources')\n images = test_dataset[0]\n labels = test_dataset[1]\n\n embedding_model = ModelLoader(flags.pretrained_model_dir, batch_size=100)\n embeddings = embedding_model.embed(images=test_dataset[0])\n embedding_model = None\n print(\"Accuracy test raw embedding: \", get_nearest_neighbour_acc(flags, embeddings, labels))\n\n\ndef get_agg_misclassification(logits_dict, labels_dict):\n summary_ops = []\n update_ops = {}\n for key, logits in logits_dict.items():\n accuracy, update = slim.metrics.streaming_accuracy(tf.argmax(logits, 1), labels_dict[key])\n\n names_to_values, names_to_updates = slim.metrics.aggregate_metric_map(\n {'misclassification_' + key: (1.0 - accuracy, update)})\n\n for metric_name, metric_value in names_to_values.items():\n op = tf.summary.scalar(metric_name, metric_value)\n op = tf.Print(op, [metric_value], metric_name)\n summary_ops.append(op)\n\n for update_name, update_op in names_to_updates.items():\n update_ops[update_name] = update_op\n return summary_ops, update_ops\n\n\ndef eval(flags, is_primary, fout):\n log_dir = get_logdir_name(flags)\n if is_primary:\n aux_prefix = ''\n else:\n aux_prefix = 'aux/'\n\n eval_writer = summary_writer(log_dir + '/eval')\n i = 0\n last_step = -1\n while i < flags.max_number_of_evaluations:\n latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir=flags.pretrained_model_dir)\n model_step = int(os.path.basename(latest_checkpoint or '0-0').split('-')[1])\n if last_step < model_step:\n results = {}\n model_train = ModelLoader(model_path=flags.pretrained_model_dir, batch_size=flags.eval_batch_size,\n is_primary=is_primary,split='train')\n acc_trn, loss_trn = model_train.eval(data_dir=flags.data_dir, num_cases_test=flags.num_cases_test,\n split='sources')\n\n model_val = ModelLoader(model_path=flags.pretrained_model_dir, batch_size=flags.eval_batch_size,\n is_primary=is_primary, split='val')\n acc_val, loss_val = model_val.eval(data_dir=flags.data_dir, num_cases_test=flags.num_cases_test,\n split='target_val')\n\n model_test = ModelLoader(model_path=flags.pretrained_model_dir, batch_size=flags.eval_batch_size,\n is_primary=is_primary, split='test')\n acc_tst, loss_tst = model_test.eval(data_dir=flags.data_dir, num_cases_test=flags.num_cases_test,\n split='target_tst')\n\n results[aux_prefix + \"accuracy_target_tst\"] = acc_tst\n results[aux_prefix + \"accuracy_target_val\"] = acc_val\n results[aux_prefix + \"accuracy_sources\"] = acc_trn\n\n results[aux_prefix + \"loss_target_tst\"] = loss_tst\n results[aux_prefix + \"loss_target_val\"] = loss_val\n results[aux_prefix + \"loss_sources\"] = loss_trn\n\n last_step = model_train.step\n eval_writer(model_train.step, **results)\n logging.info(\"accuracy_%s: %.3g, accuracy_%s: %.3g, accuracy_%s: %.3g, loss_%s: %.3g, loss_%s: %.3g, loss_%s: %.3g.\"\n % (\n aux_prefix + \"target_tst\", acc_tst, aux_prefix + \"target_val\", acc_val, aux_prefix + \"sources\",\n acc_trn, aux_prefix + \"target_tst\", loss_tst, aux_prefix + \"target_val\", loss_val, aux_prefix + \"sources\",\n loss_trn))\n fout.write(\"accuracy_test: \"+str(acc_tst)+\" accuracy_val: \"+str(acc_val)+\" accuracy_test: \"+str(acc_trn))\n if flags.eval_interval_secs > 0:\n time.sleep(flags.eval_interval_secs)\n i = i + 1\n\n\n\n\n\ndef image_augment(images):\n \"\"\"\n\n :param images:\n :return:\n \"\"\"\n pad_percent = 0.125\n flip_proba = 0.5\n image_size = images.shape[1]\n pad_size = int(pad_percent * image_size)\n max_crop = 2 * pad_size\n\n images_aug = np.pad(images, ((0, 0), (pad_size, pad_size), (pad_size, pad_size), (0, 0)), mode='constant')\n output = []\n for image in images_aug:\n if np.random.rand() < flip_proba:\n image = np.flip(image, axis=1)\n crop_val = np.random.randint(0, max_crop)\n image = image[crop_val:crop_val + image_size, crop_val:crop_val + image_size, :]\n output.append(image)\n return np.asarray(output)\n\n\ndef main(argv=None):\n config = tf.ConfigProto(allow_soft_placement=True)\n config.gpu_options.per_process_gpu_memory_fraction = 1.0\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n\n print(os.getcwd())\n\n default_params = get_arguments()\n log_dir = get_logdir_name(flags=default_params)\n\n pathlib.Path(log_dir).mkdir(parents=True, exist_ok=True)\n # This makes sure that we can store a json and recove a namespace back\n flags = Namespace(load_and_save_params(vars(default_params), log_dir))\n\n if flags.mode == 'train':\n train(flags=flags)\n elif flags.mode == 'eval':\n eval(flags=flags, is_primary=True)\n elif flags.mode == 'test':\n test(flags=flags)\n\n\nif __name__ == '__main__':\n tf.app.run()"
]
| [
[
"tensorflow.concat",
"numpy.sqrt",
"numpy.asarray",
"tensorflow.RunMetadata",
"tensorflow.contrib.slim.losses.get_regularization_losses",
"tensorflow.contrib.slim.flatten",
"tensorflow.train.AdamOptimizer",
"tensorflow.get_default_graph",
"tensorflow.contrib.slim.metrics.aggregate_metric_map",
"tensorflow.add_n",
"tensorflow.summary.scalar",
"numpy.setxor1d",
"numpy.random.randint",
"tensorflow.contrib.slim.avg_pool2d",
"tensorflow.Graph",
"numpy.pad",
"tensorflow.Variable",
"numpy.unique",
"tensorflow.get_collection",
"tensorflow.train.exponential_decay",
"tensorflow.div",
"tensorflow.ConfigProto",
"numpy.std",
"tensorflow.train.MomentumOptimizer",
"numpy.argmax",
"tensorflow.logging.set_verbosity",
"tensorflow.Session",
"tensorflow.train.Saver",
"numpy.load",
"tensorflow.argmax",
"numpy.zeros",
"tensorflow.tile",
"tensorflow.app.run",
"tensorflow.contrib.slim.learning.create_train_op",
"tensorflow.norm",
"tensorflow.Print",
"tensorflow.contrib.slim.arg_scope",
"numpy.random.choice",
"tensorflow.RunOptions",
"tensorflow.placeholder",
"tensorflow.python.framework.dtypes.as_dtype",
"numpy.int64",
"scipy.spatial.KDTree",
"tensorflow.contrib.slim.fully_connected",
"numpy.random.rand",
"tensorflow.global_variables_initializer",
"tensorflow.one_hot",
"numpy.array",
"numpy.flip",
"tensorflow.nn.embedding_lookup",
"tensorflow.constant",
"tensorflow.summary.FileWriter",
"tensorflow.train.latest_checkpoint",
"tensorflow.reduce_mean",
"tensorflow.contrib.slim.dropout",
"tensorflow.maximum",
"tensorflow.contrib.slim.max_pool2d",
"tensorflow.reshape",
"tensorflow.sigmoid",
"tensorflow.expand_dims",
"tensorflow.contrib.slim.get_model_variables",
"tensorflow.constant_initializer",
"tensorflow.python.ops.random_ops.random_normal",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.variable_scope",
"tensorflow.contrib.slim.conv2d"
]
]
|
marwan-eid/Web-Application-and-Database-System-Backend-for-Egyptian-movies | [
"5bc1f9a08b14f9917706d0f25076195bee50157d"
]
| [
"Web Application.py"
]
| [
"import dash\r\nimport dash_table\r\nimport dash_html_components as html\r\nimport dash_core_components as dcc\r\nimport MySQLdb\r\nimport numpy as np\r\nimport pandas as pd\r\nimport webbrowser\r\nfrom dash.dependencies import Input, Output, State\r\nfrom dash.exceptions import PreventUpdate\r\nfrom threading import Timer\r\n\r\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\r\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\r\napp.css.config.serve_locally = True\r\napp.scripts.config.serve_locally = True\r\n\r\nparams_movies_reviews = ['m_name', 'user_email_address', 'review']\r\nparams_cast_movies = ['cm_name', 'm_name', 'm_duration', 'm_release_date', 'm_storyline']\r\nparams_genres = ['m_name', 'm_duration', 'm_release_date', 'm_storyline']\r\nparams_movie = ['m_name', 'm_duration', 'm_rating', 'm_release_date', 'm_storyline', 'm_revenue', 'm_director_name', 'm_writer_name']\r\nparams_cast_member = ['cm_name', 'cm_biography', 'cm_birthdate', 'cm_nationality']\r\nparams_top = ['m_name', 'm_duration', 'm_rating', 'm_release_date', 'm_revenue']\r\napp.layout = html.Div([\r\n html.H1('Egyptian IMDB', style={'textAlign': 'center', 'margin': '48px 0', 'fontFamily': 'system-ui'}),\r\n html.H4('Fundamentals of Database Systems Project - Marwan Eid', style={'textAlign': 'center', 'fontFamily': 'system-ui'}),\r\n dcc.Tabs(id=\"tabs\", children=[\r\n dcc.Tab(label='Register a user', children=[\r\n html.Div([\r\n html.Form(children=[\r\n html.P(children=[\"Username: \", dcc.Input(type='text', id='user_username')], style={'marginLeft': '200'}),\r\n html.P(children=[\"Email Address: \", dcc.Input(type='email', id='user_email_address', required=True)], style={'marginLeft': '800'}),\r\n html.P(children=[\"Gender: \", dcc.Dropdown(id='gender-dropdown', options=[\r\n {'label': 'Male', 'value': 'M'}, {'label': 'Female', 'value': 'F'}])], style={'marginLeft': '200', 'width': '50%'}),\r\n html.P(children=[\"Birthdate: \", dcc.DatePickerSingle(id='user_birthdate')], style={'marginLeft': '800'}),\r\n html.Button('Register', id='register', n_clicks_timestamp=0, style={'marginLeft': '200', 'marginTop': '20px'})]),\r\n html.Div(id='out_trial')])\r\n ]),\r\n dcc.Tab(label='Find a movie', children=[\r\n html.Div([\r\n html.Form(children=[\r\n html.P(children=[\"Movie ID: \", dcc.Input(type='number', id='movie_id')], style={'marginLeft': '200'}),\r\n html.P(children=[\"Movie Name: \", dcc.Input(type='text', id='movie_name')], style={'marginLeft': '800'}),\r\n ]),\r\n html.Button('Search by movie ID', id='show-movie-by-id', n_clicks_timestamp=0, style={'marginLeft': '200', 'marginTop': '20px'}),\r\n html.Button('Search by movie Name', id='show-movie-by-name', n_clicks_timestamp=0, style={'marginLeft': '800', 'marginTop': '20px'}),\r\n dash_table.DataTable(id='movie-table',\r\n columns=([{'id': p, 'name': p} for p in params_movie]),\r\n data = [], editable=True, style_cell={'textAlign': 'left', 'whiteSpace': 'normal', 'height': 'auto'})\r\n ])\r\n ]),\r\n dcc.Tab(label='Find a cast member', children=[\r\n html.Div([\r\n html.Form(children=[\r\n html.P(children=[\"Cast Member ID: \", dcc.Input(type='number', id='cast_member_id')], style={'marginLeft': '200'}),\r\n html.P(children=[\"Cast Member Name: \", dcc.Input(type='text', id='cast_member_name')], style={'marginLeft': '800'}),\r\n ]),\r\n html.Button('Search by cast member ID', id='show-cast-member-by-id', n_clicks_timestamp=0, style={'marginLeft': '200', 'marginTop': '20px'}),\r\n html.Button('Search by cast member Name', id='show-cast-member-by-name', n_clicks_timestamp=0, style={'marginLeft': '800', 'marginTop': '20px'}),\r\n dash_table.DataTable(id='cast-member-table',\r\n columns=([{'id': p, 'name': p} for p in params_cast_member]),\r\n data = [], editable=True, style_cell={'textAlign': 'left', 'whiteSpace': 'normal', 'height': 'auto'})\r\n ])\r\n ]),\r\n dcc.Tab(label='Top 10 movies by total revenue', children=[\r\n html.Div([\r\n html.Button('Click to find the top 10 movies by revenue', id='show-top',style={'marginLeft': '565px', 'marginTop': '25px'}),\r\n dash_table.DataTable(id='top-table',\r\n columns=([{'id': 'No', 'name': 'No'}] + [{'id': p, 'name': p} for p in params_top]),\r\n data = [], editable=True, style_cell={'textAlign': 'left'})\r\n ])\r\n ]),\r\n dcc.Tab(label='Find movies by genre', children=[\r\n html.Div([dcc.Dropdown(id='genres-dropdown', options=[\r\n {'label': 'Action', 'value': 'Action'},\r\n {'label': 'Adventure', 'value': 'Adventure'},\r\n {'label': 'Animation', 'value': 'Animation'},\r\n {'label': 'Biography', 'value': 'Biography'},\r\n {'label': 'Comedy', 'value': 'Comedy'},\r\n {'label': 'Crime', 'value': 'Crime'},\r\n {'label': 'Documentary', 'value': 'Documentary'},\r\n {'label': 'Drama', 'value': 'Drama'},\r\n {'label': 'Family', 'value': 'Family'},\r\n {'label': 'Fantasy', 'value': 'Fantasy'},\r\n {'label': 'History', 'value': 'History'},\r\n {'label': 'Horror', 'value': 'Horror'},\r\n {'label': 'Musical', 'value': 'Musical'},\r\n {'label': 'Mystery', 'value': 'Mystery'},\r\n {'label': 'Religious', 'value': 'Religious'},\r\n {'label': 'Romance', 'value': 'Romance'},\r\n {'label': 'Science Fiction', 'value': 'Science Fiction'},\r\n {'label': 'Short', 'value': 'Short'},\r\n {'label': 'Sport', 'value': 'Sport'},\r\n {'label': 'Thriller', 'value': 'Thriller'},\r\n {'label': 'War', 'value': 'War'}\r\n ]),\r\n dash_table.DataTable(id='genres-table',\r\n columns=([{'id': 'No', 'name': 'No'}] + [{'id': p, 'name': p} for p in params_genres]),\r\n data = [], editable=True, style_cell={'textAlign': 'left', 'whiteSpace': 'normal', 'height': 'auto'})\r\n ])\r\n ]),\r\n dcc.Tab(label='Find movies of a cast member', children=[\r\n html.Div([\r\n html.Form(children=[\r\n html.P(children=[\"Cast Member ID: \", dcc.Input(type='number', id='cast_member_movie_id')], style={'marginLeft': '200'}),\r\n html.P(children=[\"Cast Member Name: \", dcc.Input(type='text', id='cast_member_movie_name')], style={'marginLeft': '800'}),\r\n ]),\r\n html.Button('Search by cast member ID', id='show-cast-member-movie-by-id', n_clicks_timestamp=0, style={'marginLeft': '200', 'marginTop': '20px'}),\r\n html.Button('Search by cast member Name', id='show-cast-member-movie-by-name', n_clicks_timestamp=0, style={'marginLeft': '800', 'marginTop': '20px'}),\r\n dash_table.DataTable(id='cast-member-movie-table',\r\n columns=([{'id': p, 'name': p} for p in params_cast_movies]),\r\n data = [], editable=True, style_cell={'textAlign': 'left', 'whiteSpace': 'normal', 'height': 'auto'})\r\n ])\r\n ]),\r\n dcc.Tab(label='Check movies reviews', children=[\r\n html.Div([\r\n html.P(children=[\"Movie ID: \", dcc.Input(type='number', id='find_review_movie_id')], style={'marginLeft': '200'}),\r\n html.P(children=[\"Movie Name: \", dcc.Input(type='text', id='find_review_movie_name')], style={'marginLeft': '800'})]),\r\n html.Button('Find using movie ID', id='find-review-movie-by-id', n_clicks_timestamp=0, style={'marginLeft': '200', 'marginTop': '20px'}),\r\n html.Button('Find using movie Name', id='find-review-movie-by-name', n_clicks_timestamp=0, style={'marginLeft': '800', 'marginTop': '20px'}),\r\n dash_table.DataTable(id='movies-reviews-table',\r\n columns=([{'id': 'No', 'name': 'No'}] + [{'id': p, 'name': p} for p in params_movies_reviews]),\r\n data = [], editable=True, style_cell={'textAlign': 'left', 'whiteSpace': 'normal', 'height': 'auto'})\r\n ]),\r\n dcc.Tab(label='Add a movie review', children=[\r\n html.Div([\r\n html.P(children=[\"Email Address: \", dcc.Input(type='email', id='add_review_email_address', required=True)], style={'marginLeft': '800'}),\r\n html.P(children=[\"Review: \", dcc.Input(type='text', id='add_review_review')], style={'marginLeft': '200'}),\r\n html.P(children=[\"Movie ID: \", dcc.Input(type='number', id='add_review_movie_id')], style={'marginLeft': '200'}),\r\n html.P(children=[\"Movie Name: \", dcc.Input(type='text', id='add_review_movie_name')], style={'marginLeft': '800'})]),\r\n html.Button('Add using movie ID', id='add-review-movie-by-id', n_clicks_timestamp=0, style={'marginLeft': '200', 'marginTop': '20px'}),\r\n html.Button('Add using movie Name', id='add-review-movie-by-name', n_clicks_timestamp=0, style={'marginLeft': '800', 'marginTop': '20px'}),\r\n html.Div(id='out_trial_1')\r\n ])\r\n ], style={'fontFamily': 'system-ui'})\r\n ])\r\n\r\[email protected](\r\n Output('top-table', 'data'),\r\n Input(component_id='show-top', component_property='n_clicks'))\r\ndef top10_movies_by_revenue(n_clicks):\r\n if n_clicks is None:\r\n raise PreventUpdate\r\n else:\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n print(\"Connected\")\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT m_name, m_duration, m_rating, m_release_date, m_revenue FROM movie ORDER BY m_revenue DESC LIMIT 10\")\r\n m = cursor.fetchall()\r\n df = pd.DataFrame(m, columns=params_top)\r\n df['No'] = [i for i in range(1, 11)]\r\n return df.to_dict('rows')\r\n\r\[email protected](\r\n Output('movie-table', 'data'),\r\n [Input(component_id='show-movie-by-id', component_property='n_clicks_timestamp'),\r\n Input(component_id='show-movie-by-name', component_property='n_clicks_timestamp')],\r\n state=[State('movie_id', 'value'),\r\n State('movie_name', 'value')])\r\ndef find_movie(n_clicks_1, n_clicks_2, input1, input2):\r\n if int(n_clicks_1) > int(n_clicks_2):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT m_name, m_duration, m_rating, m_release_date, m_storyline, m_revenue, c1.cm_first_name, c1.cm_last_name, c2.cm_first_name, c2.cm_last_name FROM movie INNER JOIN cast_member c1 ON movie.m_director_ID = c1.cm_ID INNER JOIN cast_member c2 ON movie.m_writer_ID = c2.cm_ID WHERE movie.m_ID='%s'\" % input1)\r\n m = cursor.fetchall()\r\n director = m[0][-2] + \" \" + m[0][-1] if m[0][-1] is not None else m[0][-2]\r\n writer = m[0][-4] + \" \" + m[0][-3] if m[0][-3] is not None else m[0][-4]\r\n l = m[0][:-4]\r\n l = list(l)\r\n l.append(director)\r\n l.append(writer)\r\n df = pd.DataFrame([l], columns=params_movie)\r\n n_clicks_1 = None\r\n return df.to_dict('rows')\r\n elif int(n_clicks_1) < int(n_clicks_2):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT m_name, m_duration, m_rating, m_release_date, m_storyline, m_revenue, c1.cm_first_name, c1.cm_last_name, c2.cm_first_name, c2.cm_last_name FROM movie INNER JOIN cast_member c1 ON movie.m_director_ID = c1.cm_ID INNER JOIN cast_member c2 ON movie.m_writer_ID = c2.cm_ID WHERE movie.m_name='%s'\" % input2)\r\n m = cursor.fetchall()\r\n director = m[0][-2] + \" \" + m[0][-1] if m[0][-1] is not None else m[0][-2]\r\n writer = m[0][-4] + \" \" + m[0][-3] if m[0][-3] is not None else m[0][-4]\r\n l = m[0][:-4]\r\n l = list(l)\r\n l.append(director)\r\n l.append(writer)\r\n df = pd.DataFrame([l], columns=params_movie)\r\n n_clicks_2 = None\r\n return df.to_dict('rows')\r\n else:\r\n raise PreventUpdate\r\n\r\[email protected](\r\n Output('cast-member-table', 'data'),\r\n [Input(component_id='show-cast-member-by-id', component_property='n_clicks_timestamp'),\r\n Input(component_id='show-cast-member-by-name', component_property='n_clicks_timestamp')],\r\n state=[State('cast_member_id', 'value'),\r\n State('cast_member_name', 'value')])\r\ndef find_cast_member(n1, n2, in1, in2):\r\n if int(n1) > int(n2):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT * FROM cast_member WHERE cm_ID='%s'\" % in1)\r\n m = cursor.fetchall()\r\n name = m[0][1] + \" \" + m[0][2] if m[0][2] is not None else m[0][1]\r\n l = []\r\n l.append(name)\r\n l.append(m[0][3])\r\n l.append(m[0][4])\r\n l.append(m[0][5])\r\n df = pd.DataFrame([l], columns=params_cast_member)\r\n n1 = None\r\n return df.to_dict('rows')\r\n elif int(n1) < int(n2):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n first = in2.split(\" \")[0]\r\n try:\r\n last = in2.split(\" \")[1]\r\n except:\r\n last = None\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT * FROM cast_member WHERE cm_first_name='%s'\" % first + \" AND cm_last_name='%s'\" % last)\r\n m = cursor.fetchall()\r\n l = []\r\n l.append(in2)\r\n l.append(m[0][3])\r\n l.append(m[0][4])\r\n l.append(m[0][5])\r\n df = pd.DataFrame([l], columns=params_cast_member)\r\n n2 = None\r\n return df.to_dict('rows')\r\n else:\r\n raise PreventUpdate\r\n\r\[email protected](\r\n Output('genres-table', 'data'),\r\n [Input('genres-dropdown', 'value')])\r\ndef find_genres(value):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n print(\"Connected\")\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT m_name, m_duration, m_release_date, m_storyline FROM movie INNER JOIN movies_genres ON movie.m_ID=movies_genres.m_ID WHERE movies_genres.genre='%s'\" % value)\r\n m = cursor.fetchall()\r\n df = pd.DataFrame(m, columns=params_genres)\r\n df['No'] = [i for i in range(1, len(m)+1)]\r\n return df.to_dict('rows')\r\n\r\[email protected](\r\n Output('cast-member-movie-table', 'data'),\r\n [Input(component_id='show-cast-member-movie-by-id', component_property='n_clicks_timestamp'),\r\n Input(component_id='show-cast-member-movie-by-name', component_property='n_clicks_timestamp')],\r\n state=[State('cast_member_movie_id', 'value'),\r\n State('cast_member_movie_name', 'value')])\r\ndef find_cast_member_movies(n1, n2, in1, in2):\r\n if int(n1) > int(n2):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT CM.cm_first_name, CM.cm_last_name, M.m_name, M.m_duration, M.m_release_date, M.m_storyline FROM movies_actors MA LEFT JOIN movie M ON MA.m_ID = M.m_ID LEFT JOIN cast_member CM ON MA.cm_ID = CM.cm_ID WHERE MA.cm_ID='%s'\" % in1)\r\n m = cursor.fetchall()\r\n name = m[0][0] + \" \" + m[0][1] if m[0][1] is not None else m[0][0]\r\n t = []\r\n for i in range(len(m)):\r\n l = []\r\n l.append(name)\r\n l.append(m[i][2])\r\n l.append(m[i][3])\r\n l.append(m[i][4])\r\n l.append(m[i][5])\r\n t.append(l)\r\n t = np.array(t)\r\n df = pd.DataFrame(t, columns=params_cast_movies)\r\n n1 = None\r\n return df.to_dict('rows')\r\n elif int(n1) < int(n2):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n first = in2.split(\" \")[0]\r\n try:\r\n last = in2.split(\" \")[1]\r\n except:\r\n last = None\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT M.m_name, M.m_duration, M.m_release_date, M.m_storyline FROM movies_actors MA LEFT JOIN movie M ON MA.m_ID = M.m_ID LEFT JOIN cast_member CM ON MA.cm_ID = CM.cm_ID WHERE CM.cm_first_name='%s'\" % first + \" AND CM.cm_last_name='%s'\" % last)\r\n m = cursor.fetchall()\r\n t = []\r\n for i in range(len(m)):\r\n l = []\r\n l.append(in2)\r\n l.append(m[i][0])\r\n l.append(m[i][1])\r\n l.append(m[i][2])\r\n l.append(m[i][3])\r\n t.append(l)\r\n t = np.array(t)\r\n df = pd.DataFrame(t, columns=params_cast_movies)\r\n n2 = None\r\n return df.to_dict('rows')\r\n else:\r\n raise PreventUpdate\r\n\r\[email protected](\r\n Output('out_trial', 'children'),\r\n [Input('register', component_property='n_clicks')],\r\n state=[State('user_username', 'value'),\r\n State('user_email_address', 'value'),\r\n State('gender-dropdown', 'value'),\r\n State('user_birthdate', 'date')])\r\ndef sign_up(n_clicks, v1, v2, v3, v4):\r\n if n_clicks is None:\r\n raise PreventUpdate\r\n else:\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n print(\"Connected\")\r\n cursor = db_connection.cursor()\r\n sql = \"INSERT INTO user (email_address, username, gender, birthdate) VALUES (%s, %s, %s, %s)\"\r\n val = (v2, v1, v3, v4)\r\n cursor.execute(sql, val)\r\n db_connection.commit()\r\n return \"Registration Successful!\"\r\n\r\[email protected](\r\n Output('out_trial_1', 'children'),\r\n [Input(component_id='add-review-movie-by-id', component_property='n_clicks_timestamp'),\r\n Input(component_id='add-review-movie-by-name', component_property='n_clicks_timestamp')],\r\n state=[State('add_review_email_address', 'value'),\r\n State('add_review_review', 'value'),\r\n State('add_review_movie_id', 'value'),\r\n State('add_review_movie_name', 'value')])\r\ndef add_review(n1, n2, v1, v2, v3, v4):\r\n if int(n1) > int(n2):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n print(\"Connected\")\r\n cursor = db_connection.cursor()\r\n sql = \"INSERT INTO review (user_email_address, m_ID, textual_review) VALUES (%s, %s, %s)\"\r\n val = (v1, v3, v2)\r\n cursor.execute(sql, val)\r\n db_connection.commit()\r\n return \"Review added.\"\r\n elif int(n1) < int(n2):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n print(\"Connected\")\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT m_ID from movie where m_name='%s'\" % v4)\r\n m = cursor.fetchall()\r\n sql = \"INSERT INTO review (user_email_address, m_ID, textual_review) VALUES (%s, %s, %s)\"\r\n val = (v1, m[0][0], v2)\r\n cursor.execute(sql, val)\r\n db_connection.commit()\r\n return \"Review added.\"\r\n else:\r\n raise PreventUpdate\r\n\r\[email protected](\r\n Output('movies-reviews-table', 'data'),\r\n [Input(component_id='find-review-movie-by-id', component_property='n_clicks_timestamp'),\r\n Input(component_id='find-review-movie-by-name', component_property='n_clicks_timestamp')],\r\n state=[State('find_review_movie_id', 'value'),\r\n State('find_review_movie_name', 'value')])\r\ndef check_review(n1, n2, v1, v2):\r\n if int(n1) > int(n2):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n print(\"Connected\")\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT m_name FROM movie WHERE m_ID='%s'\" % v1)\r\n name = cursor.fetchall()\r\n cursor.execute(\"SELECT user_email_address, textual_review FROM review WHERE review.m_ID='%s'\" % v1)\r\n m = cursor.fetchall()\r\n t = []\r\n for i in range(len(m)):\r\n l = []\r\n l.append(name)\r\n l.append(m[i][0])\r\n l.append(m[i][1])\r\n t.append(l)\r\n t = np.array(t)\r\n df = pd.DataFrame(t, columns=params_movies_reviews)\r\n n1 = None\r\n return df.to_dict('rows')\r\n elif int(n1) < int(n2):\r\n try:\r\n db_connection = MySQLdb.connect(\"sql11.freemysqlhosting.net\", \"sql11410479\", \"cSMqvaXALm\", \"sql11410479\", charset = \"utf8\")\r\n except:\r\n print(\"Can't connect to database\")\r\n return 0\r\n print(\"Connected\")\r\n cursor = db_connection.cursor()\r\n cursor.execute(\"SELECT m_ID from movie where m_name='%s'\" % v2)\r\n m = cursor.fetchall()\r\n cursor.execute(\"SELECT user_email_address, textual_review FROM review WHERE review.m_ID='%s'\" % m[0][0])\r\n m = cursor.fetchall()\r\n t = []\r\n for i in range(len(m)):\r\n l = []\r\n l.append(v2)\r\n l.append(m[i][0])\r\n l.append(m[i][1])\r\n t.append(l)\r\n t = np.array(t)\r\n df = pd.DataFrame(t, columns=params_movies_reviews)\r\n n2 = None\r\n return df.to_dict('rows')\r\n else:\r\n raise PreventUpdate\r\n\r\ndef open_browser():\r\n webbrowser.open_new('http://127.0.0.1:8050/')\r\n\r\nif __name__ == '__main__':\r\n Timer(1, open_browser).start()\r\n app.run_server()\r\n"
]
| [
[
"numpy.array",
"pandas.DataFrame"
]
]
|
OCopping/tiled | [
"6dd1e5f7ad495b004fa4b8053fc613232bcc8731"
]
| [
"tiled/server/core.py"
]
| [
"import base64\nimport collections.abc\nimport dataclasses\nimport itertools\nimport math\nimport operator\nimport re\nimport sys\nimport uuid\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\nfrom hashlib import md5\nfrom typing import Any\n\nimport dateutil.tz\nimport jmespath\nimport msgpack\nimport orjson\nfrom fastapi import HTTPException, Response\nfrom starlette.responses import JSONResponse, Send, StreamingResponse\n\n# Some are not directly used, but they register things on import.\nfrom .. import queries\nfrom ..adapters.mapping import MapAdapter\nfrom ..queries import KeyLookup, QueryValueError\nfrom ..structures import node # noqa: F401\nfrom ..structures.dataframe import serialize_arrow\nfrom ..utils import (\n APACHE_ARROW_FILE_MIME_TYPE,\n SerializationError,\n UnsupportedShape,\n modules_available,\n)\nfrom . import schemas\nfrom .etag import tokenize\nfrom .utils import record_timing\n\ndel queries\nif modules_available(\"numpy\", \"dask.array\"):\n from ..structures import array as _array # noqa: F401\n\n del _array\nif modules_available(\"pandas\", \"pyarrow\", \"dask.dataframe\"):\n from ..structures import dataframe as _dataframe # noqa: F401\n\n del _dataframe\nif modules_available(\"xarray\"):\n from ..structures import xarray as _xarray # noqa: F401\n\n del _xarray\n\n\n_FILTER_PARAM_PATTERN = re.compile(r\"filter___(?P<name>.*)___(?P<field>[^\\d\\W][\\w\\d]+)\")\n_LOCAL_TZINFO = dateutil.tz.gettz()\n\n\ndef len_or_approx(tree):\n \"\"\"\n Prefer approximate length if implemented. (It's cheaper.)\n \"\"\"\n try:\n return operator.length_hint(tree)\n except TypeError:\n return len(tree)\n\n\ndef pagination_links(route, path_parts, offset, limit, length_hint):\n path_str = \"/\".join(path_parts)\n links = {\n \"self\": f\"{route}/{path_str}?page[offset]={offset}&page[limit]={limit}\",\n # These are conditionally overwritten below.\n \"first\": None,\n \"last\": None,\n \"next\": None,\n \"prev\": None,\n }\n if limit:\n last_page = math.floor(length_hint / limit) * limit\n links.update(\n {\n \"first\": f\"{route}/{path_str}?page[offset]={0}&page[limit]={limit}\",\n \"last\": f\"{route}/{path_str}?page[offset]={last_page}&page[limit]={limit}\",\n }\n )\n if offset + limit < length_hint:\n links[\n \"next\"\n ] = f\"{route}/{path_str}?page[offset]={offset + limit}&page[limit]={limit}\"\n if offset > 0:\n links[\n \"prev\"\n ] = f\"{route}/{path_str}?page[offset]={max(0, offset - limit)}&page[limit]={limit}\"\n return links\n\n\ndef construct_entries_response(\n query_registry,\n tree,\n route,\n path,\n offset,\n limit,\n fields,\n select_metadata,\n omit_links,\n filters,\n sort,\n base_url,\n media_type,\n):\n path_parts = [segment for segment in path.split(\"/\") if segment]\n if tree.structure_family != \"node\":\n raise WrongTypeForRoute(\"This is not a Node; it does not have entries.\")\n queries = defaultdict(\n dict\n ) # e.g. {\"text\": {\"text\": \"dog\"}, \"lookup\": {\"key\": \"...\"}}\n # Group the parameters by query type.\n for key, value in filters.items():\n if value is None:\n continue\n name, field = _FILTER_PARAM_PATTERN.match(key).groups()\n queries[name][field] = value\n sorting = []\n if sort is not None:\n for item in sort.split(\",\"):\n if item:\n if item.startswith(\"-\"):\n sorting.append((item[1:], -1))\n else:\n sorting.append((item, 1))\n if sorting:\n if not hasattr(tree, \"sort\"):\n raise HTTPException(\n status_code=400, detail=\"This Tree does not support sorting.\"\n )\n tree = tree.sort(sorting)\n # Apply the queries and obtain a narrowed tree.\n key_lookups = []\n for query_name, parameters_dict_of_lists in queries.items():\n for i in itertools.count(0):\n try:\n parameters = {\n field_name: parameters_list[i]\n for field_name, parameters_list in parameters_dict_of_lists.items()\n }\n except IndexError:\n break\n query_class = query_registry.name_to_query_type[query_name]\n # Special case:\n # List fields are serialized as comma-separated strings.\n for field in dataclasses.fields(query_class):\n if getattr(field.type, \"__origin__\", None) is list:\n (inner_type,) = field.type.__args__\n parameters[field.name] = [\n inner_type(item) for item in parameters[field.name].split(\",\")\n ]\n try:\n query = query_class(**parameters)\n # Special case: Do key-lookups at the end after all other filtering.\n # We do not require trees to implement this query; we implement it\n # directly here by just calling __getitem__.\n if isinstance(query, KeyLookup):\n key_lookups.append(query.key)\n continue\n tree = tree.search(query)\n except QueryValueError as err:\n raise HTTPException(status_code=400, detail=err.args[0])\n if key_lookups:\n # Duplicates are technically legal because *any* query can be given\n # with multiple parameters.\n unique_key_lookups = set(key_lookups)\n (key_lookup), *others = unique_key_lookups\n if others:\n # Two non-equal KeyLookup queries must return no results.\n tree = MapAdapter({})\n else:\n try:\n tree = MapAdapter({key_lookup: tree[key_lookup]}, must_revalidate=False)\n except KeyError:\n tree = MapAdapter({})\n count = len_or_approx(tree)\n links = pagination_links(route, path_parts, offset, limit, count)\n data = []\n if fields != [schemas.EntryFields.none]:\n # Pull a page of items into memory.\n items = tree.items_indexer[offset : offset + limit] # noqa: E203\n else:\n # Pull a page of just the keys, which is cheaper.\n items = (\n (key, None)\n for key in tree.keys_indexer[offset : offset + limit] # noqa: E203\n )\n # This value will not leak out. It just used to seed comparisons.\n metadata_stale_at = datetime.utcnow() + timedelta(days=1_000_000)\n must_revalidate = getattr(tree, \"must_revalidate\", True)\n for key, entry in items:\n resource = construct_resource(\n base_url,\n path_parts + [key],\n entry,\n fields,\n select_metadata,\n omit_links,\n media_type,\n )\n data.append(resource)\n # If any entry has emtry.metadata_stale_at = None, then there will\n # be no 'Expires' header. We will pessimistically assume the values\n # are immediately stale.\n if metadata_stale_at is not None:\n if getattr(entry, \"metadata_stale_at\", None) is None:\n metadata_stale_at = None\n else:\n metadata_stale_at = min(metadata_stale_at, entry.metadata_stale_at)\n return (\n schemas.Response(data=data, links=links, meta={\"count\": count}),\n metadata_stale_at,\n must_revalidate,\n )\n\n\nDEFAULT_MEDIA_TYPES = {\n \"array\": \"application/octet-stream\",\n \"dataframe\": APACHE_ARROW_FILE_MIME_TYPE,\n \"node\": \"application/x-hdf5\",\n \"xarray_data_array\": \"application/octet-stream\",\n \"xarray_dataset\": \"application/netcdf\",\n}\n\n\ndef construct_data_response(\n structure_family,\n serialization_registry,\n payload,\n metadata,\n request,\n format=None,\n specs=None,\n expires=None,\n):\n request.state.endpoint = \"data\"\n if specs is None:\n specs = []\n default_media_type = DEFAULT_MEDIA_TYPES[structure_family]\n # Give priority to the `format` query parameter. Otherwise, consult Accept\n # header.\n if format is not None:\n media_types_or_aliases = format.split(\",\")\n # Resolve aliases, like \"csv\" -> \"text/csv\".\n media_types = [\n serialization_registry.resolve_alias(t) for t in media_types_or_aliases\n ]\n else:\n # The HTTP spec says these should be separated by \", \" but some\n # browsers separate with just \",\" (no space).\n # https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation/List_of_default_Accept_values#default_values # noqa\n # That variation is what we are handling below with lstrip.\n media_types = [\n s.lstrip(\" \")\n for s in request.headers.get(\"Accept\", default_media_type).split(\",\")\n ]\n\n # The client may give us a choice of media types. Find the first one\n # that we support.\n supported = set()\n for media_type in media_types:\n if media_type == \"*/*\":\n media_type = default_media_type\n # fall back to generic dataframe serializer if no specs present\n for spec in specs + [structure_family]:\n media_types_for_spec = serialization_registry.media_types(spec)\n if media_type in media_types_for_spec:\n break\n supported.update(media_types_for_spec)\n else:\n # None of the specs or the structure_family can serialize to this\n # media_type. Try the next one.\n continue\n # We found a match above. We have our media_type.\n break\n else:\n # We have checked each of the media_types, and we cannot serialize\n # to any of them.\n raise UnsupportedMediaTypes(\n f\"None of the media types requested by the client are supported. \"\n f\"Supported: {', '.join(supported)}. Requested: {', '.join(media_types)}.\",\n )\n with record_timing(request.state.metrics, \"tok\"):\n # Create an ETag that uniquely identifies this content and the media\n # type that it will be encoded as.\n etag = tokenize((payload, media_type))\n headers = {\"ETag\": etag}\n if expires is not None:\n headers[\"Expires\"] = expires.strftime(HTTP_EXPIRES_HEADER_FORMAT)\n if request.headers.get(\"If-None-Match\", \"\") == etag:\n # If the client already has this content, confirm that.\n return Response(status_code=304, headers=headers)\n # This is the expensive step: actually serialize.\n try:\n content = serialization_registry(\n structure_family, media_type, payload, metadata\n )\n except UnsupportedShape as err:\n raise UnsupportedMediaTypes(\n f\"The shape of this data {err.args[0]} is incompatible with the requested format ({media_type}). \"\n f\"Slice it or choose a different format.\",\n )\n except SerializationError as err:\n raise UnsupportedMediaTypes(\n f\"This type is supported in general but there was an error packing this specific data: {err.args}\",\n )\n return PatchedResponse(\n content=content,\n media_type=media_type,\n headers=headers,\n )\n\n\ndef construct_resource(\n base_url,\n path_parts,\n entry,\n fields,\n select_metadata,\n omit_links,\n media_type,\n):\n path_str = \"/\".join(path_parts)\n attributes = {}\n if schemas.EntryFields.metadata in fields:\n if select_metadata is not None:\n attributes[\"metadata\"] = jmespath.compile(select_metadata).search(\n entry.metadata\n )\n else:\n attributes[\"metadata\"] = entry.metadata\n if schemas.EntryFields.specs in fields:\n attributes[\"specs\"] = getattr(entry, \"specs\", None)\n if (entry is not None) and entry.structure_family == \"node\":\n attributes[\"structure_family\"] = \"node\"\n if schemas.EntryFields.count in fields:\n attributes[\"count\"] = len_or_approx(entry)\n if hasattr(entry, \"sorting\"):\n # In the Python API we encode sorting as (key, direction).\n # This order-based \"record\" notion does not play well with OpenAPI.\n # In the HTTP API, therefore, we use {\"key\": key, \"direction\": direction}.\n attributes[\"sorting\"] = [\n {\"key\": key, \"direction\": direction}\n for key, direction in entry.sorting\n ]\n d = {\n \"id\": path_parts[-1] if path_parts else \"\",\n \"attributes\": schemas.NodeAttributes(**attributes),\n }\n if not omit_links:\n d[\"links\"] = {\n \"self\": f\"{base_url}node/metadata/{path_str}\",\n \"search\": f\"{base_url}node/search/{path_str}\",\n \"full\": f\"{base_url}node/full/{path_str}\",\n }\n resource = schemas.Resource[\n schemas.NodeAttributes, schemas.NodeLinks, schemas.NodeMeta\n ](**d)\n else:\n links = {\"self\": f\"{base_url}node/metadata/{path_str}\"}\n structure = {}\n if entry is not None:\n # entry is None when we are pulling just *keys* from the\n # Tree and not values.\n ResourceLinksT = schemas.resource_links_type_by_structure_family[\n entry.structure_family\n ]\n links.update(\n {\n link: template.format(base_url=base_url, path=path_str)\n for link, template in FULL_LINKS[entry.structure_family].items()\n }\n )\n if schemas.EntryFields.structure_family in fields:\n attributes[\"structure_family\"] = entry.structure_family\n if schemas.EntryFields.macrostructure in fields:\n macrostructure = entry.macrostructure()\n if macrostructure is not None:\n structure[\"macro\"] = dataclasses.asdict(macrostructure)\n if schemas.EntryFields.microstructure in fields:\n if entry.structure_family == \"node\":\n assert False # not sure if this ever happens\n pass\n elif entry.structure_family == \"dataframe\":\n import pandas\n\n microstructure = entry.microstructure()\n arrow_encoded_meta = bytes(serialize_arrow(microstructure.meta, {}))\n divisions_wrapped_in_df = pandas.DataFrame(\n {\"divisions\": list(microstructure.divisions)}\n )\n arrow_encoded_divisions = bytes(\n serialize_arrow(divisions_wrapped_in_df, {})\n )\n if media_type == \"application/json\":\n # For JSON, base64-encode the binary Arrow-encoded data,\n # and indicate that this has been done in the data URI.\n data_uri = f\"data:{APACHE_ARROW_FILE_MIME_TYPE};base64,\"\n arrow_encoded_meta = (\n data_uri + base64.b64encode(arrow_encoded_meta).decode()\n )\n arrow_encoded_divisions = (\n data_uri\n + base64.b64encode(arrow_encoded_divisions).decode()\n )\n else:\n # In msgpack, we can encode the binary Arrow-encoded data directly.\n assert media_type == \"application/x-msgpack\"\n structure[\"micro\"] = {\n \"meta\": arrow_encoded_meta,\n \"divisions\": arrow_encoded_divisions,\n }\n else:\n microstructure = entry.microstructure()\n if microstructure is not None:\n structure[\"micro\"] = dataclasses.asdict(microstructure)\n if entry.structure_family == \"array\":\n block_template = \",\".join(\n f\"{{index_{index}}}\"\n for index in range(len(structure[\"macro\"][\"shape\"]))\n )\n links[\n \"block\"\n ] = f\"{base_url}array/block/{path_str}?block={block_template}\"\n elif entry.structure_family == \"dataframe\":\n links[\n \"partition\"\n ] = f\"{base_url}dataframe/partition/{path_str}?partition={{index}}\"\n attributes[\"structure\"] = structure\n else:\n # We only have entry names, not structure_family, so\n ResourceLinksT = schemas.SelfLinkOnly\n d = {\n \"id\": path_parts[-1],\n \"attributes\": schemas.NodeAttributes(**attributes),\n }\n if not omit_links:\n d[\"links\"] = links\n resource = schemas.Resource[\n schemas.NodeAttributes, ResourceLinksT, schemas.EmptyDict\n ](**d)\n return resource\n\n\nclass PatchedResponse(Response):\n \"Patch the render method to accept memoryview.\"\n\n def render(self, content: Any) -> bytes:\n if isinstance(content, memoryview):\n return content.cast(\"B\")\n return super().render(content)\n\n\nclass PatchedStreamingResponse(StreamingResponse):\n \"Patch the stream_response method to accept memoryview.\"\n\n async def stream_response(self, send: Send) -> None:\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": self.status_code,\n \"headers\": self.raw_headers,\n }\n )\n async for chunk in self.body_iterator:\n # BEGIN ALTERATION\n if not isinstance(chunk, (bytes, memoryview)):\n # END ALTERATION\n chunk = chunk.encode(self.charset)\n await send({\"type\": \"http.response.body\", \"body\": chunk, \"more_body\": True})\n\n await send({\"type\": \"http.response.body\", \"body\": b\"\", \"more_body\": False})\n\n\nclass NumpySafeJSONResponse(JSONResponse):\n def __init__(self, *args, metrics, **kwargs):\n self.__metrics = metrics\n super().__init__(*args, **kwargs)\n\n def render(self, content: Any) -> bytes:\n with record_timing(self.__metrics, \"pack\"):\n return orjson.dumps(content, option=orjson.OPT_SERIALIZE_NUMPY)\n\n\ndef _fallback_msgpack_encoder(obj):\n # If numpy has not been imported yet, then we can be sure that obj\n # is not a numpy object, and we want to avoid triggering a numpy\n # import. (The server does not have a hard numpy dependency.)\n if \"numpy\" in sys.modules:\n import numpy\n\n if isinstance(obj, (numpy.generic, numpy.ndarray)):\n if numpy.isscalar(obj):\n return obj.item()\n return obj.tolist()\n if isinstance(obj, uuid.UUID):\n return str(obj) # hyphen-separated hex per RFC4122\n return obj\n\n\ndef _patch_naive_datetimes(obj):\n \"\"\"\n If a naive datetime is found, attach local time.\n\n Msgpack can only serialize datetimes with tzinfo.\n \"\"\"\n if hasattr(obj, \"items\"):\n patched_obj = {}\n for k, v in obj.items():\n patched_obj[k] = _patch_naive_datetimes(v)\n elif (not isinstance(obj, str)) and isinstance(obj, collections.abc.Iterable):\n patched_obj = []\n for item in obj:\n patched_obj.append(_patch_naive_datetimes(item))\n elif isinstance(obj, datetime) and obj.tzinfo is None:\n patched_obj = obj.astimezone(_LOCAL_TZINFO)\n else:\n patched_obj = obj\n return patched_obj\n\n\nclass MsgpackResponse(Response):\n media_type = \"application/x-msgpack\"\n\n def __init__(self, *args, metrics, **kwargs):\n self.__metrics = metrics\n super().__init__(*args, **kwargs)\n\n def render(self, content: Any, _reentered=False) -> bytes:\n try:\n with record_timing(self.__metrics, \"pack\"):\n return msgpack.packb(\n content, default=_fallback_msgpack_encoder, datetime=True\n )\n except (ValueError, TypeError) as err:\n # msgpack tries to handle all datetimes, but if it\n # received a naive one (tzinfo=None) then it fails.\n # We cannot use the default hook to handle this because\n # it is not called.\n if \"can not serialize 'datetime.datetime' object\" in str(err) and (\n not _reentered\n ):\n patched_content = _patch_naive_datetimes(content)\n return self.render(patched_content, _reentered=True)\n raise\n\n\nJSON_MIME_TYPE = \"application/json\"\nMSGPACK_MIME_TYPE = \"application/x-msgpack\"\n# This is a silly time format, but it is the HTTP standard.\nHTTP_EXPIRES_HEADER_FORMAT = \"%a, %d %b %Y %H:%M:%S GMT\"\n\n\ndef resolve_media_type(request):\n media_types = request.headers.get(\"Accept\", JSON_MIME_TYPE).split(\", \")\n for media_type in media_types:\n if media_type == \"*/*\":\n media_type = JSON_MIME_TYPE\n break\n if media_type == MSGPACK_MIME_TYPE:\n break\n if media_type == JSON_MIME_TYPE:\n break\n else:\n # It is commmon in HTTP to fall back on a default representation if\n # none of the requested ones are available. We do not do this for\n # data payloads, but it makes some sense to do it for these metadata\n # messages.\n media_type = JSON_MIME_TYPE\n assert media_type in {JSON_MIME_TYPE, MSGPACK_MIME_TYPE}\n return media_type\n\n\ndef json_or_msgpack(request, content, expires=None, headers=None):\n media_type = resolve_media_type(request)\n content_as_dict = content.dict()\n with record_timing(request.state.metrics, \"tok\"):\n etag = md5(str(content_as_dict).encode()).hexdigest()\n headers = headers or {}\n headers[\"ETag\"] = etag\n if expires is not None:\n headers[\"Expires\"] = expires.strftime(HTTP_EXPIRES_HEADER_FORMAT)\n if request.headers.get(\"If-None-Match\", \"\") == etag:\n # If the client already has this content, confirm that.\n return Response(status_code=304, headers=headers)\n if media_type == \"application/x-msgpack\":\n return MsgpackResponse(\n content_as_dict, headers=headers, metrics=request.state.metrics\n )\n return NumpySafeJSONResponse(\n content_as_dict, headers=headers, metrics=request.state.metrics\n )\n\n\nclass UnsupportedMediaTypes(Exception):\n pass\n\n\nclass NoEntry(KeyError):\n pass\n\n\nclass WrongTypeForRoute(Exception):\n pass\n\n\nFULL_LINKS = {\n \"node\": {\"full\": \"{base_url}node/full/{path}\"},\n \"array\": {\"full\": \"{base_url}array/full/{path}\"},\n \"dataframe\": {\"full\": \"{base_url}node/full/{path}\"},\n \"xarray_data_array\": {\n \"full_variable\": \"{base_url}array/full/{path}/variable\",\n },\n \"xarray_dataset\": {\n \"full_variable\": \"{base_url}array/full/{path}/data_vars/{{variable}}/variable\",\n \"full_coord\": \"{base_url}array/full/{path}/coords/{{coord}}/variable\",\n \"full_dataset\": \"{base_url}node/full/{path}\",\n },\n}\n"
]
| [
[
"numpy.isscalar"
]
]
|
MBtech/rethinking-serverless | [
"973bfdc174ed639900fd1a3eaeefbafe5a3b48aa"
]
| [
"benchmarks/linpack/linpack/handler.py"
]
| [
"from numpy import matrix, array, linalg, random, amax, asscalar\nfrom time import time\n\ndef linpack(N):\n # eps=2.22e-16\n\n # ops=(2.0*N)*N*N/3.0+(2.0*N)*N\n\n # Create AxA array of random numbers -0.5 to 0.5\n A=random.random_sample((N,N))-0.5\n B=A.sum(axis=1)\n\n # Convert to matrices\n A=matrix(A)\n\n B=matrix(B.reshape((N,1)))\n # na=amax(abs(A.A))\n\n\n start = time()\n X=linalg.solve(A,B)\n latency = time() - start\n\n # mflops = (ops*1e-6/latency)\n\n result = {\n # 'mflops': mflops,\n 'latency': latency\n }\n\n return result\n\n\ndef handle(request):\n # request_json = request.get_json(silent=True)\n # N = request_json['N']\n N = int(request)\n result = linpack(N)\n # print(result)\n # return \"{latency : \" + str(result['latency']) + \", mflops : \" + str(result['mflops']) + \"}\"\n return result['latency']"
]
| [
[
"numpy.matrix",
"numpy.linalg.solve",
"numpy.random.random_sample"
]
]
|
ErmakovD/ClickHouse | [
"532cd4beaa6f2ec5c70c6f80f90c2ac34066bdab"
]
| [
"docker/test/performance-comparison/perf.py"
]
| [
"#!/usr/bin/python3\n\nimport argparse\nimport clickhouse_driver\nimport itertools\nimport functools\nimport math\nimport os\nimport pprint\nimport random\nimport re\nimport statistics\nimport string\nimport sys\nimport time\nimport traceback\nimport logging\nimport xml.etree.ElementTree as et\nfrom threading import Thread\nfrom scipy import stats\n\nlogging.basicConfig(format='%(asctime)s: %(levelname)s: %(module)s: %(message)s', level='WARNING')\n\ntotal_start_seconds = time.perf_counter()\nstage_start_seconds = total_start_seconds\n\ndef reportStageEnd(stage):\n global stage_start_seconds, total_start_seconds\n\n current = time.perf_counter()\n print(f'stage\\t{stage}\\t{current - stage_start_seconds:.3f}\\t{current - total_start_seconds:.3f}')\n stage_start_seconds = current\n\n\ndef tsv_escape(s):\n return s.replace('\\\\', '\\\\\\\\').replace('\\t', '\\\\t').replace('\\n', '\\\\n').replace('\\r','')\n\n\nparser = argparse.ArgumentParser(description='Run performance test.')\n# Explicitly decode files as UTF-8 because sometimes we have Russian characters in queries, and LANG=C is set.\nparser.add_argument('file', metavar='FILE', type=argparse.FileType('r', encoding='utf-8'), nargs=1, help='test description file')\nparser.add_argument('--host', nargs='*', default=['localhost'], help=\"Space-separated list of server hostname(s). Corresponds to '--port' options.\")\nparser.add_argument('--port', nargs='*', default=[9000], help=\"Space-separated list of server port(s). Corresponds to '--host' options.\")\nparser.add_argument('--runs', type=int, default=1, help='Number of query runs per server.')\nparser.add_argument('--max-queries', type=int, default=None, help='Test no more than this number of queries, chosen at random.')\nparser.add_argument('--queries-to-run', nargs='*', type=int, default=None, help='Space-separated list of indexes of queries to test.')\nparser.add_argument('--profile-seconds', type=int, default=0, help='For how many seconds to profile a query for which the performance has changed.')\nparser.add_argument('--long', action='store_true', help='Do not skip the tests tagged as long.')\nparser.add_argument('--print-queries', action='store_true', help='Print test queries and exit.')\nparser.add_argument('--print-settings', action='store_true', help='Print test settings and exit.')\nparser.add_argument('--keep-created-tables', action='store_true', help=\"Don't drop the created tables after the test.\")\nparser.add_argument('--use-existing-tables', action='store_true', help=\"Don't create or drop the tables, use the existing ones instead.\")\nargs = parser.parse_args()\n\nreportStageEnd('start')\n\ntest_name = os.path.splitext(os.path.basename(args.file[0].name))[0]\n\ntree = et.parse(args.file[0])\nroot = tree.getroot()\n\nreportStageEnd('parse')\n\n# Process query parameters\nsubst_elems = root.findall('substitutions/substitution')\navailable_parameters = {} # { 'table': ['hits_10m', 'hits_100m'], ... }\nfor e in subst_elems:\n available_parameters[e.find('name').text] = [v.text for v in e.findall('values/value')]\n\n# Takes parallel lists of templates, substitutes them with all combos of\n# parameters. The set of parameters is determined based on the first list.\n# Note: keep the order of queries -- sometimes we have DROP IF EXISTS\n# followed by CREATE in create queries section, so the order matters.\ndef substitute_parameters(query_templates, other_templates = []):\n query_results = []\n other_results = [[]] * (len(other_templates))\n for i, q in enumerate(query_templates):\n keys = set(n for _, n, _, _ in string.Formatter().parse(q) if n)\n values = [available_parameters[k] for k in keys]\n combos = itertools.product(*values)\n for c in combos:\n with_keys = dict(zip(keys, c))\n query_results.append(q.format(**with_keys))\n for j, t in enumerate(other_templates):\n other_results[j].append(t[i].format(**with_keys))\n if len(other_templates):\n return query_results, other_results\n else:\n return query_results\n\n\n# Build a list of test queries, substituting parameters to query templates,\n# and reporting the queries marked as short.\ntest_queries = []\nis_short = []\nfor e in root.findall('query'):\n new_queries, [new_is_short] = substitute_parameters([e.text], [[e.attrib.get('short', '0')]])\n test_queries += new_queries\n is_short += [eval(s) for s in new_is_short]\n\nassert(len(test_queries) == len(is_short))\n\n# If we're given a list of queries to run, check that it makes sense.\nfor i in args.queries_to_run or []:\n if i < 0 or i >= len(test_queries):\n print(f'There is no query no. {i} in this test, only [{0}-{len(test_queries) - 1}] are present')\n exit(1)\n\n# If we're only asked to print the queries, do that and exit.\nif args.print_queries:\n for i in args.queries_to_run or range(0, len(test_queries)):\n print(test_queries[i])\n exit(0)\n\n# Print short queries\nfor i, s in enumerate(is_short):\n if s:\n print(f'short\\t{i}')\n\n# If we're only asked to print the settings, do that and exit. These are settings\n# for clickhouse-benchmark, so we print them as command line arguments, e.g.\n# '--max_memory_usage=10000000'.\nif args.print_settings:\n for s in root.findall('settings/*'):\n print(f'--{s.tag}={s.text}')\n\n exit(0)\n\n# Skip long tests\nif not args.long:\n for tag in root.findall('.//tag'):\n if tag.text == 'long':\n print('skipped\\tTest is tagged as long.')\n sys.exit(0)\n\n# Print report threshold for the test if it is set.\nignored_relative_change = 0.05\nif 'max_ignored_relative_change' in root.attrib:\n ignored_relative_change = float(root.attrib[\"max_ignored_relative_change\"])\n print(f'report-threshold\\t{ignored_relative_change}')\n\nreportStageEnd('before-connect')\n\n# Open connections\nservers = [{'host': host or args.host[0], 'port': port or args.port[0]} for (host, port) in itertools.zip_longest(args.host, args.port)]\nall_connections = [clickhouse_driver.Client(**server) for server in servers]\n\nfor i, s in enumerate(servers):\n print(f'server\\t{i}\\t{s[\"host\"]}\\t{s[\"port\"]}')\n\nreportStageEnd('connect')\n\nif not args.use_existing_tables:\n # Run drop queries, ignoring errors. Do this before all other activity,\n # because clickhouse_driver disconnects on error (this is not configurable),\n # and the new connection loses the changes in settings.\n drop_query_templates = [q.text for q in root.findall('drop_query')]\n drop_queries = substitute_parameters(drop_query_templates)\n for conn_index, c in enumerate(all_connections):\n for q in drop_queries:\n try:\n c.execute(q)\n print(f'drop\\t{conn_index}\\t{c.last_query.elapsed}\\t{tsv_escape(q)}')\n except:\n pass\n\n reportStageEnd('drop-1')\n\n# Apply settings.\n# If there are errors, report them and continue -- maybe a new test uses a setting\n# that is not in master, but the queries can still run. If we have multiple\n# settings and one of them throws an exception, all previous settings for this\n# connection will be reset, because the driver reconnects on error (not\n# configurable). So the end result is uncertain, but hopefully we'll be able to\n# run at least some queries.\nsettings = root.findall('settings/*')\nfor conn_index, c in enumerate(all_connections):\n for s in settings:\n # requires clickhouse-driver >= 1.1.5 to accept arbitrary new settings\n # (https://github.com/mymarilyn/clickhouse-driver/pull/142)\n c.settings[s.tag] = s.text\n\nreportStageEnd('settings')\n\n# Check tables that should exist. If they don't exist, just skip this test.\ntables = [e.text for e in root.findall('preconditions/table_exists')]\nfor t in tables:\n for c in all_connections:\n try:\n res = c.execute(\"select 1 from {} limit 1\".format(t))\n except:\n exception_message = traceback.format_exception_only(*sys.exc_info()[:2])[-1]\n skipped_message = ' '.join(exception_message.split('\\n')[:2])\n print(f'skipped\\t{tsv_escape(skipped_message)}')\n sys.exit(0)\n\nreportStageEnd('preconditions')\n\nif not args.use_existing_tables:\n # Run create and fill queries. We will run them simultaneously for both\n # servers, to save time. The weird XML search + filter is because we want to\n # keep the relative order of elements, and etree doesn't support the\n # appropriate xpath query.\n create_query_templates = [q.text for q in root.findall('./*')\n if q.tag in ('create_query', 'fill_query')]\n create_queries = substitute_parameters(create_query_templates)\n\n # Disallow temporary tables, because the clickhouse_driver reconnects on\n # errors, and temporary tables are destroyed. We want to be able to continue\n # after some errors.\n for q in create_queries:\n if re.search('create temporary table', q, flags=re.IGNORECASE):\n print(f\"Temporary tables are not allowed in performance tests: '{q}'\",\n file = sys.stderr)\n sys.exit(1)\n\n def do_create(connection, index, queries):\n for q in queries:\n connection.execute(q)\n print(f'create\\t{index}\\t{connection.last_query.elapsed}\\t{tsv_escape(q)}')\n\n threads = [\n Thread(target = do_create, args = (connection, index, create_queries))\n for index, connection in enumerate(all_connections)]\n\n for t in threads:\n t.start()\n\n for t in threads:\n t.join()\n\n reportStageEnd('create')\n\n# By default, test all queries.\nqueries_to_run = range(0, len(test_queries))\n\nif args.max_queries:\n # If specified, test a limited number of queries chosen at random.\n queries_to_run = random.sample(range(0, len(test_queries)), min(len(test_queries), args.max_queries))\n\nif args.queries_to_run:\n # Run the specified queries.\n queries_to_run = args.queries_to_run\n\n# Run test queries.\nprofile_total_seconds = 0\nfor query_index in queries_to_run:\n q = test_queries[query_index]\n query_prefix = f'{test_name}.query{query_index}'\n\n # We have some crazy long queries (about 100kB), so trim them to a sane\n # length. This means we can't use query text as an identifier and have to\n # use the test name + the test-wide query index.\n query_display_name = q\n if len(query_display_name) > 1000:\n query_display_name = f'{query_display_name[:1000]}...({query_index})'\n\n print(f'display-name\\t{query_index}\\t{tsv_escape(query_display_name)}')\n\n # Prewarm: run once on both servers. Helps to bring the data into memory,\n # precompile the queries, etc.\n # A query might not run on the old server if it uses a function added in the\n # new one. We want to run them on the new server only, so that the PR author\n # can ensure that the test works properly. Remember the errors we had on\n # each server.\n query_error_on_connection = [None] * len(all_connections);\n for conn_index, c in enumerate(all_connections):\n try:\n prewarm_id = f'{query_prefix}.prewarm0'\n # Will also detect too long queries during warmup stage\n res = c.execute(q, query_id = prewarm_id, settings = {'max_execution_time': 10})\n print(f'prewarm\\t{query_index}\\t{prewarm_id}\\t{conn_index}\\t{c.last_query.elapsed}')\n except KeyboardInterrupt:\n raise\n except:\n # FIXME the driver reconnects on error and we lose settings, so this\n # might lead to further errors or unexpected behavior.\n query_error_on_connection[conn_index] = traceback.format_exc();\n continue\n\n # Report all errors that ocurred during prewarm and decide what to do next.\n # If prewarm fails for the query on all servers -- skip the query and\n # continue testing the next query.\n # If prewarm fails on one of the servers, run the query on the rest of them.\n no_errors = []\n for i, e in enumerate(query_error_on_connection):\n if e:\n print(e, file = sys.stderr)\n else:\n no_errors.append(i)\n\n if len(no_errors) == 0:\n continue\n elif len(no_errors) < len(all_connections):\n print(f'partial\\t{query_index}\\t{no_errors}')\n\n this_query_connections = [all_connections[index] for index in no_errors]\n\n # Now, perform measured runs.\n # Track the time spent by the client to process this query, so that we can\n # notice the queries that take long to process on the client side, e.g. by\n # sending excessive data.\n start_seconds = time.perf_counter()\n server_seconds = 0\n profile_seconds = 0\n run = 0\n\n # Arrays of run times for each connection.\n all_server_times = []\n for conn_index, c in enumerate(this_query_connections):\n all_server_times.append([])\n\n while True:\n run_id = f'{query_prefix}.run{run}'\n\n for conn_index, c in enumerate(this_query_connections):\n try:\n res = c.execute(q, query_id = run_id)\n except Exception as e:\n # Add query id to the exception to make debugging easier.\n e.args = (run_id, *e.args)\n e.message = run_id + ': ' + e.message\n raise\n\n elapsed = c.last_query.elapsed\n all_server_times[conn_index].append(elapsed)\n\n server_seconds += elapsed\n print(f'query\\t{query_index}\\t{run_id}\\t{conn_index}\\t{elapsed}')\n\n if elapsed > 10:\n # Stop processing pathologically slow queries, to avoid timing out\n # the entire test task. This shouldn't really happen, so we don't\n # need much handling for this case and can just exit.\n print(f'The query no. {query_index} is taking too long to run ({elapsed} s)', file=sys.stderr)\n exit(2)\n\n # Be careful with the counter, after this line it's the next iteration\n # already.\n run += 1\n\n # Try to run any query for at least the specified number of times,\n # before considering other stop conditions.\n if run < args.runs:\n continue\n\n # For very short queries we have a special mode where we run them for at\n # least some time. The recommended lower bound of run time for \"normal\"\n # queries is about 0.1 s, and we run them about 10 times, giving the\n # time per query per server of about one second. Use this value as a\n # reference for \"short\" queries.\n if is_short[query_index]:\n if server_seconds >= 2 * len(this_query_connections):\n break\n # Also limit the number of runs, so that we don't go crazy processing\n # the results -- 'eqmed.sql' is really suboptimal.\n if run >= 500:\n break\n else:\n if run >= args.runs:\n break\n\n client_seconds = time.perf_counter() - start_seconds\n print(f'client-time\\t{query_index}\\t{client_seconds}\\t{server_seconds}')\n\n # Run additional profiling queries to collect profile data, but only if test times appeared to be different.\n # We have to do it after normal runs because otherwise it will affect test statistics too much\n if len(all_server_times) != 2:\n continue\n\n if len(all_server_times[0]) < 3:\n # Don't fail if for some reason there are not enough measurements.\n continue\n\n pvalue = stats.ttest_ind(all_server_times[0], all_server_times[1], equal_var = False).pvalue\n median = [statistics.median(t) for t in all_server_times]\n # Keep this consistent with the value used in report. Should eventually move\n # to (median[1] - median[0]) / min(median), which is compatible with \"times\"\n # difference we use in report (max(median) / min(median)).\n relative_diff = (median[1] - median[0]) / median[0]\n print(f'diff\\t{query_index}\\t{median[0]}\\t{median[1]}\\t{relative_diff}\\t{pvalue}')\n if abs(relative_diff) < ignored_relative_change or pvalue > 0.05:\n continue\n\n # Perform profile runs for fixed amount of time. Don't limit the number\n # of runs, because we also have short queries.\n profile_start_seconds = time.perf_counter()\n run = 0\n while time.perf_counter() - profile_start_seconds < args.profile_seconds:\n run_id = f'{query_prefix}.profile{run}'\n\n for conn_index, c in enumerate(this_query_connections):\n try:\n res = c.execute(q, query_id = run_id, settings = {'query_profiler_real_time_period_ns': 10000000})\n print(f'profile\\t{query_index}\\t{run_id}\\t{conn_index}\\t{c.last_query.elapsed}')\n except Exception as e:\n # Add query id to the exception to make debugging easier.\n e.args = (run_id, *e.args)\n e.message = run_id + ': ' + e.message\n raise\n\n run += 1\n\n profile_total_seconds += time.perf_counter() - profile_start_seconds\n\nprint(f'profile-total\\t{profile_total_seconds}')\n\nreportStageEnd('run')\n\n# Run drop queries\nif not args.keep_created_tables and not args.use_existing_tables:\n drop_queries = substitute_parameters(drop_query_templates)\n for conn_index, c in enumerate(all_connections):\n for q in drop_queries:\n c.execute(q)\n print(f'drop\\t{conn_index}\\t{c.last_query.elapsed}\\t{tsv_escape(q)}')\n\nreportStageEnd('drop-2')\n"
]
| [
[
"scipy.stats.ttest_ind"
]
]
|
bolt25/Deep_Learning_in_8_weeks | [
"de9bf4dded525ec761c02bc05703ef3c6ba5f256"
]
| [
"Week 4/RNN.py"
]
| [
"# Recurrent Neural Network from Scratch in Python 3\n\nimport copy\nimport numpy as np\n\n# np.random.seed(0)\n\n# Sigmoid Activation Function\n# To be applied at Hidden Layers and Output Layer\ndef sigmoid(z):\n return (1 / (1 + np.exp(-z)))\n\n# Derivative of Sigmoid Function\n# Used in calculation of Back Propagation Loss\ndef sigmoidPrime(z):\n return z * (1-z)\n\n\n# Generate Input Dataset\nint_to_binary = {}\nbinary_dim = 8\n\n# Calculate the largest value which can be attained\n# 2^8 = 256\nmax_val = (2**binary_dim)\n\n# Calculate Binary values for int from 0 to 256\nbinary_val = np.unpackbits(np.array([range(max_val)], dtype=np.uint8).T, axis=1)\n\n# Function to map Integer values to Binary values\nfor i in range(max_val):\n int_to_binary[i] = binary_val[i]\n # print('\\nInteger value: ',i)\n # print('binary value: ', binary_val[i])\n\n\n# NN variables\nlearning_rate = 0.1\n\n# Inputs: Values to be added bit by bit\ninputLayerSize = 2\n\n# Hidden Layer with 16 neurons\nhiddenLayerSize = 16\n\n# Output at one time step is 1 bit\noutputLayerSize = 1\n\n# Initialize Weights\n# Weight of first Synapse (Synapse_0) from Input to Hidden Layer at Current Timestep\nW1 = 2 * np.random.random((inputLayerSize, hiddenLayerSize)) - 1\n\n# Weight of second Synapse (Synapse_1) from Hidden Layer to Output Layer\nW2 = 2 * np.random.random((hiddenLayerSize, outputLayerSize)) - 1\n\n# Weight of Synapse (Synapse_h) from Current Hidden Layer to Next Hidden Layer in Timestep\nW_h = 2 * np.random.random((hiddenLayerSize, hiddenLayerSize)) - 1\n\n\n# Initialize Updated Weights Values\nW1_update = np.zeros_like(W1)\nW2_update = np.zeros_like(W2)\nW_h_update = np.zeros_like(W_h)\n\n\n# Iterate over 10,000 samples for Training\nfor j in range(10000):\n # ----------------------------- Compute True Values for the Sum (a+b) [binary encoded] --------------------------\n # Generate a random sample value for 1st input\n a_int = np.random.randint(max_val/2)\n # Convert this Int value to Binary\n a = int_to_binary[a_int]\n\n # Generate a random sample value for 2nd input\n b_int = np.random.randint(max_val/2)\n # Map Int to Binary\n b = int_to_binary[b_int]\n\n # True Answer a + b = c\n c_int = a_int + b_int\n c = int_to_binary[c_int]\n\n # Array to save predicted outputs (binary encoded)\n d = np.zeros_like(c)\n\n # Initialize overall error to \"0\"\n overallError = 0\n\n # Save the values of dJdW1 and dJdW2 computed at Output layer into a list\n output_layer_deltas = list()\n\n # Save the values obtained at Hidden Layer of current state in a list to keep track\n hidden_layer_values = list()\n\n # Initially, there is no previous hidden state. So append \"0\" for that\n hidden_layer_values.append(np.zeros(hiddenLayerSize))\n\n # ----------------------------- Compute the Values for (a+b) using RNN [Forward Propagation] ----------------------\n # position: location of the bit amongst 8 bits; starting point \"0\"; \"0 - 7\"\n for position in range(binary_dim):\n # Generate Input Data for RNN\n # Take the binary values of \"a\" and \"b\" generated for each iteration of \"j\"\n\n # With increasing value of position, the bit location of \"a\" and \"b\" decreases from \"7 -> 0\"\n # and each iteration computes the sum of corresponding bit of \"a\" and \"b\".\n # ex. for position = 0, X = [a[7],b[7]], 7th bit of a and b.\n X = np.array([[a[binary_dim - position - 1], b[binary_dim - position - 1]]])\n\n # Actual value for (a+b) = c, c is an array of 8 bits, so take transpose to compare bit by bit with X value.\n y = np.array([[c[binary_dim - position - 1]]]).T\n\n # Values computed at current hidden layer\n # [dot product of Input(X) and Weights(W1)] + [dot product of previous hidden layer values and Weights (W_h)]\n # W_h: weight from previous step hidden layer to current step hidden layer\n # W1: weights from current step input to current hidden layer\n layer_1 = sigmoid(np.dot(X,W1) + np.dot(hidden_layer_values[-1],W_h))\n\n # The new output using new Hidden layer values\n layer_2 = sigmoid(np.dot(layer_1, W2))\n\n # Calculate the error\n output_error = y - layer_2\n\n # Save the error deltas at each step as it will be propagated back\n output_layer_deltas.append((output_error)*sigmoidPrime(layer_2))\n\n # Save the sum of error at each binary position\n overallError += np.abs(output_error[0])\n\n # Round off the values to nearest \"0\" or \"1\" and save it to a list\n d[binary_dim - position - 1] = np.round(layer_2[0][0])\n\n # Save the hidden layer to be used later\n hidden_layer_values.append(copy.deepcopy(layer_1))\n\n future_layer_1_delta = np.zeros(hiddenLayerSize)\n\n# ----------------------------------- Back Propagating the Error Values to All Previous Time-steps ---------------------\n for position in range(binary_dim):\n # a[0], b[0] -> a[1]b[1] ....\n X = np.array([[a[position], b[position]]])\n # The last step Hidden Layer where we are currently a[0],b[0]\n layer_1 = hidden_layer_values[-position - 1]\n # The hidden layer before the current layer, a[1],b[1]\n prev_hidden_layer = hidden_layer_values[-position-2]\n # Errors at Output Layer, a[1],b[1]\n output_layer_delta = output_layer_deltas[-position-1]\n layer_1_delta = (future_layer_1_delta.dot(W_h.T) + output_layer_delta.dot(W2.T)) * sigmoidPrime(layer_1)\n\n # Update all the weights and try again\n W2_update += np.atleast_2d(layer_1).T.dot(output_layer_delta)\n W_h_update += np.atleast_2d(prev_hidden_layer).T.dot(layer_1_delta)\n W1_update += X.T.dot(layer_1_delta)\n\n future_layer_1_delta = layer_1_delta\n\n # Update the weights with the values\n W1 += W1_update * learning_rate\n W2 += W2_update * learning_rate\n W_h += W_h_update * learning_rate\n\n # Clear the updated weights values\n W1_update *= 0\n W2_update *= 0\n W_h_update *= 0\n\n\n # Print out the Progress of the RNN\n if (j % 1000 == 0):\n print(\"Error:\" + str(overallError))\n print(\"Pred:\" + str(d))\n print(\"True:\" + str(c))\n out = 0\n for index, x in enumerate(reversed(d)):\n out += x * pow(2, index)\n print(str(a_int) + \" + \" + str(b_int) + \" = \" + str(out))\n print(\"------------\")\n\n# ------------------------------------- EOC -----------------------------"
]
| [
[
"numpy.dot",
"numpy.random.random",
"numpy.abs",
"numpy.round",
"numpy.atleast_2d",
"numpy.zeros_like",
"numpy.exp",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
]
]
|
YangYang-SHU/SAAE-DFR | [
"b32970c278b30e0b08da2f2c6659e54ad888f82f"
]
| [
"src/vit.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom utils import load_checkpoint\n\n\nclass PositionEmbs(nn.Module):\n def __init__(self, num_patches, emb_dim, dropout_rate=0.1):\n super(PositionEmbs, self).__init__()\n self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, emb_dim))\n if dropout_rate > 0:\n self.dropout = nn.Dropout(dropout_rate)\n else:\n self.dropout = None\n\n def forward(self, x):\n out = x + self.pos_embedding\n\n if self.dropout:\n out = self.dropout(out)\n\n return out\n\n\nclass MlpBlock(nn.Module):\n \"\"\" Transformer Feed-Forward Block \"\"\"\n def __init__(self, in_dim, mlp_dim, out_dim, dropout_rate=0.1):\n super(MlpBlock, self).__init__()\n\n # init layers\n self.fc1 = nn.Linear(in_dim, mlp_dim)\n self.fc2 = nn.Linear(mlp_dim, out_dim)\n self.act = nn.GELU()\n if dropout_rate > 0.0:\n self.dropout1 = nn.Dropout(dropout_rate)\n self.dropout2 = nn.Dropout(dropout_rate)\n else:\n self.dropout1 = None\n self.dropout2 = None\n\n def forward(self, x):\n\n out = self.fc1(x)\n out = self.act(out)\n if self.dropout1:\n out = self.dropout1(out)\n\n out = self.fc2(out)\n out = self.dropout2(out)\n return out\n\n\nclass LinearGeneral(nn.Module):\n def __init__(self, in_dim=(768,), feat_dim=(12, 64)):\n super(LinearGeneral, self).__init__()\n\n self.weight = nn.Parameter(torch.randn(*in_dim, *feat_dim))\n self.bias = nn.Parameter(torch.zeros(*feat_dim))\n\n def forward(self, x, dims):\n a = torch.tensordot(x, self.weight, dims=dims) + self.bias\n return a\n\n\nclass SelfAttention(nn.Module):\n def __init__(self, in_dim, heads=8, dropout_rate=0.1):\n super(SelfAttention, self).__init__()\n self.heads = heads\n self.head_dim = in_dim // heads\n self.scale = self.head_dim ** 0.5\n\n self.query = LinearGeneral((in_dim,), (self.heads, self.head_dim))\n self.key = LinearGeneral((in_dim,), (self.heads, self.head_dim))\n self.value = LinearGeneral((in_dim,), (self.heads, self.head_dim))\n self.out = LinearGeneral((self.heads, self.head_dim), (in_dim,))\n\n if dropout_rate > 0:\n self.dropout = nn.Dropout(dropout_rate)\n else:\n self.dropout = None\n\n def forward(self, x):\n b, n, _ = x.shape\n\n q = self.query(x, dims=([2], [0]))\n k = self.key(x, dims=([2], [0]))\n v = self.value(x, dims=([2], [0]))\n\n q = q.permute(0, 2, 1, 3)\n k = k.permute(0, 2, 1, 3)\n v = v.permute(0, 2, 1, 3)\n\n attn_weights = torch.matmul(q, k.transpose(-2, -1)) / self.scale\n attn_weights = F.softmax(attn_weights, dim=-1)\n out = torch.matmul(attn_weights, v)\n out = out.permute(0, 2, 1, 3)\n\n out = self.out(out, dims=([2, 3], [0, 1]))\n\n return out\n\n\nclass EncoderBlock(nn.Module):\n def __init__(self, in_dim, mlp_dim, num_heads, dropout_rate=0.1, attn_dropout_rate=0.1):\n super(EncoderBlock, self).__init__()\n\n self.norm1 = nn.LayerNorm(in_dim)\n self.attn = SelfAttention(in_dim, heads=num_heads, dropout_rate=attn_dropout_rate)\n if dropout_rate > 0:\n self.dropout = nn.Dropout(dropout_rate)\n else:\n self.dropout = None\n self.norm2 = nn.LayerNorm(in_dim)\n self.mlp = MlpBlock(in_dim, mlp_dim, in_dim, dropout_rate)\n\n def forward(self, x):\n residual = x\n out = self.norm1(x)\n out = self.attn(out)\n if self.dropout:\n out = self.dropout(out)\n out += residual\n residual = out\n\n out = self.norm2(out)\n out = self.mlp(out)\n out += residual\n return out\n\n\nclass Encoder(nn.Module):\n def __init__(self, num_patches, emb_dim, mlp_dim, num_layers=12, num_heads=12, dropout_rate=0.1, attn_dropout_rate=0.0):\n super(Encoder, self).__init__()\n\n # positional embedding\n self.pos_embedding = PositionEmbs(num_patches, emb_dim, dropout_rate)\n\n # encoder blocks\n in_dim = emb_dim\n self.encoder_layers = nn.ModuleList()\n for i in range(num_layers):\n layer = EncoderBlock(in_dim, mlp_dim, num_heads, dropout_rate, attn_dropout_rate)\n self.encoder_layers.append(layer)\n # self.norm = nn.LayerNorm(in_dim)\n\n def forward(self, x):\n\n out = self.pos_embedding(x)\n comb_out = torch.Tensor().to(out.device)\n for layer in self.encoder_layers:\n out = layer(out)\n comb_out = torch.cat([comb_out,out],dim=2)\n # print('each layer shape :',comb_out.shape)\n\n # out = self.norm(out)\n return out,comb_out\n\n\nclass VisionTransformer(nn.Module):\n \"\"\" Vision Transformer \n (b, w/p * h/p, p*p*3)\n 384 x 384 , 16 x 16 -> (b, 576+1, 768)\n \"\"\"\n def __init__(self,\n image_size=(384, 384),\n patch_size=(16, 16),\n emb_dim=768,\n mlp_dim=3072,\n num_heads=12,\n num_layers=12,\n num_classes=1000,\n attn_dropout_rate=0.0,\n dropout_rate=0.1,\n feat_dim=None):\n super(VisionTransformer, self).__init__()\n h, w = image_size\n\n # embedding layer\n fh, fw = patch_size\n gh, gw = h // fh, w // fw\n self.out_size = (gh, gw)\n num_patches = gh * gw\n self.embedding = nn.Conv2d(3, emb_dim, kernel_size=(fh, fw), stride=(fh, fw))\n # class token\n self.cls_token = nn.Parameter(torch.zeros(1, 1, emb_dim))\n\n # transformer\n self.transformer = Encoder(\n num_patches=num_patches,\n emb_dim=emb_dim,\n mlp_dim=mlp_dim,\n num_layers=num_layers,\n num_heads=num_heads,\n dropout_rate=dropout_rate,\n attn_dropout_rate=attn_dropout_rate)\n\n # classfier\n # self.classifier = nn.Linear(emb_dim, num_classes)\n\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, x):\n conv_emb = self.embedding(x) # (n, c, gh, gw)\n # print(conv_emb.shape)\n emb = conv_emb.permute(0, 2, 3, 1) # (n, gh, hw, c)\n # print(emb.shape)\n b, h, w, c = emb.shape\n emb = emb.reshape(b, h * w, c)\n\n # prepend class token\n cls_token = self.cls_token.repeat(b, 1, 1)\n emb = torch.cat([cls_token, emb], dim=1)\n # print(emb.shape)\n\n # transformer\n _ ,feat = self.transformer(emb)\n feat = feat[:,1:].permute(0,2,1)\n bb, cc, pp = feat.shape\n feat = feat.reshape(bb,cc,24,24)\n\n combin_out = torch.cat((conv_emb,feat),dim=1)\n # print(combin_out.shape)\n # classifier\n # logits = self.classifier(feat[:, 0])\n # print(logits.shape)\n return combin_out\n\n def feat_vec(self, features):\n b, c, w ,h = features.shape\n features = features.reshape(b,c,-1)\n # reshaping features\n features = features.permute(0, 2, 1) # (b, l, c)\n # print(\"After permute:\", features.shape)\n features = torch.unbind(features, dim=0) # [(l, c), ... (l, c)]; total b of (l, c)\n # print(\"Features len:\", len(features))\n features = torch.cat(features, dim=0) # (l*b, c); every (l, c) corresponds to a feature map\n return features\n\n\nif __name__ == '__main__':\n\n # path = '/mnt/ssd/dk-projects/transform-AE/models/imagenet21k+imagenet2012_ViT-B_16.pth'\n #path = '/mnt/ssd/dk-projects/transform-AE/models/imagenet21k+imagenet2012_ViT-L_16.pth'\n\n # model = VisionTransformer(image_size=(384,384)).cuda()\n model = VisionTransformer(image_size=(384,384),emb_dim=768,mlp_dim=3072,num_heads=12,num_layers=4)\n \n #state_dict = load_checkpoint(path)\n\n #state_dict = dict((key, value) for key, value in state_dict.items() if key in model.state_dict().keys())\n\n #model.load_state_dict(state_dict)\n x = torch.randn((2, 3, 384, 384))\n out = model(x)\n print(out.shape)\n # print(out.data)\n # import time\n # time.sleep(10)\n\n # state_dict = model.state_dict()\n\n # for key, value in state_dict.items():\n # print(\"{}: {}\".format(key, value.shape))\n\n\n\n\n\n\n\n\n\n\n"
]
| [
[
"torch.tensordot",
"torch.nn.GELU",
"torch.nn.functional.softmax",
"torch.nn.Dropout",
"torch.Tensor",
"torch.cat",
"torch.zeros",
"torch.randn",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.LayerNorm",
"torch.nn.Linear",
"torch.matmul",
"torch.unbind"
]
]
|
kalman5/tvm | [
"eb64e259546574372c8bb88eee3a4b83130b8b7d"
]
| [
"python/tvm/relay/frontend/onnx.py"
]
| [
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, import-self, len-as-condition, unused-argument, too-many-lines\n# pylint: disable=import-outside-toplevel\n\"\"\"ONNX: Open Neural Network Exchange frontend for Relay.\"\"\"\nimport warnings\nimport numpy as np\nimport tvm\nfrom tvm.ir import IRModule\nfrom tvm.topi.utils import get_const_tuple\n\nfrom ... import nd as _nd\nfrom .. import analysis\nfrom .. import expr as _expr\nfrom .. import function as _function\nfrom .. import op as _op\nfrom .. import vision as _vision\nfrom .. import loops as _loops\nfrom .. import ty as _ty\n\nfrom .common import AttrCvt, Renamer\nfrom .common import get_relay_op, new_var, infer_shape, infer_channels\nfrom .common import infer_type, get_name\n\n\n__all__ = [\"from_onnx\"]\n\n\nclass onnx_input:\n \"\"\" Dual purpose list or dictionary access object.\"\"\"\n\n def __init__(self):\n self.input_keys = []\n self.input_dict = {}\n\n def __getitem__(self, item):\n if isinstance(item, int):\n if item > (len(self.input_keys) - 1):\n return None\n return self.input_dict[self.input_keys[item]]\n if isinstance(item, str):\n if item not in self.input_keys:\n return None\n return self.input_dict[item]\n if isinstance(item, slice):\n keys = self.input_keys[item]\n return [self.input_dict[key] for key in keys]\n\n raise ValueError(\"Only integer, string, and slice accesses allowed.\")\n\n def __setitem__(self, item, value):\n if isinstance(item, int):\n self.input_dict[self.input_keys[item]] = value\n elif isinstance(item, str):\n self.input_keys.append(item)\n self.input_dict[item] = value\n else:\n raise ValueError(\"Only integer and string indexed writes allowed.\")\n\n def keys(self):\n return self.input_keys\n\n def __len__(self):\n return len(self.input_keys)\n\n def __iter__(self):\n self.n = 0\n return self\n\n def __next__(self):\n if self.n < len(self.input_keys):\n output = self.input_dict[self.input_keys[self.n]]\n self.n += 1\n return output\n\n raise StopIteration\n\n\ndef get_numpy(tensor_proto):\n \"\"\"Grab data in TensorProto and convert to numpy array.\"\"\"\n try:\n from onnx.numpy_helper import to_array\n except ImportError as e:\n raise ImportError(\"Unable to import onnx which is required {}\".format(e))\n return to_array(tensor_proto)\n\n\ndef get_type(elem_type):\n \"\"\"Converts onnx integer datatype to numpy datatype\"\"\"\n try:\n from onnx import TensorProto\n except ImportError as e:\n raise ImportError(\"Unable to import onnx which is required {}\".format(e))\n return TensorProto.DataType.Name(elem_type).lower()\n\n\ndef get_info(info_proto):\n \"\"\"Extract the shape from a ValueInfoProto.\"\"\"\n shape = []\n shape_name = []\n for dim in info_proto.type.tensor_type.shape.dim:\n name = dim.dim_param\n value = dim.dim_value\n if value is None or value == 0:\n value = _ty.Any()\n shape_name.append(name)\n else:\n shape_name.append(value)\n shape.append(value)\n\n name = info_proto.name\n dtype = get_type(info_proto.type.tensor_type.elem_type)\n return name, shape, dtype, shape_name\n\n\ndef dimension_picker(prefix, suffix=\"\"):\n \"\"\"Check that dimensions are supported.\"\"\"\n\n def _impl(attr):\n kernel = attr[\"kernel_shape\"]\n if len(kernel) == 1:\n return prefix + \"1d\" + suffix\n if len(kernel) == 2:\n return prefix + \"2d\" + suffix\n if len(kernel) == 3:\n return prefix + \"3d\" + suffix\n msg = \"Only 1D, 2D, and 3D kernels are supported for operator {}.\"\n op_name = prefix + \"1d/2d/3d\"\n raise tvm.error.OpAttributeInvalid(msg.format(op_name))\n\n return _impl\n\n\ndef revert_caffe2_pad(pads):\n \"\"\"Caffe2 requires two times the normal padding.\"\"\"\n if len(pads) == 4:\n pads = pads[:2]\n elif len(pads) == 2:\n pass\n else:\n raise tvm.error.OpAttributeInvalid(\"Number of pads must be either 2 or 4.\")\n return pads\n\n\ndef get_pad_pair(input1d, kernel1d, stride1d):\n \"\"\"infer pad size\"\"\"\n if input1d % stride1d == 0:\n pad = max(kernel1d - stride1d, 0)\n else:\n pad = max(kernel1d - (input1d % stride1d), 0)\n pad_before = pad // 2\n pad_after = pad - pad_before\n return [pad_before, pad_after]\n\n\ndef onnx_default_layout(dims):\n if dims == 1:\n return \"NCW\"\n if dims == 2:\n return \"NCHW\"\n if dims == 3:\n return \"NCDHW\"\n\n msg = \"Only 1D, 2D and 3D layouts are currently supported\"\n raise tvm.error.OpAttributeInvalid(msg.format(op_name))\n\n\ndef onnx_storage_order2layout(storage_order, dims=2):\n \"\"\"converter of onnx storage order parameter to tvm storage order format\"\"\"\n if storage_order not in (0, 1):\n raise tvm.error.OpAttributeInvalid(\"Mode of storage_order must be either 0 or 1\")\n\n if dims == 1:\n return \"NCW\" if storage_order == 0 else \"NWC\"\n if dims == 2:\n return \"NCHW\" if storage_order == 0 else \"NHWC\"\n if dims == 3:\n return \"NCDHW\" if storage_order == 0 else \"NDHWC\"\n\n msg = \"Only 1D, 2D and 3D layouts are currently supported\"\n raise tvm.error.OpAttributeInvalid(msg.format(op_name))\n\n\ndef dimension_constraint():\n def _dim_check(attrs):\n if len(attrs[\"kernel_shape\"]) in [1, 2, 3]:\n return True\n return False\n\n return _dim_check, \"Only 1d, 2d and 3d kernel supported.\"\n\n\nclass OnnxOpConverter(object):\n \"\"\"A helper class for holding onnx op converters.\"\"\"\n\n @classmethod\n def get_converter(cls, opset):\n \"\"\"Get converter matches given opset.\n\n Parameters\n ----------\n opset: int\n opset from model.\n\n Returns\n -------\n converter, which should be `_impl_vx`. Number x is the biggest\n number smaller than or equal to opset belongs to all support versions.\n \"\"\"\n versions = [int(d.replace(\"_impl_v\", \"\")) for d in dir(cls) if \"_impl_v\" in d]\n versions = sorted(versions + [opset])\n version = versions[max([i for i, v in enumerate(versions) if v == opset]) - 1]\n if hasattr(cls, \"_impl_v{}\".format(version)):\n return getattr(cls, \"_impl_v{}\".format(version))\n raise NotImplementedError(\n \"opset version {} of {} not implemented\".format(version, cls.__name__)\n )\n\n\nclass Unary(OnnxOpConverter):\n \"\"\"A helper class for unary op converters.\"\"\"\n\n name = \"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n assert len(inputs) == 1, \"Unary math op {} takes 1 input, {} given\".format(\n cls.name, len(inputs)\n )\n op_name = cls.name\n return get_relay_op(op_name)(*inputs)\n\n\nclass Elemwise(OnnxOpConverter):\n \"\"\"A helper class for elemwise op converters.\"\"\"\n\n name = \"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n assert len(inputs) == 2, \"Math op {} take 2 inputs, {} given\".format(cls.name, len(inputs))\n op_name = cls.name\n conv_ops = [\"conv2d\", \"conv2d_transpose\"]\n if attr.get(\"broadcast\", 0) and any(x in str(inputs[0]) for x in conv_ops):\n # TODO(zhreshold): remove hard coded infershape\n axis = int(attr.get(\"axis\", 0))\n inputs[1] = _op.expand_dims(inputs[1], axis=axis, num_newaxis=2)\n return get_relay_op(op_name)(*inputs)\n\n\nclass Pool(OnnxOpConverter):\n \"\"\"A helper class for pool op converters.\"\"\"\n\n name = \"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n data = inputs[0]\n input_shape = infer_shape(data)\n ndim = len(input_shape)\n if \"auto_pad\" in attr:\n attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n if attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n if cls.name == \"avg_pool\":\n pad_tuple = []\n for axis in range(len(input_shape) - 2):\n axis_shape = input_shape[2 + axis]\n stride = attr[\"strides\"][axis]\n kernel = attr[\"kernel_shape\"][axis]\n pad = get_pad_pair(axis_shape, kernel, stride)\n pad_tuple.append(pad)\n pad_tuple = tuple([val for pair in zip(*pad_tuple) for val in pair])\n attr[\"pads\"] = pad_tuple\n else:\n # Warning: Pool does not yet support dynamic shapes,\n # one will need to run dynamic_to_static on this model after import\n data = autopad(data, attr[\"strides\"], attr[\"kernel_shape\"], [1] * ndim, ndim)\n elif attr[\"auto_pad\"] == \"VALID\":\n attr[\"pads\"] = tuple([0 for i in range(ndim - 2)])\n elif attr[\"auto_pad\"] == \"NOTSET\":\n pass\n else:\n msg = 'Value {} in attribute \"auto_pad\" of operator {} is invalid.'\n raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"], cls.name))\n attr.pop(\"auto_pad\")\n\n if \"storage_order\" in attr:\n attr[\"layout\"] = onnx_storage_order2layout(\n attr[\"storage_order\"], dims=(len(input_shape) - 2)\n )\n else:\n attr[\"layout\"] = onnx_default_layout(dims=(len(input_shape) - 2))\n\n return AttrCvt(\n op_name=dimension_picker(cls.name),\n transforms={\"kernel_shape\": \"pool_size\", \"pads\": (\"padding\", 0)},\n ignores=[\"dilations\", \"storage_order\"],\n custom_check=dimension_constraint(),\n )([data], attr, params)\n\n\nclass Absolute(Unary):\n \"\"\"Operator converter for Absolute.\"\"\"\n\n name = \"abs\"\n\n\nclass Add(Elemwise):\n \"\"\"Operator converter for Add.\"\"\"\n\n name = \"add\"\n\n\nclass AveragePool(Pool):\n \"\"\"Operator converter for AveragePool.\"\"\"\n\n name = \"avg_pool\"\n\n\nclass BatchNorm(OnnxOpConverter):\n \"\"\"Operator converter for BatchNorm.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n # TODO(zhreshold): 'spatial' is not properly handled here.\n out = AttrCvt(\n op_name=\"batch_norm\", ignores=[\"spatial\", \"is_test\", \"consumed_inputs\", \"momentum\"]\n )(inputs, attr, params)\n return out[0]\n\n\nclass InstanceNorm(OnnxOpConverter):\n \"\"\"Operator converter for BatchNorm.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return AttrCvt(op_name=\"instance_norm\")(inputs, attr, params)\n\n\ndef autopad(data, strides, kernel_shape, dilations, ndim, pad_type=\"constant\", deconv=False):\n \"\"\"\n Perform autopadding with dynamic input shapes\n \"\"\"\n # get attributes as constants\n strides = _op.const(np.array(strides), dtype=\"int64\")\n dilated_kernel_shape = _op.const(\n np.array(\n [(kernel - 1) * dilation + 1 for kernel, dilation in zip(kernel_shape, dilations)]\n ),\n dtype=\"int64\",\n )\n shape = _op.strided_slice(_op.shape_of(data, dtype=\"int64\"), [2], [ndim])\n # get input shape\n\n # set up integer constants\n zero = _op.const(0, dtype=\"int64\")\n one = _op.const(1, dtype=\"int64\")\n two = _op.const(2, dtype=\"int64\")\n\n # Calculate total padding\n mod = _op.mod(shape, strides)\n\n left = _op.maximum(dilated_kernel_shape - strides, zero)\n right = _op.maximum(dilated_kernel_shape - mod, zero)\n\n total_pad = _op.where(_op.equal(mod, zero), left, right)\n if deconv:\n total_pad = _op.const(np.array(kernel_shape), dtype=\"int64\") - one - total_pad\n\n # split total padding into before and after\n pad_before = _op.floor_divide(total_pad, two)\n pad_after = total_pad - pad_before\n\n # combine\n pad = _op.concatenate(\n [_op.reshape(pad_before, [-1, 1]), _op.reshape(pad_after, [-1, 1])], axis=1\n )\n\n # pad N and C with zeros\n pad = _op.concatenate([_op.const(np.zeros([2, 2], dtype=\"int64\"), dtype=\"int64\"), pad], axis=0)\n\n return _op.nn.pad(data, pad, _op.const(0.0), pad_type)\n\n\nclass Conv(OnnxOpConverter):\n \"\"\"Operator converter for Conv.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n # Use shape of input to determine convolution type.\n data = inputs[0]\n input_shape = infer_shape(data)\n ndim = len(input_shape)\n if \"auto_pad\" in attr:\n attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n if attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n # Warning: Convolution does not yet support dynamic shapes,\n # one will need to run dynamic_to_static on this model after import\n data = autopad(data, attr[\"strides\"], attr[\"kernel_shape\"], attr[\"dilations\"], ndim)\n elif attr[\"auto_pad\"] == \"VALID\":\n attr[\"pads\"] = tuple([0 for i in range(ndim - 2)])\n elif attr[\"auto_pad\"] == \"NOTSET\":\n pass\n else:\n msg = 'Value {} in attribute \"auto_pad\" of operator Conv is invalid.'\n raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"]))\n attr.pop(\"auto_pad\")\n\n out = AttrCvt(\n op_name=dimension_picker(\"conv\"),\n transforms={\n \"kernel_shape\": \"kernel_size\",\n \"dilations\": (\"dilation\", 1),\n \"pads\": (\"padding\", 0),\n \"group\": (\"groups\", 1),\n },\n custom_check=dimension_constraint(),\n )([data, inputs[1]], attr, params)\n\n use_bias = len(inputs) == 3\n if use_bias:\n out = _op.nn.bias_add(out, inputs[2])\n return out\n\n\nclass ConvTranspose(OnnxOpConverter):\n \"\"\"Operator converter for ConvTranspose.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n # get number of channels\n channels = infer_channels(inputs[1], True)\n attr[\"channels\"] = channels\n groups = attr.pop(\"group\")\n attr[\"groups\"] = groups\n # infer pads for auto_pad\n data = inputs[0]\n input_shape = infer_shape(data)\n ndim = len(input_shape)\n if \"auto_pad\" in attr:\n attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n if attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n # Warning: Convolution does not yet support dynamic shapes,\n # one will need to run dynamic_to_static on this model after import\n data = autopad(\n data,\n attr[\"strides\"],\n attr[\"kernel_shape\"],\n attr[\"dilations\"],\n ndim,\n deconv=True,\n )\n elif attr[\"auto_pad\"] == \"VALID\":\n attr[\"pads\"] = tuple([0 for i in range(ndim - 2)])\n elif attr[\"auto_pad\"] == \"NOTSET\":\n pass\n else:\n msg = 'Value {} in attribute \"auto_pad\" of operator Conv is invalid.'\n raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"]))\n attr.pop(\"auto_pad\")\n\n out = AttrCvt(\n op_name=dimension_picker(\"conv\", \"_transpose\"),\n transforms={\n \"kernel_shape\": \"kernel_size\",\n \"dilations\": (\"dilation\", 1),\n \"pads\": (\"padding\", 0),\n \"group\": (\"groups\", 1),\n },\n disables=[\"output_shape\"],\n custom_check=dimension_constraint(),\n )([data, inputs[1]], attr, params)\n use_bias = len(inputs) == 3\n if use_bias:\n out = _op.nn.bias_add(out, inputs[2])\n return out\n\n\nclass Div(Elemwise):\n \"\"\"Operator converter for Divide.\"\"\"\n\n name = \"divide\"\n\n\nclass Elu(OnnxOpConverter):\n \"\"\"Operator converter for Elu.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n alpha = float(attr.get(\"alpha\", 1.0))\n return _expr.const(-alpha) * _op.nn.relu(\n _expr.const(1.0) - _op.exp(inputs[0])\n ) + _op.nn.relu(inputs[0])\n\n\nclass Gemm(OnnxOpConverter):\n \"\"\"Operator converter for Gemm.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n assert len(inputs) == 3, \"Gemm op take 3 inputs, {} given\".format(len(inputs))\n # Y = alpha * A * B + beta * C\n alpha = float(attr.get(\"alpha\", 1.0))\n beta = float(attr.get(\"beta\", 1.0))\n transA = int(attr.get(\"transA\", 0))\n transB = int(attr.get(\"transB\", 0))\n # get number of channels\n channels = infer_channels(inputs[1], not transB)\n if transA:\n inputs[0] = _op.transpose(inputs[0], axes=(1, 0))\n if not transB:\n inputs[1] = _op.transpose(inputs[1], axes=(1, 0))\n inputs[0] = _op.nn.batch_flatten(inputs[0])\n\n if alpha != 1.0:\n inputs[0] *= _expr.const(alpha)\n out = _op.nn.dense(inputs[0], inputs[1], units=channels)\n\n # skip (beta * C) if zero\n C_array = params[inputs[2].name_hint].asnumpy()\n if (beta == 0.0) or np.array_equal(C_array, np.array([0])):\n return out\n return _op.nn.bias_add(out, _expr.const(beta) * inputs[2])\n\n\nclass MatMul(OnnxOpConverter):\n \"\"\"Operator converter for MatMul.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n assert len(inputs) == 2, \"MatMul op take 2 inputs, {} given\".format(len(inputs))\n # Need to check input shape as batch matmul must be supported.\n a_shape = _op.shape_of(inputs[0])\n a_rank = infer_shape(a_shape)[0]\n b_shape = _op.shape_of(inputs[1])\n b_rank = infer_shape(b_shape)[0]\n # When performing a batch matmul, we need to properly handle N-dim shapes.\n if a_rank > 2 or b_rank > 2:\n\n def flatten_to_3d(x, x_shape):\n ndims = infer_shape(x_shape)[0]\n newshape = _op.concatenate(\n [_expr.const([-1]), _op.strided_slice(x_shape, [ndims - 2], [ndims])], 0\n )\n out = _op.reshape(x, newshape)\n return out\n\n # Convert a and b into 3 dimensional tensors.\n a = flatten_to_3d(inputs[0], a_shape)\n b = flatten_to_3d(inputs[1], b_shape)\n # Transpose matrix dimensions of b.\n b = _op.transpose(b, [0, 2, 1])\n # Perform a batch matmul.\n output = _op.nn.batch_matmul(a, b)\n # Determine the output batch dimension.\n if a_rank > b_rank:\n out_batch = _op.strided_slice(a_shape, [0], [a_rank - 2])\n elif a_rank < b_rank:\n out_batch = _op.strided_slice(b_shape, [0], [b_rank - 2])\n # If its unclear how broadcasting should be applied, the output\n # shape is determined by choosing the maximum value from each input.\n else:\n out_batch = _op.concatenate(\n [\n _op.maximum(\n _op.strided_slice(a_shape, [i], [i + 1]),\n _op.strided_slice(b_shape, [i], [i + 1]),\n )\n for i in range(a_rank - 2)\n ],\n 0,\n )\n # Reshape output to original dimensions.\n final_shape = _op.concatenate(\n [\n out_batch,\n _op.strided_slice(\n a_shape, [infer_shape(a_shape)[0] - 2], [infer_shape(a_shape)[0] - 1]\n ),\n _op.strided_slice(\n b_shape, [infer_shape(b_shape)[0] - 1], [infer_shape(b_shape)[0]]\n ),\n ],\n 0,\n )\n return _op.reshape(output, final_shape)\n # Otherwise a simple dense op will get the job done.\n input_1_t = _op.transpose(inputs[1], axes=(1, 0))\n return _op.nn.dense(inputs[0], input_1_t)\n\n\nclass Mod(OnnxOpConverter):\n \"\"\"Operator converter for Mod.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n assert len(inputs) == 2, \"Mod op take 2 inputs, {} given\".format(len(inputs))\n\n # Note: attr['fmod'] determines whether the operator should behave like np.fmod or np.mod.\n # attr['fmod'] == 0 will behave as np.mod and attr['fmod'] == 1 will force fmod treatment.\n # The relay equivalent of np.fmod is relay.mod and np.mod is relay.floor_mod\n if attr[\"fmod\"] == 0:\n op_name = \"floor_mod\"\n else:\n op_name = \"mod\"\n\n return AttrCvt(op_name)(inputs, {}, params)\n\n\nclass MaxPool(Pool):\n \"\"\"Operator converter for MaxPool\"\"\"\n\n name = \"max_pool\"\n\n\nclass MaxUnpool(OnnxOpConverter):\n \"\"\"Operator converter for MaxUnpool\"\"\"\n\n @classmethod\n def _impl_v11(cls, inputs, attr, params):\n # Unpack inputs and attributes\n data = inputs[0]\n data_type = infer_type(data).checked_type.dtype\n indices = inputs[1]\n output_shape = inputs[2]\n kernel_shape = attr.get(\"kernel_shape\")\n pads = attr.get(\"pads\", None)\n strides = attr.get(\"strides\", [1] * len(kernel_shape))\n\n # Compute the proper output shape before padding.\n multiplier = _op.concatenate(\n [_expr.const([1, 1], dtype=\"int64\"), _expr.const(list(strides), dtype=\"int64\")], axis=0\n )\n total_output_shape = multiplier * _op.shape_of(data, dtype=\"int64\")\n # Add extra dimensions from kernel size and stride mismatch\n total_output_shape += _op.concatenate(\n [_expr.const([0, 0], \"int64\"), _expr.const(list(kernel_shape), \"int64\")], axis=0\n ) - _op.concatenate(\n [_expr.const([0, 0], \"int64\"), _expr.const(list(strides), \"int64\")], axis=0\n )\n\n # Compute padding amount if output shape is specified.\n if output_shape is not None:\n total_output_shape = output_shape\n\n elif pads is not None:\n # Get pads in the proper format for relay.\n pads = _op.concatenate(\n [_expr.const([0, 0, 0, 0], \"int64\"), _expr.const(list(pads), \"int64\")], axis=0\n )\n pads = _op.reshape(pads, [-1, 2])\n # Compute the total padding per axis.\n total_pad = _op.sum(pads, axis=-1)\n # Reversing maxpool means that padding actually makes our output smaller.\n total_output_shape = total_output_shape - total_pad\n\n # Create a tensor of zeros then scatter our data through it.\n zeros_tensor = _op.zeros(total_output_shape, data_type)\n # We need to flatten all our tensors before scattering.\n flat_tensor = _op.scatter(\n _op.reshape(zeros_tensor, [-1]),\n _op.reshape(indices, [-1]),\n _op.reshape(data, [-1]),\n axis=0,\n )\n # Now reshape back to prepadded shape.\n output_tensor = _op.reshape(flat_tensor, total_output_shape)\n\n return output_tensor\n\n\nclass LpPool(OnnxOpConverter):\n \"\"\"A helper class for lppool op converters.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n dtype = infer_type(inputs[0]).checked_type.dtype\n data = inputs[0]\n input_shape = infer_shape(data)\n ndim = len(input_shape)\n if \"auto_pad\" in attr:\n attr[\"auto_pad\"] = attr[\"auto_pad\"].decode(\"utf-8\")\n if attr[\"auto_pad\"] in (\"SAME_UPPER\", \"SAME_LOWER\"):\n # Warning: LpPool does not yet support dynamic shapes,\n # one will need to run dynamic_to_static on this model after import\n data = autopad(data, attr[\"strides\"], attr[\"kernel_shape\"], [1] * ndim, ndim)\n elif attr[\"auto_pad\"] == \"VALID\":\n attr[\"pads\"] = tuple([0 for i in range(ndim - 2)])\n elif attr[\"auto_pad\"] == \"NOTSET\":\n pass\n else:\n msg = 'Value {} in attribute \"auto_pad\" of operator {} is invalid.'\n raise tvm.error.OpAttributeInvalid(msg.format(attr[\"auto_pad\"], \"LpPool\"))\n attr.pop(\"auto_pad\")\n\n if \"storage_order\" in attr:\n attr[\"layout\"] = onnx_storage_order2layout(\n attr[\"storage_order\"], dims=(len(input_shape) - 2)\n )\n else:\n attr[\"layout\"] = onnx_default_layout(dims=(len(input_shape) - 2))\n\n p = _expr.const(attr[\"p\"], dtype)\n reci_p = _expr.const(1.0 / attr[\"p\"], dtype)\n data = _op.power(data, p)\n\n out = AttrCvt(\n op_name=dimension_picker(\"avg_pool\"),\n transforms={\"kernel_shape\": \"pool_size\", \"pads\": (\"padding\", 0)},\n extras={\"count_include_pad\": True},\n ignores=[\"p\"],\n custom_check=dimension_constraint(),\n )([data], attr, params)\n kernels = attr[\"kernel_shape\"]\n out = _op.abs(out) * _expr.const(np.prod(kernels).astype(dtype))\n return _op.power(out, reci_p)\n\n\nclass Mul(Elemwise):\n \"\"\"Operator converter for Multiply.\"\"\"\n\n name = \"multiply\"\n\n\nclass Pad(OnnxOpConverter):\n \"\"\"Operator converter for Pad.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n pad_width = []\n pads = attr.pop(\"paddings\")\n dims = int(len(pads) / 2)\n for i in range(dims):\n pad_width.append((pads[i], pads[i + dims]))\n attr[\"pad_width\"] = pad_width\n pad_mode = attr.get(\"mode\", b\"constant\").decode(\"utf-8\")\n if pad_mode in [\"constant\", \"edge\", \"reflect\"]:\n attr[\"pad_mode\"] = pad_mode\n attr.pop(\"mode\", None)\n else:\n raise tvm.error.OpAttributeInvalid(\n \"Value \" + pad_mode + ' in attribute \"mode\" is invalid for operator Pad.'\n )\n\n return AttrCvt(\n _op.nn.pad,\n transforms={\n \"value\": \"pad_value\",\n },\n )(inputs, attr, params)\n\n @classmethod\n def _impl_v2(cls, inputs, attr, params):\n pad_width = []\n pads = attr.pop(\"pads\")\n dims = int(len(pads) / 2)\n for i in range(dims):\n pad_width.append((pads[i], pads[i + dims]))\n attr[\"pad_width\"] = pad_width\n pad_mode = attr.get(\"mode\", b\"constant\").decode(\"utf-8\")\n if pad_mode in [\"constant\", \"edge\", \"reflect\"]:\n attr[\"pad_mode\"] = pad_mode\n attr.pop(\"mode\", None)\n else:\n raise tvm.error.OpAttributeInvalid(\n \"Value \" + pad_mode + ' in attribute \"mode\" is invalid for operator Pad.'\n )\n\n return AttrCvt(\n \"pad\",\n transforms={\n \"value\": \"pad_value\",\n },\n )(inputs, attr, params)\n\n @classmethod\n def _impl_v11(cls, inputs, attr, params):\n pads = inputs[1]\n if len(inputs) == 3:\n value = _op.take(inputs[2], _op.const(0))\n else:\n value = 0\n\n pad_width_expr = _op.transpose(_op.reshape(pads, (2, -1)))\n pad_mode = attr.get(\"mode\", b\"constant\").decode(\"utf-8\")\n\n if not pad_mode in [\"constant\", \"edge\", \"reflect\"]:\n raise tvm.error.OpAttributeInvalid(\n \"Value \" + pad_mode + ' in attribute \"mode\" is invalid for operator Pad.'\n )\n\n return _op.nn.pad(inputs[0], pad_width_expr, value, pad_mode=pad_mode)\n\n\nclass ParametricSoftPlus(OnnxOpConverter):\n \"\"\"Operator converter for ParametricSoftPlus.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n alpha = _expr.const(float(attr.get(\"alpha\", 1.0)))\n beta = _expr.const(float(attr.get(\"beta\", 1.0)))\n return _op.log(_op.exp(beta * inputs[0]) + _expr.const(1.0)) * alpha\n\n\nclass Prelu(OnnxOpConverter):\n \"\"\"Operator converter for Prelu.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n assert len(inputs) == 2, \"Prelu need 2 inputs, {} given\".format(len(inputs))\n input_channels = infer_shape(inputs[0])[1]\n alpha_shape = infer_shape(inputs[1])\n if len(alpha_shape) != 1:\n alpha = _op.reshape(inputs[1], (-1,))\n else:\n alpha = inputs[1]\n return _op.nn.prelu(inputs[0], _op.broadcast_to(alpha, [input_channels]))\n\n\nclass Reciprocal(OnnxOpConverter):\n \"\"\"Operator converter for Reciprocal.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return _expr.const(1.0) / inputs[0]\n\n\nclass Flatten(OnnxOpConverter):\n \"\"\"Operator converter for Flatten.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n axis = attr.get(\"axis\", 1)\n if axis == 1:\n out = _op.nn.batch_flatten(inputs[0])\n else:\n newshape = [0] * (axis + 1)\n newshape[axis] = -1\n out = _op.reshape(inputs[0], list(newshape))\n return out\n\n\nclass Reshape(OnnxOpConverter):\n \"\"\"Operator converter for Reshape.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return _op.reshape(inputs[0], attr[\"shape\"])\n\n @classmethod\n def _impl_v5(cls, inputs, attr, params):\n if get_name(inputs[1]) in params:\n shape = tuple(params[inputs[1].name_hint].asnumpy().astype(\"int32\"))\n out = _op.reshape(inputs[0], shape)\n else:\n out = _op.reshape(*inputs)\n return out\n\n\nclass DepthToSpace(OnnxOpConverter):\n \"\"\"Operator converter for DepthToSpace.\"\"\"\n\n @classmethod\n def _impl_v11(cls, inputs, attr, params):\n\n block_size = int(attr[\"blocksize\"])\n mode = attr.get(\"mode\", b\"DCR\").decode(\"utf-8\")\n return _op.nn.depth_to_space(inputs[0], block_size, mode=mode)\n\n\nclass SpaceToDepth(OnnxOpConverter):\n \"\"\"Operator converter for SpaceToDepth.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n\n block_size = int(attr[\"blocksize\"])\n return _op.nn.space_to_depth(inputs[0], block_size)\n\n\nclass Concat(OnnxOpConverter):\n \"\"\"Operator converter for Concat.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, args, params):\n return AttrCvt(op_name=\"concatenate\")((inputs,), args)\n\n\nclass Scale(OnnxOpConverter):\n \"\"\"Operator converter for Scale.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n scale = float(attr.get(\"scale\", 1.0))\n return inputs[0] * _expr.const(scale)\n\n\nclass Selu(OnnxOpConverter):\n \"\"\"Operator converter for Selu.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n alpha = float(attr.get(\"alpha\", 1.6732))\n gamma = float(attr.get(\"gamma\", 1.0507))\n return _expr.const(gamma) * (\n _expr.const(-alpha) * _op.nn.relu(_expr.const(1.0) - _op.exp(inputs[0]))\n + _op.nn.relu(inputs[0])\n )\n\n\nclass ScaledTanh(OnnxOpConverter):\n \"\"\"Operator converter for ScaledTanh.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n alpha = float(attr.get(\"alpha\", 1.0))\n beta = float(attr.get(\"beta\", 1.0))\n return _op.tanh(_expr.const(beta) * inputs[0]) * _expr.const(alpha)\n\n\nclass Softsign(OnnxOpConverter):\n \"\"\"Operator converter for Softsign.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return inputs[0] / (_expr.const(1.0) + Absolute.get_converter(1)(inputs, attr, params))\n\n\nclass Sub(Elemwise):\n \"\"\"Operator converter for Subtract.\"\"\"\n\n name = \"subtract\"\n\n\nclass Sum(OnnxOpConverter):\n \"\"\"Operator converter for Sum.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n # Onnx Sum Operator\n for in_index in range(len(inputs) - 1):\n inputs[in_index + 1] = _op.add(inputs[in_index], inputs[in_index + 1])\n\n return inputs[len(inputs) - 1]\n\n\nclass Affine(OnnxOpConverter):\n \"\"\"Operator converter for Affine transformation.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n alpha = _expr.const(attr.get(\"alpha\", 1.0))\n beta = _expr.const(attr.get(\"beta\", 0.0))\n return (alpha * inputs[0]) + beta\n\n\nclass ThresholdedRelu(OnnxOpConverter):\n \"\"\"Operator converter for ThresholdedRelu.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n alpha = float(attr.get(\"alpha\", 1.0))\n alpha_tensor = _op.full_like(inputs[0], fill_value=_expr.const(alpha))\n mask = _op.greater(inputs[0], alpha_tensor).astype(\"float32\")\n return inputs[0] * mask\n\n\ndef _broadcast_constraint():\n def _broadcast_check(attrs):\n if attrs.get(\"axis\", None):\n return False\n return True\n\n return _broadcast_check, \"Specifying broadcast axis not allowed.\"\n\n\ndef _fully_connected(opset):\n def _impl(inputs, attr, params):\n # get number of channels\n channels = infer_channels(inputs[1], params)\n attr[\"units\"] = channels\n return AttrCvt(\"dense\", ignores=[\"axis\", \"axis_w\"])(inputs, attr)\n\n return _impl\n\n\nclass Upsample(OnnxOpConverter):\n \"\"\"Operator converter for Upsample (nearest mode).\"\"\"\n\n @classmethod\n def _impl_v9(cls, inputs, attr, params):\n scales = attr.get(\"scales\")\n\n input_shape = infer_shape(inputs[0])\n dims = len(input_shape)\n\n if not scales:\n # Here we are going to higher OPSET version.\n assert len(inputs) == 2, \"Upsample op takes 2 inputs, {} given\".format(len(inputs))\n\n if get_name(inputs[1]) in params:\n scales = params[inputs[1].name_hint].asnumpy()\n else:\n scales = inputs[1]\n\n if not isinstance(scales, _expr.Call):\n assert scales[0] == 1.0 and scales[1] == 1.0\n\n mode = attr.get(\"mode\")\n if mode == b\"nearest\":\n method = \"nearest_neighbor\"\n elif mode == b\"linear\":\n method = \"trilinear\" if dims == 5 else \"bilinear\"\n else:\n raise tvm.error.OpAttributeInvalid(\n 'Value {} in attribute \"mode\" of operator Upsample is not valid.'.format(mode)\n )\n\n if method == \"nearest_neighbor\":\n align_corners = False\n else:\n align_corners = True\n # in 3d case, we use the purely static op\n if dims == 5:\n if isinstance(scales, _expr.Call):\n scale_h = _op.take(scales, _op.const(3))\n scale_w = _op.take(scales, _op.const(4))\n scale_d = _op.take(scales, _op.const(1))\n else:\n assert len(scales) == 5\n scale_h = scales[-2]\n scale_w = scales[-1]\n scale_d = scales[-3]\n\n layout = \"NCDHW\"\n out = _op.nn.upsampling3d(\n inputs[0], scale_d, scale_h, scale_w, layout=layout, method=method\n )\n # in 2d case, use dynamic op\n else:\n if isinstance(scales, _expr.Call):\n scale_h = _op.take(scales, _op.const(3))\n scale_w = _op.take(scales, _op.const(4))\n else:\n assert len(scales) == 4\n scale_h = scales[-2]\n scale_w = scales[-1]\n layout = \"NCHW\"\n\n out = _op.nn.upsampling(\n inputs[0],\n scale_h,\n scale_w,\n layout=layout,\n method=method,\n align_corners=align_corners,\n )\n return out\n\n\nclass Shape(OnnxOpConverter):\n \"\"\"Operator converter for Shape.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return _op.shape_of(inputs[0], \"int64\")\n\n\nclass Cast(OnnxOpConverter):\n \"\"\"Operator converter for Cast.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return AttrCvt(op_name=\"cast\", transforms={\"to\": \"dtype\"})(inputs, attr)\n\n @classmethod\n def _impl_v5(cls, inputs, attr, params):\n try:\n from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE\n\n attr[\"to\"] = str(TENSOR_TYPE_TO_NP_TYPE[attr[\"to\"]])\n except ImportError as e:\n raise ImportError(\"Unable to import onnx.mapping which is required {}\".format(e))\n return AttrCvt(op_name=\"cast\", transforms={\"to\": \"dtype\"})(inputs, attr)\n\n\nclass Unsqueeze(OnnxOpConverter):\n \"\"\"Operator converter for Unsqueeze.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n for axes in attr[\"axes\"]:\n inputs[0] = _op.expand_dims(inputs[0], axis=axes, num_newaxis=1)\n return inputs[0]\n\n\nclass Split(OnnxOpConverter):\n \"\"\"Operator converter for Split.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n splits = attr.get(\"split\", False)\n if splits:\n attr[\"indices_or_sections\"] = []\n index = 0\n for i in splits[:-1]:\n index += i\n attr[\"indices_or_sections\"].append(index)\n # When splits isnt specified divide evenly over axis.\n else:\n attr[\"indices_or_sections\"] = attr[\"tvm_custom\"][\"num_outputs\"]\n return AttrCvt(\"split\", ignores=[\"split\"])(inputs, attr, params)\n\n\nclass Slice(OnnxOpConverter):\n \"\"\"Operator converter for Slice.\"\"\"\n\n @classmethod\n def _common(cls, starts, ends, axes):\n new_axes = []\n new_starts = []\n new_ends = []\n pop_index = 0\n for i in range(max(axes) + 1):\n if i in axes:\n new_axes.append(i)\n new_starts.append(starts[pop_index])\n new_ends.append(ends[pop_index])\n pop_index += 1\n else:\n new_axes.append(i)\n new_starts.append(0)\n new_ends.append(np.iinfo(np.int32).max)\n return new_starts, new_ends, new_axes\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if isinstance(attr[\"starts\"], int):\n attr[\"starts\"] = (attr[\"starts\"],)\n attr[\"ends\"] = (attr[\"ends\"],)\n\n try:\n # Update the starts and ends according to axes if required.\n if isinstance(attr[\"axes\"], int):\n attr[\"axes\"] = (attr[\"axes\"],)\n if (max(attr[\"axes\"]) + 1) != len(attr[\"axes\"]):\n new_starts, new_ends, new_axes = cls._common(\n attr[\"starts\"], attr[\"ends\"], attr[\"axes\"]\n )\n attr[\"axes\"] = new_axes\n attr[\"starts\"] = new_starts\n attr[\"ends\"] = new_ends\n except KeyError:\n pass\n begin = list(attr[\"starts\"])\n end = list(attr[\"ends\"])\n\n return _op.strided_slice(inputs[0], begin=begin, end=end)\n\n @classmethod\n def _impl_v10(cls, inputs, attr, params):\n starts = inputs[1]\n ends = inputs[2]\n axes = inputs[3]\n steps = inputs[4]\n\n data_rank = len(infer_shape(inputs[0]))\n\n # Update the starts and ends according to axes if required.\n if axes is not None:\n data_shape = _op.shape_of(inputs[0], dtype=infer_type(ends).checked_type.dtype)\n starts = _op.scatter(\n _op.const([0] * data_rank, dtype=infer_type(starts).checked_type.dtype),\n axes,\n starts,\n axis=0,\n )\n ends = _op.scatter(data_shape, axes, ends, axis=0)\n if steps is not None:\n steps = _op.scatter(\n _op.const([1] * data_rank, dtype=infer_type(steps).checked_type.dtype),\n axes,\n steps,\n axis=0,\n )\n\n if steps is None:\n steps = _op.const([1] * data_rank, dtype=infer_type(starts).checked_type.dtype)\n\n return _op.strided_slice(inputs[0], starts, ends, steps)\n\n\nclass Gather(OnnxOpConverter):\n \"\"\"Operator converter for Gather.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n axis = attr.get(\"axis\", 0)\n return AttrCvt(\"take\", extras={\"axis\": axis})(inputs, {})\n\n\nclass GatherElements(OnnxOpConverter):\n \"\"\"Operator converter for GatherElements.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n data = inputs[0]\n indices = inputs[1]\n axis = attr.get(\"axis\", 0)\n return _op.gather(data, axis, indices)\n\n\nclass GatherND(OnnxOpConverter):\n \"\"\"Operator converter for GatherND.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return _op.gather_nd(inputs[0], inputs[1])\n\n\nclass Scatter(OnnxOpConverter):\n \"\"\"Operator converter for Scatter.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n axis = attr.get(\"axis\", 0)\n return _op.scatter(inputs[0], inputs[1], inputs[2], axis)\n\n\nclass Greater(OnnxOpConverter):\n \"\"\"Operator logical greater.\"\"\"\n\n @classmethod\n def _impl_v7(cls, inputs, attr, params):\n return _op.greater(inputs[0], inputs[1])\n\n\nclass Less(OnnxOpConverter):\n \"\"\"Operator logical less than.\"\"\"\n\n @classmethod\n def _impl_v7(cls, inputs, attr, params):\n return _op.less(inputs[0], inputs[1])\n\n\nclass LRN(OnnxOpConverter):\n \"\"\"Operator converter for Local Response Normalization.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n \"\"\"LRN support only NCHW format\n https://github.com/onnx/onnx/blob/master/docs/Operators.md#LRN\n \"\"\"\n axis = 1\n alpha = attr.get(\"alpha\", 0.0001)\n beta = attr.get(\"beta\", 0.75)\n bias = attr.get(\"bias\", 1.0)\n nsize = attr.get(\"size\")\n attr = {\"size\": nsize, \"axis\": axis, \"alpha\": alpha, \"beta\": beta, \"bias\": bias}\n return AttrCvt(\"lrn\")(inputs, attr)\n\n\nclass Maximum(OnnxOpConverter):\n \"\"\"Operator converter for Maximum.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if not isinstance(inputs, (list, onnx_input)) or len(inputs) < 2:\n raise ValueError(\"Expect minimum 2 inputs\")\n _max = inputs[0]\n for i in range(1, len(inputs)):\n _max = AttrCvt(\"maximum\")([_max, inputs[i]], {})\n return _max\n\n\nclass Minimum(OnnxOpConverter):\n \"\"\"Operator converter for Minimum.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if not isinstance(inputs, (list, onnx_input)) or len(inputs) < 2:\n raise ValueError(\"Expect minimum 2 inputs\")\n _min = inputs[0]\n for i in range(1, len(inputs)):\n _min = AttrCvt(\"minimum\")([_min, inputs[i]], {})\n return _min\n\n\nclass Mean(OnnxOpConverter):\n \"\"\"Operator converter for Mean.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if not isinstance(inputs, (list, onnx_input)) or len(inputs) < 2:\n raise ValueError(\"Expect minimum 2 inputs\")\n # avoid overflow\n concat = _op.concatenate([_op.expand_dims(x, axis=0) for x in inputs], axis=0)\n return _op.mean(concat, axis=0, keepdims=False)\n\n\nclass HardSigmoid(OnnxOpConverter):\n \"\"\"Operator converter for HardSigmoid.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n alpha = attr.get(\"alpha\", 0.2)\n beta = attr.get(\"beta\", 0.5)\n transformX = (inputs[0] * _expr.const(alpha)) + _expr.const(beta)\n attr = {\"a_min\": 0, \"a_max\": 1}\n return AttrCvt(\"clip\")([transformX], attr)\n\n\nclass Reduce(OnnxOpConverter):\n \"\"\"Operator converter for reduce ops.\"\"\"\n\n name = \"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if \"axes\" in attr:\n axis = attr.get(\"axes\", 0)\n else:\n axis_len = len(infer_shape(inputs[0]))\n axis = list(range(axis_len))\n attr = {\"axis\": axis, \"keepdims\": attr.get(\"keepdims\", True)}\n return AttrCvt(cls.name)(inputs, attr)\n\n\nclass ReduceMax(Reduce):\n \"\"\"Operator converter for ReduceMax.\"\"\"\n\n name = \"max\"\n\n\nclass ReduceMin(Reduce):\n \"\"\"Operator converter for ReduceMin.\"\"\"\n\n name = \"min\"\n\n\nclass ReduceSum(Reduce):\n \"\"\"Operator converter for ReduceSum.\"\"\"\n\n name = \"sum\"\n\n\nclass ReduceMean(Reduce):\n \"\"\"Operator converter for ReduceMean.\"\"\"\n\n name = \"mean\"\n\n\nclass ReduceProd(Reduce):\n \"\"\"Operator converter for ReduceProd.\"\"\"\n\n name = \"prod\"\n\n\nclass ReduceLogSumExp(Reduce):\n \"\"\"Operator converter for ReduceLogSumExp.\"\"\"\n\n name = \"logsumexp\"\n\n\nclass ReduceSumSquare(OnnxOpConverter):\n \"\"\"Operator converter for ReduceSumSquare.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if \"axes\" in attr:\n axis = attr.get(\"axes\", 0)\n else:\n axis_len = len(infer_shape(inputs[0]))\n axis = list(range(axis_len))\n attr = {\"axis\": axis, \"keepdims\": attr.get(\"keepdims\", True)}\n inputs[0] = inputs[0] * inputs[0]\n\n return AttrCvt(\"sum\")(inputs, attr)\n\n\nclass ReduceL1(OnnxOpConverter):\n \"\"\"Operator converter for ReduceL1.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if \"axes\" in attr:\n axis = attr.get(\"axes\", 0)\n else:\n axis_len = len(infer_shape(inputs[0]))\n axis = list(range(axis_len))\n attr = {\"axis\": axis, \"keepdims\": attr.get(\"keepdims\", True)}\n inputs[0] = _op.abs(inputs[0])\n\n return AttrCvt(\"sum\")(inputs, attr)\n\n\nclass ReduceL2(OnnxOpConverter):\n \"\"\"Operator converter for ReduceL2.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if \"axes\" in attr:\n axis = attr.get(\"axes\", 0)\n else:\n axis_len = len(infer_shape(inputs[0]))\n axis = list(range(axis_len))\n attr = {\"axis\": axis, \"keepdims\": attr.get(\"keepdims\", True)}\n inputs[0] = inputs[0] * inputs[0]\n out = AttrCvt(\"sum\")(inputs, attr)\n\n return _op.sqrt(out)\n\n\nclass ReduceLogSum(OnnxOpConverter):\n \"\"\"Operator converter for ReduceLogSum.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if \"axes\" in attr:\n axis = attr.get(\"axes\", 0)\n else:\n axis_len = len(infer_shape(inputs[0]))\n axis = list(range(axis_len))\n attr = {\"axis\": axis, \"keepdims\": attr.get(\"keepdims\", True)}\n out = AttrCvt(\"sum\")(inputs, attr)\n\n return _op.log(out)\n\n\nclass ArgMax(OnnxOpConverter):\n \"\"\"Operator converter for ArgMax.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n axis = attr.get(\"axis\", 0)\n keepdims = attr.get(\"keepdims\", True)\n attr = {\"axis\": axis, \"keepdims\": keepdims}\n return AttrCvt(\"argmax\")(inputs, attr)\n\n\nclass ArgMin(OnnxOpConverter):\n \"\"\"Operator converter for ArgMin.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n axis = attr.get(\"axis\", 0)\n keepdims = attr.get(\"keepdims\", True)\n attr = {\"axis\": axis, \"keepdims\": keepdims}\n return AttrCvt(\"argmin\")(inputs, attr)\n\n\nclass Softmax(OnnxOpConverter):\n \"\"\"Operator converter for Softmax.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n # set default value when axis is not set in the model\n if \"axis\" not in attr:\n attr[\"axis\"] = 1\n return AttrCvt(\"softmax\", transforms={\"axis\": (\"axis\", 1)})(inputs, attr, params)\n\n\nclass OneHot(OnnxOpConverter):\n \"\"\"Operator converter for OneHot.\"\"\"\n\n @classmethod\n def _impl_v9(cls, inputs, attr, params):\n # Extract relay one_hot inputs.\n indices, depth, values = inputs\n # Split onnx on off values into two separate expressions.\n off_value, on_value = _op.take(values, _op.const(0)), _op.take(values, _op.const(1))\n # Extract the datatype of the output from on_value.\n dtype = infer_type(on_value).checked_type.dtype\n # set default value when axis is not set in the model\n if \"axis\" not in attr:\n attr[\"axis\"] = -1\n return _op.one_hot(indices, on_value, off_value, depth, int(attr[\"axis\"]), dtype=dtype)\n\n\nclass ConstantOfShape(OnnxOpConverter):\n \"\"\"Operator converter for ConstantOfShape.\"\"\"\n\n @classmethod\n def _impl_v9(cls, inputs, attr, params):\n if \"value\" in attr:\n np_value = get_numpy(attr.pop(\"value\"))[0]\n value = _expr.const(np_value)\n dtype = np_value.dtype.name\n else:\n value = _expr.const(0)\n dtype = \"float32\"\n output = _op.full(value, inputs[0], dtype=dtype)\n return output\n\n\nclass Sign(OnnxOpConverter):\n \"\"\"Operator converter for Sign.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return _op.sign(inputs[0])\n\n\nclass Equal(Elemwise):\n \"\"\"Operator converter for Equal.\"\"\"\n\n name = \"equal\"\n\n\nclass Not(Elemwise):\n \"\"\"Operator converter for Not.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return _op.logical_not(inputs[0])\n\n\nclass And(Elemwise):\n \"\"\"Operator converter for And.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return _op.logical_and(inputs[0], inputs[1])\n\n\nclass Tile(Elemwise):\n \"\"\"Operator converter for Tile\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if \"repeats\" not in attr:\n raise tvm.error.OpAttributeInvalid(\n 'Attribute \"repeats\" should be set ' \"for operator Tile.\"\n )\n reps = attr.pop(\"repeats\") # The number of times repeating the tensor data.\n return _op.tile(inputs[0], reps)\n\n @classmethod\n def _impl_v6(cls, inputs, attr, params):\n return _op.tile(inputs[0], inputs[1])\n\n\nclass Erf(OnnxOpConverter):\n \"\"\"Operator converter for Erf\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return _op.erf(inputs[0])\n\n\nclass Where(OnnxOpConverter):\n \"\"\"Operator converter for Where\"\"\"\n\n @classmethod\n def _impl_v9(cls, inputs, attr, params):\n condition_shape = infer_shape(inputs[0])\n x_shape = infer_shape(inputs[1])\n y_shape = infer_shape(inputs[2])\n\n # condition, x, and y can all be broadcasted.\n # broadcast each of them to the longest shape.\n # if two shapes have the same number of dimensions,\n # try to choose the one that doesn't have \"1\" as\n # a dimension.\n shapes = [condition_shape, x_shape, y_shape]\n shape_lens = [len(shape) for shape in shapes]\n max_size = max(shape_lens)\n max_size_idxs = [i for i, x in enumerate(shape_lens) if x == max_size]\n broadcast_idx = max_size_idxs[0]\n if len(max_size_idxs) > 1:\n for idx in max_size_idxs:\n if 1 not in shapes[idx]:\n broadcast_idx = idx\n\n broadcast_shape = shapes[broadcast_idx]\n\n if condition_shape != broadcast_shape:\n inputs[0] = _op.broadcast_to(inputs[0], broadcast_shape)\n if x_shape != broadcast_shape:\n inputs[1] = _op.broadcast_to(inputs[1], broadcast_shape)\n if y_shape != broadcast_shape:\n inputs[2] = _op.broadcast_to(inputs[2], broadcast_shape)\n return _op.where(inputs[0], inputs[1], inputs[2])\n\n\nclass Or(Elemwise):\n \"\"\"Operator converter for Or.\"\"\"\n\n @classmethod\n def _impl_v7(cls, inputs, attr, params):\n return _op.logical_or(inputs[0], inputs[1])\n\n\nclass Expand(OnnxOpConverter):\n \"\"\"Operator converter for Expand.\"\"\"\n\n @classmethod\n def _impl_v8(cls, inputs, attr, params):\n dtype = infer_type(inputs[1]).checked_type.dtype\n in_shape = _op.shape_of(inputs[0], dtype=dtype)\n shape = inputs[1]\n\n # Currently 'op.broadcast_to' expect the rank of the given 'shape'\n # (the 2nd input) is always higher than that of the given 'input' (the 1st input)\n # However, ONNX Expand supports multi-directional broadcasting, which allows\n # above pattern and also some extent of 'shape' can be smaller than the corresponding\n # extent of 'input'. In this case, the extent of 'shape' must be 1.\n # https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md\n # In above cases, we cannot directorly apply 'op.broadcast_to' instead of 'expand'\n # so, here we solved this problem by expanding the given 'shape' itself.\n def expand_shape(in_shape, shape):\n \"\"\"A function expands the shape when the rank is lower than that of the given\n intput. Also it replaces the extent of the shape with the corresponding extent\n of the intput when it is 1.\n \"\"\"\n in_dims = infer_shape(in_shape)[0]\n new_dims = infer_shape(shape)[0]\n if in_dims < new_dims:\n in_shape = _op.concatenate(\n [\n _expr.const(\n [\n 1,\n ]\n * (new_dims - in_dims),\n dtype=dtype,\n ),\n in_shape,\n ],\n axis=0,\n )\n elif new_dims > in_dims:\n shape = _op.concatenate(\n [\n _expr.const(\n [\n 1,\n ]\n * (in_dims - new_dims),\n dtype=dtype,\n ),\n shape,\n ],\n axis=0,\n )\n new_shape = _op.maximum(in_shape, shape)\n return new_shape\n\n shape = expand_shape(in_shape, shape)\n return _op.broadcast_to(inputs[0], shape=shape)\n\n\nclass RNN(OnnxOpConverter):\n \"\"\"Operator converter for RNNs such as LSTM and GRU.\"\"\"\n\n @classmethod\n def _activation_helper(cls, activation, alpha, beta):\n convert_map = _get_convert_map(1)\n attrs = {}\n if alpha is not None:\n attrs[\"alpha\"] = alpha\n if beta is not None:\n attrs[\"beta\"] = beta\n return lambda x: convert_map[activation.decode(\"utf-8\")]([x], attrs, {})\n\n @classmethod\n def _activation_needs_alpha(cls, activation):\n needs_alpha = [\n \"Affine\",\n \"LeakyRelu\",\n \"ThresholdedRelu\",\n \"ScaledTanh\",\n \"HardSigmoid\",\n \"Elu\",\n ]\n return activation.decode(\"utf-8\") in needs_alpha\n\n @classmethod\n def _activation_needs_beta(cls, activation):\n needs_beta = [\n \"Affine\",\n \"ScaledTanh\",\n \"HardSigmoid\",\n ]\n return activation.decode(\"utf-8\") in needs_beta\n\n\nclass LSTM(RNN):\n \"\"\"Operator converter for LSTM\"\"\"\n\n @classmethod\n def _impl_v7(cls, inputs, attr, params):\n # Unpack inputs, note that if optional and not provided then value will be None.\n X = inputs[0]\n W = inputs[1]\n R = inputs[2]\n B = inputs[3]\n # Sequence length currently unused as it can be inferred from shapes.\n # sequence_lens = inputs['sequence_lens']\n h_0 = inputs[5]\n c_0 = inputs[6]\n P = inputs[7]\n\n num_directions = infer_shape(W)[0]\n W_dtype = infer_type(W).type_annotation.dtype\n\n if num_directions != 1:\n raise NotImplementedError(\"Bidirectional LSTMs not yet supported.\")\n # Remove num_directions axis from weights.\n W = _op.squeeze(W, axis=[0])\n R = _op.squeeze(R, axis=[0])\n if B is not None:\n B = _op.squeeze(B, axis=[0])\n\n X_shape = infer_shape(X)\n hidden_size = infer_shape(R)[-1]\n batch_size = X_shape[1]\n\n # Initialize state if not provided.\n # Otherwise remove bidirectional axis.\n if h_0 is None:\n h_0 = _op.zeros((batch_size, hidden_size), W_dtype)\n else:\n h_0 = _op.squeeze(h_0, axis=[0])\n if c_0 is None:\n c_0 = _op.zeros((batch_size, hidden_size), W_dtype)\n else:\n c_0 = _op.squeeze(c_0, axis=[0])\n\n if P is not None:\n P = _op.squeeze(P, axis=[0])\n p_i, p_o, p_f = _op.split(P, 3)\n H_t = h_0\n C_t = c_0\n h_list = []\n\n if \"activations\" in attr:\n activations = attr[\"activations\"]\n if len(activations) != 3:\n raise NotImplementedError(\"LSTM assumes 3 activation functions are provided\")\n alpha_loc = 0\n alphas = attr.get(\"activation_alpha\", [])\n if isinstance(alphas, float):\n alphas = [alphas]\n beta_loc = 0\n betas = attr.get(\"activation_beta\", [])\n if isinstance(betas, float):\n betas = [betas]\n acts = []\n for i in range(3):\n alpha = None\n beta = None\n activation = activations[i]\n if cls._activation_needs_alpha(activation) and len(alphas) > alpha_loc:\n alpha = alphas[alpha_loc]\n alpha_loc += 1\n if cls._activation_needs_beta(activation) and len(betas) > beta_loc:\n beta = betas[beta_loc]\n beta_loc += 1\n acts.append(cls._activation_helper(activation, alpha, beta))\n f_act, g_act, h_act = acts\n else:\n f_act = _op.sigmoid\n g_act = _op.tanh\n h_act = _op.tanh\n\n X_steps = _op.split(X, indices_or_sections=X_shape[0], axis=0)\n for step in X_steps:\n step = _op.squeeze(step, axis=[0])\n gates = _op.nn.dense(step, W) + _op.nn.dense(H_t, R)\n if B is not None:\n WB, RB = _op.split(B, 2)\n gates += WB + RB\n i, o, f, c = _op.split(gates, 4, axis=-1)\n if P is not None:\n i = f_act(i + p_i * C_t)\n f = f_act(f + p_f * C_t)\n\n else:\n i = f_act(i)\n f = f_act(f)\n c = g_act(c)\n C = f * C_t + i * c\n if P is not None:\n o = f_act(o + p_o * C)\n else:\n o = f_act(o)\n H = o * h_act(C)\n H_t = H\n C_t = C\n h_list.append(_op.expand_dims(H, axis=0))\n # Concatenate outputs and add back in direction axis.\n concatenated = _op.concatenate(h_list, 0)\n output = _op.expand_dims(concatenated, axis=1)\n H_t = _op.expand_dims(H_t, axis=0)\n C_t = _op.expand_dims(C_t, axis=0)\n\n return _expr.TupleWrapper(_expr.Tuple((output, H_t, C_t)), 3)\n\n\nclass GRU(RNN):\n \"\"\"Operator convert for GRU\"\"\"\n\n @classmethod\n def _impl_v7(cls, inputs, attr, params):\n # Unpack inputs, note that if optional and not provided then value will be None.\n X = inputs[0]\n W = inputs[1]\n R = inputs[2]\n B = inputs[3]\n # Sequence length currently unused as it can be inferred from shapes.\n # sequence_lens = inputs['sequence_lens']\n h_0 = inputs[5]\n linear_before_reset = attr.get(\"linear_before_reset\", 0)\n\n num_directions = infer_shape(W)[0]\n W_dtype = infer_type(W).type_annotation.dtype\n\n if num_directions != 1:\n raise NotImplementedError(\"Bidirectional GRUs not yet supported.\")\n # Remove num_directions axis from weights.\n W = _op.squeeze(W, axis=[0])\n R = _op.squeeze(R, axis=[0])\n if B is not None:\n B = _op.squeeze(B, axis=[0])\n\n X_shape = infer_shape(X)\n hidden_size = infer_shape(R)[-1]\n batch_size = X_shape[1]\n\n # Initialize state if not provided.\n # Otherwise remove bidirectional axis.\n if h_0 is None:\n h_0 = _op.zeros((batch_size, hidden_size), W_dtype)\n else:\n h_0 = _op.squeeze(h_0, axis=[0])\n\n H_t = h_0\n h_list = []\n\n if \"activations\" in attr:\n activations = attr[\"activations\"]\n if len(activations) != 2:\n raise NotImplementedError(\"GRU assumes 2 activation functions are provided\")\n alpha_loc = 0\n alphas = attr.get(\"activation_alpha\", [])\n if isinstance(alphas, float):\n alphas = [alphas]\n beta_loc = 0\n betas = attr.get(\"activation_beta\", [])\n if isinstance(betas, float):\n betas = [betas]\n acts = []\n for i in range(2):\n alpha = None\n beta = None\n activation = activations[i]\n if cls._activation_needs_alpha(activation) and len(alphas) > alpha_loc:\n alpha = alphas[alpha_loc]\n alpha_loc += 1\n if cls._activation_needs_beta(activation) and len(betas) > beta_loc:\n beta = betas[beta_loc]\n beta_loc += 1\n acts.append(cls._activation_helper(activation, alpha, beta))\n f_act, g_act = acts\n else:\n f_act = _op.sigmoid\n g_act = _op.tanh\n\n X_steps = _op.split(X, indices_or_sections=X_shape[0], axis=0)\n for step in X_steps:\n step = _op.squeeze(step, axis=[0])\n current = _op.nn.dense(step, W)\n cz, cr, ch = _op.split(current, 3, axis=1)\n rz, rr, rh = _op.split(R, 3, axis=0)\n z = cz + _op.nn.dense(H_t, rz)\n r = cr + _op.nn.dense(H_t, rr)\n if B is not None:\n WB, RB = _op.split(B, 2)\n wbz, wbr, wbh = _op.split(WB, 3, axis=-1)\n rbz, rbr, rbh = _op.split(RB, 3, axis=-1)\n z += wbz + rbz\n r += wbr + rbr\n if linear_before_reset:\n h = ch + (r * (_op.nn.dense(H_t, rh) + rbh)) + wbh\n else:\n h = ch + _op.nn.dense((r * H_t), rh) + wbh + rbh\n else:\n if linear_before_reset:\n h = ch + (r * (_op.nn.dense(H_t, rh)))\n else:\n h = ch + _op.nn.dense((r * H_t), rh)\n\n z = f_act(z)\n r = f_act(r)\n h = g_act(h)\n\n H_t = ((_expr.const(1, dtype=W_dtype) - z) * h) + (z * H_t)\n h_list.append(_op.expand_dims(H_t, axis=0))\n # Concatenate outputs and add back in direction axis.\n concatenated = _op.concatenate(h_list, 0)\n output = _op.expand_dims(concatenated, axis=1)\n H_t = _op.expand_dims(H_t, axis=0)\n\n return _expr.TupleWrapper(_expr.Tuple((output, H_t)), 2)\n\n\nclass Resize(OnnxOpConverter):\n \"\"\"Operator converter for Resize\"\"\"\n\n @classmethod\n def _impl_v10(cls, inputs, attr, params):\n mode = attr.get(\"mode\")\n if mode == b\"nearest\":\n method = \"nearest_neighbor\"\n elif mode == b\"linear\":\n method = \"bilinear\"\n else:\n raise tvm.error.OpAttributeInvalid(\n 'Value {} in attribute \"mode\" of operator Resize is not valid.'.format(mode)\n )\n\n scale = inputs[1]\n size = _op.cast(_op.shape_of(inputs[0]), infer_type(scale).checked_type.dtype) * scale\n\n layout = \"NCHW\" # ONNX assumes NCHW layout\n out_size = _op.strided_slice(size, [2], [4])\n return _op.image.resize(inputs[0], out_size, layout, method, \"asymmetric\")\n\n @classmethod\n def _impl_v11(cls, inputs, attr, params):\n mode = attr.get(\"mode\")\n if mode == b\"nearest\":\n method = \"nearest_neighbor\"\n elif mode == b\"linear\":\n method = \"bilinear\"\n else:\n raise tvm.error.OpAttributeInvalid(\n 'Value {} in attribute \"mode\" of operator Resize is not valid.'.format(mode)\n )\n\n scale = inputs[2]\n scale_shape = infer_shape(scale)\n if len(inputs) == 4:\n assert (\n len(scale_shape) == 0 or scale_shape[0] == 0\n ), \"One of scale or size should be passed, not both.\"\n size = inputs[3]\n else:\n assert len(scale_shape) != 0, \"One of scale or size should be passed.\"\n size = _op.cast(_op.shape_of(inputs[0]), infer_type(scale).checked_type.dtype) * scale\n\n coord_trans = attr.get(\"coordinate_transformation_mode\")\n if coord_trans in [b\"pytorch_half_pixel\", b\"half_pixel\"]:\n coord_trans = \"half_pixel\"\n elif coord_trans == b\"align_corners\":\n coord_trans = \"align_corners\"\n elif coord_trans == b\"asymmetric\" or method == \"nearest_neighbor\":\n coord_trans = \"asymmetric\"\n else:\n raise tvm.error.OpAttributeInvalid(\n \"Unsupported coordinate_transformation_mode: {}\".format(coord_trans)\n )\n layout = \"NCHW\" # ONNX assumes NCHW layout\n out_size = _op.strided_slice(size, [2], [4])\n return _op.image.resize(inputs[0], out_size, layout, method, coord_trans)\n\n\nclass NonZero(OnnxOpConverter):\n \"\"\"Operator converter for NonZero\"\"\"\n\n @classmethod\n def _impl_v9(cls, inputs, attr, params):\n if len(inputs) > 1:\n raise ValueError(\"Expect 1 input only\")\n\n output = AttrCvt(op_name=\"argwhere\")(inputs, attr, params)\n # ONNX NonZero always outputs int64\n output = _op.cast(output, \"int64\")\n return _op.transpose(output, axes=(1, 0))\n\n\nclass TopK(OnnxOpConverter):\n \"\"\"Operator converter for TopK\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if len(inputs) != 2:\n raise ValueError(\"Expect 2 input only\")\n axis = attr.get(\"axis\", -1)\n largest = attr.get(\"largest\", 1)\n\n if largest == 0:\n raise ValueError(\"TVM only supports finding TopK largest elements\")\n\n return _op.topk(inputs[0], inputs[1], axis=axis)\n\n\nclass Range(OnnxOpConverter):\n \"\"\"Operator converter for Range\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if len(inputs) != 3:\n raise ValueError(\"Expect 3 input only\")\n\n return _op.arange(\n inputs[0], inputs[1], inputs[2], dtype=infer_type(inputs[0]).checked_type.dtype\n )\n\n\nclass MaxRoiPool(OnnxOpConverter):\n \"\"\"Operator converter for MaxRoiPool.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n assert len(inputs) == 2, \"MMaxRoiPool op take 2 inputs, {} given\".format(len(inputs))\n\n data = inputs[0]\n rois = inputs[1]\n pooled_shape = attr.get(\"pooled_shape\")\n spatial_scale = attr.get(\"spatial_scale\", 1.0)\n\n return _vision.roi_pool(data, rois, pooled_shape, spatial_scale)\n\n\nclass RoiAlign(OnnxOpConverter):\n \"\"\"Operator converter for RoiAlign.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n if len(inputs) != 3:\n raise ValueError(\"Expect 3 inputs only\")\n x = inputs[0]\n rois = inputs[1]\n batch_indices = inputs[2]\n mode = attr.get(\"mode\", \"avg\")\n if mode != b\"avg\":\n raise ValueError(\"RoiAlign in Relay only uses avg mode\")\n output_height = attr.get(\"output_height\", 1)\n output_width = attr.get(\"output_width\", 1)\n\n sampling_ratio = attr.get(\"sampling_ratio\", 0)\n spatial_scale = attr.get(\"spatial_scale\", 1.0)\n\n batch_indices = _op.expand_dims(batch_indices, axis=1, num_newaxis=1)\n batch_indices = _op.cast(batch_indices, infer_type(rois).type_annotation.dtype)\n rois = _op.concatenate([batch_indices, rois], 1)\n\n return _vision.roi_align(\n x, rois, [output_height, output_width], spatial_scale, sampling_ratio\n )\n\n\nclass Clip(OnnxOpConverter):\n \"\"\"Operator converter for Clip.\"\"\"\n\n @staticmethod\n def convert_attributes(inputs, attr, params):\n convert = AttrCvt(\"clip\", transforms={\"min\": \"a_min\", \"max\": \"a_max\"})\n return convert(inputs, attr, params)\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n return Clip.convert_attributes(inputs, attr, params)\n\n @classmethod\n def _impl_v11(cls, inputs, attr, params):\n if \"min\" in attr and \"max\" in attr:\n return Clip.convert_attributes(inputs, attr, params)\n\n assert len(inputs) <= 3, \"Clip-11 takes up to 3 inputs, input, min, max\"\n result = inputs[0]\n for i, op in enumerate([_op.tensor.maximum, _op.tensor.minimum]):\n if i < len(inputs) - 1:\n result = op(result, inputs[i + 1])\n return result\n\n\nclass Softplus(OnnxOpConverter):\n \"\"\"Operator converter for Softplus.\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n data = inputs[0]\n data_dtype = infer_type(data).checked_type.dtype\n data = _op.exp(data) + _expr.const(1, dtype=data_dtype)\n return _op.log(data)\n\n\nclass Loop(OnnxOpConverter):\n \"\"\"Operator converter for Loop\"\"\"\n\n @classmethod\n def _impl_v11(cls, inputs, attr, params):\n max_loop_count = inputs[0]\n cond = inputs[1]\n loop_deps = inputs[2:]\n num_deps = len(loop_deps)\n body = attr[\"body\"]\n iter_dtype = infer_type(max_loop_count).checked_type.dtype\n\n # Determine what condition mode we're in.\n assert cond is not None or max_loop_count is not None\n is_for_loop = max_loop_count is not None and cond is None\n is_condition_for_loop = cond is not None and max_loop_count is not None\n\n # Loop inputs will be packed as\n # [iter_count, max_count, condition, loop_deps, scan_outputs]\n def cond_fn(*loop_inputs):\n i = loop_inputs[0]\n max_count = loop_inputs[1]\n w = loop_inputs[2]\n\n if cond is not None:\n out_while = _op.equal(w, _expr.const(True, \"bool\"))\n if max_loop_count is not None:\n out_loop = _op.less(i, max_count)\n\n if is_condition_for_loop:\n return _op.logical_and(out_while, out_loop)\n if is_for_loop:\n return out_loop\n return out_while\n\n # Get the current graph proto and create a clone for the subgraph\n graph_scope = GraphProto.current\n subgraph_scope = GraphProto(graph_scope._shape, graph_scope._dtype)\n # Load nodes from outer graph into inner graph.\n subgraph_scope._nodes = graph_scope._nodes.copy()\n\n # Create a list of variables for each value updated in the loop.\n def get_var(name, val, scan=False):\n checked_type = infer_type(val)\n if hasattr(checked_type, \"type_annotation\"):\n checked_type = checked_type.type_annotation\n shape = get_const_tuple(checked_type.shape)\n actual_shape = []\n for dim in shape:\n if isinstance(dim, int) and dim == 0:\n actual_shape.append(_ty.Any())\n else:\n actual_shape.append(dim)\n if scan:\n return _expr.var(name, shape=[_ty.Any()] + actual_shape, dtype=checked_type.dtype)\n\n return _expr.var(name, shape=actual_shape, dtype=checked_type.dtype)\n\n loop_vars = [\n _expr.var(body.input[0].name, shape=(), dtype=iter_dtype), # iteration count\n _expr.var(\"max_count\", shape=(), dtype=iter_dtype), # iteration count\n get_var(body.input[1].name, cond), # exit condition\n ]\n loop_vars += [get_var(body.input[i + 2].name, v) for i, v in enumerate(loop_deps)]\n loop_var_names = [v.name_hint for v in loop_vars]\n\n num_scan_outputs = len(body.output) - (1 + num_deps)\n # TODO (jwfromm) Test with strided slice once type unifier for this case is fixed.\n if num_scan_outputs != 0 and \"Slice\" in [n.op_type for n in body.node]:\n warnings.warn(\n \"\"\"\n Using scan outputs in a loop with strided slice\n currently may cause errors during compilation.\n \"\"\"\n )\n\n # Construct variables and intial empty tensors for any scan outputs.\n scan_output_vars = []\n scan_output_init = []\n for i in range(num_scan_outputs):\n name, shape, dtype, _ = get_info(body.output[i + 1 + num_deps])\n scan_output_vars.append(_expr.var(name, shape=([_ty.Any()] + shape), dtype=dtype))\n scan_output_init.append(_op.reshape(_expr.const([]), [0] + shape))\n\n # Now we can remove loop iter variables from our inner loop's inputs.\n # This is kind of a hack since we have graph inputs that we don't\n # want to treat as actual inputs.\n while len(body.input) != 0:\n body.input.pop(0)\n\n # Define the loop body, in this function we need to unpack loop inputs,\n # convert the loop subgraph, and pack outputs for the next iteration.\n def body_fn(*loop_inputs):\n # Unpack inputs\n loop_count = loop_inputs[0]\n max_count = loop_inputs[1]\n cond = loop_inputs[2]\n current_vars = list(loop_inputs[3 : (3 + num_deps)])\n scan_outputs = loop_inputs[(3 + num_deps) :]\n\n # Prepare body inputs by adding them to node dictionary.\n new_inputs = [loop_count, max_count, cond] + current_vars\n for i, inp in enumerate(new_inputs):\n subgraph_scope._nodes[loop_var_names[i]] = inp\n\n # Get the output of the current loop using the updated inputs.\n with subgraph_scope:\n loop_outputs = subgraph_scope.from_onnx(\n body, graph_scope.opset, get_output_expr=True\n )\n # Unpack the body outputs and prepare variables for next iteration.\n new_cond = loop_outputs[0]\n new_loop_vars = [loop_outputs[i] for i in range(1, 1 + num_deps)]\n new_scan_outputs = [loop_outputs[i] for i in range(1 + num_deps, len(loop_outputs))]\n\n # Increment counter.\n if max_loop_count is not None:\n incr = _expr.const(1, dtype=iter_dtype)\n loop_count = loop_count + incr\n\n # Add new scan outputs to tracking\n combined_scan_outputs = []\n for i, scan in enumerate(scan_outputs):\n new_scan = _op.expand_dims(new_scan_outputs[i], axis=0)\n combined_scan = _op.concatenate([scan, new_scan], axis=0)\n combined_scan_outputs.append(combined_scan)\n\n # Pack loop outputs for next iteration\n # [iter_count, cond, loop_deps, loop_scans]\n return [loop_count, max_count, new_cond] + new_loop_vars + combined_scan_outputs\n\n # Create the loop function.\n loop = _loops.while_loop(cond_fn, loop_vars + scan_output_vars, body_fn)\n\n # Now need to run initial values through the graph.\n init_count = _expr.const(0, dtype=iter_dtype)\n loop_vals = loop(init_count, max_loop_count, cond, *loop_deps, *scan_output_init)\n\n # Extract final iteration outputs.\n if num_deps + num_scan_outputs == 1:\n outputs = _expr.TupleGetItem(loop_vals, 3)\n else:\n outputs = _expr.TupleWrapper(\n _expr.Tuple(\n [\n _expr.TupleGetItem(loop_vals, i + 3)\n for i in range(num_deps + num_scan_outputs)\n ]\n ),\n num_deps + num_scan_outputs,\n )\n\n # Update outer graph with constants found in the subgraph.\n free_vars = analysis.free_vars(loop)\n graph_scope._params.update(subgraph_scope._params)\n for var in free_vars:\n graph_scope._nodes.update({var.name_hint: var})\n return outputs\n\n\nclass If(OnnxOpConverter):\n \"\"\"Operator converter for If\"\"\"\n\n @classmethod\n def _impl_v1(cls, inputs, attr, params):\n cond = inputs[0]\n then_branch = attr.get(\"then_branch\", None)\n else_branch = attr.get(\"else_branch\", None)\n assert then_branch is not None and else_branch is not None\n\n # Create graph converters for both branches.\n graph_scope = GraphProto.current\n then_graph = GraphProto(graph_scope._shape, graph_scope._dtype)\n then_graph._nodes = graph_scope._nodes.copy()\n else_graph = GraphProto(graph_scope._shape, graph_scope._dtype)\n else_graph._nodes = graph_scope._nodes.copy()\n\n # Convert each branch to a relay expression.\n with then_graph:\n then_expr = then_graph.from_onnx(then_branch, graph_scope.opset, get_output_expr=True)\n with else_graph:\n else_expr = else_graph.from_onnx(else_branch, graph_scope.opset, get_output_expr=True)\n\n # Add constants from both branches to parent graph.\n graph_scope._params.update(then_graph._params)\n then_free_vars = analysis.free_vars(then_expr)\n for var in then_free_vars:\n graph_scope._nodes.update({var.name_hint: var})\n graph_scope._params.update(else_graph._params)\n else_free_vars = analysis.free_vars(else_expr)\n for var in else_free_vars:\n graph_scope._nodes.update({var.name_hint: var})\n\n # Now we can construct the relay if statement and return.\n return _expr.If(cond, then_expr, else_expr)\n\n\nclass NonMaxSuppression(OnnxOpConverter):\n \"\"\"Operator converter for NonMaxSuppression.\"\"\"\n\n @classmethod\n def _impl_v10(cls, inputs, attr, params):\n \"\"\"\n High level note: ONNX implements what TF calls combined_non_max_suppression\n It passes in scores for each box for every class in the output and expects boxes to be\n analyzed for each class independently\n\n It also asks for the data to be returned in a particular format.\n\n To support these, we implement a series of lops:\n The first loop splits over class number, performs NMS, and collects the outputs.\n The second (nested) loop takes the outputs and transforms them into the format ONNX wants\n \"\"\"\n # Get parameter values\n boxes = inputs[0]\n scores = inputs[1]\n max_output_boxes_per_class = inputs[2]\n iou_threshold = inputs[3]\n score_threshold = inputs[4]\n\n dtype = infer_type(boxes).checked_type.dtype\n\n if \"center_point_box\" in attr:\n assert (\n attr[\"center_point_box\"] == 0\n ), \"Only support center_point_box = 0 in onnx importer right now\"\n\n if iou_threshold is None:\n iou_threshold = _expr.const(0.0, dtype=\"float32\")\n if score_threshold is None:\n score_threshold = _expr.const(0.0, dtype=\"float32\")\n\n def conditionally_squeeze_scalar(x):\n rank = len(infer_shape(x))\n assert rank <= 1, \"nms thresholds must be scalars\"\n if rank == 1:\n return _op.squeeze(x, [0])\n return x\n\n max_output_boxes_per_class = conditionally_squeeze_scalar(max_output_boxes_per_class)\n iou_threshold = conditionally_squeeze_scalar(iou_threshold)\n score_threshold = conditionally_squeeze_scalar(score_threshold)\n\n ## prepare utility constants\n zero = _op.const(np.array([0]), dtype=\"int64\")\n one = _op.const(np.array([1]), dtype=\"int64\")\n two = _op.const(np.array([2]), dtype=\"int64\")\n three = _op.const(np.array([3]), dtype=\"int64\")\n three_ones = _op.const(np.array([1, 1, 1]), dtype=\"int64\")\n four_ones = _op.const(np.array([1, 1, 1, 1]), dtype=\"int64\")\n\n ## First loop: split by class and perform NMS\n # Create Loop Vars\n i = _expr.var(\"i\", shape=(1,), dtype=\"int64\")\n scores_var = _expr.var(\"scores_var\", shape=(_ty.Any(), _ty.Any(), _ty.Any()), dtype=dtype)\n boxes_var = _expr.var(\"boxes_var\", shape=(_ty.Any(), _ty.Any(), 4), dtype=dtype)\n max_output_boxes_per_class_var = _expr.var(\n \"max_output_boxes_per_class_var\", shape=(), dtype=\"int64\"\n )\n iou_threshold_var = _expr.var(\"iou_threshold_var\", shape=(), dtype=\"float32\")\n score_threshold_var = _expr.var(\"score_threshold_var\", shape=(), dtype=\"float32\")\n B = _expr.var(\"B\", shape=(1,), dtype=\"int64\")\n C = _expr.var(\"C\", shape=(1,), dtype=\"int64\")\n S = _expr.var(\"S\", shape=(1,), dtype=\"int64\")\n # Outputs of first loop should be padded nms values shape (B, C, S, 3)\n onnx_out = _expr.var(\"onnx_out\", shape=(_ty.Any(), _ty.Any(), _ty.Any(), 3), dtype=\"int64\")\n # and sizes of valid outputs, shape (B, C, 1)\n nms_size_out = _expr.var(\"nms_size_out\", shape=(_ty.Any(), _ty.Any(), 1), dtype=\"int64\")\n\n def _first_cond(\n i,\n scores,\n boxes,\n B,\n C,\n S,\n max_output_boxes_per_class,\n iou_threshold,\n score_threshold,\n onnx_out,\n nms_size_out,\n ):\n # Loop over classes, end when i == C\n return _op.min(_op.less(i, C))\n\n def _first_body(\n i,\n scores,\n boxes,\n B,\n C,\n S,\n max_output_boxes_per_class,\n iou_threshold,\n score_threshold,\n onnx_out,\n nms_size_out,\n ):\n # slice to get current class\n begin = _op.concatenate([zero, i, zero], axis=0)\n end = _op.concatenate([B, i + one, S], axis=0)\n class_scores = _op.strided_slice(scores, begin, end, three_ones)\n class_scores = _op.expand_dims(_op.squeeze(class_scores, [1]), -1, 1)\n # combine scores and boxes\n data = _op.concatenate([class_scores, boxes], axis=-1)\n\n # get valid counts\n ct, data, indices = _op.vision.get_valid_counts(\n data, score_threshold=score_threshold, id_index=-1, score_index=0\n )\n # reason why using get_valid_counts is for inference performance\n # ONNX NMS doesn't have parameter top_k\n top_k = -1\n # ONNX doesn't have class id for nms input\n score_index = 0\n # perform nms on current class\n nms_ret = _op.vision.non_max_suppression(\n data=data,\n valid_count=ct,\n indices=indices,\n max_output_size=max_output_boxes_per_class,\n iou_threshold=iou_threshold,\n force_suppress=True,\n top_k=top_k,\n coord_start=1,\n score_index=score_index,\n id_index=-1,\n return_indices=True,\n invalid_to_bottom=False,\n )\n # partially prepare ONNX output format by labeling batch_num, class_id\n nms_padded_out = _op.expand_dims(nms_ret[0], -1, 1)\n batch_num = _op.expand_dims(_op.arange(_op.squeeze(B, [0]), dtype=\"int64\"), -1, 1)\n batch_num = _op.broadcast_to(batch_num, _op.shape_of(nms_ret[0], dtype=\"int64\"))\n batch_num = _op.expand_dims(batch_num, -1, 1)\n class_num = _op.broadcast_to(i, _op.shape_of(nms_padded_out, dtype=\"int64\"))\n new_onnx_out = _op.concatenate(\n [batch_num, class_num, _op.cast(nms_padded_out, \"int64\")], -1\n )\n new_onnx_out = _op.expand_dims(new_onnx_out, 1, 1)\n # store valid nms outputs for this class\n nms_size = _op.cast(nms_ret[1], \"int64\")\n nms_size = _op.expand_dims(nms_size, 1, 1)\n return [\n i + one,\n scores,\n boxes,\n B,\n C,\n S,\n max_output_boxes_per_class,\n iou_threshold,\n score_threshold,\n _op.concatenate([onnx_out, new_onnx_out], axis=1),\n _op.concatenate([nms_size_out, nms_size], axis=1),\n ]\n\n # create the first loop\n first_loop = _loops.while_loop(\n _first_cond,\n [\n i,\n scores_var,\n boxes_var,\n B,\n C,\n S,\n max_output_boxes_per_class_var,\n iou_threshold_var,\n score_threshold_var,\n onnx_out,\n nms_size_out,\n ],\n _first_body,\n )\n\n ## Second loop slices outputs of the first loop for valid boxes and\n ## concats in the order ONNX wants\n # Second inner Loop Vars\n i = _expr.var(\"i\", shape=(1,), dtype=\"int64\")\n j = _expr.var(\"j\", shape=(1,), dtype=\"int64\")\n B = _expr.var(\"B\", shape=(1,), dtype=\"int64\")\n C = _expr.var(\"C\", shape=(1,), dtype=\"int64\")\n # Outputs of first loop should be padded nms values shape (B, C, 3)\n onnx_out = _expr.var(\"onnx_out\", shape=(_ty.Any(), _ty.Any(), _ty.Any(), 3), dtype=\"int64\")\n # and sizes of valid outputs, shape (B, C, 1)\n nms_size_out = _expr.var(\"nms_size_out\", shape=(_ty.Any(), _ty.Any(), 1), dtype=\"int64\")\n out = _expr.var(\"out\", shape=(_ty.Any(), 3), dtype=\"int64\")\n\n def _inner_cond(i, j, C, onnx_out, nms_size, out):\n # inner loop over number of classes\n return _op.min(_op.less(j, C))\n\n def _inner_body(i, j, C, onnx_out, nms_size, out):\n # slice to get current batch and class for valid box indicator\n start = _op.concatenate([i, j + one, zero], axis=0)\n end = _op.concatenate([i + one, j + two, one], axis=0)\n num_valid_boxes = _op.reshape(_op.strided_slice(nms_size, start, end, three_ones), [1])\n # slice to get current batch, class, and valid outputs\n start = _op.concatenate([i, j + one, zero, zero], axis=0)\n end = _op.concatenate([i + one, j + two, num_valid_boxes, three], axis=0)\n new_out = _op.squeeze(_op.strided_slice(onnx_out, start, end, four_ones), [0, 1])\n return i, j + one, C, onnx_out, nms_size, _op.concatenate([out, new_out], axis=0)\n\n inner_loop = _loops.while_loop(\n _inner_cond, [i, j, C, onnx_out, nms_size_out, out], _inner_body\n )\n\n # Second Outer Loop Vars\n i = _expr.var(\"i\", shape=(1,), dtype=\"int64\")\n j = _expr.var(\"j\", shape=(1,), dtype=\"int64\")\n B = _expr.var(\"B\", shape=(1,), dtype=\"int64\")\n C = _expr.var(\"C\", shape=(1,), dtype=\"int64\")\n # Outputs of first loop should be padded nms values shape (B, C, 3)\n onnx_out = _expr.var(\"onnx_out\", shape=(_ty.Any(), _ty.Any(), _ty.Any(), 3), dtype=\"int64\")\n # and sizes of valid outputs, shape (B, C, 1)\n nms_size_out = _expr.var(\"nms_size_out\", shape=(_ty.Any(), _ty.Any(), 1), dtype=\"int64\")\n out = _expr.var(\"out\", shape=(_ty.Any(), 3), dtype=\"int64\")\n\n def _outer_cond(i, B, C, onnx_out, nms_size_out, out):\n # Outer loop is over batch size\n return _op.min(_op.less(i, B))\n\n def _outer_body(i, B, C, onnx_out, nms_size_out, out):\n # Outer loop just calls inner loop\n init_count = _op.const(np.array([0]), dtype=\"int64\")\n inner_loop_vals = inner_loop(i, init_count, C, onnx_out, nms_size_out, out)\n return i + one, B, C, onnx_out, nms_size_out, _expr.TupleGetItem(inner_loop_vals, 5)\n\n # Create the second loop\n outer_loop = _loops.while_loop(\n _outer_cond, [i, B, C, onnx_out, nms_size_out, out], _outer_body\n )\n\n # Call the first loop, perform NMS\n B, C, S = _op.split(_op.shape_of(scores, dtype=\"int64\"), 3)\n init_count = _op.const(np.array([0]), dtype=\"int64\")\n init_onnx_out = _op.const([1], dtype=\"int64\")\n init_onnx_out = _op.broadcast_to(init_onnx_out, _op.concatenate([B, one, S, three], 0))\n init_nms_size_out = _op.const([1], dtype=\"int64\")\n init_nms_size_out = _op.broadcast_to(init_nms_size_out, _op.concatenate([B, one, one], 0))\n loop_vals = first_loop(\n init_count,\n scores,\n boxes,\n B,\n C,\n S,\n max_output_boxes_per_class,\n iou_threshold,\n score_threshold,\n init_onnx_out,\n init_nms_size_out,\n )\n onnx_output = _expr.TupleGetItem(loop_vals, 9)\n nms_size_output = _expr.TupleGetItem(loop_vals, 10)\n\n # Call the second loop, rework outputs into correct form\n init_count = _op.const(np.array([0]).astype(\"int64\"), dtype=\"int64\")\n init_out = _op.const(np.array([]).reshape([0, 3]).astype(\"int64\"), dtype=\"int64\")\n loop_vals = outer_loop(init_count, B, C, onnx_output, nms_size_output, init_out)\n\n return _expr.TupleGetItem(loop_vals, 5)\n\n\n# compatible operators that do NOT require any conversion.\n_identity_list = []\n\n\n# _convert_map defines maps of name to converter functor(callable)\n# for 1 to 1 mapping, use Renamer if nothing but name is different\n# use AttrCvt if attributes need to be converted\n# for 1 to N mapping(composed), use custom callable functions\n# for N to 1 mapping, currently not supported(?)\ndef _get_convert_map(opset):\n return {\n # defs/experimental\n \"Identity\": Renamer(\"copy\"),\n \"Affine\": Affine.get_converter(opset),\n \"ThresholdedRelu\": ThresholdedRelu.get_converter(opset),\n \"ScaledTanh\": ScaledTanh.get_converter(opset),\n \"ParametricSoftplus\": ParametricSoftPlus.get_converter(opset),\n \"ConstantOfShape\": ConstantOfShape.get_converter(opset),\n # 'GivenTensorFill'\n \"FC\": AttrCvt(\"dense\", ignores=[\"axis\", \"axis_w\"]),\n \"Scale\": Scale.get_converter(opset),\n # 'GRUUnit'\n # 'ATen'\n # 'ImageScaler'\n # 'MeanVarianceNormalization'\n # 'Crop'\n # 'Embedding'\n \"Upsample\": Upsample.get_converter(opset),\n \"SpatialBN\": BatchNorm.get_converter(opset),\n # defs/generator\n # 'Constant' # Implemented\n # 'RandomUniform'\n # 'RandomNormal'\n # 'RandomUniformLike'\n # 'RandomNormalLike'\n # defs/logical\n # defs/math\n \"Add\": Add.get_converter(opset),\n \"Sub\": Sub.get_converter(opset),\n \"Mul\": Mul.get_converter(opset),\n \"Div\": Div.get_converter(opset),\n \"Neg\": Renamer(\"negative\"),\n \"Abs\": Absolute.get_converter(opset),\n \"Reciprocal\": Reciprocal.get_converter(opset),\n \"Floor\": Renamer(\"floor\"),\n \"Ceil\": Renamer(\"ceil\"),\n \"Round\": Renamer(\"round\"),\n \"IsInf\": Renamer(\"isinf\"),\n \"IsNaN\": Renamer(\"isnan\"),\n \"Sqrt\": Renamer(\"sqrt\"),\n \"Relu\": Renamer(\"relu\"),\n \"LeakyRelu\": Renamer(\"leaky_relu\"),\n \"Selu\": Selu.get_converter(opset),\n \"Elu\": Elu.get_converter(opset),\n \"Exp\": Renamer(\"exp\"),\n \"Greater\": Greater.get_converter(opset),\n \"Less\": Less.get_converter(opset),\n \"Log\": Renamer(\"log\"),\n \"ACos\": Renamer(\"acos\"),\n \"ACosh\": Renamer(\"acosh\"),\n \"ASin\": Renamer(\"asin\"),\n \"ASinh\": Renamer(\"asinh\"),\n \"ATan\": Renamer(\"atan\"),\n \"ATanh\": Renamer(\"atanh\"),\n \"Cos\": Renamer(\"cos\"),\n \"Cosh\": Renamer(\"cosh\"),\n \"Sin\": Renamer(\"sin\"),\n \"Sinh\": Renamer(\"sinh\"),\n \"Tan\": Renamer(\"tan\"),\n \"Tanh\": Renamer(\"tanh\"),\n \"Pow\": Renamer(\"power\"),\n \"PRelu\": Prelu.get_converter(opset),\n \"Sigmoid\": Renamer(\"sigmoid\"),\n \"HardSigmoid\": HardSigmoid.get_converter(opset),\n \"Max\": Maximum.get_converter(opset),\n \"Min\": Minimum.get_converter(opset),\n \"Sum\": Sum.get_converter(opset),\n \"Mean\": Mean.get_converter(opset),\n \"Clip\": Clip.get_converter(opset),\n \"Softplus\": Softplus.get_converter(opset),\n # softmax default axis is different in onnx\n \"Softmax\": Softmax.get_converter(opset),\n \"LogSoftmax\": AttrCvt(\"log_softmax\", {\"axis\": (\"axis\", 1)}),\n \"OneHot\": OneHot.get_converter(opset),\n # 'Hardmax'\n \"Softsign\": Softsign.get_converter(opset),\n \"Gemm\": Gemm.get_converter(opset),\n \"MatMul\": MatMul.get_converter(opset),\n \"Mod\": Mod.get_converter(opset),\n \"Xor\": Renamer(\"logical_xor\"),\n # defs/nn\n \"AveragePool\": AveragePool.get_converter(opset),\n \"LpPool\": LpPool.get_converter(opset),\n \"MaxPool\": MaxPool.get_converter(opset),\n \"MaxUnpool\": MaxUnpool.get_converter(opset),\n \"Conv\": Conv.get_converter(opset),\n \"ConvTranspose\": ConvTranspose.get_converter(opset),\n \"GlobalAveragePool\": Renamer(\"global_avg_pool2d\"),\n \"GlobalMaxPool\": Renamer(\"global_max_pool2d\"),\n \"BatchNormalization\": BatchNorm.get_converter(opset),\n \"InstanceNormalization\": InstanceNorm.get_converter(opset),\n # 'LpNormalization'\n \"Dropout\": AttrCvt(\"dropout\", {\"ratio\": \"rate\"}, ignores=[\"is_test\"]),\n \"Flatten\": Flatten.get_converter(opset),\n \"LRN\": LRN.get_converter(opset),\n # Recurrent Layers\n \"LSTM\": LSTM.get_converter(opset),\n \"GRU\": GRU.get_converter(opset),\n # defs/vision\n \"MaxRoiPool\": MaxRoiPool.get_converter(opset),\n \"RoiAlign\": RoiAlign.get_converter(opset),\n \"NonMaxSuppression\": NonMaxSuppression.get_converter(opset),\n # defs/reduction\n \"ReduceMax\": ReduceMax.get_converter(opset),\n \"ReduceMin\": ReduceMin.get_converter(opset),\n \"ReduceSum\": ReduceSum.get_converter(opset),\n \"ReduceMean\": ReduceMean.get_converter(opset),\n \"ReduceProd\": ReduceProd.get_converter(opset),\n \"ReduceLogSumExp\": ReduceLogSumExp.get_converter(opset),\n \"ReduceLogSum\": ReduceLogSum.get_converter(opset),\n \"ReduceSumSquare\": ReduceSumSquare.get_converter(opset),\n \"ReduceL1\": ReduceL1.get_converter(opset),\n \"ReduceL2\": ReduceL2.get_converter(opset),\n # defs/sorting\n \"ArgMax\": ArgMax.get_converter(opset),\n \"ArgMin\": ArgMin.get_converter(opset),\n \"TopK\": TopK.get_converter(opset),\n # defs/tensor\n \"Cast\": Cast.get_converter(opset),\n \"Reshape\": Reshape.get_converter(opset),\n \"Expand\": Expand.get_converter(opset),\n \"Concat\": Concat.get_converter(opset),\n \"Split\": Split.get_converter(opset),\n \"Slice\": Slice.get_converter(opset),\n \"Transpose\": AttrCvt(\"transpose\", {\"perm\": \"axes\"}),\n \"DepthToSpace\": DepthToSpace.get_converter(opset),\n \"SpaceToDepth\": SpaceToDepth.get_converter(opset),\n \"Gather\": Gather.get_converter(opset),\n \"GatherElements\": GatherElements.get_converter(opset),\n \"GatherND\": GatherND.get_converter(opset),\n \"Size\": AttrCvt(\"ndarray_size\", extras={\"dtype\": \"int64\"}),\n \"Scatter\": Scatter.get_converter(opset),\n \"ScatterElements\": Scatter.get_converter(opset),\n \"Squeeze\": AttrCvt(\"squeeze\", {\"axes\": \"axis\"}),\n \"Unsqueeze\": Unsqueeze.get_converter(opset),\n \"Pad\": Pad.get_converter(opset),\n \"Shape\": Shape.get_converter(opset),\n \"Sign\": Sign.get_converter(opset),\n \"Equal\": Equal.get_converter(opset),\n \"Not\": Not.get_converter(opset),\n \"And\": And.get_converter(opset),\n \"Tile\": Tile.get_converter(opset),\n \"Erf\": Erf.get_converter(opset),\n \"Where\": Where.get_converter(opset),\n \"Or\": Or.get_converter(opset),\n \"Resize\": Resize.get_converter(opset),\n \"NonZero\": NonZero.get_converter(opset),\n \"Range\": Range.get_converter(opset),\n # defs/control_flow\n \"Loop\": Loop.get_converter(opset),\n \"If\": If.get_converter(opset),\n }\n\n\nclass GraphProto:\n \"\"\"A helper class for handling Relay expression copying from pb2.GraphProto.\n Definition: https://github.com/onnx/onnx/blob/master/onnx/onnx.proto\n\n Parameters\n ----------\n shape : dict of str to tuple, optional\n The input shape to the graph\n\n dtype : str or dict of str to str\n The input types to the graph\n \"\"\"\n\n current = None\n\n def __init__(self, shape, dtype):\n self._nodes = {}\n self._params = {}\n self._inputs = {}\n self._renames = {}\n self._num_input = 0\n self._num_param = 0\n self._shape = shape if shape else {}\n self._dtype = dtype\n self.opset = None\n\n def __enter__(self):\n self._old_manager = GraphProto.current\n GraphProto.current = self\n return self\n\n def __exit__(self, ptype, value, trace):\n GraphProto.current = self._old_manager\n\n def freeze(self, func, params):\n bind_map = {}\n for name in params.keys():\n if name in self._nodes.keys():\n bind_map[self._nodes[name]] = _expr.const(params[name])\n body = _expr.bind(func.body, bind_map)\n fn = _function.Function(analysis.free_vars(body), body)\n return fn, {}\n\n def from_onnx(self, graph, opset, freeze_params=False, get_output_expr=False):\n \"\"\"Construct Relay expression from ONNX graph.\n\n Onnx graph is a python protobuf object.\n The companion parameters will be handled automatically.\n However, the input names from onnx graph is vague, mixing inputs and\n network weights/bias such as \"1\", \"2\"...\n For convenience, we rename the `real` input names to \"input_0\",\n \"input_1\"... And renaming parameters to \"param_0\", \"param_1\"...\n\n Parameters\n ----------\n graph : onnx protobuf object\n The loaded onnx graph\n\n opset : opset version\n\n freeze_params: bool\n If this parameter is true, the importer will take any provided\n onnx input values (weights, shapes, etc) and embed them into the relay model\n as Constants instead of variables. This allows more aggressive optimizations\n at compile time and helps in making models static if certain inputs represent\n attributes relay would traditionally consider compile-time constants.\n\n get_output_expr: bool\n If set to true, this conversion will return each output expression rather\n than a packaged module. This can be useful when converting subgraphs to\n relay.\n\n Returns\n -------\n mod : tvm.IRModule\n The returned relay module\n\n params : dict\n A dict of name: tvm.nd.array pairs, used as pretrained weights\n \"\"\"\n self.opset = opset\n # parse network inputs to relay, aka parameters\n for init_tensor in graph.initializer:\n if not init_tensor.name.strip():\n raise ValueError(\"Tensor's name is required.\")\n self._params[init_tensor.name] = self._parse_array(init_tensor)\n self._nodes[init_tensor.name] = new_var(\n init_tensor.name,\n shape=self._params[init_tensor.name].shape,\n dtype=self._params[init_tensor.name].dtype,\n )\n for i in graph.input:\n # from onnx v0.2, GraphProto.input has type ValueInfoProto,\n # and the name is 'i.name'\n i_name, i_shape, d_type, i_shape_name = get_info(i)\n if i_name in self._params:\n # i is a param instead of input\n self._num_param += 1\n self._params[i_name] = self._params.pop(i_name)\n self._nodes[i_name] = new_var(\n i_name, shape=self._params[i_name].shape, dtype=self._params[i_name].dtype\n )\n else:\n self._num_input += 1\n if i_name in self._shape:\n i_shape = self._shape[i_name]\n else:\n if \"?\" in str(i_shape):\n warning_msg = (\n \"Input %s has unknown dimension shapes: %s. \"\n \"Specifying static values may improve performance\"\n % (i_name, str(i_shape_name))\n )\n warnings.warn(warning_msg)\n if isinstance(self._dtype, dict):\n dtype = self._dtype[i_name] if i_name in self._dtype else d_type\n else:\n dtype = d_type\n self._nodes[i_name] = new_var(i_name, shape=i_shape, dtype=dtype)\n self._inputs[i_name] = self._nodes[i_name]\n # get list of unsupported ops\n convert_map = _get_convert_map(opset)\n unsupported_ops = set()\n for node in graph.node:\n op_name = node.op_type\n if (\n op_name not in convert_map\n and op_name != \"Constant\"\n and op_name not in _identity_list\n ):\n unsupported_ops.add(op_name)\n if unsupported_ops:\n msg = \"The following operators are not supported for frontend ONNX: \"\n msg += \", \".join(unsupported_ops)\n raise tvm.error.OpNotImplemented(msg)\n # construct nodes, nodes are stored as directed acyclic graph\n for node in graph.node:\n op_name = node.op_type\n attr = self._parse_attr(node.attribute)\n # Create and populate onnx input object.\n inputs = onnx_input()\n for i in node.input:\n if i != \"\":\n inputs[i] = self._nodes[self._renames.get(i, i)]\n if op_name == \"Constant\":\n t_proto = self._parse_attr(node.attribute)[\"value\"]\n self._num_param += 1\n # We should convert scalar integers to int32, to normalize.\n array = self._parse_array(t_proto)\n self._params[node.output[0]] = array\n self._nodes[node.output[0]] = new_var(\n node.output[0], shape=list(t_proto.dims), dtype=array.dtype\n )\n else:\n i_name = self._parse_value_proto(node)\n node_output = self._fix_outputs(op_name, node.output)\n attr[\"tvm_custom\"] = {}\n attr[\"tvm_custom\"][\"name\"] = i_name\n attr[\"tvm_custom\"][\"num_outputs\"] = len(node_output)\n\n op = self._convert_operator(op_name, inputs, attr, opset)\n if not isinstance(op, _expr.TupleWrapper):\n outputs_num = 1\n else:\n outputs_num = len(op)\n assert (\n len(node_output) == outputs_num\n ), \"Number of output mismatch {} vs {} in {}.\".format(\n len(node_output), outputs_num, op_name\n )\n if outputs_num == 1:\n self._nodes[node_output[0]] = op\n else:\n for k, i in zip(list(node_output), range(len(node_output))):\n self._nodes[k] = op[i]\n\n # now return the outputs\n outputs = [self._nodes[self._parse_value_proto(i)] for i in graph.output]\n outputs = outputs[0] if len(outputs) == 1 else _expr.Tuple(outputs)\n # If requested, directly return the converted expressions.\n if get_output_expr:\n return outputs\n ## Maintain the order of inputs and parameters from the ONNX graph, but only include\n ## those parameters that are needed to execute the relay graph\n free_vars = analysis.free_vars(outputs)\n nodes = {v: k for k, v in self._nodes.items()}\n free_vars = [nodes[var] for var in free_vars]\n for i_name in self._params:\n if i_name in free_vars and i_name not in self._inputs:\n self._inputs[i_name] = self._nodes[i_name]\n # Create a function from our output expression and all input variables.\n func = _function.Function([v for k, v in self._inputs.items()], outputs)\n if freeze_params:\n func, params = self.freeze(func, self._params)\n return IRModule.from_expr(func), params\n return IRModule.from_expr(func), self._params\n\n def _parse_value_proto(self, value_proto):\n \"\"\"Parse ValueProto or raw str.\"\"\"\n try:\n name = value_proto.name\n except AttributeError:\n name = value_proto\n return name\n\n def _parse_array(self, tensor_proto):\n np_array = get_numpy(tensor_proto).reshape(tuple(tensor_proto.dims))\n return _nd.array(np_array)\n\n def _parse_attr(self, attr_proto):\n \"\"\"Convert a list of AttributeProto to a dict, with names as keys.\"\"\"\n attrs = {}\n for a in attr_proto:\n for f in [\"f\", \"i\", \"s\", \"g\"]:\n if a.HasField(f):\n attrs[a.name] = getattr(a, f)\n for f in [\"floats\", \"ints\", \"strings\"]:\n if list(getattr(a, f)):\n assert a.name not in attrs, \"Only one type of attr is allowed\"\n attrs[a.name] = tuple(getattr(a, f))\n for f in [\"t\"]:\n if a.HasField(f):\n attrs[a.name] = getattr(a, f)\n for f in [\"tensors\"]:\n if list(getattr(a, f)):\n assert a.name not in attrs, \"Only one type of attr is allowed\"\n attrs[a.name] = tuple(getattr(a, f))\n for f in [\"graphs\"]:\n if list(getattr(a, f)):\n raise NotImplementedError(\"Field {} is not supported in relay.\".format(f))\n if a.name not in attrs:\n raise ValueError(\"Cannot parse attribute: \\n{}\\n.\".format(a))\n return attrs\n\n def _convert_operator(self, op_name, inputs, attrs, opset):\n \"\"\"Convert ONNX operator into a Relay operator.\n The converter must specify conversions explicitly for incompatible name, and\n apply handlers to operator attributes.\n\n Parameters\n ----------\n op_name : str\n Operator name, such as Convolution, FullyConnected\n inputs : list of tvm.relay.function.Function\n List of inputs.\n attrs : dict\n Dict of operator attributes\n opset : int\n Opset version\n\n Returns\n -------\n sym : tvm.relay.function.Function\n Converted relay function\n \"\"\"\n convert_map = _get_convert_map(opset)\n if op_name in _identity_list:\n sym = get_relay_op(op_name)(*inputs, **attrs)\n elif op_name in convert_map:\n sym = convert_map[op_name](inputs, attrs, self._params)\n else:\n raise NotImplementedError(\"Operator {} not implemented.\".format(op_name))\n return sym\n\n def _fix_outputs(self, op_name, outputs):\n \"\"\"A hack to handle dropout or similar operator that have more than one out\n in ONNX.\n \"\"\"\n if op_name == \"Dropout\":\n if len(outputs) == 1:\n return outputs\n # TODO(zhreshold): support dropout mask?\n outputs = outputs[:-1]\n return outputs\n\n\ndef from_onnx(model, shape=None, dtype=\"float32\", opset=None, freeze_params=False):\n \"\"\"Convert a ONNX model into an equivalent Relay Function.\n\n ONNX graphs are represented as Python Protobuf objects.\n The companion parameters will be handled automatically.\n However, the input names from onnx graph is vague, mixing inputs and\n network weights/bias such as \"1\", \"2\"...\n For convenience, we rename the `real` input names to \"input_0\",\n \"input_1\"... And renaming parameters to \"param_0\", \"param_1\"...\n\n By default, ONNX defines models in terms of dynamic shapes. The ONNX importer\n retains that dynamism upon import, and the compiler attempts to convert the\n model into a static shapes at compile time. If this fails, there may still\n be dynamic operations in the model. Not all TVM kernels currently support\n dynamic shapes, please file an issue on discuss.tvm.apache.org\n if you hit an error with dynamic kernels.\n\n Parameters\n ----------\n model : protobuf object\n ONNX ModelProto after ONNX v1.1.0\n\n shape : dict of str to tuple, optional\n The input shape to the graph\n\n dtype : str or dict of str to str\n The input types to the graph\n\n opset : int, optional\n Override to autodetected opset.\n This can be helpful for some testing.\n\n freeze_params: bool\n If this parameter is true, the importer will take any provided\n onnx input values (weights, shapes, etc) and embed them into the relay model\n as Constants instead of variables. This allows more aggressive optimizations\n at compile time and helps in making models static if certain inputs represent\n attributes relay would traditionally consider compile-time constants.\n\n Returns\n -------\n mod : tvm.IRModule\n The relay module for compilation\n\n params : dict of str to tvm.nd.NDArray\n The parameter dict to be used by relay\n \"\"\"\n try:\n import onnx\n\n if hasattr(onnx.checker, \"check_model\"):\n # try use onnx's own model checker before converting any model\n try:\n onnx.checker.check_model(model)\n except onnx.onnx_cpp2py_export.checker.ValidationError as e: # pylint: disable=c-extension-no-member\n # the checker is a bit violent about errors, so simply print warnings here\n warnings.warn(str(e))\n except ImportError:\n pass\n g = GraphProto(shape, dtype)\n graph = model.graph\n if opset is None:\n try:\n opset = model.opset_import[0].version if model.opset_import else 1\n except AttributeError:\n opset = 1\n # Use the graph proto as a scope so that ops can access other nodes if needed.\n with g:\n mod, params = g.from_onnx(graph, opset, freeze_params)\n return mod, params\n"
]
| [
[
"numpy.array",
"numpy.zeros",
"numpy.iinfo",
"numpy.prod"
]
]
|
WeiXuanChan/heartFEM | [
"7f26c71434919c3141fac600f08685e5383e7137"
]
| [
"heartFEM/lcleeHeart/vtk_py/addLocalFiberOrientation.py"
]
| [
"########################################################################\n\nimport sys\nimport math\nimport numpy\nimport vtk\nfrom random import uniform as randuniform\nfrom heartFEM.lcleeHeart.vtk_py.addLocalFiberOrientation import *\nfrom heartFEM.lcleeHeart.vtk_py.addLocalProlateSpheroidalDirections import *\nfrom heartFEM.lcleeHeart.vtk_py.createFloatArray import *\nfrom heartFEM.lcleeHeart.vtk_py.getABPointsFromBoundsAndCenter import *\nfrom heartFEM.lcleeHeart.vtk_py.readSTL import *\nfrom heartFEM.lcleeHeart.vtk_py.readUGrid import *\nfrom heartFEM.lcleeHeart.vtk_py.writeUGrid import *\n\n########################################################################\ndef normalDistribution(x,mu,sigma):\n if sigma==0.:\n if x==mu:\n return 1.\n else:\n return 0.\n return numpy.exp(-((x-mu)/sigma)**2./2.)/(sigma* 2.5066282746310002)\ndef randomWithNearby(randFunc,x,mu,sigma,numtry=10):\n if isinstance(randFunc,(int,float)):\n return randFunc\n randVal=numpy.zeros(10)\n probVal=numpy.zeros(10)\n randVal[0]=randFunc()\n probVal[0]=normalDistribution(randVal[0],mu,sigma)\n for n in range(1,numtry):\n randVal[n]=randFunc()\n probVal[n]=normalDistribution(randVal[n],mu,sigma)+probVal[n-1]\n return randVal[numpy.argmax(randuniform(0,probVal[-1])<=probVal)]\nclass angleAssignment:\n def __new__(cls, *args, **kwargs):\n return super().__new__(cls)\n def __init__(self,angle):\n if isinstance(angle,(float,int)):\n self.type=\"constant\"\n self.angle=angle\n elif isinstance(angle,str):\n #data arranged as x,y,z,angle\n self.angle=numpy.loadtxt(angle)\n self.type=\"reference\"\n def __call__(self,*args):\n if self.type==\"constant\":\n return self.angle\n elif self.type==\"reference\":\n #args[0]=[x,y,z], args[1]=normvector x,y,z\n coord=numpy.array(args[0])\n disVec=self.angle[:,:3]-coord.reshape((1,3))\n if len(args)>1:\n normvector=numpy.array(args[1])/numpy.linalg.norm(args[1])\n dis=numpy.linalg.norm(numpy.cross(disVec,normvector),axis=1)\n else:\n dis=numpy.linalg.norm(disVec,axis=1)\n return self.angle[numpy.argmin(dis),3]\n \ndef addLocalFiberOrientation(ugrid_wall,\n fiber_angle_end_input,\n fiber_angle_epi_input,\n points_AB=None,\n fiberSheetletAngle=0., #can be a function(coord=), include **kwargs in input\n fiberSheetletWidth=0., #can be a class with __call__(coord=,sheetlet_angle=), include **kwargs in input and self.max=max_width\n radialFiberAngle=0., #can be a function(coord=), include **kwargs in input\n fiberLength=0., #can be a class with __call__(coord=,fiber_radial_angle=), include **kwargs in input and self.max=max_length\n verbose=True):\n\n if (verbose): print ('*** addLocalFiberOrientation ***')\n \n if (points_AB == None):\n points_AB = getABPointsFromBoundsAndCenter(ugrid_wall, verbose)\n assert (points_AB.GetNumberOfPoints() >= 2), \"\\\"points_AB\\\" must have at least two points. Aborting.\"\n point_A = numpy.array([0.]*3)\n point_B = numpy.array([0.]*3)\n points_AB.GetPoint( 0, point_A)\n points_AB.GetPoint(points_AB.GetNumberOfPoints()-1, point_B)\n distAB = point_B - point_A\n longitudinalLength=numpy.linalg.norm(distAB)\n eL = distAB/longitudinalLength\n\n if (verbose): print (\"Computing local fiber orientation...\")\n fiber_angle_end=angleAssignment(fiber_angle_end_input)\n fiber_angle_epi=angleAssignment(fiber_angle_epi_input)\n \n farray_norm_dist_end = ugrid_wall.GetCellData().GetArray(\"norm_dist_end\")\n farray_norm_dist_epi = ugrid_wall.GetCellData().GetArray(\"norm_dist_epi\")\n farray_eRR = ugrid_wall.GetCellData().GetArray(\"eRR\")\n farray_eCC = ugrid_wall.GetCellData().GetArray(\"eCC\")\n farray_eLL = ugrid_wall.GetCellData().GetArray(\"eLL\")\n\n nb_cells = ugrid_wall.GetNumberOfCells()\n\n farray_fiber_angle = createFloatArray(\"fiber_angle\", 1, nb_cells)\n farray_fiber_radial_angle=createFloatArray(\"fiber_radial_angle\", 1, nb_cells)\n farray_radialPos=createFloatArray(\"fiber_radial_position\", 1, nb_cells)\n farray_sheetlet_angle=createFloatArray(\"fiber_sheetlet_angle\", 1, nb_cells)\n farray_sheeletPos=createFloatArray(\"fiber_sheetlet_position\", 1, nb_cells)\n farray_fiber_shift_towards_endo=createFloatArray(\"fiber_shift_towards_endo\", 1, nb_cells)\n farray_fiber_normDensity = createFloatArray(\"fiber_normDensity\", 1, nb_cells)\n farray_eF = createFloatArray(\"fiber vectors\", 3, nb_cells)\n farray_eS = createFloatArray(\"sheet vectors\", 3, nb_cells)\n farray_eN = createFloatArray(\"sheet normal vectors\", 3, nb_cells)\n \n \n # LCL hack to have homogeneous fibers near apex\n #bds = ugrid_wall.GetBounds()\n #center = vtk.vtkCellCenters()\n #center.SetInputData(ugrid_wall)\n #center.Update()\n ###############################################\n cell_centers=[]\n for num_cell in range(nb_cells):\n cell_centers.append(numpy.array(ugrid_wall.GetPoints().GetPoint(num_cell)))\n cell_centers=numpy.array(cell_centers)\n \n \n for num_cell in range(nb_cells):\n norm_dist_end = farray_norm_dist_end.GetTuple(num_cell)[0]\n norm_dist_epi = farray_norm_dist_epi.GetTuple(num_cell)[0]\n \n eRR = numpy.array(farray_eRR.GetTuple(num_cell))\n eCC = numpy.array(farray_eCC.GetTuple(num_cell))\n eLL = numpy.array(farray_eLL.GetTuple(num_cell))\n if fiberSheetletAngle==0. and radialFiberAngle==0.:\n fiber_angle_in_degrees = (1.-norm_dist_end) * fiber_angle_end(cell_centers[num_cell]) + (1.-norm_dist_epi) * fiber_angle_epi(cell_centers[num_cell])\n farray_fiber_angle.InsertTuple(num_cell, [fiber_angle_in_degrees])\n \n fiber_angle_in_radians = math.pi*fiber_angle_in_degrees/180\n eF = math.cos(fiber_angle_in_radians) * eCC + math.sin(fiber_angle_in_radians) * eLL\n eS = eRR\n eN = numpy.cross(eF, eS)\n fiber_radial_angle=0.\n radialPos=0.\n sheetlet_angle=0.\n sheeletPos=0.\n sheeletShifttowardsEndo=0.\n fdensity=1.\n else:\n #get nearby\n if isinstance(fiberSheetletWidth,(int,float)):\n temp_fiberSheetletWidth=fiberSheetletWidth\n else:\n temp_fiberSheetletWidth=fiberSheetletWidth.max\n if isinstance(fiberLength,(int,float)):\n temp_fiberLength=fiberLength\n else:\n temp_fiberLength=fiberLength.max\n maxNearbyRadius=max(temp_fiberSheetletWidth,temp_fiberLength)\n if maxNearbyRadius>0 and fiberSheetletWidth!=0 and fiberLength!=0 and not(isinstance(fiberSheetletAngle,(int,float))):\n if num_cell>0:\n temp_cell_centers=cell_centers[:num_cell].copy()\n temp_cell_centers_Index=numpy.arange(num_cell)\n celldist=numpy.linalg.norm(numpy.cross(temp_cell_centers-cell_centers[num_cell],eRR),axis=1)\n temp_cell_centers=temp_cell_centers[celldist<maxNearbyRadius].copy()\n if len(temp_cell_centers)>0:\n temp_cell_centers_Index=temp_cell_centers_Index[celldist<maxNearbyRadius].copy()\n \n cir_dist=numpy.dot(temp_cell_centers-cell_centers[num_cell],eCC)\n norm_cir_dist=np.zeros(len(temp_cell_centers_Index))\n for n in range(len(temp_cell_centers_Index)):\n temp_radialPos=farray_radialPos.GetTuple(temp_cell_centers_Index[n])[0]\n temp_fiber_radial_angle=farray_fiber_radial_angle.GetTuple(temp_cell_centers_Index[n])[0]\n if isinstance(fiberLength,(int,float)):\n temp_fiberLength=fiberLength\n else:\n temp_fiberLength=fiberLength(coord=cell_centers_Index[n],fiber_radial_angle=temp_fiber_radial_angle)\n if cir_dist[n]>0.:\n norm_cir_dist[n]=cir_dist[n]/numpy.abs(0.5*temp_fiberLength*math.cos(math.pi*temp_fiber_radial_angle/180)+temp_radialPos)\n elif cir_dist[n]<0.:\n norm_cir_dist[n]=cir_dist[n]/numpy.abs(0.5*temp_fiberLength*math.cos(math.pi*temp_fiber_radial_angle/180)-temp_radialPos)\n \n longi_dist=numpy.dot(temp_cell_centers-cell_centers[num_cell],eLL)\n norm_longi_dist=np.zeros(len(temp_cell_centers_Index))\n for n in range(len(temp_cell_centers_Index)):\n temp_sheeletPos=farray_sheeletPos.GetTuple(temp_cell_centers_Index[n])[0]\n temp_sheetlet_angle=farray_sheetlet_angle.GetTuple(temp_cell_centers_Index[n])[0]\n if isinstance(fiberSheetletWidth,(int,float)):\n temp_fiberSheetletWidth=fiberSheetletWidth\n else:\n temp_fiberSheetletWidth=fiberSheetletWidth(coord=cell_centers_Index[n],sheetlet_angle=temp_sheetlet_angle)\n if longi_dist[n]>0.:\n norm_longi_dist[n]=longi_dist[n]/numpy.abs(0.5*temp_fiberSheetletWidth*math.cos(math.pi*temp_sheetlet_angle/180)+temp_sheeletPos)\n elif longi_dist[n]<0.:\n norm_longi_dist[n]=longi_dist[n]/numpy.abs(0.5*temp_fiberSheetletWidth*math.cos(math.pi*temp_sheetlet_angle/180)-temp_sheeletPos)\n \n norm_celldist=numpy.sqrt(norm_cir_dist**2.+norm_longi_dist**2.)\n followrandset=randuniform(0,1)\n temp_cell_centers=temp_cell_centers[norm_celldist<=followrandset]\n temp_cell_centers_Index=temp_cell_centers_Index[norm_celldist<=followrandset]\n norm_celldist=norm_celldist[norm_celldist<=followrandset]\n if len(temp_cell_centers)>0:\n minInd=numpy.argmin(norm_celldist)\n fiber_radial_angle=farray_fiber_radial_angle.GetTuple(temp_cell_centers_Index[minInd])[0]\n ref_radialPos=farray_radialPos.GetTuple(temp_cell_centers_Index[minInd])[0]\n radialPos=ref_radialPos-numpy.dot(temp_cell_centers[minInd]-cell_centers[num_cell],eCC)\n sheetlet_angle=farray_sheetlet_angle.GetTuple(temp_cell_centers_Index[minInd])[0]\n ref_sheeletPos=farray_sheeletPos.GetTuple(temp_cell_centers_Index[minInd])[0]\n sheeletPos=ref_sheeletPos-numpy.dot(temp_cell_centers[minInd]-cell_centers[num_cell],eLL)\n sheeletShifttowardsEndo=sheeletPos*math.tan(math.pi*sheetlet_angle/180)-radialPos*math.tan(math.pi*fiber_radial_angle/180)\n else:\n if isinstance(radialFiberAngle,(int,float)):\n fiber_radial_angle=radialFiberAngle\n else:\n fiber_radial_angle=radialFiberAngle(coord=cell_centers[num_cell])\n if isinstance(fiberLength,(int,float)):\n temp_fiberLength=fiberLength\n else:\n temp_fiberLength=fiberLength(coord=cell_centers[num_cell],fiber_radial_angle=temp_fiber_radial_angle)\n temp_radialFiberCirHalfLength=0.5*temp_fiberLength*math.cos(math.pi*fiber_radial_angle/180)\n radialPos=randuniform(-temp_radialFiberCirHalfLength,temp_radialFiberCirHalfLength)\n if isinstance(fiberSheetletAngle,(int,float)):\n sheetlet_angle=fiberSheetletAngle\n else:\n sheetlet_angle=fiberSheetletAngle(coord=cell_centers[num_cell])\n if isinstance(fiberSheetletWidth,(int,float)):\n temp_fiberSheetletWidth=fiberSheetletWidth\n else:\n temp_fiberSheetletWidth=fiberSheetletWidth(coord=cell_centers[num_cell],sheetlet_angle=temp_sheetlet_angle)\n temp_sheetLongiHalfLength=0.5*temp_fiberSheetletWidth*math.cos(math.pi*sheetlet_angle/180)\n sheeletPos=randuniform(-temp_sheetLongiHalfLength,temp_sheetLongiHalfLength)\n sheeletShifttowardsEndo=sheeletPos*math.tan(math.pi*sheetlet_angle/180)-radialPos*math.tan(math.pi*fiber_radial_angle/180)\n else:\n if isinstance(radialFiberAngle,(int,float)):\n fiber_radial_angle=radialFiberAngle\n else:\n fiber_radial_angle=radialFiberAngle(coord=cell_centers[num_cell])\n if isinstance(fiberLength,(int,float)):\n temp_fiberLength=fiberLength\n else:\n temp_fiberLength=fiberLength(coord=cell_centers[num_cell],fiber_radial_angle=temp_fiber_radial_angle)\n temp_radialFiberCirHalfLength=0.5*temp_fiberLength*math.cos(math.pi*fiber_radial_angle/180)\n radialPos=randuniform(-temp_radialFiberCirHalfLength,temp_radialFiberCirHalfLength)\n if isinstance(fiberSheetletAngle,(int,float)):\n sheetlet_angle=fiberSheetletAngle\n else:\n sheetlet_angle=fiberSheetletAngle(coord=cell_centers[num_cell])\n if isinstance(fiberSheetletWidth,(int,float)):\n temp_fiberSheetletWidth=fiberSheetletWidth\n else:\n temp_fiberSheetletWidth=fiberSheetletWidth(coord=cell_centers[num_cell],sheetlet_angle=temp_sheetlet_angle)\n temp_sheetLongiHalfLength=0.5*temp_fiberSheetletWidth*math.cos(math.pi*sheetlet_angle/180)\n sheeletPos=randuniform(-temp_sheetLongiHalfLength,temp_sheetLongiHalfLength)\n sheeletShifttowardsEndo=sheeletPos*math.tan(math.pi*sheetlet_angle/180)-radialPos*math.tan(math.pi*fiber_radial_angle/180)\n fiberRaidalAngle_in_radians=math.pi*fiber_radial_angle/180\n fiberSheetletAngle_in_radians=math.pi*sheetlet_angle/180\n adjusted_norm_dist_end=norm_dist_end+sheeletShifttowardsEndo\n adjusted_norm_dist_epi=norm_dist_epi-sheeletShifttowardsEndo\n fiber_angle_in_degrees = max(0,min(1,1.-adjusted_norm_dist_end)) * fiber_angle_end(cell_centers[num_cell]) + max(0,min(1,1.-adjusted_norm_dist_epi)) * fiber_angle_epi(cell_centers[num_cell])\n if adjusted_norm_dist_end>1 or adjusted_norm_dist_end<0:\n fdensity=0.\n else:\n fdensity=1.\n \n farray_fiber_angle.InsertTuple(num_cell, [fiber_angle_in_degrees])\n \n\n fiber_angle_in_radians = math.pi*fiber_angle_in_degrees/180\n temp_eF = math.cos(fiber_angle_in_radians) * eCC + math.sin(fiber_angle_in_radians) * eLL\n temp_eS = eRR\n temp_eN = numpy.cross(temp_eF, temp_eS)\n \n eF=math.cos(fiberRaidalAngle_in_radians) * temp_eF + math.sin(fiberRaidalAngle_in_radians) * eRR\n temp_eS = math.cos(fiberRaidalAngle_in_radians) * eRR - math.sin(fiberRaidalAngle_in_radians) * temp_eF\n \n eN=math.cos(fiberSheetletAngle_in_radians) * temp_eN + math.sin(fiberSheetletAngle_in_radians) * temp_eS\n eS=math.cos(fiberSheetletAngle_in_radians) * temp_eS - math.sin(fiberSheetletAngle_in_radians) * temp_eN\n \n farray_eF.InsertTuple(num_cell, eF)\n farray_eS.InsertTuple(num_cell, eS)\n farray_eN.InsertTuple(num_cell, eN)\n farray_fiber_radial_angle.InsertTuple(num_cell, [fiber_radial_angle])\n farray_radialPos.InsertTuple(num_cell, [radialPos])\n farray_sheetlet_angle.InsertTuple(num_cell, [sheetlet_angle])\n farray_sheeletPos.InsertTuple(num_cell, [sheeletPos])\n farray_fiber_shift_towards_endo.InsertTuple(num_cell, [sheeletShifttowardsEndo])\n farray_fiber_normDensity.InsertTuple(num_cell, [fdensity])\n \n\n if (verbose): print (\"Filling mesh...\")\n\n ugrid_wall.GetCellData().AddArray(farray_fiber_angle)\n ugrid_wall.GetCellData().AddArray(farray_fiber_radial_angle)\n ugrid_wall.GetCellData().AddArray(farray_radialPos)\n ugrid_wall.GetCellData().AddArray(farray_sheetlet_angle)\n ugrid_wall.GetCellData().AddArray(farray_sheeletPos)\n ugrid_wall.GetCellData().AddArray(farray_fiber_shift_towards_endo)\n ugrid_wall.GetCellData().AddArray(farray_fiber_normDensity)\n ugrid_wall.GetCellData().AddArray(farray_eF)\n ugrid_wall.GetCellData().AddArray(farray_eS)\n ugrid_wall.GetCellData().AddArray(farray_eN)\n\nif (__name__ == \"__main__\"):\n assert (len(sys.argv) in [4]), \"Number of arguments must be 3. Aborting.\"\n basename = sys.argv[1]\n ugrid_wall = readUGrid(basename + \"-Mesh.vtk\")\n pdata_end = readSTL(basename + \"-End.stl\")\n pdata_epi = readSTL(basename + \"-Epi.stl\")\n angle_end = float(sys.argv[2])\n angle_epi = float(sys.argv[3])\n addLocalProlateSpheroidalDirections(ugrid_wall, pdata_end, pdata_epi)\n addLocalFiberOrientation(ugrid_wall, angle_end, angle_epi)\n writeUGrid(ugrid_wall, basename + \"-Mesh.vtk\")\n"
]
| [
[
"numpy.dot",
"numpy.sqrt",
"numpy.arange",
"numpy.linalg.norm",
"numpy.argmin",
"numpy.cross",
"numpy.array",
"numpy.exp",
"numpy.zeros",
"numpy.loadtxt"
]
]
|
petercorke/machinevision-toolbox-python | [
"d7e465575ad3c512387e9486b3b556dc9faa43cf"
]
| [
"machinevisiontoolbox/ImageProcessingKernel.py"
]
| [
"#!/usr/bin/env python\n\nimport numpy as np\nimport spatialmath.base.argcheck as argcheck\nimport cv2 as cv\nimport scipy as sp\n\nfrom scipy import signal\n\n\nclass ImageProcessingKernelMixin:\n \"\"\"\n Image processing kernel operations on the Image class\n \"\"\"\n\n @staticmethod\n def kgauss(sigma, hw=None):\n \"\"\"\n Gaussian kernel\n\n :param sigma: standard deviation of Gaussian kernel\n :type sigma: float\n :param hw: width of the kernel\n :type hw: integer\n :return k: kernel\n :rtype: numpy array (N,H)\n\n - ``IM.kgauss(sigma)`` is a 2-dimensional Gaussian kernel of standard\n deviation ``sigma``, and centred within the matrix ``k`` whose\n half-width is ``hw=2*sigma`` and ``w=2*hw+1``.\n\n - ``IM.kgauss(sigma, hw)`` as above but the half-width ``hw`` is\n specified.\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - The volume under the Gaussian kernel is one.\n \"\"\"\n\n # make sure sigma, w are valid input\n if hw is None:\n hw = np.ceil(3 * sigma)\n\n wi = np.arange(-hw, hw + 1)\n x, y = np.meshgrid(wi, wi)\n\n m = 1.0 / (2.0 * np.pi * sigma ** 2) * \\\n np.exp(-(np.power(x, 2) + np.power(y, 2)) / 2.0 / sigma ** 2)\n # area under the curve should be 1, but the discrete case is only\n # an approximation\n return m / np.sum(m)\n\n @staticmethod\n def klaplace():\n r\"\"\"\n Laplacian kernel\n\n :return k: kernel\n :rtype: numpy array (3,3)\n\n - ``IM.klaplace()`` is the Laplacian kernel:\n\n .. math::\n\n K = \\begin{bmatrix}\n 0 & 1 & 0 \\\\\n 1 & -4 & 1 \\\\\n 0 & 1 & 0\n \\end{bmatrix}\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - This kernel has an isotropic response to image gradient.\n \"\"\"\n return np.array([[0, 1, 0],\n [1, -4, 1],\n [0, 1, 0]])\n\n @staticmethod\n def ksobel():\n r\"\"\"\n Sobel edge detector\n\n :return k: kernel\n :rtype: numpy array (3,3)\n\n - ``IM.ksobel()`` is the Sobel x-derivative kernel:\n\n .. math::\n\n K = \\frac{1}{8} \\begin{bmatrix}\n 1 & 0 & -1 \\\\\n 2 & 0 & -2 \\\\\n 1 & 0 & -1\n \\end{bmatrix}\n\n .. note::\n\n - This kernel is an effective vertical-edge detector\n - The y-derivative (horizontal-edge) kernel is K'\n \"\"\"\n return np.array([[1, 0, -1],\n [2, 0, -2],\n [1, 0, -1]]) / 8.0\n\n @staticmethod\n def kdog(sigma1, sigma2=None, hw=None):\n \"\"\"\n Difference of Gaussians kernel\n\n :param sigma1: standard deviation of first Gaussian kernel\n :type sigma1: float\n :param sigma2: standard deviation of second Gaussian kernel\n :type sigma2: float\n :param hw: half-width of Gaussian kernel\n :type hw: integer\n :return k: kernel\n :rtype: numpy array\n\n - ``IM.kdog(sigma1)`` is a 2-dimensional difference of Gaussian kernel\n equal to ``kgauss(sigma1) - kgauss(sigma2)``, where ``sigma1`` >\n ``sigma2. By default, ``sigma2 = 1.6 * sigma1``. The kernel is\n centred within the matrix ``k`` whose half-width ``hw = 3xsigma1``\n and full width of the kernel is ``2xhw+1``.\n\n - ``IM.kdog(sigma1, sigma2)`` as above but sigma2 is specified\n directly.\n\n - ``IM.kdog(sigma1, sigma2, hw)`` as above but the kernel half-width is\n specified\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - This kernel is similar to the Laplacian of Gaussian and is often\n used as an efficient approximation.\n \"\"\"\n\n # sigma1 > sigma2\n if sigma2 is None:\n sigma2 = 1.6 * sigma1\n else:\n if sigma2 > sigma1:\n t = sigma1\n sigma1 = sigma2\n sigma2 = t\n\n # thus, sigma2 > sigma1\n if hw is None:\n hw = np.ceil(3.0 * sigma1)\n\n m1 = self.kgauss(sigma1, hw) # thin kernel\n m2 = self.kgauss(sigma2, hw) # wide kernel\n\n return m2 - m1\n\n @staticmethod\n def klog(sigma, hw=None):\n \"\"\"\n Laplacian of Gaussian kernel\n\n :param sigma1: standard deviation of first Gaussian kernel\n :type sigma1: float\n :param hw: half-width of kernel\n :type hw: integer\n :return k: kernel\n :rtype: numpy array (2 * 3 * sigma + 1, 2 * 3 * sigma + 1)\n\n - ``IM.klog(sigma)`` is a 2-dimensional Laplacian of Gaussian kernel of\n width (standard deviation) sigma and centred within the matrix ``k``\n whose half-width is ``hw=3xsigma``, and ``w=2xhw+1``.\n\n - ``IM.klog(sigma, hw)`` as above but the half-width ``w`` is\n specified.\n\n Example:\n\n .. runblock:: pycon\n\n \"\"\"\n\n if hw is None:\n hw = np.ceil(3.0 * sigma)\n wi = np.arange(-hw, hw + 1)\n x, y = np.meshgrid(wi, wi)\n\n return 1.0 / (np.pi * sigma ** 4.0) * \\\n ((np.power(x, 2) + np.power(y, 2)) / (2.0 * sigma ** 2) - 1) * \\\n np.exp(-(np.power(x, 2) + np.power(y, 2)) / (2.0 * sigma ** 2))\n\n @staticmethod\n def kdgauss(sigma, hw=None):\n \"\"\"\n Derivative of Gaussian kernel\n\n :param sigma1: standard deviation of first Gaussian kernel\n :type sigma1: float\n :param hw: half-width of kernel\n :type hw: integer\n :return k: kernel\n :rtype: numpy array (2 * 3 * sigma + 1, 2 * 3 * sigma + 1)\n\n - ``IM.kdgauss(sigma)`` is a 2-dimensional derivative of Gaussian\n kernel ``(w,w)`` of width (standard deviation) sigma and centred\n within the matrix ``k`` whose half-width ``hw = 3xsigma`` and\n ``w=2xhw+1``.\n\n - ``IM.kdgauss(sigma, hw)`` as above but the half-width is explictly\n specified.\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - This kernel is the horizontal derivative of the Gaussian, dG/dx.\n - The vertical derivative, dG/dy, is k'.\n - This kernel is an effective edge detector.\n \"\"\"\n if hw is None:\n hw = np.ceil(3.0 * sigma)\n\n wi = np.arange(-hw, hw + 1)\n x, y = np.meshgrid(wi, wi)\n\n return -x / sigma ** 2 / (2.0 * np.pi) * \\\n np.exp(-np.power(x, 2) + np.power(y, 2) / 2.0 / sigma ** 2)\n\n @staticmethod\n def kcircle(r, hw=None):\n \"\"\"\n Circular structuring element\n\n :param r: radius of circle structuring element, or 2-vector (see below)\n :type r: float, 2-tuple or 2-element vector of floats\n :param hw: half-width of kernel\n :type hw: integer\n :return k: kernel\n :rtype: numpy array (2 * 3 * sigma + 1, 2 * 3 * sigma + 1)\n\n - ``IM.kcircle(r)`` is a square matrix ``(w,w)`` where ``w=2r+1`` of\n zeros with a maximal centred circular region of radius ``r`` pixels\n set to one.\n\n - ``IM.kcircle(r,w)`` as above but the dimension of the kernel is\n explicitly specified.\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - If ``r`` is a 2-element vector the result is an annulus of ones,\n and the two numbers are interpretted as inner and outer radii.\n \"\"\"\n\n # check valid input:\n if not argcheck.isscalar(r): # r.shape[1] > 1:\n r = argcheck.getvector(r)\n rmax = r.max()\n rmin = r.min()\n else:\n rmax = r\n\n if hw is not None:\n w = hw * 2 + 1\n elif hw is None:\n w = 2 * rmax + 1\n\n s = np.zeros((np.int(w), np.int(w)))\n c = np.floor(w / 2.0)\n\n if not argcheck.isscalar(r):\n s = self.kcircle(rmax, w) - self.kcircle(rmin, w)\n else:\n x = np.arange(w) - c\n X, Y = np.meshgrid(x, x)\n ll = np.where(np.round((X ** 2 + Y ** 2 - r ** 2) <= 0))\n s[ll] = 1\n return s\n\n def smooth(self, sigma, hw=None, optmode='same', optboundary='fill'):\n \"\"\"\n Smooth image\n\n :param sigma: standard deviation of the Gaussian kernel\n :type sigma: float\n :param hw: half-width of the kernel\n :type hw: float\n :param opt: convolution options np.convolve (see below)\n :type opt: string\n :return out: Image with smoothed image pixels\n :rtype: Image instance\n\n - ``IM.smooth(sigma)`` is the image after convolution with a Gaussian\n kernel of standard deviation ``sigma``\n\n - ``IM.smooth(sigma, hw)`` as above with kernel half-width ``hw``.\n\n - ``IM.smooth(sigma, opt)`` as above with options passed to np.convolve\n\n :options:\n\n - 'full' returns the full 2-D convolution (default)\n - 'same' returns OUT the same size as IM\n - 'valid' returns the valid pixels only, those where the kernel\n does not exceed the bounds of the image.\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - By default (option 'full') the returned image is larger than the\n passed image.\n - Smooths all planes of the input image.\n - The Gaussian kernel has a unit volume.\n - If input image is integer it is converted to float, convolved,\n then converted back to integer.\n \"\"\"\n\n if not argcheck.isscalar(sigma):\n raise ValueError(sigma, 'sigma must be a scalar')\n\n modeopt = {\n 'full': 'full',\n 'valid': 'valid',\n 'same': 'same'\n }\n if optmode not in modeopt:\n raise ValueError(optmode, 'opt is not a valid option')\n\n boundaryopt = {\n 'fill': 'fill',\n 'wrap': 'wrap',\n 'reflect': 'symm'\n }\n if optboundary not in boundaryopt:\n raise ValueError(optboundary, 'opt is not a valid option')\n\n is_int = False\n if np.issubdtype(self.dtype, np.integer):\n is_int = True\n img = self.float()\n else:\n img = self\n\n # make the smoothing kernel\n K = self.kgauss(sigma, hw)\n\n if img.iscolor:\n # could replace this with a nested list comprehension\n\n ims = []\n for im in img:\n o = np.dstack([signal.convolve2d(np.squeeze(im.image[:, :, i]),\n K,\n mode=modeopt[optmode],\n boundary=boundaryopt[\n optboundary])\n for i in range(im.numchannels)])\n ims.append(o)\n\n elif not img.iscolor:\n ims = []\n for im in img:\n ims.append(signal.convolve2d(im.image,\n K,\n mode=modeopt[optmode],\n boundary=boundaryopt[\n optboundary]))\n\n else:\n raise ValueError(self.iscolor, 'bad value for iscolor')\n\n if is_int:\n return self.__class__(ims).int()\n else:\n return self.__class__(ims)\n\n def sad(self, im2):\n \"\"\"\n Sum of absolute differences\n\n :param im2: image 2\n :type im2: numpy array\n :return out: sad\n :rtype out: scalar\n\n - ``IM.sad(im2)`` is the sum of absolute differences between the two\n equally sized image patches of image and ``im2``. The result is a\n scalar that indicates image similarity, a value of 0 indicates\n identical pixel patterns and is increasingly positive as image\n dissimilarity increases.\n\n Example:\n\n .. runblock:: pycon\n\n \"\"\"\n\n if not np.all(self.shape == im2.shape):\n raise ValueError(im2, 'im2 shape is not equal to self')\n\n # out = []\n # for im in self:\n # m = np.abs(im.image - im2.image)\n # out.append(np.sum(m))\n m = np.abs(self.image - im2.image)\n out = np.sum(m)\n return out\n\n def ssd(self, im2):\n \"\"\"\n Sum of squared differences\n\n :param im2: image 2\n :type im2: numpy array\n :return out: ssd\n :rtype out: scalar\n\n - ``IM.ssd(im2)`` is the sum of squared differences between the two\n equally sized image patches image and ``im2``. The result M is a\n scalar that indicates image similarity, a value of 0 indicates\n identical pixel patterns and is increasingly positive as image\n dissimilarity increases.\n\n Example:\n\n .. runblock:: pycon\n\n \"\"\"\n\n if not np.all(self.shape == im2.shape):\n raise ValueError(im2, 'im2 shape is not equal to im1')\n m = np.power((self.image - im2.image), 2)\n return np.sum(m)\n\n def ncc(self, im2):\n \"\"\"\n Normalised cross correlation\n\n :param im2: image 2\n :type im2: numpy array\n :return out: ncc\n :rtype out: scalar\n\n - ``IM.ncc(im2)`` is the normalized cross-correlation between the two\n equally sized image patches image and ``im2``. The result is a scalar\n in the interval -1 (non match) to 1 (perfect match) that indicates\n similarity.\n\n .. note::\n\n - A value of 1 indicates identical pixel patterns.\n - The ``ncc`` similarity measure is invariant to scale changes in\n image intensity.\n\n Example:\n\n .. runblock:: pycon\n\n \"\"\"\n if not np.all(self.shape == im2.shape):\n raise ValueError(im2, 'im2 shape is not equal to im1')\n\n denom = np.sqrt(np.sum(self.image ** 2) * np.sum(im2.image ** 2))\n\n if denom < 1e-10:\n return 0\n else:\n return np.sum(self.image * im2.image) / denom\n\n def zsad(self, im2):\n \"\"\"\n Zero-mean sum of absolute differences\n\n :param im2: image 2\n :type im2: numpy array\n :return out: zsad\n :rtype out: scalar\n\n - ``IM.zsad(im2)`` is the zero-mean sum of absolute differences between\n the two equally sized image patches image and ``im2``. The result is\n a scalar that indicates image similarity, a value of 0 indicates\n identical pixel patterns and is increasingly positive as image\n dissimilarity increases.\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - The ``zsad`` similarity measure is invariant to changes in image\n brightness offset.\n \"\"\"\n if not np.all(self.shape == im2.shape):\n raise ValueError(im2, 'im2 shape is not equal to im1')\n\n image = self.image - np.mean(self.image)\n image2 = im2.image - np.mean(im2.image)\n m = np.abs(image - image2)\n return np.sum(m)\n\n def zssd(self, im2):\n \"\"\"\n Zero-mean sum of squared differences\n\n :param im2: image 2\n :type im2: numpy array\n :return out: zssd\n :rtype out: scalar\n\n - ``IM.zssd(im1, im2)`` is the zero-mean sum of squared differences\n between the two equally sized image patches image and ``im2``. The\n result is a scalar that indicates image similarity, a value of 0\n indicates identical pixel patterns and is increasingly positive as\n image dissimilarity increases.\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - The ``zssd`` similarity measure is invariant to changes in image\n brightness offset.\n \"\"\"\n if not np.all(self.shape == im2.shape):\n raise ValueError(im2, 'im2 shape is not equal to im1')\n\n image = self.image - np.mean(self.image)\n image2 = im2.image - np.mean(im2.image)\n m = np.power(image - image2, 2)\n return np.sum(m)\n\n def zncc(self, im2):\n \"\"\"\n Zero-mean normalized cross correlation\n\n :param im2: image 2 :type im2: numpy array :return out: zncc :rtype\n out: scalar\n\n - ``IM.zncc(im2)`` is the zero-mean normalized cross-correlation\n between the two equally sized image patches image and ``im2``. The\n result is a scalar in the interval -1 to 1 that indicates similarity.\n A value of 1 indicates identical pixel patterns.\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - The ``zncc`` similarity measure is invariant to affine changes\n in image intensity (brightness offset and scale).\n\n \"\"\"\n if not np.all(self.shape == im2.shape):\n raise ValueError(im2, 'im2 shape is not equal to im1')\n\n image = self.image - np.mean(self.image)\n image2 = im2.image - np.mean(im2.image)\n denom = np.sqrt(np.sum(np.power(image, 2) *\n np.sum(np.power(image2, 2))))\n\n if denom < 1e-10:\n return 0\n else:\n return np.sum(image * image2) / denom\n\n def pyramid(self, sigma=1, N=None):\n \"\"\"\n Pyramidal image decomposition\n\n :param sigma: standard deviation of Gaussian kernel\n :type sigma: float\n :param N: number of pyramid levels to be computed\n :type N: int\n :return pyrimlist: list of Images for each pyramid level computed\n :rtype pyrimlist: list\n\n - ``IM.pyramid()`` is a pyramid decomposition of image using Gaussian\n smoothing with standard deviation of 1. The return is a list array of\n images each one having dimensions half that of the previous image.\n The pyramid is computed down to a non-halvable image size.\n\n - ``IM.pyramid(sigma)`` as above but the Gaussian standard deviation is\n ``sigma``.\n\n - ``IM.pyramid(sigma, N)`` as above but only ``N`` levels of the\n pyramid are computed.\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - Converts a color image to greyscale.\n - Works for greyscale images only.\n \"\"\"\n\n # check inputs, greyscale only\n im = self.mono()\n\n if not argcheck.isscalar(sigma):\n raise ValueError(sigma, 'sigma must be a scalar')\n\n if N is None:\n N = max(im.shape)\n else:\n if (not argcheck.isscalar(N)) and (N >= 0) and \\\n (N <= max(im.shape)):\n raise ValueError(N, 'N must be a scalar and \\\n 0 <= N <= max(im.shape)')\n\n # TODO options to accept different border types,\n # note that the Matlab implementation is hard-coded to 'same'\n\n # return cv.buildPyramid(im, N, borderType=cv.BORDER_REPLICATE)\n # Python version does not seem to be implemented\n\n # list comprehension approach\n # TODO pyr = [cv.pyrdown(inputs(i)) for i in range(N) if conditional]\n\n impyr = im.image\n pyr = [impyr]\n for i in range(N):\n if impyr.shape[0] == 1 or impyr.shape[1] == 1:\n break\n impyr = cv.pyrDown(impyr, borderType=cv.BORDER_REPLICATE)\n pyr.append(impyr)\n\n # output list of Image objects\n pyrimlist = [self.__class__(p) for p in pyr]\n return pyrimlist\n\n def window(self, se, func, opt='border', **kwargs):\n \"\"\"\n Generalized spatial operator\n\n :param se: structuring element\n :type se: numpy array\n :param func: function to operate\n :type funct: reference to a callable function\n :param opt: border option\n :type opt: string\n :return out: Image after function has operated on every pixel by func\n :rtype out: Image instance\n\n - ``IM.window(se, func)`` is an image where each pixel is the result of\n applying the function ``func`` to a neighbourhood centred on the\n corresponding pixel in image. The neighbourhood is defined by the\n size of the structuring element ``se`` which should have odd side\n lengths. The elements in the neighbourhood corresponding to non-zero\n elements in ``se`` are packed into a vector (in column order from top\n left) and passed to the specified callable function ``func``. The\n return value of ``func`` becomes the corresponding pixel value.\n\n - ``IM.window(se, func, opt)`` as above but performance of edge pixels\n can be controlled.\n\n :options:\n\n - 'replicate' the border value is replicated (default)\n - 'none' pixels beyond the border are not included in the\n window\n - 'trim' output is not computed for pixels where the\n structuring element crosses the image border, hence output image\n has reduced dimensions TODO\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - The structuring element should have an odd side length.\n - Is slow since the function ``func`` must be invoked once for\n every output pixel.\n - The input can be logical, uint8, uint16, float or double, the\n output is always double\n \"\"\"\n # replace window's mex function with scipy's ndimage.generic_filter\n\n # border options:\n edgeopt = {\n 'border': 'nearest',\n 'none': 'constant',\n 'wrap': 'wrap'\n }\n if opt not in edgeopt:\n raise ValueError(opt, 'opt is not a valid edge option')\n\n if not callable(func):\n raise TypeError(func, 'func not callable')\n\n out = []\n for im in self:\n out.append(sp.ndimage.generic_filter(im.image,\n func,\n footprint=se,\n mode=edgeopt[opt]))\n return self.__class__(out)\n\n def similarity(self, T, metric=None):\n \"\"\"\n Locate template in image\n\n :param T: template image\n :type T: numpy array\n :param metric: similarity metric function\n :type metric: callable function reference\n :return S: Image similarity image\n :rtype S: Image instance\n\n - ``IM.similarity(T)`` is an image where each pixel is the ``zncc``\n similarity of the template ``T`` (M,M) to the (M,M) neighbourhood\n surrounding the corresonding input pixel in image. ``S`` is same\n size as image.\n\n - ``IM.similarity(T, metric)`` as above but the similarity metric is\n specified by the function ``metric`` which can be any of @sad, @ssd,\n @ncc, @zsad, @zssd.\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - For NCC and ZNCC the maximum in S corresponds to the most likely\n template location. For SAD, SSD, ZSAD and ZSSD the minimum value\n corresponds to the most likely location.\n - Similarity is not computed for those pixels where the template\n crosses the image boundary, and these output pixels are set\n to NaN.\n - The ZNCC function is a MEX file and therefore the fastest\n - User provided similarity metrics can be used, the function\n accepts two regions and returns a scalar similarity score.\n\n :references:\n\n - Robotics, Vision & Control, Section 12.4, P. Corke,\n Springer 2011.\n \"\"\"\n\n # check inputs\n if ((T.shape[0] % 2) == 0) or ((T.shape[1] % 2) == 0):\n raise ValueError(T, 'template T must have odd dimensions')\n\n if metric is None:\n metric = self.zncc\n if not callable(metric):\n raise TypeError(metric, 'metric not a callable function')\n\n # to use metric, T must be an image class\n T = self.__class__(T)\n\n hc = np.floor(T.shape[0] / 2)\n hr = np.floor(T.shape[1] / 2)\n\n out = []\n for im in self:\n S = np.empty(im.shape)\n\n # TODO can probably replace these for loops with comprehensions\n for c in range(start=hc + 1, stop=im.shape[0] - hc):\n for r in range(start=hr + 1, stop=im.shape[1] - hr):\n S[r, c] = T.metric(im.image[r-hr:r+hr, c-hc:c+hc])\n out.append(S)\n\n return self.__class__(out)\n\n def convolve(self, K, optmode='same', optboundary='wrap'):\n \"\"\"\n Image convolution\n\n :param K: kernel\n :type K: numpy array\n :param optmode: option for convolution\n :type optmode: string\n :param optboundary: option for boundary handling\n :type optboundary: string\n :return C: Image convolved image\n :rtype C: Image instance\n\n - ``IM.convolve(K)`` is the convolution of image with the kernel ``K``\n\n - ``IM.convolve(K, optmode)`` as above but specifies the convolution\n mode. See scipy.signal.convolve2d for details, mode options below\n\n - ``IM.convolve(K, optboundary)`` as above but specifies the boundary\n handling options\n\n :options:\n\n - 'same' output image is same size as input image (default)\n - 'full' output image is larger than the input image\n - 'valid' output image is smaller than the input image, and\n contains only valid pixels TODO\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - If the image is color (has multiple planes) the kernel is\n applied to each plane, resulting in an output image with the same\n number of planes.\n - If the kernel has multiple planes, the image is convolved with\n each plane of the kernel, resulting in an output image with the\n same number of planes.\n - This function is a convenience wrapper for the MATLAB function\n CONV2.\n - Works for double, uint8 or uint16 images. Image and kernel must\n be of the same type and the result is of the same type.\n - This function replaces iconv().\n\n :references:\n\n - Robotics, Vision & Control, Section 12.4, P. Corke,\n Springer 2011.\n \"\"\"\n\n # TODO check images are of the same type\n\n # TODO check opt is valid string based on conv2 options\n modeopt = {\n 'full': 'full',\n 'valid': 'valid',\n 'same': 'same'\n }\n if optmode not in modeopt:\n raise ValueError(optmode, 'opt is not a valid option')\n\n boundaryopt = {\n 'fill': 'fill',\n 'wrap': 'wrap',\n 'reflect': 'symm'\n }\n if optboundary not in boundaryopt:\n raise ValueError(optboundary, 'opt is not a valid option')\n\n out = []\n for im in self:\n if im.iscolor and K.ndim == 2:\n # image has multiple planes:\n C = np.dstack([signal.convolve2d(im.image[:, :, i],\n K,\n mode=modeopt[optmode],\n boundary=boundaryopt[\n optboundary])\n for i in range(im.nchannels)])\n\n elif not im.iscolor and K.ndim == 2:\n # simple case, convolve image with kernel, both are 2D\n C = signal.convolve2d(im.image,\n K,\n mode=modeopt[optmode],\n boundary=boundaryopt[optboundary])\n\n elif not im.iscolor and K.ndim == 3:\n # kernel has multiple planes:\n C = np.dstack([signal.convolve2d(im.image,\n K.image[:, :, i],\n mode=modeopt[optmode],\n boundary=boundaryopt[\n optboundary])\n for i in range(K.shape[2])])\n else:\n raise ValueError(\n im, 'image and kernel cannot both have muliple planes')\n out.append(C)\n\n return self.__class__(out)\n\n def canny(self, sigma=1, th0=None, th1=None):\n \"\"\"\n Canny edge detection\n\n :param sigma: standard deviation for Gaussian kernel smoothing\n :type sigma: float\n :param th0: lower threshold\n :type th0: float\n :param th1: upper threshold\n :type th1: float\n :return E: Image with edge image\n :rtype E: Image instance\n\n - ``IM.canny()`` is an edge image obtained using the Canny edge\n detector algorithm. Hysteresis filtering is applied to the gradient\n image: edge pixels > ``th1`` are connected to adjacent pixels >\n ``th0``, those below ``th0`` are set to zero.\n\n - ``IM.canny(sigma, th0, th1)`` as above, but the standard deviation of\n the Gaussian smoothing, ``sigma``, lower and upper thresholds\n ``th0``, ``th1`` can be specified\n\n Example:\n\n .. runblock:: pycon\n\n .. note::\n\n - Produces a zero image with single pixel wide edges having\n non-zero values.\n - Larger values correspond to stronger edges.\n - If th1 is zero then no hysteresis filtering is performed.\n - A color image is automatically converted to greyscale first.\n\n :references:\n\n - \"A Computational Approach To Edge Detection\", J. Canny,\n IEEE Trans. Pattern Analysis and Machine Intelligence,\n 8(6):679–698, 1986.\n\n \"\"\"\n\n # convert to greyscale:\n img = self.mono()\n\n # set defaults (eg thresholds, eg one as a function of the other)\n if th0 is None:\n if np.issubdtype(th0, np.float):\n th0 = 0.1\n else:\n # isint\n th0 = np.round(0.1 * np.iinfo(img.dtype).max)\n if th1 is None:\n th1 = 1.5 * th0\n\n # compute gradients Ix, Iy using guassian kernel\n dg = self.kdgauss(sigma)\n\n out = []\n for im in img:\n\n Ix = np.abs(im.convolve(dg, 'same'))\n Iy = np.abs(im.convolve(np.transpose(dg), 'same'))\n\n # Ix, Iy must be 16-bit input image\n Ix = np.array(Ix, dtype=np.int16)\n Iy = np.array(Iy, dtype=np.int16)\n\n out.append((cv.Canny(Ix, Iy, th0, th1, L2gradient=True)))\n\n return self.__class__(out)\n\n\n# --------------------------------------------------------------------------#\nif __name__ == '__main__':\n\n print('ImageProcessingKernel.py')\n from machinevisiontoolbox import Image\n print(Image.kcircle(5))"
]
| [
[
"numpy.issubdtype",
"numpy.squeeze",
"numpy.all",
"numpy.int",
"numpy.round",
"numpy.mean",
"numpy.iinfo",
"numpy.arange",
"numpy.ceil",
"numpy.power",
"scipy.signal.convolve2d",
"scipy.ndimage.generic_filter",
"numpy.floor",
"numpy.transpose",
"numpy.meshgrid",
"numpy.array",
"numpy.sum",
"numpy.abs",
"numpy.empty"
]
]
|
jsmentch/pliers | [
"ef13552793ab5789065249a89230baced407c472"
]
| [
"pliers/tests/test_stims.py"
]
| [
"import tempfile\nimport os\nimport base64\nfrom os.path import join, exists\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom .utils import get_test_data_path\nfrom pliers.stimuli import (VideoStim, VideoFrameStim, ComplexTextStim,\n AudioStim, ImageStim, CompoundStim,\n TranscribedAudioCompoundStim,\n TextStim,\n TweetStimFactory,\n TweetStim,\n SeriesStim)\nfrom pliers.stimuli.base import Stim, _get_stim_class\nfrom pliers.extractors import (BrightnessExtractor, LengthExtractor,\n ComplexTextExtractor)\nfrom pliers.extractors.base import Extractor, ExtractorResult\nfrom pliers.support.download import download_nltk_data\n\n\nclass DummyExtractor(Extractor):\n\n _input_type = Stim\n\n def _extract(self, stim):\n return ExtractorResult(np.array([[1]]), stim, self,\n features=['constant'])\n\n\nclass DummyIterableExtractor(Extractor):\n\n _input_type = Stim\n\n def _extract(self, stim):\n time_bins = np.arange(0., stim.duration, 1.)\n return ExtractorResult(np.array([1] * len(time_bins)), stim, self,\n features=['constant'], onsets=time_bins,\n durations=[1.] * len(time_bins))\n\n\[email protected](scope='module')\ndef get_nltk():\n download_nltk_data()\n\n\[email protected](scope='module')\ndef dummy_extractor():\n return DummyExtractor()\n\n\[email protected](scope='module')\ndef dummy_iter_extractor():\n return DummyIterableExtractor()\n\n\ndef test_image_stim(dummy_iter_extractor):\n filename = join(get_test_data_path(), 'image', 'apple.jpg')\n stim = ImageStim(filename)\n assert stim.data.shape == (288, 420, 3)\n\n\ndef test_image_stim_bytestring():\n path = join(get_test_data_path(), 'image', 'apple.jpg')\n img = ImageStim(path)\n assert img._bytestring is None\n bs = img.get_bytestring()\n assert isinstance(bs, str)\n assert img._bytestring is not None\n raw = bs.encode()\n with open(path, 'rb') as f:\n assert raw == base64.b64encode(f.read())\n\n\ndef test_complex_text_hash():\n stims = [ComplexTextStim(text='yeah'), ComplexTextStim(text='buddy')]\n ext = ComplexTextExtractor()\n res = ext.transform(stims)\n\n assert res[0]._data != res[1]._data\n\n\ndef test_video_stim():\n ''' Test VideoStim functionality. '''\n filename = join(get_test_data_path(), 'video', 'small.mp4')\n video = VideoStim(filename, onset=4.2)\n assert video.fps == 30\n assert video.n_frames == 168\n assert video.width == 560\n assert video.duration == 5.57\n\n # Test frame iterator\n frames = [f for f in video]\n assert len(frames) == 168\n f1 = frames[100]\n assert isinstance(f1, VideoFrameStim)\n assert isinstance(f1.onset, float)\n assert np.isclose(f1.duration, 1 / 30.0, 1e-5)\n f1.data.shape == (320, 560, 3)\n\n # Test getting of specific frame\n f2 = video.get_frame(index=100)\n assert isinstance(f2, VideoFrameStim)\n assert isinstance(f2.onset, float)\n assert f2.onset > 7.5\n f2.data.shape == (320, 560, 3)\n f2_copy = video.get_frame(onset=3.33334)\n assert isinstance(f2, VideoFrameStim)\n assert isinstance(f2.onset, float)\n assert f2.onset > 7.5\n assert np.array_equal(f2.data, f2_copy.data)\n\n # Try another video\n filename = join(get_test_data_path(), 'video', 'obama_speech.mp4')\n video = VideoStim(filename)\n assert video.fps == 12\n assert video.n_frames == 105\n assert video.width == 320\n assert video.duration == 8.71\n f3 = video.get_frame(index=104)\n assert isinstance(f3, VideoFrameStim)\n assert isinstance(f3.onset, float)\n assert f3.duration > 0.0\n assert f3.data.shape == (240, 320, 3)\n\n\ndef test_video_stim_bytestring():\n path = join(get_test_data_path(), 'video', 'small.mp4')\n vid = VideoStim(path)\n assert vid._bytestring is None\n bs = vid.get_bytestring()\n assert isinstance(bs, str)\n assert vid._bytestring is not None\n raw = bs.encode()\n with open(path, 'rb') as f:\n assert raw == base64.b64encode(f.read())\n\n\ndef test_video_frame_stim():\n filename = join(get_test_data_path(), 'video', 'small.mp4')\n video = VideoStim(filename, onset=4.2)\n frame = VideoFrameStim(video, 42)\n assert frame.onset == (5.6)\n assert np.array_equal(frame.data, video.get_frame(index=42).data)\n assert frame.name == 'frame[42]'\n\n\ndef test_audio_stim():\n audio_dir = join(get_test_data_path(), 'audio')\n stim = AudioStim(join(audio_dir, 'barber.wav'))\n assert round(stim.duration) == 57\n assert stim.sampling_rate == 11025\n\n stim = AudioStim(join(audio_dir, 'homer.wav'))\n assert round(stim.duration) == 3\n assert stim.sampling_rate == 11025\n\n\ndef test_audio_formats():\n audio_dir = join(get_test_data_path(), 'audio')\n stim = AudioStim(join(audio_dir, 'crowd.mp3'))\n assert round(stim.duration) == 28\n assert stim.sampling_rate == 44100\n\n\ndef test_complex_text_stim():\n text_dir = join(get_test_data_path(), 'text')\n stim = ComplexTextStim(join(text_dir, 'complex_stim_no_header.txt'),\n columns='ot', default_duration=0.2)\n assert len(stim.elements) == 4\n assert stim.elements[2].onset == 34\n assert stim.elements[2].duration == 0.2\n stim = ComplexTextStim(join(text_dir, 'complex_stim_no_header.txt'),\n columns='ot', default_duration=0.2, onset=4.2)\n assert stim.elements[2].onset == 38.2\n assert stim.elements[1].onset == 24.2\n stim = ComplexTextStim(join(text_dir, 'complex_stim_with_header.txt'))\n assert len(stim.elements) == 4\n assert stim.elements[2].duration == 0.1\n\n assert stim._to_sec((1.0, 42, 3, 0)) == 6123\n assert stim._to_tup(6123) == (1.0, 42, 3, 0)\n\n\ndef test_complex_stim_from_text():\n textfile = join(get_test_data_path(), 'text', 'scandal.txt')\n text = open(textfile).read().strip()\n stim = ComplexTextStim(text=text)\n target = ['To', 'Sherlock', 'Holmes']\n assert [w.text for w in stim.elements[:3]] == target\n assert len(stim.elements) == 231\n stim = ComplexTextStim(text=text, unit='sent')\n # Custom tokenizer\n stim = ComplexTextStim(text=text, tokenizer=r'(\\w+)')\n assert len(stim.elements) == 209\n\n\ndef test_complex_stim_from_srt():\n srtfile = join(get_test_data_path(), 'text', 'wonderful.srt')\n textfile = join(get_test_data_path(), 'text', 'wonderful.txt')\n df = pd.read_csv(textfile, sep='\\t')\n target = df[\"text\"].tolist()\n srt_stim = ComplexTextStim(srtfile)\n texts = [sent.text for sent in srt_stim.elements]\n assert texts == target\n\n\ndef test_get_stim():\n assert issubclass(_get_stim_class('video'), VideoStim)\n assert issubclass(_get_stim_class('ComplexTextStim'), ComplexTextStim)\n assert issubclass(_get_stim_class('video_frame'), VideoFrameStim)\n\n\ndef test_compound_stim():\n audio_dir = join(get_test_data_path(), 'audio')\n audio = AudioStim(join(audio_dir, 'crowd.mp3'))\n image1 = ImageStim(join(get_test_data_path(), 'image', 'apple.jpg'))\n image2 = ImageStim(join(get_test_data_path(), 'image', 'obama.jpg'))\n filename = join(get_test_data_path(), 'video', 'small.mp4')\n video = VideoStim(filename)\n text = ComplexTextStim(text=\"The quick brown fox jumped...\")\n stim = CompoundStim([audio, image1, image2, video, text])\n assert len(stim.elements) == 5\n assert isinstance(stim.video, VideoStim)\n assert isinstance(stim.complex_text, ComplexTextStim)\n assert isinstance(stim.image, ImageStim)\n with pytest.raises(AttributeError):\n stim.nonexistent_type\n assert stim.video_frame is None\n\n # Test iteration\n len([e for e in stim]) == 5\n\n imgs = stim.get_stim(ImageStim, return_all=True)\n assert len(imgs) == 2\n assert all([isinstance(im, ImageStim) for im in imgs])\n also_imgs = stim.get_stim('image', return_all=True)\n assert imgs == also_imgs\n\n\ndef test_transformations_on_compound_stim():\n image1 = ImageStim(join(get_test_data_path(), 'image', 'apple.jpg'))\n image2 = ImageStim(join(get_test_data_path(), 'image', 'obama.jpg'))\n text = ComplexTextStim(text=\"The quick brown fox jumped...\")\n stim = CompoundStim([image1, image2, text])\n\n ext = BrightnessExtractor()\n results = ext.transform(stim)\n assert len(results) == 2\n assert np.allclose(results[0]._data[0], 0.88784294)\n\n\ndef test_transcribed_audio_stim():\n audio = AudioStim(join(get_test_data_path(), 'audio', \"barber_edited.wav\"))\n text_file = join(get_test_data_path(), 'text', \"wonderful_edited.srt\")\n text = ComplexTextStim(text_file)\n stim = TranscribedAudioCompoundStim(audio=audio, text=text)\n assert isinstance(stim.audio, AudioStim)\n assert isinstance(stim.complex_text, ComplexTextStim)\n\n\ndef test_remote_stims():\n\n video_url = 'https://archive.org/download/DisneyCastletest/Disney_Castle_512kb.mp4'\n video = VideoStim(url=video_url)\n assert video.fps == 30.0\n\n url = 'http://www.bobainsworth.com/wav/simpsons/themodyn.wav'\n audio = AudioStim(url=url)\n assert round(audio.duration) == 3\n\n url = 'https://www.whitehouse.gov/sites/whitehouse.gov/files/images/twitter_cards_potus.jpg'\n image = ImageStim(url=url)\n assert image.data.shape == (240, 240, 3)\n\n url = 'https://github.com/tyarkoni/pliers/blob/master/README.md'\n text = TextStim(url=url)\n assert len(text.text) > 1\n\n\ndef test_get_filename():\n url = 'http://www.bobainsworth.com/wav/simpsons/themodyn.wav'\n audio = AudioStim(url=url)\n with audio.get_filename() as filename:\n assert exists(filename)\n assert not exists(filename)\n\n url = 'https://via.placeholder.com/350x150'\n image = ImageStim(url=url)\n with image.get_filename() as filename:\n assert exists(filename)\n assert not exists(filename)\n\n\ndef test_save():\n cts_file = join(get_test_data_path(), 'text', 'complex_stim_no_header.txt')\n complextext_stim = ComplexTextStim(cts_file, columns='ot',\n default_duration=0.2)\n text_stim = TextStim(text='hello')\n audio_stim = AudioStim(join(get_test_data_path(), 'audio', 'crowd.mp3'))\n image_stim = ImageStim(join(get_test_data_path(), 'image', 'apple.jpg'))\n\n # Video gives travis problems\n stims = [complextext_stim, text_stim, audio_stim, image_stim]\n for s in stims:\n path = tempfile.mktemp() + s._default_file_extension\n s.save(path)\n assert exists(path)\n os.remove(path)\n\n\[email protected](\"'TWITTER_ACCESS_TOKEN_KEY' not in os.environ\")\ndef test_twitter():\n # Test stim creation\n pytest.importorskip('twitter')\n factory = TweetStimFactory()\n status_id = 821442726461931521\n pliers_tweet = factory.get_status(status_id)\n assert isinstance(pliers_tweet, TweetStim)\n assert isinstance(pliers_tweet, CompoundStim)\n assert len(pliers_tweet.elements) == 1\n\n status_id = 884392294014746624\n ut_tweet = factory.get_status(status_id)\n assert len(ut_tweet.elements) == 2\n\n # Test extraction\n ext = LengthExtractor()\n res = ext.transform(pliers_tweet)[0].to_df()\n assert res['text_length'][0] == 104\n\n # Test image extraction\n ext = BrightnessExtractor()\n res = ext.transform(ut_tweet)[0].to_df()\n brightness = res['brightness'][0]\n assert np.isclose(brightness, 0.54057, 1e-5)\n\n\ndef test_series():\n my_dict = {'a': 4, 'b': 2, 'c': 8}\n stim = SeriesStim(my_dict, onset=4, duration=2)\n ser = pd.Series([4, 2, 8], index=['a', 'b', 'c'])\n pd.testing.assert_series_equal(stim.data, ser)\n assert stim.onset == 4\n assert stim.duration == 2\n assert stim.order is None\n\n f = Path(get_test_data_path(), 'text', 'test_lexical_dictionary.txt')\n # multiple columns found and no column arg provided\n with pytest.raises(ValueError):\n stim = SeriesStim(filename=f, sep='\\t')\n\n stim = SeriesStim(filename=f, column='frequency', sep='\\t')\n assert stim.data.shape == (7,)\n assert stim.data[3] == 15.417\n\n # 2-d array should fail\n with pytest.raises(Exception):\n ser = SeriesStim(np.random.normal(size=(10, 2)))\n"
]
| [
[
"pandas.read_csv",
"pandas.testing.assert_series_equal",
"pandas.Series",
"numpy.allclose",
"numpy.array_equal",
"numpy.arange",
"numpy.random.normal",
"numpy.array",
"numpy.isclose"
]
]
|
filipecosta90/dlbench | [
"11dd2fb58050c38a4baa429b207aaecad9097ce3"
]
| [
"tests/models/tensorflow/convert_to_tensorflow_serving.py"
]
| [
"import tensorflow as tf\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import tag_constants\n\nexport_dir = './reference/00000002'\ngraph_pb = './creditcardfraud.pb'\n\nbuilder = tf.saved_model.builder.SavedModelBuilder(export_dir)\n\nwith tf.gfile.GFile(graph_pb, \"rb\") as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\nsigs = {}\n\nwith tf.Session(graph=tf.Graph()) as sess:\n # name=\"\" is important to ensure we don't get spurious prefixing\n tf.import_graph_def(graph_def, name=\"\")\n g = tf.get_default_graph()\n inp1 = g.get_tensor_by_name(\"transaction:0\")\n inp2 = g.get_tensor_by_name(\"reference:0\")\n out = g.get_tensor_by_name(\"output:0\")\n\n sigs[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \\\n tf.saved_model.signature_def_utils.predict_signature_def(\n {\"transaction\": inp1, \"reference\": inp2}, {\"output\": out})\n\n builder.add_meta_graph_and_variables(sess,\n [tag_constants.SERVING],\n signature_def_map=sigs)\n\nbuilder.save()\n"
]
| [
[
"tensorflow.Graph",
"tensorflow.import_graph_def",
"tensorflow.gfile.GFile",
"tensorflow.saved_model.builder.SavedModelBuilder",
"tensorflow.get_default_graph",
"tensorflow.GraphDef",
"tensorflow.saved_model.signature_def_utils.predict_signature_def"
]
]
|
23W/Labs | [
"64cc6eb5263c2c7a13769966a31abdd6a789d630"
]
| [
"SS/L3/lab3_part3.py"
]
| [
"import os\nimport pandas\nimport matplotlib.pyplot as plt, numpy as np\n\ndef countryPrecipitation(country, years):\n # read data\n df = pandas.read_csv('precipitation.csv')\n\n # rename indices\n df = df.set_index(df['Country or Area'])\n df.drop(['Country or Area'], axis=\"columns\", inplace=True)\n\n #slice by country and years\n precipitation = df.loc[country, years]\n\n # Output: country precipitation\n years_title = \"[{}..{}]\".format(years[0], years[-1]) if len(years)>1 else str(years[0])\n title = \"Precipitation in {} during {}\".format(country, years_title)\n with open(\"./output/precipitation_{}_{}_data.txt\".format(country, years_title), 'w') as f:\n print(title, file=f)\n print(precipitation, file=f)\n\n # Graph: country precipitation\n if len(years)>1:\n plt.figure(figsize=(10,8))\n plt.title(title)\n plt.xlabel(\"Years\")\n plt.ylabel(\"Precipitation (million cubic meters)\")\n plt.bar(precipitation.index, precipitation, width=0.5)\n plt.savefig(\"./output/precipitation_{}_{}_bar.png\".format(country, years_title))\n\n # Chart: Top wettest countries\n if len(years)>1:\n title = \"Comparision chart of precipitation in {} during {}\".format(country, years_title)\n plt.figure(figsize=(10,8))\n plt.axis(\"equal\")\n plt.title(title, y=1.08)\n plt.pie(precipitation, labels=precipitation.index, autopct=\"%1.2f%%\", radius=1.25)\n plt.savefig(\"./output/precipitation_{}_{}_chart.png\".format(country, years_title))\n\n# Main\nif not os.path.exists('output'):\n os.makedirs('output')\n\ncountry = \"Israel\"\nrange1 = [\"1990\"] # range [1990...1990]\nrange2 = [\"{:d}\".format(x) for x in range(1995, 2010)] # range [1995...2010)\ncountryPrecipitation(country, range1)\ncountryPrecipitation(country, range2)"
]
| [
[
"pandas.read_csv",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.pie",
"matplotlib.pyplot.ylabel"
]
]
|
scripples/scripp_gpt-2 | [
"d0b5b31fce107440d48c5447cc04cce7bc5ef639"
]
| [
"src/generate_snapshot.py"
]
| [
"#!/usr/bin/env python3\n\nimport os\nimport sys\nsys.path += [os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'src')]\nsys.path += [os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))]\n\nimport fire\nimport json\nimport numpy as np\nimport tensorflow as tf\n\nimport model, sample, encoder\n\nimport tflex\n\[email protected]_command\ndef clear_context():\n tflex.reset_context()\n print('')\n print('')\n print('')\n\ndef clear_output(wait=False):\n import subprocess, platform\n if platform.system()==\"Windows\":\n subprocess.Popen(\"cls\", shell=True).communicate()\n else:\n print(\"\\033c\", end=\"\")\n\ndef is_ascii(s):\n return all(ord(c) < 128 for c in s)\n\ndef interact_model(\n model_name='117M',\n restore_from=None,\n seed=None,\n nsamples=1,\n step=1,\n length=64,\n prompt=\"\\n\",\n clear=None,\n maxlen=-1,\n temperature=1,\n top_k=0,\n top_p=0,\n penalize=0\n):\n \"\"\"\n Interactively run the model\n :model_name=117M : String, which model to use\n :seed=None : Integer seed for random number generators, fix seed to reproduce\n results\n :nsamples=1 : Number of samples to return total\n :step=1 : Number of tokens to generate at a time\n :length=64 : Window size; use 1024 for maximum size per sample\n :prompt=\"\\\\n\" : Prompt to start with. The default of \"\" prompts with an <|endoftext|> token.\n :clear=None : If this string is encountered, clear the context window.\n :maxlen=-1 : if this many tokens are generated without\n encountering --clear, then print it and clear the context window.\n :temperature=1 : Float value controlling randomness in boltzmann\n distribution. Lower temperature results in less random completions. As the\n temperature approaches zero, the model will become deterministic and\n repetitive. Higher temperature results in more random completions.\n :top_k=0 : Integer value controlling diversity. 1 means only 1 word is\n considered for each step (token), resulting in deterministic completions,\n while 40 means 40 words are considered at each step. 0 (default) is a\n special setting meaning no restrictions. 40 generally is a good value.\n :top_p=0.0 : Float value controlling diversity. Implements nucleus sampling,\n overriding top_k if set to a value > 0. A good setting is 0.9.\n :penalize=0.0 : Float value controlling \"used\" penalty. Implements repetition\n reduction (similar to CTRL) if set to a value > 0. A decent setting might be 0.85\n with temperature 0.3 and top_k 40.\n \"\"\"\n batch_size = 1\n assert nsamples % batch_size == 0\n\n enc = encoder.get_encoder(model_name)\n hparams = model.default_hparams()\n with open(os.path.join('models', model_name, 'hparams.json')) as f:\n hparams.override_from_dict(json.load(f))\n\n if length > hparams.n_ctx:\n raise ValueError(\"Length can't be largeer than n_ctx: %s\" % hparams.n_ctx)\n if step > length:\n raise ValueError(\"Can't get samples longer than length: %s\" % length)\n\n with tflex.Session(graph=tf.Graph()) as sess:\n context = tf.placeholder(tf.int32, [batch_size, None])\n np.random.seed(seed)\n tf.set_random_seed(seed)\n output = sample.sample_sequence(\n hparams=hparams, length=step,\n context=context,\n batch_size=batch_size,\n temperature=temperature, top_k=top_k, top_p=top_p, penalize=penalize\n )\n\n saver = tflex.Saver(reshape=True)\n if restore_from is None:\n restore_from = os.path.join('models', model_name)\n ckpt = tflex.latest_checkpoint(restore_from)\n saver.restore(sess, ckpt)\n saver2 = tf.train.Saver()\n counter = int(ckpt.split('-')[-1].split('.')[0])\n saver2.save(\n sess,\n os.path.join('saved', 'model'),\n global_step=counter)\n\nif __name__ == '__main__':\n fire.Fire(interact_model)\n\n"
]
| [
[
"tensorflow.Graph",
"numpy.random.seed",
"tensorflow.placeholder",
"tensorflow.set_random_seed",
"tensorflow.train.Saver"
]
]
|
JoshuaWu1997/sgan | [
"8a380ae6b6c0ecb6dc516141551081a30466f221"
]
| [
"sgan-attention/models.py"
]
| [
"import torch\nimport torch.nn as nn\n\n\ndef make_mlp(dim_list, activation='relu', batch_norm=True, dropout=0.0):\n layers = []\n for dim_in, dim_out in zip(dim_list[:-1], dim_list[1:]):\n layers.append(nn.Linear(dim_in, dim_out))\n if batch_norm:\n layers.append(nn.BatchNorm1d(dim_out))\n if activation == 'relu':\n layers.append(nn.ReLU())\n elif activation == 'leakyrelu':\n layers.append(nn.LeakyReLU())\n if dropout > 0:\n layers.append(nn.Dropout(p=dropout))\n return nn.Sequential(*layers)\n\n\ndef get_noise(shape, noise_type):\n if noise_type == 'gaussian':\n return torch.randn(*shape).cuda()\n elif noise_type == 'uniform':\n return torch.rand(*shape).sub_(0.5).mul_(2.0).cuda()\n raise ValueError('Unrecognized noise type \"%s\"' % noise_type)\n\n\nclass Encoder(nn.Module):\n \"\"\"Encoder is part of both TrajectoryGenerator and\n TrajectoryDiscriminator\"\"\"\n\n def __init__(\n self, embedding_dim=64, h_dim=64, mlp_dim=1024, num_layers=1, dropout=0.0, obs_len=8\n ):\n super(Encoder, self).__init__()\n\n self.mlp_dim = mlp_dim\n self.h_dim = h_dim\n self.embedding_dim = embedding_dim\n self.num_layers = num_layers\n self.attention = nn.Sequential(\n nn.Linear(obs_len, obs_len),\n nn.ReLU(),\n nn.Softmax(dim=1)\n )\n self.encoder = nn.LSTM(\n embedding_dim, h_dim, num_layers, dropout=dropout\n )\n self.spatial_embedding = nn.Linear(2, embedding_dim)\n\n def init_hidden(self, batch):\n return (\n torch.zeros(self.num_layers, batch, self.h_dim).cuda(),\n torch.zeros(self.num_layers, batch, self.h_dim).cuda()\n )\n\n def forward(self, obs_traj):\n \"\"\"\n Inputs:\n - obs_traj: Tensor of shape (obs_len, batch, 2)\n Output:\n - final_h: Tensor of shape (self.num_layers, batch, self.h_dim)\n \"\"\"\n # Encode observed Trajectory\n batch = obs_traj.size(1)\n attn_weight = self.attention(obs_traj.permute(1, 2, 0))\n obs_traj = (obs_traj.permute(1, 2, 0) * attn_weight).permute(2, 0, 1)\n obs_traj_embedding = self.spatial_embedding(obs_traj.reshape(-1, 2))\n obs_traj_embedding = obs_traj_embedding.view(\n -1, batch, self.embedding_dim\n )\n state_tuple = self.init_hidden(batch)\n output, state = self.encoder(obs_traj_embedding, state_tuple)\n final_h = state[0]\n return final_h\n\n\nclass Decoder(nn.Module):\n \"\"\"Decoder is part of TrajectoryGenerator\"\"\"\n\n def __init__(\n self, seq_len, embedding_dim=64, h_dim=128, mlp_dim=1024, num_layers=1,\n pool_every_timestep=True, dropout=0.0, bottleneck_dim=1024,\n activation='relu', batch_norm=True, pooling_type='pool_net',\n neighborhood_size=2.0, grid_size=8\n ):\n super(Decoder, self).__init__()\n\n self.seq_len = seq_len\n self.mlp_dim = mlp_dim\n self.h_dim = h_dim\n self.embedding_dim = embedding_dim\n self.pool_every_timestep = pool_every_timestep\n self.decoder = nn.LSTM(\n embedding_dim, h_dim, num_layers, dropout=dropout\n )\n\n if pool_every_timestep:\n if pooling_type == 'pool_net':\n self.pool_net = PoolHiddenNet(\n embedding_dim=self.embedding_dim,\n h_dim=self.h_dim,\n mlp_dim=mlp_dim,\n bottleneck_dim=bottleneck_dim,\n activation=activation,\n batch_norm=batch_norm,\n dropout=dropout\n )\n elif pooling_type == 'spool':\n self.pool_net = SocialPooling(\n h_dim=self.h_dim,\n activation=activation,\n batch_norm=batch_norm,\n dropout=dropout,\n neighborhood_size=neighborhood_size,\n grid_size=grid_size,\n pool_dim=bottleneck_dim\n )\n\n mlp_dims = [h_dim + bottleneck_dim, mlp_dim, h_dim]\n self.mlp = make_mlp(\n mlp_dims,\n activation=activation,\n batch_norm=batch_norm,\n dropout=dropout\n )\n\n self.spatial_embedding = nn.Linear(2, embedding_dim)\n self.hidden2pos = nn.Linear(h_dim, 2)\n\n def forward(self, last_pos, last_pos_rel, state_tuple, seq_start_end):\n \"\"\"\n Inputs:\n - last_pos: Tensor of shape (batch, 2)\n - last_pos_rel: Tensor of shape (batch, 2)\n - state_tuple: (hh, ch) each tensor of shape (num_layers, batch, h_dim)\n - seq_start_end: A list of tuples which delimit sequences within batch\n Output:\n - pred_traj: tensor of shape (self.seq_len, batch, 2)\n \"\"\"\n batch = last_pos.size(0)\n pred_traj_fake_rel = []\n decoder_input = self.spatial_embedding(last_pos_rel)\n decoder_input = decoder_input.view(1, batch, self.embedding_dim)\n\n for _ in range(self.seq_len):\n output, state_tuple = self.decoder(decoder_input, state_tuple)\n rel_pos = self.hidden2pos(output.view(-1, self.h_dim))\n curr_pos = rel_pos + last_pos\n\n if self.pool_every_timestep:\n decoder_h = state_tuple[0]\n pool_h = self.pool_net(decoder_h, seq_start_end, curr_pos)\n decoder_h = torch.cat([decoder_h.view(-1, self.h_dim), pool_h], dim=1)\n decoder_h = self.mlp(decoder_h)\n decoder_h = torch.unsqueeze(decoder_h, 0)\n state_tuple = (decoder_h, state_tuple[1])\n\n embedding_input = rel_pos\n\n decoder_input = self.spatial_embedding(embedding_input)\n decoder_input = decoder_input.view(1, batch, self.embedding_dim)\n pred_traj_fake_rel.append(rel_pos.view(batch, -1))\n last_pos = curr_pos\n\n pred_traj_fake_rel = torch.stack(pred_traj_fake_rel, dim=0)\n return pred_traj_fake_rel, state_tuple[0]\n\n\nclass PoolHiddenNet(nn.Module):\n \"\"\"Pooling module as proposed in our paper\"\"\"\n\n def __init__(\n self, embedding_dim=64, h_dim=64, mlp_dim=1024, bottleneck_dim=1024,\n activation='relu', batch_norm=True, dropout=0.0\n ):\n super(PoolHiddenNet, self).__init__()\n\n self.mlp_dim = mlp_dim\n self.h_dim = h_dim\n self.bottleneck_dim = bottleneck_dim\n self.embedding_dim = embedding_dim\n\n mlp_pre_dim = embedding_dim + h_dim\n mlp_pre_pool_dims = [mlp_pre_dim, 512, bottleneck_dim]\n\n self.spatial_embedding = nn.Linear(2, embedding_dim)\n self.mlp_pre_pool = make_mlp(\n mlp_pre_pool_dims,\n activation=activation,\n batch_norm=batch_norm,\n dropout=dropout)\n\n def repeat(self, tensor, num_reps):\n \"\"\"\n Inputs:\n -tensor: 2D tensor of any shape\n -num_reps: Number of times to repeat each row\n Outpus:\n -repeat_tensor: Repeat each row such that: R1, R1, R2, R2\n \"\"\"\n col_len = tensor.size(1)\n tensor = tensor.unsqueeze(dim=1).repeat(1, num_reps, 1)\n tensor = tensor.view(-1, col_len)\n return tensor\n\n def forward(self, h_states, seq_start_end, end_pos):\n \"\"\"\n Inputs:\n - h_states: Tensor of shape (num_layers, batch, h_dim)\n - seq_start_end: A list of tuples which delimit sequences within batch\n - end_pos: Tensor of shape (batch, 2)\n Output:\n - pool_h: Tensor of shape (batch, bottleneck_dim)\n \"\"\"\n pool_h = []\n for _, (start, end) in enumerate(seq_start_end):\n start = start.item()\n end = end.item()\n num_ped = end - start\n curr_hidden = h_states.view(-1, self.h_dim)[start:end]\n curr_end_pos = end_pos[start:end]\n # Repeat -> H1, H2, H1, H2\n curr_hidden_1 = curr_hidden.repeat(num_ped, 1)\n # Repeat position -> P1, P2, P1, P2\n curr_end_pos_1 = curr_end_pos.repeat(num_ped, 1)\n # Repeat position -> P1, P1, P2, P2\n curr_end_pos_2 = self.repeat(curr_end_pos, num_ped)\n curr_rel_pos = curr_end_pos_1 - curr_end_pos_2\n curr_rel_embedding = self.spatial_embedding(curr_rel_pos)\n mlp_h_input = torch.cat([curr_rel_embedding, curr_hidden_1], dim=1)\n curr_pool_h = self.mlp_pre_pool(mlp_h_input)\n curr_pool_h = curr_pool_h.view(num_ped, num_ped, -1).max(1)[0]\n pool_h.append(curr_pool_h)\n pool_h = torch.cat(pool_h, dim=0)\n return pool_h\n\n\nclass SocialPooling(nn.Module):\n \"\"\"Current state of the art pooling mechanism:\n http://cvgl.stanford.edu/papers/CVPR16_Social_LSTM.pdf\"\"\"\n\n def __init__(\n self, h_dim=64, activation='relu', batch_norm=True, dropout=0.0,\n neighborhood_size=2.0, grid_size=8, pool_dim=None\n ):\n super(SocialPooling, self).__init__()\n self.h_dim = h_dim\n self.grid_size = grid_size\n self.neighborhood_size = neighborhood_size\n if pool_dim:\n mlp_pool_dims = [grid_size * grid_size * h_dim, pool_dim]\n else:\n mlp_pool_dims = [grid_size * grid_size * h_dim, h_dim]\n\n self.mlp_pool = make_mlp(\n mlp_pool_dims,\n activation=activation,\n batch_norm=batch_norm,\n dropout=dropout\n )\n\n def get_bounds(self, ped_pos):\n top_left_x = ped_pos[:, 0] - self.neighborhood_size / 2\n top_left_y = ped_pos[:, 1] + self.neighborhood_size / 2\n bottom_right_x = ped_pos[:, 0] + self.neighborhood_size / 2\n bottom_right_y = ped_pos[:, 1] - self.neighborhood_size / 2\n top_left = torch.stack([top_left_x, top_left_y], dim=1)\n bottom_right = torch.stack([bottom_right_x, bottom_right_y], dim=1)\n return top_left, bottom_right\n\n def get_grid_locations(self, top_left, other_pos):\n cell_x = torch.floor(\n ((other_pos[:, 0] - top_left[:, 0]) / self.neighborhood_size) *\n self.grid_size)\n cell_y = torch.floor(\n ((top_left[:, 1] - other_pos[:, 1]) / self.neighborhood_size) *\n self.grid_size)\n grid_pos = cell_x + cell_y * self.grid_size\n return grid_pos\n\n def repeat(self, tensor, num_reps):\n \"\"\"\n Inputs:\n -tensor: 2D tensor of any shape\n -num_reps: Number of times to repeat each row\n Outpus:\n -repeat_tensor: Repeat each row such that: R1, R1, R2, R2\n \"\"\"\n col_len = tensor.size(1)\n tensor = tensor.unsqueeze(dim=1).repeat(1, num_reps, 1)\n tensor = tensor.view(-1, col_len)\n return tensor\n\n def forward(self, h_states, seq_start_end, end_pos):\n \"\"\"\n Inputs:\n - h_states: Tesnsor of shape (num_layers, batch, h_dim)\n - seq_start_end: A list of tuples which delimit sequences within batch.\n - end_pos: Absolute end position of obs_traj (batch, 2)\n Output:\n - pool_h: Tensor of shape (batch, h_dim)\n \"\"\"\n pool_h = []\n for _, (start, end) in enumerate(seq_start_end):\n start = start.item()\n end = end.item()\n num_ped = end - start\n grid_size = self.grid_size * self.grid_size\n curr_hidden = h_states.view(-1, self.h_dim)[start:end]\n curr_hidden_repeat = curr_hidden.repeat(num_ped, 1)\n curr_end_pos = end_pos[start:end]\n curr_pool_h_size = (num_ped * grid_size) + 1\n curr_pool_h = curr_hidden.new_zeros((curr_pool_h_size, self.h_dim))\n # curr_end_pos = curr_end_pos.data\n top_left, bottom_right = self.get_bounds(curr_end_pos)\n\n # Repeat position -> P1, P2, P1, P2\n curr_end_pos = curr_end_pos.repeat(num_ped, 1)\n # Repeat bounds -> B1, B1, B2, B2\n top_left = self.repeat(top_left, num_ped)\n bottom_right = self.repeat(bottom_right, num_ped)\n\n grid_pos = self.get_grid_locations(top_left, curr_end_pos).type_as(seq_start_end)\n # Make all positions to exclude as non-zero\n # Find which peds to exclude\n x_bound = ((curr_end_pos[:, 0] >= bottom_right[:, 0]) +\n (curr_end_pos[:, 0] <= top_left[:, 0]))\n y_bound = ((curr_end_pos[:, 1] >= top_left[:, 1]) +\n (curr_end_pos[:, 1] <= bottom_right[:, 1]))\n\n within_bound = x_bound + y_bound\n within_bound[0::num_ped + 1] = 1 # Don't include the ped itself\n within_bound = within_bound.view(-1)\n\n # This is a tricky way to get scatter add to work. Helps me avoid a\n # for loop. Offset everything by 1. Use the initial 0 position to\n # dump all uncessary adds.\n grid_pos += 1\n total_grid_size = self.grid_size * self.grid_size\n offset = torch.arange(\n 0, total_grid_size * num_ped, total_grid_size\n ).type_as(seq_start_end)\n\n offset = self.repeat(offset.view(-1, 1), num_ped).view(-1)\n grid_pos += offset\n grid_pos[within_bound != 0] = 0\n grid_pos = grid_pos.view(-1, 1).expand_as(curr_hidden_repeat)\n\n curr_pool_h = curr_pool_h.scatter_add(0, grid_pos, curr_hidden_repeat)\n curr_pool_h = curr_pool_h[1:]\n pool_h.append(curr_pool_h.view(num_ped, -1))\n\n pool_h = torch.cat(pool_h, dim=0)\n pool_h = self.mlp_pool(pool_h)\n return pool_h\n\n\nclass TrajectoryGenerator(nn.Module):\n def __init__(\n self, obs_len, pred_len, embedding_dim=64, encoder_h_dim=64,\n decoder_h_dim=128, mlp_dim=1024, num_layers=1, noise_dim=(0,),\n noise_type='gaussian', noise_mix_type='ped', pooling_type=None,\n pool_every_timestep=True, dropout=0.0, bottleneck_dim=1024,\n activation='relu', batch_norm=True, neighborhood_size=2.0, grid_size=8\n ):\n super(TrajectoryGenerator, self).__init__()\n\n if pooling_type and pooling_type.lower() == 'none':\n pooling_type = None\n\n self.obs_len = obs_len\n self.pred_len = pred_len\n self.mlp_dim = mlp_dim\n self.encoder_h_dim = encoder_h_dim\n self.decoder_h_dim = decoder_h_dim\n self.embedding_dim = embedding_dim\n self.noise_dim = noise_dim\n self.num_layers = num_layers\n self.noise_type = noise_type\n self.noise_mix_type = noise_mix_type\n self.pooling_type = pooling_type\n self.noise_first_dim = 0\n self.pool_every_timestep = pool_every_timestep\n self.bottleneck_dim = 1024\n\n self.encoder = Encoder(\n embedding_dim=embedding_dim,\n h_dim=encoder_h_dim,\n mlp_dim=mlp_dim,\n num_layers=num_layers,\n dropout=dropout,\n obs_len=obs_len\n )\n\n self.decoder = Decoder(\n pred_len,\n embedding_dim=embedding_dim,\n h_dim=decoder_h_dim,\n mlp_dim=mlp_dim,\n num_layers=num_layers,\n pool_every_timestep=pool_every_timestep,\n dropout=dropout,\n bottleneck_dim=bottleneck_dim,\n activation=activation,\n batch_norm=batch_norm,\n pooling_type=pooling_type,\n grid_size=grid_size,\n neighborhood_size=neighborhood_size\n )\n\n if pooling_type == 'pool_net':\n self.pool_net = PoolHiddenNet(\n embedding_dim=self.embedding_dim,\n h_dim=encoder_h_dim,\n mlp_dim=mlp_dim,\n bottleneck_dim=bottleneck_dim,\n activation=activation,\n batch_norm=batch_norm\n )\n elif pooling_type == 'spool':\n self.pool_net = SocialPooling(\n h_dim=encoder_h_dim,\n activation=activation,\n batch_norm=batch_norm,\n dropout=dropout,\n neighborhood_size=neighborhood_size,\n grid_size=grid_size,\n pool_dim=bottleneck_dim\n )\n\n if self.noise_dim[0] == 0:\n self.noise_dim = None\n else:\n self.noise_first_dim = noise_dim[0]\n\n # Decoder Hidden\n if pooling_type:\n input_dim = encoder_h_dim + bottleneck_dim\n else:\n input_dim = encoder_h_dim\n\n if self.mlp_decoder_needed():\n mlp_decoder_context_dims = [\n input_dim, mlp_dim, decoder_h_dim - self.noise_first_dim\n ]\n\n self.mlp_decoder_context = make_mlp(\n mlp_decoder_context_dims,\n activation=activation,\n batch_norm=batch_norm,\n dropout=dropout\n )\n\n def add_noise(self, _input, seq_start_end, user_noise=None):\n \"\"\"\n Inputs:\n - _input: Tensor of shape (_, decoder_h_dim - noise_first_dim)\n - seq_start_end: A list of tuples which delimit sequences within batch.\n - user_noise: Generally used for inference when you want to see\n relation between different types of noise and outputs.\n Outputs:\n - decoder_h: Tensor of shape (_, decoder_h_dim)\n \"\"\"\n if not self.noise_dim:\n return _input\n\n if self.noise_mix_type == 'global':\n noise_shape = (seq_start_end.size(0),) + self.noise_dim\n else:\n noise_shape = (_input.size(0),) + self.noise_dim\n\n if user_noise is not None:\n z_decoder = user_noise\n else:\n z_decoder = get_noise(noise_shape, self.noise_type)\n\n if self.noise_mix_type == 'global':\n _list = []\n for idx, (start, end) in enumerate(seq_start_end):\n start = start.item()\n end = end.item()\n _vec = z_decoder[idx].view(1, -1)\n _to_cat = _vec.repeat(end - start, 1)\n _list.append(torch.cat([_input[start:end], _to_cat], dim=1))\n decoder_h = torch.cat(_list, dim=0)\n return decoder_h\n\n decoder_h = torch.cat([_input, z_decoder], dim=1)\n\n return decoder_h\n\n def mlp_decoder_needed(self):\n if (\n self.noise_dim or self.pooling_type or\n self.encoder_h_dim != self.decoder_h_dim\n ):\n return True\n else:\n return False\n\n def forward(self, obs_traj, obs_traj_rel, seq_start_end, user_noise=None):\n \"\"\"\n Inputs:\n - obs_traj: Tensor of shape (obs_len, batch, 2)\n - obs_traj_rel: Tensor of shape (obs_len, batch, 2)\n - seq_start_end: A list of tuples which delimit sequences within batch.\n - user_noise: Generally used for inference when you want to see\n relation between different types of noise and outputs.\n Output:\n - pred_traj_rel: Tensor of shape (self.pred_len, batch, 2)\n \"\"\"\n batch = obs_traj_rel.size(1)\n # Encode seq\n final_encoder_h = self.encoder(obs_traj_rel)\n # Pool States\n if self.pooling_type:\n end_pos = obs_traj[-1, :, :]\n pool_h = self.pool_net(final_encoder_h, seq_start_end, end_pos)\n # Construct input hidden states for decoder\n mlp_decoder_context_input = torch.cat([final_encoder_h.view(-1, self.encoder_h_dim), pool_h], dim=1)\n else:\n mlp_decoder_context_input = final_encoder_h.view(-1, self.encoder_h_dim)\n\n # Add Noise\n if self.mlp_decoder_needed():\n noise_input = self.mlp_decoder_context(mlp_decoder_context_input)\n else:\n noise_input = mlp_decoder_context_input\n\n decoder_h = self.add_noise(noise_input, seq_start_end, user_noise=user_noise)\n decoder_h = torch.unsqueeze(decoder_h, 0)\n decoder_c = torch.zeros(self.num_layers, batch, self.decoder_h_dim).cuda()\n\n last_pos = obs_traj[-1]\n last_pos_rel = obs_traj_rel[-1]\n state_tuple = (decoder_h, decoder_c)\n\n # Predict Trajectory\n decoder_out = self.decoder(\n last_pos,\n last_pos_rel,\n state_tuple,\n seq_start_end,\n )\n pred_traj_fake_rel, final_decoder_h = decoder_out\n\n return pred_traj_fake_rel\n\n\nclass TrajectoryDiscriminator(nn.Module):\n def __init__(\n self, obs_len, pred_len, embedding_dim=64, h_dim=64, mlp_dim=1024,\n num_layers=1, activation='relu', batch_norm=True, dropout=0.0,\n d_type='local'\n ):\n super(TrajectoryDiscriminator, self).__init__()\n\n self.obs_len = obs_len\n self.pred_len = pred_len\n self.seq_len = obs_len + pred_len\n self.mlp_dim = mlp_dim\n self.h_dim = h_dim\n self.d_type = d_type\n\n self.encoder = Encoder(\n embedding_dim=embedding_dim,\n h_dim=h_dim,\n mlp_dim=mlp_dim,\n num_layers=num_layers,\n dropout=dropout,\n obs_len=obs_len + pred_len\n )\n\n real_classifier_dims = [h_dim, mlp_dim, 1]\n self.real_classifier = make_mlp(\n real_classifier_dims,\n activation=activation,\n batch_norm=batch_norm,\n dropout=dropout\n )\n if d_type == 'global':\n mlp_pool_dims = [h_dim + embedding_dim, mlp_dim, h_dim]\n self.pool_net = PoolHiddenNet(\n embedding_dim=embedding_dim,\n h_dim=h_dim,\n mlp_dim=mlp_pool_dims,\n bottleneck_dim=h_dim,\n activation=activation,\n batch_norm=batch_norm\n )\n\n def forward(self, traj, traj_rel, seq_start_end=None):\n \"\"\"\n Inputs:\n - traj: Tensor of shape (obs_len + pred_len, batch, 2)\n - traj_rel: Tensor of shape (obs_len + pred_len, batch, 2)\n - seq_start_end: A list of tuples which delimit sequences within batch\n Output:\n - scores: Tensor of shape (batch,) with real/fake scores\n \"\"\"\n final_h = self.encoder(traj_rel)\n # Note: In case of 'global' option we are using start_pos as opposed to\n # end_pos. The intution being that hidden state has the whole\n # trajectory and relative postion at the start when combined with\n # trajectory information should help in discriminative behavior.\n if self.d_type == 'local':\n classifier_input = final_h.squeeze()\n else:\n classifier_input = self.pool_net(final_h.squeeze(), seq_start_end, traj[0])\n scores = self.real_classifier(classifier_input)\n return scores\n"
]
| [
[
"torch.nn.Sequential",
"torch.nn.Softmax",
"torch.nn.BatchNorm1d",
"torch.nn.Dropout",
"torch.floor",
"torch.cat",
"torch.nn.LSTM",
"torch.randn",
"torch.zeros",
"torch.unsqueeze",
"torch.nn.Linear",
"torch.nn.LeakyReLU",
"torch.rand",
"torch.arange",
"torch.stack",
"torch.nn.ReLU"
]
]
|
hjjpku/adaptive_sampler | [
"cf523af233c8b02c71e07d1d599e634c5ea1d634"
]
| [
"models/wide_resnet.py"
]
| [
"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable\r\nimport math\r\nfrom functools import partial\r\n\r\n__all__ = ['WideResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101']\r\n\r\n\r\ndef conv3x3x3(in_planes, out_planes, stride=1):\r\n # 3x3x3 convolution with padding\r\n return nn.Conv3d(\r\n in_planes,\r\n out_planes,\r\n kernel_size=3,\r\n stride=stride,\r\n padding=1,\r\n bias=False)\r\n\r\n\r\ndef downsample_basic_block(x, planes, stride):\r\n out = F.avg_pool3d(x, kernel_size=1, stride=stride)\r\n zero_pads = torch.Tensor(\r\n out.size(0), planes - out.size(1), out.size(2), out.size(3),\r\n out.size(4)).zero_()\r\n if isinstance(out.data, torch.cuda.FloatTensor):\r\n zero_pads = zero_pads.cuda()\r\n\r\n out = Variable(torch.cat([out.data, zero_pads], dim=1))\r\n\r\n return out\r\n\r\n\r\nclass WideBottleneck(nn.Module):\r\n expansion = 2\r\n\r\n def __init__(self, inplanes, planes, stride=1, downsample=None):\r\n super(WideBottleneck, self).__init__()\r\n self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)\r\n self.bn1 = nn.BatchNorm3d(planes)\r\n self.conv2 = nn.Conv3d(\r\n planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\r\n self.bn2 = nn.BatchNorm3d(planes)\r\n self.conv3 = nn.Conv3d(\r\n planes, planes * self.expansion, kernel_size=1, bias=False)\r\n self.bn3 = nn.BatchNorm3d(planes * self.expansion)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.downsample = downsample\r\n self.stride = stride\r\n\r\n def forward(self, x):\r\n residual = x\r\n\r\n out = self.conv1(x)\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv3(out)\r\n out = self.bn3(out)\r\n\r\n if self.downsample is not None:\r\n residual = self.downsample(x)\r\n\r\n out += residual\r\n out = self.relu(out)\r\n\r\n return out\r\n\r\n\r\nclass WideResNet(nn.Module):\r\n\r\n def __init__(self,\r\n block,\r\n layers,\r\n sample_size,\r\n sample_duration,\r\n k=1,\r\n shortcut_type='B',\r\n num_classes=400):\r\n self.inplanes = 64\r\n super(WideResNet, self).__init__()\r\n self.conv1 = nn.Conv3d(\r\n 3,\r\n 64,\r\n kernel_size=7,\r\n stride=(1, 2, 2),\r\n padding=(3, 3, 3),\r\n bias=False)\r\n self.bn1 = nn.BatchNorm3d(64)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.maxpool = nn.MaxPool3d(kernel_size=(3, 3, 3), stride=2, padding=1)\r\n self.layer1 = self._make_layer(block, 64 * k, layers[0], shortcut_type)\r\n self.layer2 = self._make_layer(\r\n block, 128 * k, layers[1], shortcut_type, stride=2)\r\n self.layer3 = self._make_layer(\r\n block, 256 * k, layers[2], shortcut_type, stride=2)\r\n self.layer4 = self._make_layer(\r\n block, 512 * k, layers[3], shortcut_type, stride=2)\r\n last_duration = int(math.ceil(sample_duration / 16))\r\n last_size = int(math.ceil(sample_size / 32))\r\n self.avgpool = nn.AvgPool3d(\r\n (last_duration, last_size, last_size), stride=1)\r\n self.fc = nn.Linear(512 * k * block.expansion, num_classes)\r\n\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv3d):\r\n m.weight = nn.init.kaiming_normal(m.weight, mode='fan_out')\r\n elif isinstance(m, nn.BatchNorm3d):\r\n m.weight.data.fill_(1)\r\n m.bias.data.zero_()\r\n\r\n def _make_layer(self, block, planes, blocks, shortcut_type, stride=1):\r\n downsample = None\r\n if stride != 1 or self.inplanes != planes * block.expansion:\r\n if shortcut_type == 'A':\r\n downsample = partial(\r\n downsample_basic_block,\r\n planes=planes * block.expansion,\r\n stride=stride)\r\n else:\r\n downsample = nn.Sequential(\r\n nn.Conv3d(\r\n self.inplanes,\r\n planes * block.expansion,\r\n kernel_size=1,\r\n stride=stride,\r\n bias=False), nn.BatchNorm3d(planes * block.expansion))\r\n\r\n layers = []\r\n layers.append(block(self.inplanes, planes, stride, downsample))\r\n self.inplanes = planes * block.expansion\r\n for i in range(1, blocks):\r\n layers.append(block(self.inplanes, planes))\r\n\r\n return nn.Sequential(*layers)\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n x = self.bn1(x)\r\n x = self.relu(x)\r\n x = self.maxpool(x)\r\n\r\n x = self.layer1(x)\r\n x = self.layer2(x)\r\n x = self.layer3(x)\r\n x = self.layer4(x)\r\n\r\n x = self.avgpool(x)\r\n\r\n x = x.view(x.size(0), -1)\r\n x = self.fc(x)\r\n\r\n return x\r\n\r\n\r\ndef get_fine_tuning_parameters(model, ft_begin_index):\r\n if ft_begin_index == 0:\r\n return model.parameters()\r\n\r\n ft_module_names = []\r\n for i in range(ft_begin_index, 5):\r\n ft_module_names.append('layer{}'.format(i))\r\n ft_module_names.append('fc')\r\n\r\n parameters = []\r\n for k, v in model.named_parameters():\r\n for ft_module in ft_module_names:\r\n if ft_module in k:\r\n parameters.append({'params': v})\r\n break\r\n else:\r\n parameters.append({'params': v, 'lr': 0.0})\r\n\r\n return parameters\r\n\r\n\r\ndef resnet50(**kwargs):\r\n \"\"\"Constructs a ResNet-50 model.\r\n \"\"\"\r\n model = WideResNet(WideBottleneck, [3, 4, 6, 3], **kwargs)\r\n return model\r\n"
]
| [
[
"torch.nn.AvgPool3d",
"torch.nn.Sequential",
"torch.nn.init.kaiming_normal",
"torch.cat",
"torch.nn.MaxPool3d",
"torch.nn.Conv3d",
"torch.nn.Linear",
"torch.nn.functional.avg_pool3d",
"torch.nn.ReLU",
"torch.nn.BatchNorm3d"
]
]
|
librairy/explainable-qa | [
"7ea753229769ce1f6d09d59d7eab67df7aef2f78"
]
| [
"test/datasets/VQuAnDa/EQAKGMetrics.py"
]
| [
"import requests\nimport json\nimport enchant\nimport csv\nimport re\nimport time\nimport itertools\nfrom sacrebleu import sentence_bleu\nimport multiprocessing as mp\nimport os\nimport pandas as pd\nimport nltk\nfrom pprint import pprint\n\ndef jsonToDict(route) -> dict:\n '''\n Funcion auxiliar que dada la ruta de un json, lo abre y lo convierte a lista de diccionarios\n '''\n with open(route, encoding=\"utf-8\") as f:\n return json.load(f)\n\ndef queryJSON(queryURL, json):\n '''\n Funcion auxiliar que dado un JSON con una pregunta, realiza una consulta (con esta pregunta) a una URL\n '''\n question = json['question']\n files = {\n 'question': (None, question),\n }\n '''\n En caso de que quisiesemos la respuesta verbalizada o larga, hacer la request con params = payload:\n payload = {\n ('text', 'true')\n }\n '''\n response = requests.get(queryURL, files = files)\n #Obtenemos la respuesta como JSonObject y la devolvemos\n return response.json()\n\ndef exactMatchScore(string1,string2):\n '''\n Funcion auxiliar que incorpora la medida EM (Exact Match). 1 si ambas cadenas son iguales, 0 e.o.c.\n Para listas de cadenas, comprueba si ambas contienen los mismos elementos (no importa el orden)\n '''\n if (\",\" in string1) and (\",\" in string2):\n string1 = string1.split(\",\")\n string2 = string2.split(\",\")\n return int((len(string1) == len(string2)) and (set(string1) == set(string2)))\n return int(string1 == string2)\n\ndef writeResults(csvRoute, rows, counter, question, modelAnswerLong, obtainedAnswer, queryTime, textLen): \n '''\n Funcion auxiliar que extrae la respuesta que se espera, hace la distancia de levenshtein y añade a la lista de filas:\n -Pregunta\n -Respuesta modelo y nuestra respuesta\n -Métricas con respecto a la respuesta modelo (Distancia Levenshtein, BLEU, EM, Meteor...)\n -Tiempo que ha tardado en ejecutarse la consulta\n -Longitud del texto del que se ha obtenido nuestra respuesta\n -Si la pregunta dada tiene respuesta modelo o no\n ''' \n #La respuesta esperada se obtiene con una expresion regular (sacar texto entre corchetes)\n modelAnswerLongGroups = re.search(r\"\\[([^\\)]+)\\]\", modelAnswerLong)\n if(modelAnswerLongGroups is not None):\n modelAnswer = modelAnswerLongGroups.group(1)\n isAnswered = \"YES\"\n if modelAnswer == \"answer\":\n isAnswered = \"NO\" \n distance = \"None\"\n if obtainedAnswer is not None:\n distance = enchant.utils.levenshtein(modelAnswer,obtainedAnswer)*100\n reference = modelAnswer.split()\n candidate = obtainedAnswer.split()\n \n rows.append( [question, modelAnswer, obtainedAnswer, distance, sentence_bleu(obtainedAnswer,[modelAnswer]).score, nltk.translate.bleu_score.sentence_bleu([modelAnswer], obtainedAnswer)*100, nltk.translate.meteor_score.single_meteor_score([modelAnswer], [obtainedAnswer]), exactMatchScore(reference,candidate), queryTime, textLen, isAnswered] )\n counter.value += 1\n #print(\"Contador: \", counter.value)\n\n #Escribimos cuando el valor del contador llegue a 24\n if(counter.value != 0 and counter.value % 8 == 0):\n #print(\"Escribiendo. Contador: \", counter.value)\n with open(csvRoute, 'a', newline='', encoding=\"utf-8\") as f:\n (pd.DataFrame.from_records(rows, columns=header)).to_csv(f, header=False, index=False, sep=';', quoting=csv.QUOTE_ALL)\n rows[:] = []\n f.close()\n\n\ndef evaluateQuestion(csvRoute, i, rows, counter, queryURL):\n '''\n Funcion auxiliar para paralelizar la ejecucion de consultas y escritura en csv de resultados. Realiza la consulta (midiendo el tiempo que tarda) y llama a writeResults\n '''\n #print(\"Process id: \", os.getpid())\n #print(\"Question: \", i['question']) \n #Para medir el tiempo que se tarda en ejecutar la consulta\n queryStartTime = time.time()\n jsonResponse = queryJSON(queryURL,i)\n queryTime = round((time.time() - queryStartTime),2)\n\n #Pasamos las respuestas a minuscula y llamamos a extractAndCompare.\n writeResults(csvRoute, rows, counter, i['question'], i['verbalized_answer'].lower(),jsonResponse['answer'].lower(),queryTime,jsonResponse['textLen'])\n\ndef EQAKGMetrics(pool, rows, counter, JSONroute, queryURL, csvRoute):\n '''\n Funcion que dado un JSON con preguntas y respuestas (asumimos que las preguntas están en la clave 'question' del JSON, y las respuestas en 'verbalized_answers'), \n una url a través de la cual realizar consultas y un csv donde guardar los resultados, hace una serie de metricas:\n - Realiza las preguntas del JSON dado\n - Lo compara con la respuesta esperada y obtiene varias metricas de rendimiento (Distancia de Levenshtein, BLEU, EM,...)\n - Escribe en el CSV la pregunta, la respuesta esperada, la respuesta obtenida y estas metricas\n '''\n VQuandaData = jsonToDict(JSONroute)\n\n #Escribimos el Header\n with open(csvRoute,'w', newline='', encoding=\"utf-8\") as f:\n\n csvwriter = csv.writer(f,delimiter=';', quotechar='\"', quoting=csv.QUOTE_ALL)\n global header\n csvwriter.writerow(header)\n f.close()\n \n for i in VQuandaData:\n #Paraleliza con metodos asincronos\n pool.apply_async(evaluateQuestion, (csvRoute,i,rows,counter,queryURL))\n\n pool.close()\n pool.join()\n\n #Escribimos lo que quede\n with open(csvRoute, 'a', newline='', encoding=\"utf-8\") as f:\n (pd.DataFrame.from_records(rows, columns=header)).to_csv(f,header=False, index=False, sep=';', quoting=csv.QUOTE_ALL)\n f.close()\n\n#Creamos el array donde guardaremos las columnas y el contador como variables globales para que sean accesibles por los multiprocesos\nrows = None\ncounter = None\nheader = [\"Question\", \"Answer\", \"Response\", \"Levenshtein Distance\",\"BLEU Score (SacreBleu)\",\"BLEU Score (ntlk)\",\"Meteor Score\",\"EM Score\",\"Query Time\",\"Text Length\",\"Is Answered\"]\n\nif __name__ == '__main__':\n\n with mp.Manager() as manager:\n\n rows = manager.list([])\n counter = manager.Value('i', 0)\n\n pool = mp.Pool(processes=6, initargs = (counter,rows,))\n\n queryUrl = \"http://localhost:5000/eqakg/dbpedia/en?text=true\"\n #queryUrl = \"https://librairy.linkeddata.es/eqakg/dbpedia/en?text=false\" \n\n EQAKGMetrics(pool,rows,counter,\"data/test.json\",queryUrl,\"results/VQuanda.csv\")"
]
| [
[
"pandas.DataFrame.from_records"
]
]
|
COFS-UWA/MPM3D | [
"1a0c5dc4e92dff3855367846002336ca5a18d124"
]
| [
"PyTests/consolidation_1d_disp_curve.py"
]
| [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport h5py as py\n\nfrom OneDConsolidation import OneDConsolidation\n\nfig = plt.figure()\nplot1 = fig.subplots(1, 1)\nplot1.set_xlabel(\"time\")\nplot1.set_ylabel(\"displacement\")\n\nout_time = []\npcl_var = []\n\n# numerical solution\nhdf5_file = py.File(\"..\\\\Build\\\\Tests\\\\t3d_chm_s_1d_consolidation.h5\", \"r\")\nth_grp = hdf5_file['TimeHistory']['consolidation']\n\noutput_num = th_grp.attrs['output_num']\nis_init = False\ninit_z = 0.0\nfor t_id in range(output_num):\n # frame\n frame_grp = th_grp['frame_%d' % t_id]\n frame_time = frame_grp.attrs['total_time']\n out_time.append(frame_time)\n # particle\n pcl_dset = frame_grp['ParticleData']['field']\n pcl_fld = pcl_dset[728]\n var = pcl_fld['z']\n if not is_init:\n init_z = var\n is_init = True\n var = var - init_z\n pcl_var.append(var)\n\nhdf5_file.close()\n\nline1, = plot1.plot(out_time, pcl_var)\n\n# analytical solution\nu0 = 1.0\nH = 1.0\nE = 1000.0\nniu = 0.0 # possion ratio\nkv = 1.0e-4\nmiu = 1.0 # dynamic viscosity\n\nEs = (1 - niu) / (1 + niu) / (1 - 2.0*niu) * E # Es = (1-v) / (1 + v) / (1-2v) * E\nCv = kv * Es / miu\ncon_res = OneDConsolidation(Cv, Es, u0, H)\ntime = 10.0 # time of consolidation\ndata_num = 100\nt_list = np.zeros(data_num + 2)\nu_list = np.zeros(data_num + 2)\nt_list[0] = 0.0\nu_list[0] = 0.0\nt_list[1] = 0.0 # time for equilibrium\nu_list[1] = u_list[0]\nfor i in range(data_num):\n t_list[i + 2] = time * float(i) / float(data_num)\n u_list[i + 2] = con_res.calSettlement(t_list[i + 2])\n t_list[i + 2] += t_list[1]\n\nline2, = plot1.plot(t_list, u_list, 'r--')\n# with open(\"consolidation_disp_ana_SE.csv\", \"w\") as out_file:\n # for i in range(len(t_list)):\n # out_file.write(\"%f, %f\\n\" % (t_list[i], u_list[i]))\n\nplt.legend(handles=[line1, line2], labels=['MPM', 'Analytical Solution'])\nplt.show()\n"
]
| [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
]
|
kpatvt/sim21 | [
"4cbbfcbef6371d3dc5404429545e003a48c69ba5"
]
| [
"sim21/data/twu.py"
]
| [
"import math\nfrom scipy.optimize import fsolve\nfrom sim21.data.chemsep_consts import GAS_CONSTANT\nfrom sim21.data.eqn import eval_eqn, eval_eqn_int, eval_eqn_int_over_t\nimport numpy as np\n\n\ndef fixed_properties(tb, sg, mw):\n \"\"\"\n Obtain the key fixed properties using the Twu correlations\n :param tb: boiling point temperature in K\n :return: Tc (in K), Pc (in Pa), Vc (m3/kmol), MW, Omega\n \"\"\"\n tb_R = tb * 1.8\n\n t1 = 0.533272 + 0.191017e-3 * tb_R + 0.779681e-7 * (tb_R ** 2) - 0.284376e-10 * (tb_R ** 3)\n t1 += 0.959468e28 * (tb_R ** -13)\n\n tc_dot_R = tb_R * (1 / t1)\n alpha = 1 - tb_R / tc_dot_R\n\n sg_dot = 0.843593 - 0.128624 * alpha - 3.336159 * (alpha ** 3) - 13749.5 * (alpha ** 12)\n\n t2 = 0.419869 - 0.505839 * alpha - 1.5436 * (alpha ** 3) - 9481.70 * (alpha ** 14)\n vc_dot_ft3_lb_mol = (1 - t2) ** (-8)\n\n # Iterate for mw_dot\n mw_dot_trial = tb_R / (10.44 - 0.0052 * tb_R)\n theta_trial = math.log(mw_dot_trial)\n\n def tb_R_error(theta_value):\n temp1 = 5.71419 + 2.7157 * theta_value - 0.286590 * (theta_value ** 2)\n temp1 = temp1 - 39.8544 / theta_value - 0.122488 / (theta_value ** 2)\n return (math.exp(temp1) - 24.7522 * theta_value + 35.3155 * (theta_value ** 2)) - tb_R\n\n theta = fsolve(tb_R_error, theta_trial)[0]\n mw_dot = math.exp(theta)\n\n alpha = 1 - tb_R / tc_dot_R\n t1 = 3.83353 + 1.19629 * (alpha ** 0.5) + 34.8888 * alpha + 36.1952 * (alpha ** 2)\n t1 += 104.193 * (alpha ** 4)\n pc_dot_psi = t1 ** 2\n\n delta_sg_t = math.exp(5 * (sg_dot - sg)) - 1\n t1 = -0.362456 / (tb_R ** 0.5) + (0.0398285 - 0.948125 / (tb_R ** 0.5)) * delta_sg_t\n f_t = delta_sg_t * t1\n tc_R = tc_dot_R * (((1 + 2 * f_t) / (1 - 2 * f_t)) ** 2)\n\n delta_sg_v = math.exp(4 * (sg_dot ** 2 - sg ** 2)) - 1\n t1 = 0.466590 / (tb_R ** 0.5) + (-0.182421 + 3.01721 / (tb_R ** 0.5)) * delta_sg_v\n f_v = delta_sg_v * t1\n vc_ft3_lb_mol = vc_dot_ft3_lb_mol * (((1 + 2 * f_v) / (1 - 2 * f_v)) ** 2)\n\n delta_sg_p = math.exp(0.5 * (sg_dot - sg)) - 1\n t1 = 2.53262 - 46.1955 / (tb_R ** 0.5) - 0.00127885 * tb_R\n t2 = -11.4277 + 252.140 / (tb_R ** 0.5) + 0.00230535 * tb_R\n f_p = delta_sg_p * (t1 + t2 * delta_sg_p)\n t3 = ((1 + 2 * f_p) / (1 - 2 * f_p)) ** 2\n pc_psi = pc_dot_psi * (tc_R / tc_dot_R) * (vc_dot_ft3_lb_mol / vc_ft3_lb_mol) * t3\n\n delta_sg_m = math.exp(5 * (sg_dot - sg)) - 1\n x = abs(0.0123420 - 0.328086 / (tb_R ** 0.5))\n f_m = delta_sg_m * (x + (-0.0175691 + 0.193168 / (tb_R ** 0.5)) * delta_sg_m)\n ln_mw = math.log(mw_dot) * (((1 + 2 * f_m) / (1 - 2 * f_m)) ** 2)\n mw_calc = math.exp(ln_mw)\n\n if mw is None:\n mw = mw_calc\n\n tr = tb_R / tc_R\n\n ln_pr_0 = (-5.96346 * (1 - tr) + 1.17639 * ((1 - tr) ** 1.5) - 0.559607 * ((1 - tr) ** 3) - 1.31901 * (\n (1 - tr) ** 6)) * (1 / tr)\n # pr_0 = math.exp(ln_pr_0)\n\n ln_pr_1 = (-4.78522 * (1 - tr) + 0.413999 * ((1 - tr) ** 1.5) - 8.913290 * ((1 - tr) ** 3) - 4.986620 * (\n (1 - tr) ** 6)) * (1 / tr)\n # pr_1 = math.exp(ln_pr_1)\n\n pc_atm = pc_psi / 14.6959487755142\n omega = (-math.log(pc_atm) - ln_pr_0) / ln_pr_1\n\n tc_K = tb_R / 1.8\n pc_pa = pc_atm * 101325.0\n vc_m3_kmol = vc_ft3_lb_mol * 0.0283168 / (453.59237 * 0.001)\n\n return tc_K, pc_pa, vc_m3_kmol, mw, omega\n\n\ndef ig_heat_cp_coeffs(tb, sg):\n tb_R = tb * 1.8\n watson_k = (tb_R ** (1 / 3)) / sg\n\n c1 = -0.33886 + 0.02827 * watson_k\n c2 = -(0.9291 - 1.1543 * watson_k + 0.0368 * (watson_k ** 2)) * 1e-4\n c3 = -1.6658e-7\n c4 = -(0.26105 - 0.59332 * watson_k)\n c5 = -4.92 * 1e-4\n c6 = -(0.536 - 0.6828 * watson_k) * 1e-7\n c7 = ((12.8 - watson_k) * (10 - watson_k) / (10 * watson_k)) ** 2\n\n a2 = c1 + c7 * c4\n a3 = c2 + c7 * c5\n a4 = c3 + c7 * c1\n\n # T - R\n # Cp - Btu/lb-mol\n\n # H = a1 + a2*T + (a3/2)*(T**2) + (a4/3)*(T**3)\n # Cp = a2 + a3*T + a4*(T**2)\n\n # Btu/lb-mol-R -> (1055.0558526*1.8)/0.45359237\n a2 = a2 * (1055.0558526 * 1.8) / 0.45359237\n a3 = a3 * (1055.0558526 * 1.8) / 0.45359237 * 1.8\n a4 = a4 * (1055.0558526 * 1.8) / 0.45359237 * 1.8 * 1.8\n\n # no, tmin, tmax, a, b, c, d, e, f\n coeffs = 1, 0, 2000, a2, a3, a4, 0, 0, 0\n return coeffs\n\n\nclass TwuHypo:\n\n def __init__(self, identifier, tb, sg, mw=None):\n self.identifier = identifier.upper()\n tc, pc, vc, mw, omega = fixed_properties(tb, sg, mw)\n self.mw = mw\n self.acen_fact = omega\n self.crit_compress_fact = pc * vc / (GAS_CONSTANT * tc) # Unitless\n self.crit_press = pc # Pa\n self.crit_temp = tc # K\n self.crit_vol_mole = vc # m3/kmol\n coeffs = np.array(ig_heat_cp_coeffs(tb, sg))\n self.ig_cp_mole_coeffs = coeffs # J/kmol-K\n # TODO Document the regression to get the ideal gas enthalpy\n self.ig_enthalpy_form_mole = -104680000+(-1476031.316)*(mw-44.097) # J/kmol\n self.ig_gibbs_form_mole = -24390000+(584256.2662)*(mw-44.097) # J/kmol\n self.ig_entropy_form_mole = (self.ig_gibbs_form_mole - self.ig_enthalpy_form_mole)/-298.15 # J/kmol-K\n\n # TODO Fix Specific Gravity conversion\n self.std_liq_vol_mole = 1/(sg*1000/mw)\n self.ig_temp_ref = 298.15\n self.ig_press_ref = 101325.0\n\n def ig_heat_cap_mole(self, temp):\n return eval_eqn(self.ig_cp_mole_coeffs, temp, self.crit_temp)\n\n def ig_enthalpy_mole(self, temp):\n return eval_eqn_int(self.ig_cp_mole_coeffs, temp, self.ig_temp_ref) + self.ig_enthalpy_form_mole\n\n def ig_entropy_mole(self, temp, press):\n p1 = eval_eqn_int_over_t(self.ig_cp_mole_coeffs, temp, self.ig_temp_ref) + self.ig_entropy_form_mole\n return p1 - GAS_CONSTANT * math.log(press / self.ig_press_ref)\n\n def ig_gibbs_mole(self, temp, press):\n return self.ig_enthalpy_mole(temp) - self.ig_entropy_mole(temp, press)\n\n def liq_visc(self, temp):\n return 0\n\n def vap_visc(self, temp):\n return 0\n\n def surf_tens(self, temp):\n return 0\n"
]
| [
[
"scipy.optimize.fsolve"
]
]
|
cssrivatsan/scqubits | [
"e1e81e9e7d51c070968e37161b24e7071fe87553"
]
| [
"scqubits/core/bifluxon.py"
]
| [
"# bifluxon.py\n#\n# This file is part of scqubits.\n#\n# Copyright (c) 2019 and later, Jens Koch and Peter Groszkowski\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n############################################################################\n\nimport os\nimport warnings\n\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\n\nfrom matplotlib.axes import Axes\nfrom matplotlib.figure import Figure\nfrom numpy import ndarray\nfrom scipy import sparse\nfrom scipy.sparse.csc import csc_matrix\nfrom scipy.sparse.dia import dia_matrix\n\nimport scqubits.core.central_dispatch as dispatch\nimport scqubits.core.constants as constants\nimport scqubits.core.descriptors as descriptors\nimport scqubits.core.discretization as discretization\nimport scqubits.core.qubit_base as base\nimport scqubits.core.storage as storage\nimport scqubits.io_utils.fileio_serializers as serializers\nimport scqubits.ui.qubit_widget as ui\nimport scqubits.utils.plotting as plot\nimport scqubits.utils.spectrum_utils as spec_utils\n\nfrom scqubits.core.discretization import Grid1d\nfrom scqubits.core.noise import NoisySystem\nfrom scqubits.core.storage import WaveFunctionOnGrid\n\n# - Bifluxon noise class\n\n\nclass NoisyBifluxon(NoisySystem):\n pass\n\n\n# -bifluxon qubit, fluxonium like phi mode discretized, small island connected with two junctions solved in the charge basis---------------------------------------------------------\n\n\nclass Bifluxon(base.QubitBaseClass, serializers.Serializable, NoisyBifluxon):\n r\"\"\"Bifluxon Qubit\n\n | [1] Kalashnikov et al., PRX Quantum 1, 010307 (2020). https://doi.org/10.1103/PRXQuantum.1.010307\n\n\n Bifluxon qubit without considering disorder in the small Josephson junctions, based Eq. (1) in [1],\n\n .. math::\n\n H &= 4E_{\\text{C}}(-i\\partial_\\theta-n_g)^2-2E_\\text{J}\\cos\\theta\\cos(\\phi/2) \\\\\n -4E_\\text{CL}\\partial_\\phi^2+E_L(\\phi -\\varphi_\\text{ext})^2.\n\n Formulation of the Hamiltonian matrix proceeds by discretization of the `phi` variable, and using charge basis for\n the `theta` variable.\n\n Parameters\n ----------\n EJ:\n mean Josephson energy of the two junctions\n EL:\n inductive energy of the inductors\n EC:\n charging energy of the superconducting islond connected to the two junctions\n ECL:\n charging energy of the large superinductor\n dEJ:\n relative disorder in EJ, i.e., (EJ1-EJ2)/EJavg\n ng:\n offset charge at the small superconducting island\n flux:\n magnetic flux through the circuit loop, measured in units of flux quanta (h/2e)\n grid:\n specifies the range and spacing of the discretization lattice\n ncut:\n charge number cutoff for the superconducting island, `n_theta = -ncut, ..., ncut`\n\n truncated_dim:\n desired dimension of the truncated quantum system; expected: truncated_dim > 1\n \"\"\"\n EJ = descriptors.WatchedProperty(\"QUANTUMSYSTEM_UPDATE\")\n EL = descriptors.WatchedProperty(\"QUANTUMSYSTEM_UPDATE\")\n EC = descriptors.WatchedProperty(\"QUANTUMSYSTEM_UPDATE\")\n ECL = descriptors.WatchedProperty(\"QUANTUMSYSTEM_UPDATE\")\n dEJ = descriptors.WatchedProperty(\"QUANTUMSYSTEM_UPDATE\")\n ng = descriptors.WatchedProperty(\"QUANTUMSYSTEM_UPDATE\")\n ncut = descriptors.WatchedProperty(\"QUANTUMSYSTEM_UPDATE\")\n\n def __init__(\n self,\n EJ: float,\n EL: float,\n EC: float,\n ECL: float,\n ng: float,\n flux: float,\n grid: Grid1d,\n ncut: int,\n dEJ: float = 0.0,\n truncated_dim: int = 6,\n ) -> None:\n self.EJ = EJ\n self.EL = EL\n self.EC = EC\n self.ECL = ECL\n self.dEJ = dEJ\n self.ng = ng\n self.flux = flux\n self.grid = grid\n self.ncut = ncut\n self.truncated_dim = truncated_dim\n self._sys_type = type(self).__name__\n self._evec_dtype = np.complex_\n\n # _default_grid is for *theta*, needed for plotting wavefunction\n self._default_grid = discretization.Grid1d(-np.pi / 2, 3 * np.pi / 2, 200)\n\n self._image_filename = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"qubit_img/bifluxon.jpg\"\n )\n dispatch.CENTRAL_DISPATCH.register(\"GRID_UPDATE\", self)\n\n @staticmethod\n def default_params() -> Dict[str, Any]:\n return {\n \"EJ\": 27.2,\n \"EL\": 0.94,\n \"EC\": 7.7,\n \"ECL\": 10.0,\n \"dEJ\": 0.0,\n \"ng\": 0.5,\n \"flux\": 0.23,\n \"ncut\": 30,\n \"truncated_dim\": 10,\n }\n\n @classmethod\n def create(cls) -> \"Bifluxon\":\n phi_grid = discretization.Grid1d(-19.0, 19.0, 200)\n init_params = cls.default_params()\n init_params[\"grid\"] = phi_grid\n bifluxon = cls(**init_params)\n bifluxon.widget()\n return bifluxon\n\n def supported_noise_channels(self) -> List[str]:\n \"\"\"Return a list of supported noise channels\"\"\"\n return [\n \"tphi_1_over_f_cc\",\n \"tphi_1_over_f_flux\",\n \"t1_flux_bias_line\",\n # 't1_capacitive',\n \"t1_inductive\",\n ]\n\n def widget(self, params: Dict[str, Any] = None) -> None:\n init_params = params or self.get_initdata()\n del init_params[\"grid\"]\n init_params[\"grid_max_val\"] = self.grid.max_val\n init_params[\"grid_min_val\"] = self.grid.min_val\n init_params[\"grid_pt_count\"] = self.grid.pt_count\n ui.create_widget(\n self.set_params, init_params, image_filename=self._image_filename\n )\n\n def set_params(self, **kwargs) -> None:\n phi_grid = discretization.Grid1d(\n kwargs.pop(\"grid_min_val\"),\n kwargs.pop(\"grid_max_val\"),\n kwargs.pop(\"grid_pt_count\"),\n )\n self.grid = phi_grid\n for param_name, param_val in kwargs.items():\n setattr(self, param_name, param_val)\n\n def receive(self, event: str, sender: object, **kwargs):\n if sender is self.grid:\n self.broadcast(\"QUANTUMSYSTEM_UPDATE\")\n\n def _evals_calc(self, evals_count: int) -> ndarray:\n hamiltonian_mat = self.hamiltonian()\n evals = sparse.linalg.eigsh(\n hamiltonian_mat,\n k=evals_count,\n sigma=0.0,\n which=\"LM\",\n return_eigenvectors=False,\n )\n return np.sort(evals)\n\n def _esys_calc(self, evals_count: int) -> Tuple[ndarray, ndarray]:\n hamiltonian_mat = self.hamiltonian()\n evals, evecs = sparse.linalg.eigsh(\n hamiltonian_mat,\n k=evals_count,\n sigma=0.0,\n which=\"LM\",\n return_eigenvectors=True,\n )\n # TODO consider normalization of zeropi wavefunctions\n # evecs /= np.sqrt(self.grid.grid_spacing())\n evals, evecs = spec_utils.order_eigensystem(evals, evecs)\n return evals, evecs\n\n def hilbertdim(self) -> int:\n \"\"\"Returns Hilbert space dimension\"\"\"\n return self.grid.pt_count * (2 * self.ncut + 1)\n\n def potential(self, phi: ndarray, theta: ndarray) -> ndarray:\n \"\"\"\n Returns\n -------\n value of the potential energy evaluated at phi, theta for Bifluxon\n \"\"\"\n return (\n -2.0 * self.EJ * np.cos(theta) * np.cos(phi/2.0 + 2.0 * np.pi * self.flux / 2.0)\n + (1/2.0) * self.EL * phi ** 2\n\n )\n\n def sparse_kinetic_mat(self) -> csc_matrix:\n \"\"\"\n Kinetic energy portion of the Hamiltonian.\n\n Returns\n -------\n matrix representing the kinetic energy operator\n \"\"\"\n pt_count = self.grid.pt_count\n dim_theta = 2 * self.ncut + 1\n identity_phi = sparse.identity(pt_count, format=\"csc\")\n identity_theta = sparse.identity(dim_theta, format=\"csc\")\n kinetic_matrix_phi = self.grid.second_derivative_matrix(\n prefactor=-4.0 * self.ECL\n )\n diag_elements = (\n 4.0\n * self.EC\n * np.square(np.arange(-self.ncut + self.ng, self.ncut + 1 + self.ng))\n )\n kinetic_matrix_theta = sparse.dia_matrix(\n (diag_elements, [0]), shape=(dim_theta, dim_theta)\n ).tocsc()\n kinetic_matrix = sparse.kron(\n kinetic_matrix_phi, identity_theta, format=\"csc\"\n ) + sparse.kron(identity_phi, kinetic_matrix_theta, format=\"csc\")\n\n return kinetic_matrix\n\n def sparse_potential_mat(self) -> csc_matrix:\n \"\"\"\n Potential energy portion of the Hamiltonian.\n\n Returns\n -------\n matrix representing the potential energy operator\n \"\"\"\n pt_count = self.grid.pt_count\n grid_linspace = self.grid.make_linspace()\n dim_theta = 2 * self.ncut + 1\n\n phi_inductive_vals = (1/2.0) * self.EL * np.square(grid_linspace)\n phi_inductive_potential = sparse.dia_matrix(\n (phi_inductive_vals, [0]), shape=(pt_count, pt_count)\n ).tocsc()\n phi_cosby2_vals = np.cos(grid_linspace/2.0 + 2.0 * np.pi * self.flux / 2.0)\n phi_cosby2_potential = sparse.dia_matrix(\n (phi_cosby2_vals, [0]), shape=(pt_count, pt_count)\n ).tocsc()\n\n theta_cos_potential = (\n -self.EJ\n * (\n sparse.dia_matrix(\n ([1.0] * dim_theta, [-1]), shape=(dim_theta, dim_theta)\n )\n + sparse.dia_matrix(\n ([1.0] * dim_theta, [1]), shape=(dim_theta, dim_theta)\n )\n )\n ).tocsc()\n potential_mat = (\n sparse.kron(phi_cosby2_potential, theta_cos_potential, format=\"csc\")\n + sparse.kron(phi_inductive_potential, self._identity_theta(), format=\"csc\")\n )\n # if self.dEJ != 0:\n # potential_mat += (\n # self.EJ\n # * self.dEJ\n # * sparse.kron(phi_sin_potential, self._identity_theta(), format=\"csc\")\n # * self.sin_theta_operator()\n # )\n return potential_mat\n\n def hamiltonian(self) -> csc_matrix:\n \"\"\"Calculates Hamiltonian in basis obtained by discretizing phi and employing charge basis for theta.\n\n Returns\n -------\n matrix representing the potential energy operator\n \"\"\"\n return self.sparse_kinetic_mat() + self.sparse_potential_mat()\n\n def sparse_d_potential_d_flux_mat(self) -> csc_matrix:\n r\"\"\"Calculates derivative of the potential energy w.r.t flux, at the current value of flux,\n as stored in the object.\n\n The flux is assumed to be given in the units of the ratio \\Phi_{ext}/\\Phi_0.\n So if \\frac{\\partial U}{ \\partial \\Phi_{\\rm ext}}, is needed, the expression returned\n by this function, needs to be multiplied by 1/\\Phi_0.\n\n Returns\n -------\n matrix representing the derivative of the potential energy.\n NEED TO UPDATE FOR BIFLUXON with phi/2 operators\n \"\"\"\n op_1 = sparse.kron(\n self._sin_phi_operator(x=-2.0 * np.pi * self.flux / 2.0),\n self._cos_theta_operator(),\n format=\"csc\",\n )\n op_2 = sparse.kron(\n self._cos_phi_operator(x=-2.0 * np.pi * self.flux / 2.0),\n self._sin_theta_operator(),\n format=\"csc\",\n )\n return -2.0 * np.pi * self.EJ * op_1 - np.pi * self.EJ * self.dEJ * op_2\n\n def d_hamiltonian_d_flux(self) -> csc_matrix:\n r\"\"\"Calculates a derivative of the Hamiltonian w.r.t flux, at the current value of flux,\n as stored in the object.\n\n The flux is assumed to be given in the units of the ratio \\Phi_{ext}/\\Phi_0.\n So if \\frac{\\partial H}{ \\partial \\Phi_{\\rm ext}}, is needed, the expression returned\n by this function, needs to be multiplied by 1/\\Phi_0.\n\n Returns\n -------\n matrix representing the derivative of the Hamiltonian\n \"\"\"\n return self.sparse_d_potential_d_flux_mat()\n\n def sparse_d_potential_d_EJ_mat(self) -> csc_matrix:\n r\"\"\"Calculates a of the potential energy w.r.t EJ.\n\n Returns\n -------\n matrix representing the derivative of the potential energy\n \"\"\"\n return -2.0 * sparse.kron(\n self._cos_phi_operator(x=-2.0 * np.pi * self.flux / 2.0),\n self._cos_theta_operator(),\n format=\"csc\",\n )\n\n def d_hamiltonian_d_EJ(self) -> csc_matrix:\n r\"\"\"Calculates a derivative of the Hamiltonian w.r.t EJ.\n\n Returns\n -------\n matrix representing the derivative of the Hamiltonian\n \"\"\"\n return self.sparse_d_potential_d_EJ_mat()\n\n def d_hamiltonian_d_ng(self) -> csc_matrix:\n r\"\"\"Calculates a derivative of the Hamiltonian w.r.t ng.\n as stored in the object.\n\n Returns\n -------\n matrix representing the derivative of the Hamiltonian\n \"\"\"\n return -8 * self.EC * self.n_theta_operator()\n\n def _identity_phi(self) -> csc_matrix:\n r\"\"\"\n Identity operator acting only on the `\\phi` Hilbert subspace.\n \"\"\"\n pt_count = self.grid.pt_count\n return sparse.identity(pt_count, format=\"csc\")\n\n def _identity_theta(self) -> csc_matrix:\n r\"\"\"\n Identity operator acting only on the `\\theta` Hilbert subspace.\n \"\"\"\n dim_theta = 2 * self.ncut + 1\n return sparse.identity(dim_theta, format=\"csc\")\n\n def i_d_dphi_operator(self) -> csc_matrix:\n r\"\"\"\n Operator :math:`i d/d\\phi`.\n \"\"\"\n return sparse.kron(\n self.grid.first_derivative_matrix(prefactor=1j),\n self._identity_theta(),\n format=\"csc\",\n )\n\n def _phi_operator(self) -> dia_matrix:\n r\"\"\"\n Operator :math:`\\phi`, acting only on the `\\phi` Hilbert subspace.\n \"\"\"\n pt_count = self.grid.pt_count\n\n phi_matrix = sparse.dia_matrix((pt_count, pt_count))\n diag_elements = self.grid.make_linspace()\n phi_matrix.setdiag(diag_elements)\n return phi_matrix\n\n def phi_operator(self) -> csc_matrix:\n r\"\"\"\n Operator :math:`\\phi`.\n \"\"\"\n return sparse.kron(self._phi_operator(), self._identity_theta(), format=\"csc\")\n\n def n_theta_operator(self) -> csc_matrix:\n r\"\"\"\n Operator :math:`n_\\theta`.\n \"\"\"\n dim_theta = 2 * self.ncut + 1\n diag_elements = np.arange(-self.ncut, self.ncut + 1)\n n_theta_matrix = sparse.dia_matrix(\n (diag_elements, [0]), shape=(dim_theta, dim_theta)\n ).tocsc()\n return sparse.kron(self._identity_phi(), n_theta_matrix, format=\"csc\")\n\n def _sin_phi_operator(self, x: float = 0) -> csc_matrix:\n r\"\"\"\n Operator :math:`\\sin(\\phi + x)`, acting only on the `\\phi` Hilbert subspace.x\n \"\"\"\n pt_count = self.grid.pt_count\n\n vals = np.sin(self.grid.make_linspace() + x)\n sin_phi_matrix = sparse.dia_matrix(\n (vals, [0]), shape=(pt_count, pt_count)\n ).tocsc()\n return sin_phi_matrix\n\n def _cos_phi_operator(self, x: float = 0) -> csc_matrix:\n r\"\"\"\n Operator :math:`\\cos(\\phi + x)`, acting only on the `\\phi` Hilbert subspace.\n \"\"\"\n pt_count = self.grid.pt_count\n\n vals = np.cos(self.grid.make_linspace() + x)\n cos_phi_matrix = sparse.dia_matrix(\n (vals, [0]), shape=(pt_count, pt_count)\n ).tocsc()\n return cos_phi_matrix\n\n def _sin_phiby2_operator(self, x: float = 0) -> csc_matrix:\n r\"\"\"\n Operator :math:`\\sin(\\phi/2 + x)`, acting only on the `\\phi` Hilbert subspace.x\n \"\"\"\n pt_count = self.grid.pt_count\n\n vals = np.sin(self.grid.make_linspace()/2.0 + x)\n sin_phiby2_matrix = sparse.dia_matrix(\n (vals, [0]), shape=(pt_count, pt_count)\n ).tocsc()\n return sin_phiby2_matrix\n\n def _cos_phiby2_operator(self, x: float = 0) -> csc_matrix:\n r\"\"\"\n Operator :math:`\\cos(\\phi/2.0 + x)`, acting only on the `\\phi` Hilbert subspace.\n \"\"\"\n pt_count = self.grid.pt_count\n\n vals = np.cos(self.grid.make_linspace()/2.0 + x)\n cos_phiby2_matrix = sparse.dia_matrix(\n (vals, [0]), shape=(pt_count, pt_count)\n ).tocsc()\n return cos_phiby2_matrix\n\n\n def _cos_theta_operator(self) -> csc_matrix:\n r\"\"\"\n Operator :math:`\\cos(\\theta)`, acting only on the `\\theta` Hilbert subspace.\n \"\"\"\n dim_theta = 2 * self.ncut + 1\n cos_theta_matrix = (\n 0.5\n * (\n sparse.dia_matrix(\n ([1.0] * dim_theta, [-1]), shape=(dim_theta, dim_theta)\n )\n + sparse.dia_matrix(\n ([1.0] * dim_theta, [1]), shape=(dim_theta, dim_theta)\n )\n ).tocsc()\n )\n return cos_theta_matrix\n\n def cos_theta_operator(self) -> csc_matrix:\n r\"\"\"\n Operator :math:`\\cos(\\theta)`.\n \"\"\"\n return sparse.kron(\n self._identity_phi(), self._cos_theta_operator(), format=\"csc\"\n )\n\n def _sin_theta_operator(self) -> csc_matrix:\n r\"\"\"\n Operator :math:`\\sin(\\theta)`, acting only on the `\\theta` Hilbert space.\n \"\"\"\n dim_theta = 2 * self.ncut + 1\n sin_theta_matrix = (\n -0.5\n * 1j\n * (\n sparse.dia_matrix(\n ([1.0] * dim_theta, [1]), shape=(dim_theta, dim_theta)\n )\n - sparse.dia_matrix(\n ([1.0] * dim_theta, [-1]), shape=(dim_theta, dim_theta)\n )\n ).tocsc()\n )\n return sin_theta_matrix\n\n def sin_theta_operator(self) -> csc_matrix:\n r\"\"\"\n Operator :math:`\\sin(\\theta)`.\n \"\"\"\n return sparse.kron(\n self._identity_phi(), self._sin_theta_operator(), format=\"csc\"\n )\n\n def plot_potential(\n self,\n theta_grid: Grid1d = None,\n contour_vals: Union[List[float], ndarray] = None,\n **kwargs\n ) -> Tuple[Figure, Axes]:\n \"\"\"Draw contour plot of the potential energy.\n\n Parameters\n ----------\n theta_grid:\n used for setting a custom grid for theta; if None use self._default_grid\n contour_vals:\n **kwargs:\n plotting parameters\n \"\"\"\n theta_grid = theta_grid or self._default_grid\n\n x_vals = self.grid.make_linspace()\n y_vals = theta_grid.make_linspace()\n return plot.contours(\n x_vals,\n y_vals,\n self.potential,\n contour_vals=contour_vals,\n xlabel=r\"$\\phi$\",\n ylabel=r\"$\\theta$\",\n **kwargs\n )\n\n def wavefunction(\n self,\n esys: Tuple[ndarray, ndarray] = None,\n which: int = 0,\n theta_grid: Grid1d = None,\n ) -> WaveFunctionOnGrid:\n \"\"\"Returns a zero-pi wave function in `phi`, `theta` basis\n\n Parameters\n ----------\n esys:\n eigenvalues, eigenvectors\n which:\n index of desired wave function (default value = 0)\n theta_grid:\n used for setting a custom grid for theta; if None use self._default_grid\n \"\"\"\n evals_count = max(which + 1, 3)\n if esys is None:\n _, evecs = self.eigensys(evals_count)\n else:\n _, evecs = esys\n\n theta_grid = theta_grid or self._default_grid\n dim_theta = 2 * self.ncut + 1\n state_amplitudes = evecs[:, which].reshape(self.grid.pt_count, dim_theta)\n\n # Calculate psi_{phi, theta} = sum_n state_amplitudes_{phi, n} A_{n, theta}\n # where a_{n, theta} = 1/sqrt(2 pi) e^{i n theta}\n n_vec = np.arange(-self.ncut, self.ncut + 1)\n theta_vec = theta_grid.make_linspace()\n a_n_theta = np.exp(1j * np.outer(n_vec, theta_vec)) / (2 * np.pi) ** 0.5\n wavefunc_amplitudes = np.matmul(state_amplitudes, a_n_theta).T\n wavefunc_amplitudes = spec_utils.standardize_phases(wavefunc_amplitudes)\n\n grid2d = discretization.GridSpec(\n np.asarray(\n [\n [self.grid.min_val, self.grid.max_val, self.grid.pt_count],\n [theta_grid.min_val, theta_grid.max_val, theta_grid.pt_count],\n ]\n )\n )\n return storage.WaveFunctionOnGrid(grid2d, wavefunc_amplitudes)\n\n def plot_wavefunction(\n self,\n esys: Tuple[ndarray, ndarray] = None,\n which: int = 0,\n theta_grid: Grid1d = None,\n mode: str = \"abs\",\n zero_calibrate: bool = True,\n **kwargs\n ) -> Tuple[Figure, Axes]:\n \"\"\"Plots 2d phase-basis wave function.\n\n Parameters\n ----------\n esys:\n eigenvalues, eigenvectors as obtained from `.eigensystem()`\n which:\n index of wave function to be plotted (default value = (0)\n theta_grid:\n used for setting a custom grid for theta; if None use self._default_grid\n mode:\n choices as specified in `constants.MODE_FUNC_DICT` (default value = 'abs_sqr')\n zero_calibrate:\n if True, colors are adjusted to use zero wavefunction amplitude as the neutral color in the palette\n **kwargs:\n plot options\n \"\"\"\n theta_grid = theta_grid or self._default_grid\n\n amplitude_modifier = constants.MODE_FUNC_DICT[mode]\n wavefunc = self.wavefunction(esys, theta_grid=theta_grid, which=which)\n wavefunc.amplitudes = amplitude_modifier(wavefunc.amplitudes)\n return plot.wavefunction2d(\n wavefunc,\n zero_calibrate=zero_calibrate,\n xlabel=r\"$\\phi$\",\n ylabel=r\"$\\theta$\",\n **kwargs\n )\n"
]
| [
[
"numpy.square",
"numpy.asarray",
"numpy.arange",
"numpy.matmul",
"numpy.cos",
"numpy.sort",
"scipy.sparse.identity",
"numpy.outer",
"scipy.sparse.kron",
"scipy.sparse.dia_matrix",
"scipy.sparse.linalg.eigsh"
]
]
|
rednodelabs/scikit-learn | [
"ddbc560603a6633b97fefeb2f2adfcfdf6bb0417"
]
| [
"sklearn/cluster/_kmeans.py"
]
| [
"\"\"\"K-means clustering.\"\"\"\n\n# Authors: Gael Varoquaux <[email protected]>\n# Thomas Rueckstiess <[email protected]>\n# James Bergstra <[email protected]>\n# Jan Schlueter <[email protected]>\n# Nelle Varoquaux\n# Peter Prettenhofer <[email protected]>\n# Olivier Grisel <[email protected]>\n# Mathieu Blondel <[email protected]>\n# Robert Layton <[email protected]>\n# License: BSD 3 clause\n\nimport warnings\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom threadpoolctl import threadpool_limits\nfrom threadpoolctl import threadpool_info\n\nfrom ..base import BaseEstimator, ClusterMixin, TransformerMixin\nfrom ..metrics.pairwise import euclidean_distances\nfrom ..metrics.pairwise import _euclidean_distances\nfrom ..utils.extmath import row_norms, stable_cumsum\nfrom ..utils.sparsefuncs_fast import assign_rows_csr\nfrom ..utils.sparsefuncs import mean_variance_axis\nfrom ..utils.validation import _deprecate_positional_args\nfrom ..utils import check_array\nfrom ..utils import gen_batches\nfrom ..utils import check_random_state\nfrom ..utils import deprecated\nfrom ..utils.validation import check_is_fitted, _check_sample_weight\nfrom ..utils._openmp_helpers import _openmp_effective_n_threads\nfrom ..exceptions import ConvergenceWarning\nfrom ._k_means_fast import CHUNK_SIZE\nfrom ._k_means_fast import _inertia_dense\nfrom ._k_means_fast import _inertia_sparse\nfrom ._k_means_fast import _mini_batch_update_csr\nfrom ._k_means_lloyd import lloyd_iter_chunked_dense\nfrom ._k_means_lloyd import lloyd_iter_chunked_sparse\nfrom ._k_means_elkan import init_bounds_dense\nfrom ._k_means_elkan import init_bounds_sparse\nfrom ._k_means_elkan import elkan_iter_chunked_dense\nfrom ._k_means_elkan import elkan_iter_chunked_sparse\n\n\n###############################################################################\n# Initialization heuristic\n\n\ndef _kmeans_plusplus(X, n_clusters, x_squared_norms,\n random_state, n_local_trials=None):\n \"\"\"Computational component for initialization of n_clusters by\n k-means++. Prior validation of data is assumed.\n\n Parameters\n ----------\n X : {ndarray, sparse matrix} of shape (n_samples, n_features)\n The data to pick seeds for.\n\n n_clusters : int\n The number of seeds to choose.\n\n x_squared_norms : ndarray of shape (n_samples,)\n Squared Euclidean norm of each data point.\n\n random_state : RandomState instance\n The generator used to initialize the centers.\n See :term:`Glossary <random_state>`.\n\n n_local_trials : int, default=None\n The number of seeding trials for each center (except the first),\n of which the one reducing inertia the most is greedily chosen.\n Set to None to make the number of trials depend logarithmically\n on the number of seeds (2+log(k)); this is the default.\n\n Returns\n -------\n centers : ndarray of shape (n_clusters, n_features)\n The inital centers for k-means.\n\n indices : ndarray of shape (n_clusters,)\n The index location of the chosen centers in the data array X. For a\n given index and center, X[index] = center.\n \"\"\"\n n_samples, n_features = X.shape\n\n centers = np.empty((n_clusters, n_features), dtype=X.dtype)\n\n # Set the number of local seeding trials if none is given\n if n_local_trials is None:\n # This is what Arthur/Vassilvitskii tried, but did not report\n # specific results for other than mentioning in the conclusion\n # that it helped.\n n_local_trials = 2 + int(np.log(n_clusters))\n\n # Pick first center randomly and track index of point\n center_id = random_state.randint(n_samples)\n indices = np.full(n_clusters, -1, dtype=int)\n if sp.issparse(X):\n centers[0] = X[center_id].toarray()\n else:\n centers[0] = X[center_id]\n indices[0] = center_id\n\n # Initialize list of closest distances and calculate current potential\n closest_dist_sq = _euclidean_distances(\n centers[0, np.newaxis], X, Y_norm_squared=x_squared_norms,\n squared=True)\n current_pot = closest_dist_sq.sum()\n\n # Pick the remaining n_clusters-1 points\n for c in range(1, n_clusters):\n # Choose center candidates by sampling with probability proportional\n # to the squared distance to the closest existing center\n rand_vals = random_state.random_sample(n_local_trials) * current_pot\n candidate_ids = np.searchsorted(stable_cumsum(closest_dist_sq),\n rand_vals)\n # XXX: numerical imprecision can result in a candidate_id out of range\n np.clip(candidate_ids, None, closest_dist_sq.size - 1,\n out=candidate_ids)\n\n # Compute distances to center candidates\n distance_to_candidates = _euclidean_distances(\n X[candidate_ids], X, Y_norm_squared=x_squared_norms, squared=True)\n\n # update closest distances squared and potential for each candidate\n np.minimum(closest_dist_sq, distance_to_candidates,\n out=distance_to_candidates)\n candidates_pot = distance_to_candidates.sum(axis=1)\n\n # Decide which candidate is the best\n best_candidate = np.argmin(candidates_pot)\n current_pot = candidates_pot[best_candidate]\n closest_dist_sq = distance_to_candidates[best_candidate]\n best_candidate = candidate_ids[best_candidate]\n\n # Permanently add best center candidate found in local tries\n if sp.issparse(X):\n centers[c] = X[best_candidate].toarray()\n else:\n centers[c] = X[best_candidate]\n indices[c] = best_candidate\n\n return centers, indices\n\n\n###############################################################################\n# K-means batch estimation by EM (expectation maximization)\n\ndef _tolerance(X, tol):\n \"\"\"Return a tolerance which is dependent on the dataset.\"\"\"\n if tol == 0:\n return 0\n if sp.issparse(X):\n variances = mean_variance_axis(X, axis=0)[1]\n else:\n variances = np.var(X, axis=0)\n return np.mean(variances) * tol\n\n\n@_deprecate_positional_args\ndef k_means(X, n_clusters, *, sample_weight=None, init='k-means++',\n precompute_distances='deprecated', n_init=10, max_iter=300,\n verbose=False, tol=1e-4, random_state=None, copy_x=True,\n n_jobs='deprecated', algorithm=\"auto\", return_n_iter=False):\n \"\"\"K-means clustering algorithm.\n\n Read more in the :ref:`User Guide <k_means>`.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The observations to cluster. It must be noted that the data\n will be converted to C ordering, which will cause a memory copy\n if the given data is not C-contiguous.\n\n n_clusters : int\n The number of clusters to form as well as the number of\n centroids to generate.\n\n sample_weight : array-like of shape (n_samples,), default=None\n The weights for each observation in X. If None, all observations\n are assigned equal weight.\n\n init : {'k-means++', 'random'}, callable or array-like of shape \\\n (n_clusters, n_features), default='k-means++'\n Method for initialization:\n\n 'k-means++' : selects initial cluster centers for k-mean\n clustering in a smart way to speed up convergence. See section\n Notes in k_init for more details.\n\n 'random': choose `n_clusters` observations (rows) at random from data\n for the initial centroids.\n\n If an array is passed, it should be of shape (n_clusters, n_features)\n and gives the initial centers.\n\n If a callable is passed, it should take arguments X, n_clusters and a\n random state and return an initialization.\n\n precompute_distances : {'auto', True, False}\n Precompute distances (faster but takes more memory).\n\n 'auto' : do not precompute distances if n_samples * n_clusters > 12\n million. This corresponds to about 100MB overhead per job using\n double precision.\n\n True : always precompute distances\n\n False : never precompute distances\n\n .. deprecated:: 0.23\n 'precompute_distances' was deprecated in version 0.23 and will be\n removed in 1.0 (renaming of 0.25). It has no effect.\n\n n_init : int, default=10\n Number of time the k-means algorithm will be run with different\n centroid seeds. The final results will be the best output of\n n_init consecutive runs in terms of inertia.\n\n max_iter : int, default=300\n Maximum number of iterations of the k-means algorithm to run.\n\n verbose : bool, default=False\n Verbosity mode.\n\n tol : float, default=1e-4\n Relative tolerance with regards to Frobenius norm of the difference\n in the cluster centers of two consecutive iterations to declare\n convergence.\n\n random_state : int, RandomState instance or None, default=None\n Determines random number generation for centroid initialization. Use\n an int to make the randomness deterministic.\n See :term:`Glossary <random_state>`.\n\n copy_x : bool, default=True\n When pre-computing distances it is more numerically accurate to center\n the data first. If copy_x is True (default), then the original data is\n not modified. If False, the original data is modified, and put back\n before the function returns, but small numerical differences may be\n introduced by subtracting and then adding the data mean. Note that if\n the original data is not C-contiguous, a copy will be made even if\n copy_x is False. If the original data is sparse, but not in CSR format,\n a copy will be made even if copy_x is False.\n\n n_jobs : int, default=None\n The number of OpenMP threads to use for the computation. Parallelism is\n sample-wise on the main cython loop which assigns each sample to its\n closest center.\n\n ``None`` or ``-1`` means using all processors.\n\n .. deprecated:: 0.23\n ``n_jobs`` was deprecated in version 0.23 and will be removed in\n 1.0 (renaming of 0.25).\n\n algorithm : {\"auto\", \"full\", \"elkan\"}, default=\"auto\"\n K-means algorithm to use. The classical EM-style algorithm is \"full\".\n The \"elkan\" variation is more efficient on data with well-defined\n clusters, by using the triangle inequality. However it's more memory\n intensive due to the allocation of an extra array of shape\n (n_samples, n_clusters).\n\n For now \"auto\" (kept for backward compatibility) chooses \"elkan\" but it\n might change in the future for a better heuristic.\n\n return_n_iter : bool, default=False\n Whether or not to return the number of iterations.\n\n Returns\n -------\n centroid : ndarray of shape (n_clusters, n_features)\n Centroids found at the last iteration of k-means.\n\n label : ndarray of shape (n_samples,)\n label[i] is the code or index of the centroid the\n i'th observation is closest to.\n\n inertia : float\n The final value of the inertia criterion (sum of squared distances to\n the closest centroid for all observations in the training set).\n\n best_n_iter : int\n Number of iterations corresponding to the best results.\n Returned only if `return_n_iter` is set to True.\n \"\"\"\n est = KMeans(\n n_clusters=n_clusters, init=init, n_init=n_init, max_iter=max_iter,\n verbose=verbose, precompute_distances=precompute_distances, tol=tol,\n random_state=random_state, copy_x=copy_x, n_jobs=n_jobs,\n algorithm=algorithm\n ).fit(X, sample_weight=sample_weight)\n if return_n_iter:\n return est.cluster_centers_, est.labels_, est.inertia_, est.n_iter_\n else:\n return est.cluster_centers_, est.labels_, est.inertia_\n\n\ndef _kmeans_single_elkan(X, sample_weight, centers_init, max_iter=300,\n verbose=False, x_squared_norms=None, tol=1e-4,\n n_threads=1):\n \"\"\"A single run of k-means elkan, assumes preparation completed prior.\n\n Parameters\n ----------\n X : {ndarray, sparse matrix} of shape (n_samples, n_features)\n The observations to cluster. If sparse matrix, must be in CSR format.\n\n sample_weight : array-like of shape (n_samples,)\n The weights for each observation in X.\n\n centers_init : ndarray of shape (n_clusters, n_features)\n The initial centers.\n\n max_iter : int, default=300\n Maximum number of iterations of the k-means algorithm to run.\n\n verbose : bool, default=False\n Verbosity mode.\n\n x_squared_norms : array-like, default=None\n Precomputed x_squared_norms.\n\n tol : float, default=1e-4\n Relative tolerance with regards to Frobenius norm of the difference\n in the cluster centers of two consecutive iterations to declare\n convergence.\n It's not advised to set `tol=0` since convergence might never be\n declared due to rounding errors. Use a very small number instead.\n\n n_threads : int, default=1\n The number of OpenMP threads to use for the computation. Parallelism is\n sample-wise on the main cython loop which assigns each sample to its\n closest center.\n\n Returns\n -------\n centroid : ndarray of shape (n_clusters, n_features)\n Centroids found at the last iteration of k-means.\n\n label : ndarray of shape (n_samples,)\n label[i] is the code or index of the centroid the\n i'th observation is closest to.\n\n inertia : float\n The final value of the inertia criterion (sum of squared distances to\n the closest centroid for all observations in the training set).\n\n n_iter : int\n Number of iterations run.\n \"\"\"\n n_samples = X.shape[0]\n n_clusters = centers_init.shape[0]\n\n # Buffers to avoid new allocations at each iteration.\n centers = centers_init\n centers_new = np.zeros_like(centers)\n weight_in_clusters = np.zeros(n_clusters, dtype=X.dtype)\n labels = np.full(n_samples, -1, dtype=np.int32)\n labels_old = labels.copy()\n center_half_distances = euclidean_distances(centers) / 2\n distance_next_center = np.partition(np.asarray(center_half_distances),\n kth=1, axis=0)[1]\n upper_bounds = np.zeros(n_samples, dtype=X.dtype)\n lower_bounds = np.zeros((n_samples, n_clusters), dtype=X.dtype)\n center_shift = np.zeros(n_clusters, dtype=X.dtype)\n\n if sp.issparse(X):\n init_bounds = init_bounds_sparse\n elkan_iter = elkan_iter_chunked_sparse\n _inertia = _inertia_sparse\n else:\n init_bounds = init_bounds_dense\n elkan_iter = elkan_iter_chunked_dense\n _inertia = _inertia_dense\n\n init_bounds(X, centers, center_half_distances,\n labels, upper_bounds, lower_bounds)\n\n strict_convergence = False\n\n for i in range(max_iter):\n elkan_iter(X, sample_weight, centers, centers_new,\n weight_in_clusters, center_half_distances,\n distance_next_center, upper_bounds, lower_bounds,\n labels, center_shift, n_threads)\n\n # compute new pairwise distances between centers and closest other\n # center of each center for next iterations\n center_half_distances = euclidean_distances(centers_new) / 2\n distance_next_center = np.partition(\n np.asarray(center_half_distances), kth=1, axis=0)[1]\n\n if verbose:\n inertia = _inertia(X, sample_weight, centers, labels)\n print(f\"Iteration {i}, inertia {inertia}\")\n\n centers, centers_new = centers_new, centers\n\n if np.array_equal(labels, labels_old):\n # First check the labels for strict convergence.\n if verbose:\n print(f\"Converged at iteration {i}: strict convergence.\")\n strict_convergence = True\n break\n else:\n # No strict convergence, check for tol based convergence.\n center_shift_tot = (center_shift**2).sum()\n if center_shift_tot <= tol:\n if verbose:\n print(f\"Converged at iteration {i}: center shift \"\n f\"{center_shift_tot} within tolerance {tol}.\")\n break\n\n labels_old[:] = labels\n\n if not strict_convergence:\n # rerun E-step so that predicted labels match cluster centers\n elkan_iter(X, sample_weight, centers, centers, weight_in_clusters,\n center_half_distances, distance_next_center,\n upper_bounds, lower_bounds, labels, center_shift,\n n_threads, update_centers=False)\n\n inertia = _inertia(X, sample_weight, centers, labels)\n\n return labels, inertia, centers, i + 1\n\n\ndef _kmeans_single_lloyd(X, sample_weight, centers_init, max_iter=300,\n verbose=False, x_squared_norms=None, tol=1e-4,\n n_threads=1):\n \"\"\"A single run of k-means lloyd, assumes preparation completed prior.\n\n Parameters\n ----------\n X : {ndarray, sparse matrix} of shape (n_samples, n_features)\n The observations to cluster. If sparse matrix, must be in CSR format.\n\n sample_weight : ndarray of shape (n_samples,)\n The weights for each observation in X.\n\n centers_init : ndarray of shape (n_clusters, n_features)\n The initial centers.\n\n max_iter : int, default=300\n Maximum number of iterations of the k-means algorithm to run.\n\n verbose : bool, default=False\n Verbosity mode\n\n x_squared_norms : ndarray of shape (n_samples,), default=None\n Precomputed x_squared_norms.\n\n tol : float, default=1e-4\n Relative tolerance with regards to Frobenius norm of the difference\n in the cluster centers of two consecutive iterations to declare\n convergence.\n It's not advised to set `tol=0` since convergence might never be\n declared due to rounding errors. Use a very small number instead.\n\n n_threads : int, default=1\n The number of OpenMP threads to use for the computation. Parallelism is\n sample-wise on the main cython loop which assigns each sample to its\n closest center.\n\n Returns\n -------\n centroid : ndarray of shape (n_clusters, n_features)\n Centroids found at the last iteration of k-means.\n\n label : ndarray of shape (n_samples,)\n label[i] is the code or index of the centroid the\n i'th observation is closest to.\n\n inertia : float\n The final value of the inertia criterion (sum of squared distances to\n the closest centroid for all observations in the training set).\n\n n_iter : int\n Number of iterations run.\n \"\"\"\n n_clusters = centers_init.shape[0]\n\n # Buffers to avoid new allocations at each iteration.\n centers = centers_init\n centers_new = np.zeros_like(centers)\n labels = np.full(X.shape[0], -1, dtype=np.int32)\n labels_old = labels.copy()\n weight_in_clusters = np.zeros(n_clusters, dtype=X.dtype)\n center_shift = np.zeros(n_clusters, dtype=X.dtype)\n\n if sp.issparse(X):\n lloyd_iter = lloyd_iter_chunked_sparse\n _inertia = _inertia_sparse\n else:\n lloyd_iter = lloyd_iter_chunked_dense\n _inertia = _inertia_dense\n\n strict_convergence = False\n\n # Threadpoolctl context to limit the number of threads in second level of\n # nested parallelism (i.e. BLAS) to avoid oversubsciption.\n with threadpool_limits(limits=1, user_api=\"blas\"):\n for i in range(max_iter):\n lloyd_iter(X, sample_weight, x_squared_norms, centers, centers_new,\n weight_in_clusters, labels, center_shift, n_threads)\n\n if verbose:\n inertia = _inertia(X, sample_weight, centers, labels)\n print(f\"Iteration {i}, inertia {inertia}.\")\n\n centers, centers_new = centers_new, centers\n\n if np.array_equal(labels, labels_old):\n # First check the labels for strict convergence.\n if verbose:\n print(f\"Converged at iteration {i}: strict convergence.\")\n strict_convergence = True\n break\n else:\n # No strict convergence, check for tol based convergence.\n center_shift_tot = (center_shift**2).sum()\n if center_shift_tot <= tol:\n if verbose:\n print(f\"Converged at iteration {i}: center shift \"\n f\"{center_shift_tot} within tolerance {tol}.\")\n break\n\n labels_old[:] = labels\n\n if not strict_convergence:\n # rerun E-step so that predicted labels match cluster centers\n lloyd_iter(X, sample_weight, x_squared_norms, centers, centers,\n weight_in_clusters, labels, center_shift, n_threads,\n update_centers=False)\n\n inertia = _inertia(X, sample_weight, centers, labels)\n\n return labels, inertia, centers, i + 1\n\n\ndef _labels_inertia(X, sample_weight, x_squared_norms, centers,\n n_threads=None):\n \"\"\"E step of the K-means EM algorithm.\n\n Compute the labels and the inertia of the given samples and centers.\n\n Parameters\n ----------\n X : {ndarray, sparse matrix} of shape (n_samples, n_features)\n The input samples to assign to the labels. If sparse matrix, must\n be in CSR format.\n\n sample_weight : ndarray of shape (n_samples,)\n The weights for each observation in X.\n\n x_squared_norms : ndarray of shape (n_samples,)\n Precomputed squared euclidean norm of each data point, to speed up\n computations.\n\n centers : ndarray of shape (n_clusters, n_features)\n The cluster centers.\n\n n_threads : int, default=None\n The number of OpenMP threads to use for the computation. Parallelism is\n sample-wise on the main cython loop which assigns each sample to its\n closest center.\n\n Returns\n -------\n labels : ndarray of shape (n_samples,)\n The resulting assignment.\n\n inertia : float\n Sum of squared distances of samples to their closest cluster center.\n \"\"\"\n n_samples = X.shape[0]\n n_clusters = centers.shape[0]\n\n n_threads = _openmp_effective_n_threads(n_threads)\n\n labels = np.full(n_samples, -1, dtype=np.int32)\n weight_in_clusters = np.zeros(n_clusters, dtype=centers.dtype)\n center_shift = np.zeros_like(weight_in_clusters)\n\n if sp.issparse(X):\n _labels = lloyd_iter_chunked_sparse\n _inertia = _inertia_sparse\n else:\n _labels = lloyd_iter_chunked_dense\n _inertia = _inertia_dense\n\n _labels(X, sample_weight, x_squared_norms, centers, centers,\n weight_in_clusters, labels, center_shift, n_threads,\n update_centers=False)\n\n inertia = _inertia(X, sample_weight, centers, labels)\n\n return labels, inertia\n\n\nclass KMeans(TransformerMixin, ClusterMixin, BaseEstimator):\n \"\"\"K-Means clustering.\n\n Read more in the :ref:`User Guide <k_means>`.\n\n Parameters\n ----------\n\n n_clusters : int, default=8\n The number of clusters to form as well as the number of\n centroids to generate.\n\n init : {'k-means++', 'random'}, callable or array-like of shape \\\n (n_clusters, n_features), default='k-means++'\n Method for initialization:\n\n 'k-means++' : selects initial cluster centers for k-mean\n clustering in a smart way to speed up convergence. See section\n Notes in k_init for more details.\n\n 'random': choose `n_clusters` observations (rows) at random from data\n for the initial centroids.\n\n If an array is passed, it should be of shape (n_clusters, n_features)\n and gives the initial centers.\n\n If a callable is passed, it should take arguments X, n_clusters and a\n random state and return an initialization.\n\n n_init : int, default=10\n Number of time the k-means algorithm will be run with different\n centroid seeds. The final results will be the best output of\n n_init consecutive runs in terms of inertia.\n\n max_iter : int, default=300\n Maximum number of iterations of the k-means algorithm for a\n single run.\n\n tol : float, default=1e-4\n Relative tolerance with regards to Frobenius norm of the difference\n in the cluster centers of two consecutive iterations to declare\n convergence.\n\n precompute_distances : {'auto', True, False}, default='auto'\n Precompute distances (faster but takes more memory).\n\n 'auto' : do not precompute distances if n_samples * n_clusters > 12\n million. This corresponds to about 100MB overhead per job using\n double precision.\n\n True : always precompute distances.\n\n False : never precompute distances.\n\n .. deprecated:: 0.23\n 'precompute_distances' was deprecated in version 0.22 and will be\n removed in 1.0 (renaming of 0.25). It has no effect.\n\n verbose : int, default=0\n Verbosity mode.\n\n random_state : int, RandomState instance or None, default=None\n Determines random number generation for centroid initialization. Use\n an int to make the randomness deterministic.\n See :term:`Glossary <random_state>`.\n\n copy_x : bool, default=True\n When pre-computing distances it is more numerically accurate to center\n the data first. If copy_x is True (default), then the original data is\n not modified. If False, the original data is modified, and put back\n before the function returns, but small numerical differences may be\n introduced by subtracting and then adding the data mean. Note that if\n the original data is not C-contiguous, a copy will be made even if\n copy_x is False. If the original data is sparse, but not in CSR format,\n a copy will be made even if copy_x is False.\n\n n_jobs : int, default=None\n The number of OpenMP threads to use for the computation. Parallelism is\n sample-wise on the main cython loop which assigns each sample to its\n closest center.\n\n ``None`` or ``-1`` means using all processors.\n\n .. deprecated:: 0.23\n ``n_jobs`` was deprecated in version 0.23 and will be removed in\n 1.0 (renaming of 0.25).\n\n algorithm : {\"auto\", \"full\", \"elkan\"}, default=\"auto\"\n K-means algorithm to use. The classical EM-style algorithm is \"full\".\n The \"elkan\" variation is more efficient on data with well-defined\n clusters, by using the triangle inequality. However it's more memory\n intensive due to the allocation of an extra array of shape\n (n_samples, n_clusters).\n\n For now \"auto\" (kept for backward compatibiliy) chooses \"elkan\" but it\n might change in the future for a better heuristic.\n\n .. versionchanged:: 0.18\n Added Elkan algorithm\n\n Attributes\n ----------\n cluster_centers_ : ndarray of shape (n_clusters, n_features)\n Coordinates of cluster centers. If the algorithm stops before fully\n converging (see ``tol`` and ``max_iter``), these will not be\n consistent with ``labels_``.\n\n labels_ : ndarray of shape (n_samples,)\n Labels of each point\n\n inertia_ : float\n Sum of squared distances of samples to their closest cluster center.\n\n n_iter_ : int\n Number of iterations run.\n\n See Also\n --------\n MiniBatchKMeans : Alternative online implementation that does incremental\n updates of the centers positions using mini-batches.\n For large scale learning (say n_samples > 10k) MiniBatchKMeans is\n probably much faster than the default batch implementation.\n\n Notes\n -----\n The k-means problem is solved using either Lloyd's or Elkan's algorithm.\n\n The average complexity is given by O(k n T), where n is the number of\n samples and T is the number of iteration.\n\n The worst case complexity is given by O(n^(k+2/p)) with\n n = n_samples, p = n_features. (D. Arthur and S. Vassilvitskii,\n 'How slow is the k-means method?' SoCG2006)\n\n In practice, the k-means algorithm is very fast (one of the fastest\n clustering algorithms available), but it falls in local minima. That's why\n it can be useful to restart it several times.\n\n If the algorithm stops before fully converging (because of ``tol`` or\n ``max_iter``), ``labels_`` and ``cluster_centers_`` will not be consistent,\n i.e. the ``cluster_centers_`` will not be the means of the points in each\n cluster. Also, the estimator will reassign ``labels_`` after the last\n iteration to make ``labels_`` consistent with ``predict`` on the training\n set.\n\n Examples\n --------\n\n >>> from sklearn.cluster import KMeans\n >>> import numpy as np\n >>> X = np.array([[1, 2], [1, 4], [1, 0],\n ... [10, 2], [10, 4], [10, 0]])\n >>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X)\n >>> kmeans.labels_\n array([1, 1, 1, 0, 0, 0], dtype=int32)\n >>> kmeans.predict([[0, 0], [12, 3]])\n array([1, 0], dtype=int32)\n >>> kmeans.cluster_centers_\n array([[10., 2.],\n [ 1., 2.]])\n \"\"\"\n @_deprecate_positional_args\n def __init__(self, n_clusters=8, *, init='k-means++', n_init=10,\n max_iter=300, tol=1e-4, precompute_distances='deprecated',\n verbose=0, random_state=None, copy_x=True,\n n_jobs='deprecated', algorithm='auto'):\n\n self.n_clusters = n_clusters\n self.init = init\n self.max_iter = max_iter\n self.tol = tol\n self.precompute_distances = precompute_distances\n self.n_init = n_init\n self.verbose = verbose\n self.random_state = random_state\n self.copy_x = copy_x\n self.n_jobs = n_jobs\n self.algorithm = algorithm\n\n def _check_params(self, X):\n # precompute_distances\n if self.precompute_distances != 'deprecated':\n warnings.warn(\"'precompute_distances' was deprecated in version \"\n \"0.23 and will be removed in 1.0 (renaming of 0.25)\"\n \". It has no effect\", FutureWarning)\n\n # n_jobs\n if self.n_jobs != 'deprecated':\n warnings.warn(\"'n_jobs' was deprecated in version 0.23 and will be\"\n \" removed in 1.0 (renaming of 0.25).\", FutureWarning)\n self._n_threads = self.n_jobs\n else:\n self._n_threads = None\n self._n_threads = _openmp_effective_n_threads(self._n_threads)\n\n # n_init\n if self.n_init <= 0:\n raise ValueError(\n f\"n_init should be > 0, got {self.n_init} instead.\")\n self._n_init = self.n_init\n\n # max_iter\n if self.max_iter <= 0:\n raise ValueError(\n f\"max_iter should be > 0, got {self.max_iter} instead.\")\n\n # n_clusters\n if X.shape[0] < self.n_clusters:\n raise ValueError(f\"n_samples={X.shape[0]} should be >= \"\n f\"n_clusters={self.n_clusters}.\")\n\n # tol\n self._tol = _tolerance(X, self.tol)\n\n # algorithm\n if self.algorithm not in (\"auto\", \"full\", \"elkan\"):\n raise ValueError(f\"Algorithm must be 'auto', 'full' or 'elkan', \"\n f\"got {self.algorithm} instead.\")\n\n self._algorithm = self.algorithm\n if self._algorithm == \"auto\":\n self._algorithm = \"full\" if self.n_clusters == 1 else \"elkan\"\n if self._algorithm == \"elkan\" and self.n_clusters == 1:\n warnings.warn(\"algorithm='elkan' doesn't make sense for a single \"\n \"cluster. Using 'full' instead.\", RuntimeWarning)\n self._algorithm = \"full\"\n\n # init\n if not (hasattr(self.init, '__array__') or callable(self.init)\n or (isinstance(self.init, str)\n and self.init in [\"k-means++\", \"random\"])):\n raise ValueError(\n f\"init should be either 'k-means++', 'random', a ndarray or a \"\n f\"callable, got '{self.init}' instead.\")\n\n if hasattr(self.init, '__array__') and self._n_init != 1:\n warnings.warn(\n f\"Explicit initial center position passed: performing only\"\n f\" one init in {self.__class__.__name__} instead of \"\n f\"n_init={self._n_init}.\", RuntimeWarning, stacklevel=2)\n self._n_init = 1\n\n def _validate_center_shape(self, X, centers):\n \"\"\"Check if centers is compatible with X and n_clusters.\"\"\"\n if centers.shape[0] != self.n_clusters:\n raise ValueError(\n f\"The shape of the initial centers {centers.shape} does not \"\n f\"match the number of clusters {self.n_clusters}.\")\n if centers.shape[1] != X.shape[1]:\n raise ValueError(\n f\"The shape of the initial centers {centers.shape} does not \"\n f\"match the number of features of the data {X.shape[1]}.\")\n\n def _check_test_data(self, X):\n X = self._validate_data(X, accept_sparse='csr', reset=False,\n dtype=[np.float64, np.float32],\n order='C', accept_large_sparse=False)\n return X\n\n def _check_mkl_vcomp(self, X, n_samples):\n \"\"\"Warns when vcomp and mkl are both present\"\"\"\n # The BLAS call inside a prange in lloyd_iter_chunked_dense is known to\n # cause a small memory leak when there are less chunks than the number\n # of available threads. It only happens when the OpenMP library is\n # vcomp (microsoft OpenMP) and the BLAS library is MKL. see #18653\n if sp.issparse(X):\n return\n\n active_threads = int(np.ceil(n_samples / CHUNK_SIZE))\n if active_threads < self._n_threads:\n modules = threadpool_info()\n has_vcomp = \"vcomp\" in [module[\"prefix\"] for module in modules]\n has_mkl = (\"mkl\", \"intel\") in [\n (module[\"internal_api\"], module.get(\"threading_layer\", None))\n for module in modules]\n if has_vcomp and has_mkl:\n if not hasattr(self, \"batch_size\"): # KMeans\n warnings.warn(\n f\"KMeans is known to have a memory leak on Windows \"\n f\"with MKL, when there are less chunks than available \"\n f\"threads. You can avoid it by setting the environment\"\n f\" variable OMP_NUM_THREADS={active_threads}.\")\n else: # MiniBatchKMeans\n warnings.warn(\n f\"MiniBatchKMeans is known to have a memory leak on \"\n f\"Windows with MKL, when there are less chunks than \"\n f\"available threads. You can prevent it by setting \"\n f\"batch_size >= {self._n_threads * CHUNK_SIZE} or by \"\n f\"setting the environment variable \"\n f\"OMP_NUM_THREADS={active_threads}\")\n\n def _init_centroids(self, X, x_squared_norms, init, random_state,\n init_size=None):\n \"\"\"Compute the initial centroids.\n\n Parameters\n ----------\n X : {ndarray, sparse matrix} of shape (n_samples, n_features)\n The input samples.\n\n x_squared_norms : ndarray of shape (n_samples,)\n Squared euclidean norm of each data point. Pass it if you have it\n at hands already to avoid it being recomputed here.\n\n init : {'k-means++', 'random'}, callable or ndarray of shape \\\n (n_clusters, n_features)\n Method for initialization.\n\n random_state : RandomState instance\n Determines random number generation for centroid initialization.\n See :term:`Glossary <random_state>`.\n\n init_size : int, default=None\n Number of samples to randomly sample for speeding up the\n initialization (sometimes at the expense of accuracy).\n\n Returns\n -------\n centers : ndarray of shape (n_clusters, n_features)\n \"\"\"\n n_samples = X.shape[0]\n n_clusters = self.n_clusters\n\n if init_size is not None and init_size < n_samples:\n init_indices = random_state.randint(0, n_samples, init_size)\n X = X[init_indices]\n x_squared_norms = x_squared_norms[init_indices]\n n_samples = X.shape[0]\n\n if isinstance(init, str) and init == 'k-means++':\n centers, _ = _kmeans_plusplus(X, n_clusters,\n random_state=random_state,\n x_squared_norms=x_squared_norms)\n elif isinstance(init, str) and init == 'random':\n seeds = random_state.permutation(n_samples)[:n_clusters]\n centers = X[seeds]\n elif hasattr(init, '__array__'):\n centers = init\n elif callable(init):\n centers = init(X, n_clusters, random_state=random_state)\n centers = check_array(\n centers, dtype=X.dtype, copy=False, order='C')\n self._validate_center_shape(X, centers)\n\n if sp.issparse(centers):\n centers = centers.toarray()\n\n return centers\n\n def fit(self, X, y=None, sample_weight=None):\n \"\"\"Compute k-means clustering.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training instances to cluster. It must be noted that the data\n will be converted to C ordering, which will cause a memory\n copy if the given data is not C-contiguous.\n If a sparse matrix is passed, a copy will be made if it's not in\n CSR format.\n\n y : Ignored\n Not used, present here for API consistency by convention.\n\n sample_weight : array-like of shape (n_samples,), default=None\n The weights for each observation in X. If None, all observations\n are assigned equal weight.\n\n .. versionadded:: 0.20\n\n Returns\n -------\n self\n Fitted estimator.\n \"\"\"\n X = self._validate_data(X, accept_sparse='csr',\n dtype=[np.float64, np.float32],\n order='C', copy=self.copy_x,\n accept_large_sparse=False)\n\n self._check_params(X)\n random_state = check_random_state(self.random_state)\n sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)\n\n # Validate init array\n init = self.init\n if hasattr(init, '__array__'):\n init = check_array(init, dtype=X.dtype, copy=True, order='C')\n self._validate_center_shape(X, init)\n\n # subtract of mean of x for more accurate distance computations\n if not sp.issparse(X):\n X_mean = X.mean(axis=0)\n # The copy was already done above\n X -= X_mean\n\n if hasattr(init, '__array__'):\n init -= X_mean\n\n # precompute squared norms of data points\n x_squared_norms = row_norms(X, squared=True)\n\n if self._algorithm == \"full\":\n kmeans_single = _kmeans_single_lloyd\n self._check_mkl_vcomp(X, X.shape[0])\n else:\n kmeans_single = _kmeans_single_elkan\n\n best_inertia = None\n\n for i in range(self._n_init):\n # Initialize centers\n centers_init = self._init_centroids(\n X, x_squared_norms=x_squared_norms, init=init,\n random_state=random_state)\n if self.verbose:\n print(\"Initialization complete\")\n\n # run a k-means once\n labels, inertia, centers, n_iter_ = kmeans_single(\n X, sample_weight, centers_init, max_iter=self.max_iter,\n verbose=self.verbose, tol=self._tol,\n x_squared_norms=x_squared_norms, n_threads=self._n_threads)\n\n # determine if these results are the best so far\n if best_inertia is None or inertia < best_inertia:\n best_labels = labels\n best_centers = centers\n best_inertia = inertia\n best_n_iter = n_iter_\n\n if not sp.issparse(X):\n if not self.copy_x:\n X += X_mean\n best_centers += X_mean\n\n distinct_clusters = len(set(best_labels))\n if distinct_clusters < self.n_clusters:\n warnings.warn(\n \"Number of distinct clusters ({}) found smaller than \"\n \"n_clusters ({}). Possibly due to duplicate points \"\n \"in X.\".format(distinct_clusters, self.n_clusters),\n ConvergenceWarning, stacklevel=2)\n\n self.cluster_centers_ = best_centers\n self.labels_ = best_labels\n self.inertia_ = best_inertia\n self.n_iter_ = best_n_iter\n return self\n\n def fit_predict(self, X, y=None, sample_weight=None):\n \"\"\"Compute cluster centers and predict cluster index for each sample.\n\n Convenience method; equivalent to calling fit(X) followed by\n predict(X).\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n New data to transform.\n\n y : Ignored\n Not used, present here for API consistency by convention.\n\n sample_weight : array-like of shape (n_samples,), default=None\n The weights for each observation in X. If None, all observations\n are assigned equal weight.\n\n Returns\n -------\n labels : ndarray of shape (n_samples,)\n Index of the cluster each sample belongs to.\n \"\"\"\n return self.fit(X, sample_weight=sample_weight).labels_\n\n def fit_transform(self, X, y=None, sample_weight=None):\n \"\"\"Compute clustering and transform X to cluster-distance space.\n\n Equivalent to fit(X).transform(X), but more efficiently implemented.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n New data to transform.\n\n y : Ignored\n Not used, present here for API consistency by convention.\n\n sample_weight : array-like of shape (n_samples,), default=None\n The weights for each observation in X. If None, all observations\n are assigned equal weight.\n\n Returns\n -------\n X_new : ndarray of shape (n_samples, n_clusters)\n X transformed in the new space.\n \"\"\"\n # Currently, this just skips a copy of the data if it is not in\n # np.array or CSR format already.\n # XXX This skips _check_test_data, which may change the dtype;\n # we should refactor the input validation.\n return self.fit(X, sample_weight=sample_weight)._transform(X)\n\n def transform(self, X):\n \"\"\"Transform X to a cluster-distance space.\n\n In the new space, each dimension is the distance to the cluster\n centers. Note that even if X is sparse, the array returned by\n `transform` will typically be dense.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n New data to transform.\n\n Returns\n -------\n X_new : ndarray of shape (n_samples, n_clusters)\n X transformed in the new space.\n \"\"\"\n check_is_fitted(self)\n\n X = self._check_test_data(X)\n return self._transform(X)\n\n def _transform(self, X):\n \"\"\"Guts of transform method; no input validation.\"\"\"\n return euclidean_distances(X, self.cluster_centers_)\n\n def predict(self, X, sample_weight=None):\n \"\"\"Predict the closest cluster each sample in X belongs to.\n\n In the vector quantization literature, `cluster_centers_` is called\n the code book and each value returned by `predict` is the index of\n the closest code in the code book.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n New data to predict.\n\n sample_weight : array-like of shape (n_samples,), default=None\n The weights for each observation in X. If None, all observations\n are assigned equal weight.\n\n Returns\n -------\n labels : ndarray of shape (n_samples,)\n Index of the cluster each sample belongs to.\n \"\"\"\n check_is_fitted(self)\n\n X = self._check_test_data(X)\n x_squared_norms = row_norms(X, squared=True)\n sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)\n\n return _labels_inertia(X, sample_weight, x_squared_norms,\n self.cluster_centers_, self._n_threads)[0]\n\n def score(self, X, y=None, sample_weight=None):\n \"\"\"Opposite of the value of X on the K-means objective.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n New data.\n\n y : Ignored\n Not used, present here for API consistency by convention.\n\n sample_weight : array-like of shape (n_samples,), default=None\n The weights for each observation in X. If None, all observations\n are assigned equal weight.\n\n Returns\n -------\n score : float\n Opposite of the value of X on the K-means objective.\n \"\"\"\n check_is_fitted(self)\n\n X = self._check_test_data(X)\n x_squared_norms = row_norms(X, squared=True)\n sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)\n\n return -_labels_inertia(X, sample_weight, x_squared_norms,\n self.cluster_centers_)[1]\n\n def _more_tags(self):\n return {\n '_xfail_checks': {\n 'check_sample_weights_invariance':\n 'zero sample_weight is not equivalent to removing samples',\n },\n }\n\n\ndef _mini_batch_step(X, sample_weight, x_squared_norms, centers, weight_sums,\n old_center_buffer, compute_squared_diff,\n distances, random_reassign=False,\n random_state=None, reassignment_ratio=.01,\n verbose=False):\n \"\"\"Incremental update of the centers for the Minibatch K-Means algorithm.\n\n Parameters\n ----------\n\n X : ndarray of shape (n_samples, n_features)\n The original data array.\n\n sample_weight : array-like of shape (n_samples,)\n The weights for each observation in X.\n\n x_squared_norms : ndarray of shape (n_samples,)\n Squared euclidean norm of each data point.\n\n centers : ndarray of shape (k, n_features)\n The cluster centers. This array is MODIFIED IN PLACE\n\n old_center_buffer : int\n Copy of old centers for monitoring convergence.\n\n compute_squared_diff : bool\n If set to False, the squared diff computation is skipped.\n\n distances : ndarray of shape (n_samples,), dtype=float, default=None\n If not None, should be a pre-allocated array that will be used to store\n the distances of each sample to its closest center.\n May not be None when random_reassign is True.\n\n random_reassign : bool, default=False\n If True, centers with very low counts are randomly reassigned\n to observations.\n\n random_state : int, RandomState instance or None, default=None\n Determines random number generation for centroid initialization and to\n pick new clusters amongst observations with uniform probability. Use\n an int to make the randomness deterministic.\n See :term:`Glossary <random_state>`.\n\n reassignment_ratio : float, default=.01\n Control the fraction of the maximum number of counts for a\n center to be reassigned. A higher value means that low count\n centers are more likely to be reassigned, which means that the\n model will take longer to converge, but should converge in a\n better clustering.\n\n verbose : bool, default=False\n Controls the verbosity.\n\n Returns\n -------\n inertia : float\n Sum of squared distances of samples to their closest cluster center.\n\n squared_diff : ndarray of shape (n_clusters,)\n Squared distances between previous and updated cluster centers.\n\n \"\"\"\n # Perform label assignment to nearest centers\n nearest_center, inertia = _labels_inertia(X, sample_weight,\n x_squared_norms, centers)\n\n if random_reassign and reassignment_ratio > 0:\n random_state = check_random_state(random_state)\n # Reassign clusters that have very low weight\n to_reassign = weight_sums < reassignment_ratio * weight_sums.max()\n # pick at most .5 * batch_size samples as new centers\n if to_reassign.sum() > .5 * X.shape[0]:\n indices_dont_reassign = \\\n np.argsort(weight_sums)[int(.5 * X.shape[0]):]\n to_reassign[indices_dont_reassign] = False\n n_reassigns = to_reassign.sum()\n if n_reassigns:\n # Pick new clusters amongst observations with uniform probability\n new_centers = random_state.choice(X.shape[0], replace=False,\n size=n_reassigns)\n if verbose:\n print(\"[MiniBatchKMeans] Reassigning %i cluster centers.\"\n % n_reassigns)\n\n if sp.issparse(X) and not sp.issparse(centers):\n assign_rows_csr(\n X, new_centers.astype(np.intp, copy=False),\n np.where(to_reassign)[0].astype(np.intp, copy=False),\n centers)\n else:\n centers[to_reassign] = X[new_centers]\n # reset counts of reassigned centers, but don't reset them too small\n # to avoid instant reassignment. This is a pretty dirty hack as it\n # also modifies the learning rates.\n weight_sums[to_reassign] = np.min(weight_sums[~to_reassign])\n\n # implementation for the sparse CSR representation completely written in\n # cython\n if sp.issparse(X):\n return inertia, _mini_batch_update_csr(\n X, sample_weight, x_squared_norms, centers, weight_sums,\n nearest_center, old_center_buffer, compute_squared_diff)\n\n # dense variant in mostly numpy (not as memory efficient though)\n k = centers.shape[0]\n squared_diff = 0.0\n for center_idx in range(k):\n # find points from minibatch that are assigned to this center\n center_mask = nearest_center == center_idx\n wsum = sample_weight[center_mask].sum()\n\n if wsum > 0:\n if compute_squared_diff:\n old_center_buffer[:] = centers[center_idx]\n\n # inplace remove previous count scaling\n centers[center_idx] *= weight_sums[center_idx]\n\n # inplace sum with new points members of this cluster\n centers[center_idx] += \\\n np.sum(X[center_mask] *\n sample_weight[center_mask, np.newaxis], axis=0)\n\n # update the count statistics for this center\n weight_sums[center_idx] += wsum\n\n # inplace rescale to compute mean of all points (old and new)\n # Note: numpy >= 1.10 does not support '/=' for the following\n # expression for a mixture of int and float (see numpy issue #6464)\n centers[center_idx] = centers[center_idx] / weight_sums[center_idx]\n\n # update the squared diff if necessary\n if compute_squared_diff:\n diff = centers[center_idx].ravel() - old_center_buffer.ravel()\n squared_diff += np.dot(diff, diff)\n\n return inertia, squared_diff\n\n\ndef _mini_batch_convergence(model, iteration_idx, n_iter, tol,\n n_samples, centers_squared_diff, batch_inertia,\n context, verbose=0):\n \"\"\"Helper function to encapsulate the early stopping logic.\"\"\"\n # Normalize inertia to be able to compare values when\n # batch_size changes\n batch_inertia /= model.batch_size\n centers_squared_diff /= model.batch_size\n\n # Compute an Exponentially Weighted Average of the squared\n # diff to monitor the convergence while discarding\n # minibatch-local stochastic variability:\n # https://en.wikipedia.org/wiki/Moving_average\n ewa_diff = context.get('ewa_diff')\n ewa_inertia = context.get('ewa_inertia')\n if ewa_diff is None:\n ewa_diff = centers_squared_diff\n ewa_inertia = batch_inertia\n else:\n alpha = float(model.batch_size) * 2.0 / (n_samples + 1)\n alpha = 1.0 if alpha > 1.0 else alpha\n ewa_diff = ewa_diff * (1 - alpha) + centers_squared_diff * alpha\n ewa_inertia = ewa_inertia * (1 - alpha) + batch_inertia * alpha\n\n # Log progress to be able to monitor convergence\n if verbose:\n progress_msg = (\n 'Minibatch iteration %d/%d:'\n ' mean batch inertia: %f, ewa inertia: %f ' % (\n iteration_idx + 1, n_iter, batch_inertia,\n ewa_inertia))\n print(progress_msg)\n\n # Early stopping based on absolute tolerance on squared change of\n # centers position (using EWA smoothing)\n if tol > 0.0 and ewa_diff <= tol:\n if verbose:\n print('Converged (small centers change) at iteration %d/%d'\n % (iteration_idx + 1, n_iter))\n return True\n\n # Early stopping heuristic due to lack of improvement on smoothed inertia\n ewa_inertia_min = context.get('ewa_inertia_min')\n no_improvement = context.get('no_improvement', 0)\n if ewa_inertia_min is None or ewa_inertia < ewa_inertia_min:\n no_improvement = 0\n ewa_inertia_min = ewa_inertia\n else:\n no_improvement += 1\n\n if (model.max_no_improvement is not None\n and no_improvement >= model.max_no_improvement):\n if verbose:\n print('Converged (lack of improvement in inertia)'\n ' at iteration %d/%d'\n % (iteration_idx + 1, n_iter))\n return True\n\n # update the convergence context to maintain state across successive calls:\n context['ewa_diff'] = ewa_diff\n context['ewa_inertia'] = ewa_inertia\n context['ewa_inertia_min'] = ewa_inertia_min\n context['no_improvement'] = no_improvement\n return False\n\n\nclass MiniBatchKMeans(KMeans):\n \"\"\"\n Mini-Batch K-Means clustering.\n\n Read more in the :ref:`User Guide <mini_batch_kmeans>`.\n\n Parameters\n ----------\n\n n_clusters : int, default=8\n The number of clusters to form as well as the number of\n centroids to generate.\n\n init : {'k-means++', 'random'}, callable or array-like of shape \\\n (n_clusters, n_features), default='k-means++'\n Method for initialization:\n\n 'k-means++' : selects initial cluster centers for k-mean\n clustering in a smart way to speed up convergence. See section\n Notes in k_init for more details.\n\n 'random': choose `n_clusters` observations (rows) at random from data\n for the initial centroids.\n\n If an array is passed, it should be of shape (n_clusters, n_features)\n and gives the initial centers.\n\n If a callable is passed, it should take arguments X, n_clusters and a\n random state and return an initialization.\n\n max_iter : int, default=100\n Maximum number of iterations over the complete dataset before\n stopping independently of any early stopping criterion heuristics.\n\n batch_size : int, default=100\n Size of the mini batches.\n\n verbose : int, default=0\n Verbosity mode.\n\n compute_labels : bool, default=True\n Compute label assignment and inertia for the complete dataset\n once the minibatch optimization has converged in fit.\n\n random_state : int, RandomState instance or None, default=None\n Determines random number generation for centroid initialization and\n random reassignment. Use an int to make the randomness deterministic.\n See :term:`Glossary <random_state>`.\n\n tol : float, default=0.0\n Control early stopping based on the relative center changes as\n measured by a smoothed, variance-normalized of the mean center\n squared position changes. This early stopping heuristics is\n closer to the one used for the batch variant of the algorithms\n but induces a slight computational and memory overhead over the\n inertia heuristic.\n\n To disable convergence detection based on normalized center\n change, set tol to 0.0 (default).\n\n max_no_improvement : int, default=10\n Control early stopping based on the consecutive number of mini\n batches that does not yield an improvement on the smoothed inertia.\n\n To disable convergence detection based on inertia, set\n max_no_improvement to None.\n\n init_size : int, default=None\n Number of samples to randomly sample for speeding up the\n initialization (sometimes at the expense of accuracy): the\n only algorithm is initialized by running a batch KMeans on a\n random subset of the data. This needs to be larger than n_clusters.\n\n If `None`, `init_size= 3 * batch_size`.\n\n n_init : int, default=3\n Number of random initializations that are tried.\n In contrast to KMeans, the algorithm is only run once, using the\n best of the ``n_init`` initializations as measured by inertia.\n\n reassignment_ratio : float, default=0.01\n Control the fraction of the maximum number of counts for a\n center to be reassigned. A higher value means that low count\n centers are more easily reassigned, which means that the\n model will take longer to converge, but should converge in a\n better clustering.\n\n Attributes\n ----------\n\n cluster_centers_ : ndarray of shape (n_clusters, n_features)\n Coordinates of cluster centers.\n\n labels_ : int\n Labels of each point (if compute_labels is set to True).\n\n inertia_ : float\n The value of the inertia criterion associated with the chosen\n partition (if compute_labels is set to True). The inertia is\n defined as the sum of square distances of samples to their nearest\n neighbor.\n\n n_iter_ : int\n Number of batches processed.\n\n counts_ : ndarray of shape (n_clusters,)\n Weigth sum of each cluster.\n\n .. deprecated:: 0.24\n This attribute is deprecated in 0.24 and will be removed in\n 1.1 (renaming of 0.26).\n\n init_size_ : int\n The effective number of samples used for the initialization.\n\n .. deprecated:: 0.24\n This attribute is deprecated in 0.24 and will be removed in\n 1.1 (renaming of 0.26).\n\n See Also\n --------\n KMeans : The classic implementation of the clustering method based on the\n Lloyd's algorithm. It consumes the whole set of input data at each\n iteration.\n\n Notes\n -----\n See https://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf\n\n Examples\n --------\n >>> from sklearn.cluster import MiniBatchKMeans\n >>> import numpy as np\n >>> X = np.array([[1, 2], [1, 4], [1, 0],\n ... [4, 2], [4, 0], [4, 4],\n ... [4, 5], [0, 1], [2, 2],\n ... [3, 2], [5, 5], [1, -1]])\n >>> # manually fit on batches\n >>> kmeans = MiniBatchKMeans(n_clusters=2,\n ... random_state=0,\n ... batch_size=6)\n >>> kmeans = kmeans.partial_fit(X[0:6,:])\n >>> kmeans = kmeans.partial_fit(X[6:12,:])\n >>> kmeans.cluster_centers_\n array([[2. , 1. ],\n [3.5, 4.5]])\n >>> kmeans.predict([[0, 0], [4, 4]])\n array([0, 1], dtype=int32)\n >>> # fit on the whole data\n >>> kmeans = MiniBatchKMeans(n_clusters=2,\n ... random_state=0,\n ... batch_size=6,\n ... max_iter=10).fit(X)\n >>> kmeans.cluster_centers_\n array([[3.95918367, 2.40816327],\n [1.12195122, 1.3902439 ]])\n >>> kmeans.predict([[0, 0], [4, 4]])\n array([1, 0], dtype=int32)\n \"\"\"\n @_deprecate_positional_args\n def __init__(self, n_clusters=8, *, init='k-means++', max_iter=100,\n batch_size=100, verbose=0, compute_labels=True,\n random_state=None, tol=0.0, max_no_improvement=10,\n init_size=None, n_init=3, reassignment_ratio=0.01):\n\n super().__init__(\n n_clusters=n_clusters, init=init, max_iter=max_iter,\n verbose=verbose, random_state=random_state, tol=tol, n_init=n_init)\n\n self.max_no_improvement = max_no_improvement\n self.batch_size = batch_size\n self.compute_labels = compute_labels\n self.init_size = init_size\n self.reassignment_ratio = reassignment_ratio\n\n @deprecated(\"The attribute 'counts_' is deprecated in 0.24\" # type: ignore\n \" and will be removed in 1.1 (renaming of 0.26).\")\n @property\n def counts_(self):\n return self._counts\n\n @deprecated(\"The attribute 'init_size_' is deprecated in \" # type: ignore\n \"0.24 and will be removed in 1.1 (renaming of 0.26).\")\n @property\n def init_size_(self):\n return self._init_size\n\n @deprecated(\"The attribute 'random_state_' is deprecated \" # type: ignore\n \"in 0.24 and will be removed in 1.1 (renaming of 0.26).\")\n @property\n def random_state_(self):\n return getattr(self, \"_random_state\", None)\n\n def _check_params(self, X):\n super()._check_params(X)\n\n # max_no_improvement\n if self.max_no_improvement is not None and self.max_no_improvement < 0:\n raise ValueError(\n f\"max_no_improvement should be >= 0, got \"\n f\"{self.max_no_improvement} instead.\")\n\n # batch_size\n if self.batch_size <= 0:\n raise ValueError(\n f\"batch_size should be > 0, got {self.batch_size} instead.\")\n\n # init_size\n if self.init_size is not None and self.init_size <= 0:\n raise ValueError(\n f\"init_size should be > 0, got {self.init_size} instead.\")\n self._init_size = self.init_size\n if self._init_size is None:\n self._init_size = 3 * self.batch_size\n if self._init_size < self.n_clusters:\n self._init_size = 3 * self.n_clusters\n elif self._init_size < self.n_clusters:\n warnings.warn(\n f\"init_size={self._init_size} should be larger than \"\n f\"n_clusters={self.n_clusters}. Setting it to \"\n f\"min(3*n_clusters, n_samples)\",\n RuntimeWarning, stacklevel=2)\n self._init_size = 3 * self.n_clusters\n self._init_size = min(self._init_size, X.shape[0])\n\n # reassignment_ratio\n if self.reassignment_ratio < 0:\n raise ValueError(\n f\"reassignment_ratio should be >= 0, got \"\n f\"{self.reassignment_ratio} instead.\")\n\n def fit(self, X, y=None, sample_weight=None):\n \"\"\"Compute the centroids on X by chunking it into mini-batches.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training instances to cluster. It must be noted that the data\n will be converted to C ordering, which will cause a memory copy\n if the given data is not C-contiguous.\n\n y : Ignored\n Not used, present here for API consistency by convention.\n\n sample_weight : array-like of shape (n_samples,), default=None\n The weights for each observation in X. If None, all observations\n are assigned equal weight (default: None).\n\n .. versionadded:: 0.20\n\n Returns\n -------\n self\n \"\"\"\n X = self._validate_data(X, accept_sparse='csr',\n dtype=[np.float64, np.float32],\n order='C', accept_large_sparse=False)\n\n self._check_params(X)\n random_state = check_random_state(self.random_state)\n sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)\n\n # Validate init array\n init = self.init\n if hasattr(init, '__array__'):\n init = check_array(init, dtype=X.dtype, copy=True, order='C')\n self._validate_center_shape(X, init)\n\n n_samples, n_features = X.shape\n x_squared_norms = row_norms(X, squared=True)\n\n if self.tol > 0.0:\n tol = _tolerance(X, self.tol)\n\n # using tol-based early stopping needs the allocation of a\n # dedicated before which can be expensive for high dim data:\n # hence we allocate it outside of the main loop\n old_center_buffer = np.zeros(n_features, dtype=X.dtype)\n else:\n tol = 0.0\n # no need for the center buffer if tol-based early stopping is\n # disabled\n old_center_buffer = np.zeros(0, dtype=X.dtype)\n\n distances = np.zeros(self.batch_size, dtype=X.dtype)\n n_batches = int(np.ceil(float(n_samples) / self.batch_size))\n n_iter = int(self.max_iter * n_batches)\n\n self._check_mkl_vcomp(X, self.batch_size)\n\n validation_indices = random_state.randint(0, n_samples,\n self._init_size)\n X_valid = X[validation_indices]\n sample_weight_valid = sample_weight[validation_indices]\n x_squared_norms_valid = x_squared_norms[validation_indices]\n\n # perform several inits with random sub-sets\n best_inertia = None\n for init_idx in range(self._n_init):\n if self.verbose:\n print(\"Init %d/%d with method: %s\"\n % (init_idx + 1, self._n_init, init))\n weight_sums = np.zeros(self.n_clusters, dtype=sample_weight.dtype)\n\n # TODO: once the `k_means` function works with sparse input we\n # should refactor the following init to use it instead.\n\n # Initialize the centers using only a fraction of the data as we\n # expect n_samples to be very large when using MiniBatchKMeans\n cluster_centers = self._init_centroids(\n X, x_squared_norms=x_squared_norms,\n init=init,\n random_state=random_state,\n init_size=self._init_size)\n\n # Compute the label assignment on the init dataset\n _mini_batch_step(\n X_valid, sample_weight_valid,\n x_squared_norms[validation_indices], cluster_centers,\n weight_sums, old_center_buffer, False, distances=None,\n verbose=self.verbose)\n\n # Keep only the best cluster centers across independent inits on\n # the common validation set\n _, inertia = _labels_inertia(X_valid, sample_weight_valid,\n x_squared_norms_valid,\n cluster_centers)\n if self.verbose:\n print(\"Inertia for init %d/%d: %f\"\n % (init_idx + 1, self._n_init, inertia))\n if best_inertia is None or inertia < best_inertia:\n self.cluster_centers_ = cluster_centers\n self._counts = weight_sums\n best_inertia = inertia\n\n # Empty context to be used inplace by the convergence check routine\n convergence_context = {}\n\n # Perform the iterative optimization until the final convergence\n # criterion\n for iteration_idx in range(n_iter):\n # Sample a minibatch from the full dataset\n minibatch_indices = random_state.randint(\n 0, n_samples, self.batch_size)\n\n # Perform the actual update step on the minibatch data\n batch_inertia, centers_squared_diff = _mini_batch_step(\n X[minibatch_indices], sample_weight[minibatch_indices],\n x_squared_norms[minibatch_indices],\n self.cluster_centers_, self._counts,\n old_center_buffer, tol > 0.0, distances=distances,\n # Here we randomly choose whether to perform\n # random reassignment: the choice is done as a function\n # of the iteration index, and the minimum number of\n # counts, in order to force this reassignment to happen\n # every once in a while\n random_reassign=((iteration_idx + 1)\n % (10 + int(self._counts.min())) == 0),\n random_state=random_state,\n reassignment_ratio=self.reassignment_ratio,\n verbose=self.verbose)\n\n # Monitor convergence and do early stopping if necessary\n if _mini_batch_convergence(\n self, iteration_idx, n_iter, tol, n_samples,\n centers_squared_diff, batch_inertia, convergence_context,\n verbose=self.verbose):\n break\n\n self.n_iter_ = iteration_idx + 1\n\n if self.compute_labels:\n self.labels_, self.inertia_ = \\\n self._labels_inertia_minibatch(X, sample_weight)\n\n return self\n\n def _labels_inertia_minibatch(self, X, sample_weight):\n \"\"\"Compute labels and inertia using mini batches.\n\n This is slightly slower than doing everything at once but prevents\n memory errors / segfaults.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Input data.\n\n sample_weight : array-like of shape (n_samples,)\n The weights for each observation in X.\n\n Returns\n -------\n labels : ndarray of shape (n_samples,)\n Cluster labels for each point.\n\n inertia : float\n Sum of squared distances of points to nearest cluster.\n \"\"\"\n if self.verbose:\n print('Computing label assignment and total inertia')\n sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)\n x_squared_norms = row_norms(X, squared=True)\n slices = gen_batches(X.shape[0], self.batch_size)\n results = [_labels_inertia(X[s], sample_weight[s], x_squared_norms[s],\n self.cluster_centers_) for s in slices]\n labels, inertia = zip(*results)\n return np.hstack(labels), np.sum(inertia)\n\n def partial_fit(self, X, y=None, sample_weight=None):\n \"\"\"Update k means estimate on a single mini-batch X.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Coordinates of the data points to cluster. It must be noted that\n X will be copied if it is not C-contiguous.\n\n y : Ignored\n Not used, present here for API consistency by convention.\n\n sample_weight : array-like of shape (n_samples,), default=None\n The weights for each observation in X. If None, all observations\n are assigned equal weight (default: None).\n\n Returns\n -------\n self\n \"\"\"\n is_first_call_to_partial_fit = not hasattr(self, 'cluster_centers_')\n\n X = self._validate_data(X, accept_sparse='csr',\n dtype=[np.float64, np.float32],\n order='C', accept_large_sparse=False,\n reset=is_first_call_to_partial_fit)\n\n self._random_state = getattr(self, \"_random_state\",\n check_random_state(self.random_state))\n sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)\n\n x_squared_norms = row_norms(X, squared=True)\n\n if is_first_call_to_partial_fit:\n # this is the first call to partial_fit on this object\n self._check_params(X)\n\n # Validate init array\n init = self.init\n if hasattr(init, '__array__'):\n init = check_array(init, dtype=X.dtype, copy=True, order='C')\n self._validate_center_shape(X, init)\n\n self._check_mkl_vcomp(X, X.shape[0])\n\n # initialize the cluster centers\n self.cluster_centers_ = self._init_centroids(\n X, x_squared_norms=x_squared_norms,\n init=init,\n random_state=self._random_state,\n init_size=self._init_size)\n\n self._counts = np.zeros(self.n_clusters,\n dtype=sample_weight.dtype)\n random_reassign = False\n distances = None\n else:\n # The lower the minimum count is, the more we do random\n # reassignment, however, we don't want to do random\n # reassignment too often, to allow for building up counts\n random_reassign = self._random_state.randint(\n 10 * (1 + self._counts.min())) == 0\n distances = np.zeros(X.shape[0], dtype=X.dtype)\n\n _mini_batch_step(X, sample_weight, x_squared_norms,\n self.cluster_centers_, self._counts,\n np.zeros(0, dtype=X.dtype), 0,\n random_reassign=random_reassign, distances=distances,\n random_state=self._random_state,\n reassignment_ratio=self.reassignment_ratio,\n verbose=self.verbose)\n\n if self.compute_labels:\n self.labels_, self.inertia_ = _labels_inertia(\n X, sample_weight, x_squared_norms, self.cluster_centers_)\n\n return self\n\n def predict(self, X, sample_weight=None):\n \"\"\"Predict the closest cluster each sample in X belongs to.\n\n In the vector quantization literature, `cluster_centers_` is called\n the code book and each value returned by `predict` is the index of\n the closest code in the code book.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n New data to predict.\n\n sample_weight : array-like of shape (n_samples,), default=None\n The weights for each observation in X. If None, all observations\n are assigned equal weight (default: None).\n\n Returns\n -------\n labels : ndarray of shape (n_samples,)\n Index of the cluster each sample belongs to.\n \"\"\"\n check_is_fitted(self)\n\n X = self._check_test_data(X)\n return self._labels_inertia_minibatch(X, sample_weight)[0]\n\n def _more_tags(self):\n return {\n '_xfail_checks': {\n 'check_sample_weights_invariance':\n 'zero sample_weight is not equivalent to removing samples',\n }\n }\n\n\ndef kmeans_plusplus(X, n_clusters, *, x_squared_norms=None,\n random_state=None, n_local_trials=None):\n \"\"\"Init n_clusters seeds according to k-means++\n\n .. versionadded:: 0.24\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The data to pick seeds from.\n\n n_clusters : int\n The number of centroids to initialize\n\n x_squared_norms : array-like of shape (n_samples,), default=None\n Squared Euclidean norm of each data point.\n\n random_state : int or RandomState instance, default=None\n Determines random number generation for centroid initialization. Pass\n an int for reproducible output across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n n_local_trials : int, default=None\n The number of seeding trials for each center (except the first),\n of which the one reducing inertia the most is greedily chosen.\n Set to None to make the number of trials depend logarithmically\n on the number of seeds (2+log(k)).\n\n Returns\n -------\n centers : ndarray of shape (n_clusters, n_features)\n The inital centers for k-means.\n\n indices : ndarray of shape (n_clusters,)\n The index location of the chosen centers in the data array X. For a\n given index and center, X[index] = center.\n\n Notes\n -----\n Selects initial cluster centers for k-mean clustering in a smart way\n to speed up convergence. see: Arthur, D. and Vassilvitskii, S.\n \"k-means++: the advantages of careful seeding\". ACM-SIAM symposium\n on Discrete algorithms. 2007\n\n Examples\n --------\n\n >>> from sklearn.cluster import kmeans_plusplus\n >>> import numpy as np\n >>> X = np.array([[1, 2], [1, 4], [1, 0],\n ... [10, 2], [10, 4], [10, 0]])\n >>> centers, indices = kmeans_plusplus(X, n_clusters=2, random_state=0)\n >>> centers\n array([[10, 4],\n [ 1, 0]])\n >>> indices\n array([4, 2])\n \"\"\"\n\n # Check data\n check_array(X, accept_sparse='csr',\n dtype=[np.float64, np.float32])\n\n if X.shape[0] < n_clusters:\n raise ValueError(f\"n_samples={X.shape[0]} should be >= \"\n f\"n_clusters={n_clusters}.\")\n\n # Check parameters\n if x_squared_norms is None:\n x_squared_norms = row_norms(X, squared=True)\n else:\n x_squared_norms = check_array(x_squared_norms,\n dtype=X.dtype,\n ensure_2d=False)\n\n if x_squared_norms.shape[0] != X.shape[0]:\n raise ValueError(\n f\"The length of x_squared_norms {x_squared_norms.shape[0]} should \"\n f\"be equal to the length of n_samples {X.shape[0]}.\")\n\n if n_local_trials is not None and n_local_trials < 1:\n raise ValueError(\n f\"n_local_trials is set to {n_local_trials} but should be an \"\n f\"integer value greater than zero.\")\n\n random_state = check_random_state(random_state)\n\n # Call private k-means++\n centers, indices = _kmeans_plusplus(X, n_clusters, x_squared_norms,\n random_state, n_local_trials)\n\n return centers, indices\n"
]
| [
[
"numpy.dot",
"numpy.minimum",
"numpy.asarray",
"numpy.zeros_like",
"numpy.argmin",
"numpy.mean",
"numpy.var",
"numpy.where",
"numpy.hstack",
"scipy.sparse.issparse",
"numpy.clip",
"numpy.full",
"numpy.ceil",
"numpy.zeros",
"numpy.log",
"numpy.min",
"numpy.argsort",
"numpy.sum",
"numpy.array_equal",
"numpy.empty"
]
]
|
FordyceLab/AcqPack | [
"e8566d9644280549093c6ad1059004718b36f477"
]
| [
"acqpack/log.py"
]
| [
"import pandas as pd\nimport IPython.display as disp\nimport inspect\nimport types\nimport time\nimport threading\n\n# TODO:\n# - continously updating display with new events (flag?)\n# - conditional formatting (pandas styler)\n# - plotting\n# - use python built-in logging backend (cross-notebook)?\n# - logging/inspection from Jupyter? reproducable Juyter plugin?\n# - fix signature of wrapper [e.g. f.goto(lookup, blah,...)]\n# - keyword args\n# - bug where __init__ time logging doesn't work properly\n# - how to handle re-running cells/etc\n# - single .track() function\n# - simulation (on ordered scale, not necessarily time-based)\n# - log state interpreter\n# - get_state(log) \n# - config .show() to hide fields\n# - thread safety https://stackoverflow.com/questions/261683/what-is-meant-by-thread-safe-code\n# - 'cls' usage problem: https://stackoverflow.com/questions/4613000/what-is-the-cls-variable-used-for-in-python-classes\nclass Log():\n \"\"\"\n Creates a pandas df for logging function calls.\n The columns of the df are:\n 't_in','ts_in','t_out','ts_out','cl','fn','fn_in','fn_out'\n \n Provides functions for replacing:\n a) functions [.track_fn(f)]\n b) classes [.track_classes(classes)]\n with wrapped versions that log calls to the df.\n \n Example: ------------------------------\n l = Log()\n \n # create tracked function (1st way)\n @l.track_fn\n def f1(input):\n output = input\n return output\n \n # create tracked function (2nd way)\n def f2(input):\n output = input\n return output\n f2 = l.track_fn(f2)\n \n # replace classes with versions whose\n # functions are all tracked\n l.track_classes([Class1, Class2, ...])\n \n # manually write to log \n l.write('A note')\n \n # make function calls as normal\n f1('input')\n f2('input')\n Class1.f('input')\n \n # display log\n l.show()\n \n # access log\n l.df\n \n \"\"\"\n def __init__(self):\n self.df = pd.DataFrame(columns=['t_in', 'ts_in', 't_out', 'ts_out', 'dt', 'th',\n 'cl', 'fn', 'fn_in', 'fn_out'])\n self.show_filter = 'index' # permissive filter\n self._lock = threading.Lock()\n self.write = self.track_fn(self.write)\n self.write('init')\n \n \n def format_time(self, time_s):\n return time.strftime(\"%Y%m%d_%H:%M:%S\", time.localtime(time_s))\n \n \n def show(self, query='', ascending=True, clear_display=True):\n if query=='':\n query = self.show_filter\n\n ret = (self.df[['ts_in', 'ts_out', 'dt', 'th',\n 'cl', 'fn', 'fn_in', 'fn_out']]\n .query(query)\n .sort_index(ascending=ascending)\n .style\n .set_properties(**{'text-align': 'left'})\n .set_table_styles([dict(selector='th', props=[('text-align', 'left')] ) ])\n .format({'dt': \"{:.3f}\"}))\n if clear_display:\n disp.clear_output(wait=True)\n disp.display(ret)\n else:\n return ret.data\n \n def write(self, msg):\n pass\n \n def track_fn(self, f):\n def wrapper(*args):\n if f.__class__.__name__ == 'instancemethod':\n cl = f.im_class.__name__\n if cl!='Log':\n inputs = args[1:]\n else:\n inputs = args\n else:\n cl = ''\n inputs = args\n #obj = str(args[0])[str(args[0]).find('at ')+3:-1]\n fn = f.__name__\n \n with self._lock:\n i = len(self.df)\n t_in = time.time()\n th = threading.currentThread().getName()\n # print 'in', fn, threading.active_count()\n self.df.loc[i, ['t_in','ts_in','th','cl','fn','fn_in']] = [t_in, self.format_time(t_in), th, cl, fn, inputs]\n outputs = f(*args)\n with self._lock:\n t_out = time.time()\n self.df.loc[i, ['t_out','ts_out','dt','fn_out']] = [t_out, self.format_time(t_out), t_out-t_in, outputs]\n # print 'out', fn, threading.active_count()\n \n return outputs \n wrapper.__doc__ = f.__doc__\n return wrapper\n \n def track_classes(self, classes):\n for cl in classes:\n for name, f in inspect.getmembers(cl):\n if isinstance(f, types.UnboundMethodType):\n setattr(cl, name, self.track_fn(f))"
]
| [
[
"pandas.DataFrame"
]
]
|
kshitijahande/CV-Project-Image-Colorization | [
"26616baf5152e0dea6218712d5efee3cd35f4bac"
]
| [
"src/convert_to_onnx.py"
]
| [
"import segmentation_models_pytorch as smp\nimport torch\nfrom dataset import ColorizationDataset\nimport glob\nimport onnx\n\n\ndef convert_to_onnx(model_state_dict, inputs):\n \"\"\"Method to convert pytorch models to onnx format.\n Args:\n model_state_dict: The state dictionary of model.\n inputs: The input tensor\n \"\"\"\n model = smp.Unet(\n encoder_name=\"efficientnet-b1\",\n encoder_weights=\"imagenet\",\n in_channels=1,\n classes=2,\n )\n\n model.load_state_dict(model_state_dict)\n model.encoder.set_swish(memory_efficient=False)\n model.eval()\n torch.onnx.export(\n model,\n inputs,\n \"generator.onnx\",\n opset_version=11,\n input_names=[\"input\"],\n output_names=[\"output\"],\n dynamic_axes={\"input\": {0: \"batch_size\"}, \"output\": {0: \"batch_size\"}},\n )\n\n\nif __name__ == \"__main__\":\n ckpt = torch.load(\"./models/model.bin\")\n path = \"./Dataset\"\n paths = glob.glob(path + \"/*.jpg\")\n sample_ds = ColorizationDataset([paths[0]], img_size=256, split=\"valid\")\n x, y = sample_ds[0]\n batch_size = 1\n inputs = x.unsqueeze(0)\n convert_to_onnx(model_state_dict=ckpt[\"model_state_dict\"][\"generator\"], inputs=inputs)\n # Check if onnx works\n onnx_model = onnx.load(\"generator.onnx\")\n onnx.checker.check_model(onnx_model)\n"
]
| [
[
"torch.onnx.export",
"torch.load"
]
]
|
CognitiaAI/equippo-scraping | [
"e1f6facece5d8be9ffcd611612363f41c1c41d1a"
]
| [
"equippo/spiders/docdownloader.py"
]
| [
"import os\n\nimport scrapy\nimport pandas as pd\nimport numpy as np\nfrom scrapy.http import Request\n\n\nclass DocdownloaderSpider(scrapy.Spider):\n name = 'docdownloader'\n print(\"Doc Downloader Constructor Called !!!\")\n final_df = pd.read_excel('./scrapy_equippo.xlsx')\n docs_df = final_df[final_df['Documents for this vehicle 1'].notna()].reset_index(drop=True)\n print(\"Done reading\")\n DOC_SAVE_DIR = './documents/'\n all_documents = os.listdir((DOC_SAVE_DIR))\n\n def start_requests(self):\n yield scrapy.Request(url='https://www.google.com/', callback=self.parse_main_page,\n dont_filter=True)\n\n def save_pdf(self, response):\n name = response.meta['name']\n self.logger.info('Saving PDF %s', name)\n with open(name, 'wb') as file:\n file.write(response.body)\n\n def parse_main_page(self, response):\n total_length = len(self.docs_df)\n for i in range(0, total_length):\n for k in range(1, 7):\n doc_name = self.docs_df['Documents for this vehicle ' + str(k)].iloc[i]\n doc_link = self.docs_df['Documents Link ' + str(k)].iloc[i]\n if doc_name is not np.nan and doc_name != '':\n try:\n length = len(doc_name)\n if doc_name not in self.all_documents:\n yield Request(\n url=doc_link, callback=self.save_pdf, meta={'name': self.DOC_SAVE_DIR + doc_name}\n )\n except:\n print(\"Exception: \", doc_name, \" \", i)\n pass\n"
]
| [
[
"pandas.read_excel"
]
]
|
buszk/GraKeL | [
"d257d6537fd2f849a7d53e106dd4c6f599d83244"
]
| [
"grakel/graph_kernels.py"
]
| [
"\"\"\"The main graph kernel class, implemented as a sci-kit transformer.\"\"\"\nimport copy\nimport time\nimport warnings\n\nimport numpy as np\n\nfrom scipy.linalg import svd\nfrom sklearn.base import BaseEstimator\nfrom sklearn.base import TransformerMixin\nfrom sklearn.utils.validation import check_is_fitted\n\nfrom grakel.kernels import GraphletSampling\nfrom grakel.kernels import RandomWalk\nfrom grakel.kernels import RandomWalkLabeled\nfrom grakel.kernels import ShortestPath\nfrom grakel.kernels import ShortestPathAttr\nfrom grakel.kernels import WeisfeilerLehman\nfrom grakel.kernels import NeighborhoodHash\nfrom grakel.kernels import PyramidMatch\nfrom grakel.kernels import SubgraphMatching\nfrom grakel.kernels import NeighborhoodSubgraphPairwiseDistance\nfrom grakel.kernels import LovaszTheta\nfrom grakel.kernels import SvmTheta\nfrom grakel.kernels import OddSth\nfrom grakel.kernels import Propagation\nfrom grakel.kernels import PropagationAttr\nfrom grakel.kernels import HadamardCode\nfrom grakel.kernels import MultiscaleLaplacian\nfrom grakel.kernels import MultiscaleLaplacianFast\nfrom grakel.kernels import VertexHistogram\nfrom grakel.kernels import EdgeHistogram\nfrom grakel.kernels import GraphHopper\nfrom grakel.kernels import CoreFramework\n\n# Python 2/3 cross-compatibility import\nfrom future.utils import iteritems\n\nnp.random.seed(int(time.time()))\n\nsupported_base_kernels = [\n \"subtree_wl\", \"random_walk\",\n \"shortest_path\",\n \"graphlet_sampling\", \"subgraph_matching\",\n \"multiscale_laplacian\",\n \"lovasz_theta\", \"svm_theta\",\n \"neighborhood_hash\", \"neighborhood_subgraph_pairwise_distance\",\n \"NSPDK\",\n \"odd_sth\", \"propagation\",\n \"pyramid_match\",\n \"propagation\", \"vertex_histogram\", \"edge_histogram\",\n \"graph_hopper\"\n ]\n\nsupported_general_kernels = [\n \"weisfeiler_lehman\",\n \"hadamard_code\",\n \"core_framework\"\n ]\n\ndefault_verbose_value = True\n\ndefault_random_seed_value = 42\n\ndefault_n_components = 100\n\n\nclass GraphKernel(BaseEstimator, TransformerMixin):\n r\"\"\"A decorator for graph kernels.\n\n Parameters\n ----------\n kernel : list(dict(key:str, value:value))\n A list of dictionaries, or a single dictionary that has the following structure:\n * \"name\" : [str] - with the kernel name\n\n * \"name_of_parameter_1\" : value\n\n * \"name_of_parameter_2\" : value\n\n * :math:`\\;\\cdots\\;`\n\n * \"name_of_parameter_k\" : value\n\n available \"names\" / \"parametres\" are:\n 1. base_kernels (the structure must always reach a base kernel)\n\n - \"random_walk\"\n + (**o**) \"with_labels\" : bool\n\n + (**o**) \"lamda\" : float\n\n + (**o**) \"method_type\" : [str], \"baseline\", \"fast\"\n\n + (**o**) \"kernel_type\" : [str], \"geometric\", \"exponential\"\n\n + (**o**) \"p\" : [int] > 0\n\n\n - \"shortest_path\"\n + (**o**) \"algorithm_type\" : [str] \"dijkstra\", \"floyd_warshall\"\n\n + (**o**) \"as_attributes\" : [bool]\n\n + (**o**) \"attribute_kernel\" : [function] : (attribute_x, attribute_y) -> number\n\n + (**o**) \"with_labels\" : [bool]\n\n - \"graphlet_sampling\"\n + (**o**) \"k\" : [int]\n\n + (**o**) \"sampling\" : [dict] or **None**\n\n - \"multiscale_laplacian\"\n + (**o**) \"which\" : [str] \"slow\", \"fast\"\n\n + (**o**) \"L\" : [int] > 0\n\n + (**o**) \"gamma\" : [float] > .0\n\n + (**o**) \"heta\" : [float] > .0\n\n + (**o**) \"N\" : [int] > 0, if \"which\": \"fast\"\n\n + (**o**) \"P\" : [int] > 0, if \"which\": \"fast\"\n\n - \"subgraph_matching\"\n + (**o**) \"kv\" : [function] : (node_x, node_y, Lx, Ly) -> number\n\n + (**o**) \"ke\" : [function] : (edge_x, edge_y, Lx, Ly) -> number\n\n + (**o**) \"lw\" : a lambda weight function for cliques: set -> number\n\n - \"lovasz_theta\"\n + (**o**) \"n_samples\" : [int] > 1\n\n + (**o**) \"subsets_size_range\" : [tuple] of two [int]\n\n + (**o**) \"metric\" : [function] (number, number) -> number\n\n - \"svm_theta\"\n + (**o**) \"n_samples\" : [int] > 1\n\n + (**o**) \"subsets_size_range\" : [tuple] with 2 [int] elements\n\n + (**o**) \"metric\" : [function] (number, number) -> number\n\n - \"neighborhood_hash\"\n + (**o**) \"nh_type\" : [str] \"simple\" or \"count-sensitive\"\n\n + (**o**) \"R\" : [int] > 0\n\n + (**o**) \"bits\" : [int] > 0\n\n - \"neighborhood_subgraph_pairwise_distance\" or \"NSPD\"\n + (**o**) \"r\" : (int) positive integer\n\n + (**o**) \"d\" : (int) positive integer\n\n - \"odd_sth\"\n + (**o**) \"h\" : [int] > 0\n\n - \"propagation\"\n + (**o**) t_max: [int] > 0\n\n + (**o**) T: [dict] [int]: [np.arrays]\n\n + (**o**) with_attributes: [bool], default=False\n\n + (**o**) M: [str] {\"H\", \"TV\"} if `with_attributes=True` else {\"L1\", \"L2\"}\n\n + (**o**) w: [int] > 0\n\n + (**o**) base_kernel: [function] x:[Counter] , y:[Counter] -> [number]\n\n - \"pyramid_match\"\n + (**o**) with_labels: [bool]\n\n + (**o**) d: [int] > 0\n\n + (**o**) L: [int] >= 0\n\n - \"graph_hopper\"\n + (**o**) kernel_type: [str: {'linear', 'gaussian'}] or [tuple: {('gaussian', mu)}]\n or [function] x:[(np.array, np.array)] , y:[(np.array, np.array)] -> [number]\n\n - \"vertex_histogram\" or \"subtree_wl\"\n *No arguments*\n\n - \"edge_histogram\"\n *No arguments*\n\n 2. general_kernels (this kernel will use the next kernel\n on the list as base kernel)\n - \"weisfeiler_lehman\"\n + (**o**) \"niter\" : [int] >= 0\n\n - \"hadamard_code\"\n + (**o**) \"niter\" : [int] > 0\n\n - \"core_framework\"\n + (**o**) \"min_core\" : [int] >= -1\n\n where (**o**): stands for optional parameters\n\n Nystroem : int or bool, optional\n Defines the number of nystroem components.\n To initialize the default (100 components), set -1 or 0.\n\n n_jobs : int or None, optional\n Defines the number of jobs of a joblib.Parallel objects needed for parallelization\n or None for direct execution. The use or not of this function depends on each kernel.\n\n normalize : bool, optional\n Normalize the output of the graph kernel.\n Ignored when Nystroem GraphKernel object is instanciated.\n\n verbose : bool, optional\n Define if messages will be printed on stdout.\n\n random_seed : int, optional\n Initialize can provide a randomness by providing a random seed.\n\n Attributes\n ----------\n kernel_ : function\n The full kernel applied between graph objects.\n\n nystroem_ : int\n Holds the nystroem, number of components.\n If not initialized, it stands as a False\n boolean variable.\n\n components_ : array, shape=(n_components, n_features)\n Subset of training graphs used to construct the feature map.\n\n nystroem_normalization_ : array, shape=(n_components, n_components)\n Normalization matrix needed for embedding.\n Square root of the kernel matrix on ``components_``.\n\n component_indices_ : array, shape=(n_components)\n Indices of ``components_`` in the training set.\n\n initialized_ : dict\n Monitors which parameter derived object should be initialized.\n\n \"\"\"\n\n def __init__(self,\n kernel=None,\n normalize=False,\n verbose=False,\n n_jobs=None,\n random_seed=default_random_seed_value,\n Nystroem=False):\n \"\"\"`__init__` for `GraphKernel` object.\"\"\"\n self.kernel = kernel\n self.normalize = normalize\n self.verbose = verbose\n self.n_jobs = n_jobs\n self.random_seed = random_seed\n self.Nystroem = Nystroem\n self.initialized_ = {\"kernel\": False,\n \"Nystroem\": False,\n \"n_jobs\": False}\n\n def fit(self, X, y=None):\n \"\"\"Fit a dataset, for a transformer.\n\n Parameters\n ----------\n X : iterable\n Each element must be an iterable with at most three features and at\n least one. The first that is obligatory is a valid graph structure\n (adjacency matrix or edge_dictionary) while the second is\n node_labels and the third edge_labels (that fitting the given grap\n format). The train samples.\n\n y : None\n There is no need of a target in a transformer, yet the pipeline API\n requires this parameter.\n\n Returns\n -------\n self : object\n Returns self.\n\n \"\"\"\n # Initialize the Graph Kernel.\n self.initialize_()\n\n # Input validation and parsing\n if bool(self.nystroem_):\n X = list(X)\n nx = len(X)\n # get basis vectors\n if self.nystroem_ > nx:\n n_components = nx\n warnings.warn(\"n_components > n_samples. This is not \"\n \"possible.\\nn_components was set to n_samples\"\n \", which results in inefficient evaluation of\"\n \" the full kernel.\")\n else:\n n_components = self.nystroem_\n\n n_components = min(nx, n_components)\n inds = np.random.permutation(nx)\n basis_inds = inds[:n_components]\n basis = [X[i] for i in basis_inds]\n\n # sqrt of kernel matrix on basis vectors\n U, S, V = svd(self.kernel_.fit_transform(basis))\n S = np.maximum(S, 1e-12)\n self.nystroem_ = n_components\n self.nystroem_normalization_ = np.dot(U / np.sqrt(S), V)\n self.components_ = basis\n self.component_indices_ = inds\n else:\n self.kernel_.fit(X)\n\n # Return the transformer\n return self\n\n def transform(self, X):\n \"\"\"Calculate the kernel matrix, between given and fitted dataset.\n\n Parameters\n ----------\n X : iterable\n Each element must be an iterable with at most three features and at\n least one. The first that is obligatory is a valid graph structure\n (adjacency matrix or edge_dictionary) while the second is\n node_labels and the third edge_labels (that fitting the given graph\n format). If None the kernel matrix is calculated upon fit data.\n The test samples.\n\n Returns\n -------\n K : numpy array, shape = [n_targets, n_input_graphs]\n corresponding to the kernel matrix, a calculation between\n all pairs of graphs between target an features\n\n \"\"\"\n # Check if nystroem has been initialized had been called\n if bool(self.nystroem_):\n check_is_fitted(self, 'components_')\n\n # Transform - calculate kernel matrix\n if bool(self.nystroem_):\n K = self.kernel_.transform(X).dot(self.nystroem_normalization_.T)\n else:\n K = self.kernel_.transform(X)\n\n return K\n \n def update_kernel(self, X):\n \"\"\"Update the kernel with new graphs\n \n Parameters\n ----------\n X : iterable\n Each element must be an iterable with at most three features and at\n least one. The first that is obligatory is a valid graph structure\n (adjacency matrix or edge_dictionary) while the second is\n node_labels and the third edge_labels (that fitting the given graph\n format). If None the kernel matrix is calculated upon fit data.\n The test samples.\n\n Returns\n -------\n K : numpy array, shape = [n_targets, n_input_graphs]\n corresponding to the kernel matrix, a calculation between\n all pairs of graphs between target an features\n all pairs of graphs between target an features\n\n \"\"\"\n return self.kernel_.update_kernel(X)\n\n def replace_kernel(self, Xn, inds):\n \"\"\"Update the kernel with new graphs\n \n Parameters\n ----------\n X : iterable\n Each element must be an iterable with at most three features and at\n least one. The first that is obligatory is a valid graph structure\n (adjacency matrix or edge_dictionary) while the second is\n node_labels and the third edge_labels (that fitting the given graph\n format). If None the kernel matrix is calculated upon fit data.\n The test samples.\n inds : list\n Each element must be a valid index of graphs that is being replaced\n by the new graph\n\n Returns\n -------\n K : numpy array, shape = [n_targets, n_input_graphs]\n corresponding to the kernel matrix, a calculation between\n all pairs of graphs between target an features\n all pairs of graphs between target an features\n\n \"\"\"\n return self.kernel_.replace_kernel(Xn, inds)\n\n def fit_transform(self, X, y=None):\n \"\"\"Fit and transform, on the same dataset.\n\n Parameters\n ----------\n X : iterable\n Each element must be an iterable with at most three features and at\n least one. The first that is obligatory is a valid graph structure\n (adjacency matrix or edge_dictionary) while the second is\n node_labels and the third edge_labels (that fitting the given graph\n format). If None the kernel matrix is calculated upon fit data.\n The test samples.\n\n y : None\n There is no need of a target in a transformer, yet the pipeline API\n requires this parameter.\n\n Returns\n -------\n K : numpy array, shape = [n_targets, n_input_graphs]\n corresponding to the kernel matrix, a calculation between\n all pairs of graphs between target an features\n\n \"\"\"\n # Initialize the Graph Kernel\n self.initialize_()\n\n # Transform - calculate kernel matrix\n if bool(self.nystroem_):\n self.fit(X)\n K = self.kernel_.transform(X).dot(self.nystroem_normalization_.T)\n else:\n K = self.kernel_.fit_transform(X)\n\n return K\n\n def initialize_(self):\n \"\"\"Initialize all transformer arguments, needing initialisation.\"\"\"\n if not self.initialized_[\"Nystroem\"]:\n if type(self.Nystroem) not in [int, bool]:\n raise ValueError('Nystroem parameter must be an int, '\n 'indicating the number of components'\n 'or a boolean')\n elif self.Nystroem is False:\n self.nystroem_ = False\n elif self.Nystroem in [0, -1] or self.Nystroem is True:\n # picking default number of components\n self.nystroem_ = default_n_components\n elif self.Nystroem <= 0:\n raise ValueError('number of nystroem components '\n 'must be positive')\n else:\n self.nystroem_ = self.Nystroem\n self.initialized_[\"Nystroem\"] = True\n\n if not self.initialized_[\"kernel\"] or not self.initialized_[\"n_jobs\"]:\n if self.kernel is None:\n raise ValueError('kernel must be defined at the __init__ '\n 'function of the graph kernel decorator ')\n else:\n hidden_args = {\"verbose\": self.verbose,\n \"normalize\": self.normalize,\n \"n_jobs\": self.n_jobs}\n\n k = self.kernel\n if type(k) is dict:\n # allow single kernel dictionary inputs\n k = [self.kernel]\n elif type(k) is not list:\n raise ValueError('unsupported kernel format')\n\n kernel, params = self.make_kernel_(\n copy.deepcopy(k), hidden_args)\n\n self.kernel_ = kernel(**params)\n self.initialized_[\"kernel\"] = True\n\n def make_kernel_(self, kernel_list, hidden_args):\n \"\"\"Produce the desired kernel function.\n\n Parameters\n ----------\n kernel_list : (list)\n List of kernel dictionaries as defined at the documentation\n of class parameters.\n\n Returns\n -------\n kernel : kernel (class).\n Returns an instance of a kernel type object corresponding to the\n certain kernel.\n\n \"\"\"\n kernel = kernel_list.pop(0)\n if type(kernel) is not dict:\n raise ValueError('each element of the list of kernels must'\n ' be a dictionary')\n if \"name\" not in kernel:\n raise ValueError('each dictionary concerning a kernel must'\n ' have a \"name\" parameter designating the'\n 'kernel')\n kernel_name = kernel.pop(\"name\")\n for (keys, val) in iteritems(hidden_args):\n kernel[keys] = val\n if kernel_name in supported_base_kernels:\n if len(kernel_list) != 0:\n warnings.warn('rest kernel arguments are being ignored\\\n - reached base kernel')\n if kernel_name in [\"vertex_histogram\", \"subtree_wl\"]:\n return VertexHistogram, kernel\n elif kernel_name == \"random_walk\":\n if kernel.pop(\"with_labels\", False):\n return RandomWalkLabeled, kernel\n else:\n return RandomWalk, kernel\n elif kernel_name == \"shortest_path\":\n if kernel.pop(\"as_attributes\", False):\n return ShortestPathAttr, kernel\n else:\n return ShortestPath, kernel\n elif kernel_name == \"graphlet_sampling\":\n if (\"random_seed\" not in kernel and\n self.random_seed is not\n default_random_seed_value):\n kernel[\"random_seed\"] = self.random_seed\n return GraphletSampling, kernel\n elif kernel_name == \"multiscale_laplacian\":\n if kernel.pop(\"which\", \"fast\") == \"slow\":\n kernel.pop(\"N\", None)\n return (MultiscaleLaplacian, kernel)\n else:\n if (\"random_seed\" not in kernel and\n self.random_seed is not\n default_random_seed_value):\n kernel[\"random_seed\"] = self.random_seed\n return (MultiscaleLaplacianFast, kernel)\n elif kernel_name == \"subgraph_matching\":\n return SubgraphMatching, kernel\n elif kernel_name == \"lovasz_theta\":\n if (\"random_seed\" not in kernel and\n self.random_seed is not\n default_random_seed_value):\n kernel[\"random_seed\"] = self.random_seed\n return LovaszTheta, kernel\n elif kernel_name == \"svm_theta\":\n if (\"random_seed\" not in kernel and\n self.random_seed is not\n default_random_seed_value):\n kernel[\"random_seed\"] = self.random_seed\n return SvmTheta, kernel\n elif kernel_name == \"neighborhood_hash\":\n return NeighborhoodHash, kernel\n elif kernel_name in [\"neighborhood_subgraph_pairwise_distance\",\n \"NSPD\"]:\n return NeighborhoodSubgraphPairwiseDistance, kernel\n elif kernel_name == \"odd_sth\":\n return OddSth, kernel\n elif kernel_name == \"propagation\":\n if (\"random_seed\" not in kernel and\n self.random_seed is not\n default_random_seed_value):\n kernel[\"random_seed\"] = self.random_seed\n if kernel.pop(\"with_attributes\", False):\n return PropagationAttr, kernel\n else:\n return Propagation, kernel\n elif kernel_name == \"graph_hopper\":\n return GraphHopper, kernel\n elif kernel_name == \"pyramid_match\":\n return PyramidMatch, kernel\n elif kernel_name == \"edge_histogram\":\n return EdgeHistogram, kernel\n elif kernel_name in supported_general_kernels:\n if (len(kernel_list) == 0):\n raise ValueError(str(kernel_name)+' is not a base kernel')\n else:\n kernel[\"base_kernel\"] = self.make_kernel_(kernel_list, {})\n if kernel_name == \"weisfeiler_lehman\":\n return (WeisfeilerLehman, kernel)\n elif kernel_name == \"hadamard_code\":\n return (HadamardCode, kernel)\n elif kernel_name == \"core_framework\":\n return (CoreFramework, kernel)\n else:\n raise ValueError(\"unsupported kernel: \" + str(kernel_name))\n\n def set_params(self, **params):\n \"\"\"Call the parent method.\"\"\"\n # Copy the parameters\n params = copy.deepcopy(params)\n\n # Iterate over the parameters\n for key, value in iteritems(params):\n key, delim, sub_key = key.partition('__')\n if delim:\n if sub_key in self.initialized_:\n self.initialized_[sub_key] = False\n elif key in self.initialized_:\n self.initialized_[key] = False\n\n # Set parameters\n super(GraphKernel, self).set_params(**params)\n\n"
]
| [
[
"sklearn.utils.validation.check_is_fitted",
"numpy.random.permutation",
"numpy.maximum",
"numpy.sqrt"
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.